Skip to content

armgit / kwant

Public Imported from GitHub
0

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.

Dev mode: watch every team's repo (0.7.2) (#359)

Oleksandr Ivanchenko3fca448828b9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 078d970c..63ab18b3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,15 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
## Unreleased
+### Changed
+- **Once 0.7.2 runs, don't go back to 0.7.1:** Dev mode stops making new cards there (nothing is lost; updating
+ again fixes it). (#359)
+
+### Fixed
+- **The Dev desk badge and the "what landed" rollup each keep their own seen time.** Opening the desk clears the
+ new reviews badge, and **Mark seen** starts the rollup over. Before, opening the desk also emptied the rollup, so
+ it almost always said "Nothing landed since you last looked". (#357)
+
## [Mac 0.7.1] - 2026-11-06
### Added
diff --git a/docs/dev-mode.md b/docs/dev-mode.md
index b118b25d..a19356cf 100644
--- a/docs/dev-mode.md
+++ b/docs/dev-mode.md
@@ -1,7 +1,8 @@
# Dev mode
-Dev mode (0.7) points a space at one GitHub repo and branch, found in the space's team folders and
-repo links. kwnt then reads the repo and turns what happens there into cards. It writes to GitHub
+Dev mode (0.7) points a space at the GitHub repos its teams work in: from 0.7.2 every team's repo,
+up to 10 a space (see [Every team's repo](#every-teams-repo-072)), found in the team folders and repo
+links. kwnt then reads each repo and turns what happens there into cards. It writes to GitHub
only when the person presses **Post to GitHub** on a review card (0.7.1, see
[Posting to GitHub](#posting-to-github)); nothing else is ever sent there.
@@ -16,7 +17,7 @@ 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`)
+tables (`dev_mode_spaces`, `dev_repos`, `dev_cards`, `dev_backups`, `dev_model_calls`, `dev_prod_connections`)
are left out of exports, like approval modes.
## Before you turn it on
@@ -76,13 +77,64 @@ reply carries a `check` that says why. A `branch` the repo doesn't have is a 400
- `other_host`: only GitLab, Gitea or other non-GitHub sources, or `local` ones. These are read
from 0.7.2.
- `new_reviews`: review cards ready to read that were made since the desk was last opened (open
- ones only, never landed cards or floor approvals). A space never opened counts 0.
+ ones only, never landed cards or floor approvals), every watched repo's together: one count for
+ the space, with one seen time. A space never opened counts 0.
`POST /api/spaces/:id/dev_mode/seen` marks the desk opened now, so phone and desktop agree. It
sets `reviews_seen_at` only. "Mark seen" (`POST …/dev/landed/seen`) sets `seen_at`, which the
landed rollup counts from, and never clears the badge. Before 0.7.2 both routes shared
`seen_at`, so opening the desk emptied the rollup; a database from then starts with
`reviews_seen_at` copied from `seen_at`, so its badge is unchanged.
+### Every team's repo (0.7.2)
+
+A space watches every team's GitHub repo at once, not just the first. Each watched repo is a row of
+`dev_repos`, keyed `host/owner/name` (lowercased), with its own branch, last seen commit, poll state
+and newest tag. The full contract is in the team's `dev-mode/team-repos/api.md`; in short:
+
+- **Rows follow the teams.** Turning on, a team's repo link changing, a team made, changed or deleted,
+ a GitHub connection added or changed, and a `GET` (at most every 30 s per space) reconcile the rows:
+ a row for each team source a connection reads (`added_by: "team"`), and a team row whose team no
+ longer points at it is dropped (its cards stay). The person can add more by hand (`PUT {repo}`,
+ `added_by: "hand"`) and remove those with `DELETE /api/spaces/:id/dev_mode/repos/:key` (the key
+ URL-encoded as one segment). A team row can't be deleted (409 `team_repo`): change or clear the
+ team's link with `PUT {repo, team}` (`repo: ""` clears it).
+- **At most 10 repos a space.** A team source past the cap shows `too_many` and has no row; a hand repo
+ past it is a 409 `too_many`.
+- **`GET` and the `PUT` reply** have `repos[]`: one entry per repo, in team order then hand rows, with
+ `key`, `repo`, `host`, `team`, `team_id`, `from`, `branch`, `status` (`watching`, `not_connected`,
+ `other_host`, `error`, `too_many`), `poll_error`, `polled_at`, `last_tag` and `added_by`. The
+ top-level `repo`, `branch`, `deploy_hint`, `last_seen_sha`, `polled_at` and `poll_error` are the
+ first watched repo's, kept for one release only (deprecated). Top-level `status` is `watching` when
+ any repo is.
+- **Polling** reads each repo in turn. A repo that fails records its own `poll_error` and the next is
+ still read. A rate limit is the token's, so it backs the whole space off.
+- **Cards** carry `repo` (the key), `repo_name` and `team`. PR #12 in two repos is two cards. The lists
+ take `?repo=<key>` (`/dev/landed`, `/dev/reviews`, and `POST /dev/release_notes` for that repo's
+ notes); an unknown key is an empty list. **Post to GitHub** writes to the card's own repo and host.
+- **Space-wide, unchanged:** the production floor, the command guards, approvals, backups and the 30
+ model calls a day.
+- **Errors** are `{error, code}`: `bad_repo`, `bad_branch`, `no_branch`, `unknown_team`,
+ `backup_too_long` (400); `unknown_repo` (404); `team_repo`, `too_many`, `no_repo`, `off` (409);
+ `github` (502); `internal` (500).
+
+**Upgrading from 0.7.1** rebuilds `dev_cards` once with a `repo` column (the unique key becomes
+`(space_id, repo, kind, ref, head_sha)`) and turns each space's one repo into a `dev_repos` row keyed
+`github.com/owner/name`, with its branch, last seen commit and poll state, so nothing is announced
+again. The first reconcile hands it to the team that points at it, re-keying it and its cards if that
+team's repo is on a GitHub Enterprise host.
+
+**Going back to 0.7.1** after this is safe but limited. 0.7.1 still starts, reads every card and
+setting, and polls its one repo, but it can't make cards: its insert names the old unique key, SQLite
+refuses it, and 0.7.1 logs "could not save a card" and goes on. A trigger
+(`dev_cards_071_keeps_to_its_repo`) keeps it off other repos' cards: 0.7.1 finds review cards by PR
+number across the whole space, so without it its poll would mark other repos' reviews stale and its CI
+recheck would overwrite their facts. Every 0.7.2 write to `dev_cards` bumps a `rev` column; a write
+that doesn't (0.7.1's) and would mark stale, or change the facts of, a card of a repo other than
+`dev_mode_spaces.repo` is skipped. Coming back up to 0.7.2 rebuilds nothing; each repo carries on from
+its own `dev_repos.last_seen_sha` (0.7.1 never writes that table), so what landed meanwhile becomes cards
+once. A repo changed by hand while on 0.7.1 is not carried over (0.7.1 writes it to
+`dev_mode_spaces.repo`); teams' repo links are.
+
`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.
@@ -297,8 +349,15 @@ Run these focused tests:
```sh
cargo test --lib -- server::dev:: prod_floor auth::tests::person_only zombie::github connections::tests::only_mcp
cargo test --test dev_post_test --test dev_github_test
+cargo test --lib -- db::dev_mode::tests
+cargo test --test dev_team_repos_test --test dev_autodetect_test
```
+`tests/dev_team_repos_test.rs` covers 0.7.2's repos: two teams' repos with PR #12 in both (two cards,
+each posted to its own repo, `?repo=` filters), a failing repo next to a working one, the 10-repo cap,
+a migrated row taken over by its team, and the routes' error codes. The 0.7.1 → 0.7.2 migration is
+tested on a 0.7.1-shaped database in `src/db/dev_mode.rs`.
+
The no-tools turns have their own: `cargo test --lib -- no_tools`.
The poller runs against a mock GitHub on a private `127.0.0.1` port. The shared mock is
diff --git a/src/db/dev_mode.rs b/src/db/dev_mode.rs
index 5a972840..d26ee3bc 100644
--- a/src/db/dev_mode.rs
+++ b/src/db/dev_mode.rs
@@ -1,8 +1,9 @@
-//! 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.
+//! Dev mode (docs/dev-mode.md): the repos each space watches (one per team, plus any the person
+//! adds by hand: plan team-repos.md T1), the cards kwant writes about what landed on them and their
+//! 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` and `dev_repos` (the routes refuse agent tokens).
+//! Add-only except for one rebuild of `dev_cards` (T2), so a 0.7.1 build still reads this database.
use super::{Database, DbError};
use chrono::{DateTime, Utc};
@@ -11,6 +12,16 @@ use sqlx::FromRow;
/// Most model calls Dev mode makes per space per day (plan D8).
pub const CALLS_CAP: i64 = 30;
+/// Most repos one space watches (team-repos.md T4).
+pub const MAX_REPOS: usize = 10;
+
+/// Who added a `dev_repos` row: a team's repo link or folder (removed when the team stops
+/// pointing at it), the person (removed only by them), or the 0.7.1 migration (decided at the
+/// first reconcile; read as `hand` until then).
+pub const BY_TEAM: &str = "team";
+pub const BY_HAND: &str = "hand";
+pub const BY_MIGRATION: &str = "migrated";
+
/// Card kinds and statuses, as stored.
pub const LANDED: &str = "landed";
pub const REVIEW: &str = "review";
@@ -44,20 +55,24 @@ const TABLES: &[&str] = &[
seen_at TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
)",
- "CREATE TABLE IF NOT EXISTS dev_cards (
- id TEXT PRIMARY KEY,
+ CARDS_TABLE,
+ // The repos a space watches (T1). `key` is `host/owner/name` lowercased; `team` is the team's id
+ "CREATE TABLE IF NOT EXISTS dev_repos (
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)
+ key TEXT NOT NULL,
+ team TEXT,
+ provider TEXT NOT NULL DEFAULT 'github',
+ repo TEXT NOT NULL,
+ host TEXT,
+ branch TEXT NOT NULL DEFAULT '',
+ deploy_hint TEXT,
+ last_seen_sha TEXT,
+ polled_at TIMESTAMP,
+ poll_error TEXT,
+ added_by TEXT NOT NULL,
+ added_at TIMESTAMP NOT NULL,
+ PRIMARY KEY (space_id, key)
)",
- "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,
@@ -85,7 +100,95 @@ const TABLES: &[&str] = &[
)",
];
-/// A space's Dev mode settings and poll state.
+/// `dev_cards` as 0.7.2 makes it: a card belongs to one repo, so PR #12 in two repos is two cards
+/// (T2). Older databases are rebuilt into this shape once, by [`Database::migrate_dev_mode`].
+const CARDS_TABLE: &str = "CREATE TABLE IF NOT EXISTS dev_cards (
+ id TEXT PRIMARY KEY,
+ space_id TEXT NOT NULL,
+ repo TEXT NOT NULL DEFAULT '',
+ 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,
+ posted TEXT,
+ post_error TEXT,
+ rev INTEGER NOT NULL DEFAULT 0,
+ UNIQUE(space_id, repo, kind, ref, head_sha)
+ )";
+
+/// Downgrade guard (Ada's condition 1 for T2). A 0.7.1 build on this database watches one repo
+/// (`dev_mode_spaces.repo`) and still finds cards by PR number across the whole space: its poll
+/// would mark every other repo's review cards stale (their PRs aren't open in its repo) and its CI
+/// recheck would read other repos' commits on its repo and overwrite their facts. Every 0.7.2
+/// write to `dev_cards` bumps `rev`; a write that leaves `rev` alone comes from 0.7.1, and when it
+/// would mark stale, or rewrite the facts of, a card of another repo than the one 0.7.1 watches,
+/// that row is skipped (`RAISE(IGNORE)`: no error, the rest of the statement goes on). 0.7.1 keeps
+/// working for its own repo. Its card inserts fail anyway (see `migrate_team_repos`).
+const CARDS_071_GUARD: &str = "CREATE TRIGGER IF NOT EXISTS dev_cards_071_keeps_to_its_repo BEFORE UPDATE ON dev_cards
+ WHEN NEW.rev = OLD.rev
+ AND (NEW.facts IS NOT OLD.facts OR (NEW.status = 'stale' AND OLD.status != 'stale'))
+ AND OLD.repo != COALESCE(
+ (SELECT lower('github.com/' || s.repo) FROM dev_mode_spaces s WHERE s.space_id = OLD.space_id AND trim(s.repo) != ''), '')
+ BEGIN SELECT RAISE(IGNORE); END";
+
+const CARD_INDEXES: &[&str] = &[
+ "CREATE INDEX IF NOT EXISTS idx_dev_cards_space ON dev_cards(space_id, kind, created_at)",
+ "CREATE INDEX IF NOT EXISTS idx_dev_cards_repo ON dev_cards(space_id, repo, kind, created_at)",
+];
+
+/// One watched repo of a space (T1) and its poll state.
+#[derive(Debug, Clone, FromRow, PartialEq)]
+pub struct DevRepoRow {
+ pub space_id: String,
+ pub key: String,
+ /// The id of the team it came from (`team` rows), or of the team that points at a hand row.
+ pub team: Option<String>,
+ pub provider: String,
+ /// `owner/name`.
+ pub repo: String,
+ pub host: Option<String>,
+ pub branch: String,
+ pub deploy_hint: Option<String>,
+ pub last_seen_sha: Option<String>,
+ pub polled_at: Option<DateTime<Utc>>,
+ pub poll_error: Option<String>,
+ pub added_by: String,
+ pub added_at: DateTime<Utc>,
+}
+
+impl DevRepoRow {
+ /// `team` or `hand` (a migrated row reads as `hand` until reconcile decides).
+ pub fn added_by_shown(&self) -> &'static str {
+ if self.added_by == BY_TEAM {
+ BY_TEAM
+ } else {
+ BY_HAND
+ }
+ }
+}
+
+/// What adding a repo row did.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum RepoAdd {
+ Added,
+ /// A row with that key was there already (its team label may have been updated).
+ Kept,
+ /// The space already watches [`MAX_REPOS`].
+ TooMany,
+}
+
+/// The repo key of `owner/name` on `host`: `host/owner/name` lowercased.
+pub fn repo_key(host: &str, repo: &str) -> String {
+ format!("{host}/{repo}").to_lowercase()
+}
+
+/// A space's Dev mode settings. Since 0.7.2 its `repo`, `branch` and poll columns are 0.7.1's,
+/// kept for a downgrade; the watched repos are [`DevRepoRow`]s. `branch` is still written when
+/// Dev mode turns on with no repo (a team folder's branch, for the production floor).
#[derive(Debug, Clone, FromRow, PartialEq)]
pub struct DevModeRow {
pub space_id: String,
@@ -125,6 +228,9 @@ pub struct DevCardRow {
pub card: Option<String>,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
+ /// The repo key the card is about (T2); `""` for a card a 0.7.1 space made with no repo.
+ #[sqlx(default)]
+ pub repo: String,
/// Review cards: `{at, login, url, comments}` once posted to GitHub (post-to-github.md P1).
/// A column of its own, so a card regenerated after CI keeps it.
#[sqlx(default)]
@@ -153,7 +259,7 @@ const MIGRATE_REVIEWS_SEEN: [&str; 2] = [
"UPDATE dev_mode_spaces SET reviews_seen_at = seen_at WHERE reviews_seen_at IS NULL",
];
-const CARD_COLS: &str = "id, space_id, kind, ref, head_sha, status, facts, card, created_at, updated_at, posted, post_error";
+const CARD_COLS: &str = "id, space_id, repo, kind, ref, head_sha, status, facts, card, created_at, updated_at, posted, post_error";
impl Database {
pub(super) async fn migrate_dev_mode(&self) -> Result<(), DbError> {
@@ -163,9 +269,7 @@ impl Database {
// Posting a review to GitHub came in 0.7.1; older builds name their columns, so they
// still read this table
for column in ["posted", "post_error"] {
- let has: Option<(String,)> =
- sqlx::query_as("SELECT name FROM pragma_table_info('dev_cards') WHERE name = ?").bind(column).fetch_optional(&self.pool).await?;
- if has.is_none() {
+ if !self.dev_cards_has(column).await? {
sqlx::query(&format!("ALTER TABLE dev_cards ADD COLUMN {column} TEXT")).execute(&self.pool).await?;
}
}
@@ -181,6 +285,66 @@ impl Database {
sqlx::query(MIGRATE_REVIEWS_SEEN[1]).execute(&mut *tx).await?;
tx.commit().await?;
}
+ if !self.dev_cards_has("repo").await? {
+ self.migrate_team_repos().await?;
+ }
+ // Built before the guard came in (0.7.2 development databases only)
+ if !self.dev_cards_has("rev").await? {
+ sqlx::query("ALTER TABLE dev_cards ADD COLUMN rev INTEGER NOT NULL DEFAULT 0").execute(&self.pool).await?;
+ }
+ sqlx::query(CARDS_071_GUARD).execute(&self.pool).await?;
+ for sql in CARD_INDEXES {
+ sqlx::query(sql).execute(&self.pool).await?;
+ }
+ Ok(())
+ }
+
+ async fn dev_cards_has(&self, column: &str) -> Result<bool, DbError> {
+ let has: Option<(String,)> =
+ sqlx::query_as("SELECT name FROM pragma_table_info('dev_cards') WHERE name = ?").bind(column).fetch_optional(&self.pool).await?;
+ Ok(has.is_some())
+ }
+
+ /// 0.7.1 → 0.7.2 (team-repos.md T2), once, in one transaction: each space's one repo becomes
+ /// a `dev_repos` row with its branch, last seen commit and poll state (so nothing is announced
+ /// again), and `dev_cards` is rebuilt with a `repo` column in its unique key. A card's repo is
+ /// the one its facts name, else its space's. 0.7.1 kept `owner/name` without a host, so the
+ /// key is github.com's; reconcile re-keys it if a team's source is on a GitHub Enterprise host.
+ ///
+ /// Going back to 0.7.1 afterwards is safe but limited, by design: 0.7.1 still reads every card
+ /// and repo setting, but its card insert names the old unique key (`ON CONFLICT(space_id, kind,
+ /// ref, head_sha)`), which this table no longer has, so SQLite refuses it; 0.7.1 logs "could not
+ /// save a card" and its poll goes on. It never sees `dev_repos`, so coming back up to 0.7.2
+ /// picks each repo up where 0.7.2 left it (`dev_repos.last_seen_sha`) and makes the cards for
+ /// what landed in between, once; this function doesn't run again (`dev_cards` has `repo`).
+ /// [`CARDS_071_GUARD`] keeps 0.7.1 off other repos' cards.
+ async fn migrate_team_repos(&self) -> Result<(), DbError> {
+ let mut tx = self.pool.begin().await?;
+ sqlx::query(
+ "INSERT OR IGNORE INTO dev_repos (space_id, key, team, provider, repo, host, branch, deploy_hint, last_seen_sha, polled_at, poll_error, added_by, added_at)
+ SELECT space_id, lower('github.com/' || repo), NULL, provider, repo, 'github.com', branch, deploy_hint, last_seen_sha, polled_at, poll_error, ?1, updated_at
+ FROM dev_mode_spaces WHERE trim(repo) != ''",
+ )
+ .bind(BY_MIGRATION)
+ .execute(&mut *tx)
+ .await?;
+ sqlx::query(&CARDS_TABLE.replace("IF NOT EXISTS dev_cards", "dev_cards_v2")).execute(&mut *tx).await?;
+ sqlx::query(
+ "INSERT INTO dev_cards_v2 (id, space_id, repo, kind, ref, head_sha, status, facts, card, created_at, updated_at, posted, post_error)
+ SELECT c.id, c.space_id,
+ COALESCE(
+ (SELECT lower('github.com/' || r) FROM (SELECT CASE WHEN json_valid(c.facts) THEN json_extract(c.facts, '$.repo') END AS r)
+ WHERE typeof(r) = 'text' AND instr(r, '/') > 0),
+ (SELECT lower('github.com/' || s.repo) FROM dev_mode_spaces s WHERE s.space_id = c.space_id AND trim(s.repo) != ''),
+ ''),
+ c.kind, c.ref, c.head_sha, c.status, c.facts, c.card, c.created_at, c.updated_at, c.posted, c.post_error
+ FROM dev_cards c",
+ )
+ .execute(&mut *tx)
+ .await?;
+ sqlx::query("DROP TABLE dev_cards").execute(&mut *tx).await?;
+ sqlx::query("ALTER TABLE dev_cards_v2 RENAME TO dev_cards").execute(&mut *tx).await?;
+ tx.commit().await?;
Ok(())
}
@@ -203,40 +367,25 @@ impl Database {
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> {
+ /// Saves the person's settings: the switch and the backup command. A new row gets no 0.7.1
+ /// repo; `branch` is what the production floor treats as the main branch while the space
+ /// watches no repo (a team folder's), and an existing row's 0.7.1 columns stay as they were.
+ pub async fn set_dev_mode(&self, space_id: &str, on: bool, branch: 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",
+ "INSERT INTO dev_mode_spaces (space_id, on_, repo, branch, backup_command, updated_at) VALUES (?1, ?2, '', COALESCE(?3, ''), ?4, ?5)
+ ON CONFLICT(space_id) DO UPDATE SET on_ = excluded.on_, backup_command = excluded.backup_command, updated_at = excluded.updated_at,
+ branch = CASE WHEN ?3 IS NOT NULL AND dev_mode_spaces.repo = '' THEN ?3 ELSE dev_mode_spaces.branch END",
)
.bind(space_id)
.bind(on)
- .bind(repo)
.bind(branch)
- .bind(deploy_hint)
.bind(backup_command)
- .bind(now)
+ .bind(Utc::now())
.execute(&self.pool)
.await;
self.refresh_dev_on().await;
@@ -244,28 +393,153 @@ impl Database {
Ok(self.dev_mode(space_id).await?.expect("just written"))
}
- /// Binds a repo to a space that is on with none (plan any-git.md S3, QA B1), and only then: a
- /// space turned off or given a repo meanwhile is left as the person set it. True when bound.
- pub async fn bind_dev_repo(&self, space_id: &str, repo: &str, branch: &str, deploy_hint: Option<&str>) -> Result<bool, DbError> {
+ /// [`Self::set_dev_mode`] plus one hand-added repo on github.com (the 0.7.1 shape, for tests
+ /// and callers that name one repo). An empty `repo` adds none.
+ 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 row = self.set_dev_mode(space_id, on, Some(branch), backup_command).await?;
+ if !repo.trim().is_empty() {
+ let key = repo_key("github.com", repo);
+ self.add_dev_repo(space_id, &key, None, repo, Some("github.com"), branch, deploy_hint, BY_HAND).await?;
+ self.set_dev_repo_branch(space_id, &key, branch).await?;
+ }
+ Ok(row)
+ }
+
+ /// A space's watched repos, oldest first.
+ pub async fn dev_repos(&self, space_id: &str) -> Result<Vec<DevRepoRow>, DbError> {
+ Ok(sqlx::query_as("SELECT * FROM dev_repos WHERE space_id = ? ORDER BY added_at, key").bind(space_id).fetch_all(&self.pool).await?)
+ }
+
+ pub async fn dev_repo(&self, space_id: &str, key: &str) -> Result<Option<DevRepoRow>, DbError> {
+ Ok(sqlx::query_as("SELECT * FROM dev_repos WHERE space_id = ? AND key = ?").bind(space_id).bind(key).fetch_optional(&self.pool).await?)
+ }
+
+ /// Adds a watched repo, unless the space watches [`MAX_REPOS`] already (T4). A row with the
+ /// same key is kept as it is (its poll state too), except that a team source names its team
+ /// on it, and a migrated row a team points at becomes that team's.
+ #[allow(clippy::too_many_arguments)]
+ pub async fn add_dev_repo(
+ &self,
+ space_id: &str,
+ key: &str,
+ team: Option<&str>,
+ repo: &str,
+ host: Option<&str>,
+ branch: &str,
+ deploy_hint: Option<&str>,
+ added_by: &str,
+ ) -> Result<RepoAdd, DbError> {
let _writes = self.dev_on.writes.lock().await;
- let done = sqlx::query(
- "UPDATE dev_mode_spaces SET repo = ?2, branch = ?3, deploy_hint = ?4, last_seen_sha = NULL, polled_at = NULL,
- poll_error = NULL, updated_at = ?5
- WHERE space_id = ?1 AND on_ = 1 AND repo = ''",
+ // Reads, then writes: holds the write lock from BEGIN, or a poller's write in between
+ // fails the insert at once with "database is locked"
+ let mut tx = self.begin_write().await?;
+ let have: Option<(String,)> = sqlx::query_as("SELECT added_by FROM dev_repos WHERE space_id = ? AND key = ?").bind(space_id).bind(key).fetch_optional(&mut *tx).await?;
+ if let Some((by,)) = have {
+ if team.is_some() {
+ let by = if by == BY_MIGRATION && added_by == BY_TEAM { BY_TEAM.to_string() } else { by };
+ sqlx::query("UPDATE dev_repos SET team = ?3, added_by = ?4 WHERE space_id = ?1 AND key = ?2")
+ .bind(space_id)
+ .bind(key)
+ .bind(team)
+ .bind(by)
+ .execute(&mut *tx)
+ .await?;
+ }
+ tx.commit().await?;
+ return Ok(RepoAdd::Kept);
+ }
+ let count: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM dev_repos WHERE space_id = ?").bind(space_id).fetch_one(&mut *tx).await?;
+ if count >= MAX_REPOS as i64 {
+ tx.rollback().await?;
+ return Ok(RepoAdd::TooMany);
+ }
+ sqlx::query(
+ "INSERT INTO dev_repos (space_id, key, team, repo, host, branch, deploy_hint, added_by, added_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
)
.bind(space_id)
+ .bind(key)
+ .bind(team)
.bind(repo)
+ .bind(host)
.bind(branch)
.bind(deploy_hint)
+ .bind(added_by)
.bind(Utc::now())
+ .execute(&mut *tx)
+ .await?;
+ tx.commit().await?;
+ Ok(RepoAdd::Added)
+ }
+
+ /// Sets a row's branch; a new branch starts its watch over (last seen commit and poll state
+ /// cleared), the same one keeps them. False: no such row.
+ pub async fn set_dev_repo_branch(&self, space_id: &str, key: &str, branch: &str) -> Result<bool, DbError> {
+ let done = sqlx::query(
+ "UPDATE dev_repos SET
+ last_seen_sha = CASE WHEN branch = ?3 THEN last_seen_sha ELSE NULL END,
+ polled_at = CASE WHEN branch = ?3 THEN polled_at ELSE NULL END,
+ poll_error = CASE WHEN branch = ?3 THEN poll_error ELSE NULL END,
+ branch = ?3
+ WHERE space_id = ?1 AND key = ?2",
+ )
+ .bind(space_id)
+ .bind(key)
+ .bind(branch)
.execute(&self.pool)
.await?;
Ok(done.rows_affected() == 1)
}
- 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")
+ /// Sets a row's deploy hint (from its root files, when GitHub was read).
+ pub async fn set_dev_repo_hint(&self, space_id: &str, key: &str, hint: Option<&str>) -> Result<(), DbError> {
+ sqlx::query("UPDATE dev_repos SET deploy_hint = ?3 WHERE space_id = ?1 AND key = ?2").bind(space_id).bind(key).bind(hint).execute(&self.pool).await?;
+ Ok(())
+ }
+
+ /// Sets who a row belongs to: `team` (with its team) or `hand`.
+ pub async fn set_dev_repo_owner(&self, space_id: &str, key: &str, added_by: &str, team: Option<&str>) -> Result<(), DbError> {
+ sqlx::query("UPDATE dev_repos SET added_by = ?3, team = ?4 WHERE space_id = ?1 AND key = ?2").bind(space_id).bind(key).bind(added_by).bind(team).execute(&self.pool).await?;
+ Ok(())
+ }
+
+ /// Removes a watched repo. Its cards stay, with their repo. False: no such row.
+ pub async fn delete_dev_repo(&self, space_id: &str, key: &str) -> Result<bool, DbError> {
+ let done = sqlx::query("DELETE FROM dev_repos WHERE space_id = ? AND key = ?").bind(space_id).bind(key).execute(&self.pool).await?;
+ Ok(done.rows_affected() == 1)
+ }
+
+ /// Moves a row and its cards to another key (a migrated github.com key whose repo is on a
+ /// GitHub Enterprise host). False when the new key is taken or the old one is gone.
+ pub async fn rekey_dev_repo(&self, space_id: &str, from: &str, to: &str, host: &str) -> Result<bool, DbError> {
+ let mut tx = self.begin_write().await?;
+ let taken: Option<(String,)> = sqlx::query_as("SELECT key FROM dev_repos WHERE space_id = ? AND key = ?").bind(space_id).bind(to).fetch_optional(&mut *tx).await?;
+ if taken.is_some() {
+ tx.rollback().await?;
+ return Ok(false);
+ }
+ let done = sqlx::query("UPDATE dev_repos SET key = ?3, host = ?4 WHERE space_id = ?1 AND key = ?2").bind(space_id).bind(from).bind(to).bind(host).execute(&mut *tx).await?;
+ if done.rows_affected() != 1 {
+ return Ok(false);
+ }
+ sqlx::query("UPDATE OR IGNORE dev_cards SET repo = ?3, rev = rev + 1 WHERE space_id = ?1 AND repo = ?2").bind(space_id).bind(from).bind(to).execute(&mut *tx).await?;
+ tx.commit().await?;
+ Ok(true)
+ }
+
+ /// Records one poll of one repo: the newest merge it turned into a card (`None` keeps the
+ /// one before), and its error (`None`: it worked).
+ pub async fn dev_repo_polled(&self, space_id: &str, key: &str, last_seen_sha: Option<&str>, error: Option<&str>) -> Result<(), DbError> {
+ sqlx::query("UPDATE dev_repos SET last_seen_sha = COALESCE(?3, last_seen_sha), polled_at = ?4, poll_error = ?5 WHERE space_id = ?1 AND key = ?2")
.bind(space_id)
+ .bind(key)
.bind(last_seen_sha)
.bind(Utc::now())
.bind(error)
@@ -274,6 +548,12 @@ impl Database {
Ok(())
}
+ /// Sets a team's repo link (`PUT dev_mode {repo, team}`, T8). The caller strips userinfo.
+ pub async fn set_team_repo_url(&self, team_id: &str, repo_url: Option<&str>) -> Result<bool, DbError> {
+ let done = sqlx::query("UPDATE teams SET repo_url = ? WHERE id = ?").bind(repo_url).bind(team_id).execute(&self.pool).await?;
+ Ok(done.rows_affected() == 1)
+ }
+
/// "Mark seen" on what landed: the rollup starts over from `at`. The badge is left alone.
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?;
@@ -296,7 +576,7 @@ impl Database {
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"] {
+ for t in ["dev_mode_spaces", "dev_repos", "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?;
@@ -327,16 +607,23 @@ impl Database {
Ok(())
}
- /// Adds a pending card. `None` when one with the same space, kind, ref and head already exists.
+ /// Adds a pending card with no repo (release notes before 0.7.2, tests). See [`Self::insert_dev_card_in`].
pub async fn insert_dev_card(&self, space_id: &str, kind: &str, ref_: &str, head_sha: &str, facts: &str) -> Result<Option<DevCardRow>, DbError> {
+ self.insert_dev_card_in(space_id, "", kind, ref_, head_sha, facts).await
+ }
+
+ /// Adds a pending card about repo `repo` (its key). `None` when one with the same space,
+ /// repo, kind, ref and head already exists.
+ pub async fn insert_dev_card_in(&self, space_id: &str, repo: &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",
+ "INSERT INTO dev_cards (id, space_id, repo, kind, ref, head_sha, status, facts, created_at, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?, 'pending', ?, ?, ?) ON CONFLICT(space_id, repo, kind, ref, head_sha) DO NOTHING",
)
.bind(&id)
.bind(space_id)
+ .bind(repo)
.bind(kind)
.bind(ref_)
.bind(head_sha)
@@ -359,7 +646,7 @@ impl Database {
/// card stays as it is: a review that finishes after its PR merged (or moved on) must not come
/// back to life. `None` when nothing was written (no such card, or it is stale).
pub async fn set_dev_card(&self, id: &str, status: &str, card: Option<&str>) -> Result<Option<DevCardRow>, DbError> {
- let done = sqlx::query("UPDATE dev_cards SET status = ?2, card = COALESCE(?3, card), updated_at = ?4 WHERE id = ?1 AND status != 'stale'")
+ let done = sqlx::query("UPDATE dev_cards SET status = ?2, card = COALESCE(?3, card), updated_at = ?4, rev = rev + 1 WHERE id = ?1 AND status != 'stale'")
.bind(id)
.bind(status)
.bind(card)
@@ -375,7 +662,7 @@ impl Database {
/// 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")
+ sqlx::query("UPDATE dev_cards SET facts = ?2, status = 'pending', updated_at = ?3, rev = rev + 1 WHERE id = ?1")
.bind(id)
.bind(facts)
.bind(Utc::now())
@@ -387,7 +674,7 @@ impl Database {
/// 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")
+ let done = sqlx::query("UPDATE dev_cards SET card = ?3, updated_at = ?4, rev = rev + 1 WHERE id = ?1 AND card IS ?2")
.bind(id)
.bind(expect)
.bind(card)
@@ -400,7 +687,7 @@ impl Database {
/// Records a review as posted, only while none is (P6): false when another post got there
/// first. Clears `post_error`.
pub async fn set_dev_card_posted(&self, id: &str, posted: &str) -> Result<bool, DbError> {
- let done = sqlx::query("UPDATE dev_cards SET posted = ?2, post_error = NULL, updated_at = ?3 WHERE id = ?1 AND posted IS NULL")
+ let done = sqlx::query("UPDATE dev_cards SET posted = ?2, post_error = NULL, updated_at = ?3, rev = rev + 1 WHERE id = ?1 AND posted IS NULL")
.bind(id)
.bind(posted)
.bind(Utc::now())
@@ -411,7 +698,7 @@ impl Database {
/// Records why a post didn't go through (`None` clears it). A posted card keeps no error.
pub async fn set_dev_card_post_error(&self, id: &str, error: Option<&str>) -> Result<(), DbError> {
- sqlx::query("UPDATE dev_cards SET post_error = ?2, updated_at = ?3 WHERE id = ?1 AND posted IS NULL")
+ sqlx::query("UPDATE dev_cards SET post_error = ?2, updated_at = ?3, rev = rev + 1 WHERE id = ?1 AND posted IS NULL")
.bind(id)
.bind(error)
.bind(Utc::now())
@@ -420,21 +707,27 @@ impl Database {
Ok(())
}
- /// A space's cards of one kind, newest first, created before `before` when given.
+ /// A space's cards of one kind, every repo's, 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> {
+ self.dev_cards_in(space_id, None, kind, before, limit).await
+ }
+
+ /// [`Self::dev_cards`] of one repo (its key) when `repo` is given.
+ pub async fn dev_cards_in(&self, space_id: &str, repo: Option<&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)
+ "SELECT {CARD_COLS} FROM dev_cards WHERE space_id = ?1 AND kind = ?2 AND (?3 IS NULL OR created_at < ?3) AND (?5 IS NULL OR repo = ?5)
ORDER BY created_at DESC, id DESC LIMIT ?4"
))
.bind(space_id)
.bind(kind)
.bind(before)
.bind(limit)
+ .bind(repo)
.fetch_all(&self.pool)
.await?)
}
- /// Cards of one kind and ref (every head a PR had), newest first.
+ /// Cards of one kind and ref (every head a PR had) in any repo, 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)
@@ -444,21 +737,44 @@ impl Database {
.await?)
}
+ /// Cards of one repo, kind and ref, newest first: PR #12 of one repo isn't another's.
+ pub async fn dev_cards_of_ref_in(&self, space_id: &str, repo: &str, kind: &str, ref_: &str) -> Result<Vec<DevCardRow>, DbError> {
+ Ok(sqlx::query_as(&format!("SELECT {CARD_COLS} FROM dev_cards WHERE space_id = ? AND repo = ? AND kind = ? AND ref = ? ORDER BY created_at DESC, id DESC"))
+ .bind(space_id)
+ .bind(repo)
+ .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.
+ /// Marks every review card of a PR (in any repo) whose head isn't `keep_head` stale; returns
+ /// their ids. The poller uses [`Self::stale_dev_reviews_in`].
pub async fn stale_dev_reviews(&self, space_id: &str, ref_: &str, keep_head: Option<&str>) -> Result<Vec<String>, DbError> {
+ self.stale_reviews(space_id, None, ref_, keep_head).await
+ }
+
+ /// Marks every review card of one repo's PR whose head isn't `keep_head` stale.
+ pub async fn stale_dev_reviews_in(&self, space_id: &str, repo: &str, ref_: &str, keep_head: Option<&str>) -> Result<Vec<String>, DbError> {
+ self.stale_reviews(space_id, Some(repo), ref_, keep_head).await
+ }
+
+ async fn stale_reviews(&self, space_id: &str, repo: Option<&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",
+ "UPDATE dev_cards SET status = 'stale', updated_at = ?4, rev = rev + 1
+ WHERE space_id = ?1 AND kind = 'review' AND ref = ?2 AND status != 'stale' AND (?3 IS NULL OR head_sha != ?3)
+ AND (?5 IS NULL OR repo = ?5) RETURNING id",
)
.bind(space_id)
.bind(ref_)
.bind(keep_head)
.bind(Utc::now())
+ .bind(repo)
.fetch_all(&self.pool)
.await?;
Ok(rows.into_iter().map(|r| r.0).collect())
@@ -526,3 +842,363 @@ impl Database {
Ok((last, ok))
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const SPACE: &str = "space_demo";
+
+ async fn db() -> (Database, tempfile::TempDir) {
+ let tmp = tempfile::tempdir().unwrap();
+ (Database::init(tmp.path()).await.unwrap(), tmp)
+ }
+
+ /// Puts the database back in 0.7.1's shape: `dev_cards` with the old unique key and no `repo`,
+ /// no `dev_repos`, no `dev_mode_spaces.reviews_seen_at` (#357), and one space watching
+ /// `Demo-Org/App` on `main` whose desk was last seen at 09:00.
+ async fn as_071(db: &Database) {
+ for sql in [
+ "ALTER TABLE dev_mode_spaces DROP COLUMN reviews_seen_at",
+ "DROP TABLE dev_repos",
+ "DROP TABLE dev_cards",
+ "CREATE TABLE 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,
+ posted TEXT, post_error TEXT,
+ UNIQUE(space_id, kind, ref, head_sha))",
+ "INSERT INTO dev_mode_spaces (space_id, on_, repo, branch, deploy_hint, last_seen_sha, polled_at, poll_error, seen_at, updated_at)
+ VALUES ('space_demo', 1, 'Demo-Org/App', 'main', 'fly', 'aaaa', '2026-11-06T10:00:00Z', NULL, '2026-11-06T09:00:00Z', '2026-11-05T10:00:00Z')",
+ "INSERT INTO dev_mode_spaces (space_id, on_, repo, branch, updated_at) VALUES ('space_empty', 0, '', 'main', '2026-11-05T10:00:00Z')",
+ "INSERT INTO dev_cards (id, space_id, kind, ref, head_sha, status, facts, card, posted)
+ VALUES ('dvc_landed', 'space_demo', 'landed', 'aaaa', 'aaaa', 'ready', '{\"repo\":\"Demo-Org/App\",\"sha\":\"aaaa\"}', '{\"headline\":\"x\"}', NULL)",
+ "INSERT INTO dev_cards (id, space_id, kind, ref, head_sha, status, facts, card, posted)
+ VALUES ('dvc_review', 'space_demo', 'review', 'pr:12', 'bbbb', 'ready', '{\"repo\":\"demo-org/app\",\"pr\":12}', NULL, '{\"url\":\"u\"}')",
+ "INSERT INTO dev_cards (id, space_id, kind, ref, head_sha, status, facts) VALUES ('dvc_notes', 'space_demo', 'release_notes', 'since:', 'x', 'ready', 'not json')",
+ "INSERT INTO dev_cards (id, space_id, kind, ref, head_sha, status, facts) VALUES ('dvc_orphan', 'space_gone', 'landed', 'cccc', 'cccc', 'ready', '{}')",
+ ] {
+ sqlx::query(sql).execute(&db.pool).await.unwrap();
+ }
+ }
+
+ #[tokio::test]
+ async fn a_071_database_migrates_once_and_nothing_is_announced_again() {
+ let (db, _tmp) = db().await;
+ as_071(&db).await;
+ db.migrate_dev_mode().await.unwrap();
+
+ // The space's one repo is a row with its poll state, keyed on github.com
+ let rows = db.dev_repos(SPACE).await.unwrap();
+ assert_eq!(rows.len(), 1);
+ let r = &rows[0];
+ assert_eq!((r.key.as_str(), r.repo.as_str(), r.host.as_deref(), r.branch.as_str()), ("github.com/demo-org/app", "Demo-Org/App", Some("github.com"), "main"));
+ assert_eq!((r.last_seen_sha.as_deref(), r.deploy_hint.as_deref(), r.added_by.as_str(), r.team.as_deref()), (Some("aaaa"), Some("fly"), BY_MIGRATION, None));
+ assert_eq!(r.added_by_shown(), BY_HAND, "a migrated row reads as hand until reconcile");
+ assert!(r.polled_at.is_some());
+ // A space with no repo gets no row; its settings stay
+ assert!(db.dev_repos("space_empty").await.unwrap().is_empty());
+ assert_eq!(db.dev_mode("space_empty").await.unwrap().unwrap().branch, "main");
+
+ // Every card kept, with its repo: from its facts, else its space's, else none
+ let repo_of = |id: &'static str| {
+ let db = &db;
+ async move { db.dev_card(id).await.unwrap().unwrap().repo }
+ };
+ assert_eq!(repo_of("dvc_landed").await, "github.com/demo-org/app");
+ assert_eq!(repo_of("dvc_review").await, "github.com/demo-org/app");
+ assert_eq!(repo_of("dvc_notes").await, "github.com/demo-org/app", "facts that aren't JSON take the space's repo");
+ assert_eq!(repo_of("dvc_orphan").await, "");
+ let review = db.dev_card("dvc_review").await.unwrap().unwrap();
+ assert_eq!((review.status.as_str(), review.posted.as_deref()), ("ready", Some("{\"url\":\"u\"}")), "status and posted survive");
+
+ // Nothing is announced again: the same card can't be inserted twice
+ assert!(db.insert_dev_card_in(SPACE, "github.com/demo-org/app", LANDED, "aaaa", "aaaa", "{}").await.unwrap().is_none());
+ assert!(db.insert_dev_card_in(SPACE, "github.com/demo-org/app", REVIEW, "pr:12", "bbbb", "{}").await.unwrap().is_none());
+
+ // #357's column came first: the badge keeps 0.7.1's seen time
+ let nine: DateTime<Utc> = "2026-11-06T09:00:00Z".parse().unwrap();
+ let mode = db.dev_mode(SPACE).await.unwrap().unwrap();
+ assert_eq!((mode.seen_at, mode.reviews_seen_at), (Some(nine), Some(nine)), "backfilled from seen_at");
+ // A Mark seen after the migration is never copied into the badge by a later start
+ let later: DateTime<Utc> = "2026-11-06T11:00:00Z".parse().unwrap();
+ db.dev_mode_seen(SPACE, later).await.unwrap();
+
+ // Idempotent: a second start changes nothing
+ db.migrate_dev_mode().await.unwrap();
+ let mode = db.dev_mode(SPACE).await.unwrap().unwrap();
+ assert_eq!((mode.seen_at, mode.reviews_seen_at), (Some(later), Some(nine)));
+ assert_eq!(db.dev_repos(SPACE).await.unwrap(), rows);
+ let n: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM dev_cards").fetch_one(&db.pool).await.unwrap();
+ assert_eq!(n, 4);
+ let tables: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM sqlite_master WHERE name = 'dev_cards_v2'").fetch_one(&db.pool).await.unwrap();
+ assert_eq!(tables, 0);
+ }
+
+ /// 0.7.1's own statements, copied from dbdff6b (src/db/dev_mode.rs), as it runs them.
+ const V071_CARD_COLS: &str = "id, space_id, kind, ref, head_sha, status, facts, card, created_at, updated_at, posted, post_error";
+ const V071_INSERT: &str = "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";
+ const V071_STALE: &str = "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";
+ const V071_FACTS: &str = "UPDATE dev_cards SET facts = ?2, status = 'pending', updated_at = ?3 WHERE id = ?1";
+ const V071_SET: &str = "UPDATE dev_cards SET status = ?2, card = COALESCE(?3, card), updated_at = ?4 WHERE id = ?1 AND status != 'stale'";
+ const V071_POLLED: &str = "UPDATE dev_mode_spaces SET last_seen_sha = COALESCE(?2, last_seen_sha), polled_at = ?3, poll_error = ?4 WHERE space_id = ?1";
+ /// 0.7.1's one seen route (desk opened and Mark seen alike).
+ const V071_SEEN: &str = "UPDATE dev_mode_spaces SET seen_at = ?2 WHERE space_id = ?1";
+
+ async fn v071_stale(db: &Database, ref_: &str, keep: Option<&str>) -> Vec<String> {
+ let rows: Vec<(String,)> =
+ sqlx::query_as(V071_STALE).bind(SPACE).bind(ref_).bind(keep).bind(Utc::now()).fetch_all(&db.pool).await.unwrap();
+ rows.into_iter().map(|r| r.0).collect()
+ }
+
+ async fn v071_facts(db: &Database, id: &str, facts: &str) {
+ sqlx::query(V071_FACTS).bind(id).bind(facts).bind(Utc::now()).execute(&db.pool).await.unwrap();
+ }
+
+ #[tokio::test]
+ async fn a_071_build_on_a_migrated_database_only_stops_making_cards_and_coming_back_catches_up() {
+ let (db, _tmp) = db().await;
+ as_071(&db).await;
+ db.migrate_dev_mode().await.unwrap();
+ // 0.7.2 then watched a second repo, with its own PR #12 and a landed card
+ let site = "github.com/demo-org/site";
+ let site_review = db.insert_dev_card_in(SPACE, site, REVIEW, "pr:12", "ssss", "{\"repo\":\"demo-org/site\"}").await.unwrap().unwrap();
+ db.set_dev_card(&site_review.id, READY, Some("{}")).await.unwrap().unwrap();
+ let site_landed = db.insert_dev_card_in(SPACE, site, LANDED, "s111", "s111", "{\"ci\":\"pending\"}").await.unwrap().unwrap();
+ db.set_dev_card(&site_landed.id, READY, Some("{}")).await.unwrap().unwrap();
+ let before: Vec<(String, String, String, String)> =
+ sqlx::query_as("SELECT id, repo, status, facts FROM dev_cards ORDER BY id").fetch_all(&db.pool).await.unwrap();
+
+ // --- Downgrade: 0.7.1 starts. Its migration is a no-op on this shape
+ for sql in [
+ "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)",
+ ] {
+ sqlx::query(sql).execute(&db.pool).await.unwrap();
+ }
+ // It reads every card, every repo's
+ let read = sqlx::query(&format!("SELECT {V071_CARD_COLS} FROM dev_cards WHERE space_id = ?")).bind(SPACE).fetch_all(&db.pool).await.unwrap();
+ assert_eq!(read.len(), 5);
+ // Its insert fails (the poller logs it and goes on): no card is made, none is lost
+ let now = Utc::now();
+ let insert = sqlx::query(V071_INSERT)
+ .bind("dvc_071").bind(SPACE).bind(LANDED).bind("dddd").bind("dddd").bind("{}").bind(now).bind(now)
+ .execute(&db.pool)
+ .await;
+ assert!(insert.is_err(), "0.7.1 can't make cards here");
+ // Its PR #12 moved on: only its own repo's old card goes stale, not demo-org/site's
+ assert_eq!(v071_stale(&db, "pr:12", Some("bnew")).await, vec!["dvc_review".to_string()]);
+ // Its "PR closed" sweep over every review card can't touch the other repo's either
+ assert!(v071_stale(&db, "pr:12", None).await.is_empty());
+ // Its CI recheck can't rewrite another repo's facts; its own repo's still work
+ v071_facts(&db, &site_landed.id, "{\"ci\":\"wrong repo\"}").await;
+ v071_facts(&db, "dvc_landed", "{\"repo\":\"Demo-Org/App\",\"ci\":\"pass\"}").await;
+ assert_eq!(db.dev_card("dvc_landed").await.unwrap().unwrap().status, PENDING);
+ // Finishing a card by id still works for any repo (the person's edits, generate)
+ sqlx::query(V071_SET).bind("dvc_landed").bind(READY).bind(None::<String>).bind(Utc::now()).execute(&db.pool).await.unwrap();
+ // It polls on, moving only its own 0.7.1 place
+ sqlx::query(V071_POLLED).bind(SPACE).bind("zzzz").bind(Utc::now()).bind(None::<String>).execute(&db.pool).await.unwrap();
+ // It reads the space row with the extra column, and its seen route moves only seen_at
+ let badge = db.dev_mode(SPACE).await.unwrap().unwrap().reviews_seen_at;
+ assert!(badge.is_some());
+ let opened_on_071 = Utc::now();
+ sqlx::query(V071_SEEN).bind(SPACE).bind(opened_on_071).execute(&db.pool).await.unwrap();
+
+ let after: Vec<(String, String, String, String)> =
+ sqlx::query_as("SELECT id, repo, status, facts FROM dev_cards ORDER BY id").fetch_all(&db.pool).await.unwrap();
+ let of = |rows: &[(String, String, String, String)], id: &str| rows.iter().find(|r| r.0 == id).cloned().unwrap();
+ assert_eq!(after.len(), before.len());
+ assert_eq!(of(&after, &site_review.id), of(&before, &site_review.id), "the other repo's review is untouched");
+ assert_eq!(of(&after, &site_landed.id), of(&before, &site_landed.id), "the other repo's facts are untouched");
+ assert_eq!(of(&after, "dvc_review").2, STALE);
+
+ // --- Back up to 0.7.2: nothing is rebuilt, every row is as 0.7.1 left it
+ db.migrate_dev_mode().await.unwrap();
+ let again: Vec<(String, String, String, String)> =
+ sqlx::query_as("SELECT id, repo, status, facts FROM dev_cards ORDER BY id").fetch_all(&db.pool).await.unwrap();
+ assert_eq!(again, after);
+ // #357's column isn't added or backfilled again: the badge keeps its time, the rollup 0.7.1's
+ let mode = db.dev_mode(SPACE).await.unwrap().unwrap();
+ assert_eq!((mode.seen_at, mode.reviews_seen_at), (Some(opened_on_071), badge));
+ let cols: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM pragma_table_info('dev_mode_spaces') WHERE name = 'reviews_seen_at'")
+ .fetch_one(&db.pool)
+ .await
+ .unwrap();
+ assert_eq!(cols, 1);
+ // 0.7.2 picks the repo up where it left it, so what landed meanwhile becomes cards, once
+ let app = "github.com/demo-org/app";
+ assert_eq!(db.dev_repo(SPACE, app).await.unwrap().unwrap().last_seen_sha.as_deref(), Some("aaaa"));
+ let caught = db.insert_dev_card_in(SPACE, app, LANDED, "dddd", "dddd", "{}").await.unwrap();
+ assert!(caught.is_some());
+ assert!(db.insert_dev_card_in(SPACE, app, LANDED, "dddd", "dddd", "{}").await.unwrap().is_none());
+ assert!(db.insert_dev_card_in(SPACE, app, REVIEW, "pr:12", "bnew", "{}").await.unwrap().is_some(), "PR #12's new head gets its card");
+ // and 0.7.2's own writes to the other repo's cards go through the guard
+ db.set_dev_card_facts(&site_landed.id, "{\"ci\":\"pass\"}").await.unwrap();
+ assert_eq!(db.dev_card(&site_landed.id).await.unwrap().unwrap().facts, "{\"ci\":\"pass\"}");
+ assert_eq!(db.stale_dev_reviews_in(SPACE, site, "pr:12", None).await.unwrap(), vec![site_review.id.clone()]);
+ }
+
+ /// Every Dev mode table's schema and rows, to compare two states of the database exactly.
+ async fn dev_state(db: &Database) -> Vec<String> {
+ let mut out: Vec<String> = sqlx::query_scalar(
+ "SELECT type || ' ' || name || ' ' || COALESCE(sql, '') FROM sqlite_master WHERE name LIKE '%dev_%' ORDER BY type, name",
+ )
+ .fetch_all(&db.pool)
+ .await
+ .unwrap();
+ for t in ["dev_mode_spaces", "dev_cards", "dev_repos"] {
+ let has: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = ?").bind(t).fetch_one(&db.pool).await.unwrap();
+ if has == 1 {
+ let cols: Vec<String> = sqlx::query_scalar(&format!("SELECT name FROM pragma_table_info('{t}') ORDER BY cid")).fetch_all(&db.pool).await.unwrap();
+ let quoted: Vec<String> = cols.iter().map(|c| format!("quote(\"{c}\")")).collect();
+ let dump: Vec<String> =
+ sqlx::query_scalar(&format!("SELECT {} FROM {t} ORDER BY 1", quoted.join(" || ',' || "))).fetch_all(&db.pool).await.unwrap();
+ out.extend(dump.into_iter().map(|r| format!("{t}: {r}")));
+ }
+ }
+ out
+ }
+
+ /// #357's `dev_mode_spaces.reviews_seen_at`, there or not, so both start orders are covered.
+ async fn with_reviews_seen(db: &Database, there: bool) {
+ let has: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM pragma_table_info('dev_mode_spaces') WHERE name = 'reviews_seen_at'").fetch_one(&db.pool).await.unwrap();
+ let sql = match (there, has == 1) {
+ (true, false) => "ALTER TABLE dev_mode_spaces ADD COLUMN reviews_seen_at TIMESTAMP",
+ (false, true) => "ALTER TABLE dev_mode_spaces DROP COLUMN reviews_seen_at",
+ _ => return,
+ };
+ sqlx::query(sql).execute(&db.pool).await.unwrap();
+ }
+
+ #[tokio::test]
+ async fn the_migration_runs_again_without_changing_anything_whether_357_ran_first_or_not() {
+ for seen_first in [false, true] {
+ let (db, _tmp) = db().await;
+ as_071(&db).await;
+ with_reviews_seen(&db, seen_first).await;
+ db.migrate_dev_mode().await.unwrap();
+ let once = dev_state(&db).await;
+ assert!(once.iter().any(|l| l.starts_with("dev_repos: ")), "migrated (#357 first: {seen_first})");
+ // A second and a third start change nothing and don't fail
+ db.migrate_dev_mode().await.unwrap();
+ db.migrate_dev_mode().await.unwrap();
+ assert_eq!(dev_state(&db).await, once, "#357 first: {seen_first}");
+ }
+ }
+
+ async fn same_clock(db: &Database) {
+ sqlx::query("UPDATE dev_cards SET created_at = '2026-11-06 00:00:00', updated_at = '2026-11-06 00:00:00'")
+ .execute(&db.pool).await.unwrap();
+ }
+
+ #[tokio::test]
+ async fn a_migration_that_dies_halfway_leaves_the_071_shape_and_the_next_start_redoes_it() {
+ let (db, _tmp) = db().await;
+ as_071(&db).await;
+ with_reviews_seen(&db, true).await;
+ let before = dev_state(&db).await;
+ // Halfway: the repo copy has run when making the new cards table fails (a name in the way
+ // stands in for the crash). Everything the migration did must be undone.
+ sqlx::query("CREATE TABLE dev_cards_v2 (x)").execute(&db.pool).await.unwrap();
+ assert!(db.migrate_dev_mode().await.is_err());
+ sqlx::query("DROP TABLE dev_cards_v2").execute(&db.pool).await.unwrap();
+ let after: Vec<String> = dev_state(&db).await;
+ // Only what runs before the transaction is new: the empty 0.7.2 tables and indexes that
+ // 0.7.1 never reads (CREATE ... IF NOT EXISTS). No row was copied, no card was moved.
+ let old: Vec<&String> = before.iter().collect();
+ let kept: Vec<&String> = after.iter().filter(|l| !l.starts_with("table dev_repos") && !l.starts_with("index sqlite_autoindex_dev_repos")).collect();
+ assert_eq!(kept, old, "the 0.7.1 shape is intact");
+ assert!(!after.iter().any(|l| l.starts_with("dev_repos: ")), "the repo copy was rolled back");
+ assert!(!db.dev_cards_has("repo").await.unwrap());
+ // The next start redoes it cleanly, as if nothing had happened
+ db.migrate_dev_mode().await.unwrap();
+ let fresh = {
+ let (clean, _t) = super::tests::db().await;
+ as_071(&clean).await;
+ with_reviews_seen(&clean, true).await;
+ clean.migrate_dev_mode().await.unwrap();
+ same_clock(&clean).await;
+ dev_state(&clean).await
+ };
+ // The two copies were seeded a moment apart; only their cards' clocks may differ
+ same_clock(&db).await;
+ assert_eq!(dev_state(&db).await, fresh);
+ assert_eq!(db.dev_repos(SPACE).await.unwrap().len(), 1);
+ assert_eq!(db.dev_card("dvc_review").await.unwrap().unwrap().repo, "github.com/demo-org/app");
+ }
+
+ #[tokio::test]
+ async fn a_fresh_database_needs_no_migration_and_reopens() {
+ let tmp = tempfile::tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ db.put_dev_mode(SPACE, true, "demo-org/app", "main", None, None).await.unwrap();
+ db.insert_dev_card_in(SPACE, "github.com/demo-org/app", LANDED, "aaaa", "aaaa", "{}").await.unwrap().unwrap();
+ drop(db);
+ let db = Database::init(tmp.path()).await.unwrap();
+ assert_eq!(db.dev_repos(SPACE).await.unwrap().len(), 1);
+ assert_eq!(db.dev_cards_in(SPACE, None, LANDED, None, 10).await.unwrap().len(), 1);
+ }
+
+ #[tokio::test]
+ async fn pr_12_in_two_repos_is_two_cards() {
+ let (db, _tmp) = db().await;
+ let app = db.insert_dev_card_in(SPACE, "github.com/demo-org/app", REVIEW, "pr:12", "same", "{}").await.unwrap().unwrap();
+ let site = db.insert_dev_card_in(SPACE, "github.com/demo-org/site", REVIEW, "pr:12", "same", "{}").await.unwrap().unwrap();
+ assert_ne!(app.id, site.id);
+ assert!(db.insert_dev_card_in(SPACE, "github.com/demo-org/app", REVIEW, "pr:12", "same", "{}").await.unwrap().is_none(), "the same repo still dedupes");
+ // Each repo's lookups and stale marks see only its own card
+ let of = db.dev_cards_of_ref_in(SPACE, "github.com/demo-org/app", REVIEW, "pr:12").await.unwrap();
+ assert_eq!(of.iter().map(|c| c.id.as_str()).collect::<Vec<_>>(), vec![app.id.as_str()]);
+ assert_eq!(db.dev_cards_in(SPACE, Some("github.com/demo-org/site"), REVIEW, None, 10).await.unwrap().len(), 1);
+ assert_eq!(db.dev_cards_in(SPACE, None, REVIEW, None, 10).await.unwrap().len(), 2);
+ let staled = db.stale_dev_reviews_in(SPACE, "github.com/demo-org/app", "pr:12", None).await.unwrap();
+ assert_eq!(staled, vec![app.id.clone()]);
+ assert_eq!(db.dev_card(&site.id).await.unwrap().unwrap().status, PENDING, "the other repo's PR #12 is untouched");
+ }
+
+ #[tokio::test]
+ async fn a_space_watches_at_most_ten_repos() {
+ let (db, _tmp) = db().await;
+ for i in 0..MAX_REPOS {
+ let key = repo_key("github.com", &format!("demo-org/r{i}"));
+ assert_eq!(db.add_dev_repo(SPACE, &key, Some("t"), &format!("demo-org/r{i}"), Some("github.com"), "main", None, BY_TEAM).await.unwrap(), RepoAdd::Added);
+ }
+ let key = repo_key("github.com", "demo-org/eleven");
+ assert_eq!(db.add_dev_repo(SPACE, &key, None, "demo-org/eleven", Some("github.com"), "main", None, BY_HAND).await.unwrap(), RepoAdd::TooMany);
+ assert_eq!(db.dev_repos(SPACE).await.unwrap().len(), MAX_REPOS);
+ // At the cap an existing key is still kept (a team label update), and another space has its own 10
+ let first = repo_key("github.com", "demo-org/r0");
+ assert_eq!(db.add_dev_repo(SPACE, &first, Some("t2"), "demo-org/r0", Some("github.com"), "main", None, BY_TEAM).await.unwrap(), RepoAdd::Kept);
+ assert_eq!(db.dev_repo(SPACE, &first).await.unwrap().unwrap().team.as_deref(), Some("t2"));
+ assert_eq!(db.add_dev_repo("space_other", &key, None, "demo-org/eleven", Some("github.com"), "main", None, BY_HAND).await.unwrap(), RepoAdd::Added);
+ // Removing one makes room
+ assert!(db.delete_dev_repo(SPACE, &first).await.unwrap());
+ assert_eq!(db.add_dev_repo(SPACE, &key, None, "demo-org/eleven", Some("github.com"), "main", None, BY_HAND).await.unwrap(), RepoAdd::Added);
+ }
+
+ #[tokio::test]
+ async fn a_new_branch_starts_the_watch_over_and_a_rekey_moves_the_cards() {
+ let (db, _tmp) = db().await;
+ let gh = repo_key("github.com", "demo-org/app");
+ db.add_dev_repo(SPACE, &gh, None, "demo-org/app", Some("github.com"), "main", None, BY_MIGRATION).await.unwrap();
+ db.dev_repo_polled(SPACE, &gh, Some("aaaa"), None).await.unwrap();
+ assert!(db.set_dev_repo_branch(SPACE, &gh, "main").await.unwrap());
+ assert_eq!(db.dev_repo(SPACE, &gh).await.unwrap().unwrap().last_seen_sha.as_deref(), Some("aaaa"), "the same branch keeps its place");
+ db.insert_dev_card_in(SPACE, &gh, LANDED, "aaaa", "aaaa", "{}").await.unwrap().unwrap();
+ let ghe = repo_key("ghe.example.com", "demo-org/app");
+ assert!(db.rekey_dev_repo(SPACE, &gh, &ghe, "ghe.example.com").await.unwrap());
+ assert_eq!(db.dev_cards_in(SPACE, Some(&ghe), LANDED, None, 10).await.unwrap().len(), 1);
+ assert!(db.dev_repo(SPACE, &gh).await.unwrap().is_none());
+ // A taken key is refused
+ db.add_dev_repo(SPACE, &gh, None, "demo-org/app", Some("github.com"), "main", None, BY_HAND).await.unwrap();
+ assert!(!db.rekey_dev_repo(SPACE, &gh, &ghe, "ghe.example.com").await.unwrap());
+ assert!(db.set_dev_repo_branch(SPACE, &ghe, "release").await.unwrap());
+ let r = db.dev_repo(SPACE, &ghe).await.unwrap().unwrap();
+ assert_eq!((r.branch.as_str(), r.last_seen_sha.as_deref()), ("release", None), "a new branch starts over");
+ }
+}
diff --git a/src/server/dev/floor.rs b/src/server/dev/floor.rs
index a7f3b6b5..2fc1fdb5 100644
--- a/src/server/dev/floor.rs
+++ b/src/server/dev/floor.rs
@@ -18,13 +18,24 @@ pub async fn ctx_for_kwant(db: &Database, kwant_id: &str, cwd: Option<&Path>) ->
}
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)?;
+ // Every watched repo's branch is protected (T9: the floor stays space-wide). The first
+ // repo's is the main one; with none, the branch a team folder named at switch-on.
+ let repos = db.dev_repos(&kwant.space_id).await.unwrap_or_default();
+ let mut branches: Vec<String> = Vec::new();
+ for b in repos.iter().map(|r| r.branch.trim()).filter(|b| !b.is_empty()) {
+ if !branches.iter().any(|x| x == b) {
+ branches.push(b.to_string());
+ }
+ }
+ let branch = if branches.is_empty() { mode.branch.clone() } else { branches.remove(0) };
+ let deploy_hint = repos.iter().find_map(|r| r.deploy_hint.clone()).or(mode.deploy_hint.clone());
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(),
+ branch,
+ protected: branches,
+ deploy_hint,
prod_connections,
head_branch: cwd.and_then(head_branch),
migration: None,
diff --git a/src/server/dev/generate.rs b/src/server/dev/generate.rs
index a885d77e..edad67e6 100644
--- a/src/server/dev/generate.rs
+++ b/src/server/dev/generate.rs
@@ -122,7 +122,7 @@ pub fn pr_ref(pr: u64) -> String {
/// `ready` and `stale` both count; a `failed` one doesn't, nor a review of another head.
async fn landed_review(state: &AppState, row: &DevCardRow, facts: &DevFacts) -> Option<(Value, String)> {
let (pr, head) = (facts.pr?, facts.pr_head_sha.as_deref()?);
- let cards = state.db.dev_cards_of_ref(&row.space_id, REVIEW, &pr_ref(pr)).await.ok()?;
+ let cards = state.db.dev_cards_of_ref_in(&row.space_id, &row.repo, REVIEW, &pr_ref(pr)).await.ok()?;
cards.into_iter().filter(|c| c.status != FAILED && c.head_sha == head).find_map(|c| Some((serde_json::from_str(c.card.as_deref()?).ok()?, c.head_sha)))
}
diff --git a/src/server/dev/poller.rs b/src/server/dev/poller.rs
index 25e72b4d..9396c9fd 100644
--- a/src/server/dev/poller.rs
+++ b/src/server/dev/poller.rs
@@ -1,13 +1,14 @@
-//! 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.
+//! The Dev mode poller (plan §3.3, D4, D5, D8; team-repos.md T5): every [`EVERY`] (and right after
+//! the switch goes on, or a repo or branch moves) it reads each repo a Dev mode space watches, 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`]. Each repo is polled on its own and
+//! keeps its own last seen commit, poll error and tag: one failing repo never stops the others.
+//! Draft PRs are skipped; diffs are cut at [`DIFF_CHARS`]. Lists go through ETags; a 403/429 rate
+//! limit backs the whole space off (it's one token) 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::dev_mode::{DevCardRow, DevRepoRow, LANDED, PENDING, REVIEW, STALE};
use crate::db::models::Kwant;
use crate::db::spaces::SpaceId;
use crate::server::AppState;
@@ -41,7 +42,7 @@ struct Shared {
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.
+ /// The newest tag of each watched repo (by [`tag_key`]), and when its commit was made.
tags: HashMap<String, (String, Option<DateTime<Utc>>)>,
}
@@ -60,7 +61,8 @@ fn etags() -> &'static EtagCache {
C.get_or_init(EtagCache::default)
}
-/// Polls `space_id` now instead of at the next tick (the switch went on, the repo moved).
+/// Polls every repo of `space_id` now instead of at the next tick (the switch went on, a repo
+/// was added or moved).
pub fn poll_soon(_state: &AppState, space_id: &str) {
shared().lock().unwrap().soon.insert(space_id.to_string());
wake().notify_one();
@@ -76,14 +78,18 @@ pub fn take_due_soon(space_id: &str) -> bool {
shared().lock().unwrap().soon.remove(space_id)
}
-/// 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())
+fn tag_key(space_id: &str, repo_key: &str) -> String {
+ format!("{space_id}\n{repo_key}")
}
-/// 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)
+/// The newest tag the last poll saw on one watched repo (by its key).
+pub fn last_tag(space_id: &str, repo_key: &str) -> Option<String> {
+ shared().lock().unwrap().tags.get(&tag_key(space_id, repo_key)).map(|(t, _)| t.clone())
+}
+
+/// When that tag's commit was made: release notes cover the repo's landed cards after it.
+pub fn last_tag_at(space_id: &str, repo_key: &str) -> Option<DateTime<Utc>> {
+ shared().lock().unwrap().tags.get(&tag_key(space_id, repo_key)).and_then(|(_, at)| *at)
}
/// Starts the poller, after picking up what a restart left: pending cards go to `generate`
@@ -105,7 +111,7 @@ pub fn spawn(state: AppState, shutdown: CancellationToken) {
if shutdown.is_cancelled() {
return;
}
- poll_logged(&state, row).await;
+ poll_space(&state, &row.space_id).await;
}
}
Err(e) => tracing::warn!("dev: could not list Dev mode spaces: {e}"),
@@ -149,9 +155,22 @@ async fn recover(state: &AppState) {
}
}
-/// [`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) {
+/// Polls every repo `space_id` watches, one after another. A repo that fails records its error
+/// and the next one is still read (T5).
+pub async fn poll_space(state: &AppState, space_id: &str) {
+ match state.db.dev_repos(space_id).await {
+ Ok(rows) => {
+ for row in rows {
+ poll_logged(state, row).await;
+ }
+ }
+ Err(e) => tracing::warn!(space = %space_id, "dev: could not list the watched repos: {e}"),
+ }
+}
+
+/// [`poll`] with its outcome recorded: the poll error on the repo's row, and a back-off of the
+/// space after a rate limit. Public for the leak tests (`tests/dev_github_test.rs`).
+pub async fn poll_logged(state: &AppState, row: DevRepoRow) {
let space = row.space_id.clone();
if shared().lock().unwrap().resume_at.get(&space).is_some_and(|t| *t > Utc::now()) {
return;
@@ -166,16 +185,16 @@ pub async fn poll_logged(state: &AppState, row: DevModeRow) {
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;
+ tracing::info!(space = %space, repo = %row.key, "dev: poll failed: {e}");
+ let _ = state.db.dev_repo_polled(&space, &row.key, 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> {
- // On with no repo (plan any-git.md S3): nothing to read, and nothing to report as an error
- if mode.repo.trim().is_empty() {
+/// One poll of one watched repo. 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: &DevRepoRow) -> Result<(), GhError> {
+ // A row whose branch isn't known yet (added while off): reconcile fills it at switch-on
+ if mode.repo.trim().is_empty() || mode.branch.trim().is_empty() {
return Ok(());
}
let space = SpaceId::new(&mode.space_id);
@@ -195,7 +214,7 @@ pub async fn poll(state: &AppState, mode: &DevModeRow) -> Result<(), GhError> {
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()))?;
+ state.db.dev_repo_polled(&mode.space_id, &mode.key, 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?;
@@ -206,19 +225,20 @@ pub async fn poll(state: &AppState, mode: &DevModeRow) -> Result<(), GhError> {
Ok(())
}
-async fn update_tag(client: &GithubSource, mode: &DevModeRow, tag: Option<(String, Option<String>)>) {
+async fn update_tag(client: &GithubSource, mode: &DevRepoRow, tag: Option<(String, Option<String>)>) {
+ let key = tag_key(&mode.space_id, &mode.key);
let Some((name, sha)) = tag else {
- shared().lock().unwrap().tags.remove(&mode.space_id);
+ shared().lock().unwrap().tags.remove(&key);
return;
};
- if shared().lock().unwrap().tags.get(&mode.space_id).is_some_and(|(t, at)| *t == name && at.is_some()) {
+ if shared().lock().unwrap().tags.get(&key).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));
+ shared().lock().unwrap().tags.insert(key, (name, at));
}
/// Which of the new commits (oldest first) become cards: the newest [`BACKFILL`] on a space's
@@ -244,8 +264,8 @@ pub(crate) fn merged_pr<'a>(pulls: &'a [GhPull], sha: &str, branch: &str) -> Res
}
}
-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) {
+async fn landed(state: &AppState, client: &GithubSource, mode: &DevRepoRow, kwants: &[Kwant], c: &GhCommit) -> Result<(), GhError> {
+ if state.db.dev_cards_of_ref_in(&mode.space_id, &mode.key, 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();
@@ -259,11 +279,11 @@ async fn landed(state: &AppState, client: &GithubSource, mode: &DevModeRow, kwan
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;
+ insert(state, mode, LANDED, &c.sha, &c.sha, &facts).await;
Ok(())
}
-async fn reviews(state: &AppState, client: &GithubSource, mode: &DevModeRow, kwants: &[Kwant], pulls: &[GhPull]) -> Result<(), GhError> {
+async fn reviews(state: &AppState, client: &GithubSource, mode: &DevRepoRow, kwants: &[Kwant], pulls: &[GhPull]) -> Result<(), GhError> {
let mut open = HashSet::new();
let mut read = 0;
for p in pulls {
@@ -271,12 +291,12 @@ async fn reviews(state: &AppState, client: &GithubSource, mode: &DevModeRow, kwa
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;
+ stale(state, mode, &ref_, None).await;
continue;
}
- let have = state.db.dev_cards_of_ref(&mode.space_id, REVIEW, &ref_).await.unwrap_or_default();
+ let have = state.db.dev_cards_of_ref_in(&mode.space_id, &mode.key, 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;
+ stale(state, mode, &ref_, Some(&p.head.sha)).await;
continue;
}
if read >= MAX_REVIEWS {
@@ -293,30 +313,31 @@ async fn reviews(state: &AppState, client: &GithubSource, mode: &DevModeRow, kwa
let security = super::scan::for_review(&state.config.data_dir, client, &mode.repo, &p.head.sha, &mut files, capped).await;
let mut facts = review_facts(mode, p, head.as_ref(), files, checks, kwants, first);
facts.security = Some(security);
- insert(state, &mode.space_id, REVIEW, &ref_, &p.head.sha, &facts).await;
- stale(state, &mode.space_id, &ref_, Some(&p.head.sha)).await;
+ insert(state, mode, REVIEW, &ref_, &p.head.sha, &facts).await;
+ stale(state, mode, &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 {
+ // A PR of this repo that closed or merged: its review cards go stale
+ if let Ok(cards) = state.db.dev_cards_in(&mode.space_id, Some(&mode.key), 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;
+ stale(state, mode, &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() {
+async fn stale(state: &AppState, mode: &DevRepoRow, ref_: &str, keep: Option<&str>) {
+ for id in state.db.stale_dev_reviews_in(&mode.space_id, &mode.key, 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) {
+async fn insert(state: &AppState, mode: &DevRepoRow, kind: &str, ref_: &str, head: &str, facts: &DevFacts) {
+ let space_id = &mode.space_id;
let Ok(json) = serde_json::to_string(facts) else { return };
- match state.db.insert_dev_card(space_id, kind, ref_, head, &json).await {
+ match state.db.insert_dev_card_in(space_id, &mode.key, kind, ref_, head, &json).await {
Ok(Some(row)) => {
super::notify_card(state, &row);
tokio::spawn(super::generate(state.clone(), row.id));
@@ -328,11 +349,11 @@ async fn insert(state: &AppState, space_id: &str, kind: &str, ref_: &str, head:
/// 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) {
+async fn recheck_ci(state: &AppState, client: &GithubSource, mode: &DevRepoRow) {
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());
+ rows.extend(state.db.dev_cards_in(&mode.space_id, Some(&mode.key), 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) {
@@ -362,7 +383,7 @@ async fn recheck_ci(state: &AppState, client: &GithubSource, mode: &DevModeRow)
/// 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> {
+async fn first_edits(client: &GithubSource, mode: &DevRepoRow, 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) {
@@ -451,7 +472,7 @@ fn author_of(commit: Option<&GhCommit>, pr: Option<&GhPull>, kwants: &[Kwant]) -
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 {
+pub fn landed_facts(mode: &DevRepoRow, 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);
@@ -480,7 +501,7 @@ pub fn landed_facts(mode: &DevModeRow, c: &GhCommit, pr: Option<&GhPull>, files:
}
}
-pub fn review_facts(mode: &DevModeRow, p: &GhPull, head: Option<&GhCommit>, files: Vec<GhFile>, checks: Vec<GhCheck>, kwants: &[Kwant], first: Vec<String>) -> DevFacts {
+pub fn review_facts(mode: &DevRepoRow, 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 {
@@ -598,20 +619,20 @@ mod tests {
#[test]
fn landed_facts_prefer_the_pr_and_keep_links_https() {
- let mode = DevModeRow {
+ let mode = DevRepoRow {
space_id: "s1".into(),
- on: true,
+ key: "github.com/demo-org/app".into(),
+ team: None,
provider: "github".into(),
repo: "demo-org/app".into(),
+ host: Some("github.com".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(),
- reviews_seen_at: None,
+ added_by: "team".into(),
+ added_at: Utc::now(),
};
let c = commit("m1");
let mut p = pull(7, Some("m1"), true, "main");
diff --git a/src/server/dev/post.rs b/src/server/dev/post.rs
index dcc2a03f..9901d937 100644
--- a/src/server/dev/post.rs
+++ b/src/server/dev/post.rs
@@ -314,9 +314,13 @@ fn gh_error(e: GhError) -> PostError {
}
}
-/// The client whose connection can read PR `number`, and the PR. Same order as Dev mode's reads.
-async fn client_for_pull(state: &AppState, repo_name: &str, number: u64) -> Result<(GithubSource, crate::zombie::github::GhPull), PostError> {
- let list = repo::clients(state).await.map_err(PostError::failed)?;
+/// The client whose connection can read PR `number`, and the PR. Same order as Dev mode's reads,
+/// with the connections of the card's own host (the first part of its repo key) first (T6).
+async fn client_for_pull(state: &AppState, host: Option<&str>, repo_name: &str, number: u64) -> Result<(GithubSource, crate::zombie::github::GhPull), PostError> {
+ let mut list = repo::clients(state).await.map_err(PostError::failed)?;
+ if let Some(h) = host {
+ list.sort_by_key(|(cfg, _)| repo::web_host(cfg) != h);
+ }
let mut last = GhError::NotFound;
for (_, c) in list {
match c.dev_pull(repo_name, number).await {
@@ -354,7 +358,8 @@ pub async fn post_review(state: &AppState, row: &DevCardRow) -> Result<Posted, P
let Some(number) = facts.pr else {
return Err(PostError::failed("this card has no pull request"));
};
- let (client, pull) = client_for_pull(state, &facts.repo, number).await?;
+ let host = row.repo.split_once('/').map(|(h, _)| h).filter(|h| !h.starts_with("local:"));
+ let (client, pull) = client_for_pull(state, host, &facts.repo, number).await?;
if pull.head.sha != row.head_sha {
return Err(PostError::new(ErrorKind::Stale, STALE_MESSAGE));
}
diff --git a/src/server/dev/repo.rs b/src/server/dev/repo.rs
index ef60f6b2..34e45661 100644
--- a/src/server/dev/repo.rs
+++ b/src/server/dev/repo.rs
@@ -1,7 +1,9 @@
-//! 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.
+//! The repo check (plan §3.2 `POST /dev_mode/check`, D4), detection of the repos a space's teams
+//! point at (any-git.md S1, S2), and [`reconcile`], which keeps a space's watched repos in step
+//! with its teams (team-repos.md T3, T4). Repos are read through the Loose ends GitHub connection
+//! (its vault token and Enterprise `api_base`). kwant writes nothing to GitHub.
+use crate::db::dev_mode::{DevRepoRow, RepoAdd, BY_HAND, BY_MIGRATION, BY_TEAM, MAX_REPOS};
use crate::db::spaces::SpaceId;
use crate::server::AppState;
use crate::zombie::github::{GhError, GithubConfig, GithubSource};
@@ -85,11 +87,14 @@ pub struct Check {
pub repo: Option<String>,
pub branch: Option<String>,
pub deploy_hint: Option<&'static str>,
+ /// The web host of the connection that found it (never in a reply).
+ #[serde(skip)]
+ pub host: Option<String>,
}
impl Check {
- fn of(state: &'static str, repo: Option<String>) -> Self {
- Check { state, repo, branch: None, deploy_hint: None }
+ pub(crate) fn of(state: &'static str, repo: Option<String>) -> Self {
+ Check { state, repo, branch: None, deploy_hint: None, host: None }
}
}
@@ -171,7 +176,7 @@ pub async fn check(state: &AppState, space: &SpaceId, input: &str) -> Result<Che
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) };
+ answer = Check { state: "found", repo: Some(r.full_name.clone()), branch: Some(r.default_branch.clone()), deploy_hint: deploy_hint(&root), host: Some(web_host(&cfg)) };
return Ok(answer);
}
Err(GhError::NotFound | GhError::Forbidden) => {}
@@ -196,6 +201,9 @@ pub async fn check(state: &AppState, space: &SpaceId, input: &str) -> Result<Che
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct Source {
pub team: String,
+ /// The team's id: a team row's `dev_repos.team`.
+ #[serde(skip)]
+ pub team_id: String,
/// `owner/name` on a GitHub host, the whole path (`group/sub/name`) on another host, and the
/// folder's own name for a `local` source.
pub repo: String,
@@ -219,6 +227,22 @@ impl Source {
self.host.as_deref().is_some_and(|h| hosts.iter().any(|g| g == h))
}
+ /// Its watched-repo key: `host/repo` lowercased (as [`repo_key`]), or `local:…` for a folder
+ /// with no remote (never shown; see [`Self::api_key`]).
+ pub fn key(&self) -> &str {
+ &self.key
+ }
+
+ /// The key the API shows: [`Self::key`], except `local:<team name lowercased>` for a `local`
+ /// source, so no folder path leaves the server.
+ pub fn api_key(&self) -> String {
+ if self.host.is_some() {
+ self.key.clone()
+ } else {
+ format!("local:{}", self.team.to_lowercase())
+ }
+ }
+
/// What [`check`] takes for this source: `host/owner/name`.
pub fn check_input(&self) -> String {
match &self.host {
@@ -283,7 +307,7 @@ pub fn parse_remote(raw: &str) -> Option<(String, String)> {
/// `(host, repo)` of what a team's repo link or folder remote says: `owner/name` on a GitHub
/// host in `gh_hosts`, the whole path on any other. In a repo link (`shorthand`), a plain
/// `owner/name` is github.com's; to git, that's a folder.
-fn source_repo(raw: &str, gh_hosts: &[String], shorthand: bool) -> Option<(String, String)> {
+pub(crate) fn source_repo(raw: &str, gh_hosts: &[String], shorthand: bool) -> Option<(String, String)> {
let (host, path) = match parse_remote(raw) {
Some(hp) => hp,
None if !shorthand => return None,
@@ -370,6 +394,7 @@ pub async fn read_folder(dir: &std::path::Path) -> Option<(Option<String>, Optio
/// One team as detection reads it: its name, folder setting and repo link.
pub struct TeamRef<'a> {
+ pub id: &'a str,
pub name: &'a str,
pub workspace_path: Option<&'a str>,
pub repo_url: Option<&'a str>,
@@ -404,7 +429,7 @@ pub async fn detect_teams(teams: &[TeamRef<'_>], space_dir: &std::path::Path, gh
if out.iter().any(|s| s.key == key) {
continue;
}
- out.push(Source { team: t.name.to_string(), repo, host, from, branch, key });
+ out.push(Source { team: t.name.to_string(), team_id: t.id.to_string(), repo, host, from, branch, key });
}
out
}
@@ -412,11 +437,210 @@ pub async fn detect_teams(teams: &[TeamRef<'_>], space_dir: &std::path::Path, gh
/// The repos `space`'s teams already point at, in team order (plan any-git.md S1).
pub async fn detect(state: &AppState, space: &SpaceId) -> Vec<Source> {
let teams = state.db.list_teams(space).await.unwrap_or_default();
- let refs: Vec<TeamRef> = teams.iter().map(|t| TeamRef { name: &t.name, workspace_path: t.workspace_path.as_deref(), repo_url: t.repo_url.as_deref() }).collect();
+ let refs: Vec<TeamRef> = teams.iter().map(|t| TeamRef { id: &t.id, name: &t.name, workspace_path: t.workspace_path.as_deref(), repo_url: t.repo_url.as_deref() }).collect();
let dir = crate::db::spaces::space_data_dir(&state.config.data_dir, space);
detect_teams(&refs, &dir, &github_hosts(state).await).await
}
+// ---------------------------------------------------------------------------------------------
+// Reconcile (team-repos.md T3, T4): the rows of `dev_repos` follow the teams.
+
+/// One reconcile at a time, server-wide: two would both see a source with no row and check it twice.
+fn reconcile_lock() -> &'static tokio::sync::Mutex<()> {
+ static L: std::sync::OnceLock<tokio::sync::Mutex<()>> = std::sync::OnceLock::new();
+ L.get_or_init(Default::default)
+}
+
+/// How often a GET may reconcile one space (the hooks and PUT don't wait for it).
+pub const RECONCILE_COOLDOWN: std::time::Duration = std::time::Duration::from_secs(30);
+
+fn reconciled() -> &'static std::sync::Mutex<std::collections::HashMap<String, std::time::Instant>> {
+ static T: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<String, std::time::Instant>>> = std::sync::OnceLock::new();
+ T.get_or_init(Default::default)
+}
+
+/// What one reconcile did, for logs and tests.
+#[derive(Debug, Default, Clone, PartialEq, Eq)]
+pub struct Reconciled {
+ /// Keys of rows added for a team source.
+ pub added: Vec<String>,
+ /// Keys of team rows removed because no team points at them any more.
+ pub removed: Vec<String>,
+ /// Keys of GitHub sources left without a row because the space watches [`MAX_REPOS`].
+ pub too_many: Vec<String>,
+}
+
+/// Brings `space`'s watched repos in line with its teams (T3):
+/// - a migrated 0.7.1 row becomes its team's row (re-keyed if that team's repo is the same
+/// `owner/name` on a GitHub Enterprise host), else a hand row;
+/// - a team row no team points at any more is removed (its cards stay);
+/// - a hand row names the team that now points at it, if any;
+/// - while on, each GitHub source with no row is checked and gets a team row, up to
+/// [`MAX_REPOS`] (T4); a source GitHub says isn't there (or no connection reads) gets none, and
+/// one GitHub doesn't answer for is added with the folder's branch (the poller says why);
+/// - while on, a row with no branch yet (added while off) gets the repo's default branch.
+///
+/// Existing rows are never checked again here: the poller reports their errors. Off, nothing is
+/// fetched (D12). A space with no Dev mode row is left alone. Non-GitHub and `local` sources never
+/// get a row: they show as `other_host`.
+pub async fn reconcile(state: &AppState, space: &SpaceId) -> Reconciled {
+ let _one = reconcile_lock().lock().await;
+ reconciled().lock().unwrap().insert(space.as_str().to_string(), std::time::Instant::now());
+ let mut out = Reconciled::default();
+ let Ok(Some(mode)) = state.db.dev_mode(space.as_str()).await else { return out };
+ let hosts = github_hosts(state).await;
+ let sources = detect(state, space).await;
+ let gh: Vec<&Source> = sources.iter().filter(|s| s.on_github(&hosts)).collect();
+ let Ok(mut rows) = state.db.dev_repos(space.as_str()).await else { return out };
+ let db = &state.db;
+ let sp = space.as_str();
+
+ // 0.7.1 rows: the team that points at the same owner/name takes them
+ for r in rows.iter().filter(|r| r.added_by == BY_MIGRATION) {
+ match gh.iter().find(|s| s.repo.eq_ignore_ascii_case(&r.repo)) {
+ Some(s) => {
+ let mut key = r.key.clone();
+ if s.key != r.key {
+ let host = s.host.clone().unwrap_or_default();
+ match db.rekey_dev_repo(sp, &r.key, &s.key, &host).await {
+ Ok(true) => key = s.key.clone(),
+ // The team's key has its own row already: this one stays a hand row
+ _ => {
+ let _ = db.set_dev_repo_owner(sp, &r.key, BY_HAND, None).await;
+ continue;
+ }
+ }
+ }
+ let _ = db.set_dev_repo_owner(sp, &key, BY_TEAM, Some(&s.team_id)).await;
+ }
+ None => {
+ let _ = db.set_dev_repo_owner(sp, &r.key, BY_HAND, None).await;
+ }
+ }
+ }
+ rows = db.dev_repos(sp).await.unwrap_or(rows);
+
+ for r in &rows {
+ let source = gh.iter().find(|s| s.key == r.key);
+ match (r.added_by.as_str(), source) {
+ // A team row whose team no longer points at it
+ (BY_TEAM, None) => {
+ if matches!(db.delete_dev_repo(sp, &r.key).await, Ok(true)) {
+ tracing::info!(space = %space, repo = %r.repo, "dev: stopped watching a repo no team points at");
+ out.removed.push(r.key.clone());
+ }
+ }
+ (BY_TEAM, Some(s)) if r.team.as_deref() != Some(s.team_id.as_str()) => {
+ let _ = db.set_dev_repo_owner(sp, &r.key, BY_TEAM, Some(&s.team_id)).await;
+ }
+ (BY_TEAM, Some(_)) => {}
+ // A hand row: names the team that points at it now, or none
+ (_, s) => {
+ let team = s.map(|s| s.team_id.as_str());
+ if r.team.as_deref() != team {
+ let _ = db.set_dev_repo_owner(sp, &r.key, BY_HAND, team).await;
+ }
+ }
+ }
+ }
+ if !mode.on {
+ return out;
+ }
+ let mut rows = db.dev_repos(sp).await.unwrap_or_default();
+
+ // Rows added while off have no branch yet
+ for r in rows.iter().filter(|r| r.branch.trim().is_empty()) {
+ if let Ok(found) = check(state, space, &r.check_input()).await {
+ if found.state == "found" {
+ let branch = found.branch.clone().unwrap_or_else(|| "main".into());
+ let _ = db.set_dev_repo_branch(sp, &r.key, &branch).await;
+ let _ = db.set_dev_repo_hint(sp, &r.key, found.deploy_hint).await;
+ }
+ }
+ }
+
+ for s in gh {
+ if rows.iter().any(|r| r.key == s.key) {
+ continue;
+ }
+ if rows.len() >= MAX_REPOS {
+ out.too_many.push(s.key.clone());
+ continue;
+ }
+ let (repo, branch, hint) = match check(state, space, &s.check_input()).await {
+ Ok(found) if found.state == "found" => {
+ let full = found.repo.clone().unwrap_or_else(|| s.repo.clone());
+ let default = found.branch.clone().unwrap_or_else(|| "main".into());
+ // The folder's branch when the repo has it, else the default (0.7.1's choice)
+ let branch = match s.branch.as_deref() {
+ Some(b) if b != default => match client_for(state, &full).await {
+ Ok((c, _)) if matches!(c.dev_branch_exists(&full, b).await, Ok(true)) => b.to_string(),
+ _ => default,
+ },
+ _ => default,
+ };
+ (full, branch, found.deploy_hint)
+ }
+ // Not there, or no connection reads it: no row; the desk says not_connected
+ Ok(_) => continue,
+ // GitHub didn't answer: watched anyway, the poller retries and says why
+ Err(_) => (s.repo.clone(), s.branch.clone().unwrap_or_else(|| "main".into()), None),
+ };
+ let host = s.host.as_deref();
+ match db.add_dev_repo(sp, &s.key, Some(&s.team_id), &repo, host, &branch, hint, BY_TEAM).await {
+ Ok(RepoAdd::Added) => {
+ tracing::info!(space = %space, repo = %repo, branch = %branch, "dev: watching a team's repo");
+ out.added.push(s.key.clone());
+ }
+ Ok(RepoAdd::Kept) => {}
+ Ok(RepoAdd::TooMany) => out.too_many.push(s.key.clone()),
+ Err(e) => tracing::warn!(space = %space, "dev: could not add a repo: {e}"),
+ }
+ rows = db.dev_repos(sp).await.unwrap_or(rows);
+ }
+ if !out.added.is_empty() {
+ super::poller::poll_soon(state, sp);
+ }
+ out
+}
+
+/// [`reconcile`] for a GET: at most once per [`RECONCILE_COOLDOWN`] for the space.
+pub async fn reconcile_on_read(state: &AppState, space: &SpaceId) {
+ let recent = reconciled().lock().unwrap().get(space.as_str()).is_some_and(|t| t.elapsed() < RECONCILE_COOLDOWN);
+ if !recent {
+ reconcile(state, space).await;
+ }
+}
+
+/// [`reconcile`] for every space with Dev mode on: after a GitHub connection is added or changed.
+pub async fn reconcile_all(state: &AppState) {
+ for row in state.db.dev_mode_on_spaces().await.unwrap_or_default() {
+ reconcile(state, &SpaceId::new(&row.space_id)).await;
+ }
+}
+
+/// [`reconcile`] in the background, after a team is made, changed or deleted: the team route
+/// doesn't wait on GitHub.
+pub fn reconcile_soon(state: &AppState, space: &SpaceId) {
+ let (state, space) = (state.clone(), space.clone());
+ tokio::spawn(async move {
+ reconcile(&state, &space).await;
+ });
+}
+
+trait CheckInput {
+ fn check_input(&self) -> String;
+}
+
+impl CheckInput for DevRepoRow {
+ fn check_input(&self) -> String {
+ match &self.host {
+ Some(h) => format!("{h}/{}", self.repo),
+ None => self.repo.clone(),
+ }
+ }
+}
+
/// The desk's line (plan any-git.md S4), from whether Dev mode is on, the watched repo (`""`:
/// none), the detected sources and whether a GitHub connection exists:
/// - `watching`: a repo is watched (or, while off, would be: a GitHub source and a connection);
@@ -532,7 +756,7 @@ mod tests {
}
fn team<'a>(name: &'a str, folder: Option<&'a str>, link: Option<&'a str>) -> TeamRef<'a> {
- TeamRef { name, workspace_path: folder, repo_url: link }
+ TeamRef { id: name, name, workspace_path: folder, repo_url: link }
}
fn gh() -> Vec<String> {
@@ -673,7 +897,7 @@ mod tests {
#[test]
fn the_status_says_what_the_desk_shows() {
- let src = |host: Option<&str>| Source { team: "T".into(), repo: "o/r".into(), host: host.map(str::to_string), from: "folder", branch: None, key: String::new() };
+ let src = |host: Option<&str>| Source { team: "T".into(), team_id: "t".into(), repo: "o/r".into(), host: host.map(str::to_string), from: "folder", branch: None, key: String::new() };
let github = [src(Some("github.com"))];
let gitlab = [src(Some("gitlab.com")), src(None)];
assert_eq!(status(true, "o/r", &github, &gh(), false), "watching");
diff --git a/src/server/dev/routes.rs b/src/server/dev/routes.rs
index 929dc069..e86aaa15 100644
--- a/src/server/dev/routes.rs
+++ b/src/server/dev/routes.rs
@@ -1,10 +1,11 @@
-//! 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`]).
+//! Dev mode's HTTP API (plan §3.2; team-repos.md T8 for the repo list). Every route is the
+//! person's, reads included: the settings hold the backup command, and the cards hold the repos'
+//! diffs. `auth::person_only` lists them and each handler also refuses a bot's turn token
+//! ([`refuse_agent_tokens`]). Errors are `{"error", "code"}`.
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::dev_mode::{repo_key, DevCardRow, DevModeRow, DevRepoRow, RepoAdd, BY_HAND, BY_TEAM, LANDED, PENDING, READY, RELEASE_NOTES, REVIEW, STALE};
use crate::db::spaces::SpaceId;
use crate::server::spaces::active_space;
use crate::server::AppState;
@@ -17,19 +18,33 @@ use axum::{
use chrono::{DateTime, Utc};
use serde::Deserialize;
use serde_json::{json, Map, Value};
+use std::collections::HashMap;
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;
+/// `{"error", "code"}` with the code the API contract names.
+fn coded(status: StatusCode, code: &str, message: impl Into<String>) -> Response {
+ (status, Json(json!({"error": message.into(), "code": code}))).into_response()
+}
+
+/// An error whose code follows from its status (the finding and card routes).
fn error(status: StatusCode, message: impl Into<String>) -> Response {
- (status, Json(json!({"error": message.into()}))).into_response()
+ let code = match status {
+ StatusCode::BAD_REQUEST => "bad_request",
+ StatusCode::NOT_FOUND => "not_found",
+ StatusCode::CONFLICT => "conflict",
+ StatusCode::BAD_GATEWAY => "github",
+ _ => "internal",
+ };
+ coded(status, code, message)
}
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")
+ coded(StatusCode::INTERNAL_SERVER_ERROR, "internal", "Dev mode could not read or save that")
}
#[allow(clippy::result_large_err)]
@@ -41,61 +56,127 @@ async fn guard(state: &AppState, headers: &HeaderMap, id: &str) -> Result<SpaceI
// ---------------------------------------------------------------------------------------------
// Settings
-/// `GET /api/spaces/:id/dev_mode` reply. With no row yet: off, the first detected GitHub repo as
-/// a prefill. Always with the detected `sources` and the desk's `status` (plan any-git.md S4).
+/// One entry of `repos[]`: a detected source, a row, or both.
+struct Entry<'a> {
+ source: Option<&'a repo::Source>,
+ row: Option<&'a DevRepoRow>,
+}
+
+/// The watched rows and detected sources of a space in the API's order (T8): each team's source in
+/// team order (with its row, if any), then hand rows not tied to a source (oldest first), then team
+/// rows no team points at any more.
+fn entries<'a>(rows: &'a [DevRepoRow], sources: &'a [repo::Source]) -> Vec<Entry<'a>> {
+ let mut out: Vec<Entry> = sources.iter().map(|s| Entry { source: Some(s), row: rows.iter().find(|r| s.host.is_some() && r.key == s.key()) }).collect();
+ let tied = |r: &DevRepoRow| out_has(sources, r);
+ out.extend(rows.iter().filter(|r| r.added_by != BY_TEAM && !tied(r)).map(|r| Entry { source: None, row: Some(r) }));
+ out.extend(rows.iter().filter(|r| r.added_by == BY_TEAM && !tied(r)).map(|r| Entry { source: None, row: Some(r) }));
+ out
+}
+
+fn out_has(sources: &[repo::Source], r: &DevRepoRow) -> bool {
+ sources.iter().any(|s| s.host.is_some() && s.key() == r.key)
+}
+
+/// The space's rows in the API's order: the first is the one the deprecated top-level fields,
+/// `{branch}` alone, release notes and landed's `last_tag` default to.
+pub fn ordered_rows(rows: &[DevRepoRow], sources: &[repo::Source]) -> Vec<DevRepoRow> {
+ entries(rows, sources).into_iter().filter_map(|e| e.row.cloned()).collect()
+}
+
+/// `GET /api/spaces/:id/dev_mode` reply (T8): the switch, `repos[]`, the deprecated one-repo
+/// fields (the first watched repo's), `sources`, `status`, `new_reviews` and the forge.
#[allow(clippy::result_large_err)]
pub async fn mode_json(state: &AppState, space: &SpaceId) -> Result<Value, Response> {
- // On with no repo and a connection now: bind the detected repo before answering (QA B1)
- bind_on_read(state, space).await;
+ repo::reconcile_on_read(state, space).await;
let row = state.db.dev_mode(space.as_str()).await.map_err(internal)?;
+ let rows = state.db.dev_repos(space.as_str()).await.map_err(internal)?;
let calls = state.db.dev_calls_today(space.as_str()).await.map_err(internal)?;
let sources = repo::detect(state, space).await;
let hosts = repo::github_hosts(state).await;
- let mut v = match &row {
- Some(r) => row_json(r, calls),
- None => json!({
- "on": false,
- "repo": sources.iter().find(|s| s.on_github(&hosts)).map(|s| s.repo.clone()),
- "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(),
- }),
- };
- with_sources(state, row.as_ref(), sources, &hosts, &mut v).await;
+ let teams = state.db.list_teams(space).await.unwrap_or_default();
+ let team_name = |id: Option<&str>| id.and_then(|id| teams.iter().find(|t| t.id == id)).map(|t| t.name.clone());
+ let on = row.as_ref().is_some_and(|r| r.on);
+ let list = entries(&rows, &sources);
+ // Only while off does a source with no row hang on a connection existing
+ let ask = !on && list.iter().any(|e| e.row.is_none() && e.source.is_some_and(|s| s.on_github(&hosts)));
+ let connected = ask && repo::clients(state).await.is_ok();
+ let mut repos = Vec::new();
+ for e in &list {
+ let status = match (e.row, e.source) {
+ (Some(r), _) if r.poll_error.is_some() => "error",
+ (Some(_), _) => "watching",
+ (None, Some(s)) if !s.on_github(&hosts) => "other_host",
+ (None, _) if rows.len() >= crate::db::dev_mode::MAX_REPOS => "too_many",
+ (None, _) if !on && connected => "watching",
+ (None, _) => "not_connected",
+ };
+ let (key, repo_name, host) = match (e.row, e.source) {
+ (Some(r), _) => (r.key.clone(), r.repo.clone(), r.host.clone()),
+ (None, Some(s)) => (s.api_key(), s.repo.clone(), s.host.clone()),
+ (None, None) => continue,
+ };
+ let team_id = match (e.source, e.row) {
+ (Some(s), _) => Some(s.team_id.clone()),
+ (None, Some(r)) => r.team.clone(),
+ _ => None,
+ };
+ let from = match (e.source, e.row) {
+ (Some(s), _) => Some(s.from),
+ (None, Some(r)) if r.added_by != BY_TEAM => Some("hand"),
+ _ => None,
+ };
+ repos.push(json!({
+ "key": key,
+ "repo": repo_name,
+ "host": host,
+ "team": team_name(team_id.as_deref()),
+ "team_id": team_id,
+ "from": from,
+ "branch": e.row.map(|r| &r.branch).filter(|b| !b.is_empty()),
+ "status": status,
+ "poll_error": e.row.and_then(|r| r.poll_error.clone()),
+ "polled_at": e.row.and_then(|r| r.polled_at),
+ "last_tag": e.row.and_then(|r| poller::last_tag(space.as_str(), &r.key)),
+ "added_by": e.row.map(|r| r.added_by_shown()),
+ }));
+ }
+ let first = list.iter().find_map(|e| e.row);
+ let mut v = json!({
+ "on": on,
+ "repos": repos,
+ // While off with nothing watched, the repo switching on would watch (0.7.1's prefill)
+ "repo": first.map(|r| r.repo.clone()).or_else(|| if on { None } else { sources.iter().find(|s| s.on_github(&hosts)).map(|s| s.repo.clone()) }),
+ // With no repo watched, the branch the production floor uses (a team folder's), as 0.7.1
+ "branch": first.map(|r| r.branch.clone()).or_else(|| row.as_ref().map(|r| r.branch.clone())).filter(|b| !b.is_empty()),
+ "deploy_hint": first.and_then(|r| r.deploy_hint.clone()),
+ "last_seen_sha": first.and_then(|r| r.last_seen_sha.clone()),
+ "polled_at": first.and_then(|r| r.polled_at),
+ "poll_error": first.and_then(|r| r.poll_error.clone()),
+ "backup_command": row.as_ref().and_then(|r| r.backup_command.clone()),
+ "calls_today": calls,
+ "calls_cap": super::call_cap(),
+ });
+ let any_watching = repos.iter().any(|r| matches!(r["status"].as_str(), Some("watching" | "error")));
+ v["status"] = json!(if any_watching { "watching" } else { repo::status(on, "", &sources, &hosts, connected) });
+ v["sources"] = json!(sources);
+ v["new_reviews"] = json!(new_reviews(state, row.as_ref()).await);
// Where a review would be posted, and as whom (post-to-github.md P7 and its amendment)
- let has_repo = v["repo"].as_str().is_some_and(|r| !r.is_empty());
- let (forge, login) = super::post::forge_json(state, has_repo).await;
+ let (forge, login) = super::post::forge_json(state, v["repo"].as_str().is_some_and(|r| !r.is_empty())).await;
v["forge"] = forge;
v["forge_login"] = login;
Ok(v)
}
-/// Adds `sources` (`[{team, repo, host, from}]`, no paths) and `status` to a settings reply.
-async fn with_sources(state: &AppState, row: Option<&DevModeRow>, sources: Vec<repo::Source>, hosts: &[String], v: &mut Value) {
- let on = row.is_some_and(|r| r.on);
- let watched = row.map(|r| r.repo.as_str()).unwrap_or("");
- // Only while off with nothing watched does the answer hang on a connection existing
- let ask = !on && watched.is_empty() && sources.iter().any(|s| s.on_github(hosts));
- let connected = ask && repo::clients(state).await.is_ok();
- v["status"] = json!(repo::status(on, watched, &sources, hosts, connected));
- v["sources"] = json!(sources);
- v["new_reviews"] = json!(new_reviews(state, row).await);
-}
-
/// Review cards ready to read that were made after the person last opened the desk (plan
/// user-flow.md F6): the open ones only (newest of each PR, not stale), never landed cards or
-/// floor approvals. A space whose desk was never opened counts nothing, so an update shows no
-/// surprise badge. Reads `reviews_seen_at`, never the rollup's `seen_at`.
+/// floor approvals, every repo together (a space total). A space whose desk was never opened
+/// counts nothing, so an update shows no surprise badge. Reads `reviews_seen_at`, never the
+/// rollup's `seen_at`.
async fn new_reviews(state: &AppState, row: Option<&DevModeRow>) -> usize {
let Some((space, seen)) = row.and_then(|r| Some((r.space_id.as_str(), r.reviews_seen_at?))) else {
return 0;
};
- match open_reviews(state, &SpaceId::new(space)).await {
+ match open_reviews(state, &SpaceId::new(space), None).await {
Ok(rows) => rows.iter().filter(|r| r.status == READY && r.created_at > seen).count(),
Err(e) => {
tracing::warn!("dev: {e}");
@@ -104,19 +185,11 @@ async fn new_reviews(state: &AppState, row: Option<&DevModeRow>) -> usize {
}
}
-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(),
- })
+async fn mode_reply(state: &AppState, space: &SpaceId) -> Response {
+ match mode_json(state, space).await {
+ Ok(v) => Json(v).into_response(),
+ Err(r) => r,
+ }
}
pub async fn get_mode(State(state): State<AppState>, headers: HeaderMap, Path(id): Path<String>) -> Response {
@@ -124,10 +197,7 @@ pub async fn get_mode(State(state): State<AppState>, headers: HeaderMap, Path(id
Ok(s) => s,
Err(r) => return r,
};
- match mode_json(&state, &space).await {
- Ok(v) => Json(v).into_response(),
- Err(r) => r,
- }
+ mode_reply(&state, &space).await
}
#[derive(Deserialize)]
@@ -143,7 +213,7 @@ pub async fn check(State(state): State<AppState>, headers: HeaderMap, Path(id):
};
match repo::check(&state, &space, &body.repo).await {
Ok(c) => Json(c).into_response(),
- Err(e) => error(StatusCode::BAD_GATEWAY, e),
+ Err(e) => coded(StatusCode::BAD_GATEWAY, "github", e),
}
}
@@ -152,11 +222,16 @@ fn double_option<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<Option
Ok(Some(Option::deserialize(d)?))
}
+/// `PUT /api/spaces/:id/dev_mode` (T8). Every field is optional; `on` keeps its value when missing.
#[derive(Deserialize)]
pub struct PutBody {
- pub on: bool,
+ #[serde(default)]
+ pub on: Option<bool>,
#[serde(default)]
pub repo: Option<String>,
+ /// A team's id or name: `repo` is then that team's repo link.
+ #[serde(default)]
+ pub team: Option<String>,
#[serde(default)]
pub branch: Option<String>,
#[serde(default, deserialize_with = "double_option")]
@@ -181,81 +256,35 @@ pub fn valid_branch(b: &str) -> bool {
&& b.chars().all(|c| !c.is_control() && !c.is_whitespace() && !"~^:?*[\\".contains(c))
}
-/// How often a GET may try to bind a detected repo for one space (the source hooks don't wait).
-const BIND_COOLDOWN: std::time::Duration = std::time::Duration::from_secs(30);
-
-fn bind_tried() -> &'static std::sync::Mutex<std::collections::HashMap<String, std::time::Instant>> {
- static T: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<String, std::time::Instant>>> = std::sync::OnceLock::new();
- T.get_or_init(Default::default)
+/// [`repo::reconcile_all`]: after a GitHub connection is added or changed (QA B1, T3).
+pub async fn bind_detected_all(state: &AppState) {
+ repo::reconcile_all(state).await;
}
-/// A space that is on with no repo watches the first detected GitHub source a connection now
-/// reads, the same choice as turning on, and the poller wakes (QA B1: a GitHub connection added
-/// while on). A space off, or with a repo, is never touched. True when a repo was bound.
-pub async fn bind_detected(state: &AppState, space: &SpaceId) -> bool {
- let Ok(Some(row)) = state.db.dev_mode(space.as_str()).await else { return false };
- if !row.on || !row.repo.is_empty() {
- return false;
- }
- bind_tried().lock().unwrap().insert(space.as_str().to_string(), std::time::Instant::now());
- let hosts = repo::github_hosts(state).await;
- let mut seen: Vec<String> = Vec::new();
- for s in repo::detect(state, space).await.into_iter().filter(|s| s.on_github(&hosts)) {
- let key = s.check_input().to_lowercase();
- if seen.contains(&key) {
- continue;
- }
- seen.push(key);
- let Ok(found) = repo::check(state, space, &s.check_input()).await else { continue };
- if found.state != "found" {
- continue;
+/// What a team's repo link is stored as (T8): userinfo dropped; a GitHub repo as
+/// `https://<host>/<owner>/<name>`, another host's URL as typed. `None`: not a repo.
+pub fn team_link(input: &str, gh_hosts: &[String]) -> Option<String> {
+ let s = repo::strip_userinfo(input);
+ if let Some((host, name)) = repo::normalize(&s) {
+ let host = host.map(|h| h.strip_prefix("www.").map(str::to_string).unwrap_or(h)).unwrap_or_else(|| "github.com".into());
+ if gh_hosts.contains(&host) {
+ return Some(format!("https://{host}/{name}"));
}
- let full = found.repo.clone().unwrap_or_default();
- let default = found.branch.clone().unwrap_or_else(|| "main".into());
- // The branch the space already names (a folder's or the person's) when the repo has it
- let branch = match row.branch.trim() {
- b if b.is_empty() || b == default => default.clone(),
- b => match repo::client_for(state, &full).await {
- Ok((c, _)) if matches!(c.dev_branch_exists(&full, b).await, Ok(true)) => b.to_string(),
- _ => default.clone(),
- },
- };
- return match state.db.bind_dev_repo(space.as_str(), &full, &branch, found.deploy_hint).await {
- Ok(true) => {
- tracing::info!(space = %space, repo = %full, branch = %branch, "dev: bound the detected repo");
- poller::poll_soon(state, space.as_str());
- true
- }
- Ok(false) => false,
- Err(e) => {
- tracing::warn!("dev: {e}");
- false
- }
- };
- }
- false
-}
-
-/// [`bind_detected`] for every space that is on with no repo: after a GitHub source is added or
-/// changed.
-pub async fn bind_detected_all(state: &AppState) {
- for row in state.db.dev_mode_on_spaces().await.unwrap_or_default().into_iter().filter(|r| r.repo.is_empty()) {
- bind_detected(state, &SpaceId::new(&row.space_id)).await;
}
+ repo::parse_remote(&s).map(|_| s)
}
-/// The GET fallback: on, no repo, a GitHub source detected and a connection there, at most once
-/// per [`BIND_COOLDOWN`] for the space.
-async fn bind_on_read(state: &AppState, space: &SpaceId) -> bool {
- let Ok(Some(row)) = state.db.dev_mode(space.as_str()).await else { return false };
- if !row.on || !row.repo.is_empty() {
- return false;
- }
- let recent = bind_tried().lock().unwrap().get(space.as_str()).is_some_and(|t| t.elapsed() < BIND_COOLDOWN);
- if recent || repo::clients(state).await.is_err() {
- return false;
+/// Checks that `branch` exists on `row`'s repo (on only). `Err` is the reply.
+#[allow(clippy::result_large_err)]
+async fn branch_exists(state: &AppState, repo_name: &str, branch: &str) -> Result<(), Response> {
+ match repo::client_for(state, repo_name).await {
+ Ok((c, _)) => match c.dev_branch_exists(repo_name, branch).await {
+ Ok(true) => Ok(()),
+ Ok(false) => Err(coded(StatusCode::BAD_REQUEST, "no_branch", format!("{repo_name} has no branch {branch}"))),
+ Err(e) => Err(coded(StatusCode::BAD_GATEWAY, "github", e.to_string())),
+ },
+ Err(e) => Err(coded(StatusCode::BAD_GATEWAY, "github", e.to_string())),
}
- bind_detected(state, space).await
}
pub async fn put_mode(State(state): State<AppState>, headers: HeaderMap, Path(id): Path<String>, Json(body): Json<PutBody>) -> Response {
@@ -263,151 +292,234 @@ pub async fn put_mode(State(state): State<AppState>, headers: HeaderMap, Path(id
Ok(s) => s,
Err(r) => return r,
};
- let before = match state.db.dev_mode(space.as_str()).await {
+ let sp = space.as_str();
+ let before = match state.db.dev_mode(sp).await {
Ok(r) => r,
Err(e) => return internal(e),
};
+ let rows_before = state.db.dev_repos(sp).await.unwrap_or_default();
+ let on = body.on.unwrap_or_else(|| before.as_ref().is_some_and(|r| r.on));
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"));
+ return coded(StatusCode::BAD_REQUEST, "backup_too_long", 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");
- }
- }
- // Any user:token@ part of a typed URL is dropped before it is read or kept (plan any-git.md S2)
- let asked_owned = body.repo.as_deref().map(repo::strip_userinfo);
- let asked_repo = asked_owned.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 asked_branch = body.branch.as_deref().map(str::trim).filter(|b| !b.is_empty());
- let sources = repo::detect(&state, &space).await;
+ if asked_branch.is_some_and(|b| !valid_branch(b)) {
+ return coded(StatusCode::BAD_REQUEST, "bad_branch", "that isn't a branch name");
+ }
let hosts = repo::github_hosts(&state).await;
- let mut asked_check = None;
- let (repo_name, branch, hint) = if body.on {
- // Turning on always works (plan any-git.md S3): the repo asked for, else the one watched,
- // else the first detected source a connection reads. With none, it's on with no repo.
- let kept_on = before.as_ref().filter(|b| b.on && !b.repo.is_empty() && asked_repo.is_none_or(|a| repo::normalize(a).is_some_and(|(_, n)| n.eq_ignore_ascii_case(&b.repo))));
- let mut candidates: Vec<String> = Vec::new();
- if let Some(a) = asked_repo {
- candidates.push(a.to_string());
- } else if let Some(b) = kept_on {
- candidates.push(b.repo.clone());
+ let sources = repo::detect(&state, &space).await;
+
+ // A team's repo link: checked before anything is saved
+ let mut team_change = None;
+ if let Some(t) = body.team.as_deref().map(str::trim).filter(|t| !t.is_empty()) {
+ let teams = state.db.list_teams(&space).await.unwrap_or_default();
+ let Some(team) = teams.iter().find(|x| x.id == t).or_else(|| teams.iter().find(|x| x.name.eq_ignore_ascii_case(t))) else {
+ return coded(StatusCode::BAD_REQUEST, "unknown_team", "no team of this space has that id or name");
+ };
+ let asked = body.repo.as_deref().unwrap_or("").trim();
+ let link = if asked.is_empty() {
+ None
} else {
- candidates.extend(kept_repo.clone());
- candidates.extend(sources.iter().filter(|s| s.on_github(&hosts)).map(|s| s.check_input()));
+ match team_link(asked, &hosts) {
+ Some(l) => Some(l),
+ None => return coded(StatusCode::BAD_REQUEST, "bad_repo", "that isn't a repo URL or owner/name"),
+ }
+ };
+ team_change = Some((team.id.clone(), link));
+ }
+
+ // A hand repo: parsed, and checked on GitHub while on
+ let mut hand = None;
+ let mut asked_check = None;
+ if body.team.as_deref().is_none_or(|t| t.trim().is_empty()) {
+ if let Some(asked) = body.repo.as_deref().map(repo::strip_userinfo).filter(|r| !r.trim().is_empty()) {
+ // Switching on always works (0.7.1, any-git.md S3): with `on: true` a repo that can't be
+ // read is not an error, the reply's `check` says why; alone it is a 400
+ let switching_on = body.on == Some(true);
+ match repo::normalize(&asked) {
+ None if switching_on => asked_check = Some(repo::Check::of("not_found", None)),
+ None => return coded(StatusCode::BAD_REQUEST, "bad_repo", "that isn't a GitHub repo URL or owner/name"),
+ Some((host, name)) => {
+ // `owner/name` with no host: whichever connection reads it (github.com while off)
+ let typed_host = host.is_some();
+ let host = host.map(|h| h.strip_prefix("www.").map(str::to_string).unwrap_or(h)).unwrap_or_else(|| "github.com".into());
+ if hosts.contains(&host) {
+ hand = Some((host, name, typed_host));
+ } else if switching_on {
+ asked_check = Some(repo::Check::of("not_found", Some(name)));
+ } else {
+ return coded(StatusCode::BAD_REQUEST, "bad_repo", "Dev mode reads GitHub repos: connect that host in Loose ends first");
+ }
+ }
+ }
}
- let mut found = None;
- let mut unanswered = None;
- let mut seen: Vec<String> = Vec::new();
- for c in candidates {
- let key = repo::normalize(&c).map(|(_, n)| n.to_lowercase()).unwrap_or_default();
- if !key.is_empty() && seen.contains(&key) {
- continue;
+ }
+
+ let fallback_branch = if hand.is_none() && rows_before.is_empty() { asked_branch.map(str::to_string).or_else(|| sources.iter().find_map(|s| s.branch.clone())) } else { None };
+ let row = match state.db.set_dev_mode(sp, on, fallback_branch.as_deref(), backup_command.as_deref()).await {
+ Ok(r) => r,
+ Err(e) => return internal(e),
+ };
+
+ if let Some((team_id, link)) = &team_change {
+ if let Err(e) = state.db.set_team_repo_url(team_id, link.as_deref()).await {
+ return internal(e);
+ }
+ tracing::info!(space = %space, team = %team_id, "the person set a team's repo link for Dev mode");
+ }
+
+ if let Some((host, name, typed_host)) = &hand {
+ let mut key = repo_key(host, name);
+ let mut existing = state.db.dev_repo(sp, &key).await;
+ if !typed_host && matches!(existing, Ok(None)) {
+ // The same `owner/name` already watched on another GitHub host
+ if let Ok(rows) = state.db.dev_repos(sp).await {
+ if let Some(r) = rows.into_iter().find(|r| r.repo.eq_ignore_ascii_case(name)) {
+ key = r.key.clone();
+ existing = Ok(Some(r));
+ }
}
- seen.push(key);
- match repo::check(&state, &space, &c).await {
- Ok(ch) if ch.state == "found" => {
- found = Some(ch);
- break;
+ }
+ match existing {
+ Ok(Some(r)) => {
+ if let Some(b) = asked_branch.filter(|b| *b != r.branch) {
+ if on {
+ if let Err(resp) = branch_exists(&state, &r.repo, b).await {
+ return resp;
+ }
+ }
+ let _ = state.db.set_dev_repo_branch(sp, &key, b).await;
}
- Ok(ch) => {
- if asked_repo.is_some() {
- asked_check = Some(ch);
+ }
+ Ok(None) if on => match repo::check(&state, &space, &if *typed_host { format!("{host}/{name}") } else { name.clone() }).await {
+ Ok(found) if found.state == "found" => {
+ let full = found.repo.clone().unwrap_or_else(|| name.clone());
+ let host = found.host.clone().unwrap_or_else(|| host.clone());
+ let key = repo_key(&host, name);
+ let branch = match asked_branch {
+ Some(b) if Some(b) != found.branch.as_deref() => {
+ if let Err(resp) = branch_exists(&state, &full, b).await {
+ return resp;
+ }
+ b.to_string()
+ }
+ _ => found.branch.clone().unwrap_or_else(|| "main".into()),
+ };
+ match state.db.add_dev_repo(sp, &key, None, &full, Some(&host), &branch, found.deploy_hint, BY_HAND).await {
+ Ok(RepoAdd::TooMany) => return coded(StatusCode::CONFLICT, "too_many", format!("Dev mode watches at most {} repos in a space", crate::db::dev_mode::MAX_REPOS)),
+ Ok(_) => tracing::info!(space = %space, repo = %full, "the person added a repo to Dev mode"),
+ Err(e) => return internal(e),
}
}
- // GitHub didn't answer (a rate limit, an outage): kept for the poller to retry
- Err(_) => {
- unanswered.get_or_insert(c);
+ // The repo asked for wasn't read: no row, and the reply says why
+ Ok(found) => asked_check = Some(found),
+ Err(e) => return coded(StatusCode::BAD_GATEWAY, "github", e),
+ },
+ Ok(None) => {
+ // Off: kept as given, the branch is read at switch-on (D12)
+ match state.db.add_dev_repo(sp, &key, None, name, Some(host.as_str()), asked_branch.unwrap_or(""), None, BY_HAND).await {
+ Ok(RepoAdd::TooMany) => return coded(StatusCode::CONFLICT, "too_many", format!("Dev mode watches at most {} repos in a space", crate::db::dev_mode::MAX_REPOS)),
+ Ok(_) => {}
+ Err(e) => return internal(e),
}
}
+ Err(e) => return internal(e),
}
- if let Some(found) = found {
- 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 asked_branch {
- 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::BAD_REQUEST, 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()),
+ } else if team_change.is_none() {
+ // `{branch}` alone (deprecated): the first watched repo's
+ if let (Some(b), Some(first)) = (asked_branch, ordered_rows(&rows_before, &sources).first()) {
+ if b != first.branch {
+ if on {
+ if let Err(resp) = branch_exists(&state, &first.repo, b).await {
+ return resp;
+ }
}
+ let _ = state.db.set_dev_repo_branch(sp, &first.key, b).await;
}
- (full, branch, found.deploy_hint.map(str::to_string))
- } else if let Some(b) = kept_on {
- // A watched repo stays watched through a failed read; the poller says why
- (b.repo.clone(), asked_branch.map(str::to_string).unwrap_or_else(|| b.branch.clone()), b.deploy_hint.clone())
- } else if let Some((_, name)) = unanswered.as_deref().and_then(repo::normalize) {
- let source_branch = sources.iter().find(|s| s.repo.eq_ignore_ascii_case(&name)).and_then(|s| s.branch.clone());
- let branch = asked_branch.map(str::to_string).or(source_branch).unwrap_or_else(|| "main".into());
- (name, branch, None)
- } else {
- // On with no repo: the floor and guards work, the poller idles. The branch, when a
- // team folder says it, still tells the floor which branch is the main one.
- let branch = asked_branch.map(str::to_string).or_else(|| sources.iter().find_map(|s| s.branch.clone())).unwrap_or_default();
- (String::new(), branch, None)
}
- } 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),
- };
+ }
+
+ repo::reconcile(&state, &space).await;
+ // A team's branch, asked with its repo link, once reconcile made its row
+ if let (Some((team_id, Some(_))), Some(b)) = (&team_change, asked_branch) {
+ let rows = state.db.dev_repos(sp).await.unwrap_or_default();
+ if let Some(r) = rows.iter().find(|r| r.team.as_deref() == Some(team_id.as_str()) && r.branch != b) {
+ if on {
+ if let Err(resp) = branch_exists(&state, &r.repo, b).await {
+ return resp;
+ }
+ }
+ let _ = state.db.set_dev_repo_branch(sp, &r.key, b).await;
+ }
+ }
+
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");
+ tracing::info!(space = %space, on = row.on, "the person set Dev mode");
if was_on != row.on {
- notify_mode(&state, space.as_str(), row.on);
+ notify_mode(&state, sp, 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 after = state.db.dev_repos(sp).await.unwrap_or_default();
+ let shape = |rs: &[DevRepoRow]| rs.iter().map(|r| (r.key.clone(), r.branch.clone())).collect::<Vec<_>>();
+ if !was_on || shape(&after) != shape(&rows_before) {
+ poller::poll_soon(&state, sp);
}
}
- let calls = state.db.dev_calls_today(space.as_str()).await.unwrap_or(0);
- let mut v = row_json(&row, calls);
- with_sources(&state, Some(&row), sources, &hosts, &mut v).await;
+ let mut v = match mode_json(&state, &space).await {
+ Ok(v) => v,
+ Err(r) => return r,
+ };
if let Some(c) = asked_check {
- // The repo asked for wasn't read: Dev mode is on without it, and this says why
v["check"] = json!(c);
}
Json(v).into_response()
}
+/// `DELETE /api/spaces/:id/dev_mode/repos/*key`: stops watching a hand-added repo. Its cards
+/// stay. A team's repo is changed through the team's link instead (409 `team_repo`).
+pub async fn delete_repo(State(state): State<AppState>, headers: HeaderMap, Path((id, key)): Path<(String, String)>) -> Response {
+ let space = match guard(&state, &headers, &id).await {
+ Ok(s) => s,
+ Err(r) => return r,
+ };
+ let key = key.trim_matches('/').to_lowercase();
+ let row = match state.db.dev_repo(space.as_str(), &key).await {
+ Ok(Some(r)) => r,
+ Ok(None) => return coded(StatusCode::NOT_FOUND, "unknown_repo", "Dev mode doesn't watch that repo"),
+ Err(e) => return internal(e),
+ };
+ if row.added_by == BY_TEAM || row.team.is_some() {
+ return coded(StatusCode::CONFLICT, "team_repo", "a team points at this repo: change or clear the team's repo link instead");
+ }
+ match state.db.delete_dev_repo(space.as_str(), &key).await {
+ Ok(_) => tracing::info!(space = %space, repo = %row.repo, "the person stopped watching a repo"),
+ Err(e) => return internal(e),
+ }
+ mode_reply(&state, &space).await
+}
+
// ---------------------------------------------------------------------------------------------
// 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.
+/// A card as the routes return it: `{id, kind, status, created_at, repo, repo_name, team,
+/// ...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.
+/// `team` is null here; [`card_json_in`] names it.
pub fn card_json(row: &DevCardRow) -> Value {
+ card_json_in(row, &HashMap::new())
+}
+
+/// [`card_json`] with `team` named from `teams` (repo key → the team name of its row now).
+pub fn card_json_in(row: &DevCardRow, teams: &HashMap<String, String>) -> Value {
let mut out = Map::new();
if row.kind == LANDED || row.kind == REVIEW {
if let Ok(f) = serde_json::from_str::<DevFacts>(&row.facts) {
@@ -432,6 +544,11 @@ pub fn card_json(row: &DevCardRow) -> Value {
out.insert("kind".into(), json!(row.kind));
out.insert("status".into(), json!(row.status));
out.insert("created_at".into(), json!(row.created_at));
+ // The repo chip (T8): the key, owner/name from the card's own facts, and the team now
+ let repo_name = serde_json::from_str::<Value>(&row.facts).ok().and_then(|f| f["repo"].as_str().map(str::to_string));
+ out.insert("repo".into(), json!(row.repo));
+ out.insert("repo_name".into(), json!(repo_name));
+ out.insert("team".into(), json!(teams.get(&row.repo)));
if row.kind == REVIEW {
// post-to-github.md P1: null until posted, null when the last post went through
let stored = |s: &Option<String>| s.as_deref().and_then(|v| serde_json::from_str::<Value>(v).ok()).unwrap_or(Value::Null);
@@ -449,6 +566,32 @@ fn short(sha: &str) -> String {
pub struct LandedQuery {
pub before: Option<DateTime<Utc>>,
pub limit: Option<i64>,
+ /// One repo's cards (its key); every repo's without it.
+ pub repo: Option<String>,
+}
+
+#[derive(Deserialize)]
+pub struct RepoQuery {
+ pub repo: Option<String>,
+}
+
+/// `?repo=` as a key: trimmed, lowercased, empty as none.
+fn repo_filter(q: Option<&str>) -> Option<String> {
+ q.map(|r| r.trim().trim_matches('/').to_lowercase()).filter(|r| !r.is_empty())
+}
+
+/// Repo key → the name of the team of that row now, for the cards' `team`.
+async fn team_names(state: &AppState, space: &SpaceId) -> HashMap<String, String> {
+ let rows = state.db.dev_repos(space.as_str()).await.unwrap_or_default();
+ let teams = state.db.list_teams(space).await.unwrap_or_default();
+ rows.into_iter().filter_map(|r| Some((r.key, teams.iter().find(|t| Some(&t.id) == r.team.as_ref())?.name.clone()))).collect()
+}
+
+/// The first watched repo in the API's order, for the defaults of the deprecated one-repo fields.
+async fn first_repo(state: &AppState, space: &SpaceId) -> Option<DevRepoRow> {
+ let rows = state.db.dev_repos(space.as_str()).await.ok()?;
+ let sources = repo::detect(state, space).await;
+ ordered_rows(&rows, &sources).into_iter().next()
}
/// How many cards the rollup reads back.
@@ -460,21 +603,28 @@ pub async fn landed(State(state): State<AppState>, headers: HeaderMap, Path(id):
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 {
+ let only = repo_filter(q.repo.as_deref());
+ let rows = match state.db.dev_cards_in(space.as_str(), only.as_deref(), 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 {
+ let recent = match state.db.dev_cards_in(space.as_str(), only.as_deref(), LANDED, None, ROLLUP_WINDOW).await {
Ok(r) => r,
Err(e) => return internal(e),
};
- let reviews = open_reviews(&state, &space).await.unwrap_or_default();
+ let reviews = open_reviews(&state, &space, only.as_deref()).await.unwrap_or_default();
let rollup = rollup(&recent, &reviews, mode.as_ref().and_then(|m| m.seen_at), Utc::now());
+ // The repo asked for, else the first watched one (deprecated, like the top-level `repo`)
+ let tag_repo = match &only {
+ Some(k) => Some(k.clone()),
+ None => first_repo(&state, &space).await.map(|r| r.key),
+ };
+ let teams = team_names(&state, &space).await;
Json(json!({
- "cards": rows.iter().map(card_json).collect::<Vec<_>>(),
+ "cards": rows.iter().map(|r| card_json_in(r, &teams)).collect::<Vec<_>>(),
"rollup": rollup,
- "last_tag": poller::last_tag(space.as_str()),
+ "last_tag": tag_repo.and_then(|k| poller::last_tag(space.as_str(), &k)),
}))
.into_response()
}
@@ -556,20 +706,28 @@ pub async fn desk_seen(State(state): State<AppState>, headers: HeaderMap, Path(i
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?;
+/// Review cards still open: the newest card of each PR of each repo (PR #12 in two repos is two
+/// cards), stale ones left out, newest first. `repo`: one repo's only.
+async fn open_reviews(state: &AppState, space: &SpaceId, repo: Option<&str>) -> Result<Vec<DevCardRow>, crate::db::DbError> {
+ let rows = state.db.dev_cards_in(space.as_str(), repo, REVIEW, None, ROLLUP_WINDOW).await?;
+ Ok(open_of(rows))
+}
+
+/// The newest card per (repo, PR), stale ones left out.
+pub fn open_of(rows: Vec<DevCardRow>) -> Vec<DevCardRow> {
let mut seen = std::collections::HashSet::new();
- Ok(rows.into_iter().filter(|r| r.status != STALE).filter(|r| seen.insert(r.ref_.clone())).collect())
+ rows.into_iter().filter(|r| r.status != STALE).filter(|r| seen.insert((r.repo.clone(), r.ref_.clone()))).collect()
}
-pub async fn reviews(State(state): State<AppState>, headers: HeaderMap, Path(id): Path<String>) -> Response {
+pub async fn reviews(State(state): State<AppState>, headers: HeaderMap, Path(id): Path<String>, Query(q): Query<RepoQuery>) -> 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(),
+ let only = repo_filter(q.repo.as_deref());
+ let teams = team_names(&state, &space).await;
+ match open_reviews(&state, &space, only.as_deref()).await {
+ Ok(rows) => Json(json!({"cards": rows.iter().map(|r| card_json_in(r, &teams)).collect::<Vec<_>>()})).into_response(),
Err(e) => internal(e),
}
}
@@ -586,10 +744,12 @@ pub async fn card(State(state): State<AppState>, headers: HeaderMap, Path(card_i
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()
+ let space = match active_space(&state, &row.space_id).await {
+ Ok(s) => s,
+ Err(r) => return r,
+ };
+ let teams = team_names(&state, &space).await;
+ Json(card_json_in(&row, &teams)).into_response()
}
// ---------------------------------------------------------------------------------------------
@@ -852,30 +1012,39 @@ async fn cancel_fix_task(state: &AppState, task_id: &str) {
// ---------------------------------------------------------------------------------------------
// Release notes and backups
-pub async fn release_notes(State(state): State<AppState>, headers: HeaderMap, Path(id): Path<String>) -> Response {
+/// `POST /api/spaces/:id/dev/release_notes?repo=<key>`: a draft for one repo, since its newest
+/// tag. Without `repo`, the first watched repo's.
+pub async fn release_notes(State(state): State<AppState>, headers: HeaderMap, Path(id): Path<String>, Query(q): Query<RepoQuery>) -> 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");
+ if state.db.dev_mode(space.as_str()).await.ok().flatten().is_none_or(|m| !m.on) {
+ return coded(StatusCode::CONFLICT, "off", "Dev mode is off in this space");
+ }
+ let watched = match repo_filter(q.repo.as_deref()) {
+ Some(k) => state.db.dev_repo(space.as_str(), &k).await.ok().flatten(),
+ None => first_repo(&state, &space).await,
+ };
+ let Some(watched) = watched else {
+ return coded(StatusCode::CONFLICT, "no_repo", "Dev mode watches no such repo 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 {
+ let since_tag = poller::last_tag(space.as_str(), &watched.key);
+ let landed = match state.db.dev_cards_in(space.as_str(), Some(&watched.key), 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 cut = poller::last_tag_at(space.as_str(), &watched.key);
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 facts = ReleaseFacts { repo: watched.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 {
+ let row = match state.db.insert_dev_card_in(space.as_str(), &watched.key, 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),
@@ -911,6 +1080,7 @@ mod tests {
DevCardRow {
id: format!("dvc_{}", at.timestamp_millis()),
space_id: "s1".into(),
+ repo: "github.com/demo-org/demo".into(),
kind: kind.into(),
ref_: "pr:1".into(),
head_sha: "abc".into(),
@@ -1073,6 +1243,8 @@ mod tests {
#[test]
fn backup_command_null_clears_and_missing_keeps() {
+ let keep: PutBody = serde_json::from_value(json!({})).unwrap();
+ assert!(keep.on.is_none(), "on keeps its value when missing");
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();
diff --git a/src/server/mod.rs b/src/server/mod.rs
index 323bdca0..42c7b9a1 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -254,6 +254,7 @@ pub fn create_router(state: AppState) -> Router {
.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_mode/seen", post(dev::routes::desk_seen))
+ .route("/api/spaces/:id/dev_mode/repos/*key", delete(dev::routes::delete_repo))
.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))
diff --git a/src/server/routes.rs b/src/server/routes.rs
index fd86c71f..d76af729 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -565,12 +565,14 @@ pub async fn create_team(
) -> Result<Json<Team>, axum::response::Response> {
check_team_name(&state, &space, &mut payload.name, None).await?;
check_workspace(&state, &space, None, &payload).await?;
- state
+ let team = state
.db
.create_team(&space, &payload)
.await
- .map(Json)
- .map_err(|e| db_error(&e, &team_clash(&payload.name)))
+ .map_err(|e| db_error(&e, &team_clash(&payload.name)))?;
+ // Dev mode watches each team's repo (team-repos.md T3)
+ super::dev::repo::reconcile_soon(&state, &space);
+ Ok(Json(team))
}
pub async fn get_team(
@@ -621,6 +623,7 @@ pub async fn update_team(
.map_err(|_| status(StatusCode::INTERNAL_SERVER_ERROR))?;
team.instructions = Some(text.trim().to_string()).filter(|t| !t.is_empty());
}
+ super::dev::repo::reconcile_soon(&state, &space);
Ok(Json(team))
}
Ok(None) => Err(status(StatusCode::NOT_FOUND)),
@@ -632,9 +635,13 @@ pub async fn delete_team(
State(state): State<AppState>,
Path(id): Path<String>,
) -> Result<Json<serde_json::Value>, StatusCode> {
+ let space = state.db.space_of_team(&id).await.ok().flatten();
match state.db.delete_team(&id).await {
Ok(true) => {
super::passwords::forget_deleted_owners(&state, &[&id]).await;
+ if let Some(space) = &space {
+ super::dev::repo::reconcile_soon(&state, space);
+ }
Ok(Json(json!({ "status": "deleted" })))
}
Ok(false) => Err(StatusCode::NOT_FOUND),
diff --git a/tests/dev_autodetect_test.rs b/tests/dev_autodetect_test.rs
index 30d9a748..ea30f9db 100644
--- a/tests/dev_autodetect_test.rs
+++ b/tests/dev_autodetect_test.rs
@@ -135,9 +135,10 @@ async fn an_empty_space_turns_on_with_no_repo_and_the_poller_idles() {
assert!(env.state.db.any_dev_mode_on());
let mode = env.state.db.dev_mode(SpaceId::default_space().as_str()).await.unwrap().unwrap();
assert!(mode.on && mode.repo.is_empty());
- // The poller idles: no read, no error
- poller::poll(&env.state, &mode).await.expect("an empty repo polls clean");
- poller::poll_logged(&env.state, mode).await;
+ // The poller idles: no repo rows, no read, no error
+ assert!(env.state.db.dev_repos(SpaceId::default_space().as_str()).await.unwrap().is_empty());
+ poller::poll_space(&env.state, SpaceId::default_space().as_str()).await;
+ assert!(env.state.db.dev_repos(SpaceId::default_space().as_str()).await.unwrap().is_empty());
let after = env.state.db.dev_mode(SpaceId::default_space().as_str()).await.unwrap().unwrap();
assert_eq!(after.poll_error, None);
@@ -324,7 +325,8 @@ async fn a_detected_repo_wakes_the_poller_counts_new_reviews_and_never_replaces_
assert_eq!(v["sources"], json!([{"team": "Shop", "repo": REPO, "host": host, "from": "folder"}]));
assert!(poller::is_due_soon(space.as_str()), "on with a detected repo wakes the poller");
// ...and that first poll backfills (both commits are within BACKFILL) plus the open PR
- let mode = env.state.db.dev_mode(space.as_str()).await.unwrap().unwrap();
+ let mode = env.state.db.dev_repos(space.as_str()).await.unwrap().remove(0);
+ assert_eq!((mode.added_by.as_str(), mode.key.as_str()), ("team", format!("{host}/{REPO}").as_str()));
poller::poll(&env.state, &mode).await.expect("a clean first 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();
@@ -351,17 +353,21 @@ async fn a_detected_repo_wakes_the_poller_counts_new_reviews_and_never_replaces_
let (_, v) = call(&env.app, "GET", &u, None).await;
assert_eq!(v["new_reviews"], 0, "seen clears the count: {v}");
- // F10: a repo the person typed is kept; the folder's repo never replaces it
+ // F10 (0.7.2): a repo the person typed is watched next to the team's; neither replaces the other
+ let watched = |v: &Value| v["repos"].as_array().unwrap().iter().map(|r| (r["repo"].as_str().unwrap().to_string(), r["added_by"].as_str().unwrap_or("").to_string())).collect::<Vec<_>>();
+ let both = vec![(REPO.to_string(), "team".to_string()), (other.to_string(), "hand".to_string())];
let (s, v) = call(&env.app, "PUT", &u, Some(json!({"on": true, "repo": other}))).await;
- assert_eq!((s.as_u16(), v["repo"].clone()), (200, json!(other)), "{v}");
+ assert_eq!(s.as_u16(), 200, "{v}");
+ assert_eq!(watched(&v), both, "{v}");
+ assert_eq!(v["repo"], json!(REPO), "the deprecated field is the first row's: {v}");
let (_, v) = call(&env.app, "PUT", &u, Some(json!({"on": true}))).await;
- assert_eq!((v["repo"].clone(), v["status"].clone()), (json!(other), json!("watching")), "{v}");
+ assert_eq!((watched(&v), v["status"].clone()), (both.clone(), json!("watching")), "{v}");
let (_, v) = call(&env.app, "PUT", &u, Some(json!({"on": false}))).await;
assert_eq!(v["on"], false);
let (_, v) = call(&env.app, "PUT", &u, Some(json!({"on": true}))).await;
- assert_eq!(v["repo"], json!(other), "off and on again keeps the typed repo: {v}");
+ assert_eq!(watched(&v), both, "off and on again keeps the typed repo: {v}");
let (_, v) = call(&env.app, "GET", &u, None).await;
- assert_eq!((v["repo"].clone(), v["status"].clone()), (json!(other), json!("watching")), "{v}");
+ assert_eq!((watched(&v), v["status"].clone()), (both.clone(), json!("watching")), "{v}");
gh.assert_read_only();
}
@@ -394,8 +400,8 @@ async fn connecting_github_while_on_binds_the_detected_repo_without_off_and_on()
let (_, v) = call(&env.app, "GET", &u, None).await;
assert_eq!(v["repo"], Value::Null, "no connection yet: {v}");
// The wake from turning on has been taken by a poll, which had nothing to read
- let mode = env.state.db.dev_mode(space.as_str()).await.unwrap().unwrap();
- poller::poll(&env.state, &mode).await.unwrap();
+ assert!(env.state.db.dev_repos(space.as_str()).await.unwrap().is_empty(), "no connection, no row");
+ poller::poll_space(&env.state, space.as_str()).await;
poller::take_due_soon(space.as_str());
assert!(!poller::is_due_soon(space.as_str()));
@@ -407,7 +413,7 @@ async fn connecting_github_while_on_binds_the_detected_repo_without_off_and_on()
let (_, v) = call(&env.app, "GET", &u, None).await;
assert_eq!((v["on"].clone(), v["repo"].clone(), v["branch"].clone(), v["status"].clone()), (json!(true), json!(REPO), json!("main"), json!("watching")), "{v}");
assert_eq!(v["deploy_hint"], "fly");
- let mode = env.state.db.dev_mode(space.as_str()).await.unwrap().unwrap();
+ let mode = env.state.db.dev_repos(space.as_str()).await.unwrap().remove(0);
poller::poll(&env.state, &mode).await.expect("the bound repo polls");
assert_eq!(env.state.db.dev_cards(space.as_str(), LANDED, None, 50).await.unwrap().len(), 2, "the first poll backfilled");
@@ -430,8 +436,9 @@ async fn connecting_github_while_on_binds_the_detected_repo_without_off_and_on()
let (s, v) = call(&env.app, "PATCH", &format!("/api/zombie/sources/{id}"), Some(json!({"label": "GitHub (work)"}))).await;
assert_eq!(s.as_u16(), 200, "{v}");
for s in [&changed, &read] {
- let m = env.state.db.dev_mode(s.as_str()).await.unwrap().unwrap();
- assert_eq!((m.on, m.repo.as_str(), m.branch.as_str()), (true, REPO, "main"), "the source change bound {}", s.as_str());
+ let rows = env.state.db.dev_repos(s.as_str()).await.unwrap();
+ let got: Vec<_> = rows.iter().map(|r| (r.repo.as_str(), r.branch.as_str(), r.added_by.as_str())).collect();
+ assert_eq!(got, vec![(REPO, "main", "team")], "the source change bound {}", s.as_str());
}
// When no source change happened, the GET falls back to the same binding
let late = SpaceId::new(env.state.db.create_space(&mk("Late")).await.unwrap().id);
diff --git a/tests/dev_card_route_test.rs b/tests/dev_card_route_test.rs
index 63b90ed1..5b438650 100644
--- a/tests/dev_card_route_test.rs
+++ b/tests/dev_card_route_test.rs
@@ -8,7 +8,7 @@ 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;
+use serde_json::{json, Value};
/// A turn token of bot `a`, as its CLI holds it.
async fn turn_token(env: &Env) -> String {
@@ -37,7 +37,9 @@ async fn a_release_notes_draft_is_read_by_id() {
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}");
+ assert!(v["created_at"].is_string() && v.get("markdown").is_none() && v.get("since_tag").is_none() && v.get("cards").is_none(), "{v}");
+ // 0.7.2: every card names its repo (key, label, team); a 0.7.1 card made with no repo has key ""
+ assert_eq!((v["repo"].clone(), v["repo_name"].clone(), v["team"].clone()), (json!(""), json!("demo-org/demo-app"), Value::Null), "{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"});
diff --git a/tests/dev_github_test.rs b/tests/dev_github_test.rs
index 17ff2ff3..14bbbdd5 100644
--- a/tests/dev_github_test.rs
+++ b/tests/dev_github_test.rs
@@ -246,7 +246,7 @@ async fn the_github_token_never_leaves_the_vault() {
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();
+ let mode = env.state.db.dev_repos(space.as_str()).await.unwrap().remove(0);
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();
@@ -256,10 +256,10 @@ async fn the_github_token_never_leaves_the_vault() {
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();
+ let mode = env.state.db.dev_repos(space.as_str()).await.unwrap().remove(0);
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();
+ let after = env.state.db.dev_repos(space.as_str()).await.unwrap().remove(0);
errors.push(after.poll_error.clone().unwrap_or_else(|| panic!("{fault:?} left no poll error")));
}
gh.heal(R);
diff --git a/tests/dev_stale_guard_test.rs b/tests/dev_stale_guard_test.rs
index b43a0f61..738fabbd 100644
--- a/tests/dev_stale_guard_test.rs
+++ b/tests/dev_stale_guard_test.rs
@@ -75,7 +75,7 @@ async fn a_review_that_finishes_after_its_pr_merged_stays_stale() {
assert_eq!(s.as_u16(), 200, "{v}");
// Poll 1: the review card for PR #5, under the poller's own ref
- let mode = env.state.db.dev_mode(space.as_str()).await.unwrap().unwrap();
+ let mode = env.state.db.dev_repos(space.as_str()).await.unwrap().remove(0);
poller::poll(&env.state, &mode).await.expect("a clean poll");
cards_written(&env).await;
let reviews = env.state.db.dev_cards(space.as_str(), REVIEW, None, 50).await.unwrap();
@@ -97,7 +97,7 @@ async fn a_review_that_finishes_after_its_pr_merged_stays_stale() {
.json(&format!("{R}/commits/{merge}/check-runs"), green.clone())
.json(&format!("{R}/commits"), json!([c, direct.clone()]))
.json(&format!("{R}/pulls"), json!([]));
- let mode = env.state.db.dev_mode(space.as_str()).await.unwrap().unwrap();
+ let mode = env.state.db.dev_repos(space.as_str()).await.unwrap().remove(0);
poller::poll(&env.state, &mode).await.expect("a clean poll");
cards_written(&env).await;
let before = env.state.db.dev_card(&rid).await.unwrap().unwrap();
diff --git a/tests/dev_team_repos_test.rs b/tests/dev_team_repos_test.rs
new file mode 100644
index 00000000..e79ec43f
--- /dev/null
+++ b/tests/dev_team_repos_test.rs
@@ -0,0 +1,419 @@
+//! Dev mode watches every team's repo (0.7.2, plan team-repos.md T1–T9), against the mock GitHub
+//! only: two teams with two repos in one space, PR #12 in both, a repo that fails next to one that
+//! works, the 10-repo cap, a 0.7.1 row taken over by its team, and the routes' error codes.
+//!
+//! Each test has a space of its own, so the poller's per-space state (wake list, back-off, tags)
+//! is that test's alone. No real GitHub is called: every connection points at the mock.
+
+mod common;
+#[path = "support/mock_github.rs"]
+mod mock_github;
+
+use common::*;
+use kwnt::db::dev_mode::{repo_key, BY_MIGRATION, LANDED, MAX_REPOS, READY, REVIEW};
+use kwnt::db::models::{NewKwant, NewTeam};
+use kwnt::db::spaces::{NewSpace, SpaceId};
+use kwnt::server::dev::{poller, repo};
+use mock_github::*;
+use serde_json::{json, Value};
+
+const APP: &str = "demo-org/app";
+const SITE: &str = "demo-org/site";
+const TOOLS: &str = "demo-org/tools";
+
+fn sha(n: u8) -> String {
+ format!("{n:0>40}")
+}
+
+/// One repo on the mock: a commit on main and open PR #12 at the same head in every repo, so only
+/// the repo tells their cards apart.
+fn seed(gh: &MockGithub, name: &str) {
+ let r = format!("/repos/{name}");
+ let person = ("Lin (kwant bot)", "[email protected]");
+ let patch = "@@ -1,2 +1,2 @@\n-let retries = 1;\n+let retries = 3;";
+ let green = check_runs(&[("rust", "completed", Some("success"))]);
+ let mut first = commit(&sha(1), "Fix the README", person, &[], "2026-11-05T01:00:00Z");
+ gh.json(&r, repo(name, "main"))
+ .json(&format!("{r}/contents"), json!([{"name": "Cargo.toml", "type": "file"}]))
+ .json(&format!("{r}/branches/main"), json!({"name": "main"}))
+ .json(&format!("{r}/tags"), json!([]))
+ .json(&format!("{r}/commits"), json!([first.clone()]));
+ first["files"] = json!([file("README.md", "modified", "-old\n+new")]);
+ gh.json(&format!("{r}/commits/{}", sha(1)), first)
+ .json(&format!("{r}/commits/{}/pulls", sha(1)), json!([]))
+ .json(&format!("{r}/commits/{}/check-runs", sha(1)), green.clone())
+ .json(&format!("{r}/pulls"), json!([pull(12, "Add a cache", ("cache", &sha(3)), "main", "demo-person", None)]))
+ .json(&format!("{r}/pulls/12"), pull(12, "Add a cache", ("cache", &sha(3)), "main", "demo-person", None))
+ .json(&format!("{r}/pulls/12/files"), json!([file("src/cache.rs", "modified", patch)]))
+ .json(&format!("{r}/commits/{}", sha(3)), commit(&sha(3), "Add a cache", person, &[&sha(1)], "2026-11-05T03:00:00Z"))
+ .json(&format!("{r}/commits/{}/check-runs", sha(3)), green);
+}
+
+struct Space {
+ id: SpaceId,
+ lead: String,
+}
+
+/// A new space, a GitHub connection to the mock, and the token the mock wants.
+async fn space(env: &Env, gh: &MockGithub, name: &str) -> Space {
+ let s = env.state.db.create_space(&NewSpace { name: name.into(), icon: "S".into(), color: None, this_machine_enabled: true }).await.unwrap();
+ let id = SpaceId::new(s.id);
+ for s in [&id, &SpaceId::default_space()] {
+ env.state.db.set_space_approvals(s, "ask").await.unwrap();
+ }
+ let k = NewKwant {
+ name: format!("{name} lead"),
+ title: "Lead".into(),
+ persona_prompt: "Test persona".into(),
+ soul: String::new(),
+ avatar_sprite: "s".into(),
+ driver_type: "api".into(),
+ preferred_model: "claude".into(),
+ };
+ let lead = env.state.db.create_kwant(&id, &k).await.unwrap().id;
+ let token = canary_token();
+ gh.require_token(&token);
+ gh.json("/user", user("demo-person"));
+ 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}");
+ Space { id, lead }
+}
+
+/// A team of `space` whose repo link is `name` on the mock (`None`: no link).
+async fn team(env: &Env, space: &Space, team: &str, gh: &MockGithub, name: Option<&str>) -> String {
+ let t = NewTeam {
+ name: team.into(),
+ description: None,
+ icon: None,
+ lead_kwant_id: space.lead.clone(),
+ member_kwants: vec![space.lead.clone()],
+ workspace_path: None,
+ repo_url: name.map(|n| format!("{}/{n}", gh.base)),
+ };
+ env.state.db.create_team(&space.id, &t).await.unwrap().id
+}
+
+fn host(gh: &MockGithub) -> String {
+ gh.base.trim_start_matches("http://").split(':').next().unwrap().to_string()
+}
+
+fn uri(space: &Space) -> String {
+ format!("/api/spaces/{}/dev_mode", space.id.as_str())
+}
+
+/// `(repo, team, status, added_by)` of each `repos[]` row.
+fn rows(v: &Value) -> Vec<(String, String, String, String)> {
+ let s = |x: &Value| x.as_str().unwrap_or("-").to_string();
+ v["repos"].as_array().unwrap_or_else(|| panic!("no repos[]: {v}")).iter().map(|r| (s(&r["repo"]), s(&r["team"]), s(&r["status"]), s(&r["added_by"]))).collect()
+}
+
+fn row(repo: &str, team: &str, status: &str, by: &str) -> (String, String, String, String) {
+ (repo.into(), team.into(), status.into(), by.into())
+}
+
+fn enc(key: &str) -> String {
+ key.replace('/', "%2F")
+}
+
+fn review_card() -> Value {
+ json!({
+ "kind": "review", "pr": 12, "title": "Add a cache",
+ "reviewer": {"id": "kw_v", "name": "Vega", "engine": "codex", "model": "gpt"},
+ "risk": {"level": "low", "reasons": []},
+ "intent": {"source": "pr", "asked": "A cache", "rows": [], "none": true},
+ "tamper": {"flags": [], "unread": []},
+ "security": {"secrets": {"state": "pass", "count": 0, "missing": 0}, "packages": {"state": "pass", "count": 0, "missing": 0}, "osv": {"state": "later"}, "semgrep": {"state": "later"}},
+ "findings": [],
+ })
+}
+
+/// T1, T3, T5, T6, T8: two teams, two repos, PR #12 in both is two cards; each card posts to its
+/// own repo; the card lists filter by repo; a team's link change adds and removes its row.
+#[tokio::test]
+async fn two_teams_two_repos_and_pr_12_in_both_is_two_cards() {
+ let env = setup().await;
+ let gh = MockGithub::start(&[0]).await;
+ seed(&gh, APP);
+ seed(&gh, SITE);
+ seed(&gh, TOOLS);
+ let sp = space(&env, &gh, "Two teams").await;
+ team(&env, &sp, "App", &gh, Some(APP)).await;
+ let site_team = team(&env, &sp, "Site", &gh, Some(SITE)).await;
+ let h = host(&gh);
+ let (app_key, site_key) = (repo_key(&h, APP), repo_key(&h, SITE));
+
+ // Off: nothing is fetched, both show what on would watch
+ let (s, v) = call(&env.app, "GET", &uri(&sp), None).await;
+ assert_eq!(s.as_u16(), 200, "{v}");
+ assert_eq!(rows(&v), vec![row(APP, "App", "watching", "-"), row(SITE, "Site", "watching", "-")], "{v}");
+ assert!(env.state.db.dev_repos(sp.id.as_str()).await.unwrap().is_empty(), "off reads only");
+
+ // On: a team row for each, in team order
+ let (s, v) = call(&env.app, "PUT", &uri(&sp), Some(json!({"on": true}))).await;
+ assert_eq!(s.as_u16(), 200, "{v}");
+ assert_eq!(rows(&v), vec![row(APP, "App", "watching", "team"), row(SITE, "Site", "watching", "team")], "{v}");
+ assert_eq!((v["repos"][0]["key"].clone(), v["repos"][1]["team_id"].clone()), (json!(app_key), json!(site_team)), "{v}");
+ assert_eq!((v["status"].clone(), v["repo"].clone(), v["branch"].clone()), (json!("watching"), json!(APP), json!("main")), "deprecated fields are the first row's: {v}");
+ assert!(poller::is_due_soon(sp.id.as_str()));
+
+ // The desk is opened before the first reviews (#357: its own seen time)
+ let (s, v) = call(&env.app, "POST", &format!("{}/seen", uri(&sp)), None).await;
+ assert_eq!(s.as_u16(), 200, "{v}");
+
+ // One poll of the space reads both: PR #12 in each is its own card
+ poller::poll_space(&env.state, sp.id.as_str()).await;
+ let reviews = env.state.db.dev_cards_in(sp.id.as_str(), None, REVIEW, None, 50).await.unwrap();
+ let mut got: Vec<_> = reviews.iter().map(|c| (c.repo.clone(), c.ref_.clone(), c.head_sha.clone())).collect();
+ got.sort();
+ assert_eq!(got, vec![(app_key.clone(), "pr:12".into(), sha(3)), (site_key.clone(), "pr:12".into(), sha(3))]);
+ assert_eq!(env.state.db.dev_cards_in(sp.id.as_str(), None, LANDED, None, 50).await.unwrap().len(), 2);
+ for r in env.state.db.dev_repos(sp.id.as_str()).await.unwrap() {
+ assert_eq!((r.last_seen_sha.as_deref(), r.poll_error.as_deref()), (Some(sha(1).as_str()), None), "{}", r.key);
+ }
+ // A second poll makes nothing new
+ poller::poll_space(&env.state, sp.id.as_str()).await;
+ assert_eq!(env.state.db.dev_cards_in(sp.id.as_str(), None, REVIEW, None, 50).await.unwrap().len(), 2);
+
+ // The badge is the space's total over every repo; Mark seen (the rollup) leaves it, opening the
+ // desk clears it. The cards' own text runs first, so it can't overwrite the status set here
+ wait_for("the cards' text", || async { env.state.db.pending_dev_cards().await.map(|p| p.is_empty()).unwrap_or(false) }).await;
+ for c in &reviews {
+ env.state.db.set_dev_card(&c.id, READY, Some(&review_card().to_string())).await.unwrap().unwrap();
+ }
+ let badge = |v: &Value| v["new_reviews"].clone();
+ let (_, v) = call(&env.app, "GET", &uri(&sp), None).await;
+ assert_eq!(badge(&v), json!(2), "PR #12 in both repos: {v}");
+ let (s, v) = call(&env.app, "POST", &format!("/api/spaces/{}/dev/landed/seen", sp.id.as_str()), None).await;
+ assert_eq!(s.as_u16(), 200, "{v}");
+ let (_, v) = call(&env.app, "GET", &uri(&sp), None).await;
+ assert_eq!(badge(&v), json!(2), "Mark seen moves only the rollup: {v}");
+ let (s, v) = call(&env.app, "POST", &format!("{}/seen", uri(&sp)), None).await;
+ assert_eq!(s.as_u16(), 200, "{v}");
+ let (_, v) = call(&env.app, "GET", &uri(&sp), None).await;
+ assert_eq!(badge(&v), json!(0), "{v}");
+
+ // The lists: every repo, or one with ?repo= (encoded or not)
+ let base = format!("/api/spaces/{}/dev", sp.id.as_str());
+ let (_, v) = call(&env.app, "GET", &format!("{base}/reviews"), None).await;
+ let cards = v["cards"].as_array().unwrap_or_else(|| panic!("{v}")).clone();
+ assert_eq!(cards.len(), 2, "{v}");
+ for c in &cards {
+ let (team, name) = if c["repo"] == json!(app_key) { ("App", APP) } else { ("Site", SITE) };
+ assert_eq!((c["team"].clone(), c["repo_name"].clone(), c["pr"].clone()), (json!(team), json!(name), json!(12)), "{c}");
+ }
+ for q in [enc(&site_key), site_key.clone()] {
+ let (s, v) = call(&env.app, "GET", &format!("{base}/reviews?repo={q}"), None).await;
+ assert_eq!(s.as_u16(), 200, "{v}");
+ let list = v["cards"].as_array().unwrap().clone();
+ assert_eq!(list.iter().map(|c| c["repo"].clone()).collect::<Vec<_>>(), vec![json!(site_key)], "{v}");
+ }
+ let (_, v) = call(&env.app, "GET", &format!("{base}/landed?repo={}", enc(&app_key)), None).await;
+ let landed = v["cards"].as_array().or_else(|| v["landed"].as_array()).unwrap_or_else(|| panic!("{v}")).clone();
+ assert_eq!(landed.iter().map(|c| c["repo"].clone()).collect::<Vec<_>>(), vec![json!(app_key)], "{v}");
+ let (s, v) = call(&env.app, "GET", &format!("{base}/landed?repo=github.com%2Fnobody%2Fhere"), None).await;
+ assert_eq!(s.as_u16(), 200, "{v}");
+ assert_eq!(v["cards"].as_array().or_else(|| v["landed"].as_array()).map(Vec::len), Some(0), "an unknown repo is an empty list: {v}");
+
+ // T6: posting the Site card writes to Site's PR #12 only
+ let site_card = reviews.iter().find(|c| c.repo == site_key).unwrap();
+ env.state.db.set_dev_card(&site_card.id, READY, Some(&review_card().to_string())).await.unwrap();
+ let to = format!("/repos/{SITE}/pulls/12/reviews");
+ gh.accept_write("POST", &to, 200, json!({"id": 7, "user": user("demo-person"), "body": "…", "commit_id": sha(3), "state": "COMMENTED", "html_url": "https://github.example/demo-org/site/pull/12#pullrequestreview-7"}));
+ let (s, v) = call(&env.app, "POST", &format!("/api/dev/cards/{}/post", site_card.id), None).await;
+ assert_eq!(s.as_u16(), 200, "{v}");
+ assert!(v["posted"].is_object() || v["posted"].is_string(), "posted: {v}");
+ assert_eq!(gh.writes().iter().map(|w| w.path.clone()).collect::<Vec<_>>(), vec![to.clone()]);
+ gh.assert_no_unexpected_writes();
+
+ // A hand repo next to them; DELETE removes only a hand row
+ let (s, v) = call(&env.app, "PUT", &uri(&sp), Some(json!({"repo": TOOLS}))).await;
+ assert_eq!(s.as_u16(), 200, "{v}");
+ assert_eq!(rows(&v).last().unwrap(), &row(TOOLS, "-", "watching", "hand"), "{v}");
+ let tools_key = repo_key(&h, TOOLS);
+ let (s, v) = call(&env.app, "DELETE", &format!("{}/repos/{}", uri(&sp), enc(&app_key)), None).await;
+ assert_eq!((s.as_u16(), v["code"].clone()), (409, json!("team_repo")), "{v}");
+ let (s, v) = call(&env.app, "DELETE", &format!("{}/repos/{}", uri(&sp), enc("github.com/nobody/here")), None).await;
+ assert_eq!((s.as_u16(), v["code"].clone()), (404, json!("unknown_repo")), "{v}");
+ let (s, v) = call(&env.app, "DELETE", &format!("{}/repos/{}", uri(&sp), tools_key), None).await;
+ assert_eq!(s.as_u16(), 200, "raw slashes work too: {v}");
+ assert_eq!(rows(&v).len(), 2, "{v}");
+
+ // T3 remove: clearing Site's link stops watching it; its cards stay with their repo
+ let (s, v) = call(&env.app, "PUT", &uri(&sp), Some(json!({"repo": "", "team": "Site"}))).await;
+ assert_eq!(s.as_u16(), 200, "{v}");
+ assert_eq!(rows(&v), vec![row(APP, "App", "watching", "team")], "{v}");
+ assert_eq!(env.state.db.dev_cards_in(sp.id.as_str(), Some(&site_key), REVIEW, None, 50).await.unwrap().len(), 1);
+ let (_, v) = call(&env.app, "GET", &format!("/api/dev/cards/{}", site_card.id), None).await;
+ assert_eq!((v["repo_name"].clone(), v["team"].clone()), (json!(SITE), Value::Null), "a removed repo keeps its label: {v}");
+
+ // T3 keep: App's row is the same row, its place kept
+ let before = env.state.db.dev_repo(sp.id.as_str(), &app_key).await.unwrap().unwrap();
+ // T3 add, by the team's id, with userinfo that is never stored or returned
+ let secret = secret_like("ghp_", 36);
+ let (s, v) = call(&env.app, "PUT", &uri(&sp), Some(json!({"repo": format!("http://demo:{secret}@{}/{SITE}", gh.base.trim_start_matches("http://")), "team": site_team}))).await;
+ assert_eq!(s.as_u16(), 200, "{v}");
+ assert_eq!(rows(&v), vec![row(APP, "App", "watching", "team"), row(SITE, "Site", "watching", "team")], "{v}");
+ assert!(!v.to_string().contains(&secret));
+ let teams = env.state.db.list_teams(&sp.id).await.unwrap();
+ let link = teams.iter().find(|t| t.id == site_team).unwrap().repo_url.clone().unwrap();
+ assert!(!link.contains(&secret) && !link.contains('@'), "{link}");
+ assert_eq!(env.state.db.dev_repo(sp.id.as_str(), &app_key).await.unwrap().unwrap(), before, "a kept row is untouched");
+
+ // Deleting a team stops watching its repo (in the background: the route doesn't wait)
+ let (s, _) = call(&env.app, "DELETE", &format!("/api/teams/{site_team}"), None).await;
+ assert_eq!(s.as_u16(), 200);
+ wait_for("the Site row to go", || async { env.state.db.dev_repo(sp.id.as_str(), &site_key).await.unwrap().is_none() }).await;
+ gh.assert_no_unexpected_writes();
+}
+
+/// T5: a repo that fails records its own error, and the next one is still read.
+#[tokio::test]
+async fn one_failing_repo_does_not_stop_the_other() {
+ let env = setup().await;
+ let gh = MockGithub::start(&[0]).await;
+ seed(&gh, APP);
+ seed(&gh, SITE);
+ let sp = space(&env, &gh, "One fails").await;
+ team(&env, &sp, "App", &gh, Some(APP)).await;
+ team(&env, &sp, "Site", &gh, Some(SITE)).await;
+ let h = host(&gh);
+ let (app_key, site_key) = (repo_key(&h, APP), repo_key(&h, SITE));
+ let (s, v) = call(&env.app, "PUT", &uri(&sp), Some(json!({"on": true}))).await;
+ assert_eq!(s.as_u16(), 200, "{v}");
+ assert_eq!(env.state.db.dev_repos(sp.id.as_str()).await.unwrap().first().map(|r| r.key.clone()), Some(app_key.clone()), "App is read first");
+
+ for fault in [Fault::Server(502), Fault::Forbidden, Fault::Unauthorized] {
+ gh.fault(&format!("/repos/{APP}/commits"), fault.clone());
+ poller::poll_space(&env.state, sp.id.as_str()).await;
+ let app = env.state.db.dev_repo(sp.id.as_str(), &app_key).await.unwrap().unwrap();
+ let site = env.state.db.dev_repo(sp.id.as_str(), &site_key).await.unwrap().unwrap();
+ assert!(app.poll_error.is_some(), "{fault:?}: App records its error");
+ assert_eq!((site.poll_error.as_deref(), site.last_seen_sha.as_deref()), (None, Some(sha(1).as_str())), "{fault:?}: Site is still read");
+ assert!(site.polled_at.is_some());
+ }
+ assert_eq!(env.state.db.dev_cards_in(sp.id.as_str(), Some(&site_key), REVIEW, None, 50).await.unwrap().len(), 1);
+ assert!(env.state.db.dev_cards_in(sp.id.as_str(), Some(&app_key), LANDED, None, 50).await.unwrap().is_empty());
+
+ // The desk: App says error with why, Site watching; the space is still watching
+ let (_, v) = call(&env.app, "GET", &uri(&sp), None).await;
+ assert_eq!(rows(&v), vec![row(APP, "App", "error", "team"), row(SITE, "Site", "watching", "team")], "{v}");
+ assert!(v["repos"][0]["poll_error"].is_string() && v["repos"][1]["poll_error"].is_null(), "{v}");
+ assert_eq!(v["status"], "watching");
+ assert!(!v.to_string().contains(&gh.base), "no mock URL in the reply: {v}");
+
+ // Healed: the error clears on the next poll
+ gh.heal(&format!("/repos/{APP}/commits"));
+ poller::poll_space(&env.state, sp.id.as_str()).await;
+ let app = env.state.db.dev_repo(sp.id.as_str(), &app_key).await.unwrap().unwrap();
+ assert_eq!((app.poll_error.as_deref(), app.last_seen_sha.as_deref()), (None, Some(sha(1).as_str())));
+
+ // A rate limit is the token's, so it backs off the whole space (both repos wait)
+ gh.fault(&format!("/repos/{APP}/commits"), Fault::TooMany { retry_after: Some(120) });
+ let site_before = env.state.db.dev_repo(sp.id.as_str(), &site_key).await.unwrap().unwrap().polled_at;
+ poller::poll_space(&env.state, sp.id.as_str()).await;
+ assert!(env.state.db.dev_repo(sp.id.as_str(), &app_key).await.unwrap().unwrap().poll_error.is_some());
+ assert_eq!(env.state.db.dev_repo(sp.id.as_str(), &site_key).await.unwrap().unwrap().polled_at, site_before, "Site waits out the limit too");
+ gh.assert_read_only();
+}
+
+/// T4: at most 10 repos a space; the 11th team's repo shows `too_many`, and a hand repo past the
+/// cap is refused with 409 `too_many`.
+#[tokio::test]
+async fn a_space_watches_at_most_ten_repos() {
+ let env = setup().await;
+ let gh = MockGithub::start(&[0]).await;
+ let sp = space(&env, &gh, "Many").await;
+ let names: Vec<String> = (0..=MAX_REPOS).map(|i| format!("demo-org/r{i:02}")).collect();
+ for (i, n) in names.iter().enumerate() {
+ seed(&gh, n);
+ team(&env, &sp, &format!("Team {i:02}"), &gh, Some(n)).await;
+ }
+ seed(&gh, TOOLS);
+ let (s, v) = call(&env.app, "PUT", &uri(&sp), Some(json!({"on": true}))).await;
+ assert_eq!(s.as_u16(), 200, "{v}");
+ let got = rows(&v);
+ assert_eq!(got.len(), MAX_REPOS + 1, "{v}");
+ assert_eq!(got.iter().filter(|r| r.2 == "watching" && r.3 == "team").count(), MAX_REPOS, "{v}");
+ assert_eq!(got.last().unwrap(), &row(&names[MAX_REPOS], &format!("Team {MAX_REPOS:02}"), "too_many", "-"), "{v}");
+ assert_eq!(env.state.db.dev_repos(sp.id.as_str()).await.unwrap().len(), MAX_REPOS);
+
+ let (s, v) = call(&env.app, "PUT", &uri(&sp), Some(json!({"repo": TOOLS}))).await;
+ assert_eq!((s.as_u16(), v["code"].clone()), (409, json!("too_many")), "{v}");
+ assert_eq!(env.state.db.dev_repos(sp.id.as_str()).await.unwrap().len(), MAX_REPOS);
+
+ // Clearing one team's link makes room for the 11th at the next reconcile
+ let (s, v) = call(&env.app, "PUT", &uri(&sp), Some(json!({"repo": "", "team": "Team 00"}))).await;
+ assert_eq!(s.as_u16(), 200, "{v}");
+ let got = rows(&v);
+ assert_eq!(got.len(), MAX_REPOS, "{v}");
+ assert!(got.iter().all(|r| r.2 == "watching"), "{v}");
+ gh.assert_read_only();
+}
+
+/// T2 + T3: a space's 0.7.1 repo, migrated as `github.com/…`, is taken over by the team that points
+/// at it on another GitHub host: re-keyed with its cards, its place kept, nothing announced again.
+#[tokio::test]
+async fn a_migrated_repo_becomes_its_teams_row_and_nothing_is_announced_again() {
+ let env = setup().await;
+ let gh = MockGithub::start(&[0]).await;
+ seed(&gh, APP);
+ let sp = space(&env, &gh, "Migrated").await;
+ let s = sp.id.as_str();
+ // As the migration leaves a 0.7.1 space: one row with its place, and its old card
+ env.state.db.set_dev_mode(s, false, None, None).await.unwrap();
+ let old = repo_key("github.com", APP);
+ env.state.db.add_dev_repo(s, &old, None, APP, Some("github.com"), "main", None, BY_MIGRATION).await.unwrap();
+ env.state.db.dev_repo_polled(s, &old, Some(&sha(1)), None).await.unwrap();
+ env.state.db.insert_dev_card_in(s, &old, LANDED, &sha(1), &sha(1), &json!({"repo": APP}).to_string()).await.unwrap().unwrap();
+ assert_eq!(env.state.db.dev_repo(s, &old).await.unwrap().unwrap().added_by_shown(), "hand", "until a reconcile it reads as hand");
+
+ // The team was there in 0.7.1 too (its link is what the space watched); the first read settles it
+ let team_id = team(&env, &sp, "App", &gh, Some(APP)).await;
+ let (_, v) = call(&env.app, "GET", &uri(&sp), None).await;
+ assert_eq!(rows(&v), vec![row(APP, "App", "watching", "team")], "{v}");
+ let (s2, v) = call(&env.app, "PUT", &uri(&sp), Some(json!({"on": true}))).await;
+ assert_eq!(s2.as_u16(), 200, "{v}");
+ assert_eq!(rows(&v), vec![row(APP, "App", "watching", "team")], "{v}");
+ let new = repo_key(&host(&gh), APP);
+ let r = env.state.db.dev_repo(s, &new).await.unwrap().expect("re-keyed to the team's host");
+ assert_eq!((r.team.as_deref(), r.last_seen_sha.as_deref()), (Some(team_id.as_str()), Some(sha(1).as_str())));
+ assert!(env.state.db.dev_repo(s, &old).await.unwrap().is_none());
+ assert_eq!(env.state.db.dev_cards_in(s, Some(&new), LANDED, None, 10).await.unwrap().len(), 1, "its cards moved with it");
+
+ poller::poll_space(&env.state, s).await;
+ assert_eq!(env.state.db.dev_cards_in(s, None, LANDED, None, 10).await.unwrap().len(), 1, "the commit it had seen isn't announced again");
+ assert_eq!(env.state.db.dev_cards_in(s, None, REVIEW, None, 10).await.unwrap().len(), 1, "the open PR is new");
+ // A plain reconcile later changes nothing
+ let done = repo::reconcile(&env.state, &sp.id).await;
+ assert!(done.added.is_empty() && done.removed.is_empty() && done.too_many.is_empty());
+ gh.assert_read_only();
+}
+
+/// T8: the route errors carry their codes.
+#[tokio::test]
+async fn the_routes_say_what_went_wrong() {
+ let env = setup().await;
+ let gh = MockGithub::start(&[0]).await;
+ seed(&gh, APP);
+ let sp = space(&env, &gh, "Codes").await;
+ team(&env, &sp, "App", &gh, Some(APP)).await;
+ let u = uri(&sp);
+ for (body, status, code) in [
+ (json!({"repo": "not a repo at all"}), 400, "bad_repo"),
+ (json!({"repo": APP, "team": "Nobody"}), 400, "unknown_team"),
+ (json!({"repo": "nope", "team": "App"}), 400, "bad_repo"),
+ (json!({"branch": "bad..branch"}), 400, "bad_branch"),
+ (json!({"backup_command": "x".repeat(2001)}), 400, "backup_too_long"),
+ ] {
+ let (s, v) = call(&env.app, "PUT", &u, Some(body.clone())).await;
+ assert_eq!((s.as_u16(), v["code"].clone()), (status, json!(code)), "{body}: {v}");
+ assert!(v["error"].is_string());
+ }
+ let (s, v) = call(&env.app, "POST", &format!("/api/spaces/{}/dev/release_notes", sp.id.as_str()), None).await;
+ assert_eq!((s.as_u16(), v["code"].clone()), (409, json!("off")), "{v}");
+ let (s, v) = call(&env.app, "PUT", &u, Some(json!({"on": true}))).await;
+ assert_eq!(s.as_u16(), 200, "{v}");
+ let (s, v) = call(&env.app, "PUT", &u, Some(json!({"repo": APP, "branch": "no-such-branch"}))).await;
+ assert_eq!((s.as_u16(), v["code"].clone()), (400, json!("no_branch")), "{v}");
+ gh.assert_read_only();
+}
diff --git a/tests/dev_verified_test.rs b/tests/dev_verified_test.rs
index 0c5ea203..b4d3319f 100644
--- a/tests/dev_verified_test.rs
+++ b/tests/dev_verified_test.rs
@@ -84,7 +84,7 @@ async fn a_merged_pr_takes_its_reviewer_from_the_review_of_the_merged_head() {
assert_eq!(s.as_u16(), 200, "{v}");
// Poll 1: a review card for each open PR, under the poller's own ref
- let mode = env.state.db.dev_mode(space.as_str()).await.unwrap().unwrap();
+ let mode = env.state.db.dev_repos(space.as_str()).await.unwrap().remove(0);
poller::poll(&env.state, &mode).await.expect("a clean poll");
cards_written(&env).await;
let reviews = env.state.db.dev_cards(space.as_str(), REVIEW, None, 50).await.unwrap();
@@ -113,7 +113,7 @@ async fn a_merged_pr_takes_its_reviewer_from_the_review_of_the_merged_head() {
gh.json(&format!("{R}/commits"), Value::Array(list)).json(&format!("{R}/pulls"), json!([]));
// Poll 2: three landed cards; the merge stales every review
- let mode = env.state.db.dev_mode(space.as_str()).await.unwrap().unwrap();
+ let mode = env.state.db.dev_repos(space.as_str()).await.unwrap().remove(0);
poller::poll(&env.state, &mode).await.expect("a clean poll");
cards_written(&env).await;
let reviews = env.state.db.dev_cards(space.as_str(), REVIEW, None, 50).await.unwrap();