diff --git a/.orly/orly.json b/.orly/orly.json index a768812e..4f30bc73 100644 --- a/.orly/orly.json +++ b/.orly/orly.json @@ -1,6 +1,6 @@ { "schema_version": 1, - "orly_version": "0.60.4", + "orly_version": "0.70.0", "packs": [ "domain.auth", "domain.changelog", diff --git a/AGENTS.md b/AGENTS.md index f2999187..1131824f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -136,7 +136,6 @@ Inspect prerequisites first and report unrun commands. Reuse requires explicit o ## SOUL.md — Aiwa's working notes > Working notes for Aiwa: how Indy decides. `AGENTS.md` carries the rules. -> Re-read when padding or burying an answer. ### Reply shape diff --git a/README.md b/README.md index 0fabe8ae..18a444ca 100644 --- a/README.md +++ b/README.md @@ -36,11 +36,14 @@ Declare the commands your repository already has in `.orly/orly.json`; at least |---|---| | `gate work` | configuration and the `conform` command | | `gate verify` | documentation and the non-test `verify.*` commands | -| `gate pr` | branch, clean pushed revision, documentation and every `verify.*` command | +| `gate pr` | branch, clean pushed revision, documentation, coupled paths and every `verify.*` command | The default `gate` runs `work` then `pr`, with fast verification once. Checks run fresh unless reviewed policies explicitly permit evidence reuse. Only the owner records an override. +`orly proof` records that a new test failed with its change reverted, and `gate pr` names new tests without such a record. +`orly note` adds an owner's ruling, dated, to the active spec. + [Architecture](docs/ORLY_ARCHITECTURE.md) covers limits, opt-in evidence reuse and overrides. ## Burst lanes @@ -49,7 +52,7 @@ Only the owner records an override. bunx --bun @agentsfleet/orly burst acceptance --provider aws-spot ``` -Slow `burst.` lanes run on a machine rented for the run, on AWS or E2E Networks. +Slow `burst.` lanes run on a machine rented for the run, on AWS or E2E Networks, reached over the caller's Tailscale tailnet. No gate runs them; [Burst lanes](docs/BURST.md) covers setup and costs. ## Update diff --git a/SOUL.md b/SOUL.md index f52f4b30..68c4f586 100644 --- a/SOUL.md +++ b/SOUL.md @@ -2,7 +2,6 @@ # SOUL.md — Aiwa's working notes > Working notes for Aiwa: how Indy decides. `AGENTS.md` carries the rules. -> Re-read when padding or burying an answer. ## Reply shape diff --git a/docs/BURST.md b/docs/BURST.md index 79550d77..82d20c74 100644 --- a/docs/BURST.md +++ b/docs/BURST.md @@ -1,8 +1,8 @@ --- type: how-to audience: operator -verified: 2026-11-18 -product_version: 0.60.0 +verified: 2026-11-22 +product_version: 0.70.0 executable: false --- @@ -16,19 +16,24 @@ Amazon Web Services (AWS) Spot and E2E Networks start one machine per lane, in p The gates never run `burst.*` commands, because every cloud run costs money. ```text -caller rented machine - 1. read burst.secrets (environment or op) +caller (on a tailnet) rented machine + 1. check `tailscale status`, read burst.secrets (environment or op) 2. bundle the ref with git - 3. create the machine ------- cloud API ---> boots the newest snapshot - 4. ssh: the commits it lacks SSH ---------> /tmp/orly-burst.bundle - 5. ssh: bash -s ------------- SSH ---------> setup, then secrets, then lane - [lane] log lines <-------- SSH ---------- standard output and errors - 6. ssh: tar of results <----- SSH ---------- burst.artifacts that exist - 7. delete the machine, the key and the security group + 3. mint a single-use Tailscale key - Tailscale API + 4. create the machine ------- cloud API ---> boots, runs the boot script: + installs Tailscale, joins the tailnet + 5. delete the Tailscale key once the machine has joined + 6. ssh over the tailnet: the commits it lacks, then the job, started detached + [lane] log lines <-------- SSH ---------- the job's log, from the last byte read + a lost session is reconnected, and the log resumes where it stopped + 7. ssh: the job's exit code and the tar of results + 8. log the machine out of the tailnet, delete it, the key pair and the security group ``` -One transport serves both clouds: Secure Shell (SSH) with a key pair made for the run. -Nothing is staged in object storage, and no secret is stored in the cloud. +One transport serves both clouds: Secure Shell (SSH) with a key pair made for the run, carried by the caller's tailnet. +No cloud firewall opens port 22, and nothing is staged in object storage. + +The only secret stored in the cloud is a machine's Tailscale key, in its boot script. ## Before you begin @@ -57,7 +62,7 @@ Declare the lanes as `burst.` commands, and the `burst` object beside them | `burst.` command | One lane. A name has 1 to 24 lowercase letters, digits or hyphens. | none | | `burst.setup` | Runs as root before every lane and snapshot warm-up, with no secret. Keep it fast on a warm machine. | none | | `burst.warm` | Runs after setup when a snapshot is captured, with no secret, to fill build caches. | none | -| `burst.secrets` | Environment variable name to an `op://` reference, read on the caller. | none | +| `burst.secrets` | Environment variable name to an `op://` reference, read on the caller. A name may not be `OP_SERVICE_ACCOUNT_TOKEN` or start with `TS_OAUTH_`, `E2E_` or `AWS_`. | none | | `burst.artifacts` | Paths below the checkout that a lane brings back. A missing path is skipped. | none | | `burst.directories` | Variables naming directories on the caller, copied to each lane's machine over SSH. | none | | `burst.e2e.location` | TIR location. | `Delhi` | @@ -71,16 +76,44 @@ Declare the lanes as `burst.` commands, and the `burst` object beside them A lane starts from the repository's newest ready snapshot of the configured image; `--no-snapshot` starts it from the image itself. orly reads this object from the ref it runs, so a branch carries its own placement. -Each machine installs Git, curl, unzip, Docker and Docker Compose on its first boot, and runs every lane with `CI=1`. -The caller needs `git`, `ssh`, `ssh-keygen`, `tar` and the provider's credentials below. +Each machine installs Tailscale, Git, curl, unzip, Docker and Docker Compose on its first boot, and runs every lane with `CI=1`. +The caller needs `git`, `ssh`, `ssh-keygen`, `tar`, `tailscale`, the Tailscale credential below and the provider's credentials. A secret already in the caller's environment is used as it is; any other is read with `op read`. > [!IMPORTANT] -> The caller must open outbound SSH on port 22, and keep the same public address for the whole run. -> Sessions behind an HTTP-only proxy start the repository's Continuous Integration (CI) workflow instead, which runs `orly burst`. +> The caller must be on a tailnet, with `tailscale status` reporting it online, or `orly burst` refuses to start. +> The caller may change network mid-run: the lane keeps running on its machine, and orly reconnects to it. orly accepts a fresh machine's host key on first connection, into the run's own `known_hosts` file only. -Run lanes from networks you trust, since someone intercepting that first connection could stand in for the machine. +That connection travels inside the tailnet's encrypted tunnel to the node the run's key created. + +### One-time setup for Tailscale + +Every run's machines join the caller's tailnet as ephemeral nodes tagged `tag:orly-burst`. + +1. In the tailnet policy, declare the tag and let members reach its SSH port: + + ```json + { + "tagOwners": {"tag:orly-burst": ["autogroup:admin"]}, + "grants": [{"src": ["autogroup:member"], "dst": ["tag:orly-burst"], "ip": ["tcp:22"]}] + } + ``` + +2. Create an OAuth trust credential with the `auth_keys` write scope whose only tag is `tag:orly-burst`. + orly mints every key with exactly that tag set, and a credential mints no other. +3. Store its client ID and secret as `TS_OAUTH_CLIENT_ID` and `TS_OAUTH_CLIENT_SECRET` on the caller. + +> [!WARNING] +> `tag:orly-burst` must appear in no rule's `src`, and the policy's default allow-all grant must go. +> Never reuse a CI job's credential or tag set: a key carrying both tags reaches whatever the CI tag reaches. +> Either mistake lets every burst machine reach devices on the tailnet, CI runners and laptops included. + +Each machine gets its own key: single use, ephemeral, preauthorized and valid for 10 minutes. +orly deletes it as soon as the machine has joined, or failed to. + +A node logs out before its machine is deleted, and an ephemeral node that missed that leaves the tailnet once offline. +Each run names its nodes `orly-burst---`, so a node left behind can be found and removed in the admin console. ### One-time setup for AWS Spot @@ -106,7 +139,7 @@ The launcher's policy creates and removes only resources tagged `owner=agent`: {"Effect": "Allow", "Action": "ec2:CreateSecurityGroup", "Resource": "arn:aws:ec2:*:*:vpc/*"}, {"Effect": "Allow", "Action": "ec2:CreateTags", "Resource": "*", "Condition": {"StringEquals": {"ec2:CreateAction": ["RunInstances", "ImportKeyPair", "CreateSecurityGroup", "CreateImage"]}}}, - {"Effect": "Allow", "Action": ["ec2:TerminateInstances", "ec2:StopInstances", "ec2:AuthorizeSecurityGroupIngress", + {"Effect": "Allow", "Action": ["ec2:TerminateInstances", "ec2:StopInstances", "ec2:DeleteSecurityGroup", "ec2:DeleteKeyPair", "ec2:DeregisterImage", "ec2:DeleteSnapshot"], "Resource": "*", "Condition": {"StringEquals": {"aws:ResourceTag/owner": "agent"}}}, {"Effect": "Allow", "Action": "ec2:CreateImage", "Resource": "arn:aws:ec2:*:*:instance/*", @@ -131,6 +164,13 @@ The `e2e` provider runs TIR virtual machines, reached as root over SSH. MyAccount keys do not work. Each run saves its public key and a security group named `orly-burst-` in TIR, and deletes both after. +TIR refuses a group with no inbound rule, so its one inbound rule admits UDP port 41641, Tailscale's direct-connection port. +No rule opens SSH. + +TIR VMs take no user data, so each VM boots a start script of its own, named `obs---`, which joins it to the tailnet. +orly deletes the script once the VM is gone. +A run's teardown also deletes any script left by a run that began more than 25 hours ago. + ### Settings These variables shape a run, not where it runs: @@ -146,7 +186,8 @@ orly's own limits, which no setting changes: | Wait | Limit | |---|---| -| A machine booting, then answering SSH | 10 minutes each | +| A machine booting, joining the tailnet, then answering SSH | 10 minutes each | +| Reconnecting to a lane whose session was lost | 10 minutes since the log last grew, or the run's deadline when sooner | | One request to TIR or EC2 | 60 seconds | | TIR retries of a busy answer (429, 5xx, timeout), creates excepted | 10, backing off up to `ORLY_BURST_POLL_SECONDS` | | EC2 attempts of one call | 10 | @@ -228,7 +269,7 @@ A local orly checkout runs the same way: `~/Projects/orly/bin/orly burst accepta ### Run a lane from a CI job -A session that cannot open SSH starts a workflow like this one: +A session that cannot run Tailscale starts a workflow like this one, on a runner that joins the tailnet first: ```yaml name: burst @@ -255,15 +296,22 @@ jobs: - if: inputs.provider == 'aws-spot' uses: aws-actions/configure-aws-credentials@v4 with: {role-to-assume: "", aws-region: ap-south-1} - - run: bunx --bun @agentsfleet/orly@0.60.0 burst "$LANE" --provider "$PROVIDER" --ref "$GITHUB_REF_NAME" + - uses: tailscale/github-action@v3 + with: {oauth-client-id: "${{ secrets.TS_CI_OAUTH_CLIENT_ID }}", oauth-secret: "${{ secrets.TS_CI_OAUTH_SECRET }}", tags: "tag:ci"} + - run: bunx --bun @agentsfleet/orly@0.70.0 burst "$LANE" --provider "$PROVIDER" --ref "$GITHUB_REF_NAME" env: LANE: ${{ inputs.lane }} PROVIDER: ${{ inputs.provider }} E2E_API_KEY: ${{ secrets.E2E_API_KEY }} E2E_AUTH_TOKEN: ${{ secrets.E2E_AUTH_TOKEN }} E2E_PROJECT_ID: ${{ vars.E2E_PROJECT_ID }} + TS_OAUTH_CLIENT_ID: ${{ secrets.TS_OAUTH_CLIENT_ID }} + TS_OAUTH_CLIENT_SECRET: ${{ secrets.TS_OAUTH_CLIENT_SECRET }} ``` +The runner joins as `tag:ci` with its own credential, and the lane's machines as `tag:orly-burst` with theirs. +The policy must let `tag:ci` reach `tag:orly-burst` on port 22. + `` carries the launcher policy and trusts the repository's GitHub identity. A full clone matters, because a shallow clone cannot be bundled. @@ -276,6 +324,8 @@ orly burst: lane= provider= machine= minutes= c ``` Only a number after `exit=` is evidence about the code; `interrupted`, `deadline`, `cancelled`, `unlaunched` and `not_run` mean the lane never finished. +The number is the one the machine wrote when the lane's job ended, never the exit of an SSH session. + The evidence directory holds `run.log` and the declared results the machine had. Setup and warm never see `burst.secrets` or the cloud credentials, and a cloud lane gets only its declared secrets. @@ -284,18 +334,25 @@ Setup and warm never see `burst.secrets` or the cloud credentials, and a cloud l - **`set E2E_AUTH_TOKEN for this provider`**: the variable is missing or empty. Export it and run again. - **`orly burst no longer reads `**: placement moved to `.orly/orly.json`. Set the key the message names, and unset the variable. - **`could not read the secret for `**: `op` is not signed in, or the reference is wrong. -- **`this machine's address changed from to `**: the caller changed network after launch. Run the lane again from the new network. -- **`the deadline passed while waiting for SSH`**: port 22 is blocked between the caller and the machine. Run the lane from a CI job instead. -- **`exit=interrupted` on AWS**: AWS took the Spot instance back, or the session dropped. Run it again, or set `ORLY_BURST_MARKET=on-demand`. +- **`this machine is not on a tailnet`**: run `tailscale up` on the caller, and run again. +- **`Tailscale POST /api/v2/oauth/token answered 401`**: `TS_OAUTH_CLIENT_ID` or `TS_OAUTH_CLIENT_SECRET` is wrong. +- **`Tailscale POST /api/v2/tailnet/-/keys answered 400`**: the credential's tags are not exactly `tag:orly-burst`. +- **`the deadline passed while waiting for to join the tailnet`**: the machine could not install Tailscale or reach it. The lane's machine is deleted; run it again. +- **`the deadline passed while waiting for SSH`**: the tailnet policy does not let the caller reach `tag:orly-burst` on port 22. +- **`could not reconnect to
`**: the caller stayed off the tailnet for 10 minutes. Run the lane again. +- **`exit=interrupted` on AWS**: AWS took the Spot instance back. Run it again, or set `ORLY_BURST_MARKET=on-demand`. - **`exit=not_run`**: the machine's preparation, the checkout or `burst.setup` failed before the lane started. The lane's `run.log` names the step. - **`run-instances refused`**: the launcher policy lacks the permission the message names. - **`Access Denied Read..` from E2E**: the keys belong to MyAccount. Create a TIR API token for the project instead. ## Remove or undo -A run deletes its machines, key, security group, bundle and private key, even when a lane fails, on Ctrl-C, SIGTERM or a closed terminal. +A run deletes its machines and everything it made for them, even when a lane fails, on Ctrl-C, SIGTERM or a closed terminal. +That is the Tailscale keys, the key pair, the security group, the start scripts, the bundle and the private key. A VM whose create reply TIR lost is found by name and deleted too. + A process killed outright, such as by a CI runner, leaves them behind; they are tagged or labelled `orly-burst` and safe to delete. +Its Tailscale keys expire 10 minutes after they were minted, and its ephemeral nodes leave the tailnet once their machines are deleted or go offline. **Deleting a snapshot is permanent**, and the next run starts cold from the image. A snapshot's name ends in a digest of its base image, so changing `burst.e2e.image` or `burst.aws.image` starts lanes cold until the next capture. diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 79e7c339..ac2b4177 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -1,5 +1,20 @@ # Changelog +## 0.70.0 (2026-11-22) + +Burst machines join the caller's tailnet, and a lane survives the caller changing network. `orly gate pr` reuses a run made before the commit, and checks coupled paths and new tests. + +- **Tailscale** — `orly burst` now requires the caller on a tailnet and a Tailscale OAuth trust credential in `TS_OAUTH_CLIENT_ID` and `TS_OAUTH_CLIENT_SECRET`, whose only tag is `tag:orly-burst`. Each machine joins with its own single-use key, deleted once it has joined. +- **No public SSH** — No AWS or E2E security group opens port 22; SSH runs over the tailnet, and the caller-address check is gone. +- **Detached lanes** — A lane runs detached on its machine. A lost session reconnects for up to 10 minutes, and the log resumes where it stopped. The lane's `exit=` is the code the machine wrote. +- **E2E** — Each VM boots a TIR start script of its own, deleted with the VM. +- **Reuse** — Evidence is keyed to tracked content, not the revision. A lane run before the commit is reused once that tree is committed and pushed. +- **Coupled paths** — `coupled` path groups in `.orly/orly.json` fail `gate pr` on a one-sided change. +- **Proofs** — `orly proof` records that a new test failed with its change reverted, and `gate pr` names new tests without such a record. +- **Notes** — `orly note` adds an owner's ruling, dated, to the active spec. +- **Spec review** — `orly-spec` runs the Elephant-Goldfish Model (EGM) reviewers itself and applies their accepted findings to the spec. +- **Upgrade** — Follow the Tailscale setup in [Burst lanes](BURST.md#one-time-setup-for-tailscale) before the next run, then run `bunx --bun @agentsfleet/orly@0.70.0 update` after this version is published. Drop any `reuse` policy whose command reads Git history; evidence from earlier releases runs fresh. + ## 0.60.4 (2026-11-20) A release publishes without rerunning the Pull Request's gates. diff --git a/docs/ORLY_ARCHITECTURE.md b/docs/ORLY_ARCHITECTURE.md index 309cb27c..bb38cff5 100644 --- a/docs/ORLY_ARCHITECTURE.md +++ b/docs/ORLY_ARCHITECTURE.md @@ -31,7 +31,7 @@ The `pr` group includes fast verification, so those checks run once. Invoke `orl |---|---| | `work` | repository configuration and the declared `conform` command | | `verify` | documentation checks and the non-test `verify.*` commands | -| `pr` | branch, clean tree, exact pushed revision, documentation, and every declared `verify.*` command | +| `pr` | branch, clean tree, exact pushed revision, documentation, coupled paths, and every declared `verify.*` command | Missing comparison history blocks the PR gate; fetch the target branch before retrying. Every criterion reads an exit code or a file. Prerequisite failures block commands, and blocked or unrun groups never count as passes. @@ -39,10 +39,25 @@ Every criterion reads an exit code or a file. Prerequisite failures block comman - **Slow lanes are conditional.** `verify.integration` and `verify.memory` run when the diff carries code or build inputs, including executable entrypoints, Makefiles and lockfiles. - **The docs gate follows the diff.** A change under `surfaces.user` with no change under `surfaces.docs` is red; tests and specs never count. - **`docs.language`** rejects mechanical language findings in changed Markdown and MDX paragraphs, and template slots left in a changed spec. +- **Coupled paths change together.** A branch that changes a path under a `coupled` group's `when` prefix and none under its `then` prefixes fails `paths.coupled`. +- **New tests carry fail-before proofs.** `tests.proven` counts new tests without one and names up to three. It reads TypeScript, JavaScript, Rust, Go and Python, and never fails the gate. - **A worktree is its repository.** Commands run in the worktree, which resolves to its primary checkout through Git's shared object store. `burst.*` lanes rent machines by the hour, so no gate runs them; `orly burst` runs them on request ([Burst lanes](BURST.md)). +## Proofs and notes + +`orly proof --test -- ` runs the command while the code a new test covers is reverted or mutated. +It keeps a signed record only when the command fails and an output line reports that test failing, so a build error proves nothing. +The record holds the command, the failing line and the code diff from `HEAD`, beside the verification evidence. + +A test counts as new when the branch adds its declaration line; a changed body under an old declaration is not seen. +A missing proof is reported and never fails `gate pr`, because records live beneath one worktree's Git metadata. +A verdict must not depend on private history that another clone lacks. + +`orly note ""` appends the owner's verbatim words, with the time, to the end of the active spec's Discovery. +The owner's name is the `owner` of a selected persona pack in `registry.json`, and `--spec` picks a spec when several are active. + ## Overrides `orly override --reason ` writes an empty commit carrying an `Orly-Override: ()` trailer. @@ -58,7 +73,8 @@ A matching trailer turns a failed criterion into `overridden`; blocked or unrun "schema_version": 1, "commands": { "conform": [["make", "conform"]], "verify.unit": [["make", "test-unit-all"]] }, "limits": { "verify.unit": { "timeout_ms": 1800000, "output_bytes": 67108864 } }, - "surfaces": { "user": ["src/", "cli/src/"], "docs": ["docs/"] } + "surfaces": { "user": ["src/", "cli/src/"], "docs": ["docs/"] }, + "coupled": [{ "when": ["src/wire/"], "then": ["src/wire/VERSION"] }] } ``` @@ -72,11 +88,13 @@ A command over either limit is stopped with its process group, and fails with it ## Verification evidence Checks run fresh. `gate pr --reuse-verification` may reuse a lane's last pass only when `reuse.` declares it hermetic, with a maximum age, toolchain probes and any extra inputs. -Live integration and memory lanes always run fresh. +Live integration and memory lanes always run fresh, and a hermetic command reads no Git history. -By default, evidence binds every tracked file and the exact revision. An optional `tracked_inputs` list selects tracked files or directory prefixes for cross-revision reuse. +Evidence binds tracked content, never a revision: every tracked path's mode and working-tree bytes. +A run before the commit, under `gate pr --accept-dirty`, or before the push, under `gate verify`, is reused once that tree is committed, clean and pushed. -The selection must cover every tracked dependency; commands that read Git history cannot use it. Selectors are literal relative paths, and every selector must match tracked content. +An optional `tracked_inputs` list narrows the content to tracked files or directory prefixes. +The selection must cover every tracked dependency. Selectors are literal relative paths, and every selector must match tracked content. Both modes bind the merge base, commands, limits, configuration, environment, engine and toolchain. Extra ignored dependencies belong in `inputs`; raw environment values are never stored. @@ -98,11 +116,13 @@ This example needs review against the consuming repository's actual dependencies Source is observed before the first toolchain probes and after the last probes, even when a result is reused. Scope selection uses the existing full snapshot; overlapping paths are hashed once within each input collection. -Missing, dirty, unpushed or symlinked inputs disable reuse, and inputs must not change while a check runs. +An untracked file, a symlink or a missing input keeps a run from recording evidence. +Only a clean tree at the pushed revision accepts evidence, and inputs must not change while a check runs. One attempt per worktree holds a private lock, and only the latest attempt can be reused. A failed attempt or one without a valid completion record never falls back to an older pass. -Signed records name the original run revision and the revision accepting it. Reuse preserves the original output, run time and age; older record formats run fresh. +Signed records name the original run revision, whether it carried uncommitted changes, and the revision accepting it. +Reuse preserves the original output, run time and age; records from before Nov 26, 2026 bind a revision and run fresh. An interrupted attempt keeps its lock: after the old workload has stopped, delete the private evidence directory beneath Git metadata and run fresh. Records protect local integrity only, not against another process running as the same user. @@ -113,6 +133,9 @@ Rules live in `standards/`, one page per standard, and packs select standards th Each rule has an identifier, a statement, and the fields Applies to, Checked by, Bad, Good and Why. Three skills carry the steps: `orly-spec`, `orly-build` and `orly-ship`, plus `orly-burst` for paid lanes. +The Elephant-Goldfish Model (EGM) review skill refuses model invocation, so `orly-spec` dispatches its reviewers itself, stage by stage, each with no conversation. +Accepted findings change the spec, and Discovery keeps the owner's rulings; no review file enters the repository. + `orly-standards-reviewer` judges a diff against the standards with no session history, and reports only findings tied to a rule and a changed line. Skills announce their stage and state, then report the outcome and next action. After publishing, `orly-ship` proposes evidenced lessons and asks for any approval still needed. @@ -126,5 +149,5 @@ A rule change edits its standard; a new rule takes a new identifier, and `orly v Every commit runs `orly gate work`, which runs `orly verify`, and a push runs gitleaks. CI runs `make audit`, `make install-evals` and the unit suite with coverage on every pull request. -`orly doctor` checks that every agent runtime on the machine has gstack and the Elephant-Goldfish Model (EGM), and prints the install command for a missing one. +`orly doctor` checks that every agent runtime on the machine has gstack and EGM, and prints the install command for a missing one. A machine with no agent runtime, such as a CI runner, skips that check. Orly collects no usage telemetry. diff --git a/docs/v2/done/M17_001_P1_CLI_DOCS_GOV_SKILL_SCOPED_VERIFICATION_REUSE.md b/docs/v2/done/M17_001_P1_CLI_DOCS_GOV_SKILL_SCOPED_VERIFICATION_REUSE.md index 0718df98..c2e10d8a 100644 --- a/docs/v2/done/M17_001_P1_CLI_DOCS_GOV_SKILL_SCOPED_VERIFICATION_REUSE.md +++ b/docs/v2/done/M17_001_P1_CLI_DOCS_GOV_SKILL_SCOPED_VERIFICATION_REUSE.md @@ -74,7 +74,7 @@ ship -> publish PR -> summarize evidenced lessons -> ask owner -> approved sourc | `core/operating-model.md`, `SOUL.md`, generated `AGENTS.md` | EDIT | Stage start, outcome and next action | | `skills/orly-ship/SKILL.md` | EDIT | Evidence-backed learning proposal and owner approval | | `README.md`, `docs/ORLY_ARCHITECTURE.md`, `docs/architecture/installation.md`, `standards/tests.md`, `src/cli_help.ts`, `llms.txt` | EDIT | Actual behavior, constraints and upgrade instructions | -| `docs/v2/evidence/M17_REPOSITORY_REVIEW.md` | CREATE | Review inventory, findings, dispositions and measurements | +| The repository review record | CREATE | Review inventory, findings, dispositions and measurements; removed on Nov 26, 2026 at the owner's direction, and Git history keeps it | | `package.json`, `.orly/orly.json` | EDIT | 0.50.0 version sources | | `docs/CHANGELOG.md` | EDIT | User-visible 0.50.0 changes and upgrade requirements | @@ -248,4 +248,4 @@ All Dimensions are done. The repaired pushed gate at `414e270` passed every crit Packed installation passed all 24 cases. Final review and the gate for this documentation closure are recorded separately in the PR. The size failure was repaired without raising the limit. The two process failures reproduce at the exact base and pass under normal orphan reaping. -[Repository review evidence](../evidence/M17_REPOSITORY_REVIEW.md) records the tests, environment diagnosis and review findings. +A repository review record held the tests, environment diagnosis and review findings until Nov 26, 2026, when the owner ruled review records out of the tree; Git history keeps it. diff --git a/docs/v2/done/M18_001_P2_CLI_DOCS_GOV_SKILL_GATE_PROVES_MORE_RERUNS_LESS.md b/docs/v2/done/M18_001_P2_CLI_DOCS_GOV_SKILL_GATE_PROVES_MORE_RERUNS_LESS.md new file mode 100644 index 00000000..749ee395 --- /dev/null +++ b/docs/v2/done/M18_001_P2_CLI_DOCS_GOV_SKILL_GATE_PROVES_MORE_RERUNS_LESS.md @@ -0,0 +1,217 @@ +# M18_001: The PR gate proves more and reruns less + +**Prototype:** v2.0.0 +**Milestone:** M18 +**Workstream:** 001 +**Date:** Nov 26, 2026 +**Status:** DONE +**Priority:** P2, harness tooling; every consumer's agent pays for reruns and missed couplings +**Categories:** CLI, DOCS, GOV, SKILL +**Batch:** B1, folded into the open 0.70.0 Pull Request #90 at the owner's request +**Depends on:** M17_001, scoped reuse and signed evidence +**Provenance:** agent-generated from the owner's approved list of improvements (Nov 26, 2026) +**Canonical architecture:** `docs/ORLY_ARCHITECTURE.md`, Gates and Verification evidence + +## Overview + +**Goal (testable):** A lane run on an uncommitted tree is reused once that tree is committed and pushed, a branch that changes one side of a coupled pair fails `orly gate pr`, and new tests without a fail-before proof are named. + +**Problem:** In an `agentsfleet` session on Nov 26, 2026, a lane run before the commit counted for nothing, so `orly gate pr` repeated about 40 minutes of identical work. A wire change shipped without its protocol version file, caught only by a human. A new test passed for the wrong reason, because every row shared one timestamp. `orly-spec` asked for `egm-review`, which an agent cannot start, so the review never ran. Owner rulings lived in a scratch file and were copied into specs by hand. + +**Solution summary:** Key reuse to tracked content instead of the revision; add `coupled` path groups to `.orly/orly.json`, checked at `gate pr`; add `orly proof`, which runs a test with its change reverted and keeps a signed record only when that test is reported failing; report new tests without one; add `orly note`; make `orly-spec` dispatch the EGM reviewers itself. The version stays 0.70.0. + +**Design flow:** + +```text +edit -> gate pr --accept-dirty -> lane runs -> evidence keyed to (base, tracked content) +commit + push -> gate pr --reuse-verification -> same content, clean, pushed -> reused + +branch diff -> coupled {when, then} -> a `when` path changed, no `then` path -> red +branch diff -> added test declarations -> signed proof per test? -> reported list +revert code -> orly proof FILE --test NAME -- CMD -> CMD fails, a line reports NAME failing -> record +orly note "QUOTE" -> persona pack owner -> one active spec -> end of Discovery +orly-spec step 6 -> stages 5..9 -> egm:* reviewers, no context -> evidence file -> fixes +``` + +## PR Intent & comprehension handshake + +- **PR title (eventual):** unchanged, Pull Request #90 carries 0.70.0 +- **Intent:** An agent stops repeating verified work and stops shipping what a mechanical check could have caught. +- **Authoring handshake:** ASSUMPTIONS I'M MAKING: 1. "Hermetic" now also means the command reads no Git history, because evidence outlives the commit it ran beside. 2. `--accept-dirty` may publish evidence, because evidence binds content and only a clean pushed tree accepts it. 3. A coupling runs one way. 4. A missing proof is reported, never a failure. 5. The owner name comes from the persona pack, as data in `registry.json`. +- **Implementer handshake:** recorded in the Pull Request Session Notes. + +## Implementing agent — read these first + +1. `src/verification_identity.ts` — the identity that binds evidence. +2. `src/criteria.ts` — where `docs.updated` shows a branch-diff criterion. +3. `src/verification_store.ts` — signed private records beneath Git metadata. +4. `https://github.com/google/elephant-goldfish-model` — `skills/egm_review/SKILL.md` names the five review stages and allows direct dispatch: 5 zoom-out, 6 comprehension, 7 design with structural and style, 8 zoom-out again, 9 implementation readiness with codebase details and style. +5. `docs/v2/done/M17_001_P1_CLI_DOCS_GOV_SKILL_SCOPED_VERIFICATION_REUSE.md` — the invariants reuse keeps. + +## Files Changed (blast radius) + +| File | Action | Why | +|---|---|---| +| This spec, then its path under `done/` | CREATE, MOVE | Acceptance and evidence | +| `src/verification_identity.ts`, `src/verification.ts`, `src/verification_store.ts` | EDIT | Content-keyed binding, format 2 records, proof records | +| `src/config.ts`, `src/config_validation.ts`, `schemas/profile.schema.json` | EDIT | `coupled` path groups | +| `src/surfaces.ts`, `src/criteria.ts` | EDIT | `paths.coupled` and `tests.proven` | +| `src/proof.ts`, `src/note.ts` | CREATE | Test declarations, proofs, notes | +| `src/cli.ts`, `src/cli_help.ts` | EDIT | `orly proof`, `orly note`, help | +| `src/model.ts`, `registry.json` | EDIT | A persona pack names its owner | +| `src/*.test.ts` touched above, `src/coupled_paths.integration.test.ts`, `src/proof.integration.test.ts`, `src/note.integration.test.ts` | EDIT, CREATE | Proof of each Dimension | +| `SOUL.md`, `AGENTS.md`, the skills and `src/burst/*.ts` | EDIT | The owner's reduction review's one-form cuts | +| Both review records in the evidence folder | DELETE | The owner ruled review records out of the tree | +| `src/layout.test.ts` | EDIT | A retired evidence path cited anywhere outside history fails | +| `skills/orly-spec/SKILL.md`, `skills/orly-build/SKILL.md`, `skills/orly-ship/SKILL.md` | EDIT | EGM review, proof and note steps | +| `README.md`, `docs/ORLY_ARCHITECTURE.md`, `llms.txt`, `docs/CHANGELOG.md`, `standards/tests.md` | EDIT | Behaviour as shipped | + +## Applicable Rules + +- **`tests.md`** — TCF, TEST-MUTATE, TEST-NEG, TEST-ERROR, TEST-GITENV, TEST-LANE, TEST-CLAIM +- **`code.md`** — NDC, NRC, HLP, FLL, CODE-GITZ, PSR +- **`languages/typescript.md`** — TS-ORDER, TS-CAST, TS-NONNULL, TS-SCHEMA, TS-ERRSTYLE +- **`spec.md`** — SPEC-DEFER, SPEC-MODEL; **`changelog.md`** — CL-BUDGET, CL-USER; **`docs.md`** — DOC-02, DOC-03, DOC-05 + +## Applicable Gates + +| Gate | Fires? | Satisfaction strategy | +|---|---|---| +| `docs.language` | yes, skills and docs change | three sentences per paragraph, findings as table rows | +| `docs.updated` | yes, `src/` changes | README, architecture page, changelog | +| File & Function Length (file ≤350 lines, function ≤50, method ≤70) | yes, `src/cli.ts` nears 350 | parsing helpers shared by `proof` and `note` | + +## Prior-Art / Reference Implementations + +- **Reference:** `docsUpdated` in `src/criteria.ts` for a branch-diff criterion; `completeAttempt` in `src/verification_store.ts` for signed private records; `scanDocument` in `src/doc_rules.ts` for fence-aware heading scans. Practices: handlers return data and the CLI prints; human text stays the default output, as before. + +## Sections (implementation slices) + +### §1 — Reuse keyed to the tree + +The binding holds the merge base and a digest of every tracked path's mode and working-tree bytes, or of `tracked_inputs`, never the revision. A run records evidence when no untracked file is present; reuse still needs a clean tree at the pushed revision. Records move to format 2 with `executed_uncommitted`, so a revision-keyed record runs fresh. **Implementation default:** `--accept-dirty` publishes evidence, because content binding makes the flag irrelevant to what evidence proves. + +- **Dimension 1.1** — DONE — an uncommitted edit, its commit and its push bind one value → Test `an uncommitted tree binds the same evidence as the commit that records it` (integration): three identities, one binding, `current` only after the push +- **Dimension 1.2** — DONE — a run before the commit is reused after it → Test `a run on an uncommitted tree is reused once that tree is committed and pushed` (e2e): count stays 1, provenance names the parent revision `with uncommitted changes` +- **Dimension 1.3** — DONE — a different committed tree runs fresh → Test `an uncommitted run never vouches for a different committed tree` (e2e): count 2 +- **Dimension 1.4** — DONE — an untracked file during the run blocks its reuse → Test `an untracked file present during a run keeps it from being reused` (e2e): count 2 after the file is removed and the tree committed +- **Dimension 1.5** — DONE — an unstaged deletion binds as the commit that deletes → Test `a tracked file deleted from the working tree binds as the commit that deletes it` (integration): `README.md` removed, then committed with `-a`, gives one binding + +### §2 — Coupled paths + +`coupled` is a list of `{when, then}` prefix groups, validated by `couplingsSchema` and the profile schema. `paths.coupled` in `gate pr` fails when a branch path matches a `when` prefix and none matches its `then`; the detail names both sides. **Implementation default:** one way and pr-only, like `docs.updated`, because a version may move alone and a Section in progress may push one side first. + +- **Dimension 2.1** — DONE — the failing fixture → Test `a wire change without its version change fails and names both sides` (integration): `src/wire/frame.ts` changed alone gives `failed` and a detail naming `src/wire/` and `protocol/VERSION` +- **Dimension 2.2** — DONE — the passing fixture → Test `a wire change that moves its version passes` (integration): both changed gives `passed`, "1 coupled path group(s) changed together or not at all" +- **Dimension 2.3** — DONE — malformed groups are refused by both readers → Test `both configuration readers reject invalid coupled value []` and its siblings (unit): `[]`, a missing `then`, `../VERSION`, `.git/HEAD` and an unknown key each throw naming `coupled` + +### §3 — The spec skill runs the EGM review + +`skills/orly-spec/SKILL.md` step 6 dispatches `egm:egm-*` reviewers stage by stage with no conversation and resolves their findings as `egm-resolve` does. It writes no review file: accepted findings change the spec, and Discovery records rulings and declined findings with their reasons. `orly doctor` keeps its EGM check. + +- **Dimension 3.1** — DONE — installed skills pass their own prose gate → Test `fresh installation passes its own prose gate and still checks skill edits` (integration): a fresh install's `docs.language` detail is "changed documentation prose is clean" +- **Dimension 3.2** — DONE — no tracked file outside history cites an evidence path → Test `no reference to a retired file` (unit): an evidence-folder path left in a skill makes the citing list non-empty + +### §4 — Fail-before proofs + +`orly proof` refuses a name the file does not declare, a passing command, a run without a verdict, and a failure whose output never reports the test failing. It stores the command, the failing line and the code diff from HEAD, signed, under the evidence directory. `tests.proven` reads new declarations from the lines the branch adds in TypeScript, JavaScript, Rust, Go and Python. **Implementation default:** a missing proof is reported and never fails the gate, because the record is private to one worktree and a verdict must not depend on private local history. + +- **Dimension 4.1** — DONE — a reverted change that fails the test is recorded and counted → Test `a test that fails with its change reverted is recorded, and the pr gate counts it` (e2e): a flipped comparator gives exit 0, a record whose `mutation` holds the flipped line, and "1 of 2" unproven +- **Dimension 4.2** — DONE — a passing run is refused → Test `a test that passes with its change reverted is refused and records nothing` (e2e): exit 1, "the command passed", no record +- **Dimension 4.3** — DONE — another test's failure is refused → Test `a failure of another test is refused, even when the name says failed` (e2e): a verbose runner's `... ok` line for the named test gives exit 1, no record +- **Dimension 4.4** — DONE — an altered record proves nothing → Test `an altered proof record proves nothing` (integration): a changed `failing_line` gives "2 of 2" unproven +- **Dimension 4.5** — DONE — declarations per language → Test `new tests are read from added declarations in each supported language` (integration): seven declarations across `.go`, `.ts`, `.rs` and `.py`, and none from a body-only change or a non-test file + +### §5 — Owner notes + +`orly note` appends `- > Owner (, ): "" — context: ` after the last line of Discovery, outside code fences. The name is the `owner` of a selected persona pack. **Implementation default:** the time is kept, because SPEC-DEFER's form carries `HH:MM`. + +- **Dimension 5.1** — DONE — placement before the next section → Test `a note lands dated at the end of Discovery, before the next section` (e2e): the line follows the fenced block and precedes `## Appendix` +- **Dimension 5.2** — DONE — ambiguity is refused → Test `a --spec path chooses among several active specs, which are otherwise refused` (e2e): two active specs give "2 specs are active", and `--spec` writes only the named one +- **Dimension 5.3** — DONE — no owner is never invented → Test `a repository whose packs name no owner is refused, never given an invented name` (e2e): empty `packs` gives exit 1, "no selected pack names an owner", and no line written + +### §6 — Documentation + +Help, README, the architecture page, `llms.txt`, TEST-LANE and the 0.70.0 entry describe what shipped. + +- **Dimension 6.1** — DONE — help names both new commands → Test `uses the concise public command surface` (e2e): `--help` contains both usage lines + +## Interfaces + +`orly proof --test -- ...` and `orly note "" [--context ""] [--spec ]`; usage errors are `[ORLY-PROOF-001]` and `[ORLY-NOTE-001]`. `.orly/orly.json` gains `"coupled": [{"when": [""], "then": [""]}]`; `registry.json` packs may carry `owner`. Gate criteria `paths.coupled` and `tests.proven` join `gate pr`. + +## Failure Modes + +| Mode | Kind | Cause | Handling | Test | +|---|---|---|---|---| +| Untracked input | security | a file the commit lacks was readable | no binding; fresh run later | `an untracked file present during a run keeps it from being reused` | +| Revision-keyed record | failure | evidence from an earlier release | schema refuses format 1 | `signed provenance rejects old formats and retains original age` | +| Build error as proof | failure | mutation breaks compilation | refused | `a build error is refused, because no line reports the test failing` | +| Forged proof | security | hand-edited record | signature fails, test unproven | `an altered proof record proves nothing` | +| Missing Discovery | failure | spec lacks the section | refused, file unchanged | `a spec without a Discovery section is refused and left unchanged` | + +## Invariants + +1. A reused result comes only from a clean tree at the pushed revision — `before.current` in `src/verification.ts`. +2. A proof exists only for a run orly saw fail — `recordProof` writes after the verdict checks. + +## Metrics & Observability + +N/A: no product or operator signal changes; orly collects no telemetry. + +## Acceptance Rubric (single scoring surface) + +| # | Criterion | Verify | Expected | Priority | Graded | +|---|---|---|---|---|---| +| R1 | Tree-keyed reuse (§1) | `bun test src/verification.integration.test.ts src/verification_identity.integration.test.ts src/verification-scoped.integration.test.ts src/verification_store.integration.test.ts` | 0 fail | P0 | ✅ 61 pass, 0 fail (4 files) | +| R2 | Coupled paths (§2) | `bun test src/coupled_paths.integration.test.ts src/config_validation.test.ts` | 0 fail | P0 | ✅ 61 pass, 0 fail (2 files) | +| R3 | Proofs (§4) | `bun test src/proof.integration.test.ts` | 0 fail | P0 | ✅ 16 pass, 0 fail | +| R4 | Notes (§5) | `bun test src/note.integration.test.ts src/model.test.ts` | 0 fail | P1 | ✅ 22 pass, 0 fail | +| R5 | Skills pass their prose gate (§3) | `bun test src/doc_changes.integration.test.ts` | 0 fail | P1 | ✅ 19 pass, 0 fail | +| S1 | Conform | `make conform` | exit 0 | P0 | ✅ exit 0, `standards.catalogue`, `generated.root.current` and `packs.sources.current` green | +| S2 | Types | `bun run typecheck` | exit 0 | P0 | final `orly gate pr` run, Pull Request #90 Session notes 1 | +| S3 | Unit | `bun test src` | exit 0 | P0 | final `orly gate pr` run, Pull Request #90 Session notes 1 | +| S4 | No secrets | `gitleaks detect --redact --no-banner` | exit 0 | P0 | ✅ exit 0, 692 commits scanned, no leaks found | + +## Dead Code Sweep + +N/A: no files deleted. The `Completion` type folds into the shared signature helper. + +## Out of Scope + +- `egm-brainstorm` in `orly-spec` step 2 has the same refusal; it is listed for the owner in the reduction review. +- Detecting a changed test body under an unchanged declaration; not planned. + +--- + +## Product Clarity (authoring record) + +1. **Successful user moment** — `gate pr --reuse-verification` prints `reused run … with uncommitted changes` after the commit. +2. **Preserved user behaviour** — reuse stays opt-in per lane, live lanes stay fresh, gate verdicts ignore local records. +3. **Optimal-way check** — content keys replace revision keys inside the existing identity; no new store. +4. **Rebuild-vs-iterate** — iterate. +5. **What we build** — one binding change, two criteria, two commands, one skill step. +6. **What we do NOT build** — remote evidence, enforced proofs, glob couplings. +7. **Fit with existing features** — must not destabilize the full-source guard around each run. +8. **Surface order** — CLI and repository configuration together. +9. **Dashboard restraint** — none. +10. **Confused-user next step** — the criterion's detail names the command or override to run. + +## Decomposition & alternatives (patch vs refactor) + +- **Chosen shape:** five slices, one per approved item, plus documentation. +- **Alternatives considered:** a Git tree object for the binding needs blob writes, while the existing file digests already hold the content; failing on a missing proof would make a fresh clone red. +- **Patch-vs-refactor verdict:** a **patch** because each item extends an existing owner. + +## Discovery (consult log) + +- **Consults** — base `origin/main` at `bb741d6`; branch `feat/burst-tailnet` at `3979189`. The owner approved items 1, 3, 6, 7 and 8 and named this Pull Request and version. +- **Model reviews** — none of the spec: the owner approved the items. Claude Opus 5.5 (`claude-opus-5-5`) ran three fresh-context reviews. The standards review found 13: 12 fixed, and CL-BUDGET stands on the owner's ruling below. The rule-text reduction review found 30, with 5 applied and 25 proposed. The code reduction review found 22, with 9 applied and 13 proposed. The owner ruled review records out of the tree, so the proposals went to him in the session report and their file was deleted. +- **Proofs** — `orly proof` recorded a fail-before proof for each of the 33 new test declarations, run by an unmutated copy of the engine. Its first run found three defects, fixed in `fix(proof)`: a mutated `src/proof.ts` also mutated the recording tool, a multi-line `test.each` table went unread, and bun prints no passing lines off a terminal, which made one test vacuous. +- **CL-BUDGET** — the 0.70.0 entry carries ten bullets, over the five-bullet budget, because the owner kept both changes in one version; his ruling is quoted below. +- **Open blockers** — none. +- **Deferrals and transfers** — none. +- > Owner (Indy, Nov 26, 2026 16:21): "Yes i agree on 1, 3, 6 - have the skill do egm-review, 7, 8 and push it in the existing PR with 0.70 in orly." — context: approves the five improvements this spec builds, in Pull Request #90 at 0.70.0 +- > Owner (Indy, Nov 26, 2026 16:22): "In orly i recommend you to check the code files in the PR and other to see if we could reduce and make the skill to be more deterministic including the AGENTS.md and others" — context: the reduction review; only meaning-preserving cuts apply without sign-off, and the rest go to him as proposals +- > Owner (Indy, Nov 26, 2026 16:54): "Dont keep adding more documents so i prefer you delete docs/v2/evidence/* in orly and ensure you suggest review and clean up the docs to be deterministic the md files in orly" — context: both review records deleted; orly-spec writes no review file; the Markdown cleanup plan went to him as a proposal +- > Owner (Indy, Nov 26, 2026 16:54): "1. keep it at 0.70.0" — context: CL-BUDGET: both changes stay in the one 0.70.0 entry, past the five-bullet budget diff --git a/docs/v2/evidence/M17_REPOSITORY_REVIEW.md b/docs/v2/evidence/M17_REPOSITORY_REVIEW.md deleted file mode 100644 index d20f76cd..00000000 --- a/docs/v2/evidence/M17_REPOSITORY_REVIEW.md +++ /dev/null @@ -1,164 +0,0 @@ -# M17 repository review and verification costs - -## Candidate and evidence limits - -The candidate targets 0.50.0 on `feat/m17-scoped-verification-reuse`, based on 0.42.0 revision `9c177c333010b11fc83bb49bc2d00cadd549c6c3`. -The base was fetched again during review and remained unchanged. - -Counters below come from disposable Git repositories and local processes. Provider tests use controlled AWS and E2E Networks responses; no paid machine was launched. - -No consumer installation or live cloud acceptance is claimed. Wall-clock suite timings describe those test runs, not a speedup against a comparable consumer baseline. - -## Measured reductions - -| Change | Before | Candidate observation | Evidence | -|---|---|---|---| -| Default gate path | Fast verification runs in `verify` and again in `pr` | One execution in `work → pr`; a separate explicit `verify` still runs | `src/gate-determinism.integration.test.ts`, default gate counter | -| Documentation commit after a scoped pass | Exact-revision evidence causes another execution | Cumulative executions 1, 1, 2 after initial run, excluded documentation commit, selected input edit | `src/verification-scoped.integration.test.ts`, real command-line journey | -| Scoped selection | No cross-revision selection | Uses the existing tracked snapshot, with no extra file read for selection | `src/verification_identity.integration.test.ts`, file-open counter | -| Overlapping extra paths | Duplicate declarations reread a file | One file read per identity collection | Same counter, directory plus file plus repeated directory | -| Full skill delivery | Four private bodies plus twelve runtime pointers | Twelve full runtime bodies; no private managed skill copies | `src/installation/skill-migration.integration.test.ts` | -| Repeat install | Existing idempotence | Zero writes on a repeat install remains true | Same migration suite | -| Already-cancelled cloud run | Could prepare resources before noticing cancellation | Zero provider API calls | `src/burst/cancellation.integration.test.ts` | -| Captured process timeout | Leader termination could leave descendants holding pipes | Group termination and child reaping on deadline, cancellation and parent exit | `src/burst/process.integration.test.ts` | - -The hashing claim applies within each collection. A tracked file also declared as an extra input is read in both collections. -Full snapshots before and after the work remain required. - -The toolchain runs inside those observations, and source changes still block a result. - -Scoped reuse needs both a reviewed repository policy and `--reuse-verification`. It is not enabled automatically in consumers or in this repository's configuration. -Engine changes, missing inputs, changed dependencies, failed or unsigned evidence, expiry and newer failed attempts require fresh work. - -## Repository inventory - -`git ls-files -z` at the opening revision listed 193 files. Subsystem reviewers read implementation, tests, settings and current guidance; this table records the limits. - -| Inventory | Review performed | -|---|---| -| 96 tracked `src/` files | Execution, installation, verification, configuration and documentation scanners reviewed by subsystem; new candidate files reviewed with their owners | -| 21 standards, four skills, core, working notes and reviewer | Current instructions read; contradictions traced to authored sources | -| Registry, two schemas and six fixtures | Selection, validation, installed references and generated parity reviewed | -| Three installation evaluation scripts | Distribution tests and language isolation reviewed | -| Four workflows, two hooks, package, lockfile and build files | Read for repeated work, reproducibility and release recovery; workflows remain unchanged | -| Current architecture, installation guide and active specs | Read for implementation agreement; M15's remaining manual dimensions remain open | -| Fourteen historical done specs | Headers, status and purpose inventoried; M16 evidence spec read in full. Other historical bodies were not reread in full | -| Fourteen branding assets | Metadata, SVG structure and PNG dimensions inventoried; no new visual assessment claimed | - -The inventory is a repository audit, not a claim that every historical prose line or image received a new visual review. - -## Findings and dispositions - -| Finding | Repair or disposition | Proof | -|---|---|---| -| Documentation commits invalidate every lane | Optional literal `tracked_inputs` extends existing signed evidence | Cross-revision, add/delete/rename/mode and negative evidence tests | -| Default fast checks run twice | Default path runs work then pr | Invocation counter; explicit verify preserved | -| Toolchain probe can edit after final snapshot | Final observation follows probes | Second-probe edit regression blocks the result | -| Clean, pushed excluded edit during a lane could be confused with dirty-state handling | Test independently exercises the full-source comparison | Clean/pushed concurrent documentation commit is blocked | -| Ignored or index-hidden managed edits can be lost | Positive tracked/clean inspection for replacement and obsolete deletion | Ignored, skip-worktree and assume-unchanged migration tests | -| Interrupted migration misses a mode-only edit | Compare index and disk executable modes, independently of Git's mode display setting | Planning and recovery refuse hidden executable edits; journal remains | -| Skills require private bodies and pointer files | Full body at each runtime destination | Fresh install, migration, repeat install and recovery | -| Runtime reviewer citations skip owner instructions | Preserve root `AGENTS.md` citations in runtime guidance | Installed reviewer assertion | -| Linked architecture pages absent from governance pack | Ship the installation and burst pages | Fresh governance-pack installation | -| Scheduled deletion can satisfy a reference | Exclude obsolete files from fallback closure | Positive reference resolves; scheduled deletion refuses it | -| Two registry paths normalize to one destination | Detect conflicts using installed destination | Plain and `.orly/` target conflict tests | -| Missing merge base looks like no changes | Block PR commands and name the required fetch | Missing-history fixture starts no verification command | -| Build inputs evade slow-lane classification | Include entrypoints, Makefiles and lockfiles | Each input triggers declared integration verification | -| A remote default branch named develop passes | Compare with remote default ref | Default-branch refusal fixture | -| Override commit captures staged owner edits | Use an empty commit that leaves the index alone | Tree equality and staged file assertions | -| Digits or hyphens in override names cannot be read back | Align validation and trailer parsing; refuse multiline reasons | Override round trip and no-commit negative tests | -| Misspelled install flags can perform writes | Reject unsupported arguments before installation | Typo cases create no `.orly` directory | -| Failed ignored-file inspection looks clean | Refuse failed Git inspection | Non-repository negative case | -| Test Git defaults vary by machine | Explicit main branch, isolated global settings and synchronous fixture writes | Gate tests; child-process inherited-environment regression | -| Captured children can leave pipes open | Stop owned process group and reap leader | Real local descendant tests | -| Cancelled cloud work can still create resources | Check before mutation; cancel reads and retain bounded mutation replies for cleanup | Zero-call, catalogue and key/group/machine response-boundary fixtures | -| Key deletion failure prevents group cleanup | Attempt independent cleanup and report remaining key | Key failure leaves no fixture machine or group | -| Spot retry depends on price lookup | Track the market independently of the optional quote | Missing price still permits the requested retry | -| Snapshot names collide across hosts, accounts or shortened paths | Digest full origin identity and home-relative SSH account; timestamp plus random suffix | Host, account, punctuation, long path, absolute transport and same-instant cases | -| Paragraph exception text bypasses documentation checks | Require a reasoned HTML comment and keep its scope local | Bare text, code spans, missing reasons and page-budget tests | -| Renderer retains unused project-root branch | Remove unused parameter and branch | Existing render and parity checks | -| Installation language evaluation always includes Rust and shell | Start language-only cases without either seed | Isolated packed installation evaluation | -| Long AWS test module mixes lifecycle and market tests | Split around those responsibilities; keep shared fixture helpers | Existing cases retained; new missing-price case | -| Reviewer skips rules merely named as automated | Require actual checker evidence for reviewed inputs | Source and installed guidance assertions | -| Shipping omits lessons and stage outcomes | Add owner-approved learning proposal and stage reporting | Source and installed guidance assertions | - -## Findings outside the implementation repairs - -The workflow audit found duplicate full-suite runs in Harness and coverage jobs, floating tool installs, unused secret-scanner setup, and a partial-release recovery gap. -Changing `.github/workflows/**` requires explicit approval under the repository's operating model. No workflow was changed or check weakened. - -Let the coverage job own the unit run and retain Harness configuration and distribution checks. -Pin fetched tools and resume missing release assets after publication. -Review those changes against `harness.yml`, `test.yml`, `gitleaks.yml` and `release.yml` before approval; this candidate makes no hosted-time saving claim. - -E2E Networks lost-acknowledgement handling still warns that a virtual machine may exist and names it for inspection. -The existing simulated failure does not create a machine before losing the response, so it does not prove remote-effect recovery. A provider reconciliation design and real effect-then-lost-reply fixture remain separate work. - -Process snapshots do not detect a transient edit restored between observations. Local signatures do not defend against another process with the same user's privileges. -These are stated limits, not newly claimed guarantees. - -## Checks run - -| Check | Result | Evidence | -|---|---|---| -| Base full suite at `9c177c3` | 507 passed, 0 failed; 2,209 assertions | [Harness run](https://github.com/agentsfleet/orly/actions/runs/44027560130) | -| Base packed installs | 24 passed, 0 failed | Same Harness run | -| Base coverage suite | 507 passed, 0 failed; 97.22% functions, 95.72% lines | [Test run](https://github.com/agentsfleet/orly/actions/runs/44027560287) | -| Gate and identity counters | 35 passed, 0 failed; 139 assertions | `bun test src/gate-determinism.integration.test.ts src/verification_identity.integration.test.ts src/verification-scoped.integration.test.ts` | -| Probe repair, guidance and document checks | 71 passed, 0 failed; 238 assertions | `bun test src/verification-scoped.integration.test.ts src/verification_identity.integration.test.ts src/learning_guidance.integration.test.ts src/doc_rules.test.ts src/references.test.ts` | -| Local process and config checks | 28 passed, 0 failed; 51 assertions | `bun test src/burst/process.integration.test.ts src/config.test.ts` | -| Cloud cancellation and AWS lifecycle | 22 passed, 0 failed; 127 assertions | `bun test src/burst/cancellation.integration.test.ts src/burst/aws.test.ts` | -| Review regressions before repair | 1 passed, 6 assertion failures; 27 assertions | Mode-ignore planning/recovery, home-relative account and three cancellation-after-effect cases | -| Review repairs | 56 passed, 0 failed; 252 assertions | Criteria, guidance, references, skill migration, repository ownership and cancellation suites | -| Nested fixture Git isolation | Before: 1 assertion failure; after: 1 passed, 0 failed, 5 assertions | Scoped concurrent-edit test with injected disposable global signing configuration | -| Packed installation before review repairs | 24 passed, 0 failed | `make install-evals`; migration changed afterward, so final distribution check remains due | -| Work gate | Passed configuration, catalogue, render and pack parity | `bin/orly gate work` | -| Repaired packed installation | 24 passed, 0 failed | `make install-evals` after mode-preservation repairs | -| First pushed gate at `dd8930b` | Type check passed; 572 tests passed, 3 failed; 2,550 assertions | Generated size limit plus two process tests, investigated below | -| Render size and ambiguous owner repair | 30 passed, 0 failed; 118 assertions | Ownership, render and installed guidance suites | -| Repaired pushed gate at `414e270` | Passed all criteria; 577 tests passed, 0 failed; 2,554 assertions; type check passed | `python3 /tmp/orly-m17-reap.py bin/orly gate pr`; 49 test files, 58.34 seconds | -| Final documentation revision gate and review | Pending at closure commit | Forge description records final-head outcomes | - -Earlier diagnostics found missing dependencies, a fixture missing its managed file, and an omitted test import. -A blocked concurrent-edit result also retained proof metadata. - -Each was repaired; the affected tests passed afterward. Final verification remains distinct from these targeted observations. - -## Review coverage and repairs - -The full gstack review read all 73 candidate paths, 250 tracked hunks and ten new files. Seven specialists and a fresh native adversarial reviewer contributed. -Its candidate digest was `3380c3ea42bb5c043b481f5af5e90d78ef75952e`. - -The review found seven defects: two imports, optional signal types, executable-mode preservation, cancellation ownership, home-relative account identity and nested fixture Git isolation. -The repairs have focused and full-gate evidence above. Final review of the closure revision remains due. - -The independent standards review read the same candidate and screened 326 rule blocks. It reported 16 findings covering imports, test assertions, size, source agreement and prose. -These findings were repaired in authored sources; generated instructions were regenerated afterward. - -Outside structured and adversarial reviews were unavailable because the installed outside provider selected the active Codex harness. No outside or paid process ran. -Native reviews do not substitute for that missing outside coverage. - -## Final-gate diagnostics - -The first pushed gate found generated instructions at 16,878 bytes, above the existing 16,384-byte limit. -Authored wording was shortened; the generated file is now 16,299 bytes. The unchanged size and hard-safety tests pass. - -Two command-runner tests also failed on unchanged 0.42.0 in an isolated archive on this host. Both owned children were dead zombies adopted by process 1. -The container's process manager did not reap them; the assertions and supervisor sources remain unchanged. - -Running under a Linux child subreaper restored normal orphan cleanup. The same baseline cases passed 2/2; the candidate command-runner suite passed 3/3. -The final local gate uses that environment wrapper, which adopts and reaps only descendants of its command. - -The wrapper uses `prctl(PR_SET_CHILD_SUBREAPER, 1)` before spawning the unchanged command, then waits for its children and returns the command's exit status. -Local command: `python3 /tmp/orly-m17-reap.py bin/orly gate pr`. Hosted checks use their own process manager. - -Standards reconciliation found one stale pruning example and home-relative origins lacking an explicit SSH account. -The example now uses the current snapshot format; ambiguous owners are refused. Both new negative ownership cases failed before the repair and passed afterward. - -## Performance interpretation - -The full suite grew from 507 baseline tests to 577 candidate tests, an increase of 70. The local candidate run took 58.34 seconds. -The hosted baseline took 33.09 seconds on different hardware; those times do not establish a speedup or regression. - -The proven savings are invocation counts: one default fast-check run instead of two, and scoped lane counts of 1, 1, 2 across three revisions. -No workflow files changed, so this delivery claims no reduction in hosted duplicate jobs. diff --git a/llms.txt b/llms.txt index e9c2986f..6e4c58e3 100644 --- a/llms.txt +++ b/llms.txt @@ -12,10 +12,10 @@ Package: `@agentsfleet/orly` (npm) Source: https://github.com/agentsfleet/orly License: Massachusetts Institute of Technology (MIT) -This guide describes orly 0.60.1. The `bunx` commands below fetch the +This guide describes orly 0.70.0. The `bunx` commands below fetch the published package; available versions are listed at https://github.com/agentsfleet/orly/releases. Use an installed local tarball for -candidate checks. orly collects no usage telemetry. Authorized cloud burst runs call provider APIs; package installation may fetch dependencies. +candidate checks. orly collects no usage telemetry. Authorized cloud burst runs call provider and Tailscale APIs; package installation may fetch dependencies. --- @@ -171,6 +171,8 @@ never with a placeholder reason. | `orly gate` | run work then pr, with fast verification once; stop at the first failure | | `orly gate pr` | the Pull Request criteria check | | `orly gate pr --reuse-verification` | reuse intact current-input evidence only for reviewed hermetic policies | +| `orly proof --test -- ` | with the test's covered code reverted, record that the test fails | +| `orly note ""` | add the owner's verbatim ruling, dated, to the active spec's Discovery | | `orly override --reason ` | record a gate exception (user-authorised only) | | `orly doctor` | check installed files and required command configuration | | `orly burst` | list the declared `burst.*` lanes; exits 2 | @@ -181,7 +183,9 @@ AWS lanes rent Spot machines unless `ORLY_BURST_MARKET` says `on-demand`. Region Gates inspect prerequisites before commands and report blocked or unrun groups explicitly. Fresh execution is the default; a reuse flag alone cannot skip any command. Repository-owned `reuse` policies require hermetic input ownership, a maximum age and toolchain identities. Original execution output stays visible, and failed latest attempts or attempts without a completion record prevent fallback to an older pass. -An optional `tracked_inputs` policy permits reuse across documentation commits only when every tracked dependency is declared and the command does not read Git history. +Evidence binds tracked content, not the revision. A run before the commit is reused once that tree is committed and pushed, and a hermetic command reads no Git history. +An optional `tracked_inputs` policy narrows that content, and must declare every tracked dependency. +`coupled` path groups fail `gate pr` when a branch changes one side only. `gate pr` names new tests that have no `orly proof` record, and never fails on them. Full-source observations still bracket the commands and toolchain probes. Keep fixture evidence, live acceptance and injected-delay measurements separate. Unavailable reviews remain blocked, and final review follows the same pushed head through two quiet polls. diff --git a/package.json b/package.json index 899a84d3..f6483dfd 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@agentsfleet/orly", - "version": "0.60.4", + "version": "0.70.0", "description": "Repository-scoped engineering harness: renders agent rules, materialises the gates that enforce them, and proves the PR boundary — for any coding agent.", "license": "MIT", "type": "module", diff --git a/registry.json b/registry.json index aecf6aad..03589ba6 100644 --- a/registry.json +++ b/registry.json @@ -6,6 +6,7 @@ ], "packs": { "persona.indy": { + "owner": "Indy", "extensions": [], "managed_files": [] }, diff --git a/schemas/profile.schema.json b/schemas/profile.schema.json index e3abb961..9b02f2ea 100644 --- a/schemas/profile.schema.json +++ b/schemas/profile.schema.json @@ -22,6 +22,16 @@ "docs": {"type": "array", "items": {"$ref": "#/$defs/nonempty"}} } }, + "coupled": { + "type": "array", "minItems": 1, + "items": { + "type": "object", "additionalProperties": false, "required": ["when", "then"], + "properties": { + "when": {"type": "array", "minItems": 1, "items": {"$ref": "#/$defs/input"}}, + "then": {"type": "array", "minItems": 1, "items": {"$ref": "#/$defs/input"}} + } + } + }, "reuse": { "type": "object", "propertyNames": {"type": "string", "pattern": "^verify\\.", "not": {"enum": ["verify.integration", "verify.memory"]}}, @@ -84,6 +94,7 @@ "$defs": { "trackedInput": {"type": "string", "minLength": 1, "pattern": "^(?!/)(?![A-Za-z]:)(?!.*(?:^|/)(?:\\.{1,2}|\\.git)(?:/|$))(?!.*//)[^\\u0000\\\\*?\\[\\]{}]+$"}, "nonempty": {"type": "string", "minLength": 1, "pattern": "^[^\\u0000]+$"}, + "input": {"type": "string", "minLength": 1, "pattern": "^(?!/)(?![A-Za-z]:)(?!.*(?:^|[/\\\\])(?:\\.\\.|\\.git)(?:[/\\\\]|$))[^\\u0000]+$"}, "invocations": {"type": "array", "items": {"type": "array", "minItems": 1, "items": {"$ref": "#/$defs/nonempty"}}} } } diff --git a/skills/orly-build/SKILL.md b/skills/orly-build/SKILL.md index 38ed4fb4..e17ce25d 100644 --- a/skills/orly-build/SKILL.md +++ b/skills/orly-build/SKILL.md @@ -25,15 +25,15 @@ it applies are the standards listed in `AGENTS.md`; tests follow with the spec's Intent stops the work. Keep the restatement for the Pull Request Session Notes. 5. **Build each Section.** Read the standards for the files the Section touches. - Write a test per Dimension and a negative test per failure mode. Add an - integration test when the diff crosses a module boundary with real - input/output. + Write a test per Dimension and a negative test per failure mode. + + Prove each new test fails: revert or mutate the code it covers, run + `orly proof --test -- `, then restore the code. + An owner ruling goes into the spec with `orly note`. 6. **Commit.** The pre-commit hook runs `orly gate work`; if hooks did not run, run it yourself. Mark the Section's Dimensions `DONE` in the same commit as - their code and tests. Never use `--no-verify`. -7. **When stuck.** Use gstack `/investigate` for a failure you cannot explain, - and gstack `/qa` to exercise a user-facing path. Outside Claude Code their - names carry a `gstack-` prefix. + their code and tests. +7. **When stuck.** Use gstack `/qa` to exercise a user-facing path. 8. **Hand off.** When every Dimension is `DONE`, continue with `orly-ship`. ## Codex cloud tasks diff --git a/skills/orly-burst/SKILL.md b/skills/orly-burst/SKILL.md index b214d75a..b0f8075e 100644 --- a/skills/orly-burst/SKILL.md +++ b/skills/orly-burst/SKILL.md @@ -25,9 +25,10 @@ https://github.com/agentsfleet/orly/blob/main/docs/BURST.md ## Steps 1. **List the lanes.** Run `orly burst`; pick only lanes it lists. -2. **Pick the provider.** Use `aws-spot` or `e2e` where outbound SSH on port - 22 works and the caller stays on one network for the run. From an - HTTP-only session, start the repository's burst workflow instead. +2. **Pick the provider.** `aws-spot` or `e2e`. The caller must be on a + tailnet (`tailscale status` online); a network change mid-run is + reconnected. Where Tailscale cannot run, start the repository's burst + workflow instead. 3. **Warm once.** Capture `orly burst snapshot --provider

` after setup changes, and prove a new provider with one capture before any lane. `orly burst snapshot --prune --provider

` keeps the newest one. @@ -56,3 +57,6 @@ print the result lines and what was deleted. - AWS credentials come from the caller's `aws` configuration or the job's login step. E2E needs a TIR API token's `E2E_API_KEY`, `E2E_AUTH_TOKEN` and `E2E_PROJECT_ID`; MyAccount keys do not work. +- Tailscale needs `TS_OAUTH_CLIENT_ID` and `TS_OAUTH_CLIENT_SECRET`, an OAuth + trust credential whose only tag is `tag:orly-burst`. Never pair it with a + CI credential's tags. diff --git a/skills/orly-ship/SKILL.md b/skills/orly-ship/SKILL.md index a32c6106..007f24fa 100644 --- a/skills/orly-ship/SKILL.md +++ b/skills/orly-ship/SKILL.md @@ -17,10 +17,9 @@ This skill owns the steps from review to land. Pull Request rules live in 1. **Check the setup.** Run `orly doctor` and stop on any red line. Fetch the target base branch and record its revision. Before publishing, ensure this branch contains that revision and reconcile release versions against it. -2. **Review.** Run gstack `/review` on the diff (`gstack-review` outside Claude - Code). Then give `orly-standards-reviewer` the diff, the spec, the +2. **Review.** Run gstack `/review` on the diff. Then give `orly-standards-reviewer` the diff, the spec, the standards for the touched files and the repository's own instructions. Fix - each finding, or record the owner's verbatim deferral quote. + each finding, or record the owner's verbatim deferral quote with `orly note`. Record each review's name, reviewed revision, findings and limits separately in the PR's Review section. A partial gstack review is not done; another @@ -46,6 +45,9 @@ This skill owns the steps from review to land. Pull Request rules live in hermetic policy, `--reuse-verification` may reuse valid matching completion evidence; keep the original run, counts and provenance in the Pull Request. Every required criterion passes or carries an owner-recorded override. + + Copy the `tests.proven` line, which names new tests without a fail-before + proof, into the Make section. 7. **Publish for review.** An authorized request to open a PR targets ready-for-review unless the owner explicitly requests a draft. Open it with a body that follows the PR standard. If this stream already has a draft, diff --git a/skills/orly-spec/SKILL.md b/skills/orly-spec/SKILL.md index 8ca88bc9..8284ad2e 100644 --- a/skills/orly-spec/SKILL.md +++ b/skills/orly-spec/SKILL.md @@ -22,16 +22,50 @@ and its shape in `.orly/standards/spec-template.md`. `egm-brainstorm` on the idea. 3. **Choose.** Put two to four shapes with their costs to the owner through AskUserQuestion, with your call first. A question that times out is not an - answer: wait. Record the owner's verbatim words in Discovery. + answer: wait. Record the owner's verbatim words in Discovery with + `orly note "" --spec ` once the spec file exists. 4. **Name.** Fetch `origin/main`, then take the next free `M{N}_{WS}` from `git ls-tree -r --name-only origin/main docs/`. The file is `docs/v{P}/pending/M{N}_{WS}_P{priority}_{CATEGORIES}_{NAME}.md`. 5. **Draft.** Copy the spec template and fill it in the order the spec standard gives. Delete every `tpl:` hint. Every Dimension names its test, and every failure mode its negative test. -6. **Review.** Run EGM's `egm-review` on the draft. Its reviewers start with no - context. Apply accepted findings with `egm-resolve`; scope and design calls - go to the owner. +6. **Review.** Run the EGM review yourself, because its `egm-review` and + `egm-resolve` skills refuse model invocation. The EGM root is the + `installPath` that `~/.claude/plugins/installed_plugins.json` records for + `egm@egm`, or in Codex the folder under `$CODEX_HOME/plugins/cache/egm/egm/`. + + The feature range ends before `## Sections`, and the detailed range starts + there. Run the stages in order, and a stage's reviewers in parallel: + + | Stage | Reviewers | Range | Standard | + |---|---|---|---| + | 5 | `egm:egm-zoom-out` | whole spec | `zoom-out-standard.md` | + | 6 | `egm:egm-comprehension` | both ranges | `re-implementation-standard.md` | + | 7 | `egm:egm-design`, `egm:egm-structural`, `egm:egm-style` | feature | `feature-spec-standard.md` | + | 8 | `egm:egm-zoom-out`, given stage 5's findings | whole spec | `zoom-out-standard.md` | + | 9 | `egm:egm-implementation-readiness`, `egm:egm-codebase-details`, `egm:egm-style` | detailed | `implementation-readiness-standard.md` | + + Each reviewer is a fresh subagent with no conversation. Its prompt holds + `Mode: REVIEW`, the spec's absolute path and range, and two standards. They + are the stage's file under `/resources/document_standards/` and + `.orly/standards/spec.md`. + + The prompt asks for each finding's severity (Blocker, Major or Nit), lines + and reason. Without the `egm:` agent types, start a general-purpose subagent + that first reads the file in `/agents/` whose frontmatter `name` + is the type. With no subagent tool, stop. + + Write no review file, in the repository or out of it; the findings stay in + the session. Resolve them as `egm-resolve` does: PROPOSE FIX with the exact + edit, or CONTEST with the code or rule that answers it. + + Apply accepted fixes to the spec after stages 7 and 9, before the next + stage, and rerun a stage at most once. Scope and design calls go to the + owner, and `orly note` records each ruling. + + Discovery records the model, its version, the finding counts, and each + contested finding with the reason it was declined. 7. **Land.** Cut `docs/m{N}--spec` from the fetched `origin/main`, commit the spec, push, and open a docs-only Pull Request. The default branch requires pull requests. @@ -39,5 +73,6 @@ and its shape in `.orly/standards/spec-template.md`. ## Stop conditions - `orly doctor` is red, or EGM is missing: report the doctor lines. +- No subagent can be started: the review cannot run, so the spec stays unreviewed. - The goal cannot be written as a test name: the intent is not understood yet. - A `[?]` survives the golden-path walk: the spec stays in `pending/`. diff --git a/src/burst/aws-test-support.ts b/src/burst/aws-test-support.ts index 627fc487..8e986de3 100644 --- a/src/burst/aws-test-support.ts +++ b/src/burst/aws-test-support.ts @@ -1,17 +1,19 @@ // EC2, in memory, as orly's aws-spot provider uses it. aws-sdk-client-mock // answers every EC2Client in the process from here while a FakeEc2 is -// installed; restoreEc2 removes it. Each launched instance gets its own -// address, which the fake `ssh` then plays the machine at. +// installed; restoreEc2 removes it. Each launched instance runs its user data +// at once, joining the fake tailnet, whose address the fake `ssh` then plays +// the machine at. import { readFileSync } from "node:fs"; import { join } from "node:path"; import { - AuthorizeSecurityGroupIngressCommand, CreateImageCommand, CreateSecurityGroupCommand, DeleteKeyPairCommand, DeleteSecurityGroupCommand, + CreateImageCommand, CreateSecurityGroupCommand, DeleteKeyPairCommand, DeleteSecurityGroupCommand, DeleteSnapshotCommand, DeregisterImageCommand, DescribeImagesCommand, DescribeInstancesCommand, DescribeSecurityGroupsCommand, DescribeSpotPriceHistoryCommand, EC2Client, ImportKeyPairCommand, RunInstancesCommand, StopInstancesCommand, TerminateInstancesCommand, } from "@aws-sdk/client-ec2"; import { mockClient } from "aws-sdk-client-mock"; -import { burstDependencies, burstEnvironment, burstRepository, callerAddress, fakeBin, REPOSITORY } from "./test_support"; +import { FakeTailscale } from "./fake_tailscale"; +import { burstDependencies, burstEnvironment, burstRepository, fakeBin, REPOSITORY } from "./test_support"; // noCapacity: types with no capacity. refuse: the error every launch answers. // vanish: an instance is terminated before it answers. lostReply: the @@ -26,7 +28,7 @@ type Call = { command: string; input: Record; region: string }; type Tagged = { TagSpecifications?: Array<{ Tags?: Array<{ Key?: string; Value?: string }> }> }; const COMMANDS = { - AuthorizeSecurityGroupIngressCommand, CreateImageCommand, CreateSecurityGroupCommand, DeleteKeyPairCommand, DeleteSecurityGroupCommand, + CreateImageCommand, CreateSecurityGroupCommand, DeleteKeyPairCommand, DeleteSecurityGroupCommand, DeleteSnapshotCommand, DeregisterImageCommand, DescribeImagesCommand, DescribeInstancesCommand, DescribeSecurityGroupsCommand, DescribeSpotPriceHistoryCommand, ImportKeyPairCommand, RunInstancesCommand, StopInstancesCommand, TerminateInstancesCommand, }; @@ -42,7 +44,7 @@ export class FakeEc2 { groups: string[] = []; #nextInstance = 1; - constructor(readonly scenario: Ec2Scenario = {}) { + constructor(readonly scenario: Ec2Scenario = {}, readonly tailnet: FakeTailscale) { ec2Mock.reset(); for (const [name, command] of Object.entries(COMMANDS)) { ec2Mock.on(command as never).callsFake(async (input: Record, getClient: () => unknown) => { @@ -98,6 +100,7 @@ export class FakeEc2 { const id = `i-${String(number).padStart(17, "0")}`; const run = tag(input, "orly-burst"); this.instances.set(id, { id, type, state: this.scenario.vanish ? "terminated" : "running", address: `198.51.100.${number}`, run, spot: Boolean(input.InstanceMarketOptions), shutdown: String(input.InstanceInitiatedShutdownBehavior) }); + if (!this.scenario.vanish) this.tailnet.join(Buffer.from(String(input.UserData ?? ""), "base64").toString()); if (this.scenario.lostReply) throw named("RequestTimeout", "the connection closed before the reply"); return { Instances: [{ InstanceId: id, Placement: { AvailabilityZone: "ap-south-1a" } }] }; } @@ -155,8 +158,9 @@ export function restoreEc2(): void { export async function awsRun(scenario: Ec2Scenario = {}, burstConfig: Record = {}, extra: Record = {}) { const root = burstRepository(burstConfig); const { bin, state } = fakeBin(); - const ec2 = new FakeEc2(scenario); - return { root, state, ec2, ...burstDependencies(root, burstEnvironment(bin, state, extra), callerAddress) }; + const tailnet = new FakeTailscale(state); + const ec2 = new FakeEc2(scenario, tailnet); + return { root, state, ec2, tailnet, ...burstDependencies(root, burstEnvironment(bin, state, extra), tailnet.fetch) }; } export function machineScript(state: string, address: string): string { diff --git a/src/burst/aws.test.ts b/src/burst/aws.test.ts index 198077f3..c9cc1aa9 100644 --- a/src/burst/aws.test.ts +++ b/src/burst/aws.test.ts @@ -4,7 +4,7 @@ import { join } from "node:path"; import { burst } from "./index"; import { awsRun, GROUP_ID, machineScript, restoreEc2 } from "./aws-test-support"; -import { burstDependencies, burstEnvironment, burstRepository, CALLER_ADDRESS, fakeBin, recordedCalls, REPOSITORY, SECRET_VALUE, snapshotOf } from "./test_support"; +import { recordedCalls, REPOSITORY, SECRET_VALUE, snapshotOf } from "./test_support"; import { cleanupTemporaryDirectories } from "../gates_test_support"; const BASE_IMAGE = "resolve:ssm:/aws/service/debian/release/13/latest/amd64"; @@ -19,15 +19,15 @@ afterEach(() => { }); describe("aws-spot lanes", () => { - test("a run imports its key, opens SSH to the caller only, launches lanes at once and removes it all", async () => { + test("a run imports its key, opens no inbound port, launches lanes at once and removes it all", async () => { const run = await awsRun({ noCapacity: ["c7i.4xlarge"] }); expect(await burst(LANES, run.dependencies)).toBe(0); const commands = run.ec2.calls.map((call) => call.command); - expect(commands.slice(0, 4)).toEqual(["DescribeImages", "ImportKeyPair", "CreateSecurityGroup", "AuthorizeSecurityGroupIngress"]); + expect(commands.slice(0, 3)).toEqual(["DescribeImages", "ImportKeyPair", "CreateSecurityGroup"]); + expect(commands).not.toContain("AuthorizeSecurityGroupIngress"); expect(String(run.ec2.inputs("ImportKeyPair")[0]?.KeyName)).toMatch(RUN_NAME); - expect(run.ec2.inputs("AuthorizeSecurityGroupIngress")[0]?.IpPermissions).toEqual([{ IpProtocol: "tcp", FromPort: 22, ToPort: 22, IpRanges: [{ CidrIp: `${CALLER_ADDRESS}/32` }] }]); const launches = run.ec2.inputs("RunInstances"); expect(launches.map((launch) => launch.InstanceType).sort()).toEqual(["c7a.4xlarge", "c7a.4xlarge", "c7i.4xlarge", "c7i.4xlarge"]); expect(commands.lastIndexOf("RunInstances")).toBeLessThan(commands.indexOf("TerminateInstances")); @@ -42,11 +42,11 @@ describe("aws-spot lanes", () => { expect(run.ec2.inputs("TerminateInstances")).toHaveLength(2); expect(commands.slice(-3)).toEqual(["DescribeInstances", "DeleteSecurityGroup", "DeleteKeyPair"]); const ssh = recordedCalls(run.state).filter((call) => call[0] === "ssh"); - expect(ssh.every((call) => call.includes("admin@198.51.100.1") || call.includes("admin@198.51.100.2"))).toBe(true); - expect(ssh.some((call) => call.at(-1) === "sudo -n bash -s")).toBe(true); + expect(ssh.every((call) => call.includes("admin@100.64.0.1") || call.includes("admin@100.64.0.2"))).toBe(true); + expect(ssh.some((call) => call.at(-1)?.startsWith("sudo -n bash -c "))).toBe(true); const text = run.output.text(); expect(text).toContain("no capacity for c7i.4xlarge (InsufficientInstanceCapacity); trying the next type"); - expect(text).toContain(`admits SSH from ${CALLER_ADDRESS} only`); + expect(text).toContain("opens no inbound port; the run's instances are reached over the tailnet"); expect(text).toMatch(/orly burst: lane=acceptance provider=aws-spot machine=c7a\.4xlarge minutes=\d+ cost≈\$0\.2345\/h \(spot\) exit=0 evidence=\S+/); expect(text).toContain("orly burst: total provider=aws-spot lanes=2 passed=2 failed=0"); }); @@ -56,7 +56,7 @@ describe("aws-spot lanes", () => { await burst(["acceptance", "--provider", "aws-spot"], run.dependencies); - expect(machineScript(run.state, "198.51.100.1")).toContain(` export API_TOKEN='${SECRET_VALUE}'`); + expect(machineScript(run.state, "100.64.0.1")).toContain(` export API_TOKEN='${SECRET_VALUE}'`); expect(JSON.stringify(run.ec2.calls)).not.toContain(SECRET_VALUE); expect(run.output.text()).not.toContain(SECRET_VALUE); const evidence = run.output.text().match(/evidence=(\S+)/)?.[1] ?? ""; @@ -64,13 +64,13 @@ describe("aws-spot lanes", () => { expect(readFileSync(join(evidence, "run.log"), "utf8")).toBe("== packages\nlane acceptance ran\n"); }); - test("a lane's exit code is the run's, and a dropped session is interrupted", async () => { + test("a lane's exit code is the run's, and a dropped session is resumed", async () => { const run = await awsRun(); - await Bun.write(join(run.state, "scenario.json"), JSON.stringify({ exits: { acceptance: 4, integration: "drop" } })); + await Bun.write(join(run.state, "scenario.json"), JSON.stringify({ exits: { acceptance: 4 }, drops: { integration: 1 } })); expect(await burst(LANES, run.dependencies)).toBe(4); expect(run.output.text()).toMatch(/lane=acceptance .* exit=4 /); - expect(run.output.text()).toMatch(/lane=integration .* exit=interrupted /); + expect(run.output.text()).toMatch(/lane=integration .* exit=0 /); }); test("an instance gone before it answers is interrupted, and still terminated", async () => { @@ -140,18 +140,6 @@ describe("aws-spot lanes", () => { expect(run.ec2.inputs("TerminateInstances").length).toBeGreaterThanOrEqual(1); }); - test("a caller that cannot learn its address is refused before anything is registered or written", async () => { - const root = burstRepository(); - const { bin, state } = fakeBin(); - const run = await awsRun(); - const unreachable = async () => new Response("", { status: 503 }); - const { dependencies } = burstDependencies(root, burstEnvironment(bin, state), unreachable); - - await expect(burst(["acceptance", "--provider", "aws-spot"], dependencies)).rejects.toThrow("could not learn this machine's public IPv4 address"); - expect(run.ec2.calls).toHaveLength(0); - expect([...new Bun.Glob("**/*").scanSync({ cwd: state, onlyFiles: true })].filter((path) => path.startsWith("out/"))).toEqual([]); - }); - test("ORLY_BURST_MARKET=on-demand rents a lane on demand that still terminates when it shuts down", async () => { const run = await awsRun({}, {}, { ORLY_BURST_MARKET: "on-demand" }); @@ -179,7 +167,7 @@ describe("aws-spot snapshots", () => { const launch = run.ec2.inputs("RunInstances")[0] ?? {}; expect(launch).not.toHaveProperty("InstanceMarketOptions"); expect(launch.InstanceInitiatedShutdownBehavior).toBe("stop"); - const job = machineScript(run.state, "198.51.100.1"); + const job = machineScript(run.state, "100.64.0.1"); expect(job).toContain("BURST_MODE='warm'"); expect(job).not.toContain("export API_TOKEN"); expect(existsSync(join(run.state, "op-calls.txt"))).toBe(false); diff --git a/src/burst/aws.ts b/src/burst/aws.ts index 19bfa986..7b53a6a1 100644 --- a/src/burst/aws.ts +++ b/src/burst/aws.ts @@ -3,7 +3,7 @@ import type { BurstSettings } from "./settings"; import type { BurstRun, CloudProvider, Image, Job, Machine, Snapshot, SnapshotScope } from "./types"; import { - _InstanceType as INSTANCE_TYPES, AuthorizeSecurityGroupIngressCommand, CreateImageCommand, CreateSecurityGroupCommand, DeleteKeyPairCommand, DeleteSecurityGroupCommand, + _InstanceType as INSTANCE_TYPES, CreateImageCommand, CreateSecurityGroupCommand, DeleteKeyPairCommand, DeleteSecurityGroupCommand, DeleteSnapshotCommand, DeregisterImageCommand, DescribeImagesCommand, DescribeInstancesCommand, DescribeSecurityGroupsCommand, DescribeSpotPriceHistoryCommand, EC2Client, ImportKeyPairCommand, RunInstancesCommand, StopInstancesCommand, TerminateInstancesCommand, } from "@aws-sdk/client-ec2"; @@ -42,8 +42,9 @@ const FAILED_IMAGE_STATES = new Set(["failed", "error", "invalid", "deregistered const SNAPSHOT_DOLLARS_PER_GB_MONTH = 0.05; // EC2 through the AWS SDK. Each run imports its public key and makes a -// security group open to SSH from the caller's address alone; both go when -// the run's instances have. A lane is a one-time Spot instance that +// security group with no inbound rule, since the caller reaches its instances +// over the tailnet each one joins from its user data; both go when the run's +// instances have. A lane is a one-time Spot instance that // terminates when it shuts down, unless ORLY_BURST_MARKET says on-demand; a // snapshot warm-up is on demand, so it can stop to be imaged. The SDK retries // throttling and transient failures inside each call, so an error that @@ -90,23 +91,20 @@ export class AwsSpot implements CloudProvider { this.#started = true; await this.#ec2.send(new ImportKeyPairCommand({ KeyName: name, PublicKeyMaterial: new TextEncoder().encode(run.publicKey), TagSpecifications: tagged("key-pair", run.runId) }), { abortSignal: run.signal }) .catch(duplicateIsMade); - const group = await this.#ec2.send(new CreateSecurityGroupCommand({ GroupName: name, Description: `orly burst ${run.runId}: SSH from the caller only`, TagSpecifications: tagged("security-group", run.runId) }), { abortSignal: run.signal }) + const group = await this.#ec2.send(new CreateSecurityGroupCommand({ GroupName: name, Description: `orly burst ${run.runId}: no inbound rule, reached over Tailscale`, TagSpecifications: tagged("security-group", run.runId) }), { abortSignal: run.signal }) .catch(duplicateIsMade); this.#group = group?.GroupId ?? await this.#groupNamed(name); - await this.#ec2.send(new AuthorizeSecurityGroupIngressCommand({ - GroupId: this.#group, IpPermissions: [{ IpProtocol: "tcp", FromPort: 22, ToPort: 22, IpRanges: [{ CidrIp: `${run.caller}/32` }] }], - }), { abortSignal: run.signal }).catch(duplicateIsMade); - run.write(done(`${name} admits SSH from ${run.caller} only`)); + run.write(done(`${name} opens no inbound port; the run's instances are reached over the tailnet`)); } - async create(run: BurstRun, job: Job): Promise { + async create(run: BurstRun, job: Job, boot: string): Promise { const spot = job.kind === "lane" && this.#settings.aws.market !== "on-demand"; const root = await this.#rootDevice(job.image, run.signal); let refusal = ""; for (const type of this.#settings.aws.types) { if (!isInstanceType(type)) throw new OrlyError(`burst.aws.instance_types names ${type}, which EC2 does not offer`); try { - const launched = await this.#ec2.send(this.#runInstances(run, job, type, spot, root), { abortSignal: run.signal }); + const launched = await this.#ec2.send(this.#runInstances(run, job, type, spot, root, boot), { abortSignal: run.signal }); const instance = launched.Instances?.[0]; const id = instance?.InstanceId; if (!id) throw new OrlyError("run-instances answered no instance"); @@ -204,9 +202,12 @@ export class AwsSpot implements CloudProvider { .catch((error: unknown) => run.write(failed(`could not delete key pair ${name}: ${messageOf(error)}; delete it by hand`))); } - #runInstances(run: BurstRun, job: Job, type: _InstanceType, spot: boolean, root: string): RunInstancesCommand { + // cloud-init runs `boot` once, at the instance's first boot; a snapshot's + // instance is a new one, so it runs there too. + #runInstances(run: BurstRun, job: Job, type: _InstanceType, spot: boolean, root: string, boot: string): RunInstancesCommand { return new RunInstancesCommand({ ImageId: job.image.id, InstanceType: type, MinCount: 1, MaxCount: 1, KeyName: runName(run), SecurityGroupIds: this.#group ? [this.#group] : [], + UserData: Buffer.from(boot).toString("base64"), ...(spot ? { InstanceMarketOptions: { MarketType: "spot", SpotOptions: { SpotInstanceType: "one-time", InstanceInterruptionBehavior: "terminate" } } } : {}), // A lane's machine is gone when it shuts down, on either market; only a // warm-up stops, so it can be imaged. diff --git a/src/burst/cancellation.integration.test.ts b/src/burst/cancellation.integration.test.ts index e44e5092..06ca985a 100644 --- a/src/burst/cancellation.integration.test.ts +++ b/src/burst/cancellation.integration.test.ts @@ -1,6 +1,7 @@ import { afterEach, expect, setSystemTime, test } from "bun:test"; import { cleanupTemporaryDirectories } from "../gates_test_support"; +import { FakeTailscale } from "./fake_tailscale"; import { FakeTir } from "./fake_tir"; import { burst } from "./index"; import { burstSettings } from "./settings"; @@ -113,6 +114,6 @@ test("same-instant snapshots have distinct names and legacy snapshots are never function fixture() { const root = burstRepository(); const { bin, state } = fakeBin(); - const api = new FakeTir(); + const api = new FakeTir(new FakeTailscale(state)); return { api, ...burstDependencies(root, burstEnvironment(bin, state, CREDENTIALS), api.fetch) }; } diff --git a/src/burst/cloud.ts b/src/burst/cloud.ts index b03980b6..ab9d80c1 100644 --- a/src/burst/cloud.ts +++ b/src/burst/cloud.ts @@ -1,20 +1,23 @@ import type { Environment } from "./settings"; import type { StagedDirectory } from "./ssh"; +import type { AuthKey } from "./tailnet"; import type { BurstRun, CloudProvider, Image, Job, LaneResult, Machine, Snapshot, SnapshotScope, Status } from "./types"; import { mkdirSync } from "node:fs"; import { join } from "node:path"; -import { remoteScript } from "./job"; +import { bootScript, FORGET, remoteScript } from "./job"; import { done, failed, ongoing } from "./progress"; -import { resolveSecrets } from "./process"; -import { archiveDirectories, forgetRunFiles, reachable, runOverSsh } from "./ssh"; -import { LANE_PREFIX, MINUTE_MS } from "./types"; +import { machineDeadline, resolveSecrets } from "./process"; +import { archiveDirectories, forgetRunFiles, leaveTailnet, reachable, runOverSsh } from "./ssh"; +import { LANE_PREFIX, MINUTE_MS, runTail } from "./types"; import { messageOf, OrlyError } from "../model"; // What only a lane receives: its secrets and its copied directories. type LaneInputs = { secrets: Environment; directories: readonly StagedDirectory[] }; type NamedSnapshot = { snapshot: Snapshot; stamp: string; digest: string }; +// A machine on the tailnet, as `node`, at its tailnet address. +type Joined = Machine & { node: string }; const NO_INPUTS: LaneInputs = Object.freeze({ secrets: {}, directories: [] }); const SNAPSHOT_JOB = "snapshot"; @@ -24,6 +27,8 @@ const KEEP = 1; // then 4 random ones, so two captures in one millisecond still differ. const SUFFIX_CHARS = 8; const IMAGE_DIGEST_CHARS = 4; +// How long a warm-up machine is given to leave the tailnet before it is imaged. +const LEAVE_MS = 2 * MINUTE_MS; // Every lane gets its own machine, all at once. Secrets are resolved here, // on the caller, before anything is rented. A lane's machine is deleted when @@ -57,14 +62,15 @@ export async function cloudSnapshot(provider: CloudProvider, run: BurstRun): Pro requireActive(run); await provider.prepare(run); requireActive(run); - machine = await provider.create(run, job); - machine = await provider.ready(run, job, machine); + const joined = await start(provider, run, job, (started) => { machine = started; }); + machine = joined; await reachable(run, job, machine, provider.user); const status = await runOverSsh(run, job, machine, provider.user, await script(run, job, NO_INPUTS), []); if (status !== 0) { run.write(failed(`the warm-up ended with exit=${status}; no snapshot was taken`)); return undefined; } + machine = await leaveForCapture(provider, run, joined); return await provider.capture(run, job, machine, snapshotName(run.repo, image, new Date())); } finally { if (machine) await release(provider, run, machine); @@ -111,8 +117,7 @@ async function cloudLane(provider: CloudProvider, run: BurstRun, job: Job, input let status: Status = "unlaunched"; try { requireActive(run); - machine = await provider.create(run, job); - machine = await provider.ready(run, job, machine); + machine = await start(provider, run, job, (started) => { machine = started; }); await reachable(run, job, machine, provider.user); status = await runOverSsh(run, job, machine, provider.user, await script(run, job, inputs), inputs.directories); if (status === "not_run") run.write(failed(`lane=${job.name} the machine or burst.setup failed before the lane started; see ${join(job.evidence, "run.log")}`)); @@ -126,6 +131,49 @@ async function cloudLane(provider: CloudProvider, run: BurstRun, job: Job, input return { lane: job.name, provider: provider.name, machine: machine?.label ?? "none", minutes, cost: machine ? provider.cost(machine) : "none", status, evidence: job.evidence }; } +// A machine boots holding a key minted for it alone, joins the caller's +// tailnet and is reached at its tailnet address. The key is deleted once the +// machine has joined, or has failed to. `started` learns each stage of the +// machine, so whatever ends the start, the caller still deletes it. +async function start(provider: CloudProvider, run: BurstRun, job: Job, started: (machine: Machine) => void): Promise { + const node = `orly-burst-${job.name}-${runTail(run.runId)}`; + const key = await run.tailnet.mint(node); + try { + const created = { ...await provider.create(run, job, bootScript(node, key.secret)), node }; + started(created); + const running = await provider.ready(run, job, created); + started(running); + run.write(ongoing(`waiting for ${node} to join the tailnet`)); + const address = await run.tailnet.joined(node, { deadline: machineDeadline(job), signal: run.signal, pollMs: run.settings.pollMs }); + run.write(done(`${node} joined the tailnet at ${address}`)); + const joined = { ...running, address, node }; + started(joined); + return joined; + } finally { + await forgetKey(run, key, node); + } +} + +async function forgetKey(run: BurstRun, key: AuthKey, node: string): Promise { + try { + await run.tailnet.revoke(key); + run.write(done(`deleted the tailnet key ${key.id} of ${node}`)); + } catch (error) { + run.write(failed(`could not delete the tailnet key ${key.id} of ${node}: ${messageOf(error)}; delete it in the Tailscale admin console`)); + } +} + +// A snapshot of a machine still on the tailnet would boot every later lane +// as that node, so the warm-up leaves first, and is not imaged if it cannot. +async function leaveForCapture(provider: CloudProvider, run: BurstRun, machine: Joined): Promise { + const { node } = machine; + run.write(ongoing(`${node} leaves the tailnet before it is imaged`)); + if (!await leaveTailnet(run, machine, provider.user, FORGET)) throw new OrlyError(`could not log ${node} out of the tailnet; no snapshot was taken`); + await run.tailnet.left(node, { deadline: Date.now() + LEAVE_MS, signal: run.signal, pollMs: run.settings.pollMs }); + run.write(done(`${node} left the tailnet`)); + return { ...machine, node: undefined }; +} + function script(run: BurstRun, job: Job, inputs: LaneInputs): Promise { const burst = run.config.burst ?? {}; const lane = job.kind === "lane" ? inputs : NO_INPUTS; @@ -139,6 +187,14 @@ function script(run: BurstRun, job: Job, inputs: LaneInputs): Promise { // A machine that outlives its run bills until someone deletes it, so a failed // delete is said loudly, with the identifier to delete by hand. async function release(provider: CloudProvider, run: BurstRun, machine: Machine): Promise { + // The node is looked up afresh, so one that joined after the run stopped + // waiting for it is logged out too. + const node = machine.node; + const address = node ? await run.tailnet.find(node).catch(() => undefined) : undefined; + if (node && address) { + const left = await leaveTailnet(run, { ...machine, address }, provider.user).catch(() => false); + run.write(left ? done(`${node} is leaving the tailnet`) : failed(`${node} did not log out; as an ephemeral node it leaves the tailnet once offline, or remove it in the Tailscale admin console`)); + } try { run.write(ongoing(`deleting ${provider.name} machine ${machine.id}`)); await provider.remove(machine); diff --git a/src/burst/e2e-cleanup.test.ts b/src/burst/e2e-cleanup.test.ts index c8491854..66be75d6 100644 --- a/src/burst/e2e-cleanup.test.ts +++ b/src/burst/e2e-cleanup.test.ts @@ -4,6 +4,7 @@ import { join } from "node:path"; import { burst } from "./index"; import { UNSCOPED_ENVIRONMENT } from "../git_env"; +import { FakeTailscale } from "./fake_tailscale"; import { FakeTir } from "./fake_tir"; import { created, CREDENTIALS, e2eRun, LANES, machineScript, ONE_LANE } from "./e2e-test-support"; import { burstDependencies, burstEnvironment, burstRepository, fakeBin } from "./test_support"; @@ -15,7 +16,7 @@ afterEach(cleanupTemporaryDirectories); describe("e2e cleanup, failures and what a warm machine is sent", () => { describe("what a warm machine is sent", () => { function sent(run: ReturnType): string | undefined { - const machine = [...new Bun.Glob("203.0.113.*").scanSync({ cwd: run.state, onlyFiles: false })][0] ?? ""; + const machine = [...new Bun.Glob("100.64.*").scanSync({ cwd: run.state, onlyFiles: false })][0] ?? ""; const bundle = join(run.state, machine, "repo.bundle"); return existsSync(bundle) ? bundle : undefined; } @@ -70,7 +71,7 @@ describe("e2e cleanup, failures and what a warm machine is sent", () => { test("a cancelled run deletes the VM it started and its key", async () => { const root = burstRepository(); const { bin, state } = fakeBin(); - const api = new FakeTir(); + const api = new FakeTir(new FakeTailscale(state)); const controller = new AbortController(); await Bun.write(join(state, "scenario.json"), JSON.stringify({ sleepMs: 2_000 })); const { dependencies, output } = burstDependencies(root, burstEnvironment(bin, state, CREDENTIALS), api.fetch, controller.signal); diff --git a/src/burst/e2e-test-support.ts b/src/burst/e2e-test-support.ts index cb2a4a0e..49b66492 100644 --- a/src/burst/e2e-test-support.ts +++ b/src/burst/e2e-test-support.ts @@ -3,6 +3,7 @@ import { readFileSync } from "node:fs"; import { join } from "node:path"; +import { FakeTailscale } from "./fake_tailscale"; import { FakeTir } from "./fake_tir"; import { burstDependencies, burstEnvironment, burstRepository, fakeBin, fields, REPOSITORY } from "./test_support"; @@ -19,13 +20,14 @@ export const VM = /^\/notebooks\/\d+\/$/; export function e2eRun(extra: Record = {}, burstConfig: Record = {}) { const root = burstRepository(burstConfig); const { bin, state } = fakeBin(); - const api = new FakeTir(); + const tailnet = new FakeTailscale(state); + const api = new FakeTir(tailnet); const env = burstEnvironment(bin, state, { ...CREDENTIALS, ...extra }); - return { root, state, api, env, ...burstDependencies(root, env, api.fetch) }; + return { root, state, api, tailnet, env, ...burstDependencies(root, env, api.fetch) }; } export function machineScript(state: string): string { - const machine = [...new Bun.Glob("203.0.113.*").scanSync({ cwd: state, onlyFiles: false })][0] ?? ""; + const machine = [...new Bun.Glob("100.64.*").scanSync({ cwd: state, onlyFiles: false })][0] ?? ""; return readFileSync(join(state, machine, "job.sh"), "utf8"); } diff --git a/src/burst/e2e.test.ts b/src/burst/e2e.test.ts index b4c26e0a..56ebaf71 100644 --- a/src/burst/e2e.test.ts +++ b/src/burst/e2e.test.ts @@ -7,7 +7,8 @@ import { tirLabel } from "./e2e"; import { MACHINE_WAIT_MS, machineDeadline } from "./process"; import { DEBIAN_13 } from "./fake_tir"; import { API_KEY, AUTH_TOKEN, CREATE, e2eRun, LANES, machineScript, ONE_LANE, SECRETS, VM } from "./e2e-test-support"; -import { burstDependencies, CALLER_ADDRESS, fields, recordedCalls, SECRET_VALUE } from "./test_support"; +import { CLIENT_SECRET } from "./fake_tailscale"; +import { fields, recordedCalls, SECRET_VALUE } from "./test_support"; import { cleanupTemporaryDirectories, git, temporaryDirectory } from "../gates_test_support"; setDefaultTimeout(60_000); @@ -42,14 +43,18 @@ describe("e2e lanes on TIR virtual machines", () => { const group = fields(run.api.callsTo("POST", /^\/security_groups\/$/)[0]?.body); expect(String(group.name)).toMatch(/^orly-burst-feat-burst-fixture-\d{14}-[0-9a-f]{4}$/); expect(group.rules).toEqual([ - { rule_type: "inbound", protocol: "TCP", protocol_type: "CustomTCP", network_type: "manual", cidr_ip: CALLER_ADDRESS, cidr_subnet: 32, ports: [22], description: "SSH from the orly burst caller" }, + { rule_type: "inbound", protocol: "UDP", protocol_type: "CustomUDP", network_type: "any", ports: [41641], description: "Tailscale WireGuard for the orly burst machine" }, { rule_type: "outbound", protocol: "All", protocol_type: "AllTraffic", network_type: "any", ports: [], description: "All traffic from the orly burst machine" }, ]); expect(run.api.groups.size).toBe(0); + expect(body.init_script_id_list).toEqual([300]); + expect(run.api.scripts.size).toBe(0); const order = run.api.calls.map((call) => `${call.method} ${call.path}`); expect(order.lastIndexOf("DELETE /notebooks/5002/")).toBeLessThan(order.indexOf("DELETE /security_groups/700/")); const text = run.output.text(); - expect(text).toContain(`admits SSH from ${CALLER_ADDRESS} only`); + expect(text).toContain("opens no SSH port; the run's VMs are reached over the tailnet"); + expect(text).toContain("caller-laptop is on the tailnet"); + expect(text).toMatch(/🟢 orly-burst-acceptance-\d{14}-[0-9a-f]{4} joined the tailnet at 100\.64\.0\.\d/); expect(text).toContain("[acceptance] lane acceptance ran"); expect(text).toMatch(/orly burst: lane=acceptance provider=e2e machine=C3\.32GB minutes=\d+ cost≈₹25\/h \+ GST \(billed hourly\) exit=0 evidence=\S+/); expect(text).toContain("orly burst: total provider=e2e lanes=2 passed=2 failed=0"); @@ -59,6 +64,8 @@ describe("e2e lanes on TIR virtual machines", () => { expect(text).toMatch(/orly burst: 🟢 deleted TIR key orly-burst-/); expect(text).toContain("orly burst: 🟢 deleted TIR security group 700"); expect(text).not.toContain(API_KEY); + expect(text).not.toContain(CLIENT_SECRET); + expect(text).not.toContain("tskey-fake-auth"); }); test("a branch name past 19 characters still fits TIR's 50-character key label", async () => { @@ -123,17 +130,6 @@ describe("e2e lanes on TIR virtual machines", () => { expect(run.api.groups.size).toBe(0); }); - test("a caller address that cannot be learnt stops the run before any VM, and the key still goes", async () => { - const run = e2eRun(); - const answer = run.api.fetch; - const { dependencies } = burstDependencies(run.root, run.env, async (input, init) => String(input).includes("checkip") ? new Response("", { status: 503 }) : answer(input, init)); - - await expect(burst(ONE_LANE, dependencies)).rejects.toThrow("could not learn this machine's public IPv4 address"); - expect(run.api.callsTo("POST", CREATE)).toHaveLength(0); - expect(run.api.groups.size).toBe(0); - expect(run.api.keys.size).toBe(0); - }); - test("secrets are read on the caller and reach the lane only through the session's input", async () => { const run = e2eRun({}, SECRETS); @@ -183,7 +179,7 @@ describe("e2e lanes on TIR virtual machines", () => { expect(await burst(ONE_LANE, run.dependencies)).toBe(0); - const machine = [...new Bun.Glob("203.0.113.*").scanSync({ cwd: run.state, onlyFiles: false })][0] ?? ""; + const machine = [...new Bun.Glob("100.64.*").scanSync({ cwd: run.state, onlyFiles: false })][0] ?? ""; const listed = Bun.spawnSync(["tar", "-tzf", join(run.state, machine, "input-TOOLBOX_DIR.tgz")], { stdout: "pipe" }).stdout.toString(); expect(listed).toContain("./toolbox-0000.erofs"); const job = machineScript(run.state); @@ -202,13 +198,14 @@ describe("e2e lanes on TIR virtual machines", () => { expect(run.api.callsTo("POST", CREATE)).toHaveLength(0); }); - test("a lane's own exit code is the run's, and a dropped session is interrupted", async () => { + test("the exit code the machine wrote is the lane's, whatever ended the session", async () => { const run = e2eRun(); - await Bun.write(join(run.state, "scenario.json"), JSON.stringify({ exits: { acceptance: 3, integration: "drop" } })); + await Bun.write(join(run.state, "scenario.json"), JSON.stringify({ exits: { acceptance: 3 }, drops: { integration: 1 } })); expect(await burst(LANES, run.dependencies)).toBe(3); expect(run.output.text()).toMatch(/lane=acceptance .* exit=3 /); - expect(run.output.text()).toMatch(/lane=integration .* exit=interrupted /); + expect(run.output.text()).toMatch(/lane=integration .* exit=0 /); + expect(recordedCalls(run.state).filter((call) => call.at(-1)?.endsWith("cat /run/orly-burst/exit"))).toHaveLength(2); expect(run.api.vms.size).toBe(0); }); @@ -217,26 +214,12 @@ describe("e2e lanes on TIR virtual machines", () => { expect(machineDeadline({ deadline: 5_000 }, 1_000)).toBe(5_000); }); - test("a caller whose address changes mid-run ends the lane at once, naming both addresses", async () => { - const run = e2eRun(); - run.api.callerMovesTo = "203.0.113.200"; - await Bun.write(join(run.state, "scenario.json"), JSON.stringify({ unreachable: true })); - - expect(await burst(ONE_LANE, run.dependencies)).toBe(1); - const text = run.output.text(); - expect(text).toContain("orly burst: ⏳ waiting for SSH on 203.0.113."); - expect(text).toContain(`🔴 lane=acceptance this machine's address changed from ${CALLER_ADDRESS} to 203.0.113.200, and the run admits SSH from ${CALLER_ADDRESS} only; run it again from this network`); - expect(recordedCalls(run.state).filter((call) => call.at(-1) === "true")).toHaveLength(3); - expect(text).toMatch(/lane=acceptance .* exit=interrupted /); - expect(run.api.vms.size).toBe(0); - }); - test("SSH that never answers ends the wait with ssh's own error, and the VM still goes", async () => { const run = e2eRun({ ORLY_BURST_DEADLINE_MINUTES: "0.01" }); await Bun.write(join(run.state, "scenario.json"), JSON.stringify({ unreachable: true })); expect(await burst(ONE_LANE, run.dependencies)).toBe(1); - expect(run.output.text()).toMatch(/🔴 lane=acceptance the deadline passed while waiting for SSH to 203\.0\.113\.\d+: ssh: connect to host 203\.0\.113\.\d+ port 22: Operation timed out/); + expect(run.output.text()).toMatch(/🔴 lane=acceptance the deadline passed while waiting for SSH to 100\.64\.0\.\d+: ssh: connect to host 100\.64\.0\.\d+ port 22: Operation timed out/); expect(run.output.text()).not.toContain("answers"); expect(run.api.vms.size).toBe(0); }); diff --git a/src/burst/e2e.ts b/src/burst/e2e.ts index 0c5c927d..4d0f7fd3 100644 --- a/src/burst/e2e.ts +++ b/src/burst/e2e.ts @@ -5,13 +5,21 @@ import type { OsImage, Plan, VmSnapshot } from "./tir"; import { messageOf, OrlyError } from "../model"; import { machineDeadline, pause, until } from "./process"; import { done, failed, ongoing } from "./progress"; +import { MAX_DEADLINE_MINUTES } from "./settings"; import { E2eApi, E2eRequestFailed } from "./tir"; +import { MINUTE_MS, runBegan, runTail } from "./types"; // TIR caps a key label at 50 characters. A run id ends in its 14-digit stamp // and 4-character suffix, which keep labels unique, so the ref part is cut. export const TIR_LABEL_LIMIT = 50; const LABEL_PREFIX = "orly-burst-"; const RUN_ID_TAIL = 20; +// A start script is named `obs--`, within TIR's 50 +// characters. One whose run began longer ago than any run may last, with +// its staging before the deadline starts and its cleanup after, is an +// orphan of a run that died, and a later run's teardown deletes it. +const SCRIPT_PREFIX = "obs-"; +const ORPHAN_AGE_MS = MAX_DEADLINE_MINUTES * MINUTE_MS + 60 * MINUTE_MS; const DEFAULT_IMAGE = "Debian 13"; // How long VM deletion, then the group's delete, are waited for before each // is reported for deletion by hand. @@ -37,10 +45,13 @@ const RUPEES_PER_HOUR = 25; const RUPEES_PER_SNAPSHOT_MONTH = 200; // E2E Networks TIR virtual machines: whole Linux machines with their own -// kernel, reached as root over SSH. TIR accepts only a public key already -// saved in the account, so each run saves its key; each run also makes a -// security group admitting SSH from the caller's address alone. Both go when -// the run's VMs have. The client retries TIR's busy answers (tir.ts). +// kernel, reached as root over SSH through the caller's tailnet. TIR accepts +// only a public key already saved in the account, so each run saves its key; +// each run also makes a security group that opens no SSH port. Each VM boots +// a start script of its own, which joins it to the tailnet; TIR has no user +// data, and a start script is how a VM runs a command before anyone can reach +// it. The key, the group and the scripts go when the run's VMs have. The +// client retries TIR's busy answers (tir.ts). export class E2eNodes implements CloudProvider { readonly name = "e2e"; readonly user: string; @@ -55,6 +66,9 @@ export class E2eNodes implements CloudProvider { readonly #statuses = new Map(); // VMs whose create request failed after it may have reached TIR. readonly #unconfirmed = new Set(); + // Each VM's start script, deleted once the VM is gone; finish deletes the + // rest by name. + readonly #scripts = new Map(); constructor(settings: BurstSettings, fetcher: Fetch) { this.#settings = settings; @@ -85,27 +99,29 @@ export class E2eNodes implements CloudProvider { this.#label = name; await this.#api.addKey(name, run.publicKey, run.signal); this.#keyConfirmed = true; - this.#group = await this.#api.createSshGroup(name, run.caller, run.signal); - run.write(done(`${name} admits SSH from ${run.caller} only`)); + this.#group = await this.#api.createGroup(name, run.signal); + run.write(done(`${name} opens no SSH port; the run's VMs are reached over the tailnet`)); } - async create(run: BurstRun, job: Job): Promise { + async create(run: BurstRun, job: Job, boot: string): Promise { const plan = await this.#resolvePlan(run.signal); const source = job.image.snapshot ? await this.#snapshotSource(job.image.id, run.signal) : await this.#osImage(job.image.name, run.signal); const name = `orly-burst-${job.name}-${run.runId.slice(-4)}`; + const script = await this.#api.createStartScript(scriptPrefix(run.runId) + job.name, boot, run.signal); let id: string; try { id = await this.#api.createVm({ name, kind: "vm", cluster_type: "tir-cluster", image_type: "pre-built", image_version_id: source.versionId, - sku_item_price_id: plan.priceId, disk_size_in_gb: DISK_GB, quantity: 1, + sku_item_price_id: plan.priceId, disk_size_in_gb: DISK_GB, quantity: 1, init_script_id_list: [Number(script)], public_key: [run.publicKey], security_group_id: Number(this.#group), ...(source.snapshotId ? { snapshot_id: Number(source.snapshotId) } : {}), }, run.signal); } catch (error) { // A request that failed after reaching TIR may still have made the VM; - // finish looks for it by name. + // finish looks for it by name, then deletes the script it held. if (!(error instanceof E2eRequestFailed && error.status < SERVER_ERROR)) this.#unconfirmed.add(name); throw error; } + this.#scripts.set(id, script); run.write(done(`lane=${job.name} VM ${id} (${plan.sku}, ${job.image.name}) created`)); return { id, label: plan.sku, address: undefined }; } @@ -153,6 +169,10 @@ export class E2eNodes implements CloudProvider { // cancellation: it is what a cancellation runs. async remove(machine: Machine): Promise { await this.#deleteVm(machine.id); + // A script whose delete fails stays listed, for finish to retry and report. + const script = this.#scripts.get(machine.id); + if (!script) return; + await this.#api.deleteStartScript(script).catch(goneIsDeleted).then(() => this.#scripts.delete(machine.id), () => undefined); } // Each VM's status is written once per change, so a status orly does not @@ -187,6 +207,7 @@ export class E2eNodes implements CloudProvider { const label = this.#label; if (!label) return; if (this.#unconfirmed.size > 0) await this.#sweep(run); + await this.#deleteScripts(run); try { const pk = (await this.#api.keys()).find((key) => key.label === label)?.pk; if (pk) { @@ -221,6 +242,24 @@ export class E2eNodes implements CloudProvider { } } + // A start script outlives its VM when the VM was never made, the create's + // reply was lost, or the delete failed; it holds a key already deleted. + // This run's are found by name, with any a dead run left behind. + async #deleteScripts(run: BurstRun): Promise { + const listed = await this.#api.startScripts().catch((error: unknown) => { + run.write(failed(`could not list TIR start scripts: ${messageOf(error)}; delete any named ${scriptPrefix(run.runId)}* by hand`)); + return []; + }); + const mine = scriptPrefix(run.runId); + for (const script of listed.filter((candidate) => candidate.name.startsWith(mine) || orphaned(candidate.name))) { + await this.#api.deleteStartScript(script.id).catch(goneIsDeleted) + .then(() => run.write(done(`deleted TIR start script ${script.id} (${script.name})`))) + .catch((error: unknown) => run.write(error instanceof E2eRequestFailed && IN_USE.has(error.status) + ? ongoing(`TIR start script ${script.id} (${script.name}) is still used by a VM; it goes with that VM, or at a later run's teardown`) + : failed(`could not delete TIR start script ${script.id} (${script.name}): ${messageOf(error)}; delete it by hand`))); + } + } + #resolvePlan(signal: AbortSignal): Promise { const { plan: sku, location } = this.#settings.e2e; this.#plan ??= this.#api.plans(signal).then((plans) => { @@ -261,6 +300,16 @@ function toSnapshot(snapshot: VmSnapshot): Snapshot { } +// A run id ends in `<14-digit stamp>-<4 hexadecimal characters>`. +function scriptPrefix(runId: string): string { + return `${SCRIPT_PREFIX}${runTail(runId)}-`; +} + +function orphaned(name: string): boolean { + const began = name.startsWith(SCRIPT_PREFIX) ? runBegan(name.slice(SCRIPT_PREFIX.length).split("-").slice(0, 2).join("-")) : undefined; + return began !== undefined && Date.now() - began > ORPHAN_AGE_MS; +} + export function tirLabel(runId: string): string { const tail = runId.slice(-RUN_ID_TAIL); const ref = runId.slice(0, -RUN_ID_TAIL).slice(0, TIR_LABEL_LIMIT - LABEL_PREFIX.length - RUN_ID_TAIL).replace(/-+$/, ""); diff --git a/src/burst/fake_ssh.ts b/src/burst/fake_ssh.ts index 727f5852..6d3af30d 100644 --- a/src/burst/fake_ssh.ts +++ b/src/burst/fake_ssh.ts @@ -1,16 +1,27 @@ // A stand-in for `ssh`, for the cloud tests. Each machine is a directory under -// FAKE_SSH_STATE named by its address. It stores the staged bundle, records -// the job script it was handed on standard input, plays the job a line at a -// time, answers the results request, and records every call's arguments. +// FAKE_SSH_STATE named by its tailnet address. It stores the staged bundle, +// records the job script it was launched with, plays that job detached a line +// at a time into its log, follows the log from the offset it is asked for, +// answers the exit code and the results request, and records every call's +// arguments. import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; -// unreachable: no machine's SSH answers, as when a security group stops admitting the caller. -// warmCommit: the commit every machine's warm checkout holds; unset, machines are cold. -type Scenario = { exits?: Record; sleepMs?: number; unreachable?: boolean; warmCommit?: string }; +import { leaveTailnet } from "./fake_tailscale"; + +// unreachable: no machine's SSH answers. warmCommit: the commit every +// machine's warm checkout holds; unset, machines are cold. drops: how many +// sessions following a lane's log are cut after its first line. lost: lanes +// whose machine never answers again once a session was cut. cutUpload: the +// first launch's session is lost before the whole job script arrived. +type Scenario = { exits?: Record; sleepMs?: number; unreachable?: boolean; warmCommit?: string; drops?: Record; lost?: string[]; cutUpload?: boolean }; const RESULTS_MARKER = 'tar -czf - "$@"'; const NO_RESULTS = 3; +const NO_JOB = 3; +const SSH_LOST = 255; +const UPLOAD_CUT = 4; +const FOLLOW_POLL_MS = 5; const state = process.env.FAKE_SSH_STATE ?? ""; const argv = Bun.argv.slice(2); appendFileSync(join(state, "calls.jsonl"), `${JSON.stringify(["ssh", ...argv])}\n`); @@ -22,11 +33,8 @@ const scenario: Scenario = existsSync(join(state, "scenario.json")) ? JSON.parse process.exit(await dispatch()); async function dispatch(): Promise { - if (command === "true") { - if (!scenario.unreachable) return 0; - process.stderr.write(`ssh: connect to host ${address} port 22: Operation timed out\n`); - return 255; - } + if (existsSync(join(node, "gone"))) return lostConnection(); + if (command === "true") return scenario.unreachable ? lostConnection() : 0; if (command.endsWith("rev-parse --verify --quiet HEAD")) { if (!scenario.warmCommit) return 128; process.stdout.write(`${scenario.warmCommit}\n`); @@ -41,30 +49,83 @@ async function dispatch(): Promise { writeFileSync(join(node, `input-${input}.tgz`), Buffer.from(await Bun.stdin.arrayBuffer())); return 0; } + if (command.includes("mkdir /run/orly-burst/launched")) { + const script = await Bun.stdin.text(); + if (scenario.cutUpload && !existsSync(join(node, "cut"))) { + writeFileSync(join(node, "cut"), ""); + return lostConnection(); + } + const bytes = Number(command.match(/-ne (\d+)/)?.[1]); + if (Buffer.byteLength(script) !== bytes) return UPLOAD_CUT; + return launch(script); + } + const offset = command.match(/tail -c \+(\d+)/)?.[1]; + if (offset) return follow(Number(offset) - 1); + if (command.endsWith("cat /run/orly-burst/exit")) return exitCode(); + if (command.includes("tailscale logout")) { + leaveTailnet(state, address); + return 0; + } if (command === "bash -s" || command === "sudo -n bash -s") { const script = await Bun.stdin.text(); - return script.includes(RESULTS_MARKER) ? results() : job(script); + if (script.includes(RESULTS_MARKER)) return results(); } process.stderr.write(`fake ssh: unsupported ${command}\n`); return 2; } -async function job(script: string): Promise { +// The job runs detached, as the launcher starts it: it outlives this session +// and every later one, writing its log and then its exit code. +function launch(script: string): number { + if (existsSync(join(node, "launched"))) return 0; + writeFileSync(join(node, "launched"), ""); writeFileSync(join(node, "job.sh"), script); const value = (name: string) => script.match(new RegExp(`^BURST_${name}='([^']*)'`, "m"))?.[1] ?? ""; const lane = value("LANE"); - for (const line of ["== packages", `lane ${lane} ran`]) { - process.stdout.write(`${line}\n`); - await Bun.sleep(scenario.sleepMs ?? 5); - } if (value("MODE") === "lane") { const directory = join(node, "work"); mkdirSync(join(directory, "report"), { recursive: true }); writeFileSync(join(directory, "report", "summary.txt"), `lane ${lane} results\n`); Bun.spawnSync(["tar", "-czf", join(node, "results.tar.gz"), "-C", directory, "report"]); } - const outcome = scenario.exits?.[lane] ?? 0; - return outcome === "drop" ? 255 : outcome; + const pause = `sleep ${(scenario.sleepMs ?? 5) / 1000}`; + const play = [ + ...["== packages", `lane ${lane} ran`].map((line) => `printf '%s\\n' '${line}' >> run.log; ${pause}`), + `echo ${scenario.exits?.[lane] ?? 0} > exit.part && mv exit.part exit`, + ].join("; "); + Bun.spawn(["sh", "-c", play], { cwd: node, detached: true, stdin: "ignore", stdout: "ignore", stderr: "ignore" }).unref(); + return 0; +} + +// The log from `offset` until the job has written its exit code. A session +// the scenario cuts ends with ssh's own code after the log's first line. +async function follow(offset: number): Promise { + if (!existsSync(join(node, "launched"))) return NO_JOB; + const lane = readFileSync(join(node, "job.sh"), "utf8").match(/^BURST_LANE='([^']*)'/m)?.[1] ?? ""; + const dropped = existsSync(join(node, "drops")) ? Number(readFileSync(join(node, "drops"), "utf8")) : 0; + const cut = dropped < (scenario.drops?.[lane] ?? 0); + let sent = offset; + for (;;) { + const finished = existsSync(join(node, "exit")); + const log = existsSync(join(node, "run.log")) ? readFileSync(join(node, "run.log")) : Buffer.alloc(0); + if (log.length > sent) { + const end = cut ? log.indexOf("\n", sent) + 1 || log.length : log.length; + process.stdout.write(log.subarray(sent, end)); + sent = end; + if (cut) { + writeFileSync(join(node, "drops"), String(dropped + 1)); + if (scenario.lost?.includes(lane)) writeFileSync(join(node, "gone"), ""); + return lostConnection(); + } + } else if (finished) return 0; + await Bun.sleep(FOLLOW_POLL_MS); + } +} + +function exitCode(): number { + if (!existsSync(join(node, "exit"))) return 1; + process.stdout.write(readFileSync(join(node, "exit"))); + return 0; } function results(): number { @@ -72,3 +133,8 @@ function results(): number { process.stdout.write(readFileSync(join(node, "results.tar.gz"))); return 0; } + +function lostConnection(): number { + process.stderr.write(`ssh: connect to host ${address} port 22: Operation timed out\n`); + return SSH_LOST; +} diff --git a/src/burst/fake_tailscale.ts b/src/burst/fake_tailscale.ts new file mode 100644 index 00000000..30c4ced9 --- /dev/null +++ b/src/burst/fake_tailscale.ts @@ -0,0 +1,165 @@ +// Tailscale, for the burst tests, in two halves. In the test process, +// FakeTailscale answers the API orly mints and deletes keys through, and +// joins a machine to the tailnet when the fake cloud boots it with a key. Run +// as a program, this file is the caller's `tailscale` CLI, which prints +// `status --json` from the files the first half writes under +// FAKE_SSH_STATE/tailnet: the caller in self.json and one file per node. +import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; + +import { isObject } from "../model"; + +type Call = { method: string; path: string; body: string; authorization: string | null }; +type FakeKey = { id: string; secret: string; request: Record; used: boolean }; +type Peer = { HostName: string; Online: boolean; TailscaleIPs: string[]; Tags?: string[] }; + +const CLIENT_ID = "fake-client-id"; +export const CLIENT_SECRET = "tskey-fake-client-secret"; +export const TAILSCALE_CREDENTIALS = { TS_OAUTH_CLIENT_ID: CLIENT_ID, TS_OAUTH_CLIENT_SECRET: CLIENT_SECRET }; +const TOKEN = "fake-access-token"; +const JSON_HEADERS = { "Content-Type": "application/json" }; + +export class FakeTailscale { + readonly calls: Call[] = []; + // What happened to each key and node, in order: `mint k1`, `join k1 `, `delete k1`. + readonly events: string[] = []; + readonly keys = new Map(); + // The status a mint or a key delete answers with, to fail them. + mintStatus = 200; + deleteStatus = 200; + // A node that joins but never reads as online, as one still coming up when + // the run stops waiting. + joinOffline = false; + // Another device that claims each joining node's name, with these tags. + impostorTags: string[] | undefined; + readonly #directory: string; + #nextKey = 1; + #nextAddress = 1; + + constructor(state: string) { + this.#directory = join(state, "tailnet"); + mkdirSync(join(this.#directory, "peers"), { recursive: true }); + this.caller("Running", true); + } + + // What the caller's own Tailscale reports; `undefined` is no daemon at all. + caller(backend: string | undefined, online: boolean): void { + const self = join(this.#directory, "self.json"); + if (backend === undefined) rmSync(self, { force: true }); + else writeFileSync(self, JSON.stringify({ BackendState: backend, Self: { HostName: "caller-laptop", Online: online } })); + } + + fetch = async (input: string | URL | Request, init?: RequestInit): Promise => { + const request = input instanceof Request ? input : new Request(input, init); + const url = new URL(request.url); + const body = await request.text(); + const authorization = request.headers.get("Authorization"); + this.calls.push({ method: request.method, path: url.pathname, body, authorization }); + if (request.method === "POST" && url.pathname === "/api/v2/oauth/token") return this.#token(new URLSearchParams(body)); + if (authorization !== `Bearer ${TOKEN}`) return reply({ message: "unauthorized" }, 401); + if (request.method === "POST" && url.pathname === "/api/v2/tailnet/-/keys") return this.#mint(JSON.parse(body)); + const deleted = url.pathname.match(/^\/api\/v2\/tailnet\/-\/keys\/([^/]+)$/)?.[1]; + if (request.method === "DELETE" && deleted) return this.#delete(deleted); + return reply({ message: "not found" }, 404); + }; + + // The calls that carried a request body, parsed. + bodies(path: string): Array> { + return this.calls.filter((call) => call.method === "POST" && call.path === path).map((call) => { + const parsed: unknown = JSON.parse(call.body); + return isObject(parsed) ? parsed : {}; + }); + } + + // A machine runs its boot script: it joins with the key in it, which must + // be live, unused and for one ephemeral, preauthorized, tagged device. + join(boot: string): void { + const secret = boot.match(/printf '%s' '([^']+)' > "\$key"/)?.[1] ?? ""; + const host = boot.match(/--hostname='([^']+)'/)?.[1] ?? ""; + const key = [...this.keys.values()].find((candidate) => candidate.secret === secret); + if (!key || key.used || !host || !singleUse(key.request)) return; + key.used = true; + const address = `100.64.0.${this.#nextAddress}`; + this.#nextAddress += 1; + this.events.push(`join ${key.id} ${host}`); + const peer: Peer = { HostName: host, Online: !this.joinOffline, TailscaleIPs: [address, `fd7a:115c:a1e0::${this.#nextAddress}`], Tags: ["tag:orly-burst"] }; + writeFileSync(join(this.#directory, "peers", `${host}.json`), JSON.stringify(peer)); + if (this.impostorTags) { + const impostor: Peer = { HostName: host, Online: true, TailscaleIPs: ["100.64.9.9"], Tags: this.impostorTags }; + writeFileSync(join(this.#directory, "peers", `${host}-impostor.json`), JSON.stringify(impostor)); + } + } + + nodes(): string[] { + return readdirSync(join(this.#directory, "peers")).map((name) => name.replace(/\.json$/, "")); + } + + #token(form: URLSearchParams): Response { + if (form.get("client_id") !== CLIENT_ID || form.get("client_secret") !== CLIENT_SECRET) return reply({ message: "invalid client credentials" }, 401); + return reply({ access_token: TOKEN, token_type: "Bearer", expires_in: 3600 }); + } + + #mint(request: Record): Response { + if (this.mintStatus !== 200) return reply({ message: "minting refused" }, this.mintStatus); + // The trust credential's only tag is tag:orly-burst, and it mints nothing else. + const tags = field(field(field(request, "capabilities"), "devices"), "create").tags; + if (JSON.stringify(tags) !== JSON.stringify(["tag:orly-burst"])) return reply({ message: "requested tags are invalid or not permitted" }, 400); + const id = `k${this.#nextKey}`; + this.#nextKey += 1; + const key = { id, secret: `tskey-fake-auth-${id}`, request, used: false }; + this.keys.set(id, key); + this.events.push(`mint ${id}`); + return reply({ id, key: key.secret, capabilities: request.capabilities, expirySeconds: request.expirySeconds }); + } + + #delete(id: string): Response { + if (this.deleteStatus !== 200) return reply({ message: "delete refused" }, this.deleteStatus); + if (!this.keys.delete(id)) return reply({ message: "not found" }, 404); + this.events.push(`delete ${id}`); + return new Response(null, { status: 200 }); + } +} + +// A node logs out: it leaves the caller's view of the tailnet at once. +export function leaveTailnet(state: string, address: string): void { + const peers = join(state, "tailnet", "peers"); + for (const name of readdirSync(peers)) { + const peer: Peer = JSON.parse(readFileSync(join(peers, name), "utf8")); + if (peer.TailscaleIPs.includes(address)) rmSync(join(peers, name), { force: true }); + } +} + +// What Tailscale enforces, so a key minted otherwise never joins. +function singleUse(request: Record): boolean { + const create = field(field(field(request, "capabilities"), "devices"), "create"); + return create.reusable === false && create.ephemeral === true && create.preauthorized === true; +} + +function field(value: Record, name: string): Record { + const inner = value[name]; + return isObject(inner) ? inner : {}; +} + +function reply(data: unknown, status = 200): Response { + return new Response(JSON.stringify(data), { status, headers: JSON_HEADERS }); +} + +// `tailscale status --json`, as the caller's daemon answers it. +function cli(state: string, args: string[]): number { + if (args.join(" ") !== "status --json") { + process.stderr.write(`fake tailscale: unsupported ${args.join(" ")}\n`); + return 2; + } + const self = join(state, "tailnet", "self.json"); + if (!existsSync(self)) { + process.stderr.write("failed to connect to local Tailscale daemon; is Tailscale running?\n"); + return 1; + } + const peers = join(state, "tailnet", "peers"); + const listed = readdirSync(peers).map((name): Peer => JSON.parse(readFileSync(join(peers, name), "utf8"))); + const status = { ...JSON.parse(readFileSync(self, "utf8")), Peer: Object.fromEntries(listed.map((peer, index) => [`nodekey:${index}`, peer])) }; + process.stdout.write(`${JSON.stringify(status, undefined, 2)}\n`); + return 0; +} + +if (import.meta.main) process.exit(cli(process.env.FAKE_SSH_STATE ?? "", Bun.argv.slice(2))); diff --git a/src/burst/fake_tir.ts b/src/burst/fake_tir.ts index 2c358c7a..9cb5927f 100644 --- a/src/burst/fake_tir.ts +++ b/src/burst/fake_tir.ts @@ -1,9 +1,12 @@ -// E2E Networks TIR, in memory, as orly uses it, for the e2e tests, plus the -// caller-address lookup. A VM runs after one status poll, and reads as -// `terminating`, as TIR's does, for one poll while it stops. A snapshot is -// pending for `savingLists` list calls, then `ready`, or `savedStatus`. A -// group's delete fails `groupDeleteFailures` times. -import { CALLER_ADDRESS, fields } from "./test_support"; +// E2E Networks TIR, in memory, as orly uses it, for the e2e tests; requests +// to Tailscale's API go to the FakeTailscale it is given. A VM runs after one +// status poll, when it runs its start scripts and so joins the tailnet, and +// reads as `terminating`, as TIR's does, for one poll while it stops. A +// snapshot is pending for `savingLists` list calls, then `ready`, or +// `savedStatus`. A group's delete fails `groupDeleteFailures` times. +import type { FakeTailscale } from "./fake_tailscale"; + +import { fields } from "./test_support"; import { TIR_LABEL_LIMIT } from "./e2e"; import { isObject } from "../model"; @@ -28,6 +31,8 @@ export class FakeTir { readonly vms = new Map(); readonly keys = new Map(); readonly groups = new Map(); + readonly scripts = new Map(); + scriptStatus = 201; snapshots: FakeSnapshot[] = []; createStatus = 201; // The VM is made, but the reply to its create is a gateway timeout. @@ -49,18 +54,18 @@ export class FakeTir { #saving = new Map(); #nextVm = 5001; #nextKey = 1; - // The caller's address after the run's first lookup, when its network changes mid-run. - callerMovesTo: string | undefined; - #addressLookups = 0; + #nextScript = 300; + readonly #tailnet: FakeTailscale; + + constructor(tailnet: FakeTailscale) { + this.#tailnet = tailnet; + } - // ky hands a Request; the caller-address lookup hands a URL string. + // ky hands a Request; a test's own call may hand a URL string. fetch = async (input: string | URL | Request, init?: RequestInit): Promise => { const request = input instanceof Request ? input : new Request(input, init); const url = new URL(request.url); - if (url.host === "checkip.amazonaws.com") { - this.#addressLookups += 1; - return new Response(`${this.#addressLookups > 1 && this.callerMovesTo ? this.callerMovesTo : CALLER_ADDRESS}\n`); - } + if (url.host === "api.tailscale.com") return this.#tailnet.fetch(request); const method = request.method; const path = url.pathname.replace(PREFIX, ""); const text = await request.text(); @@ -75,6 +80,12 @@ export class FakeTir { return this.calls.filter((call) => call.method === method && pattern.test(call.path)); } + // A start script some other run, or a person, left in the project. + leftScript(name: string): void { + this.scripts.set(String(this.#nextScript), { id: this.#nextScript, name, init_script: "#!/bin/bash\n" }); + this.#nextScript += 1; + } + snapshot(name: string, id: number, status = "ready"): void { this.snapshots.push({ id, name, status, size_gb: 100, image_details: { version_id: UBUNTU_24 } }); } @@ -90,6 +101,9 @@ export class FakeTir { if (route === "POST /security_groups/") return this.lost(path, this.addGroup(body)); if (route === "GET /security_groups/") return reply([...this.groups.values()].map((group) => ({ id: group.id, name: group.name }))); if (route === "DELETE /security_groups/{id}/") return this.deleteGroup(id); + if (route === "POST /notebooks/init-script/") return this.lost(path, this.addScript(body)); + if (route === "GET /notebooks/init-script/") return reply([...this.scripts.values()]); + if (route === "DELETE /notebooks/init-script/{id}/") return this.deleteScript(id); if (route === "POST /notebooks/") return this.create(body); if (route === "GET /notebooks/") return reply([...this.vms.values()].map((vm) => ({ id: Number(vm.id), name: vm.name, status: vm.status }))); if (route === "GET /notebooks/{id}/") return this.poll(id); @@ -163,6 +177,32 @@ export class FakeTir { return reply("Security Group deleted successfully", this.groups.delete(id) ? 200 : 404); } + // A refused script's errors quote the script back, as a validation error may. + private addScript(body: Record): Response { + if (this.scriptStatus !== 201) return new Response(JSON.stringify({ code: this.scriptStatus, data: {}, message: "Failed", errors: { init_script: [String(body.init_script)] } }), { status: this.scriptStatus, headers: JSON_HEADERS }); + const script = { id: this.#nextScript, name: String(body.name), init_script: String(body.init_script) }; + this.#nextScript += 1; + this.scripts.set(String(script.id), script); + return reply(script, 201); + } + + // A script a VM still uses is refused, as TIR does. + private deleteScript(id: string): Response { + if (!this.scripts.has(id)) return reply({}, 404); + if ([...this.vms.values()].some((vm) => this.#scriptsOf(vm).includes(Number(id)))) return reply("The init script is currently in use by one or more notebooks.", 400); + this.scripts.delete(id); + return reply("Init Script deleted successfully"); + } + + #scriptsOf(vm: FakeVm): number[] { + return Array.isArray(vm.body.init_script_id_list) ? vm.body.init_script_id_list.map(Number) : []; + } + + // A booting VM runs its start scripts as root. + #boot(vm: FakeVm): void { + for (const id of this.#scriptsOf(vm)) this.#tailnet.join(this.scripts.get(String(id))?.init_script ?? ""); + } + private create(body: Record): Response { if (this.createStatus !== 201) return reply({}, this.createStatus); const id = String(this.#nextVm); @@ -182,7 +222,10 @@ export class FakeTir { if (!vm) return reply({}, 404); if (vm.status === "terminating") return reply({ id: Number(id), status: "terminating", public_ip: "" }); vm.polls += 1; - if (vm.status === "waiting" && vm.polls > 1) vm.status = this.bootStatus; + if (vm.status === "waiting" && vm.polls > 1) { + vm.status = this.bootStatus; + if (vm.status === "ready") this.#boot(vm); + } else if (vm.status === "stopping") vm.status = "stopped"; return reply({ id: Number(id), status: vm.status === "stopping" ? "terminating" : vm.status, public_ip: vm.status === "waiting" ? "" : vm.address }); } diff --git a/src/burst/index.ts b/src/burst/index.ts index 2a211363..9b77cc07 100644 --- a/src/burst/index.ts +++ b/src/burst/index.ts @@ -10,11 +10,13 @@ import { UNSCOPED_ENVIRONMENT } from "../git_env"; import { isObject, OrlyError } from "../model"; import { cloudLanes, cloudPrune, cloudSnapshot } from "./cloud"; import { captureProcess } from "./process"; +import { done } from "./progress"; import { repositoryIdentity } from "./repository"; import { CLOUD_PROVIDERS } from "./providers"; import { burstSettings } from "./settings"; -import { callerAddress, newKeyPair } from "./ssh"; -import { LANE_PREFIX, MINUTE_MS, PROVIDER_NAMES } from "./types"; +import { newKeyPair } from "./ssh"; +import { Tailnet } from "./tailnet"; +import { LANE_PREFIX, MINUTE_MS, newRunId, PROVIDER_NAMES } from "./types"; export type BurstDependencies = Io & { root: string; env: Environment; fetch: Fetch }; type Request = { snapshot: boolean; prune: boolean; provider: ProviderName | undefined; ref: string | undefined; useSnapshot: boolean; lanes: string[] }; @@ -106,7 +108,7 @@ async function cloud(request: Request, name: ProviderName, dependencies: BurstDe await cloudPrune(provider, { repo: repositoryIdentity(dependencies.root), settings, write: dependencies.write, signal: dependencies.signal }); return 0; } - const run = await stage(dependencies, settings, ref, config); + const run = await stage(dependencies, settings, ref, config, new Tailnet(settings, dependencies.fetch)); if (request.snapshot) { const snapshot = await cloudSnapshot(provider, run); if (!snapshot) return 1; @@ -121,18 +123,20 @@ async function cloud(request: Request, name: ProviderName, dependencies: BurstDe } // Everything a cloud run reads before a machine exists. -async function stage(dependencies: BurstDependencies, settings: BurstSettings, ref: string, config: RepoConfig): Promise { +async function stage(dependencies: BurstDependencies, settings: BurstSettings, ref: string, config: RepoConfig, tailnet: Tailnet): Promise { const { root } = dependencies; const repo = repositoryIdentity(root); const io = { write: dependencies.write, signal: dependencies.signal }; - // First, so a caller that cannot learn its address leaves nothing behind. - const caller = await callerAddress(dependencies.fetch); - const runId = newRunId(ref, new Date()); + // First, so a caller off the tailnet, or with an OAuth client Tailscale + // refuses, leaves nothing behind. + const caller = await tailnet.admit(); + dependencies.write(done(`${caller} is on the tailnet; the run's machines join it`)); + const runId = newRunId(slug(ref, REF_NAME_CHARS) || "ref", new Date()); const directory = runDirectory(settings.outRoot, runId); const bundle = await bundleRef(root, ref, directory); const commit = (await git(root, ["rev-parse", "--verify", `${ref}^{commit}`])).stdout.trim(); const { key, publicKey } = await newKeyPair(directory, `orly-burst-${runId}`, settings.env); - return { ...io, root, config, settings, fetch: dependencies.fetch, ref, repo, runId, runDirectory: directory, commit, bundle, key, publicKey, knownHosts: join(directory, "known_hosts"), caller }; + return { ...io, root, config, settings, ref, repo, runId, runDirectory: directory, commit, bundle, key, publicKey, knownHosts: join(directory, "known_hosts"), tailnet }; } function requireDeclared(config: RepoConfig, lanes: string[]): void { @@ -176,11 +180,6 @@ async function configAt(root: string, ref: string): Promise { return parseConfig(value); } -function newRunId(ref: string, now: Date): string { - const stamp = now.toISOString().replaceAll(/[-:T]/g, "").slice(0, 14); - return `${slug(ref, REF_NAME_CHARS) || "ref"}-${stamp}-${crypto.randomUUID().slice(0, 4)}`; -} - // Holds the run's private key, so only this user may read it. function runDirectory(outRoot: string, runId: string): string { const directory = join(outRoot, runId); diff --git a/src/burst/job.ts b/src/burst/job.ts index 35cf1fae..4dbc17d0 100644 --- a/src/burst/job.ts +++ b/src/burst/job.ts @@ -25,6 +25,90 @@ export const BUNDLE = "/tmp/orly-burst.bundle"; // The exit of a job whose machine preparation, checkout or burst.setup // failed, so the caller reports the lane as not run instead of failed. export const SETUP_FAILED = 254; +// The detached job's files. /run is memory and empties at boot, so the job +// script holding a lane's secrets never reaches a disk, and a snapshot never +// carries a finished job's log or exit code into the next lane. +const JOB_DIR = "/run/orly-burst"; +export const JOB_EXIT = `${JOB_DIR}/exit`; +// The follower's exit when the machine holds no launched job, as after a reboot. +export const NO_JOB = 3; +// The launcher's exit when fewer bytes arrived than were sent, as when the +// session was lost mid-upload: nothing is started, and the launch is retried. +export const UPLOAD_CUT = 4; + +// The launcher: the job script, `bytes` long, arrives on standard input and +// is kept only until the detached shell opens it. A script that arrived short +// is discarded, since `cat` ends as gladly at a lost session's end as at the +// script's. `launched` is made only after the whole script arrived, so a +// launch retried after a lost session never starts a second job. The job +// outlives the session: its output goes to the log, and its exit code to +// JOB_EXIT. +export function launchScript(bytes: number): string { + return [ + "set -eu", "umask 077", `mkdir -p ${JOB_DIR}`, `cat > ${JOB_DIR}/job.part`, + `if [ "$(wc -c < ${JOB_DIR}/job.part)" -ne ${bytes} ]; then rm -f ${JOB_DIR}/job.part; exit ${UPLOAD_CUT}; fi`, + `if ! mkdir ${JOB_DIR}/launched 2>/dev/null; then rm -f ${JOB_DIR}/job.part; exit 0; fi`, + `mv ${JOB_DIR}/job.part ${JOB_DIR}/job.sh`, `: > ${JOB_DIR}/run.log`, + `setsid nohup bash -c ${shellQuote([ + `echo $$ > ${JOB_DIR}/pid.part && mv ${JOB_DIR}/pid.part ${JOB_DIR}/pid`, + `exec 3<${JOB_DIR}/job.sh`, `rm -f ${JOB_DIR}/job.sh`, + `bash -s <&3 3<&- >>${JOB_DIR}/run.log 2>&1`, + `echo $? > ${JOB_DIR}/exit.part`, `mv ${JOB_DIR}/exit.part ${JOB_EXIT}`, + ].join("; "))} /dev/null 2>&1 &`, + "", + ].join("\n"); +} + +// Logs the machine out of the tailnet, which removes its ephemeral node at +// once. It runs detached, since it ends the session it arrives over. +export const LEAVE = "setsid nohup tailscale logout >/dev/null 2>&1 /dev/null 2>&1 /dev/null && [ -d launched ] || exit ${NO_JOB}`, + "while [ ! -s pid ]; do sleep 1; done", + `tail -c +${offset + 1} --pid="$(cat pid)" -f run.log`, + "", + ].join("\n"); +} + +// The boot script a machine runs as root before anything else: install +// Tailscale where the image lacks it, and join the caller's tailnet as `host` +// with a key minted for this machine alone. A machine already joined, such +// as one E2E boots again, is left as it is. +export function bootScript(host: string, key: string): string { + return [ + "#!/bin/bash", + "# orly burst: join the caller's tailnet, so the caller reaches this machine with no public port.", + "set -u", + "if tailscale status >/dev/null 2>&1; then exit 0; fi", + "for attempt in 1 2 3 4 5 6; do", + " command -v tailscale >/dev/null && break", + " if command -v curl >/dev/null || { apt-get update -qq && apt-get install -y -qq curl ca-certificates; }; then", + " curl -fsSL https://tailscale.com/install.sh | sh && break", + " fi", + " sleep 10", + "done", + "systemctl enable --now tailscaled", + // The key reaches tailscale through a file in memory, never its arguments. + "key=/run/orly-burst.key", + "trap 'rm -f \"$key\"' EXIT", + `(umask 077 && printf '%s' ${shellQuote(key)} > "$key")`, + "for attempt in 1 2 3 4 5 6; do", + ` tailscale up --reset --auth-key="file:$key" --hostname=${shellQuote(host)} && exit 0`, + " sleep 5", + "done", + "exit 1", + "", + ].join("\n"); +} // The whole job, prelude first. Every value is single-quoted, so a ref, an // argument or a secret can never become shell syntax on the machine. Setup @@ -78,6 +162,6 @@ export function resultsScript(paths: readonly string[]): string { ].join("\n"); } -function shellQuote(value: string): string { +export function shellQuote(value: string): string { return `'${value.replaceAll("'", `'\\''`)}'`; } diff --git a/src/burst/process.ts b/src/burst/process.ts index d97babed..5a99fe92 100644 --- a/src/burst/process.ts +++ b/src/burst/process.ts @@ -9,7 +9,7 @@ import { OrlyError } from "../model"; type Stopped = "deadline" | "cancelled"; // A child killed by a signal it was not sent by orly has no exit code: it was // interrupted, which is never a lane's own answer. -export type Outcome = { code: number } | { stopped: Stopped | "interrupted" }; +type Outcome = { code: number } | { stopped: Stopped | "interrupted" }; export type Captured = { code: number; stdout: string; stderr: string }; type StreamOptions = { env: Environment; @@ -17,6 +17,9 @@ type StreamOptions = { // Standard output goes to this file instead of the line sink, for a binary // stream such as a results archive. stdoutFile?: string; + // Standard output goes here, chunk by chunk, instead of the line sink, for + // a reader that counts the bytes it was sent. + chunks?: (chunk: Uint8Array) => void; lines: (line: string) => void; deadline: number; signal: AbortSignal; @@ -56,7 +59,8 @@ export async function streamProcess(argv: string[], options: StreamOptions): Pro if (options.signal.aborted) cancel(); else options.signal.addEventListener("abort", cancel, { once: true }); try { - const stdout = child.stdout instanceof ReadableStream ? streamLines(child.stdout, options.lines) : undefined; + const { chunks } = options; + const stdout = child.stdout instanceof ReadableStream ? chunks ? streamChunks(child.stdout, chunks) : streamLines(child.stdout, options.lines) : undefined; await Promise.all([stdout, streamLines(child.stderr, options.lines), child.exited]); } finally { clearTimeout(timer); @@ -174,21 +178,51 @@ function locate(argv: string[], env: Environment): string { return found; } -async function streamLines(stream: ReadableStream, write: (line: string) => void): Promise { - const decoder = new TextDecoder(); - let pending = ""; - for await (const chunk of stream) { - pending += decoder.decode(chunk, { stream: true }); - const parts = pending.split("\n"); - pending = parts.pop() ?? ""; - for (const line of parts) write(line); - if (pending.length > MAX_LINE_CHARS) { - write(pending); - pending = ""; +// Bytes in, whole lines out. It may be fed by several streams in turn, such +// as the sessions one detached job's log is followed through, so a line cut +// by a lost session is written once, whole, when the next one completes it. +export class Lines { + readonly #write: (line: string) => void; + readonly #decoder = new TextDecoder(); + #pending = ""; + #bytes = 0; + + constructor(write: (line: string) => void) { + this.#write = write; + } + + // Every byte taken so far: where a resumed stream starts. + get bytes(): number { + return this.#bytes; + } + + take(chunk: Uint8Array): void { + this.#bytes += chunk.byteLength; + this.#pending += this.#decoder.decode(chunk, { stream: true }); + const parts = this.#pending.split("\n"); + this.#pending = parts.pop() ?? ""; + for (const line of parts) this.#write(line); + if (this.#pending.length > MAX_LINE_CHARS) { + this.#write(this.#pending); + this.#pending = ""; } } - pending += decoder.decode(); - if (pending) write(pending); + + end(): void { + this.#pending += this.#decoder.decode(); + if (this.#pending) this.#write(this.#pending); + this.#pending = ""; + } +} + +async function streamLines(stream: ReadableStream, write: (line: string) => void): Promise { + const lines = new Lines(write); + await streamChunks(stream, (chunk) => lines.take(chunk)); + lines.end(); +} + +async function streamChunks(stream: ReadableStream, take: (chunk: Uint8Array) => void): Promise { + for await (const chunk of stream) take(chunk); } diff --git a/src/burst/settings.ts b/src/burst/settings.ts index 71704b53..c3fa2186 100644 --- a/src/burst/settings.ts +++ b/src/burst/settings.ts @@ -15,6 +15,7 @@ export type BurstSettings = Readonly<{ outRoot: string; aws: Readonly<{ region: string; types: readonly string[]; image: string | undefined; user: string; market: AwsMarket }>; e2e: Readonly<{ apiKey: string | undefined; authToken: string | undefined; projectId: string | undefined; location: string; plan: string; image: string | undefined; user: string }>; + tailscale: Readonly<{ clientId: string | undefined; clientSecret: string | undefined }>; }>; // What a lane's machine is rented as. Spot is about a tenth of the price, and @@ -37,15 +38,20 @@ const MOVED: Readonly> = { ORLY_BURST_SUBNET: "unset it; lanes use the default network", ORLY_BURST_SNAPSHOT_KEEP: "unset it; --prune keeps the newest snapshot", ORLY_BURST_AWS_ACCESS: "unset it; lanes are reached over SSH", ORLY_BURST_AWS_INSTANCE_PROFILE: "unset it; lanes are reached over SSH", }; +// The longest a run may take, so anything a run left behind longer ago than +// this, with a margin, belongs to a run that died. +export const MAX_DEADLINE_MINUTES = 1440; const bounded = (max: number) => z.coerce.number().positive().max(max); const environmentSchema = z.object({ - ORLY_BURST_DEADLINE_MINUTES: bounded(1440).default(120), + ORLY_BURST_DEADLINE_MINUTES: bounded(MAX_DEADLINE_MINUTES).default(120), ORLY_BURST_POLL_SECONDS: bounded(600).default(30), ORLY_BURST_OUT: z.string().min(1).default(join(tmpdir(), "orly-burst")), ORLY_BURST_MARKET: z.enum(AWS_MARKETS).default("spot"), E2E_API_KEY: z.string().min(1).optional(), E2E_AUTH_TOKEN: z.string().min(1).optional(), E2E_PROJECT_ID: z.string().regex(/^\d+$/).optional(), + TS_OAUTH_CLIENT_ID: z.string().min(1).optional(), + TS_OAUTH_CLIENT_SECRET: z.string().min(1).optional(), }); // Every variable `orly burst` reads, read once. A blank value means unset, so @@ -74,6 +80,7 @@ export function burstSettings(env: Environment, burst: BurstConfig = {}): BurstS location: burst.e2e?.location ?? "Delhi", plan: burst.e2e?.plan ?? "C3.32GB", image: burst.e2e?.image, user: burst.e2e?.user ?? "root", }), + tailscale: Object.freeze({ clientId: value.TS_OAUTH_CLIENT_ID, clientSecret: value.TS_OAUTH_CLIENT_SECRET }), }); } diff --git a/src/burst/ssh.ts b/src/burst/ssh.ts index 36b1afa9..b5ae1f40 100644 --- a/src/burst/ssh.ts +++ b/src/burst/ssh.ts @@ -1,16 +1,14 @@ -import type { Outcome } from "./process"; import type { Environment } from "./settings"; -import type { BurstRun, Fetch, Job, Machine, Status } from "./types"; +import type { BurstRun, Job, Machine, Status } from "./types"; import { existsSync, readdirSync, rmSync, statSync } from "node:fs"; import { join } from "node:path"; import { OrlyError } from "../model"; -import { BUNDLE, INPUTS, resultsScript, SETUP_FAILED, WORK } from "./job"; -import { captureProcess, machineDeadline, streamProcess, until } from "./process"; -import { done, ongoing } from "./progress"; +import { BUNDLE, followScript, INPUTS, JOB_EXIT, launchScript, LEAVE, NO_JOB, resultsScript, SETUP_FAILED, shellQuote, UPLOAD_CUT, WORK } from "./job"; +import { captureProcess, Lines, machineDeadline, pause, streamProcess, until } from "./process"; +import { done, failed, ongoing } from "./progress"; import { bundleFor } from "./repository"; -import { IPV4 } from "./types"; export type StagedDirectory = { name: string; archive: string }; @@ -25,12 +23,7 @@ const SSH_LOST = 255; const NO_RESULTS = 3; const COMMIT = /^[0-9a-f]{40}$/; const SHORT = 7; -// Each provider's SSH rule admits only the caller's public IPv4, learnt here. -const CALLER_ADDRESS_URL = "https://checkip.amazonaws.com"; -const CALLER_TIMEOUT_MS = 15_000; -// A booting machine refuses SSH for a while, so the caller's address is -// checked only after this many probes in a row have failed. -const PROBES_BEFORE_ADDRESS_CHECK = 3; +const EXIT_CODE = /^\d{1,3}$/; // The run's own key pair, made in the run's private directory. ssh-keygen // writes the private half with mode 0600; only the public half leaves this @@ -51,43 +44,26 @@ export function forgetRunFiles(run: BurstRun): void { // A booting machine refuses connections for a while, so the first connect is // retried. A booted machine answers within minutes, so the wait is bounded -// well inside the job's deadline, and it ends at once when the caller's -// address has changed, since the run admits only the one it launched from. -// A failure carries ssh's own last error. +// well inside the job's deadline. A failure carries ssh's own last error. export async function reachable(run: BurstRun, job: Job, machine: Machine, user: string): Promise { const target = machine.address ?? machine.id; run.write(ongoing(`waiting for SSH on ${target}`)); let refusal = ""; - let failures = 0; const probe = async () => { const tried = await captureProcess(sshArgs(run, machine, user, "true"), { env: run.settings.env, timeoutMs: PROBE_TIMEOUT_MS, signal: run.signal }); if (tried.code === 0) return true; refusal = tried.stderr.trim().split("\n").at(-1) ?? ""; - failures += 1; - const reason = failures >= PROBES_BEFORE_ADDRESS_CHECK ? await movedCaller(run.fetch, run.caller) : undefined; - if (reason) throw new LockedOut(reason); return undefined; }; try { await until(`SSH to ${target}`, probe, { deadline: machineDeadline(job), signal: run.signal, pollMs: run.settings.pollMs }); } catch (error) { - if (error instanceof LockedOut || !(error instanceof OrlyError) || !refusal) throw error; + if (!(error instanceof OrlyError) || !refusal) throw error; throw new OrlyError(`${error.message}: ${refusal}`); } run.write(done(`SSH on ${target} answers`)); } -class LockedOut extends OrlyError {} - -// A caller that changed network mid-run can never connect again, so the -// reason is said instead of waited out. An address that cannot be learnt -// changes nothing. -async function movedCaller(fetcher: Fetch, admitted: string): Promise { - const now = await callerAddress(fetcher).catch(() => undefined); - if (!now || now === admitted) return undefined; - return `this machine's address changed from ${admitted} to ${now}, and the run admits SSH from ${admitted} only; run it again from this network`; -} - // Each burst.directories variable must name a directory on this machine. It // is archived once per run, beside the bundle, for every lane to receive. export async function archiveDirectories(run: BurstRun, names: readonly string[]): Promise { @@ -103,11 +79,13 @@ export async function archiveDirectories(run: BurstRun, names: readonly string[] return staged; } -// Stages the ref's bundle and any copied directories, runs the job script as -// the session's standard input, streams its output with the job's name in -// front, and brings the declared results back. The script carries a lane's -// secrets, so it exists only as this process's memory and the remote shell's -// input. +// Stages the ref's bundle and any copied directories, starts the job script +// detached on the machine, follows its log with the job's name in front, and +// brings the declared results back. The job outlives any one session: a lost +// one is reconnected, and the log resumes from the last byte received. Its +// exit code is the one the machine wrote, never ssh's. The script carries a +// lane's secrets, so it exists only as this process's memory, the session's +// input and, until the job opens it, a file in the machine's memory. export async function runOverSsh(run: BurstRun, job: Job, machine: Machine, user: string, script: string, directories: readonly StagedDirectory[]): Promise { const base = await warmCommit(run, machine, user); const bundle = bundleFor(run.root, run.ref, run.commit, base, run.bundle); @@ -117,22 +95,124 @@ export async function runOverSsh(run: BurstRun, job: Job, machine: Machine, user await stage(run, machine, user, `rm -rf ${INPUTS}/${name} && mkdir -p ${INPUTS}/${name} && tar -xzf - -C ${INPUTS}/${name}`, archive, name); } const log = Bun.file(join(job.evidence, "run.log")).writer(); - let outcome: Outcome; + const lines = new Lines((line) => { + log.write(`${line}\n`); + run.write(`[${job.name}] ${line}`); + }); + let status: Status; try { - outcome = await streamProcess(sshArgs(run, machine, user, asRoot(user, "bash -s")), { - env: run.settings.env, stdin: new Blob([script]), deadline: job.deadline, signal: run.signal, - lines: (line) => { - log.write(`${line}\n`); - run.write(`[${job.name}] ${line}`); - }, - }); + status = await new Session(run, job, machine, user).run(script, lines); } finally { + lines.end(); await log.end(); } if (!run.signal.aborted) await collect(run, job, machine, user); - if ("stopped" in outcome) return outcome.stopped; - if (outcome.code === SETUP_FAILED) return "not_run"; - return outcome.code === SSH_LOST ? "interrupted" : outcome.code; + return status; +} + +// A machine that joined the tailnet leaves it before it is deleted or +// imaged, so its node goes at once instead of when the tailnet notices it +// offline. Logout runs detached, since it ends the session it was sent over. +// A warm-up about to be imaged sends FORGET instead, which also wipes its node. +export async function leaveTailnet(run: BurstRun, machine: Machine, user: string, command = LEAVE): Promise { + const sent = await captureProcess(sshArgs(run, machine, user, asRoot(user, command)), { env: run.settings.env, timeoutMs: PROBE_TIMEOUT_MS }); + return sent.code === 0; +} + +// One detached job on one machine, followed through as many SSH sessions as +// it takes. A lost session is retried every poll interval for as long as a +// booting machine is waited for, counted from the first failure since the +// log last grew, and never past the job's deadline. +class Session { + readonly #run: BurstRun; + readonly #job: Job; + readonly #machine: Machine; + readonly #user: string; + #lostAt: number | undefined; + + constructor(run: BurstRun, job: Job, machine: Machine, user: string) { + this.#run = run; + this.#job = job; + this.#machine = machine; + this.#user = user; + } + + async run(script: string, lines: Lines): Promise { + for (;;) { + const job = new Blob([script]); + const launched = await this.#capture(`bash -c ${shellQuote(launchScript(job.size))}`, STAGE_TIMEOUT_MS, job); + if (launched.code === 0) break; + if (launched.code !== SSH_LOST && launched.code !== UPLOAD_CUT) throw new OrlyError(`could not start the job on ${this.#machine.id}: ${launched.stderr.trim()}`); + const stop = await this.#lost(lines.bytes); + if (stop) return stop; + } + for (;;) { + const from = lines.bytes; + const outcome = await streamProcess(this.#ssh(`bash -c ${shellQuote(followScript(from))}`), { + env: this.#run.settings.env, deadline: this.#job.deadline, signal: this.#run.signal, + // ssh's complaint is said once per loss, not at every retry. + chunks: (chunk) => lines.take(chunk), lines: (line) => { + if (this.#lostAt === undefined) this.#run.write(`[${this.#job.name}] ${line}`); + }, + }); + if ("stopped" in outcome && outcome.stopped === "cancelled") return "cancelled"; + if ("stopped" in outcome && outcome.stopped === "deadline") return this.#lostAt === undefined ? "deadline" : this.#giveUp(Date.now()); + if (lines.bytes > from) this.#lostAt = undefined; + if ("code" in outcome && outcome.code === NO_JOB) { + this.#run.write(failed(`lane=${this.#job.name} ${this.#machine.id} holds no job any more; it may have restarted`)); + return "interrupted"; + } + if ("code" in outcome && outcome.code === 0) { + const code = await this.#exitCode(); + if (code !== undefined) return code; + } + const stop = await this.#lost(lines.bytes); + if (stop) return stop; + } + } + + // What the job wrote as its exit, undefined when the session to read it was + // lost, and interrupted when the job ended without writing one. + async #exitCode(): Promise { + const read = await this.#capture(`cat ${JOB_EXIT}`, PROBE_TIMEOUT_MS); + if (read.code === SSH_LOST) return undefined; + const code = read.stdout.trim(); + if (read.code !== 0 || !EXIT_CODE.test(code)) { + this.#run.write(failed(`lane=${this.#job.name} the job on ${this.#machine.id} ended without an exit code`)); + return "interrupted"; + } + return Number(code) === SETUP_FAILED ? "not_run" : Number(code); + } + + // Waits one poll interval before the next attempt, or says why there is none. + async #lost(offset: number): Promise { + const now = Date.now(); + if (this.#run.signal.aborted) return "cancelled"; + if (this.#lostAt === undefined) { + this.#lostAt = now; + this.#run.write(ongoing(`lane=${this.#job.name} lost its session to ${this.#target()}; reconnecting, the log resumes at byte ${offset}`)); + } + if (now >= machineDeadline(this.#job, this.#lostAt)) return this.#giveUp(now); + await pause(this.#run.settings.pollMs, this.#run.signal); + return this.#run.signal.aborted ? "cancelled" : undefined; + } + + #giveUp(now: number): Status { + this.#run.write(failed(`lane=${this.#job.name} could not reconnect to ${this.#target()} within ${Math.round((now - (this.#lostAt ?? now)) / 1000)}s`)); + return "interrupted"; + } + + #target(): string { + return this.#machine.address ?? this.#machine.id; + } + + #capture(command: string, timeoutMs: number, stdin?: Blob) { + return captureProcess(this.#ssh(command), { env: this.#run.settings.env, timeoutMs, signal: this.#run.signal, ...(stdin ? { stdin } : {}) }); + } + + #ssh(command: string): string[] { + return sshArgs(this.#run, this.#machine, this.#user, asRoot(this.#user, command)); + } } // A fresh machine's host key is one nobody has seen, so the run trusts it on @@ -145,13 +225,6 @@ function sshArgs(run: BurstRun, machine: Machine, user: string, command: string) `${user}@${machine.address ?? ""}`, command]; } -export async function callerAddress(fetcher: Fetch): Promise { - const response = await fetcher(CALLER_ADDRESS_URL, { signal: AbortSignal.timeout(CALLER_TIMEOUT_MS) }); - const address = (await response.text()).trim(); - if (!response.ok || !IPV4.test(address)) throw new OrlyError(`could not learn this machine's public IPv4 address from ${CALLER_ADDRESS_URL}`); - return address; -} - // An upload of tens of megabytes over a slow link takes minutes, so it is // announced with its size and reported with its duration. async function stage(run: BurstRun, machine: Machine, user: string, command: string, file: string, what: string): Promise { diff --git a/src/burst/tailnet.test.ts b/src/burst/tailnet.test.ts new file mode 100644 index 00000000..0c0dfda4 --- /dev/null +++ b/src/burst/tailnet.test.ts @@ -0,0 +1,286 @@ +import { afterEach, describe, expect, setDefaultTimeout, test } from "bun:test"; +import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { burst } from "./index"; +import { awsRun, restoreEc2 } from "./aws-test-support"; +import { CREATE, e2eRun, LANES, ONE_LANE } from "./e2e-test-support"; +import { CLIENT_SECRET } from "./fake_tailscale"; +import { bootScript, launchScript, UPLOAD_CUT } from "./job"; +import { fields, recordedCalls } from "./test_support"; +import { cleanupTemporaryDirectories } from "../gates_test_support"; + +const KEYS = "/api/v2/tailnet/-/keys"; +const NODE = /^orly-burst-acceptance-\d{14}-[0-9a-f]{4}$/; + +setDefaultTimeout(60_000); +afterEach(() => { + restoreEc2(); + cleanupTemporaryDirectories(); +}); + +describe("the caller's tailnet", () => { + test.each([ + ["no Tailscale daemon", undefined, false, "this machine's `tailscale status` failed: failed to connect to local Tailscale daemon"], + ["a stopped Tailscale", "Stopped", false, "this machine is not on a tailnet (Tailscale reports Stopped, offline); run `tailscale up`"], + ["an offline Tailscale", "Running", false, "this machine is not on a tailnet (Tailscale reports Running, offline)"], + ])("a caller with %s is refused before anything is minted or rented", async (_case, backend, online, reason) => { + const run = e2eRun(); + run.tailnet.caller(backend, online); + + await expect(burst(ONE_LANE, run.dependencies)).rejects.toThrow(reason); + expect(run.api.calls).toHaveLength(0); + expect(run.tailnet.calls).toHaveLength(0); + expect(existsSync(join(run.state, "out"))).toBe(false); + }); + + test("missing OAuth credentials are named before any request", async () => { + const run = e2eRun({ TS_OAUTH_CLIENT_SECRET: "" }); + + await expect(burst(ONE_LANE, run.dependencies)).rejects.toThrow("set TS_OAUTH_CLIENT_SECRET"); + expect(run.api.calls).toHaveLength(0); + expect(run.tailnet.calls).toHaveLength(0); + }); + + test("an OAuth client Tailscale refuses stops the run before anything is rented, and the secret is never said", async () => { + const run = e2eRun({ TS_OAUTH_CLIENT_SECRET: "tskey-fake-wrong-secret" }); + + const refused = burst(ONE_LANE, run.dependencies); + await expect(refused).rejects.toThrow("Tailscale POST /api/v2/oauth/token answered 401: invalid client credentials"); + await refused.catch((error: unknown) => expect(String(error)).not.toContain("tskey-fake-wrong-secret")); + expect(run.api.calls).toHaveLength(0); + expect(existsSync(join(run.state, "out"))).toBe(false); + }); + + test("each machine joins with a single-use, ephemeral, tagged key of its own, deleted once it joined", async () => { + const run = e2eRun(); + + expect(await burst(LANES, run.dependencies)).toBe(0); + + const minted = run.tailnet.bodies(KEYS); + expect(minted).toHaveLength(2); + for (const body of minted) { + expect(body.capabilities).toEqual({ devices: { create: { reusable: false, ephemeral: true, preauthorized: true, tags: ["tag:orly-burst"] } } }); + expect(body.expirySeconds).toBe(600); + } + expect(run.tailnet.keys.size).toBe(0); + for (const id of ["k1", "k2"]) { + const order = run.tailnet.events.filter((event) => event.split(" ")[1] === id).map((event) => event.split(" ")[0]); + expect(order).toEqual(["mint", "join", "delete"]); + } + const scripts = run.api.callsTo("POST", /^\/notebooks\/init-script\/$/).map((call) => String(fields(call.body).init_script)); + expect(scripts.map((script) => script.match(/printf '%s' '([^']+)'/)?.[1]).sort()).toEqual(["tskey-fake-auth-k1", "tskey-fake-auth-k2"]); + expect(scripts.every((script) => script.includes('tailscale up --reset --auth-key="file:$key"'))).toBe(true); + expect(scripts.some((script) => /--hostname='orly-burst-acceptance-\d{14}-[0-9a-f]{4}'/.test(script))).toBe(true); + const tokenForm = new URLSearchParams(run.tailnet.calls.find((call) => call.path === "/api/v2/oauth/token")?.body ?? ""); + expect(tokenForm.get("client_secret")).toBe(CLIENT_SECRET); + const elsewhere = JSON.stringify(recordedCalls(run.state)) + run.output.text() + readFileSync(join(run.output.text().match(/evidence=(\S+)/)?.[1] ?? "", "run.log"), "utf8"); + expect(elsewhere).not.toContain("tskey-fake-auth"); + expect(elsewhere).not.toContain(CLIENT_SECRET); + expect(run.output.text()).toMatch(/🟢 deleted the tailnet key k\d of orly-burst-acceptance-/); + }); + + test("a machine that never boots never joins, and its key is still deleted", async () => { + const run = e2eRun(); + run.api.bootStatus = "error"; + + expect(await burst(ONE_LANE, run.dependencies)).toBe(1); + expect(run.tailnet.events).toEqual(["mint k1", "delete k1"]); + expect(run.api.vms.size).toBe(0); + expect(run.api.scripts.size).toBe(0); + }); + + test("a key Tailscale will not delete is reported by its identifier, for a person to delete", async () => { + const run = e2eRun(); + run.tailnet.deleteStatus = 500; + + expect(await burst(ONE_LANE, run.dependencies)).toBe(0); + expect(run.output.text()).toMatch(/🔴 could not delete the tailnet key k1 of orly-burst-acceptance-\S+: Tailscale DELETE \/api\/v2\/tailnet\/-\/keys\/k1 answered 500: delete refused; delete it in the Tailscale admin console/); + }); + + test("a refused mint rents no machine", async () => { + const run = e2eRun(); + run.tailnet.mintStatus = 403; + + expect(await burst(ONE_LANE, run.dependencies)).toBe(1); + expect(run.api.callsTo("POST", CREATE)).toHaveLength(0); + expect(run.output.text()).toMatch(/lane=acceptance .* exit=unlaunched /); + }); + + test("SSH goes only to the machine's tailnet address, and the node logs out before the machine is deleted", async () => { + const run = e2eRun(); + + expect(await burst(ONE_LANE, run.dependencies)).toBe(0); + const ssh = recordedCalls(run.state); + expect(ssh.every((call) => call.includes("root@100.64.0.1"))).toBe(true); + expect(ssh.findIndex((call) => call.at(-1)?.includes("tailscale logout"))).toBeGreaterThan(-1); + expect(run.tailnet.nodes()).toEqual([]); + const text = run.output.text(); + expect(text.indexOf("is leaving the tailnet")).toBeLessThan(text.indexOf("deleting e2e machine 5001")); + expect(text).toMatch(/🟢 orly-burst-acceptance-\S+ is leaving the tailnet/); + }); + + test("a warm-up leaves the tailnet before it is imaged, so no snapshot carries its node", async () => { + const run = e2eRun(); + + expect(await burst(["snapshot", "--provider", "e2e"], run.dependencies)).toBe(0); + const text = run.output.text(); + expect(text.indexOf("left the tailnet")).toBeGreaterThan(-1); + expect(text.indexOf("left the tailnet")).toBeLessThan(text.indexOf("stopping VM 5001 to save it")); + expect(text).not.toContain("is leaving the tailnet"); + expect(run.tailnet.nodes()).toEqual([]); + }); + + test("a device that claims the node's name without the burst tag is never reached", async () => { + const run = e2eRun(); + run.tailnet.impostorTags = []; + + expect(await burst(ONE_LANE, run.dependencies)).toBe(0); + expect(recordedCalls(run.state).some((call) => call.some((argument) => argument.includes("100.64.9.9")))).toBe(false); + }); + + test("two burst-tagged nodes of one name are refused rather than guessed between", async () => { + const run = e2eRun(); + run.tailnet.impostorTags = ["tag:orly-burst"]; + + expect(await burst(ONE_LANE, run.dependencies)).toBe(1); + expect(run.output.text()).toMatch(/🔴 lane=acceptance 2 tailnet nodes tagged tag:orly-burst are named orly-burst-acceptance-\S+; remove the stale ones/); + expect(recordedCalls(run.state).filter((call) => call.at(-1) !== undefined && !call.at(-1)?.includes("tailscale logout"))).toEqual([]); + expect(run.api.vms.size).toBe(0); + }); + + test("a node that joins after the run stopped waiting for it is still logged out", async () => { + const run = e2eRun({ ORLY_BURST_DEADLINE_MINUTES: "0.02" }); + run.tailnet.joinOffline = true; + + expect(await burst(ONE_LANE, run.dependencies)).toBe(1); + expect(run.output.text()).toContain("the deadline passed while waiting for orly-burst-acceptance-"); + expect(recordedCalls(run.state).filter((call) => call.at(-1)?.includes("tailscale logout"))).toHaveLength(1); + expect(run.tailnet.nodes()).toEqual([]); + expect(run.tailnet.keys.size).toBe(0); + }); + + test("a warm-up forgets its node and its user data before it is imaged; a lane only logs out", async () => { + const run = e2eRun(); + + expect(await burst(["snapshot", "--provider", "e2e"], run.dependencies)).toBe(0); + expect(await burst(ONE_LANE, run.dependencies)).toBe(0); + const leaves = recordedCalls(run.state).flatMap((call) => call.at(-1)?.includes("tailscale logout") ? [call.at(-1) ?? ""] : []); + expect(leaves).toHaveLength(2); + expect(leaves[0]).toContain("cloud-init clean --logs; tailscale logout; systemctl stop tailscaled; rm -f /var/lib/tailscale/tailscaled.state"); + expect(leaves[1]).toBe("setsid nohup tailscale logout >/dev/null 2>&1 { + const script = bootScript("orly-burst-acceptance-20261122000000-ab12", "tskey-fake-it's"); + + expect(script).toContain("printf '%s' 'tskey-fake-it'\\''s' > \"$key\""); + expect(script).toContain("tailscale up --reset --auth-key=\"file:$key\" --hostname='orly-burst-acceptance-20261122000000-ab12'"); + expect(script).not.toMatch(/--auth-key='/); + expect(Bun.spawnSync(["bash", "-n"], { stdin: new Blob([script]) }).exitCode).toBe(0); + }); +}); + +describe("a detached lane", () => { + test("a dropped session reconnects, and the log resumes from the last byte received", async () => { + const run = e2eRun(); + await Bun.write(join(run.state, "scenario.json"), JSON.stringify({ drops: { acceptance: 1 } })); + + expect(await burst(ONE_LANE, run.dependencies)).toBe(0); + const offsets = recordedCalls(run.state).flatMap((call) => call.at(-1)?.match(/tail -c \+(\d+)/)?.[1] ?? []); + expect(offsets).toEqual(["1", String("== packages\n".length + 1)]); + const evidence = run.output.text().match(/evidence=(\S+)/)?.[1] ?? ""; + expect(readFileSync(join(evidence, "run.log"), "utf8")).toBe("== packages\nlane acceptance ran\n"); + expect(run.output.text()).toContain("lane=acceptance lost its session to 100.64.0.1; reconnecting, the log resumes at byte 12"); + expect(run.output.text().match(/\[acceptance\] lane acceptance ran/g)).toHaveLength(1); + expect(run.output.text()).toMatch(/lane=acceptance .* exit=0 /); + }); + + test("a launch whose session was lost mid-upload is sent again, and the job starts once", async () => { + const run = e2eRun(); + await Bun.write(join(run.state, "scenario.json"), JSON.stringify({ cutUpload: true })); + + expect(await burst(ONE_LANE, run.dependencies)).toBe(0); + expect(recordedCalls(run.state).filter((call) => call.at(-1)?.includes("mkdir /run/orly-burst/launched"))).toHaveLength(2); + expect(run.output.text()).toMatch(/lane=acceptance .* exit=0 /); + }); + + test("the launcher discards a script that arrived short, and keeps one that arrived whole", () => { + const directory = mkdtempSync(join(tmpdir(), "orly-launch-")); + try { + const script = "echo whole\n"; + const launch = (input: string) => Bun.spawnSync(["bash", "-c", launchScript(Buffer.byteLength(script)).replaceAll("/run/orly-burst", directory)], { stdin: new Blob([input]), stdout: "ignore", stderr: "ignore" }).exitCode; + + expect(launch(script.slice(0, 4))).toBe(UPLOAD_CUT); + expect(existsSync(join(directory, "launched"))).toBe(false); + expect(existsSync(join(directory, "job.part"))).toBe(false); + expect(launch(script)).toBe(0); + expect(existsSync(join(directory, "launched"))).toBe(true); + } finally { + rmSync(directory, { recursive: true, force: true }); + } + }); + + test("a launch is sent once: the job is started on the machine a single time", async () => { + const run = e2eRun(); + + expect(await burst(ONE_LANE, run.dependencies)).toBe(0); + expect(recordedCalls(run.state).filter((call) => call.at(-1)?.includes("mkdir /run/orly-burst/launched"))).toHaveLength(1); + }); + + test("a machine that never answers again before the deadline leaves the lane interrupted, and the VM still goes", async () => { + // Long enough that a loaded machine reaches the lost session before the deadline. + const run = e2eRun({ ORLY_BURST_DEADLINE_MINUTES: "0.15" }); + await Bun.write(join(run.state, "scenario.json"), JSON.stringify({ drops: { acceptance: 1 }, lost: ["acceptance"], sleepMs: 200 })); + + expect(await burst(ONE_LANE, run.dependencies)).toBe(1); + const text = run.output.text(); + expect(text).toContain("lost its session to 100.64.0.1"); + expect(text).toMatch(/🔴 lane=acceptance could not reconnect to 100\.64\.0\.1 within \d+s/); + expect(text).toMatch(/lane=acceptance .* exit=interrupted /); + expect(run.api.vms.size).toBe(0); + expect(run.tailnet.keys.size).toBe(0); + }); +}); + +describe("e2e start scripts", () => { + test("a refused start script is named by its status alone, never by what TIR quoted back", async () => { + const run = e2eRun(); + run.api.scriptStatus = 400; + + expect(await burst(ONE_LANE, run.dependencies)).toBe(1); + expect(run.output.text()).toContain("E2E TIR POST /notebooks/init-script/ answered 400"); + expect(run.output.text()).not.toContain("tskey-fake-auth"); + expect(run.tailnet.keys.size).toBe(0); + }); + + test("a script whose create reply was lost is deleted by name, with a dead run's orphans; others stay", async () => { + const run = e2eRun(); + run.api.lostReplies.add("/notebooks/init-script/"); + run.api.leftScript("obs-20200101000000-ab12-acceptance"); + const recent = `obs-${new Date().toISOString().replaceAll(/\D/g, "").slice(0, 14)}-cd34-acceptance`; + run.api.leftScript(recent); + run.api.leftScript("someone-elses-script"); + + expect(await burst(ONE_LANE, run.dependencies)).toBe(1); + expect([...run.api.scripts.values()].map((script) => script.name).sort()).toEqual([recent, "someone-elses-script"]); + expect(run.output.text()).toMatch(/🟢 deleted TIR start script \d+ \(obs-\d{14}-[0-9a-f]{4}-acceptance\)/); + expect(run.output.text()).toContain("(obs-20200101000000-ab12-acceptance)"); + }); +}); + +describe("aws-spot on the tailnet", () => { + test("an instance opens no inbound port and joins the tailnet from its user data", async () => { + const run = await awsRun(); + + expect(await burst(["acceptance", "--provider", "aws-spot"], run.dependencies)).toBe(0); + expect(run.ec2.inputs("AuthorizeSecurityGroupIngress")).toHaveLength(0); + const boot = Buffer.from(String(run.ec2.inputs("RunInstances")[0]?.UserData ?? ""), "base64").toString(); + expect(boot.split("\n")[0]).toBe("#!/bin/bash"); + expect(boot.match(/--hostname='([^']+)'/)?.[1]).toMatch(NODE); + expect(run.tailnet.events).toEqual(["mint k1", expect.stringMatching(/^join k1 orly-burst-acceptance-/), "delete k1"]); + expect(recordedCalls(run.state).every((call) => call.includes("admin@100.64.0.1"))).toBe(true); + expect(run.output.text()).toContain("opens no inbound port; the run's instances are reached over the tailnet"); + }); +}); diff --git a/src/burst/tailnet.ts b/src/burst/tailnet.ts new file mode 100644 index 00000000..4da16883 --- /dev/null +++ b/src/burst/tailnet.ts @@ -0,0 +1,179 @@ +import type { BurstSettings, Environment } from "./settings"; +import type { Fetch } from "./types"; +import type { KyInstance } from "ky"; + +import ky, { isHTTPError } from "ky"; +import { z } from "zod"; + +import { OrlyError } from "../model"; +import { captureProcess, until } from "./process"; +import { required } from "./settings"; +import { IPV4 } from "./types"; + +// One single-use key a machine joins the tailnet with. `secret` is the key +// itself: it reaches the machine only inside its boot script, which goes to +// the cloud API, and is never printed, an argument or a file on the caller. +export type AuthKey = { id: string; secret: string }; +type Wait = { deadline: number; signal: AbortSignal; pollMs: number }; +type TailscaleStatus = z.infer; +type Peer = z.infer; + +// Every machine joins tagged, so the tailnet's access rules decide who may +// reach it, and the OAuth client may only mint keys for this tag. +const BURST_TAG = "tag:orly-burst"; +const API = "https://api.tailscale.com/api/v2/"; +const DOCS = "https://github.com/agentsfleet/orly/blob/main/docs/BURST.md"; +// A key outlives its mint only by the machine's boot: the cloud starts the +// machine at once, and a key nobody used is worthless in ten minutes. +const KEY_SECONDS = 600; +// Tailscale caps a key's description at 50 characters. +const DESCRIPTION_CHARS = 50; +const REQUEST_TIMEOUT_MS = 60_000; +const MAX_RESPONSE_BYTES = 1024 * 1024; +// GET and DELETE are retried on 429, 5xx and timeouts; a mint is not, since +// a retried mint whose first reply was lost would leave a key nobody deletes. +const RETRIES = 5; +// A token is renewed this long before Tailscale says it expires. +const TOKEN_MARGIN_MS = 60_000; +const STATUS_TIMEOUT_MS = 30_000; +const NOT_FOUND = 404; +// Tailscale gives each node an IPv4 address in 100.64.0.0/10. +const TAILNET_PREFIX = "100."; +const tokenSchema = z.object({ access_token: z.string().min(1), expires_in: z.number().positive() }); +const keySchema = z.object({ id: z.string().min(1), key: z.string().min(1) }); +const peerSchema = z.object({ HostName: z.string(), Online: z.boolean().optional(), TailscaleIPs: z.array(z.string()).nullish(), Tags: z.array(z.string()).nullish() }); +const statusSchema = z.object({ + BackendState: z.string(), + Self: z.object({ Online: z.boolean().optional(), HostName: z.string().optional() }).nullish(), + Peer: z.record(z.string(), peerSchema).nullish(), +}); + +// The caller's tailnet, which every burst machine joins for its run: the +// caller reaches it over Tailscale, so no cloud opens SSH to the internet and +// a caller that changes network keeps its sessions. The OAuth client mints +// one key per machine; the caller's own `tailscale` reports the joined node. +export class Tailnet { + readonly #http: KyInstance; + readonly #client: { id: string; secret: string }; + readonly #env: Environment; + #token: { value: string; expires: number } | undefined; + + constructor(settings: BurstSettings, fetcher: Fetch) { + this.#client = { id: required(settings.tailscale.clientId, "TS_OAUTH_CLIENT_ID"), secret: required(settings.tailscale.clientSecret, "TS_OAUTH_CLIENT_SECRET") }; + this.#env = settings.env; + this.#http = ky.create({ + prefix: API, fetch: fetcher, timeout: REQUEST_TIMEOUT_MS, maxResponseSize: MAX_RESPONSE_BYTES, + retry: { limit: RETRIES, retryOnTimeout: true, backoffLimit: settings.pollMs }, + }); + } + + // Refuses a caller whose own Tailscale is not running and online, before + // anything is rented, then proves the OAuth client with one token. + async admit(): Promise { + const status = await this.#status().catch((error: unknown) => { + throw new OrlyError(`orly burst reaches its machines over Tailscale, and this machine's \`tailscale status\` failed: ${error instanceof Error ? error.message : String(error)}; install Tailscale and join a tailnet (${DOCS})`); + }); + if (status.BackendState !== "Running" || status.Self?.Online !== true) { + throw new OrlyError(`orly burst reaches its machines over Tailscale, and this machine is not on a tailnet (Tailscale reports ${status.BackendState}${status.Self?.Online === false ? ", offline" : ""}); run \`tailscale up\` (${DOCS})`); + } + await this.#bearer(); + return status.Self.HostName ?? "this machine"; + } + + // One key a single machine joins with: single use, preauthorized, tagged, + // and ephemeral, so the node leaves the tailnet once it goes offline. + async mint(host: string): Promise { + const body = { + capabilities: { devices: { create: { reusable: false, ephemeral: true, preauthorized: true, tags: [BURST_TAG] } } }, + expirySeconds: KEY_SECONDS, description: host.slice(0, DESCRIPTION_CHARS), + }; + const minted = keySchema.parse(await this.#request("POST", "tailnet/-/keys", body)); + return { id: minted.id, secret: minted.key }; + } + + // Cleanup takes no cancellation: it is what a cancellation runs. + async revoke(key: AuthKey): Promise { + await this.#request("DELETE", `tailnet/-/keys/${encodeURIComponent(key.id)}`).catch((error: unknown) => { + if (!(error instanceof TailscaleRequestFailed && error.status === NOT_FOUND)) throw error; + }); + } + + // The joined node's tailnet IPv4 address, as the caller's Tailscale sees it. + async joined(host: string, wait: Wait): Promise { + return until(`${host} to join the tailnet`, async () => { + const peer = this.#peer(await this.#status(wait.signal), host); + return peer?.Online === true ? address(peer) : undefined; + }, wait); + } + + // Where the node is now, online or not, when it joined at all; for logging + // out a machine that joined after its run stopped waiting for it. + async find(host: string): Promise { + const peer = this.#peer(await this.#status(), host); + return peer ? address(peer) : undefined; + } + + // Waits until the node is gone from the caller's view of the tailnet. + async left(host: string, wait: Wait): Promise { + await until(`${host} to leave the tailnet`, async () => this.#peer(await this.#status(wait.signal), host) === undefined || undefined, wait); + } + + // A name any device can claim, so only a node carrying the burst tag counts, + // and two such nodes of one name are refused rather than guessed between. + #peer(status: TailscaleStatus, host: string): Peer | undefined { + const named = Object.values(status.Peer ?? {}).filter((peer) => peer.HostName.toLowerCase() === host.toLowerCase() && peer.Tags?.includes(BURST_TAG)); + if (named.length > 1) throw new OrlyError(`${named.length} tailnet nodes tagged ${BURST_TAG} are named ${host}; remove the stale ones in the Tailscale admin console`); + return named[0]; + } + + async #status(signal?: AbortSignal): Promise { + const read = await captureProcess(["tailscale", "status", "--json"], { env: this.#env, timeoutMs: STATUS_TIMEOUT_MS, ...(signal ? { signal } : {}) }); + if (read.code !== 0) throw new OrlyError(read.stderr.trim().split("\n")[0] || `tailscale status exited ${read.code}`); + return statusSchema.parse(JSON.parse(read.stdout)); + } + + // The client secret goes in a form body, never a URL, an argument or a file. + async #bearer(): Promise { + if (this.#token && Date.now() < this.#token.expires - TOKEN_MARGIN_MS) return this.#token.value; + const form = new URLSearchParams({ client_id: this.#client.id, client_secret: this.#client.secret, grant_type: "client_credentials" }); + const answered = await this.#call("POST", "oauth/token", { body: form }); + const token = tokenSchema.parse(answered); + this.#token = { value: token.access_token, expires: Date.now() + token.expires_in * 1000 }; + return token.access_token; + } + + async #request(method: string, path: string, json?: unknown): Promise { + const authorization = `Bearer ${await this.#bearer()}`; + return this.#call(method, path, { headers: { Authorization: authorization }, ...(json === undefined ? {} : { json }) }); + } + + // A failure names the method, the path and Tailscale's own message, which + // carries neither the secret nor a key. + async #call(method: string, path: string, options: { body?: URLSearchParams; json?: unknown; headers?: Record }): Promise { + try { + const text = await (await this.#http(path, { method, ...options })).text(); + return text ? JSON.parse(text) : {}; + } catch (error) { + if (isHTTPError(error)) throw new TailscaleRequestFailed(`Tailscale ${method} /api/v2/${path} answered ${error.response.status}: ${tailscaleMessage(error.data)}`, error.response.status); + throw error; + } + } +} + +class TailscaleRequestFailed extends OrlyError { + readonly status: number; + + constructor(message: string, status: number) { + super(message); + this.status = status; + } +} + +function address(peer: Peer): string | undefined { + return peer.TailscaleIPs?.find((candidate) => IPV4.test(candidate) && candidate.startsWith(TAILNET_PREFIX)); +} + +function tailscaleMessage(body: unknown): string { + const parsed = z.object({ message: z.string() }).safeParse(body); + return parsed.success ? parsed.data.message : "no message"; +} diff --git a/src/burst/test_support.ts b/src/burst/test_support.ts index f6822115..94674279 100644 --- a/src/burst/test_support.ts +++ b/src/burst/test_support.ts @@ -1,8 +1,9 @@ // Shared fixtures for the burst suites: a repository with lanes declared, a -// directory of fake executables first on PATH, a line sink, and the -// caller-address answer; fake_tir.ts answers for E2E Networks TIR and -// aws-test-support.ts for EC2. No suite reaches a real cloud: `ssh` and `op` -// on the PATH they hand orly are fakes, and so is every fetch. +// directory of fake executables first on PATH and a line sink; +// fake_tailscale.ts answers for Tailscale, fake_tir.ts for E2E Networks TIR +// and aws-test-support.ts for EC2. No suite reaches a real cloud or tailnet: +// `ssh`, `tailscale` and `op` on the PATH they hand orly are fakes, and so is +// every fetch. import type { BurstDependencies } from "./index"; import type { Environment } from "./settings"; @@ -10,6 +11,7 @@ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "n import { join } from "node:path"; import { CONFIG_PATH } from "../config"; +import { TAILSCALE_CREDENTIALS } from "./fake_tailscale"; import { git, newRepository, ROOT, temporaryDirectory } from "../gates_test_support"; import { isObject } from "../model"; @@ -18,7 +20,6 @@ export const FIXTURE_BRANCH = "feat/burst-fixture"; // Independently derived SHA-256 prefix of example.invalid/acme/widget. export const REPOSITORY = "de3cf852395d210d0d756297"; export const SECRET_VALUE = "op-value-test-0000"; -export const CALLER_ADDRESS = "198.51.100.77"; export function burstRepository(burst: Record = {}, lanes: Record = {}): string { const root = newRepository(); @@ -36,13 +37,14 @@ export function burstRepository(burst: Record = {}, lanes: Reco return root; } -// `ssh` runs the TypeScript fake beside this file; `op` prints SECRET_VALUE -// and records how it was called. +// `ssh` and `tailscale` run the TypeScript fakes beside this file; `op` +// prints SECRET_VALUE and records how it was called. export function fakeBin(): { bin: string; state: string } { const bin = temporaryDirectory(); const state = temporaryDirectory(); const tools = { ssh: `exec bun ${join(ROOT, "src/burst/fake_ssh.ts")} "$@"`, + tailscale: `exec bun ${join(ROOT, "src/burst/fake_tailscale.ts")} "$@"`, op: `printf '%s\\n' "$*" >> "${join(state, "op-calls.txt")}"\n[ -n "\${FAKE_OP_FAIL:-}" ] && { echo "[ERROR] could not read secret" >&2; exit 1; }\nprintf '%s' "${SECRET_VALUE}"`, }; for (const [name, body] of Object.entries(tools)) { @@ -69,20 +71,14 @@ export function burstDependencies(root: string, env: Environment, fetcher: Burst } // The environment every burst suite starts from: fast polls, a private -// output directory and the fakes first on PATH. +// output directory, the fakes first on PATH and the fake OAuth client. export function burstEnvironment(bin: string, state: string, extra: Environment = {}): Environment { return { PATH: `${bin}:${process.env.PATH ?? ""}`, HOME: process.env.HOME, TMPDIR: process.env.TMPDIR, - ORLY_BURST_POLL_SECONDS: "0.01", ORLY_BURST_OUT: join(state, "out"), FAKE_SSH_STATE: state, ...extra, + ORLY_BURST_POLL_SECONDS: "0.01", ORLY_BURST_OUT: join(state, "out"), FAKE_SSH_STATE: state, ...TAILSCALE_CREDENTIALS, ...extra, }; } -// What checkip.amazonaws.com answers a caller at CALLER_ADDRESS. -export async function callerAddress(input: string | URL | Request): Promise { - if (String(input) !== "https://checkip.amazonaws.com") throw new Error(`unexpected request to ${String(input)}`); - return new Response(`${CALLER_ADDRESS}\n`); -} - export function recordedCalls(state: string): string[][] { const file = join(state, "calls.jsonl"); if (!existsSync(file)) return []; diff --git a/src/burst/tir.ts b/src/burst/tir.ts index 28f7e482..902a4538 100644 --- a/src/burst/tir.ts +++ b/src/burst/tir.ts @@ -19,6 +19,7 @@ type Body = Record; // Instance created with `kind: "vm"`, a whole Linux machine reached as root. const BASE_URL = "https://api.e2enetworks.com/myaccount/api/v1/gpu/"; const REQUEST_TIMEOUT_MS = 60_000; +const WIREGUARD_PORT = 41641; // The image and plan catalogues are the largest answers; past this is not one. const MAX_RESPONSE_BYTES = 8 * 1024 * 1024; // TIR answers 429, a 5xx or nothing while it is busy. ky retries those for @@ -32,8 +33,9 @@ const skusSchema = z.object({ data: z.object({ CPU: z.array(z.object({ const imagesSchema = z.object({ data: z.array(z.object({ name: z.string(), versions: z.array(z.object({ image_version_id: z.number(), version: z.coerce.string() })).default([]) })) }); const keysSchema = z.object({ data: z.array(z.object({ pk: identifier, label: z.string() })) }); const vmsSchema = z.object({ data: z.array(z.object({ id: identifier, name: z.string() })), total_page_number: z.number().nullish() }); -const groupSchema = z.object({ data: z.object({ id: identifier }) }); -const groupsSchema = z.object({ data: z.array(z.object({ id: identifier, name: z.string() })) }); +// A security group's or a start script's create answers `data.id`; a list, each one's id and name. +const createdOneSchema = z.object({ data: z.object({ id: identifier }) }); +const namedSchema = z.object({ data: z.array(z.object({ id: identifier, name: z.string() })) }); // One VM answers `data.id`; a quantity of them answers `data.created`. const createdSchema = z.object({ data: z.union([z.object({ id: identifier }), z.object({ created: z.array(z.object({ id: identifier })).min(1) })]) }); const vmSchema = z.object({ data: z.object({ status: z.string(), public_ip: z.string().nullish() }) }); @@ -92,19 +94,36 @@ export class E2eApi { await this.#request("DELETE", `/ssh_keys/${pk}/`, { project: false }); } - // POST /security_groups/: a group whose one rule admits SSH from `address`. - async createSshGroup(name: string, address: string, signal?: AbortSignal): Promise { - // TIR refuses a group without an outbound rule; the machine's own traffic, - // such as package installs, leaves through this one. + // POST /security_groups/: a group that opens no SSH port. TIR refuses a + // group without an inbound and an outbound rule, so the inbound one admits + // Tailscale's WireGuard port, which lets the caller connect directly rather + // than through a relay; the machine's own traffic leaves by the outbound one. + async createGroup(name: string, signal?: AbortSignal): Promise { const rules = [ - { rule_type: "inbound", protocol: "TCP", protocol_type: "CustomTCP", network_type: "manual", cidr_ip: address, cidr_subnet: 32, ports: [22], description: "SSH from the orly burst caller" }, + { rule_type: "inbound", protocol: "UDP", protocol_type: "CustomUDP", network_type: "any", ports: [WIREGUARD_PORT], description: "Tailscale WireGuard for the orly burst machine" }, { rule_type: "outbound", protocol: "All", protocol_type: "AllTraffic", network_type: "any", ports: [], description: "All traffic from the orly burst machine" }, ]; - return groupSchema.parse(await this.#request("POST", "/security_groups/", { signal, body: { name, description: "SSH for one orly burst run", rules } })).data.id; + return createdOneSchema.parse(await this.#request("POST", "/security_groups/", { signal, body: { name, description: "One orly burst run, reached over Tailscale", rules } })).data.id; + } + + // POST /notebooks/init-script/: a start script, which a VM created with + // its identifier runs as root at boot. Its text holds a single-use key, so + // a refusal names its status only: TIR's errors may quote the text back. + async createStartScript(name: string, script: string, signal?: AbortSignal): Promise { + return createdOneSchema.parse(await this.#request("POST", "/notebooks/init-script/", { signal, body: { name, init_script: script }, quiet: true })).data.id; + } + + async startScripts(): Promise> { + return namedSchema.parse(await this.#request("GET", "/notebooks/init-script/")).data; + } + + // TIR refuses to delete a script a VM still uses. + async deleteStartScript(id: string): Promise { + await this.#request("DELETE", `/notebooks/init-script/${id}/`); } async groups(): Promise> { - return groupsSchema.parse(await this.#request("GET", "/security_groups/")).data; + return namedSchema.parse(await this.#request("GET", "/security_groups/")).data; } // DELETE /security_groups/{id}/; the `/rules/` path answers 405. @@ -157,7 +176,7 @@ export class E2eApi { await this.#request("DELETE", `/notebooks/vm/snapshots/${id}/`, { signal }); } - async #request(method: string, path: string, options: { signal?: AbortSignal | undefined; body?: Body; query?: Record; project?: boolean } = {}): Promise { + async #request(method: string, path: string, options: { signal?: AbortSignal | undefined; body?: Body; query?: Record; project?: boolean; quiet?: boolean } = {}): Promise { options.signal?.throwIfAborted(); const searchParams = { ...(options.project === false ? {} : { project_id: this.#credentials.project }), @@ -172,7 +191,7 @@ export class E2eApi { const text = await response.text(); return text ? JSON.parse(text) : {}; } catch (error) { - if (isHTTPError(error)) throw new E2eRequestFailed(`E2E TIR ${method} ${path} answered ${error.response.status}: ${errorMessage(error.data)}`, error.response.status); + if (isHTTPError(error)) throw new E2eRequestFailed(`E2E TIR ${method} ${path} answered ${error.response.status}${options.quiet ? "" : `: ${errorMessage(error.data)}`}`, error.response.status); throw error; } } diff --git a/src/burst/types.ts b/src/burst/types.ts index 4281b1d0..73d6f2fb 100644 --- a/src/burst/types.ts +++ b/src/burst/types.ts @@ -1,10 +1,15 @@ import type { RepoConfig } from "../config"; import type { BurstSettings } from "./settings"; +import type { Tailnet } from "./tailnet"; // Shared by the command line and the cloud lifecycle. export const LANE_PREFIX = "burst."; export const MINUTE_MS = 60_000; export const IPV4 = /^\d{1,3}(?:\.\d{1,3}){3}$/; +// A run id is `-<14-digit UTC stamp>-<4 hexadecimal characters>`. Its +// tail names the run's machines, nodes and start scripts, unique to the run. +const RUN_TAIL = /(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})-[0-9a-f]{4}$/; +const RUN_TAIL_CHARS = 19; // The fetch a provider calls its cloud with, so tests can answer for it. export type Fetch = (input: string | URL | Request, init?: RequestInit) => Promise; @@ -19,12 +24,11 @@ export type Io = { write: (line: string) => void; signal: AbortSignal }; // What a cloud run fixes before any machine starts: the repository, the ref // and its commit, the bundle of that ref, the run's own SSH key pair and -// known_hosts, and the one caller address its SSH rule admits. +// known_hosts, and the caller's tailnet its machines join. export type BurstRun = Io & { root: string; config: RepoConfig; settings: BurstSettings; - fetch: Fetch; ref: string; commit: string; repo: string; @@ -34,7 +38,7 @@ export type BurstRun = Io & { key: string; publicKey: string; knownHosts: string; - caller: string; + tailnet: Tailnet; }; // What listing and pruning a repository's snapshots needs, which is less than a run. @@ -48,7 +52,9 @@ export type Image = { id: string; name: string; snapshot: boolean }; export type Snapshot = { id: string; name: string; sizeGb: number | undefined; parts: string[]; ready: boolean }; // How an AWS machine is rented; a Spot price is there when AWS said it. export type Billing = { market: "on-demand" } | { market: "spot"; hourly: number | undefined }; -export type Machine = { id: string; label: string; address: string | undefined; billing?: Billing }; +// `node` is the name the machine joins the tailnet as. `address` is the +// public one the cloud reports until it has joined, and its tailnet one after. +export type Machine = { id: string; label: string; address: string | undefined; node?: string | undefined; billing?: Billing }; // The seam a cloud provider fills: how its machines start, become reachable, // stop and turn into images. The shared code in cloud.ts owns the order, @@ -64,10 +70,12 @@ export interface CloudProvider { // What a snapshot warms from and a lane with no matching snapshot boots. baseImage(): Image; snapshots(scope: SnapshotScope): Promise; - // Registers what the run's machines share: its public key, and an SSH rule - // admitting run.caller alone. + // Registers what the run's machines share: its public key, and a firewall + // that opens no SSH port, since the caller reaches them over its tailnet. prepare(run: BurstRun): Promise; - create(run: BurstRun, job: Job): Promise; + // Starts a machine that runs `boot` as root on its first boot, through the + // cloud's own user data, so it joins the tailnet with no inbound port. + create(run: BurstRun, job: Job, boot: string): Promise; // Waits until the machine runs, and returns it with its public address. ready(run: BurstRun, job: Job, machine: Machine): Promise; capture(run: BurstRun, job: Job, machine: Machine, name: string): Promise; @@ -77,3 +85,17 @@ export interface CloudProvider { // started without learning its identifier, once every lane has ended. finish(run: BurstRun): Promise; } + +export function newRunId(ref: string, now: Date): string { + return `${ref}-${now.toISOString().replaceAll(/[-:T]/g, "").slice(0, 14)}-${crypto.randomUUID().slice(0, 4)}`; +} + +export function runTail(runId: string): string { + return runId.slice(-RUN_TAIL_CHARS); +} + +// When the run whose tail ends `text` began, or undefined when it is none. +export function runBegan(text: string): number | undefined { + const [, year, month, day, hour, minute, second] = (RUN_TAIL.exec(text) ?? []).map(Number); + return year === undefined || month === undefined ? undefined : Date.UTC(year, month - 1, day, hour, minute, second); +} diff --git a/src/cli.test.ts b/src/cli.test.ts index 4ce64c97..dd0241ea 100644 --- a/src/cli.test.ts +++ b/src/cli.test.ts @@ -27,6 +27,8 @@ describe("orly command", () => { expect(result.exitCode).toBe(0); expect(output).toContain("orly gate"); expect(output).toContain("orly override --reason "); + expect(output).toContain("orly proof --test -- ..."); + expect(output).toContain(`orly note "" [--context ""] [--spec ]`); expect(output).not.toContain("orly adopt"); expect(output).not.toContain("oracle-rules"); }); diff --git a/src/cli.ts b/src/cli.ts index 56714d0b..52dbc956 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -1,6 +1,6 @@ #!/usr/bin/env bun -import { existsSync } from "node:fs"; -import { join, resolve } from "node:path"; +import { existsSync, realpathSync } from "node:fs"; +import { isAbsolute, join, relative, resolve } from "node:path"; import { burst } from "./burst/index"; import { printHelp } from "./cli_help"; @@ -10,6 +10,8 @@ import { GateReport, isGateName, recordOverride, runGate, runGates } from "./gat import { agentRuntimes, defaultHomes, helperSources, missingHelpers } from "./helpers"; import { install, InstallResult } from "./install"; import { isString, messageOf, OrlyError, readJsonObject, RulesModel } from "./model"; +import { appendNote } from "./note"; +import { recordProof } from "./proof"; import { Renderer } from "./render"; import { verifyRuleset } from "./verify"; import { commandSetupErrors } from "./validation"; @@ -39,6 +41,12 @@ const GATE_ERRORS = { reuse: "[ORLY-GATE-002] --reuse-verification requires the named pr gate", } as const; const INSTALL_OPTIONS_ERROR = "[ORLY-INSTALL-001] install accepts only --force, --no-hooks, --with , --dry-run and --json"; +const TEST_FLAG = "--test"; +const CONTEXT_FLAG = "--context"; +const SPEC_FLAG = "--spec"; +const COMMAND_SEPARATOR = "--"; +const PROOF_USAGE = "[ORLY-PROOF-001] usage: orly proof --test -- ..."; +const NOTE_USAGE = "[ORLY-NOTE-001] usage: orly note \"\" [--context \"\"] [--spec ]"; const { root, arguments: commandArguments } = parseRoot(Bun.argv.slice(2)); process.exit(await execute(root, commandArguments)); @@ -71,6 +79,8 @@ async function run(model: RulesModel, args: string[]): Promise { if (command === "gate") return gate(model, rest); if (command === "override") return override(rest); if (command === "burst") return burstCommand(rest); + if (command === "proof") return proof(rest); + if (command === "note") return note(model, rest); throw new OrlyError(`unknown command: ${command}`); } @@ -109,6 +119,37 @@ async function burstCommand(args: string[]): Promise { } } +// The agent reverts or mutates the code a new test covers; orly runs the +// command and keeps what it saw only when that test is reported failing. +function proof(args: string[]): number { + const separator = args.indexOf(COMMAND_SEPARATOR); + const command = separator < 0 ? [] : args.slice(separator + 1); + const { values, positional } = options(separator < 0 ? args : args.slice(0, separator), [TEST_FLAG], PROOF_USAGE); + const test = values.get(TEST_FLAG); + if (positional.length !== 1 || !test || command.length === 0) throw new OrlyError(PROOF_USAGE); + const root = projectRoot(); + const file = repositoryPath(root, positional[0] ?? ""); + const recorded = recordProof(root, file, test, command); + console.log(`${PASS_GLYPH} fail-before proof recorded for ${file} › ${test}`); + console.log(` ${recorded.failing_line}`); + console.log(` ran ${recorded.revision.slice(0, 12)}${recorded.mutation ? " with the code changes shown by git diff HEAD" : " with its code unchanged"}`); + return 0; +} + +async function note(model: RulesModel, args: string[]): Promise { + const { values, positional } = options(args, [CONTEXT_FLAG, SPEC_FLAG], NOTE_USAGE); + if (positional.length !== 1) throw new OrlyError(NOTE_USAGE); + const root = projectRoot(); + const spec = values.get(SPEC_FLAG); + const context = values.get(CONTEXT_FLAG); + const written = await appendNote(model, root, { + quote: positional[0] ?? "", now: new Date(), + ...(context === undefined ? {} : { context }), ...(spec === undefined ? {} : { spec: repositoryPath(root, spec) }), + }); + console.log(`${PASS_GLYPH} noted in ${written.spec} Discovery:\n${written.line}`); + return 0; +} + function override(args: string[]): number { const criterion = args.find((argument) => !argument.startsWith("-")) ?? ""; if (!criterion) throw new OrlyError("override requires one criterion name"); @@ -264,6 +305,27 @@ function parseRoot(args: string[]): { root: string; arguments: string[] } { return { root: resolve(value), arguments: args.filter((_, position) => position !== index && position !== index + 1) }; } +// Each named flag takes one value and appears at most once; anything else +// that starts with a dash is refused with the command's usage. +function options(args: string[], flags: string[], usage: string): { values: Map; positional: string[] } { + const values = new Map(); + const positional: string[] = []; + for (let index = 0; index < args.length; index++) { + const argument = args[index] ?? ""; + if (!argument.startsWith("-")) { positional.push(argument); continue; } + const value = args[++index]; + if (!flags.includes(argument) || values.has(argument) || value === undefined || value.startsWith("-")) throw new OrlyError(usage); + values.set(argument, value); + } + return { values, positional }; +} + +function repositoryPath(root: string, path: string): string { + const inside = relative(realpathSync(root), resolve(realpathSync(process.cwd()), path)); + if (!inside || inside.startsWith("..") || isAbsolute(inside)) throw new OrlyError(`${path} is outside this repository`); + return inside; +} + function requireNoArguments(args: string[], usage: string): void { if (args.length > 0) throw new OrlyError(usage); } diff --git a/src/cli_help.ts b/src/cli_help.ts index c0135b2d..bcd92e3b 100644 --- a/src/cli_help.ts +++ b/src/cli_help.ts @@ -12,8 +12,9 @@ Gates (working tree unchanged; required checks must pass or carry an owner overr state, so a commit hook's own dirty tree never blocks it verify does the work hold up? configuration, docs language, and the non-test verify.* set; Sections in progress may be pushed - pr can this ship? branch, tree, pushed, configuration, docs, and - every declared verify.* command + pr can this ship? branch, tree, pushed, configuration, docs, + coupled paths, and every declared verify.* command; it also + reports new tests that carry no fail-before proof orly override --reason empty commit with an Orly-Override trailer Commands default to 30 minutes and 64 mebibytes of combined output each. @@ -22,11 +23,27 @@ Gates (working tree unchanged; required checks must pass or carry an owner overr Prerequisite failures block commands; a command failure leaves later groups not_run. Results distinguish passed, failed, blocked, cancelled, skipped and not_run. Reuse is off by default. A reviewed reuse. policy must declare - hermetic: true, max_age_ms, toolchain probes and any extra input paths. - Optional tracked_inputs selects tracked dependencies for cross-revision reuse; - omit it to keep exact-revision evidence. Full-source mutation checks stay fresh. + hermetic: true, max_age_ms, toolchain probes and any extra input paths; a + hermetic command reads no Git history. Evidence is keyed to tracked content: + a run before the commit (gate pr --accept-dirty) or the push (gate verify) is + reused once that same tree is committed, clean and pushed. Optional + tracked_inputs narrows the content to the tracked paths it names. An + untracked file during the run, or any later change, forces a fresh run. Invalid prior completion runs fresh; lock or start-marker failures block commands. Private attempt history stays beneath Git metadata. + coupled: [{"when": [...], "then": [...]}] in .orly/orly.json + makes gate pr fail a branch that changes a path under when and none under then. + +Records (the agent writes them; the pr gate reads them): + orly proof --test -- ... + with the code a new test covers reverted or + mutated, run COMMAND, and keep the record + only when it fails and an output line reports + NAME failing. gate pr names new TypeScript, + JavaScript, Rust, Go and Python tests without one + orly note "" [--context ""] [--spec ] + append the owner's verbatim words, dated, to + the Discovery section of the one active spec Install (the repository is the unit — no checkout of this package required): orly init [--force] [--no-hooks] [--with ] [--dry-run] [--json] diff --git a/src/command_process.ts b/src/command_process.ts index 27c5bae3..415feecd 100644 --- a/src/command_process.ts +++ b/src/command_process.ts @@ -7,6 +7,10 @@ const PRIVATE_FILE_MODE = 0o600; const TEXT_ENCODING = "utf8"; const KILL_SIGNAL = "SIGKILL"; const MISSING_PROCESS = "ESRCH"; +// macOS refuses to signal a group whose members have all exited but are not +// yet reaped, as a command that ended just as its deadline came; that group, +// like a missing one, needs no stopping. +const EXITED_GROUP = "EPERM"; const PIPE_OUTPUT = "pipe"; const OWNER_POLL_MS = 100; const TERMINATION_SIGNALS = ["SIGTERM", "SIGINT", "SIGHUP"] as const; @@ -20,7 +24,7 @@ export type CommandResult = { exit_code: number | null; elapsed_ms: number; outp export function stopOwnedGroup(pid: number): void { if (!Number.isSafeInteger(pid) || pid <= 0) throw new Error("invalid owned process group"); try { process.kill(-pid, KILL_SIGNAL); } - catch (error) { if (!hasErrorCode(error, MISSING_PROCESS)) throw error; } + catch (error) { if (!hasErrorCode(error, MISSING_PROCESS) && !hasErrorCode(error, EXITED_GROUP)) throw error; } } async function capture(stream: ReadableStream, file: string, onBytes: (size: number) => void): Promise { diff --git a/src/config.ts b/src/config.ts index 3df5cfcf..42c593e5 100644 --- a/src/config.ts +++ b/src/config.ts @@ -5,7 +5,7 @@ import { assertWritableInside, hashContent, isObject, isString, JsonObject, obje import { git } from "./git_env"; import { selectPacks, sniffCommands } from "./config_discovery"; import { validateCommands, validateSurfaces } from "./validation"; -import { burstSchema, validateConfiguration, reusePoliciesSchema, type BurstConfig, type ReusePolicies } from "./config_validation"; +import { burstSchema, couplingsSchema, validateConfiguration, reusePoliciesSchema, type BurstConfig, type Coupling, type ReusePolicies } from "./config_validation"; import { commandLimitsSchema, type LaneLimits } from "./command_limits"; const ORACLE_DIRECTORY = ".orly"; @@ -33,6 +33,7 @@ export type RepoConfig = { packs: string[]; commands: Record; surfaces: JsonObject | undefined; + coupled?: Coupling[]; managed: string[]; limits?: LaneLimits; reuse?: ReusePolicies; @@ -83,6 +84,7 @@ export function parseConfig(value: JsonObject): RepoConfig { packs: stringArray(value[PACKS_FIELD] ?? [], `${CONFIG_PATH} ${PACKS_FIELD}`), commands: readCommands(value[COMMANDS_FIELD]), surfaces: isObject(value.surfaces) ? value.surfaces : undefined, + ...(value.coupled !== undefined ? { coupled: couplingsSchema.parse(value.coupled) } : {}), managed: stringArray(value[MANAGED_FIELD] ?? [], `${CONFIG_PATH} ${MANAGED_FIELD}`), ...(isObject(value.limits) ? { limits: Object.fromEntries(Object.entries(value.limits).map(([lane, limits]) => [lane, commandLimitsSchema.parse(limits)])) } : {}), ...(value.reuse !== undefined ? { reuse: reusePoliciesSchema.parse(value.reuse) } : {}), @@ -153,6 +155,7 @@ export function serialiseConfig(config: RepoConfig): string { packs: config.packs, commands: config.commands, ...(config.surfaces ? { surfaces: config.surfaces } : {}), + ...(config.coupled ? { coupled: config.coupled } : {}), ...(config.limits ? { limits: config.limits } : {}), ...(config.reuse ? { reuse: config.reuse } : {}), ...(config.burst ? { burst: config.burst } : {}), diff --git a/src/config_validation.test.ts b/src/config_validation.test.ts index ff891e38..62d8bd3e 100644 --- a/src/config_validation.test.ts +++ b/src/config_validation.test.ts @@ -21,11 +21,15 @@ for (const [field, value] of [ ["limits", { [UNIT_LANE]: { typo: 10 } }], ["limits", { [UNIT_LANE]: null }], ["burst", []], ["burst", { setup: "make setup" }], ["burst", { setup: [[]] }], ["burst", { warm: [[""]] }], ["burst", { secrets: { API_TOKEN: "Vault/item/field" } }], ["burst", { secrets: { "1API": "op://v/i/f" } }], - ["burst", { secrets: { OP_SERVICE_ACCOUNT_TOKEN: "op://v/i/f" } }], ["burst", { secrets: { API_TOKEN: "op://v/i/f\nx" } }], + ["burst", { secrets: { OP_SERVICE_ACCOUNT_TOKEN: "op://v/i/f" } }], ["burst", { secrets: { TS_OAUTH_CLIENT_SECRET: "op://v/i/f" } }], + ["burst", { secrets: { E2E_API_KEY: "op://v/i/f" } }], ["burst", { secrets: { AWS_SECRET_ACCESS_KEY: "op://v/i/f" } }], ["burst", { secrets: { API_TOKEN: "op://v/i/f\nx" } }], ["burst", { artifacts: ["../outside"] }], ["burst", { artifacts: ["/abs/path"] }], ["burst", { artifacts: [".git/config"] }], ["burst", { e2e: { location: "Mumbai" } }], ["burst", { e2e: { region: "Chennai" } }], ["burst", { aws: { instance_types: [] } }], ["burst", { aws: { image: "ubuntu" } }], ["burst", { aws: { region: "Mumbai" } }], ["burst", { lanes: {} }], ["burst", { directories: ["TOOLBOX_DIR", "TOOLBOX_DIR"] }], ["burst", { directories: ["1DIR"] }], + ["coupled", []], ["coupled", {}], ["coupled", [{ when: ["src/wire/"] }]], ["coupled", [{ when: [], then: ["VERSION"] }]], + ["coupled", [{ when: ["src/wire/"], then: ["../VERSION"] }]], ["coupled", [{ when: [".git/HEAD"], then: ["VERSION"] }]], + ["coupled", [{ when: ["src/wire/"], then: ["VERSION"], why: "unknown key" }]], ["coupled", [{ when: [""], then: ["VERSION"] }]], ] as Array<[string, unknown]>) { test(`both configuration readers reject invalid ${field} value ${JSON.stringify(value)}`, async () => { const root = mkdtempSync(join(tmpdir(), "orly-config-validation-")); @@ -49,6 +53,13 @@ test("a burst object survives a rewrite exactly, with no fields it did not have" expect(parseConfig(JSON.parse(serialiseConfig(config)))).toEqual(config); }); +test("coupled path groups survive a rewrite exactly", () => { + const coupled = [{ when: ["src/wire/"], then: ["src/wire/VERSION", "docs/protocol.md"] }]; + const config = parseConfig({ ...BASE, coupled }); + expect(JSON.parse(serialiseConfig(config)).coupled).toEqual(coupled); + expect(parseConfig(JSON.parse(serialiseConfig(config)))).toEqual(config); +}); + test("configuration limits survive a rewrite and override only their named lane", () => { const limits = { [UNIT_LANE]: { timeout_ms: 200, output_bytes: 4096 }, conform: { timeout_ms: 500 } }; const config = parseConfig({ ...BASE, limits }); diff --git a/src/config_validation.ts b/src/config_validation.ts index 25d8e290..3762fba9 100644 --- a/src/config_validation.ts +++ b/src/config_validation.ts @@ -22,8 +22,9 @@ const ENVIRONMENT_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/; // 1Password names a vault and an item with spaces allowed, never a control // character; `op read` resolves the reference on the caller. const OP_REFERENCE = /^op:\/\/[^/\u0000-\u001f]+\/[^/\u0000-\u001f]+\/[^\u0000-\u001f]+$/; -// The token `op` itself reads, which no declared secret may overwrite. -const OP_TOKEN = "OP_SERVICE_ACCOUNT_TOKEN"; +// orly's own credentials, which a lane's secret must never name: a value +// already in the caller's environment is sent to the machine as it is. +const OWN_CREDENTIALS = /^(?:OP_SERVICE_ACCOUNT_TOKEN$|TS_OAUTH_|E2E_|AWS_)/; const invocations = z.array(z.array(nonempty).min(1)); const LOGIN_USER = /^[a-z_][a-z0-9_-]*$/; export const E2E_LOCATIONS = ["Delhi", "Chennai"] as const; @@ -47,7 +48,7 @@ const awsPlacement = z.object({ export const burstSchema = z.object({ setup: invocations.optional(), warm: invocations.optional(), - secrets: z.record(z.string().regex(ENVIRONMENT_NAME).refine((name) => name !== OP_TOKEN, `must not be ${OP_TOKEN}`), z.string().regex(OP_REFERENCE, "must be an op:// reference")).optional(), + secrets: z.record(z.string().regex(ENVIRONMENT_NAME).refine((name) => !OWN_CREDENTIALS.test(name), "must not name OP_SERVICE_ACCOUNT_TOKEN or a TS_OAUTH_, E2E_ or AWS_ variable"), z.string().regex(OP_REFERENCE, "must be an op:// reference")).optional(), artifacts: z.array(input).optional(), // Variables that name a directory on the caller, copied to the machine for // the lane, such as a signed toolbox fetched just before the run. @@ -56,6 +57,10 @@ export const burstSchema = z.object({ aws: awsPlacement.optional(), }).strict(); export type BurstConfig = z.infer; +// A change under any `when` prefix needs a change under a `then` prefix on the +// same branch, such as a wire format and the protocol version that names it. +export const couplingsSchema = z.array(z.object({ when: z.array(input).min(1), then: z.array(input).min(1) }).strict()).min(1); +export type Coupling = z.infer[number]; export const reusePoliciesSchema = z.record(nonempty, z.object({ hermetic: z.literal(true), max_age_ms: z.number().int().positive().max(Number.MAX_SAFE_INTEGER), toolchain: z.array(z.array(nonempty).min(1)).min(1), inputs: z.array(input).default([]), @@ -68,6 +73,7 @@ const configurationSchema = z.object({ packs: z.array(nonempty).optional(), commands: z.unknown().optional(), surfaces: z.unknown().optional(), + coupled: couplingsSchema.optional(), managed: z.array(nonempty).optional(), limits: z.record(nonempty, commandLimitsSchema).optional(), reuse: reusePoliciesSchema.optional(), diff --git a/src/coupled_paths.integration.test.ts b/src/coupled_paths.integration.test.ts new file mode 100644 index 00000000..e925fae0 --- /dev/null +++ b/src/coupled_paths.integration.test.ts @@ -0,0 +1,100 @@ +import { afterEach, expect, test } from "bun:test"; +import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; + +import { CONFIG_PATH } from "./config"; +import { recordOverride, runGate } from "./gates"; +import { cleanupTemporaryDirectories, git, modelFor, newRepository } from "./gates_test_support"; + +const CRITERION = "paths.coupled"; +const WIRE = "src/wire/"; +// Outside the wire prefix, so a version change alone triggers nothing. +const VERSION = "protocol/VERSION"; + +afterEach(cleanupTemporaryDirectories); + +// A repository whose wire format and protocol version must move together, with +// a branch cut from main; each test commits what its branch changes. +async function coupledRepository(coupled: unknown = [{ when: [WIRE], then: [VERSION] }]) { + const root = newRepository(); + mkdirSync(join(root, WIRE), { recursive: true }); + mkdirSync(join(root, "protocol")); + writeFileSync(join(root, "src/wire/frame.ts"), "export const FRAME = 1;\n"); + writeFileSync(join(root, VERSION), "1\n"); + const model = await modelFor(root); + const config = JSON.parse(readFileSync(join(root, CONFIG_PATH), "utf8")); + writeFileSync(join(root, CONFIG_PATH), JSON.stringify({ ...config, coupled })); + commit(root, "chore: couple the wire and its version"); + git(root, "checkout", "-q", "-b", "feat/wire"); + return { root, model }; +} + +function commit(root: string, message: string): void { + git(root, "add", "."); + git(root, "commit", "-q", "-m", message); +} + +function coupledResult(root: string, model: Awaited>) { + return runGate(model, root, "pr").results.find((result) => result.name === CRITERION); +} + +test("a wire change without its version change fails and names both sides", async () => { + const { root, model } = await coupledRepository(); + writeFileSync(join(root, "src/wire/frame.ts"), "export const FRAME = 2;\n"); + commit(root, "feat: widen the frame"); + const result = coupledResult(root, model); + expect(result).toMatchObject({ ok: false, status: "failed" }); + expect(result?.detail).toStartWith(`src/wire/frame.ts changed under ${WIRE}, but nothing under ${VERSION} did`); + expect(result?.detail).toContain(`orly override ${CRITERION} --reason `); +}); + +test("a wire change that moves its version passes", async () => { + const { root, model } = await coupledRepository(); + writeFileSync(join(root, "src/wire/frame.ts"), "export const FRAME = 2;\n"); + writeFileSync(join(root, VERSION), "2\n"); + commit(root, "feat: widen the frame and bump the protocol"); + expect(coupledResult(root, model)).toMatchObject({ ok: true, status: "passed", detail: "1 coupled path group(s) changed together or not at all" }); +}); + +test("a coupling runs one way: the version alone may move", async () => { + const { root, model } = await coupledRepository(); + writeFileSync(join(root, VERSION), "2\n"); + commit(root, "chore: bump the protocol"); + expect(coupledResult(root, model)?.ok).toBeTrue(); +}); + +test("each broken group is named, and an unrelated change breaks none", async () => { + const { root, model } = await coupledRepository([{ when: [WIRE], then: [VERSION] }, { when: ["schemas/"], then: ["src/config.ts"] }, { when: ["docs/"], then: ["README.md"] }]); + mkdirSync(join(root, "schemas")); + writeFileSync(join(root, "schemas/profile.json"), "{}\n"); + writeFileSync(join(root, "src/wire/frame.ts"), "export const FRAME = 3;\n"); + commit(root, "feat: two one-sided changes"); + const detail = coupledResult(root, model)?.detail ?? ""; + expect(detail).toContain(`but nothing under ${VERSION} did`); + expect(detail).toContain("schemas/profile.json changed under schemas/, but nothing under src/config.ts did"); + expect(detail).not.toContain("README.md"); +}); + +test("a sibling that only shares a prefix's spelling is matched as the prefix says", async () => { + const { root, model } = await coupledRepository([{ when: ["src/wire/frame"], then: [VERSION] }]); + writeFileSync(join(root, "src/wire/frame_test_data.ts"), "export const SAMPLE = 1;\n"); + commit(root, "test: add frame data"); + expect(coupledResult(root, model)?.ok).toBeFalse(); +}); + +test("an owner override satisfies a broken coupling without turning it green", async () => { + const { root, model } = await coupledRepository(); + writeFileSync(join(root, "src/wire/frame.ts"), "export const FRAME = 2;\n"); + commit(root, "refactor: rename inside the frame"); + recordOverride(root, CRITERION, "a rename with no wire effect"); + expect(coupledResult(root, model)).toMatchObject({ ok: true, override: "a rename with no wire effect" }); +}); + +test("a repository with no coupling declared passes and says so", async () => { + const root = newRepository(); + const model = await modelFor(root); + git(root, "checkout", "-q", "-b", "feat/plain"); + writeFileSync(join(root, "frame.ts"), "export const FRAME = 1;\n"); + commit(root, "feat: add a frame"); + expect(coupledResult(root, model)).toMatchObject({ ok: true, detail: "no coupled paths declared in .orly/orly.json" }); +}); diff --git a/src/criteria.ts b/src/criteria.ts index d69460b3..0186610e 100644 --- a/src/criteria.ts +++ b/src/criteria.ts @@ -4,10 +4,12 @@ import { gitOutput } from "./git_env"; import { scanChangedDocuments } from "./doc_changes"; import { JsonObject, messageOf } from "./model"; import { NOT_INSTALLED, readConfigSync, RepoConfig } from "./config"; -import { classifyBranch, DEFAULT_BRANCHES, SurfaceReport } from "./surfaces"; +import { classifyBranch, couplingGaps, DEFAULT_BRANCHES, defaultMergeBase, SurfaceReport } from "./surfaces"; import { commandSetupErrors } from "./validation"; import { limitsFor } from "./command_limits"; import { runVerification } from "./verification"; +import { hasProof } from "./verification_store"; +import { newTests } from "./proof"; type CommandTier = typeof CONFORM_TIER | typeof FAST_TIER | typeof ALL_TIER; @@ -25,6 +27,8 @@ const GIT_PUSHED = "git.pushed"; const REPO_CONFIG = "repo.config"; const DOCS_UPDATED = "docs.updated"; const DOCS_LANGUAGE = "docs.language"; +const PATHS_COUPLED = "paths.coupled"; +const TESTS_PROVEN = "tests.proven"; // How many findings a report names before it stops listing them. A criterion // line is a summary, not a linter dump. const NAMED_FINDINGS = 3; @@ -52,7 +56,7 @@ export function criteriaFor(gate: string, context: CriterionContext): Criterion[ return [ gitBranch(), gitTree(), gitPushed(), criterion("git.base", (inner) => { report(inner, resolvedConfig(inner)?.surfaces); return { ok: true, detail: "branch diff is available" }; }), - repositoryConfig(), docsLanguage(), docsUpdated(), ...commandCriteria(context, ALL_TIER), + repositoryConfig(), docsLanguage(), docsUpdated(), pathsCoupled(), testsProven(), ...commandCriteria(context, ALL_TIER), ]; } return []; @@ -150,6 +154,33 @@ function docsUpdated(): Criterion { }); } +// A boundary check like docs.updated: a Section in progress may push one side +// before the other, so only the pr gate asks for both. +function pathsCoupled(): Criterion { + return criterion(PATHS_COUPLED, (context) => { + const config = resolvedConfig(context); + if (!config?.coupled) return { ok: true, detail: "no coupled paths declared in .orly/orly.json" }; + const gaps = couplingGaps(config.coupled, report(context, config.surfaces).changed); + if (gaps.length === 0) return { ok: true, detail: `${config.coupled.length} coupled path group(s) changed together or not at all` }; + return { ok: false, detail: `${gaps.join(DETAIL_SEPARATOR)}; change both sides, or record: orly override ${PATHS_COUPLED} --reason ` }; + }); +} + +// Reported, never enforced: a proof lives beneath one worktree's Git metadata, +// so another clone or CI holds none, and private local history may change how +// much work a gate repeats but never its verdict. +function testsProven(): Criterion { + return criterion(TESTS_PROVEN, (context) => { + const changed = report(context, resolvedConfig(context)?.surfaces).changed; + const tests = newTests(context.root, defaultMergeBase(context.root), changed); + if (tests.length === 0) return { ok: true, detail: "no new test declarations on this branch" }; + const unproven = tests.filter(({ file, test }) => !hasProof(context.root, file, test)); + if (unproven.length === 0) return { ok: true, detail: `${tests.length} new test(s), each with a fail-before proof` }; + const named = unproven.slice(0, NAMED_FINDINGS).map(({ file, test }) => `${file} › ${test}`).join(DETAIL_SEPARATOR); + return { ok: true, detail: `reported, not enforced: ${unproven.length} of ${tests.length} new test(s) have no fail-before proof; record one with orly proof: ${named}` }; + }); +} + function docsLanguage(): Criterion { return criterion(DOCS_LANGUAGE, (context) => { try { diff --git a/src/gates.test.ts b/src/gates.test.ts index e1b5601c..ccbe0749 100644 --- a/src/gates.test.ts +++ b/src/gates.test.ts @@ -37,7 +37,7 @@ describe("gate groups", () => { expect(names(runGate(model, project, "work"))).toEqual(["cmd.conform", "repo.config"]); expect(names(runGate(model, project, "verify"))).toEqual(["docs.language", "repo.config"]); expect(names(runGate(model, project, "pr"))).toEqual([ - "cmd.verify.unit", "docs.language", "docs.updated", "git.base", "git.branch", "git.pushed", "git.tree", "repo.config", + "cmd.verify.unit", "docs.language", "docs.updated", "git.base", "git.branch", "git.pushed", "git.tree", "paths.coupled", "repo.config", "tests.proven", ]); }); diff --git a/src/layout.test.ts b/src/layout.test.ts index efb4d9fc..2d241681 100644 --- a/src/layout.test.ts +++ b/src/layout.test.ts @@ -13,9 +13,9 @@ const FRONT_MATTER = /^---\n([\s\S]*?)\n---/; const MAX_DESCRIPTION = 1_024; const RETIRED_PAGE = ".orly/dispatch/write_rust.md"; const RETIRED_BODY = "a page the previous release installed\n"; -// Every path this release deleted. A tracked file that still cites one points -// a reader at nothing. -const RETIRED_REFERENCE = /(? { expect(() => model.validate()).toThrow(); }); + test.each([["", "blank"], [7, "a number"]])("rejects a pack owner that is %j (%s)", async (owner) => { + const source = await RulesModel.load(ROOT); + const registry = structuredClone(source.registry); + const packs = registry.packs; + const persona = isObject(packs) ? packs["persona.indy"] : undefined; + if (!isObject(packs) || !isObject(persona)) throw new Error("persona pack missing"); + packs["persona.indy"] = { ...persona, owner }; + expect(() => new RulesModel(source.root, registry).validate()).toThrow("pack persona.indy owner must be a non-empty string"); + }); + test("rejects missing mechanical rule fixtures", async () => { const source = await RulesModel.load(ROOT); const registry = structuredClone(source.registry); diff --git a/src/model.ts b/src/model.ts index b741ab82..108ee060 100644 --- a/src/model.ts +++ b/src/model.ts @@ -131,6 +131,8 @@ export class RulesModel { return; } if (!Array.isArray(value.extensions)) errors.push(`pack ${name} extensions must be an array`); + // The name `orly note` writes into a spec's Discovery as the owner's. + if (value.owner !== undefined && !(isString(value.owner) && value.owner.trim())) errors.push(`pack ${name} owner must be a non-empty string`); if (!Array.isArray(value.managed_files)) { errors.push(`pack ${name} managed_files must be an array`); return; diff --git a/src/note.integration.test.ts b/src/note.integration.test.ts new file mode 100644 index 00000000..50e72df9 --- /dev/null +++ b/src/note.integration.test.ts @@ -0,0 +1,122 @@ +import { afterEach, expect, test } from "bun:test"; +import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; + +import { CONFIG_PATH } from "./config"; +import { cleanupTemporaryDirectories, newRepository, orly, ROOT, writeFixtureConfig } from "./gates_test_support"; + +const SPEC = "docs/v2/active/M40_001_P2_CLI_FIXTURE_NOTES.md"; +const OTHER = "docs/v2/active/M41_001_P2_CLI_OTHER_NOTES.md"; +const QUOTE = "ship it without the alias"; +const STAMPED = /^- > Owner \(Indy, [A-Z][a-z]{2} \d{2}, \d{4} \d{2}:\d{2}\): "ship it without the alias"/; +const DISCOVERY = [ + "## Discovery (consult log)", + "", + "- **Model reviews** — none yet.", + "", + "```text", + "## not a heading inside a fence", + "```", + "", +].join("\n"); + +afterEach(cleanupTemporaryDirectories); + +// A repository that selects the persona pack naming its owner, with one spec +// whose Discovery holds a fenced heading and is followed by another section. +function noteRepository(packs = ["persona.indy"], specs: Record = { [SPEC]: `# M40_001: Fixture\n\n${DISCOVERY}\n## Appendix\n\nLater text.\n` }): string { + const root = newRepository(); + writeFixtureConfig(root); + const config = JSON.parse(readFileSync(join(root, CONFIG_PATH), "utf8")); + writeFileSync(join(root, CONFIG_PATH), JSON.stringify({ ...config, packs })); + mkdirSync(join(root, "docs/v2/active"), { recursive: true }); + for (const [path, text] of Object.entries(specs)) writeFileSync(join(root, path), text); + return root; +} + +function lines(root: string, path = SPEC): string[] { + return readFileSync(join(root, path), "utf8").split("\n"); +} + +test("a note lands dated at the end of Discovery, before the next section", () => { + const root = noteRepository(); + const result = orly(root, ROOT, "note", QUOTE, "--context", "NLG: no alias beside the renamed flag"); + expect(result.code, result.output).toBe(0); + const written = lines(root); + const at = written.findIndex((line) => STAMPED.test(line)); + expect(written[at]).toEndWith(`"${QUOTE}" — context: NLG: no alias beside the renamed flag`); + expect(written[at - 1]).toBe("```"); + expect(written[at + 2]).toBe("## Appendix"); + expect(result.output).toContain(`noted in ${SPEC} Discovery`); +}); + +test("a second note follows the first, and a note without context ends at the quote", () => { + const root = noteRepository(["persona.indy"], { [SPEC]: `# M40_001: Fixture\n\n${DISCOVERY}` }); + expect(orly(root, ROOT, "note", "first ruling").code).toBe(0); + expect(orly(root, ROOT, "note", QUOTE).code).toBe(0); + const written = lines(root).filter((line) => line.startsWith("- > Owner")); + expect(written).toHaveLength(2); + expect(written[0]).toEndWith(`: "first ruling"`); + expect(written[1]).toMatch(STAMPED); + expect(written[1]).toEndWith(`"${QUOTE}"`); +}); + +test("a --spec path chooses among several active specs, which are otherwise refused", () => { + const root = noteRepository(["persona.indy"], { [SPEC]: `# A\n\n${DISCOVERY}`, [OTHER]: `# B\n\n${DISCOVERY}` }); + const refused = orly(root, ROOT, "note", QUOTE); + expect(refused.code).toBe(1); + expect(refused.output).toContain(`2 specs are active (${SPEC}, ${OTHER}); name one with --spec `); + expect(orly(root, ROOT, "note", QUOTE, "--spec", OTHER).code).toBe(0); + expect(lines(root, OTHER).some((line) => STAMPED.test(line))).toBeTrue(); + expect(lines(root, SPEC).some((line) => STAMPED.test(line))).toBeFalse(); +}); + +test("no active spec is refused", () => { + const root = noteRepository(["persona.indy"], {}); + const result = orly(root, ROOT, "note", QUOTE); + expect(result.code).toBe(1); + expect(result.output).toContain("no spec is active under docs/v*/active/; name one with --spec "); +}); + +test("a spec without a Discovery section is refused and left unchanged", () => { + const text = "# M40_001: Fixture\n\n## Overview\n\n```text\n## Discovery\n```\n"; + const root = noteRepository(["persona.indy"], { [SPEC]: text }); + const result = orly(root, ROOT, "note", QUOTE); + expect(result.code).toBe(1); + expect(result.output).toContain(`${SPEC} has no "## Discovery" section`); + expect(readFileSync(join(root, SPEC), "utf8")).toBe(text); +}); + +test("a repository whose packs name no owner is refused, never given an invented name", () => { + const root = noteRepository([]); + const result = orly(root, ROOT, "note", QUOTE); + expect(result.code).toBe(1); + expect(result.output).toContain("no selected pack names an owner"); + expect(lines(root).some((line) => line.startsWith("- > Owner"))).toBeFalse(); +}); + +test.each([ + [["line one\nline two"], "a note is one non-empty line"], + [[" "], "a note is one non-empty line"], + [[QUOTE, "--context", "two\nlines"], "--context takes one non-empty line"], + [[], "[ORLY-NOTE-001] usage"], + [[QUOTE, "another quote"], "[ORLY-NOTE-001] usage"], + [[QUOTE, "--reason", "wrong flag"], "[ORLY-NOTE-001] usage"], + [[QUOTE, "--spec"], "[ORLY-NOTE-001] usage"], + [[QUOTE, "--spec", "../outside.md"], "../outside.md is outside this repository"], + [[QUOTE, "--spec", "docs/v2/active/missing.md"], "docs/v2/active/missing.md is not a spec file in this repository"], +])("orly note %j is refused", (args, message) => { + const root = noteRepository(); + const before = readFileSync(join(root, SPEC), "utf8"); + const result = orly(root, ROOT, "note", ...args); + expect(result.code).toBe(1); + expect(result.output).toContain(message); + expect(readFileSync(join(root, SPEC), "utf8")).toBe(before); +}); + +test("a spec written with CRLF line endings keeps them", () => { + const root = noteRepository(["persona.indy"], { [SPEC]: `# M40_001: Fixture\r\n\r\n## Discovery\r\n\r\n- none\r\n` }); + expect(orly(root, ROOT, "note", QUOTE).code).toBe(0); + const text = readFileSync(join(root, SPEC), "utf8"); + expect(text).toMatch(/- none\r\n- > Owner \(Indy, [^)]+\): "ship it without the alias"\r\n$/); +}); diff --git a/src/note.ts b/src/note.ts new file mode 100644 index 00000000..cea28c50 --- /dev/null +++ b/src/note.ts @@ -0,0 +1,79 @@ +import type { RulesModel } from "./model"; + +import { lstatSync, readFileSync } from "node:fs"; +import { join } from "node:path"; + +import { CONFIG_PATH, readConfigSync } from "./config"; +import { isObject, isString, OrlyError } from "./model"; + +type NoteRequest = { quote: string; context?: string; spec?: string; now: Date }; + +const ACTIVE_SPECS = "docs/v*/active/*.md"; +const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; +const DISCOVERY = /^#{2}[ \t]+Discovery\b/; +const HEADING = /^[ \t]{0,3}(#{1,6})[ \t]/; +const FENCE = /^[ \t]*(`{3,}|~{3,})/; +const LINE_BREAK = /[\r\n]/; + +// Append the owner's verbatim words to the Discovery section of the active +// spec, in the form the spec standard asks a deferral to carry. +export async function appendNote(model: RulesModel, root: string, request: NoteRequest): Promise<{ spec: string; line: string }> { + const quote = request.quote.trim(); + if (!quote || LINE_BREAK.test(quote)) throw new OrlyError("a note is one non-empty line: the owner's words, verbatim"); + if (request.context !== undefined && (!request.context.trim() || LINE_BREAK.test(request.context))) throw new OrlyError("--context takes one non-empty line"); + const owner = ownerOf(model, root); + const spec = request.spec ?? activeSpec(root); + const path = join(root, spec); + if (!lstatSync(path, { throwIfNoEntry: false })?.isFile()) throw new OrlyError(`${spec} is not a spec file in this repository`); + const text = readFileSync(path, "utf8"); + const newline = text.includes("\r\n") ? "\r\n" : "\n"; + const lines = text.split(/\r?\n/); + const at = insertionPoint(lines); + if (at === undefined) throw new OrlyError(`${spec} has no "## Discovery" section; add the template's Discovery section first`); + const line = `- > Owner (${owner}, ${stamp(request.now)}): "${quote}"${request.context ? ` — context: ${request.context.trim()}` : ""}`; + lines.splice(at, 0, line); + await Bun.write(path, lines.join(newline)); + return { spec, line }; +} + +// The owner is named by a persona pack the repository selects, never guessed. +function ownerOf(model: RulesModel, root: string): string { + const packs = readConfigSync(root)?.packs ?? []; + for (const pack of packs) { + const entry = model.packs[pack]; + if (isObject(entry) && isString(entry.owner)) return entry.owner; + } + throw new OrlyError(`no selected pack names an owner; add a persona pack that names one to packs in ${CONFIG_PATH}`); +} + +function activeSpec(root: string): string { + const specs = [...new Bun.Glob(ACTIVE_SPECS).scanSync({ cwd: root, onlyFiles: true })].sort(); + if (specs.length === 1 && specs[0]) return specs[0]; + if (specs.length === 0) throw new OrlyError("no spec is active under docs/v*/active/; name one with --spec "); + throw new OrlyError(`${specs.length} specs are active (${specs.join(", ")}); name one with --spec `); +} + +// After the last non-blank line of Discovery, which ends at the next heading +// of its level or above; a heading inside a code fence ends nothing. +function insertionPoint(lines: string[]): number | undefined { + let fence = ""; + let start: number | undefined; + let last: number | undefined; + for (const [index, line] of lines.entries()) { + const marker = FENCE.exec(line)?.[1] ?? ""; + if (fence) { + if (marker.startsWith(fence)) fence = ""; + } else if (marker) fence = marker; + else if (start === undefined) { + if (DISCOVERY.test(line)) start = last = index; + continue; + } else if ((HEADING.exec(line)?.[1]?.length ?? 7) <= 2) break; + if (start !== undefined && line.trim()) last = index; + } + return last === undefined ? undefined : last + 1; +} + +function stamp(now: Date): string { + const pad = (value: number) => String(value).padStart(2, "0"); + return `${MONTHS[now.getMonth()]} ${pad(now.getDate())}, ${now.getFullYear()} ${pad(now.getHours())}:${pad(now.getMinutes())}`; +} diff --git a/src/proof.integration.test.ts b/src/proof.integration.test.ts new file mode 100644 index 00000000..1ac68b50 --- /dev/null +++ b/src/proof.integration.test.ts @@ -0,0 +1,176 @@ +import { afterEach, expect, test } from "bun:test"; +import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; + +import { runGate } from "./gates"; +import { cleanupTemporaryDirectories, git, gitOutput, modelFor, newRepository, orly, ROOT } from "./gates_test_support"; +import { newTests } from "./proof"; +import { verificationState } from "./verification_store"; + +const SOURCE = "src/age.ts"; +const TESTS = "src/age.test.ts"; +const SORTS = "sorts the oldest first"; +const REFUSES = "refuses a failed age"; +const CORRECT = "export const oldestFirst = (ages: number[]) => [...ages].sort((a, b) => b - a);\nexport const valid = (age: number) => age >= 0;\n"; +const RUN_TESTS = ["--", process.execPath, "test", TESTS]; + +afterEach(cleanupTemporaryDirectories); + +// A branch adding a module and two tests of it; `ages` are distinct, so only +// the comparator decides the order the first test claims. +async function proofRepository() { + const root = newRepository(); + const model = await modelFor(root); + git(root, "checkout", "-q", "-b", "feat/ages"); + mkdirSync(join(root, "src")); + writeFileSync(join(root, SOURCE), CORRECT); + writeFileSync(join(root, TESTS), [ + `import { expect, test } from "bun:test";`, + `import { oldestFirst, valid } from "./age";`, + `test("${SORTS}", () => { expect(oldestFirst([3, 9, 5])).toEqual([9, 5, 3]); });`, + `test("${REFUSES}", () => { expect(valid(-1)).toBe(false); });`, + "", + ].join("\n")); + git(root, "add", "."); + git(root, "commit", "-q", "-m", "feat: order ages"); + return { root, model }; +} + +function proofRecords(root: string) { + const directory = join(verificationState(root), "proofs"); + return existsSync(directory) ? readdirSync(directory).map((name) => JSON.parse(readFileSync(join(directory, name), "utf8")).payload) : []; +} + +function proven(root: string, model: Awaited>) { + return runGate(model, root, "pr").results.find((result) => result.name === "tests.proven"); +} + +test("a test that fails with its change reverted is recorded, and the pr gate counts it", async () => { + const { root, model } = await proofRepository(); + writeFileSync(join(root, SOURCE), CORRECT.replace("b - a", "a - b")); + const result = orly(root, ROOT, "proof", TESTS, "--test", SORTS, ...RUN_TESTS); + expect(result.code, result.output).toBe(0); + expect(result.output).toContain(`fail-before proof recorded for ${TESTS} › ${SORTS}`); + expect(result.output).toContain(`(fail) ${SORTS}`); + const [record] = proofRecords(root); + expect(record).toMatchObject({ format: 1, file: TESTS, test: SORTS, command: [process.execPath, "test", TESTS] }); + expect(record.mutation).toContain("+export const oldestFirst = (ages: number[]) => [...ages].sort((a, b) => a - b);"); + expect(record.failing_line).toStartWith(`(fail) ${SORTS}`); + writeFileSync(join(root, SOURCE), CORRECT); + expect(proven(root, model)?.detail).toBe(`reported, not enforced: 1 of 2 new test(s) have no fail-before proof; record one with orly proof: ${TESTS} › ${REFUSES}`); +}); + +test("a test that passes with its change reverted is refused and records nothing", async () => { + const { root } = await proofRepository(); + const result = orly(root, ROOT, "proof", TESTS, "--test", SORTS, ...RUN_TESTS); + expect(result.code).toBe(1); + expect(result.output).toContain("orly: the command passed, so the test did not fail"); + expect(proofRecords(root)).toEqual([]); +}); + +// A verbose runner, as cargo is, prints a line for the passing test too. Its +// name holds the word "failed", so that line must not pass for the failing one. +test("a failure of another test is refused, even when the name says failed", async () => { + const { root } = await proofRepository(); + const verbose = `console.log("test ${REFUSES} ... ok"); console.log("test ${SORTS} ... FAILED"); process.exit(1);`; + const result = orly(root, ROOT, "proof", TESTS, "--test", REFUSES, "--", process.execPath, "-e", verbose); + expect(result.code).toBe(1); + expect(result.output).toContain(`no output line reports "${REFUSES}" failing; a build error or another test failed instead`); + expect(proofRecords(root)).toEqual([]); +}); + +test("a build error is refused, because no line reports the test failing", async () => { + const { root } = await proofRepository(); + writeFileSync(join(root, SOURCE), "export const oldestFirst = (;\n"); + const result = orly(root, ROOT, "proof", TESTS, "--test", SORTS, ...RUN_TESTS); + expect(result.code).toBe(1); + expect(result.output).toContain(`no output line reports "${SORTS}" failing`); +}); + +test.each([ + [[TESTS, "--test", "no such test", ...RUN_TESTS], `${TESTS} declares no test named "no such test"`], + [["README.md", "--test", SORTS, ...RUN_TESTS], "README.md is not a test file orly reads; it reads tests in TypeScript and JavaScript, Rust, Go, Python"], + [["../elsewhere.test.ts", "--test", SORTS, ...RUN_TESTS], "../elsewhere.test.ts is outside this repository"], + [[TESTS, "--test", SORTS], "[ORLY-PROOF-001] usage"], + [[TESTS, ...RUN_TESTS], "[ORLY-PROOF-001] usage"], + [[TESTS, SOURCE, "--test", SORTS, ...RUN_TESTS], "[ORLY-PROOF-001] usage"], + [[TESTS, "--test", SORTS, "--test", REFUSES, ...RUN_TESTS], "[ORLY-PROOF-001] usage"], + [[TESTS, "--name", SORTS, ...RUN_TESTS], "[ORLY-PROOF-001] usage"], +])("orly proof %j is refused", async (args, message) => { + const { root } = await proofRepository(); + const result = orly(root, ROOT, "proof", ...args); + expect(result.code).toBe(1); + expect(result.output).toContain(message); + expect(proofRecords(root)).toEqual([]); +}); + +test("an altered proof record proves nothing", async () => { + const { root, model } = await proofRepository(); + writeFileSync(join(root, SOURCE), CORRECT.replace("b - a", "a - b")); + expect(orly(root, ROOT, "proof", TESTS, "--test", SORTS, ...RUN_TESTS).code).toBe(0); + writeFileSync(join(root, SOURCE), CORRECT); + const directory = join(verificationState(root), "proofs"); + const [name] = readdirSync(directory); + const path = join(directory, name ?? ""); + const record = JSON.parse(readFileSync(path, "utf8")); + // The name and file still match, so only the signature can refuse it. + record.payload.failing_line = "forged"; + writeFileSync(path, JSON.stringify(record)); + expect(proven(root, model)?.detail).toStartWith("reported, not enforced: 2 of 2 new test(s)"); +}); + +test("the pr gate reports unproven tests and still passes", async () => { + const { root, model } = await proofRepository(); + expect(proven(root, model)).toMatchObject({ ok: true, status: "passed" }); + expect(proven(root, model)?.detail).toBe(`reported, not enforced: 2 of 2 new test(s) have no fail-before proof; record one with orly proof: ${TESTS} › ${SORTS}; ${TESTS} › ${REFUSES}`); + expect(existsSync(join(root, ".git/orly-verification"))).toBeFalse(); +}); + +test("a branch with no new test declarations says so", async () => { + const root = newRepository(); + const model = await modelFor(root); + git(root, "checkout", "-q", "-b", "feat/docs"); + writeFileSync(join(root, "README.md"), "More words.\n"); + git(root, "commit", "-q", "-am", "docs: more words"); + expect(proven(root, model)?.detail).toBe("no new test declarations on this branch"); +}); + +// Declarations are read from the lines a branch adds, per language; a changed +// body under an unchanged declaration, and a test-shaped call outside a test +// file, are not new tests. +test("new tests are read from added declarations in each supported language", async () => { + const root = newRepository(); + const files: Record = { + "src/lib.rs": "pub fn helper() {}\n", + "src/kept.test.ts": `test("kept", () => {\n expect(1).toBe(1);\n});\n`, + }; + for (const [path, text] of Object.entries(files)) { + mkdirSync(join(root, "src"), { recursive: true }); + writeFileSync(join(root, path), text); + } + git(root, "add", "."); + git(root, "commit", "-q", "-m", "test: base"); + const added: Record = { + "src/lib.rs": "pub fn helper() {}\n#[cfg(test)]\nmod tests {\n #[tokio::test]\n #[ignore = \"needs a database\"]\n async fn stores_one_row() {}\n fn not_a_test() {}\n}\n", + "src/kept.test.ts": `test("kept", () => {\n expect(2).toBe(2);\n});\ntest.each([\n [1, 2],\n])("adds %d to %d", (a, b) => { expect(a + b).toBe(3); });\ntest.each([1, 2])("doubles %d", (n) => { expect(n * 2).toBeGreaterThan(n); });\nit.skip('waits', () => {});\n`, + "pkg/store_test.go": "package pkg\nfunc TestStoresOneRow(t *testing.T) {}\nfunc helper() {}\n", + "tests/test_store.py": "def test_stores_one_row():\n pass\nasync def test_reads_back():\n pass\n", + "src/runner.ts": `test("not in a test file", () => {});\n`, + }; + for (const [path, text] of Object.entries(added)) { + mkdirSync(join(root, path, ".."), { recursive: true }); + writeFileSync(join(root, path), text); + } + git(root, "add", "."); + git(root, "commit", "-q", "-m", "test: add declarations"); + const base = gitOutput(root, "rev-parse", "HEAD^"); + expect(newTests(root, base, Object.keys(added).sort())).toEqual([ + { file: "pkg/store_test.go", test: "TestStoresOneRow" }, + { file: "src/kept.test.ts", test: "adds %d to %d" }, + { file: "src/kept.test.ts", test: "doubles %d" }, + { file: "src/kept.test.ts", test: "waits" }, + { file: "src/lib.rs", test: "stores_one_row" }, + { file: "tests/test_store.py", test: "test_stores_one_row" }, + { file: "tests/test_store.py", test: "test_reads_back" }, + ]); +}); diff --git a/src/proof.ts b/src/proof.ts new file mode 100644 index 00000000..4dcb70b2 --- /dev/null +++ b/src/proof.ts @@ -0,0 +1,110 @@ +import { lstatSync, readFileSync } from "node:fs"; +import { join } from "node:path"; + +import { runCommand } from "./command_runner"; +import { gitOutput } from "./git_env"; +import { OrlyError } from "./model"; +import { saveProof, type Proof } from "./verification_store"; + +type Language = { name: string; file: RegExp; declarations: (lines: string[]) => string[] }; +type DeclaredTest = { file: string; test: string }; + +const UTF8 = "utf8"; +const NEWLINE = /\r?\n/; +const TEST_PATH = /(^|\/)tests?\/|\.test\.|_test\.|\.spec\./; +// `test("name")`, `it.each([…])("name")` and their modifiers, on one line, +// or the `])("name"` line that closes a table spread over several lines. +const SCRIPT_TEST = /^\s*(?:(?:test|it)(?:\.\w+(?:\([^()]*\))?)*|\]\))\(\s*(["'`])((?:\\.|(?!\1).)*)\1/; +const RUST_TEST_ATTRIBUTE = /^\s*#\[(?:[\w:]+::)?test\b/; +const RUST_FUNCTION = /^\s*(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?fn\s+(\w+)/; +const GO_TEST = /^func\s+(Test\w*)\s*\(/; +const PYTHON_TEST = /^\s*(?:async\s+)?def\s+(test\w*)\s*\(/; +// The verdict word a runner prints beside a failing test's name: bun's +// `(fail)`, cargo's `FAILED`, go's `--- FAIL:`, pytest's `FAILED`, or a cross. +// Runners print the verdict after the assertion detail, so the last line wins. +const FAIL_MARK = /\bfail(?:ed|ure|s)?\b|✗|✕|×/i; +// A parameterised name prints with its placeholders filled, so only the text +// before the first placeholder is looked for. +const PLACEHOLDER = /%|\$/; +// The languages whose test declarations orly reads, each from its test files. +const LANGUAGES: Language[] = [ + { name: "TypeScript and JavaScript", file: /\.(?:ts|tsx|js|jsx|mjs|cjs)$/, declarations: (lines) => matches(lines, SCRIPT_TEST, 2) }, + { name: "Rust", file: /\.rs$/, declarations: rustTests }, + { name: "Go", file: /_test\.go$/, declarations: (lines) => matches(lines, GO_TEST, 1) }, + { name: "Python", file: /\.py$/, declarations: (lines) => matches(lines, PYTHON_TEST, 1) }, +]; + +// Run the command with the covered change reverted or mutated, and record what +// orly saw only when it failed and a failing output line names the test. +export function recordProof(root: string, file: string, test: string, command: string[]): Proof { + const declared = declaredIn(root, file); + if (!declared.includes(test)) throw new OrlyError(`${file} declares no test named "${test}"; name it exactly as its declaration does`); + const prefix = test.split(PLACEHOLDER)[0]?.trim() ?? ""; + if (!prefix) throw new OrlyError(`"${test}" starts with a placeholder, so no output line can be matched to it`); + const result = runCommand(root, command); + if (result.status === "passed") throw new OrlyError("the command passed, so the test did not fail; revert or mutate the code it covers, then rerun orly proof"); + if (result.status !== "failed") throw new OrlyError(`the command reached no verdict (${result.status}): ${result.detail.split(NEWLINE)[0] ?? ""}`); + const failing = result.detail.split(NEWLINE).filter((line) => line.includes(prefix) && FAIL_MARK.test(line.replace(prefix, ""))).at(-1); + if (failing === undefined) throw new OrlyError(`the command failed, but no output line reports "${prefix}" failing; a build error or another test failed instead`); + const proof = { file, test, command, failing_line: failing.trim(), mutation: mutation(root), revision: gitOutput(root, ["rev-parse", "HEAD"]), recorded_at: Date.now() }; + saveProof(root, proof); + return proof; +} + +// The tests a branch declares anew or renames, read from the lines it adds. +// A changed body under an unchanged declaration is not seen. +export function newTests(root: string, base: string, changed: string[]): DeclaredTest[] { + return changed.filter((file) => languageOf(file) !== undefined).flatMap((file) => { + const patch = gitOutput(root, ["diff", "--no-ext-diff", "--no-color", "--unified=0", `${base}..HEAD`, "--", file], true); + const added = patch.split(NEWLINE).filter((line) => line.startsWith("+") && !line.startsWith("+++")).map((line) => line.slice(1)); + return [...new Set(languageOf(file)?.declarations(added))].map((test) => ({ file, test })); + }); +} + +function supportedLanguages(): string { + return LANGUAGES.map((language) => language.name).join(", "); +} + +function declaredIn(root: string, file: string): string[] { + const language = languageOf(file); + if (!language) throw new OrlyError(`${file} is not a test file orly reads; it reads tests in ${supportedLanguages()}`); + const path = join(root, file); + if (!lstatSync(path, { throwIfNoEntry: false })?.isFile()) throw new OrlyError(`${file} is not a file in this repository`); + return language.declarations(readFileSync(path, UTF8).split(NEWLINE)); +} + +function languageOf(file: string): Language | undefined { + const language = LANGUAGES.find((candidate) => candidate.file.test(file)); + // Rust keeps unit tests beside the code, so any Rust file may declare one. + if (!language || (language.name !== "Rust" && !TEST_PATH.test(file) && !/(^|\/)test_[^/]*\.py$/.test(file))) return undefined; + return language; +} + +function matches(lines: string[], pattern: RegExp, group: number): string[] { + return lines.flatMap((line) => { + const name = pattern.exec(line)?.[group]; + return name ? [name] : []; + }); +} + +// A Rust test is the function after a `#[test]`-style attribute; other +// attributes, such as `#[ignore]`, may sit between them. +function rustTests(lines: string[]): string[] { + const names: string[] = []; + let pending = false; + for (const line of lines) { + if (RUST_TEST_ATTRIBUTE.test(line)) pending = true; + const name = RUST_FUNCTION.exec(line)?.[1]; + if (name === undefined) continue; + if (pending) names.push(name); + pending = false; + } + return names; +} + +// The code the run saw, as a diff from HEAD of every changed path that is not +// a test: the reverted hunk or the mutation, or nothing when HEAD's code ran. +function mutation(root: string): string { + const paths = gitOutput(root, ["diff", "--name-only", "-z", "HEAD"], true).split("\0").filter((path) => path && !TEST_PATH.test(path)); + return paths.length === 0 ? "" : gitOutput(root, ["diff", "--no-ext-diff", "--no-color", "HEAD", "--", ...paths], true); +} diff --git a/src/surfaces.ts b/src/surfaces.ts index e4be24a7..1f5fd29a 100644 --- a/src/surfaces.ts +++ b/src/surfaces.ts @@ -1,3 +1,4 @@ +import type { Coupling } from "./config_validation"; import type { JsonObject } from "./model"; import { isObject, OrlyError, stringArray } from "./model"; @@ -57,6 +58,16 @@ export function isDocs(path: string, prefixes: string[]): boolean { return prefixes.some((prefix) => path.startsWith(prefix)); } +// One sentence per coupling the branch breaks: a path under a `when` prefix +// changed while no path under its `then` prefixes did. +export function couplingGaps(couplings: Coupling[], changed: string[]): string[] { + return couplings.flatMap(({ when, then }) => { + const trigger = changed.find((path) => when.some((prefix) => path.startsWith(prefix))); + if (trigger === undefined || changed.some((path) => then.some((prefix) => path.startsWith(prefix)))) return []; + return [`${trigger} changed under ${when.join(", ")}, but nothing under ${then.join(", ")} did`]; + }); +} + function branchDiff(root: string): string[] { const base = defaultMergeBase(root); if (!base) throw new OrlyError("comparison base is unavailable; fetch the target branch and its history before verification"); diff --git a/src/verification-scoped.integration.test.ts b/src/verification-scoped.integration.test.ts index bbedbe4b..64514f94 100644 --- a/src/verification-scoped.integration.test.ts +++ b/src/verification-scoped.integration.test.ts @@ -25,7 +25,7 @@ test("documentation commits reuse a scoped lane through the CLI", async () => { expect(reused.output).toContain(`from ${originalRevision} for ${acceptedRevision}`); expect(reused.output).toContain("fixture report: 7 checks passed"); expect(verificationCount(root)).toBe(1); - expect(completion(root)).toMatchObject({ format: 1, executed_revision: originalRevision, accepted_revision: acceptedRevision, executed_at: original.executed_at, origin: original.origin, scope: original.scope }); + expect(completion(root)).toMatchObject({ format: 2, executed_revision: originalRevision, executed_uncommitted: false, accepted_revision: acceptedRevision, executed_at: original.executed_at, origin: original.origin, scope: original.scope }); writeFileSync(join(root, "tracked-input.txt"), "changed input"); commit(root); const changed = orly(root, ROOT, "gate", "pr", "--reuse-verification"); diff --git a/src/verification.integration.test.ts b/src/verification.integration.test.ts index 93c6eba9..d8c72ebc 100644 --- a/src/verification.integration.test.ts +++ b/src/verification.integration.test.ts @@ -3,7 +3,7 @@ import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, symlinkSync, wr import { join } from "node:path"; import { contentDigest } from "./config"; -import { cleanupTemporaryDirectories, git, orly, ROOT } from "./gates_test_support"; +import { cleanupTemporaryDirectories, git, gitOutput, orly, ROOT } from "./gates_test_support"; import { UNSCOPED_ENVIRONMENT } from "./git_env"; import { recordOverride, runGate } from "./gates"; import { RulesModel } from "./model"; @@ -128,10 +128,41 @@ test("tracked symlinks disable reuse while preserving fresh execution", async () } }); -test("clean accept-dirty checks cannot publish reusable evidence", async () => { +test("a run on an uncommitted tree is reused once that tree is committed and pushed", async () => { const { root } = await verificationFixture(); + writeFileSync(join(root, "tracked-input.txt"), "edited before the commit"); + const dirty = orly(root, ROOT, "gate", "pr", "--accept-dirty"); + expect(dirty.code, dirty.output).toBe(0); + expect(dirty.output).toContain("evidence keyed to this tree, reusable once it is committed and pushed"); + const parent = gitOutput(root, "rev-parse", "HEAD"); + commitAndPush(root); + const reused = orly(root, ROOT, "gate", "pr", "--reuse-verification"); + expect(reused.code, reused.output).toBe(0); + expect(reused.output).toContain(`from ${parent} with uncommitted changes for ${gitOutput(root, "rev-parse", "HEAD")}`); + expect(reused.output).toContain("fixture report: 7 checks passed"); + expect(verificationCount(root)).toBe(1); +}); + +test("an uncommitted run never vouches for a different committed tree", async () => { + const { root } = await verificationFixture(); + writeFileSync(join(root, "tracked-input.txt"), "edited before the commit"); expect(orly(root, ROOT, "gate", "pr", "--accept-dirty").code).toBe(0); - expect(JSON.parse(readFileSync(join(attemptPaths(root)[0]!, "complete.json"), "utf8")).payload.binding).toBeNull(); + writeFileSync(join(root, "README.md"), "edited after the run\n"); + commitAndPush(root); + const next = orly(root, ROOT, "gate", "pr", "--reuse-verification"); + expect(next.code, next.output).toBe(0); + expect(next.output).toContain("fresh run"); + expect(verificationCount(root)).toBe(2); +}); + +test("an untracked file present during a run keeps it from being reused", async () => { + const { root } = await verificationFixture(); + writeFileSync(join(root, "tracked-input.txt"), "edited before the commit"); + writeFileSync(join(root, "scratch.txt"), "a file the command may have read"); + const dirty = orly(root, ROOT, "gate", "pr", "--accept-dirty"); + expect(dirty.output).toContain("reuse unavailable: untracked files are outside the tree; add or remove them"); + rmSync(join(root, "scratch.txt")); + commitAndPush(root); const next = orly(root, ROOT, "gate", "pr", "--reuse-verification"); expect(next.code, next.output).toBe(0); expect(next.output).toContain("fresh run"); @@ -273,3 +304,9 @@ test("interrupted_and_concurrent_attempts_never_select_an_old_pass", async () => if (child && processAlive(child)) process.kill(-child, "SIGKILL"); } }, 20000); + +function commitAndPush(root: string): void { + git(root, "add", "."); + git(root, "commit", "-q", "-m", "test: commit the verified tree"); + git(root, "push", "-q"); +} diff --git a/src/verification.ts b/src/verification.ts index 40d6fc0b..0b489553 100644 --- a/src/verification.ts +++ b/src/verification.ts @@ -32,7 +32,7 @@ export function runVerification(context: CriterionContext, config: RepoConfig, l function execute(context: CriterionContext, request: IdentityRequest, attempt: Attempt, lock: VerificationLock): Verdict { const before = verificationIdentity(request); let reused: VerifiedPass | undefined; - if (!context.acceptDirty && context.reuseVerification && "binding" in before) reused = previousPass(attempt, before.binding, request.policy.max_age_ms); + if (!context.acceptDirty && context.reuseVerification && "binding" in before && before.current) reused = previousPass(attempt, before.binding, request.policy.max_age_ms); let result = reused ? { ok: true, status: "passed" as const, detail: reused.detail } : runCommandGroup(request.root, request.invocations, request.limits); const after = verificationIdentity(request, "after-probes"); const unchanged = before.source === after.source && "binding" in before && "binding" in after && before.binding === after.binding; @@ -40,12 +40,12 @@ function execute(context: CriterionContext, request: IdentityRequest, attempt: A reused = undefined; result = { ok: false, status: "blocked", detail: `verification inputs changed during the attempt; result is not current-revision proof\n${result.detail}` }; } - try { completeAttempt(attempt, !context.acceptDirty && unchanged ? before : undefined, result, reused); } + try { completeAttempt(attempt, unchanged ? before : undefined, result, reused); } catch (error) { lock.abandon(); return { ...result, detail: `${result.detail}\ncompletion could not be saved; reuse disabled: ${String(error)}` }; } - const provenance = reused && "binding" in before ? `reused run ${reused.origin} from ${reused.revision} for ${before.revision}` : "fresh run"; - const eligibility = "reason" in before ? `; reuse unavailable: ${before.reason}` : ""; + const provenance = reused && "binding" in before ? `reused run ${reused.origin} from ${reused.revision}${reused.uncommitted ? " with uncommitted changes" : ""} for ${before.revision}` : "fresh run"; + const eligibility = "reason" in before ? `; reuse unavailable: ${before.reason}` : before.current ? "" : "; evidence keyed to this tree, reusable once it is committed and pushed"; return { ...result, detail: `${provenance}${eligibility}; evidence: ${attempt.path}\n${result.detail}` }; } diff --git a/src/verification_identity.integration.test.ts b/src/verification_identity.integration.test.ts index bc4a2d9d..a6a4caf2 100644 --- a/src/verification_identity.integration.test.ts +++ b/src/verification_identity.integration.test.ts @@ -1,7 +1,7 @@ import { afterEach, expect, spyOn, test } from "bun:test"; import * as fs from "node:fs"; import { randomBytes, randomUUID } from "node:crypto"; -import { chmodSync, cpSync, mkdirSync, realpathSync, symlinkSync, writeFileSync } from "node:fs"; +import { chmodSync, cpSync, mkdirSync, realpathSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { limitsFor } from "./command_limits"; @@ -74,13 +74,42 @@ test("declared ignored bytes are bound and missing or symlink inputs disable reu expect(verificationIdentity(request)).toHaveProperty("reason"); }); -test("dirty and unpushed inputs do not produce reusable identity", async () => { +test("an uncommitted tree binds the same evidence as the commit that records it", async () => { const request = await requestFixture(); writeFileSync(join(request.root, "tracked-input.txt"), "changed"); - expect(verificationIdentity(request)).toHaveProperty("reason"); + const uncommitted = verificationIdentity(request); + expect(uncommitted).toMatchObject({ uncommitted: true, current: false }); git(request.root, "add", "."); git(request.root, "commit", "-q", "-m", "test: unpushed input"); - expect(verificationIdentity(request)).toHaveProperty("reason"); + const unpushed = verificationIdentity(request); + expect(unpushed).toMatchObject({ uncommitted: false, current: false }); + git(request.root, "push", "-q"); + const pushed = verificationIdentity(request); + expect(pushed).toMatchObject({ uncommitted: false, current: true }); + expect("binding" in pushed && pushed.binding).toBe("binding" in uncommitted && uncommitted.binding); + expect("binding" in unpushed && unpushed.binding).toBe("binding" in uncommitted && uncommitted.binding); +}); + +test("a different tree binds different evidence", async () => { + const request = await requestFixture(); + writeFileSync(join(request.root, "tracked-input.txt"), "changed"); + const first = binding(request); + writeFileSync(join(request.root, "README.md"), "another tracked edit\n"); + expect(binding(request)).not.toBe(first); +}); + +test("untracked files leave the tree unbound", async () => { + const request = await requestFixture(); + writeFileSync(join(request.root, "scratch.ts"), "export const unstaged = 1;\n"); + expect(verificationIdentity(request)).toMatchObject({ reason: "untracked files are outside the tree; add or remove them" }); +}); + +test("a tracked file deleted from the working tree binds as the commit that deletes it", async () => { + const request = await requestFixture(); + unlinkSync(join(request.root, "README.md")); + const deleted = binding(request); + git(request.root, "commit", "-q", "-am", "test: delete a tracked file"); + expect(binding(request)).toBe(deleted); }); test("engine sources and executable bytes invalidate matching version output", async () => { diff --git a/src/verification_identity.ts b/src/verification_identity.ts index db4bfbb1..3104c465 100644 --- a/src/verification_identity.ts +++ b/src/verification_identity.ts @@ -8,13 +8,15 @@ import { release } from "node:os"; import { runCommand } from "./command_runner"; import { contentDigest } from "./config"; -import { git, UNSCOPED_ENVIRONMENT } from "./git_env"; +import { git, gitOutput, UNSCOPED_ENVIRONMENT } from "./git_env"; import { defaultMergeBase } from "./surfaces"; -import { objectValue, stringArray } from "./model"; +import { hasErrorCode, objectValue, stringArray } from "./model"; type InputEntry = { path: string; directory: true } | { path: string; mode: number; bytes: string } | { path: string; mode: number; link: string }; -export type VerificationProof = { binding: string; revision: string; scope: string | null }; +// `current` marks an observation that may accept earlier evidence: a clean +// tree at the pushed revision. Any tree without untracked files may record it. +export type VerificationProof = { binding: string; revision: string; scope: string | null; uncommitted: boolean; current: boolean }; type VerificationIdentity = { source: string } & (VerificationProof | { reason: string }); export type IdentityRequest = { root: string; engineRoot: string; config: RepoConfig; lane: string; policy: ReusePolicy; @@ -24,6 +26,7 @@ export type IdentityRequest = { const PROBE_LIMITS = { timeout_ms: 10_000, output_bytes: 64 * 1024 }; const HASH_CHUNK_BYTES = 64 * 1024; const MANIFEST_BYTES = 1024 * 1024; +const UNTRACKED = "?? "; export function verificationIdentity(request: IdentityRequest, observation: "before-probes" | "after-probes" = "before-probes"): VerificationIdentity { // Bracket all executed probes with the two source snapshots, without hashing @@ -32,27 +35,31 @@ export function verificationIdentity(request: IdentityRequest, observation: "bef const root = realpathSync(request.root); const revision = gitInput(root, ["rev-parse", "HEAD"]).trim(); const base = defaultMergeBase(root); - const dirty = gitInput(root, ["status", "--porcelain=v1", "-uall"]); + const dirty = gitInput(root, ["status", "--porcelain=v1", "-z", "--no-renames", "-uall"]); const files = inputIdentity(root, trackedPaths(root), true); const source = contentDigest(JSON.stringify({ revision, base, dirty, files })); try { if (files.some((entry) => "link" in entry)) return { source, reason: "symlink inputs require fresh execution" }; - const upstream = gitInput(root, ["rev-parse", "@{upstream}"]).trim(); - if (!revision || revision !== upstream || dirty) return { source, reason: "reuse requires a clean, pushed worktree" }; - if (!base) return { source, reason: "reuse requires an exact merge base" }; + // A command may read an untracked file that the committed tree will lack. + if (dirty.split("\0").some((entry) => entry.startsWith(UNTRACKED))) return { source, reason: "untracked files are outside the tree; add or remove them" }; + if (!revision || !base) return { source, reason: "reuse requires an exact merge base" }; const toolchain = observation === "after-probes" ? finalToolchain : probeToolchain(request); if (!toolchain) return { source, reason: "toolchain identity is unavailable" }; + // The tree is the tracked content the command reads, never the commit that + // holds it, so a run on uncommitted edits matches the commit that records them. const scope = request.policy.tracked_inputs ? scopedDigest(files, request.policy.tracked_inputs) : null; + const tree = scope ?? contentDigest(JSON.stringify(files)); const environment = Object.entries(UNSCOPED_ENVIRONMENT).filter(([, value]) => value !== undefined).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0); const identity = { - root, source: scope === null ? source : { base, scope }, + root, source: { base, tree }, lane: request.lane, invocations: request.invocations, limits: request.limits, config: request.config, environment: new Bun.CryptoHasher("sha256", request.key).update(JSON.stringify(environment)).digest("hex"), engine: { root: realpathSync(request.engineRoot), inputs: inputIdentity(realpathSync(request.engineRoot), enginePaths(request.engineRoot)) }, runtime: { versions: process.versions, platform: process.platform, arch: process.arch, release: release() }, inputs: inputIdentity(root, request.policy.inputs), toolchain, }; - return { source, binding: contentDigest(JSON.stringify(identity)), revision, scope }; + const current = !dirty && revision === gitOutput(root, ["rev-parse", "@{upstream}"]); + return { source, binding: contentDigest(JSON.stringify(identity)), revision, scope, uncommitted: dirty !== "", current }; } catch { return { source, reason: "verification inputs are missing, unsupported or unreadable" }; } @@ -98,8 +105,15 @@ function inputIdentity(root: string, paths: string[], allowLinks = false): Input return [...entries.values()]; } +// A tracked path deleted from the working tree is absent from the tree a commit +// of that working tree records, so it is left out rather than refused. function trackedPaths(root: string): string[] { - return gitInput(root, ["ls-files", "--cached", "-z"]).split("\0").filter(Boolean); + return gitInput(root, ["ls-files", "--cached", "-z"]).split("\0").filter((path) => path && present(join(root, path))); +} + +function present(path: string): boolean { + try { return lstatSync(path, { throwIfNoEntry: false }) !== undefined; } + catch (error) { if (hasErrorCode(error, "ENOTDIR")) return false; throw error; } } function gitInput(root: string, args: string[]): string { diff --git a/src/verification_store.integration.test.ts b/src/verification_store.integration.test.ts index d755a1e2..ded535ec 100644 --- a/src/verification_store.integration.test.ts +++ b/src/verification_store.integration.test.ts @@ -9,7 +9,7 @@ import { beginAttempt, completeAttempt, previousPass, verificationState, type At const LANE = "verify.unit"; const BINDING = contentDigest("fixture binding"); -const PROOF = { binding: BINDING, revision: "a".repeat(40), scope: null }; +const PROOF = { binding: BINDING, revision: "a".repeat(40), scope: null, uncommitted: false, current: true }; const PASS = { ok: true, status: "passed" as const, detail: "fixture report: 7 checks passed" }; afterEach(() => { cleanupTemporaryDirectories(); }); @@ -32,14 +32,16 @@ test("signed completion preserves private output and original execution time", ( test("signed provenance rejects old formats and retains original age", () => { const { state, attempt } = fixture(); - completeAttempt(attempt, PROOF, PASS); + completeAttempt(attempt, { ...PROOF, uncommitted: true, current: false }, PASS); const next = beginAttempt(state, LANE); const original = previousPass(next, BINDING, 3600000); - expect(original?.revision).toBe("a".repeat(40)); + expect(original).toMatchObject({ revision: "a".repeat(40), uncommitted: true }); completeAttempt(next, { ...PROOF, revision: "b".repeat(40) }, PASS, original); const record = JSON.parse(readFileSync(join(next.path, "complete.json"), "utf8")); - expect(record.payload).toMatchObject({ format: 1, executed_revision: "a".repeat(40), accepted_revision: "b".repeat(40), executed_at: original?.executedAt }); - delete record.payload.format; + expect(record.payload).toMatchObject({ format: 2, executed_revision: "a".repeat(40), executed_uncommitted: true, accepted_revision: "b".repeat(40), executed_at: original?.executedAt }); + // A revision-keyed record from an earlier release, validly signed, still runs fresh. + record.payload.format = 1; + delete record.payload.executed_uncommitted; record.signature = `hmac-sha256:${createHmac("sha256", next.key).update(JSON.stringify(record.payload)).digest("hex")}`; writeFileSync(join(next.path, "complete.json"), JSON.stringify(record)); expect(previousPass(beginAttempt(state, LANE), BINDING, 3600000)).toBeUndefined(); diff --git a/src/verification_store.ts b/src/verification_store.ts index d94e3164..2263248b 100644 --- a/src/verification_store.ts +++ b/src/verification_store.ts @@ -10,33 +10,69 @@ import { DEFAULT_COMMAND_OUTPUT_BYTES } from "./command_limits"; import { gitOutput } from "./git_env"; import { hasErrorCode, hashContent } from "./model"; -type Completion = z.infer; +export type Proof = Omit, "format">; export type Attempt = { path: string; id: string; key: Uint8Array; previous?: string }; -export type VerifiedPass = { detail: string; executedAt: number; origin: string; revision: string }; +export type VerifiedPass = { detail: string; executedAt: number; origin: string; revision: string; uncommitted: boolean }; const MANIFEST_BYTES = 64 * 1024; const KEY_BYTES = 32; const ENCODING = "utf8"; const COMPLETE = "complete.json"; const OUTPUT = "output.log"; +const PROOFS = "proofs"; +const SIGNING_KEY = "signing.key"; const ATTEMPT_NAME = /^\d{12}-[0-9a-f-]{36}$/; +// Format 2 keys evidence to tracked content, so a format 1 record, keyed to a +// revision, never parses and its lane runs fresh. const completionSchema = z.object({ - format: z.literal(1), + format: z.literal(2), id: z.string(), binding: z.string().nullable(), - executed_revision: z.string().nullable(), accepted_revision: z.string().nullable(), scope: z.string().nullable(), + executed_revision: z.string().nullable(), executed_uncommitted: z.boolean(), accepted_revision: z.string().nullable(), scope: z.string().nullable(), executed_at: z.number().int().nonnegative(), origin: z.string(), status: z.enum(["passed", "failed", "blocked", "cancelled"]), output_digest: z.string(), }).strict(); const signedSchema = z.object({ payload: completionSchema, signature: z.string() }).strict(); +// What orly saw when a test failed with the change it covers reverted. +const proofSchema = z.object({ + format: z.literal(1), file: z.string(), test: z.string(), command: z.array(z.string()).min(1), + failing_line: z.string(), mutation: z.string(), revision: z.string(), recorded_at: z.number().int().nonnegative(), +}).strict(); +const signedProofSchema = z.object({ payload: proofSchema, signature: z.string() }).strict(); export function verificationState(root: string): string { - const path = gitOutput(root, ["rev-parse", "--git-path", "orly-verification"]); - if (!path) throw new Error("verification needs Git-owned private state"); - const state = resolve(root, path); + const state = statePath(root); privateDirectory(state); return state; } +// One signed record per test, replaced by the next proof of the same test. +export function saveProof(root: string, proof: Proof): void { + const state = verificationState(root); + const parent = join(state, PROOFS); + privateDirectory(parent); + const payload = proofSchema.parse({ format: 1, ...proof }); + const path = proofPath(state, proof.file, proof.test); + const temporary = `${path}.${crypto.randomUUID()}.tmp`; + writeDurable(temporary, JSON.stringify({ payload, signature: signature(payload, signingKey(state)) })); + renameSync(temporary, path); + syncDirectory(parent); +} + +// Reading creates nothing: a repository that never recorded a proof keeps no +// private state, and an unsigned, altered or misplaced record proves nothing. +export function hasProof(root: string, file: string, test: string): boolean { + try { + const state = statePath(root); + const key = join(state, SIGNING_KEY); + if (!existsSync(key)) return false; + const path = proofPath(state, file, test); + requirePrivateFile(path); + requirePrivateFile(key, KEY_BYTES); + const record = signedProofSchema.parse(JSON.parse(readFileSync(path, ENCODING))); + return record.payload.file === file && record.payload.test === test && sameSignature(record.signature, signature(record.payload, readFileSync(key))); + } catch { return false; } +} + export function beginAttempt(state: string, lane: string): Attempt { const parent = join(state, hashContent(lane)); privateDirectory(parent); @@ -73,15 +109,16 @@ export function previousPass(attempt: Attempt, binding: string, maxAge: number): requirePrivateFile(output); const detail = readFileSync(output, ENCODING); if (contentDigest(detail) !== payload.output_digest) return undefined; - return { detail, executedAt: payload.executed_at, origin: payload.origin, revision: payload.executed_revision }; + return { detail, executedAt: payload.executed_at, origin: payload.origin, revision: payload.executed_revision, uncommitted: payload.executed_uncommitted }; } catch { return undefined; } } export function completeAttempt(attempt: Attempt, proof: VerificationProof | undefined, result: Verdict, reused?: VerifiedPass): void { if (result.status && result.ok !== (result.status === "passed")) throw new Error("inconsistent native verification outcome"); const payload = completionSchema.parse({ - format: 1, id: attempt.id, binding: proof?.binding ?? null, executed_at: reused?.executedAt ?? Date.now(), - executed_revision: reused?.revision ?? proof?.revision ?? null, accepted_revision: proof?.revision ?? null, scope: proof?.scope ?? null, + format: 2, id: attempt.id, binding: proof?.binding ?? null, executed_at: reused?.executedAt ?? Date.now(), + executed_revision: reused?.revision ?? proof?.revision ?? null, executed_uncommitted: reused?.uncommitted ?? proof?.uncommitted ?? false, + accepted_revision: proof?.revision ?? null, scope: proof?.scope ?? null, origin: reused?.origin ?? attempt.id, status: result.status ?? (result.ok ? "passed" : "failed"), output_digest: contentDigest(result.detail), }); @@ -114,7 +151,17 @@ export class VerificationLock { release(): void { if (!this.#retained) { unlinkSync(this.#owner); rmdirSync(this.#path); } } } -function signature(payload: Completion, key: Uint8Array): string { +function statePath(root: string): string { + const path = gitOutput(root, ["rev-parse", "--git-path", "orly-verification"]); + if (!path) throw new Error("verification needs Git-owned private state"); + return resolve(root, path); +} + +function proofPath(state: string, file: string, test: string): string { + return join(state, PROOFS, `${hashContent(`${file}\0${test}`)}.json`); +} + +function signature(payload: object, key: Uint8Array): string { return `hmac-sha256:${new Bun.CryptoHasher("sha256", key).update(JSON.stringify(payload)).digest("hex")}`; } @@ -128,7 +175,7 @@ function sameSignature(stored: string, expected: string): boolean { } function signingKey(state: string): Uint8Array { - const path = join(state, "signing.key"); + const path = join(state, SIGNING_KEY); if (!existsSync(path)) { writeDurable(path, crypto.getRandomValues(new Uint8Array(KEY_BYTES))); syncDirectory(state); diff --git a/standards/tests.md b/standards/tests.md index f0cb15b9..99929a5e 100644 --- a/standards/tests.md +++ b/standards/tests.md @@ -332,7 +332,9 @@ A missed budget is a design finding, and the threshold never loosens silently. Retain the original command, output, counts and run provenance when a result is reused. Live datastore and network observations remain fresh unless an explicit supported freshness policy exists. -An optional `tracked_inputs` declaration permits cross-revision reuse only when it covers every tracked dependency and the command does not read Git history. Extra ignored dependencies still belong in `inputs` or the toolchain identity. Keep the full-worktree before/after guard; an unchanged subset does not excuse edits during a run. +Reuse matches tracked content, never the revision, so a reused command reads no Git history. An optional `tracked_inputs` declaration narrows that content and must cover every tracked dependency. + +Extra ignored dependencies still belong in `inputs` or the toolchain identity. Keep the full-worktree before/after guard; an unchanged subset does not excuse edits during a run. ### TEST-CLAIM — A claim that tests pass names the command it ran and the counts it printed. - **Applies to:** done messages, Pull Request descriptions and Session Notes