From d8e48bd2318c90d9a9fd9a5f7dbbd17e65d841e2 Mon Sep 17 00:00:00 2001 From: csjones <637026+csjones@users.noreply.github.com> Date: Thu, 9 Jul 2026 16:56:02 -0700 Subject: [PATCH] =?UTF-8?q?feat:=20implement=20deterministic=20scorers=20?= =?UTF-8?q?=E2=86=92=20SARIF=202.1.0=20(F17)=20with=20`skillet=20score`=20?= =?UTF-8?q?command?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add `skillet score [--format tty|json|sarif]` so produced text can be checked with free, model-free deterministic scorers emitting standard SARIF 2.1.0, closing the "no static signal" gap where skill outputs bypass triage/editor/CI integration. - `ScoreKit` implements S001–S007 (slop-vocabulary, puffery, em-dash, rule-of-three, knowledge-cutoff, not-x-but-y experimental, sarif-validity) --- AGENTS.md | 16 +- Package.swift | 10 +- README.md | 8 +- ROADMAP-changelog.md | 4 + ROADMAP.md | 4 +- Roadmap/phase-2-measurement-static-gates.md | 25 +- Sources/EDDCore/Boundary/SarifDocument.swift | 133 ++++ Sources/EDDCore/EDDError.swift | 10 +- Sources/EDDCore/ScoreReport.swift | 84 +++ Sources/EDDCore/SkilletConfig.swift | 47 +- Sources/HarnessKit/SkillBundleRules.swift | 12 +- Sources/ProjectKit/SafeFile.swift | 86 +++ Sources/RenderKit/Renderer.swift | 40 ++ Sources/RunKit/WorkspaceManager.swift | 59 +- Sources/ScoreKit/DensityScorers.swift | 180 +++++ Sources/ScoreKit/ScoreRunner.swift | 192 ++++++ Sources/ScoreKit/Scorer.swift | 114 ++++ Sources/ScoreKit/ScorerRegistry.swift | 39 ++ Sources/ScoreKit/Vocabulary.swift | 62 ++ Sources/skillet/ScoreCommand.swift | 87 +++ Sources/skillet/SkilletCommand.swift | 2 +- Specs/012-deterministic-scorers/plan.md | 616 ++++++++++++++++++ Specs/README.md | 1 + Tests/EDDCoreTests/ScoreBoundaryTests.swift | 85 +++ .../ScoreIntegrationTests.swift | 108 +++ Tests/ProjectKitTests/SafeFileTests.swift | 116 ++++ Tests/RunKitTests/RunnerTests.swift | 7 +- Tests/ScoreKitTests/ScoreKitTests.swift | 167 +++++ skillet-design-changelog.md | 4 + skillet-design.md | 45 +- 30 files changed, 2278 insertions(+), 85 deletions(-) create mode 100644 Sources/EDDCore/Boundary/SarifDocument.swift create mode 100644 Sources/EDDCore/ScoreReport.swift create mode 100644 Sources/ProjectKit/SafeFile.swift create mode 100644 Sources/ScoreKit/DensityScorers.swift create mode 100644 Sources/ScoreKit/ScoreRunner.swift create mode 100644 Sources/ScoreKit/Scorer.swift create mode 100644 Sources/ScoreKit/ScorerRegistry.swift create mode 100644 Sources/ScoreKit/Vocabulary.swift create mode 100644 Sources/skillet/ScoreCommand.swift create mode 100644 Specs/012-deterministic-scorers/plan.md create mode 100644 Tests/EDDCoreTests/ScoreBoundaryTests.swift create mode 100644 Tests/IntegrationTests/ScoreIntegrationTests.swift create mode 100644 Tests/ProjectKitTests/SafeFileTests.swift create mode 100644 Tests/ScoreKitTests/ScoreKitTests.swift diff --git a/AGENTS.md b/AGENTS.md index a147938..8d0c162 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,14 +8,16 @@ structured evidence, and ship a `SKILL.md` edit only after a previously-failing > **Phase 2 IN PROGRESS — F3 (`skillet doctor`, the $0 preflight) and F14 (`skillet run --axis > trigger`, the deterministic description axis) shipped 2026-07-04; F15 (`skillet run --ab`, the > provably skill-free baseline arm with paired Δ) shipped 2026-07-07; F16 (`skillet run --judge -> grounded-judge`, the file-contents grader) shipped 2026-07-08** +> grounded-judge`, the file-contents grader) shipped 2026-07-08; F17 (`skillet score`, free +> deterministic scorers over produced text → SARIF 2.1.0) shipped 2026-07-09** > ([Specs/008](Specs/008-doctor-preflight/plan.md), [Specs/009](Specs/009-trigger-axis/plan.md), -> [Specs/010](Specs/010-ab-baseline/plan.md), [Specs/011](Specs/011-grounded-judge/plan.md)). +> [Specs/010](Specs/010-ab-baseline/plan.md), [Specs/011](Specs/011-grounded-judge/plan.md), +> [Specs/012](Specs/012-deterministic-scorers/plan.md)). > `Package.swift` plus `EDDCore`, `TraceKit`, -> `ProjectKit`, `RenderKit`, `HarnessKit`, `LintKit`, `JudgeKit`, `RunKit`, `ConfigYAML`, and the +> `ProjectKit`, `RenderKit`, `HarnessKit`, `LintKit`, `ScoreKit`, `JudgeKit`, `RunKit`, `ConfigYAML`, and the > `skillet` executable exist — the executable owns the full ArgumentParser command tree (no -> `skilletCLI` library; `ProjectKit` is the discovery/config-IO home) — with 356 tests green -> (`swift build && swift test`). Shipped commands: `init` · `doctor` · `lint` · `run` · `harness +> `skilletCLI` library; `ProjectKit` is the discovery/config-IO home) — with 390 tests green +> (`swift build && swift test`). Shipped commands: `init` · `doctor` · `lint` · `score` · `run` · `harness > list`/`info` — see *Commands* below. **Per-feature records live nearest the artifact**: each > feature's detailed capsule is its [`Specs/NNN` plan](Specs/README.md) status, with design-only > changes in [`skillet-design-changelog.md`](skillet-design-changelog.md); this banner stays a @@ -44,11 +46,11 @@ Contributing, security disclosure, and code of conduct are handled at the org le ## Commands (true now — Phase 1 / F1, F2, F4–F8) - `swift build` — build the package (resolves `swift-argument-parser`, `swift-subprocess`, `swift-system`, `swift-yaml`). -- `swift test` — run the unit + integration suites (356 tests, all green). The integration suite drives +- `swift test` — run the unit + integration suites (390 tests, all green). The integration suite drives the built binary, which `swift test` builds first; filter with tags, e.g. `swift test --skip slow`. - `.build/debug/skillet` — the CLI: try `skillet`, `skillet --json`, `skillet -C `, `skillet init`, `skillet init --json`, `skillet doctor [...] [--json]` (free $0 preflight; exit 3 + remedy on failure), - `skillet lint [--json]`, `skillet harness list`, `skillet harness info [--json]`, + `skillet lint [--json]`, `skillet score [--format tty|json|sarif]` (free, model-free deterministic scorers over produced text → SARIF 2.1.0; a reporter, not a gate — exit 0 even with findings, exit 4 on a corrupt config), `skillet harness list`, `skillet harness info [--json]`, `skillet run [] [--axis behavior|trigger|all] [--ab] [--judge text-judge|grounded-judge] [--runs ] [--dry-run] [--yes] [--no-input] [--keep-workspace]` (paid: shells `claude`, resolved via `SKILLET_CLAUDE_CODE_BIN` env → `harness.claude-code.path` in `skillet.yaml` → `PATH` — behavioral trials add the judge; trigger trials are judge-free single calls; `--ab` doubles behavioral trials with a provably skill-free baseline arm, both arms judged; `--judge grounded-judge` reads produced-file contents to catch created-but-wrong, larger grading requests — gated by the combined spend estimate), `skillet --help`, `skillet --version`. Hidden test seams on `run`: `--replay` (offline adapter+judge), `--replay-map ` (with-arm canned verdicts), `--replay-baseline-map ` (baseline-arm canned diff --git a/Package.swift b/Package.swift index 21e778d..7f0a0cf 100644 --- a/Package.swift +++ b/Package.swift @@ -52,11 +52,15 @@ let package = Package( .target(name: "RenderKit", dependencies: ["EDDCore"]), // Free static-lint rule engine — pure (rules run over a parsed SkillSource), no I/O, no YAML. .target(name: "LintKit", dependencies: ["EDDCore"]), + // Free, model-free deterministic output scorers → SARIF (F17). Reads produced text via ProjectKit's + // SafeFile; emits EDDCore's SarifDocument / ScoreReport. No network, no subprocess. + .target(name: "ScoreKit", dependencies: ["EDDCore", "ProjectKit"]), .target( name: "HarnessKit", dependencies: [ "TraceKit", "EDDCore", + "ProjectKit", // SafeFile — shared confinement/hidden predicates (F17) // Sole sanctioned launcher — for the real ProcessLauncher (probe; F7's run). .product(name: "Subprocess", package: "swift-subprocess"), .product(name: "SystemPackage", package: "swift-system") @@ -68,7 +72,7 @@ let package = Package( .target(name: "JudgeKit", dependencies: ["EDDCore", "TraceKit"]), // The runner (F7): the per-trial sandbox lifecycle + the run/judge/aggregate loop. The // orchestrator that wires the harness adapter + judge over the pure pass^k core. - .target(name: "RunKit", dependencies: ["EDDCore", "TraceKit", "HarnessKit", "JudgeKit"]), + .target(name: "RunKit", dependencies: ["EDDCore", "TraceKit", "HarnessKit", "JudgeKit", "ProjectKit"]), // Isolated YAML config seam: swift-yaml + C++ interop live ONLY here. It exposes a pure-Swift // API (decodes into EDDCore's pure SkilletConfig), so consumers stay interop-free. @@ -90,6 +94,7 @@ let package = Package( "ProjectKit", "RenderKit", "LintKit", + "ScoreKit", "TraceKit", "HarnessKit", "JudgeKit", @@ -109,7 +114,8 @@ let package = Package( .testTarget(name: "LintKitTests", dependencies: ["LintKit"]), .testTarget(name: "HarnessKitTests", dependencies: ["HarnessKit"]), .testTarget(name: "JudgeKitTests", dependencies: ["JudgeKit"]), - .testTarget(name: "RunKitTests", dependencies: ["RunKit"]), + .testTarget(name: "RunKitTests", dependencies: ["RunKit", "ProjectKit"]), + .testTarget(name: "ScoreKitTests", dependencies: ["ScoreKit"]), // Consumer of ConfigYAML — must also enable C++ interop (it's viral to direct importers). .testTarget(name: "ConfigYAMLTests", dependencies: ["ConfigYAML"], swiftSettings: [.interoperabilityMode(.Cxx)]), diff --git a/README.md b/README.md index 89f4bb7..323a843 100644 --- a/README.md +++ b/README.md @@ -13,8 +13,9 @@ skillet drafts and proves — **a human lands every write**. > F7 (`skillet run` — the neutral runner with `pass^k`) have landed, and Phase 2 is underway: > F3 (`skillet doctor` — the free $0 preflight), F14 (`skillet run --axis trigger` — the > description axis: does the skill *fire*?), F15 (`skillet run --ab` — the provably -> skill-free baseline arm with paired Δ), and F16 (`skillet run --judge grounded-judge` — the -> file-contents grader: did it write the *right* file?) shipped. The rest +> skill-free baseline arm with paired Δ), F16 (`skillet run --judge grounded-judge` — the +> file-contents grader: did it write the *right* file?), and F17 (`skillet score` — free, +> model-free deterministic scorers over produced text → SARIF 2.1.0) shipped. The rest > of the loop lights up across later phases. See [ROADMAP.md](ROADMAP.md). ## How it works @@ -69,6 +70,9 @@ skillet doctor [...] # free $0 preflight: config, harness, skill visibili skillet doctor --json # machine-readable check rows (schema: skillet.doctor/1) skillet lint # free static analysis of SKILL.md (exit 1 on error-tier findings) skillet lint --json # machine-readable findings (schema: skillet.lint/1) +skillet score # free, model-free scorers over produced text → SARIF 2.1.0 (reporter, not a gate; exit 0 with findings) +skillet score --format json # machine-readable findings (schema: skillet.score/1) +skillet score --format sarif # standard SARIF 2.1.0 on stdout skillet run # run the skill's evals k×, judge, report pass^k (paid; spend-gated) skillet run -n # dry-run: preview the trial-count estimate, spend nothing skillet run --axis trigger # description axis: did it fire? (deterministic, judge-free) diff --git a/ROADMAP-changelog.md b/ROADMAP-changelog.md index 941d617..b91e6f6 100644 --- a/ROADMAP-changelog.md +++ b/ROADMAP-changelog.md @@ -4,6 +4,10 @@ The roadmap's versioned change log, extracted from `ROADMAP.md` on 2026-07-04 (v stays lean. Latest first; every version is a linkable heading; historical entries are never rewritten. Companion: [`skillet-design-changelog.md`](skillet-design-changelog.md). +## v1.17.0 — 2026-07-09 + +MINOR — **F17 SHIPPED: deterministic scorers → SARIF** ([Specs/012](Specs/012-deterministic-scorers/plan.md); design → v0.49). New `skillet score [--format tty|json|sarif]` — free, model-free checks over produced text emitting standard SARIF 2.1.0; a reporter, not a gate. Adds `ScoreKit` (S001–S007 + S000), `scorers:` config block, `SarifDocument`/`ScoreReport` frozen boundary formats, RenderKit human table, and ProjectKit safe-read/confinement ownership. 390 tests green. Phase 2 remains IN PROGRESS. + ## v1.16.6 — 2026-07-08 PATCH — **F16 polish round 6** (4 optional-polish observations; 2 acted, 2 reaffirmed-as-tracked; diff --git a/ROADMAP.md b/ROADMAP.md index 1d94b59..34f2ce3 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1,7 +1,7 @@ # Product Roadmap — skillet -**Version:** v1.16.6 -**Last Updated:** 2026-07-08 +**Version:** v1.17.0 +**Last Updated:** 2026-07-09 `skillet` is the SKILL.md Evaluation Toolkit — eval-driven development (EDD) for agent skills, as a public, multi-harness Swift CLI. This roadmap is diff --git a/Roadmap/phase-2-measurement-static-gates.md b/Roadmap/phase-2-measurement-static-gates.md index 2d25e3b..72af7cc 100644 --- a/Roadmap/phase-2-measurement-static-gates.md +++ b/Roadmap/phase-2-measurement-static-gates.md @@ -86,16 +86,24 @@ believable before the workflow layer starts acting on it. explicitly (default `text-judge`); auto-routing staged (design §14-21); a P9 cost note prints. Suite green — see the Specs/011 status row. -5. **[F17]** Deterministic scorers → SARIF (CLI: `skillet score`) — PLANNED · Ported - - Purpose & user value: Free, model-free checks over outputs/bundles emitting +5. **[F17]** Deterministic scorers → SARIF (CLI: `skillet score `) — IMPLEMENTED + - Purpose & user value: Free, model-free checks over produced text emitting standard SARIF 2.1.0 — the deterministic-first signal that feeds triage and - editors/CI. + editors/CI. A reporter, not a gate (exit 0 even with findings). - Northstar: deterministic-first; gap #1 input. - Success metrics: - - `score ` emits valid SARIF 2.1.0 on stdout (schema-validated). + - `score ` emits valid SARIF 2.1.0 on stdout (`--format sarif`; structural + goldens). *(`` input ships now; the saved-run `` mode arrives with + capture, Phase 3.)* - Runs with no model and no network. - - Dependencies: Trace/bundle model. - - Confidence: Medium — design §6.2, §11 (ScoreKit). + - Checks: `SKILL-S001`–`S005` (slop-vocabulary, puffery, em-dash, rule-of-three, + knowledge-cutoff), `S006` not-x-but-y (experimental, default-off), `S007` + sarif-validity, `S000` file-unreadable. Also `--format tty|json`. + - Dependencies: ProjectKit `SafeFile`; EDDCore `SarifDocument`/`ScoreReport`. + - Known limitation: reads repo `skillet.yaml` + built-in defaults only; the + user/`$XDG_CONFIG_HOME` config layer for `scorers` is deferred to **F24** (config + precedence), a known gap vs. design §5.2. + - Confidence: High — shipped; Specs/012-deterministic-scorers/plan.md, design §6.2, §11 (ScoreKit). 6. **[F18]** Flaky-eval hygiene, watchdog & infra-only retry — PLANNED · Net-new - Purpose & user value: Make reliability honest — flag flaky evals as hygiene @@ -224,6 +232,11 @@ believable before the workflow layer starts acting on it. ## Phase Change Log +- 2026-07-09: **F17 IMPLEMENTED** — deterministic scorers → SARIF ([Specs/012](../Specs/012-deterministic-scorers/plan.md)): + `skillet score [--format tty|json|sarif]`, free model-free checks over produced text, + `ScoreKit` (S001–S007 + S000), `scorers:` config block, EDDCore `SarifDocument`/`ScoreReport` + frozen boundaries, RenderKit human table. A reporter, not a gate. Fifth Phase-2 feature. + Roadmap → v1.17.0. Design → v0.49. - 2026-07-08: PATCH — F16 capture-hardening rounds 1–5 (17 reviewed points, incl. one correctness bug): grounded capture never opens special files (FIFO/socket/device — a hang past the harness timeout) or hard-linked/symlinked files (host-content leak), withholds non-UTF-8/unreadable files diff --git a/Sources/EDDCore/Boundary/SarifDocument.swift b/Sources/EDDCore/Boundary/SarifDocument.swift new file mode 100644 index 0000000..f6ef659 --- /dev/null +++ b/Sources/EDDCore/Boundary/SarifDocument.swift @@ -0,0 +1,133 @@ +import Foundation + +/// A discrete SARIF severity (`result.level`). Distinct from the continuous ``SarifResult/rank``: +/// `level` buckets, `rank` (0–100) carries the fine-grained score. `none` is emitted for a pass-like +/// result; the scorers use `note`/`warning`/`error` only. +public enum SarifLevel: String, Codable, Sendable, Equatable, CaseIterable { + case none, note, warning, error +} + +/// A **typed, emit-only** SARIF 2.1.0 log (F17). Companion to the tolerant reader ``SarifLog`` — this +/// is the *writer*: skillet authors the shape, so there is no unknown-key round-tripping to preserve. +/// Serialized by ``jsonString()`` with a **camelCase** encoder (the shared `SkilletJSON` is snake_case, +/// which would emit `start_line`/`rule_id` and break GitHub/SonarQube ingestion). Frozen boundary +/// format — golden-tested. +public struct SarifDocument: Encodable, Sendable, Equatable { + /// The advisory schema pointer. The community mirror (what the repo's reader tests already use); + /// the OASIS canonical is the authoritative source: + /// `https://docs.oasis-open.org/sarif/sarif/v2.1.0/errata01/os/schemas/sarif-schema-2.1.0.json`. + public static let schemaURI = "https://json.schemastore.org/sarif-2.1.0.json" + public static let version = "2.1.0" + + public let runs: [SarifRun] + public init(runs: [SarifRun]) { self.runs = runs } + + private enum CodingKeys: String, CodingKey { case schema = "$schema"; case version; case runs } + public func encode(to encoder: Encoder) throws { + var c = encoder.container(keyedBy: CodingKeys.self) + try c.encode(Self.schemaURI, forKey: .schema) + try c.encode(Self.version, forKey: .version) + try c.encode(runs, forKey: .runs) + } + + /// Serialize to camelCase SARIF 2.1.0 JSON (no trailing newline). Deterministic (`sortedKeys`), and + /// **not** via `SkilletJSON` — the default key strategy keeps `startLine`/`ruleId`/`$schema` literal. + public func jsonString() throws -> String { + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes] + return String(decoding: try encoder.encode(self), as: UTF8.self) + } +} + +public struct SarifRun: Encodable, Sendable, Equatable { + public let tool: SarifTool + public let results: [SarifResult] + public init(tool: SarifTool, results: [SarifResult]) { self.tool = tool; self.results = results } +} + +public struct SarifTool: Encodable, Sendable, Equatable { + public let driver: SarifDriver + public init(driver: SarifDriver) { self.driver = driver } +} + +/// The tool descriptor. `rules` is a **static catalog** — every rule the tool can emit, listed whether +/// or not it fired this run (the SARIF-idiomatic "advertise your catalog" model). +public struct SarifDriver: Encodable, Sendable, Equatable { + public let name: String + public let version: String + public let rules: [SarifRule] + public init(name: String, version: String, rules: [SarifRule]) { + self.name = name; self.version = version; self.rules = rules + } +} + +public struct SarifRule: Encodable, Sendable, Equatable { + public let id: String + public let name: String + public let shortDescription: SarifMessage + public let properties: [String: JSONValue]? + public init(id: String, name: String, shortDescription: String, properties: [String: JSONValue]? = nil) { + self.id = id; self.name = name; self.shortDescription = SarifMessage(text: shortDescription) + self.properties = (properties?.isEmpty ?? true) ? nil : properties + } +} + +public struct SarifResult: Encodable, Sendable, Equatable { + public let ruleId: String + public let level: SarifLevel + public let rank: Double? + public let message: SarifMessage + public let locations: [SarifLocation] + public let properties: [String: JSONValue]? + + public init(ruleId: String, level: SarifLevel, rank: Double?, message: String, + locations: [SarifLocation], properties: [String: JSONValue]?) { + self.ruleId = ruleId; self.level = level; self.rank = rank + self.message = SarifMessage(text: message); self.locations = locations + self.properties = (properties?.isEmpty ?? true) ? nil : properties + } +} + +public struct SarifMessage: Encodable, Sendable, Equatable { + public let text: String + public init(text: String) { self.text = text } +} + +public struct SarifLocation: Encodable, Sendable, Equatable { + public let physicalLocation: SarifPhysicalLocation + public init(physicalLocation: SarifPhysicalLocation) { self.physicalLocation = physicalLocation } + /// A file-level location (categorical rules): `artifactLocation` only, no `region`. + public static func file(_ uri: String) -> SarifLocation { + SarifLocation(physicalLocation: SarifPhysicalLocation(artifactLocation: SarifArtifactLocation(uri: uri), region: nil)) + } +} + +public struct SarifPhysicalLocation: Encodable, Sendable, Equatable { + public let artifactLocation: SarifArtifactLocation + public let region: SarifRegion? + public init(artifactLocation: SarifArtifactLocation, region: SarifRegion?) { + self.artifactLocation = artifactLocation; self.region = region + } +} + +public struct SarifArtifactLocation: Encodable, Sendable, Equatable { + public let uri: String + public init(uri: String) { self.uri = uri } +} + +/// A region within an artifact. Line/column are **1-based**; `charOffset`/`charLength` are **0-based**, +/// per the SARIF spec. All counts are **Unicode scalars** (§4.3). `endColumn` is the column immediately +/// after the region. +public struct SarifRegion: Encodable, Sendable, Equatable { + public let startLine: Int + public let startColumn: Int + public let endLine: Int + public let endColumn: Int + public let charOffset: Int + public let charLength: Int + public init(startLine: Int, startColumn: Int, endLine: Int, endColumn: Int, charOffset: Int, charLength: Int) { + self.startLine = startLine; self.startColumn = startColumn + self.endLine = endLine; self.endColumn = endColumn + self.charOffset = charOffset; self.charLength = charLength + } +} diff --git a/Sources/EDDCore/EDDError.swift b/Sources/EDDCore/EDDError.swift index 6671c14..cc40587 100644 --- a/Sources/EDDCore/EDDError.swift +++ b/Sources/EDDCore/EDDError.swift @@ -7,6 +7,9 @@ public enum EDDError: Error, Sendable, Equatable { case usage(message: String, remedy: String) /// `-C ` pointed at a directory that does not exist or is not readable. Exit ``ExitCode/environment``. case directoryNotFound(path: String) + /// A command argument that must name an existing file or directory did not (e.g. `skillet score `). + /// Exit ``ExitCode/environment``. + case pathNotFound(path: String) /// A command that requires a project was run outside one. Exit ``ExitCode/environment``. case projectNotFound(cwd: String) /// A harness binary could not be resolved (no flag/env/config/PATH). Exit ``ExitCode/environment``. @@ -29,7 +32,7 @@ public enum EDDError: Error, Sendable, Equatable { public var exitCode: ExitCode { switch self { case .usage: .usage - case .directoryNotFound, .projectNotFound, .harnessNotFound, .harnessBanned, .harnessUnauthenticated, .skillNotVisible, .baselineNotIsolable: .environment + case .directoryNotFound, .pathNotFound, .projectNotFound, .harnessNotFound, .harnessBanned, .harnessUnauthenticated, .skillNotVisible, .baselineNotIsolable: .environment case .invalidArtifact: .artifact } } @@ -39,6 +42,7 @@ public enum EDDError: Error, Sendable, Equatable { switch self { case .usage: "usage" case .directoryNotFound: "directory_not_found" + case .pathNotFound: "path_not_found" case .projectNotFound: "project_not_found" case .harnessNotFound: "harness_not_found" case .harnessBanned: "harness_banned" @@ -56,6 +60,8 @@ public enum EDDError: Error, Sendable, Equatable { message case let .directoryNotFound(path): "the directory passed to -C does not exist or is not readable: \(path)" + case let .pathNotFound(path): + "the path to score does not exist or is not readable: \(path)" case let .projectNotFound(cwd): "no skillet project found from \(cwd) (no skillet.yaml or .git boundary up the tree)" case let .harnessNotFound(harness): @@ -86,6 +92,8 @@ public enum EDDError: Error, Sendable, Equatable { remedy case .directoryNotFound: "pass an existing, readable directory to -C, or omit -C to use the current directory" + case .pathNotFound: + "pass an existing, readable file or directory to `skillet score`" case .projectNotFound: "run from inside a skills repository, or initialize one with `skillet init`" case let .harnessNotFound(harness): diff --git a/Sources/EDDCore/ScoreReport.swift b/Sources/EDDCore/ScoreReport.swift new file mode 100644 index 0000000..b6a1f15 --- /dev/null +++ b/Sources/EDDCore/ScoreReport.swift @@ -0,0 +1,84 @@ +import Foundation + +/// The `skillet.score/1` machine payload (`skillet score --format json`) — the house `--json` surface +/// (design §5.5), emitted via ``SkilletJSON`` (snake_case, schema-stamped). Distinct from the camelCase +/// ``SarifDocument`` (F17 emits both): SARIF's casing is spec-mandated, this one is house-consistent. +public struct ScoreReport: SchemaIdentified, Sendable, Equatable { + public static let schema = "skillet.score/1" + public let findings: [ScoreFinding] + public let summary: ScoreSummary + public init(findings: [ScoreFinding], summary: ScoreSummary) { + self.findings = findings; self.summary = summary + } +} + +public struct ScoreFinding: Codable, Sendable, Equatable { + public let ruleId: String // → rule_id + public let level: SarifLevel + public let rank: Double? + public let message: String + public let location: ScoreLocation + public let properties: [String: JSONValue]? + public init(ruleId: String, level: SarifLevel, rank: Double?, message: String, + location: ScoreLocation, properties: [String: JSONValue]?) { + self.ruleId = ruleId; self.level = level; self.rank = rank + self.message = message; self.location = location + self.properties = (properties?.isEmpty ?? true) ? nil : properties + } +} + +public struct ScoreSummary: Codable, Sendable, Equatable { + public let perRule: [String: Int] // → per_rule (object keyed by rule id, not an array) + public let filesScored: Int + public let filesSkipped: Int + public let filesUnreadable: Int + public init(perRule: [String: Int], filesScored: Int, filesSkipped: Int, filesUnreadable: Int) { + self.perRule = perRule; self.filesScored = filesScored + self.filesSkipped = filesSkipped; self.filesUnreadable = filesUnreadable + } +} + +/// A finding's location — a **sum type** the encoder flattens into one object, so a categorical finding +/// cannot carry region fields (the type enforces the SARIF "artifactLocation with no region" rule). A +/// Swift enum does not synthesize to the flat object the `skillet.score/1` schema documents, so the +/// `Codable` is hand-written: `file` is always present; the region fields appear only for `.region`. +/// The `SkilletJSON` key strategy still snake_cases the camelCase `CodingKeys` (`start_line`, …). +public enum ScoreLocation: Codable, Sendable, Equatable { + case file(String) // S000/S007 + case region(file: String, startLine: Int, startColumn: Int, endLine: Int, endColumn: Int, charOffset: Int, charLength: Int) // S001–S006 + + private enum CodingKeys: String, CodingKey { + case file, startLine, startColumn, endLine, endColumn, charOffset, charLength + } + + public func encode(to encoder: Encoder) throws { + var c = encoder.container(keyedBy: CodingKeys.self) + switch self { + case let .file(f): + try c.encode(f, forKey: .file) + case let .region(f, sl, sc, el, ec, co, cl): + try c.encode(f, forKey: .file) + try c.encode(sl, forKey: .startLine) + try c.encode(sc, forKey: .startColumn) + try c.encode(el, forKey: .endLine) + try c.encode(ec, forKey: .endColumn) + try c.encode(co, forKey: .charOffset) + try c.encode(cl, forKey: .charLength) + } + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + let f = try c.decode(String.self, forKey: .file) + if let sl = try c.decodeIfPresent(Int.self, forKey: .startLine) { + self = .region(file: f, startLine: sl, + startColumn: try c.decode(Int.self, forKey: .startColumn), + endLine: try c.decode(Int.self, forKey: .endLine), + endColumn: try c.decode(Int.self, forKey: .endColumn), + charOffset: try c.decode(Int.self, forKey: .charOffset), + charLength: try c.decode(Int.self, forKey: .charLength)) + } else { + self = .file(f) + } + } +} diff --git a/Sources/EDDCore/SkilletConfig.swift b/Sources/EDDCore/SkilletConfig.swift index 76eaf2e..d7167c5 100644 --- a/Sources/EDDCore/SkilletConfig.swift +++ b/Sources/EDDCore/SkilletConfig.swift @@ -8,13 +8,15 @@ public struct SkilletConfig: Codable, Sendable, Equatable { public var lint: Lint? public var runs: Runs? public var judge: Judge? + public var scorers: Scorers? - public init(project: Project? = nil, harness: Harness? = nil, lint: Lint? = nil, runs: Runs? = nil, judge: Judge? = nil) { + public init(project: Project? = nil, harness: Harness? = nil, lint: Lint? = nil, runs: Runs? = nil, judge: Judge? = nil, scorers: Scorers? = nil) { self.project = project self.harness = harness self.lint = lint self.runs = runs self.judge = judge + self.scorers = scorers } public struct Project: Codable, Sendable, Equatable { @@ -145,4 +147,47 @@ public struct SkilletConfig: Codable, Sendable, Equatable { model = try container.decodeIfPresent(String.self, forKey: .model) } } + + /// The `scorers:` knobs (design §5.2), read by `skillet score` (F17). All lists default to `[]`, so a + /// partial — or absent — block is valid. `vendored_prefixes` = folder names to skip (gitignore-style + /// whole-segment, any depth). `vocab.exempt` = domain phrases removed from the slop word-list before + /// scoring (whole-entry, case-insensitive). `disable` = default-on rule ids to turn off; `enable` = + /// experimental/default-off rule ids (e.g. `SKILL-S006`) to turn on (`disable` wins over `enable`). + /// Built-in defaults are all `[]`; `skillet init`'s template pre-writes suggested `vendored_prefixes`. + public struct Scorers: Codable, Sendable, Equatable { + public var vendoredPrefixes: [String] + public var vocab: Vocab + public var disable: [String] + public var enable: [String] + + public init(vendoredPrefixes: [String] = [], vocab: Vocab = Vocab(), disable: [String] = [], enable: [String] = []) { + self.vendoredPrefixes = vendoredPrefixes + self.vocab = vocab + self.disable = disable + self.enable = enable + } + + enum CodingKeys: String, CodingKey { + case vendoredPrefixes = "vendored_prefixes" + case vocab, disable, enable + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + vendoredPrefixes = try container.decodeIfPresent([String].self, forKey: .vendoredPrefixes) ?? [] + vocab = try container.decodeIfPresent(Vocab.self, forKey: .vocab) ?? Vocab() + disable = try container.decodeIfPresent([String].self, forKey: .disable) ?? [] + enable = try container.decodeIfPresent([String].self, forKey: .enable) ?? [] + } + + public struct Vocab: Codable, Sendable, Equatable { + public var exempt: [String] + public init(exempt: [String] = []) { self.exempt = exempt } + enum CodingKeys: String, CodingKey { case exempt } + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + exempt = try container.decodeIfPresent([String].self, forKey: .exempt) ?? [] + } + } + } } diff --git a/Sources/HarnessKit/SkillBundleRules.swift b/Sources/HarnessKit/SkillBundleRules.swift index 10d6fc6..1e0c384 100644 --- a/Sources/HarnessKit/SkillBundleRules.swift +++ b/Sources/HarnessKit/SkillBundleRules.swift @@ -1,10 +1,12 @@ import Foundation +import ProjectKit /// The staging-filter rules shared by the run stager (RunKit's `WorkspaceManager`) and the $0 /// preflight audit (`SkillBundleAudit`) — the single source of truth Specs/008 §3 calls for, so a /// rule change cannot drift between "what stages" and "what doctor checks" without both moving. /// Walk *structure* stays per-consumer (copy vs. report) and is guarded by `RunKitTests`' -/// `StagingParityTests`. +/// `StagingParityTests`. The symlink/hidden predicates now live in ProjectKit's `SafeFile` (F17, so +/// ScoreKit can share them); these stay as thin delegates so existing callers don't churn. public enum SkillBundleRules { /// The private eval namespace — never part of the model-visible bundle (constitution VI): the /// answers and records the model must never see. A *denylist* — not a fixed allowlist — because @@ -14,12 +16,8 @@ public enum SkillBundleRules { /// Whether `url` is itself a symbolic link (lstat semantics — does not follow the link). /// Symlinks are dropped by staging at any depth (the escape/leak guard for a paid harness). - public static func isSymlink(_ url: URL) -> Bool { - (try? url.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink) == true - } + public static func isSymlink(_ url: URL) -> Bool { SafeFile.isSymlink(url) } /// Whether a path component is hidden — dropped by staging at any depth (`.git`/`.env`/`.skillet`/…). - public static func isHidden(_ name: String) -> Bool { - name.hasPrefix(".") - } + public static func isHidden(_ name: String) -> Bool { SafeFile.isHidden(name) } } diff --git a/Sources/ProjectKit/SafeFile.swift b/Sources/ProjectKit/SafeFile.swift new file mode 100644 index 0000000..b863c8b --- /dev/null +++ b/Sources/ProjectKit/SafeFile.swift @@ -0,0 +1,86 @@ +import Foundation + +/// Filesystem-confinement + safe-read primitives — the single source of truth for "is this a +/// symlink / hidden / confined below a base?", and for a size-capped UTF-8 read. Shared by the run +/// stager (RunKit's `WorkspaceManager`), the bundle rules/audit (HarnessKit's `SkillBundleRules` / +/// `SkillBundleAudit`), and the deterministic scorers (ScoreKit). Pure Foundation — ProjectKit stays +/// `EDDCore`-only, so every consumer depends on it *downward* (no dependency cycle). Extracted here +/// (F17) from `SkillBundleRules`/`WorkspaceManager`; those keep thin delegating wrappers so their +/// callers don't churn. +public enum SafeFile { + /// Whether `url` is itself a symbolic link (lstat semantics — does not follow the link). + /// Symlinks are the escape/leak guard: staging drops them; scoring never follows them. + public static func isSymlink(_ url: URL) -> Bool { + (try? url.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink) == true + } + + /// Whether a path component is hidden (`.git`/`.env`/`.skillet`/…) — a leading dot. + public static func isHidden(_ name: String) -> Bool { + name.hasPrefix(".") + } + + /// True iff no component from `base` down to `url` is a symlink, and `url` nests none. + public static func noSymlink(at url: URL, under base: URL) -> Bool { + var walk = base + for component in url.path.dropFirst(base.path.count).split(separator: "/") { + walk.appendPathComponent(String(component)) + if isSymlink(walk) { return false } + } + return firstSymlink(in: url) == nil + } + + /// The first symlink at or under `url` (recursively), or `nil` if the subtree is symlink-free. + public static func firstSymlink(in url: URL) -> URL? { + if isSymlink(url) { return url } + guard let enumerator = FileManager.default.enumerator(at: url, includingPropertiesForKeys: [.isSymbolicLinkKey]) else { return nil } + for case let child as URL in enumerator where isSymlink(child) { return child } + return nil + } + + /// The first symlink among the path components from `base` (exclusive) down to `target` + /// (inclusive), or `nil` if every component is a real entry. Returns `target` when it is not under + /// `base` at all (an escape), so callers treat "not confined" like "blocked". + public static func firstSymlinkOnPath(from base: URL, to target: URL) -> URL? { + let basePath = base.standardizedFileURL.path + let targetPath = target.standardizedFileURL.path + guard targetPath == basePath || targetPath.hasPrefix(basePath + "/") else { return target } // not under base → escape + var walk = base.standardizedFileURL + for component in targetPath.dropFirst(basePath.count).split(separator: "/") { + walk.appendPathComponent(String(component)) + if isSymlink(walk) { return walk } + } + return nil + } + + /// Read up to `cap` bytes without slurping a huge file whole; also returns the file's full byte + /// size (from metadata) so truncation can be disclosed precisely. `nil` if unreadable. + public static func boundedRead(_ url: URL, cap: Int) -> (data: Data, fullSize: Int)? { + guard let handle = try? FileHandle(forReadingFrom: url) else { return nil } + defer { try? handle.close() } + let data = (try? handle.read(upToCount: max(cap, 0))) ?? Data() + let fullSize = (try? FileManager.default.attributesOfItem(atPath: url.path)[.size] as? Int).flatMap { $0 } ?? data.count + return (data, fullSize) + } + + /// Decode `data` as UTF-8 text, or `nil` for binary. A NUL byte ⇒ binary. When `truncated` (the + /// read hit the cap), a trailing *incomplete* multi-byte sequence is trimmed before the final + /// decode so a boundary cut isn't misread as binary; a genuinely invalid byte (e.g. `0xFF` that is + /// not a boundary artifact) still falls through to `nil`. + /// + /// Known heuristic limitation (accepted): with an absurdly small cap (< one scalar, ~4 bytes), a + /// prefix of only stray continuation bytes can trim to empty and read as empty text. Unreachable at + /// the shipped caps — a genuinely binary file's first bytes carry a NUL or a non-continuation + /// invalid byte and fail to binary. + public static func decodeText(_ data: Data, truncated: Bool) -> String? { + if data.contains(0) { return nil } + if let whole = String(bytes: data, encoding: .utf8) { return whole } + guard truncated else { return nil } // invalid UTF-8 that isn't a boundary cut ⇒ binary + var d = data + var trimmedContinuations = 0 + while let last = d.last, (last & 0b1100_0000) == 0b1000_0000, trimmedContinuations < 3 { + d.removeLast(); trimmedContinuations += 1 + } + if let last = d.last, ((0xC2 as UInt8)...(0xF4 as UInt8)).contains(last) { d.removeLast() } // a genuine incomplete lead byte only + return String(bytes: d, encoding: .utf8) // still invalid ⇒ binary + } +} diff --git a/Sources/RenderKit/Renderer.swift b/Sources/RenderKit/Renderer.swift index ee25fbb..2092228 100644 --- a/Sources/RenderKit/Renderer.swift +++ b/Sources/RenderKit/Renderer.swift @@ -84,6 +84,18 @@ public struct Renderer: Sendable { } } + /// `skillet score`'s output (F17): the findings table + a summary line (human), or the + /// `skillet.score/1` payload (json). The SARIF surface bypasses the renderer — the command emits + /// `SarifDocument.jsonString()` straight to stdout, since `Renderer` models only `.human`/`.json`. + public func renderScore(_ report: ScoreReport, nextSteps: [String] = []) throws -> Rendering { + switch mode { + case .json: + return Rendering(stdout: try SkilletJSON.encode(report) + "\n") + case .human: + return Rendering(stdout: humanScore(report, nextSteps: nextSteps)) + } + } + /// A generic aligned table for plumbing/listing output (e.g. `harness info`). Column widths come /// from the widest cell; the last column is left unpadded to avoid trailing whitespace. public func renderTable(_ headers: [String], _ rows: [[String]]) -> Rendering { @@ -138,6 +150,34 @@ public struct Renderer: Sendable { return out } + private func humanScore(_ report: ScoreReport, nextSteps: [String]) -> String { + var out = "" + if report.findings.isEmpty { + out += bold("✓ score: no findings") + "\n" + } else { + let rows = report.findings.map { finding -> [String] in + let location: String + switch finding.location { + case let .region(file, line, _, _, _, _, _): location = "\(file):\(line)" + case let .file(file): location = file + } + let rank = finding.rank.map { String(Int($0)) } ?? "" + return [finding.ruleId, finding.level.rawValue, rank, location, finding.message] + } + out += renderTable(["RULE", "LEVEL", "RANK", "FILE:LINE", "MESSAGE"], rows).stdout + let errors = report.findings.filter { $0.level == .error }.count + let warnings = report.findings.filter { $0.level == .warning }.count + let findingCount = report.findings.count, fileCount = report.summary.filesScored + let findingWord = findingCount == 1 ? "finding" : "findings" + let fileWord = fileCount == 1 ? "file" : "files" + out += "\n\(findingCount) \(findingWord) (\(errors) error · \(warnings) warning) across \(fileCount) \(fileWord)\n" + } + if !nextSteps.isEmpty { + out += "\(bold("→ next:")) \(nextSteps.joined(separator: " · "))\n" + } + return out + } + private func humanInit(_ report: InitReport, nextSteps: [String]) -> String { var out = bold("Initialized skillet") + "\n" out += " created \(report.created.count) · skipped \(report.skipped.count) · skills \(report.skills.count)\n" diff --git a/Sources/RunKit/WorkspaceManager.swift b/Sources/RunKit/WorkspaceManager.swift index bc08548..696a459 100644 --- a/Sources/RunKit/WorkspaceManager.swift +++ b/Sources/RunKit/WorkspaceManager.swift @@ -1,6 +1,7 @@ import Foundation import HarnessKit import JudgeKit +import ProjectKit // SafeFile — the shared confinement/safe-read primitives (F17) /// Creates and tears down the per-trial sandbox a run executes in, and lists its post-run contents as /// ground truth for the judge. Staging copies the skill (`SKILL.md` + `references/` + `scripts/` + @@ -63,45 +64,24 @@ public struct WorkspaceManager: Sendable { return ResolvedFixture(source: source, sandboxRelativePath: entry) } + // These confinement predicates now live in ProjectKit's ``SafeFile`` (F17, shared with ScoreKit); + // the wrappers below keep RunKit's existing call sites (and `RunnerTests`) unchanged. + /// True iff no component from `base` down to `url` is a symlink, and `url` nests none. - static func noSymlink(at url: URL, under base: URL) -> Bool { - var walk = base - for component in url.path.dropFirst(base.path.count).split(separator: "/") { - walk.appendPathComponent(String(component)) - if isSymlink(walk) { return false } - } - return firstSymlink(in: url) == nil - } + static func noSymlink(at url: URL, under base: URL) -> Bool { SafeFile.noSymlink(at: url, under: base) } /// Whether `url` is itself a symbolic link (lstat semantics — does not follow the link). - /// Delegates to the shared ``SkillBundleRules`` (kept here so existing call sites don't churn). - public static func isSymlink(_ url: URL) -> Bool { - SkillBundleRules.isSymlink(url) - } + public static func isSymlink(_ url: URL) -> Bool { SafeFile.isSymlink(url) } /// The first symlink at or under `url` (recursively), or `nil` if the subtree is symlink-free. /// Used to reject symlinks in staged skill-bundle entries and directory fixtures (F7 policy). - public static func firstSymlink(in url: URL) -> URL? { - if isSymlink(url) { return url } - guard let enumerator = FileManager.default.enumerator(at: url, includingPropertiesForKeys: [.isSymbolicLinkKey]) else { return nil } - for case let child as URL in enumerator where isSymlink(child) { return child } - return nil - } + public static func firstSymlink(in url: URL) -> URL? { SafeFile.firstSymlink(in: url) } /// The first symlink among the path components from `base` (exclusive) down to `target` (inclusive), /// or `nil` if every component is a real entry. Confines the skill / `evaluations/` I/O paths so a - /// symlinked component can't redirect reads or writes outside the project — the staging check skips - /// `evaluations/` and the skill root itself, so those need this guard. + /// symlinked component can't redirect reads or writes outside the project. public static func firstSymlinkOnPath(from base: URL, to target: URL) -> URL? { - let basePath = base.standardizedFileURL.path - let targetPath = target.standardizedFileURL.path - guard targetPath == basePath || targetPath.hasPrefix(basePath + "/") else { return target } // not under base → escape - var walk = base.standardizedFileURL - for component in targetPath.dropFirst(basePath.count).split(separator: "/") { - walk.appendPathComponent(String(component)) - if isSymlink(walk) { return walk } - } - return nil + SafeFile.firstSymlinkOnPath(from: base, to: target) } /// Top-level skill entries that staging copies: not `evaluations/`, not hidden. Shared by staging @@ -379,18 +359,7 @@ public struct WorkspaceManager: Sendable { /// prefix of only stray continuation bytes can trim to empty and read as empty text. Unreachable at /// the shipped 32 KiB cap — a genuinely binary file's first 32 KiB carries a NUL or a /// non-continuation invalid byte and fails to binary. - static func decodeText(_ data: Data, truncated: Bool) -> String? { - if data.contains(0) { return nil } - if let whole = String(bytes: data, encoding: .utf8) { return whole } - guard truncated else { return nil } // invalid UTF-8 that isn't a boundary cut ⇒ binary - var d = data - var trimmedContinuations = 0 - while let last = d.last, (last & 0b1100_0000) == 0b1000_0000, trimmedContinuations < 3 { - d.removeLast(); trimmedContinuations += 1 - } - if let last = d.last, ((0xC2 as UInt8)...(0xF4 as UInt8)).contains(last) { d.removeLast() } // a genuine incomplete lead byte only - return String(bytes: d, encoding: .utf8) // still invalid ⇒ binary - } + static func decodeText(_ data: Data, truncated: Bool) -> String? { SafeFile.decodeText(data, truncated: truncated) } /// Non-`.claude` file-or-symlink entries under the workspace (dirs excluded), sorted. Symlink /// entries are kept (to be disclosed, never read); real directories are skipped. @@ -419,11 +388,5 @@ public struct WorkspaceManager: Sendable { /// Read up to `cap` bytes (the capture ceiling) without slurping a huge file whole; also returns /// the file's full byte size (from metadata) so truncation can be disclosed precisely. - private func boundedRead(_ url: URL, cap: Int) -> (data: Data, fullSize: Int)? { - guard let handle = try? FileHandle(forReadingFrom: url) else { return nil } - defer { try? handle.close() } - let data = (try? handle.read(upToCount: max(cap, 0))) ?? Data() - let fullSize = (try? FileManager.default.attributesOfItem(atPath: url.path)[.size] as? Int).flatMap { $0 } ?? data.count - return (data, fullSize) - } + private func boundedRead(_ url: URL, cap: Int) -> (data: Data, fullSize: Int)? { SafeFile.boundedRead(url, cap: cap) } } diff --git a/Sources/ScoreKit/DensityScorers.swift b/Sources/ScoreKit/DensityScorers.swift new file mode 100644 index 0000000..649b151 --- /dev/null +++ b/Sources/ScoreKit/DensityScorers.swift @@ -0,0 +1,180 @@ +import Foundation +import EDDCore + +// MARK: - Match helpers (each returns the located ranges, so a count becomes located findings) + +/// Word-boundary, case-insensitive matches of any phrase — for the vocabulary checks (S001/S002). +func wordBoundaryMatches(phrases: [String], in text: String) -> [Range] { + var out: [Range] = [] + let full = NSRange(text.startIndex..., in: text) + for phrase in phrases { + let pattern = #"\b"# + NSRegularExpression.escapedPattern(for: phrase) + #"\b"# + guard let regex = try? NSRegularExpression(pattern: pattern, options: [.caseInsensitive]) else { continue } + for m in regex.matches(in: text, range: full) where Range(m.range, in: text) != nil { + out.append(Range(m.range, in: text)!) + } + } + return out +} + +/// Case-insensitive **substring** matches on the original text (not a lowercased copy, so scalar offsets +/// stay accurate) — for the knowledge-cutoff phrases (S005), which are multi-word and not word-bounded. +func substringMatches(phrases: [String], in text: String) -> [Range] { + var out: [Range] = [] + for phrase in phrases where !phrase.isEmpty { + var start = text.startIndex + while let r = text.range(of: phrase, options: [.caseInsensitive], range: start.. [Range] { + var out: [Range] = [] + var i = text.startIndex + while i < text.endIndex { + let next = text.index(after: i) + if text[i] == "\u{2014}" { out.append(i.. [Range] { + let patterns = [ + #"\bnot\s+(just|only|merely|simply)\b[^.?!\n]{0,60}?\bbut\b"#, + #"\b(it|that|this|they|we|you)['’]?s\b[^.?!\n]{0,60}?,\s*(it['’]?s|but)\b"#, + #"\bless\s+about\b[^.?!\n]{0,60}?\bmore\s+about\b"#, + ] + var out: [Range] = [] + let full = NSRange(text.startIndex..., in: text) + for p in patterns { + guard let regex = try? NSRegularExpression(pattern: p, options: [.caseInsensitive]) else { continue } + for m in regex.matches(in: text, range: full) where Range(m.range, in: text) != nil { + out.append(Range(m.range, in: text)!) + } + } + return out +} + +/// Rule-of-three matcher with a referential/technical skip, ported + generalized (S004). A `X, Y, and Z` +/// triple is NOT counted when ≥2 items are referential (markdown link or inline code) or technical +/// (all-caps run, digit-bearing, or identifier punctuation) — so concrete technical enumerations +/// ("P2WPKH, P2WSH, and P2SH") don't over-flag. Returns the whole-triple ranges. +enum RuleOfThreeMatcher { + static func rhetoricalTripleRanges(in text: String) -> [Range] { + let pattern = #"([^,.;!?\n]{1,60}),\s+([^,.;!?\n]{1,60}),\s+(?:and\s+)?([^,.;!?\n]{1,60})(?:[.,;!?\s]|$)"# + guard let regex = try? NSRegularExpression(pattern: pattern, options: [.caseInsensitive]) else { return [] } + let full = NSRange(text.startIndex..., in: text) + var out: [Range] = [] + for m in regex.matches(in: text, range: full) where m.numberOfRanges == 4 { + guard let r0 = Range(m.range(at: 0), in: text), + let r1 = Range(m.range(at: 1), in: text), + let r2 = Range(m.range(at: 2), in: text), + let r3 = Range(m.range(at: 3), in: text) else { continue } + let items = [r1, r2, r3].map { String(text[$0]).trimmingCharacters(in: .whitespaces) } + let concrete = items.filter { isReferential($0) || isTechnical($0) }.count + if concrete < 2 { out.append(r0) } + } + return out + } + + static func isReferential(_ item: String) -> Bool { + if item.contains("](") { return true } // markdown link + if item.range(of: #"`[^`]+`"#, options: .regularExpression) != nil { return true } // inline code (generalizes DocC ``X``) + return false + } + + static func isTechnical(_ item: String) -> Bool { + if item.range(of: #"[A-Z]{2,}"#, options: .regularExpression) != nil { return true } // all-caps acronym + if item.range(of: #"\d"#, options: .regularExpression) != nil { return true } // digit-bearing + if item.contains("_") || item.contains("::") || item.contains("/") { return true } // identifier / path + return false + } +} + +// MARK: - The six density scorers (S001–S006) + +struct SlopVocabularyScorer: Scorer { + let ruleId = "SKILL-S001"; let name = "slop-vocabulary" + let scale = ScorerScale(min: 0, max: 20, good: .low) + func measure(_ file: ScoredFile, config: SkilletConfig.Scorers) -> ScorerMeasurement { + let words = SlopTextStats.wordCount(file.text) + guard words > 0 else { return .notApplicable } + let exempt = Set(config.vocab.exempt.map { $0.lowercased() }) + let phrases = AIVocabulary.combined.filter { !exempt.contains($0.lowercased()) } + let occ = wordBoundaryMatches(phrases: phrases, in: file.text).map { + Occurrence(range: $0, message: "AI-slop vocabulary: `\(file.text[$0])`") + } + return .density(value: Double(occ.count) / Double(words) * 1000, denominator: words, occurrences: occ) + } +} + +struct PufferyScorer: Scorer { + let ruleId = "SKILL-S002"; let name = "puffery" + let scale = ScorerScale(min: 0, max: 20, good: .low) + func measure(_ file: ScoredFile, config: SkilletConfig.Scorers) -> ScorerMeasurement { + let words = SlopTextStats.wordCount(file.text) + guard words > 0 else { return .notApplicable } + let exempt = Set(config.vocab.exempt.map { $0.lowercased() }) + let phrases = AIVocabulary.puffery.filter { !exempt.contains($0.lowercased()) } + let occ = wordBoundaryMatches(phrases: phrases, in: file.text).map { + Occurrence(range: $0, message: "Marketing puffery: `\(file.text[$0])`") + } + return .density(value: Double(occ.count) / Double(words) * 1000, denominator: words, occurrences: occ) + } +} + +struct EmDashScorer: Scorer { + let ruleId = "SKILL-S003"; let name = "em-dash" + let scale = ScorerScale(min: 0, max: 10, good: .target(1.5)) + func measure(_ file: ScoredFile, config: SkilletConfig.Scorers) -> ScorerMeasurement { + let words = SlopTextStats.wordCount(file.text) + guard words > 0 else { return .notApplicable } + let occ = emDashMatches(in: file.text).map { Occurrence(range: $0, message: "Over-used em-dash") } + return .density(value: Double(occ.count) / Double(words) * 100, denominator: words, occurrences: occ) + } +} + +struct RuleOfThreeScorer: Scorer { + let ruleId = "SKILL-S004"; let name = "rule-of-three" + let scale = ScorerScale(min: 0, max: 20, good: .low) + func measure(_ file: ScoredFile, config: SkilletConfig.Scorers) -> ScorerMeasurement { + let sentences = SlopTextStats.sentenceCount(file.text) + guard sentences > 0 else { return .notApplicable } + let occ = RuleOfThreeMatcher.rhetoricalTripleRanges(in: file.text).map { + Occurrence(range: $0, message: "Rule-of-three rhetorical triple") + } + return .density(value: Double(occ.count) / Double(sentences) * 100, denominator: sentences, occurrences: occ) + } +} + +struct KnowledgeCutoffScorer: Scorer { + let ruleId = "SKILL-S005"; let name = "knowledge-cutoff" + let scale = ScorerScale(min: 0, max: 5, good: .low) + func measure(_ file: ScoredFile, config: SkilletConfig.Scorers) -> ScorerMeasurement { + guard !file.text.isEmpty else { return .notApplicable } + let occ = substringMatches(phrases: AIVocabulary.knowledgeCutoffPhrases, in: file.text).map { + Occurrence(range: $0, message: "Knowledge-cutoff disclaimer: `\(file.text[$0])`") + } + return .density(value: Double(occ.count), denominator: nil, occurrences: occ) // raw count + } +} + +/// Experimental (default-off; §4.7). Regex-only approximation of EQ-Bench's contrast detector. +struct NotXButYScorer: Scorer { + let ruleId = "SKILL-S006"; let name = "not-x-but-y" + let scale = ScorerScale(min: 0, max: 15, good: .low) // provisional; pinned by the calibration fixture + func measure(_ file: ScoredFile, config: SkilletConfig.Scorers) -> ScorerMeasurement { + let words = SlopTextStats.wordCount(file.text) + guard words > 0 else { return .notApplicable } + let occ = contrastMatches(in: file.text).map { + Occurrence(range: $0, message: "\"not X, but Y\" contrast construction") + } + return .density(value: Double(occ.count) / Double(words) * 1000, denominator: words, occurrences: occ) + } +} diff --git a/Sources/ScoreKit/ScoreRunner.swift b/Sources/ScoreKit/ScoreRunner.swift new file mode 100644 index 0000000..8c64980 --- /dev/null +++ b/Sources/ScoreKit/ScoreRunner.swift @@ -0,0 +1,192 @@ +import Foundation +import EDDCore +import ProjectKit + +/// Runs the deterministic scorers over a folder (or single file) and produces both boundary outputs: +/// the SARIF findings document and the native `ScoreReport`. Free, model-free, no network. Walk order +/// is irrelevant — findings are sorted `(relativePath, charOffset, ruleId)` for byte-stable output. +public struct ScoreRunner: Sendable { + /// Files larger than this are disclosed (`S000`) rather than read/scored (§3.2). + public static let sizeCap = 1 << 20 // 1 MiB + let toolVersion: String + public init(toolVersion: String) { self.toolVersion = toolVersion } + + public struct Output: Sendable { + public let sarif: SarifDocument + public let report: ScoreReport + } + + /// One accumulated finding, holding everything both outputs and the sort need. + struct RawFinding { + let relativePath: String + let ruleId: String + let level: SarifLevel + let rank: Double? + let message: String + let region: SarifRegion? // nil ⇒ categorical (file-level) + let properties: [String: JSONValue]? + } + + /// Score `path`, which the caller has already confirmed exists (a missing/unreadable path is the + /// command's exit-3 concern). A directory is walked recursively; a single file is scored alone. + /// `onStart` is called once with the candidate-file count before scoring begins — the command uses + /// it for a stderr progress note on a TTY. + public func run(path: URL, config: SkilletConfig.Scorers, + onStart: (@Sendable (Int) -> Void)? = nil) -> Output { + var findings: [RawFinding] = [] + var perRule: [String: Int] = [:] + var scored = 0, skipped = 0, unreadable = 0 + let scorers = ScorerRegistry.active(config) + + let toScore = candidates(under: path, config: config) + onStart?(toScore.count) + for (rel, url) in toScore { + guard let (data, fullSize) = SafeFile.boundedRead(url, cap: Self.sizeCap) else { + findings.append(disclosure(rel, "Not scored: unreadable (permissions)")); unreadable += 1 + bump(&perRule, "SKILL-S000"); continue + } + let isSarif = rel.hasSuffix(".sarif") || rel.hasSuffix(".sarif.json") + if fullSize > Self.sizeCap { // oversized ⇒ S000, never decoded + findings.append(disclosure(rel, "Not scored: exceeds 1 MiB")); unreadable += 1 + bump(&perRule, "SKILL-S000"); continue + } + guard let text = SafeFile.decodeText(data, truncated: false) else { // binary / non-UTF-8 + if isSarif { + findings.append(sarifInvalid(rel, "not UTF-8")); scored += 1; bump(&perRule, "SKILL-S007") + } else { + skipped += 1 // silent skip — no finding + } + continue + } + if isSarif { // validity only; excluded from density + if let reason = sarifInvalidReason(text) { + findings.append(sarifInvalid(rel, reason)); bump(&perRule, "SKILL-S007") + } + scored += 1; continue + } + let file = ScoredFile(relativePath: rel, text: text) // density scorers + for scorer in scorers { + for f in map(scorer.measure(file, config: config), scorer: scorer, file: file) { + findings.append(f); bump(&perRule, f.ruleId) + } + } + scored += 1 + } + + findings.sort { + if $0.relativePath != $1.relativePath { return $0.relativePath < $1.relativePath } + let a = $0.region?.charOffset ?? -1, b = $1.region?.charOffset ?? -1 + if a != b { return a < b } + return $0.ruleId < $1.ruleId + } + + let sarif = SarifDocument(runs: [SarifRun( + tool: SarifTool(driver: SarifDriver(name: "skillet", version: toolVersion, rules: ScorerRegistry.catalog)), + results: findings.map(sarifResult))]) + let report = ScoreReport( + findings: findings.map(scoreFinding), + summary: ScoreSummary(perRule: perRule, filesScored: scored, filesSkipped: skipped, filesUnreadable: unreadable)) + return Output(sarif: sarif, report: report) + } + + // MARK: - Candidate selection (§3.2) + + private func candidates(under path: URL, config: SkilletConfig.Scorers) -> [(rel: String, url: URL)] { + let fm = FileManager.default + var isDir: ObjCBool = false + guard fm.fileExists(atPath: path.path, isDirectory: &isDir) else { return [] } + guard isDir.boolValue else { return [(path.lastPathComponent, path)] } // single file + + let root = path.standardizedFileURL + guard let en = fm.enumerator(at: root, includingPropertiesForKeys: [.isRegularFileKey], options: []) else { return [] } + var out: [(String, URL)] = [] + for case let url as URL in en { + let rel = relativePath(of: url, under: root) + let segments = rel.split(separator: "/").map(String.init) + if segments.contains(where: { $0.hasPrefix(".") }) { continue } // dot-entries (.git/.build) + if SafeFile.isSymlink(url) { continue } // never follow + if isVendored(segments, prefixes: config.vendoredPrefixes) { continue } // skip before read + guard (try? url.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile) == true else { continue } + out.append((rel, url)) + } + return out + } + + /// gitignore-style: skip when any whole path segment equals a configured folder name (trailing slash + /// stripped, case-sensitive) — so `Vendored/` skips `Vendored/x` and `sub/Vendored/x`, never `VendoredFoo.swift`. + private func isVendored(_ segments: [String], prefixes: [String]) -> Bool { + guard !prefixes.isEmpty else { return false } + let names = Set(prefixes.map { $0.hasSuffix("/") ? String($0.dropLast()) : $0 }) + return segments.contains(where: names.contains) + } + + private func relativePath(of url: URL, under root: URL) -> String { + let full = url.standardizedFileURL.path, base = root.path + if full.hasPrefix(base + "/") { return String(full.dropFirst(base.count + 1)) } + return url.lastPathComponent + } + + // MARK: - Measurement → findings + + private func map(_ m: ScorerMeasurement, scorer: any Scorer, file: ScoredFile) -> [RawFinding] { + switch m { + case .notApplicable: + return [] + case let .categorical(level, message): + return [RawFinding(relativePath: file.relativePath, ruleId: scorer.ruleId, level: level, rank: nil, message: message, region: nil, properties: nil)] + case let .density(value, denominator, occurrences): + let goodness = scorer.scale.normalizedGoodness(value) + guard goodness < 0.5 else { return [] } // clean ⇒ no findings + let level: SarifLevel = goodness < 0.4 ? .error : .warning + let rank = ((1 - goodness) * 100).rounded() + var props: [String: JSONValue] = [ + "skillet.goodness": .number(goodness), + "skillet.scale": scorer.scale.json, + ] + if let denominator { + props["skillet.density"] = .number(value) + props["skillet.denominator"] = .number(Double(denominator)) + } else { + props["skillet.count"] = .number(value) + } + return occurrences.map { occ in + RawFinding(relativePath: file.relativePath, ruleId: scorer.ruleId, level: level, rank: rank, + message: occ.message, region: SarifRegionCompute.region(for: occ.range, in: file.text), properties: props) + } + } + } + + private func disclosure(_ rel: String, _ message: String) -> RawFinding { + RawFinding(relativePath: rel, ruleId: "SKILL-S000", level: .note, rank: nil, message: message, region: nil, properties: nil) + } + private func sarifInvalid(_ rel: String, _ reason: String) -> RawFinding { + RawFinding(relativePath: rel, ruleId: "SKILL-S007", level: .error, rank: nil, message: "Invalid SARIF 2.1.0: \(reason)", region: nil, properties: nil) + } + + /// `nil` if the text is a valid SARIF 2.1.0 shell (parses, `version == "2.1.0"`, `runs` present), else the defect. + private func sarifInvalidReason(_ text: String) -> String? { + guard let data = text.data(using: .utf8), + let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return "not valid JSON" } + guard let version = obj["version"] as? String else { return "missing version" } + guard version == "2.1.0" else { return "version \(version) ≠ 2.1.0" } + guard obj["runs"] != nil else { return "missing runs" } + return nil + } + + private func bump(_ perRule: inout [String: Int], _ ruleId: String) { perRule[ruleId, default: 0] += 1 } + + private func sarifResult(_ f: RawFinding) -> SarifResult { + let locations: [SarifLocation] = f.region.map { + [SarifLocation(physicalLocation: SarifPhysicalLocation(artifactLocation: SarifArtifactLocation(uri: f.relativePath), region: $0))] + } ?? [.file(f.relativePath)] + return SarifResult(ruleId: f.ruleId, level: f.level, rank: f.rank, message: f.message, locations: locations, properties: f.properties) + } + + private func scoreFinding(_ f: RawFinding) -> ScoreFinding { + let loc: ScoreLocation = f.region.map { + .region(file: f.relativePath, startLine: $0.startLine, startColumn: $0.startColumn, + endLine: $0.endLine, endColumn: $0.endColumn, charOffset: $0.charOffset, charLength: $0.charLength) + } ?? .file(f.relativePath) + return ScoreFinding(ruleId: f.ruleId, level: f.level, rank: f.rank, message: f.message, location: loc, properties: f.properties) + } +} diff --git a/Sources/ScoreKit/Scorer.swift b/Sources/ScoreKit/Scorer.swift new file mode 100644 index 0000000..3a2c0f2 --- /dev/null +++ b/Sources/ScoreKit/Scorer.swift @@ -0,0 +1,114 @@ +import Foundation +import EDDCore + +/// A `[min, max]` quality scale with a "good" direction, ported verbatim from the predecessor +/// (`Scorer.swift`). `normalizedGoodness` maps a raw measurement to `[0, 1]` where `1` is ideal; the +/// runner turns that into the SARIF `level` band + `rank` (§4.2). +public struct ScorerScale: Sendable, Equatable { + public enum Direction: Sendable, Equatable { case high, low, target(Double) } + public let min: Double + public let max: Double + public let good: Direction + public init(min: Double, max: Double, good: Direction) { self.min = min; self.max = max; self.good = good } + + /// Normalise a raw measurement to `[0, 1]` goodness (1 = ideal), honouring `good`. A `.target(t)` + /// scale peaks at `t` and falls off toward either end. Degenerate (zero-span) scales return `1`. + public func normalizedGoodness(_ value: Double) -> Double { + let span = max - min + guard span > 0 else { return 1.0 } + let t = Swift.max(0, Swift.min(1, (value - min) / span)) + switch good { + case .high: return t + case .low: return 1.0 - t + case let .target(target): + let distance = abs(value - target) + let maxDistance = Swift.max(target - min, max - target) + guard maxDistance > 0 else { return 1.0 } + return 1.0 - Swift.min(1.0, distance / maxDistance) + } + } + + /// The `skillet.scale` property shape: `{ min, max, good, target? }` (the `.target` associated value + /// lifted to a sibling field so it serializes cleanly). + var json: JSONValue { + var o: [String: JSONValue] = ["min": .number(min), "max": .number(max)] + switch good { + case .high: o["good"] = .string("high") + case .low: o["good"] = .string("low") + case let .target(target): o["good"] = .string("target"); o["target"] = .number(target) + } + return .object(o) + } +} + +/// One decoded produced file handed to each scorer (per-file scoring — §4.9). +public struct ScoredFile: Sendable, Equatable { + public let relativePath: String + public let text: String + public init(relativePath: String, text: String) { self.relativePath = relativePath; self.text = text } +} + +/// One located match: the text range plus the human message for its finding (the message carries the +/// matched word/phrase for the vocabulary/cutoff checks, or a fixed string otherwise). +public struct Occurrence: Sendable, Equatable { + public let range: Range + public let message: String + public init(range: Range, message: String) { self.range = range; self.message = message } +} + +/// What a scorer reports for one file. `.density` → goodness → level/rank + one finding per occurrence +/// (or none if clean). `.categorical` → one fixed-level file-level finding. `.notApplicable` → nothing. +public enum ScorerMeasurement: Sendable { + /// `denominator` is `nil` for a raw-count check (S005), else the word/sentence count. + case density(value: Double, denominator: Int?, occurrences: [Occurrence]) + case categorical(level: SarifLevel, message: String) + case notApplicable +} + +/// A deterministic, model-free check over one file's text. +public protocol Scorer: Sendable { + /// The stable SARIF rule id, e.g. `SKILL-S001`. + var ruleId: String { get } + /// The kebab rule name for the catalog, e.g. `slop-vocabulary`. + var name: String { get } + /// The ported goodness scale. + var scale: ScorerScale { get } + func measure(_ file: ScoredFile, config: SkilletConfig.Scorers) -> ScorerMeasurement +} + +/// Turns a text range into a SARIF region with **Unicode-scalar** counts: 1-based line/column, 0-based +/// `charOffset`/`charLength`. A `\r` immediately before a `\n` is treated as part of the line ending +/// (CRLF); a lone `\r` is content. +enum SarifRegionCompute { + static func region(for range: Range, in text: String) -> SarifRegion { + let scalars = text.unicodeScalars + let lower = range.lowerBound.samePosition(in: scalars) ?? scalars.startIndex + let upper = range.upperBound.samePosition(in: scalars) ?? scalars.endIndex + let charOffset = scalars.distance(from: scalars.startIndex, to: lower) + let charLength = scalars.distance(from: lower, to: upper) + let (startLine, startColumn) = lineColumn(scalars, upTo: lower) + let (endLine, endColumn) = lineColumn(scalars, upTo: upper) + return SarifRegion(startLine: startLine, startColumn: startColumn, + endLine: endLine, endColumn: endColumn, + charOffset: charOffset, charLength: charLength) + } + + private static func lineColumn(_ scalars: String.UnicodeScalarView, upTo idx: String.UnicodeScalarView.Index) -> (Int, Int) { + var line = 1, col = 1 + var i = scalars.startIndex + let newline: Unicode.Scalar = "\n", cr: Unicode.Scalar = "\r" + while i < idx { + let s = scalars[i] + let next = scalars.index(after: i) + if s == cr, next < scalars.endIndex, scalars[next] == newline { + // CRLF: the \r is part of the ending — don't count it; the \n resets on the next step. + } else if s == newline { + line += 1; col = 1 + } else { + col += 1 + } + i = next + } + return (line, col) + } +} diff --git a/Sources/ScoreKit/ScorerRegistry.swift b/Sources/ScoreKit/ScorerRegistry.swift new file mode 100644 index 0000000..2df4eaf --- /dev/null +++ b/Sources/ScoreKit/ScorerRegistry.swift @@ -0,0 +1,39 @@ +import Foundation +import EDDCore + +/// The scorer set and the static SARIF rule catalog. +public enum ScorerRegistry { + /// All density scorers, in stable rule-id order. + static let all: [any Scorer] = [ + SlopVocabularyScorer(), PufferyScorer(), EmDashScorer(), + RuleOfThreeScorer(), KnowledgeCutoffScorer(), NotXButYScorer(), + ] + + /// Experimental, default-off checks (§4.7) — run only when opted in via `scorers.enable`. + static let defaultOff: Set = ["SKILL-S006"] + + /// The scorers active for this run: `disable` turns a default-on check off (and **wins** over + /// `enable`); a default-off check runs only if listed in `enable`. + static func active(_ config: SkilletConfig.Scorers) -> [any Scorer] { + let disable = Set(config.disable), enable = Set(config.enable) + return all.filter { s in + if disable.contains(s.ruleId) { return false } + if defaultOff.contains(s.ruleId) { return enable.contains(s.ruleId) } + return true + } + } + + /// The full static rule catalog (S000–S007) for `tool.driver.rules` — advertised whether or not each + /// rule fires this run (the SARIF-idiomatic "advertise your catalog" model). + public static let catalog: [SarifRule] = [ + SarifRule(id: "SKILL-S000", name: "file-unreadable", shortDescription: "File not scored"), + SarifRule(id: "SKILL-S001", name: "slop-vocabulary", shortDescription: "Over-used AI vocabulary"), + SarifRule(id: "SKILL-S002", name: "puffery", shortDescription: "Marketing-puffery language"), + SarifRule(id: "SKILL-S003", name: "em-dash", shortDescription: "Em-dash over-use"), + SarifRule(id: "SKILL-S004", name: "rule-of-three", shortDescription: "Rule-of-three over-use"), + SarifRule(id: "SKILL-S005", name: "knowledge-cutoff", shortDescription: "Knowledge-cutoff mention"), + SarifRule(id: "SKILL-S006", name: "not-x-but-y", shortDescription: "Negative-parallelism over-use", + properties: ["skillet.enabledByDefault": .bool(false)]), + SarifRule(id: "SKILL-S007", name: "sarif-validity", shortDescription: "Emitted findings-file validity"), + ] +} diff --git a/Sources/ScoreKit/Vocabulary.swift b/Sources/ScoreKit/Vocabulary.swift new file mode 100644 index 0000000..0e8eea9 --- /dev/null +++ b/Sources/ScoreKit/Vocabulary.swift @@ -0,0 +1,62 @@ +import Foundation + +/// Wikipedia-derived word-lists for AI-writing detection (`WP:AIVOCAB` / `WP:AIPUFFERY` / +/// `WP:AIDASH`), ported verbatim (F17) from the predecessor's `SkillEvalKit/Scoring/Code/AIVocabulary`. +/// `combined` feeds the slop-vocabulary check (S001); `puffery` feeds the marketing-puffery check +/// (S002); `knowledgeCutoffPhrases` feeds the knowledge-cutoff check (S005). Kept in-code (small, +/// curated); large lists would move to a resource file (design §5.2), a deferred option. +public enum AIVocabulary { + /// The broadest combined AI-vocabulary net (Wikipedia's inclusive-ascending GPT-4 era list). + public static let combined: [String] = [ + // gpt5 era + "emphasizing", "enhance", "highlighting", "showcasing", + // gpt4o additions + "align with", "bolstered", "crucial", "enduring", "fostering", "pivotal", "underscore", "vibrant", + // gpt4 additions + "additionally", "boasts", "delve", "garner", "intricate", "intricacies", "interplay", + "landscape", "meticulous", "meticulously", "tapestry", "testament", "valuable", + ] + + /// Promotional / puffery language (`WP:AIPUFFERY`). + public static let puffery: [String] = [ + "vibrant", "rich tapestry", "stands as", "seamlessly", + "world-class", "nestled", "breathtaking", "lifeline", + ] + + /// Knowledge-cutoff disclaimers — an AI model hedging about training-data recency. **Substring** + /// match (not word-boundary), because most are multi-word phrases. + public static let knowledgeCutoffPhrases: [String] = [ + "as of my last", "knowledge cutoff", "i cannot verify", "my training data", + "i do not have access", "i don't have access", "i'm not able to access", "last updated knowledge", + ] +} + +/// Text statistics — the density denominators, ported verbatim from the predecessor (F17). Denominators +/// count `Character`s (graphemes), matching the predecessor so calibration transfers; SARIF *regions* +/// count Unicode scalars separately (§4.3). +enum SlopTextStats { + /// Approximate word count: whitespace-separated tokens containing at least one letter or digit (so + /// em-dashes, lone punctuation, and decorative glyphs don't inflate the count). + static func wordCount(_ text: String) -> Int { + text.split(whereSeparator: { $0.isWhitespace || $0.isNewline }) + .filter { token in token.contains(where: { $0.isLetter || $0.isNumber }) } + .count + } + + /// Approximate sentence count: `.`/`!`/`?` followed by whitespace or end-of-string. Capped at min 1 + /// for non-empty text so per-100-sentences math doesn't divide by zero on prose without terminal + /// punctuation. + static func sentenceCount(_ text: String) -> Int { + guard !text.isEmpty else { return 0 } + var count = 0 + let chars = Array(text) + for i in 0..` — free, model-free deterministic scorers over produced text, emitting SARIF +/// 2.1.0 findings (design §6.2, F17). A **reporter, not a gate**: exit 0 even when scorers fire (the +/// signal feeds triage/next; it does not fail a build, unlike `lint`). No model, no network. +struct ScoreCommand: AsyncParsableCommand { + static let configuration = CommandConfiguration( + commandName: "score", + abstract: "Free deterministic scorers over produced text → SARIF findings.", + discussion: """ + Runs deterministic, model-free checks (AI-slop vocabulary, marketing puffery, em-dash over-use, \ + rule-of-three, knowledge-cutoff mentions) over the text files under and emits standard \ + findings JSON (SARIF 2.1.0). No model, no network. A reporter, not a gate — exit 0 even with \ + findings. The human table is the default; scripts opt in: + skillet score . --format sarif > out.sarif + Configure folder skips and vocabulary exemptions under `scorers:` in skillet.yaml. + """ + ) + + @OptionGroup var options: GlobalOptions + + @Argument(help: "File or directory of produced text to score.") + var path: String + + @Option(name: .long, help: "Output format: tty (default), json, or sarif.") + var format: ScoreFormat? + + enum ScoreFormat: String, ExpressibleByArgument, CaseIterable { case tty, json, sarif } + + func run() async throws { + // Resolve the output surface up front (R8 C2: an explicit `--format` wins; else `--json` ⇒ json; + // else tty) so **errors follow it too** — a machine format (`json`/`sarif`) renders errors as the + // `skillet.error/1` JSON payload on stderr, not a human line, even when `--format json` is used + // without the global `--json`. + let fmt = format ?? (options.json ? .json : .tty) + let errorRenderer = Renderer(mode: fmt == .tty ? .human : .json, color: options.makeRenderer().color) + do { + let url = URL(fileURLWithPath: path) + // `isReadableFile` is false for a missing *or* unreadable path — both are exit-3 environment + // errors (not a silent empty/S000 result). + guard FileManager.default.isReadableFile(atPath: url.path) else { + throw EDDError.pathNotFound(path: path) + } + + // Config: repo skillet.yaml + built-in defaults (no user layer until F24); a corrupt config + // is an artifact error (exit 4). Outside a repo → defaults. + let cwd = URL(fileURLWithPath: FileManager.default.currentDirectoryPath) + let context = try ProjectLocator().locate(dashC: options.directory, cwd: cwd) + let scorers = (try loadConfig(options: options, context: context))?.scorers ?? SkilletConfig.Scorers() + + // Progress note (clig.dev): a one-line status on stderr for the human table only, never when + // piped or emitting machine output. + let showProgress = fmt == .tty && Console.isStdoutTTY() + let output = ScoreRunner(toolVersion: SkilletVersion.current).run(path: url, config: scorers) { count in + guard showProgress else { return } + let noun = count == 1 ? "file" : "files" + FileHandle.standardError.write(Data("scoring \(count) \(noun)…\n".utf8)) + } + + switch fmt { + case .sarif: + Console.emit(Rendering(stdout: try output.sarif.jsonString() + "\n")) // bypasses Renderer + case .json: + Console.emit(Rendering(stdout: try SkilletJSON.encode(output.report) + "\n")) + case .tty: + let renderer = Renderer(mode: .human, color: errorRenderer.color) + Console.emit(try renderer.renderScore(output.report, nextSteps: Self.nextSteps())) + } + // Reporter: no non-zero exit on findings. + } catch let error as EDDError { + Console.emit(errorRenderer.renderError(error)) + throw SilentExit(code: error.exitCode.rawValue) + } + } + + /// Suggest the next loop steps that exist today (registration-filtered, like `LintCommand`). + static func nextSteps() -> [String] { + let registered = Set(SkilletCommand.configuration.subcommands.compactMap { $0.configuration.commandName }) + let available = ["lint", "run"].filter { registered.contains($0) }.map { "skillet \($0)" } + return available.isEmpty ? ["skillet --help"] : available + } +} diff --git a/Sources/skillet/SkilletCommand.swift b/Sources/skillet/SkilletCommand.swift index 9ed1787..788bc38 100644 --- a/Sources/skillet/SkilletCommand.swift +++ b/Sources/skillet/SkilletCommand.swift @@ -17,7 +17,7 @@ struct SkilletCommand: AsyncParsableCommand { """, discussion: "Run from anywhere: skillet finds its project by walking up to skillet.yaml or a .git boundary.", version: SkilletVersion.current, - subcommands: [InitCommand.self, DoctorCommand.self, LintCommand.self, HarnessCommand.self, RunCommand.self] + subcommands: [InitCommand.self, DoctorCommand.self, LintCommand.self, ScoreCommand.self, HarnessCommand.self, RunCommand.self] ) @OptionGroup var options: GlobalOptions diff --git a/Specs/012-deterministic-scorers/plan.md b/Specs/012-deterministic-scorers/plan.md new file mode 100644 index 0000000..60be81a --- /dev/null +++ b/Specs/012-deterministic-scorers/plan.md @@ -0,0 +1,616 @@ +# Plan — Phase 2 · F17: deterministic scorers → SARIF (`skillet score`) + +| | | +|---|---| +| **Feature** | F17 — free, model-free checks over a skill's produced text that emit standard findings JSON (SARIF 2.1.0) — the deterministic-first signal (CLI: `skillet score `) | +| **Phase** | 2 — Trustworthy Measurement & Static Gates ([Roadmap/phase-2-measurement-static-gates.md](../../Roadmap/phase-2-measurement-static-gates.md), F17) | +| **Status** | IMPLEMENTED (2026-07-09) — plan converged over 11 review rounds; **shipped + green (390 tests)**: ProjectKit `SafeFile`, EDDCore `SarifDocument`/`ScoreReport`, ScoreKit (S001–S007/S000), `skillet score --format tty\|json\|sarif`, RenderKit table, docs ripple | +| **Last updated** | 2026-07-09 | +| **Builds on** | EDDCore (`SarifLog` tolerant *reader*; `SchemaIdentified`/`LintReport`; `JSONValue`; `SkilletConfig`; `Diagnostic`/`SKILL-Lxxx`; `ExitCode`; §5.1 discovery; `EDDCore/JSON.swift:40` snake_case encoder — the **house `--json` convention**, §4.5); **ProjectKit** (EDDCore-only filesystem home — the confinement + safe-read helpers **move** here, §3.2); RenderKit (`Renderer` `.human`/`.json`); F8 golden discipline; the F16 confinement + `decodeText`/`boundedRead` discipline | +| **Adapted from** (concepts, **not** a type port) | `~/Developer/skills/Sources/SkillEvalKit/Scoring/`: **measurement concepts + word-lists** — `Code/AIVocabulary.swift` (incl. `knowledgeCutoffPhrases:127`), `Code/AISlopScorers.swift` counting/regex (incl. `RuleOfThreeMatcher` + `isReferentialItem`/`isTechnicalItem` :449-475), each check's `ScorerScale(min,max,good)`. The **`Scorer` protocol / `ScorerContext` / result model / `ScorerRegistry` are redesigned** for per-occurrence SARIF over a folder (the predecessor is single-value, docc-locked, session+diff-built). **Every generalized check (S001–S006) needs its own calibration fixture.** NOT carried over: `.judge`, `Scorecard`/pass-fail, taxonomy/routing/suggest, the two markdown/tone checks, citations. | +| **Authoritative refs** | design §4, §5.1 (discovery), §5.2 (`scorers.*` config + wordlists), §5.4 (exit codes), §5.5 (`--json`/no-auto-switch/progress/next-step), §6.2 (`skillet score`), §7.2 (SARIF frozen format), §8 (contradiction — the F34 *consumer*), §11 (ScoreKit); constitution I–VI, §constitution:381; P8, D5, D6 | +| **Decisions** | **D-1 Input** = a folder path (dir recursive, or a single file), with a **file-selection policy** (§3.2). **D-2 Checks** = five word/punctuation logics generalized + re-calibrated (S001–S005), **plus** experimental **default-off** S006 "not X, but Y" (§4.7), **plus** S007 sarif-validity + S000 file-unreadable; two markdown/tone checks defer (Option C, §4.7). **D-3 Output** = per-occurrence findings, dual **`level`+`rank`** (§4.2), `level` grounded on the predecessor's universal cuts (`ScorecardFeedback:116-118`: ≥0.5 clean, 0.4–0.5 `warning`, <0.4 `error`). **D-4 Data** = word-lists in-code; a new `SkilletConfig.Scorers` (`vendored_prefixes`, `vocab.exempt`, `disable`, `enable` — §3.1) from repo `skillet.yaml` + defaults (no user layer until F24). **D-5 Surface** = one `--format tty\|json\|sarif`; `--json` = shorthand for `--format json` yielding to explicit `--format`; **no TTY auto-switch — human default** (§3.3). | +| **Assumptions** | A1: new **`ScoreKit`** — deps **`EDDCore` + `ProjectKit`** — + **`ScoreKitTests`**. A2: SARIF emitter **emit-only**, **dedicated camelCase encoder**; `ScoreReport`/`--format json` follows the **house snake_case** convention (§4.5). A3: **`score` is a reporter, not a gate (R8 · C1)** — exit **0 even when scorers fire** (the signal feeds triage F33 / +next / contradiction F34; deliberately unlike `lint`'s exit-1 error-tier gate, so `skillet score` won't fail a +build); **2** usage / **3** environment (bad ``) / **4** corrupt *config* artifact (§3.3). A4: **no new dependency** ("valid SARIF" = structural golden checks). A5: additive/greenfield. | +| **Workflow** | Standalone plan (spec-kit workflow intentionally skipped) | + +--- + +## 1. Goal & success criteria + +Ship the **deterministic-first signal**: `skillet score ` runs free, model-free, no-network checks +over a skill's produced text and emits standard findings JSON (SARIF 2.1.0) — the cheap, reproducible +layer beneath the paid judge. + +**F17 deliverable:** `skillet score --format sarif` emits **valid SARIF 2.1.0** on stdout (structural +conformance pinned by golden fixtures — no external validator, §4.6); **no model, no network**; also +`--format tty` (human table, default) and `--format json` (`ScoreReport`/`skillet.score/1`, §4.5). + +> **Roadmap reconciliation (R1 #5).** The metric "`score `" becomes `score ` with a +> `` (Phase 3) note; design §6.2's `skillet score ` → `` too (§6). + +## 2. Scope + +### In scope +- **EDDCore**: the typed **SARIF 2.1.0 emitter** (emit-only, camelCase, **incl. `tool.driver.{name,version, + rules}`** — §4.6) + a **`ScoreReport`** type (`SchemaIdentified`, `skillet.score/1`, snake_case — §4.5), + both frozen + golden-tested; the tolerant `SarifLog` reader untouched. A new **`SkilletConfig.Scorers`** (§3.1). +- **ProjectKit**: the **moved** shared confinement predicates + safe bounded UTF-8 read (§3.2) — the single + home for this boundary; RunKit/HarnessKit re-import from here (no cycle — §3.2). +- **ScoreKit** (new, `EDDCore` + `ProjectKit`): the redesigned `Scorer` protocol, a general folder-scoped + `ScorerContext`, the finding model, `ScorerRegistry`, generalized + re-calibrated logic, in-code + word-lists, exemption/enable/disable, the ported `ScorerScale`. +- **Checks** (§4.1): S001–S005 generalized, S006 (experimental, **default-off**), S007, S000. +- **executable**: `skillet score [--format tty|json|sarif]` (§3.3); exits 0/2/3/4. +- **RenderKit**: a `score` table + a next-step + a progress note (§3.3). **Tests** (§5). **Docs/Package** (§6). + +### Out of scope (→ owner) +- Two markdown/tone checks + citations → bring-your-own-check (Option C, §4.7). `.judge` → later. + Scorecard/rollup → triage F33 / report F23. Contradiction → F34. External word-list files + `migrate + knobs` → later. User-config precedence → F24. Bundle input + role-rename + corrupt-manifest exit → capture. + drift/fixtures-verify → F35/F36/F22. **lint's `--format` surface → a separate follow-up (R3 #13).** + +## 3. Architecture + +`EDDCore` (emitter + `ScoreReport` + config — pure) ; `ProjectKit` (confinement + safe-read — effectful, +EDDCore-only) ← `ScoreKit` ← `skillet` ; `RenderKit`. One **new kit** (`ScoreKit` = `EDDCore` + `ProjectKit`) ++ `ScoreKitTests`; **no new dependency**. EDDCore owns the pure emission inputs; ScoreKit maps onto them. + +### 3.1 Config + the `scorers` section (R2 #7; R3 #7; R4 nb) + +Discovery via the existing `loadConfigWithOrigin` (upward walk → `--config` / repo `skillet.yaml` / +defaults; **no user layer until F24** — a known gap vs design §5.2, not a new design change, R5 nb; a +**corrupt** explicit/repo config → exit 4, §3.3). Outside a repo → defaults. The per-skill overlay is not +consulted (directory-scoped). Single layer → repo **replaces** defaults. **`SkilletConfig` currently *ignores* +a `scorers:` block on decode (the template already writes one) — F17 adds the model so it is read.** +**Init ripple (R11 · B3):** adding `public var scorers: Scorers?` requires updating `SkilletConfig`'s explicit +memberwise `init(project:harness:lint:runs:judge:)` → `…judge:scorers:)` (a new stored property isn't +auto-added to an explicit init). The param is defaulted (`scorers: Scorers? = nil`) so it's additive — and a +repo grep finds **no direct `SkilletConfig(...)` call sites** (construction is via `Codable` decode), so the +ripple is the initializer alone; tracked so it isn't missed. +``` +scorers: # SkilletConfig.Scorers (optional; snake_case keys; absent = defaults) + vendored_prefixes: [String] # folder names to skip (gitignore-style, R8/B1 — see below). BUILT-IN DEFAULT + # [] (score everything); `skillet init`'s template pre-writes + # ["Vendored/","Generated/"] as a suggestion. + vocab: { exempt: [String] } # domain terms to NOT flag; default []. See the vocab.exempt note below. + disable: [String] # rule-ids OFF among default-on scorers (mirrors [lint].disable) + enable: [String] # rule-ids ON among experimental/default-off scorers (S006) +``` +**`disable` overrides `enable`** if a rule-id appears in both (safe default: an explicit off wins). +**Partial-block decode (R6 nb):** `Scorers` decodes like `Lint`/`Runs` — **each key defaults individually**, +so a repo file with only `scorers.disable:` keeps the built-in `vocab`/`vendored_prefixes`/`enable` defaults +rather than zeroing them (via optional properties / an `init(from:)` that fills missing keys). + +**`vendored_prefixes` matching (R8 · B1 · decided — gitignore-style):** a candidate file is skipped iff **any +whole path segment** of its path *relative to ``* equals an entry (trailing slash stripped) — the +[gitignore](https://git-scm.com/docs/gitignore) folder-name-at-any-depth model that ESLint and most tools +follow, and the mental model developers already have. So `Vendored/` skips `Vendored/x.md` **and** +`sub/Vendored/x.md`, but **never** `VendoredFoo.swift` (a different segment — the trailing slash is +conventional, *not* the guard, because whole-segment matching already prevents partial-word hits). +**Case-sensitive** (gitignore default; Linux paths). **No wildcards/negation/leading-slash anchoring in F17** +(a documented future extension). The setting's "prefix" name is legacy (the predecessor's ignore file); +entries match folder segments — noted so the name doesn't mislead. + +**`vocab.exempt` semantics (R8 · R3):** an exempt phrase **removes matching entries from the configured slop +word-list *before* scoring** (case-insensitive, whole-phrase — mirrors the predecessor, AISlopScorers.swift:54-55: +the exempt set is built at :54, the word-list `.filter` that drops exempt entries is :55; applied to **both** +S001 `combined` and S002 `puffery` — :54/:79, R10 #8); +it does **not** mask or rewrite occurrences in the source text. So exempting "delve" means the scorer never +counts "delve"; it does not alter what the file says. **Matching is whole-list-entry, exact (lowercased), not +substring (R11 · B1):** `exempt.contains($0.lowercased())` compares against each *word-list phrase*, so +`exempt: ["tapestry"]` removes the list entry `"tapestry"` but does **not** suppress a list entry +`"rich tapestry"` — to exempt that, write the exact entry `["rich tapestry"]`. + +### 3.2 Filesystem: selection, safe read, confinement, char unit (R1 #3; R3 #4/#11/#12; R4 #4/#11 · Principle VI) + +**File-selection policy (R4 #4).** Recurse `` (or take the one file). A path is a **candidate** iff it +is a **regular file** (symlinks/FIFOs/sockets/devices excluded — confinement), is **not** a dot-entry +(`.git`, `.build`, hidden), and does **not** match a `vendored_prefixes` prefix (checked **before read**). +**No extension filter** — the caller points at a produced-text directory; non-text bytes are handled by the read. + +**Confinement + safe read (ProjectKit — the moved home; R3 #4, R6 B2).** `lstat` + never follow symlinks + +never traverse above ``. A new `SafeFile` enum in ProjectKit gathers the boundary. **Moved vs stays:** + +| helper (signature) | today | action | callers after | +|---|---|---|---| +| `isSymlink(_: URL) -> Bool` | **one impl** `SkillBundleRules:17`, **re-exported** by `WorkspaceManager:78` | move impl → ProjectKit; both keep thin re-exports | SkillBundleRules, WorkspaceManager, **SkillBundleAudit, TriggerEvalSupport, RunCommand:462, DoctorCommand:241**, ScoreKit (R10 #2 — more callers than first listed; all keep working via the wrappers) | +| `isHidden(_ name: String) -> Bool` | `SkillBundleRules:22` | move | SkillBundleRules, **SkillBundleAudit**, WorkspaceManager, ScoreKit | +| `noSymlink(at: URL, under: URL) -> Bool` | `WorkspaceManager:67` | move | WorkspaceManager, ScoreKit | +| `firstSymlink(in:)` / `firstSymlinkOnPath(from:to:) -> URL?` | `WorkspaceManager:84/:95` | move | WorkspaceManager, ScoreKit | +| `decodeText(_ data: Data, truncated: Bool) -> String?` | `WorkspaceManager:382` | move | WorkspaceManager, ScoreKit | +| `boundedRead(_ url: URL, cap: Int) -> (data: Data, fullSize: Int)?` | `WorkspaceManager:422` (`private`→`public static`) | move | WorkspaceManager, ScoreKit | +| bundle-staging policy (`resolveFixture`, audit) | `SkillBundleRules`/`SkillBundleAudit` | **stays** (calls the moved predicates) | HarnessKit | + +**Package.swift:** ProjectKit still imports only Foundation + EDDCore, so adding `ProjectKit` to `HarnessKit` +and `RunKit` (and `ScoreKit`) is **downward — no cycle**. `isHidden` is confirmed shared by all three current +sites (SkillBundleRules/SkillBundleAudit/WorkspaceManager), so it moves rather than duplicates. **Move ripple +(R8 · R1; corrected R10 #1):** `SkillBundleRules` becomes a thin policy wrapper calling ProjectKit. The only +test that names moved helpers directly is **`Tests/RunKitTests/RunnerTests.swift`** (`firstSymlink`/ +`firstSymlinkOnPath`, :124/:128/:204) — it re-points at ProjectKit. `StagingParityTests` exercises +`WorkspaceManager.prepare`/`.destroy` + `SkillBundleAudit.audit` (which **stay**), so it needs no change +beyond staying green. The moved helpers use only `FileManager`/`FileHandle`, so +**ProjectKit stays Foundation+EDDCore-only — re-verify no new import creeps in after the move.** + +**Build order (R9 · B3 — the move is a *prerequisite*, sequenced explicitly):** +1. **Move** `isSymlink`/`isHidden`/`noSymlink`/`firstSymlink*`/`decodeText`/`boundedRead` into ProjectKit; + turn `SkillBundleRules` into a thin wrapper; update `Package.swift` (`HarnessKit`/`RunKit` → `ProjectKit`). +2. **HARD GATE (R11 · B4): the full existing suite must be green on CI before any scorer code lands** — + `RunnerTests` re-points at ProjectKit's helpers; `StagingParityTests`/`HarnessKitTests` pass **unchanged** + (they use the staying `prepare`/`destroy`/`audit` APIs, not the moved helpers, R10 #1). This is a separate, + reviewable refactor commit with **no `score` code**. +3. **Only then build `ScoreKit`** (emitter + `ScoreReport` + scorers + `score`) on the now-shared helpers. + Landing 1–2 first keeps the DAG refactor reviewable in isolation and de-risks it. + +**Per-candidate read + disposition (R4 #11; R7 #3):** safe bounded UTF-8 read, **1 MiB cap**. **A `.sarif`/ +`.sarif.json` name is dispositive** — detected by **exact suffix** (`path.hasSuffix(".sarif") || +path.hasSuffix(".sarif.json")`, R9 risk — not substring) — such a file is a findings artifact, so a +read/parse failure is a *validity finding*, not a silent skip: + +| candidate | within 1 MiB cap? | disposition | +|---|---|---| +| `.sarif`/`.sarif.json` | yes | route to **S007** only (excluded from S001–S006): valid JSON **and** `version=="2.1.0"` **and** `runs` present ⇒ no finding; **invalid JSON, non-UTF-8, missing `version`/`runs`, or `version`≠"2.1.0"** ⇒ `S007` `error` (R7 #3 — for a `.sarif`, non-UTF-8 *is* malformed, **not** a skip) | +| `.sarif`/`.sarif.json` | **no (> cap)** | `S000` note — oversized, **not decoded**, so not validated (R6 B3) | +| other file | yes, UTF-8 text | scored by S001–S006 (§4.8) | +| other file | yes, binary / non-UTF-8 | **silently skipped** (counted in `summary.files_skipped`; **no** finding — surfacing every non-text file in a mixed dir would be noise) | +| any file | unreadable (permissions) | `S000` note | +| any file | oversized (> cap) | `S000` note — **no `decodeText` on the truncated prefix** (R6 B3) | + +**Never crashes.** + +**Character unit (R3 #12):** all region offsets/columns count **Unicode scalars** (`String.unicodeScalars`), +per the SARIF spec's "a character = a Unicode code point"; documented, multi-byte golden-locked (UTF-16 +caveat noted, not adopted). + +### 3.3 CLI, precedence, default, exit codes (R1 #4; R3 #3/#13; R4 #7) + +`skillet score [--format tty|json|sarif]` — plumbing. **One selector**; global `--json` = shorthand +for `--format json` yielding to an explicit `--format`: + +| invocation | result | via | +|---|---|---| +| *(none)* — TTY **or piped** | `tty` — human table (**default; no auto-switch**) | `Renderer(.human)` | +| `--json` | `json` — `ScoreReport`/`skillet.score/1` | `Renderer(.json)` | +| `--format sarif` | SARIF 2.1.0 | **direct emitter — bypasses `Renderer`** | +| `--json --format sarif` | **sarif** (explicit wins) | — | + +No TTY auto-switch (house §5.5 + clig.dev + Docker's auto-switch-is-annoying report; two machine formats → +auto-pick is arbitrary). Because piped runs still default to the table, the command's **`--help` discussion +shows a piped machine example** — e.g. `skillet score . --format sarif > out.sarif` (R11 · risk) — so script +users know to opt in. `score` lands `--format` first; `lint` follows separately (R3 #13). **Wiring (R6 nb; R8 C2; R9 · B2 — coexistence proven, not a risk):** the inherited global `--json` +(`@OptionGroup GlobalOptions`) and a **command-local `@Option var format`** parse independently — **already the +established pattern** (`RunCommand` combines `GlobalOptions.--json` with local `--judge`/`--axis`/`--runs`, so +distinct flag names never conflict at parse time). Precedence (`--format` wins) is **resolved in `run()` +against `options.json` in code**, not via ArgumentParser conflict handling. `json` (or `--json`) builds +`Renderer(.json)`; `tty` builds `Renderer(.human)`; **`sarif` bypasses `Renderer` entirely** (the emitter +writes straight to stdout, since `Renderer` only models `.human`/`.json`). **TTY extras +(§5.5, R4 nb):** a one-line `scoring N files…` progress note (stderr; suppressed under `--json`/`--format +sarif`/pipes) and a **next-step suggestion** after the human table, built with the **same registration-filter mechanism as +`LintCommand.nextSteps()`** — suggest the loop steps that exist today, else `skillet --help` (R7 #1 — +**correction:** lint's filter is by *registration*, **not** free-vs-paid, so the earlier "free-only mirror" +framing was a false claim about current code; a next-step *suggestion* is not a spend, and `run` confirms +before spending, so suggesting it stays P9-safe). + +**Exit codes** (§5.4): `0` report (even with findings — D6) · `2` usage · `3` environment (`` +non-existent/unreadable) · **`4` a corrupt explicit/repo `skillet.yaml`** (via `loadConfigWithOrigin`, +Principle III — R4 #7). **A malformed scored `.sarif` under `` is a *finding* (S007), not exit 4.** + +## 4. Output contract + +### 4.1 Rule-ids, levels, triggers (R1 #9; R3 #9; R4 #1) + +| ruleId | kebab name | kind | level | trigger | +|---|---|---|---|---| +| `SKILL-S001` | `slop-vocabulary` | density | §4.2 band | per slop-word match | +| `SKILL-S002` | `puffery` | density | §4.2 band | per puffery match | +| `SKILL-S003` | `em-dash` | density | §4.2 band | per em-dash occurrence (severity per-file) | +| `SKILL-S004` | `rule-of-three` | density | §4.2 band | per non-referential/non-technical triple (§4.8) | +| `SKILL-S005` | `knowledge-cutoff` | count | §4.2 band | per cutoff-phrase mention (§4.8) | +| `SKILL-S006` | `not-x-but-y` | density (**experimental, default-off**) | §4.2 band | per contrast construction (§4.7) | +| `SKILL-S007` | `sarif-validity` | categorical | **`error`** | a `.sarif`/`.sarif.json` that is invalid JSON, missing `version`/`runs`, or whose `version` ≠ `"2.1.0"` (R5 nb) | +| `SKILL-S000` | `file-unreadable` | categorical | **`note`** | a regular file that is unreadable (permissions) or exceeds the 1 MiB cap (§3.2) | + +### 4.2 Severity: dual `level` + `rank` (R2 #6; R3 #2; R4 #1) + +Raw metric → `ScorerScale.normalizedGoodness` → `[0,1]` goodness (1 = ideal). Per occurrence, from the +**file's** goodness: **`rank` = `round((1 − goodness) × 100)`**; **`level`**: `≥0.5` clean (no finding), +`0.4–0.5` `warning`, `<0.4` `error` (`ScorecardFeedback:116-118`, cited; `note` reserved for S000). Scored +per file; clean files emit nothing. Categorical rules fix `level`, no `rank`. + +**`normalizedGoodness` formula (R9 · B1 — ported verbatim from `SkillEvalKit/Scoring/Scorer.swift:57-70`; +ScoreKit must reproduce it exactly so calibration matches):** +```swift +let span = max - min +guard span > 0 else { return 1.0 } // degenerate scale ⇒ nothing to judge +let t = Swift.max(0, Swift.min(1, (value - min) / span)) +switch good { +case .high: return t +case .low: return 1.0 - t +case .target(let target): + let distance = abs(value - target) + let maxDistance = Swift.max(target - min, max - target) + guard maxDistance > 0 else { return 1.0 } + return 1.0 - Swift.min(1.0, distance / maxDistance) // S003: value 0, target 1.5, max 10 ⇒ 1 − 1.5/8.5 ≈ 0.82 +} +``` + +**Per-scorer metric / denominator / scale — all verified against source (R4 #1); locked by fixtures:** + +| ruleId | raw metric | denominator | `ScorerScale(min,max,good)` | source (scale · denominator) | +|---|---|---|---|---| +| S001 | slop-word hits | per **1000 words** | `(0, 20, .low)` | AISlopScorers.swift **:39** · :57 | +| S002 | puffery hits | per **1000 words** | `(0, 20, .low)` | **:67** · :82 | +| S003 | em-dashes | **per 100 words** ✳ | `(0, 10, .target(1.5))` | **:92** · :105 | +| S004 | non-ref/non-tech triples | per **100 sentences** | `(0, 20, .low)` | **:115** · :128 | +| S005 | cutoff-phrase mentions | **raw count** | `(0, 5, .low)` | **:138** · :159 | +| S006 | contrast constructions | per **1000 words** | *provisional `(0, 15, .low)`* (§4.7) | new | + +✳ S003 is per **100** words (`* 100.0` at :105, target ~1.5/100w), not per-1000. Citations (R6 B1): the +**scale** is defined at the bold line, the **denominator/multiplier** at the second — both verified. + +**S003 target-scale intent (R8 · R4).** `.target(1.5)` with `max 10` penalizes **over-use**, not absence: a +clean article with **0 em-dashes** normalizes to goodness ≈ **0.82** (≥ 0.5 ⇒ **no finding**); S003 only fires +(goodness < 0.5) above ~5.75/100w. This is the intended ported behavior — a required calibration fixture +proves a 0-em-dash file stays silent so the target scale isn't mistaken for penalizing absence. + +### 4.3 SARIF `region` (R1 #7; R3 #12) +`startLine`+`startColumn`+`endLine`+`endColumn` (**1-based**) **and** `charOffset`+`charLength` (**0-based**, +per the SARIF spec), all counting **Unicode scalars** (R5 nb — stated to avoid an off-by-one). **`endColumn` +is the 1-based column immediately *after* the region (R6 nb)**, so for a single-line match `endColumn == +startColumn + charLength`. Categorical results: `artifactLocation`, no region. **Conversion task (R8 · R2):** +the scorers use `NSRegularExpression`, which returns **UTF-16 `NSRange`s** — a dedicated +`SARIFRegion.from(regexMatch:in:)` converts those to **scalar-counted** `charOffset`/`charLength` and 1-based +line/column, and is unit-tested with **emoji (astral), combining marks, CJK, and CRLF** (easy to get wrong; +§5). §5 asserts `startLine`/`startColumn` + the multi-byte case. + +### 4.4 `properties` +`skillet.`-namespaced: `skillet.density` (or `count` for S005), `skillet.denominator`, `skillet.goodness`, +`skillet.scale`. **Encoding (R6 nb):** `properties` is a `[String: JSONValue]` **map with literal dotted +keys**, not a struct — so both encoders emit `skillet.density` verbatim (JSON key-encoding strategies, +incl. the shared `.convertToSnakeCase`, do **not** transform dictionary keys), keeping the key stable across +the camelCase SARIF and snake_case `ScoreReport` outputs; goldens lock it. **`skillet.scale` shape:** `{ min: +Double, max: Double, good: "high"|"low"|"target", target: Double? }` (`target` present only when `good == +"target"`) — the enum's associated value is lifted to a sibling field so it serializes cleanly in both. + +### 4.5 `ScoreReport` / `skillet.score/1` — snake_case (R2 #6; R3 #6; R4 #8) +A new **EDDCore** type mirroring `LintReport` (`SchemaIdentified`), golden-tested. **It follows the house +`--json` convention — snake_case via the shared encoder** (like `skillet.lint/1`), **distinct from the SARIF +output's camelCase** (§4.6). The two casings are intentional: SARIF's is spec-mandated, `skillet.score/1`'s +is house-consistent. +``` +ScoreReport { schema = "skillet.score/1" + findings: [ { rule_id, level, rank?, message, + location{ file, start_line, start_column, end_line, end_column, char_offset, char_length }, + properties } ] // B2: density findings (S001–S006) carry ALL location + // fields. Categorical S000/S007: location is EXACTLY + // { file } — no start/end/char fields at all (R7 #2), + // mirroring SARIF artifactLocation with no `region`. + summary: { per_rule: { : }, // B3: a JSON object ([String: Int]), not an array + files_scored: Int, files_skipped: Int, files_unreadable: Int } } +``` +> Illustrative only — `SkilletJSON.encoder()` uses `.sortedKeys`, so `schema` is **not** first in real output; +> golden tests lock the sorted-key bytes, not this layout (R5 nb). +> **Compile-time shape (R9 risk):** `location` is a **sum type** — `.file(String)` for categorical S000/S007 +> vs `.region(file, startLine, …, charLength)` for density findings — so a categorical finding **cannot** carry +> region fields (the SARIF "`artifactLocation` with no `region`" rule is enforced by the type, not by convention). +> **Custom `Codable` required (R11 · B2):** a Swift enum does **not** synthesize to the documented *flat* object +> (`location{ file, start_line?, … }`) — the default encoding emits a case-tagged shape. `Location` needs a +> hand-written `Codable` that flattens both cases into one object: `file` always present; `start_line`/…/ +> `char_length` present only for `.region`. This is the sole part of the frozen `skillet.score/1` schema whose +> encoding isn't mechanical — a golden locks the exact bytes for both cases. + +### 4.6 Emitter: casing, `$schema`, `tool.driver.rules`, "schema-validated" (R1 #8; R2 #3/#7; R4 #6) +- **Distinct type name (R9 risk):** the typed emit-only model is **`SarifDocument`** (+ a `SarifEmitter` + serializer), **not** reusing `SarifLog` — the existing raw/tolerant *reader* stays under that name to avoid + confusion between the reader and the writer. +- **Dedicated camelCase encoder** for SARIF — **`SarifDocument` must not use `SkilletJSON.encoder()`** + (`JSON.swift:35-43`, snake_case), R11 risk; goldens lock `startLine`/`ruleId`/`$schema`/`tool.driver.rules` + literally. +- **`tool.driver` carries `name` ("skillet"), `version`, and a `rules[]`** — a **static catalog of the full + rule set S000–S007** (`id`, `name`, `shortDescription`), listed **regardless of whether a rule fired or is + disabled** (B4 — the SARIF-idiomatic "advertise your catalog" model; S006's default-off state rides in its + rule `properties`). This keeps golden tests stable when S006 is off; golden-asserted. +- **`$schema`** = `https://json.schemastore.org/sarif-2.1.0.json` (R8 · S1 · decided — the community mirror the + repo's reader test already uses; the value is advisory since consumers validate *structure*, not by fetching + the URL). A code comment cites the **OASIS canonical** schema URL as the authoritative provenance. **Emit-only**; + `SarifLog` stays the reader. + **"Schema-validated" = structural golden checks**, not an external validator. + +### 4.7 S006: matching rule, default-off, Option C (R1 #12; R3 #10; R4 #3 · Principle II) +**Matching rule (designed — R4 #3; EQ-Bench's contrast family, regex-only since a POS-tagger would be a new +dependency).** Case-insensitive; each match is **one intra-sentence span** (no `.?!` sentence-ender inside; +distance-capped ≤ ~60 chars), located at the negator, covering the three families: +1. `not (just|only|merely|simply) … but …` 2. `(it|that|this|they|we|you)'s not …, (it's|but) …` (the +"it's not X, it's Y" form) 3. `less about … more about …`. Metric = matches per 1000 words; **provisional +scale `(0, 15, .low)`**, both pinned by the calibration fixture. Because it is regex-only (no POS stage) and +uncalibrated, S006 ships **default-OFF**, opted in via `scorers.enable: ["SKILL-S006"]`; its calibration +fixture (legit `not X, but Y` prose must not over-flag; sloppy repetition must) is a **hard completion +gate**; default-on is deferred until evidence. **Option C future revisit:** the deferred markdown/tone checks +can later ship under this same opt-in tier. + +### 4.8 Generic matching for S004 / S005 + `.sarif` exclusion (R3 #8; R4 #2/#5) +- **S004 rule-of-three** — port `RuleOfThreeMatcher`, keeping its two skips (a triple `X, Y, and Z` is **not** + counted when **≥2 items are referential or technical**), with one generalization spelled out (**B1**): + - *Referential*: the predecessor's `isReferentialItem` checks a **markdown + link** `](`, a DocC **symbol** `` `` ``, and a DocC **article link** `]) // S001–S006 + case categorical(level: SarifLevel, message: String) // S007 + case notApplicable // e.g. 0 words +} +protocol Scorer { var ruleId: String { get }; var scale: ScorerScale { get } + func measure(_ file: ScoredFile, config: Scorers) -> ScorerMeasurement } +``` +The **runner** maps a measurement → findings: `.notApplicable` → none; `.density` → goodness = +`scale.normalizedGoodness(value)`; **goodness ≥ 0.5 → none (clean)**, else **one located finding per +occurrence** at the file's `level`/`rank` (§4.2). `.categorical` → one file-level finding. **S000 is emitted +by the file reader** during disposition (§3.2), not by a `Scorer`. + +**Counting (R10 #5) — ported verbatim; two units, deliberately.** Port `SlopTextStats.wordCount` +(AISlopScorers.swift:341) and `.sentenceCount` (:353) unchanged. **Denominators count `Character`s** +(graphemes, as the predecessor — changing this shifts every calibration number); **regions count Unicode +scalars** (SARIF, §4.3). Different purposes, different units — no conflict. + +**Per-rule match + region span (R10 #4).** Each density scorer is refactored from "return a count" to "return +count + the scalar range of each match"; **`SARIFRegion.from(scalarRange:in:)`** (generalized from the +regex-only form so the non-regex scorers work) turns a range into the region: + +| rule | match mechanism | region span | +|---|---|---| +| S001/S002 | word-list membership over `\b`-delimited words | the matched word's range | +| S003 | scalar scan for **U+2014 only** (not en-dash/`--`, :104) | the single em-dash scalar (`charLength 1`) | +| S004 | `RuleOfThreeMatcher` regex (:422) | the whole `X, Y, and Z` match (group 0) | +| S005 | case-insensitive phrase search **on the original text** (not a lowercased copy) | the matched phrase range | +| S006 | the three contrast regexes below | the whole contrast-span match | + +**Finding ordering (R10 #2) — determinism for goldens.** The walk order is irrelevant: after all files × +scorers run, **sort findings by `(relativePath, charOffset, ruleId)`** before emitting — the total order the +golden tests require (`FileManager` enumeration is unordered; `.sortedKeys` does not sort arrays). + +**Level band operators (R10 #11), exact (`ScorecardFeedback:117-118`):** `goodness ≥ 0.5` clean · `0.4 ≤ +goodness < 0.5` `warning` · `goodness < 0.4` `error`. + +**Word lists (R10 #8):** S001 = `AIVocabulary.combined` (AIVocabulary.swift:87) **only** (the un-ported +`FormalRegisterDensity` list is not merged in); S002 = `AIVocabulary.puffery` (:90). `vocab.exempt` filters +**both** (:54 for S001, :79 for S002). + +**S006 patterns (R10 #9), literal** (case-insensitive; each within one sentence — no `.?!` between; ≤ 60 scalars): +1. `\bnot\s+(just|only|merely|simply)\b[^.?!\n]{0,60}?\bbut\b` +2. `\b(it|that|this|they|we|you)['’]?s\b[^.?!\n]{0,60}?,\s*(it['’]?s|but)\b` +3. `\bless\s+about\b[^.?!\n]{0,60}?\bmore\s+about\b` +Located at the leading negator. The calibration fixture (the hard gate) locks these against false positives. + +**Multi-line regions (R10 #7).** Line break = **`\n`** (a `\r` immediately before `\n` is part of the ending; +a lone `\r` is content). `startLine` = 1 + `\n`-count before the range start; `startColumn` = 1 + scalars +since the last `\n`. A match crossing a `\n` sets `endLine > startLine`, `endColumn` = scalars on the final +line + 1. (Reachable via S004/S006 `\s+`; CRLF is in the §5 test matrix.) + +**Summary counters (R10 #6).** `files_scored` = readable text files run through ≥1 density scorer **incl. +zero-word files (0 findings) and `.sarif` files (S007 ran)**; `files_skipped` = read but non-scorable +(binary/non-UTF-8); `files_unreadable` = S000 (permission/oversized). Vendored/dot paths are excluded during +the walk and **not counted**. + +**Message text (R10 #3)** — `result.message.text` + each `tool.driver.rules[].shortDescription`: + +| rule | `message.text` | `shortDescription` | +|---|---|---| +| S001 | `` AI-slop vocabulary: `` `` | Over-used AI vocabulary | +| S002 | `` Marketing puffery: `` `` | Marketing-puffery language | +| S003 | `Over-used em-dash` | Em-dash over-use | +| S004 | `Rule-of-three rhetorical triple` | Rule-of-three over-use | +| S005 | `` Knowledge-cutoff disclaimer: `` `` | Knowledge-cutoff mention | +| S006 | `"not X, but Y" contrast construction` | Negative-parallelism over-use | +| S007 | `Invalid SARIF 2.1.0: ` | Emitted findings-file validity | +| S000 | `Not scored: unreadable (permissions)` / `Not scored: exceeds 1 MiB` | File not scored | + +**RenderKit `score` table (R10 #10):** columns `RULE · LEVEL · RANK · FILE:LINE · MESSAGE` via +`Renderer.renderTable`; empty state `✓ score: no findings` (mirroring lint's `✓ lint: no findings`, +Renderer.swift:153); summary `N findings (E error · W warning) across M files`. + +**Minors (R10).** Em-dash = **U+2014 only**. S007 "`runs` present" = the **key exists** (`SarifLog.runs` +returns `[]` when absent). `tool.driver.version` = `SkilletVersion.current`, **normalized in goldens** (not a +literal, so releases don't churn fixtures). No file-count cap on the walk (bounded per-file at 1 MiB — a +reporter walking everything is acceptable; stated so it isn't mistaken for an oversight). An unreadable or +oversized `.sarif` is **S000** (the read-failure rows in §3.2 precede S007). + +## 5. Test plan (TDD) — free-first + +1. **EDDCore goldens + region conversion.** SARIF emitter: exact 2.1.0 JSON, **camelCase literal**, + **`tool.driver.{name,version,rules}`** present (static S000–S007 catalog), a `region` with + `startLine`+`startColumn` **and** `charOffset`/`charLength`, `rank`+`level`, `skillet.` properties incl. + the `skillet.scale` shape — **incl. a golden for S003 asserting `skillet.scale.good == "target"` and + `skillet.scale.target == 1.5` (R9 risk — the sibling-field serialization + dictionary-key preservation)** — + empty `results: []` for zero findings. **`SARIFRegion.from(regexMatch:in:)` unit-tested (R8 · R2)** with + **emoji/astral, combining marks, CJK, and CRLF** → correct scalar offsets + 1-based line/column. + `ScoreReport`/`skillet.score/1` **snake_case** JSON golden (schema, `per_rule` object). +2. **ScoreKitTests** (≤300 lines/file, UUID temp dirs). + - *Per scorer, re-calibrated (S001–S006)*: clean → none; sloppy → located findings at expected scalar + line/column with the §4.2 `level`+`rank`; **S003 per-100-words + a 0-em-dash file stays silent (R8/R4)**; + **S004 both skips** — the + single-backtick generalization ("`` `foo`, `bar`, and `baz` ``" → **skip**), the technical skip + ("P2WPKH, P2WSH, and P2SH" → skip), **and a plain rhetorical triple ("fast, cheap, and reliable" → + count)** to prove the generalization doesn't over-suppress (R6 B1); **S005** phrase list + raw count; + **S006 matching-rule fixture** (the three families hit; legit contrast prose does not over-flag). + - *Config*: `vocab.exempt` phrase **removed from the word-list** (not flagged, source unchanged — R3); + **`vendored_prefixes` gitignore-matching (R8/B1)** — `Vendored/` skips `Vendored/x.md` **and** + `sub/Vendored/x.md` (any depth) but **scores** `VendoredFoo.swift` (different segment); case-sensitive; + skipped **before read**; **S006 off by default**, on via `enable`; a default-on scorer off via `disable`; + `disable` beats `enable`; outside-repo defaults; a **corrupt repo `skillet.yaml` → exit 4**. + - *File selection / safety*: dot-dirs (`.git`) skipped; symlink not followed; escape rejected; **binary / + non-UTF-8 → silently skipped (counted), no finding**; **unreadable / >1 MiB → an `S000` note, no crash**; + `.sarif` excluded from density, routed to S007. + - *Validity*: a malformed `.sarif`, and a well-formed one with `version: "2.0.0"` → an `S007` `error` + finding (exit **0**); an **oversized `.sarif` (> 1 MiB)** → an `S000` note and is **not** validated by + S007 (R5 nb — the read cap precedes validation). +3. **IntegrationTests (built binary).** `--format sarif` → structural 2.1.0 (incl. `tool.driver.rules`) on + stdout, **exit 0**, no model/net; **`--format json` → asserts top-level `schema == "skillet.score/1"` and + that `summary.per_rule` is an object keyed by rule-id, not an array (R8 · S2)**; `--json --format sarif` → + SARIF; `--format tty`/bare-pipe → the human table + next-step; single-file ``; clean folder → empty + findings; **missing `` argument → exit 2 (R8 · S3)**; **bad `` → exit 3**; **corrupt config → + exit 4**; unknown flag → 2. + +> **Moved-helper parity (R8 · R1; R10 #1):** `RunnerTests` re-points at ProjectKit (it names the moved +> helpers); `StagingParityTests`/`HarnessKitTests` stay green unchanged — together proving the +> confinement/safe-read move preserved behavior (§3.2). + +## 6. Docs ripple (§ doc-sync contract) + +- **Roadmap** F17: IMPLEMENTED; metric `score ` → `score ` + `` (Phase 3) note; **add a + tracked known-limitation line (R7 #7): the user/`$XDG_CONFIG_HOME` config layer for `scorers` is deferred to + F24** (repo + built-in defaults only in F17) — captured here so it does not silently drift vs design §5.2. +- **design.md**: **§6.2 `skillet score ` → ``** (`` deferred note); §5.2 the + `scorers` section + **the new `SkilletConfig.Scorers` model + its `CodingKeys`** documented in the config-model + list (R7 #4 — *not* a §7.2 frozen boundary *format*; it is a config model, now read rather than ignored); + §5.4/§6.2 **record the reporter-vs-gate reconciliation (R7 #6): `score` is a *reporter* — exit 0 even when + scorers fire (D6 "gates advise"; the scorer signal feeds later gating in triage F33 / contradiction F34) — + deliberately unlike `lint`, a *pre-paid gate* that exits 1 on an error-tier finding; a corrupt *config* + still exits 4**; §5.5 note `score` lands `--format` first + its progress/next-step; §11 `ScoreKit` shipped; + §7.2 `SKILL-Sxxx` beside `SKILL-Lxxx`. Header + changelog bump. + - **Design-doc amendment = a tracked deliverable landing *with* the feature commit (R9 · B4), proposed text:** + - **§6.2** — change the plumbing row to `skillet score ` · "Deterministic scorers → SARIF on stdout + (`--format sarif`); reporter, exit 0. `` input lands with capture (Phase 3)." + - **§5.2** — add: "`scorers:` — `vendored_prefixes` (gitignore-style folder skips), `vocab.exempt` (domain + terms removed from the slop word-list, whole-entry), `disable`/`enable` (rule-id opt-out/opt-in). Repo + + built-in defaults only; the user/`$XDG_CONFIG_HOME` layer lands with F24." **And explicitly (R11 · doc): + the built-in defaults are `[]` for *both* `vendored_prefixes` and `vocab.exempt`; `skillet init` pre-writes + `["Vendored/","Generated/"]` as a *suggestion*; the example values shown at design.md:174-186 (incl. + `["secp256k1","Schnorr"]`) are illustrative *template output*, not runtime defaults** — the current §5.2 + example doesn't draw that line and must. + - **§5.4** — add a note: "`score` is a **reporter**, not a gate: it exits 0 even when scorers fire (the + SARIF signal feeds triage/contradiction), deliberately unlike `lint`'s error-tier exit 1. A corrupt + config still exits 4." + These edits land in the same PR as F17 so the source-of-truth doc stays in sync (not deferred). +- **AGENTS.md** banner + Commands gains `score`; **README.md** command list gains `score`. +- **Package.swift**: `ScoreKit` (`EDDCore` + `ProjectKit`) + `ScoreKitTests`; `RunKit`/`HarnessKit` gain + `ProjectKit` (the moved helpers); `skillet` gains `ScoreKit`. +- **Specs/README.md** index: add `012`. **ROADMAP.md / ROADMAP-changelog.md**: F17 status + `score` row. + +## 7. Status log & review-round changelog + +- **2026-07-09 · Authored** + **Review round 1 (12)** + **round 2 (7 + Q&A)** + **round 3 (13, research)** — + see git history of this file; net: exit codes, config discovery, confinement, dual `level`+`rank`, one + `--format` selector (no auto-switch), five logics generalized + re-calibrated, ProjectKit home, `ScoreReport`, + `scorers` config, camelCase emitter, region unit = scalars, S006 default-off. +- **2026-07-09 · Review round 4 (8 blockers + non-blockers), research-cross-referenced.** (1) **S003 = per + 100 words** (verified `*100.0`); all denominators re-pinned against source. (2) **S004 retains + `isTechnicalItem`** (all-caps/digit/identifier) generalized, not just links/inline-code — prevents technical + triples over-flagging. (3) **S006 matching rule designed** (EQ-Bench contrast family, regex-only, three + intra-sentence patterns) + provisional scale. (4) **File-selection policy** added (regular, non-dot, + non-vendored candidates; no extension filter). (5) **`.sarif` excluded from S001–S006**, routed to S007. + (6) **`tool.driver.{name,version,rules}`** added to the emitter + goldens. (7) **Exit 4** for a corrupt + config (via `loadConfigWithOrigin`) added. (8) **`ScoreReport` is snake_case** (house `--json` convention), + distinct from SARIF camelCase; sample corrected. **Non-blockers:** design ref §7.6→§5.2; §6.2 `` + ripple; `vendored_prefixes` default `[]` vs template-suggested values clarified; `disable` beats `enable`; + `skillet.scale` JSON shape; S003 trigger wording; TTY progress note; next-step suggestion. **Architecture + risk** addressed: confinement/safe-read **moved** (not duplicated) into ProjectKit; ProjectKit stays + EDDCore-only, so RunKit/HarnessKit importing it is downward — no cycle. +- **2026-07-09 · Review round 5 (4 blockers + non-blockers), research-cross-referenced.** (B1) S004 + referential-skip corrected: `](` kept, ` cap` ⇒ `S000`, never + `decodeText` on the truncated prefix (so an oversized `.sarif` is never partially validated). **Non-blockers:** + `properties` is a dotted-key map both encoders emit verbatim (dictionary keys bypass `.convertToSnakeCase`); + `--format`↔`Renderer` wiring (`.json`/`.human`/`sarif`-bypass) stated; `Scorers` decodes with per-key + defaults (partial block doesn't zero siblings); `endColumn` = 1-based-after (`startColumn + charLength`); + S004 fixture made explicit (single-backtick skip, technical skip, rhetorical triple counts); documented why + SARIF is the special-cased extension (skillet-owned artifact; other machine files score near-zero naturally). +- **2026-07-09 · Review round 7 (4 blockers, 1 editorial + 3 clarifications).** (1) **Next-step claim + corrected** — `LintCommand.nextSteps()` filters by *registration*, not free-vs-paid; dropped the false + "free-only mirror" wording (score uses the same registration mechanism; a suggestion isn't a spend). + (2) **Categorical location shape pinned** — S000/S007 `location` is **exactly `{ file }`** (no start/end/char), + i.e. SARIF `artifactLocation` with no `region`. (3) **`.sarif` non-UTF-8/parse failure → S007 `error`** + (not a silent skip) — read-disposition rewritten as a table branching on `.sarif`-ness. (4) Removed the + **duplicate table header**; "frozen-artifact list" → **config-model list** (not a §7.2 boundary format). + (5) **S004 single-backtick predicate stated exactly** (`item` contains `` `[^`]+` `` — a superset that also + covers DocC `` ``X`` ``). (6) **Exit-0-with-findings recorded** as a deliberate reporter-vs-gate choice in + design §5.4/§6.2. (7) **Deferred user-config layer** tracked as a roadmap known-limitation vs §5.2. +- **2026-07-09 · Review round 8 (1 blocker, 2 clarifications, 4 risks, 4 minors) + decision Q&A.** **Decided:** + (B1) **`vendored_prefixes` = gitignore-style** folder-name-at-any-depth, whole-segment, case-sensitive, no + wildcards/anchoring in F17 (research: gitignore spec + ESLint follow it); (S1) **`$schema` = the community + mirror** (advisory value; OASIS canonical cited in a comment). **Applied:** (C1) reporter-not-gate rationale + lifted into the Assumptions cell (A3); (C2) `--format` resolved in code against `options.json`, not + ArgumentParser conflict handling; (R1) move ripple spelled out — `SkillBundleRules` → thin wrapper, + `StagingParity`/`RunnerTests` re-point at ProjectKit, ProjectKit stays Foundation+EDDCore-only (re-verify); + (R2) `SARIFRegion.from(regexMatch:in:)` converts UTF-16 `NSRange`→scalars, unit-tested with emoji/combining/ + CJK/CRLF; (R3) `vocab.exempt` **removes word-list entries**, not text-masking; (R4) S003 target-scale intent + confirmed (0 em-dashes ⇒ goodness ≈0.82 ⇒ silent; fixture proves it); (S2) integration asserts `schema` + + `per_rule` object; (S3) missing `` → exit 2; (S4) `boundedRead` keeps its `cap:` param (already true). +- **2026-07-09 · Review round 9 (4 blockers + risks; "implementation-ready" verdict).** (B1) **`normalizedGoodness` + formula added verbatim** to §4.2 (Scorer.swift:57-70) — S003's 0-em-dash⇒0.82 now reproducible. (B2) + **Global `--json` + local `--format` coexistence confirmed proven**, not a risk (`RunCommand` already does + `GlobalOptions.--json` + local `--judge`/`--axis`); precedence resolved in `run()`. (B3) **ProjectKit move + sequenced** as a prerequisite: (1) move + Package.swift, (2) green existing tests, (3) then ScoreKit. (B4) + **Design-doc amendment made a tracked deliverable with proposed §6.2/§5.2/§5.4 text**, landing in the F17 PR. + **Risks:** emitter named **`SarifDocument`/`SarifEmitter`** (distinct from the `SarifLog` reader); `.sarif` + detection by **exact suffix**, not substring; `ScoreReport.location` is a **sum type** enforcing categorical = + `{file}` at compile time; a golden pins `skillet.scale.good=="target"`/`target==1.5`. **Minors** all confirmed + (citations, snake_case encoder, untouched reader, TTY default). Implementation-ready. +- **2026-07-09 · Review round 10 (independent dual review — accuracy + implementability).** Accuracy pass + confirmed **every code citation correct** (rounds 6–9 held); fixed 5 drifts: (#1) `StagingParityTests` + does **not** call moved helpers — only `RunnerTests` does; (#2) `isSymlink` is **one impl re-exported**, not + duplicated, with more callers than listed; (#3/#4) two stale round-5 changelog phrases annotated as + superseded (trailing-slash; free-lint next-step); (#5) `vocab.exempt` cite → :54-55, filters both S001+S002. + **Implementability pass added §4.9** resolving the "how, not what" gaps the policy rounds missed: (#1) the + concrete **`Scorer`/`ScoredFile`/`ScorerMeasurement` model** + per-file scoring; (#2) **finding total-order** + `(path, charOffset, ruleId)`; (#3) **message + shortDescription text** table; (#4) **per-rule region spans** + + generalized `SARIFRegion.from(scalarRange:in:)`; (#5) **ported `wordCount`/`sentenceCount`** + the + Character-denominator / scalar-region unit split; (#6) **counter semantics**; (#7) **multi-line/CRLF region** + rule; (#8) **S001=`combined`/S002=`puffery`** list identity + exempt-filters-both; (#9) **literal S006 + regexes** + bound; (#10) **`score` table columns**; (#11) **exact band operators**. Minors: em-dash U+2014 + only, `runs`-key-exists, version normalized in goldens, no walk cap, S005 locate-on-original. Now specifies + *what* and *how*. +- **2026-07-09 · Review round 11 (4 blockers + risks + doc/sync).** (B1) **`vocab.exempt` = whole-list-entry + exact match (lowercased), not substring**, filtering **both** S001 `combined` and S002 `puffery` (verified + AISlopScorers.swift:51-55/:79-81) — `["tapestry"]` won't suppress a `"rich tapestry"` entry. (B2) + **`ScoreReport.Location` needs a hand-written `Codable`** to flatten the sum type into the documented flat + object (Swift won't synthesize it) — the one non-mechanical part of the `--json` schema, golden-locked. + (B3) **`SkilletConfig` init ripple** tracked: explicit init gains `scorers:` (additive; no direct call sites + — decode-only). (B4) **ProjectKit move is a hard CI gate** — full existing suite green as a separate refactor + commit before any scorer code; `StagingParityTests` passes *unchanged* (staying APIs), only `RunnerTests` + re-points. **Risks:** piped `--format sarif` example in `--help`; `SarifDocument` must not use the snake_case + encoder (goldens lock literals incl. `tool.driver.rules`). **Doc/sync:** amended §5.2 must state built-in + defaults are `[]` for both, `skillet init` pre-writes the vendored values as a *suggestion*, and design.md:174-186's + example values are illustrative template output, not runtime defaults. diff --git a/Specs/README.md b/Specs/README.md index 626118c..e46fb34 100644 --- a/Specs/README.md +++ b/Specs/README.md @@ -24,3 +24,4 @@ roadmap re-phasing. | 009 | The trigger axis — description-fires-skill measurement (`skillet run --axis trigger`) | 2 · F14 | Implemented | [plan.md](009-trigger-axis/plan.md) | | 010 | The A/B baseline arm — paired with/without-skill Δ (`skillet run --ab`) | 2 · F15 | Implemented | [plan.md](010-ab-baseline/plan.md) | | 011 | The grounded judge — file-contents grading (`skillet run --judge grounded-judge`) | 2 · F16 | Implemented | [plan.md](011-grounded-judge/plan.md) | +| 012 | Deterministic scorers → SARIF (`skillet score`) | 2 · F17 | Implemented | [plan.md](012-deterministic-scorers/plan.md) | diff --git a/Tests/EDDCoreTests/ScoreBoundaryTests.swift b/Tests/EDDCoreTests/ScoreBoundaryTests.swift new file mode 100644 index 0000000..ba6ee0f --- /dev/null +++ b/Tests/EDDCoreTests/ScoreBoundaryTests.swift @@ -0,0 +1,85 @@ +import Testing +import Foundation +@testable import EDDCore + +/// Frozen-format goldens for the F17 boundary types: the camelCase SARIF *writer* (`SarifDocument`) and +/// the snake_case native report (`ScoreReport`), including the hand-flattened `ScoreLocation`. +@Suite("F17 score boundary formats") +struct ScoreBoundaryTests { + private func sampleSarif() -> SarifDocument { + let rules = [ + SarifRule(id: "SKILL-S001", name: "slop-vocabulary", shortDescription: "Over-used AI vocabulary"), + SarifRule(id: "SKILL-S007", name: "sarif-validity", shortDescription: "Emitted findings-file validity") + ] + let region = SarifResult( + ruleId: "SKILL-S001", level: .warning, rank: 62, message: "AI-slop vocabulary: `delve`", + locations: [SarifLocation(physicalLocation: SarifPhysicalLocation( + artifactLocation: SarifArtifactLocation(uri: "notes.md"), + region: SarifRegion(startLine: 2, startColumn: 5, endLine: 2, endColumn: 10, charOffset: 12, charLength: 5)))], + properties: ["skillet.density": .number(8), "skillet.goodness": .number(0.38)]) + let categorical = SarifResult( + ruleId: "SKILL-S007", level: .error, rank: nil, message: "Invalid SARIF 2.1.0: missing version", + locations: [.file("out.sarif")], properties: nil) + return SarifDocument(runs: [SarifRun(tool: SarifTool(driver: SarifDriver( + name: "skillet", version: "0.0.0", rules: rules)), results: [region, categorical])]) + } + + @Test("SARIF writer emits camelCase keys, $schema, tool.driver.rules, rank, and a scalar region") + func sarifCamelCase() throws { + let json = try sampleSarif().jsonString() + // camelCase literals (NOT snake_case) — the GitHub/SonarQube-compatible casing. + for key in ["\"$schema\"", "\"version\":\"2.1.0\"", "\"ruleId\"", "\"startLine\"", "\"startColumn\"", + "\"endColumn\"", "\"charOffset\"", "\"charLength\"", "\"shortDescription\"", + "\"physicalLocation\"", "\"artifactLocation\"", "\"rank\":62", "\"tool\"", "\"driver\"", "\"rules\""] { + #expect(json.contains(key), "SARIF JSON missing \(key)") + } + #expect(json.contains("json.schemastore.org/sarif-2.1.0.json")) + #expect(!json.contains("rule_id") && !json.contains("start_line")) // never snake_case + #expect(json.contains("\"skillet.density\":8")) // dotted property key verbatim + // The categorical result carries no region. + #expect(json.contains("out.sarif")) + } + + @Test("Empty SARIF run round-trips to a valid empty results array") + func sarifEmpty() throws { + let doc = SarifDocument(runs: [SarifRun(tool: SarifTool(driver: SarifDriver(name: "skillet", version: "0.0.0", rules: [])), results: [])]) + let json = try doc.jsonString() + #expect(json.contains("\"results\":[]")) + #expect(json.contains("\"rules\":[]")) + } + + @Test("ScoreReport is snake_case, schema-stamped, per_rule is an object, and location flattens") + func scoreReportSnakeCase() throws { + let report = ScoreReport(findings: [ + ScoreFinding(ruleId: "SKILL-S001", level: .warning, rank: 62, message: "AI-slop vocabulary: `delve`", + location: .region(file: "notes.md", startLine: 2, startColumn: 5, endLine: 2, endColumn: 10, charOffset: 12, charLength: 5), + properties: ["skillet.density": .number(8)]), + ScoreFinding(ruleId: "SKILL-S007", level: .error, rank: nil, message: "Invalid SARIF 2.1.0", + location: .file("out.sarif"), properties: nil) + ], summary: ScoreSummary(perRule: ["SKILL-S001": 1, "SKILL-S007": 1], filesScored: 2, filesSkipped: 1, filesUnreadable: 0)) + let json = try SkilletJSON.encode(report) + + #expect(json.contains("\"schema\":\"skillet.score\\/1\"") || json.contains("\"schema\":\"skillet.score/1\"")) + for key in ["\"rule_id\"", "\"start_line\"", "\"start_column\"", "\"char_offset\"", "\"char_length\"", + "\"per_rule\"", "\"files_scored\"", "\"files_skipped\"", "\"files_unreadable\""] { + #expect(json.contains(key), "ScoreReport JSON missing \(key)") + } + #expect(json.contains("\"skillet.density\":8")) // dotted key verbatim in snake_case output too + // per_rule is an object keyed by rule id, not an array. + #expect(json.contains("\"per_rule\":{")) + #expect(json.contains("\"SKILL-S001\":1")) + // Flattened location: the categorical finding has `file` but NO region fields anywhere near it. + #expect(json.contains("\"file\":\"out.sarif\"")) + } + + @Test("ScoreReport round-trips: a file-only location decodes back to .file, a region to .region") + func scoreReportRoundTrip() throws { + let loc1 = ScoreLocation.file("a.md") + let loc2 = ScoreLocation.region(file: "b.md", startLine: 1, startColumn: 1, endLine: 1, endColumn: 3, charOffset: 0, charLength: 2) + for loc in [loc1, loc2] { + let data = try SkilletJSON.encoder().encode(loc) + let back = try SkilletJSON.decoder().decode(ScoreLocation.self, from: data) + #expect(back == loc) + } + } +} diff --git a/Tests/IntegrationTests/ScoreIntegrationTests.swift b/Tests/IntegrationTests/ScoreIntegrationTests.swift new file mode 100644 index 0000000..10477d5 --- /dev/null +++ b/Tests/IntegrationTests/ScoreIntegrationTests.swift @@ -0,0 +1,108 @@ +import Foundation +import Testing + +/// Drives the built `skillet score` binary end-to-end (F17): the three output surfaces, the format +/// precedence, and the exit-code contract. +@Suite("skillet score via the binary") +struct ScoreIntegrationTests { + private func tempDir(_ files: [String: String]) throws -> URL { + let dir = FileManager.default.temporaryDirectory.appendingPathComponent("score-it-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + for (name, content) in files { + let url = dir.appendingPathComponent(name) + try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data(content.utf8).write(to: url) + } + return dir + } + private func json(_ s: String) -> [String: Any]? { + (try? JSONSerialization.jsonObject(with: Data(s.utf8))) as? [String: Any] + } + private let sloppy = "This delve into the intricate tapestry shows a crucial testament.\n" + + @Test("--format sarif emits valid SARIF 2.1.0 (schema, tool.driver.rules, located result), exit 0") + func sarif() async throws { + let dir = try tempDir(["notes.md": sloppy]); defer { try? FileManager.default.removeItem(at: dir) } + let out = try await SkilletHarness().run(["score", dir.path, "--format", "sarif"]) + #expect(out.exitCode == 0) + let obj = json(out.stdout) + #expect(obj?["version"] as? String == "2.1.0") + #expect((obj?["$schema"] as? String)?.contains("sarif-2.1.0") == true) + let run0 = (obj?["runs"] as? [[String: Any]])?.first + let driver = ((run0?["tool"] as? [String: Any])?["driver"]) as? [String: Any] + #expect((driver?["name"] as? String) == "skillet") + #expect(((driver?["rules"] as? [[String: Any]])?.count ?? 0) >= 8) // static S000–S007 catalog + let result0 = (run0?["results"] as? [[String: Any]])?.first + #expect((result0?["ruleId"] as? String) == "SKILL-S001") + let region = (((result0?["locations"] as? [[String: Any]])?.first?["physicalLocation"]) as? [String: Any])?["region"] as? [String: Any] + #expect(region?["startLine"] != nil && region?["charOffset"] != nil) // camelCase, located + } + + @Test("--format json emits skillet.score/1 with an object-shaped per_rule") + func jsonFormat() async throws { + let dir = try tempDir(["notes.md": sloppy]); defer { try? FileManager.default.removeItem(at: dir) } + let out = try await SkilletHarness().run(["score", dir.path, "--format", "json"]) + #expect(out.exitCode == 0) + let obj = json(out.stdout) + #expect(obj?["schema"] as? String == "skillet.score/1") + let summary = obj?["summary"] as? [String: Any] + #expect(summary?["per_rule"] is [String: Any]) // object, not array + #expect(summary?["files_scored"] as? Int == 1) + } + + @Test("--json --format sarif → SARIF wins (explicit format beats the generic switch)") + func precedence() async throws { + let dir = try tempDir(["notes.md": sloppy]); defer { try? FileManager.default.removeItem(at: dir) } + let out = try await SkilletHarness().run(["score", dir.path, "--json", "--format", "sarif"]) + #expect(out.exitCode == 0) + #expect(out.stdout.contains("$schema") && out.stdout.contains("sarif-2.1.0")) + #expect(!out.stdout.contains("skillet.score/1")) + } + + @Test("Default (and a bare run) is the human table with a next-step") + func ttyDefault() async throws { + let dir = try tempDir(["notes.md": sloppy]); defer { try? FileManager.default.removeItem(at: dir) } + let out = try await SkilletHarness().run(["score", dir.path]) + #expect(out.exitCode == 0) + #expect(out.stdout.contains("SKILL-S001") && out.stdout.contains("MESSAGE")) + #expect(out.stdout.contains("→ next:")) + } + + @Test("A single file path is accepted; a clean folder emits valid empty findings, exit 0") + func fileAndClean() async throws { + let dir = try tempDir(["clean.md": "The parser reads input and returns output.\n"]) + defer { try? FileManager.default.removeItem(at: dir) } + let folder = try await SkilletHarness().run(["score", dir.path, "--format", "sarif"]) + #expect(folder.exitCode == 0) + #expect((((json(folder.stdout)?["runs"] as? [[String: Any]])?.first?["results"]) as? [Any])?.isEmpty == true) + let file = try await SkilletHarness().run(["score", dir.appendingPathComponent("clean.md").path]) + #expect(file.exitCode == 0) + } + + @Test("Exit codes: missing path → 2, bad path → 3, corrupt config → 4, unknown flag → 2") + func exitCodes() async throws { + let harness = try SkilletHarness() + #expect(try await harness.run(["score"]).exitCode == 2) // missing required + #expect(try await harness.run(["score", "/no/such/path"]).exitCode == 3) // environment + #expect(try await harness.run(["score", ".", "--frobnicate"]).exitCode == 2) // unknown flag + + // Corrupt repo skillet.yaml discovered from the working directory → artifact error (exit 4). + let bad = try tempDir(["skillet.yaml": "runs:\n k: [1, 2, 3]\n", "notes.md": sloppy]) + defer { try? FileManager.default.removeItem(at: bad) } + let out = try await harness.run(["score", bad.path], workingDirectory: bad) + #expect(out.exitCode == 4) + } + + @Test("Errors follow the chosen surface: --format json emits JSON on stderr; tty emits a human line") + func errorFollowsFormat() async throws { + let harness = try SkilletHarness() + let asJSON = try await harness.run(["score", "/no/such/path", "--format", "json"]) + #expect(asJSON.exitCode == 3) + #expect(asJSON.stdout.isEmpty) + #expect(asJSON.stderr.trimmingCharacters(in: .whitespacesAndNewlines).hasPrefix("{")) + #expect(asJSON.stderr.contains("path_not_found")) + let asTTY = try await harness.run(["score", "/no/such/path"]) + #expect(asTTY.exitCode == 3) + #expect(asTTY.stderr.contains("error:") && asTTY.stderr.contains("fix:")) + } +} diff --git a/Tests/ProjectKitTests/SafeFileTests.swift b/Tests/ProjectKitTests/SafeFileTests.swift new file mode 100644 index 0000000..170faf0 --- /dev/null +++ b/Tests/ProjectKitTests/SafeFileTests.swift @@ -0,0 +1,116 @@ +import Testing +import Foundation +@testable import ProjectKit + +/// Direct unit tests for the shared filesystem primitive extracted in F17. The suite covers the two +/// fiddly parts — the UTF-8-vs-binary decode heuristic and the size-capped read — plus the symlink / +/// hidden / confinement predicates, so the boundary is protected independently of its consumers. +@Suite("SafeFile — shared confinement + safe-read primitive") +struct SafeFileTests { + private func tempDir() -> URL { + let dir = FileManager.default.temporaryDirectory.appendingPathComponent("safefile-\(UUID().uuidString)") + try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + return dir + } + + // MARK: decodeText + + @Test("Plain UTF-8 and valid multi-byte decode; a NUL byte is binary") + func decodeBasics() { + #expect(SafeFile.decodeText(Data("hello".utf8), truncated: false) == "hello") + #expect(SafeFile.decodeText(Data("café ☕️".utf8), truncated: false) == "café ☕️") + #expect(SafeFile.decodeText(Data([0x61, 0x00, 0x62]), truncated: false) == nil) // NUL ⇒ binary + #expect(SafeFile.decodeText(Data(), truncated: false) == "") // empty is empty text + } + + @Test("Invalid UTF-8 that is NOT a truncation artifact stays binary") + func decodeInvalidUntruncated() { + // 0xFF is never valid UTF-8; without the truncation flag there is nothing to forgive. + #expect(SafeFile.decodeText(Data([0x61, 0xFF]), truncated: false) == nil) + } + + @Test("A truncated trailing incomplete multi-byte lead is trimmed, not misread as binary") + func decodeTruncatedBoundaryCut() { + // "caf" + 0xC3 (the incomplete lead byte of 'é') cut at the cap ⇒ trim the lead ⇒ "caf". + #expect(SafeFile.decodeText(Data([0x63, 0x61, 0x66, 0xC3]), truncated: true) == "caf") + } + + @Test("A genuine invalid byte at a truncated boundary still fails to binary (not stripped)") + func decodeTruncatedGenuineBinary() { + // 0xFF is neither a continuation byte nor a valid lead — even when truncated, it must stay binary. + #expect(SafeFile.decodeText(Data([0x61, 0xFF]), truncated: true) == nil) + } + + // MARK: boundedRead + + @Test("boundedRead returns up to `cap` bytes and the file's full size; nil when unreadable") + func boundedRead() throws { + let dir = tempDir(); defer { try? FileManager.default.removeItem(at: dir) } + let file = dir.appendingPathComponent("f.txt") + try Data("hello world".utf8).write(to: file) // 11 bytes + + let capped = SafeFile.boundedRead(file, cap: 5) + #expect(capped?.data == Data("hello".utf8)) + #expect(capped?.fullSize == 11) // full size from metadata, beyond the cap + + let whole = SafeFile.boundedRead(file, cap: 100) + #expect(whole?.data == Data("hello world".utf8)) + #expect(whole?.fullSize == 11) + + #expect(SafeFile.boundedRead(dir.appendingPathComponent("nope.txt"), cap: 10) == nil) + } + + // MARK: predicates + + @Test("isSymlink is lstat semantics; isHidden is a leading dot") + func predicates() throws { + let dir = tempDir(); defer { try? FileManager.default.removeItem(at: dir) } + let real = dir.appendingPathComponent("real.txt") + try Data("x".utf8).write(to: real) + let link = dir.appendingPathComponent("link.txt") + try FileManager.default.createSymbolicLink(at: link, withDestinationURL: real) + + #expect(SafeFile.isSymlink(link) == true) + #expect(SafeFile.isSymlink(real) == false) + #expect(SafeFile.isHidden(".git") == true) + #expect(SafeFile.isHidden("references") == false) + } + + @Test("firstSymlink finds a nested symlink; nil on a clean subtree") + func firstSymlink() throws { + let dir = tempDir(); defer { try? FileManager.default.removeItem(at: dir) } + let sub = dir.appendingPathComponent("sub") + try FileManager.default.createDirectory(at: sub, withIntermediateDirectories: true) + try Data("x".utf8).write(to: sub.appendingPathComponent("real.txt")) + #expect(SafeFile.firstSymlink(in: dir) == nil) + + try FileManager.default.createSymbolicLink(at: sub.appendingPathComponent("link"), + withDestinationURL: dir.appendingPathComponent("real.txt")) + #expect(SafeFile.firstSymlink(in: dir) != nil) + } + + @Test("firstSymlinkOnPath flags a symlinked component; returns target on escape; nil when confined") + func firstSymlinkOnPath() throws { + let root = tempDir(); defer { try? FileManager.default.removeItem(at: root) } + try FileManager.default.createDirectory(at: root.appendingPathComponent("real/sub"), withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink(at: root.appendingPathComponent("link"), + withDestinationURL: root.appendingPathComponent("real")) + + #expect(SafeFile.firstSymlinkOnPath(from: root, to: root.appendingPathComponent("real/sub")) == nil) // all real + #expect(SafeFile.firstSymlinkOnPath(from: root, to: root.appendingPathComponent("link/sub")) != nil) // crosses a symlink + let outside = URL(fileURLWithPath: "/etc/hosts") + #expect(SafeFile.firstSymlinkOnPath(from: root, to: outside) == outside) // escape ⇒ returns target + } + + @Test("noSymlink is false when any component is a symlink, true when the subtree is clean") + func noSymlink() throws { + let root = tempDir(); defer { try? FileManager.default.removeItem(at: root) } + let real = root.appendingPathComponent("real") + try FileManager.default.createDirectory(at: real.appendingPathComponent("sub"), withIntermediateDirectories: true) + #expect(SafeFile.noSymlink(at: real.appendingPathComponent("sub"), under: root) == true) + + let link = root.appendingPathComponent("link") + try FileManager.default.createSymbolicLink(at: link, withDestinationURL: real) + #expect(SafeFile.noSymlink(at: link.appendingPathComponent("sub"), under: root) == false) + } +} diff --git a/Tests/RunKitTests/RunnerTests.swift b/Tests/RunKitTests/RunnerTests.swift index f41c2e2..21183fb 100644 --- a/Tests/RunKitTests/RunnerTests.swift +++ b/Tests/RunKitTests/RunnerTests.swift @@ -4,6 +4,7 @@ import EDDCore import TraceKit import HarnessKit import JudgeKit +import ProjectKit // SafeFile — the confinement helpers now live here (F17) @testable import RunKit @Suite("RunKit") @@ -125,8 +126,8 @@ struct RunKitTests { let root = tempDir(); defer { try? FileManager.default.removeItem(at: root) } try FileManager.default.createDirectory(at: root.appendingPathComponent("real/sub"), withIntermediateDirectories: true) try FileManager.default.createSymbolicLink(at: root.appendingPathComponent("link"), withDestinationURL: root.appendingPathComponent("real")) - #expect(WorkspaceManager.firstSymlinkOnPath(from: root, to: root.appendingPathComponent("real/sub")) == nil) // every component real - #expect(WorkspaceManager.firstSymlinkOnPath(from: root, to: root.appendingPathComponent("link/sub")) != nil) // crosses a symlink + #expect(SafeFile.firstSymlinkOnPath(from: root, to: root.appendingPathComponent("real/sub")) == nil) // every component real + #expect(SafeFile.firstSymlinkOnPath(from: root, to: root.appendingPathComponent("link/sub")) != nil) // crosses a symlink } @Test("fixtures/ falls back to evaluations/fixtures/ as the physical source, staged as fixtures/") @@ -201,7 +202,7 @@ struct RunKitTests { let base = tempDir(); defer { try? FileManager.default.removeItem(at: base) } let ws = try WorkspaceManager().prepare(skill: SkillRef(name: "demo", path: skill.path), files: [], base: base, label: "t0") #expect(!FileManager.default.fileExists(atPath: ws.root.appendingPathComponent(".claude/skills/demo/secret").path)) - #expect(WorkspaceManager.firstSymlink(in: skill) != nil) // the helper detects it (preflight fails loud on it) + #expect(SafeFile.firstSymlink(in: skill) != nil) // the helper detects it (preflight fails loud on it) } @Test("listing() returns produced files as ground truth, excluding the injected .claude tree") diff --git a/Tests/ScoreKitTests/ScoreKitTests.swift b/Tests/ScoreKitTests/ScoreKitTests.swift new file mode 100644 index 0000000..9292192 --- /dev/null +++ b/Tests/ScoreKitTests/ScoreKitTests.swift @@ -0,0 +1,167 @@ +import Testing +import Foundation +import EDDCore +@testable import ScoreKit + +/// Behavior + calibration for the deterministic scorers. Samples are small and targeted, seeded with the +/// real predecessor slop words/patterns (per the plan): a clean sample stays silent, a sloppy sample +/// fires at the expected rule/level. Runs end-to-end through `ScoreRunner` over temp files. +@Suite("ScoreKit — scorers, disposition, calibration") +struct ScoreKitTests { + private func run(_ files: [String: String], + config: SkilletConfig.Scorers = SkilletConfig.Scorers()) -> ScoreRunner.Output { + let dir = FileManager.default.temporaryDirectory.appendingPathComponent("score-\(UUID().uuidString)") + try! FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + defer {} // caller-independent temp; left for the OS to reap + for (name, content) in files { + let url = dir.appendingPathComponent(name) + try! FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + try! Data(content.utf8).write(to: url) + } + return ScoreRunner(toolVersion: "0.0.0").run(path: dir, config: config) + } + private func findings(_ out: ScoreRunner.Output, _ rule: String) -> [ScoreFinding] { + out.report.findings.filter { $0.ruleId == rule } + } + + // MARK: calibration — clean stays silent, sloppy fires + + @Test("S001 slop-vocabulary: clean prose is silent; sloppy prose fires with a located message") + func s001() { + #expect(findings(run(["a.md": "The parser reads the file and returns a value cleanly here."]), "SKILL-S001").isEmpty) + let out = run(["a.md": "This delve into the intricate tapestry shows a crucial testament indeed."]) + let f = findings(out, "SKILL-S001") + #expect(!f.isEmpty) + #expect(f.allSatisfy { $0.level == .error || $0.level == .warning }) + #expect(f.contains { $0.message.contains("delve") }) + } + + @Test("S002 puffery fires on marketing language") + func s002() { + #expect(findings(run(["a.md": "The function parses input and writes output."]), "SKILL-S002").isEmpty) + #expect(!findings(run(["a.md": "This world-class library works seamlessly and stands as a lifeline."]), "SKILL-S002").isEmpty) + } + + @Test("S003 em-dash: a 0-em-dash file stays SILENT (target scale, not penalizing absence); over-use fires") + func s003() { + #expect(findings(run(["a.md": "A clean technical sentence with no em dashes at all here."]), "SKILL-S003").isEmpty) + #expect(!findings(run(["a.md": "One—two—three—four dashes pack this short line densely now."]), "SKILL-S003").isEmpty) + } + + @Test("S004 rule-of-three: rhetorical triple fires; technical + inline-code triples are skipped") + func s004() { + #expect(!findings(run(["a.md": "It is fast, cheap, and reliable."]), "SKILL-S004").isEmpty) // rhetorical + #expect(findings(run(["a.md": "The variants P2WPKH, P2WSH, and P2SH all work."]), "SKILL-S004").isEmpty) // technical skip + #expect(findings(run(["a.md": "Compose `foo`, `bar`, and `baz` together."]), "SKILL-S004").isEmpty) // inline-code skip + } + + @Test("S005 knowledge-cutoff: three disclaimer phrases fire as a raw count") + func s005() { + #expect(findings(run(["a.md": "The API returns a value synchronously."]), "SKILL-S005").isEmpty) + let out = run(["a.md": "As of my last update, my training data is limited, and I cannot verify this."]) + #expect(!findings(out, "SKILL-S005").isEmpty) + } + + @Test("S006 not-x-but-y is DEFAULT-OFF; enabling it via config makes the contrast fire") + func s006() { + let text = "It's not about speed, it's about correctness." + #expect(findings(run(["a.md": text]), "SKILL-S006").isEmpty) // off by default + let enabled = SkilletConfig.Scorers(enable: ["SKILL-S006"]) + #expect(!findings(run(["a.md": text], config: enabled), "SKILL-S006").isEmpty) // on via enable + } + + // MARK: config + + @Test("vocab.exempt removes a whole word-list entry (so the exempt term stops firing)") + func exempt() { + let text = "This tapestry and tapestry and tapestry is everywhere." + #expect(!findings(run(["a.md": text]), "SKILL-S001").isEmpty) + let exempted = SkilletConfig.Scorers(vocab: .init(exempt: ["tapestry"])) + let out = run(["a.md": text], config: exempted) + #expect(!out.report.findings.contains { $0.message.contains("tapestry") }) + } + + @Test("vendored_prefixes skips a folder at any depth (gitignore-style), never a look-alike file") + func vendored() { + let files = ["Vendored/x.md": "delve delve delve here.", "sub/Vendored/y.md": "delve delve delve here.", + "VendoredFoo.md": "delve delve delve here."] + let config = SkilletConfig.Scorers(vendoredPrefixes: ["Vendored/"]) + let out = run(files, config: config) + // Only VendoredFoo.md (a look-alike file, not a Vendored folder) is scored. + let paths = Set(out.report.findings.compactMap { finding -> String? in + if case let .region(file, _, _, _, _, _, _) = finding.location { return file } else { return nil } }) + #expect(paths == ["VendoredFoo.md"]) + } + + @Test("disable turns a default-on scorer off") + func disable() { + let text = "This delve into the intricate tapestry shows a crucial testament." + #expect(!findings(run(["a.md": text]), "SKILL-S001").isEmpty) + #expect(findings(run(["a.md": text], config: SkilletConfig.Scorers(disable: ["SKILL-S001"])), "SKILL-S001").isEmpty) + } + + // MARK: disposition + + @Test("A malformed .sarif is an S007 error (exit stays 0); a valid one is silent and un-scored") + func sarifValidity() { + #expect(!findings(run(["out.sarif": "{ not json"]), "SKILL-S007").isEmpty) + #expect(!findings(run(["out.sarif": #"{"version":"2.0.0","runs":[]}"#]), "SKILL-S007").isEmpty) // wrong version + let valid = run(["out.sarif": #"{"version":"2.1.0","runs":[]}"#]) + #expect(findings(valid, "SKILL-S007").isEmpty) + #expect(findings(valid, "SKILL-S001").isEmpty) // excluded from density scoring + } + + @Test("A binary file is silently skipped (counted, no finding); an oversized file is an S000 note") + func skipAndOversize() { + let binary = run(["b.dat": "\u{0}binary data with a NUL"]) // NUL ⇒ decodeText returns nil ⇒ binary + #expect(binary.report.summary.filesSkipped >= 1) + #expect(findings(binary, "SKILL-S000").isEmpty) + + let big = String(repeating: "word ", count: 230_000) // > 1 MiB + let over = run(["big.md": big]) + #expect(!findings(over, "SKILL-S000").isEmpty) + #expect(over.report.summary.filesUnreadable >= 1) + } + + @Test("Findings are sorted deterministically by (path, offset, rule)") + func ordering() { + let out = run(["z.md": "delve here.", "a.md": "delve tapestry crucial here."]) + let paths = out.report.findings.compactMap { f -> String? in + if case let .region(file, _, _, _, _, _, _) = f.location { return file } else { return nil } } + #expect(paths == paths.sorted()) // a.md before z.md + } + + // MARK: region math + + @Test("Region offsets count Unicode scalars, not UTF-16 units or bytes (multi-byte safe)") + func scalarRegion() { + // 😀 (one scalar) + space + "delve": 'delve' starts at scalar offset 2, column 3. + let out = run(["e.md": "😀 delve delve delve."]) + let f = findings(out, "SKILL-S001").first + guard case let .region(_, startLine, startColumn, _, _, charOffset, charLength)? = f?.location else { + Issue.record("expected a region finding"); return + } + #expect(startLine == 1) + #expect(charOffset == 2) // 😀=0, space=1, d=2 + #expect(startColumn == 3) // 1-based + #expect(charLength == 5) // "delve" + } + + @Test("Region math counts scalars for combining marks + CJK, and treats CRLF as one line break") + func regionMath() { + // Combining mark: "é" as e + U+0301 = TWO scalars before the space. + let combining = "e\u{301} delve" + let r1 = SarifRegionCompute.region(for: combining.range(of: "delve")!, in: combining) + #expect(r1.charOffset == 3 && r1.startColumn == 4) // e(0) ́(1) space(2) d(3) + + // CJK: each ideograph is one scalar. + let cjk = "日本語 delve" + let r2 = SarifRegionCompute.region(for: cjk.range(of: "delve")!, in: cjk) + #expect(r2.charOffset == 4 && r2.startColumn == 5) // 日(0)本(1)語(2)space(3)d(4) + + // CRLF: the \r is part of the ending, so the match is on line 2, column 1. + let crlf = "top\r\ndelve" + let r3 = SarifRegionCompute.region(for: crlf.range(of: "delve")!, in: crlf) + #expect(r3.startLine == 2 && r3.startColumn == 1) + } +} diff --git a/skillet-design-changelog.md b/skillet-design-changelog.md index 5e2ba5f..28b040f 100644 --- a/skillet-design-changelog.md +++ b/skillet-design-changelog.md @@ -8,6 +8,10 @@ so the hot document stays lean. Latest first; every version is a linkable headin record is its [`Specs/NNN` plan](Specs/README.md) status; design-only or decision changes are recorded here in full; other logs (ROADMAP, phase files) carry a short summary + link. Companion: [`ROADMAP-changelog.md`](ROADMAP-changelog.md). +## v0.49 — 2026-07-09 + +**F17 SHIPPED: deterministic scorers → SARIF (`skillet score`).** Adds `skillet score [--format tty|json|sarif]` — a reporter, not a gate (exit 0 even with findings; exit 3 for a missing/unreadable ``, exit 4 for a corrupt repo `skillet.yaml`); new `ScoreKit` (deps `EDDCore` + `ProjectKit`) with scorers S001–S007 plus S000 file-unreadable; new `scorers:` config block (`vendored_prefixes`, `vocab.exempt`, `disable`, `enable`) in `skillet.yaml`; EDDCore `SarifDocument`/`ScoreReport` frozen boundary formats; RenderKit human table and next-step. S006 is experimental and default-off (recorded in its SARIF rule `properties`); S007 validates `.sarif`/`.sarif.json` files for structural 2.1.0 conformance. ProjectKit owns the moved safe-read + confinement helpers. 390 tests green. Detail: [Specs/012](Specs/012-deterministic-scorers/plan.md); design §6.2, §5.2, §11. + ## v0.48 — 2026-07-08 **F16 optional-polish review round 6 (4 observations; 2 acted, 2 reaffirmed-as-tracked).** ACTED: (1) `import TraceKit` added to **both** `GroundedJudge.swift` and `TextJudge.swift` — the reviewer noted GroundedJudge's implicit dependency, and on checking, its sibling `TextJudge` had the identical implicit dependency (both use `evidence.trace` and relied on `Judge.swift`'s module import), so making it explicit in both keeps them consistent rather than adding it to one. (2) A dedicated `FileContent.omitted` flag: when the total evidence budget is spent before a file, it's now disclosed as `omitted: true` (with `sizeBytes`) instead of overloading `truncatedBytes` — so `truncatedBytes > 0` now **strictly** pairs with a shown `content` prefix, sharpening the judge contract (the prompt lists `omitted` among the withheld reasons; the total-cap test asserts it). REAFFIRMED as tracked future items (no change): `snapshotStaged`'s full-fixture read (bounded reads — fixtures are maintainer-controlled/copied, not a boundary) and a `--judge` `ExpressibleByArgument` enum (fine at two values; the raw string keeps the CLI value == recorded `judge_id`). Also noted in-code: `FileContent`'s six withheld-reason booleans are ripe to consolidate into one enum on the next substantive touch. No grading-behavior change. Detail: [Specs/011](Specs/011-grounded-judge/plan.md). 356 tests green. ROADMAP → v1.16.6. diff --git a/skillet-design.md b/skillet-design.md index bccca2e..5e16950 100644 --- a/skillet-design.md +++ b/skillet-design.md @@ -3,12 +3,12 @@ | | | |---|---| -| **Status** | Draft v0.48 — for review | +| **Status** | Draft v0.49 — for review | | **Name** | `skillet` (settled — SKILL · E · T, the *SKILL.md Evaluation Toolkit*); EDD remains the methodology's name | | **Deliverable** | Public, open-source, multi-harness Swift CLI | | **Supersedes** | The repo-private `swift-skill-eval` tool + the Python trigger harness | | **Decision provenance** | §2 — every load-bearing choice here was settled in the design Q&A | -| **Revision log** | Extracted to [skillet-design-changelog.md](skillet-design-changelog.md) (v0.1 → v0.48, latest first, one linkable heading per version; historical entries never rewritten). Latest — v0.48 (2026-07-08): F16 polish round 6 — explicit `import TraceKit` in both judge files, and a dedicated `FileContent.omitted` flag so `truncatedBytes` strictly means "a prefix was shown" (budget-omitted files no longer overload it); `snapshotStaged` bounded-read and a `--judge` enum reaffirmed as tracked future items. No behavior change to grading. (v0.47: hard-link guard.) | +| **Revision log** | Extracted to [skillet-design-changelog.md](skillet-design-changelog.md) (v0.1 → v0.49, latest first, one linkable heading per version; historical entries never rewritten). Latest — v0.49 (2026-07-09): F17 deterministic scorers shipped — `skillet score [--format tty|json|sarif]`, `ScoreKit` (S001–S007/S000), `scorers:` config block in `skillet.yaml`, SARIF 2.1.0 emitter, `ScoreReport` boundary format, and human table. (v0.48: F16 polish round 6.) | --- @@ -176,15 +176,25 @@ gates: # (Supersedes the predecessor's .skill-eval/vendored-prefixes.txt and vocab-exemptions.txt; # one-time import via `skillet migrate knobs`.) scorers: - vendored_prefixes: ["Vendored/", "Generated/"] + vendored_prefixes: ["Vendored/", "Generated/"] # ILLUSTRATIVE — see note vocab: - exempt: ["secp256k1", "Schnorr"] + exempt: ["secp256k1", "Schnorr"] # ILLUSTRATIVE — see note + disable: [] # default-on `SKILL-Sxxx` ids to turn off + enable: [] # experimental/default-off ids to turn on (e.g. ["SKILL-S006"]) lint: disable: [] # stable rule ids, e.g. ["SKILL-L011"] body_warn_lines: 500 # SKILL-L003: warn above this … body_error_lines: 1000 # … error above this ``` +> **`scorers:` defaults vs. suggestions (F17).** The **built-in defaults are `[]`** for both +> `vendored_prefixes` and `vocab.exempt` (score everything; exempt nothing). The values shown above are +> **illustrative template output**, not runtime defaults — `skillet init` pre-writes the +> `["Vendored/","Generated/"]` skips as a starting suggestion, and `secp256k1`/`Schnorr` illustrate the +> per-repo domain-term exemptions a crypto skill might add. `vendored_prefixes` matches gitignore-style +> (a folder name at any depth; whole-segment; case-sensitive); `vocab.exempt` removes whole word-list +> entries (case-insensitive) before scoring. The user/`$XDG_CONFIG_HOME` layer is deferred to F24. + > **Config writes stay surgical.** `swift-yaml` (§11) parses this file but does not > preserve comments on re-emit, so `skillet config set` rewrites the targeted lines > in place rather than parse→mutate→serialize — the documented defaults above @@ -232,6 +242,12 @@ standard environment: `NO_COLOR`/`TERM` (color), `EDITOR` (`friction add`), `PAG > by the eval loader, which runs first). The code is **command-contextual**: `skillet lint`'s own > error-tier finding is *that command's result* → exit 1; the same finding as `run`'s *preflight* → exit 2. +> **`score` is a reporter, not a gate (F17).** `skillet score` is deterministic-first *signal* that feeds +> triage/§8 — it emits findings and **exits 0 even when scorers fire**, deliberately unlike `lint`'s +> error-tier gate (exit 1). A missing/unreadable `` is exit 3 (environment) and a corrupt +> `skillet.yaml` is still exit 4 (artifact); a malformed *scored* `.sarif` under `` is a *finding* +> (`SKILL-S007`), never a command failure. CI that wants a hard gate keys off the emitted SARIF itself. + ### 5.5 Output contract Human output is conversational, table-oriented, and ends with a suggested next command. It is **not** an API. `--json` payloads each carry `"schema": "skillet./1"` and are versioned independently of the binary. Timestamps in artifacts are ISO-8601 UTC. Prompts appear only on a TTY and every prompt has a flag equivalent. @@ -321,6 +337,25 @@ Roadmap rules, framed as *additions* (not existing behavior): name↔directory m This command is the implementer of the `lint` lever, the free pre-API gate (`skillet lint && skillet fixtures verify` is the intended pre-commit pair), its error-tier findings surface in `doctor` and `next`, and it's where "fix it without touching prose" usually lands. +##### The `SKILL-Sxxx` scorer catalog (F17) + +`skillet score` (§6.2 plumbing) emits its own stable id space beside `SKILL-Lxxx` — the deterministic-first +signal over produced *output* (vs. lint's checks over *source*). Unlike lint, scorers **never gate** (§5.4). + +| ID | Checks | Level | +|---|---|---| +| `SKILL-S001` slop-vocabulary | over-used AI vocabulary density (`WP:AIVOCAB`) | note/warning/error | +| `SKILL-S002` puffery | marketing-puffery density (`WP:AIPUFFERY`) | note/warning/error | +| `SKILL-S003` em-dash | em-dash (U+2014) over-use vs. a ~1.5/100w target | note/warning/error | +| `SKILL-S004` rule-of-three | rhetorical `X, Y, and Z` triples (technical/inline-code triples skipped) | note/warning/error | +| `SKILL-S005` knowledge-cutoff | AI knowledge-cutoff disclaimer count | note/warning/error | +| `SKILL-S006` not-x-but-y | "not X, but Y" contrast constructions — **experimental, default-off** (`scorers.enable`) | note/warning/error | +| `SKILL-S007` sarif-validity | a produced `.sarif`/`.sarif.json` parses as SARIF 2.1.0 | error | +| `SKILL-S000` file-unreadable | a file couldn't be scored (unreadable/oversized) — disclosure | note | + +Density levels derive from a ported goodness scale (≥0.5 clean, 0.4–0.5 `warning`, <0.4 `error`); each finding +also carries a continuous `rank` (0–100). Exemptions/skips live in the `[scorers]` knob tables (§5.2). + --- #### `skillet run` @@ -576,7 +611,7 @@ Everything porcelain does decomposes into these; all support `--json`; their con | `skillet harness which [--search ]` | Print the resolved binary as an `export`-able pin; `--search` is the *opt-in* recursive vendored-copy finder — it probes each candidate's `--version` and picks the **highest non-denylisted version** (newest-mtime only as a tiebreaker), so it never returns a stale or banned copy. Adapters never auto-probe other apps' private caches (§9.1) | | `skillet grade --rubric --against ` | One Judge pass over criteria; the grading primitive | | `skillet grade --run [--judge ]` | Offline re-grade of a recorded run under a new judge/prompt version — no harness, no re-execution | -| `skillet score ` | Deterministic scorers → SARIF on stdout | +| `skillet score ` | Deterministic, model-free scorers over produced text → SARIF on stdout (`--format tty\|json\|sarif`). A **reporter, not a gate**: exit 0 even with findings (feeds triage/§8); config-corrupt → exit 4. *(saved-run `` input arrives with capture, Phase 3.)* **Shipped (F17).** | | `skillet baseline compare --from --to ` | SARIF drift between two captures: resolution-to-discovery ratio, severity drift (pp), rule-ID Shannon entropy — emitted **un-gated** (§8) | | `skillet baseline matrix ` | Cross-corpus drift: per-rule trajectories across packages, surfacing **generalizing rules** (firing in ≥3 packages) and **stuck rules** (zero variance across ≥3) as producer-skill friction candidates | | `skillet fixtures verify []` | The producer-output contract: every finding in a fixture's `expected.audit-baseline.sarif` must appear in `actual` (recall), and any extra `ruleId` must be in `fixture.json`'s `allowedExtraRuleIds`. For SARIF-emitting skills this is the *only* positive-output correctness assertion — judges grade prose, not emitted-finding recall |