Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Dev mode core: tables, GitHub poller, routes, production floor (0.7) (#313)
Oleksandr Ivanchenko29ea5135e600
diff --git a/docs/dev-mode.md b/docs/dev-mode.mdnew file mode 100644index 00000000..108edd85--- /dev/null+++ b/docs/dev-mode.md@@ -0,0 +1,183 @@+# Dev mode++Dev mode (0.7) points a space at one GitHub repo and branch. kwnt then reads the repo, **read only**,+and turns what happens there into cards:++- **Landed**: one card per commit that reaches the watched branch, saying what changed and how risky it is.+- **Review**: one card per open pull request head, with findings. The person can press **Fix it**+ (the finding goes to the bot that wrote the PR) or **Dismiss** on each finding.+- **Release notes**: written on request, from the landed cards since the last tag.++It also turns on the **production floor** for the space's bots: steps that can reach production+always ask (see below).++Everything in Dev mode belongs to the person. Every route is refused for a bot's turn token, reads+included, because the settings hold the backup command and the cards hold the repo's diffs. The+tables (`dev_mode_spaces`, `dev_cards`, `dev_backups`, `dev_model_calls`, `dev_prod_connections`)+are left out of exports, like approval modes.++## Settings++`PUT /api/spaces/:id/dev_mode` saves these fields:++- `repo`: a URL, an ssh address or `owner/name`, normalised to `owner/name`;+- `branch`: the branch to watch;+- `deploy_hint`: how the repo ships, for example `cloudflare_pages` or `fly`;+- `backup_command`: the command that backs up production data.++`POST …/dev_mode/check` looks the repo up through the Loose ends GitHub connection and answers+`found`, `not_found` or `not_connected`. A new repo or branch starts the watch over. The same one+keeps its place.++`GET /api/dev/cards/:id` returns one card of any kind, in the same shape as the lists, or 404. The+desk reads a release notes draft here once its `dev_card` event says it is ready, since no list+returns those. A card in an archived space is refused like that space's lists.++Turning Dev mode **off** (D12) stops the polling, the reviews and the floor. Cards stay readable,+and approvals stay as they were.++## Reading GitHub++Reads go through the GitHub connection only, and kwnt never writes to the repo. Every read sends+the last ETag it got, so an unchanged answer costs no rate limit. A rate limit (a 403 or 429 with+`retry-after` or `x-ratelimit-remaining: 0`) backs the space off until the reset time GitHub gives,+at most an hour, or a minute for a bare 429. Another 403 is a permission error. The settings show+either one as the poll error.++Every 5 minutes, for each space with Dev mode on, kwnt:++1. Reads the latest tag. Release notes start from it.+2. Reads the commits on the branch since `last_seen_sha`. The first poll backfills the last 5. A+ poll writes at most 20 new cards. A rebase merge (several commits, one PR, no merge commit) is+ skipped.+3. For each commit, reads the PR it came from, the files and patches, and the check runs, and+ writes a `landed` card with its DevFacts. A patch past 60k characters is dropped whole, and the+ facts say "diff cut, N file(s) not read". The bot that wrote it is matched by commit author name+ (with "(kwant bot)" removed) or by the `<name>-bot` email.+4. Reads the open PRs and writes a `review` card per new head, at most 10 per poll. A new push makes+ the old head's card stale, and so does a draft or a closed PR.+5. Checks CI again on the last 10 cards whose CI was pending, for 6 hours. A change re-runs the+ card's text.++Each new card is pending until `crate::server::dev::generate` writes its text, using at most 30+model calls per space per day. After a restart, cards still pending are generated again, and a+**Fix it** that was sent but never reached its bot is sent again.++## The production floor++In a space with Dev mode on, these steps always show an approval card, whatever the bot's+approvals say (`ask`, `smart` or `off`), and whatever "always allow" was given before:++| Kind | What it is | Needs a backup |+| --- | --- | --- |+| `push_main` | pushing to the watched branch or a protected one (`main`, `master`, `production`, `prod`, `live`, `stable`, `trunk`, `gh-pages`), or `gh pr merge` | no |+| `force_push` | `git push --force`, `-f`, `--force-with-lease` or `+ref` to a protected branch | no |+| `delete_ref` | deleting a protected branch or a release tag | no |+| `deploy` | wrangler, fly, vercel `--prod`, netlify `--prod`, firebase, railway, kamal, serverless, kubectl, helm, terraform or pulumi apply, `docker compose up` or `restart` when the space deploys with Docker (or on another host, or over `ssh`), a push to a deploy remote (heroku, dokku, …), `make`, `npm` or `just` targets and scripts (`./deploy.sh`, `python release.py`, `node deploy.js`) named deploy, ship or release, deploy tools on infrastructure MCP servers | no |+| `deploy_migration` | a migration run against production: sqlx, diesel, prisma `migrate deploy`, rails `db:migrate`, alembic, `manage.py migrate` and others, when the command names a production database or environment (before or after it: `RAILS_ENV=production`, `--settings=app.prod`) | **yes** |+| `destructive` | `DROP`, `TRUNCATE`, or `DELETE`/`UPDATE` with no `WHERE` through a database client, `rm -r` on data folders or database files, `docker volume rm`, `compose down -v`, `terraform destroy`, delete tools on infrastructure apps | **yes** |+| `prod_key` | any tool on a connection the person marked **production** (D10) | no |++- The card's `details.prod_floor` is `{kind, why, blast, needs_backup, space_id, backup}`.+ - `blast` is a list of `[label, value]` rows, and only rows that are known: Where, What changes,+ Downtime, Data, Key used, Migration, If it fails.+ - `backup` is the space's backup state: `{state, age_s, bytes, path, error}`, where `state` is+ `fresh`, `old`, `none`, `no_data`, `no_command`, `taking` or `failed`.+- **Always this session** on a floor card allows that one call. Nothing is remembered, and the+ next one asks again. The same goes for a late Allow.+- **Allow** on a card that needs a backup is refused by the server (`409`, `status: "needs_backup"`)+ until the space has an `ok` backup at most 10 minutes old. This is checked when the person+ answers, so a backup taken while the card waits counts.+- `POST /api/spaces/:id/dev/backup` runs the backup command in the bot's workspace, with a+ 10-minute limit and one run at a time per space. The run finishes and is recorded even if the+ request goes away (the browser closes), and the space is free for the next one either way.+ kwnt then records what it can tell:+ - the exit code;+ - the file or folder the output names (a bare name is looked up in the bot's workspace), its+ size, and whether it is empty;+ - whether that file was written by this run: one older than the run's start (with 5 seconds of+ slack) isn't counted, so an old dump can't stand in for a new one;+ - a remote target (`s3://`, `gs://`, `r2://`, …), which counts as ok on exit 0 because its size+ can't be checked.++ Exit 0 with no file or remote target named in the output is **not** a backup: the reply is+ `ok: false` with "kwant couldn't find a backup file in the output". Make the command print+ where it wrote, for example `… && echo "Backup saved to backups/app.sql"`.+- **Marking a connection production** (D10): `PUT /api/connections/:id/production?space=` with+ `{production: true|false}`. Only an MCP server in the space (`mcp:<id>`) or a Composio app+ (`composio:<slug>`) can be marked. `GET /api/connections` shows `production` on each one.++Like the payment floor, the classifier (`src/mcp/prod_floor.rs`) is a pure function. It reads only+the call and the space's Dev mode settings, never anything the bot says about the call. It runs:++- in `BrokerApprover`, which covers claude's own tools (Bash and the rest, through claude's+ permission prompt) and every MCP tool;+- in `approve_local_shell_in`, which covers the API drivers' `execute_shell`.++It asks for some things that never reach production, such as `npm run release` in a test repo.+Compose is only read as a deploy where the space's deploy hint is Docker, or when it runs on+another host (`-H`, `--context`) or over `ssh`; `compose down`, `stop`, `pull`, `rm` and `create`+never ask, and `compose down -v` always does because it deletes volumes. That is accepted: an extra card costs a tap, and a missed+deploy can cost a site.++### What the floor can't see++- **Codex's own shell.** kwnt never sees Codex's commands, only the MCP tools Codex calls. Its+ sandbox has no network, so it can't push or deploy. It can still delete files inside its+ workspace, a local database file included.+- **Commands hidden in scripts.** Running a script (`./deploy.sh`, `bash script.sh`,+ `python release.py`, `node deploy.js`, `ruby ship.rb`) is read by the script's *name* only. A script called `run.sh` that deploys+ doesn't ask. The same goes for Makefile targets, npm scripts and CI workflows named for+ something else, and for git hooks and aliases.+- **Indirection.** A command built from variables (`$CMD`, `git push origin $BRANCH`), piped into+ a shell (`curl … | sh`, `echo … | bash`), loaded from a file, or run through another language+ (`python -c "subprocess…"`) isn't seen. `eval '…'` with literal text is read, and so are+ wrappers that run the rest of the line with their own flags (`sudo -u`, `env`, `timeout 60`,+ `nice -n 10`, `ionice`, `stdbuf`, `setsid`, `nohup`, `watch -n1`, `xargs`). Nesting deeper than+ 3 levels of `ssh` or `sh -c` isn't read, and neither are quotes nested inside quotes.+- **SDKs and HTTP calls.** A deploy or delete made with `curl` against a provider's API, or from+ code that uses its SDK, doesn't ask unless it goes through a connection marked production.+- **Tools and providers missing from the lists**, and MCP tools whose names don't say what they+ do. Mark such a connection production to make every one of its tools ask.+- **Git writes through a connection.** A GitHub MCP server or Composio app that isn't marked+ production can write to the repo with no card: `push_files`, `create_or_update_file` on `main`,+ `merge_pull_request`, `delete_branch` and the like reach the watched branch directly. The floor+ reads git commands and deploy tools, not these tool names. Mark that connection production+ (Connections → Production) to make every one of its tools ask.+- **Where a command runs.** The floor can't tell a production database from a local copy unless+ the command says so (a remote URL, `--prod`, `RAILS_ENV=production`, …). So a plain+ `sqlx migrate run` doesn't ask, but `DROP TABLE` does, wherever it runs.+- **What CI does after a push.** A push to the watched branch asks, because it may deploy. A push+ to another branch that CI deploys from doesn't ask, unless that branch is protected.+- **The checked-out branch** is read from `.git/HEAD` in the bot's folder, or the folder above it.+ A `git checkout` or `git switch` earlier in the same command is followed: `git switch main &&+ git push` asks. `git checkout x` could restore a file `x`, so unless `x` is protected the branch+ then counts as unknown, and a bare push after it asks. A `cd other-repo && git push` is judged by+ the first repo's branch. A bare `git push` from a+ detached head, or from a folder that isn't a repo, counts as a push to a protected branch.++## Tests++Run these focused tests:++```sh+cargo test --lib -- server::dev:: prod_floor auth::tests::person_only zombie::github connections::tests::only_mcp+```++The poller runs against a mock GitHub on a private `127.0.0.1` port. The shared mock is+`tests/support/mock_github.rs` (include it with `#[path = "support/mock_github.rs"] mod mock_github;`):+fixtures by path with ETags and 304s, `Link: next` headers (to another host too), each GitHub+error (401, 403, rate limits, secondary limits, 429, 5xx, slow answers, a lost base commit), and a+log of every request. Anything but a GET fails the test. `tests/dev_github_test.rs` holds the+contract tests and the canary: a token built at runtime goes through a whole poll, failures+included, and must appear nowhere but the vault (logs, errors, events, cards, the database, model+prompts, other files under the data folder).++Test seams, for the test server only: `KWANT_DEV_POLL_SECS` (5–86400, default 300) and+`KWANT_DEV_CALL_CAP` (0–1000, default 30), read once at the first use. The daily cap counts per UTC+day. Tests move Dev mode's clock in-process with `server::dev::set_clock_skew`+(`tests/dev_seams_test.rs`). There are table tests for each+floor kind in `src/mcp/prod_floor.rs`. The backup checks and the Allow refusal are tested in+`src/server/dev/backup.rs` and `src/server/dev/floor.rs`. `tests/dev_floor_test.rs` drives the refusal+through `POST /api/approvals/:id/resolve`: a 409 with no backup or an old one, then a 200 once a+fresh one exists, and Deny always accepted.diff --git a/src/db/dev_mode.rs b/src/db/dev_mode.rsnew file mode 100644index 00000000..2ce76747--- /dev/null+++ b/src/db/dev_mode.rs@@ -0,0 +1,432 @@+//! Dev mode (docs/dev-mode.md): one watched GitHub repo per space, the cards kwant writes about+//! what landed on it and its open pull requests, and the backups the production floor asks for.+//! Kept in their own tables, outside exports, like approval modes, so an imported bundle can't+//! switch Dev mode on or off. Only the person writes `dev_mode_spaces` (the routes refuse agent+//! tokens). Add-only: `CREATE TABLE IF NOT EXISTS`, so a 0.6.12 build still runs on this database.++use super::{Database, DbError};+use chrono::{DateTime, Utc};+use sqlx::FromRow;++/// Most model calls Dev mode makes per space per day (plan D8).+pub const CALLS_CAP: i64 = 30;++/// Card kinds and statuses, as stored.+pub const LANDED: &str = "landed";+pub const REVIEW: &str = "review";+pub const RELEASE_NOTES: &str = "release_notes";+pub const PENDING: &str = "pending";+pub const READY: &str = "ready";+pub const FAILED: &str = "failed";+pub const STALE: &str = "stale";++/// "Some space has Dev mode on", kept in memory so the production floor skips its reads while+/// Dev mode is off everywhere. Read at open and re-read after every write to `dev_mode_spaces`,+/// under `writes`, so two toggles can't leave it stale. A failed read counts as on (the floor runs).+#[derive(Debug, Default)]+pub struct DevOn {+ on: std::sync::atomic::AtomicBool,+ writes: tokio::sync::Mutex<()>,+}++const TABLES: &[&str] = &[+ "CREATE TABLE IF NOT EXISTS dev_mode_spaces (+ space_id TEXT PRIMARY KEY,+ on_ INTEGER NOT NULL DEFAULT 0,+ provider TEXT NOT NULL DEFAULT 'github',+ repo TEXT NOT NULL,+ branch TEXT NOT NULL,+ deploy_hint TEXT,+ backup_command TEXT,+ last_seen_sha TEXT,+ polled_at TIMESTAMP,+ poll_error TEXT,+ seen_at TIMESTAMP,+ updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP+ )",+ "CREATE TABLE IF NOT EXISTS dev_cards (+ id TEXT PRIMARY KEY,+ space_id TEXT NOT NULL,+ kind TEXT NOT NULL,+ ref TEXT NOT NULL,+ head_sha TEXT NOT NULL,+ status TEXT NOT NULL,+ facts TEXT NOT NULL,+ card TEXT,+ created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,+ updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,+ UNIQUE(space_id, kind, ref, head_sha)+ )",+ "CREATE INDEX IF NOT EXISTS idx_dev_cards_space ON dev_cards(space_id, kind, created_at)",+ "CREATE TABLE IF NOT EXISTS dev_backups (+ id TEXT PRIMARY KEY,+ space_id TEXT NOT NULL,+ kwant_id TEXT,+ path TEXT,+ bytes INTEGER,+ ok INTEGER NOT NULL,+ error TEXT,+ taken_at TIMESTAMP NOT NULL+ )",+ "CREATE INDEX IF NOT EXISTS idx_dev_backups_space ON dev_backups(space_id, taken_at)",+ // Model calls per space per UTC day, for the D8 cap (not in exports either)+ "CREATE TABLE IF NOT EXISTS dev_model_calls (+ space_id TEXT NOT NULL,+ day TEXT NOT NULL,+ calls INTEGER NOT NULL DEFAULT 0,+ PRIMARY KEY (space_id, day)+ )",+ // Connections the person marked production (D10): `mcp:<server id>` or `composio:<toolkit slug>`+ "CREATE TABLE IF NOT EXISTS dev_prod_connections (+ space_id TEXT NOT NULL,+ connection_id TEXT NOT NULL,+ marked_at TIMESTAMP NOT NULL,+ PRIMARY KEY (space_id, connection_id)+ )",+];++/// A space's Dev mode settings and poll state.+#[derive(Debug, Clone, FromRow, PartialEq)]+pub struct DevModeRow {+ pub space_id: String,+ #[sqlx(rename = "on_")]+ pub on: bool,+ pub provider: String,+ pub repo: String,+ pub branch: String,+ pub deploy_hint: Option<String>,+ pub backup_command: Option<String>,+ pub last_seen_sha: Option<String>,+ pub polled_at: Option<DateTime<Utc>>,+ pub poll_error: Option<String>,+ pub seen_at: Option<DateTime<Utc>>,+ pub updated_at: DateTime<Utc>,+}++/// One card: what landed, a review of an open PR head, or a release-notes draft.+#[derive(Debug, Clone, FromRow, PartialEq)]+pub struct DevCardRow {+ pub id: String,+ pub space_id: String,+ pub kind: String,+ #[sqlx(rename = "ref")]+ pub ref_: String,+ pub head_sha: String,+ pub status: String,+ /// `server::dev::facts::DevFacts` JSON (or `ReleaseFacts` for release notes).+ pub facts: String,+ /// The card JSON (plan §3.4) once generated.+ pub card: Option<String>,+ pub created_at: DateTime<Utc>,+ pub updated_at: DateTime<Utc>,+}++#[derive(Debug, Clone, FromRow, PartialEq, serde::Serialize)]+pub struct DevBackupRow {+ pub id: String,+ pub space_id: String,+ pub kwant_id: Option<String>,+ pub path: Option<String>,+ pub bytes: Option<i64>,+ pub ok: bool,+ pub error: Option<String>,+ pub taken_at: DateTime<Utc>,+}++const CARD_COLS: &str = "id, space_id, kind, ref, head_sha, status, facts, card, created_at, updated_at";++impl Database {+ pub(super) async fn migrate_dev_mode(&self) -> Result<(), DbError> {+ for sql in TABLES {+ sqlx::query(sql).execute(&self.pool).await?;+ }+ Ok(())+ }++ /// False only when no space has Dev mode on: then there is no production floor anywhere.+ pub fn any_dev_mode_on(&self) -> bool {+ self.dev_on.on.load(std::sync::atomic::Ordering::SeqCst)+ }++ pub(super) async fn refresh_dev_on(&self) {+ let on = sqlx::query_scalar::<_, bool>("SELECT EXISTS(SELECT 1 FROM dev_mode_spaces WHERE on_ = 1)").fetch_one(&self.pool).await;+ self.dev_on.on.store(on.unwrap_or(true), std::sync::atomic::Ordering::SeqCst);+ }++ pub async fn dev_mode(&self, space_id: &str) -> Result<Option<DevModeRow>, DbError> {+ Ok(sqlx::query_as("SELECT * FROM dev_mode_spaces WHERE space_id = ?").bind(space_id).fetch_optional(&self.pool).await?)+ }++ /// Every space with Dev mode on, for the poller.+ pub async fn dev_mode_on_spaces(&self) -> Result<Vec<DevModeRow>, DbError> {+ Ok(sqlx::query_as("SELECT * FROM dev_mode_spaces WHERE on_ = 1 ORDER BY space_id").fetch_all(&self.pool).await?)+ }++ /// Saves the person's settings. A new repo or branch starts the watch over (`last_seen_sha`+ /// and the poll state are cleared); the same one keeps them.+ pub async fn put_dev_mode(+ &self,+ space_id: &str,+ on: bool,+ repo: &str,+ branch: &str,+ deploy_hint: Option<&str>,+ backup_command: Option<&str>,+ ) -> Result<DevModeRow, DbError> {+ let _writes = self.dev_on.writes.lock().await;+ if on {+ // Before the row, so no call slips between the write and the flag+ self.dev_on.on.store(true, std::sync::atomic::Ordering::SeqCst);+ }+ let now = Utc::now();+ let done = sqlx::query(+ "INSERT INTO dev_mode_spaces (space_id, on_, repo, branch, deploy_hint, backup_command, updated_at)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)+ ON CONFLICT(space_id) DO UPDATE SET+ last_seen_sha = CASE WHEN dev_mode_spaces.repo = excluded.repo AND dev_mode_spaces.branch = excluded.branch THEN dev_mode_spaces.last_seen_sha ELSE NULL END,+ polled_at = CASE WHEN dev_mode_spaces.repo = excluded.repo AND dev_mode_spaces.branch = excluded.branch THEN dev_mode_spaces.polled_at ELSE NULL END,+ poll_error = CASE WHEN dev_mode_spaces.repo = excluded.repo AND dev_mode_spaces.branch = excluded.branch THEN dev_mode_spaces.poll_error ELSE NULL END,+ on_ = excluded.on_, repo = excluded.repo, branch = excluded.branch,+ deploy_hint = excluded.deploy_hint, backup_command = excluded.backup_command, updated_at = excluded.updated_at",+ )+ .bind(space_id)+ .bind(on)+ .bind(repo)+ .bind(branch)+ .bind(deploy_hint)+ .bind(backup_command)+ .bind(now)+ .execute(&self.pool)+ .await;+ self.refresh_dev_on().await;+ done?;+ Ok(self.dev_mode(space_id).await?.expect("just written"))+ }++ pub async fn dev_mode_polled(&self, space_id: &str, last_seen_sha: Option<&str>, error: Option<&str>) -> Result<(), DbError> {+ sqlx::query("UPDATE dev_mode_spaces SET last_seen_sha = COALESCE(?2, last_seen_sha), polled_at = ?3, poll_error = ?4 WHERE space_id = ?1")+ .bind(space_id)+ .bind(last_seen_sha)+ .bind(Utc::now())+ .bind(error)+ .execute(&self.pool)+ .await?;+ Ok(())+ }++ pub async fn dev_mode_seen(&self, space_id: &str, at: DateTime<Utc>) -> Result<(), DbError> {+ sqlx::query("UPDATE dev_mode_spaces SET seen_at = ?2 WHERE space_id = ?1").bind(space_id).bind(at).execute(&self.pool).await?;+ Ok(())+ }++ pub async fn delete_dev_mode_of_space(&self, space_id: &str) -> Result<(), DbError> {+ let _writes = self.dev_on.writes.lock().await;+ let done = self.delete_dev_rows(space_id).await;+ self.refresh_dev_on().await;+ done+ }++ async fn delete_dev_rows(&self, space_id: &str) -> Result<(), DbError> {+ let mut tx = self.pool.begin().await?;+ for t in ["dev_mode_spaces", "dev_cards", "dev_backups", "dev_model_calls", "dev_prod_connections"] {+ sqlx::query(&format!("DELETE FROM {t} WHERE space_id = ?")).bind(space_id).execute(&mut *tx).await?;+ }+ tx.commit().await?;+ Ok(())+ }++ /// The connection ids the person marked production in a space (D10).+ pub async fn prod_connections(&self, space_id: &str) -> Result<Vec<String>, DbError> {+ let rows: Vec<(String,)> = sqlx::query_as("SELECT connection_id FROM dev_prod_connections WHERE space_id = ? ORDER BY connection_id")+ .bind(space_id)+ .fetch_all(&self.pool)+ .await?;+ Ok(rows.into_iter().map(|r| r.0).collect())+ }++ /// Marks or unmarks a connection production.+ pub async fn set_prod_connection(&self, space_id: &str, connection_id: &str, production: bool) -> Result<(), DbError> {+ if production {+ sqlx::query("INSERT INTO dev_prod_connections (space_id, connection_id, marked_at) VALUES (?, ?, ?) ON CONFLICT DO NOTHING")+ .bind(space_id)+ .bind(connection_id)+ .bind(Utc::now())+ .execute(&self.pool)+ .await?;+ } else {+ sqlx::query("DELETE FROM dev_prod_connections WHERE space_id = ? AND connection_id = ?").bind(space_id).bind(connection_id).execute(&self.pool).await?;+ }+ Ok(())+ }++ /// Adds a pending card. `None` when one with the same space, kind, ref and head already exists.+ pub async fn insert_dev_card(&self, space_id: &str, kind: &str, ref_: &str, head_sha: &str, facts: &str) -> Result<Option<DevCardRow>, DbError> {+ let id = format!("dvc_{}", uuid::Uuid::new_v4().simple());+ let now = Utc::now();+ let done = sqlx::query(+ "INSERT INTO dev_cards (id, space_id, kind, ref, head_sha, status, facts, created_at, updated_at)+ VALUES (?, ?, ?, ?, ?, 'pending', ?, ?, ?) ON CONFLICT(space_id, kind, ref, head_sha) DO NOTHING",+ )+ .bind(&id)+ .bind(space_id)+ .bind(kind)+ .bind(ref_)+ .bind(head_sha)+ .bind(facts)+ .bind(now)+ .bind(now)+ .execute(&self.pool)+ .await?;+ if done.rows_affected() == 0 {+ return Ok(None);+ }+ self.dev_card(&id).await+ }++ pub async fn dev_card(&self, id: &str) -> Result<Option<DevCardRow>, DbError> {+ Ok(sqlx::query_as(&format!("SELECT {CARD_COLS} FROM dev_cards WHERE id = ?")).bind(id).fetch_optional(&self.pool).await?)+ }++ /// Sets a card's status, and its card JSON when given (`None` keeps the stored one).+ pub async fn set_dev_card(&self, id: &str, status: &str, card: Option<&str>) -> Result<Option<DevCardRow>, DbError> {+ sqlx::query("UPDATE dev_cards SET status = ?2, card = COALESCE(?3, card), updated_at = ?4 WHERE id = ?1")+ .bind(id)+ .bind(status)+ .bind(card)+ .bind(Utc::now())+ .execute(&self.pool)+ .await?;+ self.dev_card(id).await+ }++ /// New facts for a card (CI finished after the card was made): back to pending so `generate`+ /// runs again; the card JSON stays until then.+ pub async fn set_dev_card_facts(&self, id: &str, facts: &str) -> Result<Option<DevCardRow>, DbError> {+ sqlx::query("UPDATE dev_cards SET facts = ?2, status = 'pending', updated_at = ?3 WHERE id = ?1")+ .bind(id)+ .bind(facts)+ .bind(Utc::now())+ .execute(&self.pool)+ .await?;+ self.dev_card(id).await+ }++ /// Replaces a card's JSON only while it still has `expect` (compare-and-set), so two finding+ /// actions can't overwrite each other. False when it changed in between.+ pub async fn swap_dev_card_json(&self, id: &str, expect: Option<&str>, card: &str) -> Result<bool, DbError> {+ let done = sqlx::query("UPDATE dev_cards SET card = ?3, updated_at = ?4 WHERE id = ?1 AND card IS ?2")+ .bind(id)+ .bind(expect)+ .bind(card)+ .bind(Utc::now())+ .execute(&self.pool)+ .await?;+ Ok(done.rows_affected() == 1)+ }++ /// A space's cards of one kind, newest first, created before `before` when given.+ pub async fn dev_cards(&self, space_id: &str, kind: &str, before: Option<DateTime<Utc>>, limit: i64) -> Result<Vec<DevCardRow>, DbError> {+ Ok(sqlx::query_as(&format!(+ "SELECT {CARD_COLS} FROM dev_cards WHERE space_id = ?1 AND kind = ?2 AND (?3 IS NULL OR created_at < ?3)+ ORDER BY created_at DESC, id DESC LIMIT ?4"+ ))+ .bind(space_id)+ .bind(kind)+ .bind(before)+ .bind(limit)+ .fetch_all(&self.pool)+ .await?)+ }++ /// Cards of one kind and ref (every head a PR had), newest first.+ pub async fn dev_cards_of_ref(&self, space_id: &str, kind: &str, ref_: &str) -> Result<Vec<DevCardRow>, DbError> {+ Ok(sqlx::query_as(&format!("SELECT {CARD_COLS} FROM dev_cards WHERE space_id = ? AND kind = ? AND ref = ? ORDER BY created_at DESC, id DESC"))+ .bind(space_id)+ .bind(kind)+ .bind(ref_)+ .fetch_all(&self.pool)+ .await?)+ }++ /// Cards still pending (a restart left them), oldest first.+ pub async fn pending_dev_cards(&self) -> Result<Vec<DevCardRow>, DbError> {+ Ok(sqlx::query_as(&format!("SELECT {CARD_COLS} FROM dev_cards WHERE status = 'pending' ORDER BY created_at")).fetch_all(&self.pool).await?)+ }++ /// Marks every review card of a PR whose head isn't `keep_head` stale; returns their ids.+ pub async fn stale_dev_reviews(&self, space_id: &str, ref_: &str, keep_head: Option<&str>) -> Result<Vec<String>, DbError> {+ let rows: Vec<(String,)> = sqlx::query_as(+ "UPDATE dev_cards SET status = 'stale', updated_at = ?4+ WHERE space_id = ?1 AND kind = 'review' AND ref = ?2 AND status != 'stale' AND (?3 IS NULL OR head_sha != ?3) RETURNING id",+ )+ .bind(space_id)+ .bind(ref_)+ .bind(keep_head)+ .bind(Utc::now())+ .fetch_all(&self.pool)+ .await?;+ Ok(rows.into_iter().map(|r| r.0).collect())+ }++ /// Model calls Dev mode made in a space today (the UTC day of `dev::now()`).+ pub async fn dev_calls_today(&self, space_id: &str) -> Result<i64, DbError> {+ self.dev_calls_on(space_id, &crate::server::dev::utc_day(crate::server::dev::now())).await+ }++ pub async fn dev_calls_on(&self, space_id: &str, day: &str) -> Result<i64, DbError> {+ let row: Option<(i64,)> = sqlx::query_as("SELECT calls FROM dev_model_calls WHERE space_id = ? AND day = ?")+ .bind(space_id)+ .bind(day)+ .fetch_optional(&self.pool)+ .await?;+ Ok(row.map(|r| r.0).unwrap_or(0))+ }++ /// Takes one model call from today's cap (`dev::call_cap()`, default [`CALLS_CAP`]): false (and+ /// nothing counted) once it's used up.+ pub async fn take_dev_call(&self, space_id: &str) -> Result<bool, DbError> {+ self.take_dev_call_at(space_id, crate::server::dev::now(), crate::server::dev::call_cap()).await+ }++ /// [`Self::take_dev_call`] on the UTC day of `now`, against `cap`.+ pub async fn take_dev_call_at(&self, space_id: &str, now: DateTime<Utc>, cap: i64) -> Result<bool, DbError> {+ if cap <= 0 {+ return Ok(false);+ }+ let done = sqlx::query(+ "INSERT INTO dev_model_calls (space_id, day, calls) VALUES (?1, ?2, 1)+ ON CONFLICT(space_id, day) DO UPDATE SET calls = calls + 1 WHERE calls < ?3",+ )+ .bind(space_id)+ .bind(crate::server::dev::utc_day(now))+ .bind(cap)+ .execute(&self.pool)+ .await?;+ Ok(done.rows_affected() == 1)+ }++ pub async fn insert_dev_backup(&self, b: &DevBackupRow) -> Result<(), DbError> {+ sqlx::query("INSERT INTO dev_backups (id, space_id, kwant_id, path, bytes, ok, error, taken_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")+ .bind(&b.id)+ .bind(&b.space_id)+ .bind(&b.kwant_id)+ .bind(&b.path)+ .bind(b.bytes)+ .bind(b.ok)+ .bind(&b.error)+ .bind(b.taken_at)+ .execute(&self.pool)+ .await?;+ Ok(())+ }++ /// The space's newest backup, and its newest one that worked.+ pub async fn latest_dev_backups(&self, space_id: &str) -> Result<(Option<DevBackupRow>, Option<DevBackupRow>), DbError> {+ let last = sqlx::query_as("SELECT * FROM dev_backups WHERE space_id = ? ORDER BY taken_at DESC LIMIT 1").bind(space_id).fetch_optional(&self.pool).await?;+ let ok = sqlx::query_as("SELECT * FROM dev_backups WHERE space_id = ? AND ok = 1 ORDER BY taken_at DESC LIMIT 1")+ .bind(space_id)+ .fetch_optional(&self.pool)+ .await?;+ Ok((last, ok))+ }+}diff --git a/src/db/mod.rs b/src/db/mod.rsindex 22ed1ab3..3a724cc2 100644--- a/src/db/mod.rs+++ b/src/db/mod.rs@@ -41,6 +41,7 @@ pub mod lessons;pub mod reactions;pub mod routing;pub mod smart_results;+pub mod dev_mode;/// What a space's #general says about itself.pub const GENERAL_DESCRIPTION: &str = "Everyone in this space. Laya picks who answers.";@@ -89,6 +90,8 @@ pub struct Database {pool: Pool<Sqlite>,/// Where attachments live (`<data_dir>/attachments`), for file previews in Smart Results.data_dir: std::path::PathBuf,+ /// Whether any space has Dev mode on (see `dev_mode::DevOn`), shared by every clone.+ dev_on: std::sync::Arc<dev_mode::DevOn>,}/// Built-in kwants: (name, title, persona, soul, avatar).@@ -171,7 +174,7 @@ impl Database {// The chat a card that outlived its turn resumes in (see `park_approval`)let _ = sqlx::query("ALTER TABLE approvals ADD COLUMN resume TEXT;").execute(&pool).await;- let db = Self { pool, data_dir: data_dir.to_path_buf() };+ let db = Self { pool, data_dir: data_dir.to_path_buf(), dev_on: Default::default() };db.migrate_profiles().await?;db.migrate_browser_sites().await?;db.migrate_continuity().await?;@@ -233,6 +236,8 @@ impl Database {// Phase C1: the Truth Ledger mirrors memory (add-only). Last, so no later step rebuilds// a table its triggers or lookups depend ondb.migrate_truth_ledger().await?;+ // 0.7: Dev mode (add-only, outside exports)+ db.migrate_dev_mode().await?;db.pool.close().await;// Said out loud rather than left to sqlx's default: every writer, a goal proposal@@ -243,7 +248,9 @@ impl Database {.connect_with(options).await?;sqlx::query("PRAGMA synchronous = NORMAL;").execute(&pool).await?;- Ok(Self { pool, data_dir: data_dir.to_path_buf() })+ let db = Self { pool, data_dir: data_dir.to_path_buf(), dev_on: Default::default() };+ db.refresh_dev_on().await;+ Ok(db)}/// A transaction that holds SQLite's write lock from the start, for one that reads before itdiff --git a/src/drivers/events.rs b/src/drivers/events.rsindex 8b8df3b2..7391ddaa 100644--- a/src/drivers/events.rs+++ b/src/drivers/events.rs@@ -288,6 +288,13 @@ pub enum RuntimeEvent {/// A goal changed (status, checks, schedule, its fix task); `GET /api/goals/:id` has the rest.#[serde(rename = "goal_updated", alias = "GoalUpdated")]GoalUpdated { id: String, status: String, space_id: String },+ /// A Dev mode card was added or changed (plan §3.2); refetch `GET /api/spaces/:id/dev/…`.+ /// `kind` is `landed`, `review` or `release_notes`; `status` `pending`, `ready`, `failed` or `stale`.+ #[serde(rename = "dev_card", alias = "DevCard")]+ DevCard { space_id: String, id: String, kind: String, status: String },+ /// Dev mode was turned on or off in a space.+ #[serde(rename = "dev_mode", alias = "DevMode")]+ DevMode { space_id: String, on: bool },/// Something the user asked to be told about. `kind` is one of `continuity::NOTIFY_KINDS`/// ("turn_finished", "approval_needed", "human_step", …). `body` never holds chat text, tool arguments or secrets.#[serde(rename = "notify", alias = "Notify")]diff --git a/src/mcp/mod.rs b/src/mcp/mod.rsindex dec7b8bd..54bb858d 100644--- a/src/mcp/mod.rs+++ b/src/mcp/mod.rs@@ -9,6 +9,7 @@ pub mod echo_server;pub mod fetch_risk;pub mod oauth;pub mod payment_floor;+pub mod prod_floor;pub mod oauth_mock;pub mod registry;pub mod session;diff --git a/src/mcp/prod_floor.rs b/src/mcp/prod_floor.rsnew file mode 100644index 00000000..0ab81bf5--- /dev/null+++ b/src/mcp/prod_floor.rs@@ -0,0 +1,1514 @@+//! The production floor (0.7 Dev mode, plan §3.5, D9, D10): in a space with Dev mode on, tool+//! calls that push to the watched branch, force-push or delete a protected ref, deploy, destroy+//! data, or go through a connection marked production always get an approval card, whatever the+//! bot's approvals are and whatever "always allow" was given. Like the payment floor it sits+//! next to, [`reason`] and [`shell_reason`] are pure: they read the call and a [`DevCtx`] the+//! caller builds from the space's Dev mode row, never anything the bot says about the call.+//!+//! The lists err on the side of asking: an extra card costs a tap, a missed deploy can cost a+//! site. What the floor can't see is written down in docs/dev-mode.md.++use super::ToolApprovalRequest;+use serde::Serialize;+use serde_json::Value;++/// What kind of production step a call is.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]+#[serde(rename_all = "snake_case")]+pub enum FloorKind {+ PushMain,+ ForcePush,+ DeleteRef,+ Deploy,+ DeployMigration,+ Destructive,+ ProdKey,+}++impl FloorKind {+ /// Destructive steps need an `ok` backup from the last 10 minutes before Allow (D9).+ pub fn needs_backup(self) -> bool {+ matches!(self, FloorKind::Destructive | FloorKind::DeployMigration)+ }++ /// How sure the floor is that this matters most: the stronger kind wins when one command+ /// does several things.+ fn rank(self) -> u8 {+ match self {+ FloorKind::Destructive => 7,+ FloorKind::DeployMigration => 6,+ FloorKind::ForcePush => 5,+ FloorKind::DeleteRef => 4,+ FloorKind::Deploy => 3,+ FloorKind::PushMain => 2,+ FloorKind::ProdKey => 1,+ }+ }+}++/// Why a call hits the floor, with the blast-radius rows the card shows (only what's known).+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+pub struct Floor {+ pub kind: FloorKind,+ pub why: String,+ /// `(label, value)`, labels from: Where, What changes, Downtime, Data, Key used, Migration,+ /// If it fails. Serialised as `[label, value]` pairs.+ pub blast: Vec<(String, String)>,+ pub needs_backup: bool,+}++impl Floor {+ fn new(kind: FloorKind, why: impl Into<String>) -> Self {+ Floor { kind, why: why.into(), blast: Vec::new(), needs_backup: kind.needs_backup() }+ }++ fn row(mut self, label: &str, value: impl Into<String>) -> Self {+ let value = value.into();+ if !value.is_empty() && !self.blast.iter().any(|(l, _)| l == label) {+ self.blast.push((label.to_string(), value));+ }+ self+ }++ /// The stronger of two findings; rows of both are kept.+ fn merge(self, other: Floor) -> Floor {+ let (mut keep, extra) = if other.kind.rank() > self.kind.rank() { (other, self) } else { (self, other) };+ for (l, v) in extra.blast {+ if !keep.blast.iter().any(|(k, _)| *k == l) {+ keep.blast.push((l, v));+ }+ }+ keep.needs_backup = keep.kind.needs_backup();+ keep+ }+}++/// What the floor knows about the space, built by the caller from `dev_mode_spaces`.+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct DevCtx {+ /// The watched branch (`main`).+ pub branch: String,+ /// More branches to protect besides [`PROTECTED`] and the watched one.+ pub protected: Vec<String>,+ /// `docker`, `cloudflare_pages`, `fly` or `None`.+ pub deploy_hint: Option<String>,+ /// MCP server names and Composio toolkit slugs marked production (D10).+ pub prod_connections: Vec<String>,+ /// The branch checked out in the bot's folder, when the caller could read it; a bare+ /// `git push` pushes that branch. `None` counts as protected (it can't be told).+ pub head_branch: Option<String>,+ /// Whether the code a deploy ships changes the database. `None`: kwant can't tell, so a+ /// deploy counts as having a migration (D9), except where nothing holds data.+ pub migration: Option<bool>,+}++impl DevCtx {+ fn is_protected(&self, branch: &str) -> bool {+ let b = branch.strip_prefix("refs/heads/").unwrap_or(branch);+ b == self.branch || PROTECTED.contains(&b) || self.protected.iter().any(|p| p == b) || b.starts_with("release/")+ }++ /// The target keeps no data (a static Pages site): nothing to back up.+ pub fn no_data(&self) -> bool {+ self.deploy_hint.as_deref() == Some("cloudflare_pages")+ }++ /// A deploy, upgraded to a migration deploy unless the site holds no data or the caller+ /// knows there's no database change.+ fn deploy(&self, why: String) -> Floor {+ let migration = !self.no_data() && self.migration != Some(false);+ if migration {+ let known = self.migration == Some(true);+ Floor::new(FloorKind::DeployMigration, why).row(+ "Migration",+ if known { "This deploy changes the database." } else { "kwant can't tell whether this deploy changes the database, so it counts as one." },+ )+ .row("If it fails", "The app goes back on its own. The database goes back only from a backup.")+ } else {+ let f = Floor::new(FloorKind::Deploy, why);+ if self.no_data() {+ f.row("Data", "Nothing to back up: this site has no database or uploads.")+ } else {+ f+ }+ }+ }+}++/// Branches always protected, besides the watched one.+pub const PROTECTED: &[&str] = &["main", "master", "production", "prod", "live", "stable", "trunk", "gh-pages"];++/// Git remotes whose push is itself a deploy.+const DEPLOY_REMOTES: &[&str] = &["heroku", "dokku", "production", "prod", "live", "deploy", "fly"];++/// Words in a script, make target, npm script or workflow name that mean shipping.+const SHIP_WORDS: &[&str] = &["deploy", "redeploy", "ship", "rollout", "release", "promote"];++/// Infrastructure apps (MCP server names, Composio toolkits) whose tools change real systems.+const INFRA_APPS: &[&str] = &[+ "cloudflare", "digitalocean", "aws", "gcp", "gcloud", "google_cloud", "azure", "vercel", "netlify", "fly", "flyio", "render",+ "railway", "heroku", "supabase", "neon", "planetscale", "turso", "kubernetes", "k8s", "docker", "hetzner", "linode", "vultr",+ "firebase", "mongodb", "atlas", "redis", "upstash", "postgres", "mysql", "sqlite", "database",+];++/// Tool words that destroy something on an infrastructure app.+const DESTROY_WORDS: &[&str] = &[+ "delete", "destroy", "drop", "purge", "wipe", "truncate", "rebuild", "reset", "restore", "remove", "rm", "terminate", "erase",+ "flush", "shutdown", "poweroff", "uninstall",+];++/// Tool words that ship.+const DEPLOY_TOOL_WORDS: &[&str] = &["deploy", "redeploy", "rollout", "promote", "publish", "release"];++/// Path parts that hold data a person would miss.+const DATA_WORDS: &[&str] = &[+ "data", "db", "database", "databases", "uploads", "upload", "media", "volumes", "volume", "backups", "backup", "storage",+ "prod", "production", "postgres", "postgresql", "mysql", "redis", "var",+];++/// Why this call hits the production floor, or `None`. Only called when the bot's space has+/// Dev mode on.+pub fn reason(req: &ToolApprovalRequest, ctx: &DevCtx) -> Option<Floor> {+ let shell = |cmd: Option<&str>| cmd.and_then(|c| shell_reason(c, ctx));+ let found = if req.builtin.is_some() {+ match req.tool.as_str() {+ "Bash" => shell(req.arguments["command"].as_str()),+ _ => None,+ }+ } else if req.tool == "execute_shell" {+ shell(req.arguments["command"].as_str())+ } else if req.server == super::SELF_SERVER_NAME {+ None+ } else {+ mcp_reason(&req.server, &req.tool, &req.arguments, ctx)+ };+ // A production connection is checked last: what the call does names the card first+ match (found, prod_key(&req.server, &req.tool, &req.arguments, ctx)) {+ (Some(f), Some(k)) => Some(f.merge(k)),+ (f, k) => f.or(k),+ }+}++/// The connection a call goes through, when it's marked production.+fn prod_key(server: &str, tool: &str, args: &Value, ctx: &DevCtx) -> Option<Floor> {+ if ctx.prod_connections.is_empty() || server.is_empty() || server == super::SELF_SERVER_NAME {+ return None;+ }+ let s = server.to_lowercase();+ let mut names = vec![s.clone()];+ // Composio: the toolkit is the first word of the tool slug (`GITHUB_CREATE_ISSUE`)+ let mut slugs = Vec::new();+ collect_slugs(args, &mut slugs, 0);+ slugs.push(tool.to_string());+ for slug in slugs {+ if let Some(first) = slug.to_lowercase().split(['_', '-']).find(|w| !w.is_empty() && *w != "composio") {+ names.push(first.to_string());+ }+ }+ let hit = ctx.prod_connections.iter().find(|p| names.iter().any(|n| n == &p.to_lowercase()))?;+ Some(Floor::new(FloorKind::ProdKey, format!("{tool} goes through {hit}, a connection marked production")).row("Key used", format!("{hit} · production")))+}++/// Composio-style slugs in the arguments (`tool_slug`, `tools: [{tool_slug}]`).+fn collect_slugs(v: &Value, out: &mut Vec<String>, depth: usize) {+ if depth > 4 || out.len() > 20 {+ return;+ }+ match v {+ Value::Object(m) => {+ for (k, val) in m {+ let k = k.to_lowercase();+ if matches!(k.as_str(), "tool_slug" | "slug" | "action" | "tool") {+ if let Some(s) = val.as_str() {+ out.push(s.to_string());+ }+ }+ collect_slugs(val, out, depth + 1);+ }+ }+ Value::Array(a) => a.iter().for_each(|x| collect_slugs(x, out, depth + 1)),+ _ => {}+ }+}++/// An MCP or Composio tool by its name and arguments.+fn mcp_reason(server: &str, tool: &str, args: &Value, ctx: &DevCtx) -> Option<Floor> {+ let mut slugs = vec![tool.to_string()];+ collect_slugs(args, &mut slugs, 0);+ let app_words = words(server);+ let mut best: Option<Floor> = None;+ let mut add = |f: Floor| best = Some(match best.take() { Some(b) => b.merge(f), None => f });+ for slug in &slugs {+ let w = words(slug);+ let infra = app_words.iter().chain(w.iter()).any(|x| INFRA_APPS.contains(&x.as_str()));+ if w.first().is_some_and(|f| READ_VERBS.contains(&f.as_str())) {+ continue;+ }+ if w.iter().any(|x| DEPLOY_TOOL_WORDS.contains(&x.as_str())) && (infra || w.iter().any(|x| x == "deploy" || x == "redeploy" || x == "rollout")) {+ add(ctx.deploy(format!("{slug} deploys")).row("Where", server.to_string()));+ }+ if infra && w.iter().any(|x| DESTROY_WORDS.contains(&x.as_str())) {+ add(Floor::new(FloorKind::Destructive, format!("{slug} deletes or rebuilds something on {server}")).row("Data", "Can't be undone without a backup."));+ }+ }+ // SQL a database tool runs+ let mut texts = Vec::new();+ collect_strings(args, &mut texts, 0);+ if let Some(why) = texts.iter().find_map(|t| destructive_sql(t)) {+ add(Floor::new(FloorKind::Destructive, format!("{tool} runs {why}")).row("Data", "Can't be undone without a backup."));+ }+ // A shell an MCP server runs (a remote bash tool) is checked like Bash+ let tw = words(tool);+ if tw.iter().any(|x| matches!(x.as_str(), "bash" | "shell" | "exec" | "execute" | "command" | "terminal" | "run" | "ssh")) {+ for key in ["command", "cmd", "script"] {+ if let Some(f) = args[key].as_str().and_then(|c| shell_reason(c, ctx)) {+ add(f);+ }+ }+ }+ best+}++fn collect_strings(v: &Value, out: &mut Vec<String>, depth: usize) {+ if depth > 4 || out.len() > 50 {+ return;+ }+ match v {+ Value::String(s) => out.push(s.chars().take(20_000).collect()),+ Value::Object(m) => m.values().for_each(|x| collect_strings(x, out, depth + 1)),+ Value::Array(a) => a.iter().for_each(|x| collect_strings(x, out, depth + 1)),+ _ => {}+ }+}++/// A tool whose first action word is one of these only reads.+const READ_VERBS: &[&str] = &[+ "get", "list", "retrieve", "search", "find", "read", "fetch", "describe", "view", "show", "count", "lookup", "query", "inspect",+ "status", "info", "logs", "log", "whoami", "docs",+];++/// `snake_case`, `kebab-case` and `camelCase` words, lower-cased.+fn words(name: &str) -> Vec<String> {+ let mut out = Vec::new();+ let mut cur = String::new();+ let mut prev_lower = false;+ for c in name.chars() {+ if !c.is_alphanumeric() {+ if !cur.is_empty() {+ out.push(std::mem::take(&mut cur));+ }+ prev_lower = false;+ continue;+ }+ if c.is_uppercase() && prev_lower && !cur.is_empty() {+ out.push(std::mem::take(&mut cur));+ }+ prev_lower = c.is_lowercase() || c.is_ascii_digit();+ cur.extend(c.to_lowercase());+ }+ if !cur.is_empty() {+ out.push(cur);+ }+ out+}++/// SQL that drops, empties or rewrites data: `DROP TABLE|DATABASE|SCHEMA`, `TRUNCATE`,+/// `DELETE FROM` or `UPDATE … SET` with no `WHERE`, `ALTER TABLE … DROP`, and the Redis/Mongo+/// equivalents.+pub fn destructive_sql(text: &str) -> Option<String> {+ let lower = text.to_lowercase();+ let flat: String = lower.split_whitespace().collect::<Vec<_>>().join(" ");+ for (pat, what) in [+ ("drop table", "DROP TABLE"),+ ("drop database", "DROP DATABASE"),+ ("drop schema", "DROP SCHEMA"),+ ("drop collection", "DROP COLLECTION"),+ ("truncate table", "TRUNCATE"),+ ("flushall", "FLUSHALL"),+ ("flushdb", "FLUSHDB"),+ ("dropdatabase(", "dropDatabase()"),+ (".drop(", "a collection drop"),+ ("deletemany({})", "deleteMany({})"),+ ] {+ if flat.contains(pat) {+ return Some(what.to_string());+ }+ }+ if flat.contains("alter table") && flat.contains(" drop ") {+ return Some("ALTER TABLE … DROP".into());+ }+ if starts_sql(&flat, "truncate ") {+ return Some("TRUNCATE".into());+ }+ // DELETE FROM x and UPDATE x SET with no WHERE, statement by statement+ for stmt in flat.split(';') {+ if let Some(i) = stmt.find("delete from ") {+ if !stmt[i..].contains(" where ") {+ return Some("DELETE FROM with no WHERE".into());+ }+ }+ if update_without_where(stmt) {+ return Some("UPDATE with no WHERE".into());+ }+ }+ None+}++/// `UPDATE t SET …` with no `WHERE`. `UPDATE` must start the statement or a quoted argument+/// (`psql -c 'UPDATE t SET x=1'`) and `SET` follow the table, so prose such as "update the docs+/// and set a date" in a message doesn't count.+fn update_without_where(stmt: &str) -> bool {+ stmt.match_indices("update ").any(|(i, _)| {+ let before = stmt[..i].trim_end();+ let starts = before.is_empty() || matches!(before.as_bytes().last(), Some(b'\'' | b'"' | b'(' | b'`'));+ let mut rest = stmt[i + 7..].split_whitespace();+ let table = match rest.next() {+ Some("only") => rest.next(),+ t => t,+ };+ starts && table.is_some() && rest.next() == Some("set") && !stmt[i..].contains(" where ")+ })+}++fn starts_sql(flat: &str, kw: &str) -> bool {+ // A statement starts the text, follows a `;`, or opens a quoted argument (`-c 'TRUNCATE x'`)+ flat.split([';', '\'', '"']).any(|s| s.trim_start().starts_with(kw))+}++/// Why a shell command hits the floor, or `None`.+pub fn shell_reason(command: &str, ctx: &DevCtx) -> Option<Floor> {+ shell_reason_at(command, ctx, 0, false)+}++/// `over_ssh`: the command runs on another machine (`ssh host '…'`), where a compose `up` is a+/// deploy whatever the space's hint says.+fn shell_reason_at(command: &str, ctx: &DevCtx, depth: usize, over_ssh: bool) -> Option<Floor> {+ if depth > 3 {+ return None;+ }+ let mut best: Option<Floor> = None;+ let mut add = |f: Floor| best = Some(match best.take() { Some(b) => b.merge(f), None => f });+ let lower = command.to_lowercase();+ // SQL through a database client anywhere in the command+ if DB_CLIENTS.iter().any(|c| lower.split(|ch: char| !(ch.is_ascii_alphanumeric() || ch == '-' || ch == '_')).any(|w| w == *c)) {+ if let Some(why) = destructive_sql(command) {+ add(Floor::new(FloorKind::Destructive, format!("a database command that runs {why}")).row("Data", "Can't be undone without a backup."));+ }+ }+ let mut ssh_host: Option<String> = None;+ // A `git checkout`/`git switch` earlier in the chain changes what a bare `git push` pushes+ let mut cur = ctx.clone();+ // `ssh host 'cd /srv && docker compose up -d'`: the quoted remote command spans segments;+ // the quote still open after `ssh`, until it closes+ let mut ssh_quote: Option<char> = None;+ for segment in command.split([';', '&', '|', '\n', '(', ')', '`']) {+ let remote = ssh_quote.is_some();+ if let Some(q) = ssh_quote {+ if segment.matches(q).count() % 2 == 1 {+ ssh_quote = None;+ }+ }+ let over_ssh = over_ssh || remote;+ let words: Vec<String> = segment+ .split_whitespace()+ .map(|w| w.trim_matches(|c| c == '\'' || c == '"').to_string())+ .filter(|w| !w.is_empty())+ .collect();+ // Env assignments, and wrappers that run the rest of the line (with their own flags)+ let mut i = 0;+ let mut env_prod = false;+ while i < words.len() {+ let w = words[i].as_str();+ if w.contains('=') && !w.starts_with('-') {+ env_prod |= prod_env(w);+ i += 1;+ } else if let Some(n) = wrapper_len(w.trim_start_matches('\\'), &words[i + 1..]) {+ i = (i + n).min(words.len());+ } else {+ break;+ }+ }+ let Some((program, args)) = words[i..].split_first() else { continue };+ // `\git` skips aliases and still runs git+ let program = program.trim_start_matches('\\');+ let program = program.rsplit('/').next().unwrap_or(program).to_lowercase();+ let args: Vec<String> = args.to_vec();+ let a: Vec<&str> = args.iter().map(String::as_str).collect();+ // Wrappers that run another command: classify what they run+ match program.as_str() {+ "ssh" => {+ if let Some((host, rest)) = ssh_target(&a) {+ ssh_host = Some(host.clone());+ ssh_quote = ['\'', '"'].into_iter().find(|q| segment.matches(*q).count() % 2 == 1);+ if !rest.is_empty() {+ if let Some(f) = shell_reason_at(&rest.join(" "), ctx, depth + 1, true) {+ add(f.row("Where", host));+ }+ }+ }+ continue;+ }+ "bash" | "sh" | "zsh" | "dash" => {+ if let Some(p) = a.iter().position(|x| *x == "-c" || *x == "-lc") {+ if let Some(f) = shell_reason_at(&a[p + 1..].join(" "), &cur, depth + 1, over_ssh) {+ add(f);+ }+ } else if let Some(script) = first_operand(&a, &["-o", "+o", "-O", "+O"]) {+ if let Some(f) = script_reason(script, &cur) {+ add(f);+ }+ }+ continue;+ }+ "git" => {+ if let Some(head) = git_switches_to(&a, &cur) {+ cur.head_branch = head;+ continue;+ }+ }+ _ => {}+ }+ if let Some(f) = program_reason(&program, &a, &cur, env_prod, over_ssh) {+ add(f);+ }+ }+ best.map(|f| match ssh_host {+ Some(h) => f.row("Where", h),+ None => f,+ })+}++/// How many words a wrapper that runs the rest of the line takes (itself, its flags and their+/// values, and `timeout`'s duration), or `None` when `w` isn't one: `timeout 60 git push`,+/// `nice -n 10 …`, `sudo -u deploy …`, `watch -n1 '…'`, `eval '…'`.+fn wrapper_len(w: &str, rest: &[String]) -> Option<usize> {+ // Flags that take the next word as their value+ let takes: &[&str] = match w {+ "sudo" => &["-u", "-g", "-h", "-p", "-C", "-U", "-r", "-t", "-D", "--user", "--group", "--host", "--prompt", "--chdir"],+ "doas" => &["-u", "-C"],+ "env" => &["-u", "-C", "-S", "--unset", "--chdir", "--split-string"],+ "timeout" => &["-s", "-k", "--signal", "--kill-after"],+ "nice" => &["-n", "--adjustment"],+ "ionice" => &["-c", "-n", "-t", "--class", "--classdata"],+ "stdbuf" => &["-i", "-o", "-e", "--input", "--output", "--error"],+ "watch" => &["-n", "-q", "--interval", "--equexit"],+ "xargs" => &["-I", "-i", "-n", "-P", "-L", "-l", "-d", "-E", "-e", "-a", "-s", "--max-args", "--max-procs", "--max-lines", "--delimiter", "--arg-file", "--max-chars", "--replace"],+ "npx" | "pnpx" | "bunx" => &["-p", "--package", "-c", "--call"],+ "exec" => &["-a"],+ "time" => &["-f", "-o", "--format", "--output"],+ "setsid" | "nohup" | "command" | "eval" => &[],+ _ => return None,+ };+ let mut n = 1;+ while let Some(x) = rest.get(n - 1) {+ if !x.starts_with('-') || x == "-" {+ break;+ }+ n += if takes.contains(&x.as_str()) { 2 } else { 1 };+ if x == "--" {+ break;+ }+ }+ // `timeout [flags] DURATION command`+ if w == "timeout" && rest.get(n - 1).is_some_and(|d| d.starts_with(|c: char| c.is_ascii_digit() || c == '.')) {+ n += 1;+ }+ Some(n)+}++/// The first word that isn't a flag or a flag's value.+fn first_operand<'a>(a: &[&'a str], takes: &[&str]) -> Option<&'a str> {+ let mut i = 0;+ while let Some(x) = a.get(i) {+ if takes.contains(x) {+ i += 2;+ } else if x.starts_with('-') || x.starts_with('+') {+ i += 1;+ } else {+ return Some(x);+ }+ }+ None+}++/// The branch `git checkout`/`git switch` leaves checked out: `Some(Some(b))` when that's+/// certain, `Some(None)` when it can't be told (a bare `git push` then counts as protected), and+/// `None` when the command doesn't change branches. `git checkout x` may restore a file `x`, so it+/// only counts as a switch to `x` when `x` is protected; otherwise the branch becomes unknown.+fn git_switches_to(a: &[&str], ctx: &DevCtx) -> Option<Option<String>> {+ let mut i = 0;+ while i < a.len() && a[i].starts_with('-') {+ i += if matches!(a[i], "-C" | "-c" | "--git-dir" | "--work-tree") { 2 } else { 1 };+ }+ let sub = *a.get(i)?;+ if sub != "checkout" && sub != "switch" {+ return None;+ }+ let args = &a[i + 1..];+ let create: &[&str] = if sub == "checkout" { &["-b", "-B", "--orphan"] } else { &["-c", "-C", "--create", "--force-create", "--orphan"] };+ let mut pos: Vec<&str> = Vec::new();+ let mut j = 0;+ while let Some(x) = args.get(j) {+ if create.contains(x) {+ return Some(args.get(j + 1).map(|b| b.to_string()));+ }+ match *x {+ "--" => return Some(if sub == "checkout" { ctx.head_branch.clone() } else { None }),+ "--detach" | "-d" if sub == "switch" || *x == "--detach" => return Some(None),+ "-" => return Some(None),+ _ if x.starts_with('-') => {}+ _ => pos.push(x),+ }+ j += 1;+ }+ match (sub, pos.as_slice()) {+ // `git checkout`, `git switch` alone change nothing+ (_, []) => None,+ ("switch", [b, ..]) => Some(Some(b.to_string())),+ // `git checkout .` restores files+ ("checkout", ["."]) => None,+ ("checkout", [b]) if ctx.is_protected(b) => Some(Some(b.to_string())),+ // `git checkout x` (a branch or a file) or `git checkout ref -- paths`+ _ => Some(None),+ }+}++/// Database clients whose arguments may hold SQL.+const DB_CLIENTS: &[&str] = &["sqlite3", "sqlite", "psql", "mysql", "mariadb", "mongosh", "mongo", "redis-cli", "d1", "turso", "pgcli", "duckdb"];++/// `RAILS_ENV=production`, `NODE_ENV=production`, `DATABASE_URL=postgres://db.example.com/…`.+fn prod_env(assign: &str) -> bool {+ let Some((k, v)) = assign.split_once('=') else { return false };+ let v = v.trim_matches(|c| c == '\'' || c == '"').to_lowercase();+ let k = k.to_uppercase();+ if k.ends_with("_ENV") || k == "ENV" || k == "ENVIRONMENT" || k == "STAGE" {+ return matches!(v.as_str(), "production" | "prod" | "live");+ }+ if k.ends_with("DATABASE_URL") || k.ends_with("DB_URL") {+ return remote_url(&v);+ }+ false+}++/// A database URL that isn't on this machine.+fn remote_url(v: &str) -> bool {+ match url::Url::parse(v) {+ // A file database is on this machine+ Ok(u) if matches!(u.scheme(), "sqlite" | "file" | "sqlite3" | "duckdb") => false,+ Ok(u) => match u.host_str() {+ Some(h) => !matches!(h, "localhost" | "127.0.0.1" | "::1" | "[::1]" | "0.0.0.0") && !h.ends_with(".local"),+ None => false,+ },+ Err(_) => false,+ }+}++/// `ssh [options] host [command…]` → host and command words.+fn ssh_target<'a>(args: &[&'a str]) -> Option<(String, Vec<&'a str>)> {+ let mut i = 0;+ while i < args.len() {+ let a = args[i];+ if a.starts_with('-') {+ // Options that take a value+ let takes = matches!(a, "-p" | "-i" | "-l" | "-o" | "-F" | "-J" | "-L" | "-R" | "-D" | "-b" | "-c" | "-E" | "-e" | "-m" | "-O" | "-S" | "-W" | "-w" | "-B" | "-Q");+ i += if takes { 2 } else { 1 };+ continue;+ }+ let host = a.rsplit('@').next().unwrap_or(a).to_string();+ return Some((host, args[i + 1..].to_vec()));+ }+ None+}++/// A script file by its name: `./deploy.sh`, `scripts/release-prod.sh`.+fn script_reason(script: &str, ctx: &DevCtx) -> Option<Floor> {+ let name = script.rsplit('/').next().unwrap_or(script).to_lowercase();+ let ws = words(&name);+ ws.iter().any(|w| SHIP_WORDS.contains(&w.as_str())).then(|| ctx.deploy(format!("runs {script}, a deploy script")))+}++fn has(args: &[&str], x: &str) -> bool {+ args.contains(&x)+}++/// Positional arguments (not starting with `-`).+fn positional<'a>(args: &[&'a str]) -> Vec<&'a str> {+ args.iter().copied().filter(|a| !a.starts_with('-')).collect()+}++fn program_reason(program: &str, a: &[&str], ctx: &DevCtx, env_prod: bool, over_ssh: bool) -> Option<Floor> {+ let pos = positional(a);+ let sub = pos.first().copied().unwrap_or("");+ let sub2 = pos.get(1).copied().unwrap_or("");+ let destroy = |why: String| Floor::new(FloorKind::Destructive, why).row("Data", "Can't be undone without a backup.");+ // A script run by path+ if program.ends_with(".sh") || program.ends_with(".py") || program.ends_with(".rb") || program.ends_with(".js") {+ return script_reason(program, ctx);+ }+ // A script run by an interpreter is read by its name too: `python release.py`, `node deploy.js`+ if let Some(f) = interpreter_script(program, a).and_then(|s| script_reason(s, ctx)) {+ return Some(f);+ }+ match program {+ "git" => git_reason(a, ctx),+ "gh" => match (sub, sub2) {+ ("pr", "merge") => Some(+ Floor::new(FloorKind::PushMain, "gh pr merge lands a PR on its base branch").row("What changes", "The PR's commits land on the base branch."),+ ),+ ("workflow", "run") => {+ let name = pos.get(2).copied().unwrap_or("");+ ship_name(name).then(|| ctx.deploy(format!("starts the {name} workflow")))+ }+ ("release", "create") => Some(ctx.deploy("gh release create makes a release, which can start a deploy".into())),+ ("release", "delete") | ("repo", "delete") => Some(destroy(format!("gh {sub} delete removes it from GitHub"))),+ _ => None,+ },+ "fly" | "flyctl" => {+ let app = flag_value(a, &["-a", "--app"]);+ let f = match (sub, sub2) {+ ("deploy", _) | ("releases", "rollback") => Some(ctx.deploy(format!("{program} deploy ships the app"))),+ ("apps", "destroy") | ("volumes", "destroy") | ("volumes", "delete") | ("destroy", _) | ("postgres", "destroy") => {+ Some(destroy(format!("{program} {sub} {sub2} destroys it")))+ }+ ("machine", "destroy") | ("machines", "destroy") => Some(destroy(format!("{program} {sub} destroy removes a machine"))),+ ("secrets", "set") | ("secrets", "unset") => Some(Floor::new(FloorKind::Deploy, format!("{program} secrets {sub2} restarts the app"))),+ _ => None,+ }?;+ Some(match app {+ Some(app) => f.row("Where", format!("Fly app {app}")),+ None => f,+ })+ }+ "wrangler" => {+ let pages = sub == "pages";+ match (sub, sub2) {+ ("deploy", _) | ("publish", _) | ("pages", "deploy") | ("pages", "publish") | ("versions", "deploy") | ("rollback", _) => {+ // A Pages site holds no data; a Worker might (D1, KV, R2)+ let mut c = ctx.clone();+ if pages {+ c.deploy_hint = Some("cloudflare_pages".into());+ }+ Some(c.deploy(format!("wrangler {sub} ships to Cloudflare")))+ }+ ("d1", "execute") => {+ let sql = flag_value(a, &["--command"]).unwrap_or("");+ destructive_sql(sql).map(|w| destroy(format!("wrangler d1 execute runs {w}")))+ }+ ("d1", "delete") | ("r2", _) | ("kv", _) | ("delete", _) => {+ let removes = sub == "delete" || sub2 == "delete" || a.iter().any(|x| *x == "delete" || *x == "rm");+ removes.then(|| destroy(format!("wrangler {sub} {sub2} deletes data on Cloudflare")))+ }+ _ => None,+ }+ }+ "docker" | "docker-compose" | "podman" => docker_reason(program, a, ctx, over_ssh),+ "kubectl" | "oc" => match sub {+ "apply" | "rollout" | "set" | "replace" | "patch" | "scale" | "create" => Some(ctx.deploy(format!("{program} {sub} changes the cluster"))),+ "delete" | "drain" => Some(destroy(format!("{program} {sub} removes it from the cluster"))),+ _ => None,+ },+ "helm" => match sub {+ "install" | "upgrade" | "rollback" => Some(ctx.deploy(format!("helm {sub} changes the cluster"))),+ "uninstall" | "delete" => Some(destroy("helm uninstall removes a release".into())),+ _ => None,+ },+ "terraform" | "tofu" | "terragrunt" => match sub {+ "apply" => Some(if has(a, "-destroy") { destroy(format!("{program} apply -destroy removes infrastructure")) } else { ctx.deploy(format!("{program} apply changes infrastructure")) }),+ "destroy" => Some(destroy(format!("{program} destroy removes infrastructure"))),+ _ => None,+ },+ "pulumi" => match sub {+ "up" | "update" => Some(ctx.deploy("pulumi up changes infrastructure".into())),+ "destroy" => Some(destroy("pulumi destroy removes infrastructure".into())),+ _ => None,+ },+ "vercel" => (has(a, "--prod") || sub == "promote" || sub == "rollback" || (sub == "deploy" && has(a, "--prod"))).then(|| ctx.deploy("vercel ships to production".into())),+ "netlify" => (sub == "deploy" && has(a, "--prod")).then(|| ctx.deploy("netlify deploy --prod ships the site".into())),+ "firebase" => (sub == "deploy").then(|| ctx.deploy("firebase deploy ships the project".into())),+ "railway" => (sub == "up" || sub == "redeploy").then(|| ctx.deploy(format!("railway {sub} ships the app"))),+ "kamal" | "cap" | "mina" => (a.contains(&"deploy") || sub == "rollback").then(|| ctx.deploy(format!("{program} deploy ships the app"))),+ "serverless" | "sls" | "sst" | "cdk" | "amplify" | "eb" | "zappa" => (a.contains(&"deploy") || a.contains(&"publish")).then(|| ctx.deploy(format!("{program} deploy ships the app"))),+ "heroku" => match sub {+ "releases:rollback" | "container:release" | "restart" => Some(ctx.deploy(format!("heroku {sub} changes the running app"))),+ "pg:reset" | "apps:destroy" | "destroy" => Some(destroy(format!("heroku {sub} deletes data"))),+ _ => None,+ },+ "gcloud" => (a.contains(&"deploy")).then(|| ctx.deploy("gcloud … deploy ships the service".into())),+ "aws" => {+ if a.contains(&"deploy") || a.contains(&"update-service") || a.contains(&"update-function-code") {+ Some(ctx.deploy("aws … changes a running service".into()))+ } else if (sub == "s3" && (sub2 == "rb" || (sub2 == "rm" && has(a, "--recursive")))) || a.iter().any(|x| x.starts_with("delete-") || x.starts_with("terminate-")) {+ Some(destroy("an aws command that deletes resources or data".into()))+ } else {+ None+ }+ }+ "gsutil" => ((sub == "rm" && (has(a, "-r") || has(a, "-rf"))) || sub == "rb").then(|| destroy("gsutil deletes a bucket or its objects".into())),+ "make" | "just" | "task" | "mage" | "rake" => pos.iter().find(|t| ship_name(t)).map(|t| ctx.deploy(format!("{program} {t}"))),+ "npm" | "yarn" | "pnpm" | "bun" => {+ let script = if sub == "run" || sub == "run-script" { sub2 } else { sub };+ ship_name(script).then(|| ctx.deploy(format!("{program} runs the {script} script")))+ }+ "rm" | "shred" | "unlink" => rm_reason(program, a),+ "truncate" => a.iter().any(|x| is_db_file(x)).then(|| destroy("truncate empties a database file".into())),+ "dd" => a.iter().any(|x| x.starts_with("of=/dev/")).then(|| destroy("dd writes over a disk".into())),+ p if p.starts_with("mkfs") => Some(destroy(format!("{p} formats a disk"))),+ "dropdb" | "dropuser" => Some(destroy(format!("{program} deletes a database"))),+ "redis-cli" => a.iter().any(|x| x.eq_ignore_ascii_case("flushall") || x.eq_ignore_ascii_case("flushdb")).then(|| destroy("redis-cli empties the store".into())),+ // Migrations run against production+ _ if migrate_cmd(program, a) => (env_prod || a.iter().any(|x| is_prod_flag(x) || prod_env(x)) || flag_value(a, &["--settings"]).is_some_and(prod_settings))+ .then(|| Floor::new(FloorKind::DeployMigration, format!("{program} migrates a production database")).row("Migration", "Runs database migrations on production.")),+ _ => None,+ }+}++/// The script `python|node|ruby [flags] script.py …` runs (`python -m pkg` runs `pkg`); `None`+/// for `-c`/`-e` code or another program.+fn interpreter_script<'a>(program: &str, a: &[&'a str]) -> Option<&'a str> {+ let (takes, code): (&[&str], &[&str]) = if program.starts_with("python") && !program.contains('-') {+ (&["-W", "-X", "-Q"], &["-c"])+ } else if matches!(program, "node" | "nodejs") {+ (&["-r", "--require", "--import", "--loader", "--experimental-loader", "--env-file", "--conditions", "-C"], &["-e", "--eval", "-p", "--print"])+ } else if program == "ruby" {+ (&["-r", "-I", "-C", "-E", "--encoding"], &["-e"])+ } else {+ return None;+ };+ let mut i = 0;+ while let Some(x) = a.get(i) {+ if code.contains(x) {+ return None;+ }+ if *x == "-m" {+ return a.get(i + 1).copied();+ }+ if takes.contains(x) {+ i += 2;+ } else if x.starts_with('-') {+ i += 1;+ } else {+ return Some(x);+ }+ }+ None+}++/// A Django settings module for production: `app.settings.prod`, `settings_production`.+fn prod_settings(v: &str) -> bool {+ let last = v.rsplit(['.', '_', '-']).next().unwrap_or("").to_lowercase();+ matches!(last.as_str(), "prod" | "production" | "live")+}++fn ship_name(name: &str) -> bool {+ let ws = words(name);+ ws.iter().any(|w| SHIP_WORDS.contains(&w.as_str()))+}++fn flag_value<'a>(a: &[&'a str], names: &[&str]) -> Option<&'a str> {+ for (i, x) in a.iter().enumerate() {+ for n in names {+ if x == n {+ return a.get(i + 1).copied();+ }+ if let Some(v) = x.strip_prefix(&format!("{n}=")) {+ return Some(v);+ }+ }+ }+ None+}++fn is_prod_flag(x: &str) -> bool {+ let l = x.to_lowercase();+ matches!(l.as_str(), "--prod" | "--production" | "production" | "prod" | "-e=production" | "--env=production" | "--env=prod" | "--environment=production")+ || remote_url(&l)+}++fn migrate_cmd(program: &str, a: &[&str]) -> bool {+ let joined = a.join(" ").to_lowercase();+ match program {+ "sqlx" | "diesel" | "refinery" | "goose" | "migrate" | "dbmate" | "flyway" | "liquibase" | "atlas" => joined.contains("migrat") || joined.contains("up") || joined.contains("apply"),+ "rails" | "rake" | "bin/rails" => joined.contains("db:migrate") || joined.contains("db:schema:load"),+ "prisma" => joined.contains("migrate deploy") || joined.contains("db push"),+ "alembic" => joined.contains("upgrade") || joined.contains("downgrade"),+ "knex" => joined.contains("migrate:"),+ "python" | "python3" => joined.contains("manage.py migrate"),+ "php" => joined.contains("artisan migrate"),+ _ => false,+ }+}++fn is_db_file(x: &str) -> bool {+ let l = x.to_lowercase();+ l.ends_with(".db") || l.ends_with(".sqlite") || l.ends_with(".sqlite3") || l.ends_with(".db-wal")+}++/// `rm -r` of a place that holds data, or of a database file.+fn rm_reason(program: &str, a: &[&str]) -> Option<Floor> {+ let recursive = a.iter().any(|x| {+ x.starts_with('-') && !x.starts_with("--") && (x.contains('r') || x.contains('R')) || *x == "--recursive"+ });+ let targets = positional(a);+ let destroy = |what: &str| Some(Floor::new(FloorKind::Destructive, format!("{program} deletes {what}")).row("Data", "Can't be undone without a backup."));+ if let Some(t) = targets.iter().find(|t| is_db_file(t)) {+ return destroy(&format!("the database file {t}"));+ }+ if !recursive && program == "rm" {+ return None;+ }+ for t in &targets {+ let t = t.trim_end_matches('/');+ if matches!(t, "" | "/" | "/*" | "~" | "~/*" | "$HOME" | "${HOME}" | "*" | "." | "..") {+ return destroy(&format!("everything in {}", if t.is_empty() { "/" } else { t }));+ }+ let parts = words(t);+ if parts.iter().any(|p| DATA_WORDS.contains(&p.as_str())) && !t.contains("node_modules") && !t.starts_with("/tmp") && !t.contains("target") {+ return destroy(&format!("{t}, which looks like data"));+ }+ }+ None+}++/// `over_ssh`: run on another machine through `ssh`.+fn docker_reason(program: &str, a: &[&str], ctx: &DevCtx, over_ssh: bool) -> Option<Floor> {+ // docker's and compose's options that take a value: `--context prod`, `-f compose.prod.yml`+ const TAKES: &[&str] = &[+ "-H", "--host", "--context", "-c", "--config", "-l", "--log-level", "-f", "--file", "-p", "--project-name", "--profile", "--env-file",+ "--project-directory", "--ansi",+ ];+ let mut pos: Vec<&str> = Vec::new();+ let mut k = 0;+ while let Some(x) = a.get(k) {+ if TAKES.contains(x) {+ k += 2;+ continue;+ }+ if !x.starts_with('-') {+ pos.push(x);+ }+ k += 1;+ }+ let compose = program == "docker-compose" || pos.first() == Some(&"compose");+ let cmd: Vec<&str> = if compose && program != "docker-compose" { pos[1..].to_vec() } else { pos.clone() };+ let sub = cmd.first().copied().unwrap_or("");+ let destroy = |why: String| Floor::new(FloorKind::Destructive, why).row("Data", "Can't be undone without a backup.");+ let remote = flag_value(a, &["-H", "--host", "--context", "-c"]);+ let f = if compose {+ match sub {+ "down" if has(a, "-v") || has(a, "--volumes") => Some(destroy("docker compose down -v deletes the volumes".into())),+ // On a laptop compose is local dev: it ships only where the space deploys with Docker,+ // on another host (`-H`, `--context`) or over ssh (plan §3). down, stop, pull, rm and+ // create don't ship anything.+ "up" | "restart" if ctx.deploy_hint.as_deref() == Some("docker") || remote.is_some() || over_ssh => {+ Some(ctx.deploy(format!("docker compose {sub} changes running containers")).row("Downtime", "While the containers restart."))+ }+ _ => None,+ }+ } else {+ match (sub, cmd.get(1).copied().unwrap_or("")) {+ ("volume", "rm") | ("volume", "prune") => Some(destroy(format!("{program} volume {} deletes volumes", cmd[1]))),+ ("system", "prune") if has(a, "--volumes") => Some(destroy(format!("{program} system prune --volumes deletes volumes"))),+ ("rm", _) if has(a, "-v") || has(a, "--volumes") || has(a, "-fv") || has(a, "-vf") => Some(destroy(format!("{program} rm -v deletes a container's volumes"))),+ ("stack", "deploy") | ("service", "update") | ("service", "create") | ("service", "rollback") => Some(ctx.deploy(format!("{program} {sub} {} changes the swarm", cmd[1]))),+ ("stack", "rm") | ("service", "rm") => Some(destroy(format!("{program} {sub} rm removes it from the swarm"))),+ // Replacing a running container: rm -f, then run with a name or a restart policy+ ("run", _) if (flag_value(a, &["--name"]).is_some() && (flag_value(a, &["--restart"]).is_some() || has(a, "-d"))) || remote.is_some() => {+ Some(ctx.deploy(format!("{program} run starts a long-running container")).row("Downtime", "While the container restarts."))+ }+ ("rm", _) | ("stop", _) | ("restart", _) | ("kill", _) if remote.is_some() || has(a, "-f") || sub == "restart" => {+ Some(ctx.deploy(format!("{program} {sub} stops or replaces a running container")).row("Downtime", "While the container restarts."))+ }+ _ => None,+ }+ }?;+ Some(match remote {+ Some(r) => f.row("Where", r.to_string()),+ None => f,+ })+}++/// `git push` to a protected branch, a force-push, a ref deletion, a tag or a deploy remote.+fn git_reason(a: &[&str], ctx: &DevCtx) -> Option<Floor> {+ // Global options before the subcommand: -C dir, -c k=v+ let mut i = 0;+ while i < a.len() && a[i].starts_with('-') {+ i += if matches!(a[i], "-C" | "-c" | "--git-dir" | "--work-tree") { 2 } else { 1 };+ }+ if a.get(i) != Some(&"push") {+ return None;+ }+ let args = &a[i + 1..];+ let mut force = false;+ let mut delete = false;+ let mut all = false;+ let mut tags = false;+ let mut pos: Vec<&str> = Vec::new();+ let mut j = 0;+ while j < args.len() {+ let x = args[j];+ match x {+ "-f" | "--force" | "--force-if-includes" => force = true,+ _ if x.starts_with("--force-with-lease") => force = true,+ "-d" | "--delete" => delete = true,+ "--all" | "--branches" => all = true,+ "--mirror" => {+ all = true;+ force = true;+ delete = true;+ }+ "--tags" => tags = true,+ "-o" | "--push-option" | "--repo" | "--receive-pack" | "--exec" => j += 1,+ _ if x.starts_with('-') => {+ // Combined short flags: -uf+ if !x.starts_with("--") && x.contains('f') {+ force = true;+ }+ if !x.starts_with("--") && x.contains('d') {+ delete = true;+ }+ }+ _ => pos.push(x),+ }+ j += 1;+ }+ let remote = pos.first().copied();+ let refspecs: Vec<&str> = pos.iter().skip(1).copied().collect();+ let mut best: Option<Floor> = None;+ let mut add = |f: Floor| best = Some(match best.take() { Some(b) => b.merge(f), None => f });+ if let Some(r) = remote {+ if DEPLOY_REMOTES.contains(&r.to_lowercase().as_str()) {+ add(ctx.deploy(format!("git push {r} deploys the app")).row("Where", format!("the {r} remote")));+ }+ }+ if tags {+ add(ctx.deploy("git push --tags pushes tags, which can start a release".into()));+ }+ if all {+ add(Floor::new(if force { FloorKind::ForcePush } else { FloorKind::PushMain }, "git push --all pushes every branch, the protected ones too"));+ }+ // The branches this push writes, and how+ let mut targets: Vec<(String, bool, bool)> = Vec::new(); // (dst, force, delete)+ if refspecs.is_empty() && !all && !tags {+ // A bare push writes the checked-out branch; unknown counts as protected+ let head = ctx.head_branch.clone().unwrap_or_default();+ targets.push((head, force, delete));+ }+ for spec in refspecs {+ let plus = spec.starts_with('+');+ let spec = spec.trim_start_matches('+');+ let (src, dst) = match spec.split_once(':') {+ Some((s, d)) => (s, if d.is_empty() { s } else { d }),+ None => (spec, spec),+ };+ let del = delete || src.is_empty();+ let dst = if dst == "HEAD" || dst == "@" { ctx.head_branch.clone().unwrap_or_default() } else { dst.to_string() };+ targets.push((dst, force || plus, del));+ }+ for (dst, force, del) in targets {+ let tag = dst.starts_with("refs/tags/") || looks_like_version(&dst);+ let protected = dst.is_empty() || ctx.is_protected(&dst);+ let shown = if dst.is_empty() { "the checked-out branch (kwant can't tell which)".to_string() } else { dst.trim_start_matches("refs/heads/").to_string() };+ if del && (protected || tag) {+ add(Floor::new(FloorKind::DeleteRef, format!("git push deletes {shown} on the remote")).row("What changes", format!("{shown} is deleted on GitHub.")));+ } else if tag {+ add(ctx.deploy(format!("git push sends the tag {shown}, which can start a release")));+ } else if protected && force {+ add(Floor::new(FloorKind::ForcePush, format!("a force-push to {shown}")).row("What changes", format!("{shown} is rewritten; commits others have can be lost.")));+ } else if protected {+ add(Floor::new(FloorKind::PushMain, format!("git push to {shown}")).row("What changes", format!("New commits land on {shown}.")));+ }+ }+ best+}++fn looks_like_version(r: &str) -> bool {+ // `v0.7.0`, `0.7.0`; a branch like `release/0.7` isn't a tag+ if r.contains('/') {+ return false;+ }+ let r = r.strip_prefix('v').unwrap_or(r);+ let mut parts = r.split('.');+ parts.next().is_some_and(|p| !p.is_empty() && p.chars().all(|c| c.is_ascii_digit())) && parts.next().is_some_and(|p| p.chars().next().is_some_and(|c| c.is_ascii_digit()))+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ fn ctx() -> DevCtx {+ DevCtx { branch: "main".into(), head_branch: Some("lin-dev-core".into()), deploy_hint: Some("docker".into()), ..Default::default() }+ }++ fn kind(cmd: &str, c: &DevCtx) -> Option<FloorKind> {+ shell_reason(cmd, c).map(|f| f.kind)+ }++ fn req(server: &str, tool: &str, args: Value) -> ToolApprovalRequest {+ ToolApprovalRequest {+ kwant_id: "k".into(),+ kwant_name: "Demo".into(),+ turn_id: "t".into(),+ tool_name: format!("mcp__{server}__{tool}"),+ server: server.into(),+ tool: tool.into(),+ arguments: args,+ builtin: None,+ smart: None,+ payment: None,+ }+ }++ #[test]+ fn pushes_to_protected_branches_ask() {+ use FloorKind::*;+ let c = ctx();+ let table: &[(&str, Option<FloorKind>)] = &[+ ("git push origin main", Some(PushMain)),+ ("git push origin HEAD:main", Some(PushMain)),+ ("git push origin feature:refs/heads/main", Some(PushMain)),+ ("git push -u origin master", Some(PushMain)),+ ("git -C /srv/app push origin main", Some(PushMain)),+ ("cd app && git push origin main", Some(PushMain)),+ ("git push origin release/0.7", Some(PushMain)),+ ("git push origin gh-pages", Some(PushMain)),+ ("git push --all origin", Some(PushMain)),+ ("gh pr merge 301 --squash", Some(PushMain)),+ // Feature branches don't+ ("git push origin lin-dev-core", None),+ ("git push -u origin pixel-mobile-room", None),+ ("git push", None),+ ("git push origin", None),+ ("git push origin HEAD", None),+ ("git push origin mainline-fix", None),+ ("git status && git log -1", None),+ ("git pull origin main", None),+ ("git fetch origin main", None),+ ];+ for (cmd, want) in table {+ assert_eq!(kind(cmd, &c), *want, "{cmd}");+ }+ }++ #[test]+ fn a_bare_push_from_main_or_an_unknown_branch_asks() {+ let mut c = ctx();+ c.head_branch = Some("main".into());+ assert_eq!(kind("git push", &c), Some(FloorKind::PushMain));+ assert_eq!(kind("git push origin HEAD", &c), Some(FloorKind::PushMain));+ c.head_branch = None;+ assert_eq!(kind("git push", &c), Some(FloorKind::PushMain), "unknown counts as protected");+ let f = shell_reason("git push", &c).unwrap();+ assert!(f.why.contains("can't tell"), "{}", f.why);+ }++ #[test]+ fn the_watched_branch_and_extra_protected_ones_count() {+ let c = DevCtx { branch: "develop".into(), protected: vec!["staging".into()], head_branch: Some("x".into()), ..Default::default() };+ assert_eq!(kind("git push origin develop", &c), Some(FloorKind::PushMain));+ assert_eq!(kind("git push origin staging", &c), Some(FloorKind::PushMain));+ assert_eq!(kind("git push origin main", &c), Some(FloorKind::PushMain), "main is always protected");+ }++ #[test]+ fn force_pushes_and_deletions_of_protected_refs_ask() {+ use FloorKind::*;+ let c = ctx();+ let table: &[(&str, Option<FloorKind>)] = &[+ ("git push -f origin main", Some(ForcePush)),+ ("git push --force origin main", Some(ForcePush)),+ ("git push --force-with-lease origin main", Some(ForcePush)),+ ("git push --force-with-lease=main:abc origin main", Some(ForcePush)),+ ("git push origin +main", Some(ForcePush)),+ ("git push origin +HEAD:main", Some(ForcePush)),+ ("git push -uf origin main", Some(ForcePush)),+ ("git push --mirror", Some(ForcePush)),+ ("git push origin --delete main", Some(DeleteRef)),+ ("git push origin :main", Some(DeleteRef)),+ ("git push origin :refs/tags/mac-v0.6.12", Some(DeleteRef)),+ ("git push -d origin v0.6.12", Some(DeleteRef)),+ // A force-push or deletion of a feature branch is routine+ ("git push -f origin lin-dev-core", None),+ ("git push --force-with-lease origin pixel-dev-switch", None),+ ("git push origin --delete old-feature", None),+ ("git push origin :old-feature", None),+ ];+ for (cmd, want) in table {+ assert_eq!(kind(cmd, &c), *want, "{cmd}");+ }+ }++ #[test]+ fn deploys_ask_and_count_as_migrations_unless_known_otherwise() {+ use FloorKind::*;+ let c = ctx();+ let table: &[(&str, Option<FloorKind>)] = &[+ ("fly deploy", Some(DeployMigration)),+ ("flyctl deploy -a demo-app", Some(DeployMigration)),+ ("npx wrangler deploy", Some(DeployMigration)),+ ("wrangler pages deploy dist --project-name demo", Some(Deploy)),+ ("docker compose up -d", Some(DeployMigration)),+ ("docker compose -f compose.prod.yml pull && docker compose up -d --force-recreate", Some(DeployMigration)),+ ("docker-compose up -d", Some(DeployMigration)),+ ("docker stack deploy -c stack.yml demo", Some(DeployMigration)),+ ("docker run -d --name kwant-demo --restart unless-stopped demo:1", Some(DeployMigration)),+ ("docker rm -f kwant-demo", Some(DeployMigration)),+ ("kubectl apply -f k8s/", Some(DeployMigration)),+ ("helm upgrade demo ./chart", Some(DeployMigration)),+ ("terraform apply -auto-approve", Some(DeployMigration)),+ ("vercel --prod", Some(DeployMigration)),+ ("netlify deploy --prod", Some(DeployMigration)),+ ("firebase deploy", Some(DeployMigration)),+ ("gcloud run deploy demo --image x", Some(DeployMigration)),+ ("git push heroku main", Some(DeployMigration)),+ ("git push origin v0.7.0", Some(DeployMigration)),+ ("git push --tags", Some(DeployMigration)),+ ("gh workflow run deploy.yml", Some(DeployMigration)),+ ("gh release create v0.7.0", Some(DeployMigration)),+ ("make deploy", Some(DeployMigration)),+ ("npm run deploy:prod", Some(DeployMigration)),+ ("pnpm release", Some(DeployMigration)),+ ("./scripts/deploy.sh", Some(DeployMigration)),+ ("bash scripts/deploy-prod.sh", Some(DeployMigration)),+ ("bash -c 'fly deploy'", Some(DeployMigration)),+ ("sudo docker compose up -d", Some(DeployMigration)),+ // Building and testing isn't deploying+ ("docker build -t demo .", None),+ ("docker compose build", None),+ ("docker compose logs -f", None),+ ("docker ps", None),+ ("docker run --rm demo cargo test", None),+ ("npm run build", None),+ ("npm test", None),+ ("make test", None),+ ("vercel", None),+ ("netlify deploy", None),+ ("wrangler dev", None),+ ("kubectl get pods", None),+ ("terraform plan", None),+ ("fly status", None),+ ("fly logs -a demo-app", None),+ ("cargo build --release", None),+ ("gh pr create --fill", None),+ ("gh workflow run ci.yml", None),+ ];+ for (cmd, want) in table {+ assert_eq!(kind(cmd, &c), *want, "{cmd}");+ }+ }++ #[test]+ fn a_deploy_with_no_data_or_no_migration_is_plain() {+ let pages = DevCtx { deploy_hint: Some("cloudflare_pages".into()), ..ctx() };+ let f = shell_reason("npx wrangler deploy", &pages).unwrap();+ assert_eq!(f.kind, FloorKind::Deploy);+ assert!(!f.needs_backup);+ assert!(f.blast.iter().any(|(l, v)| l == "Data" && v.contains("Nothing to back up")));+ let known = DevCtx { migration: Some(false), ..ctx() };+ let f = shell_reason("fly deploy", &known).unwrap();+ assert_eq!(f.kind, FloorKind::Deploy);+ assert!(!f.needs_backup);+ let unknown = shell_reason("fly deploy", &ctx()).unwrap();+ assert!(unknown.needs_backup);+ assert!(unknown.blast.iter().any(|(l, v)| l == "Migration" && v.contains("can't tell")));+ }++ #[test]+ fn destructive_commands_need_a_backup() {+ use FloorKind::*;+ let c = ctx();+ let table: &[(&str, Option<FloorKind>)] = &[+ ("rm -rf /", Some(Destructive)),+ ("rm -rf ~", Some(Destructive)),+ ("rm -rf *", Some(Destructive)),+ ("rm -rf /srv/app/data", Some(Destructive)),+ ("rm -rf ./uploads/", Some(Destructive)),+ ("rm -r /var/lib/postgresql", Some(Destructive)),+ ("rm kwnt.db", Some(Destructive)),+ ("rm -f data/app.sqlite3", Some(Destructive)),+ ("docker volume rm kwant-data", Some(Destructive)),+ ("docker volume prune -f", Some(Destructive)),+ ("docker compose down -v", Some(Destructive)),+ ("docker system prune -a --volumes", Some(Destructive)),+ ("sqlite3 kwnt.db 'DROP TABLE tasks'", Some(Destructive)),+ ("sqlite3 kwnt.db \"delete from tasks\"", Some(Destructive)),+ ("psql $DATABASE_URL -c 'TRUNCATE users'", Some(Destructive)),+ ("docker exec db psql -c 'drop database app'", Some(Destructive)),+ ("mysql -e 'ALTER TABLE users DROP COLUMN email'", Some(Destructive)),+ ("redis-cli FLUSHALL", Some(Destructive)),+ ("dropdb app", Some(Destructive)),+ ("kubectl delete namespace prod", Some(Destructive)),+ ("terraform destroy", Some(Destructive)),+ ("fly apps destroy demo-app", Some(Destructive)),+ ("fly volumes destroy vol_123", Some(Destructive)),+ ("aws s3 rm s3://demo-bucket --recursive", Some(Destructive)),+ ("gh repo delete demo-org/demo", Some(Destructive)),+ ("ssh [email protected] 'rm -rf /srv/kwant/data'", Some(Destructive)),+ ("dd if=/dev/zero of=/dev/sda", Some(Destructive)),+ ("RAILS_ENV=production rails db:migrate", Some(DeployMigration)),+ ("DATABASE_URL=postgres://db.example.com/app sqlx migrate run", Some(DeployMigration)),+ // Everyday clean-ups and reads don't+ ("rm -rf target", None),+ ("rm -rf node_modules dist", None),+ ("rm -rf /tmp/build-data", None),+ ("rm notes.txt", None),+ ("rm -f src/old.rs", None),+ ("sqlite3 kwnt.db 'select count(*) from tasks'", None),+ ("sqlite3 kwnt.db \"delete from tasks where id = 'x'\"", None),+ ("grep -rn 'DROP TABLE' src", None),+ ("sqlx migrate run", None),+ ("DATABASE_URL=sqlite://./dev.db sqlx migrate run", None),+ ("cargo test -j 3 db::dev_mode", None),+ // F8: down only stops local containers+ ("docker compose down", None),+ ];+ for (cmd, want) in table {+ assert_eq!(kind(cmd, &c), *want, "{cmd}");+ }+ assert!(shell_reason("rm -rf /srv/app/data", &c).unwrap().needs_backup);+ }++ #[test]+ fn the_strongest_kind_wins_and_rows_are_kept() {+ let f = shell_reason("git push origin main && fly deploy -a demo-app", &ctx()).unwrap();+ assert_eq!(f.kind, FloorKind::DeployMigration);+ assert!(f.blast.iter().any(|(l, v)| l == "Where" && v == "Fly app demo-app"));+ assert!(f.blast.iter().any(|(l, _)| l == "What changes"));+ let f = shell_reason("ssh [email protected] docker compose up -d", &ctx()).unwrap();+ assert!(f.blast.iter().any(|(l, v)| l == "Where" && v == "kwant.example.com"), "{:?}", f.blast);+ }++ #[test]+ fn claude_bash_and_local_shell_go_through_the_shell_rules() {+ let c = ctx();+ let mut r = req("claude", "Bash", json!({"command": "fly deploy"}));+ r.builtin = Some(crate::mcp::BuiltinCall { cwd: None, outside_folder: false });+ assert_eq!(reason(&r, &c).map(|f| f.kind), Some(FloorKind::DeployMigration));+ let r = req("local", "execute_shell", json!({"command": "git push -f origin main"}));+ assert_eq!(reason(&r, &c).map(|f| f.kind), Some(FloorKind::ForcePush));+ let mut r = req("claude", "Write", json!({"file_path": "deploy.sh", "content": "fly deploy"}));+ r.builtin = Some(crate::mcp::BuiltinCall { cwd: None, outside_folder: false });+ assert_eq!(reason(&r, &c), None, "writing a script isn't running it");+ }++ #[test]+ fn mcp_deploy_and_destroy_tools_ask() {+ let c = ctx();+ let k = |server: &str, tool: &str, args: Value| reason(&req(server, tool, args), &c).map(|f| f.kind);+ assert_eq!(k("cloudflare", "workers_deploy", json!({})), Some(FloorKind::DeployMigration));+ assert_eq!(k("vercel", "deploy_to_vercel", json!({})), Some(FloorKind::DeployMigration));+ assert_eq!(k("digitalocean-droplets", "droplet-delete", json!({"id": 1})), Some(FloorKind::Destructive));+ assert_eq!(k("digitalocean-droplets", "rebuild-droplet", json!({"id": 1})), Some(FloorKind::Destructive));+ assert_eq!(k("supabase", "execute_sql", json!({"query": "DROP TABLE users"})), Some(FloorKind::Destructive));+ assert_eq!(k("composio", "COMPOSIO_REMOTE_BASH_TOOL", json!({"command": "fly deploy"})), Some(FloorKind::DeployMigration));+ // Reads and unrelated writes don't+ assert_eq!(k("digitalocean-droplets", "droplet-list", json!({})), None);+ assert_eq!(k("cloudflare", "search", json!({"query": "delete worker"})), None);+ assert_eq!(k("supabase", "execute_sql", json!({"query": "select * from users"})), None);+ assert_eq!(k("slack", "delete_message", json!({})), None);+ assert_eq!(k("github", "create_issue", json!({})), None);+ assert_eq!(k("notion", "publish_page", json!({})), None);+ }++ #[test]+ fn production_connections_always_ask() {+ let c = DevCtx { prod_connections: vec!["digitalocean-droplets".into(), "stripe".into()], ..ctx() };+ let f = reason(&req("digitalocean-droplets", "droplet-list", json!({})), &c).unwrap();+ assert_eq!(f.kind, FloorKind::ProdKey);+ assert!(!f.needs_backup);+ assert!(f.blast.iter().any(|(l, v)| l == "Key used" && v == "digitalocean-droplets · production"));+ // Composio: the toolkit is the slug's first word+ let f = reason(&req("composio", "COMPOSIO_MULTI_EXECUTE_TOOL", json!({"tools": [{"tool_slug": "STRIPE_CREATE_REFUND"}]})), &c).unwrap();+ assert_eq!(f.kind, FloorKind::ProdKey);+ // A destructive call through a production key keeps the stronger kind and the key row+ let f = reason(&req("digitalocean-droplets", "droplet-delete", json!({})), &c).unwrap();+ assert_eq!(f.kind, FloorKind::Destructive);+ assert!(f.blast.iter().any(|(l, _)| l == "Key used"));+ // Not marked: no card+ assert_eq!(reason(&req("github", "list_issues", json!({})), &c), None);+ }++ #[test]+ fn the_payload_serialises_as_the_contract_says() {+ let f = shell_reason("rm -rf /srv/app/data", &ctx()).unwrap();+ let v = serde_json::to_value(&f).unwrap();+ assert_eq!(v["kind"], "destructive");+ assert_eq!(v["needs_backup"], true);+ assert_eq!(v["blast"][0][0], "Data");+ for k in [FloorKind::PushMain, FloorKind::ForcePush, FloorKind::DeleteRef, FloorKind::Deploy, FloorKind::DeployMigration, FloorKind::ProdKey] {+ let s = serde_json::to_value(k).unwrap();+ assert!(s.as_str().unwrap().chars().all(|c| c.is_ascii_lowercase() || c == '_'));+ }+ assert!(FloorKind::Destructive.needs_backup() && FloorKind::DeployMigration.needs_backup());+ assert!(!FloorKind::Deploy.needs_backup() && !FloorKind::PushMain.needs_backup() && !FloorKind::ProdKey.needs_backup());+ }++ #[test]+ fn destructive_sql_reads_the_statement() {+ assert!(destructive_sql("DROP TABLE x").is_some());+ assert!(destructive_sql("drop table x").is_some());+ assert!(destructive_sql("TRUNCATE users").is_some());+ assert!(destructive_sql("delete from t; select 1").is_some());+ assert!(destructive_sql("DELETE FROM t WHERE id=1").is_none());+ assert!(destructive_sql("select * from drops").is_none());+ assert!(destructive_sql("db.users.deleteMany({})").is_some());+ assert!(destructive_sql("insert into t values (1)").is_none());+ }++ /// F4 (Rigel, #313): `UPDATE … SET` with no `WHERE` rewrites every row.+ #[test]+ fn update_with_no_where_is_destructive() {+ use FloorKind::*;+ let c = ctx();+ for (cmd, want) in [+ ("psql -c 'UPDATE users SET admin=1'", Some(Destructive)),+ ("sqlite3 app.db \"UPDATE t SET x=1\"", Some(Destructive)),+ ("psql -c 'BEGIN; update only accounts set balance = 0; COMMIT'", Some(Destructive)),+ ("mysql -e \"UPDATE users SET admin=1 WHERE id=7\"", None),+ ("sqlite3 app.db \"update t set x='a b' where id = 1\"", None),+ ("psql -c 'select last_update from t'", None),+ ] {+ assert_eq!(kind(cmd, &c), want, "{cmd}");+ }+ assert_eq!(destructive_sql("UPDATE users SET plan = 'free'").as_deref(), Some("UPDATE with no WHERE"));+ // Prose in a message an MCP tool sends isn't SQL+ assert!(destructive_sql("Please update the docs and set a date for the release").is_none());+ assert!(destructive_sql("We'll update everything set up last week").is_none());+ }++ /// F5: a `git checkout`/`git switch` earlier in the chain changes what a bare push pushes.+ #[test]+ fn a_checkout_earlier_in_the_chain_moves_the_head() {+ use FloorKind::*;+ let c = DevCtx { head_branch: Some("feature/x".into()), ..ctx() };+ for (cmd, want) in [+ ("git checkout main && git merge feature/x && git push", Some(PushMain)),+ ("git switch main; git push", Some(PushMain)),+ ("git -C . checkout release/1.2 && git push origin", Some(PushMain)),+ ("git checkout -b feature/deploy && git push", None),+ ("git switch -c feature/y && git push", None),+ ("git checkout -- src/main.rs && git push", None),+ ("git checkout . && git push", None),+ // A branch or a file: can't be told, so the push counts as protected+ ("git checkout other && git push", Some(PushMain)),+ ("git switch --detach v1.0 && git push", Some(PushMain)),+ ("git checkout - && git push", Some(PushMain)),+ ("git push && git checkout main", None),+ ] {+ assert_eq!(kind(cmd, &c), want, "{cmd}");+ }+ }++ /// F6: wrappers that run the rest of the line, with their own flags and values.+ #[test]+ fn wrappers_with_flags_are_read_through() {+ use FloorKind::*;+ let c = DevCtx { head_branch: Some("feature/x".into()), ..ctx() };+ for cmd in [+ "timeout 60 git push origin main",+ "timeout 10 git push origin main",+ "timeout -k 5 -s TERM 1m git push origin main",+ "nice git push origin main",+ "nice -n 10 git push origin main",+ "ionice -c3 git push origin main",+ "ionice -c 2 -n 7 git push origin main",+ "stdbuf -oL git push origin main",+ "setsid git push origin main",+ "watch -n1 'git push origin main'",+ "xargs -n 1 git push origin main",+ "eval 'git push origin main'",+ "eval \"git push origin main\"",+ "sudo -u deploy -E git push origin main",+ "env -u GIT_DIR git push origin main",+ "\\git push origin main",+ "nohup nice -n 5 timeout 30 git push origin main",+ ] {+ assert_eq!(kind(cmd, &c), Some(PushMain), "{cmd}");+ }+ assert_eq!(kind("timeout 60 fly deploy", &c), Some(DeployMigration));+ assert_eq!(kind("timeout 60 git push origin feature/x", &c), None);+ assert_eq!(kind("nice -n 10 cargo -j 2 test", &c), None);+ // A wrapper with nothing after it+ assert_eq!(kind("sudo -u", &c), None);+ assert_eq!(kind("timeout", &c), None);+ }++ /// F7: a script an interpreter runs is read by its name, like `./deploy.sh`.+ #[test]+ fn interpreter_scripts_are_read_by_name() {+ use FloorKind::*;+ let c = ctx();+ for (cmd, want) in [+ ("python release.py", Some(DeployMigration)),+ ("python3 deploy.py --env prod", Some(DeployMigration)),+ ("python3 -u scripts/ship_it.py", Some(DeployMigration)),+ ("node deploy.js", Some(DeployMigration)),+ ("node --require dotenv/config scripts/release.mjs", Some(DeployMigration)),+ ("ruby deploy.rb", Some(DeployMigration)),+ ("bash -x deploy.sh", Some(DeployMigration)),+ ("sh -o errexit scripts/release.sh", Some(DeployMigration)),+ ("python3 script.py", None),+ ("node build.js", None),+ ("python -c 'import sys' deploy.py", None),+ ("node -e 'console.log(1)'", None),+ ("python3 -m http.server 9481", None),+ ("python3 manage.py runserver", None),+ ("bash -x build.sh", None),+ ] {+ assert_eq!(kind(cmd, &c), want, "{cmd}");+ }+ // Not a deploy script: the migration rules still read it+ assert_eq!(kind("python manage.py migrate --settings=app.prod", &c), Some(DeployMigration));+ }++ /// F8: compose ships only where the space deploys with Docker, on another host, or over ssh.+ #[test]+ fn compose_ships_only_where_the_space_deploys_with_docker() {+ use FloorKind::*;+ let docker = ctx();+ let none = DevCtx { deploy_hint: None, ..ctx() };+ let fly = DevCtx { deploy_hint: Some("fly".into()), ..ctx() };+ for sub in ["down", "stop", "pull", "rm -f", "create", "build", "logs -f", "ps"] {+ for c in [&docker, &none] {+ assert_eq!(kind(&format!("docker compose {sub}"), c), None, "compose {sub} {:?}", c.deploy_hint);+ assert_eq!(kind(&format!("docker-compose {sub}"), c), None, "docker-compose {sub}");+ }+ }+ for cmd in ["docker compose up -d", "docker-compose up -d", "docker compose restart web"] {+ assert_eq!(kind(cmd, &docker), Some(DeployMigration), "{cmd}");+ assert_eq!(kind(cmd, &none), None, "{cmd}");+ assert_eq!(kind(cmd, &fly), None, "{cmd}");+ }+ // Another host or over ssh ships whatever the hint+ assert_eq!(kind("docker --context prod compose up -d", &none), Some(DeployMigration));+ assert_eq!(kind("ssh prod 'docker compose up -d'", &none), Some(DeployMigration));+ assert_eq!(kind("ssh [email protected] 'cd /srv/app && docker compose up -d'", &none), Some(DeployMigration));+ // Deleting volumes is destructive anywhere+ for c in [&docker, &none] {+ assert_eq!(kind("docker compose down -v", c), Some(Destructive));+ assert_eq!(kind("docker-compose down --volumes", c), Some(Destructive));+ }+ }++ /// F9: `RAILS_ENV=production` and `--settings=…prod` after the command.+ #[test]+ fn trailing_production_env_and_settings_migrate_production() {+ use FloorKind::*;+ let c = ctx();+ for (cmd, want) in [+ ("rails db:migrate RAILS_ENV=production", Some(DeployMigration)),+ ("bin/rails db:migrate RAILS_ENV=production", Some(DeployMigration)),+ ("RAILS_ENV=production rails db:migrate", Some(DeployMigration)),+ ("python manage.py migrate --settings=app.prod", Some(DeployMigration)),+ ("python3 manage.py migrate --settings app.settings.production", Some(DeployMigration)),+ ("python manage.py migrate --settings=config.settings_production", Some(DeployMigration)),+ ("rails db:migrate", None),+ ("rails db:migrate RAILS_ENV=development", None),+ ("python manage.py migrate", None),+ ("python manage.py migrate --settings=app.dev", None),+ ("python manage.py migrate --settings=app.products", None),+ ] {+ assert_eq!(kind(cmd, &c), want, "{cmd}");+ }+ }+}diff --git a/src/server/auth.rs b/src/server/auth.rsindex 71f618d2..724e606b 100644--- a/src/server/auth.rs+++ b/src/server/auth.rs@@ -365,6 +365,10 @@ pub fn person_only(method: &Method, path: &str) -> bool {// person's; the status stays readable["", "api", "app", "update", ..] => *method != Method::GET && *method != Method::HEAD,["", "api", "approvals", _, "resolve"] => *method == Method::POST,+ // Dev mode (0.7): the watched repo, its cards, Fix it and Dismiss, release notes and the+ // backup command are the person's; bots never read the desk either (D3)+ ["", "api", "spaces", _, "dev_mode" | "dev", ..] => true,+ ["", "api", "dev", ..] => true,["", "api", "spaces" | "kwants", _, "approvals"] => *method != Method::GET && *method != Method::HEAD,// A team's instructions go into every member's prompt (PUT and PATCH both set them), and a// channel's PATCH sets its instructions and members: bots change these through their@@ -877,6 +881,22 @@ mod tests {assert!(person_only(&post, "/api/sandbox/t1/interact"));assert!(!person_only(&post, "/api/sandbox/t1/act"));assert!(person_only(&get, "/api/passwords/store"));+ for (m, p) in [+ (&get, "/api/spaces/s1/dev_mode"),+ (&put, "/api/spaces/s1/dev_mode"),+ (&post, "/api/spaces/s1/dev_mode/check"),+ (&get, "/api/spaces/s1/dev/landed?before=2026-11-05T00:00:00Z"),+ (&post, "/api/spaces/s1/dev/landed/seen"),+ (&get, "/api/spaces/s1/dev/reviews"),+ (&post, "/api/spaces/s1/dev/release_notes"),+ (&post, "/api/spaces/s1/dev/backup"),+ (&get, "/api/dev/cards/dvc_1"),+ (&post, "/api/dev/cards/dvc_1/findings/f1"),+ (&Method::HEAD, "/api/spaces/s1/dev/reviews"),+ ] {+ assert!(person_only(m, p), "{m} {p}");+ }+ assert!(!person_only(&get, "/api/spaces/s1/developers"));assert!(person_only(&post, "/api/messages/m1/decisions/0/change"));assert!(person_only(&put, "/api/messages/m1/reaction"));assert!(person_only(&post, "/api/messages/m1/reaction"));diff --git a/src/server/computer.rs b/src/server/computer.rsindex 2c72ab5d..5a0a44d7 100644--- a/src/server/computer.rs+++ b/src/server/computer.rs@@ -206,11 +206,17 @@ pub async fn approve_local_shell_in(Some(_) => None,None => super::missions::flight_school::shell_gate(&state.db, target_id).await,};- if let Some(why) = tier {+ if let Some(why) = &tier {details["tier_reason"] = json!(why);}+ // The production floor (plan §3.5): in a Dev mode space, a command that can reach production+ // always asks, and "always allow" covers this one command+ let floor = super::dev::floor::for_shell(&state.db, target_id, command, cwd).await;+ if let Some((_, card)) = &floor {+ details["prod_floor"] = card.clone();+ }// "Always this session" under smart: per bot and conversation, like claude's tools- let remembered = conversation.filter(|_| mode == SMART && payment.is_none());+ let remembered = conversation.filter(|_| mode == SMART && payment.is_none() && floor.is_none());if crate::sandbox::credentials::call_touches_kwnt_secrets(&details["arguments"], Some(cwd)) {tracing::warn!(target = %target_id, "refused a shell command that names kwnt's secret files");let record = NewApproval {@@ -229,7 +235,7 @@ pub async fn approve_local_shell_in(return true;}}- if payment.is_none() && tier.is_none() && (mode == OFF || verdict.as_ref().is_some_and(|v| v.is_allowed())) {+ if payment.is_none() && tier.is_none() && floor.is_none() && (mode == OFF || verdict.as_ref().is_some_and(|v| v.is_allowed())) {if verdict.is_some() {tracing::info!(target = %target_id, "ran a local command without a card: not risky");}diff --git a/src/server/connections.rs b/src/server/connections.rsindex 6de9b0ca..b7a5e794 100644--- a/src/server/connections.rs+++ b/src/server/connections.rs@@ -65,6 +65,9 @@ pub struct Connection {pub logins_stored: &'static str,/// The API that manages it.pub manage: String,+ /// The person marked it production (D10): in a Dev mode space every call through it gets the+ /// production floor's card. Only MCP servers (and Composio apps, by toolkit slug) can be.+ pub production: bool,}// Last MCP test results (POST /api/mcp/servers/:id/test), kept in memory@@ -165,6 +168,7 @@ async fn mcp_connections(state: &AppState, space: &SpaceId, kwants: &[Kwant]) ->used_by: used(&users),logins_stored: if is_composio(s) { "composio" } else { "kwnt" },manage: format!("/api/mcp/servers/{}", s.id),+ production: false,}}).collect()@@ -243,6 +247,7 @@ async fn account_connections(state: &AppState, space: &SpaceId, kwants: &[Kwant]used_by: users.get(&p.id).cloned().unwrap_or_default(),logins_stored: "kwnt",manage: format!("/api/profiles/{}", p.id),+ production: false,}}).collect()@@ -285,6 +290,7 @@ async fn login_connections(state: &AppState, space: &SpaceId, kwants: &[Kwant])used_by: used(&users),logins_stored: "vault",manage: format!("/api/sandbox/{owner}/passwords"),+ production: false,});}}@@ -331,6 +337,7 @@ async fn source_connections(state: &AppState, space: &SpaceId) -> Vec<Connectionused_by: users.clone(),logins_stored: "vault",manage: format!("/api/zombie/sources/{}", s.id),+ production: false,})}).collect()@@ -390,6 +397,10 @@ pub async fn list(State(state): State<AppState>, headers: HeaderMap, Scope(space}};connections.extend(source_connections(&state, &space).await);+ let marked = state.db.prod_connections(space.as_str()).await.unwrap_or_default();+ for c in connections.iter_mut() {+ c.production = marked.contains(&c.id);+ }let servers = state.db.list_mcp_servers(&space).await.unwrap_or_default();let mut counts: BTreeMap<&str, usize> = BTreeMap::new();for c in &connections {@@ -400,10 +411,56 @@ pub async fn list(State(state): State<AppState>, headers: HeaderMap, Scope(space"counts": counts,"vault": vault,"catalog": catalog(&servers),+ // Composio apps marked production by toolkit slug (D10), as `composio:<slug>`+ "production": marked.iter().filter(|m| m.starts_with("composio:")).collect::<Vec<_>>(),})).into_response()}+#[derive(Debug, Deserialize)]+pub struct ProductionBody {+ pub production: bool,+}++/// Whether a connection id can carry the production mark: an MCP server of the space, or a+/// Composio toolkit slug (`composio:github`). Accounts, logins and Loose ends sources can't.+pub fn production_target(id: &str, servers: &[McpServer]) -> Result<(), &'static str> {+ if let Some(sid) = id.strip_prefix("mcp:") {+ return if servers.iter().any(|s| s.id == sid) { Ok(()) } else { Err("No such MCP server in this space") };+ }+ if let Some(slug) = id.strip_prefix("composio:") {+ let ok = !slug.is_empty() && slug.len() <= 64 && slug.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_' || c == '-');+ return if ok { Ok(()) } else { Err("A Composio app is named by its toolkit slug, like composio:github") };+ }+ Err("Only MCP servers and Composio apps can be marked production")+}++/// `PUT /api/connections/:id/production?space=` `{production}`: the person marks a connection+/// production (D10), or clears the mark. Replies `{id, production}`.+pub async fn put_production(+ State(state): State<AppState>,+ headers: HeaderMap,+ Scope(space): Scope,+ axum::extract::Path(id): axum::extract::Path<String>,+ Json(body): Json<ProductionBody>,+) -> Response {+ if let Err(r) = refuse_agent_tokens(&state, &headers, REFUSAL).await {+ return r;+ }+ let servers = state.db.list_mcp_servers(&space).await.unwrap_or_default();+ // Clearing a mark always works, so a server deleted since can be unmarked+ if body.production {+ if let Err(why) = production_target(&id, &servers) {+ return error(StatusCode::BAD_REQUEST, why);+ }+ }+ if let Err(e) = state.db.set_prod_connection(space.as_str(), &id, body.production).await {+ tracing::warn!(error = %e, "connections: could not save the production mark");+ return error(StatusCode::INTERNAL_SERVER_ERROR, "The production mark could not be saved");+ }+ Json(json!({"id": id, "production": body.production})).into_response()+}+#[derive(Debug, Deserialize)]pub struct ComposioBody {/// The MCP URL Composio gives for the person's server, `https://….composio.dev/…`.@@ -613,6 +670,19 @@ mod tests {}}+ #[test]+ fn only_mcp_servers_and_composio_slugs_can_be_marked_production() {+ assert!(production_target("composio:github", &[]).is_ok());+ assert!(production_target("composio:google_sheets", &[]).is_ok());+ assert!(production_target("composio:", &[]).is_err());+ assert!(production_target("composio:GitHub", &[]).is_err());+ assert!(production_target("composio:../x", &[]).is_err());+ assert!(production_target(&format!("composio:{}", "a".repeat(65)), &[]).is_err());+ assert!(production_target("mcp:srv_gone", &[]).is_err(), "a server not in this space");+ assert!(production_target("account:p1", &[]).is_err());+ assert!(production_target("telegram", &[]).is_err());+ }+#[test]fn composio_urls_are_https_on_composio_dev_only() {assert!(is_composio_url("https://backend.composio.dev/v3/mcp/abc/mcp?user_id=u"));diff --git a/src/server/dev/backup.rs b/src/server/dev/backup.rsnew file mode 100644index 00000000..b9182a6e--- /dev/null+++ b/src/server/dev/backup.rs@@ -0,0 +1,478 @@+//! Backups for the production floor (D9). The person sets a backup command in Dev mode settings;+//! **Back up first** runs it in the bot's folder through the normal shell path (never gated by the+//! floor: the person wrote it) and records the path, size and time it printed, checked against+//! the file on disk when the path is local. A step that `needs_backup` is refused Allow until an+//! `ok` backup is at most [`FRESH_SECS`] old.++use crate::db::dev_mode::DevBackupRow;+use crate::db::spaces::SpaceId;+use crate::server::AppState;+use chrono::{DateTime, Utc};+use serde_json::{json, Value};+use std::collections::HashSet;+use std::path::{Path, PathBuf};+use std::sync::Mutex;+use std::time::{Duration, SystemTime};++/// An `ok` backup younger than this lets a step that needs one through.+pub const FRESH_SECS: i64 = 600;+/// The longest a backup command may run.+pub const TIMEOUT_SECS: u64 = 600;+/// How much of the command's output an error keeps.+const ERROR_CHARS: usize = 400;+/// A local backup file may be dated this much before the command started (coarse file-system+/// clocks, a dump that opened its file a moment early).+pub const MTIME_SLACK: Duration = Duration::from_secs(5);+/// The error when exit 0 is all there is to go on.+pub const NOTHING_NAMED: &str = "kwant couldn't find a backup file in the output";++static RUNNING: Mutex<Option<HashSet<String>>> = Mutex::new(None);++/// Whether a backup is running in the space now (the card's `taking`).+pub fn is_running(space_id: &str) -> bool {+ RUNNING.lock().unwrap().as_ref().is_some_and(|s| s.contains(space_id))+}++/// A space's running backup. Dropping it frees the space, however the run ends: done, failed,+/// panicked or cancelled.+struct Claim(String);++impl Claim {+ fn take(space_id: &str) -> Option<Claim> {+ RUNNING.lock().unwrap().get_or_insert_with(HashSet::new).insert(space_id.to_string()).then(|| Claim(space_id.to_string()))+ }+}++impl Drop for Claim {+ fn drop(&mut self) {+ if let Some(s) = RUNNING.lock().unwrap_or_else(|e| e.into_inner()).as_mut() {+ s.remove(&self.0);+ }+ }+}++#[derive(Debug)]+pub enum BackupError {+ NoCommand,+ Busy,+ Db(crate::db::DbError),+ /// The run's task ended without an answer (it panicked).+ Lost(String),+}++/// The folder the command runs in: the bot's own folder when a bot's card asked for it, else the+/// space's shared folder.+pub fn folder(state: &AppState, space: &SpaceId, kwant_id: Option<&str>) -> PathBuf {+ let dir = crate::db::spaces::space_data_dir(&state.config.data_dir, space);+ match kwant_id {+ Some(k) => crate::tools::bot_workspace(&dir, k),+ None => {+ let d = dir.join("workspace");+ let _ = std::fs::create_dir_all(&d);+ d+ }+ }+}++/// Runs the space's backup command and records the result. A failed run is recorded too (`ok`+/// false with the error), so the card can say why.+///+/// The run is its own task: if the person's request goes away (a closed tab, a dropped+/// connection), the dump still finishes and is recorded, and the space is freed when it ends.+pub async fn run(state: &AppState, space: &SpaceId, kwant_id: Option<&str>) -> Result<DevBackupRow, BackupError> {+ let (state, space, kwant_id) = (state.clone(), space.clone(), kwant_id.map(str::to_string));+ match tokio::spawn(async move { run_here(&state, &space, kwant_id.as_deref()).await }).await {+ Ok(r) => r,+ Err(e) => Err(BackupError::Lost(e.to_string())),+ }+}++async fn run_here(state: &AppState, space: &SpaceId, kwant_id: Option<&str>) -> Result<DevBackupRow, BackupError> {+ let mode = state.db.dev_mode(space.as_str()).await.map_err(BackupError::Db)?;+ let Some(command) = mode.and_then(|m| m.backup_command).filter(|c| !c.trim().is_empty()) else {+ return Err(BackupError::NoCommand);+ };+ let Some(_claim) = Claim::take(space.as_str()) else {+ return Err(BackupError::Busy);+ };+ let cwd = folder(state, space, kwant_id);+ let started = SystemTime::now();+ let out = crate::tools::shell::execute_shell(&cwd, &json!({"command": command, "timeout_secs": TIMEOUT_SECS})).await;+ let taken_at = super::now();+ let (ok, path, bytes, error) = match out {+ Ok(v) => judge(&v, &cwd, started),+ Err(e) => (false, None, None, Some(e.to_string())),+ };+ let row = DevBackupRow {+ id: format!("dvb_{}", uuid::Uuid::new_v4().simple()),+ space_id: space.as_str().into(),+ kwant_id: kwant_id.map(str::to_string),+ path,+ bytes,+ ok,+ error,+ taken_at,+ };+ state.db.insert_dev_backup(&row).await.map_err(BackupError::Db)?;+ tracing::info!(space = %space, ok = row.ok, "dev: backup taken");+ Ok(row)+}++/// `ok`, path, bytes and error from the command's result. A backup is `ok` only when the command+/// exits 0 and its output names either a remote target or a local file (or folder) that exists,+/// isn't empty, and was written after the command `started` (less [`MTIME_SLACK`]). Exit 0 with+/// nothing named is not a backup: `echo done` proves nothing.+pub fn judge(v: &Value, cwd: &Path, started: SystemTime) -> (bool, Option<String>, Option<i64>, Option<String>) {+ let stdout = v["stdout"].as_str().unwrap_or("");+ let stderr = v["stderr"].as_str().unwrap_or("");+ if v["success"] != true {+ let code = v["exit_code"].as_i64().unwrap_or(-1);+ let tail = tail_of(if stderr.trim().is_empty() { stdout } else { stderr });+ return (false, None, None, Some(format!("The backup command stopped with exit code {code}. {tail}").trim().to_string()));+ }+ match find_path(stdout, cwd).or_else(|| find_path(stderr, cwd)) {+ Some(Found::Local(p, 0, _)) => (false, Some(p), Some(0), Some("The backup file is empty".into())),+ Some(Found::Local(p, bytes, modified)) if !modified.is_some_and(|m| m + MTIME_SLACK >= started) => {+ (false, Some(p), Some(bytes as i64), Some("The backup file is older than this backup run, so it isn't the one the command just made".into()))+ }+ Some(Found::Local(p, bytes, _)) => (true, Some(p), Some(bytes as i64), None),+ Some(Found::Missing(p)) => (false, Some(p), None, Some("The backup command named a file that isn't there".into())),+ Some(Found::Remote(p)) => (true, Some(p), printed_bytes(stdout), None),+ None => (false, None, None, Some(NOTHING_NAMED.into())),+ }+}++fn tail_of(s: &str) -> String {+ let s = s.trim();+ let n = s.chars().count();+ if n <= ERROR_CHARS {+ s.to_string()+ } else {+ format!("…{}", s.chars().skip(n - ERROR_CHARS).collect::<String>())+ }+}++#[derive(Debug, PartialEq)]+enum Found {+ /// Path, bytes, and when it was last written (the newest file, for a folder).+ Local(String, u64, Option<SystemTime>),+ Missing(String),+ Remote(String),+}++const REMOTE: [&str; 6] = ["s3://", "gs://", "r2://", "b2://", "az://", "https://"];+const BACKUP_EXT: [&str; 12] = [".sql", ".gz", ".tgz", ".tar", ".zip", ".zst", ".dump", ".db", ".sqlite", ".sqlite3", ".bak", ".xz"];++/// The path a backup printed: the last word, from the end, that is a remote URL, an existing file+/// or folder, or a file name with a backup extension. A bare name (`backups`, `latest`) counts+/// when it exists in `cwd` and its line says it's the backup.+fn find_path(out: &str, cwd: &Path) -> Option<Found> {+ let mut missing = None;+ for line in out.lines().rev().take(200) {+ for word in line.split_whitespace().rev() {+ let w = word+ .trim_start_matches(['"', '\'', '`', '(', '[', '<'])+ .trim_end_matches(['"', '\'', '`', ',', ';', ')', ']', '>', '.', ':']);+ let w = w.split_once('=').map(|(_, v)| v).unwrap_or(w);+ if w.len() < 2 || w.len() > 1024 {+ continue;+ }+ if REMOTE.iter().any(|p| w.starts_with(p)) {+ return Some(Found::Remote(w.to_string()));+ }+ let looks = w.contains('/') || BACKUP_EXT.iter().any(|e| w.to_lowercase().ends_with(e));+ let bare = !looks && w != "." && w != ".." && line_names_backup(line);+ if !looks && !bare {+ continue;+ }+ let p = expand(w, cwd);+ match std::fs::metadata(&p) {+ Ok(m) if m.is_file() => return Some(Found::Local(p.to_string_lossy().into(), m.len(), m.modified().ok())),+ Ok(m) if m.is_dir() && line_names_backup(line) => {+ let (bytes, newest) = dir_stats(&p, 0);+ return Some(Found::Local(p.to_string_lossy().into(), bytes, newest));+ }+ Ok(_) => {}+ Err(_) if BACKUP_EXT.iter().any(|e| w.to_lowercase().ends_with(e)) && missing.is_none() => missing = Some(p.to_string_lossy().into()),+ Err(_) => {}+ }+ }+ }+ missing.map(Found::Missing)+}++fn line_names_backup(line: &str) -> bool {+ let l = line.to_lowercase();+ l.contains("backup") || l.contains("saved") || l.contains("wrote") || l.contains("dump") || l.contains("snapshot")+}++fn expand(w: &str, cwd: &Path) -> PathBuf {+ if let Some(rest) = w.strip_prefix("~/") {+ if let Ok(home) = std::env::var("HOME") {+ return PathBuf::from(home).join(rest);+ }+ }+ let p = PathBuf::from(w);+ if p.is_absolute() {+ p+ } else {+ cwd.join(p)+ }+}++/// A folder's bytes and its newest file's write time.+fn dir_stats(p: &Path, depth: usize) -> (u64, Option<SystemTime>) {+ if depth > 6 {+ return (0, None);+ }+ let Ok(rd) = std::fs::read_dir(p) else { return (0, None) };+ let mut bytes = 0;+ let mut newest: Option<SystemTime> = None;+ for e in rd.flatten().take(10_000) {+ let (b, t) = match e.metadata() {+ Ok(m) if m.is_file() => (m.len(), m.modified().ok()),+ Ok(m) if m.is_dir() => dir_stats(&e.path(), depth + 1),+ _ => (0, None),+ };+ bytes += b;+ newest = newest.max(t);+ }+ (bytes, newest)+}++/// `12345 bytes`, `bytes=12345`, `size: 12345` in the output, for a remote backup.+fn printed_bytes(out: &str) -> Option<i64> {+ let words: Vec<&str> = out.split(|c: char| c.is_whitespace() || c == '=' || c == ':').filter(|w| !w.is_empty()).collect();+ for (i, w) in words.iter().enumerate() {+ let lw = w.to_lowercase();+ if lw == "bytes" && i > 0 {+ if let Ok(n) = words[i - 1].replace(',', "").parse::<i64>() {+ return Some(n);+ }+ }+ if matches!(lw.as_str(), "bytes" | "size") {+ if let Some(n) = words.get(i + 1).and_then(|x| x.replace(',', "").parse::<i64>().ok()) {+ return Some(n);+ }+ }+ }+ None+}++/// `POST /dev/backup`'s reply.+pub fn json(b: &DevBackupRow) -> Value {+ json!({"id": b.id, "ok": b.ok, "path": b.path, "bytes": b.bytes, "taken_at": b.taken_at, "error": b.error})+}++/// Whether an `ok` backup is fresh enough for a step that needs one.+pub fn is_fresh(ok: Option<&DevBackupRow>, now: DateTime<Utc>) -> bool {+ ok.is_some_and(|b| b.ok && (now - b.taken_at).num_seconds() <= FRESH_SECS && b.taken_at <= now + chrono::Duration::seconds(5))+}++/// The floor card's `backup` object (plan §3.5): `state` is `fresh`, `old`, `none`, `no_data`,+/// `no_command`, `taking` or `failed`.+pub fn card_state(no_data: bool, has_command: bool, taking: bool, last: Option<&DevBackupRow>, last_ok: Option<&DevBackupRow>, now: DateTime<Utc>) -> Value {+ let age = |b: &DevBackupRow| (now - b.taken_at).num_seconds().max(0);+ let shown = last_ok.or(last);+ let state = if no_data {+ "no_data"+ } else if taking {+ "taking"+ } else if !has_command {+ "no_command"+ } else if last.is_some_and(|b| !b.ok) && !is_fresh(last_ok, now) {+ "failed"+ } else if is_fresh(last_ok, now) {+ "fresh"+ } else if last_ok.is_some() {+ "old"+ } else {+ "none"+ };+ let error = if state == "failed" { last.and_then(|b| b.error.clone()) } else { None };+ json!({+ "state": state,+ "age_s": shown.filter(|_| state != "no_data").map(age),+ "bytes": last_ok.filter(|_| state != "no_data").and_then(|b| b.bytes),+ "path": last_ok.filter(|_| state != "no_data").and_then(|b| b.path.clone()),+ "error": error,+ })+}++/// The `backup` object for a space now.+pub async fn state_of(db: &crate::db::Database, space_id: &str, no_data: bool) -> Value {+ let has_command = db.dev_mode(space_id).await.ok().flatten().and_then(|m| m.backup_command).is_some_and(|c| !c.trim().is_empty());+ let (last, ok) = db.latest_dev_backups(space_id).await.unwrap_or((None, None));+ card_state(no_data, has_command, is_running(space_id), last.as_ref(), ok.as_ref(), super::now())+}++#[cfg(test)]+mod tests {+ use super::*;++ fn b(ok: bool, secs_ago: i64, now: DateTime<Utc>) -> DevBackupRow {+ DevBackupRow {+ id: "dvb_1".into(),+ space_id: "s1".into(),+ kwant_id: None,+ path: Some("/srv/backups/app.sql.gz".into()),+ bytes: Some(1024),+ ok,+ error: (!ok).then(|| "pg_dump: connection refused".into()),+ taken_at: now - chrono::Duration::seconds(secs_ago),+ }+ }++ #[test]+ fn a_backup_is_fresh_for_ten_minutes() {+ let now = Utc::now();+ assert!(is_fresh(Some(&b(true, 0, now)), now));+ assert!(is_fresh(Some(&b(true, 600, now)), now));+ assert!(!is_fresh(Some(&b(true, 601, now)), now));+ assert!(!is_fresh(Some(&b(false, 10, now)), now), "a failed backup never counts");+ assert!(!is_fresh(None, now));+ assert!(!is_fresh(Some(&b(true, -3600, now)), now), "a backup dated in the future doesn't count");+ }++ #[test]+ fn the_card_has_all_seven_backup_states() {+ let now = Utc::now();+ let s = |no_data, cmd, taking, last: Option<DevBackupRow>, ok: Option<DevBackupRow>| card_state(no_data, cmd, taking, last.as_ref(), ok.as_ref(), now)["state"].clone();+ assert_eq!(s(true, false, false, None, None), "no_data");+ assert_eq!(s(false, false, false, None, None), "no_command");+ assert_eq!(s(false, true, true, None, None), "taking");+ assert_eq!(s(false, true, false, None, None), "none");+ assert_eq!(s(false, true, false, Some(b(true, 30, now)), Some(b(true, 30, now))), "fresh");+ assert_eq!(s(false, true, false, Some(b(true, 3600, now)), Some(b(true, 3600, now))), "old");+ assert_eq!(s(false, true, false, Some(b(false, 5, now)), Some(b(true, 3600, now))), "failed");+ // A failure after a fresh one keeps the fresh one usable+ assert_eq!(s(false, true, false, Some(b(false, 5, now)), Some(b(true, 60, now))), "fresh");+ let v = card_state(false, true, false, Some(&b(false, 5, now)), None, now);+ assert_eq!(v["error"], "pg_dump: connection refused");+ let v = card_state(false, true, false, Some(&b(true, 30, now)), Some(&b(true, 30, now)), now);+ assert_eq!(v["age_s"], 30);+ assert_eq!(v["bytes"], 1024);+ assert_eq!(v["path"], "/srv/backups/app.sql.gz");+ }++ #[test]+ fn the_output_names_the_backup_and_the_disk_confirms_it() {+ let dir = std::env::temp_dir().join(format!("kwnt-dev-backup-{}", uuid::Uuid::new_v4().simple()));+ std::fs::create_dir_all(dir.join("backups")).unwrap();+ std::fs::write(dir.join("backups/app-2026-11-05.sql.gz"), vec![1u8; 2048]).unwrap();+ std::fs::write(dir.join("backups/empty.sql"), b"").unwrap();+ let ok = |out: &str| json!({"success": true, "exit_code": 0, "stdout": out, "stderr": ""});+ let started = SystemTime::now() - Duration::from_secs(1);+ let judge = |v: &Value, dir: &Path| super::judge(v, dir, started);+ let (good, path, bytes, err) = judge(&ok("dumping…\nBackup saved to backups/app-2026-11-05.sql.gz\n"), &dir);+ assert!(good, "{err:?}");+ assert!(path.unwrap().ends_with("backups/app-2026-11-05.sql.gz"));+ assert_eq!(bytes, Some(2048));+ let abs = dir.join("backups/app-2026-11-05.sql.gz");+ assert_eq!(judge(&ok(&format!("wrote \"{}\".", abs.display())), &dir).2, Some(2048));+ assert_eq!(judge(&ok(&format!("path={}", abs.display())), &dir).2, Some(2048));+ let (good, _, _, err) = judge(&ok("saved backups/empty.sql"), &dir);+ assert!(!good);+ assert_eq!(err.as_deref(), Some("The backup file is empty"));+ let (good, path, _, err) = judge(&ok("saved backups/missing.sql.gz"), &dir);+ assert!(!good && path.is_some());+ assert!(err.unwrap().contains("isn't there"));+ let (good, path, bytes, _) = judge(&ok("upload: ./x.gz to s3://demo-backups/app.sql.gz\n12345 bytes"), &dir);+ assert!(good);+ assert_eq!(path.as_deref(), Some("s3://demo-backups/app.sql.gz"));+ assert_eq!(bytes, Some(12345));+ // A whole folder, when the line says it's the backup+ let (good, _, bytes, _) = judge(&ok(&format!("Backup written to {}", dir.join("backups").display())), &dir);+ assert!(good);+ assert_eq!(bytes, Some(2048));+ // Nothing named is not a backup (F2)+ assert_eq!(judge(&ok("done"), &dir), (false, None, None, Some(NOTHING_NAMED.into())));+ let (good, _, _, err) = judge(&json!({"success": false, "exit_code": 2, "stdout": "", "stderr": "pg_dump: error: connection to db.example.com failed"}), &dir);+ assert!(!good);+ assert!(err.unwrap().contains("exit code 2") );+ std::fs::remove_dir_all(&dir).unwrap();+ }++ #[test]+ fn one_backup_runs_at_a_time_per_space() {+ let a = Claim::take("s-claim").unwrap();+ assert!(is_running("s-claim"));+ assert!(Claim::take("s-claim").is_none());+ let b = Claim::take("s-other").unwrap();+ drop(a);+ drop(b);+ assert!(!is_running("s-claim"));+ assert!(!is_running("s-other"));+ }++ /// F1: a run that is cancelled midway (the request went away) still frees the space.+ #[tokio::test]+ async fn a_cancelled_run_frees_the_space() {+ let run = tokio::spawn(async {+ let _claim = Claim::take("s-cancel").unwrap();+ tokio::time::sleep(Duration::from_secs(60)).await;+ });+ tokio::time::sleep(Duration::from_millis(50)).await;+ assert!(is_running("s-cancel"));+ run.abort();+ let _ = run.await;+ assert!(!is_running("s-cancel"), "an aborted run must not hold the space");+ // And a panicking one+ let run = tokio::spawn(async {+ let _claim = Claim::take("s-cancel").unwrap();+ panic!("the dump crashed");+ });+ assert!(run.await.is_err());+ assert!(!is_running("s-cancel"));+ }++ /// F2: exit 0 with nothing named is never ok, whatever it printed.+ #[test]+ fn exit_zero_with_no_file_named_is_not_a_backup() {+ let dir = std::env::temp_dir().join(format!("kwnt-dev-backup-{}", uuid::Uuid::new_v4().simple()));+ std::fs::create_dir_all(&dir).unwrap();+ let ok = |out: &str| json!({"success": true, "exit_code": 0, "stdout": out, "stderr": ""});+ for out in ["", "done", "Backup complete!", "OK 12345 bytes"] {+ let (good, path, _, err) = judge(&ok(out), &dir, SystemTime::now());+ assert!(!good, "{out:?} must not count as a backup");+ assert_eq!(path, None);+ assert_eq!(err.as_deref(), Some(NOTHING_NAMED), "{out:?}");+ }+ std::fs::remove_dir_all(&dir).unwrap();+ }++ /// F3: a file written before the command started is not this run's backup; a bare folder+ /// name is found in the run's folder.+ #[test]+ fn an_old_file_is_not_this_runs_backup_and_bare_names_resolve() {+ let dir = std::env::temp_dir().join(format!("kwnt-dev-backup-{}", uuid::Uuid::new_v4().simple()));+ std::fs::create_dir_all(dir.join("snapshots")).unwrap();+ std::fs::write(dir.join("old.sql.gz"), vec![1u8; 512]).unwrap();+ std::fs::write(dir.join("snapshots/app.dump"), vec![1u8; 256]).unwrap();+ let ok = |out: &str| json!({"success": true, "exit_code": 0, "stdout": out, "stderr": ""});+ // Started a minute after the files were written: they're stale+ let later = SystemTime::now() + Duration::from_secs(60);+ let (good, path, bytes, err) = judge(&ok("Backup saved to old.sql.gz"), &dir, later);+ assert!(!good);+ assert!(path.unwrap().ends_with("old.sql.gz"));+ assert_eq!(bytes, Some(512));+ assert!(err.unwrap().contains("older than this backup run"));+ let (good, _, _, err) = judge(&ok("Backup written to snapshots"), &dir, later);+ assert!(!good, "a folder whose newest file is old is stale too");+ assert!(err.unwrap().contains("older"));+ // Started now (within the slack): fresh, and the bare folder name resolves against cwd+ let now = SystemTime::now();+ let (good, path, _, _) = judge(&ok("Backup saved to old.sql.gz"), &dir, now);+ assert!(good);+ assert!(path.unwrap().ends_with("old.sql.gz"));+ let (good, path, bytes, err) = judge(&ok("Backup written to snapshots"), &dir, now);+ assert!(good, "{err:?}");+ assert_eq!(path.as_deref(), Some(dir.join("snapshots").to_string_lossy().as_ref()));+ assert_eq!(bytes, Some(256));+ // A bare word on a line that doesn't say it's the backup is ignored+ std::fs::create_dir_all(dir.join("notes")).unwrap();+ std::fs::write(dir.join("notes/a.txt"), b"x").unwrap();+ assert_eq!(judge(&ok("updated notes"), &dir, now).3.as_deref(), Some(NOTHING_NAMED));+ std::fs::remove_dir_all(&dir).unwrap();+ }+}diff --git a/src/server/dev/facts.rs b/src/server/dev/facts.rsnew file mode 100644index 00000000..8b9d76d2--- /dev/null+++ b/src/server/dev/facts.rs@@ -0,0 +1,185 @@+//! What the poller learned about one merge or one open PR head (plan §3.3). Lin writes it into+//! `dev_cards.facts`; card generation (`generate`) reads it. Facts only: nothing here is model text.++use chrono::{DateTime, Utc};+use serde::{Deserialize, Serialize};++/// Most diff characters kept across a card's files (plan D8).+pub const DIFF_CHARS: usize = 60_000;++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum Kind {+ Landed,+ Review,+}++#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+pub struct DevFacts {+ /// `owner/name`.+ pub repo: String,+ pub kind: Kind,+ /// The PR number: a review always has one; a landed card when the merge came from a PR.+ pub pr: Option<u64>,+ /// PR title, else the commit's first line.+ pub title: String,+ /// PR body, else the rest of the commit message.+ pub body: String,+ /// Landed: the merge (or pushed) commit. Review: the PR head.+ pub head_sha: String,+ pub base_branch: String,+ pub merged_at: Option<DateTime<Utc>>,+ /// GitHub login of whoever merged it (landed only).+ pub merged_by: Option<String>,+ pub author: Author,+ pub files: Vec<FileDiff>,+ /// `"diff cut, N files not read"` when the diff went past [`DIFF_CHARS`], else none.+ pub cut: Option<String>,+ pub checks: Vec<Check>,+ pub ci: CiState,+ /// The kwant task, mission or thread text the PR came from, if known.+ pub task: Option<String>,+ /// Files with no earlier commit by anyone in the last 90 days.+ pub first_edit_files: Vec<String>,+ /// Review only: GitHub marks the PR a draft (the poller skips drafts, D8).+ #[serde(default)]+ pub draft: bool,+ /// Review only: the PR's head branch.+ #[serde(default)]+ pub head_branch: Option<String>,+ /// Links for the card footer: PR, commit and CI pages (https only).+ #[serde(default)]+ pub links: Links,+}++#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]+pub struct Links {+ pub pr: Option<String>,+ pub commit: Option<String>,+ pub ci: Option<String>,+}++#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]+pub struct Author {+ /// GitHub login, when the commit is linked to an account.+ pub login: Option<String>,+ /// Git author name.+ pub name: String,+ /// Git author email.+ pub email: Option<String>,+ /// The kwant bot this was matched to by name or email (plan D7); none means the person.+ pub bot: Option<KwantRef>,+}++#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+pub struct KwantRef {+ pub id: String,+ pub name: String,+ /// `claude`, `codex`, `grok`, …+ pub engine: String,+ pub model: String,+}++#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+pub struct FileDiff {+ pub path: String,+ /// GitHub's file status: `added`, `modified`, `removed`, `renamed`, `copied`, `changed`, `unchanged`.+ pub status: String,+ pub additions: u64,+ pub deletions: u64,+ /// The unified diff hunk text, cut to fit [`DIFF_CHARS`]; none for binary, very large or unread files.+ pub patch: Option<String>,+ pub previous_path: Option<String>,+}++#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+pub struct Check {+ pub name: String,+ /// `queued`, `in_progress` or `completed`.+ pub status: String,+ /// When completed: `success`, `failure`, `neutral`, `cancelled`, `skipped`, `timed_out`, `action_required`.+ pub conclusion: Option<String>,+ pub url: Option<String>,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum CiState {+ Green,+ Red,+ Pending,+ None,+}++impl CiState {+ /// Red if any completed check failed, else pending while any runs, else green; no checks is none.+ pub fn of(checks: &[Check]) -> CiState {+ if checks.is_empty() {+ return CiState::None;+ }+ let bad = |c: &Check| matches!(c.conclusion.as_deref(), Some("failure" | "timed_out" | "cancelled" | "action_required" | "startup_failure"));+ if checks.iter().any(bad) {+ CiState::Red+ } else if checks.iter().any(|c| c.status != "completed") {+ CiState::Pending+ } else {+ CiState::Green+ }+ }+}++/// What a `release_notes` card is drafted from: the landed cards since the last tag.+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+pub struct ReleaseFacts {+ pub repo: String,+ /// The newest tag on the watched branch, if any (`mac-v0.6.12`).+ pub since_tag: Option<String>,+ /// The landed `dev_cards` ids it covers, oldest first.+ pub cards: Vec<String>,+}++#[cfg(test)]+mod tests {+ use super::*;++ fn check(status: &str, conclusion: Option<&str>) -> Check {+ Check { name: "rust".into(), status: status.into(), conclusion: conclusion.map(Into::into), url: None }+ }++ #[test]+ fn ci_state_reads_failures_first_then_running_checks() {+ assert_eq!(CiState::of(&[]), CiState::None);+ assert_eq!(CiState::of(&[check("completed", Some("success")), check("completed", Some("skipped"))]), CiState::Green);+ assert_eq!(CiState::of(&[check("completed", Some("success")), check("in_progress", None)]), CiState::Pending);+ assert_eq!(CiState::of(&[check("in_progress", None), check("completed", Some("failure"))]), CiState::Red);+ }++ #[test]+ fn facts_round_trip_as_snake_case_json() {+ let f = DevFacts {+ repo: "o/r".into(),+ kind: Kind::Review,+ pr: Some(7),+ title: "t".into(),+ body: String::new(),+ head_sha: "abc".into(),+ base_branch: "main".into(),+ merged_at: None,+ merged_by: None,+ author: Author::default(),+ files: vec![],+ cut: None,+ checks: vec![],+ ci: CiState::None,+ task: None,+ first_edit_files: vec![],+ draft: false,+ head_branch: Some("b".into()),+ links: Links::default(),+ };+ let v = serde_json::to_value(&f).unwrap();+ assert_eq!(v["kind"], "review");+ assert_eq!(v["ci"], "none");+ assert_eq!(serde_json::from_value::<DevFacts>(v).unwrap(), f);+ }+}diff --git a/src/server/dev/floor.rs b/src/server/dev/floor.rsnew file mode 100644index 00000000..a7f3b6b5--- /dev/null+++ b/src/server/dev/floor.rs@@ -0,0 +1,222 @@+//! The production floor in the approval path (plan §3.5): builds a space's [`DevCtx`], runs the+//! pure classifier in `crate::mcp::prod_floor`, and gives the card its `prod_floor` payload. The+//! approvers treat a hit as `forced` (it asks whatever the approvals say) with no "always allow";+//! [`allow_refusal`] is the server-side check that refuses **Allow** while a step needs a backup+//! and none is fresh.++use crate::db::Database;+use crate::mcp::prod_floor::{self, DevCtx, Floor};+use crate::mcp::ToolApprovalRequest;+use serde_json::{json, Value};+use std::path::Path;++/// The Dev mode context of a bot's space, or `None` when Dev mode is off there (no floor).+/// With Dev mode off in every space it reads nothing.+pub async fn ctx_for_kwant(db: &Database, kwant_id: &str, cwd: Option<&Path>) -> Option<(String, DevCtx)> {+ if !db.any_dev_mode_on() {+ return None;+ }+ let kwant = db.get_kwant(kwant_id).await.ok().flatten()?;+ let mode = db.dev_mode(&kwant.space_id).await.ok().flatten().filter(|m| m.on)?;+ let marked = db.prod_connections(&kwant.space_id).await.unwrap_or_default();+ let servers = db.list_mcp_servers(&crate::db::spaces::SpaceId::new(&kwant.space_id)).await.unwrap_or_default();+ let prod_connections = prod_names(&marked, servers.iter().map(|s| (s.id.as_str(), s.name.as_str())));+ let ctx = DevCtx {+ branch: mode.branch.clone(),+ protected: Vec::new(),+ deploy_hint: mode.deploy_hint.clone(),+ prod_connections,+ head_branch: cwd.and_then(head_branch),+ migration: None,+ };+ Some((kwant.space_id, ctx))+}++/// Marked connection ids as the classifier names them: `mcp:<id>` becomes the server's name,+/// `composio:<slug>` the toolkit slug. A mark whose server is gone is dropped.+pub fn prod_names<'a>(marked: &[String], servers: impl Iterator<Item = (&'a str, &'a str)>) -> Vec<String> {+ let servers: Vec<(&str, &str)> = servers.collect();+ marked+ .iter()+ .filter_map(|m| {+ if let Some(id) = m.strip_prefix("mcp:") {+ servers.iter().find(|(sid, _)| *sid == id).map(|(_, name)| name.to_string())+ } else {+ m.strip_prefix("composio:").map(str::to_string)+ }+ })+ .collect()+}++/// The branch checked out in `cwd` (walking up to its `.git`), from `HEAD` alone: no git process.+/// `None` for a detached head or no repo.+pub fn head_branch(cwd: &Path) -> Option<String> {+ let mut dir = Some(cwd);+ for _ in 0..12 {+ let d = dir?;+ let git = d.join(".git");+ let head_file = if git.is_dir() {+ git.join("HEAD")+ } else if git.is_file() {+ // A worktree: `.git` says `gitdir: <path>`+ let text = std::fs::read_to_string(&git).ok()?;+ let gd = text.trim().strip_prefix("gitdir:")?.trim().to_string();+ let gd = if Path::new(&gd).is_absolute() { Path::new(&gd).to_path_buf() } else { d.join(gd) };+ gd.join("HEAD")+ } else {+ dir = d.parent();+ continue;+ };+ let head = std::fs::read_to_string(head_file).ok()?;+ return head.trim().strip_prefix("ref: refs/heads/").map(str::to_string);+ }+ None+}++/// The card's `prod_floor` object: `{kind, why, blast, needs_backup, space_id, backup}`.+pub async fn payload(db: &Database, space_id: &str, floor: &Floor, ctx: &DevCtx) -> Value {+ let mut v = serde_json::to_value(floor).unwrap_or_else(|_| json!({}));+ v["space_id"] = json!(space_id);+ v["backup"] = super::backup::state_of(db, space_id, ctx.no_data()).await;+ v+}++/// The floor for a tool call (an MCP tool, or one of claude's own), with its payload.+pub async fn for_call(db: &Database, req: &ToolApprovalRequest) -> Option<(Floor, Value)> {+ let cwd = req.builtin.as_ref().and_then(|b| b.cwd.as_deref()).map(Path::new);+ let (space_id, ctx) = ctx_for_kwant(db, &req.kwant_id, cwd).await?;+ let floor = prod_floor::reason(req, &ctx)?;+ let p = payload(db, &space_id, &floor, &ctx).await;+ Some((floor, p))+}++/// The floor for a command kwant's own shell runs for a bot (`execute_shell`).+pub async fn for_shell(db: &Database, kwant_id: &str, command: &str, cwd: &Path) -> Option<(Floor, Value)> {+ let (space_id, ctx) = ctx_for_kwant(db, kwant_id, Some(cwd)).await?;+ let floor = prod_floor::shell_reason(command, &ctx)?;+ let p = payload(db, &space_id, &floor, &ctx).await;+ Some((floor, p))+}++/// Why **Allow** is refused on this card now, or `None`: the card carries a `prod_floor` that+/// needs a backup, and the space has no `ok` backup at most 10 minutes old. Checked when the+/// person answers, not when the card was made, so a backup taken in between counts and one that+/// went old doesn't.+pub async fn allow_refusal(db: &Database, details: &Value) -> Option<Value> {+ let f = details.get("prod_floor")?;+ if f["needs_backup"] != true {+ return None;+ }+ let space_id = f["space_id"].as_str()?;+ let (_, ok) = db.latest_dev_backups(space_id).await.unwrap_or((None, None));+ if super::backup::is_fresh(ok.as_ref(), super::now()) {+ return None;+ }+ let backup = super::backup::state_of(db, space_id, false).await;+ Some(json!({+ "error": "Back up first: this step needs a backup from the last 10 minutes",+ "backup": backup,+ }))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn marks_become_server_names_and_slugs() {+ let marked = vec!["mcp:srv_1".to_string(), "mcp:gone".into(), "composio:github".into(), "account:p1".into()];+ let names = prod_names(&marked, [("srv_1", "cloudflare"), ("srv_2", "notion")].into_iter());+ assert_eq!(names, ["cloudflare", "github"]);+ }++ #[test]+ fn the_checked_out_branch_is_read_from_head() {+ let root = std::env::temp_dir().join(format!("kwnt-dev-head-{}", uuid::Uuid::new_v4().simple()));+ std::fs::create_dir_all(root.join(".git")).unwrap();+ std::fs::create_dir_all(root.join("src/deep")).unwrap();+ std::fs::write(root.join(".git/HEAD"), "ref: refs/heads/lin-dev-core\n").unwrap();+ assert_eq!(head_branch(&root.join("src/deep")).as_deref(), Some("lin-dev-core"));+ std::fs::write(root.join(".git/HEAD"), "3ca2bf7aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n").unwrap();+ assert_eq!(head_branch(&root), None, "a detached head can't be told");+ // A worktree's `.git` file+ let wt = root.join("wt");+ std::fs::create_dir_all(root.join(".git/worktrees/wt")).unwrap();+ std::fs::create_dir_all(&wt).unwrap();+ std::fs::write(wt.join(".git"), format!("gitdir: {}\n", root.join(".git/worktrees/wt").display())).unwrap();+ std::fs::write(root.join(".git/worktrees/wt/HEAD"), "ref: refs/heads/release/0.7\n").unwrap();+ assert_eq!(head_branch(&wt).as_deref(), Some("release/0.7"));+ std::fs::remove_dir_all(&root).unwrap();+ assert_eq!(head_branch(Path::new("/nonexistent/kwnt-dev")), None);+ }++ fn backup(space: &str, ok: bool, age_s: i64) -> crate::db::dev_mode::DevBackupRow {+ crate::db::dev_mode::DevBackupRow {+ id: format!("dvb_{}", uuid::Uuid::new_v4().simple()),+ space_id: space.into(),+ kwant_id: None,+ path: Some("/tmp/demo.sql".into()),+ bytes: Some(10),+ ok,+ error: (!ok).then(|| "exit 1".into()),+ taken_at: chrono::Utc::now() - chrono::Duration::seconds(age_s),+ }+ }++ #[tokio::test]+ async fn allow_is_refused_until_a_fresh_ok_backup() {+ let tmp = tempfile::tempdir().unwrap();+ let db = Database::init(tmp.path()).await.unwrap();+ let card = json!({"prod_floor": {"kind": "migration", "needs_backup": true, "space_id": "s1"}});+ // No backup at all, and then no backup command either+ let r = allow_refusal(&db, &card).await.expect("refused with no backup");+ assert!(r["error"].as_str().unwrap().starts_with("Back up first"));+ assert_eq!(r["backup"]["state"], "no_command");+ db.put_dev_mode("s1", true, "demo-org/demo-app", "main", None, Some("pg_dump demo > /tmp/demo.sql")).await.unwrap();+ assert_eq!(allow_refusal(&db, &card).await.unwrap()["backup"]["state"], "none");+ // Only a failed one, and an ok one 11 minutes old+ db.insert_dev_backup(&backup("s1", false, 5)).await.unwrap();+ db.insert_dev_backup(&backup("s1", true, 660)).await.unwrap();+ assert!(allow_refusal(&db, &card).await.is_some(), "a failed or old backup doesn't count");+ // Another space's fresh backup doesn't count either+ db.insert_dev_backup(&backup("s2", true, 5)).await.unwrap();+ assert!(allow_refusal(&db, &card).await.is_some());+ // A fresh ok one in this space does+ db.insert_dev_backup(&backup("s1", true, 30)).await.unwrap();+ assert!(allow_refusal(&db, &card).await.is_none());+ // A step that needs no backup, or a card that isn't the floor's, is never refused here+ assert!(allow_refusal(&db, &json!({"prod_floor": {"needs_backup": false, "space_id": "s3"}})).await.is_none());+ assert!(allow_refusal(&db, &json!({"source": "mcp"})).await.is_none());+ }++ #[tokio::test]+ async fn production_marks_round_trip() {+ let tmp = tempfile::tempdir().unwrap();+ let db = Database::init(tmp.path()).await.unwrap();+ db.set_prod_connection("s1", "composio:github", true).await.unwrap();+ db.set_prod_connection("s1", "composio:github", true).await.unwrap();+ db.set_prod_connection("s1", "mcp:srv_1", true).await.unwrap();+ db.set_prod_connection("s2", "composio:notion", true).await.unwrap();+ let mut marked = db.prod_connections("s1").await.unwrap();+ marked.sort();+ assert_eq!(marked, ["composio:github", "mcp:srv_1"]);+ db.set_prod_connection("s1", "composio:github", false).await.unwrap();+ assert_eq!(db.prod_connections("s1").await.unwrap(), ["mcp:srv_1"]);+ // Off: no context, so no floor+ assert!(ctx_for_kwant(&db, "no-such-bot", None).await.is_none());+ }++ #[tokio::test]+ async fn the_dev_mode_flag_is_read_at_startup() {+ let tmp = tempfile::tempdir().unwrap();+ let db = Database::init(tmp.path()).await.unwrap();+ assert!(!db.any_dev_mode_on());+ db.put_dev_mode("s1", true, "demo-org/demo-app", "main", None, None).await.unwrap();+ drop(db);+ let db = Database::init(tmp.path()).await.unwrap();+ assert!(db.any_dev_mode_on(), "a restart with a space on starts with the floor on");+ db.put_dev_mode("s1", false, "demo-org/demo-app", "main", None, None).await.unwrap();+ drop(db);+ assert!(!Database::init(tmp.path()).await.unwrap().any_dev_mode_on());+ }+}diff --git a/src/server/dev/generate.rs b/src/server/dev/generate.rsnew file mode 100644index 00000000..16560b9f--- /dev/null+++ b/src/server/dev/generate.rs@@ -0,0 +1,13 @@+//! Card generation (Vega, plan §4): turns a pending card's DevFacts into the card JSON (§3.4).+//! This is Lin's stub so the core is testable alone: it marks the card ready with no text.++use crate::server::AppState;++/// Generates the card `card_id`, then sets its status (`ready` or `failed`) and sends `dev_card`.+pub async fn generate(state: AppState, card_id: String) {+ match state.db.set_dev_card(&card_id, crate::db::dev_mode::READY, None).await {+ Ok(Some(row)) => super::notify_card(&state, &row),+ Ok(None) => {}+ Err(e) => tracing::warn!(card = %card_id, "dev: could not mark the card ready: {e}"),+ }+}diff --git a/src/server/dev/landed.rs b/src/server/dev/landed.rsnew file mode 100644index 00000000..262a0247--- /dev/null+++ b/src/server/dev/landed.rs@@ -0,0 +1 @@+//! Dev mode card generation: landed (Vega, plan §4).diff --git a/src/server/dev/mod.rs b/src/server/dev/mod.rsnew file mode 100644index 00000000..7a8ff16c--- /dev/null+++ b/src/server/dev/mod.rs@@ -0,0 +1,127 @@+//! Dev mode (docs/dev-mode.md, plan 0.7): a space watches one GitHub repo, read only. The poller+//! writes a pending card per merge to the watched branch and per open PR head, with its DevFacts;+//! `generate` turns them into cards. The production floor lives in `crate::mcp::prod_floor`.+//!+//! Lin owns `facts`, `routes`, `poller`, `repo`, `backup` and `floor`; Vega owns `generate`, `landed`,+//! `review`, `risk`, `tamper` and `notes`.++pub mod backup;+pub mod facts;+pub mod floor;+pub mod generate;+pub mod landed;+pub mod notes;+pub mod poller;+pub mod repo;+pub mod review;+pub mod risk;+pub mod routes;+pub mod tamper;++pub use generate::generate;++use crate::db::dev_mode::{DevCardRow, CALLS_CAP};+use crate::drivers::events::RuntimeEvent;+use crate::server::AppState;++/// Sends `dev_card {space_id, id, kind, status}` on the event stream.+pub fn notify_card(state: &AppState, row: &DevCardRow) {+ let _ = state.event_sender.send(RuntimeEvent::DevCard {+ space_id: row.space_id.clone(),+ id: row.id.clone(),+ kind: row.kind.clone(),+ status: row.status.clone(),+ });+}++/// Sends `dev_mode {space_id, on}` on the event stream.+pub fn notify_mode(state: &AppState, space_id: &str, on: bool) {+ let _ = state.event_sender.send(RuntimeEvent::DevMode { space_id: space_id.into(), on });+}++// Test seams (QA plan §2.2), read here and nowhere else. Unset, Dev mode runs as documented.++/// How often each Dev mode space is read: `KWANT_DEV_POLL_SECS` (5–86400), else 300.+pub fn poll_every() -> std::time::Duration {+ static SECS: std::sync::OnceLock<u64> = std::sync::OnceLock::new();+ std::time::Duration::from_secs(*SECS.get_or_init(|| env_num("KWANT_DEV_POLL_SECS", 5, 86_400).unwrap_or(poller::EVERY.as_secs())))+}++/// Most model calls Dev mode makes per space per UTC day: `KWANT_DEV_CALL_CAP` (0–1000), else 30.+pub fn call_cap() -> i64 {+ static CAP: std::sync::OnceLock<i64> = std::sync::OnceLock::new();+ *CAP.get_or_init(|| env_num("KWANT_DEV_CALL_CAP", 0, 1000).map_or(CALLS_CAP, |v| v as i64))+}++fn env_num(name: &str, min: u64, max: u64) -> Option<u64> {+ let raw = std::env::var(name).ok()?;+ let v = raw.trim().parse::<u64>().ok().filter(|v| (min..=max).contains(v));+ match v {+ Some(v) => tracing::info!("dev: {name}={v}"),+ None => tracing::warn!("dev: {name} must be a whole number from {min} to {max}; the default is used"),+ }+ v+}++static CLOCK_SKEW_S: std::sync::atomic::AtomicI64 = std::sync::atomic::AtomicI64::new(0);++/// Dev mode's clock: when a backup was taken, whether it is still fresh (10 minutes), and the+/// daily cap's day. The real clock unless a test moved it with [`set_clock_skew`].+pub fn now() -> chrono::DateTime<chrono::Utc> {+ chrono::Utc::now() + chrono::Duration::seconds(CLOCK_SKEW_S.load(std::sync::atomic::Ordering::SeqCst))+}++/// Moves [`now`] `skew_s` seconds from the real clock; 0 puts it back. For tests only, and+/// process-wide: a test that uses it lives in its own test binary (see tests/dev_seams_test.rs).+#[doc(hidden)]+pub fn set_clock_skew(skew_s: i64) {+ CLOCK_SKEW_S.store(skew_s, std::sync::atomic::Ordering::SeqCst);+}++/// The daily cap's day: the UTC calendar day of `now`, `YYYY-MM-DD`, wherever the server is.+pub fn utc_day(now: chrono::DateTime<chrono::Utc>) -> String {+ now.format("%Y-%m-%d").to_string()+}++#[cfg(test)]+mod tests {+ use super::*;+ use chrono::{DateTime, Utc};++ fn at(rfc3339: &str) -> DateTime<Utc> {+ DateTime::parse_from_rfc3339(rfc3339).unwrap().with_timezone(&Utc)+ }++ #[test]+ fn the_cap_day_is_the_utc_day() {+ assert_eq!(utc_day(at("2026-11-05T23:59:59Z")), "2026-11-05");+ assert_eq!(utc_day(at("2026-11-06T00:00:00Z")), "2026-11-06");+ // Late evening in California is already tomorrow in UTC; early morning in India, yesterday+ assert_eq!(utc_day(at("2026-11-05T17:30:00-08:00")), "2026-11-06");+ assert_eq!(utc_day(at("2026-11-06T03:00:00+05:30")), "2026-11-05");+ }++ #[test]+ fn unset_seams_keep_the_defaults() {+ // CI sets neither variable+ assert_eq!(poll_every(), std::time::Duration::from_secs(300));+ assert_eq!(call_cap(), 30);+ assert!((now() - Utc::now()).num_seconds().abs() <= 1);+ }++ #[tokio::test]+ async fn the_daily_cap_resets_at_midnight_utc() {+ let tmp = tempfile::tempdir().unwrap();+ let db = crate::db::Database::init(tmp.path()).await.unwrap();+ let late = at("2026-11-05T23:59:59Z");+ assert!(db.take_dev_call_at("s1", late, 2).await.unwrap());+ assert!(db.take_dev_call_at("s1", late, 2).await.unwrap());+ assert!(!db.take_dev_call_at("s1", late, 2).await.unwrap(), "the cap holds for the rest of the UTC day");+ // 16:00 in California on the 5th is midnight UTC: a new day+ let midnight = at("2026-11-05T16:00:00-08:00");+ assert!(db.take_dev_call_at("s1", midnight, 2).await.unwrap());+ assert_eq!(db.dev_calls_on("s1", "2026-11-05").await.unwrap(), 2);+ assert_eq!(db.dev_calls_on("s1", "2026-11-06").await.unwrap(), 1);+ assert!(db.take_dev_call_at("s2", late, 2).await.unwrap(), "each space has its own cap");+ }+}diff --git a/src/server/dev/notes.rs b/src/server/dev/notes.rsnew file mode 100644index 00000000..48666649--- /dev/null+++ b/src/server/dev/notes.rs@@ -0,0 +1 @@+//! Dev mode card generation: notes (Vega, plan §4).diff --git a/src/server/dev/poller.rs b/src/server/dev/poller.rsnew file mode 100644index 00000000..37a52ad6--- /dev/null+++ b/src/server/dev/poller.rs@@ -0,0 +1,608 @@+//! The Dev mode poller (plan §3.3, D4, D5, D8): every [`EVERY`] (and right after the switch goes+//! on, or the repo or branch moves) it reads each Dev mode space's repo, read only, and writes a+//! pending `dev_cards` row with its [`DevFacts`] per merge to the watched branch and per open PR+//! head, then hands it to [`super::generate`]. Draft PRs are skipped; diffs are cut at+//! [`DIFF_CHARS`]. Lists go through ETags; a 403/429 rate limit backs the space off until GitHub+//! says it may ask again.++use super::facts::{Author, CiState, Check, DevFacts, FileDiff, Kind, KwantRef, Links, DIFF_CHARS};+use super::repo;+use crate::db::dev_mode::{DevCardRow, DevModeRow, LANDED, PENDING, REVIEW, STALE};+use crate::db::models::Kwant;+use crate::db::spaces::SpaceId;+use crate::server::AppState;+use crate::zombie::github::{EtagCache, GhCheck, GhCommit, GhError, GhFile, GhPull, GithubSource};+use chrono::{DateTime, Duration, Utc};+use std::collections::{HashMap, HashSet};+use std::sync::{Mutex, OnceLock};+use tokio::sync::Notify;+use tokio_util::sync::CancellationToken;++/// How often each Dev mode space is read, unless `KWANT_DEV_POLL_SECS` says otherwise ([`super::poll_every`]).+pub const EVERY: std::time::Duration = std::time::Duration::from_secs(5 * 60);+/// Merges a space's first poll back-fills, so the desk isn't empty on day one.+pub const BACKFILL: usize = 5;+/// Most new merges one poll turns into cards (a long pause or a force-push takes the newest).+pub const MAX_NEW: usize = 20;+/// Most new review heads one poll reads (each costs a few requests).+pub const MAX_REVIEWS: usize = 10;+/// Files whose history is read for `first_edit_files`.+pub const FIRST_EDIT_FILES: usize = 20;+/// "First edit" means no commit to the file in this many days.+pub const FIRST_EDIT_DAYS: i64 = 90;+/// Cards whose CI was still running are re-read for this long after they were made.+pub const CI_RECHECK_HOURS: i64 = 6;+/// Most cards one poll re-reads CI for.+pub const CI_RECHECK_CARDS: usize = 10;++#[derive(Default)]+struct Shared {+ /// Spaces to poll at the next wake, ahead of the timer.+ soon: HashSet<String>,+ /// A space backed off after a rate limit is left alone until then.+ resume_at: HashMap<String, DateTime<Utc>>,+ /// The newest tag of each space's repo, and when its commit was made.+ tags: HashMap<String, (String, Option<DateTime<Utc>>)>,+}++fn shared() -> &'static Mutex<Shared> {+ static S: OnceLock<Mutex<Shared>> = OnceLock::new();+ S.get_or_init(Default::default)+}++fn wake() -> &'static Notify {+ static N: OnceLock<Notify> = OnceLock::new();+ N.get_or_init(Notify::new)+}++fn etags() -> &'static EtagCache {+ static C: OnceLock<EtagCache> = OnceLock::new();+ C.get_or_init(EtagCache::default)+}++/// Polls `space_id` now instead of at the next tick (the switch went on, the repo moved).+pub fn poll_soon(_state: &AppState, space_id: &str) {+ shared().lock().unwrap().soon.insert(space_id.to_string());+ wake().notify_one();+}++/// The newest tag the last poll saw on the space's repo.+pub fn last_tag(space_id: &str) -> Option<String> {+ shared().lock().unwrap().tags.get(space_id).map(|(t, _)| t.clone())+}++/// When the newest tag's commit was made: release notes cover the landed cards after it.+pub fn last_tag_at(space_id: &str) -> Option<DateTime<Utc>> {+ shared().lock().unwrap().tags.get(space_id).and_then(|(_, at)| *at)+}++/// Starts the poller, after picking up what a restart left: pending cards go to `generate`+/// again, and a Fix it whose task never went out is sent.+pub fn spawn(state: AppState, shutdown: CancellationToken) {+ tokio::spawn(async move {+ recover(&state).await;+ let mut next_all = Utc::now();+ loop {+ let now = Utc::now();+ let all = now >= next_all;+ if all {+ next_all = now + Duration::from_std(super::poll_every()).unwrap_or(Duration::minutes(5));+ }+ let soon = std::mem::take(&mut shared().lock().unwrap().soon);+ match state.db.dev_mode_on_spaces().await {+ Ok(rows) => {+ for row in rows.into_iter().filter(|r| all || soon.contains(&r.space_id)) {+ if shutdown.is_cancelled() {+ return;+ }+ poll_logged(&state, row).await;+ }+ }+ Err(e) => tracing::warn!("dev: could not list Dev mode spaces: {e}"),+ }+ let wait = (next_all - Utc::now()).to_std().unwrap_or_default();+ tokio::select! {+ _ = shutdown.cancelled() => return,+ _ = wake().notified() => {}+ _ = tokio::time::sleep(wait) => {}+ }+ }+ });+}++async fn recover(state: &AppState) {+ match state.db.pending_dev_cards().await {+ Ok(rows) => {+ for r in rows {+ super::generate(state.clone(), r.id).await;+ }+ }+ Err(e) => tracing::warn!("dev: could not read pending cards: {e}"),+ }+ let Ok(spaces) = state.db.dev_mode_on_spaces().await else { return };+ for m in spaces {+ let Ok(cards) = state.db.dev_cards(&m.space_id, REVIEW, None, 200).await else { continue };+ for c in cards {+ let Some(card) = c.card.as_deref().and_then(|j| serde_json::from_str::<serde_json::Value>(j).ok()) else { continue };+ for f in card["findings"].as_array().into_iter().flatten() {+ if f["state"] == "sent" && !f["task_id"].is_string() {+ if let Some(fid) = f["id"].as_str() {+ let (state, card_id, fid) = (state.clone(), c.id.clone(), fid.to_string());+ tokio::spawn(async move {+ tokio::time::sleep(std::time::Duration::from_secs(super::routes::FIX_UNDO_SECS)).await;+ super::routes::deliver_fix(&state, &card_id, &fid).await;+ });+ }+ }+ }+ }+ }+}++/// [`poll`] with its outcome recorded: the poll error on the settings, and a back-off after a+/// rate limit. Public for the leak tests (`tests/dev_github_test.rs`).+pub async fn poll_logged(state: &AppState, row: DevModeRow) {+ let space = row.space_id.clone();+ if shared().lock().unwrap().resume_at.get(&space).is_some_and(|t| *t > Utc::now()) {+ return;+ }+ let result = poll(state, &row).await;+ let error = match &result {+ Ok(()) => None,+ Err(GhError::Limited { retry_after_s }) => {+ shared().lock().unwrap().resume_at.insert(space.clone(), Utc::now() + Duration::seconds(*retry_after_s as i64));+ Some(GhError::Limited { retry_after_s: *retry_after_s }.to_string())+ }+ Err(e) => Some(e.to_string()),+ };+ if let Some(e) = &error {+ tracing::info!(space = %space, "dev: poll failed: {e}");+ let _ = state.db.dev_mode_polled(&space, None, Some(e)).await;+ }+}++/// One poll of one space. Merges are recorded as `last_seen_sha` one by one, so a failure part+/// way keeps the ones done.+pub async fn poll(state: &AppState, mode: &DevModeRow) -> Result<(), GhError> {+ let space = SpaceId::new(&mode.space_id);+ let (client, _) = repo::client_for(state, &mode.repo).await?;+ let kwants = state.db.list_kwants(&space).await.unwrap_or_default();+ let cache = etags();++ // The newest tag, for release notes+ if let Ok(tag) = client.dev_latest_tag(&mode.repo, cache).await {+ update_tag(&client, mode, tag).await;+ }++ // What landed+ let (commits, found) = client.dev_commits_since(&mode.repo, &mode.branch, mode.last_seen_sha.as_deref(), cache).await?;+ let mut last = None;+ for c in window(commits, mode.last_seen_sha.is_none(), found) {+ landed(state, &client, mode, &kwants, &c).await?;+ last = Some(c.sha.clone());+ }+ state.db.dev_mode_polled(&mode.space_id, last.as_deref(), None).await.map_err(|e| GhError::Other(e.to_string()))?;++ // Open PRs+ let pulls = client.dev_open_pulls(&mode.repo, &mode.branch, cache).await?;+ reviews(state, &client, mode, &kwants, &pulls).await?;++ // CI that was still running+ recheck_ci(state, &client, mode).await;+ Ok(())+}++async fn update_tag(client: &GithubSource, mode: &DevModeRow, tag: Option<(String, Option<String>)>) {+ let Some((name, sha)) = tag else {+ shared().lock().unwrap().tags.remove(&mode.space_id);+ return;+ };+ if shared().lock().unwrap().tags.get(&mode.space_id).is_some_and(|(t, at)| *t == name && at.is_some()) {+ return;+ }+ let at = match sha {+ Some(s) => client.dev_commit(&mode.repo, &s).await.ok().and_then(|c| c.commit.committer.date.or(c.commit.author.date)),+ None => None,+ };+ shared().lock().unwrap().tags.insert(mode.space_id.clone(), (name, at));+}++/// Which of the new commits (oldest first) become cards: the newest [`BACKFILL`] on a space's+/// first poll, else up to [`MAX_NEW`] (the newest, when there were more or `last_seen` was lost).+pub fn window(commits: Vec<GhCommit>, first: bool, _found: bool) -> Vec<GhCommit> {+ let keep = if first { BACKFILL } else { MAX_NEW };+ let skip = commits.len().saturating_sub(keep);+ commits.into_iter().skip(skip).collect()+}++/// The merged PR a commit on the branch is the merge (or squash) commit of. `Err(())` when the+/// commit is one of several a rebase-merge put on the branch and isn't the last: the PR's card+/// is made from its merge commit, so this one is skipped.+pub(crate) fn merged_pr<'a>(pulls: &'a [GhPull], sha: &str, branch: &str) -> Result<Option<&'a GhPull>, ()> {+ let merged: Vec<&GhPull> = pulls.iter().filter(|p| p.merged_at.is_some() && p.base.branch == branch).collect();+ if let Some(p) = merged.iter().find(|p| p.merge_commit_sha.as_deref() == Some(sha)) {+ return Ok(Some(p));+ }+ if merged.is_empty() {+ Ok(None)+ } else {+ Err(())+ }+}++async fn landed(state: &AppState, client: &GithubSource, mode: &DevModeRow, kwants: &[Kwant], c: &GhCommit) -> Result<(), GhError> {+ if state.db.dev_cards_of_ref(&mode.space_id, LANDED, &c.sha).await.map(|v| !v.is_empty()).unwrap_or(false) {+ return Ok(());+ }+ let pulls = client.dev_pulls_for_commit(&mode.repo, &c.sha).await.unwrap_or_default();+ let Ok(pr) = merged_pr(&pulls, &c.sha, &mode.branch) else { return Ok(()) };+ let full = client.dev_commit(&mode.repo, &c.sha).await?;+ let files = match pr {+ Some(p) => client.dev_pull_files(&mode.repo, p.number).await?,+ None => full.files.clone(),+ };+ let checks = client.dev_check_runs(&mode.repo, &c.sha, etags()).await.unwrap_or_default();+ let until = pr.and_then(|p| p.merged_at).or(full.commit.committer.date).unwrap_or_else(Utc::now) - Duration::seconds(1);+ let first = first_edits(client, mode, &files, until).await;+ let facts = landed_facts(mode, &full, pr, files, checks, kwants, first);+ insert(state, &mode.space_id, LANDED, &c.sha, &c.sha, &facts).await;+ Ok(())+}++async fn reviews(state: &AppState, client: &GithubSource, mode: &DevModeRow, kwants: &[Kwant], pulls: &[GhPull]) -> Result<(), GhError> {+ let mut open = HashSet::new();+ let mut read = 0;+ for p in pulls {+ let ref_ = format!("pr:{}", p.number);+ open.insert(ref_.clone());+ if p.draft {+ // Drafts are skipped (D8); a PR that went back to draft loses its card+ stale(state, &mode.space_id, &ref_, None).await;+ continue;+ }+ let have = state.db.dev_cards_of_ref(&mode.space_id, REVIEW, &ref_).await.unwrap_or_default();+ if have.iter().any(|c| c.head_sha == p.head.sha) {+ stale(state, &mode.space_id, &ref_, Some(&p.head.sha)).await;+ continue;+ }+ if read >= MAX_REVIEWS {+ continue;+ }+ read += 1;+ let files = client.dev_pull_files(&mode.repo, p.number).await?;+ let head = client.dev_commit(&mode.repo, &p.head.sha).await.ok();+ let checks = client.dev_check_runs(&mode.repo, &p.head.sha, etags()).await.unwrap_or_default();+ let first = first_edits(client, mode, &files, Utc::now()).await;+ let facts = review_facts(mode, p, head.as_ref(), files, checks, kwants, first);+ insert(state, &mode.space_id, REVIEW, &ref_, &p.head.sha, &facts).await;+ stale(state, &mode.space_id, &ref_, Some(&p.head.sha)).await;+ }+ // A PR that closed or merged: its review cards go stale+ if let Ok(cards) = state.db.dev_cards(&mode.space_id, REVIEW, None, 200).await {+ let gone: HashSet<String> = cards.into_iter().filter(|c| c.status != STALE && !open.contains(&c.ref_)).map(|c| c.ref_).collect();+ for r in gone {+ stale(state, &mode.space_id, &r, None).await;+ }+ }+ Ok(())+}++async fn stale(state: &AppState, space_id: &str, ref_: &str, keep: Option<&str>) {+ for id in state.db.stale_dev_reviews(space_id, ref_, keep).await.unwrap_or_default() {+ if let Ok(Some(row)) = state.db.dev_card(&id).await {+ super::notify_card(state, &row);+ }+ }+}++async fn insert(state: &AppState, space_id: &str, kind: &str, ref_: &str, head: &str, facts: &DevFacts) {+ let Ok(json) = serde_json::to_string(facts) else { return };+ match state.db.insert_dev_card(space_id, kind, ref_, head, &json).await {+ Ok(Some(row)) => {+ super::notify_card(state, &row);+ tokio::spawn(super::generate(state.clone(), row.id));+ }+ Ok(None) => {}+ Err(e) => tracing::warn!(space = %space_id, "dev: could not save a card: {e}"),+ }+}++/// Landed and review cards made in the last [`CI_RECHECK_HOURS`] whose CI was pending: read the+/// checks again, and when they changed, store them and run `generate` again.+async fn recheck_ci(state: &AppState, client: &GithubSource, mode: &DevModeRow) {+ let since = Utc::now() - Duration::hours(CI_RECHECK_HOURS);+ let mut rows: Vec<DevCardRow> = Vec::new();+ for kind in [LANDED, REVIEW] {+ rows.extend(state.db.dev_cards(&mode.space_id, kind, None, 50).await.unwrap_or_default());+ }+ let mut done = 0;+ for row in rows.into_iter().filter(|r| r.created_at >= since && r.status != STALE && r.status != PENDING) {+ if done >= CI_RECHECK_CARDS {+ break;+ }+ let Ok(mut facts) = serde_json::from_str::<DevFacts>(&row.facts) else { continue };+ if facts.ci != CiState::Pending {+ continue;+ }+ done += 1;+ let Ok(checks) = client.dev_check_runs(&mode.repo, &row.head_sha, etags()).await else { continue };+ let checks = to_checks(checks);+ if checks == facts.checks {+ continue;+ }+ facts.ci = CiState::of(&checks);+ facts.links.ci = ci_link(&checks);+ facts.checks = checks;+ let Ok(json) = serde_json::to_string(&facts) else { continue };+ if let Ok(Some(r)) = state.db.set_dev_card_facts(&row.id, &json).await {+ super::notify_card(state, &r);+ tokio::spawn(super::generate(state.clone(), r.id));+ }+ }+}++/// The changed files (not new ones) nobody committed to in the last [`FIRST_EDIT_DAYS`] before+/// `until`, reading at most [`FIRST_EDIT_FILES`] histories.+async fn first_edits(client: &GithubSource, mode: &DevModeRow, files: &[GhFile], until: DateTime<Utc>) -> Vec<String> {+ let since = until - Duration::days(FIRST_EDIT_DAYS);+ let mut out = Vec::new();+ for f in files.iter().filter(|f| f.status != "added").take(FIRST_EDIT_FILES) {+ let path = f.previous_filename.as_deref().unwrap_or(&f.filename);+ if let Ok(0) = client.dev_path_commits(&mode.repo, &mode.branch, path, since, until).await {+ out.push(f.filename.clone());+ }+ }+ out+}++/// GitHub's files with their patches, cut so the patches add up to at most [`DIFF_CHARS`]: a+/// patch that doesn't fit is dropped whole, and `cut` says how many files weren't read.+pub fn cut_diffs(files: Vec<GhFile>) -> (Vec<FileDiff>, Option<String>) {+ let mut left = DIFF_CHARS;+ let mut unread = 0;+ let out = files+ .into_iter()+ .map(|f| {+ let patch = match f.patch {+ Some(p) if p.chars().count() <= left => {+ left -= p.chars().count();+ Some(p)+ }+ Some(_) => {+ unread += 1;+ None+ }+ None => None,+ };+ FileDiff { path: f.filename, status: f.status, additions: f.additions, deletions: f.deletions, patch, previous_path: f.previous_filename }+ })+ .collect();+ let cut = (unread > 0).then(|| format!("diff cut, {unread} {} not read", if unread == 1 { "file" } else { "files" }));+ (out, cut)+}++/// The kwant bot that wrote a commit (D7): git author name `Lin` or `Lin (kwant bot)`, or an+/// email whose local part is `lin-bot`, matched case-insensitively to a bot in the space.+pub fn match_bot(name: &str, email: Option<&str>, kwants: &[Kwant]) -> Option<KwantRef> {+ let name = name.trim();+ let bare = name.strip_suffix("(kwant bot)").map(str::trim).unwrap_or(name);+ let local = email.and_then(|e| e.split('@').next()).map(str::to_lowercase);+ let slug = |n: &str| n.trim().to_lowercase().split_whitespace().collect::<Vec<_>>().join("-");+ let hit = kwants+ .iter()+ .find(|k| !k.name.trim().is_empty() && k.name.trim().eq_ignore_ascii_case(bare))+ .or_else(|| kwants.iter().find(|k| local.as_deref().is_some_and(|l| !k.name.trim().is_empty() && l == format!("{}-bot", slug(&k.name)))))?;+ Some(KwantRef { id: hit.id.clone(), name: hit.name.clone(), engine: hit.driver_type.clone(), model: hit.preferred_model.clone() })+}++/// The commit message's first line, and the rest.+pub fn split_message(msg: &str) -> (String, String) {+ let mut it = msg.splitn(2, '\n');+ let title = it.next().unwrap_or("").trim().to_string();+ let body = it.next().unwrap_or("").trim().to_string();+ (title, body)+}++fn https(u: Option<&str>) -> Option<String> {+ u.filter(|u| u.starts_with("https://")).map(str::to_string)+}++fn to_checks(cs: Vec<GhCheck>) -> Vec<Check> {+ let mut v: Vec<Check> = cs.into_iter().map(|c| Check { name: c.name, status: c.status, conclusion: c.conclusion, url: https(c.html_url.as_deref()) }).collect();+ v.sort_by(|a, b| a.name.cmp(&b.name));+ v+}++/// The CI link: the first failed check's page, else the first check's.+fn ci_link(checks: &[Check]) -> Option<String> {+ let bad = |c: &&Check| matches!(c.conclusion.as_deref(), Some("failure" | "timed_out" | "cancelled" | "action_required" | "startup_failure"));+ checks.iter().find(bad).or(checks.first()).and_then(|c| c.url.clone())+}++fn author_of(commit: Option<&GhCommit>, pr: Option<&GhPull>, kwants: &[Kwant]) -> Author {+ let login = pr.and_then(|p| p.user.as_ref()).or(commit.and_then(|c| c.author.as_ref())).map(|u| u.login.clone());+ let name = commit.map(|c| c.commit.author.name.clone()).filter(|n| !n.trim().is_empty()).or_else(|| login.clone()).unwrap_or_default();+ let email = commit.and_then(|c| c.commit.author.email.clone());+ let bot = match_bot(&name, email.as_deref(), kwants);+ Author { login, name, email, bot }+}++pub fn landed_facts(mode: &DevModeRow, c: &GhCommit, pr: Option<&GhPull>, files: Vec<GhFile>, checks: Vec<GhCheck>, kwants: &[Kwant], first: Vec<String>) -> DevFacts {+ let (msg_title, msg_body) = split_message(&c.commit.message);+ let (files, cut) = cut_diffs(files);+ let checks = to_checks(checks);+ DevFacts {+ repo: mode.repo.clone(),+ kind: Kind::Landed,+ pr: pr.map(|p| p.number),+ title: pr.map(|p| p.title.trim().to_string()).filter(|t| !t.is_empty()).unwrap_or(msg_title),+ body: pr.and_then(|p| p.body.clone()).unwrap_or(msg_body),+ head_sha: c.sha.clone(),+ base_branch: mode.branch.clone(),+ merged_at: pr.and_then(|p| p.merged_at).or(c.commit.committer.date),+ merged_by: pr.and_then(|p| p.merged_by.as_ref()).map(|u| u.login.clone()),+ author: author_of(Some(c), pr, kwants),+ files,+ cut,+ ci: CiState::of(&checks),+ links: Links { pr: https(pr.and_then(|p| p.html_url.as_deref())), commit: https(c.html_url.as_deref()), ci: ci_link(&checks) },+ checks,+ task: None,+ first_edit_files: first,+ draft: false,+ head_branch: None,+ }+}++pub fn review_facts(mode: &DevModeRow, p: &GhPull, head: Option<&GhCommit>, files: Vec<GhFile>, checks: Vec<GhCheck>, kwants: &[Kwant], first: Vec<String>) -> DevFacts {+ let (files, cut) = cut_diffs(files);+ let checks = to_checks(checks);+ DevFacts {+ repo: mode.repo.clone(),+ kind: Kind::Review,+ pr: Some(p.number),+ title: p.title.trim().to_string(),+ body: p.body.clone().unwrap_or_default(),+ head_sha: p.head.sha.clone(),+ base_branch: p.base.branch.clone(),+ merged_at: None,+ merged_by: None,+ author: author_of(head, Some(p), kwants),+ files,+ cut,+ ci: CiState::of(&checks),+ links: Links { pr: https(p.html_url.as_deref()), commit: https(head.and_then(|c| c.html_url.as_deref())), ci: ci_link(&checks) },+ checks,+ task: None,+ first_edit_files: first,+ draft: p.draft,+ head_branch: Some(p.head.branch.clone()),+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ fn file(name: &str, patch_len: Option<usize>) -> GhFile {+ serde_json::from_value(json!({"filename": name, "status": "modified", "additions": 3, "deletions": 1, "patch": patch_len.map(|n| "x".repeat(n))})).unwrap()+ }++ fn kwant(id: &str, name: &str) -> Kwant {+ serde_json::from_value(json!({+ "id": id, "name": name, "title": "Engineer", "persona_prompt": "", "soul": "", "avatar_sprite": "",+ "driver_type": "claude", "preferred_model": "demo-model", "temperature": 0.0, "max_tokens": 0,+ "level": 1, "turns_completed": 0, "created_at": null, "space_id": "s1"+ }))+ .unwrap()+ }++ fn pull(n: u64, merge: Option<&str>, merged: bool, base: &str) -> GhPull {+ serde_json::from_value(json!({+ "number": n, "title": format!("PR {n}"), "state": if merged { "closed" } else { "open" }, "draft": false,+ "head": {"ref": "feature", "sha": "h1"}, "base": {"ref": base, "sha": "b1"},+ "merged_at": if merged { json!("2026-11-05T01:00:00Z") } else { json!(null) },+ "merge_commit_sha": merge,+ }))+ .unwrap()+ }++ fn commit(sha: &str) -> GhCommit {+ serde_json::from_value(json!({+ "sha": sha, "html_url": format!("https://github.com/demo-org/app/commit/{sha}"),+ "commit": {"message": "Fix the thing\n\nLonger words.", "author": {"name": "Lin (kwant bot)", "email": "[email protected]", "date": "2026-11-05T01:00:00Z"},+ "committer": {"name": "GitHub", "email": "[email protected]", "date": "2026-11-05T01:00:00Z"}},+ "parents": []+ }))+ .unwrap()+ }++ #[test]+ fn diffs_are_cut_at_sixty_thousand_characters() {+ let (files, cut) = cut_diffs(vec![file("a.rs", Some(40_000)), file("b.rs", Some(30_000)), file("c.rs", Some(20_000)), file("logo.png", None)]);+ assert!(files[0].patch.is_some());+ assert!(files[1].patch.is_none(), "40k + 30k is past 60k: b is dropped whole");+ assert!(files[2].patch.is_some(), "a later smaller patch still fits");+ assert!(files[3].patch.is_none());+ assert_eq!(cut.as_deref(), Some("diff cut, 1 file not read"));+ let total: usize = files.iter().filter_map(|f| f.patch.as_ref()).map(|p| p.len()).sum();+ assert!(total <= DIFF_CHARS);+ let (_, cut) = cut_diffs(vec![file("a.rs", Some(60_000))]);+ assert_eq!(cut, None, "exactly 60k fits");+ let (_, cut) = cut_diffs(vec![file("a.rs", Some(60_001)), file("b.rs", Some(60_001))]);+ assert_eq!(cut.as_deref(), Some("diff cut, 2 files not read"));+ }++ #[test]+ fn authors_match_bots_by_name_or_bot_email() {+ let ks = [kwant("k1", "Lin"), kwant("k2", "Flix Dev"), kwant("k3", "")];+ assert_eq!(match_bot("Lin (kwant bot)", None, &ks).unwrap().id, "k1");+ assert_eq!(match_bot("lin", None, &ks).unwrap().id, "k1");+ assert_eq!(match_bot("Someone", Some("[email protected]"), &ks).unwrap().id, "k2");+ let r = match_bot("Lin", None, &ks).unwrap();+ assert_eq!((r.engine.as_str(), r.model.as_str()), ("claude", "demo-model"));+ assert_eq!(match_bot("Oleks Demo", Some("[email protected]"), &ks), None, "a person isn't a bot");+ assert_eq!(match_bot("", Some("[email protected]"), &ks), None, "an unnamed bot never matches");+ assert_eq!(match_bot("Linus", Some("[email protected]"), &ks), None);+ }++ #[test]+ fn the_first_poll_backfills_five_and_later_ones_twenty() {+ let cs: Vec<GhCommit> = (0..30).map(|i| commit(&format!("c{i:02}"))).collect();+ let w = window(cs.clone(), true, false);+ assert_eq!(w.iter().map(|c| c.sha.as_str()).collect::<Vec<_>>(), ["c25", "c26", "c27", "c28", "c29"]);+ let w = window(cs.clone(), false, true);+ assert_eq!(w.len(), MAX_NEW);+ assert_eq!(w.last().unwrap().sha, "c29", "the newest are kept");+ assert_eq!(window(cs[..3].to_vec(), false, true).len(), 3);+ }++ #[test]+ fn a_merge_commit_finds_its_pr_and_rebased_commits_are_skipped() {+ let squash = [pull(7, Some("m1"), true, "main")];+ assert_eq!(merged_pr(&squash, "m1", "main").unwrap().unwrap().number, 7);+ assert!(merged_pr(&squash, "earlier", "main").is_err(), "an earlier commit of a rebase-merge");+ assert!(merged_pr(&[pull(8, Some("m2"), true, "release")], "m2", "main").unwrap().is_none(), "a PR into another branch");+ assert!(merged_pr(&[pull(9, None, false, "main")], "x", "main").unwrap().is_none(), "an open PR containing the commit");+ assert!(merged_pr(&[], "direct", "main").unwrap().is_none(), "a direct push");+ }++ #[test]+ fn landed_facts_prefer_the_pr_and_keep_links_https() {+ let mode = DevModeRow {+ space_id: "s1".into(),+ on: true,+ provider: "github".into(),+ repo: "demo-org/app".into(),+ branch: "main".into(),+ deploy_hint: None,+ backup_command: None,+ last_seen_sha: None,+ polled_at: None,+ poll_error: None,+ seen_at: None,+ updated_at: Utc::now(),+ };+ let c = commit("m1");+ let mut p = pull(7, Some("m1"), true, "main");+ p.html_url = Some("javascript:alert(1)".into());+ let checks: Vec<GhCheck> = serde_json::from_value(json!([+ {"name": "rust", "status": "completed", "conclusion": "failure", "html_url": "https://github.com/demo-org/app/actions/runs/1"},+ {"name": "frontend", "status": "completed", "conclusion": "success", "html_url": "https://github.com/demo-org/app/actions/runs/2"}+ ]))+ .unwrap();+ let f = landed_facts(&mode, &c, Some(&p), vec![file("src/a.rs", Some(10))], checks, &[kwant("k1", "Lin")], vec!["src/a.rs".into()]);+ assert_eq!(f.pr, Some(7));+ assert_eq!(f.title, "PR 7");+ assert_eq!(f.ci, CiState::Red);+ assert_eq!(f.links.pr, None, "a non-https link is dropped");+ assert_eq!(f.links.ci.as_deref(), Some("https://github.com/demo-org/app/actions/runs/1"), "the failing check");+ assert_eq!(f.author.bot.unwrap().id, "k1");+ assert_eq!(f.checks[0].name, "frontend", "checks are sorted so a re-read compares equal");+ let f = landed_facts(&mode, &c, None, vec![], vec![], &[], vec![]);+ assert_eq!((f.title.as_str(), f.body.as_str()), ("Fix the thing", "Longer words."));+ assert_eq!(f.ci, CiState::None);+ assert_eq!(f.links.commit.as_deref(), Some("https://github.com/demo-org/app/commit/m1"));+ }+}diff --git a/src/server/dev/repo.rs b/src/server/dev/repo.rsnew file mode 100644index 00000000..e21a4f44--- /dev/null+++ b/src/server/dev/repo.rs@@ -0,0 +1,249 @@+//! The repo check (plan §3.2 `POST /dev_mode/check`, D4): one GitHub repo per space, read+//! through the Loose ends GitHub connection (its vault token and Enterprise `api_base`).+//! kwant writes nothing to GitHub.++use crate::db::spaces::SpaceId;+use crate::server::AppState;+use crate::zombie::github::{GhError, GithubConfig, GithubSource};+use serde::Serialize;++/// `owner/name` from what a person pastes: `owner/name`, a web URL (with or without `.git`,+/// `/tree/main`, a query), `github.com/owner/name`, `git@host:owner/name.git` or+/// `ssh://git@host/owner/name.git`. Returns the host it named, if any, and `owner/name`.+pub fn normalize(input: &str) -> Option<(Option<String>, String)> {+ let s = input.trim();+ if s.is_empty() || s.len() > 300 || s.chars().any(char::is_whitespace) {+ return None;+ }+ let (host, path) = if let Some(rest) = s.strip_prefix("git@") {+ // scp-like: [email protected]:owner/name.git+ let (host, path) = rest.split_once(':')?;+ (Some(host.to_string()), path.to_string())+ } else if s.contains("://") {+ let s = s.strip_prefix("git+").unwrap_or(s);+ let url = url::Url::parse(s).ok()?;+ if !matches!(url.scheme(), "https" | "http" | "ssh" | "git") || url.password().is_some() {+ return None;+ }+ (url.host_str().map(str::to_string), url.path().to_string())+ } else if let Some((first, rest)) = s.split_once('/') {+ // `github.com/owner/name` or plain `owner/name`+ if first.contains('.') && rest.contains('/') {+ (Some(first.to_string()), rest.to_string())+ } else {+ (None, s.to_string())+ }+ } else {+ return None;+ };+ let mut parts = path.trim_matches('/').split('/');+ let owner = parts.next()?;+ let name = parts.next()?;+ let name = name.strip_suffix(".git").unwrap_or(name);+ // Owner and repo names are ASCII letters, digits, `-`, `_` and `.` on GitHub+ let ok = |p: &str| !p.is_empty() && p != "." && p != ".." && !p.starts_with('-') && p.chars().all(|c| c.is_ascii_alphanumeric() || "-_.".contains(c));+ if !ok(owner) || !ok(name) || owner.len() > 100 || name.len() > 100 {+ return None;+ }+ // A plain `owner/name/extra` isn't a repo; a URL path may go on (`/tree/main`, `/pull/3`)+ if host.is_none() && parts.next().is_some() {+ return None;+ }+ Some((host.map(|h| h.to_lowercase()), format!("{owner}/{name}")))+}++/// The web host repos of this API base live on: `api.github.com` → `github.com`,+/// `https://ghe.example/api/v3` → `ghe.example`.+pub fn web_host(cfg: &GithubConfig) -> String {+ let host = url::Url::parse(cfg.api_base.trim()).ok().and_then(|u| u.host_str().map(str::to_lowercase)).unwrap_or_default();+ if host == "api.github.com" {+ "github.com".into()+ } else {+ host+ }+}++/// What a repo's root says about how it ships (plan §3.1 `deploy_hint`).+pub fn deploy_hint(root: &[String]) -> Option<&'static str> {+ let has = |n: &str| root.iter().any(|r| r.eq_ignore_ascii_case(n));+ if has("fly.toml") {+ Some("fly")+ } else if has("wrangler.toml") || has("wrangler.json") || has("wrangler.jsonc") {+ Some("cloudflare_pages")+ } else if ["docker-compose.yml", "docker-compose.yaml", "compose.yml", "compose.yaml", "Dockerfile"].iter().any(|n| has(n)) {+ Some("docker")+ } else {+ None+ }+}++/// The reply of `POST /dev_mode/check`.+#[derive(Debug, Clone, Serialize, PartialEq)]+pub struct Check {+ /// `found`, `not_found` or `not_connected`.+ pub state: &'static str,+ pub repo: Option<String>,+ pub branch: Option<String>,+ pub deploy_hint: Option<&'static str>,+}++impl Check {+ fn of(state: &'static str, repo: Option<String>) -> Self {+ Check { state, repo, branch: None, deploy_hint: None }+ }+}++/// The GitHub connections Loose ends has, as Dev mode clients, enabled ones first. `Err` says+/// why there is none (no connection, a locked vault).+pub async fn clients(state: &AppState) -> Result<Vec<(GithubConfig, GithubSource)>, String> {+ let mut rows: Vec<_> = state.db.zombie_sources().await.map_err(|e| e.to_string())?.into_iter().filter(|r| r.kind == "github").collect();+ rows.sort_by_key(|r| !r.enabled);+ let mut out = Vec::new();+ let mut why = "Connect GitHub in Loose ends first: Dev mode reads the repo with that token".to_string();+ for row in rows {+ let Ok(cfg) = serde_json::from_str::<GithubConfig>(&row.config) else { continue };+ if cfg.validate().is_err() {+ continue;+ }+ match crate::zombie::hunt::source_secret(state.credentials.as_ref(), &row.id, &cfg.vault_origin()).await {+ Ok(Some(token)) => out.push((cfg.clone(), GithubSource::for_dev(&row.id, cfg, token))),+ Ok(None) => {}+ Err(crate::sandbox::credentials::StoreError::Locked) => why = "The password vault is locked: unlock it so kwant can read GitHub".into(),+ Err(e) => tracing::warn!(source = %row.id, "dev: vault read failed: {e}"),+ }+ }+ if out.is_empty() {+ Err(why)+ } else {+ Ok(out)+ }+}++/// The client whose connection can read `repo` (the first that finds it), with the repo.+pub async fn client_for(state: &AppState, repo: &str) -> Result<(GithubSource, crate::zombie::github::GhRepo), GhError> {+ let list = clients(state).await.map_err(|_| GhError::Auth)?;+ let mut last = GhError::NotFound;+ for (_, c) in list {+ match c.dev_repo(repo).await {+ Ok(r) => return Ok((c, r)),+ Err(e @ GhError::Limited { .. }) => return Err(e),+ Err(e) => last = e,+ }+ }+ Err(last)+}++/// The repo a space's teams point at, normalised: the first team whose `repo_url` reads.+pub async fn prefill(state: &AppState, space: &SpaceId) -> Option<String> {+ let teams = state.db.list_teams(space).await.ok()?;+ teams.iter().filter_map(|t| t.repo_url.as_deref()).find_map(normalize).map(|(_, r)| r)+}++/// Checks `input` (or the team's repo when it's empty). `Err` is a GitHub failure that is+/// neither found nor not found (a rate limit, GitHub down): the route answers 502 with it.+pub async fn check(state: &AppState, space: &SpaceId, input: &str) -> Result<Check, String> {+ let input = if input.trim().is_empty() { prefill(state, space).await.unwrap_or_default() } else { input.to_string() };+ let Some((host, repo)) = normalize(&input) else {+ return Ok(Check::of("not_found", None));+ };+ let list = match clients(state).await {+ Ok(l) => l,+ Err(_) => return Ok(Check::of("not_connected", Some(repo))),+ };+ let mut answer = Check::of("not_found", Some(repo.clone()));+ let mut refused = 0;+ let total = list.len();+ for (cfg, client) in list {+ // A URL on another host isn't this connection's repo+ if let Some(h) = &host {+ let h = h.strip_prefix("www.").unwrap_or(h);+ if h != web_host(&cfg) && !(h == "github.com" && web_host(&cfg) == "github.com") {+ continue;+ }+ }+ match client.dev_repo(&repo).await {+ Ok(r) => {+ let root = client.dev_root_names(&r.full_name, &r.default_branch).await.unwrap_or_default();+ answer = Check { state: "found", repo: Some(r.full_name.clone()), branch: Some(r.default_branch.clone()), deploy_hint: deploy_hint(&root) };+ return Ok(answer);+ }+ Err(GhError::NotFound | GhError::Forbidden) => {}+ Err(GhError::Auth) => refused += 1,+ Err(e) => return Err(e.to_string()),+ }+ }+ // Every connection's token was refused: that's a connection problem, not a missing repo+ if refused > 0 && refused == total {+ answer.state = "not_connected";+ }+ Ok(answer)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn repo_urls_normalise_to_owner_and_name() {+ let r = |s: &str| normalize(s).map(|(h, r)| (h.unwrap_or_default(), r));+ let gh = |r: &str| Some(("github.com".to_string(), r.to_string()));+ assert_eq!(r("alexsergivan/kwant"), Some((String::new(), "alexsergivan/kwant".into())));+ assert_eq!(r(" alexsergivan/kwant "), Some((String::new(), "alexsergivan/kwant".into())));+ assert_eq!(r("https://github.com/alexsergivan/kwant"), gh("alexsergivan/kwant"));+ assert_eq!(r("https://github.com/alexsergivan/kwant.git"), gh("alexsergivan/kwant"));+ assert_eq!(r("https://github.com/alexsergivan/kwant/"), gh("alexsergivan/kwant"));+ assert_eq!(r("https://github.com/alexsergivan/kwant/tree/main/src"), gh("alexsergivan/kwant"));+ assert_eq!(r("https://github.com/alexsergivan/kwant/pull/301?x=1#y"), gh("alexsergivan/kwant"));+ assert_eq!(r("https://GitHub.com/alexsergivan/kwant"), gh("alexsergivan/kwant"));+ assert_eq!(r("github.com/alexsergivan/kwant"), gh("alexsergivan/kwant"));+ assert_eq!(r("[email protected]:alexsergivan/kwant.git"), gh("alexsergivan/kwant"));+ assert_eq!(r("[email protected]:alexsergivan/kwant"), gh("alexsergivan/kwant"));+ assert_eq!(r("ssh://[email protected]/alexsergivan/kwant.git"), gh("alexsergivan/kwant"));+ assert_eq!(r("git+https://github.com/alexsergivan/kwant.git"), gh("alexsergivan/kwant"));+ assert_eq!(r("https://ghe.example.com/team/app"), Some(("ghe.example.com".into(), "team/app".into())));+ assert_eq!(r("demo-org/my.site_2"), Some((String::new(), "demo-org/my.site_2".into())));+ }++ #[test]+ fn malformed_repos_are_refused() {+ for bad in [+ "",+ "kwant",+ "owner/",+ "/name",+ "owner/name/extra",+ "owner/..",+ "../name",+ "-owner/name",+ "owner name/x",+ "owner/na me",+ "https://github.com/onlyowner",+ "https://user:[email protected]/o/r",+ "file:///etc/passwd",+ "javascript:alert(1)/x",+ "owner/name;rm -rf",+ "owner/na%2e%2e",+ ] {+ assert_eq!(normalize(bad), None, "{bad:?}");+ }+ assert_eq!(normalize(&format!("o/{}", "n".repeat(101))), None);+ }++ #[test]+ fn the_web_host_follows_the_api_base() {+ assert_eq!(web_host(&GithubConfig { api_base: "https://api.github.com".into() }), "github.com");+ assert_eq!(web_host(&GithubConfig { api_base: "https://ghe.example.com/api/v3".into() }), "ghe.example.com");+ }++ #[test]+ fn the_deploy_hint_reads_the_repo_root() {+ let v = |xs: &[&str]| xs.iter().map(|s| s.to_string()).collect::<Vec<_>>();+ assert_eq!(deploy_hint(&v(&["Cargo.toml", "Dockerfile", "fly.toml"])), Some("fly"));+ assert_eq!(deploy_hint(&v(&["package.json", "wrangler.toml"])), Some("cloudflare_pages"));+ assert_eq!(deploy_hint(&v(&["wrangler.jsonc", "Dockerfile"])), Some("cloudflare_pages"));+ assert_eq!(deploy_hint(&v(&["docker-compose.yml"])), Some("docker"));+ assert_eq!(deploy_hint(&v(&["compose.yaml"])), Some("docker"));+ assert_eq!(deploy_hint(&v(&["dockerfile"])), Some("docker"));+ assert_eq!(deploy_hint(&v(&["README.md", "src/"])), None);+ }+}diff --git a/src/server/dev/review.rs b/src/server/dev/review.rsnew file mode 100644index 00000000..4a9d12b6--- /dev/null+++ b/src/server/dev/review.rs@@ -0,0 +1 @@+//! Dev mode card generation: review (Vega, plan §4).diff --git a/src/server/dev/risk.rs b/src/server/dev/risk.rsnew file mode 100644index 00000000..8fadad96--- /dev/null+++ b/src/server/dev/risk.rs@@ -0,0 +1 @@+//! Dev mode card generation: risk (Vega, plan §4).diff --git a/src/server/dev/routes.rs b/src/server/dev/routes.rsnew file mode 100644index 00000000..f04ae2fd--- /dev/null+++ b/src/server/dev/routes.rs@@ -0,0 +1,829 @@+//! Dev mode's HTTP API (plan §3.2). Every route is the person's, reads included: the settings+//! hold the backup command, and the cards hold the repo's diffs. `auth::person_only` lists them+//! and each handler also refuses a bot's turn token ([`refuse_agent_tokens`]).++use super::facts::{CiState, DevFacts, ReleaseFacts};+use super::{backup, notify_card, notify_mode, poller, repo};+use crate::db::dev_mode::{DevCardRow, DevModeRow, LANDED, PENDING, READY, RELEASE_NOTES, REVIEW, STALE};+use crate::db::spaces::SpaceId;+use crate::server::spaces::active_space;+use crate::server::AppState;+use axum::{+ extract::{Path, Query, State},+ http::{HeaderMap, StatusCode},+ response::{IntoResponse, Response},+ Json,+};+use chrono::{DateTime, Utc};+use serde::Deserialize;+use serde_json::{json, Map, Value};++pub const REFUSAL: &str = "only the person can read or change Dev mode";++/// How long Fix it waits before the finding reaches the bot, so Undo can take it back (design §5).+pub const FIX_UNDO_SECS: u64 = 10;++fn error(status: StatusCode, message: impl Into<String>) -> Response {+ (status, Json(json!({"error": message.into()}))).into_response()+}++fn internal(e: impl std::fmt::Display) -> Response {+ tracing::warn!("dev: {e}");+ error(StatusCode::INTERNAL_SERVER_ERROR, "Dev mode could not read or save that")+}++#[allow(clippy::result_large_err)]+async fn guard(state: &AppState, headers: &HeaderMap, id: &str) -> Result<SpaceId, Response> {+ super::super::mcp_suggest::refuse_agent_tokens(state, headers, REFUSAL).await?;+ active_space(state, id).await+}++// ---------------------------------------------------------------------------------------------+// Settings++/// `GET /api/spaces/:id/dev_mode` reply. With no row yet: off, the team's repo as a prefill.+#[allow(clippy::result_large_err)]+pub async fn mode_json(state: &AppState, space: &SpaceId) -> Result<Value, Response> {+ let row = state.db.dev_mode(space.as_str()).await.map_err(internal)?;+ let calls = state.db.dev_calls_today(space.as_str()).await.map_err(internal)?;+ Ok(match row {+ Some(r) => row_json(&r, calls),+ None => json!({+ "on": false,+ "repo": repo::prefill(state, space).await,+ "branch": null,+ "deploy_hint": null,+ "backup_command": null,+ "last_seen_sha": null,+ "polled_at": null,+ "poll_error": null,+ "calls_today": calls,+ "calls_cap": super::call_cap(),+ }),+ })+}++fn row_json(r: &DevModeRow, calls: i64) -> Value {+ json!({+ "on": r.on,+ "repo": if r.repo.is_empty() { None } else { Some(&r.repo) },+ "branch": if r.branch.is_empty() { None } else { Some(&r.branch) },+ "deploy_hint": r.deploy_hint,+ "backup_command": r.backup_command,+ "last_seen_sha": r.last_seen_sha,+ "polled_at": r.polled_at,+ "poll_error": r.poll_error,+ "calls_today": calls,+ "calls_cap": super::call_cap(),+ })+}++pub async fn get_mode(State(state): State<AppState>, headers: HeaderMap, Path(id): Path<String>) -> Response {+ let space = match guard(&state, &headers, &id).await {+ Ok(s) => s,+ Err(r) => return r,+ };+ match mode_json(&state, &space).await {+ Ok(v) => Json(v).into_response(),+ Err(r) => r,+ }+}++#[derive(Deserialize)]+pub struct CheckBody {+ #[serde(default)]+ pub repo: String,+}++pub async fn check(State(state): State<AppState>, headers: HeaderMap, Path(id): Path<String>, Json(body): Json<CheckBody>) -> Response {+ let space = match guard(&state, &headers, &id).await {+ Ok(s) => s,+ Err(r) => return r,+ };+ match repo::check(&state, &space, &body.repo).await {+ Ok(c) => Json(c).into_response(),+ Err(e) => error(StatusCode::BAD_GATEWAY, e),+ }+}++/// `Some(None)` is an explicit `null` (clear it); a missing field is `None` (keep it).+fn double_option<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<Option<String>>, D::Error> {+ Ok(Some(Option::deserialize(d)?))+}++#[derive(Deserialize)]+pub struct PutBody {+ pub on: bool,+ #[serde(default)]+ pub repo: Option<String>,+ #[serde(default)]+ pub branch: Option<String>,+ #[serde(default, deserialize_with = "double_option")]+ pub backup_command: Option<Option<String>>,+}++/// The longest backup command kept.+pub const BACKUP_COMMAND_CHARS: usize = 2_000;++/// A branch name GitHub would take (`git check-ref-format`, roughly).+pub fn valid_branch(b: &str) -> bool {+ !b.is_empty()+ && b.len() <= 200+ && !b.starts_with('-')+ && !b.starts_with('/')+ && !b.ends_with('/')+ && !b.ends_with(".lock")+ && !b.ends_with('.')+ && !b.contains("..")+ && !b.contains("//")+ && !b.contains("@{")+ && b.chars().all(|c| !c.is_control() && !c.is_whitespace() && !"~^:?*[\\".contains(c))+}++pub async fn put_mode(State(state): State<AppState>, headers: HeaderMap, Path(id): Path<String>, Json(body): Json<PutBody>) -> Response {+ let space = match guard(&state, &headers, &id).await {+ Ok(s) => s,+ Err(r) => return r,+ };+ let before = match state.db.dev_mode(space.as_str()).await {+ Ok(r) => r,+ Err(e) => return internal(e),+ };+ let backup_command = match body.backup_command {+ None => before.as_ref().and_then(|r| r.backup_command.clone()),+ Some(None) => None,+ Some(Some(c)) => {+ let c = c.trim().to_string();+ if c.chars().count() > BACKUP_COMMAND_CHARS || c.contains('\0') {+ return error(StatusCode::BAD_REQUEST, format!("the backup command must be at most {BACKUP_COMMAND_CHARS} characters"));+ }+ (!c.is_empty()).then_some(c)+ }+ };+ if let Some(b) = body.branch.as_deref().map(str::trim).filter(|b| !b.is_empty()) {+ if !valid_branch(b) {+ return error(StatusCode::BAD_REQUEST, "that isn't a branch name");+ }+ }+ let asked_repo = body.repo.as_deref().map(str::trim).filter(|r| !r.is_empty());+ let kept_repo = before.as_ref().map(|r| r.repo.clone()).filter(|r| !r.is_empty());+ let (repo_name, branch, hint) = if body.on {+ // Turning on (or staying on) needs a repo GitHub finds, through the person's connection+ let input = asked_repo.map(str::to_string).or(kept_repo.clone()).unwrap_or_default();+ let found = match repo::check(&state, &space, &input).await {+ Ok(c) => c,+ Err(e) => return error(StatusCode::BAD_GATEWAY, e),+ };+ if found.state != "found" {+ return (StatusCode::CONFLICT, Json(json!({"error": "Dev mode needs a repo kwant can read", "check": found}))).into_response();+ }+ let full = found.repo.clone().unwrap_or_default();+ let same_repo = before.as_ref().is_some_and(|r| r.repo.eq_ignore_ascii_case(&full));+ let branch = match body.branch.as_deref().map(str::trim).filter(|b| !b.is_empty()) {+ Some(b) => b.to_string(),+ None if same_repo && !before.as_ref().unwrap().branch.is_empty() => before.as_ref().unwrap().branch.clone(),+ None => found.branch.clone().unwrap_or_else(|| "main".into()),+ };+ if Some(&branch) != found.branch.as_ref() {+ match repo::client_for(&state, &full).await {+ Ok((c, _)) => match c.dev_branch_exists(&full, &branch).await {+ Ok(true) => {}+ Ok(false) => return error(StatusCode::CONFLICT, format!("{full} has no branch {branch}")),+ Err(e) => return error(StatusCode::BAD_GATEWAY, e.to_string()),+ },+ Err(e) => return error(StatusCode::BAD_GATEWAY, e.to_string()),+ }+ }+ (full, branch, found.deploy_hint.map(str::to_string))+ } else {+ // Off: settings are kept as given, nothing is fetched (D12)+ let repo_name = match asked_repo {+ Some(r) => match repo::normalize(r) {+ Some((_, n)) => n,+ None => return error(StatusCode::BAD_REQUEST, "that isn't a GitHub repo"),+ },+ None => kept_repo.unwrap_or_default(),+ };+ let same_repo = before.as_ref().is_some_and(|r| r.repo.eq_ignore_ascii_case(&repo_name));+ let branch = body.branch.as_deref().map(str::trim).filter(|b| !b.is_empty()).map(str::to_string).or_else(|| before.as_ref().filter(|_| same_repo).map(|r| r.branch.clone())).unwrap_or_default();+ let hint = before.as_ref().filter(|_| same_repo).and_then(|r| r.deploy_hint.clone());+ (repo_name, branch, hint)+ };+ let row = match state.db.put_dev_mode(space.as_str(), body.on, &repo_name, &branch, hint.as_deref(), backup_command.as_deref()).await {+ Ok(r) => r,+ Err(e) => return internal(e),+ };+ let was_on = before.as_ref().is_some_and(|r| r.on);+ tracing::info!(space = %space, on = body.on, repo = %row.repo, branch = %row.branch, "the person set Dev mode");+ if was_on != row.on {+ notify_mode(&state, space.as_str(), row.on);+ }+ if row.on {+ // Right after the switch is turned on (D5), and after a repo or branch change+ let moved = before.as_ref().is_none_or(|b| !b.on || b.repo != row.repo || b.branch != row.branch);+ if moved {+ poller::poll_soon(&state, space.as_str());+ }+ }+ let calls = state.db.dev_calls_today(space.as_str()).await.unwrap_or(0);+ Json(row_json(&row, calls)).into_response()+}++// ---------------------------------------------------------------------------------------------+// Cards++/// A card as the routes return it: `{id, kind, status, created_at, ...card}`. Before the card is+/// written (pending, failed, or the stub's ready with no text) a few fields come from the facts,+/// so the desk can show the PR it is about; the card's own fields win.+pub fn card_json(row: &DevCardRow) -> Value {+ let mut out = Map::new();+ if row.kind == LANDED || row.kind == REVIEW {+ if let Ok(f) = serde_json::from_str::<DevFacts>(&row.facts) {+ out.insert("pr".into(), json!(f.pr));+ out.insert("title".into(), json!(f.title));+ out.insert("links".into(), json!(f.links));+ if row.kind == LANDED {+ out.insert("sha".into(), json!(short(&f.head_sha)));+ out.insert("merged_at".into(), json!(f.merged_at));+ out.insert("merged_by".into(), json!(f.merged_by));+ } else {+ out.insert("branch".into(), json!(f.head_branch));+ out.insert("base".into(), json!(f.base_branch));+ out.insert("draft".into(), json!(f.draft));+ }+ }+ }+ if let Some(Value::Object(card)) = row.card.as_deref().and_then(|c| serde_json::from_str::<Value>(c).ok()) {+ out.extend(card);+ }+ out.insert("id".into(), json!(row.id));+ out.insert("kind".into(), json!(row.kind));+ out.insert("status".into(), json!(row.status));+ out.insert("created_at".into(), json!(row.created_at));+ Value::Object(out)+}++fn short(sha: &str) -> String {+ sha.chars().take(7).collect()+}++#[derive(Deserialize)]+pub struct LandedQuery {+ pub before: Option<DateTime<Utc>>,+ pub limit: Option<i64>,+}++/// How many cards the rollup reads back.+const ROLLUP_WINDOW: i64 = 200;++pub async fn landed(State(state): State<AppState>, headers: HeaderMap, Path(id): Path<String>, Query(q): Query<LandedQuery>) -> Response {+ let space = match guard(&state, &headers, &id).await {+ Ok(s) => s,+ Err(r) => return r,+ };+ let limit = q.limit.unwrap_or(30).clamp(1, 100);+ let rows = match state.db.dev_cards(space.as_str(), LANDED, q.before, limit).await {+ Ok(r) => r,+ Err(e) => return internal(e),+ };+ let mode = state.db.dev_mode(space.as_str()).await.ok().flatten();+ let recent = match state.db.dev_cards(space.as_str(), LANDED, None, ROLLUP_WINDOW).await {+ Ok(r) => r,+ Err(e) => return internal(e),+ };+ let reviews = open_reviews(&state, &space).await.unwrap_or_default();+ let rollup = rollup(&recent, &reviews, mode.as_ref().and_then(|m| m.seen_at), Utc::now());+ Json(json!({+ "cards": rows.iter().map(card_json).collect::<Vec<_>>(),+ "rollup": rollup,+ "last_tag": poller::last_tag(space.as_str()),+ }))+ .into_response()+}++/// The desk's rollup (design §4): what landed since the person last looked.+/// - `since`: when they last looked (`null`: never, and every card counts).+/// - `count`: landed cards since then.+/// - `needs_you`: those with failed tests or a high risk, plus open reviews that are high risk or+/// have an open critical or high finding.+/// - `main_green`: CI on the newest landed card (`null` when it has no checks or is pending).+/// - `areas`: cards since then by `area`, newest area first, with the newest card's headline.+pub fn rollup(landed: &[DevCardRow], reviews: &[DevCardRow], since: Option<DateTime<Utc>>, now: DateTime<Utc>) -> Value {+ let fresh: Vec<&DevCardRow> = landed.iter().filter(|r| since.is_none_or(|s| r.created_at > s)).collect();+ let card = |r: &DevCardRow| r.card.as_deref().and_then(|c| serde_json::from_str::<Value>(c).ok()).unwrap_or(Value::Null);+ let mut needs = 0usize;+ for r in &fresh {+ let c = card(r);+ if c["tests"]["state"] == "failed" || c["risk"]["level"] == "high" {+ needs += 1;+ }+ }+ for r in reviews {+ let c = card(r);+ let hot = c["findings"].as_array().is_some_and(|fs| fs.iter().any(|f| f["state"] == "open" && matches!(f["severity"].as_str(), Some("critical" | "high"))));+ if c["risk"]["level"] == "high" || hot {+ needs += 1;+ }+ }+ let main_green = landed.first().and_then(|r| serde_json::from_str::<DevFacts>(&r.facts).ok()).and_then(|f| match f.ci {+ CiState::Green => Some(true),+ CiState::Red => Some(false),+ _ => None,+ });+ let mut areas: Vec<(String, usize, Option<String>)> = Vec::new();+ for r in &fresh {+ let c = card(r);+ let area = c["area"].as_str().filter(|a| !a.trim().is_empty()).unwrap_or("Other").to_string();+ match areas.iter_mut().find(|(a, _, _)| *a == area) {+ Some(e) => e.1 += 1,+ None => areas.push((area, 1, c["headline"].as_str().map(str::to_string))),+ }+ }+ json!({+ "since": since,+ "until": now,+ "count": fresh.len(),+ "needs_you": needs,+ "main_green": main_green,+ "areas": areas.into_iter().map(|(area, count, first_headline)| json!({"area": area, "count": count, "first_headline": first_headline})).collect::<Vec<_>>(),+ })+}++pub async fn seen(State(state): State<AppState>, headers: HeaderMap, Path(id): Path<String>) -> Response {+ let space = match guard(&state, &headers, &id).await {+ Ok(s) => s,+ Err(r) => return r,+ };+ let now = Utc::now();+ if let Err(e) = state.db.dev_mode_seen(space.as_str(), now).await {+ return internal(e);+ }+ Json(json!({"seen_at": now})).into_response()+}++/// Review cards still open: the newest card of each PR, stale ones left out, newest first.+async fn open_reviews(state: &AppState, space: &SpaceId) -> Result<Vec<DevCardRow>, crate::db::DbError> {+ let rows = state.db.dev_cards(space.as_str(), REVIEW, None, ROLLUP_WINDOW).await?;+ let mut seen = std::collections::HashSet::new();+ Ok(rows.into_iter().filter(|r| r.status != STALE).filter(|r| seen.insert(r.ref_.clone())).collect())+}++pub async fn reviews(State(state): State<AppState>, headers: HeaderMap, Path(id): Path<String>) -> Response {+ let space = match guard(&state, &headers, &id).await {+ Ok(s) => s,+ Err(r) => return r,+ };+ match open_reviews(&state, &space).await {+ Ok(rows) => Json(json!({"cards": rows.iter().map(card_json).collect::<Vec<_>>()})).into_response(),+ Err(e) => internal(e),+ }+}++/// `GET /api/dev/cards/:id`: one card of any kind, as the lists return it. The desk reads a+/// release notes draft here once its `dev_card` event says it is ready, since no list holds those.+/// 404 for no such card; a card in an archived space is refused like that space's lists.+pub async fn card(State(state): State<AppState>, headers: HeaderMap, Path(card_id): Path<String>) -> Response {+ if let Err(r) = super::super::mcp_suggest::refuse_agent_tokens(&state, &headers, REFUSAL).await {+ return r;+ }+ let row = match state.db.dev_card(card_id.trim()).await {+ Ok(Some(r)) => r,+ Ok(None) => return error(StatusCode::NOT_FOUND, "no such card"),+ Err(e) => return internal(e),+ };+ if let Err(r) = active_space(&state, &row.space_id).await {+ return r;+ }+ Json(card_json(&row)).into_response()+}++// ---------------------------------------------------------------------------------------------+// Findings++#[derive(Deserialize)]+pub struct FindingBody {+ pub action: String,+ #[serde(default)]+ pub reason: Option<String>,+ #[serde(default)]+ pub note: Option<String>,+}++pub const DISMISS_REASONS: [&str; 4] = ["not_a_problem", "fine_here", "later", "wrong"];+const NOTE_CHARS: usize = 500;++/// What a finding action does to the card JSON, or why it can't. Pure, so the rules are tested+/// without a database. `fix` sets `sent` with `sent_at` (the task goes out after the Undo window);+/// `undo_fix` puts it back to `open` (and says which task to cancel, if one went out); `dismiss`+/// stores the reason.+pub fn apply_finding(card: &mut Value, fid: &str, body: &FindingBody, now: DateTime<Utc>) -> Result<Option<String>, (StatusCode, String)> {+ let Some(f) = card["findings"].as_array_mut().and_then(|fs| fs.iter_mut().find(|f| f["id"] == fid)) else {+ return Err((StatusCode::NOT_FOUND, "no such finding on this card".into()));+ };+ let state = f["state"].as_str().unwrap_or("open").to_string();+ match body.action.as_str() {+ "fix" => {+ if state == "sent" {+ return Ok(None);+ }+ f["state"] = json!("sent");+ f["sent_at"] = json!(now);+ f["dismissed"] = Value::Null;+ Ok(None)+ }+ "undo_fix" => {+ if state != "sent" {+ return Err((StatusCode::CONFLICT, "this finding wasn't sent".into()));+ }+ let task = f["task_id"].as_str().map(str::to_string);+ f["state"] = json!("open");+ f["sent_at"] = Value::Null;+ if let Some(m) = f.as_object_mut() {+ m.remove("task_id");+ m.remove("sent_to");+ }+ Ok(task)+ }+ "dismiss" => {+ let reason = body.reason.as_deref().unwrap_or("");+ if !DISMISS_REASONS.contains(&reason) {+ return Err((StatusCode::BAD_REQUEST, "reason must be not_a_problem, fine_here, later or wrong".into()));+ }+ let note = body.note.as_deref().unwrap_or("").trim();+ if note.chars().count() > NOTE_CHARS {+ return Err((StatusCode::BAD_REQUEST, format!("the note must be at most {NOTE_CHARS} characters")));+ }+ if state == "sent" && f["task_id"].is_string() {+ return Err((StatusCode::CONFLICT, "this finding went to the bot already: undo the fix first".into()));+ }+ f["state"] = json!("dismissed");+ f["sent_at"] = Value::Null;+ f["dismissed"] = json!({"reason": reason, "note": note, "by": "person", "at": now});+ Ok(None)+ }+ _ => Err((StatusCode::BAD_REQUEST, "action must be fix, undo_fix or dismiss".into())),+ }+}++pub async fn finding(State(state): State<AppState>, headers: HeaderMap, Path((card_id, fid)): Path<(String, String)>, Json(body): Json<FindingBody>) -> Response {+ if let Err(r) = super::super::mcp_suggest::refuse_agent_tokens(&state, &headers, REFUSAL).await {+ return r;+ }+ // Two taps at once: the compare-and-set loses one, which reads again+ for _ in 0..3 {+ let row = match state.db.dev_card(&card_id).await {+ Ok(Some(r)) => r,+ Ok(None) => return error(StatusCode::NOT_FOUND, "no such card"),+ Err(e) => return internal(e),+ };+ if let Err(r) = active_space(&state, &row.space_id).await {+ return r;+ }+ let Some(mut card) = row.card.as_deref().and_then(|c| serde_json::from_str::<Value>(c).ok()) else {+ return error(StatusCode::CONFLICT, "this card has no findings yet");+ };+ let cancel = match apply_finding(&mut card, &fid, &body, Utc::now()) {+ Ok(c) => c,+ Err((s, m)) => return error(s, m),+ };+ let text = card.to_string();+ match state.db.swap_dev_card_json(&row.id, row.card.as_deref(), &text).await {+ Ok(true) => {}+ Ok(false) => continue,+ Err(e) => return internal(e),+ }+ if let Some(task_id) = cancel {+ cancel_fix_task(&state, &task_id).await;+ }+ if body.action == "fix" {+ let (st, id, f) = (state.clone(), row.id.clone(), fid.clone());+ tokio::spawn(async move {+ tokio::time::sleep(std::time::Duration::from_secs(FIX_UNDO_SECS)).await;+ deliver_fix(&st, &id, &f).await;+ });+ }+ let row = state.db.dev_card(&row.id).await.ok().flatten().unwrap_or(row);+ notify_card(&state, &row);+ return Json(card_json(&row)).into_response();+ }+ error(StatusCode::CONFLICT, "the card changed while saving: try again")+}++/// Sends a finding still `sent` (and not delivered) to the card's author bot, as a task in its+/// chat, and records the task on the finding. Also called after a restart for findings whose+/// Undo window ran out while kwant was down.+pub async fn deliver_fix(state: &AppState, card_id: &str, fid: &str) {+ for _ in 0..3 {+ let Ok(Some(row)) = state.db.dev_card(card_id).await else { return };+ let Some(mut card) = row.card.as_deref().and_then(|c| serde_json::from_str::<Value>(c).ok()) else { return };+ let Some(f) = card["findings"].as_array().and_then(|fs| fs.iter().find(|f| f["id"] == fid)).cloned() else { return };+ if f["state"] != "sent" || f["task_id"].is_string() {+ return;+ }+ let facts: Option<DevFacts> = serde_json::from_str(&row.facts).ok();+ let bot = facts.as_ref().and_then(|x| x.author.bot.clone());+ let space = SpaceId::new(&row.space_id);+ let target = match &bot {+ Some(b) => crate::server::missions::bot_in_space(state, &space, &b.id).await,+ None => None,+ };+ let entry = card["findings"].as_array_mut().and_then(|fs| fs.iter_mut().find(|x| x["id"] == fid));+ let Some(entry) = entry else { return };+ match target {+ Some(k) => {+ let task = fix_task(&space, &k.id, card_id, fid, &f, facts.as_ref());+ match crate::server::missions::create_task(state, &space, task).await {+ Ok(t) => {+ let change = crate::db::missions::TaskChange { reason: Some("Fix it on a Dev mode review".into()), ..Default::default() };+ let _ = crate::server::missions::transition(state, &t.id, "backlog", "ready", crate::server::missions::Actor::Kwant, "kwant", change).await;+ entry["task_id"] = json!(t.id);+ entry["sent_to"] = json!(k.name);+ }+ Err(e) => {+ tracing::warn!(card = %card_id, "dev: Fix it could not make the task: {e}");+ entry["state"] = json!("open");+ entry["sent_at"] = Value::Null;+ entry["send_error"] = json!("kwant could not hand this to the bot");+ }+ }+ }+ None => {+ // A person wrote the PR, or its bot is gone: nothing to send it to+ entry["state"] = json!("open");+ entry["sent_at"] = Value::Null;+ entry["send_error"] = json!("No bot wrote this PR, so there is no one to send it to");+ }+ }+ match state.db.swap_dev_card_json(card_id, row.card.as_deref(), &card.to_string()).await {+ Ok(true) => {+ if let Ok(Some(r)) = state.db.dev_card(card_id).await {+ notify_card(state, &r);+ }+ return;+ }+ Ok(false) => {+ // Changed in between (an Undo): a task made just now is cancelled again+ if let Some(t) = card["findings"].as_array().and_then(|fs| fs.iter().find(|x| x["id"] == fid)).and_then(|x| x["task_id"].as_str()) {+ cancel_fix_task(state, t).await;+ }+ continue;+ }+ Err(e) => {+ tracing::warn!(card = %card_id, "dev: Fix it could not save: {e}");+ return;+ }+ }+ }+}++/// The task Fix it hands the author bot: in its own chat, ready at once.+pub fn fix_task(space: &SpaceId, kwant_id: &str, card_id: &str, fid: &str, f: &Value, facts: Option<&DevFacts>) -> crate::db::missions::NewTask {+ let s = |k: &str| f[k].as_str().unwrap_or("").trim().to_string();+ let title: String = format!("Fix: {}", s("title")).chars().take(200).collect();+ let mut where_ = s("file");+ if let Some(l) = f["line"].as_u64() {+ where_ = format!("{where_}:{l}");+ }+ let pr = facts.and_then(|x| x.pr.map(|n| format!("PR #{n}"))).unwrap_or_else(|| "the PR".into());+ let branch = facts.and_then(|x| x.head_branch.clone()).map(|b| format!(" on branch {b}")).unwrap_or_default();+ let repo = facts.map(|x| format!(" in {}", x.repo)).unwrap_or_default();+ let mut acceptance = format!("A Dev mode review of {pr}{repo}{branch} found this ({} severity).\n", s("severity"));+ if !where_.is_empty() {+ acceptance.push_str(&format!("Where: {where_}\n"));+ }+ if !s("detail").is_empty() {+ acceptance.push_str(&format!("What: {}\n", s("detail")));+ }+ if !s("fix").is_empty() {+ acceptance.push_str(&format!("Suggested fix: {}\n", s("fix")));+ }+ acceptance.push_str("Done when the fix is pushed to the PR's branch and its tests pass.");+ let _ = space;+ crate::db::missions::NewTask {+ mission_id: None,+ title,+ acceptance: acceptance.chars().take(4_000).collect(),+ state: "backlog".into(),+ priority: if matches!(f["severity"].as_str(), Some("critical" | "high")) { 2 } else { 1 },+ owner_kwant_id: None,+ suggested_kwant_id: Some(kwant_id.into()),+ budget_tokens: 0,+ max_attempts: crate::server::missions::DEFAULT_MAX_ATTEMPTS,+ source_kind: "person".into(),+ source_id: Some(format!("dev:{card_id}:{fid}")),+ channel_id: None,+ direct_kwant_id: Some(kwant_id.into()),+ thread_id: None,+ created_by: "person".into(),+ }+}++async fn cancel_fix_task(state: &AppState, task_id: &str) {+ let Ok(Some(t)) = state.db.get_task(task_id).await else { return };+ if crate::db::missions::TERMINAL.contains(&t.state.as_str()) {+ return;+ }+ let change = crate::db::missions::TaskChange { reason: Some("the person took back Fix it".into()), ..Default::default() };+ if let Err(e) = crate::server::missions::transition(state, task_id, &t.state, "cancelled", crate::server::missions::Actor::Person, "person", change).await {+ tracing::warn!(task = %task_id, "dev: could not cancel the Fix it task: {e:?}");+ }+}++// ---------------------------------------------------------------------------------------------+// Release notes and backups++pub async fn release_notes(State(state): State<AppState>, headers: HeaderMap, Path(id): Path<String>) -> Response {+ let space = match guard(&state, &headers, &id).await {+ Ok(s) => s,+ Err(r) => return r,+ };+ let Some(mode) = state.db.dev_mode(space.as_str()).await.ok().flatten().filter(|m| m.on) else {+ return error(StatusCode::CONFLICT, "Dev mode is off in this space");+ };+ let since_tag = poller::last_tag(space.as_str());+ let landed = match state.db.dev_cards(space.as_str(), LANDED, None, ROLLUP_WINDOW).await {+ Ok(r) => r,+ Err(e) => return internal(e),+ };+ // Cards since the tag: the poller knows when the tag's commit was made+ let cut = poller::last_tag_at(space.as_str());+ let cards: Vec<String> = landed.iter().filter(|r| r.status == READY).filter(|r| cut.is_none_or(|t| r.created_at > t)).map(|r| r.id.clone()).collect();+ let facts = ReleaseFacts { repo: mode.repo.clone(), since_tag: since_tag.clone(), cards };+ let text = match serde_json::to_string(&facts) {+ Ok(t) => t,+ Err(e) => return internal(e),+ };+ // One draft per tag and moment: the head is the time it was asked for+ let head = Utc::now().format("%Y%m%dT%H%M%S%.3f").to_string();+ let row = match state.db.insert_dev_card(space.as_str(), RELEASE_NOTES, &format!("since:{}", since_tag.as_deref().unwrap_or("")), &head, &text).await {+ Ok(Some(r)) => r,+ Ok(None) => return error(StatusCode::CONFLICT, "a draft is being written already"),+ Err(e) => return internal(e),+ };+ notify_card(&state, &row);+ tokio::spawn(super::generate(state.clone(), row.id.clone()));+ debug_assert_eq!(row.status, PENDING);+ (StatusCode::ACCEPTED, Json(card_json(&row))).into_response()+}++pub async fn take_backup(State(state): State<AppState>, headers: HeaderMap, Path(id): Path<String>) -> Response {+ let space = match guard(&state, &headers, &id).await {+ Ok(s) => s,+ Err(r) => return r,+ };+ match backup::run(&state, &space, None).await {+ Ok(b) => Json(backup::json(&b)).into_response(),+ Err(backup::BackupError::NoCommand) => error(StatusCode::CONFLICT, "Set a backup command in Dev mode settings"),+ Err(backup::BackupError::Busy) => error(StatusCode::CONFLICT, "A backup is running already"),+ Err(backup::BackupError::Db(e)) => internal(e),+ Err(backup::BackupError::Lost(e)) => {+ tracing::warn!(space = %space, error = %e, "dev: the backup run ended without an answer");+ error(StatusCode::INTERNAL_SERVER_ERROR, "The backup run stopped unexpectedly")+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn row(kind: &str, card: Option<Value>, facts: Value, at: DateTime<Utc>) -> DevCardRow {+ DevCardRow {+ id: format!("dvc_{}", at.timestamp_millis()),+ space_id: "s1".into(),+ kind: kind.into(),+ ref_: "pr:1".into(),+ head_sha: "abc".into(),+ status: READY.into(),+ facts: facts.to_string(),+ card: card.map(|c| c.to_string()),+ created_at: at,+ updated_at: at,+ }+ }++ fn facts(ci: &str) -> Value {+ json!({"repo": "demo-org/demo", "kind": "landed", "pr": 290, "title": "Sidebar rows", "body": "", "head_sha": "51f9141aaaa",+ "base_branch": "main", "merged_at": null, "merged_by": "demo", "author": {"name": "Ada"}, "files": [], "cut": null,+ "checks": [], "ci": ci, "task": null, "first_edit_files": []})+ }++ #[test]+ fn a_card_without_text_shows_its_pr_and_the_card_wins() {+ let at = Utc::now();+ let r = row(LANDED, None, facts("green"), at);+ let v = card_json(&r);+ assert_eq!(v["pr"], 290);+ assert_eq!(v["sha"], "51f9141");+ assert_eq!(v["status"], "ready");+ assert_eq!(v["kind"], "landed");+ let r = row(LANDED, Some(json!({"headline": "Rows stop jumping", "sha": "51f9141", "kind": "evil", "id": "x"})), facts("green"), at);+ let v = card_json(&r);+ assert_eq!(v["headline"], "Rows stop jumping");+ assert_eq!(v["kind"], "landed", "the row's kind and id can't be overwritten by the card");+ assert_eq!(v["id"], r.id);+ }++ #[test]+ fn the_rollup_counts_since_the_last_look() {+ let now = Utc::now();+ let h = |n: i64| now - chrono::Duration::hours(n);+ let landed = vec![+ row(LANDED, Some(json!({"area": "Sidebar", "headline": "B", "risk": {"level": "low"}, "tests": {"state": "passed"}})), facts("green"), h(1)),+ row(LANDED, Some(json!({"area": "Sidebar", "headline": "A", "risk": {"level": "high"}})), facts("red"), h(2)),+ row(LANDED, Some(json!({"area": "", "tests": {"state": "failed"}})), facts("red"), h(3)),+ row(LANDED, Some(json!({"area": "Chat", "headline": "old"})), facts("green"), h(30)),+ ];+ let reviews = vec![+ row(REVIEW, Some(json!({"risk": {"level": "low"}, "findings": [{"state": "open", "severity": "high"}]})), facts("none"), h(1)),+ row(REVIEW, Some(json!({"risk": {"level": "low"}, "findings": [{"state": "dismissed", "severity": "critical"}]})), facts("none"), h(1)),+ ];+ let v = rollup(&landed, &reviews, Some(h(24)), now);+ assert_eq!(v["count"], 3);+ assert_eq!(v["needs_you"], 3, "high risk, failed tests, a review with an open high finding");+ assert_eq!(v["main_green"], true);+ assert_eq!(v["areas"][0], json!({"area": "Sidebar", "count": 2, "first_headline": "B"}));+ assert_eq!(v["areas"][1], json!({"area": "Other", "count": 1, "first_headline": null}));+ let all = rollup(&landed, &[], None, now);+ assert_eq!(all["count"], 4);+ assert_eq!(all["since"], Value::Null);+ assert_eq!(rollup(&[], &[], None, now)["main_green"], Value::Null);+ }++ fn body(action: &str, reason: Option<&str>) -> FindingBody {+ FindingBody { action: action.into(), reason: reason.map(str::to_string), note: None }+ }++ #[test]+ fn finding_actions_follow_the_rules() {+ let now = Utc::now();+ let mut card = json!({"findings": [{"id": "f1", "state": "open", "severity": "high", "title": "t"}]});+ assert_eq!(apply_finding(&mut card, "f1", &body("fix", None), now), Ok(None));+ assert_eq!(card["findings"][0]["state"], "sent");+ assert!(card["findings"][0]["sent_at"].is_string());+ // Fix twice is a no-op+ assert_eq!(apply_finding(&mut card, "f1", &body("fix", None), now), Ok(None));+ // Undo before the task went out: nothing to cancel+ assert_eq!(apply_finding(&mut card, "f1", &body("undo_fix", None), now), Ok(None));+ assert_eq!(card["findings"][0]["state"], "open");+ assert_eq!(card["findings"][0]["sent_at"], Value::Null);+ assert_eq!(apply_finding(&mut card, "f1", &body("undo_fix", None), now).unwrap_err().0, StatusCode::CONFLICT);+ // Undo after it went out: the task is named so it can be cancelled+ apply_finding(&mut card, "f1", &body("fix", None), now).unwrap();+ card["findings"][0]["task_id"] = json!("tsk_1");+ assert_eq!(apply_finding(&mut card, "f1", &body("dismiss", Some("later")), now).unwrap_err().0, StatusCode::CONFLICT);+ assert_eq!(apply_finding(&mut card, "f1", &body("undo_fix", None), now), Ok(Some("tsk_1".into())));+ assert!(card["findings"][0].get("task_id").is_none());+ // Dismiss stores the reason and needs a known one+ assert_eq!(apply_finding(&mut card, "f1", &body("dismiss", Some("nope")), now).unwrap_err().0, StatusCode::BAD_REQUEST);+ assert_eq!(apply_finding(&mut card, "f1", &body("dismiss", None), now).unwrap_err().0, StatusCode::BAD_REQUEST);+ let mut b = body("dismiss", Some("fine_here"));+ b.note = Some(" covered by #303 ".into());+ apply_finding(&mut card, "f1", &b, now).unwrap();+ assert_eq!(card["findings"][0]["state"], "dismissed");+ assert_eq!(card["findings"][0]["dismissed"]["reason"], "fine_here");+ assert_eq!(card["findings"][0]["dismissed"]["note"], "covered by #303");+ b.note = Some("x".repeat(501));+ assert_eq!(apply_finding(&mut card, "f1", &b, now).unwrap_err().0, StatusCode::BAD_REQUEST);+ // Fix after dismiss clears the dismissal+ apply_finding(&mut card, "f1", &body("fix", None), now).unwrap();+ assert_eq!(card["findings"][0]["dismissed"], Value::Null);+ // Unknown finding and action+ assert_eq!(apply_finding(&mut card, "f9", &body("fix", None), now).unwrap_err().0, StatusCode::NOT_FOUND);+ assert_eq!(apply_finding(&mut card, "f1", &body("merge", None), now).unwrap_err().0, StatusCode::BAD_REQUEST);+ }++ #[test]+ fn the_fix_task_goes_to_the_bot_in_its_chat() {+ let f = json!({"id": "f1", "severity": "high", "title": "Token logged", "file": "src/a.rs", "line": 12, "detail": "d", "fix": "x"});+ let mut fx: DevFacts = serde_json::from_value(facts("green")).unwrap();+ fx.head_branch = Some("pixel-live-redact-n3".into());+ let t = fix_task(&SpaceId::new("s1"), "k_pixel", "dvc_1", "f1", &f, Some(&fx));+ assert_eq!(t.direct_kwant_id.as_deref(), Some("k_pixel"));+ assert_eq!(t.suggested_kwant_id.as_deref(), Some("k_pixel"));+ assert_eq!(t.source_id.as_deref(), Some("dev:dvc_1:f1"));+ assert_eq!(t.priority, 2);+ assert!(t.title.starts_with("Fix: Token logged"));+ assert!(t.acceptance.contains("src/a.rs:12") && t.acceptance.contains("PR #290") && t.acceptance.contains("pixel-live-redact-n3"));+ }++ #[test]+ fn branch_names_are_checked() {+ for ok in ["main", "release/0.7", "pixel-dev-switch", "v1.2"] {+ assert!(valid_branch(ok), "{ok}");+ }+ for bad in ["", "-x", "a..b", "a b", "a:b", "x.lock", "/x", "x/", "a@{1}", "a\\b", "a~1"] {+ assert!(!valid_branch(bad), "{bad}");+ }+ }++ #[test]+ fn backup_command_null_clears_and_missing_keeps() {+ let keep: PutBody = serde_json::from_value(json!({"on": false})).unwrap();+ assert!(keep.backup_command.is_none());+ let clear: PutBody = serde_json::from_value(json!({"on": false, "backup_command": null})).unwrap();+ assert_eq!(clear.backup_command, Some(None));+ let set: PutBody = serde_json::from_value(json!({"on": false, "backup_command": "make backup"})).unwrap();+ assert_eq!(set.backup_command, Some(Some("make backup".into())));+ }+}diff --git a/src/server/dev/tamper.rs b/src/server/dev/tamper.rsnew file mode 100644index 00000000..bb652108--- /dev/null+++ b/src/server/dev/tamper.rs@@ -0,0 +1 @@+//! Dev mode card generation: tamper (Vega, plan §4).diff --git a/src/server/mcp_runtime.rs b/src/server/mcp_runtime.rsindex 351db933..d538ce20 100644--- a/src/server/mcp_runtime.rs+++ b/src/server/mcp_runtime.rs@@ -198,7 +198,11 @@ impl BrokerApprover {Some(_) => None,None => self.tier_gate(&req).await,};- let forced = payment.is_some() || tier.is_some();+ // The production floor (plan §3.5): in a Dev mode space, a step that can reach production+ // (a deploy, a push to the watched branch, a migration, a marked connection) always asks,+ // and "always allow" covers just that call.+ let floor = super::dev::floor::for_call(&self.db, &req).await;+ let forced = payment.is_some() || tier.is_some() || floor.is_some();// The two audit calls only record the audit in kwnt (risks the person closes), so they// follow approvals off even in an always-asking audit turn; its other tools still asklet audit_call = req.server == mcp::SELF_SERVER_NAME && super::missions::auditor::TOOL_NAMES.contains(&req.tool.as_str());@@ -240,6 +244,9 @@ impl BrokerApprover {if let Some(why) = &tier {details["tier_reason"] = json!(why);}+ if let Some((_, card)) = &floor {+ details["prod_floor"] = card.clone();+ }let record = NewApproval {turn_id: req.turn_id.clone(),kwant_id: req.kwant_id.clone(),@@ -265,6 +272,8 @@ impl BrokerApprover {}if payment.is_some() {tracing::info!(kwant = %req.kwant_id, tool = %req.tool_name, reason = ?payment, "a payment: asking whatever the approvals say");+ } else if let Some((f, _)) = &floor {+ tracing::info!(kwant = %req.kwant_id, tool = %req.tool_name, kind = ?f.kind, "can reach production: asking whatever the approvals say");} else if !off && !self.always_ask && self.broker.is_allowed_for_session(&req.kwant_id, &self.conversation, &req.tool_name).await {return (ApprovalOutcome::Allowed, "allowed", None);}@@ -329,6 +338,8 @@ impl BrokerApprover {Ok(Ok(ApprovalDecision::AllowOnce)) => ApprovalOutcome::Allowed,// A payment's "always allow" covers this one call: nothing is rememberedOk(Ok(ApprovalDecision::AlwaysAllowSession)) if payment.is_some() => ApprovalOutcome::Allowed,+ // So does a production step's+ Ok(Ok(ApprovalDecision::AlwaysAllowSession)) if floor.is_some() => ApprovalOutcome::Allowed,Ok(Ok(ApprovalDecision::AlwaysAllowSession)) => {self.broker.allow_for_session(&req.kwant_id, &self.conversation, &req.tool_name).await;ApprovalOutcome::Allowed@@ -438,8 +449,8 @@ pub async fn resume_late_approval(state: &AppState, ticket_id: &str, decision: Alet channel_id = chat["channel_id"].as_str().map(str::to_string);let conversation = thread_id.clone().or_else(|| channel_id.clone()).or_else(|| chat["direct_kwant_id"].as_str().map(str::to_string)).unwrap_or_else(|| kwant.id.clone());state.broker.grant_once(&kwant.id, &conversation, &approval.tool_name, &arguments).await;- // A payment's "always allow" covers the one call (the payment floor, D8)- if decision == ApprovalDecision::AlwaysAllowSession && details.get("payment_reason").is_none() {+ // A payment's "always allow" covers the one call (the payment floor, D8). So does a production step's (plan §3.5)+ if decision == ApprovalDecision::AlwaysAllowSession && details.get("payment_reason").is_none() && details.get("prod_floor").is_none() {state.broker.allow_for_session(&kwant.id, &conversation, &approval.tool_name).await;}let depth = match &thread_id {diff --git a/src/server/mod.rs b/src/server/mod.rsindex 70fc6536..e397c939 100644--- a/src/server/mod.rs+++ b/src/server/mod.rs@@ -54,6 +54,7 @@ pub mod missions;pub mod goals;pub mod app_update_routes;pub mod smart_results;+pub mod dev;use crate::broker::PermissionBroker;use crate::config::Config;@@ -249,6 +250,15 @@ pub fn create_router(state: AppState) -> Router {.route("/api/approvals", get(approval_modes::list)).route("/api/approvals/:id/resolve", post(routes::resolve_approval)).route("/api/spaces/:id/approvals", get(approval_modes::get_space).put(approval_modes::put_space))+ .route("/api/spaces/:id/dev_mode", get(dev::routes::get_mode).put(dev::routes::put_mode))+ .route("/api/spaces/:id/dev_mode/check", post(dev::routes::check))+ .route("/api/spaces/:id/dev/landed", get(dev::routes::landed))+ .route("/api/spaces/:id/dev/landed/seen", post(dev::routes::seen))+ .route("/api/spaces/:id/dev/reviews", get(dev::routes::reviews))+ .route("/api/spaces/:id/dev/release_notes", post(dev::routes::release_notes))+ .route("/api/spaces/:id/dev/backup", post(dev::routes::take_backup))+ .route("/api/dev/cards/:id", get(dev::routes::card))+ .route("/api/dev/cards/:id/findings/:fid", post(dev::routes::finding)).route("/api/kwants/:id/approvals", get(approval_modes::get_kwant).put(approval_modes::put_kwant)).route("/api/settings", get(routes::get_settings).post(routes::save_settings)).route("/api/settings/computer", get(computer::get_computer).put(computer::put_computer))@@ -315,6 +325,7 @@ pub fn create_router(state: AppState) -> Router {.route("/api/parallel/runs", get(parallel_routes::list_runs)).route("/api/parallel/runs/:id", get(parallel_routes::get_run)).route("/api/connections", get(connections::list))+ .route("/api/connections/:id/production", put(connections::put_production)).route("/api/connections/composio", post(connections::add_composio)).route("/api/connections/composio/apps", get(connections::search_composio_apps)).route("/api/connections/composio/apps/:slug/connect", post(connections::connect_composio_app))diff --git a/src/server/routes.rs b/src/server/routes.rsindex fdf02319..624b768c 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -3816,6 +3816,26 @@ pub async fn resolve_approval(ApprovalDecision::Deny => "denied",};+ // The production floor (plan §3.5): Allow on a step that needs a backup is refused here,+ // not only greyed out on the card, until the space has an ok backup at most 10 minutes old+ if decision != ApprovalDecision::Deny {+ let details = state+ .db+ .get_approval(&ticket_id)+ .await+ .ok()+ .flatten()+ .and_then(|a| serde_json::from_str::<serde_json::Value>(&a.parameters).ok());+ if let Some(details) = details {+ if let Some(mut refusal) = super::dev::floor::allow_refusal(&state.db, &details).await {+ refusal["ticket_id"] = json!(ticket_id);+ refusal["resolved"] = json!(false);+ refusal["status"] = json!("needs_backup");+ return Ok((StatusCode::CONFLICT, Json(refusal)).into_response());+ }+ }+ }+// Only a ticket still waiting can be answered; a withdrawn one (turn ended, expired)// keeps its status and its tool never runslet resolved = state.broker.resolve(&ticket_id, decision.clone()).await;diff --git a/src/server/scheduler.rs b/src/server/scheduler.rsindex 37a87cd5..596c6b8a 100644--- a/src/server/scheduler.rs+++ b/src/server/scheduler.rs@@ -843,5 +843,6 @@ pub fn spawn_background(state: AppState, shutdown: CancellationToken) {super::missions::foundry::spawn(state.clone(), shutdown.clone());super::goals::runner::spawn(state.clone(), shutdown.clone());super::missions::discovery::spawn(state.clone(), shutdown.clone());+ super::dev::poller::spawn(state.clone(), shutdown.clone());spawn(state, shutdown);}diff --git a/src/server/sse.rs b/src/server/sse.rsindex 27d75bf1..3d87540e 100644--- a/src/server/sse.rs+++ b/src/server/sse.rs@@ -114,6 +114,7 @@ pub fn owners(event: &RuntimeEvent) -> Vec<Owner> {E::RoutineRun { routine_id, .. } => vec![Owner::Routine(routine_id.clone())],E::TaskUpdated { task: v } | E::MissionUpdated { mission: v } => fields(v, &["space_id"], Owner::Space),E::GoalUpdated { space_id, .. } => vec![Owner::Space(space_id.clone())],+ E::DevCard { space_id, .. } | E::DevMode { space_id, .. } => vec![Owner::Space(space_id.clone())],E::Notify { space_id, kwant_id, channel_id, .. } => {let mut out: Vec<Owner> = space_id.iter().cloned().map(Owner::Space).collect();out.extend(contexts([channel_id, &Some(kwant_id.clone())]));@@ -298,6 +299,8 @@ mod tests {E::TaskUpdated { task: json!({"id": "t", "space_id": "spc_x"}) },E::MissionUpdated { mission: json!({"id": "m", "space_id": "spc_x"}) },E::GoalUpdated { id: s("g"), status: s("met"), space_id: s("spc_x") },+ E::DevCard { space_id: s("spc_x"), id: s("dvc_1"), kind: s("landed"), status: s("ready") },+ E::DevMode { space_id: s("spc_x"), on: true },E::Notify {kind: s("x"),kwant_id: s("k"),@@ -354,6 +357,8 @@ mod tests {| E::TaskUpdated { .. }| E::MissionUpdated { .. }| E::GoalUpdated { .. }+ | E::DevCard { .. }+ | E::DevMode { .. }| E::Notify { .. } => {}}}diff --git a/src/zombie/github.rs b/src/zombie/github.rsindex 1d72b56f..2fd6df6d 100644--- a/src/zombie/github.rs+++ b/src/zombie/github.rs@@ -129,6 +129,400 @@ impl GithubSource {}}+// ---------------------------------------------------------------------------------------------+// Dev mode reads (0.7, plan D4/D5). GET only, against the same API base and token. Lists that+// are polled go through an [`EtagCache`], so an unchanged answer is a 304 that GitHub doesn't+// count against the rate limit; 403/429 with a rate-limit sign come back as [`GhError::Limited`]+// so the poller can back off.++/// Why a Dev mode read failed.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum GhError {+ /// 401: the token is wrong or expired.+ Auth,+ /// 403 without a rate-limit sign: the token can't read this.+ Forbidden,+ /// 404 (GitHub also answers 404 for a private repo the token can't see).+ NotFound,+ /// 429, or 403 with `retry-after` or no requests left: wait this long.+ Limited { retry_after_s: u64 },+ Other(String),+}++impl std::fmt::Display for GhError {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self {+ GhError::Auth => write!(f, "GitHub refused the token (401): check it in Loose ends"),+ GhError::Forbidden => write!(f, "GitHub refused the request (403): the token may lack access to this repo"),+ GhError::NotFound => write!(f, "GitHub has no such repo or branch, or the token can't see it"),+ GhError::Limited { retry_after_s } => write!(f, "GitHub's rate limit was hit: kwant tries again in {} min", retry_after_s.div_ceil(60).max(1)),+ GhError::Other(e) => write!(f, "{e}"),+ }+ }+}++/// How long to wait after a 403/429, from GitHub's own headers. `None` when the answer+/// carries no rate-limit sign (a plain 403 is about access, not speed).+pub fn retry_after(status: u16, headers: &reqwest::header::HeaderMap, now_epoch: u64) -> Option<u64> {+ let h = |name: &str| headers.get(name).and_then(|v| v.to_str().ok()).map(str::trim);+ if let Some(s) = h("retry-after").and_then(|v| v.parse::<u64>().ok()) {+ return Some(s.clamp(1, 3600));+ }+ if h("x-ratelimit-remaining") == Some("0") {+ let reset = h("x-ratelimit-reset").and_then(|v| v.parse::<u64>().ok()).unwrap_or(now_epoch + 60);+ return Some(reset.saturating_sub(now_epoch).clamp(1, 3600));+ }+ // GitHub's docs: a 429, or a secondary limit with neither header, waits at least a minute+ (status == 429).then_some(60)+}++/// Remembered answers by URL, for conditional requests. Bounded: the oldest half is dropped+/// when it grows past [`EtagCache::MAX`].+#[derive(Default)]+pub struct EtagCache {+ map: std::sync::Mutex<std::collections::HashMap<String, (u64, String, serde_json::Value)>>,+ tick: std::sync::atomic::AtomicU64,+}++impl EtagCache {+ const MAX: usize = 400;++ fn get(&self, url: &str) -> Option<(String, serde_json::Value)> {+ self.map.lock().ok()?.get(url).map(|(_, e, v)| (e.clone(), v.clone()))+ }++ fn put(&self, url: &str, etag: String, body: serde_json::Value) {+ let n = self.tick.fetch_add(1, std::sync::atomic::Ordering::Relaxed);+ let Ok(mut m) = self.map.lock() else { return };+ if m.len() >= Self::MAX {+ let mut ages: Vec<u64> = m.values().map(|(t, _, _)| *t).collect();+ ages.sort_unstable();+ let cut = ages[ages.len() / 2];+ m.retain(|_, (t, _, _)| *t > cut);+ }+ m.insert(url.to_string(), (n, etag, body));+ }+}++#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]+pub struct GhRepo {+ pub full_name: String,+ pub default_branch: String,+ #[serde(default)]+ pub private: bool,+}++#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Default)]+pub struct GhUser {+ pub login: String,+ #[serde(rename = "type", default)]+ pub kind: String,+}++#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Default)]+pub struct GhGitPerson {+ #[serde(default)]+ pub name: String,+ #[serde(default)]+ pub email: Option<String>,+ #[serde(default)]+ pub date: Option<DateTime<Utc>>,+}++#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Default)]+pub struct GhCommitInner {+ #[serde(default)]+ pub message: String,+ #[serde(default)]+ pub author: GhGitPerson,+ #[serde(default)]+ pub committer: GhGitPerson,+}++#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Default)]+pub struct GhCommit {+ pub sha: String,+ #[serde(default)]+ pub html_url: Option<String>,+ #[serde(default)]+ pub commit: GhCommitInner,+ #[serde(default)]+ pub author: Option<GhUser>,+ #[serde(default)]+ pub parents: Vec<serde_json::Value>,+ /// Only on a single-commit read.+ #[serde(default)]+ pub files: Vec<GhFile>,+}++#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Default)]+pub struct GhRef {+ #[serde(rename = "ref", default)]+ pub branch: String,+ #[serde(default)]+ pub sha: String,+}++#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Default)]+pub struct GhPull {+ pub number: u64,+ #[serde(default)]+ pub title: String,+ #[serde(default)]+ pub body: Option<String>,+ #[serde(default)]+ pub state: String,+ #[serde(default)]+ pub draft: bool,+ #[serde(default)]+ pub html_url: Option<String>,+ #[serde(default)]+ pub user: Option<GhUser>,+ #[serde(default)]+ pub head: GhRef,+ #[serde(default)]+ pub base: GhRef,+ #[serde(default)]+ pub merged_at: Option<DateTime<Utc>>,+ #[serde(default)]+ pub merge_commit_sha: Option<String>,+ #[serde(default)]+ pub merged_by: Option<GhUser>,+ #[serde(default)]+ pub updated_at: Option<DateTime<Utc>>,+}++#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Default)]+pub struct GhFile {+ pub filename: String,+ #[serde(default)]+ pub status: String,+ #[serde(default)]+ pub additions: u64,+ #[serde(default)]+ pub deletions: u64,+ #[serde(default)]+ pub patch: Option<String>,+ #[serde(default)]+ pub previous_filename: Option<String>,+}++#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Default)]+pub struct GhCheck {+ pub name: String,+ #[serde(default)]+ pub status: String,+ #[serde(default)]+ pub conclusion: Option<String>,+ #[serde(default)]+ pub html_url: Option<String>,+}++#[derive(Debug, Deserialize)]+struct CheckRuns {+ #[serde(default)]+ check_runs: Vec<GhCheck>,+}++#[derive(Debug, Deserialize)]+struct Tag {+ name: String,+ #[serde(default)]+ commit: Option<TagCommit>,+}++#[derive(Debug, Deserialize)]+struct TagCommit {+ sha: String,+}++#[derive(Debug, Deserialize)]+struct ContentItem {+ name: String,+ #[serde(rename = "type", default)]+ kind: String,+}++/// Most PR files read (GitHub stops at 3000; a card never needs that many).+const MAX_PR_FILES: usize = 300;+/// Most commits read back from the branch head per poll.+pub const MAX_COMMITS: usize = 50;++/// A path segment for an `owner/name` repo, a branch or a sha: only the characters GitHub+/// allows there, so nothing a repo or a response holds can change the URL's shape.+fn seg_ok(s: &str) -> bool {+ !s.is_empty() && s != "." && s != ".." && !s.starts_with('-') && s.chars().all(|c| c.is_ascii_alphanumeric() || "-_.".contains(c))+}++/// `owner/name` checked for use in a URL.+pub fn repo_path(repo: &str) -> Result<&str, GhError> {+ match repo.split_once('/') {+ Some((o, n)) if seg_ok(o) && seg_ok(n) => Ok(repo),+ _ => Err(GhError::Other("the repo must be owner/name".into())),+ }+}++/// A branch, path or ref for a query string or path, percent-encoded.+fn enc(s: &str) -> String {+ url::form_urlencoded::byte_serialize(s.as_bytes()).collect()+}++impl GithubSource {+ /// A client for Dev mode reads against `cfg` (the Loose ends GitHub connection's API base).+ pub fn for_dev(id: &str, cfg: GithubConfig, token: Zeroizing<String>) -> Self {+ Self::new(id, cfg, token)+ }++ async fn get_dev(&self, path_and_query: &str, cache: Option<&EtagCache>) -> Result<serde_json::Value, GhError> {+ let url = format!("{}{path_and_query}", self.cfg.base());+ let cached = cache.and_then(|c| c.get(&url));+ let mut req = self+ .http+ .get(&url)+ .bearer_auth(self.token.as_str())+ .header("Accept", "application/vnd.github+json")+ .header("X-GitHub-Api-Version", "2022-11-28");+ if let Some((etag, _)) = &cached {+ req = req.header("If-None-Match", etag.as_str());+ }+ let res = req.send().await.map_err(|e| GhError::Other(format!("GitHub could not be reached: {}", e.without_url())))?;+ let status = res.status().as_u16();+ let now = Utc::now().timestamp().max(0) as u64;+ match status {+ 200 => {+ let etag = res.headers().get("etag").and_then(|v| v.to_str().ok()).map(str::to_string);+ let body: serde_json::Value = res.json().await.map_err(|_| GhError::Other("GitHub sent an answer kwant could not read".into()))?;+ if let (Some(c), Some(e)) = (cache, etag) {+ c.put(&url, e, body.clone());+ }+ Ok(body)+ }+ 304 => cached.map(|(_, v)| v).ok_or_else(|| GhError::Other("GitHub answered 304 to a request kwant never made".into())),+ 401 => Err(GhError::Auth),+ 404 | 422 => Err(GhError::NotFound),+ 403 | 429 => Err(match retry_after(status, res.headers(), now) {+ Some(s) => GhError::Limited { retry_after_s: s },+ None => GhError::Forbidden,+ }),+ s => Err(GhError::Other(format!("GitHub answered {s}"))),+ }+ }++ async fn get_as<T: serde::de::DeserializeOwned>(&self, path: &str, cache: Option<&EtagCache>) -> Result<T, GhError> {+ serde_json::from_value(self.get_dev(path, cache).await?).map_err(|_| GhError::Other("GitHub sent an answer kwant could not read".into()))+ }++ /// The repo and its default branch.+ pub async fn dev_repo(&self, repo: &str) -> Result<GhRepo, GhError> {+ self.get_as(&format!("/repos/{}", repo_path(repo)?), None).await+ }++ /// Whether `branch` exists.+ pub async fn dev_branch_exists(&self, repo: &str, branch: &str) -> Result<bool, GhError> {+ match self.get_dev(&format!("/repos/{}/branches/{}", repo_path(repo)?, enc(branch)), None).await {+ Ok(_) => Ok(true),+ Err(GhError::NotFound) => Ok(false),+ Err(e) => Err(e),+ }+ }++ /// Names of the files and folders at the repo's root on `branch` (for the deploy hint).+ pub async fn dev_root_names(&self, repo: &str, branch: &str) -> Result<Vec<String>, GhError> {+ let items: Vec<ContentItem> = self.get_as(&format!("/repos/{}/contents?ref={}", repo_path(repo)?, enc(branch)), None).await?;+ Ok(items.into_iter().map(|i| if i.kind == "dir" { format!("{}/", i.name) } else { i.name }).collect())+ }++ /// Commits on `branch` newer than `last_seen`, oldest first. `None` when `last_seen` isn't+ /// among the newest [`MAX_COMMITS`] (a force-push, or a long pause): the caller then takes+ /// the newest ones only.+ pub async fn dev_commits_since(&self, repo: &str, branch: &str, last_seen: Option<&str>, cache: &EtagCache) -> Result<(Vec<GhCommit>, bool), GhError> {+ let list: Vec<GhCommit> = self+ .get_as(&format!("/repos/{}/commits?sha={}&per_page={MAX_COMMITS}", repo_path(repo)?, enc(branch)), Some(cache))+ .await?;+ let found = last_seen.and_then(|s| list.iter().position(|c| c.sha == s));+ let mut newer: Vec<GhCommit> = match found {+ Some(i) => list[..i].to_vec(),+ None => list,+ };+ newer.reverse();+ Ok((newer, found.is_some()))+ }++ /// One commit with its files.+ pub async fn dev_commit(&self, repo: &str, sha: &str) -> Result<GhCommit, GhError> {+ if !seg_ok(sha) {+ return Err(GhError::Other("bad sha".into()));+ }+ self.get_as(&format!("/repos/{}/commits/{sha}", repo_path(repo)?), None).await+ }++ /// The pull requests a commit belongs to.+ pub async fn dev_pulls_for_commit(&self, repo: &str, sha: &str) -> Result<Vec<GhPull>, GhError> {+ if !seg_ok(sha) {+ return Err(GhError::Other("bad sha".into()));+ }+ self.get_as(&format!("/repos/{}/commits/{sha}/pulls", repo_path(repo)?), None).await+ }++ pub async fn dev_pull(&self, repo: &str, number: u64) -> Result<GhPull, GhError> {+ self.get_as(&format!("/repos/{}/pulls/{number}", repo_path(repo)?), None).await+ }++ /// A PR's files with their patches, up to [`MAX_PR_FILES`].+ pub async fn dev_pull_files(&self, repo: &str, number: u64) -> Result<Vec<GhFile>, GhError> {+ let repo = repo_path(repo)?;+ let mut out = Vec::new();+ for page in 1..=(MAX_PR_FILES / 100) {+ let batch: Vec<GhFile> = self.get_as(&format!("/repos/{repo}/pulls/{number}/files?per_page=100&page={page}"), None).await?;+ let last = batch.len() < 100;+ out.extend(batch);+ if last {+ break;+ }+ }+ Ok(out)+ }++ /// Check runs on a commit.+ pub async fn dev_check_runs(&self, repo: &str, sha: &str, cache: &EtagCache) -> Result<Vec<GhCheck>, GhError> {+ if !seg_ok(sha) {+ return Err(GhError::Other("bad sha".into()));+ }+ let runs: CheckRuns = self.get_as(&format!("/repos/{}/commits/{sha}/check-runs?per_page=100", repo_path(repo)?), Some(cache)).await?;+ Ok(runs.check_runs)+ }++ /// Open PRs into `base`, most recently updated first.+ pub async fn dev_open_pulls(&self, repo: &str, base: &str, cache: &EtagCache) -> Result<Vec<GhPull>, GhError> {+ self.get_as(&format!("/repos/{}/pulls?state=open&base={}&sort=updated&direction=desc&per_page=50", repo_path(repo)?, enc(base)), Some(cache))+ .await+ }++ /// The newest tag's name and the sha it points at.+ pub async fn dev_latest_tag(&self, repo: &str, cache: &EtagCache) -> Result<Option<(String, Option<String>)>, GhError> {+ let tags: Vec<Tag> = self.get_as(&format!("/repos/{}/tags?per_page=1", repo_path(repo)?), Some(cache)).await?;+ Ok(tags.into_iter().next().map(|t| (t.name, t.commit.map(|c| c.sha))))+ }++ /// How many commits on `branch` touched `path` between `since` and `until` (counting at most 2).+ pub async fn dev_path_commits(&self, repo: &str, branch: &str, path: &str, since: DateTime<Utc>, until: DateTime<Utc>) -> Result<usize, GhError> {+ let list: Vec<serde_json::Value> = self+ .get_as(+ &format!(+ "/repos/{}/commits?sha={}&path={}&since={}&until={}&per_page=2",+ repo_path(repo)?,+ enc(branch),+ enc(path),+ since.format("%Y-%m-%dT%H:%M:%SZ"),+ until.format("%Y-%m-%dT%H:%M:%SZ")+ ),+ None,+ )+ .await?;+ Ok(list.len())+ }+}+/// `owner/repo` from `https://api.github.com/repos/owner/repo`.fn repo_of(repository_url: &str) -> Option<String> {let mut parts = repository_url.trim_end_matches('/').rsplit('/');@@ -228,10 +622,119 @@ mod tests {assert_eq!(GithubConfig { api_base: "https://ghe.example/api/v3/".into() }.vault_origin(), "https://ghe.example");}+ #[test]+ fn rate_limits_back_off_by_githubs_own_headers() {+ use reqwest::header::{HeaderMap, HeaderValue};+ let mut h = HeaderMap::new();+ assert_eq!(retry_after(403, &h, 1000), None, "a plain 403 is about access");+ assert_eq!(retry_after(429, &h, 1000), Some(60));+ h.insert("retry-after", HeaderValue::from_static("120"));+ assert_eq!(retry_after(403, &h, 1000), Some(120));+ let mut h = HeaderMap::new();+ h.insert("x-ratelimit-remaining", HeaderValue::from_static("0"));+ h.insert("x-ratelimit-reset", HeaderValue::from_static("1300"));+ assert_eq!(retry_after(403, &h, 1000), Some(300));+ h.insert("x-ratelimit-reset", HeaderValue::from_static("99999"));+ assert_eq!(retry_after(403, &h, 1000), Some(3600), "never more than an hour");+ }++ #[test]+ fn dev_paths_take_only_well_formed_repos() {+ assert!(repo_path("alexsergivan/kwant").is_ok());+ for bad in ["kwant", "o/r/x", "../r", "o/..", "o/r?x=1", "-o/r", "o /r", ""] {+ assert!(repo_path(bad).is_err(), "{bad}");+ }+ assert_eq!(enc("feat/a b&c"), "feat%2Fa+b%26c");+ }++ #[test]+ fn the_etag_cache_stays_bounded() {+ let c = EtagCache::default();+ for i in 0..(EtagCache::MAX + 50) {+ c.put(&format!("u{i}"), "e".into(), serde_json::json!(i));+ }+ assert!(c.map.lock().unwrap().len() <= EtagCache::MAX);+ assert!(c.get(&format!("u{}", EtagCache::MAX + 49)).is_some(), "the newest stays");+ }+#[test]fn repos_come_only_from_well_formed_urls() {assert_eq!(repo_of("https://api.github.com/repos/o/r").as_deref(), Some("o/r"));assert_eq!(repo_of("https://api.github.com/repos/o/.."), None);assert_eq!(repo_of("https://api.github.com/repos/o/r?x=1"), None);}++ /// A mock GitHub on a private local port (9481–9484 on the shared server, any free one+ /// otherwise): Dev mode's reads send the ETag back, reuse the cached answer on a 304, and+ /// report a rate limit with its wait.+ #[tokio::test]+ async fn dev_reads_against_a_mock_github() {+ use axum::{extract::State, http::HeaderMap, response::IntoResponse, routing::get, Json, Router};+ use std::sync::atomic::{AtomicUsize, Ordering};+ use std::sync::Arc;++ #[derive(Default)]+ struct Seen {+ commits: AtomicUsize,+ revalidated: AtomicUsize,+ }+ async fn commits(State(seen): State<Arc<Seen>>, headers: HeaderMap) -> axum::response::Response {+ seen.commits.fetch_add(1, Ordering::SeqCst);+ assert_eq!(headers.get("authorization").and_then(|v| v.to_str().ok()), Some("Bearer demo-token"));+ if headers.get("if-none-match").and_then(|v| v.to_str().ok()) == Some("\"c3\"") {+ seen.revalidated.fetch_add(1, Ordering::SeqCst);+ return axum::http::StatusCode::NOT_MODIFIED.into_response();+ }+ let c = |sha: &str| serde_json::json!({"sha": sha, "commit": {"message": format!("demo {sha}"), "author": {"name": "Demo (kwant bot)", "email": "[email protected]"}}});+ ([("etag", "\"c3\"")], Json(serde_json::json!([c("c3"), c("c2"), c("c1")]))).into_response()+ }+ async fn pulls() -> axum::response::Response {+ (axum::http::StatusCode::TOO_MANY_REQUESTS, [("retry-after", "120")], "slow down").into_response()+ }+ async fn tags() -> Json<serde_json::Value> {+ Json(serde_json::json!([{"name": "v0.7.0", "commit": {"sha": "c2"}}]))+ }+ let seen = Arc::new(Seen::default());+ let app = Router::new()+ .route("/repos/demo-org/demo-app/commits", get(commits))+ .route("/repos/demo-org/demo-app/pulls", get(pulls))+ .route("/repos/demo-org/demo-app/tags", get(tags))+ .with_state(seen.clone());+ let mut listener = None;+ for port in [9481u16, 9482, 9483, 9484, 0] {+ if let Ok(l) = tokio::net::TcpListener::bind(("127.0.0.1", port)).await {+ listener = Some(l);+ break;+ }+ }+ let listener = listener.expect("a local port for the mock");+ let base = format!("http://{}", listener.local_addr().unwrap());+ let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });++ let cfg = GithubConfig { api_base: base };+ cfg.validate().unwrap();+ let gh = GithubSource::for_dev("demo", cfg, Zeroizing::new("demo-token".into()));+ let cache = EtagCache::default();++ let (newer, found) = gh.dev_commits_since("demo-org/demo-app", "main", Some("c1"), &cache).await.unwrap();+ assert!(found);+ assert_eq!(newer.iter().map(|c| c.sha.as_str()).collect::<Vec<_>>(), ["c2", "c3"], "oldest first, after last_seen");+ // The second read sends the ETag back and gets the same answer from the cache+ let (again, _) = gh.dev_commits_since("demo-org/demo-app", "main", Some("c2"), &cache).await.unwrap();+ assert_eq!(again.iter().map(|c| c.sha.as_str()).collect::<Vec<_>>(), ["c3"]);+ assert_eq!(seen.commits.load(Ordering::SeqCst), 2);+ assert_eq!(seen.revalidated.load(Ordering::SeqCst), 1);+ // A last_seen GitHub no longer lists: everything it sent, and `found` says so+ let (all, found) = gh.dev_commits_since("demo-org/demo-app", "main", Some("gone"), &cache).await.unwrap();+ assert!(!found);+ assert_eq!(all.len(), 3);++ match gh.dev_open_pulls("demo-org/demo-app", "main", &cache).await {+ Err(GhError::Limited { retry_after_s }) => assert_eq!(retry_after_s, 120),+ other => panic!("expected a rate limit, got {other:?}"),+ }+ assert_eq!(gh.dev_latest_tag("demo-org/demo-app", &cache).await.unwrap(), Some(("v0.7.0".into(), Some("c2".into()))));+ assert!(matches!(gh.dev_latest_tag("demo-org/no-such", &cache).await, Err(GhError::NotFound)));+ server.abort();+ }}diff --git a/tests/dev_backup_test.rs b/tests/dev_backup_test.rsnew file mode 100644index 00000000..b8f55f9f--- /dev/null+++ b/tests/dev_backup_test.rs@@ -0,0 +1,78 @@+//! **Back up first** through `POST /api/spaces/:id/dev/backup` (D9, Rigel's F1–F3 on #313): a+//! request that goes away mid-backup doesn't strand the space, and only a file this run wrote+//! counts as a backup.++mod common;++use common::*;+use kwnt::db::spaces::SpaceId;+use kwnt::server::dev::backup;+use std::time::Duration;++const URI: &str = "/api/spaces/spc_default/dev/backup";++async fn set_command(env: &Env, command: &str) {+ env.state.db.put_dev_mode(SpaceId::default_space().as_str(), true, "demo-org/demo-app", "main", None, Some(command)).await.unwrap();+}++#[tokio::test]+async fn a_dropped_request_frees_the_space_and_only_a_file_this_run_wrote_counts() {+ let env = setup().await;+ let space = SpaceId::default_space();+ set_command(&env, "sleep 1; mkdir -p bk && head -c 300 /dev/zero > bk/app.sql && echo \"Backup saved to bk/app.sql\"").await;++ // The browser goes away while the command runs: the handler's future is dropped+ let gone = tokio::time::timeout(Duration::from_millis(300), call(&env.app, "POST", URI, None)).await;+ assert!(gone.is_err(), "the request should still be running at 300 ms");+ assert!(backup::is_running(space.as_str()), "the backup keeps running without its request");+ let (s, v) = call(&env.app, "POST", URI, None).await;+ assert_eq!(s.as_u16(), 409, "a second press while it runs is refused: {v}");++ // It finishes on its own, is recorded, and frees the space+ let deadline = tokio::time::Instant::now() + Duration::from_secs(15);+ while backup::is_running(space.as_str()) {+ assert!(tokio::time::Instant::now() < deadline, "the space was never freed");+ tokio::time::sleep(Duration::from_millis(100)).await;+ }+ let (last, ok) = env.state.db.latest_dev_backups(space.as_str()).await.unwrap();+ let last = last.expect("the dropped run was recorded");+ assert!(last.ok, "{:?}", last.error);+ assert!(last.path.as_deref().unwrap().ends_with("bk/app.sql"));+ assert_eq!(last.bytes, Some(300));+ assert_eq!(ok.map(|b| b.id), Some(last.id));++ // The next press runs again instead of a 409 until restart+ let (s, v) = call(&env.app, "POST", URI, None).await;+ assert_eq!(s.as_u16(), 200, "{v}");+ assert_eq!(v["ok"], true, "{v}");+ assert!(!backup::is_running(space.as_str()));++ // Only a file this run wrote counts. (One test, not two: the one-run-per-space claim is+ // process-wide, so two tests on the default space would refuse each other.)+ // Exit 0 and nothing named: not a backup (F2)+ set_command(&env, "echo done").await;+ let (s, v) = call(&env.app, "POST", URI, None).await;+ assert_eq!(s.as_u16(), 200, "{v}");+ assert_eq!(v["ok"], false, "{v}");+ assert_eq!(v["error"], backup::NOTHING_NAMED);++ // An existing file from an hour ago, named but not written by this run (F3)+ set_command(&env, "mkdir -p bk && head -c 300 /dev/zero > bk/old.sql && touch -d '1 hour ago' bk/old.sql && echo \"Backup saved to bk/old.sql\"").await;+ let (s, v) = call(&env.app, "POST", URI, None).await;+ assert_eq!(s.as_u16(), 200, "{v}");+ assert_eq!(v["ok"], false, "{v}");+ assert!(v["error"].as_str().unwrap().contains("older than this backup run"), "{v}");++ // A bare folder name in the run's folder, written now (F3)+ set_command(&env, "mkdir -p snapshots && head -c 64 /dev/zero > snapshots/app.dump && echo \"Backup written to snapshots\"").await;+ let (s, v) = call(&env.app, "POST", URI, None).await;+ assert_eq!(s.as_u16(), 200, "{v}");+ assert_eq!(v["ok"], true, "{v}");+ assert!(v["path"].as_str().unwrap().ends_with("/snapshots"), "{v}");+ assert_eq!(v["bytes"], 64);++ // The Allow gate reads the newest ok backup: the failed ones above don't count+ let (last, ok) = env.state.db.latest_dev_backups(SpaceId::default_space().as_str()).await.unwrap();+ assert!(last.unwrap().ok);+ assert!(ok.unwrap().path.unwrap().ends_with("/snapshots"));+}diff --git a/tests/dev_card_route_test.rs b/tests/dev_card_route_test.rsnew file mode 100644index 00000000..63b90ed1--- /dev/null+++ b/tests/dev_card_route_test.rs@@ -0,0 +1,77 @@+//! `GET /api/dev/cards/:id` (impl/lin.md): the desk reads one card by id, chiefly a release+//! notes draft once its `dev_card` event says it is ready, since no list returns those.++mod common;++use common::*;+use kwnt::db::dev_mode::{PENDING, READY, RELEASE_NOTES};+use kwnt::db::spaces::SpaceId;+use kwnt::server::continuity::{SelfScope, TurnOrigin};+use kwnt::server::mcp_runtime;+use serde_json::json;++/// A turn token of bot `a`, as its CLI holds it.+async fn turn_token(env: &Env) -> String {+ let bot = env.state.db.get_kwant(&env.a).await.unwrap().unwrap();+ let scope = SelfScope {+ kwant_id: bot.id.clone(),+ kwant_name: bot.name.clone(),+ origin: Some(TurnOrigin { direct_kwant_id: Some(bot.id.clone()), ..Default::default() }),+ cancel: Some(tokio_util::sync::CancellationToken::new()),+ turn_id: Some("turn-dev-card".into()),+ sandbox_target: Some(bot.id.clone()),+ ..Default::default()+ };+ mcp_runtime::prepare_turn_with_self(&env.state, &bot, Some("turn-dev-card".into()), None, Some(scope)).await.unwrap().1+}++#[tokio::test]+async fn a_release_notes_draft_is_read_by_id() {+ let env = setup().await;+ let space = SpaceId::default_space();+ let facts = json!({"repo": "demo-org/demo-app", "since_tag": "v1.0.0", "cards": []}).to_string();+ let row = env.state.db.insert_dev_card(space.as_str(), RELEASE_NOTES, "since:v1.0.0", "20261105T030000.000", &facts).await.unwrap().unwrap();+ let uri = format!("/api/dev/cards/{}", row.id);++ // Pending: the row's fields only, no facts leak into the card+ let (s, v) = call(&env.app, "GET", &uri, None).await;+ assert_eq!(s.as_u16(), 200, "{v}");+ assert_eq!((v["id"].as_str(), v["kind"].as_str(), v["status"].as_str()), (Some(row.id.as_str()), Some(RELEASE_NOTES), Some(PENDING)));+ assert!(v["created_at"].is_string() && v.get("markdown").is_none() && v.get("repo").is_none(), "{v}");++ // Ready: the draft's text, with the row's id, kind, status and created_at winning+ let card = json!({"since_tag": "v1.0.0", "markdown": "## What's new\n- Faster sign-in", "whats_new": ["Faster sign-in"], "id": "spoof", "status": "spoof"});+ env.state.db.set_dev_card(&row.id, READY, Some(&card.to_string())).await.unwrap();+ let (s, v) = call(&env.app, "GET", &uri, None).await;+ assert_eq!(s.as_u16(), 200, "{v}");+ assert_eq!(v["markdown"], "## What's new\n- Faster sign-in");+ assert_eq!(v["whats_new"], json!(["Faster sign-in"]));+ assert_eq!((v["id"].as_str(), v["status"].as_str(), v["kind"].as_str()), (Some(row.id.as_str()), Some(READY), Some(RELEASE_NOTES)));+}++#[tokio::test]+async fn an_unknown_card_is_a_404() {+ let env = setup().await;+ let (s, v) = call(&env.app, "GET", "/api/dev/cards/dvc_nope", None).await;+ assert_eq!(s.as_u16(), 404, "{v}");+ assert_eq!(v["error"], "no such card");+}++#[tokio::test]+async fn a_bot_cannot_read_a_card() {+ let env = setup().await;+ let space = SpaceId::default_space();+ let row = env.state.db.insert_dev_card(space.as_str(), RELEASE_NOTES, "since:", "20261105T030001.000", "{}").await.unwrap().unwrap();+ env.state.db.set_dev_card(&row.id, READY, Some(&json!({"markdown": "secret diff summary"}).to_string())).await.unwrap();+ let uri = format!("/api/dev/cards/{}", row.id);++ let token = turn_token(&env).await;+ for auth in [format!("Bearer {token}"), "Bearer not-the-person".to_string()] {+ let (s, v) = call_with(&env.app, "GET", &uri, None, &[("authorization", auth.as_str())]).await;+ assert_eq!(s.as_u16(), 403, "{v}");+ assert!(!v.to_string().contains("secret diff summary"), "{v}");+ }+ let (s, _) = call(&env.app, "GET", &uri, None).await;+ assert_eq!(s.as_u16(), 200, "the person still reads it");+ assert!(call_remote(&env.app, "GET", &uri).await.is_client_error(), "a remote client without the API token is refused");+}diff --git a/tests/dev_floor_test.rs b/tests/dev_floor_test.rsnew file mode 100644index 00000000..546c8e65--- /dev/null+++ b/tests/dev_floor_test.rs@@ -0,0 +1,162 @@+//! The production floor through the real approval route (plan §3.5): in a Dev mode space a step+//! that needs a backup gets a card with `prod_floor`, and **Allow** on it is refused by the server+//! (409, the card stays waiting) until the space has an ok backup at most 10 minutes old. Deny is+//! always accepted.++mod common;++use common::*;+use kwnt::db::dev_mode::DevBackupRow;+use kwnt::mcp::{ApprovalOutcome, ToolApprovalRequest, ToolApprover};+use kwnt::server::mcp_runtime::BrokerApprover;+use serde_json::{json, Value};+use std::sync::Arc;+use std::time::Duration;++fn approver(env: &Env) -> Arc<BrokerApprover> {+ Arc::new(BrokerApprover {+ db: env.state.db.clone(),+ data_dir: env.state.config.data_dir.clone(),+ broker: env.state.broker.clone(),+ events: env.state.event_sender.clone(),+ timeout: Duration::from_millis(200),+ conversation: env.a.clone(),+ chat: Some(json!({"direct_kwant_id": env.a})),+ always_ask: false,+ })+}++fn request(env: &Env, command: &str) -> ToolApprovalRequest {+ ToolApprovalRequest {+ kwant_id: env.a.clone(),+ kwant_name: "A".into(),+ turn_id: "t-floor".into(),+ tool_name: "Bash".into(),+ server: String::new(),+ tool: "Bash".into(),+ arguments: json!({"command": command, "description": "demo"}),+ builtin: None,+ smart: None,+ payment: None,+ }+}++/// Runs one call nobody answers and returns its waiting card.+async fn unanswered(env: &Env, command: &str) -> (String, Value) {+ assert_eq!(approver(env).decide(request(env, command)).await, ApprovalOutcome::Unanswered);+ let rows = env.state.db.list_approvals(&kwnt::db::spaces::SpaceId::default_space(), Some("waiting"), Some(&env.a)).await.unwrap();+ let row = rows.into_iter().find(|r| r.parameters.contains(command)).expect("a waiting card");+ let details: Value = serde_json::from_str(&row.parameters).unwrap();+ (row.id, details)+}++async fn space_of_a(env: &Env) -> String {+ env.state.db.get_kwant(&env.a).await.unwrap().unwrap().space_id+}++fn backup(space: &str, ok: bool, age_s: i64) -> DevBackupRow {+ DevBackupRow {+ id: format!("dvb_{}", uuid::Uuid::new_v4().simple()),+ space_id: space.into(),+ kwant_id: None,+ path: Some("/tmp/demo.sql".into()),+ bytes: Some(10),+ ok,+ error: (!ok).then(|| "exit 1".into()),+ taken_at: chrono::Utc::now() - chrono::Duration::seconds(age_s),+ }+}++#[tokio::test]+async fn allow_on_a_step_that_needs_a_backup_is_refused_until_a_fresh_one() {+ let env = setup().await;+ let space = space_of_a(&env).await;++ // Dev mode off: no floor on the card+ let (_, off) = unanswered(&env, "sqlite3 demo.db 'DROP TABLE demo_off'").await;+ assert!(off.get("prod_floor").is_none(), "{off}");++ env.state.db.put_dev_mode(&space, true, "demo-org/demo-app", "main", None, Some("pg_dump demo > /tmp/demo.sql")).await.unwrap();+ let (ticket, details) = unanswered(&env, "sqlite3 demo.db 'DROP TABLE demo_on'").await;+ let floor = &details["prod_floor"];+ assert_eq!(floor["kind"], "destructive", "{details}");+ assert_eq!(floor["needs_backup"], true);+ assert_eq!(floor["space_id"], space.as_str());+ assert_eq!(floor["backup"]["state"], "none");++ // No backup, then an 11-minute-old one: Allow and Always allow are refused, the card waits+ env.state.db.insert_dev_backup(&backup(&space, true, 660)).await.unwrap();+ for decision in ["allow_once", "always_allow"] {+ let (s, v) = call(&env.app, "POST", &format!("/api/approvals/{ticket}/resolve"), Some(json!({"decision": decision}))).await;+ assert_eq!(s.as_u16(), 409, "{v}");+ assert_eq!(v["status"], "needs_backup");+ assert_eq!(v["resolved"], false);+ assert_eq!(v["ticket_id"], ticket.as_str());+ assert_eq!(v["backup"]["state"], "old");+ assert!(v["error"].as_str().unwrap().starts_with("Back up first"));+ }+ assert_eq!(env.state.db.get_approval(&ticket).await.unwrap().unwrap().status, "waiting");++ // A fresh ok backup, taken while the card waits, lets Allow through+ env.state.db.insert_dev_backup(&backup(&space, true, 20)).await.unwrap();+ let (s, v) = call(&env.app, "POST", &format!("/api/approvals/{ticket}/resolve"), Some(json!({"decision": "allow_once"}))).await;+ assert_eq!(s.as_u16(), 200, "{v}");+ assert_eq!(env.state.db.get_approval(&ticket).await.unwrap().unwrap().status, "allowed_once");+ wait_for("the resumed turn to end", || async { env.state.turns.active_turns().is_empty() }).await;+}++#[tokio::test]+async fn deny_is_always_accepted_on_a_floor_card() {+ let env = setup().await;+ let space = space_of_a(&env).await;+ env.state.db.put_dev_mode(&space, true, "demo-org/demo-app", "main", None, None).await.unwrap();+ let (ticket, details) = unanswered(&env, "psql postgres://db.example.com/demo -c 'TRUNCATE demo'").await;+ assert_eq!(details["prod_floor"]["needs_backup"], true, "{details}");+ assert_eq!(details["prod_floor"]["backup"]["state"], "no_command");+ let (s, v) = call(&env.app, "POST", &format!("/api/approvals/{ticket}/resolve"), Some(json!({"decision": "deny"}))).await;+ assert_eq!(s.as_u16(), 200, "{v}");+ assert_eq!(env.state.db.get_approval(&ticket).await.unwrap().unwrap().status, "denied");+}++/// The floor skips its reads while no space has Dev mode on (an in-memory flag). Turning it on+/// anywhere applies the floor to the very next call, and turning it off in one space leaves the+/// others' floor in place: the flag is never stale.+#[tokio::test]+async fn turning_dev_mode_on_applies_the_floor_at_once() {+ let env = setup().await;+ let space = space_of_a(&env).await;+ let db = &env.state.db;+ let floor_of = |n: u32| {+ let env = &env;+ async move { unanswered(env, &format!("sqlite3 demo.db 'DROP TABLE demo_{n}'")).await.1.get("prod_floor").cloned() }+ };+ assert!(!db.any_dev_mode_on());+ assert!(floor_of(1).await.is_none());++ // On in another space only: the flag is up, but A's space still has no floor+ db.put_dev_mode("spc_other", true, "demo-org/other", "main", None, None).await.unwrap();+ assert!(db.any_dev_mode_on());+ assert!(floor_of(2).await.is_none());++ // On in A's space: the next call gets the floor, with no wait+ db.put_dev_mode(&space, true, "demo-org/demo-app", "main", None, None).await.unwrap();+ assert_eq!(floor_of(3).await.expect("the floor applies at once")["kind"], "destructive");++ // Off in the other space: A's floor stays+ db.put_dev_mode("spc_other", false, "demo-org/other", "main", None, None).await.unwrap();+ assert!(db.any_dev_mode_on());+ assert!(floor_of(4).await.is_some());++ // Off everywhere: no floor, flag down; on again (a clone shares the flag), floor back+ db.put_dev_mode(&space, false, "demo-org/demo-app", "main", None, None).await.unwrap();+ assert!(!db.any_dev_mode_on());+ assert!(floor_of(5).await.is_none());+ db.clone().put_dev_mode(&space, true, "demo-org/demo-app", "main", None, None).await.unwrap();+ assert!(db.any_dev_mode_on());+ assert!(floor_of(6).await.is_some());++ // Deleting the space's Dev mode rows takes the flag down too+ db.delete_dev_mode_of_space(&space).await.unwrap();+ assert!(!db.any_dev_mode_on());+ assert!(floor_of(7).await.is_none());+}diff --git a/tests/dev_github_test.rs b/tests/dev_github_test.rsnew file mode 100644index 00000000..17ff2ff3--- /dev/null+++ b/tests/dev_github_test.rs@@ -0,0 +1,316 @@+//! Dev mode's GitHub reads against the shared mock (`tests/support/mock_github.rs`, QA plan §2.1):+//! ETags and 304, every error GitHub sends and what kwant makes of it, a `Link: next` to another+//! host that is never followed, a lost base commit, and only GETs, always with the token.+//!+//! The canary (QA plan §2.5): a GitHub token built at runtime goes through a whole poll, its+//! failures included, and appears nowhere but the vault: not in logs, errors, the event stream,+//! card facts, the database, model prompts, or any other file under the data folder.++mod common;+#[path = "support/mock_github.rs"]+mod mock_github;++use common::*;+use kwnt::db::dev_mode::{LANDED, REVIEW};+use kwnt::db::spaces::SpaceId;+use kwnt::server::dev::poller;+use kwnt::zombie::github::{EtagCache, GhError, GithubConfig, GithubSource};+use mock_github::*;+use serde_json::{json, Value};+use std::sync::{Arc, Mutex, OnceLock};+use std::time::{Duration, Instant};+use zeroize::Zeroizing;++const REPO: &str = "demo-org/demo-app";+const R: &str = "/repos/demo-org/demo-app";+const PORTS: [u16; 2] = [9481, 9482];+const OTHER_PORTS: [u16; 2] = [9483, 9484];++fn sha(n: u8) -> String {+ format!("{n:x}").repeat(40)+}++fn client(gh: &MockGithub, token: &str) -> GithubSource {+ GithubSource::for_dev("src_demo", GithubConfig { api_base: gh.base.clone() }, Zeroizing::new(token.to_string()))+}++#[tokio::test]+async fn an_unchanged_answer_is_a_304_and_reads_from_the_cache() {+ let gh = MockGithub::start(&PORTS).await;+ let token = canary_token();+ gh.require_token(&token).json(&format!("{R}/tags"), json!([{"name": "v1.0.0", "commit": {"sha": sha(1)}}]));+ let c = client(&gh, &token);+ let cache = EtagCache::default();++ let first = c.dev_latest_tag(REPO, &cache).await.unwrap();+ let second = c.dev_latest_tag(REPO, &cache).await.unwrap();+ assert_eq!(first, Some(("v1.0.0".into(), Some(sha(1)))));+ assert_eq!(second, first, "a 304 answers from the cache");+ let hits = gh.hits_of(&format!("{R}/tags"));+ assert_eq!(hits.iter().map(|h| h.not_modified).collect::<Vec<_>>(), [false, true], "{hits:?}");++ gh.json(&format!("{R}/tags"), json!([{"name": "v1.1.0", "commit": {"sha": sha(2)}}]));+ assert_eq!(c.dev_latest_tag(REPO, &cache).await.unwrap(), Some(("v1.1.0".into(), Some(sha(2)))), "a changed ETag is read again");+ assert!(gh.hits().iter().all(|h| h.authorized && h.method == "GET"));+}++#[tokio::test]+async fn each_github_error_is_told_apart() {+ let gh = MockGithub::start(&PORTS).await;+ let token = canary_token();+ gh.require_token(&token).json(R, repo(REPO, "main"));+ let c = client(&gh, &token);+ assert_eq!(c.dev_repo(REPO).await.unwrap().default_branch, "main");++ let reset = chrono::Utc::now().timestamp() as u64 + 600;+ type Expect = fn(&GhError) -> bool;+ let cases: Vec<(Fault, Expect)> = vec![+ (Fault::Unauthorized, |e| *e == GhError::Auth),+ (Fault::Forbidden, |e| *e == GhError::Forbidden),+ (Fault::RateLimited { reset_epoch: reset }, |e| matches!(e, GhError::Limited { retry_after_s } if (590..=600).contains(retry_after_s))),+ (Fault::SecondaryLimit { retry_after: 120 }, |e| *e == GhError::Limited { retry_after_s: 120 }),+ (Fault::TooMany { retry_after: Some(30) }, |e| *e == GhError::Limited { retry_after_s: 30 }),+ (Fault::TooMany { retry_after: None }, |e| *e == GhError::Limited { retry_after_s: 60 }),+ (Fault::Server(500), |e| *e == GhError::Other("GitHub answered 500".into())),+ (Fault::Server(502), |e| *e == GhError::Other("GitHub answered 502".into())),+ (Fault::Server(503), |e| *e == GhError::Other("GitHub answered 503".into())),+ (Fault::MissingBase, |e| *e == GhError::NotFound),+ ];+ for (fault, expected) in cases {+ gh.fault(R, fault.clone());+ let e = c.dev_repo(REPO).await.unwrap_err();+ assert!(expected(&e), "{fault:?} gave {e:?}");+ assert!(!e.to_string().contains(&token) && !format!("{e:?}").contains(&token), "{fault:?}: the error carries no token");+ }++ gh.heal(R);+ assert_eq!(client(&gh, &canary_token()).dev_repo(REPO).await.unwrap_err(), GhError::Auth, "another token is refused");+ assert!(gh.hits().last().unwrap().authorized);++ gh.fault(R, Fault::Slow(Duration::from_millis(1500)));+ let t = Instant::now();+ assert_eq!(c.dev_repo(REPO).await.unwrap().full_name, REPO, "a slow answer still counts");+ assert!(t.elapsed() >= Duration::from_millis(1500));+ assert!(gh.hits().iter().all(|h| h.method == "GET"));+}++/// kwant pages PR files on its own base (`?page=N`) and never follows a `Link: next`, so a link+/// to another host is never fetched and never gets the token.+#[tokio::test]+async fn a_next_link_to_another_host_is_never_followed() {+ let gh = MockGithub::start(&PORTS).await;+ let elsewhere = MockGithub::start(&OTHER_PORTS).await;+ let token = canary_token();+ gh.require_token(&token);+ let files = |from: usize, n: usize| Value::Array((from..from + n).map(|i| file(&format!("src/f{i}.rs"), "modified", "+a\n-b")).collect());+ let page1 = format!("{R}/pulls/7/files?per_page=100&page=1");+ gh.json(&page1, files(0, 100))+ .json(&format!("{R}/pulls/7/files?per_page=100&page=2"), files(100, 3))+ .link_next(&page1, &format!("{}{R}/pulls/7/files?per_page=100&page=2", elsewhere.base));++ let got = client(&gh, &token).dev_pull_files(REPO, 7).await.unwrap();+ assert_eq!(got.len(), 103, "page 2 came from GitHub's own base");+ assert!(elsewhere.hits().is_empty(), "the other host was never asked: {:?}", elsewhere.hits());+ let paths: Vec<String> = gh.hits().into_iter().map(|h| h.path).collect();+ assert_eq!(paths, [page1, format!("{R}/pulls/7/files?per_page=100&page=2")]);+}++/// A force push took the last seen commit off the branch: the list doesn't hold it, so kwant takes+/// the newest commits only, and reading the lost commit is a plain not-found.+#[tokio::test]+async fn a_lost_base_commit_falls_back_to_the_newest() {+ let gh = MockGithub::start(&PORTS).await;+ let token = canary_token();+ gh.require_token(&token);+ let list: Vec<Value> = (2..=4).rev().map(|n| commit(&sha(n), &format!("Change {n}"), ("Demo Person", "[email protected]"), &[], "2026-11-05T01:00:00Z")).collect();+ gh.json(&format!("{R}/commits"), Value::Array(list)).fault(&format!("{R}/commits/{}", sha(1)), Fault::MissingBase);+ let c = client(&gh, &token);++ let (commits, found) = c.dev_commits_since(REPO, "main", Some(&sha(1)), &EtagCache::default()).await.unwrap();+ assert!(!found);+ assert_eq!(commits.iter().map(|c| c.sha.clone()).collect::<Vec<_>>(), [sha(2), sha(3), sha(4)], "oldest first");+ assert_eq!(poller::window(commits, false, found).len(), 3, "at most MAX_NEW of them");+ assert_eq!(c.dev_commit(REPO, &sha(1)).await.unwrap_err(), GhError::NotFound);++ let (commits, found) = c.dev_commits_since(REPO, "main", Some(&sha(3)), &EtagCache::default()).await.unwrap();+ assert!(found);+ assert_eq!(commits.iter().map(|c| c.sha.clone()).collect::<Vec<_>>(), [sha(4)]);+}++#[tokio::test]+async fn a_write_to_the_mock_fails_the_test() {+ let gh = MockGithub::start(&OTHER_PORTS).await;+ let res = reqwest::Client::new().post(format!("{}{R}/merges", gh.base)).body("{}").send().await.unwrap();+ assert_eq!(res.status().as_u16(), 405);+ assert_eq!(gh.hits()[0].method, "POST");+ let dropped = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || drop(gh)));+ assert!(dropped.is_err(), "dropping a mock that saw a write panics");+}++// ---- the canary -------------------------------------------------------------------------------++static LOG: OnceLock<Arc<Mutex<Vec<u8>>>> = OnceLock::new();++struct Capture(Arc<Mutex<Vec<u8>>>);++impl std::io::Write for Capture {+ fn write(&mut self, b: &[u8]) -> std::io::Result<usize> {+ self.0.lock().unwrap().extend_from_slice(b);+ Ok(b.len())+ }+ fn flush(&mut self) -> std::io::Result<()> {+ Ok(())+ }+}++/// Every log line of this test binary, at debug (trace for kwnt itself).+fn capture_logs() -> Arc<Mutex<Vec<u8>>> {+ LOG.get_or_init(|| {+ let buf = Arc::new(Mutex::new(Vec::new()));+ let writer = buf.clone();+ let sub = tracing_subscriber::fmt()+ .with_env_filter(tracing_subscriber::EnvFilter::new("debug,kwnt=trace"))+ .with_ansi(false)+ .with_writer(move || Capture(writer.clone()))+ .finish();+ tracing::subscriber::set_global_default(sub).expect("no other subscriber in this binary");+ buf+ })+ .clone()+}++/// A repo with one merged PR, one direct commit, one open PR, CI and a tag.+fn seed(gh: &MockGithub) {+ let person = ("Lin (kwant bot)", "[email protected]");+ let with_files = |mut c: Value, files: Value| {+ c["files"] = files;+ c+ };+ let patch = "@@ -1,2 +1,2 @@\n-let retries = 1;\n+let retries = 3;";+ let merged = commit(&sha(2), "Retry the upload (#5)", person, &[&sha(1)], "2026-11-05T02:00:00Z");+ let direct = commit(&sha(1), "Fix the README", person, &[], "2026-11-05T01:00:00Z");+ gh.json("/user", user("demo-person"))+ .json(R, repo(REPO, "main"))+ .json(&format!("{R}/branches/main"), json!({"name": "main"}))+ .json(&format!("{R}/contents"), json!([{"name": "Cargo.toml", "type": "file"}]))+ .json(&format!("{R}/tags"), json!([{"name": "v0.1.0", "commit": {"sha": sha(1)}}]))+ .json(&format!("{R}/commits"), json!([merged, direct]))+ .json(&format!("{R}/commits/{}", sha(2)), with_files(merged.clone(), json!([file("src/upload.rs", "modified", patch)])))+ .json(&format!("{R}/commits/{}", sha(1)), with_files(direct.clone(), json!([file("README.md", "modified", "-old\n+new")])))+ .json(&format!("{R}/commits/{}/pulls", sha(2)), json!([pull(5, "Retry the upload", ("retry", &sha(9)), "main", "demo-person", Some((&sha(2), "2026-11-05T02:00:00Z")))]))+ .json(&format!("{R}/commits/{}/pulls", sha(1)), json!([]))+ .json(&format!("{R}/pulls/5/files"), json!([file("src/upload.rs", "modified", patch)]))+ .json(&format!("{R}/commits/{}/check-runs", sha(2)), check_runs(&[("rust", "completed", Some("success"))]))+ .json(&format!("{R}/commits/{}/check-runs", sha(1)), check_runs(&[("rust", "completed", Some("failure"))]))+ .json(&format!("{R}/pulls"), json!([pull(8, "Add a cache", ("cache", &sha(3)), "main", "demo-person", None)]))+ .json(&format!("{R}/pulls/8/files"), json!([file("src/cache.rs", "added", "+pub struct Cache;")]))+ .json(&format!("{R}/commits/{}", sha(3)), commit(&sha(3), "Add a cache", person, &[&sha(2)], "2026-11-05T03:00:00Z"))+ .json(&format!("{R}/commits/{}/check-runs", sha(3)), check_runs(&[("rust", "in_progress", None)]));+}++/// Every file under `dir` (the vault's folder left out) that holds `needle`.+fn files_with(dir: &std::path::Path, needle: &[u8], vault: &std::path::Path, out: &mut Vec<String>) {+ for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() {+ let p = entry.path();+ if p.starts_with(vault) {+ continue;+ }+ if p.is_dir() {+ files_with(&p, needle, vault, out);+ } else if std::fs::read(&p).is_ok_and(|b| b.windows(needle.len()).any(|w| w == needle)) {+ out.push(p.display().to_string());+ }+ }+}++#[tokio::test]+async fn the_github_token_never_leaves_the_vault() {+ let logs = capture_logs();+ let env = setup().await;+ let space = SpaceId::default_space();+ // An asking install, so the login may be saved here (F-10)+ env.state.db.set_space_approvals(&space, "ask").await.unwrap();+ let token = canary_token();+ let gh = MockGithub::start(&PORTS).await;+ gh.require_token(&token);+ seed(&gh);+ let mut events = env.state.event_sender.subscribe();++ let (s, v) = call(&env.app, "POST", "/api/zombie/sources", Some(json!({"kind": "github", "label": "GitHub", "config": {"api_base": gh.base}, "secret": token}))).await;+ assert_eq!(s.as_u16(), 201, "{v}");+ let source_id = v["source"]["id"].as_str().unwrap().to_string();+ let mut replies = vec![v];+ let (s, v) = call(&env.app, "PUT", &format!("/api/spaces/{}/dev_mode", space.as_str()), Some(json!({"on": true, "repo": REPO, "branch": "main"}))).await;+ assert_eq!(s.as_u16(), 200, "{v}");+ replies.push(v);+ let (_, v) = call(&env.app, "POST", &format!("/api/spaces/{}/dev_mode/check", space.as_str()), Some(json!({"repo": REPO}))).await;+ replies.push(v);++ let mode = env.state.db.dev_mode(space.as_str()).await.unwrap().unwrap();+ poller::poll(&env.state, &mode).await.expect("a clean poll");+ let landed = env.state.db.dev_cards(space.as_str(), LANDED, None, 50).await.unwrap();+ let reviews = env.state.db.dev_cards(space.as_str(), REVIEW, None, 50).await.unwrap();+ assert_eq!((landed.len(), reviews.len()), (2, 1), "both commits and the open PR made cards");++ // Failures, as the poller records them+ let mut errors = Vec::new();+ for fault in [Fault::Server(502), Fault::Unauthorized, Fault::Forbidden] {+ gh.fault(R, fault.clone());+ let mode = env.state.db.dev_mode(space.as_str()).await.unwrap().unwrap();+ errors.push(format!("{:?}", poller::poll(&env.state, &mode).await.unwrap_err()));+ poller::poll_logged(&env.state, mode).await;+ let after = env.state.db.dev_mode(space.as_str()).await.unwrap().unwrap();+ errors.push(after.poll_error.clone().unwrap_or_else(|| panic!("{fault:?} left no poll error")));+ }+ gh.heal(R);+ let (_, v) = call(&env.app, "GET", &format!("/api/spaces/{}/dev_mode", space.as_str()), None).await;+ replies.push(v);+ let (_, v) = call(&env.app, "GET", &format!("/api/spaces/{}/dev/landed", space.as_str()), None).await;+ replies.push(v);+ let (_, v) = call(&env.app, "GET", &format!("/api/spaces/{}/dev/reviews", space.as_str()), None).await;+ replies.push(v);+ let (_, v) = call(&env.app, "GET", "/api/zombie/sources", None).await;+ replies.push(v);++ // Let the cards' text be written (the fake model answers), so its prompts are on disk too+ for _ in 0..100 {+ if env.state.db.pending_dev_cards().await.map(|p| p.is_empty()).unwrap_or(true) {+ break;+ }+ tokio::time::sleep(Duration::from_millis(100)).await;+ }++ let leaks = |what: &str, text: &str| assert!(!text.contains(&token), "the token leaked into {what}");+ for e in &errors {+ leaks("an error", e);+ }+ for r in &replies {+ leaks("an API reply", &r.to_string());+ }+ for row in landed.iter().chain(&reviews).chain(&env.state.db.dev_cards(space.as_str(), LANDED, None, 50).await.unwrap()) {+ leaks("card facts", &row.facts);+ leaks("a card", row.card.as_deref().unwrap_or_default());+ }+ let mut seen = 0;+ while let Ok(ev) = events.try_recv() {+ leaks("the event stream", &serde_json::to_string(&ev).unwrap());+ seen += 1;+ }+ assert!(seen > 0, "the poll sent card events");+ let log = String::from_utf8_lossy(&logs.lock().unwrap()).to_string();+ assert!(log.contains("dev: poll failed"), "the log capture works");+ leaks("the log", &log);+ assert!(invocations_with(&token).is_empty(), "the token reached a model prompt");++ // The database (every table, WAL included) and every other file under the data folder+ let data = env.state.config.data_dir.clone();+ let mut found = Vec::new();+ files_with(&data, token.as_bytes(), &data.join("kwnt-vault"), &mut found);+ assert!(found.is_empty(), "the token is in {found:?}");+ assert!(data.join("kwnt.db").exists());+ let kept = kwnt::zombie::hunt::source_secret(env.state.credentials.as_ref(), &source_id, &gh.base).await.unwrap();+ assert_eq!(kept.as_deref().map(String::as_str), Some(token.as_str()), "the vault holds it, and only the vault");++ // Only reads, each with the token+ assert!(gh.hits().iter().all(|h| h.method == "GET" && h.authorized), "{:?}", gh.hits());+}diff --git a/tests/dev_seams_test.rs b/tests/dev_seams_test.rsnew file mode 100644index 00000000..96716693--- /dev/null+++ b/tests/dev_seams_test.rs@@ -0,0 +1,61 @@+//! Dev mode's test seams (QA plan §2.2), in their own binary because both are process-wide:+//! `KWANT_DEV_POLL_SECS` / `KWANT_DEV_CALL_CAP` are read once, and the clock skew moves+//! `kwnt::server::dev::now()` for everything in the process.++use chrono::{Duration, Utc};+use kwnt::db::dev_mode::DevBackupRow;+use kwnt::db::Database;+use kwnt::server::dev::{self, floor};+use serde_json::json;++/// The two tests change process-wide state: one at a time.+static ONE: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());++#[tokio::test]+async fn the_clock_seam_ages_a_backup_past_ten_minutes() {+ let _one = ONE.lock().await;+ let tmp = tempfile::tempdir().unwrap();+ let db = Database::init(tmp.path()).await.unwrap();+ let card = json!({"prod_floor": {"kind": "destructive", "needs_backup": true, "space_id": "s1"}});+ db.put_dev_mode("s1", true, "demo-org/demo-app", "main", None, Some("pg_dump demo > /tmp/demo.sql")).await.unwrap();++ db.insert_dev_backup(&DevBackupRow {+ id: "dvb_clock".into(),+ space_id: "s1".into(),+ kwant_id: None,+ path: Some("/tmp/demo.sql".into()),+ bytes: Some(10),+ ok: true,+ error: None,+ taken_at: dev::now(),+ })+ .await+ .unwrap();+ assert_eq!(floor::allow_refusal(&db, &card).await, None, "a backup taken just now is fresh");++ dev::set_clock_skew(9 * 60);+ assert_eq!(floor::allow_refusal(&db, &card).await, None, "9 minutes on, still fresh");+ dev::set_clock_skew(11 * 60);+ assert!((dev::now() - Utc::now() - Duration::minutes(11)).num_seconds().abs() <= 1);+ let refusal = floor::allow_refusal(&db, &card).await.expect("11 minutes on, Allow is refused");+ assert_eq!(refusal["backup"]["state"], "old", "{refusal}");+ dev::set_clock_skew(0);+ assert_eq!(floor::allow_refusal(&db, &card).await, None);+}++#[tokio::test]+async fn the_env_seams_set_the_poll_and_the_cap() {+ let _one = ONE.lock().await;+ // Read once per process: set before the first read, as a test server would at launch+ std::env::set_var("KWANT_DEV_POLL_SECS", "7");+ std::env::set_var("KWANT_DEV_CALL_CAP", "2");+ assert_eq!(dev::poll_every(), std::time::Duration::from_secs(7));+ assert_eq!(dev::call_cap(), 2);++ let tmp = tempfile::tempdir().unwrap();+ let db = Database::init(tmp.path()).await.unwrap();+ assert!(db.take_dev_call("s1").await.unwrap());+ assert!(db.take_dev_call("s1").await.unwrap());+ assert!(!db.take_dev_call("s1").await.unwrap(), "the third call today is over the cap of 2");+ assert_eq!(db.dev_calls_today("s1").await.unwrap(), 2);+}diff --git a/tests/payment_floor_test.rs b/tests/payment_floor_test.rsindex 11728057..e051b50f 100644--- a/tests/payment_floor_test.rs+++ b/tests/payment_floor_test.rs@@ -120,22 +120,40 @@ async fn claude_asks(e: &Env, tool: &str, input: Value, answer: ApprovalDecisionlet text = v["result"]["content"][0]["text"].as_str().unwrap();serde_json::from_str::<Value>(text).unwrap()["behavior"].as_str().unwrap().to_string()};- let answered = tokio::time::timeout(Duration::from_millis(1500), &mut prompt).await;- let card = loop {- match events.try_recv() {- Ok(RuntimeEvent::ApprovalRequired { id, details, .. }) => break Some((id, details)),- Ok(_) => continue,- Err(_) => break None,+ // Whichever comes first, the answer or a card, up to 10 s: a fixed wait flaked under load+ let first = tokio::time::timeout(Duration::from_secs(10), async {+ loop {+ tokio::select! {+ done = &mut prompt => break Ok(done.unwrap().1),+ ev = events.recv() => match ev {+ Ok(RuntimeEvent::ApprovalRequired { id, details, .. }) => break Err((id, details)),+ Ok(_) | Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue,+ Err(e) => panic!("event stream closed: {e}"),+ },+ }}- };- let out = match (answered, card) {- (Ok(done), None) => Ok(behavior(&done.unwrap().1)),- (Err(_), Some((id, details))) => {+ })+ .await+ .expect("no answer and no card within 10 s");+ let out = match first {+ Ok(v) => {+ // Answered without asking: no card may have gone out on the way+ let card = loop {+ match events.try_recv() {+ Ok(RuntimeEvent::ApprovalRequired { id, details, .. }) => break Some((id, details)),+ Ok(_) | Err(tokio::sync::broadcast::error::TryRecvError::Lagged(_)) => continue,+ Err(_) => break None,+ }+ };+ assert!(card.is_none(), "answered with card {card:?}");+ Ok(behavior(&v))+ }+ Err((id, details)) => {+ assert!(!prompt.is_finished(), "a card went out and the prompt answered anyway");assert!(e.state.broker.resolve(&id, answer).await);let (_, v) = prompt.await.unwrap();Err((details, behavior(&v)))}- (answered, card) => panic!("answered {} with card {card:?}", answered.is_ok()),};mcp_runtime::finish_turn(&e.state, &token).await;e.state.turns.end_turn(&turn_id);@@ -295,7 +313,7 @@ async fn a_local_shell_payment_waits_for_the_person_with_approvals_off() {set_approvals(&e, "off").await;let folder = tempdir().unwrap();let ran = tokio::time::timeout(- Duration::from_secs(3),+ Duration::from_secs(10),kwnt::server::computer::approve_local_shell(&e.state, &e.bot.id, "touch x", folder.path()),).awaitdiff --git a/tests/support/mock_github.rs b/tests/support/mock_github.rsnew file mode 100644index 00000000..6259ea10--- /dev/null+++ b/tests/support/mock_github.rs@@ -0,0 +1,328 @@+//! A mock GitHub REST API for Dev mode tests (QA plan §2.1), shared by Lin, Vega, Juno and Rigel.+//!+//! ```ignore+//! #[path = "support/mock_github.rs"]+//! mod mock_github;+//! let gh = mock_github::MockGithub::start(&[9481, 9482]).await; // your own ports; 0 = any+//! gh.json("/repos/demo-org/demo-app", json!({...})); // 200 + an ETag (304 on a match)+//! gh.fault("/repos/demo-org/demo-app/pulls", Fault::TooMany { retry_after: Some(120) });+//! gh.link_next("/repos/demo-org/demo-app/pulls/7/files", "https://elsewhere.example/page2");+//! ... point kwant at gh.base ...+//! assert!(gh.hits().iter().all(|h| h.authorized));+//! ```+//!+//! - Replies are looked up by the full path with its query first, then by the path alone. A path+//! with neither gets GitHub's 404 `{"message": "Not Found"}`.+//! - Every 200 carries a strong ETag (a hash of the body); a request whose `If-None-Match` matches+//! gets 304 with no body, as GitHub does.+//! - With [`MockGithub::require_token`], a request without that bearer token gets 401.+//! - Every request is logged: method, path with query, and whether `Authorization` was sent.+//! - Dev mode only reads. Any request that isn't a GET is answered 405, logged, and fails the test:+//! [`MockGithub::assert_read_only`] panics, and so does dropping the mock (unless the test is+//! already failing).+//! - Secret-looking strings are built at runtime ([`canary_token`], [`secret_like`]), so GitHub push+//! protection and Gitleaks never see one in the source.++#![allow(dead_code)]++use axum::body::Body;+use axum::extract::{Request, State};+use axum::http::{HeaderMap, HeaderValue, Method, StatusCode};+use axum::response::{IntoResponse, Response};+use axum::Router;+use serde_json::{json, Value};+use std::collections::HashMap;+use std::sync::{Arc, Mutex};+use std::time::Duration;++/// How a path fails instead of answering.+#[derive(Clone, Debug, PartialEq)]+pub enum Fault {+ /// 401 Bad credentials.+ Unauthorized,+ /// A plain 403: no access, and no rate-limit sign.+ Forbidden,+ /// 403 with `x-ratelimit-remaining: 0` and `x-ratelimit-reset` = this epoch second.+ RateLimited { reset_epoch: u64 },+ /// GitHub's secondary limit: 403 with `retry-after` seconds.+ SecondaryLimit { retry_after: u64 },+ /// 429, with or without `retry-after`.+ TooMany { retry_after: Option<u64> },+ /// A 5xx status, e.g. 500, 502 or 503.+ Server(u16),+ /// Waits this long, then answers as usual (the fixture, or 404).+ Slow(Duration),+ /// A compare whose base commit is gone (a force push): 404 "No commit found for SHA".+ MissingBase,+}++/// One request the mock saw.+#[derive(Clone, Debug, PartialEq)]+pub struct Hit {+ pub method: String,+ /// The path with its query, e.g. `/repos/o/n/commits?sha=main&per_page=50`.+ pub path: String,+ /// Whether an `Authorization` header was sent at all.+ pub authorized: bool,+ /// Whether the reply was a 304.+ pub not_modified: bool,+}++#[derive(Default)]+struct Inner {+ replies: Mutex<HashMap<String, Value>>,+ faults: Mutex<HashMap<String, Fault>>,+ links: Mutex<HashMap<String, String>>,+ token: Mutex<Option<String>>,+ hits: Mutex<Vec<Hit>>,+}++pub struct MockGithub {+ /// `http://127.0.0.1:<port>`: the API base to give kwant.+ pub base: String,+ pub port: u16,+ inner: Arc<Inner>,+ server: tokio::task::JoinHandle<()>,+}++impl MockGithub {+ /// Starts on the first free port of `ports` (each team member has their own range), else on+ /// any free port.+ pub async fn start(ports: &[u16]) -> MockGithub {+ let mut listener = None;+ for port in ports.iter().copied().chain([0]) {+ if let Ok(l) = tokio::net::TcpListener::bind(("127.0.0.1", port)).await {+ listener = Some(l);+ break;+ }+ }+ let listener = listener.expect("a local port for the mock GitHub");+ let port = listener.local_addr().unwrap().port();+ let inner = Arc::new(Inner::default());+ let app = Router::new().fallback(answer).with_state(inner.clone());+ let server = tokio::spawn(async move {+ let _ = axum::serve(listener, app).await;+ });+ MockGithub { base: format!("http://127.0.0.1:{port}"), port, inner, server }+ }++ /// 200 with `body` for `path` (with a query to match only that query).+ pub fn json(&self, path: &str, body: Value) -> &Self {+ self.inner.replies.lock().unwrap().insert(path.to_string(), body);+ self+ }++ /// Makes `path` fail. [`MockGithub::heal`] takes it back.+ pub fn fault(&self, path: &str, fault: Fault) -> &Self {+ self.inner.faults.lock().unwrap().insert(path.to_string(), fault);+ self+ }++ pub fn heal(&self, path: &str) -> &Self {+ self.inner.faults.lock().unwrap().remove(path);+ self+ }++ /// Adds `Link: <next>; rel="next"` to `path`'s answer. `next` may be on another host: kwant+ /// must never follow it there.+ pub fn link_next(&self, path: &str, next: &str) -> &Self {+ self.inner.links.lock().unwrap().insert(path.to_string(), next.to_string());+ self+ }++ /// Answers 401 to any request without `Authorization: Bearer <token>`.+ pub fn require_token(&self, token: &str) -> &Self {+ *self.inner.token.lock().unwrap() = Some(token.to_string());+ self+ }++ pub fn hits(&self) -> Vec<Hit> {+ self.inner.hits.lock().unwrap().clone()+ }++ /// The hits whose path (without query) is `path`.+ pub fn hits_of(&self, path: &str) -> Vec<Hit> {+ self.hits().into_iter().filter(|h| h.path.split('?').next() == Some(path)).collect()+ }++ pub fn clear_hits(&self) {+ self.inner.hits.lock().unwrap().clear();+ }++ /// Panics if anything but a GET reached the mock.+ pub fn assert_read_only(&self) {+ let writes: Vec<Hit> = self.hits().into_iter().filter(|h| h.method != "GET").collect();+ assert!(writes.is_empty(), "Dev mode only reads GitHub, but the mock got {writes:?}");+ }+}++impl Drop for MockGithub {+ fn drop(&mut self) {+ self.server.abort();+ if !std::thread::panicking() {+ self.assert_read_only();+ }+ }+}++/// A strong ETag for a body, as GitHub sends them.+pub fn etag_of(body: &Value) -> String {+ use std::hash::{Hash, Hasher};+ let mut h = std::collections::hash_map::DefaultHasher::new();+ body.to_string().hash(&mut h);+ format!("\"{:016x}\"", h.finish())+}++async fn answer(State(inner): State<Arc<Inner>>, req: Request) -> Response {+ let method = req.method().clone();+ let headers = req.headers().clone();+ let full = req.uri().path_and_query().map(|p| p.as_str().to_string()).unwrap_or_else(|| req.uri().path().to_string());+ let path = req.uri().path().to_string();+ fn find<T: Clone>(m: &Mutex<HashMap<String, T>>, full: &str, path: &str) -> Option<T> {+ let m = m.lock().unwrap();+ m.get(full).or_else(|| m.get(path)).cloned()+ }+ let mut hit = Hit { method: method.to_string(), path: full.clone(), authorized: headers.contains_key("authorization"), not_modified: false };++ if method != Method::GET {+ inner.hits.lock().unwrap().push(hit);+ return (StatusCode::METHOD_NOT_ALLOWED, axum::Json(json!({"message": "the mock GitHub only answers GET"}))).into_response();+ }+ let token = inner.token.lock().unwrap().clone();+ if let Some(t) = token {+ if bearer(&headers) != Some(t.as_str()) {+ inner.hits.lock().unwrap().push(hit);+ return gh_error(StatusCode::UNAUTHORIZED, "Bad credentials", &[]);+ }+ }+ let fault: Option<Fault> = find(&inner.faults, &full, &path);+ if let Some(Fault::Slow(d)) = &fault {+ tokio::time::sleep(*d).await;+ }+ let reply = match fault {+ Some(Fault::Unauthorized) => Some(gh_error(StatusCode::UNAUTHORIZED, "Bad credentials", &[])),+ Some(Fault::Forbidden) => Some(gh_error(StatusCode::FORBIDDEN, "Resource not accessible by personal access token", &[])),+ Some(Fault::RateLimited { reset_epoch }) => Some(gh_error(+ StatusCode::FORBIDDEN,+ "API rate limit exceeded",+ &[("x-ratelimit-limit", "5000".into()), ("x-ratelimit-remaining", "0".into()), ("x-ratelimit-reset", reset_epoch.to_string())],+ )),+ Some(Fault::SecondaryLimit { retry_after }) => {+ Some(gh_error(StatusCode::FORBIDDEN, "You have exceeded a secondary rate limit", &[("retry-after", retry_after.to_string())]))+ }+ Some(Fault::TooMany { retry_after }) => {+ let h: Vec<(&'static str, String)> = retry_after.map(|s| ("retry-after", s.to_string())).into_iter().collect();+ Some(gh_error(StatusCode::TOO_MANY_REQUESTS, "Too many requests", &h))+ }+ Some(Fault::Server(code)) => Some(gh_error(StatusCode::from_u16(code).unwrap_or(StatusCode::BAD_GATEWAY), "Server Error", &[])),+ Some(Fault::MissingBase) => Some(gh_error(StatusCode::NOT_FOUND, "No commit found for SHA", &[])),+ Some(Fault::Slow(_)) | None => None,+ };+ let reply = reply.unwrap_or_else(|| match find(&inner.replies, &full, &path) {+ None => gh_error(StatusCode::NOT_FOUND, "Not Found", &[]),+ Some(body) => {+ let etag = etag_of(&body);+ if headers.get("if-none-match").and_then(|v| v.to_str().ok()) == Some(etag.as_str()) {+ hit.not_modified = true;+ return_304(&etag)+ } else {+ let mut r = (StatusCode::OK, axum::Json(body)).into_response();+ r.headers_mut().insert("etag", HeaderValue::from_str(&etag).unwrap());+ r+ }+ }+ });+ let mut reply = reply;+ if let Some(next) = find(&inner.links, &full, &path) {+ if let Ok(v) = HeaderValue::from_str(&format!("<{next}>; rel=\"next\"")) {+ reply.headers_mut().insert("link", v);+ }+ }+ inner.hits.lock().unwrap().push(hit);+ reply+}++fn bearer(headers: &HeaderMap) -> Option<&str> {+ let v = headers.get("authorization")?.to_str().ok()?;+ v.strip_prefix("Bearer ").or_else(|| v.strip_prefix("token "))+}++fn return_304(etag: &str) -> Response {+ let mut r = Response::new(Body::empty());+ *r.status_mut() = StatusCode::NOT_MODIFIED;+ r.headers_mut().insert("etag", HeaderValue::from_str(etag).unwrap());+ r+}++fn gh_error(status: StatusCode, message: &str, headers: &[(&'static str, String)]) -> Response {+ let mut r = (status, axum::Json(json!({"message": message, "documentation_url": "https://docs.github.com/rest"}))).into_response();+ for (k, v) in headers {+ r.headers_mut().insert(*k, HeaderValue::from_str(v).unwrap());+ }+ r+}++// ---- Fixtures ---------------------------------------------------------------------------------++/// A GitHub-token-shaped canary (`ghp_` + `CANARY` + 30 chars), unique per call and built at+/// runtime so no scanner finds one in the source.+pub fn canary_token() -> String {+ let tail = uuid::Uuid::new_v4().simple().to_string().to_uppercase();+ ["gh", "p_", "CANARY", &tail[..30]].concat()+}++/// `prefix` + `n` random alphanumerics, for any secret shape (`secret_like(&["sk", "_live_"].concat(), 24)`).+pub fn secret_like(prefix: &str, n: usize) -> String {+ let mut s = prefix.to_string();+ while s.len() < prefix.len() + n {+ s.push_str(&uuid::Uuid::new_v4().simple().to_string());+ }+ s.truncate(prefix.len() + n);+ s+}++pub fn repo(full_name: &str, default_branch: &str) -> Value {+ json!({"full_name": full_name, "default_branch": default_branch, "private": false})+}++pub fn user(login: &str) -> Value {+ json!({"login": login, "type": if login.ends_with("[bot]") { "Bot" } else { "User" }})+}++/// A commit as the list and the single-commit reads return it (`files` only on the latter).+pub fn commit(sha: &str, message: &str, author: (&str, &str), parents: &[&str], date: &str) -> Value {+ let person = json!({"name": author.0, "email": author.1, "date": date});+ json!({+ "sha": sha,+ "html_url": format!("https://github.com/demo-org/demo-app/commit/{sha}"),+ "commit": {"message": message, "author": person, "committer": person},+ "author": null,+ "parents": parents.iter().map(|p| json!({"sha": p})).collect::<Vec<_>>(),+ })+}++pub fn file(name: &str, status: &str, patch: &str) -> Value {+ let adds = patch.lines().filter(|l| l.starts_with('+')).count();+ let dels = patch.lines().filter(|l| l.starts_with('-')).count();+ json!({"filename": name, "status": status, "additions": adds, "deletions": dels, "patch": patch})+}++/// A pull request; `merged` gives `(merge_commit_sha, merged_at)`.+pub fn pull(number: u64, title: &str, head: (&str, &str), base: &str, author: &str, merged: Option<(&str, &str)>) -> Value {+ json!({+ "number": number, "title": title, "body": "", "state": if merged.is_some() { "closed" } else { "open" },+ "draft": false, "html_url": format!("https://github.com/demo-org/demo-app/pull/{number}"),+ "user": user(author),+ "head": {"ref": head.0, "sha": head.1}, "base": {"ref": base, "sha": "0000000000000000000000000000000000000000"},+ "merged_at": merged.map(|m| m.1), "merge_commit_sha": merged.map(|m| m.0),+ "merged_by": merged.map(|_| user("demo-person")), "updated_at": "2026-11-05T03:00:00Z",+ })+}++pub fn check_runs(runs: &[(&str, &str, Option<&str>)]) -> Value {+ let runs: Vec<Value> = runs+ .iter()+ .map(|(name, status, conclusion)| json!({"name": name, "status": status, "conclusion": conclusion, "html_url": "https://github.com/demo-org/demo-app/actions"}))+ .collect();+ json!({"total_count": runs.len(), "check_runs": runs})+}