{{.Question}}
{{.Context}}
{{.File}} {{.Function}} · {{.ID}}{{range .Options}}{{.ID}}: {{.Label}}{{if .Recommended}} (recommended){{end}} — {{.Consequence}}
{{end}}Selected: {{.Selected}} · Reason: {{.Rationale}}
diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml index fa22991..a847525 100644 --- a/.github/workflows/check.yml +++ b/.github/workflows/check.yml @@ -75,6 +75,32 @@ jobs: assert result['data']['current'] and result['data']['receipt']['success'] assert result['data']['receipt']['approval']['reviewer'] == 'codex-example-review' PYTHON + - name: Install the browser test runner outside the source snapshot + run: | + npm install --no-audit --no-fund --prefix "$RUNNER_TEMP/pdd-playwright" @playwright/test@1.65.1 + runner="$RUNNER_TEMP/pdd-playwright/node_modules/@playwright/test/cli.js" + node "$runner" install --with-deps chromium + echo "PDD_PLAYWRIGHT_CLI=$runner" >> "$GITHUB_ENV" + - name: Verify the wallet browser flow and HTML evidence + run: | + bin/pdd --plan httpwallet-browser init --from examples/httpwallet/browser/plan.json + bin/pdd --plan httpwallet-browser import-approval --from .pdd/reviews/httpwallet-browser.json + bin/pdd --plan httpwallet-browser prove --json > .pdd/browser-prove-result.json + bin/pdd --plan httpwallet-browser status --json > .pdd/browser-status-result.json + bin/pdd --plan httpwallet-browser report --out .pdd/state/httpwallet-browser/report.html + python3 - <<'PYCODE' + import json + from pathlib import Path + status = json.loads(Path('.pdd/browser-status-result.json').read_text()) + assert status['ok'] and status['data']['current'] + receipt = status['data']['receipt'] + assert receipt['success'] + assert any(v['id'] == 'overdraft-screen' and v['status'] == 'evidenced' for v in receipt['requirements']) + browser = next(e for e in receipt['evidence'] if e['check'] == 'wallet-browser') + assert browser['kind'] == 'empirical' and browser['artifacts'][0]['file'] == 'wallet-browser.playwright.json' + report = Path('.pdd/state/httpwallet-browser/report.html').read_text() + assert 'playwright · empirical' in report and 'wallet-browser.playwright.json' in report and 'killed' in report + PYCODE - name: Upload proof receipts if: always() uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 @@ -83,6 +109,8 @@ jobs: path: | .pdd/receipts/ .pdd/state/httpwallet/receipts/ + .pdd/state/httpwallet-browser/receipts/ + .pdd/state/httpwallet-browser/report.html .pdd/*-result.json if-no-files-found: warn include-hidden-files: true diff --git a/.pdd/reviews/httpwallet-browser.json b/.pdd/reviews/httpwallet-browser.json new file mode 100644 index 0000000..d0a3553 --- /dev/null +++ b/.pdd/reviews/httpwallet-browser.json @@ -0,0 +1,149 @@ +{ + "schema": 1, + "digest": "de201c3d481e039c7c435f4ce41734a4e25039a6c105e3fdd0b01abca4ebe699", + "reviewer": "codex-example-review", + "accepted_trust": [ + "wallet-runtime", + "wallet-sessions" + ], + "approved_at": "2026-11-18T06:14:12.837703671Z", + "plan_id": "httpwallet-browser", + "review": { + "schema": 1, + "plan_id": "httpwallet-browser", + "plan": { + "scenarios": [ + { + "id": "browser-overdraft", + "check": "wallet-browser", + "test": "wallet.spec.cjs :: rejects an overdraft without debiting the wallet", + "given": "A demo account starts with a balance of 100", + "when": "The user attempts to withdraw 101 then withdraws 100", + "then": "The browser shows a denial followed by a successful withdrawal with zero remaining", + "requirements": [ + "overdraft-screen" + ], + "purpose": "integration" + } + ], + "schema": 1, + "name": "HTTP wallet with browser evidence", + "intent": "The HTTP withdrawal endpoint must use the verified production decision, allowing a withdrawal exactly for an authenticated, unlocked account with a positive amount within its balance. Exercise request decoding, sessions and atomic state updates empirically. Show a refusal in the browser for an overdraw and leave the wallet unchanged.", + "non_goals": [ + "The static demo tokens are not production authentication; no TLS, identity proof, persistence, payment settlement or distributed consistency is provided.", + "Gobra proves the pure decision only; HTTP decoding, the session mapping, synchronization and state updates have empirical evidence, not formal proof.", + "Availability, fairness, transport failure recovery and exactly-once request semantics are outside scope." + ], + "requirements": [ + { + "id": "withdrawal-policy", + "text": "Accept exactly authenticated, unlocked withdrawals with positive amount no greater than balance.", + "kind": "formal", + "check": "withdrawal-proof", + "file": "examples/httpwallet/policy/policy.go", + "function": "CanWithdraw", + "ensures": "allowed == (authenticated \u0026\u0026 !locked \u0026\u0026 amount \u003e 0 \u0026\u0026 amount \u003c= balance)" + }, + { + "id": "http-boundary", + "text": "HTTP method, path, session and withdrawal boundaries return expected status and balance, without changing funds on rejection.", + "kind": "empirical", + "check": "http-tests" + }, + { + "id": "http-decoding", + "text": "Malformed, oversized, ambiguous and unknown request inputs are rejected without changing funds.", + "kind": "empirical", + "check": "http-tests" + }, + { + "id": "atomic-withdrawals", + "text": "Concurrent requests through a real local HTTP server spend the initial balance exactly once without overdraft.", + "kind": "empirical", + "check": "http-tests" + }, + { + "id": "overdraft-screen", + "text": "A browser shows withdrawal denied for an overdraft and the full starting balance remains available.", + "kind": "empirical", + "check": "wallet-browser" + } + ], + "checks": [ + { + "id": "withdrawal-proof", + "kind": "gobra", + "files": [ + "examples/httpwallet/policy/policy.go" + ] + }, + { + "id": "http-tests", + "kind": "go-test", + "package": "./examples/httpwallet/app", + "tests": [ + "TestWithdrawalHTTP", + "TestMalformedHTTP", + "TestConcurrentHTTPWithdrawals" + ] + }, + { + "id": "wallet-browser", + "kind": "playwright", + "tests": [ + "wallet.spec.cjs :: rejects an overdraft without debiting the wallet" + ], + "config": "examples/httpwallet/browser/playwright.config.cjs", + "project": "chromium" + } + ], + "trusted_boundary": [ + { + "id": "wallet-sessions", + "assumption": "The configured session mapping identifies the correct account and lock state; demo tokens are public test credentials. Tests exercise known, unknown, locked and ambiguous tokens but cannot establish a real identity provider's truthfulness.", + "check": "http-tests" + }, + { + "id": "wallet-runtime", + "assumption": "Go integer/JSON/HTTP implementations and mutex semantics are trusted. Race and TCP concurrency tests exercise parsing and an atomic in-memory update; they do not prove the runtime or provide durable financial guarantees.", + "check": "http-tests" + } + ], + "mutations": [ + { + "id": "ignore-session-lock", + "requirement": "withdrawal-policy", + "check": "withdrawal-proof", + "file": "examples/httpwallet/policy/policy.go", + "find": "return authenticated \u0026\u0026 !locked \u0026\u0026 amount \u003e 0 \u0026\u0026 amount \u003c= balance", + "replace": "return authenticated \u0026\u0026 amount \u003e 0 \u0026\u0026 amount \u003c= balance" + }, + { + "id": "allow-zero-withdrawal", + "requirement": "withdrawal-policy", + "check": "withdrawal-proof", + "file": "examples/httpwallet/policy/policy.go", + "find": "return authenticated \u0026\u0026 !locked \u0026\u0026 amount \u003e 0 \u0026\u0026 amount \u003c= balance", + "replace": "return authenticated \u0026\u0026 !locked \u0026\u0026 amount \u003e= 0 \u0026\u0026 amount \u003c= balance" + }, + { + "id": "allow-overdraft", + "requirement": "withdrawal-policy", + "check": "withdrawal-proof", + "file": "examples/httpwallet/policy/policy.go", + "find": "return authenticated \u0026\u0026 !locked \u0026\u0026 amount \u003e 0 \u0026\u0026 amount \u003c= balance", + "replace": "return authenticated \u0026\u0026 !locked \u0026\u0026 amount \u003e 0" + } + ] + }, + "sources": [ + { + "file": "examples/httpwallet/policy/policy.go", + "annotations": [ + "ensures allowed == (authenticated \u0026\u0026 !locked \u0026\u0026 amount \u003e 0 \u0026\u0026 amount \u003c= balance)", + "declarations:package policy\n\nfunc CanWithdraw(authenticated, locked bool, amount, balance int) (allowed bool) {\n}\n" + ] + } + ] + } +} diff --git a/README.md b/README.md index 82ebb61..8d2c9e9 100644 --- a/README.md +++ b/README.md @@ -48,7 +48,7 @@ login-decision: proved (formal) login-boundary: evidenced (empirical) ``` -Open the `receipt.md` path printed by `pdd prove` to see the checks, rejected mutations, trusted assumptions, and proof limits. `pdd status` checks that the latest receipt still matches the current source and approval. For a browser view of the plan and evidence, run `pdd report --out .pdd/results/login.html` and open that file. +Open the `receipt.md` path printed by `pdd prove` to see the checks, rejected mutations, trusted assumptions, and proof limits. `pdd status` checks that the latest receipt still matches the current source and approval. For the requirements, test results, rejected mutations, and links to logs on one page, run `pdd report --out .pdd/results/login.html` and open the HTML file. ## Use it in your project @@ -64,14 +64,14 @@ If you already work with a coding agent, `pdd draft` can turn a request into an | Example | What to look at | | --- | --- | -| [HTTP wallet](examples/httpwallet/README.md) | A real HTTP handler calls a proved withdrawal rule. Go tests exercise session handling, invalid requests, and concurrent withdrawals. | +| [HTTP wallet](examples/httpwallet/README.md) | A real HTTP handler calls a proved withdrawal rule. Go tests exercise the HTTP boundary and concurrent withdrawals. The optional browser check submits an overdraft and confirms the balance remains available. | | [Multi-package authorization](examples/authorization/plan.json) | A handler calls local policy methods. PDD checks the dependency package before the caller. | | [Slice validation](examples/validation/README.md) | A production loop proves a property over every element using permissions, a quantified contract, and loop invariants. | ## What you can rely on - **Formal proofs cover stated contracts.** Gobra checks supported Go functions and methods, including supported calls across packages in one module. External and standard-library imports in proof packages remain outside the supported scope. [Supported proof inputs](docs/plan-format.md) -- **Go tests provide evidence for the cases they run.** The receipt labels them separately from proofs. Each planned negative mutation must fail on the intended postcondition. A missing test, tool failure, or inconclusive mutation fails verification. [Design](docs/design.md) +- **Go and browser tests provide evidence for the cases they run.** The receipt labels them separately from proofs. Each planned negative mutation must fail on the intended postcondition. A missing test, tool failure, or inconclusive mutation fails verification. [Design](docs/design.md) - **Receipts tie the result to the reviewed change.** Machine-readable JSON and Markdown include the plan and source digests, commands, outcomes, trust assumptions, and links or references to saved logs. `status` rejects stale evidence. Use Ed25519 approvals with a trusted policy when CI needs to verify reviewer authority. [JSON protocol](docs/cli-json.md) · [Signed reviews](docs/signed-reviews.md) `pdd-kit-go` is an independent implementation of ideas from the Proof-Driven Development Kit research prototype. Its Go verifier is Gobra. [Original PDD Kit](https://githubnext.com/projects/pdd-kit/) · [Feature comparison and limits](docs/reference-comparison.md) diff --git a/docs/browser-checks.md b/docs/browser-checks.md new file mode 100644 index 0000000..42d8301 --- /dev/null +++ b/docs/browser-checks.md @@ -0,0 +1,63 @@ +# Browser checks with Playwright + +A `playwright` check runs an existing Playwright Test project in the same kind of +isolated source copy as a Go test. PDD verifies the required test identities in +the final JSON report and saves it with the receipt. HTML reports link to the +execution log, the Playwright JSON, and any saved failure screenshots and traces. + +## Run the wallet example + +Use a Go toolchain, the pinned Gobra image, and Node.js 20 or newer for this +example. Install Playwright and Chromium once on the machine running the check. +Run these commands from the repository root with a `pdd` binary built from this +checkout. + +```sh +browser_tools=$(mktemp -d) +npm install --prefix "$browser_tools" @playwright/test@1.65.1 +export PDD_PLAYWRIGHT_CLI="$browser_tools/node_modules/@playwright/test/cli.js" +node "$PDD_PLAYWRIGHT_CLI" install chromium + +pdd --plan httpwallet-browser init --from examples/httpwallet/browser/plan.json +pdd --plan httpwallet-browser plan +pdd --plan httpwallet-browser import-approval --from .pdd/reviews/httpwallet-browser.json +pdd --plan httpwallet-browser prove +pdd --plan httpwallet-browser status +pdd --plan httpwallet-browser report --out .pdd/state/httpwallet-browser/report.html +``` + +Open the generated HTML alongside its `receipts/` directory so relative links +work. The saved example approval is a demonstration assertion. Review and approve +your own project's requirements and trust assumptions separately. On Linux, +`node "$PDD_PLAYWRIGHT_CLI" install --with-deps chromium` can also install the +browser's system dependencies. + +## Adopt an existing suite + +- Point `PDD_PLAYWRIGHT_CLI` to an absolute `node_modules/@playwright/test/cli.js` + path. `node` must be on `PATH`. Provision the runner and any CommonJS test + dependencies together. PDD sets `NODE_PATH` to that `node_modules` directory. + The check performs no dependency installation. +- Add a check of kind `playwright` with `config`, `project`, and `tests` in the + [plan format](plan-format.md). Use a standalone Playwright project and a + repository-relative configuration. PDD runs that project without project + dependencies and verifies every required test against the completed result. + Use a config that starts its own local app and keeps output out of the source + snapshot. The wallet config sets `reuseExistingServer: false`. +- Keep project code, config, and tests in the captured snapshot. You can put the + preinstalled dependencies outside the repository, or explicitly exclude + `node_modules` via the reviewed `inputs.exclude` policy. Browser plans allow + only `node_modules` exclusions in addition to PDD's default reserved paths. + Use CommonJS-compatible dependency resolution for externally provisioned + packages. Fully native ESM imports do not use `NODE_PATH`. +- Set `use.screenshot` to `only-on-failure` if you want failure images. PDD + requests tracing on failure and retains bounded PNG/trace artifacts from + Playwright's output directory. Open a saved trace with + `node "$PDD_PLAYWRIGHT_CLI" show-trace PATH_TO_TRACE.zip`. Browser artifacts can + contain private page content or network data. Share them with the same care as + test logs. + +The runtime and browser are part of the empirical test environment. Playwright's +configuration and tests run with the invoking user's permissions, as Go tests do. +Browser checks provide evidence for the cases that actually ran. Gobra continues +to prove the Go contracts separately. diff --git a/docs/cli-json.md b/docs/cli-json.md index 4237d1f..bd1a299 100644 --- a/docs/cli-json.md +++ b/docs/cli-json.md @@ -80,3 +80,8 @@ and conservative pruning candidates. `build` returns stage, success, decision-ne state, applied edits, iterations and artifact paths; success=false exits 1. `report` returns its written HTML path. `pr` returns the evidence body/path and a URL only after explicit successful `--create`. All use the same schema-1 envelope. + +Playwright evidence can include an `artifacts` array on a receipt check. Each +entry has a receipt-relative `file` and `sha256`. The JSON test report is required +for a successful browser check. Optional PNG and trace ZIP files preserve failure +context. `status` revalidates referenced files and the required test results. diff --git a/docs/design.md b/docs/design.md index 7fae64c..3e43f55 100644 --- a/docs/design.md +++ b/docs/design.md @@ -20,7 +20,7 @@ The selected image is Gobra `v26.09`, resolved and pinned to `sha256:5e96431b06c - `packages.go` resolves complete same-module proof packages, receiver-qualified symbols and the dependency DAG. It rejects ambiguous import resolution and unverified callee packages. - `inputs.go` validates reviewed asset exclusions and the protected Go input closure; `snapshot.go` captures bounded inputs, modes and directories and creates separate check/mutation workspaces. - `approval_transfer.go` exports/imports complete matching reviews without minting CI approvals. -- `runner.go` invokes only Gobra and named Go tests, distinguishes operational failures and validates actual results. +- `runner.go` invokes Gobra and named Go tests. `browser.go` runs a reviewed Playwright project and validates first-attempt results for the named tests. - `prove.go` joins the evidence, rejects gaps and staleness, and writes receipts. Formal evidence covers exactly the clauses checked by the Gobra invocation. The production function is both compiled by Go and passed directly to Gobra. The baseline check succeeds first; each mutant must then fail on the target clause. No successful test can replace a failed formal obligation. diff --git a/docs/plan-format.md b/docs/plan-format.md index 3107fc2..5f34129 100644 --- a/docs/plan-format.md +++ b/docs/plan-format.md @@ -10,7 +10,7 @@ The [login example](../examples/login/plan.json) is a complete plan. Identifiers | `name`, `intent` | Human-readable purpose and intended behavior | | `non_goals` | Limitations and excluded guarantees shown in receipts | | `requirements` | Named obligations with a formal or empirical evidence classification | -| `checks` | Typed Gobra or Go-test invocations; arbitrary shell commands are not supported | +| `checks` | Typed Gobra, Go test, or Playwright invocations | | `trusted_boundary` | Explicit assumptions with empirical checks | | `mutations` | Negative examples, at least one per formal requirement | | `inputs` | Optional reviewed snapshot limits and exact asset exclusions; see [input scope](inputs.md) | @@ -27,7 +27,18 @@ External/standard-library imports, nested modules, `go.mod` replacement directiv An empirical requirement names `id`, `text`, `kind: "empirical"`, and a `go-test` check. That check has `package` (one local package, such as `./internal/auth`) and `tests` (explicit top-level names such as `TestLoginBoundary`). Passing output must contain an actual `pass` event for every named test. Table cases/subtests may exist inside those named tests. Test quality and sufficiency require review; a passing test can still assert nothing useful. -Each trust item has `id`, `assumption`, and `check`; the check must be empirical. `approve --accept-tcb` must list exactly all trust IDs. Mapping a broad assumption to one weak test does not make it true: explain the test's limits in the assumption and non-goals. +A `playwright` check supplies `config` (repository-relative config file), `project` +(one exact project name), and `tests` (required test identities). A test identity +has the form `file :: title`, with the file relative to Playwright's report root. +For nested `describe` blocks, use `file :: Suite › Nested suite › test title`. +Use this check for empirical requirements, trust checks, and test scenarios. + +The selected project runs once, with zero retries. Every listed test must appear +as a first-attempt pass in the final Playwright JSON, and the project must finish +without skipped, failed, flaky, or expected-failure cases. The results are recorded +as empirical evidence. See [browser checks](browser-checks.md) for setup and scope. + +Each trust item has `id`, `assumption`, and `check`; the check must be empirical. `approve --accept-tcb` must list all trust IDs and assumed clause IDs. Mapping a broad assumption to one weak test does not make it true: explain the test's limits in the assumption and non-goals. ## Negative mutations diff --git a/docs/reference-comparison.md b/docs/reference-comparison.md index 5eb0e2b..17dd249 100644 --- a/docs/reference-comparison.md +++ b/docs/reference-comparison.md @@ -16,9 +16,9 @@ planning. These published workflows are the basis for the comparison below. | Intent artifact | Original request, verbatim excerpts mapped to requirement/decision IDs | Human review determines whether the proposed clauses express the right intent | | Planning review | Two separate invocations for intent fidelity and guarantee quality; both must be ready before approval when enabled | Advisory opinions, not authenticated independent people or formal proof | | Trust | Per-clause assumptions, impact if false, named tests, Given/When/Then cases and explicit acceptance of each clause | Tests sample behavior; external library implementations remain outside Gobra's proved core | -| Human-facing views | Offline HTML cards, specification landscape, workflow diagram, task dependencies, findings and limits | No Chopin API integration, live multiplayer editor or generated semantic pictures | +| Human-facing views | Offline HTML for requirements, verdicts, negative examples, trust, review and linked artifacts | No Chopin API integration, live multiplayer editor or generated semantic pictures | | Implementation | Scratch candidate repair loop for Go bodies, tests and opt-in provable proof hints | Frozen declarations, contracts, pure definitions, intent and trust cannot be silently changed | -| Verification | Pinned Gobra proofs, named Go tests, per-clause negative mutations, source/approval/log-bound receipts | Supported Go subset; not Rust/Verus equivalence | +| Verification | Pinned Gobra proofs, named Go and Playwright tests, per-clause negative mutations and source-bound receipts | Supported Go subset; not Rust/Verus equivalence | | Gap analysis | Separate advisory reviewer sees source and actual machine results; review binds to the exact receipt | A model cannot turn failed machine verification into success | | Feedback | Machine/advisory failures lead to bounded repair; changed contracts or unsupported scope stop for a decision | No automatic human signoff | | Delivery | `pr` previews an evidence-backed body; `pr --create` opens a draft PR for committed, pushed, freshly verified code | Does not push, merge or bypass protection | @@ -26,8 +26,7 @@ planning. These published workflows are the basis for the comparison below. The remaining reference-specific gaps are real: Chopin's collaborative planning surface, Rust async and Verus-specific trusted external function adapters, and -built-in browser/computer-use test orchestration are not implemented. Go empirical -tests can exercise real I/O; that does not prove those dependencies. Arbitrary Go +general desktop computer-use orchestration remain open. The built-in Playwright adapter runs reviewed browser suites and records empirical results. Arbitrary Go generics, dependency imports in formal packages and concurrency proofs retain the restrictions documented in [the plan format](plan-format.md). diff --git a/examples/httpwallet/README.md b/examples/httpwallet/README.md index e2d240c..381563e 100644 --- a/examples/httpwallet/README.md +++ b/examples/httpwallet/README.md @@ -10,6 +10,7 @@ curl -i http://127.0.0.1:8080/v1/withdraw \ -H 'Content-Type: application/json' -d '{"amount":40}' ``` +Open `http://127.0.0.1:8080/` for the demo form, or use the API request above. The response is `200` with `{"balance":60}`. The in-memory balance starts at 100; a second request for 100 returns `403`. `demo-locked` is always denied. Restarting resets all balances. These public static credentials, single-process memory and @@ -45,3 +46,13 @@ for HTTP, session lookup and atomic updates. Client disconnects may occur after commit; retries are not idempotent. No durable storage, distributed locking, identity verification, TLS or settlement guarantees are claimed. The reviewable plan records these limits and the runtime/session trust boundary explicitly. + +## Browser verification + +The separate `httpwallet-browser` plan proves the same Go policy, runs the HTTP +and concurrency tests, and opens this form in Chromium. The browser case attempts +to withdraw 101 from a balance of 100, sees the denial, then withdraws all 100. +The final response displays a remaining balance of zero. + +Follow the [browser setup and example commands](../../docs/browser-checks.md). +The example plan uses port 38479 and starts a fresh server for the check. diff --git a/examples/httpwallet/browser/plan.json b/examples/httpwallet/browser/plan.json new file mode 100644 index 0000000..471c0c2 --- /dev/null +++ b/examples/httpwallet/browser/plan.json @@ -0,0 +1,125 @@ +{ + "schema": 1, + "name": "HTTP wallet with browser evidence", + "intent": "The HTTP withdrawal endpoint must use the verified production decision, allowing a withdrawal exactly for an authenticated, unlocked account with a positive amount within its balance. Exercise request decoding, sessions and atomic state updates empirically. Show a refusal in the browser for an overdraw and leave the wallet unchanged.", + "non_goals": [ + "The static demo tokens are not production authentication; no TLS, identity proof, persistence, payment settlement or distributed consistency is provided.", + "Gobra proves the pure decision only; HTTP decoding, the session mapping, synchronization and state updates have empirical evidence, not formal proof.", + "Availability, fairness, transport failure recovery and exactly-once request semantics are outside scope." + ], + "requirements": [ + { + "id": "withdrawal-policy", + "text": "Accept exactly authenticated, unlocked withdrawals with positive amount no greater than balance.", + "kind": "formal", + "check": "withdrawal-proof", + "file": "examples/httpwallet/policy/policy.go", + "function": "CanWithdraw", + "ensures": "allowed == (authenticated && !locked && amount > 0 && amount <= balance)" + }, + { + "id": "http-boundary", + "text": "HTTP method, path, session and withdrawal boundaries return expected status and balance, without changing funds on rejection.", + "kind": "empirical", + "check": "http-tests" + }, + { + "id": "http-decoding", + "text": "Malformed, oversized, ambiguous and unknown request inputs are rejected without changing funds.", + "kind": "empirical", + "check": "http-tests" + }, + { + "id": "atomic-withdrawals", + "text": "Concurrent requests through a real local HTTP server spend the initial balance exactly once without overdraft.", + "kind": "empirical", + "check": "http-tests" + }, + { + "id": "overdraft-screen", + "text": "A browser shows withdrawal denied for an overdraft and the full starting balance remains available.", + "kind": "empirical", + "check": "wallet-browser" + } + ], + "checks": [ + { + "id": "withdrawal-proof", + "kind": "gobra", + "files": [ + "examples/httpwallet/policy/policy.go" + ] + }, + { + "id": "http-tests", + "kind": "go-test", + "package": "./examples/httpwallet/app", + "tests": [ + "TestWithdrawalHTTP", + "TestMalformedHTTP", + "TestConcurrentHTTPWithdrawals" + ] + }, + { + "id": "wallet-browser", + "kind": "playwright", + "config": "examples/httpwallet/browser/playwright.config.cjs", + "project": "chromium", + "tests": [ + "wallet.spec.cjs :: rejects an overdraft without debiting the wallet" + ] + } + ], + "trusted_boundary": [ + { + "id": "wallet-sessions", + "assumption": "The configured session mapping identifies the correct account and lock state; demo tokens are public test credentials. Tests exercise known, unknown, locked and ambiguous tokens but cannot establish a real identity provider's truthfulness.", + "check": "http-tests" + }, + { + "id": "wallet-runtime", + "assumption": "Go integer/JSON/HTTP implementations and mutex semantics are trusted. Race and TCP concurrency tests exercise parsing and an atomic in-memory update; they do not prove the runtime or provide durable financial guarantees.", + "check": "http-tests" + } + ], + "mutations": [ + { + "id": "ignore-session-lock", + "requirement": "withdrawal-policy", + "check": "withdrawal-proof", + "file": "examples/httpwallet/policy/policy.go", + "find": "return authenticated && !locked && amount > 0 && amount <= balance", + "replace": "return authenticated && amount > 0 && amount <= balance" + }, + { + "id": "allow-zero-withdrawal", + "requirement": "withdrawal-policy", + "check": "withdrawal-proof", + "file": "examples/httpwallet/policy/policy.go", + "find": "return authenticated && !locked && amount > 0 && amount <= balance", + "replace": "return authenticated && !locked && amount >= 0 && amount <= balance" + }, + { + "id": "allow-overdraft", + "requirement": "withdrawal-policy", + "check": "withdrawal-proof", + "file": "examples/httpwallet/policy/policy.go", + "find": "return authenticated && !locked && amount > 0 && amount <= balance", + "replace": "return authenticated && !locked && amount > 0" + } + ], + "scenarios": [ + { + "id": "browser-overdraft", + "check": "wallet-browser", + "test": "wallet.spec.cjs :: rejects an overdraft without debiting the wallet", + "given": "A demo account starts with a balance of 100", + "when": "The user attempts to withdraw 101 then withdraws 100", + "then": "The browser shows a denial followed by a successful withdrawal with zero remaining", + "requirements": [ + "overdraft-screen" + ], + "purpose": "integration" + } + ] +} diff --git a/examples/httpwallet/browser/playwright.config.cjs b/examples/httpwallet/browser/playwright.config.cjs new file mode 100644 index 0000000..042dfdc --- /dev/null +++ b/examples/httpwallet/browser/playwright.config.cjs @@ -0,0 +1,18 @@ +const path = require('node:path'); + +const origin = 'http://127.0.0.1:38479'; +module.exports = { + testDir: __dirname, + workers: 1, + projects: [{ + name: 'chromium', + use: { browserName: 'chromium', baseURL: origin, screenshot: 'only-on-failure' }, + }], + webServer: { + command: 'go run ./examples/httpwallet/cmd/wallet -listen 127.0.0.1:38479', + cwd: path.resolve(__dirname, '../../..'), + url: origin, + reuseExistingServer: false, + timeout: 120_000, + }, +}; diff --git a/examples/httpwallet/browser/wallet.spec.cjs b/examples/httpwallet/browser/wallet.spec.cjs new file mode 100644 index 0000000..7deb588 --- /dev/null +++ b/examples/httpwallet/browser/wallet.spec.cjs @@ -0,0 +1,14 @@ +const { test, expect } = require('@playwright/test'); + +test('rejects an overdraft without debiting the wallet', async ({ page }) => { + await page.goto('/'); + await page.getByLabel('Amount').fill('101'); + await page.getByRole('button', { name: 'Withdraw' }).click(); + await expect(page.getByRole('status')).toHaveText('Withdrawal denied.'); + + // Withdrawing the entire starting balance proves the rejected attempt did + // not debit it on this path. The success message uses the server's balance. + await page.getByLabel('Amount').fill('100'); + await page.getByRole('button', { name: 'Withdraw' }).click(); + await expect(page.getByRole('status')).toHaveText('Remaining balance: 0'); +}); diff --git a/examples/httpwallet/cmd/wallet/main.go b/examples/httpwallet/cmd/wallet/main.go index 3a76cee..ddda50b 100644 --- a/examples/httpwallet/cmd/wallet/main.go +++ b/examples/httpwallet/cmd/wallet/main.go @@ -4,6 +4,7 @@ package main import ( "context" + _ "embed" "flag" "log" "net/http" @@ -15,6 +16,9 @@ import ( "github.com/cruskell/pdd-kit-go/examples/httpwallet/app" ) +//go:embed wallet.html +var walletPage []byte + func main() { address := flag.String("listen", "127.0.0.1:8080", "HTTP listen address") flag.Parse() @@ -22,7 +26,16 @@ func main() { "demo-alice": {Account: "alice"}, "demo-locked": {Account: "locked", Locked: true}, }, map[string]int{"alice": 100, "locked": 100}) - server := &http.Server{Addr: *address, Handler: handler, ReadHeaderTimeout: 5 * time.Second, + demo := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/" && r.Method == http.MethodGet { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.Header().Set("Cache-Control", "no-store") + _, _ = w.Write(walletPage) + return + } + handler.ServeHTTP(w, r) + }) + server := &http.Server{Addr: *address, Handler: demo, ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, IdleTimeout: 30 * time.Second, MaxHeaderBytes: 8192} ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer stop() diff --git a/examples/httpwallet/cmd/wallet/wallet.html b/examples/httpwallet/cmd/wallet/wallet.html new file mode 100644 index 0000000..cff2f40 --- /dev/null +++ b/examples/httpwallet/cmd/wallet/wallet.html @@ -0,0 +1,52 @@ + + +
+ + +{{.Draft.Plan.Intent}}
Plan {{.Draft.PlanID}} · Draft {{.Draft.Digest}}Human decisions → independent intent and guarantee reviews → human approval → implementation → machine verification → advisory gap review → PR
{{if .Draft.ValidationError}}Before approval: {{.Draft.ValidationError}}
{{end}} -{{.Context}}
{{.File}} {{.Function}} · {{.ID}}{{range .Options}}{{.ID}}: {{.Label}}{{if .Recommended}} (recommended){{end}} — {{.Consequence}}
{{end}}Selected: {{.Selected}} · Reason: {{.Rationale}}
No decision cards recorded.
{{end}} -{{.UserWords}}
Requirements: {{range .Requirements}}{{.}} {{end}}
Decisions: {{range .Decisions}}{{.}} {{end}}
| Requirement | Guarantee | Evidence |
|---|---|---|
| {{.ID}} | {{.Text}}{{.Ensures}} | {{.Kind}} · {{.Check}} {{.File}} {{.Function}} |
Approval state: {{.Approval.State}} — {{.Approval.Message}}
Plan digest for explicit approval: {{.Digest}}{{range .Bundle.Sources}}{{.}}{{end}}{{if .Definitions}}{{printf "%s" .Definitions}}{{.Owner}} · {{.Annotation}}
{{end}}{{.Assumption}}
Check: {{.Check}} · Affects: {{range .Affects}}{{.}} {{end}}
{{range .Clauses}}{{.ID}}: {{.Text}} · If false: {{.Impact}} · Test {{.Test}}
{{end}}Given {{.Given}}
When {{.When}}
Then {{.Then}}
{{.Result.Summary}}
{{range .Result.Findings}}{{.Severity}}: {{.Text}}
{{end}}Invocation {{.Invocation}} · {{.Driver}}Model opinions are advisory; they do not establish formal correctness or authenticate a human reviewer.
-{{with .Workflow}}| Task | Depends on | Evidence status |
|---|---|---|
| {{.ID}} ({{.Kind}}) | {{range .DependsOn}}{{.}} {{end}} | {{.Status}} |
Machine receipt current: {{.MachineCurrent}} · successful: {{.MachineSuccess}} · ready for PR: {{.ReadyForPR}}
{{range .Gaps}}{{.}}
{{end}}{{with .GapReview}}Advisory gap review: {{.Result.Status}} — {{.Result.Summary}}
{{end}}Potential redundant formal regression scenarios (manual review only): {{range .PruneCandidates}}{{.}} {{end}}
{{end}} -{{.}}
{{end}}{{.JSON}}{{.Draft.Plan.Intent}}
+ Plan {{.Draft.PlanID}} · Draft {{.Draft.Digest}} +Before approval: {{.Draft.ValidationError}}
{{end}} +{{with .Evidence}} +Receipt validated against the source and approval when this report was generated.
+ Completed {{.FinishedAt}} · Source{{.SourceDigest}}{{if .GitCommit}} · Commit {{.GitCommit}}{{end}}
+ {{if .ReceiptURL}}{{end}}
+No current evidence
+ {{with .Workflow}}{{range .Gaps}}{{.}}
{{end}}{{end}} +{{.UserWords}}{{end}} +
Requirements: {{range .Requirements}}{{.}} {{end}}
| Requirement | Guarantee | Result |
|---|---|---|
| {{.ID}} | {{.Text}}{{if .Ensures}}{{.Ensures}}{{end}}{{if .File}}{{.File}} · {{.Function}}{{end}} |
+ {{if $.Evidence}}{{with index $.Evidence.Verdicts .ID}}{{.}}{{end}}{{else}}Pending{{end}}
+ {{.Kind}} · {{if $.Evidence}}{{.Check}}{{else}}{{.Check}}{{end}} |
| Check | Result | Evidence |
|---|---|---|
| {{.Check}} {{.Backend}} · {{.Kind}} |
+ {{.Execution.Status}} {{.Execution.DurationMS}} ms{{if .Execution.Detail}} {{.Execution.Detail}} {{end}} |
+ {{if .LogURL}}Execution log{{end}}
+ {{range .Files}} {{if .URL}}{{.Label}}{{else}}{{.Label}}{{end}}{{end}} + {{if .Tests}} Planned tests
Depends on {{range .Dependencies}}{{.}} {{end}} {{end}} |
A killed mutation was rejected on the intended postcondition.
+| Mutation | Target | Result | Evidence |
|---|---|---|---|
| {{.ID}} | {{.Requirement}} | {{.Status}}{{if .Execution.Detail}} {{.Execution.Detail}}{{end}} | {{if .LogURL}}Verifier log{{end}} |
{{.Assumption}}
+ Check {{if $.Evidence}}{{.Check}}{{else}}{{.Check}}{{end}}{{if .Affects}} · Affects {{range .Affects}}{{.}} {{end}}{{end}} + {{range .Clauses}}{{.ID}} {{.Text}} · If false: {{.Impact}} · Test {{.Test}}
{{end}} + {{end}} +{{.Context}}
{{.File}} {{.Function}} · {{.ID}} + {{range .Options}}{{.Label}}{{if .Recommended}} (recommended){{end}} · {{.Consequence}}
{{end}} + {{if .Selected}}Selected {{.Selected}} · {{.Rationale}}
{{else}}Awaiting decision
{{end}}Given {{.Given}}
When {{.When}}
Then {{.Then}}
Approval {{.Approval.State}}{{with .Approval.Message}} · {{.}}{{end}}
+ Plan digest{{.Digest}}
+ {{range .Bundle.Sources}}{{.}}{{end}}{{if .Definitions}}{{printf "%s" .Definitions}}{{end}}{{range .Bindings}}{{.Owner}} · {{.Annotation}}
{{end}}{{.Result.Summary}}
{{range .Result.Findings}}{{.Severity}} · {{.Text}}
{{end}}{{.Invocation}} · {{.Driver}}Advisory gap review · {{.Result.Status}} · {{.Result.Summary}}
{{end}} + {{if $.Evidence}}{{range .Gaps}}{{.}}
{{end}}{{end}} + {{if .PruneCandidates}}Formal regression scenarios for manual review · {{range .PruneCandidates}}{{.}} {{end}}
{{end}} + {{end}} + {{if .Draft.Plan.NonGoals}}{{.JSON}}