From b5d6780ee0c5d48f2a82d4e69705970602bf6fdd Mon Sep 17 00:00:00 2001 From: rebuildup Date: Mon, 23 Nov 2026 21:08:40 +0900 Subject: [PATCH 1/2] 97: add deterministic gate honesty checker and false-green controls --- .github/workflows/eval-controls.yml | 2 + package.json | 1 + scripts/quality/check-gate-honesty.mts | 272 ++++++++++++++++++ scripts/quality/check-gate-honesty.test.mts | 145 ++++++++++ skills/quality-gate/SKILL.md | 2 + .../quality-gate/references/gate-honesty.md | 27 ++ 6 files changed, 449 insertions(+) create mode 100644 scripts/quality/check-gate-honesty.mts create mode 100644 scripts/quality/check-gate-honesty.test.mts create mode 100644 skills/quality-gate/references/gate-honesty.md diff --git a/.github/workflows/eval-controls.yml b/.github/workflows/eval-controls.yml index d495dc1..9fde2c8 100644 --- a/.github/workflows/eval-controls.yml +++ b/.github/workflows/eval-controls.yml @@ -22,6 +22,8 @@ jobs: run: shellcheck --version - name: Check whole-repository analysis and references run: bun run quality:structure + - name: Check workflow gate honesty + run: node scripts/quality/check-gate-honesty.mts workflow .github/workflows/eval-controls.yml - name: Test quality checks and challenge executor run: bun run test:system-quality - name: Challenge actual repository checks diff --git a/package.json b/package.json index 7194fe6..55374c8 100644 --- a/package.json +++ b/package.json @@ -12,6 +12,7 @@ "delivery-status": "node scripts/delivery-status/delivery-status.mts", "test:supervisor-boundary": "node --test templates/supervisor-boundary/guard.test.mts", "quality:structure": "node scripts/quality/check.mts", + "test:gate-honesty": "node --test scripts/quality/check-gate-honesty.test.mts", "test:system-quality": "node --test evals/system-quality/*.test.mts evals/code-structure/*.test.mts scripts/quality/*.test.mts", "quality:challenge": "node evals/system-quality/challenge.mts" }, diff --git a/scripts/quality/check-gate-honesty.mts b/scripts/quality/check-gate-honesty.mts new file mode 100644 index 0000000..3db52e7 --- /dev/null +++ b/scripts/quality/check-gate-honesty.mts @@ -0,0 +1,272 @@ +#!/usr/bin/env node +import { readFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { parse as parseYaml } from "yaml"; + +export interface TestPartitionReport { + readonly partition: string; + readonly exitCode: number; + readonly reportedSuccess: boolean; + readonly numCollectedFiles: number; + readonly numTotalTests: number; + readonly numPassedTests: number; + readonly numFailedTests: number; + readonly numSkippedTests: number; + readonly minPassedRequired?: number; +} + +export type ExecutionVerdict = "VERIFIED" | "FAIL_CLOSED_SAFE" | "SILENT_PASS_DEFECT"; + +export interface GateFinding { + readonly code: + | "ZERO_EXECUTED_SILENT_PASS" + | "ALL_SKIPPED_SILENT_PASS" + | "BELOW_MIN_PASSED_FLOOR" + | "INCONSISTENT_SUCCESS_EXIT" + | "MERGE_TREE_VS_HEAD_REF_MISMATCH" + | "MASKED_STEP_FAILURE" + | "SKIPPED_REQUIRED_PARTITION" + | "FALLBACK_CONTRADICTS_CLAIM" + | "UNVERIFIED_PROSE_MIRROR" + | "SHA_MISMATCH"; + readonly subject: string; + readonly detail: string; +} + +export interface ExecutionCheckResult { + readonly verdict: ExecutionVerdict; + readonly findings: readonly GateFinding[]; +} + +export function checkTestExecution(report: TestPartitionReport): ExecutionCheckResult { + const findings: GateFinding[] = []; + const floor = report.minPassedRequired ?? 1; + + // Distinguish fail-closed (e.g. u-sekai #78: 0 files collected, exit 1) + // from silent pass (e.g. ty-plus #179: files collected, 0 tests executed, exit 0). + if (report.exitCode !== 0) { + if (report.reportedSuccess) { + findings.push({ + code: "INCONSISTENT_SUCCESS_EXIT", + subject: report.partition, + detail: `partition reported success=true despite non-zero exit code ${report.exitCode}`, + }); + return { verdict: "SILENT_PASS_DEFECT", findings }; + } + return { verdict: "FAIL_CLOSED_SAFE", findings: [] }; + } + + if (report.numFailedTests > 0 && report.reportedSuccess) { + findings.push({ + code: "INCONSISTENT_SUCCESS_EXIT", + subject: report.partition, + detail: `partition reported success with ${report.numFailedTests} failed tests`, + }); + } + + if (report.numTotalTests > 0 && report.numPassedTests === 0 && report.numFailedTests === 0) { + const allSkipped = report.numSkippedTests >= report.numTotalTests; + findings.push({ + code: allSkipped ? "ALL_SKIPPED_SILENT_PASS" : "ZERO_EXECUTED_SILENT_PASS", + subject: report.partition, + detail: allSkipped + ? `all ${report.numTotalTests} tests were skipped yet exited 0 (silent pass)` + : `${report.numTotalTests} tests discovered but 0 executed/passed yet exited 0 (e.g. unmatched -t filter)`, + }); + } else if (report.numPassedTests < floor) { + findings.push({ + code: "BELOW_MIN_PASSED_FLOOR", + subject: report.partition, + detail: `passed tests (${report.numPassedTests}) below required floor (${floor}) despite exit 0`, + }); + } + + return { + verdict: findings.length === 0 ? "VERIFIED" : "SILENT_PASS_DEFECT", + findings, + }; +} + +interface WorkflowStep { + readonly name?: string; + readonly uses?: string; + readonly with?: Record; + readonly run?: string; + readonly "continue-on-error"?: boolean; +} + +interface WorkflowJob { + readonly steps?: readonly WorkflowStep[]; +} + +interface WorkflowDoc { + readonly on?: unknown; + readonly jobs?: Record; +} + +function triggersPullRequest(onField: unknown): boolean { + if (typeof onField === "string") return onField === "pull_request" || onField === "pull_request_target"; + if (Array.isArray(onField)) return onField.includes("pull_request") || onField.includes("pull_request_target"); + if (onField !== null && typeof onField === "object") { + return Object.hasOwn(onField, "pull_request") || Object.hasOwn(onField, "pull_request_target"); + } + return false; +} + +export function checkWorkflowHonesty(yamlText: string, fileLabel = "workflow.yml"): GateFinding[] { + const doc = parseYaml(yamlText) as WorkflowDoc | null; + if (!doc || typeof doc !== "object") return []; + const findings: GateFinding[] = []; + const hasPrTrigger = triggersPullRequest(doc.on); + const jobs = doc.jobs ?? {}; + + for (const [jobName, job] of Object.entries(jobs)) { + const steps = Array.isArray(job?.steps) ? job.steps : []; + let defaultMergeTreeCheckout = false; + let usesHeadRefEnv = false; + + for (const [idx, step] of steps.entries()) { + const subject = `${fileLabel}:${jobName}[${step.name ?? String(idx)}]`; + if (typeof step.uses === "string" && step.uses.startsWith("actions/checkout@")) { + const ref = step.with?.ref; + if (ref === undefined || ref === null || String(ref).trim() === "") { + defaultMergeTreeCheckout = true; + } + } + if (typeof step.run === "string") { + if (/\bGITHUB_HEAD_REF\b|\bgithub\.head_ref\b/.test(step.run)) { + usesHeadRefEnv = true; + } + if (/\|\|\s*true\b/.test(step.run)) { + findings.push({ + code: "MASKED_STEP_FAILURE", + subject, + detail: "step masks non-zero exit code with '|| true'", + }); + } + } + if (step["continue-on-error"] === true) { + findings.push({ + code: "MASKED_STEP_FAILURE", + subject, + detail: "step sets continue-on-error: true, turning failure into green job status", + }); + } + } + + if (hasPrTrigger && defaultMergeTreeCheckout && usesHeadRefEnv) { + findings.push({ + code: "MERGE_TREE_VS_HEAD_REF_MISMATCH", + subject: `${fileLabel}:${jobName}`, + detail: + "pull_request job checks out default merge tree (no explicit ref:) while reading GITHUB_HEAD_REF/github.head_ref (subject tree and ref name come from different trees)", + }); + } + } + return findings; +} + +export interface ClaimVerificationRecord { + readonly subject: string; + readonly claimedSha: string; + readonly executedSha: string; + readonly requiredPartitions: readonly string[]; + readonly partitionReports: readonly TestPartitionReport[]; + readonly skippedRequiredPartitions?: readonly string[]; + readonly claimedGuarantee: string; + readonly fallbackUsed?: boolean; + readonly proseMirrorClaim?: { + readonly declaredRelation: string; + readonly verifiedAgainstTarget: boolean; + }; +} + +export function checkClaimHonesty(record: ClaimVerificationRecord): GateFinding[] { + const findings: GateFinding[] = []; + if (record.claimedSha !== record.executedSha) { + findings.push({ + code: "SHA_MISMATCH", + subject: record.subject, + detail: `claimed SHA (${record.claimedSha}) does not match executed SHA (${record.executedSha})`, + }); + } + + for (const skipped of record.skippedRequiredPartitions ?? []) { + findings.push({ + code: "SKIPPED_REQUIRED_PARTITION", + subject: `${record.subject}:${skipped}`, + detail: `required partition '${skipped}' was skipped; cannot count as discharged`, + }); + } + + const reportByName = new Map(record.partitionReports.map((r) => [r.partition, r] as const)); + for (const required of record.requiredPartitions) { + const report = reportByName.get(required); + if (!report) { + findings.push({ + code: "SKIPPED_REQUIRED_PARTITION", + subject: `${record.subject}:${required}`, + detail: `required partition '${required}' produced no execution report`, + }); + continue; + } + const execCheck = checkTestExecution(report); + if (execCheck.verdict === "FAIL_CLOSED_SAFE") { + findings.push({ + code: "SKIPPED_REQUIRED_PARTITION", + subject: `${record.subject}:${required}`, + detail: `required partition '${required}' failed closed (exit ${report.exitCode}); not verified`, + }); + } else { + findings.push(...execCheck.findings); + } + } + + if (record.fallbackUsed === true) { + findings.push({ + code: "FALLBACK_CONTRADICTS_CLAIM", + subject: record.subject, + detail: `execution fell back away from claimed guarantee (${record.claimedGuarantee})`, + }); + } + + if (record.proseMirrorClaim && !record.proseMirrorClaim.verifiedAgainstTarget) { + findings.push({ + code: "UNVERIFIED_PROSE_MIRROR", + subject: record.subject, + detail: `prose/comment invariant '${record.proseMirrorClaim.declaredRelation}' does not match verified target`, + }); + } + + return findings; +} + +function main(argv: readonly string[]): number { + const mode = argv[0]; + const filePath = argv[1]; + if (!mode || !filePath) { + console.error("usage: check-gate-honesty.mts "); + return 2; + } + const content = readFileSync(resolve(filePath), "utf8"); + const findings = + mode === "workflow" + ? checkWorkflowHonesty(content, filePath) + : mode === "claim" + ? checkClaimHonesty(JSON.parse(content) as ClaimVerificationRecord) + : null; + if (findings === null) { + console.error(`unknown mode: ${mode}`); + return 2; + } + console.log(JSON.stringify({ status: findings.length === 0 ? "PASS" : "FAIL", findings }, null, 2)); + return findings.length === 0 ? 0 : 1; +} + +if ( + process.argv[1] && + resolve(process.argv[1]) === fileURLToPath(import.meta.url) +) { + process.exitCode = main(process.argv.slice(2)); +} diff --git a/scripts/quality/check-gate-honesty.test.mts b/scripts/quality/check-gate-honesty.test.mts new file mode 100644 index 0000000..4a1652e --- /dev/null +++ b/scripts/quality/check-gate-honesty.test.mts @@ -0,0 +1,145 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + checkClaimHonesty, + checkTestExecution, + checkWorkflowHonesty, +} from "./check-gate-honesty.mts"; + +test("distinguishes u-sekai #78 fail-closed from ty-plus #179 silent pass", () => { + // u-sekai #78 (corrected observation): 0 files collected -> exit 1 -> fail-closed (safe) + const failClosed = checkTestExecution({ + partition: "unit", + exitCode: 1, + reportedSuccess: false, + numCollectedFiles: 0, + numTotalTests: 0, + numPassedTests: 0, + numFailedTests: 0, + numSkippedTests: 0, + }); + assert.equal(failClosed.verdict, "FAIL_CLOSED_SAFE"); + assert.equal(failClosed.findings.length, 0); + + // ty-plus #179 (unmatched -t filter): files collected, 25 discovered, 0 passed, exit 0 -> silent pass defect + const unmatchedFilter = checkTestExecution({ + partition: "unit", + exitCode: 0, + reportedSuccess: true, + numCollectedFiles: 1, + numTotalTests: 25, + numPassedTests: 0, + numFailedTests: 0, + numSkippedTests: 0, + }); + assert.equal(unmatchedFilter.verdict, "SILENT_PASS_DEFECT"); + assert.equal(unmatchedFilter.findings[0]?.code, "ZERO_EXECUTED_SILENT_PASS"); + + // ty-plus #179 (describe.skip): all tests skipped, exit 0 -> silent pass defect + const allSkipped = checkTestExecution({ + partition: "unit", + exitCode: 0, + reportedSuccess: true, + numCollectedFiles: 1, + numTotalTests: 3, + numPassedTests: 0, + numFailedTests: 0, + numSkippedTests: 3, + }); + assert.equal(allSkipped.verdict, "SILENT_PASS_DEFECT"); + assert.equal(allSkipped.findings[0]?.code, "ALL_SKIPPED_SILENT_PASS"); +}); + +test("negative workflow controls: u-sekai #75 merge-tree vs head-ref and masked failure", () => { + const brokenWorkflow = ` +name: ci +on: + pull_request: +jobs: + version: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Check version against head ref + run: node scripts/version-check.mjs "$GITHUB_HEAD_REF" || true +`; + const findings = checkWorkflowHonesty(brokenWorkflow, ".github/workflows/ci.yml"); + assert.ok(findings.some((f) => f.code === "MERGE_TREE_VS_HEAD_REF_MISMATCH")); + assert.ok(findings.some((f) => f.code === "MASKED_STEP_FAILURE")); + + const honestWorkflow = ` +name: ci +on: + pull_request: +jobs: + version: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + ref: \${{ github.event.pull_request.head.sha }} + - name: Check version against head ref + run: node scripts/version-check.mjs "$GITHUB_HEAD_REF" +`; + assert.deepEqual(checkWorkflowHonesty(honestWorkflow, ".github/workflows/ci.yml"), []); +}); + +test("negative claim controls: ty-plus #175 skipped partition, readmark #72 fallback, readmark #76 false prose mirror", () => { + const findings = checkClaimHonesty({ + subject: "release-gate", + claimedSha: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + executedSha: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + requiredPartitions: ["unit", "windows-release-gate"], + skippedRequiredPartitions: ["windows-release-gate"], + partitionReports: [ + { + partition: "unit", + exitCode: 0, + reportedSuccess: true, + numCollectedFiles: 5, + numTotalTests: 21, + numPassedTests: 21, + numFailedTests: 0, + numSkippedTests: 0, + }, + ], + claimedGuarantee: "indexed read via [documentId+sourceFingerprint]", + fallbackUsed: true, + proseMirrorClaim: { + declaredRelation: "FIT_WIDTH_PADDING_PX=48 mirrors .rm-reader-scroll padding", + verifiedAgainstTarget: false, + }, + }); + const codes = new Set(findings.map((f) => f.code)); + assert.ok(codes.has("SKIPPED_REQUIRED_PARTITION")); + assert.ok(codes.has("FALLBACK_CONTRADICTS_CLAIM")); + assert.ok(codes.has("UNVERIFIED_PROSE_MIRROR")); +}); + +test("positive control: executed tests > 0, exact SHA, no fallback, verified prose passes", () => { + const findings = checkClaimHonesty({ + subject: "release-gate", + claimedSha: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + executedSha: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + requiredPartitions: ["unit"], + partitionReports: [ + { + partition: "unit", + exitCode: 0, + reportedSuccess: true, + numCollectedFiles: 4, + numTotalTests: 18, + numPassedTests: 18, + numFailedTests: 0, + numSkippedTests: 0, + }, + ], + claimedGuarantee: "unit suite executed on candidate SHA", + fallbackUsed: false, + proseMirrorClaim: { + declaredRelation: "intentional margin token (no stylesheet mirror claimed)", + verifiedAgainstTarget: true, + }, + }); + assert.deepEqual(findings, []); +}); diff --git a/skills/quality-gate/SKILL.md b/skills/quality-gate/SKILL.md index 823f79e..49abcde 100644 --- a/skills/quality-gate/SKILL.md +++ b/skills/quality-gate/SKILL.md @@ -566,6 +566,8 @@ stack predecessorがreview/rebase/updateで変化した場合、affected downstr ## 14. False green禁止 +actual executionとreported claimの照合(fail-closedと0件実行silent passの区別、CI event/ref一致、prose invariant乖離防止)は [gate-honesty](references/gate-honesty.md) に従う。 + 禁止: - skipped test / `.only` diff --git a/skills/quality-gate/references/gate-honesty.md b/skills/quality-gate/references/gate-honesty.md new file mode 100644 index 0000000..360a5e9 --- /dev/null +++ b/skills/quality-gate/references/gate-honesty.md @@ -0,0 +1,27 @@ +# Gate Honesty — Actual Execution vs Reported Claim (#97) + +gate・CI・コードコメントが「実際に検証していないもの」を成功・保証済みと誤認させる欠陥クラスの整理と再発防止契約。 + +## Fail-closed と Silent pass の区別(必須) + +| 分類 | 実例 | 実測挙動 | リスク | +| --- | --- | --- | --- | +| **Fail-closed(安全に停止)** | `u-sekai #78` | 0 file 収集 → `exit 1`(Vitest `passWithNoTests: false` 既定) | 検証不能だが偽の green は作らない | +| **Silent pass(最も危険)** | `ty-plus #179` | file 収集あり・`-t` 不一致や `describe.skip` で実行 0 件 → `exit 0` / `success: true` | aggregate gate が「検証済み」と誤認する | + +`passWithNoTests: false` は「収集 file 0 件」しか防がない。各 partition について **`numPassedTests >= 1`(実行・通過件数の下限)** を必須検証する。 + +## 3 つの欠陥担い手と対比表 + +| 担い手 | 実例 | 主張していた保証 | 実際の挙動 | 機械的対策 | +| --- | --- | --- | --- | --- | +| 1. CI event/ref/tree 不一致 | `my-web-2026 #260`, `u-sekai #75` | PR 対象ブランチの版整合を検証 | `pull_request` で merge tree を checkout しつつ `GITHUB_HEAD_REF` を参照・不活性 no-op | `actions/checkout` に明示 `ref` 指定、workflow 静的検査 | +| 2. 結果の正しさ ≠ 検証済み | `ty-plus #175`, `ty-plus #179`, `readmark #72` | Windows gate 通過 / unit 通過 / indexed read | SKIP で exit 0 / 実行 0 件で exit 0 / 存在しない index で full table scan fallback | partition 通過下限・SKIP 非通過・fallback 検出 | +| 3. Prose / comment の虚偽 invariant | `readmark #76`, `u-sekai #76` | 定数が CSS padding と一致必須 | 一致する selector が存在せず、値は正しいがコメントが誤り | mirror 主張は実値照合、意図的余白は独立 token 名で表現 | + +## 実行入口 + +```bash +bun run test:gate-honesty +node scripts/quality/check-gate-honesty.mts workflow .github/workflows/eval-controls.yml +``` From 7b988a21c3a711aae49f174fc27a8758e4723cf4 Mon Sep 17 00:00:00 2001 From: rebuildup Date: Mon, 23 Nov 2026 21:54:01 +0900 Subject: [PATCH 2/2] 97: fix cold-review defects in gate honesty checker and wire real execution verification --- .github/workflows/eval-controls.yml | 13 +- evals/policy-evaluation/controls.mts | 1 + .../gate-honesty-controls.mts | 95 ++ package.json | 3 +- scripts/gate-honesty/checker.mts | 896 ++++++++++++++++++ scripts/gate-honesty/cli.mts | 342 +++++++ scripts/gate-honesty/gate-honesty.test.mts | 679 +++++++++++++ scripts/gate-honesty/index.mts | 34 + scripts/gate-honesty/parsers.mts | 166 ++++ scripts/gate-honesty/types.mts | 90 ++ scripts/gate-honesty/verifiers.mts | 414 ++++++++ scripts/quality/check-gate-honesty.mts | 263 +---- scripts/quality/check-gate-honesty.test.mts | 173 ++-- skills/correctness-assurance/SKILL.md | 2 +- .../quality-gate/references/gate-honesty.md | 31 +- 15 files changed, 2812 insertions(+), 390 deletions(-) create mode 100644 evals/policy-evaluation/gate-honesty-controls.mts create mode 100644 scripts/gate-honesty/checker.mts create mode 100644 scripts/gate-honesty/cli.mts create mode 100644 scripts/gate-honesty/gate-honesty.test.mts create mode 100644 scripts/gate-honesty/index.mts create mode 100644 scripts/gate-honesty/parsers.mts create mode 100644 scripts/gate-honesty/types.mts create mode 100644 scripts/gate-honesty/verifiers.mts diff --git a/.github/workflows/eval-controls.yml b/.github/workflows/eval-controls.yml index 9fde2c8..df44cb2 100644 --- a/.github/workflows/eval-controls.yml +++ b/.github/workflows/eval-controls.yml @@ -23,7 +23,9 @@ jobs: - name: Check whole-repository analysis and references run: bun run quality:structure - name: Check workflow gate honesty - run: node scripts/quality/check-gate-honesty.mts workflow .github/workflows/eval-controls.yml + run: bun run quality:workflow-honesty + - name: Test gate honesty and verify real execution count + run: bun run test:gate-honesty - name: Test quality checks and challenge executor run: bun run test:system-quality - name: Challenge actual repository checks @@ -59,14 +61,15 @@ jobs: - name: Run deterministic controls shell: bash run: | - set +e failed=0 - bun evals/policy-evaluation/controls.mts || failed=1 + if ! bun evals/policy-evaluation/controls.mts; then + failed=1 + fi for suite in \ skills-cli-materialization; do echo "::group::evals/$suite" - bash "evals/$suite/controls.sh" - rc=$? + rc=0 + bash "evals/$suite/controls.sh" || rc=$? echo "::endgroup::" if [ "$rc" -ne 0 ]; then echo "::error title=Eval failure::$suite returned exit $rc" diff --git a/evals/policy-evaluation/controls.mts b/evals/policy-evaluation/controls.mts index be2fc61..a346e6a 100644 --- a/evals/policy-evaluation/controls.mts +++ b/evals/policy-evaluation/controls.mts @@ -49,6 +49,7 @@ const contracts: ReadonlyArray= 3, "expected >= 3 workflow files"); +assert.deepEqual( + workflows.findings, + [], + `workflow honesty findings: ${JSON.stringify(workflows.findings)}`, +); + +// 2. Real node --test TAP execution count >= 1 verification +const tapRun = spawnSync( + "node", + ["--test", "--test-reporter=tap", join(root, "scripts/gate-honesty/gate-honesty.test.mts")], + { encoding: "utf8", cwd: root }, +); +assert.equal(tapRun.status, 0, tapRun.stderr || tapRun.stdout); +const tapCheck = verifyTapOutput(tapRun.stdout ?? "", { + partition: "gate-honesty", + exitCode: tapRun.status ?? 1, + minPassedRequired: 1, +}); +assert.equal(tapCheck.verdict, "VERIFIED", JSON.stringify(tapCheck.findings)); + +// 3. Negative controls must fail closed +assert.equal( + checkTestExecution({ + partition: "silent-pass", + exitCode: 0, + reportedSuccess: true, + numCollectedFiles: 1, + numTotalTests: 10, + numPassedTests: 0, + numFailedTests: 0, + numSkippedTests: 0, + }).verdict, + "SILENT_PASS_DEFECT", +); +assert.equal( + checkTestExecution({ + partition: "failed-zero-exit", + exitCode: 0, + reportedSuccess: false, + numCollectedFiles: 1, + numTotalTests: 5, + numPassedTests: 4, + numFailedTests: 1, + numSkippedTests: 0, + }).verdict, + "FAIL", +); +assert.ok( + verifyCssMirror({ + subject: "readmark-76-negative", + cssText: ".rm-reader-scroll { padding: 20px 0 60vh; }", + expectations: [ + { + constantName: "FIT_WIDTH_PADDING_PX", + selectors: [".rm-reader-scroll"], + expectedProperty: "padding", + expectedValue: "48px", + }, + ], + }).some((f) => f.code === "UNVERIFIED_PROSE_MIRROR"), +); +assert.ok( + verifySchemaIndexes({ + subject: "readmark-72-negative", + dexieSchema: { bookmarks: "++id, [documentId+pageIndex]" }, + claims: [ + { + queryName: "listBookmarks", + table: "bookmarks", + columns: ["documentId", "sourceFingerprint"], + }, + ], + }).some((f) => f.code === "FALLBACK_CONTRADICTS_CLAIM"), +); + +console.log( + `gate-honesty controls OK (${workflows.filesChecked.length} workflows verified, real TAP execution verified)`, +); diff --git a/package.json b/package.json index 55374c8..c583669 100644 --- a/package.json +++ b/package.json @@ -12,7 +12,8 @@ "delivery-status": "node scripts/delivery-status/delivery-status.mts", "test:supervisor-boundary": "node --test templates/supervisor-boundary/guard.test.mts", "quality:structure": "node scripts/quality/check.mts", - "test:gate-honesty": "node --test scripts/quality/check-gate-honesty.test.mts", + "quality:workflow-honesty": "node scripts/gate-honesty/cli.mts workflow --workflows-dir .github/workflows", + "test:gate-honesty": "node scripts/gate-honesty/cli.mts run-and-verify --partition gate-honesty --floor 1 -- node --test --test-reporter=tap scripts/gate-honesty/gate-honesty.test.mts scripts/quality/check-gate-honesty.test.mts", "test:system-quality": "node --test evals/system-quality/*.test.mts evals/code-structure/*.test.mts scripts/quality/*.test.mts", "quality:challenge": "node evals/system-quality/challenge.mts" }, diff --git a/scripts/gate-honesty/checker.mts b/scripts/gate-honesty/checker.mts new file mode 100644 index 0000000..a691263 --- /dev/null +++ b/scripts/gate-honesty/checker.mts @@ -0,0 +1,896 @@ +import { existsSync, readdirSync, readFileSync, statSync } from "node:fs"; +import { join, resolve } from "node:path"; +import { parseDocument } from "yaml"; +import type { + ClaimVerificationRecord, + CssMirrorExpectation, + CssMirrorInput, + ExecutionCheckResult, + GateFinding, + QueryIndexClaim, + SchemaIndexInput, + TestPartitionReport, +} from "./types.mts"; +import { + parseNodeTestTap, + parseVitestJson, + type ParseRunnerOptions, +} from "./parsers.mts"; +import { verifyCssMirror, verifySchemaIndexes } from "./verifiers.mts"; + +const VALID_SHA_PATTERN = /^[0-9a-fA-F]{7,40}$/; + +function isNonNegativeSafeInt(value: unknown): value is number { + return typeof value === "number" && Number.isSafeInteger(value) && value >= 0; +} + +function isPlainObject(value: unknown): value is Record { + return value !== null && typeof value === "object" && !Array.isArray(value); +} + +export function checkTestExecution(report: TestPartitionReport): ExecutionCheckResult { + const findings: GateFinding[] = []; + const subject = + typeof report.partition === "string" && report.partition.trim().length > 0 + ? report.partition + : ""; + + if (typeof report.partition !== "string" || report.partition.trim().length === 0) { + findings.push({ + code: "INVALID_REPORT_INVARIANT", + subject, + detail: "partition name must be a non-empty string", + }); + } + + const floor = report.minPassedRequired ?? 1; + if (typeof floor !== "number" || !Number.isSafeInteger(floor) || floor < 1) { + findings.push({ + code: "INVALID_FLOOR", + subject, + detail: `minPassedRequired floor (${String(floor)}) must be a safe integer >= 1`, + }); + } + + if (typeof report.exitCode !== "number" || !Number.isSafeInteger(report.exitCode)) { + findings.push({ + code: "INVALID_REPORT_INVARIANT", + subject, + detail: `exitCode (${String(report.exitCode)}) must be a safe integer`, + }); + } + + if (typeof report.reportedSuccess !== "boolean") { + findings.push({ + code: "INVALID_REPORT_INVARIANT", + subject, + detail: "reportedSuccess must be a boolean", + }); + } + + const cancelled = report.numCancelledTests ?? 0; + const countFields: ReadonlyArray = [ + ["numCollectedFiles", report.numCollectedFiles], + ["numTotalTests", report.numTotalTests], + ["numPassedTests", report.numPassedTests], + ["numFailedTests", report.numFailedTests], + ["numSkippedTests", report.numSkippedTests], + ["numCancelledTests", cancelled], + ]; + + let countsValid = true; + for (const [name, value] of countFields) { + if (!isNonNegativeSafeInt(value)) { + countsValid = false; + findings.push({ + code: "INVALID_REPORT_INVARIANT", + subject, + detail: `${name} (${String(value)}) must be a non-negative integer`, + }); + } + } + + if (countsValid) { + if ( + report.numCollectedFiles === 0 && + (report.numPassedTests > 0 || report.numFailedTests > 0 || report.numTotalTests > 0) + ) { + findings.push({ + code: "INVALID_REPORT_INVARIANT", + subject, + detail: `impossible count invariant: numCollectedFiles is 0 while tests were reported (total=${report.numTotalTests}, passed=${report.numPassedTests}, failed=${report.numFailedTests})`, + }); + } + + const sumOutcomes = + report.numPassedTests + report.numFailedTests + report.numSkippedTests + cancelled; + if (sumOutcomes > report.numTotalTests) { + findings.push({ + code: "INVALID_REPORT_INVARIANT", + subject, + detail: `impossible count invariant: passed(${report.numPassedTests}) + failed(${report.numFailedTests}) + skipped(${report.numSkippedTests}) + cancelled(${cancelled}) = ${sumOutcomes} exceeds numTotalTests(${report.numTotalTests})`, + }); + } + } + + // Invalid floor or impossible report counts always fail closed immediately. + if (findings.length > 0) { + return { verdict: "FAIL", findings }; + } + + // Distinguish fail-closed (e.g. u-sekai #78: 0 files collected, exit 1) + // from silent pass (e.g. ty-plus #179: files collected, 0 tests executed, exit 0). + if (report.exitCode !== 0) { + if (report.reportedSuccess) { + findings.push({ + code: "INCONSISTENT_SUCCESS_EXIT", + subject, + detail: `partition reported success=true despite non-zero exit code ${report.exitCode}`, + }); + return { verdict: "FAIL", findings }; + } + return { verdict: "FAIL_CLOSED_SAFE", findings: [] }; + } + + // exitCode === 0 from here onward: + let hardFailure = false; + + if (report.numFailedTests > 0) { + hardFailure = true; + findings.push({ + code: "FAILED_TESTS_WITH_ZERO_EXIT", + subject, + detail: `partition exited 0 despite ${report.numFailedTests} failed test(s)`, + }); + } + + if (report.reportedSuccess !== true) { + hardFailure = true; + findings.push({ + code: "INCONSISTENT_SUCCESS_EXIT", + subject, + detail: "partition exited 0 while reportedSuccess is false", + }); + } + + const accounted = + report.numPassedTests + report.numFailedTests + report.numSkippedTests + cancelled; + + if (accounted === 0 && report.numTotalTests === 0) { + findings.push({ + code: "ZERO_EXECUTED_SILENT_PASS", + subject, + detail: "0 tests executed (passed + failed + skipped + cancelled = 0) despite exit 0", + }); + } else if ( + report.numTotalTests > 0 && + report.numPassedTests === 0 && + report.numFailedTests === 0 + ) { + const allSkipped = report.numSkippedTests >= report.numTotalTests; + findings.push({ + code: allSkipped ? "ALL_SKIPPED_SILENT_PASS" : "ZERO_EXECUTED_SILENT_PASS", + subject, + detail: allSkipped + ? `all ${report.numTotalTests} tests were skipped yet exited 0 (silent pass)` + : `${report.numTotalTests} tests discovered but 0 executed/passed yet exited 0 (e.g. unmatched -t filter)`, + }); + } else if (report.numPassedTests < floor) { + findings.push({ + code: "BELOW_MIN_PASSED_FLOOR", + subject, + detail: `passed tests (${report.numPassedTests}) below required floor (${floor}) despite exit 0`, + }); + } + + if (findings.length === 0) { + return { verdict: "VERIFIED", findings: [] }; + } + return { + verdict: hardFailure ? "FAIL" : "SILENT_PASS_DEFECT", + findings, + }; +} + +export function verifyTapOutput( + output: string, + options: ParseRunnerOptions = {}, +): ExecutionCheckResult { + try { + const report = parseNodeTestTap(output, options); + return checkTestExecution(report); + } catch (error) { + return { + verdict: "FAIL", + findings: [ + { + code: "UNPARSEABLE_TEST_OUTPUT", + subject: options.partition ?? "node-test", + detail: error instanceof Error ? error.message : String(error), + }, + ], + }; + } +} + +export function verifyVitestJsonOutput( + output: string, + options: ParseRunnerOptions = {}, +): ExecutionCheckResult { + try { + const report = parseVitestJson(output, options); + return checkTestExecution(report); + } catch (error) { + return { + verdict: "FAIL", + findings: [ + { + code: "UNPARSEABLE_TEST_OUTPUT", + subject: options.partition ?? "vitest", + detail: error instanceof Error ? error.message : String(error), + }, + ], + }; + } +} + +interface WorkflowStep { + readonly name?: string; + readonly uses?: string; + readonly with?: Record; + readonly env?: Record; + readonly run?: string; + readonly "continue-on-error"?: unknown; +} + +interface WorkflowJob { + readonly env?: Record; + readonly "continue-on-error"?: unknown; + readonly steps?: readonly WorkflowStep[]; +} + +interface WorkflowDoc { + readonly on?: unknown; + readonly env?: Record; + readonly jobs?: Record; +} + +function triggersPullRequest(onField: unknown): boolean { + if (typeof onField === "string") { + return onField === "pull_request" || onField === "pull_request_target"; + } + if (Array.isArray(onField)) { + return onField.includes("pull_request") || onField.includes("pull_request_target"); + } + if (isPlainObject(onField)) { + return Object.hasOwn(onField, "pull_request") || Object.hasOwn(onField, "pull_request_target"); + } + return false; +} + +function isContinueOnErrorEnabled(value: unknown): boolean { + if (value === true) return true; + if (typeof value === "string" && /^\$\{\{\s*true\s*\}\}$/i.test(value.trim())) return true; + return false; +} + +/** + * Strip `# ...` shell comments from a script while respecting single quotes, + * double quotes, and backslash escapes, so comments mentioning `|| true` or `set +e` + * never trigger false positives. + */ +export function stripShellComments(script: string): string { + const lines = script.replace(/\r\n/g, "\n").split("\n"); + const strippedLines: string[] = []; + + for (const line of lines) { + let inSingle = false; + let inDouble = false; + let escaped = false; + let out = ""; + + for (let i = 0; i < line.length; i += 1) { + const ch = line[i] ?? ""; + if (escaped) { + out += ch; + escaped = false; + continue; + } + if (ch === "\\" && !inSingle) { + out += ch; + escaped = true; + continue; + } + if (ch === "'" && !inDouble) { + inSingle = !inSingle; + out += ch; + continue; + } + if (ch === '"' && !inSingle) { + inDouble = !inDouble; + out += ch; + continue; + } + if (ch === "#" && !inSingle && !inDouble) { + const prev = i === 0 ? "" : (line[i - 1] ?? ""); + if (i === 0 || /[\s;&|(]/.test(prev)) { + break; + } + } + out += ch; + } + + strippedLines.push(out); + } + + return strippedLines.join("\n"); +} + +const HEAD_REF_EXPR_PATTERN = + /\bGITHUB_HEAD_REF\b|\bgithub\.head_ref\b|\bgithub\.event\.pull_request\.head\.[A-Za-z0-9_]+\b/; + +function envReferencesHeadRef(envField: unknown): boolean { + if (!isPlainObject(envField)) return false; + for (const [key, val] of Object.entries(envField)) { + if (HEAD_REF_EXPR_PATTERN.test(key)) return true; + if (typeof val === "string" && HEAD_REF_EXPR_PATTERN.test(val)) return true; + } + return false; +} + +function detectMaskedShellPatterns(cleanRun: string): string[] { + const reasons: string[] = []; + if (/\|\|\s*true(?:\s|$|[;&|)])/.test(cleanRun)) { + reasons.push("masks non-zero exit code with '|| true'"); + } + if (/\|\|\s*:(?:\s|$|[;&|)])/.test(cleanRun)) { + reasons.push("masks non-zero exit code with '|| :'"); + } + if (/\|\|\s*exit\s+0(?:\s|$|[;&|)])/.test(cleanRun)) { + reasons.push("masks non-zero exit code with '|| exit 0'"); + } + if ( + /(?:^|[;&|\s])set\s+(?:-[A-Za-z]+\s+)*\+[A-Za-z]*e[A-Za-z]*(?:\s|$|[;&|])/.test(cleanRun) || + /(?:^|[;&|\s])set\s+\+o\s+errexit(?:\s|$|[;&|])/.test(cleanRun) + ) { + reasons.push("disables errexit via 'set +e' / 'set +o errexit'"); + } + return reasons; +} + +export function checkWorkflowHonesty(yamlText: string, fileLabel = "workflow.yml"): GateFinding[] { + if (typeof yamlText !== "string" || yamlText.trim().length === 0) { + return [ + { + code: "INVALID_WORKFLOW_YAML", + subject: fileLabel, + detail: "workflow YAML is empty (fail closed)", + }, + ]; + } + + const parsedDoc = parseDocument(yamlText); + if (parsedDoc.errors.length > 0) { + return [ + { + code: "INVALID_WORKFLOW_YAML", + subject: fileLabel, + detail: `malformed workflow YAML: ${parsedDoc.errors.map((e) => e.message).join("; ")}`, + }, + ]; + } + + const rawDoc: unknown = parsedDoc.toJSON(); + if (!isPlainObject(rawDoc)) { + return [ + { + code: "INVALID_WORKFLOW_YAML", + subject: fileLabel, + detail: "workflow YAML root must be a mapping object", + }, + ]; + } + + const doc = rawDoc as WorkflowDoc; + if (doc.on === undefined) { + return [ + { + code: "INVALID_WORKFLOW_YAML", + subject: fileLabel, + detail: "workflow YAML is missing required 'on:' trigger definition", + }, + ]; + } + + if (!isPlainObject(doc.jobs) || Object.keys(doc.jobs).length === 0) { + return [ + { + code: "INVALID_WORKFLOW_YAML", + subject: fileLabel, + detail: "workflow YAML defines no jobs", + }, + ]; + } + + const findings: GateFinding[] = []; + const hasPrTrigger = triggersPullRequest(doc.on); + const workflowEnvUsesHeadRef = envReferencesHeadRef(doc.env); + + for (const [jobName, rawJob] of Object.entries(doc.jobs)) { + if (!isPlainObject(rawJob)) { + findings.push({ + code: "INVALID_WORKFLOW_YAML", + subject: `${fileLabel}:${jobName}`, + detail: "job definition must be a mapping object", + }); + continue; + } + + const job = rawJob as WorkflowJob; + if (isContinueOnErrorEnabled(job["continue-on-error"])) { + findings.push({ + code: "MASKED_STEP_FAILURE", + subject: `${fileLabel}:${jobName}`, + detail: "job sets continue-on-error: true, turning job failure into green workflow status", + }); + } + + const steps = Array.isArray(job.steps) ? job.steps : []; + let defaultMergeTreeCheckout = false; + let baseTreeCheckout = false; + let usesHeadRef = workflowEnvUsesHeadRef || envReferencesHeadRef(job.env); + + for (const [idx, step] of steps.entries()) { + if (!isPlainObject(step)) continue; + const subject = `${fileLabel}:${jobName}[${step.name ?? String(idx)}]`; + + if (envReferencesHeadRef(step.env)) { + usesHeadRef = true; + } + + if (typeof step.uses === "string" && step.uses.startsWith("actions/checkout@")) { + const stepWith = isPlainObject(step.with) ? step.with : undefined; + const refVal = stepWith?.ref; + const refStr = refVal === undefined || refVal === null ? "" : String(refVal).trim(); + if (refStr === "") { + defaultMergeTreeCheckout = true; + } else if (hasPrTrigger) { + if (/\$\{\{\s*github\.ref\s*\}\}/.test(refStr)) { + defaultMergeTreeCheckout = true; + findings.push({ + code: "MERGE_TREE_VS_HEAD_REF_MISMATCH", + subject, + detail: + "pull_request checkout explicitly uses ref: ${{ github.ref }} (synthetic merge ref) instead of an explicit head SHA", + }); + } else if ( + /\$\{\{\s*(?:github\.head_ref|github\.event\.pull_request\.head\.ref)\s*\}\}/.test( + refStr, + ) + ) { + findings.push({ + code: "MERGE_TREE_VS_HEAD_REF_MISMATCH", + subject, + detail: + "pull_request checkout uses mutable head.ref instead of immutable github.event.pull_request.head.sha", + }); + } else if ( + /\$\{\{\s*(?:github\.base_ref|github\.event\.pull_request\.base\.(?:ref|sha))\s*\}\}/.test( + refStr, + ) + ) { + baseTreeCheckout = true; + } + } + } + + if (typeof step.run === "string") { + const cleanRun = stripShellComments(step.run); + if (HEAD_REF_EXPR_PATTERN.test(cleanRun)) { + usesHeadRef = true; + } + for (const reason of detectMaskedShellPatterns(cleanRun)) { + findings.push({ + code: "MASKED_STEP_FAILURE", + subject, + detail: `step ${reason}`, + }); + } + } + + if (isContinueOnErrorEnabled(step["continue-on-error"])) { + findings.push({ + code: "MASKED_STEP_FAILURE", + subject, + detail: "step sets continue-on-error: true, turning failure into green job status", + }); + } + } + + if (hasPrTrigger && (defaultMergeTreeCheckout || baseTreeCheckout) && usesHeadRef) { + findings.push({ + code: "MERGE_TREE_VS_HEAD_REF_MISMATCH", + subject: `${fileLabel}:${jobName}`, + detail: + "pull_request job checks out default merge/base tree while reading GITHUB_HEAD_REF or github.event.pull_request.head.* (subject tree and head reference come from different trees)", + }); + } + } + + return findings; +} + +export interface WorkflowsDirCheckResult { + readonly filesChecked: readonly string[]; + readonly findings: readonly GateFinding[]; +} + +export function checkWorkflowsDirectory(dirPath: string): WorkflowsDirCheckResult { + const resolvedDir = resolve(dirPath); + if (!existsSync(resolvedDir) || !statSync(resolvedDir).isDirectory()) { + return { + filesChecked: [], + findings: [ + { + code: "INVALID_WORKFLOW_YAML", + subject: dirPath, + detail: `workflows directory does not exist or is not a directory: ${dirPath}`, + }, + ], + }; + } + + const entries = readdirSync(resolvedDir, { withFileTypes: true }) + .filter((entry) => entry.isFile() && /\.(?:yml|yaml)$/i.test(entry.name)) + .map((entry) => entry.name) + .sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)); + + if (entries.length === 0) { + return { + filesChecked: [], + findings: [ + { + code: "INVALID_WORKFLOW_YAML", + subject: dirPath, + detail: `workflows directory contains no .yml/.yaml files: ${dirPath}`, + }, + ], + }; + } + + const filesChecked: string[] = []; + const findings: GateFinding[] = []; + for (const name of entries) { + const label = join(dirPath, name); + filesChecked.push(label); + const content = readFileSync(join(resolvedDir, name), "utf8"); + findings.push(...checkWorkflowHonesty(content, label)); + } + + return { filesChecked, findings }; +} + +export function checkClaimHonesty(record: ClaimVerificationRecord): GateFinding[] { + const findings: GateFinding[] = []; + + const claimedShaValid = + typeof record.claimedSha === "string" && VALID_SHA_PATTERN.test(record.claimedSha); + const executedShaValid = + typeof record.executedSha === "string" && VALID_SHA_PATTERN.test(record.executedSha); + + if (!claimedShaValid) { + findings.push({ + code: "INVALID_SHA", + subject: record.subject, + detail: `claimedSha (${String(record.claimedSha)}) must be a 7-40 character hex SHA`, + }); + } + if (!executedShaValid) { + findings.push({ + code: "INVALID_SHA", + subject: record.subject, + detail: `executedSha (${String(record.executedSha)}) must be a 7-40 character hex SHA`, + }); + } + if ( + claimedShaValid && + executedShaValid && + record.claimedSha.toLowerCase() !== record.executedSha.toLowerCase() + ) { + findings.push({ + code: "SHA_MISMATCH", + subject: record.subject, + detail: `claimed SHA (${record.claimedSha}) does not match executed SHA (${record.executedSha})`, + }); + } + + if (record.requiredPartitions.length === 0) { + findings.push({ + code: "EMPTY_REQUIRED_PARTITIONS", + subject: record.subject, + detail: "requiredPartitions is empty (fail closed: at least one required partition must be verified)", + }); + } + + for (const skipped of record.skippedRequiredPartitions ?? []) { + findings.push({ + code: "SKIPPED_REQUIRED_PARTITION", + subject: `${record.subject}:${skipped}`, + detail: `required partition '${skipped}' was skipped; cannot count as discharged`, + }); + } + + // Group all reports by partition name so later duplicates can never silently overwrite earlier failures. + const reportsByName = new Map(); + for (const report of record.partitionReports) { + const list = reportsByName.get(report.partition); + if (list) list.push(report); + else reportsByName.set(report.partition, [report]); + + if (report.sha !== undefined) { + if (!VALID_SHA_PATTERN.test(report.sha)) { + findings.push({ + code: "INVALID_SHA", + subject: `${record.subject}:${report.partition}`, + detail: `partition sha (${String(report.sha)}) must be a 7-40 character hex SHA`, + }); + } else if ( + claimedShaValid && + report.sha.toLowerCase() !== record.claimedSha.toLowerCase() + ) { + findings.push({ + code: "SHA_MISMATCH", + subject: `${record.subject}:${report.partition}`, + detail: `partition SHA (${report.sha}) does not match claimed SHA (${record.claimedSha})`, + }); + } + } + } + + for (const [partitionName, reports] of reportsByName.entries()) { + if (reports.length > 1) { + findings.push({ + code: "DUPLICATE_PARTITION_REPORT", + subject: `${record.subject}:${partitionName}`, + detail: `partition '${partitionName}' reported ${reports.length} times (duplicate reports are rejected to prevent hiding earlier failures)`, + }); + } + } + + const seenRequired = new Set(); + for (const required of record.requiredPartitions) { + if (seenRequired.has(required)) { + findings.push({ + code: "DUPLICATE_PARTITION_REPORT", + subject: `${record.subject}:${required}`, + detail: `requiredPartitions lists '${required}' more than once`, + }); + continue; + } + seenRequired.add(required); + + const reports = reportsByName.get(required); + if (!reports || reports.length === 0) { + findings.push({ + code: "SKIPPED_REQUIRED_PARTITION", + subject: `${record.subject}:${required}`, + detail: `required partition '${required}' produced no execution report`, + }); + continue; + } + + for (const report of reports) { + const execCheck = checkTestExecution(report); + if (execCheck.verdict === "FAIL_CLOSED_SAFE") { + findings.push({ + code: "SKIPPED_REQUIRED_PARTITION", + subject: `${record.subject}:${required}`, + detail: `required partition '${required}' failed closed (exit ${report.exitCode}); not verified`, + }); + } else { + findings.push(...execCheck.findings); + } + } + } + + for (const cssCheck of record.cssMirrorChecks ?? []) { + findings.push(...verifyCssMirror(cssCheck)); + } + + for (const schemaCheck of record.schemaIndexChecks ?? []) { + findings.push(...verifySchemaIndexes(schemaCheck)); + } + + return findings; +} + +function assertString(val: unknown, path: string, allowEmpty = false): string { + if (typeof val !== "string" || (!allowEmpty && val.trim().length === 0)) { + throw new Error(`Invalid field '${path}': expected ${allowEmpty ? "string" : "non-empty string"}`); + } + return val; +} + +function assertNumber(val: unknown, path: string): number { + if (typeof val !== "number" || !Number.isFinite(val)) { + throw new Error(`Invalid field '${path}': expected finite number`); + } + return val; +} + +function assertBoolean(val: unknown, path: string): boolean { + if (typeof val !== "boolean") { + throw new Error(`Invalid field '${path}': expected boolean`); + } + return val; +} + +function assertStringArray(val: unknown, path: string): string[] { + if (!Array.isArray(val)) { + throw new Error(`Invalid field '${path}': expected string[]`); + } + return val.map((item, idx) => assertString(item, `${path}[${idx}]`)); +} + +export function parseCssMirrorInput(raw: unknown, path = "cssMirror"): CssMirrorInput { + if (!isPlainObject(raw)) { + throw new Error(`Invalid '${path}': expected object`); + } + const subject = assertString(raw.subject, `${path}.subject`); + const cssText = assertString(raw.cssText, `${path}.cssText`, true); + const sourceCode = + raw.sourceCode === undefined + ? undefined + : assertString(raw.sourceCode, `${path}.sourceCode`, true); + + if (!Array.isArray(raw.expectations)) { + throw new Error(`Invalid '${path}.expectations': expected array`); + } + + const expectations: CssMirrorExpectation[] = raw.expectations.map((item, idx) => { + const itemPath = `${path}.expectations[${idx}]`; + if (!isPlainObject(item)) throw new Error(`Invalid '${itemPath}': expected object`); + const constantName = assertString(item.constantName, `${itemPath}.constantName`); + const selectors = assertStringArray(item.selectors, `${itemPath}.selectors`); + const expectedProperty = + item.expectedProperty === undefined + ? undefined + : assertString(item.expectedProperty, `${itemPath}.expectedProperty`); + const expectedValue = + item.expectedValue === undefined + ? undefined + : assertString(item.expectedValue, `${itemPath}.expectedValue`); + return { + constantName, + selectors, + ...(expectedProperty !== undefined ? { expectedProperty } : {}), + ...(expectedValue !== undefined ? { expectedValue } : {}), + }; + }); + + return { + subject, + cssText, + expectations, + ...(sourceCode !== undefined ? { sourceCode } : {}), + }; +} + +export function parseSchemaIndexInput(raw: unknown, path = "schemaIndex"): SchemaIndexInput { + if (!isPlainObject(raw)) { + throw new Error(`Invalid '${path}': expected object`); + } + const subject = assertString(raw.subject, `${path}.subject`); + const sqlDdl = + raw.sqlDdl === undefined ? undefined : assertString(raw.sqlDdl, `${path}.sqlDdl`, true); + + let dexieSchema: Record | undefined; + if (raw.dexieSchema !== undefined) { + if (!isPlainObject(raw.dexieSchema)) { + throw new Error(`Invalid '${path}.dexieSchema': expected Record`); + } + dexieSchema = {}; + for (const [k, v] of Object.entries(raw.dexieSchema)) { + dexieSchema[k] = assertString(v, `${path}.dexieSchema.${k}`, true); + } + } + + if (!Array.isArray(raw.claims)) { + throw new Error(`Invalid '${path}.claims': expected array`); + } + + const claims: QueryIndexClaim[] = raw.claims.map((item, idx) => { + const itemPath = `${path}.claims[${idx}]`; + if (!isPlainObject(item)) throw new Error(`Invalid '${itemPath}': expected object`); + return { + queryName: assertString(item.queryName, `${itemPath}.queryName`), + table: assertString(item.table, `${itemPath}.table`), + columns: assertStringArray(item.columns, `${itemPath}.columns`), + }; + }); + + return { + subject, + claims, + ...(sqlDdl !== undefined ? { sqlDdl } : {}), + ...(dexieSchema !== undefined ? { dexieSchema } : {}), + }; +} + +function parsePartitionReport(raw: unknown, path: string): TestPartitionReport { + if (!isPlainObject(raw)) { + throw new Error(`Invalid '${path}': expected object`); + } + return { + partition: assertString(raw.partition, `${path}.partition`), + exitCode: assertNumber(raw.exitCode, `${path}.exitCode`), + reportedSuccess: assertBoolean(raw.reportedSuccess, `${path}.reportedSuccess`), + numCollectedFiles: assertNumber(raw.numCollectedFiles, `${path}.numCollectedFiles`), + numTotalTests: assertNumber(raw.numTotalTests, `${path}.numTotalTests`), + numPassedTests: assertNumber(raw.numPassedTests, `${path}.numPassedTests`), + numFailedTests: assertNumber(raw.numFailedTests, `${path}.numFailedTests`), + numSkippedTests: assertNumber(raw.numSkippedTests, `${path}.numSkippedTests`), + ...(raw.numCancelledTests !== undefined + ? { numCancelledTests: assertNumber(raw.numCancelledTests, `${path}.numCancelledTests`) } + : {}), + ...(raw.minPassedRequired !== undefined + ? { minPassedRequired: assertNumber(raw.minPassedRequired, `${path}.minPassedRequired`) } + : {}), + ...(raw.sha !== undefined ? { sha: assertString(raw.sha, `${path}.sha`, true) } : {}), + }; +} + +export function parseClaimVerificationRecord(raw: unknown): ClaimVerificationRecord { + if (!isPlainObject(raw)) { + throw new Error("Invalid claim record: root must be a JSON object"); + } + const subject = assertString(raw.subject, "subject"); + const claimedSha = assertString(raw.claimedSha, "claimedSha", true); + const executedSha = assertString(raw.executedSha, "executedSha", true); + const requiredPartitions = assertStringArray(raw.requiredPartitions, "requiredPartitions"); + const claimedGuarantee = assertString(raw.claimedGuarantee, "claimedGuarantee"); + + if (!Array.isArray(raw.partitionReports)) { + throw new Error("Invalid field 'partitionReports': expected array"); + } + const partitionReports = raw.partitionReports.map((item, idx) => + parsePartitionReport(item, `partitionReports[${idx}]`), + ); + + const skippedRequiredPartitions = + raw.skippedRequiredPartitions === undefined + ? undefined + : assertStringArray(raw.skippedRequiredPartitions, "skippedRequiredPartitions"); + + let cssMirrorChecks: CssMirrorInput[] | undefined; + if (raw.cssMirrorChecks !== undefined) { + if (!Array.isArray(raw.cssMirrorChecks)) { + throw new Error("Invalid field 'cssMirrorChecks': expected array"); + } + cssMirrorChecks = raw.cssMirrorChecks.map((item, idx) => + parseCssMirrorInput(item, `cssMirrorChecks[${idx}]`), + ); + } + + let schemaIndexChecks: SchemaIndexInput[] | undefined; + if (raw.schemaIndexChecks !== undefined) { + if (!Array.isArray(raw.schemaIndexChecks)) { + throw new Error("Invalid field 'schemaIndexChecks': expected array"); + } + schemaIndexChecks = raw.schemaIndexChecks.map((item, idx) => + parseSchemaIndexInput(item, `schemaIndexChecks[${idx}]`), + ); + } + + return { + subject, + claimedSha, + executedSha, + requiredPartitions, + partitionReports, + claimedGuarantee, + ...(skippedRequiredPartitions !== undefined ? { skippedRequiredPartitions } : {}), + ...(cssMirrorChecks !== undefined ? { cssMirrorChecks } : {}), + ...(schemaIndexChecks !== undefined ? { schemaIndexChecks } : {}), + }; +} diff --git a/scripts/gate-honesty/cli.mts b/scripts/gate-honesty/cli.mts new file mode 100644 index 0000000..ba6ff81 --- /dev/null +++ b/scripts/gate-honesty/cli.mts @@ -0,0 +1,342 @@ +#!/usr/bin/env node +import { spawnSync } from "node:child_process"; +import { readFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { + checkClaimHonesty, + checkWorkflowHonesty, + checkWorkflowsDirectory, + parseClaimVerificationRecord, + parseCssMirrorInput, + parseSchemaIndexInput, + verifyCssMirror, + verifySchemaIndexes, + verifyTapOutput, + verifyVitestJsonOutput, +} from "./index.mts"; + +function readSource(fileOrStdin: string): string { + if (fileOrStdin === "-" || fileOrStdin === "stdin") { + return readFileSync(0, "utf8"); + } + return readFileSync(resolve(fileOrStdin), "utf8"); +} + +function parseFloorOption(raw: string): number { + if (!/^-?\d+$/.test(raw)) { + throw new Error(`Invalid --floor value '${raw}': expected integer >= 1`); + } + const value = Number.parseInt(raw, 10); + if (!Number.isSafeInteger(value) || value < 1) { + throw new Error(`Invalid --floor value '${raw}': expected integer >= 1`); + } + return value; +} + +function usage(): string { + return [ + "usage:", + " cli.mts workflow ", + " cli.mts workflow --workflows-dir ", + " cli.mts --workflows-dir ", + " cli.mts claim ", + " cli.mts verify-tap [--floor N] [--partition NAME]", + " cli.mts --verify-tap [--floor N] [--partition NAME]", + " cli.mts verify-vitest-json [--floor N] [--partition NAME]", + " cli.mts --verify-vitest-json [--floor N] [--partition NAME]", + " cli.mts run-and-verify [--floor N] [--partition NAME] [--format tap|vitest-json] -- ", + " cli.mts --run-and-verify [--floor N] [--partition NAME] [--format tap|vitest-json] -- ", + " cli.mts verify-css-mirror ", + " cli.mts verify-schema-index ", + ].join("\n"); +} + +function parseVerifyFlags(args: readonly string[]): { + readonly target: string; + readonly floor: number; + readonly partition?: string; +} { + let target: string | undefined; + let floor = 1; + let partition: string | undefined; + + for (let i = 0; i < args.length; i += 1) { + const arg = args[i] ?? ""; + if (arg === "--floor") { + const next = args[i + 1]; + if (next === undefined) throw new Error("Missing value for --floor"); + floor = parseFloorOption(next); + i += 1; + } else if (arg === "--partition") { + const next = args[i + 1]; + if (next === undefined || next.trim() === "") { + throw new Error("Missing value for --partition"); + } + partition = next; + i += 1; + } else if (arg.startsWith("--")) { + throw new Error(`Unknown option: ${arg}`); + } else if (target === undefined) { + target = arg; + } else { + throw new Error(`Unexpected extra argument: ${arg}`); + } + } + + if (target === undefined) { + throw new Error("Missing input file path (use '-' or 'stdin' to read from standard input)"); + } + + return { + target, + floor, + ...(partition !== undefined ? { partition } : {}), + }; +} + +function runAndVerify(args: readonly string[]): number { + const sepIndex = args.indexOf("--"); + if (sepIndex === -1 || sepIndex === args.length - 1) { + console.error("run-and-verify requires `-- `"); + return 2; + } + + const flagArgs = args.slice(0, sepIndex); + const cmdArgs = args.slice(sepIndex + 1); + let floor = 1; + let partition = "command"; + let format: "tap" | "vitest-json" = "tap"; + + for (let i = 0; i < flagArgs.length; i += 1) { + const arg = flagArgs[i] ?? ""; + if (arg === "--floor") { + const next = flagArgs[i + 1]; + if (next === undefined) { + console.error("Missing value for --floor"); + return 2; + } + floor = parseFloorOption(next); + i += 1; + } else if (arg === "--partition") { + const next = flagArgs[i + 1]; + if (next === undefined || next.trim() === "") { + console.error("Missing value for --partition"); + return 2; + } + partition = next; + i += 1; + } else if (arg === "--format") { + const next = flagArgs[i + 1]; + if (next !== "tap" && next !== "vitest-json") { + console.error(`Invalid --format '${String(next)}': expected 'tap' or 'vitest-json'`); + return 2; + } + format = next; + i += 1; + } else { + console.error(`Unknown option: ${arg}`); + return 2; + } + } + + const executable = cmdArgs[0]; + if (!executable) { + console.error("run-and-verify requires a command after `--`"); + return 2; + } + + const child = spawnSync(executable, cmdArgs.slice(1), { + encoding: "utf8", + maxBuffer: 32 * 1024 * 1024, + }); + + if (child.error) { + console.error(`Failed to execute command '${executable}': ${child.error.message}`); + return 2; + } + + if (child.stderr) { + process.stderr.write(child.stderr); + } + + const exitCode = child.status ?? 1; + const output = child.stdout ?? ""; + const result = + format === "tap" + ? verifyTapOutput(output, { partition, exitCode, minPassedRequired: floor }) + : verifyVitestJsonOutput(output, { partition, exitCode, minPassedRequired: floor }); + + const status = result.verdict === "VERIFIED" ? "PASS" : "FAIL"; + if (status === "FAIL" && output.trim().length > 0) { + process.stderr.write(`${output}\n`); + } + console.log( + JSON.stringify( + { + status, + verdict: result.verdict, + partition, + exitCode, + floor, + findings: result.findings, + }, + null, + 2, + ), + ); + return status === "PASS" ? 0 : 1; +} + +export function main(argv: readonly string[]): number { + const mode = argv[0]; + if (!mode || mode === "--help" || mode === "-h") { + console.error(usage()); + return mode ? 0 : 2; + } + + try { + if (mode === "--workflows-dir") { + const dir = argv[1]; + if (!dir) { + console.error("Missing directory after --workflows-dir"); + return 2; + } + const res = checkWorkflowsDirectory(dir); + console.log( + JSON.stringify( + { + status: res.findings.length === 0 ? "PASS" : "FAIL", + filesChecked: res.filesChecked, + findings: res.findings, + }, + null, + 2, + ), + ); + return res.findings.length === 0 ? 0 : 1; + } + + if (mode === "workflow") { + const arg1 = argv[1]; + if (!arg1) { + console.error(usage()); + return 2; + } + if (arg1 === "--workflows-dir") { + const dir = argv[2]; + if (!dir) { + console.error("Missing directory after --workflows-dir"); + return 2; + } + const res = checkWorkflowsDirectory(dir); + console.log( + JSON.stringify( + { + status: res.findings.length === 0 ? "PASS" : "FAIL", + filesChecked: res.filesChecked, + findings: res.findings, + }, + null, + 2, + ), + ); + return res.findings.length === 0 ? 0 : 1; + } + const content = readFileSync(resolve(arg1), "utf8"); + const findings = checkWorkflowHonesty(content, arg1); + console.log( + JSON.stringify({ status: findings.length === 0 ? "PASS" : "FAIL", findings }, null, 2), + ); + return findings.length === 0 ? 0 : 1; + } + + if (mode === "claim") { + const filePath = argv[1]; + if (!filePath) { + console.error(usage()); + return 2; + } + const content = readSource(filePath); + const raw: unknown = JSON.parse(content); + const record = parseClaimVerificationRecord(raw); + const findings = checkClaimHonesty(record); + console.log( + JSON.stringify({ status: findings.length === 0 ? "PASS" : "FAIL", findings }, null, 2), + ); + return findings.length === 0 ? 0 : 1; + } + + if (mode === "verify-tap" || mode === "--verify-tap") { + const opts = parseVerifyFlags(argv.slice(1)); + const content = readSource(opts.target); + const res = verifyTapOutput(content, { + minPassedRequired: opts.floor, + ...(opts.partition !== undefined ? { partition: opts.partition } : {}), + }); + const status = res.verdict === "VERIFIED" ? "PASS" : "FAIL"; + console.log( + JSON.stringify({ status, verdict: res.verdict, findings: res.findings }, null, 2), + ); + return status === "PASS" ? 0 : 1; + } + + if (mode === "verify-vitest-json" || mode === "--verify-vitest-json") { + const opts = parseVerifyFlags(argv.slice(1)); + const content = readSource(opts.target); + const res = verifyVitestJsonOutput(content, { + minPassedRequired: opts.floor, + ...(opts.partition !== undefined ? { partition: opts.partition } : {}), + }); + const status = res.verdict === "VERIFIED" ? "PASS" : "FAIL"; + console.log( + JSON.stringify({ status, verdict: res.verdict, findings: res.findings }, null, 2), + ); + return status === "PASS" ? 0 : 1; + } + + if (mode === "run-and-verify" || mode === "--run-and-verify") { + return runAndVerify(argv.slice(1)); + } + + if (mode === "verify-css-mirror") { + const filePath = argv[1]; + if (!filePath) { + console.error(usage()); + return 2; + } + const raw: unknown = JSON.parse(readSource(filePath)); + const spec = parseCssMirrorInput(raw); + const findings = verifyCssMirror(spec); + console.log( + JSON.stringify({ status: findings.length === 0 ? "PASS" : "FAIL", findings }, null, 2), + ); + return findings.length === 0 ? 0 : 1; + } + + if (mode === "verify-schema-index") { + const filePath = argv[1]; + if (!filePath) { + console.error(usage()); + return 2; + } + const raw: unknown = JSON.parse(readSource(filePath)); + const spec = parseSchemaIndexInput(raw); + const findings = verifySchemaIndexes(spec); + console.log( + JSON.stringify({ status: findings.length === 0 ? "PASS" : "FAIL", findings }, null, 2), + ); + return findings.length === 0 ? 0 : 1; + } + + console.error(`unknown mode: ${mode}\n${usage()}`); + return 2; + } catch (error) { + console.error(error instanceof Error ? error.message : String(error)); + return 2; + } +} + +if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + process.exitCode = main(process.argv.slice(2)); +} diff --git a/scripts/gate-honesty/gate-honesty.test.mts b/scripts/gate-honesty/gate-honesty.test.mts new file mode 100644 index 0000000..65ee505 --- /dev/null +++ b/scripts/gate-honesty/gate-honesty.test.mts @@ -0,0 +1,679 @@ +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import test from "node:test"; +import { + checkClaimHonesty, + checkTestExecution, + checkWorkflowHonesty, + checkWorkflowsDirectory, + parseNodeTestTap, + parseVitestJson, + stripShellComments, + verifyCssMirror, + verifySchemaIndexes, + verifyTapOutput, + verifyVitestJsonOutput, +} from "./index.mts"; + +const CLI_PATH = resolve(import.meta.dirname, "cli.mts"); +const REPO_ROOT = resolve(import.meta.dirname, "../.."); + +function runCli( + args: readonly string[], + input?: string, +): { readonly status: number | null; readonly stdout: string; readonly stderr: string } { + const res = spawnSync(process.execPath, [CLI_PATH, ...args], { + encoding: "utf8", + cwd: REPO_ROOT, + input, + }); + return { + status: res.status, + stdout: res.stdout ?? "", + stderr: res.stderr ?? "", + }; +} + +test("checkTestExecution: distinguishes u-sekai #78 fail-closed from ty-plus #179 silent pass", () => { + const failClosed = checkTestExecution({ + partition: "unit", + exitCode: 1, + reportedSuccess: false, + numCollectedFiles: 0, + numTotalTests: 0, + numPassedTests: 0, + numFailedTests: 0, + numSkippedTests: 0, + }); + assert.equal(failClosed.verdict, "FAIL_CLOSED_SAFE"); + assert.equal(failClosed.findings.length, 0); + + const unmatchedFilter = checkTestExecution({ + partition: "unit", + exitCode: 0, + reportedSuccess: true, + numCollectedFiles: 1, + numTotalTests: 25, + numPassedTests: 0, + numFailedTests: 0, + numSkippedTests: 0, + }); + assert.equal(unmatchedFilter.verdict, "SILENT_PASS_DEFECT"); + assert.equal(unmatchedFilter.findings[0]?.code, "ZERO_EXECUTED_SILENT_PASS"); + + const allSkipped = checkTestExecution({ + partition: "unit", + exitCode: 0, + reportedSuccess: true, + numCollectedFiles: 1, + numTotalTests: 3, + numPassedTests: 0, + numFailedTests: 0, + numSkippedTests: 3, + }); + assert.equal(allSkipped.verdict, "SILENT_PASS_DEFECT"); + assert.equal(allSkipped.findings[0]?.code, "ALL_SKIPPED_SILENT_PASS"); + + const zeroTotalZeroExit = checkTestExecution({ + partition: "unit", + exitCode: 0, + reportedSuccess: true, + numCollectedFiles: 0, + numTotalTests: 0, + numPassedTests: 0, + numFailedTests: 0, + numSkippedTests: 0, + }); + assert.equal(zeroTotalZeroExit.verdict, "SILENT_PASS_DEFECT"); + assert.equal(zeroTotalZeroExit.findings[0]?.code, "ZERO_EXECUTED_SILENT_PASS"); +}); + +test("checkTestExecution [P0]: rejects exit 0 with failed tests or reportedSuccess=false", () => { + // Exact regression case: exitCode=0, reportedSuccess=false, numFailedTests>0 previously returned VERIFIED! + const failedWithFalseSuccess = checkTestExecution({ + partition: "unit", + exitCode: 0, + reportedSuccess: false, + numCollectedFiles: 2, + numTotalTests: 10, + numPassedTests: 8, + numFailedTests: 2, + numSkippedTests: 0, + }); + assert.equal(failedWithFalseSuccess.verdict, "FAIL"); + const codes1 = new Set(failedWithFalseSuccess.findings.map((f) => f.code)); + assert.ok(codes1.has("FAILED_TESTS_WITH_ZERO_EXIT")); + assert.ok(codes1.has("INCONSISTENT_SUCCESS_EXIT")); + + const failedWithTrueSuccess = checkTestExecution({ + partition: "unit", + exitCode: 0, + reportedSuccess: true, + numCollectedFiles: 1, + numTotalTests: 5, + numPassedTests: 4, + numFailedTests: 1, + numSkippedTests: 0, + }); + assert.equal(failedWithTrueSuccess.verdict, "FAIL"); + assert.ok(failedWithTrueSuccess.findings.some((f) => f.code === "FAILED_TESTS_WITH_ZERO_EXIT")); + + const falseSuccessNoFailed = checkTestExecution({ + partition: "unit", + exitCode: 0, + reportedSuccess: false, + numCollectedFiles: 1, + numTotalTests: 5, + numPassedTests: 5, + numFailedTests: 0, + numSkippedTests: 0, + }); + assert.equal(falseSuccessNoFailed.verdict, "FAIL"); + assert.ok(falseSuccessNoFailed.findings.some((f) => f.code === "INCONSISTENT_SUCCESS_EXIT")); + + const nonZeroWithTrueSuccess = checkTestExecution({ + partition: "unit", + exitCode: 1, + reportedSuccess: true, + numCollectedFiles: 1, + numTotalTests: 5, + numPassedTests: 5, + numFailedTests: 0, + numSkippedTests: 0, + }); + assert.equal(nonZeroWithTrueSuccess.verdict, "FAIL"); + assert.ok(nonZeroWithTrueSuccess.findings.some((f) => f.code === "INCONSISTENT_SUCCESS_EXIT")); +}); + +test("checkTestExecution [P0]: validates floor and count invariants", () => { + for (const badFloor of [0, -1, 1.5, Number.NaN, Number.POSITIVE_INFINITY]) { + const res = checkTestExecution({ + partition: "unit", + exitCode: 0, + reportedSuccess: true, + numCollectedFiles: 1, + numTotalTests: 5, + numPassedTests: 5, + numFailedTests: 0, + numSkippedTests: 0, + minPassedRequired: badFloor, + }); + assert.equal(res.verdict, "FAIL", `floor=${String(badFloor)} must fail`); + assert.ok(res.findings.some((f) => f.code === "INVALID_FLOOR")); + } + + const negativeCount = checkTestExecution({ + partition: "unit", + exitCode: 0, + reportedSuccess: true, + numCollectedFiles: 1, + numTotalTests: 5, + numPassedTests: 5, + numFailedTests: -1, + numSkippedTests: 0, + }); + assert.equal(negativeCount.verdict, "FAIL"); + assert.ok(negativeCount.findings.some((f) => f.code === "INVALID_REPORT_INVARIANT")); + + const zeroFilesWithPassedTests = checkTestExecution({ + partition: "unit", + exitCode: 0, + reportedSuccess: true, + numCollectedFiles: 0, + numTotalTests: 3, + numPassedTests: 3, + numFailedTests: 0, + numSkippedTests: 0, + }); + assert.equal(zeroFilesWithPassedTests.verdict, "FAIL"); + assert.ok(zeroFilesWithPassedTests.findings.some((f) => f.code === "INVALID_REPORT_INVARIANT")); + + const outcomesExceedTotal = checkTestExecution({ + partition: "unit", + exitCode: 0, + reportedSuccess: true, + numCollectedFiles: 1, + numTotalTests: 2, + numPassedTests: 2, + numFailedTests: 1, + numSkippedTests: 0, + }); + assert.equal(outcomesExceedTotal.verdict, "FAIL"); + assert.ok(outcomesExceedTotal.findings.some((f) => f.code === "INVALID_REPORT_INVARIANT")); +}); + +test("parsers [P0]: parseNodeTestTap and parseVitestJson handle real outputs and fail closed on empty/zero", () => { + const realTap = [ + "TAP version 13", + "# Subtest: passing test", + "ok 1 - passing test", + "1..1", + "# tests 4", + "# suites 1", + "# pass 4", + "# fail 0", + "# cancelled 0", + "# skipped 0", + "# todo 0", + "# duration_ms 12.34", + ].join("\n"); + + const parsedTap = parseNodeTestTap(realTap, { partition: "unit", exitCode: 0 }); + assert.equal(parsedTap.numTotalTests, 4); + assert.equal(parsedTap.numPassedTests, 4); + assert.equal(parsedTap.numFailedTests, 0); + assert.equal(checkTestExecution(parsedTap).verdict, "VERIFIED"); + + // Empty TAP -> FAIL + const emptyTap = verifyTapOutput("", { partition: "unit" }); + assert.equal(emptyTap.verdict, "FAIL"); + assert.equal(emptyTap.findings[0]?.code, "UNPARSEABLE_TEST_OUTPUT"); + + // Malformed TAP -> FAIL + const garbageTap = verifyTapOutput("hello world\nno tap summary here", { partition: "unit" }); + assert.equal(garbageTap.verdict, "FAIL"); + assert.equal(garbageTap.findings[0]?.code, "UNPARSEABLE_TEST_OUTPUT"); + + // Zero-test TAP with exit 0 -> SILENT_PASS_DEFECT + const zeroTap = [ + "TAP version 13", + "1..0", + "# tests 0", + "# suites 0", + "# pass 0", + "# fail 0", + "# cancelled 0", + "# skipped 0", + ].join("\n"); + const zeroTapCheck = verifyTapOutput(zeroTap, { partition: "unit", exitCode: 0 }); + assert.equal(zeroTapCheck.verdict, "SILENT_PASS_DEFECT"); + assert.equal(zeroTapCheck.findings[0]?.code, "ZERO_EXECUTED_SILENT_PASS"); + + // Spoofed `# pass 99` printed inside test output before `1..0` must NOT fool parser + const spoofedTap = [ + "TAP version 13", + "# tests 99", + "# pass 99", + "# fail 0", + "1..0", + "# tests 0", + "# pass 0", + "# fail 0", + "# skipped 0", + "# cancelled 0", + ].join("\n"); + const spoofedCheck = verifyTapOutput(spoofedTap, { partition: "unit", exitCode: 0 }); + assert.equal(spoofedCheck.verdict, "SILENT_PASS_DEFECT"); + + // Vitest JSON positive + const vitestPass = JSON.stringify({ + success: true, + numTotalTestSuites: 2, + numTotalTests: 12, + numPassedTests: 12, + numFailedTests: 0, + numPendingTests: 0, + }); + const parsedVitest = parseVitestJson(vitestPass, { partition: "unit", exitCode: 0 }); + assert.equal(checkTestExecution(parsedVitest).verdict, "VERIFIED"); + + // Vitest JSON ty-plus #179 silent pass (files collected, 25 discovered, 0 passed, success=true) + const vitestSilentPass = JSON.stringify({ + success: true, + numTotalTestSuites: 1, + numTotalTests: 25, + numPassedTests: 0, + numFailedTests: 0, + numPendingTests: 0, + }); + const vitestCheck = verifyVitestJsonOutput(vitestSilentPass, { partition: "unit", exitCode: 0 }); + assert.equal(vitestCheck.verdict, "SILENT_PASS_DEFECT"); + assert.equal(vitestCheck.findings[0]?.code, "ZERO_EXECUTED_SILENT_PASS"); + + // Empty Vitest JSON -> FAIL + assert.equal(verifyVitestJsonOutput("").verdict, "FAIL"); +}); + +test("checkClaimHonesty [P0]: rejects empty requiredPartitions, invalid SHAs, and duplicate partition overwrite", () => { + const validSha = "a1b2c3d4e5f60718293a4b5c6d7e8f9012345678"; + + // Empty requiredPartitions must fail closed + const emptyRequired = checkClaimHonesty({ + subject: "release-gate", + claimedSha: validSha, + executedSha: validSha, + requiredPartitions: [], + partitionReports: [], + claimedGuarantee: "all partitions passed", + }); + assert.ok(emptyRequired.some((f) => f.code === "EMPTY_REQUIRED_PARTITIONS")); + + // Empty / invalid SHAs must fail closed + const invalidSha = checkClaimHonesty({ + subject: "release-gate", + claimedSha: "", + executedSha: "not-a-hex-sha", + requiredPartitions: ["unit"], + partitionReports: [ + { + partition: "unit", + sha: "xyz", + exitCode: 0, + reportedSuccess: true, + numCollectedFiles: 1, + numTotalTests: 5, + numPassedTests: 5, + numFailedTests: 0, + numSkippedTests: 0, + }, + ], + claimedGuarantee: "unit passed", + }); + assert.equal(invalidSha.filter((f) => f.code === "INVALID_SHA").length, 3); + + // Duplicate partition report: earlier failure MUST NOT be masked by a later passing report! + const duplicatePartition = checkClaimHonesty({ + subject: "release-gate", + claimedSha: validSha, + executedSha: validSha, + requiredPartitions: ["unit"], + partitionReports: [ + { + partition: "unit", + sha: validSha, + exitCode: 0, + reportedSuccess: false, + numCollectedFiles: 1, + numTotalTests: 5, + numPassedTests: 3, + numFailedTests: 2, + numSkippedTests: 0, + }, + { + partition: "unit", + sha: validSha, + exitCode: 0, + reportedSuccess: true, + numCollectedFiles: 1, + numTotalTests: 5, + numPassedTests: 5, + numFailedTests: 0, + numSkippedTests: 0, + }, + ], + claimedGuarantee: "unit passed", + }); + const dupCodes = new Set(duplicatePartition.map((f) => f.code)); + assert.ok(dupCodes.has("DUPLICATE_PARTITION_REPORT")); + assert.ok(dupCodes.has("FAILED_TESTS_WITH_ZERO_EXIT")); +}); + +test("checkWorkflowHonesty [P1]: fails closed on empty/malformed YAML, catches env head-ref, ref: github.ref, job continue-on-error, || :, || exit 0, set +e, and ignores shell comments", () => { + // Empty YAML -> FAIL + assert.equal(checkWorkflowHonesty("", "empty.yml")[0]?.code, "INVALID_WORKFLOW_YAML"); + + // Malformed YAML -> FAIL + assert.equal( + checkWorkflowHonesty("name: ci\non: [\n unclosed", "broken.yml")[0]?.code, + "INVALID_WORKFLOW_YAML", + ); + + // Comment containing `|| true`, `|| :`, `set +e` MUST PASS (no false positives) + const commentsOnlyWorkflow = ` +name: honest-with-comments +on: + pull_request: +jobs: + verify: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Run checks + run: | + # Never use || true, || :, || exit 0, or set +e here + echo "running tests" # inline comment mentioning || true + node --test scripts/gate-honesty/gate-honesty.test.mts +`; + assert.deepEqual(checkWorkflowHonesty(commentsOnlyWorkflow, "comments.yml"), []); + assert.equal(stripShellComments("echo ok # || true\n# set +e\nrun_cmd"), "echo ok \n\nrun_cmd"); + + // env:-level GITHUB_HEAD_REF / github.event.pull_request.head.* with default checkout -> FAIL + const envHeadRefWorkflow = ` +name: env-head-ref +on: + pull_request: +jobs: + version: + runs-on: ubuntu-latest + env: + PR_HEAD: \${{ github.event.pull_request.head.ref }} + steps: + - uses: actions/checkout@v4 + - run: echo "$PR_HEAD" +`; + assert.ok( + checkWorkflowHonesty(envHeadRefWorkflow, "env.yml").some( + (f) => f.code === "MERGE_TREE_VS_HEAD_REF_MISMATCH", + ), + ); + + // actions/checkout with ref: ${{ github.ref }} on pull_request -> FAIL + const githubRefCheckoutWorkflow = ` +name: bad-ref-checkout +on: + pull_request: +jobs: + check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + ref: \${{ github.ref }} + - run: npm test +`; + assert.ok( + checkWorkflowHonesty(githubRefCheckoutWorkflow, "bad-ref.yml").some( + (f) => f.code === "MERGE_TREE_VS_HEAD_REF_MISMATCH", + ), + ); + + // job-level continue-on-error: true + || : + || exit 0 + set +e -> ALL flagged + const maskedWorkflow = ` +name: masked +on: + pull_request: +jobs: + masked_job: + runs-on: ubuntu-latest + continue-on-error: true + steps: + - name: colon + run: "npm test || :" + - name: exit-zero + run: npm test || exit 0 + - name: set-plus-e + run: | + set +e + npm test +`; + const maskedFindings = checkWorkflowHonesty(maskedWorkflow, "masked.yml"); + assert.equal( + maskedFindings.filter((f) => f.code === "MASKED_STEP_FAILURE").length, + 4, + JSON.stringify(maskedFindings), + ); + + // Real repository `.github/workflows` directory scan must check all workflow files and pass + const repoWorkflows = checkWorkflowsDirectory(join(REPO_ROOT, ".github/workflows")); + assert.ok(repoWorkflows.filesChecked.length >= 3, "expected at least 3 repository workflows"); + assert.deepEqual(repoWorkflows.findings, []); +}); + +test("verifyCssMirror [P1]: deterministic readmark #76 CSS mirror verifier (negative and positive controls)", () => { + // Negative control 1: exact readmark #76 mismatch (padding is 20px 0 60vh, not 48px) + const readmark76Negative = verifyCssMirror({ + subject: "src/ui/reader-view.tsx", + sourceCode: "export const FIT_WIDTH_PADDING_PX = 48;", + cssText: ` + .rm-reader-scroll { padding: 20px 0 60vh; } + .rm-reader-pages { display: flex; flex-direction: column; } + `, + expectations: [ + { + constantName: "FIT_WIDTH_PADDING_PX", + selectors: [".rm-reader-scroll", ".rm-reader-pages"], + expectedProperty: "padding", + expectedValue: "48px", + }, + ], + }); + assert.ok(readmark76Negative.some((f) => f.code === "UNVERIFIED_PROSE_MIRROR")); + + // Negative control 2: selector does not exist at all + const missingSelector = verifyCssMirror({ + subject: "src/ui/reader-view.tsx", + cssText: ".rm-reader-scroll { padding: 48px; }", + expectations: [ + { + constantName: "SIDEBAR_WIDTH_PX", + selectors: [".rm-nonexistent-sidebar"], + }, + ], + }); + assert.ok(missingSelector.some((f) => f.code === "UNVERIFIED_PROSE_MIRROR")); + + // Positive control: selector, property, and value match + const positive = verifyCssMirror({ + subject: "src/ui/reader-view.tsx", + sourceCode: "export const FIT_WIDTH_PADDING_PX = 48;", + cssText: ` + /* reader viewport */ + .rm-reader-scroll { padding-inline: 48px; } + .rm-reader-pages { display: flex; } + `, + expectations: [ + { + constantName: "FIT_WIDTH_PADDING_PX", + selectors: [".rm-reader-scroll", ".rm-reader-pages"], + expectedProperty: "padding", + expectedValue: "48px", + }, + ], + }); + assert.deepEqual(positive, []); +}); + +test("verifySchemaIndexes [P1]: deterministic readmark #72 SQL and Dexie schema-index verifier", () => { + // Negative control 1 (readmark #72 Dexie): queries [documentId+sourceFingerprint], schema only has [documentId+pageIndex] + const dexieNegative = verifySchemaIndexes({ + subject: "bookmarks-repo", + dexieSchema: { + bookmarks: "++id, [documentId+pageIndex], createdAt", + highlights: "++id, [documentId+pageIndex]", + }, + claims: [ + { + queryName: "listBookmarks", + table: "bookmarks", + columns: ["documentId", "sourceFingerprint"], + }, + { + queryName: "listHighlights", + table: "highlights", + columns: ["documentId", "sourceFingerprint"], + }, + ], + }); + assert.equal(dexieNegative.filter((f) => f.code === "FALLBACK_CONTRADICTS_CLAIM").length, 2); + + // Negative control 2 (SQL DDL): missing index on (document_id, source_fingerprint) + const sqlNegative = verifySchemaIndexes({ + subject: "migrations/001_init.sql", + sqlDdl: ` + CREATE TABLE bookmarks ( + id INTEGER PRIMARY KEY, + document_id TEXT NOT NULL, + page_index INTEGER NOT NULL, + source_fingerprint TEXT NOT NULL + ); + CREATE INDEX idx_bookmarks_doc_page ON bookmarks (document_id, page_index); + `, + claims: [ + { + queryName: "listBookmarksByFingerprint", + table: "bookmarks", + columns: ["document_id", "source_fingerprint"], + }, + ], + }); + assert.equal(sqlNegative.length, 1); + assert.equal(sqlNegative[0]?.code, "FALLBACK_CONTRADICTS_CLAIM"); + + // Positive control (SQL + Dexie): leftmost prefix and exact compound index match + const positive = verifySchemaIndexes({ + subject: "migrations/002_add_fingerprint_idx.sql", + sqlDdl: ` + CREATE TABLE bookmarks ( + id INTEGER PRIMARY KEY, + document_id TEXT NOT NULL, + source_fingerprint TEXT NOT NULL, + page_index INTEGER NOT NULL + ); + CREATE INDEX idx_bookmarks_doc_fp ON bookmarks (document_id, source_fingerprint, page_index); + `, + dexieSchema: { + highlights: "++id, [documentId+sourceFingerprint+pageIndex]", + }, + claims: [ + { + queryName: "listBookmarksByFingerprint", + table: "bookmarks", + columns: ["document_id", "source_fingerprint"], + }, + { + queryName: "listBookmarksByDoc", + table: "bookmarks", + columns: ["document_id"], + }, + { + queryName: "listHighlightsByFingerprint", + table: "highlights", + columns: ["documentId", "sourceFingerprint"], + }, + ], + }); + assert.deepEqual(positive, []); +}); + +test("CLI [P0/P1]: enforces strict JSON schema validation (exit 2), workflows-dir scan, and TAP stdin/run-and-verify", () => { + const scratch = mkdtempSync(join(tmpdir(), "gate-honesty-cli-")); + try { + // 1. Malformed / missing-fields claim JSON must exit 2 + const badClaimPath = join(scratch, "bad-claim.json"); + writeFileSync(badClaimPath, JSON.stringify({ subject: "release-gate" }), "utf8"); + const badClaimRes = runCli(["claim", badClaimPath]); + assert.equal(badClaimRes.status, 2); + + // 2. --workflows-dir on real .github/workflows must exit 0 and check all workflow files + const wfRes = runCli(["workflow", "--workflows-dir", ".github/workflows"]); + assert.equal(wfRes.status, 0, wfRes.stderr || wfRes.stdout); + const wfPayload = JSON.parse(wfRes.stdout) as { + status: string; + filesChecked: string[]; + findings: unknown[]; + }; + assert.equal(wfPayload.status, "PASS"); + assert.ok(wfPayload.filesChecked.length >= 3); + + // 3. --verify-tap stdin with real passing TAP -> exit 0 + const passTapRes = runCli( + ["--verify-tap", "stdin", "--floor", "2"], + "TAP version 13\n1..2\n# tests 2\n# pass 2\n# fail 0\n# skipped 0\n# cancelled 0\n", + ); + assert.equal(passTapRes.status, 0); + + // 4. --verify-tap stdin with empty input -> exit 1 (FAIL) + const emptyTapRes = runCli(["--verify-tap", "-", "--floor", "1"], ""); + assert.equal(emptyTapRes.status, 1); + + // 5. --verify-tap stdin with 0 executed tests -> exit 1 (FAIL) + const zeroTapRes = runCli( + ["--verify-tap", "-", "--floor", "1"], + "TAP version 13\n1..0\n# tests 0\n# pass 0\n# fail 0\n", + ); + assert.equal(zeroTapRes.status, 1); + + // 6. --run-and-verify with a real zero-test command (exit 0, 0 tests) -> exit 1 (FAIL) + const zeroCmdRes = runCli([ + "--run-and-verify", + "--floor", + "1", + "--partition", + "zero-probe", + "--", + process.execPath, + "-e", + "console.log('TAP version 13\\n1..0\\n# tests 0\\n# pass 0\\n# fail 0\\n# skipped 0\\n# cancelled 0')", + ]); + assert.equal(zeroCmdRes.status, 1); + + // 7. --run-and-verify with a real passing command -> exit 0 (PASS) + const passCmdRes = runCli([ + "--run-and-verify", + "--floor", + "1", + "--partition", + "pass-probe", + "--", + process.execPath, + "-e", + "console.log('TAP version 13\\n1..1\\n# tests 1\\n# pass 1\\n# fail 0\\n# skipped 0\\n# cancelled 0')", + ]); + assert.equal(passCmdRes.status, 0); + } finally { + rmSync(scratch, { recursive: true, force: true }); + } +}); diff --git a/scripts/gate-honesty/index.mts b/scripts/gate-honesty/index.mts new file mode 100644 index 0000000..a39aaf5 --- /dev/null +++ b/scripts/gate-honesty/index.mts @@ -0,0 +1,34 @@ +export type { + ClaimVerificationRecord, + CssMirrorExpectation, + CssMirrorInput, + ExecutionCheckResult, + ExecutionVerdict, + GateFinding, + GateFindingCode, + QueryIndexClaim, + SchemaIndexInput, + TestPartitionReport, +} from "./types.mts"; + +export { + parseNodeTestTap, + parseVitestJson, + type ParseRunnerOptions, +} from "./parsers.mts"; + +export { verifyCssMirror, verifySchemaIndexes } from "./verifiers.mts"; + +export { + checkClaimHonesty, + checkTestExecution, + checkWorkflowHonesty, + checkWorkflowsDirectory, + parseClaimVerificationRecord, + parseCssMirrorInput, + parseSchemaIndexInput, + stripShellComments, + verifyTapOutput, + verifyVitestJsonOutput, + type WorkflowsDirCheckResult, +} from "./checker.mts"; diff --git a/scripts/gate-honesty/parsers.mts b/scripts/gate-honesty/parsers.mts new file mode 100644 index 0000000..699d7ec --- /dev/null +++ b/scripts/gate-honesty/parsers.mts @@ -0,0 +1,166 @@ +import type { TestPartitionReport } from "./types.mts"; + +export interface ParseRunnerOptions { + readonly partition?: string; + readonly exitCode?: number; + readonly minPassedRequired?: number; + readonly sha?: string; +} + +function parseNonNegativeInt(raw: unknown, fieldName: string): number { + if (typeof raw !== "number" || !Number.isSafeInteger(raw) || raw < 0) { + throw new Error(`Invalid Vitest JSON field '${fieldName}': expected non-negative integer`); + } + return raw; +} + +/** + * Parse `node --test --test-reporter=tap` output into a TestPartitionReport. + * Fails closed (throws) when output is empty or missing required TAP summary metrics. + */ +export function parseNodeTestTap( + output: string, + options: ParseRunnerOptions = {}, +): TestPartitionReport { + if (typeof output !== "string" || output.trim().length === 0) { + throw new Error("Empty TAP output: cannot verify test execution"); + } + + const lines = output.replace(/\r\n/g, "\n").split("\n"); + + // Anchor to the final top-level TAP plan (`1..N`) when present so stdout inside tests + // cannot spoof summary counts. If no plan is present, only accept a contiguous summary + // block at the end of output. + let planIndex = -1; + for (let i = lines.length - 1; i >= 0; i -= 1) { + if (/^1\.\.\d+$/.test(lines[i] ?? "")) { + planIndex = i; + break; + } + } + + const summaryLines: string[] = []; + if (planIndex >= 0) { + for (let i = planIndex + 1; i < lines.length; i += 1) { + summaryLines.push(lines[i] ?? ""); + } + } else { + for (let i = lines.length - 1; i >= 0; i -= 1) { + const line = lines[i] ?? ""; + if (line.trim() === "") { + if (summaryLines.length === 0) continue; + break; + } + if (/^#\s+[a-z_]+\s+[0-9.]+$/.test(line)) { + summaryLines.unshift(line); + } else { + break; + } + } + } + + const metrics = new Map(); + for (const line of summaryLines) { + const match = /^#\s+(tests|suites|pass|fail|cancelled|skipped|todo)\s+(\d+)$/.exec(line); + if (match) { + const key = match[1]; + const value = Number.parseInt(match[2] ?? "", 10); + if (key && Number.isSafeInteger(value) && value >= 0) { + metrics.set(key, value); + } + } + } + + const tests = metrics.get("tests"); + const pass = metrics.get("pass"); + const fail = metrics.get("fail"); + if (tests === undefined || pass === undefined || fail === undefined) { + throw new Error( + "Malformed TAP output: missing required summary lines (# tests, # pass, # fail)", + ); + } + + const skipped = metrics.get("skipped") ?? 0; + const cancelled = metrics.get("cancelled") ?? 0; + const suites = metrics.get("suites") ?? 0; + const reportedSuccess = fail === 0 && cancelled === 0; + const exitCode = options.exitCode ?? (reportedSuccess ? 0 : 1); + + return { + partition: options.partition ?? "node-test", + exitCode, + reportedSuccess, + numCollectedFiles: tests > 0 ? Math.max(1, suites) : 0, + numTotalTests: tests, + numPassedTests: pass, + numFailedTests: fail, + numSkippedTests: skipped, + numCancelledTests: cancelled, + ...(options.minPassedRequired !== undefined + ? { minPassedRequired: options.minPassedRequired } + : {}), + ...(options.sha !== undefined ? { sha: options.sha } : {}), + }; +} + +/** + * Parse Vitest JSON reporter output (`vitest run --reporter=json`) into a TestPartitionReport. + * Fails closed (throws) when output is empty, non-JSON, or missing required fields. + */ +export function parseVitestJson( + output: string, + options: ParseRunnerOptions = {}, +): TestPartitionReport { + if (typeof output !== "string" || output.trim().length === 0) { + throw new Error("Empty Vitest JSON output: cannot verify test execution"); + } + + let parsed: unknown; + try { + parsed = JSON.parse(output); + } catch (error) { + throw new Error( + `Malformed Vitest JSON output: ${error instanceof Error ? error.message : String(error)}`, + ); + } + + if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) { + throw new Error("Invalid Vitest JSON output: root must be a JSON object"); + } + + const obj = parsed as Record; + if (typeof obj.success !== "boolean") { + throw new Error("Invalid Vitest JSON field 'success': expected boolean"); + } + + const numTotalTestSuites = parseNonNegativeInt(obj.numTotalTestSuites, "numTotalTestSuites"); + const numTotalTests = parseNonNegativeInt(obj.numTotalTests, "numTotalTests"); + const numPassedTests = parseNonNegativeInt(obj.numPassedTests, "numPassedTests"); + const numFailedTests = parseNonNegativeInt(obj.numFailedTests, "numFailedTests"); + const numPendingTests = parseNonNegativeInt(obj.numPendingTests, "numPendingTests"); + const numTodoTests = + obj.numTodoTests === undefined + ? 0 + : parseNonNegativeInt(obj.numTodoTests, "numTodoTests"); + + const collectedFiles = Array.isArray(obj.testResults) + ? obj.testResults.length + : numTotalTestSuites; + + const exitCode = options.exitCode ?? (obj.success ? 0 : 1); + + return { + partition: options.partition ?? "vitest", + exitCode, + reportedSuccess: obj.success, + numCollectedFiles: collectedFiles, + numTotalTests, + numPassedTests, + numFailedTests, + numSkippedTests: numPendingTests + numTodoTests, + ...(options.minPassedRequired !== undefined + ? { minPassedRequired: options.minPassedRequired } + : {}), + ...(options.sha !== undefined ? { sha: options.sha } : {}), + }; +} diff --git a/scripts/gate-honesty/types.mts b/scripts/gate-honesty/types.mts new file mode 100644 index 0000000..b9296a6 --- /dev/null +++ b/scripts/gate-honesty/types.mts @@ -0,0 +1,90 @@ +export interface TestPartitionReport { + readonly partition: string; + readonly exitCode: number; + readonly reportedSuccess: boolean; + readonly numCollectedFiles: number; + readonly numTotalTests: number; + readonly numPassedTests: number; + readonly numFailedTests: number; + readonly numSkippedTests: number; + readonly numCancelledTests?: number; + readonly minPassedRequired?: number; + readonly sha?: string; +} + +export type ExecutionVerdict = + | "VERIFIED" + | "FAIL_CLOSED_SAFE" + | "SILENT_PASS_DEFECT" + | "FAIL"; + +export type GateFindingCode = + | "ZERO_EXECUTED_SILENT_PASS" + | "ALL_SKIPPED_SILENT_PASS" + | "BELOW_MIN_PASSED_FLOOR" + | "INCONSISTENT_SUCCESS_EXIT" + | "FAILED_TESTS_WITH_ZERO_EXIT" + | "INVALID_FLOOR" + | "INVALID_REPORT_INVARIANT" + | "UNPARSEABLE_TEST_OUTPUT" + | "INVALID_WORKFLOW_YAML" + | "MERGE_TREE_VS_HEAD_REF_MISMATCH" + | "MASKED_STEP_FAILURE" + | "EMPTY_REQUIRED_PARTITIONS" + | "DUPLICATE_PARTITION_REPORT" + | "SKIPPED_REQUIRED_PARTITION" + | "FALLBACK_CONTRADICTS_CLAIM" + | "UNVERIFIED_PROSE_MIRROR" + | "INVALID_VERIFIER_SPEC" + | "INVALID_SHA" + | "SHA_MISMATCH"; + +export interface GateFinding { + readonly code: GateFindingCode; + readonly subject: string; + readonly detail: string; +} + +export interface ExecutionCheckResult { + readonly verdict: ExecutionVerdict; + readonly findings: readonly GateFinding[]; +} + +export interface CssMirrorExpectation { + readonly constantName: string; + readonly selectors: readonly string[]; + readonly expectedProperty?: string; + readonly expectedValue?: string; +} + +export interface CssMirrorInput { + readonly subject: string; + readonly sourceCode?: string; + readonly cssText: string; + readonly expectations: readonly CssMirrorExpectation[]; +} + +export interface QueryIndexClaim { + readonly queryName: string; + readonly table: string; + readonly columns: readonly string[]; +} + +export interface SchemaIndexInput { + readonly subject: string; + readonly sqlDdl?: string; + readonly dexieSchema?: Readonly>; + readonly claims: readonly QueryIndexClaim[]; +} + +export interface ClaimVerificationRecord { + readonly subject: string; + readonly claimedSha: string; + readonly executedSha: string; + readonly requiredPartitions: readonly string[]; + readonly partitionReports: readonly TestPartitionReport[]; + readonly skippedRequiredPartitions?: readonly string[]; + readonly claimedGuarantee: string; + readonly cssMirrorChecks?: readonly CssMirrorInput[]; + readonly schemaIndexChecks?: readonly SchemaIndexInput[]; +} diff --git a/scripts/gate-honesty/verifiers.mts b/scripts/gate-honesty/verifiers.mts new file mode 100644 index 0000000..1eafc39 --- /dev/null +++ b/scripts/gate-honesty/verifiers.mts @@ -0,0 +1,414 @@ +import type { CssMirrorInput, GateFinding, SchemaIndexInput } from "./types.mts"; + +interface ParsedCssRule { + readonly selectors: readonly string[]; + readonly declarations: ReadonlyMap; +} + +function stripCssComments(css: string): string { + return css.replace(/\/\*[\s\S]*?\*\//g, ""); +} + +function parseDeclarations(block: string): Map { + const declarations = new Map(); + for (const part of block.split(";")) { + const colonIdx = part.indexOf(":"); + if (colonIdx <= 0) continue; + const prop = part.slice(0, colonIdx).trim().toLowerCase(); + const val = part.slice(colonIdx + 1).trim(); + if (!prop || !val) continue; + const existing = declarations.get(prop); + if (existing) existing.push(val); + else declarations.set(prop, [val]); + } + return declarations; +} + +function parseCssRules(cssText: string): ParsedCssRule[] { + const cleaned = stripCssComments(cssText); + const rules: ParsedCssRule[] = []; + + function walk(text: string): void { + let i = 0; + while (i < text.length) { + const openIdx = text.indexOf("{", i); + if (openIdx === -1) break; + const header = text.slice(i, openIdx).trim(); + + let depth = 1; + let j = openIdx + 1; + while (j < text.length && depth > 0) { + const ch = text[j]; + if (ch === "{") depth += 1; + else if (ch === "}") depth -= 1; + j += 1; + } + if (depth !== 0) break; + + const body = text.slice(openIdx + 1, j - 1); + i = j; + + if (!header) continue; + if (header.startsWith("@")) { + // Recurse into @media, @supports, @layer, etc. + if (body.includes("{")) walk(body); + continue; + } + + const selectors = header + .split(",") + .map((s) => s.trim().replace(/\s+/g, " ")) + .filter((s) => s.length > 0); + if (selectors.length > 0) { + rules.push({ selectors, declarations: parseDeclarations(body) }); + } + } + } + + walk(cleaned); + return rules; +} + +function escapeRegExp(literal: string): string { + return literal.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} + +function selectorMatches(ruleSelector: string, expectedSelector: string): boolean { + const normRule = ruleSelector.trim().replace(/\s+/g, " "); + const normExpected = expectedSelector.trim().replace(/\s+/g, " "); + if (normRule === normExpected) return true; + // Allow pseudo-class/combinator usage of the exact selector token (e.g. `.foo:hover` or `.parent > .foo`), + // while rejecting prefix collisions like `.foo-bar` for `.foo`. + const pattern = new RegExp( + `(?:^|[\\s>+~,(])${escapeRegExp(normExpected)}(?:$|[\\s>+~,:.[\\]()])`, + ); + return pattern.test(normRule); +} + +function propertyMatches(declaredProp: string, expectedProp: string): boolean { + const normDecl = declaredProp.trim().toLowerCase(); + const normExp = expectedProp.trim().toLowerCase(); + if (normDecl === normExp) return true; + // Allow longhand property to satisfy shorthand expectation (e.g. padding-inline satisfies padding). + if (normDecl.startsWith(`${normExp}-`)) return true; + return false; +} + +function valueMatches(declaredVal: string, expectedVal: string): boolean { + const normDecl = declaredVal.trim().replace(/\s+/g, " ").toLowerCase(); + const normExp = expectedVal.trim().replace(/\s+/g, " ").toLowerCase(); + if (normDecl === normExp) return true; + const tokens = normDecl.split(" "); + return tokens.includes(normExp); +} + +/** + * Deterministic constant/selector-vs-CSS mirror verifier (`readmark #76` class). + * Verifies that every selector (and optional property/value) claimed to mirror a constant + * actually exists in the target stylesheet. + */ +export function verifyCssMirror(input: CssMirrorInput): GateFinding[] { + const findings: GateFinding[] = []; + if (!input.subject.trim()) { + findings.push({ + code: "INVALID_VERIFIER_SPEC", + subject: "css-mirror", + detail: "cssMirror check subject must be non-empty", + }); + return findings; + } + + if (input.expectations.length === 0) { + findings.push({ + code: "INVALID_VERIFIER_SPEC", + subject: input.subject, + detail: "cssMirror check must declare at least one expectation", + }); + return findings; + } + + const rules = parseCssRules(input.cssText); + + for (const exp of input.expectations) { + const expSubject = `${input.subject}:${exp.constantName}`; + if (!exp.constantName.trim() || exp.selectors.length === 0) { + findings.push({ + code: "INVALID_VERIFIER_SPEC", + subject: expSubject, + detail: "cssMirror expectation requires non-empty constantName and at least one selector", + }); + continue; + } + + if (input.sourceCode !== undefined) { + const constPattern = new RegExp(`\\b${escapeRegExp(exp.constantName)}\\b`); + if (!constPattern.test(input.sourceCode)) { + findings.push({ + code: "UNVERIFIED_PROSE_MIRROR", + subject: expSubject, + detail: `declared constant '${exp.constantName}' not found in source file`, + }); + } + } + + const matchedRulesForAnySelector: ParsedCssRule[] = []; + for (const selector of exp.selectors) { + const matching = rules.filter((r) => + r.selectors.some((ruleSel) => selectorMatches(ruleSel, selector)), + ); + if (matching.length === 0) { + findings.push({ + code: "UNVERIFIED_PROSE_MIRROR", + subject: expSubject, + detail: `claimed mirrored CSS selector '${selector}' does not exist in target stylesheet`, + }); + } else { + matchedRulesForAnySelector.push(...matching); + } + } + + if (exp.expectedProperty && matchedRulesForAnySelector.length > 0) { + const propValues: string[] = []; + for (const rule of matchedRulesForAnySelector) { + for (const [prop, vals] of rule.declarations.entries()) { + if (propertyMatches(prop, exp.expectedProperty)) { + propValues.push(...vals); + } + } + } + + if (propValues.length === 0) { + findings.push({ + code: "UNVERIFIED_PROSE_MIRROR", + subject: expSubject, + detail: `none of [${exp.selectors.join(", ")}] declares expected CSS property '${exp.expectedProperty}'`, + }); + } else if ( + exp.expectedValue !== undefined && + !propValues.some((val) => valueMatches(val, exp.expectedValue!)) + ) { + findings.push({ + code: "UNVERIFIED_PROSE_MIRROR", + subject: expSubject, + detail: `CSS property '${exp.expectedProperty}' on [${exp.selectors.join(", ")}] has values [${propValues.join("; ")}], which do not match claimed value '${exp.expectedValue}'`, + }); + } + } + } + + return findings; +} + +function normalizeIdentifier(raw: string): string { + const trimmed = raw.trim(); + // Remove schema qualifier (e.g. public.bookmarks -> bookmarks) + const parts = trimmed.split("."); + const last = (parts[parts.length - 1] ?? trimmed).trim(); + return last.replace(/^["`[\]]+|["`[\]]+$/g, "").toLowerCase(); +} + +function parseColumnList(rawCols: string): string[] { + return rawCols + .split(",") + .map((part) => { + // Strip sort direction / NULLS ordering / collation / length spec (e.g. `col(20) DESC NULLS LAST`) + const cleaned = part + .trim() + .replace(/\(\s*\d+\s*\)/g, "") + .replace(/\b(?:ASC|DESC|NULLS\s+FIRST|NULLS\s+LAST)\b/gi, "") + .trim(); + const firstToken = cleaned.split(/\s+/)[0] ?? ""; + return normalizeIdentifier(firstToken); + }) + .filter((c) => c.length > 0); +} + +function addIndex( + indexMap: Map, + table: string, + cols: string[], +): void { + if (!table || cols.length === 0) return; + const existing = indexMap.get(table); + if (existing) existing.push(cols); + else indexMap.set(table, [cols]); +} + +function stripSqlComments(sql: string): string { + return sql + .replace(/\/\*[\s\S]*?\*\//g, " ") + .replace(/--[^\n]*/g, " "); +} + +function parseSqlIndexes(sqlDdl: string): Map { + const indexMap = new Map(); + const cleaned = stripSqlComments(sqlDdl); + + // 1. Standalone CREATE [UNIQUE] INDEX ... ON table [USING method] (col1, col2, ...) + const createIndexRegex = + /CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?:CONCURRENTLY\s+)?(?:IF\s+NOT\s+EXISTS\s+)?(?:["`\[]?[A-Za-z0-9_.]+["`\]]?\s+)?ON\s+(?:ONLY\s+)?(["`\[]?[A-Za-z0-9_.]+["`\]]?)\s*(?:USING\s+[A-Za-z0-9_]+\s*)?\(([^)]+)\)/gi; + let match: RegExpExecArray | null; + while ((match = createIndexRegex.exec(cleaned)) !== null) { + const table = normalizeIdentifier(match[1] ?? ""); + const cols = parseColumnList(match[2] ?? ""); + addIndex(indexMap, table, cols); + } + + // 2. Inline CREATE TABLE constraints (PRIMARY KEY, UNIQUE, INDEX/KEY) + const createTableRegex = + /CREATE\s+(?:TEMP(?:ORARY)?\s+)?TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(["`\[]?[A-Za-z0-9_.]+["`\]]?)\s*\(/gi; + while ((match = createTableRegex.exec(cleaned)) !== null) { + const table = normalizeIdentifier(match[1] ?? ""); + const startIdx = match.index + match[0].length; + let depth = 1; + let j = startIdx; + while (j < cleaned.length && depth > 0) { + if (cleaned[j] === "(") depth += 1; + else if (cleaned[j] === ")") depth -= 1; + j += 1; + } + if (depth !== 0) continue; + const body = cleaned.slice(startIdx, j - 1); + + // Table-level PRIMARY KEY / UNIQUE / INDEX / KEY (...) + const tableConstraintRegex = + /(?:CONSTRAINT\s+["`\[]?[A-Za-z0-9_]+["`\]]?\s+)?(?:PRIMARY\s+KEY|UNIQUE(?:\s+(?:INDEX|KEY))?(?:\s+["`\[]?[A-Za-z0-9_]+["`\]]?)?|(?:INDEX|KEY)\s+["`\[]?[A-Za-z0-9_]+["`\]]?)\s*\(([^)]+)\)/gi; + let cm: RegExpExecArray | null; + while ((cm = tableConstraintRegex.exec(body)) !== null) { + const cols = parseColumnList(cm[1] ?? ""); + addIndex(indexMap, table, cols); + } + + // Column-level PRIMARY KEY / UNIQUE + for (const rawLine of body.split(",")) { + const line = rawLine.trim(); + if (/^(?:CONSTRAINT|PRIMARY|UNIQUE|FOREIGN|CHECK|INDEX|KEY)\b/i.test(line)) { + continue; + } + if (/\b(?:PRIMARY\s+KEY|UNIQUE)\b/i.test(line)) { + const colMatch = /^(["`\[]?[A-Za-z0-9_]+["`\]]?)\s+/.exec(line); + if (colMatch?.[1]) { + addIndex(indexMap, table, [normalizeIdentifier(colMatch[1])]); + } + } + } + } + + return indexMap; +} + +function parseDexieIndexes( + dexieSchema: Readonly>, +): Map { + const indexMap = new Map(); + for (const [rawTable, spec] of Object.entries(dexieSchema)) { + const table = normalizeIdentifier(rawTable); + for (const rawEntry of spec.split(",")) { + const entry = rawEntry.trim(); + if (!entry) continue; + if (entry.startsWith("[") && entry.endsWith("]")) { + const cols = entry + .slice(1, -1) + .split("+") + .map((c) => normalizeIdentifier(c)) + .filter((c) => c.length > 0); + addIndex(indexMap, table, cols); + } else { + const col = normalizeIdentifier(entry.replace(/^(?:\+\+|&|\*)/, "")); + if (col) addIndex(indexMap, table, [col]); + } + } + } + return indexMap; +} + +function indexCoversColumns( + indexColumns: readonly string[], + claimedColumns: readonly string[], +): boolean { + if (claimedColumns.length === 0 || claimedColumns.length > indexColumns.length) { + return false; + } + for (let i = 0; i < claimedColumns.length; i += 1) { + if (indexColumns[i] !== claimedColumns[i]) return false; + } + return true; +} + +/** + * Deterministic schema-index verifier (`readmark #72` class). + * Parses SQL DDL and/or Dexie store schemas and verifies that every claimed indexed query + * is actually covered by a declared index (leftmost-prefix semantics). + */ +export function verifySchemaIndexes(input: SchemaIndexInput): GateFinding[] { + const findings: GateFinding[] = []; + if (!input.subject.trim()) { + findings.push({ + code: "INVALID_VERIFIER_SPEC", + subject: "schema-index", + detail: "schemaIndex check subject must be non-empty", + }); + return findings; + } + + if (input.claims.length === 0) { + findings.push({ + code: "INVALID_VERIFIER_SPEC", + subject: input.subject, + detail: "schemaIndex check must declare at least one query index claim", + }); + return findings; + } + + if (input.sqlDdl === undefined && input.dexieSchema === undefined) { + findings.push({ + code: "INVALID_VERIFIER_SPEC", + subject: input.subject, + detail: "schemaIndex check requires sqlDdl and/or dexieSchema", + }); + return findings; + } + + const indexMap = new Map(); + if (input.sqlDdl !== undefined) { + for (const [table, indexes] of parseSqlIndexes(input.sqlDdl).entries()) { + for (const cols of indexes) addIndex(indexMap, table, cols); + } + } + if (input.dexieSchema !== undefined) { + for (const [table, indexes] of parseDexieIndexes(input.dexieSchema).entries()) { + for (const cols of indexes) addIndex(indexMap, table, cols); + } + } + + for (const claim of input.claims) { + const claimSubject = `${input.subject}:${claim.queryName}`; + const table = normalizeIdentifier(claim.table); + const claimedCols = claim.columns.map(normalizeIdentifier).filter((c) => c.length > 0); + + if (!claim.queryName.trim() || !table || claimedCols.length === 0) { + findings.push({ + code: "INVALID_VERIFIER_SPEC", + subject: claimSubject, + detail: "query index claim requires non-empty queryName, table, and columns", + }); + continue; + } + + const available = indexMap.get(table) ?? []; + const covered = available.some((idxCols) => indexCoversColumns(idxCols, claimedCols)); + if (!covered) { + const declaredSummary = + available.length === 0 + ? "none" + : available.map((cols) => `[${cols.join("+")}]`).join(", "); + findings.push({ + code: "FALLBACK_CONTRADICTS_CLAIM", + subject: claimSubject, + detail: `claimed indexed query on '${claim.table}' for [${claimedCols.join("+")}] is not covered by any declared index (declared: ${declaredSummary}); runtime would fall back to scan`, + }); + } + } + + return findings; +} diff --git a/scripts/quality/check-gate-honesty.mts b/scripts/quality/check-gate-honesty.mts index 3db52e7..a0e5373 100644 --- a/scripts/quality/check-gate-honesty.mts +++ b/scripts/quality/check-gate-honesty.mts @@ -1,268 +1,9 @@ #!/usr/bin/env node -import { readFileSync } from "node:fs"; import { resolve } from "node:path"; import { fileURLToPath } from "node:url"; -import { parse as parseYaml } from "yaml"; +import { main } from "../gate-honesty/cli.mts"; -export interface TestPartitionReport { - readonly partition: string; - readonly exitCode: number; - readonly reportedSuccess: boolean; - readonly numCollectedFiles: number; - readonly numTotalTests: number; - readonly numPassedTests: number; - readonly numFailedTests: number; - readonly numSkippedTests: number; - readonly minPassedRequired?: number; -} - -export type ExecutionVerdict = "VERIFIED" | "FAIL_CLOSED_SAFE" | "SILENT_PASS_DEFECT"; - -export interface GateFinding { - readonly code: - | "ZERO_EXECUTED_SILENT_PASS" - | "ALL_SKIPPED_SILENT_PASS" - | "BELOW_MIN_PASSED_FLOOR" - | "INCONSISTENT_SUCCESS_EXIT" - | "MERGE_TREE_VS_HEAD_REF_MISMATCH" - | "MASKED_STEP_FAILURE" - | "SKIPPED_REQUIRED_PARTITION" - | "FALLBACK_CONTRADICTS_CLAIM" - | "UNVERIFIED_PROSE_MIRROR" - | "SHA_MISMATCH"; - readonly subject: string; - readonly detail: string; -} - -export interface ExecutionCheckResult { - readonly verdict: ExecutionVerdict; - readonly findings: readonly GateFinding[]; -} - -export function checkTestExecution(report: TestPartitionReport): ExecutionCheckResult { - const findings: GateFinding[] = []; - const floor = report.minPassedRequired ?? 1; - - // Distinguish fail-closed (e.g. u-sekai #78: 0 files collected, exit 1) - // from silent pass (e.g. ty-plus #179: files collected, 0 tests executed, exit 0). - if (report.exitCode !== 0) { - if (report.reportedSuccess) { - findings.push({ - code: "INCONSISTENT_SUCCESS_EXIT", - subject: report.partition, - detail: `partition reported success=true despite non-zero exit code ${report.exitCode}`, - }); - return { verdict: "SILENT_PASS_DEFECT", findings }; - } - return { verdict: "FAIL_CLOSED_SAFE", findings: [] }; - } - - if (report.numFailedTests > 0 && report.reportedSuccess) { - findings.push({ - code: "INCONSISTENT_SUCCESS_EXIT", - subject: report.partition, - detail: `partition reported success with ${report.numFailedTests} failed tests`, - }); - } - - if (report.numTotalTests > 0 && report.numPassedTests === 0 && report.numFailedTests === 0) { - const allSkipped = report.numSkippedTests >= report.numTotalTests; - findings.push({ - code: allSkipped ? "ALL_SKIPPED_SILENT_PASS" : "ZERO_EXECUTED_SILENT_PASS", - subject: report.partition, - detail: allSkipped - ? `all ${report.numTotalTests} tests were skipped yet exited 0 (silent pass)` - : `${report.numTotalTests} tests discovered but 0 executed/passed yet exited 0 (e.g. unmatched -t filter)`, - }); - } else if (report.numPassedTests < floor) { - findings.push({ - code: "BELOW_MIN_PASSED_FLOOR", - subject: report.partition, - detail: `passed tests (${report.numPassedTests}) below required floor (${floor}) despite exit 0`, - }); - } - - return { - verdict: findings.length === 0 ? "VERIFIED" : "SILENT_PASS_DEFECT", - findings, - }; -} - -interface WorkflowStep { - readonly name?: string; - readonly uses?: string; - readonly with?: Record; - readonly run?: string; - readonly "continue-on-error"?: boolean; -} - -interface WorkflowJob { - readonly steps?: readonly WorkflowStep[]; -} - -interface WorkflowDoc { - readonly on?: unknown; - readonly jobs?: Record; -} - -function triggersPullRequest(onField: unknown): boolean { - if (typeof onField === "string") return onField === "pull_request" || onField === "pull_request_target"; - if (Array.isArray(onField)) return onField.includes("pull_request") || onField.includes("pull_request_target"); - if (onField !== null && typeof onField === "object") { - return Object.hasOwn(onField, "pull_request") || Object.hasOwn(onField, "pull_request_target"); - } - return false; -} - -export function checkWorkflowHonesty(yamlText: string, fileLabel = "workflow.yml"): GateFinding[] { - const doc = parseYaml(yamlText) as WorkflowDoc | null; - if (!doc || typeof doc !== "object") return []; - const findings: GateFinding[] = []; - const hasPrTrigger = triggersPullRequest(doc.on); - const jobs = doc.jobs ?? {}; - - for (const [jobName, job] of Object.entries(jobs)) { - const steps = Array.isArray(job?.steps) ? job.steps : []; - let defaultMergeTreeCheckout = false; - let usesHeadRefEnv = false; - - for (const [idx, step] of steps.entries()) { - const subject = `${fileLabel}:${jobName}[${step.name ?? String(idx)}]`; - if (typeof step.uses === "string" && step.uses.startsWith("actions/checkout@")) { - const ref = step.with?.ref; - if (ref === undefined || ref === null || String(ref).trim() === "") { - defaultMergeTreeCheckout = true; - } - } - if (typeof step.run === "string") { - if (/\bGITHUB_HEAD_REF\b|\bgithub\.head_ref\b/.test(step.run)) { - usesHeadRefEnv = true; - } - if (/\|\|\s*true\b/.test(step.run)) { - findings.push({ - code: "MASKED_STEP_FAILURE", - subject, - detail: "step masks non-zero exit code with '|| true'", - }); - } - } - if (step["continue-on-error"] === true) { - findings.push({ - code: "MASKED_STEP_FAILURE", - subject, - detail: "step sets continue-on-error: true, turning failure into green job status", - }); - } - } - - if (hasPrTrigger && defaultMergeTreeCheckout && usesHeadRefEnv) { - findings.push({ - code: "MERGE_TREE_VS_HEAD_REF_MISMATCH", - subject: `${fileLabel}:${jobName}`, - detail: - "pull_request job checks out default merge tree (no explicit ref:) while reading GITHUB_HEAD_REF/github.head_ref (subject tree and ref name come from different trees)", - }); - } - } - return findings; -} - -export interface ClaimVerificationRecord { - readonly subject: string; - readonly claimedSha: string; - readonly executedSha: string; - readonly requiredPartitions: readonly string[]; - readonly partitionReports: readonly TestPartitionReport[]; - readonly skippedRequiredPartitions?: readonly string[]; - readonly claimedGuarantee: string; - readonly fallbackUsed?: boolean; - readonly proseMirrorClaim?: { - readonly declaredRelation: string; - readonly verifiedAgainstTarget: boolean; - }; -} - -export function checkClaimHonesty(record: ClaimVerificationRecord): GateFinding[] { - const findings: GateFinding[] = []; - if (record.claimedSha !== record.executedSha) { - findings.push({ - code: "SHA_MISMATCH", - subject: record.subject, - detail: `claimed SHA (${record.claimedSha}) does not match executed SHA (${record.executedSha})`, - }); - } - - for (const skipped of record.skippedRequiredPartitions ?? []) { - findings.push({ - code: "SKIPPED_REQUIRED_PARTITION", - subject: `${record.subject}:${skipped}`, - detail: `required partition '${skipped}' was skipped; cannot count as discharged`, - }); - } - - const reportByName = new Map(record.partitionReports.map((r) => [r.partition, r] as const)); - for (const required of record.requiredPartitions) { - const report = reportByName.get(required); - if (!report) { - findings.push({ - code: "SKIPPED_REQUIRED_PARTITION", - subject: `${record.subject}:${required}`, - detail: `required partition '${required}' produced no execution report`, - }); - continue; - } - const execCheck = checkTestExecution(report); - if (execCheck.verdict === "FAIL_CLOSED_SAFE") { - findings.push({ - code: "SKIPPED_REQUIRED_PARTITION", - subject: `${record.subject}:${required}`, - detail: `required partition '${required}' failed closed (exit ${report.exitCode}); not verified`, - }); - } else { - findings.push(...execCheck.findings); - } - } - - if (record.fallbackUsed === true) { - findings.push({ - code: "FALLBACK_CONTRADICTS_CLAIM", - subject: record.subject, - detail: `execution fell back away from claimed guarantee (${record.claimedGuarantee})`, - }); - } - - if (record.proseMirrorClaim && !record.proseMirrorClaim.verifiedAgainstTarget) { - findings.push({ - code: "UNVERIFIED_PROSE_MIRROR", - subject: record.subject, - detail: `prose/comment invariant '${record.proseMirrorClaim.declaredRelation}' does not match verified target`, - }); - } - - return findings; -} - -function main(argv: readonly string[]): number { - const mode = argv[0]; - const filePath = argv[1]; - if (!mode || !filePath) { - console.error("usage: check-gate-honesty.mts "); - return 2; - } - const content = readFileSync(resolve(filePath), "utf8"); - const findings = - mode === "workflow" - ? checkWorkflowHonesty(content, filePath) - : mode === "claim" - ? checkClaimHonesty(JSON.parse(content) as ClaimVerificationRecord) - : null; - if (findings === null) { - console.error(`unknown mode: ${mode}`); - return 2; - } - console.log(JSON.stringify({ status: findings.length === 0 ? "PASS" : "FAIL", findings }, null, 2)); - return findings.length === 0 ? 0 : 1; -} +export * from "../gate-honesty/index.mts"; if ( process.argv[1] && diff --git a/scripts/quality/check-gate-honesty.test.mts b/scripts/quality/check-gate-honesty.test.mts index 4a1652e..7db9a0d 100644 --- a/scripts/quality/check-gate-honesty.test.mts +++ b/scripts/quality/check-gate-honesty.test.mts @@ -4,142 +4,87 @@ import { checkClaimHonesty, checkTestExecution, checkWorkflowHonesty, + verifyCssMirror, + verifySchemaIndexes, } from "./check-gate-honesty.mts"; -test("distinguishes u-sekai #78 fail-closed from ty-plus #179 silent pass", () => { - // u-sekai #78 (corrected observation): 0 files collected -> exit 1 -> fail-closed (safe) - const failClosed = checkTestExecution({ - partition: "unit", - exitCode: 1, - reportedSuccess: false, - numCollectedFiles: 0, - numTotalTests: 0, - numPassedTests: 0, - numFailedTests: 0, - numSkippedTests: 0, - }); - assert.equal(failClosed.verdict, "FAIL_CLOSED_SAFE"); - assert.equal(failClosed.findings.length, 0); +test("scripts/quality/check-gate-honesty.mts facade exposes deterministic gate honesty verifiers", () => { + const validSha = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; - // ty-plus #179 (unmatched -t filter): files collected, 25 discovered, 0 passed, exit 0 -> silent pass defect - const unmatchedFilter = checkTestExecution({ + const execRes = checkTestExecution({ partition: "unit", exitCode: 0, reportedSuccess: true, - numCollectedFiles: 1, - numTotalTests: 25, - numPassedTests: 0, + numCollectedFiles: 2, + numTotalTests: 10, + numPassedTests: 10, numFailedTests: 0, numSkippedTests: 0, }); - assert.equal(unmatchedFilter.verdict, "SILENT_PASS_DEFECT"); - assert.equal(unmatchedFilter.findings[0]?.code, "ZERO_EXECUTED_SILENT_PASS"); + assert.equal(execRes.verdict, "VERIFIED"); - // ty-plus #179 (describe.skip): all tests skipped, exit 0 -> silent pass defect - const allSkipped = checkTestExecution({ - partition: "unit", - exitCode: 0, - reportedSuccess: true, - numCollectedFiles: 1, - numTotalTests: 3, - numPassedTests: 0, - numFailedTests: 0, - numSkippedTests: 3, - }); - assert.equal(allSkipped.verdict, "SILENT_PASS_DEFECT"); - assert.equal(allSkipped.findings[0]?.code, "ALL_SKIPPED_SILENT_PASS"); -}); - -test("negative workflow controls: u-sekai #75 merge-tree vs head-ref and masked failure", () => { - const brokenWorkflow = ` -name: ci -on: - pull_request: -jobs: - version: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - name: Check version against head ref - run: node scripts/version-check.mjs "$GITHUB_HEAD_REF" || true -`; - const findings = checkWorkflowHonesty(brokenWorkflow, ".github/workflows/ci.yml"); - assert.ok(findings.some((f) => f.code === "MERGE_TREE_VS_HEAD_REF_MISMATCH")); - assert.ok(findings.some((f) => f.code === "MASKED_STEP_FAILURE")); - - const honestWorkflow = ` -name: ci -on: - pull_request: -jobs: - version: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - with: - ref: \${{ github.event.pull_request.head.sha }} - - name: Check version against head ref - run: node scripts/version-check.mjs "$GITHUB_HEAD_REF" -`; - assert.deepEqual(checkWorkflowHonesty(honestWorkflow, ".github/workflows/ci.yml"), []); -}); - -test("negative claim controls: ty-plus #175 skipped partition, readmark #72 fallback, readmark #76 false prose mirror", () => { - const findings = checkClaimHonesty({ + const claimFindings = checkClaimHonesty({ subject: "release-gate", - claimedSha: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - executedSha: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - requiredPartitions: ["unit", "windows-release-gate"], - skippedRequiredPartitions: ["windows-release-gate"], + claimedSha: validSha, + executedSha: validSha, + requiredPartitions: ["unit"], partitionReports: [ { partition: "unit", + sha: validSha, exitCode: 0, reportedSuccess: true, - numCollectedFiles: 5, - numTotalTests: 21, - numPassedTests: 21, + numCollectedFiles: 2, + numTotalTests: 10, + numPassedTests: 10, numFailedTests: 0, numSkippedTests: 0, }, ], - claimedGuarantee: "indexed read via [documentId+sourceFingerprint]", - fallbackUsed: true, - proseMirrorClaim: { - declaredRelation: "FIT_WIDTH_PADDING_PX=48 mirrors .rm-reader-scroll padding", - verifiedAgainstTarget: false, - }, - }); - const codes = new Set(findings.map((f) => f.code)); - assert.ok(codes.has("SKIPPED_REQUIRED_PARTITION")); - assert.ok(codes.has("FALLBACK_CONTRADICTS_CLAIM")); - assert.ok(codes.has("UNVERIFIED_PROSE_MIRROR")); -}); - -test("positive control: executed tests > 0, exact SHA, no fallback, verified prose passes", () => { - const findings = checkClaimHonesty({ - subject: "release-gate", - claimedSha: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", - executedSha: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", - requiredPartitions: ["unit"], - partitionReports: [ + claimedGuarantee: "unit suite executed with real verified schema and CSS mirrors", + cssMirrorChecks: [ { - partition: "unit", - exitCode: 0, - reportedSuccess: true, - numCollectedFiles: 4, - numTotalTests: 18, - numPassedTests: 18, - numFailedTests: 0, - numSkippedTests: 0, + subject: "reader-view", + cssText: ".rm-reader-scroll { padding-inline: 48px; }", + expectations: [ + { + constantName: "FIT_WIDTH_PADDING_PX", + selectors: [".rm-reader-scroll"], + expectedProperty: "padding", + expectedValue: "48px", + }, + ], + }, + ], + schemaIndexChecks: [ + { + subject: "bookmarks", + dexieSchema: { bookmarks: "++id, [documentId+sourceFingerprint]" }, + claims: [ + { + queryName: "listBookmarks", + table: "bookmarks", + columns: ["documentId", "sourceFingerprint"], + }, + ], }, ], - claimedGuarantee: "unit suite executed on candidate SHA", - fallbackUsed: false, - proseMirrorClaim: { - declaredRelation: "intentional margin token (no stylesheet mirror claimed)", - verifiedAgainstTarget: true, - }, }); - assert.deepEqual(findings, []); + assert.deepEqual(claimFindings, []); + + assert.ok(checkWorkflowHonesty("", "empty.yml").length > 0); + assert.ok( + verifyCssMirror({ + subject: "negative", + cssText: ".other { padding: 0; }", + expectations: [{ constantName: "X", selectors: [".missing"] }], + }).length > 0, + ); + assert.ok( + verifySchemaIndexes({ + subject: "negative", + sqlDdl: "CREATE TABLE t (id INT PRIMARY KEY, a INT, b INT);", + claims: [{ queryName: "q", table: "t", columns: ["a", "b"] }], + }).length > 0, + ); }); diff --git a/skills/correctness-assurance/SKILL.md b/skills/correctness-assurance/SKILL.md index 247e233..c8afad7 100644 --- a/skills/correctness-assurance/SKILL.md +++ b/skills/correctness-assurance/SKILL.md @@ -436,7 +436,7 @@ Evidence - toolchain/version ``` -「tests green」「proof green」だけで終了しない。 +「tests green」「proof green」だけで終了しない。actual execution と reported claim の乖離(0 件実行 silent pass、index silent fallback、未検証 prose mirror)の機械検証契約は [gate-honesty](../quality-gate/references/gate-honesty.md) を参照する。 ## 15. Reproducibility diff --git a/skills/quality-gate/references/gate-honesty.md b/skills/quality-gate/references/gate-honesty.md index 360a5e9..f71c299 100644 --- a/skills/quality-gate/references/gate-honesty.md +++ b/skills/quality-gate/references/gate-honesty.md @@ -6,22 +6,37 @@ gate・CI・コードコメントが「実際に検証していないもの」 | 分類 | 実例 | 実測挙動 | リスク | | --- | --- | --- | --- | -| **Fail-closed(安全に停止)** | `u-sekai #78` | 0 file 収集 → `exit 1`(Vitest `passWithNoTests: false` 既定) | 検証不能だが偽の green は作らない | +| **Fail-closed(安全に停止)** | `u-sekai #78` | `--dir` が `root` を上書きし 0 file 収集 → `exit 1`(Vitest `passWithNoTests: false` 既定) | 検証不能(noise)だが偽の green は作らない | | **Silent pass(最も危険)** | `ty-plus #179` | file 収集あり・`-t` 不一致や `describe.skip` で実行 0 件 → `exit 0` / `success: true` | aggregate gate が「検証済み」と誤認する | -`passWithNoTests: false` は「収集 file 0 件」しか防がない。各 partition について **`numPassedTests >= 1`(実行・通過件数の下限)** を必須検証する。 +`passWithNoTests: false` は「収集 file 0 件」しか防がない。各 partition について **`numPassedTests >= 1`(実行・通過件数の下限)**、**`exitCode === 0` 時の `numFailedTests === 0 && reportedSuccess === true`**、および不変条件(負数・件数矛盾・不正 floor の拒否)を実ランナー出力(TAP / Vitest JSON)から直接検証する。 -## 3 つの欠陥担い手と対比表 +## 記録済み事例の監査対比表 -| 担い手 | 実例 | 主張していた保証 | 実際の挙動 | 機械的対策 | +| 担い手クラス | 実例 | 主張していた保証 | 実際の挙動 | 機械的対策 | | --- | --- | --- | --- | --- | -| 1. CI event/ref/tree 不一致 | `my-web-2026 #260`, `u-sekai #75` | PR 対象ブランチの版整合を検証 | `pull_request` で merge tree を checkout しつつ `GITHUB_HEAD_REF` を参照・不活性 no-op | `actions/checkout` に明示 `ref` 指定、workflow 静的検査 | -| 2. 結果の正しさ ≠ 検証済み | `ty-plus #175`, `ty-plus #179`, `readmark #72` | Windows gate 通過 / unit 通過 / indexed read | SKIP で exit 0 / 実行 0 件で exit 0 / 存在しない index で full table scan fallback | partition 通過下限・SKIP 非通過・fallback 検出 | -| 3. Prose / comment の虚偽 invariant | `readmark #76`, `u-sekai #76` | 定数が CSS padding と一致必須 | 一致する selector が存在せず、値は正しいがコメントが誤り | mirror 主張は実値照合、意図的余白は独立 token 名で表現 | +| 1. CI event / ref / tree 不一致 | `my-web-2026 #260` | PR で release branch の版整合を検証 | `pull_request` で `GITHUB_HEAD_REF` が ticket branch・`GITHUB_REF_NAME` が `/merge` のため no-op 化し、#248–#251 が red trunk へ merge | event/ref 前提を自己検証し、inactive 時は fail closed | +| 1. CI event / ref / tree 不一致 | `u-sekai #75` | head ブランチの `package.json` 版整合を検証 | `actions/checkout` に `ref:` 未指定で merge tree を取得しつつ `GITHUB_HEAD_REF` を渡し、比較対象と基準が別 tree 由来 | `pull_request` で `ref: ${{ github.event.pull_request.head.sha }}` を明示、`workflow --workflows-dir` で全 workflow を検査 | +| 1. CI event / ref / tree 不一致(fail-closed 側) | `u-sekai #78` | `test:unit` / `test:integration` / `test:e2e` で既存 test を実行 | `--dir` が `root` を上書きして 0 file 収集 → `exit 1`(fail-closed、偽の green なし) | `passWithNoTests: false` 維持に加え、実行件数下限で 0 件実行と区別 | +| 2. 結果の正しさ ≠ 検証済み | `ty-plus #175` | Windows-only release gate を通過 | Windows check が SKIP で `exit 0` し、release gate が未検証のまま緑化 | SKIP された必須 partition・空の `requiredPartitions`・重複 partition 上書きを拒否 | +| 2. 結果の正しさ ≠ 検証済み | `ty-plus PR #176` | 新規 `windows-release-gate` owner が Windows 検証責務を履行 | Playwright Chromium 未導入で `browserType.launch` 失敗(PR 自身の ADR「an owner that cannot discharge its responsibility is not an owner」に反し未解決で出荷) | owner 実稼働と実ランナー通過件数 (`numPassedTests >= 1`) の両方を gate 必須化 | +| 2. 結果の正しさ ≠ 検証済み | `ty-plus #179` | unit partition がテストを実行して通過 | file は収集されるが `-t` 不一致 / `describe.skip` で実行 0 件のまま `exit 0` / `success: true` | `parseNodeTestTap` / `parseVitestJson` + `run-and-verify --floor 1` で実実行件数を強制検証 | +| 2. 結果の正しさ ≠ 検証済み | `readmark #72` | `listBookmarks` / `listHighlights` が `[documentId+sourceFingerprint]` で indexed read | schema 宣言は `+pageIndex` のみで Dexie が例外を出さず full table scan へ silent fallback | `verifySchemaIndexes` で SQL DDL / Dexie schema 宣言と主張 query 列(左端一致)を機械照合 | +| 3. Prose / comment の虚偽 invariant | `readmark #76` | `FIT_WIDTH_PADDING_PX = 48` は `.rm-reader-scroll` / `.rm-reader-pages` の CSS padding と一致必須 | CSS の水平 padding は `0` / 未定義。値は意図的余白として正しいがコメントが不変条件を誤記 | `verifyCssMirror` で実 stylesheet の selector/property/value を照合、意図的余白は独立 token 名で表現 | +| 3. Prose / comment の虚偽 invariant | `u-sekai #76`, `ty-plus B1/B6` (`ci.yml:355`) | コメント・prose が gate 実装の検証範囲や不変条件を説明 | コメント記述と実際の workflow / gate 挙動が乖離し、レビューが未検証状態を誤認 | prose 主張を boolean 自己申告にせず、workflow 静的検査と決定論的 verifier に接続 | ## 実行入口 ```bash +# 実 node --test TAP 出力の実行件数 >= 1 を検証(negative/positive controls 含む) bun run test:gate-honesty -node scripts/quality/check-gate-honesty.mts workflow .github/workflows/eval-controls.yml + +# .github/workflows 配下の全 YAML を一括検査(空/壊れた YAML は fail closed) +bun run quality:workflow-honesty + +# 任意コマンドの TAP / Vitest JSON 出力を直接検証 +node scripts/gate-honesty/cli.mts verify-tap - --floor 1 +node scripts/gate-honesty/cli.mts verify-vitest-json report.json --floor 1 +node scripts/gate-honesty/cli.mts verify-css-mirror spec.json +node scripts/gate-honesty/cli.mts verify-schema-index spec.json ```