diff --git a/.github/workflows/verification.yml b/.github/workflows/verification.yml new file mode 100644 index 0000000..4e68b54 --- /dev/null +++ b/.github/workflows/verification.yml @@ -0,0 +1,42 @@ +# Verification suites beyond the Turborepo pipeline: the standalone security +# suite and evaluation harness (with its negative control), plus the +# verification-gate validator tests. PRs that touch security/, evaluation/, or +# packages/domain run these on every push; the merge gate itself additionally +# demands green checks on the exact head SHA (verification/README.md). +name: Verification + +on: + pull_request: + branches: [master] + push: + branches: [master] + +concurrency: + group: verification-${{ github.ref }} + cancel-in-progress: true + +jobs: + suites: + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v4 + + - uses: oven-sh/setup-bun@v2 + with: + bun-version: 1.3.14 + + - name: Security suite (17 fail-closed access cases) + run: bun test ./security + + - name: Evaluation harness (corpus vs worked example) + working-directory: evaluation + run: bun src/run.ts + + - name: Evaluation negative control (broken adapter must fail) + working-directory: evaluation + run: bun src/run.ts --adapter=./src/example/broken-adapter.ts --expect-failure + + - name: Verification-gate validator tests (positive + negative controls) + working-directory: verification + run: bun test ./test diff --git a/.obvious/obvious.md b/.obvious/obvious.md index 860efde..abf57f5 100644 --- a/.obvious/obvious.md +++ b/.obvious/obvious.md @@ -64,7 +64,23 @@ bun src/run.ts --adapter=./src/example/broken-adapter.ts --expect-failure # ne The security suite and evaluation harness are standalone (`security/` and `evaluation/` are not pnpm workspace members), so CI's `pnpm turbo run test` does not cover them — run them locally whenever you touch `security/`, -`evaluation/`, or the domain contracts. +`evaluation/`, or the domain contracts. `.github/workflows/verification.yml` +runs both suites (plus the evaluation negative control and the +verification-gate validator tests) on every PR and push to `master`. + +## Verification gate (executable merge workflow) + +The review → repair → merge workflow below is executable in +`verification/` (see `verification/README.md`). PRs record a +`verification-manifest:v1` block (body or comment — review result, check and +suite runs, behavior/playable-flow evidence, all on the exact tested HEAD). +`bun verification/src/cli.ts validate-pr --pr=` validates the latest +manifest against live PR state; the merge owner runs +`sweep --pr= --owner=` which refuses unless the PR is open on +master, checks are green on the exact head SHA, and the manifest validates, +then merges `--squash` and emits the evidence receipt. Arena candidate +branches are held regardless of evidence. The validator is pinned by +positive + negative controls (`cd verification && bun test ./test`). ## CI diff --git a/verification/README.md b/verification/README.md new file mode 100644 index 0000000..11bc08b --- /dev/null +++ b/verification/README.md @@ -0,0 +1,93 @@ +# Verification Gate + +Executes the repo's review → repair → merge contract (`.obvious/obvious.md`) +as an inspectable tool instead of prose. Zero dependencies, runs under Bun. + +**Load-bearing assumption:** a PR-comment manifest plus live GitHub reads can +carry the contract's merge decision without inventing approvals. The gate +validates only what is recorded and observed; it can detect contradiction, not +verify intent — a fabricated-but-self-consistent manifest passes. What keeps +that honest: every field must carry a URL, the sweep re-observes live state +(checks on the exact head SHA, live diff paths), and the evidence receipt +records everything for post-hoc review. If a receipt is ever found to +misstate reality, the manifest's `reviewer`/`url` fields name who claimed it. + +## Manifest format + +Recorded on the PR (body or any comment; the **latest** block across +body + comments wins, and a later malformed block fails loudly rather than +falling back): + +````html + +```json +{ + "manifestVersion": 1, + "pr": 13, + "prUrl": "https://github.com/OCPdev25/obv-hackaton/pull/13", + "testedHeadSha": "<40-hex HEAD under review>", + "classification": "ui | backend-only | docs-only", + "classificationJustification": "required for backend-only / docs-only", + "review": { "result": "pass|pass-with-notes", "reviewer": "...", + "reviewedHeadSha": "...", "date": "YYYY-MM-DD", "url": "..." }, + "checks": [{ "name": "...", "status": "green", "headSha": "...", "url": "..." }], + "evidence": [ + { "kind": "behavior-run | test-run | suite-run | playable-flow", + "name": "...", "headSha": "...", "result": "pass", "url": "..." } + ], + "suites": { + "security": { "ran": true, "result": "pass", "headSha": "...", "url": "..." }, + "evaluation": { "ran": true, "result": "pass", "headSha": "...", + "negativeControl": "fail-as-expected", "url": "..." } + }, + "notes": "optional" +} +``` +```` + +## What the validator enforces (each pinned by a test) + +| Code | Meaning | +| --- | --- | +| `invalid_manifest` | structure: version, SHA shapes, evidence item shape | +| `pr_mismatch` | manifest points at a different PR than the one validated | +| `arena_hold` | branch is `arena/candidate-*` — excluded from auto-merge (rule 8) | +| `stale_head_sha` | `testedHeadSha` ≠ live PR head (rule 5: results don't carry over) | +| `mismatched_sha` | review/check/evidence/suite recorded against a different commit | +| `missing_review` / `review_not_passing` / `invalid_review_fields` | rule 2–3 review record | +| `missing_checks` | no named green CI check recorded (rule 4) | +| `missing_evidence` / `evidence_result_not_passing` | failing/absent behavior evidence | +| `no_playable_flow` / `invalid_playable_flow` | UI PRs need scenario + assertions + environment | +| `native_claim_unsupported` | on-device/simulator/TestFlight claims need playable-flow evidence | +| `classification_mismatch` | claimed classification contradicts the live diff paths | +| `classification_justification_required` | backend-only/docs-only need a justification | +| `suite_not_recorded` / `suite_not_passing` / `suite_negative_control_missing` | security + evaluation runs on the tested HEAD | + +Suite applicability is derived from the **live diff**: any change under +`apps/`, `backend/`, `packages/`, `security/`, or `evaluation/` requires both +suites; docs-only changes require neither. + +## CLI + +```bash +bun verification/src/cli.ts validate-pr --pr= # CI-safe advisory +bun verification/src/cli.ts validate-pr --pr= --require # strict (merge owner) +bun verification/src/cli.ts check --file=f.json --pr= --head= --branch= --paths=a,b +bun verification/src/cli.ts sweep --pr= --owner= [--dry-run] [--smoke] [--post-receipt] +``` + +The **sweep** is the serialized merge owner's gate, in order: open PR on +master, not draft → not an arena candidate → live checks green on the exact +head SHA → latest manifest parses → validator merge → `gh pr merge --squash` +→ receipt. `--smoke` re-runs the full local verification table on the merge +commit from a temp worktree. Exit codes: 0 merge/would-merge, 1 refuse/hold, +2 environment error. + +Factual limits: checks/comments are read from a single page (~100); check-run +pagination would be needed past that. The sweep trusts `gh` auth entirely. + +## Tests + +```bash +cd verification && bun test ./test # 2 positive controls + 9 negative controls + extraction tests +``` diff --git a/verification/fixtures/nc1-stale-sha.json b/verification/fixtures/nc1-stale-sha.json new file mode 100644 index 0000000..6cb6309 --- /dev/null +++ b/verification/fixtures/nc1-stale-sha.json @@ -0,0 +1,48 @@ +{ + "manifestVersion": 1, + "pr": 99, + "prUrl": "https://github.com/OCPdev25/obv-hackaton/pull/99", + "testedHeadSha": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "classification": "backend-only", + "classificationJustification": "touches backend/convex and packages/domain only — no UI surface", + "review": { + "result": "pass", + "reviewer": "sibling-qa-worker (independent of the PR author)", + "reviewedHeadSha": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "date": "2026-09-17", + "url": "https://github.com/OCPdev25/obv-hackaton/pull/99#review" + }, + "checks": [ + { + "name": "CI / Typecheck, test, build", + "status": "green", + "headSha": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "url": "https://github.com/OCPdev25/obv-hackaton/actions/runs/999001" + } + ], + "evidence": [ + { + "kind": "behavior-run", + "name": "convex entries adapter round-trip behavior against synthetic family data", + "headSha": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "result": "pass", + "url": "https://github.com/OCPdev25/obv-hackaton/actions/runs/999002" + } + ], + "suites": { + "security": { + "ran": true, + "result": "pass", + "headSha": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "url": "https://github.com/OCPdev25/obv-hackaton/actions/runs/999003" + }, + "evaluation": { + "ran": true, + "result": "pass", + "headSha": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "negativeControl": "fail-as-expected", + "url": "https://github.com/OCPdev25/obv-hackaton/actions/runs/999004" + } + }, + "notes": "fixture: NEGATIVE CONTROL nc1 — testedHeadSha is an older commit; internal SHAs are internally consistent, so the ONLY refusal must be stale_head_sha" +} diff --git a/verification/fixtures/nc1b-mismatched-sha.json b/verification/fixtures/nc1b-mismatched-sha.json new file mode 100644 index 0000000..25cdf0c --- /dev/null +++ b/verification/fixtures/nc1b-mismatched-sha.json @@ -0,0 +1,48 @@ +{ + "manifestVersion": 1, + "pr": 99, + "prUrl": "https://github.com/OCPdev25/obv-hackaton/pull/99", + "testedHeadSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "classification": "backend-only", + "classificationJustification": "touches backend/convex and packages/domain only — no UI surface", + "review": { + "result": "pass", + "reviewer": "sibling-qa-worker (independent of the PR author)", + "reviewedHeadSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "date": "2026-09-17", + "url": "https://github.com/OCPdev25/obv-hackaton/pull/99#review" + }, + "checks": [ + { + "name": "CI / Typecheck, test, build", + "status": "green", + "headSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "url": "https://github.com/OCPdev25/obv-hackaton/actions/runs/999001" + } + ], + "evidence": [ + { + "kind": "behavior-run", + "name": "convex entries adapter round-trip behavior — recorded against an EARLIER commit than testedHeadSha", + "headSha": "cccccccccccccccccccccccccccccccccccccccc", + "result": "pass", + "url": "https://github.com/OCPdev25/obv-hackaton/actions/runs/999002" + } + ], + "suites": { + "security": { + "ran": true, + "result": "pass", + "headSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "url": "https://github.com/OCPdev25/obv-hackaton/actions/runs/999003" + }, + "evaluation": { + "ran": true, + "result": "pass", + "headSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "negativeControl": "fail-as-expected", + "url": "https://github.com/OCPdev25/obv-hackaton/actions/runs/999004" + } + }, + "notes": "fixture: NEGATIVE CONTROL nc1b — evidence recorded against a different commit than testedHeadSha; ONLY refusal must be mismatched_sha" +} diff --git a/verification/fixtures/nc2-missing-evidence.json b/verification/fixtures/nc2-missing-evidence.json new file mode 100644 index 0000000..5ddb84d --- /dev/null +++ b/verification/fixtures/nc2-missing-evidence.json @@ -0,0 +1,40 @@ +{ + "manifestVersion": 1, + "pr": 99, + "prUrl": "https://github.com/OCPdev25/obv-hackaton/pull/99", + "testedHeadSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "classification": "backend-only", + "classificationJustification": "touches backend/convex and packages/domain only — no UI surface", + "review": { + "result": "pass", + "reviewer": "sibling-qa-worker (independent of the PR author)", + "reviewedHeadSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "date": "2026-09-17", + "url": "https://github.com/OCPdev25/obv-hackaton/pull/99#review" + }, + "checks": [ + { + "name": "CI / Typecheck, test, build", + "status": "green", + "headSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "url": "https://github.com/OCPdev25/obv-hackaton/actions/runs/999001" + } + ], + "evidence": [], + "suites": { + "security": { + "ran": true, + "result": "pass", + "headSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "url": "https://github.com/OCPdev25/obv-hackaton/actions/runs/999003" + }, + "evaluation": { + "ran": true, + "result": "pass", + "headSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "negativeControl": "fail-as-expected", + "url": "https://github.com/OCPdev25/obv-hackaton/actions/runs/999004" + } + }, + "notes": "fixture: NEGATIVE CONTROL nc2 — no evidence items; refusal must be missing_evidence (no review or SHA noise)" +} diff --git a/verification/fixtures/nc3-invalid-playable-flow.json b/verification/fixtures/nc3-invalid-playable-flow.json new file mode 100644 index 0000000..7bafcc7 --- /dev/null +++ b/verification/fixtures/nc3-invalid-playable-flow.json @@ -0,0 +1,47 @@ +{ + "manifestVersion": 1, + "pr": 98, + "prUrl": "https://github.com/OCPdev25/obv-hackaton/pull/98", + "testedHeadSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "classification": "ui", + "review": { + "result": "pass", + "reviewer": "sibling-qa-worker (independent of the PR author)", + "reviewedHeadSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "date": "2026-09-17", + "url": "https://github.com/OCPdev25/obv-hackaton/pull/98#review" + }, + "checks": [ + { + "name": "CI / Typecheck, test, build", + "status": "green", + "headSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "url": "https://github.com/OCPdev25/obv-hackaton/actions/runs/998001" + } + ], + "evidence": [ + { + "kind": "playable-flow", + "name": "capture flow walkthrough", + "headSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "result": "pass", + "url": "https://github.com/OCPdev25/obv-hackaton/pull/98#walkthrough" + } + ], + "suites": { + "security": { + "ran": true, + "result": "pass", + "headSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "url": "https://github.com/OCPdev25/obv-hackaton/actions/runs/998003" + }, + "evaluation": { + "ran": true, + "result": "pass", + "headSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "negativeControl": "fail-as-expected", + "url": "https://github.com/OCPdev25/obv-hackaton/actions/runs/998004" + } + }, + "notes": "fixture: NEGATIVE CONTROL nc3 — playable-flow item without scenario/assertions/environment; ONLY refusal must be invalid_playable_flow" +} diff --git a/verification/fixtures/nc4-native-claim.json b/verification/fixtures/nc4-native-claim.json new file mode 100644 index 0000000..247f745 --- /dev/null +++ b/verification/fixtures/nc4-native-claim.json @@ -0,0 +1,48 @@ +{ + "manifestVersion": 1, + "pr": 99, + "prUrl": "https://github.com/OCPdev25/obv-hackaton/pull/99", + "testedHeadSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "classification": "backend-only", + "classificationJustification": "verified on-device with the native build on TestFlight — no simulator needed", + "review": { + "result": "pass", + "reviewer": "sibling-qa-worker (independent of the PR author)", + "reviewedHeadSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "date": "2026-09-17", + "url": "https://github.com/OCPdev25/obv-hackaton/pull/99#review" + }, + "checks": [ + { + "name": "CI / Typecheck, test, build", + "status": "green", + "headSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "url": "https://github.com/OCPdev25/obv-hackaton/actions/runs/999001" + } + ], + "evidence": [ + { + "kind": "behavior-run", + "name": "convex entries adapter round-trip behavior against synthetic family data", + "headSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "result": "pass", + "url": "https://github.com/OCPdev25/obv-hackaton/actions/runs/999002" + } + ], + "suites": { + "security": { + "ran": true, + "result": "pass", + "headSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "url": "https://github.com/OCPdev25/obv-hackaton/actions/runs/999003" + }, + "evaluation": { + "ran": true, + "result": "pass", + "headSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "negativeControl": "fail-as-expected", + "url": "https://github.com/OCPdev25/obv-hackaton/actions/runs/999004" + } + }, + "notes": "fixture: NEGATIVE CONTROL nc4 — claims native/device verification without playable-flow evidence; ONLY refusal must be native_claim_unsupported" +} diff --git a/verification/fixtures/nc5-classification-mismatch.json b/verification/fixtures/nc5-classification-mismatch.json new file mode 100644 index 0000000..796ac53 --- /dev/null +++ b/verification/fixtures/nc5-classification-mismatch.json @@ -0,0 +1,48 @@ +{ + "manifestVersion": 1, + "pr": 99, + "prUrl": "https://github.com/OCPdev25/obv-hackaton/pull/99", + "testedHeadSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "classification": "backend-only", + "classificationJustification": "touches backend/convex and packages/domain only — no UI surface", + "review": { + "result": "pass", + "reviewer": "sibling-qa-worker (independent of the PR author)", + "reviewedHeadSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "date": "2026-09-17", + "url": "https://github.com/OCPdev25/obv-hackaton/pull/99#review" + }, + "checks": [ + { + "name": "CI / Typecheck, test, build", + "status": "green", + "headSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "url": "https://github.com/OCPdev25/obv-hackaton/actions/runs/999001" + } + ], + "evidence": [ + { + "kind": "behavior-run", + "name": "convex entries adapter round-trip behavior against synthetic family data", + "headSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "result": "pass", + "url": "https://github.com/OCPdev25/obv-hackaton/actions/runs/999002" + } + ], + "suites": { + "security": { + "ran": true, + "result": "pass", + "headSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "url": "https://github.com/OCPdev25/obv-hackaton/actions/runs/999003" + }, + "evaluation": { + "ran": true, + "result": "pass", + "headSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "negativeControl": "fail-as-expected", + "url": "https://github.com/OCPdev25/obv-hackaton/actions/runs/999004" + } + }, + "notes": "fixture: NEGATIVE CONTROL nc5 — claims backend-only but the live diff (test context) touches apps/mobile; ONLY refusal must be classification_mismatch" +} diff --git a/verification/fixtures/nc5b-docs-mismatch.json b/verification/fixtures/nc5b-docs-mismatch.json new file mode 100644 index 0000000..92b1005 --- /dev/null +++ b/verification/fixtures/nc5b-docs-mismatch.json @@ -0,0 +1,33 @@ +{ + "manifestVersion": 1, + "pr": 99, + "prUrl": "https://github.com/OCPdev25/obv-hackaton/pull/99", + "testedHeadSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "classification": "docs-only", + "classificationJustification": "documentation and comment updates only", + "review": { + "result": "pass", + "reviewer": "sibling-qa-worker (independent of the PR author)", + "reviewedHeadSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "date": "2026-09-17", + "url": "https://github.com/OCPdev25/obv-hackaton/pull/99#review" + }, + "checks": [ + { + "name": "CI / Typecheck, test, build", + "status": "green", + "headSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "url": "https://github.com/OCPdev25/obv-hackaton/actions/runs/999001" + } + ], + "evidence": [ + { + "kind": "test-run", + "name": "docs link check (no code changed — minimal behavior evidence)", + "headSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "result": "pass", + "url": "https://github.com/OCPdev25/obv-hackaton/actions/runs/999002" + } + ], + "notes": "fixture: NEGATIVE CONTROL nc5b — claims docs-only but the live diff (test context) touches packages/domain source; ONLY refusal must be classification_mismatch" +} diff --git a/verification/fixtures/nc6-no-review.json b/verification/fixtures/nc6-no-review.json new file mode 100644 index 0000000..8a157d8 --- /dev/null +++ b/verification/fixtures/nc6-no-review.json @@ -0,0 +1,41 @@ +{ + "manifestVersion": 1, + "pr": 99, + "prUrl": "https://github.com/OCPdev25/obv-hackaton/pull/99", + "testedHeadSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "classification": "backend-only", + "classificationJustification": "touches backend/convex and packages/domain only — no UI surface", + "checks": [ + { + "name": "CI / Typecheck, test, build", + "status": "green", + "headSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "url": "https://github.com/OCPdev25/obv-hackaton/actions/runs/999001" + } + ], + "evidence": [ + { + "kind": "behavior-run", + "name": "convex entries adapter round-trip behavior against synthetic family data", + "headSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "result": "pass", + "url": "https://github.com/OCPdev25/obv-hackaton/actions/runs/999002" + } + ], + "suites": { + "security": { + "ran": true, + "result": "pass", + "headSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "url": "https://github.com/OCPdev25/obv-hackaton/actions/runs/999003" + }, + "evaluation": { + "ran": true, + "result": "pass", + "headSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "negativeControl": "fail-as-expected", + "url": "https://github.com/OCPdev25/obv-hackaton/actions/runs/999004" + } + }, + "notes": "fixture: NEGATIVE CONTROL nc6 — no review object; ONLY refusal must be missing_review" +} diff --git a/verification/fixtures/nc7-suites-missing.json b/verification/fixtures/nc7-suites-missing.json new file mode 100644 index 0000000..74ae34e --- /dev/null +++ b/verification/fixtures/nc7-suites-missing.json @@ -0,0 +1,33 @@ +{ + "manifestVersion": 1, + "pr": 99, + "prUrl": "https://github.com/OCPdev25/obv-hackaton/pull/99", + "testedHeadSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "classification": "backend-only", + "classificationJustification": "touches backend/convex and packages/domain only — no UI surface", + "review": { + "result": "pass", + "reviewer": "sibling-qa-worker (independent of the PR author)", + "reviewedHeadSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "date": "2026-09-17", + "url": "https://github.com/OCPdev25/obv-hackaton/pull/99#review" + }, + "checks": [ + { + "name": "CI / Typecheck, test, build", + "status": "green", + "headSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "url": "https://github.com/OCPdev25/obv-hackaton/actions/runs/999001" + } + ], + "evidence": [ + { + "kind": "behavior-run", + "name": "convex entries adapter round-trip behavior against synthetic family data", + "headSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "result": "pass", + "url": "https://github.com/OCPdev25/obv-hackaton/actions/runs/999002" + } + ], + "notes": "fixture: NEGATIVE CONTROL nc7 — diff requires security+evaluation suites but none recorded; refusal must include suite_not_recorded" +} diff --git a/verification/fixtures/nc8-eval-negative-control-missing.json b/verification/fixtures/nc8-eval-negative-control-missing.json new file mode 100644 index 0000000..04421e8 --- /dev/null +++ b/verification/fixtures/nc8-eval-negative-control-missing.json @@ -0,0 +1,47 @@ +{ + "manifestVersion": 1, + "pr": 99, + "prUrl": "https://github.com/OCPdev25/obv-hackaton/pull/99", + "testedHeadSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "classification": "backend-only", + "classificationJustification": "touches backend/convex and packages/domain only — no UI surface", + "review": { + "result": "pass", + "reviewer": "sibling-qa-worker (independent of the PR author)", + "reviewedHeadSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "date": "2026-09-17", + "url": "https://github.com/OCPdev25/obv-hackaton/pull/99#review" + }, + "checks": [ + { + "name": "CI / Typecheck, test, build", + "status": "green", + "headSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "url": "https://github.com/OCPdev25/obv-hackaton/actions/runs/999001" + } + ], + "evidence": [ + { + "kind": "behavior-run", + "name": "convex entries adapter round-trip behavior against synthetic family data", + "headSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "result": "pass", + "url": "https://github.com/OCPdev25/obv-hackaton/actions/runs/999002" + } + ], + "suites": { + "security": { + "ran": true, + "result": "pass", + "headSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "url": "https://github.com/OCPdev25/obv-hackaton/actions/runs/999003" + }, + "evaluation": { + "ran": true, + "result": "pass", + "headSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "url": "https://github.com/OCPdev25/obv-hackaton/actions/runs/999004" + } + }, + "notes": "fixture: NEGATIVE CONTROL nc8 — evaluation suite run recorded but its broken-adapter negative control is not; ONLY refusal must be suite_negative_control_missing" +} diff --git a/verification/fixtures/positive-backend.json b/verification/fixtures/positive-backend.json new file mode 100644 index 0000000..a22ae5a --- /dev/null +++ b/verification/fixtures/positive-backend.json @@ -0,0 +1,48 @@ +{ + "manifestVersion": 1, + "pr": 99, + "prUrl": "https://github.com/OCPdev25/obv-hackaton/pull/99", + "testedHeadSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "classification": "backend-only", + "classificationJustification": "touches backend/convex and packages/domain only — no UI surface (no apps/ or packages/ui/ paths in the diff)", + "review": { + "result": "pass", + "reviewer": "sibling-qa-worker (independent of the PR author)", + "reviewedHeadSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "date": "2026-09-17", + "url": "https://github.com/OCPdev25/obv-hackaton/pull/99#review" + }, + "checks": [ + { + "name": "CI / Typecheck, test, build", + "status": "green", + "headSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "url": "https://github.com/OCPdev25/obv-hackaton/actions/runs/999001" + } + ], + "evidence": [ + { + "kind": "behavior-run", + "name": "convex entries adapter round-trip behavior against synthetic family data", + "headSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "result": "pass", + "url": "https://github.com/OCPdev25/obv-hackaton/actions/runs/999002" + } + ], + "suites": { + "security": { + "ran": true, + "result": "pass", + "headSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "url": "https://github.com/OCPdev25/obv-hackaton/actions/runs/999003" + }, + "evaluation": { + "ran": true, + "result": "pass", + "headSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "negativeControl": "fail-as-expected", + "url": "https://github.com/OCPdev25/obv-hackaton/actions/runs/999004" + } + }, + "notes": "fixture: positive control (backend-only) — validator must say merge" +} diff --git a/verification/fixtures/positive-ui.json b/verification/fixtures/positive-ui.json new file mode 100644 index 0000000..f316270 --- /dev/null +++ b/verification/fixtures/positive-ui.json @@ -0,0 +1,60 @@ +{ + "manifestVersion": 1, + "pr": 98, + "prUrl": "https://github.com/OCPdev25/obv-hackaton/pull/98", + "testedHeadSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "classification": "ui", + "review": { + "result": "pass-with-notes", + "reviewer": "sibling-qa-worker (independent of the PR author)", + "reviewedHeadSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "date": "2026-09-17", + "url": "https://github.com/OCPdev25/obv-hackaton/pull/98#review" + }, + "checks": [ + { + "name": "CI / Typecheck, test, build", + "status": "green", + "headSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "url": "https://github.com/OCPdev25/obv-hackaton/actions/runs/998001" + }, + { + "name": "Verification / Security + evaluation suites", + "status": "green", + "headSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "url": "https://github.com/OCPdev25/obv-hackaton/actions/runs/998002" + } + ], + "evidence": [ + { + "kind": "playable-flow", + "name": "parent records a 20-second voice note; typed entry appears on the child timeline", + "headSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "result": "pass", + "scenario": "open capture screen → dictate a synthetic nap note → submit → open the child's timeline", + "assertions": [ + "raw transcript retained verbatim on the entry", + "typed event attributed to the recording caregiver appears on the timeline", + "publication state stays review-only until a parent approves" + ], + "environment": "Expo Go on iOS 26 simulator; synthetic family data only (no real children)", + "url": "https://github.com/OCPdev25/obv-hackaton/pull/98#playable-flow-recording" + } + ], + "suites": { + "security": { + "ran": true, + "result": "pass", + "headSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "url": "https://github.com/OCPdev25/obv-hackaton/actions/runs/998003" + }, + "evaluation": { + "ran": true, + "result": "pass", + "headSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "negativeControl": "fail-as-expected", + "url": "https://github.com/OCPdev25/obv-hackaton/actions/runs/998004" + } + }, + "notes": "fixture: positive control (ui) — validator must say merge" +} diff --git a/verification/src/cli.ts b/verification/src/cli.ts new file mode 100644 index 0000000..2c807a4 --- /dev/null +++ b/verification/src/cli.ts @@ -0,0 +1,391 @@ +/** + * Verification gate CLI (runs under bun; zero dependencies). + * + * Commands: + * check — offline validation of a manifest file against a synthetic + * context (tests, fixtures, local what-ifs) + * validate-pr — live validation of the PR's recorded manifest; strict when a + * manifest exists, advisory when absent (CI mode), refusing + * when absent with --require (merge-owner mode) + * sweep — the serialized merge owner's gate: preflight refusals, live + * green checks on the exact head SHA, manifest validation, + * then merge (or dry-run) + receipt + * + * Exit codes: 0 = merge/would-merge/not-applicable · 1 = refuse/hold · + * 2 = environment error (gh/network). + */ +import { extractManifests, latestManifest, type ExtractedManifest } from './manifest.ts' +import { validateManifest, requiredSuites } from './validate.ts' +import { + liveChecks, masterSha, mergeSquash, postPrComment, prBody, prChangedPaths, prComments, prView, sleep, +} from './gh.ts' +import { short, type VerificationContext, type Verdict } from './types.ts' +import { readFileSync } from 'node:fs' +import { spawnSync } from 'node:child_process' + +// --- arg plumbing ----------------------------------------------------------- + +function args(): Map { + const map = new Map() + const argv = process.argv.slice(2) + for (let i = 0; i < argv.length; i++) { + const a = argv[i] + if (a.startsWith('--')) { + const eq = a.indexOf('=') + if (eq > 2) { + map.set(a.slice(2, eq), a.slice(eq + 1)) + continue + } + const key = a.slice(2) + const next = argv[i + 1] + if (next !== undefined && !next.startsWith('--')) { + map.set(key, next) + i++ + } else { + map.set(key, '') + } + } + } + return map +} + +function need(map: Map, key: string): string { + const v = map.get(key) + if (v === undefined || v === '') { + console.error(`missing required --${key}`) + process.exit(2) + } + return v +} + +function printVerdict(v: Verdict): void { + for (const r of v.reasons) console.log(` ✗ ${r.code}: ${r.detail}`) + if (v.reasons.length === 0) console.log(' ✓ all applicable rules satisfied') + console.log(`VERDICT ${JSON.stringify({ decision: v.decision, reasons: v.reasons.map((r) => r.code) })}`) +} + +// --- check (offline) --------------------------------------------------------- + +function cmdCheck(): number { + const map = args() + const file = need(map, 'file') + const pr = Number(need(map, 'pr')) + const head = need(map, 'head') + const branch = need(map, 'branch') + const paths = (map.get('paths') ?? '').split(',').map((s) => s.trim()).filter(Boolean) + + let raw: unknown + try { + raw = JSON.parse(readFileSync(file, 'utf8')) + } catch (err) { + console.error(`could not read/parse ${file}: ${String(err)}`) + return 2 + } + const ctx: VerificationContext = { liveHeadSha: head, headBranch: branch, prNumber: pr, changedPaths: paths } + const verdict = validateManifest(raw, ctx) + console.log(`offline check: ${file} (pr=${pr} head=${short(head)} branch=${branch} paths=[${paths.join(', ')}])`) + console.log(`required suites from diff: ${requiredSuites(paths).join(', ') || 'none'}`) + printVerdict(verdict) + return verdict.decision === 'merge' ? 0 : 1 +} + +// --- manifest collection (live) ---------------------------------------------- + +function collectManifestBlocks(n: number): { ok: true; latest?: ExtractedManifest } | { ok: false; err: string } { + const bodyRes = prBody(n) + if (!bodyRes.ok) return { ok: false, err: bodyRes.err } + const commentsRes = prComments(n) + if (!commentsRes.ok) return { ok: false, err: commentsRes.err } + + const blocks = [ + ...extractManifests(bodyRes.body, 'PR body'), + ...commentsRes.comments.flatMap((c) => extractManifests(c.body, `comment ${c.id} (${c.createdAt})`)), + ] + return { ok: true, latest: latestManifest(blocks) } +} + +// --- validate-pr (live) -------------------------------------------------------- + +function cmdValidatePr(): number { + const map = args() + const n = Number(need(map, 'pr')) + const requireManifest = map.has('require') + + const view = prView(n) + if (!view.ok) { + console.error(`gh pr view failed: ${view.err}`) + return 2 + } + const pr = view.pr + const diff = prChangedPaths(n) + if (!diff.ok) { + console.error(`gh pr diff failed: ${diff.err}`) + return 2 + } + const ctx: VerificationContext = { + liveHeadSha: pr.headRefOid, + headBranch: pr.headRefName, + prNumber: pr.number, + changedPaths: diff.paths, + } + + console.log(`validate-pr: PR #${pr.number} "${pr.title}" head=${short(pr.headRefOid)} branch=${pr.headRefName}`) + console.log(`changed paths (${ctx.changedPaths.length}): ${ctx.changedPaths.join(', ') || '(none)'}`) + console.log(`required suites from diff: ${requiredSuites(ctx.changedPaths).join(', ') || 'none'}`) + + const collected = collectManifestBlocks(n) + if (!collected.ok) { + console.error(collected.err) + return 2 + } + if (collected.latest === undefined) { + if (requireManifest) { + console.log('✗ manifest_missing: no verification manifest recorded on this PR — merge gate refuses (verification/README.md)') + console.log('VERDICT {"decision":"refuse","reasons":["manifest_missing"]}') + return 1 + } + console.log('ℹ no verification manifest recorded yet — PR is not merge-eligible until one is; nothing to validate (CI mode)') + console.log('VERDICT {"decision":"refuse","reasons":["manifest_missing"],"advisory":true}') + return 0 + } + if (!collected.latest.ok) { + console.log(`✗ invalid_manifest: latest manifest block (${collected.latest.source}) does not parse: ${collected.latest.error}`) + console.log('VERDICT {"decision":"refuse","reasons":["invalid_manifest"]}') + return 1 + } + + const verdict = validateManifest(collected.latest.raw, ctx) + console.log(`validating latest manifest (${collected.latest.source}) against live head ${short(pr.headRefOid)}`) + printVerdict(verdict) + return verdict.decision === 'merge' ? 0 : 1 +} + +// --- sweep (merge owner) ------------------------------------------------------- + +function cmdSweep(): number { + const map = args() + const n = Number(need(map, 'pr')) + const owner = need(map, 'owner') + const dryRun = map.has('dry-run') + const smoke = map.has('smoke') + const postReceipt = map.has('post-receipt') + + console.log(`merge sweep (owner: ${owner})${dryRun ? ' — DRY RUN' : ''}`) + + const view = prView(n) + if (!view.ok) { + console.error(`gh pr view failed: ${view.err}`) + return 2 + } + const pr = view.pr + console.log(`PR #${pr.number} "${pr.title}" state=${pr.state} draft=${pr.isDraft} base=${pr.baseRefName} head=${short(pr.headRefOid)} branch=${pr.headRefName} url=${pr.url}`) + + if (pr.state === 'MERGED') { + console.log('✗ already_merged: this PR is already merged; nothing to do') + console.log('VERDICT {"decision":"refuse","reasons":["already_merged"]}') + return 1 + } + if (pr.state !== 'OPEN') { + console.log('✗ not_open: PR is not open — refusing') + console.log('VERDICT {"decision":"refuse","reasons":["not_open"]}') + return 1 + } + if (pr.isDraft) { + console.log('✗ draft: PR is a draft — refusing (mark ready and record a verification manifest first)') + console.log('VERDICT {"decision":"refuse","reasons":["draft"]}') + return 1 + } + if (pr.baseRefName !== 'master') { + console.log(`✗ wrong_base: PR targets ${pr.baseRefName}, not master — refusing (master is the only PR target)`) + console.log('VERDICT {"decision":"refuse","reasons":["wrong_base"]}') + return 1 + } + + const diff = prChangedPaths(n) + if (!diff.ok) { + console.error(`gh pr diff failed: ${diff.err}`) + return 2 + } + + const ctx: VerificationContext = { + liveHeadSha: pr.headRefOid, + headBranch: pr.headRefName, + prNumber: pr.number, + changedPaths: diff.paths, + } + console.log(`changed paths (${ctx.changedPaths.length}): ${ctx.changedPaths.join(', ') || '(none)'}`) + console.log(`required suites from diff: ${requiredSuites(ctx.changedPaths).join(', ') || 'none'}`) + + // Arena hold (contract rule 8) — decided before anything else: candidates are + // excluded from individual auto-merge until selection, whatever their evidence. + if (/^arena\/candidate-/.test(pr.headRefName)) { + console.log(`⏸ arena_hold: branch ${pr.headRefName} is an arena candidate — excluded from individual auto-merge until arena selection completes`) + console.log('VERDICT {"decision":"hold","reasons":["arena_hold"]}') + return 1 + } + + const live = liveChecks(pr.headRefOid) + if (!live.ok) { + console.error(live.err) + return 2 + } + console.log(`live checks on ${short(pr.headRefOid)}: ${live.checks.detail}`) + if (!live.checks.any) { + console.log('✗ no_live_checks: no check runs or commit statuses on the head SHA — checks-green-required cannot be verified') + console.log('VERDICT {"decision":"refuse","reasons":["no_live_checks"]}') + return 1 + } + if (live.checks.pending > 0) { + console.log(`✗ live_checks_pending: ${live.checks.pending} check(s) still running — merge refused until all are terminal`) + console.log('VERDICT {"decision":"refuse","reasons":["live_checks_pending"]}') + return 1 + } + if (live.checks.failed > 0) { + console.log(`✗ live_checks_failed: ${live.checks.failed} check(s) red on the head SHA`) + console.log('VERDICT {"decision":"refuse","reasons":["live_checks_failed"]}') + return 1 + } + + const collected = collectManifestBlocks(n) + if (!collected.ok) { + console.error(collected.err) + return 2 + } + if (collected.latest === undefined) { + console.log('✗ manifest_missing: no verification manifest recorded on this PR (marker + fenced JSON, verification/README.md) — refusing') + console.log('VERDICT {"decision":"refuse","reasons":["manifest_missing"]}') + return 1 + } + if (!collected.latest.ok) { + console.log(`✗ invalid_manifest: latest manifest block (${collected.latest.source}) does not parse: ${collected.latest.error}`) + console.log('VERDICT {"decision":"refuse","reasons":["invalid_manifest"]}') + return 1 + } + + const verdict = validateManifest(collected.latest.raw, ctx) + console.log(`manifest from ${collected.latest.source}:`) + printVerdict(verdict) + + if (verdict.decision !== 'merge') { + console.log(`→ refusing to merge PR #${n} (${verdict.decision})`) + return 1 + } + + if (dryRun) { + console.log(`→ ELIGIBLE: PR #${n} would merge now (--squash) — dry run, no merge executed`) + printReceipt(pr, collected.latest.raw as Record, '(dry run — no merge commit)') + return 0 + } + + console.log(`→ merging PR #${n} with --squash (single serialized merge owner: ${owner})`) + const merge = mergeSquash(n) + if (!merge.ok) { + console.error(`merge failed: ${merge.err}`) + return 2 + } + + const preMaster = masterSha() + let mergeSha = '(lookup pending)' + for (let i = 0; i < 10; i++) { + sleep(3000) + const now = masterSha() + if (now.ok && now.sha !== preMaster.sha) { + mergeSha = now.sha + break + } + } + console.log(`merge commit on master: ${mergeSha}`) + printReceipt(pr, collected.latest.raw as Record, mergeSha) + + if (smoke && /^[0-9a-f]{40}$/.test(mergeSha)) { + const code = runSmoke(mergeSha) + if (code !== 0) { + console.error('post-merge smoke FAILED — investigate before treating downstream tasks as unlocked') + return code + } + } + + if (postReceipt) { + const receipt = renderReceipt(pr, collected.latest.raw as Record, mergeSha, smoke ? 'ran via --smoke (see sweep log)' : 'pending — run the local verification table on the merge commit') + const posted = postPrComment(n, receipt) + if (!posted.ok) { + console.error(`receipt post failed (merge itself succeeded): ${posted.err}`) + return 2 + } + console.log('receipt posted as PR comment') + } + + return 0 +} + +function renderReceipt(pr: { url: string; number: number }, manifest: Record, mergeSha: string, smoke: string): string { + const review = manifest.review as { result?: string; reviewer?: string; date?: string; url?: string } + const checks = (manifest.checks as Array<{ name?: string }> | undefined) ?? [] + const head = String(manifest.testedHeadSha ?? '') + return [ + '### Evidence receipt (verification gate)', + '', + '```', + `PR: ${pr.url}`, + `Tested head SHA: ${head}`, + `Review result: ${review?.result ?? '?'} — ${review?.reviewer ?? '?'}, ${review?.date ?? '?'} (${review?.url ?? '?'})`, + `Checks: ${checks.map((c) => c.name).join(', ')} — green on ${head}`, + `Merge commit: ${mergeSha}`, + `Post-merge smoke: ${smoke}`, + 'Unlocked tasks: (merge owner fills)', + '```', + ].join('\n') +} + +function printReceipt(pr: { url: string }, manifest: Record, mergeSha: string): void { + console.log('----- evidence receipt (fill "Unlocked tasks"; record per contract) -----') + console.log(renderReceipt(pr, manifest, mergeSha, 'pending — run the local verification table on the merge commit')) +} + +/** Post-merge smoke: full local verification table on the merge commit (temp worktree). */ +function runSmoke(sha: string): number { + const worktree = `/tmp/verification-smoke-${Date.now()}` + console.log(`post-merge smoke on ${short(sha)} (worktree ${worktree})`) + const steps: Array<[string, string]> = [ + ['fetch', `git fetch origin master`], + ['worktree', `git worktree add --detach ${worktree} ${sha}`], + ['install', `cd ${worktree} && corepack pnpm install --frozen-lockfile`], + ['verify', `cd ${worktree} && pnpm turbo run typecheck test build`], + ['security', `cd ${worktree} && bun test ./security`], + ['evaluation', `cd ${worktree}/evaluation && bun src/run.ts && bun src/run.ts --adapter=./src/example/broken-adapter.ts --expect-failure`], + ] + for (const [label, cmd] of steps) { + console.log(` smoke/${label}…`) + const res = spawnSync('bash', ['-c', cmd], { stdio: 'inherit', env: process.env }) + if (res.status !== 0) { + console.error(` smoke/${label} exited ${res.status}`) + return res.status ?? 1 + } + } + spawnSync('bash', ['-c', `git worktree remove --force ${worktree || ''} 2>/dev/null || true`], { stdio: 'ignore' }) + console.log('post-merge smoke: PASS') + return 0 +} + + +// --- main ---------------------------------------------------------------------- + +function main(): number { + const command = process.argv[2] + switch (command) { + case 'check': + return cmdCheck() + case 'validate-pr': + return cmdValidatePr() + case 'sweep': + return cmdSweep() + default: + console.error(`usage: bun verification/src/cli.ts [flags] + check --file= --pr= --head= --branch= --paths=a,b + validate-pr --pr= [--require] (strict when a manifest exists; --require refuses when absent) + sweep --pr= --owner= [--dry-run] [--smoke] [--post-receipt]`) + return 2 + } +} + +process.exitCode = main() diff --git a/verification/src/gh.ts b/verification/src/gh.ts new file mode 100644 index 0000000..9f03866 --- /dev/null +++ b/verification/src/gh.ts @@ -0,0 +1,167 @@ +/** + * Thin read-mostly `gh` CLI wrappers for the verification CLI. + * + * Auth: uses whatever `gh` is configured with (GH_TOKEN in CI, gh auth in the + * sandbox). No credentials are read, written, or stored here. All calls are + * read-only except mergeSquash and postPrComment (both explicit merge-owner + * actions). + */ +import { spawnSync } from 'node:child_process' +import { REPO } from './types.ts' + +export interface GhResult { + ok: boolean + out: string + err: string +} + +function gh(args: string[]): GhResult { + const res = spawnSync('gh', args, { encoding: 'utf8', env: process.env, maxBuffer: 16 * 1024 * 1024 }) + if (res.error) return { ok: false, out: '', err: `gh failed to run: ${res.error.message}` } + if (res.status !== 0) return { ok: false, out: res.stdout, err: (res.stderr || res.stdout || `gh ${args.join(' ')} exited ${res.status}`).trim() } + return { ok: true, out: res.stdout, err: '' } +} + +export interface PrView { + number: number + state: 'OPEN' | 'CLOSED' | 'MERGED' + isDraft: boolean + baseRefName: string + headRefName: string + headRefOid: string + url: string + title: string +} + +export function prView(n: number): { ok: true; pr: PrView } | { ok: false; err: string } { + const res = gh([ + 'pr', 'view', String(n), '--repo', REPO, + '--json', 'number,state,isDraft,baseRefName,headRefName,headRefOid,url,title', + ]) + if (!res.ok) return { ok: false, err: res.err } + try { + return { ok: true, pr: JSON.parse(res.out) as PrView } + } catch (err) { + return { ok: false, err: `could not parse gh pr view output: ${String(err)}` } + } +} + +export function prBody(n: number): { ok: true; body: string } | { ok: false; err: string } { + const res = gh(['pr', 'view', String(n), '--repo', REPO, '--json', 'body', '--jq', '.body']) + return res.ok ? { ok: true, body: res.out } : { ok: false, err: res.err } +} + +export interface PrComment { + id: number + createdAt: string + body: string +} + +/** Issue comments on the PR, chronological (GitHub returns ascending). */ +export function prComments(n: number): { ok: true; comments: PrComment[] } | { ok: false; err: string } { + const res = gh(['api', `repos/${REPO}/issues/${n}/comments?per_page=100`]) + if (!res.ok) return { ok: false, err: res.err } + try { + const parsed = JSON.parse(res.out) as Array<{ id: number; created_at: string; body: string }> + const comments = parsed + .map((c) => ({ id: c.id, createdAt: c.created_at, body: c.body })) + .sort((a, b) => (a.createdAt === b.createdAt ? a.id - b.id : a.createdAt < b.createdAt ? -1 : 1)) + return { ok: true, comments } + } catch (err) { + return { ok: false, err: `could not parse PR comments: ${String(err)}` } + } +} + +/** Changed file paths on the PR (names only). */ +export function prChangedPaths(n: number): { ok: true; paths: string[] } | { ok: false; err: string } { + const res = gh(['pr', 'diff', String(n), '--repo', REPO, '--name-only']) + if (!res.ok) return { ok: false, err: res.err } + return { ok: true, paths: res.out.split('\n').map((s) => s.trim()).filter(Boolean) } +} + +export interface LiveChecks { + /** any check run or commit status present at all */ + any: boolean + pending: number + failed: number + allGreen: boolean + names: string[] + detail: string +} + +/** + * Live check state for an exact SHA — check runs (Actions) plus legacy commit + * statuses. Single page per source (>100 checks per commit would need + * pagination; documented as a factual limit in verification/README.md). + */ +export function liveChecks(sha: string): { ok: true; checks: LiveChecks } | { ok: false; err: string } { + const names: string[] = [] + let pending = 0 + let failed = 0 + let any = false + + const cr = gh(['api', `repos/${REPO}/commits/${sha}/check-runs`]) + if (!cr.ok) return { ok: false, err: `check-runs lookup failed: ${cr.err}` } + try { + const parsed = JSON.parse(cr.out) as { total_count: number; check_runs: Array<{ name: string; status: string; conclusion: string | null }> } + for (const run of parsed.check_runs ?? []) { + any = true + if (run.status !== 'completed') { + pending += 1 + names.push(`${run.name} (${run.status})`) + } else if (run.conclusion !== 'success' && run.conclusion !== 'neutral' && run.conclusion !== 'skipped') { + failed += 1 + names.push(`${run.name} (${run.conclusion})`) + } else { + names.push(`${run.name} (${run.conclusion})`) + } + } + } catch (err) { + return { ok: false, err: `could not parse check-runs: ${String(err)}` } + } + + const st = gh(['api', `repos/${REPO}/commits/${sha}/status`]) + if (!st.ok) return { ok: false, err: `commit status lookup failed: ${st.err}` } + try { + const parsed = JSON.parse(st.out) as { state: string; total_count: number; statuses: Array<{ context: string; state: string }> } + if (parsed.total_count > 0) { + any = true + if (parsed.state === 'pending') pending += 1 + else if (parsed.state !== 'success') failed += 1 + for (const s of parsed.statuses) names.push(`${s.context} (${s.state})`) + } + } catch (err) { + return { ok: false, err: `could not parse commit status: ${String(err)}` } + } + + return { + ok: true, + checks: { + any, + pending, + failed, + allGreen: any && pending === 0 && failed === 0, + names, + detail: names.length === 0 ? 'no checks on this SHA' : names.join(', '), + }, + } +} + +export function mergeSquash(n: number): GhResult { + return gh(['pr', 'merge', String(n), '--repo', REPO, '--squash']) +} + +export function masterSha(): { ok: true; sha: string } | { ok: false; err: string } { + const res = gh(['api', `repos/${REPO}/commits/master`, '--jq', '.sha']) + if (!res.ok) return { ok: false, err: res.err } + const sha = res.out.trim() + return /^[0-9a-f]{40}$/.test(sha) ? { ok: true, sha } : { ok: false, err: `unexpected master sha: ${sha}` } +} + +export function postPrComment(n: number, body: string): GhResult { + return gh(['pr', 'comment', String(n), '--repo', REPO, '--body', body]) +} + +export function sleep(ms: number): void { + spawnSync('sleep', [String(ms / 1000)]) +} diff --git a/verification/src/manifest.ts b/verification/src/manifest.ts new file mode 100644 index 0000000..3b54eeb --- /dev/null +++ b/verification/src/manifest.ts @@ -0,0 +1,48 @@ +/** + * Extract verification manifests from PR surfaces (body + comments). + * + * Recording format (append-only; the latest block across body and comments, + * oldest → newest, wins): + * + * + * ```json + * { ...manifest... } + * ``` + * + * Manifest authoring/recording tooling is owned by the workers recording + * evidence; this module only parses the convention for the validator. + */ + +export const MANIFEST_MARKER = 'verification-manifest:v1' + +const BLOCK_RE = /\s*```json[^\S\n]*\n?([\s\S]*?)```/g + +export type ExtractedManifest = + | { ok: true; raw: unknown; source: string; index: number } + | { ok: false; error: string; source: string; index: number } + +/** Pull every manifest block out of one text surface, in order of appearance. */ +export function extractManifests(text: string, source: string): Array { + const out: Array = [] + for (const match of text.matchAll(BLOCK_RE)) { + const json = match[1] + let parsed: unknown + try { + parsed = JSON.parse(json) + } catch (err) { + out.push({ ok: false, error: `JSON parse failed: ${err instanceof Error ? err.message : String(err)}`, source, index: out.length }) + continue + } + out.push({ ok: true, raw: parsed, source, index: out.length }) + } + return out +} + +/** + * Latest manifest across surfaces, in recording order (body first, then + * comments oldest → newest). A later unparseable block supersedes earlier + * valid ones — an invalid latest manifest must fail loudly, not fall back. + */ +export function latestManifest(blocks: Array): ExtractedManifest | undefined { + return blocks.length === 0 ? undefined : blocks[blocks.length - 1] +} diff --git a/verification/src/types.ts b/verification/src/types.ts new file mode 100644 index 0000000..ecd068e --- /dev/null +++ b/verification/src/types.ts @@ -0,0 +1,125 @@ +/** + * Verification manifest v1 — types for the executable verification gate. + * + * Policy source: `.obvious/obvious.md` → "Review → repair → merge workflow" + * (merged via PR #10, squash 241ffe6). A PR's workers record one manifest as a + * PR comment (marker + fenced JSON, see verification/README.md); the validator + * (verification/src/validate.ts) decides merge eligibility from it against the + * live PR state. + * + * Design constraints: + * - Zero dependencies (runs under `bun` directly, standalone like `security/` + * and `evaluation/` — not a pnpm workspace member). + * - Reason codes are stable and documented in verification/README.md; the test + * suite pins the exact reason set per control, so a validator that refuses + * for the wrong reason also fails (same discipline as security/access). + */ + +export type Classification = 'ui' | 'backend-only' | 'docs-only' +export type EvidenceKind = 'playable-flow' | 'behavior-run' | 'test-run' | 'suite-run' +export type SuiteName = 'security' | 'evaluation' + +export interface EvidenceItem { + kind: EvidenceKind + name: string + /** 40-hex — evidence only counts for the exact tested HEAD (contract rule 3) */ + headSha: string + result: 'pass' | 'fail' + url: string + /** playable-flow only: what a person did in the running app */ + scenario?: string + /** playable-flow only: assertions observed on screen/state */ + assertions?: string[] + /** playable-flow only: where it ran (device/simulator/browser + data note) */ + environment?: string +} + +export interface SuiteRun { + ran: boolean + result: 'pass' | 'fail' + headSha: string + url: string + /** evaluation only: the broken-adapter negative control ran and failed as expected */ + negativeControl?: 'fail-as-expected' +} + +export interface VerificationManifest { + manifestVersion: 1 + pr: number + prUrl: string + /** 40-hex — exact HEAD the review and every evidence item ran against */ + testedHeadSha: string + classification: Classification + /** required for backend-only and docs-only */ + classificationJustification?: string + review: { + result: 'pass' | 'pass-with-notes' + reviewer: string + reviewedHeadSha: string + date: string + url: string + } + checks: Array<{ name: string; status: 'green'; headSha: string; url: string }> + evidence: EvidenceItem[] + suites?: Partial> + notes?: string +} + +/** Stable refusal/hold codes — documented in verification/README.md, pinned by tests. */ +export type ReasonCode = + | 'invalid_manifest' + | 'arena_hold' + | 'stale_head_sha' + | 'mismatched_sha' + | 'pr_mismatch' + | 'missing_evidence' + | 'evidence_result_not_passing' + | 'invalid_playable_flow' + | 'no_playable_flow' + | 'missing_review' + | 'review_not_passing' + | 'invalid_review_fields' + | 'missing_checks' + | 'classification_justification_required' + | 'classification_mismatch' + | 'native_claim_unsupported' + | 'suite_not_recorded' + | 'suite_not_passing' + | 'suite_negative_control_missing' + +export interface Reason { + code: ReasonCode + detail: string +} + +/** + * merge — every applicable rule satisfied for the live context + * refuse — a policy rule failed; the merge owner must not merge + * hold — arena/candidate-* branch: waits for arena selection regardless of + * manifest quality (contract rule 8) + */ +export type Decision = 'merge' | 'refuse' | 'hold' + +export interface Verdict { + decision: Decision + reasons: Reason[] +} + +export interface VerificationContext { + /** live PR head SHA at validation time (gh pr view → headRefOid) */ + liveHeadSha: string + /** PR head branch name (drives the arena/candidate-* hold) */ + headBranch: string + /** live PR number */ + prNumber: number + /** paths changed by the PR (gh pr diff --name-only) — drives classification and suite applicability */ + changedPaths: string[] +} + +export const SHA_RE = /^[0-9a-f]{40}$/ + +export const REPO = 'OCPdev25/obv-hackaton' + +export function short(sha: string): string { + return SHA_RE.test(sha) ? sha.slice(0, 12) : sha +} diff --git a/verification/src/validate.ts b/verification/src/validate.ts new file mode 100644 index 0000000..3acb044 --- /dev/null +++ b/verification/src/validate.ts @@ -0,0 +1,293 @@ +/** + * Pure merge-eligibility validator for PR verification manifests. + * + * PR #10 policy → executable. I/O-free by design: callers build a + * VerificationContext from live GitHub state (verification/src/gh.ts); every + * rule below is pinned by a positive or negative control in + * verification/test/validate.test.ts. + * + * Rules implemented (contract rule references are .obvious/obvious.md): + * R1 manifest structure — schema/version/SHA shape (invalid_manifest) + * R2 PR identity — pr number + prUrl match the live PR (pr_mismatch) + * R3 arena hold — arena/candidate-* → hold (rule 8) + * R4 HEAD freshness — testedHeadSha === live head; internal SHAs + * (review, checks, evidence, suites) all equal + * testedHeadSha (rules 3 & 5: stale/mismatched) + * R5 independent review recorded — pass | pass-with-notes, reviewer, date, + * link, reviewed HEAD (rules 2–3) + * R6 checks — ≥1 named green check on the tested HEAD + * (rule 4; live greenness is verified by the sweep) + * R7 evidence — ≥1 passing item on the tested HEAD; UI also + * needs playable-flow with scenario, + * assertions, environment; backend-only needs + * executable behavior evidence + * R8 classification — backend-only/docs-only need justification; + * claimed class must match the actual diff + * (unsupported claims refuse) + * R9 native claims — on-device/simulator/TestFlight-style claims + * require passing playable-flow evidence with + * environment + link, else refuse + * R10 applicable suites — diffs touching code require security and + * evaluation suite runs (incl. the evaluation + * negative control) on the tested HEAD + */ +import type { Reason, ReasonCode, SuiteName, VerificationContext, Verdict } from './types.ts' +import { SHA_RE, short } from './types.ts' + +const UI_PATH_RE = /^(apps\/|packages\/ui\/)/ +const CODE_PATH_RE = /^(apps\/|backend\/|packages\/|security\/|evaluation\/)/ +const DOCS_PATH_RE = /^(docs\/.*|.*\.md)$/ + +const NATIVE_CLAIM_RE = + /\b(on[\s-]?device|physical device|native device|native build|device build|simulator|emulator|expo go|testflight)\b/i + +const EVIDENCE_KINDS = ['playable-flow', 'behavior-run', 'test-run', 'suite-run'] as const +const CLASSIFICATIONS = ['ui', 'backend-only', 'docs-only'] as const + +/** + * Suites applicable to a diff. Both suites are fast (17 access cases + 6 + * fixtures) and both exercise contracts any code change can perturb, so any + * change under a code path requires both; docs-only requires neither. + */ +export function requiredSuites(changedPaths: string[]): SuiteName[] { + return changedPaths.some((p) => CODE_PATH_RE.test(p)) ? ['security', 'evaluation'] : [] +} + +function isRecord(v: unknown): v is Record { + return typeof v === 'object' && v !== null && !Array.isArray(v) +} + +function str(v: unknown): v is string { + return typeof v === 'string' +} + +function nonEmpty(v: unknown): v is string { + return typeof v === 'string' && v.trim().length > 0 +} + +function shaOk(v: unknown): v is string { + return str(v) && SHA_RE.test(v) +} + +export function validateManifest(raw: unknown, ctx: VerificationContext): Verdict { + const reasons: Reason[] = [] + const add = (code: ReasonCode, detail: string): void => reasons.push({ code, detail }) + + if (!isRecord(raw)) { + add('invalid_manifest', 'manifest is not a JSON object') + return decide(reasons) + } + const m = raw as Record + + // --- R1: structure --------------------------------------------------------- + if (m.manifestVersion !== 1) { + add('invalid_manifest', `manifestVersion must be 1, got ${JSON.stringify(m.manifestVersion)}`) + } + const testedHeadSha = m.testedHeadSha + if (!shaOk(testedHeadSha)) { + add('invalid_manifest', 'testedHeadSha must be a 40-char hex SHA') + } + if (!shaOk(ctx.liveHeadSha)) { + throw new Error(`VerificationContext.liveHeadSha is not a 40-char hex SHA: ${String(ctx.liveHeadSha)}`) + } + + // --- R2: PR identity ------------------------------------------------------- + if (m.pr !== ctx.prNumber) { + add('pr_mismatch', `manifest targets PR ${JSON.stringify(m.pr)} but validates PR ${ctx.prNumber}`) + } + if (m.prUrl !== `https://github.com/OCPdev25/obv-hackaton/pull/${ctx.prNumber}`) { + add('pr_mismatch', `prUrl must be https://github.com/OCPdev25/obv-hackaton/pull/${ctx.prNumber}, got ${JSON.stringify(m.prUrl)}`) + } + + // --- R3: arena hold -------------------------------------------------------- + if (/^arena\/candidate-/.test(ctx.headBranch)) { + add( + 'arena_hold', + `branch ${ctx.headBranch} is an arena candidate — excluded from individual auto-merge until arena selection completes (contract rule 8)`, + ) + } + + // --- R4: HEAD freshness (live + internal) ---------------------------------- + if (shaOk(testedHeadSha) && testedHeadSha !== ctx.liveHeadSha) { + add( + 'stale_head_sha', + `manifest tested ${short(testedHeadSha)} but PR HEAD is ${short(ctx.liveHeadSha)} — results from an earlier commit do not carry over (contract rule 5)`, + ) + } + const headMatch = (sha: unknown, what: string): void => { + if (!shaOk(sha)) { + add('invalid_manifest', `${what} must be a 40-char hex SHA`) + } else if (shaOk(testedHeadSha) && sha !== testedHeadSha) { + add('mismatched_sha', `${what} is on ${short(sha)} but the manifest tested ${short(testedHeadSha)}`) + } + } + + // --- R5: independent review ------------------------------------------------ + const review = m.review + if (!isRecord(review)) { + add('missing_review', 'manifest records no review object') + } else { + if (review.result !== 'pass' && review.result !== 'pass-with-notes') { + add('review_not_passing', `review.result must be "pass" or "pass-with-notes", got ${JSON.stringify(review.result)}`) + } + if (!nonEmpty(review.reviewer)) { + add('invalid_review_fields', 'review.reviewer must name the independent reviewer') + } + if (!str(review.date) || !/^\d{4}-\d{2}-\d{2}$/.test(review.date)) { + add('invalid_review_fields', 'review.date must be YYYY-MM-DD') + } + if (!nonEmpty(review.url)) { + add('invalid_review_fields', 'review.url must link to the review thread/comment') + } + if (shaOk(review.reviewedHeadSha) && shaOk(testedHeadSha) && review.reviewedHeadSha !== testedHeadSha) { + add('mismatched_sha', `review covered ${short(review.reviewedHeadSha)} but the manifest tested ${short(testedHeadSha)}`) + } else { + headMatch(review.reviewedHeadSha, 'review.reviewedHeadSha') + } + } + + // --- R6: checks (manifest-level; live greenness is the sweep's job) -------- + const checks = m.checks + if (!Array.isArray(checks) || checks.length === 0) { + add('missing_checks', 'manifest records no CI checks') + } else { + for (const [i, c] of checks.entries()) { + if (!isRecord(c) || !nonEmpty(c.name) || c.status !== 'green' || !nonEmpty(c.url)) { + add('missing_checks', `checks[${i}] must be { name, status: "green", headSha, url }`) + continue + } + headMatch(c.headSha, `check "${c.name}"`) + } + } + + // --- R7: evidence ---------------------------------------------------------- + const evidence = m.evidence + const items: Array> = Array.isArray(evidence) ? evidence.filter(isRecord) : [] + if (!Array.isArray(evidence) || evidence.length === 0) { + add('missing_evidence', 'manifest records no evidence items') + } else { + if (items.length !== evidence.length) { + add('invalid_manifest', 'evidence must be an array of objects') + } + for (const [i, e] of items.entries()) { + const label = `evidence[${i}]` + if (!nonEmpty(e.name) || !nonEmpty(e.url)) { + add('invalid_manifest', `${label} needs a non-empty name and url`) + } + if (!str(e.kind) || !EVIDENCE_KINDS.includes(e.kind)) { + add('invalid_manifest', `${label}.kind must be one of ${EVIDENCE_KINDS.join(', ')}`) + } + headMatch(e.headSha, `${label}`) + if (e.result !== 'pass') { + add('evidence_result_not_passing', `${label}.result must be "pass" — failing runs are not merge evidence`) + } + if (e.kind === 'playable-flow') { + const missing: string[] = [] + if (!nonEmpty(e.scenario)) missing.push('scenario') + if (!Array.isArray(e.assertions) || e.assertions.length === 0 || !e.assertions.every(nonEmpty)) { + missing.push('assertions') + } + if (!nonEmpty(e.environment)) missing.push('environment') + if (missing.length > 0) { + add('invalid_playable_flow', `${label} is playable-flow but missing ${missing.join(', ')}`) + } + } + } + } + + // --- R8: classification ---------------------------------------------------- + const classification = m.classification + if (!str(classification) || !CLASSIFICATIONS.includes(classification)) { + add('invalid_manifest', `classification must be one of ${CLASSIFICATIONS.join(', ')}`) + } + const justification = m.classificationJustification + if ((classification === 'backend-only' || classification === 'docs-only') && !nonEmpty(justification)) { + add( + 'classification_justification_required', + `classification "${String(classification)}" requires a non-empty classificationJustification`, + ) + } + if (str(classification)) { + if (classification === 'ui' && !ctx.changedPaths.some((p) => UI_PATH_RE.test(p))) { + add('classification_mismatch', 'classified "ui" but no changed path is a UI path (apps/** or packages/ui/**)') + } + if (classification === 'backend-only' && ctx.changedPaths.some((p) => UI_PATH_RE.test(p))) { + add( + 'classification_mismatch', + 'classified "backend-only" but the diff touches UI paths (apps/** or packages/ui/**) — reclassify "ui" and supply playable-flow evidence', + ) + } + if (classification === 'docs-only' && ctx.changedPaths.some((p) => !DOCS_PATH_RE.test(p))) { + add('classification_mismatch', 'classified "docs-only" but the diff touches non-documentation paths') + } + if (classification === 'backend-only') { + const behavior = items.some( + (e) => e.kind === 'behavior-run' || e.kind === 'test-run' || e.kind === 'suite-run', + ) + if (!behavior) { + add( + 'missing_evidence', + 'backend-only requires executable behavior evidence (behavior-run | test-run | suite-run) on the tested HEAD', + ) + } + } + if (classification === 'ui') { + const playable = items.some((e) => e.kind === 'playable-flow') + if (!playable) { + add( + 'no_playable_flow', + 'ui changes require at least one playable-flow evidence item (scenario, assertions, environment, linked to the tested HEAD)', + ) + } + } + } + + // --- R9: native/device claims --------------------------------------------- + const claimParts = [ + nonEmpty(justification) ? justification : '', + nonEmpty(m.notes) ? m.notes : '', + ...items.flatMap((e) => [nonEmpty(e.name) ? e.name : '', nonEmpty(e.scenario) ? e.scenario : '', nonEmpty(e.environment) ? e.environment : '']), + ] + if (claimParts.some((p) => NATIVE_CLAIM_RE.test(p))) { + const playable = items.some( + (e) => e.kind === 'playable-flow' && e.result === 'pass' && nonEmpty(e.environment) && nonEmpty(e.url), + ) + if (!playable) { + add( + 'native_claim_unsupported', + 'manifest claims native/device verification but records no passing playable-flow evidence with environment + link — supply the evidence or drop the claim', + ) + } + } + + // --- R10: applicable suites ------------------------------------------------ + for (const suite of requiredSuites(ctx.changedPaths)) { + const suites = isRecord(m.suites) ? m.suites : {} + const rec = suites[suite] + if (!isRecord(rec)) { + add('suite_not_recorded', `suite "${suite}" is applicable to this diff but the manifest records no run (see verification/README.md)`) + continue + } + if (!nonEmpty(rec.url)) { + add('suite_not_recorded', `suite "${suite}" needs a run URL`) + } + if (rec.ran !== true || rec.result !== 'pass') { + add('suite_not_passing', `suite "${suite}" must be recorded as ran: true, result: "pass"`) + continue + } + headMatch(rec.headSha, `suite "${suite}"`) + if (suite === 'evaluation' && rec.negativeControl !== 'fail-as-expected') { + add( + 'suite_negative_control_missing', + 'evaluation suite requires negativeControl "fail-as-expected" — the broken-adapter control must be recorded as failing', + ) + } + } + + return decide(reasons) +} + +function decide(reasons: Reason[]): Verdict { + if (reasons.some((r) => r.code === 'arena_hold')) return { decision: 'hold', reasons } + return reasons.length === 0 ? { decision: 'merge', reasons: [] } : { decision: 'refuse', reasons } +} diff --git a/verification/test/validate.test.ts b/verification/test/validate.test.ts new file mode 100644 index 0000000..8c595f3 --- /dev/null +++ b/verification/test/validate.test.ts @@ -0,0 +1,236 @@ +/** + * Verification-gate validator tests — positive controls + negative controls. + * + * Positive controls prove a well-formed manifest merges. + * Negative controls prove each contract rule blocks on its own term: each + * fixture is internally consistent except for ONE defect, and the assertion + * pins the exact refusal-code set — the gate must fire on that term and stay + * silent on everything else (the same fail-closed discipline the repo's + * security suite applies to access cases). + */ +import { describe, expect, it } from 'bun:test' +import { readFileSync } from 'node:fs' +import { extractManifests, latestManifest } from '../src/manifest.ts' +import { requiredSuites, validateManifest } from '../src/validate.ts' +import type { VerificationContext, Verdict } from '../src/types.ts' + +const GOOD_SHA = 'a'.repeat(40) +const STALE_SHA = 'b'.repeat(40) + +const load = (name: string): unknown => + JSON.parse(readFileSync(new URL(`../fixtures/${name}.json`, import.meta.url), 'utf8')) + +const backendCtx: VerificationContext = { + liveHeadSha: GOOD_SHA, + headBranch: 'feat/entry-adapter', + prNumber: 99, + changedPaths: ['backend/convex/entries.ts', 'packages/domain/src/index.ts'], +} +const uiCtx: VerificationContext = { + liveHeadSha: GOOD_SHA, + headBranch: 'feat/timeline-ui', + prNumber: 98, + changedPaths: ['apps/mobile/app/timeline.tsx'], +} +const docsCtx: VerificationContext = { + liveHeadSha: GOOD_SHA, + headBranch: 'docs/guide', + prNumber: 99, + changedPaths: ['packages/domain/src/index.ts'], +} + +const codes = (v: Verdict) => new Set(v.reasons.map((r) => r.code)) + +describe('requiredSuites (diff → applicable suites)', () => { + it('requires both suites for code paths', () => { + expect(requiredSuites(['backend/convex/entries.ts'])).toEqual(['security', 'evaluation']) + expect(requiredSuites(['packages/domain/src/index.ts'])).toEqual(['security', 'evaluation']) + expect(requiredSuites(['apps/mobile/app/timeline.tsx'])).toEqual(['security', 'evaluation']) + expect(requiredSuites(['packages/ui/src/timeline.tsx'])).toEqual(['security', 'evaluation']) + }) + it('requires nothing for docs/markdown', () => { + expect(requiredSuites(['README.md', 'docs/guide.md'])).toEqual([]) + }) +}) + +describe('positive controls', () => { + it('backend-only manifest with full evidence merges', () => { + const v = validateManifest(load('positive-backend'), backendCtx) + expect(v.decision).toBe('merge') + expect(v.reasons).toEqual([]) + }) + it('ui manifest with playable-flow evidence merges', () => { + const v = validateManifest(load('positive-ui'), uiCtx) + expect(v.decision).toBe('merge') + expect(v.reasons).toEqual([]) + }) +}) + +describe('nc1 — stale tested HEAD (contract rule 3/5)', () => { + it('refuses with stale_head_sha only', () => { + const v = validateManifest(load('nc1-stale-sha'), backendCtx) + expect(v.decision).toBe('refuse') + expect(codes(v)).toEqual(new Set(['stale_head_sha'])) + }) +}) + +describe('nc1b — internal SHA mismatch', () => { + it('refuses with mismatched_sha only', () => { + const v = validateManifest(load('nc1b-mismatched-sha'), backendCtx) + expect(v.decision).toBe('refuse') + expect(codes(v)).toEqual(new Set(['mismatched_sha'])) + }) +}) + +describe('nc2 — no evidence items', () => { + it('refuses with missing_evidence', () => { + const v = validateManifest(load('nc2-missing-evidence'), backendCtx) + expect(v.decision).toBe('refuse') + expect(codes(v).has('missing_evidence')).toBe(true) + expect(codes(v).has('stale_head_sha')).toBe(false) + expect(codes(v).has('missing_review')).toBe(false) + }) +}) + +describe('nc3 — hollow playable-flow', () => { + it('refuses with invalid_playable_flow only', () => { + const v = validateManifest(load('nc3-invalid-playable-flow'), uiCtx) + expect(v.decision).toBe('refuse') + expect(codes(v)).toEqual(new Set(['invalid_playable_flow'])) + }) +}) + +describe('nc4 — unsupported native/device claim', () => { + it('refuses with native_claim_unsupported only', () => { + const v = validateManifest(load('nc4-native-claim'), backendCtx) + expect(v.decision).toBe('refuse') + expect(codes(v)).toEqual(new Set(['native_claim_unsupported'])) + }) +}) + +describe('nc5 — classification contradicts the live diff', () => { + it('backend-only claim over UI paths refuses with classification_mismatch only', () => { + const v = validateManifest(load('nc5-classification-mismatch'), { ...uiCtx, prNumber: 99 }) + expect(v.decision).toBe('refuse') + expect(codes(v)).toEqual(new Set(['classification_mismatch'])) + }) + it('docs-only claim over source paths refuses with classification_mismatch (and the diff still owes its suites)', () => { + const v = validateManifest(load('nc5b-docs-mismatch'), docsCtx) + expect(v.decision).toBe('refuse') + // The diff touches source, so the classification is wrong AND the + // suites the real diff requires are unrecorded — both are true failures. + expect(codes(v)).toEqual(new Set(['classification_mismatch', 'suite_not_recorded'])) + }) +}) + +describe('nc6 — review missing', () => { + it('refuses with missing_review only', () => { + const v = validateManifest(load('nc6-no-review'), backendCtx) + expect(v.decision).toBe('refuse') + expect(codes(v)).toEqual(new Set(['missing_review'])) + }) +}) + +describe('nc7 — required suites not recorded', () => { + it('refuses with suite_not_recorded for both applicable suites', () => { + const v = validateManifest(load('nc7-suites-missing'), backendCtx) + expect(v.decision).toBe('refuse') + expect(codes(v).has('suite_not_recorded')).toBe(true) + expect(v.reasons.filter((r) => r.code === 'suite_not_recorded').length).toBe(2) + }) +}) + +describe('nc8 — evaluation negative control not recorded', () => { + it('refuses with suite_negative_control_missing only', () => { + const v = validateManifest(load('nc8-eval-negative-control-missing'), backendCtx) + expect(v.decision).toBe('refuse') + expect(codes(v)).toEqual(new Set(['suite_negative_control_missing'])) + }) +}) + +describe('arena candidate hold (contract rule 8)', () => { + it('holds regardless of evidence quality', () => { + const v = validateManifest(load('positive-backend'), { ...backendCtx, headBranch: 'arena/candidate-b' }) + expect(v.decision).toBe('hold') + expect(codes(v).has('arena_hold')).toBe(true) + }) +}) + +describe('manifest integrity rules (inline mutations of the positive control)', () => { + const base = load('positive-backend') as Record + + it('rejects a wrong manifestVersion', () => { + const v = validateManifest({ ...base, manifestVersion: 2 }, backendCtx) + expect(codes(v)).toEqual(new Set(['invalid_manifest'])) + }) + it('rejects a manifest pointed at a different PR', () => { + const v = validateManifest({ ...base, pr: 100, prUrl: 'https://github.com/OCPdev25/obv-hackaton/pull/100' }, backendCtx) + expect(codes(v)).toEqual(new Set(['pr_mismatch'])) + }) + it('rejects a failed review (no invented approvals)', () => { + const mutated = structuredClone(base) as Record + ;(mutated.review as Record).result = 'fail' + const v = validateManifest(mutated, backendCtx) + expect(codes(v)).toEqual(new Set(['review_not_passing'])) + }) + it('rejects failed evidence (evidence_result_not_passing)', () => { + const mutated = structuredClone(base) as Record + ;(mutated.evidence as Array>)[0]!.result = 'fail' + const v = validateManifest(mutated, backendCtx) + expect(codes(v)).toEqual(new Set(['evidence_result_not_passing'])) + }) + it('rejects a suite run that failed', () => { + const mutated = structuredClone(base) as Record + ;(mutated.suites as Record>).security.result = 'fail' + const v = validateManifest(mutated, backendCtx) + expect(codes(v)).toEqual(new Set(['suite_not_passing'])) + }) + it('rejects non-JSON garbage with invalid_manifest', () => { + const v = validateManifest('not a manifest', backendCtx) + expect(v.decision).toBe('refuse') + expect(codes(v).has('invalid_manifest')).toBe(true) + }) +}) + +describe('manifest extraction (latest-wins across body and comments)', () => { + const marker = 'verification-manifest:v1' + // Recording format: HTML comment marker, then a json fence (GitHub renders + // the comment invisibly). + const block = (json: string): string => `\n\`\`\`json\n${json}\n\`\`\`` + + it('finds the marker block in a PR body', () => { + const body = `some prose\n\n${block('{"manifestVersion":1}')}\nmore prose` + const found = extractManifests(body, 'body') + expect(found.length).toBe(1) + expect(found[0]!.source).toBe('body') + expect(found[0]!.ok).toBe(true) + }) + it('latest valid manifest wins, ordered by comment time then id', () => { + const body = block('{"manifestVersion":1}') + const c1 = block('{"manifestVersion":1,"notes":"first comment"}') + const c2 = block('{"manifestVersion":1,"notes":"second comment"}') + const blocks = [ + ...extractManifests(body, 'body'), + ...extractManifests(c1, 'comment 1'), + ...extractManifests(c2, 'comment 2'), + ] + expect(blocks.length).toBe(3) + const latest = latestManifest(blocks) + expect(latest?.ok).toBe(true) + if (latest?.ok) expect((latest.raw as { notes?: string }).notes).toBe('second comment') + }) + it('a later malformed marker block invalidates rather than falling back', () => { + const c1 = block('{"manifestVersion":1,"notes":"good"}') + const c2 = `\n\`\`\`json\n{"manifestVersion":1, broken\n\`\`\`` + const blocks = [...extractManifests(c1, 'comment 1'), ...extractManifests(c2, 'comment 2')] + expect(blocks.length).toBe(2) + expect(blocks[0]!.ok).toBe(true) + expect(blocks[1]!.ok).toBe(false) + const latest = latestManifest(blocks) + expect(latest?.ok).toBe(false) + }) + it('ignores prose mentioning the marker without a fenced block', () => { + const body = `we should add a block here` + expect(extractManifests(body, 'body').length).toBe(0) + }) +}) diff --git a/verification/tsconfig.json b/verification/tsconfig.json new file mode 100644 index 0000000..22a517c --- /dev/null +++ b/verification/tsconfig.json @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "bundler", + "strict": true, + "noUncheckedIndexedAccess": true, + "skipLibCheck": true, + "noEmit": true, + "allowImportingTsExtensions": true, + "types": [] + }, + "include": ["src/**/*.ts", "test/**/*.ts"] +}