Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Mission Control: checks that wait (exit 75) for outside services (#564)
Oleksandr Ivanchenko4c62ae88441b
diff --git a/docs/mission-control.md b/docs/mission-control.mdindex 6119f726..22f73299 100644--- a/docs/mission-control.md+++ b/docs/mission-control.md@@ -93,8 +93,8 @@ outcome_checks(id, task_id, kind, spec JSON, required, approved, status, output_| kind | spec | passes when | who may add it ||---|---|---|---|-| `command` | `{"command": "cargo test -q", "timeout_secs": 300}` | exit code 0. Runs in the mission's folder with `bash -c`. | The person, or a bot in `mission_plan` (approved with the mission). A bot adding one later gets `approved:false`, and it runs only after the person approves it. |-| `http` | `{"url": "https://…", "expect_status": 200, "contains": "optional text"}` | GET returns the status (default any 2xx) and the text if given | Anyone. A URL on this computer or a private network needs the person's approval (same rule as WebFetch). |+| `command` | `{"command": "cargo test -q", "timeout_secs": 300, "recheck_mins?": 15, "wait_hours?": 72}` | exit code 0. Exit 75 means "not ready yet" (the check waits, below); any other code fails. Runs in the mission's folder with `bash -c`. | The person, or a bot in `mission_plan` (approved with the mission). A bot adding one later gets `approved:false`, and it runs only after the person approves it. |+| `http` | `{"url": "https://…", "expect_status": 200, "contains": "optional text", "waiting_status?": 202, "waiting_contains?": "pending", "recheck_mins?": 15, "wait_hours?": 72}` | GET returns the status (default any 2xx) and the text if given. A `waiting_status` reply, or a body with `waiting_contains`, means "not ready yet" and wins over pass or fail. | Anyone. A URL on this computer or a private network needs the person's approval (same rule as WebFetch). || `file_exists` | `{"path": "dist/app.dmg"}` | the file exists inside the mission's folder | Anyone (the task's own bot: see below) || `file_contains` | `{"path": "CHANGELOG.md", "text": "0.1.4"}` | the file contains the text | Anyone || `file_sha256` | `{"path": "out.zip", "sha256": "…"}` | the hash matches | Anyone |@@ -104,8 +104,8 @@ outcome_checks(id, task_id, kind, spec JSON, required, approved, status, output_- Paths are relative to the mission's folder (the team's workspace when the mission came from a teamchat, else the lead bot's folder). `..`, absolute paths outside it, symlinks out of it andpassword/key files are refused.-- `status`: `pending` | `needs_approval` | `running` | `passed` | `failed` | `error` (couldn't run, e.g.- a timeout; counts as not passed). `output_excerpt` is at most 2 000 chars, with secrets left as the+- `status`: `pending` | `needs_approval` | `running` | `waiting` | `passed` | `failed` | `error` (couldn't+ run, e.g. a timeout; counts as not passed). `output_excerpt` is at most 2 000 chars, with secrets left as thecommand printed them, so commands that print secrets are the person's responsibility.- kwant runs `command`, `http` and `file_*` checks itself (`checked_by: "kwant"`) and stores the outputas evidence (`kind: "check_output"`).@@ -129,8 +129,49 @@ outcome_checks(id, task_id, kind, spec JSON, required, approved, status, output_and `checks_summary.needs_approval` counts it.- A task with no checks stays in `review` ("not checked") until a peer review or the person verifies it.+### Waiting checks (exit 75)++A `command` check that exits **75**, or an `http` check that gets its `waiting_status` or finds its+`waiting_contains`, means "not ready yet": the thing it checks is real but still running elsewhere.++- The check gets `status: "waiting"`, `waiting_since` (the round's first "not yet"), `next_run_at`,+ `wait_until` (the deadline) and `runs` (runs this round). Its verdict holds the task in `review`.+- Waiting costs nothing: no failure row, no Needs-you item, no AutoFix attempt, no tokens, no lease and+ no bot turn. Every run still stores its output as `check_output` evidence.+- The missions tick runs waiting checks again when `next_run_at` is due (at most 8 per tick, one+ at a time, in the background, only while the task is in `review`). `recheck_mins` (default 15,+ 5–1440) is the gap; the last run is never later than the deadline. A restart keeps the schedule;+ a waiting check that was running when kwant stopped waits again and is due at once.+- `wait_hours` (default 72, 1–336) is the deadline from the round's first "not yet". A "not yet" at or+ past it ends the check `error` with `timed_out_at` set and failure class `waited_too_long`, which+ AutoFix never retries (a `skipped` attempt, `not_retryable`). The task stays in `review` and gets one+ Needs-you item: `{"kind": "check_timed_out", "id": <check id>, "text": "<label> didn't answer in+ 72 h. Wait longer, or verify by hand.", "actions": ["wait_more", "verify"], "wait_more_hours": 24}`,+ for required checks that count. **Wait 24 h more** is `POST /api/checks/:id/wait-more` (person+ only): the deadline moves 24 h past the later of now and the old deadline, and the check is due at+ once. **Verify** is the person's usual `POST /api/tasks/:id/verify`, which settles waiting and+ timed-out checks.+- Exit 0 passes, any other code fails as before (`check_failed` → `retry_with_diagnostics`, so the+ bot gets the output). The next round starts at run 1 with a new key.+- Waiting is Mission Control's only. The Verifier, goals, Foundry and AutoFix's own runs of a check+ read exit 75 or a waiting reply as not passed.+- A `command` check runs with these environment variables:++ | variable | value |+ |---|---|+ | `KWANT_TASK_ID`, `KWANT_TASK_TITLE`, `KWANT_TASK_ACCEPTANCE` | the task |+ | `KWANT_CHECK_ID` | the check |+ | `KWANT_CHECK_RUN` | 1, 2, 3… within the round |+ | `KWANT_CHECK_ROUND` | how many times the task has gone to `review` (1 the first time) |+ | `KWANT_IDEMPOTENCY_KEY` | sha256 of `<check id>:<round>`: the same for every run of a round, new after a fail sends the task back |++ This `KWANT_IDEMPOTENCY_KEY` is the check's own. The `KWANT_IDEMPOTENCY_KEY=` line in an AutoFix+ retry prompt is the attempt's key for the bot's tool calls, a different value.+`checks_summary` on each task: `{"status": "not_checked" | "pending" | "passed" | "failed",-"passed": n, "failed": n, "needs_approval": n, "required_needs_approval": n, "total": n}`.+"passed": n, "failed": n, "waiting": n, "needs_approval": n, "required_needs_approval": n, "total": n}`.+`waiting` counts checks that count and are waiting or waited too long; `status` stays `pending` while+one waits, and a timed-out check is never counted in `failed`.`passed`/`failed` count checks that count; `needs_approval` counts checks waiting for the person, and`required_needs_approval` how many of those are required (so hold the task in `review`). A card shows"Needs you" only when `required_needs_approval > 0`; `status: "pending"` with@@ -138,6 +179,34 @@ outcome_checks(id, task_id, kind, spec JSON, required, approved, status, output_could be verified on them, and `pending` while a required check waits for approval (an optionalone waiting is counted in `needs_approval` but doesn't hold the task).+### Gate on an outside service++When the work finishes somewhere else (a store review, a build farm, a payout, a slow export), make the+check start the job once and then ask how it is going. Use `$KWANT_IDEMPOTENCY_KEY` so a second run+never starts a second job, and exit 75 while it is still going:++```bash+#!/usr/bin/env bash+# spec: {"command": "./gate.sh", "recheck_mins": 30, "wait_hours": 48}+set -u+state=".gate-$KWANT_IDEMPOTENCY_KEY" # one job per round+if [ "$KWANT_CHECK_RUN" = 1 ] || [ ! -f "$state" ]; then+ job=$(curl -fsS -X POST "$SERVICE_URL/jobs" \+ -H "Idempotency-Key: $KWANT_IDEMPOTENCY_KEY" | jq -r .id) || exit 1+ echo "$job" > "$state"+fi+status=$(curl -fsS "$SERVICE_URL/jobs/$(cat "$state")" | jq -r .status) || exit 75+echo "job $(cat "$state"): $status (run $KWANT_CHECK_RUN)"+case "$status" in+ done) exit 0 ;; # passed: the task can be verified+ failed) exit 1 ;; # failed: the bot gets this output+ *) exit 75 ;; # not ready yet: ask again later+esac+```++A network hiccup while asking exits 75 too, so it is asked again instead of failing the task; past+`wait_hours` the person decides. Keep keys out of the script (it is shown, masked, in the task).+## 5. Bot tools (MCP self tools; only while `mission_board` is on)| tool | args | result / rules |@@ -187,6 +256,8 @@ POST /api/tasks/:id/cancel -> TaskPOST /api/tasks/:id/checks {kind, spec, required?} -> Check (approved, runs if the task is in review)POST /api/tasks/:id/checks/run -> {checks: [Check], task: Task}POST /api/checks/:id/approve -> Check (needs_approval -> runs)+POST /api/checks/:id/wait-more -> Check (person only; a waiting or timed-out check of a+ task in review waits 24 h more; 409 otherwise)(runs in review or verified; on a verified task theresult is recorded and the state never changes)```@@ -213,9 +284,10 @@ claim conflict), 403 (bot token on a person route)."depends_on": ["task id"], "waiting_on": ["task id not verified yet"],"claim": null | {"kwant_id","claimed_at","expires_at"},"needs_you": [{"kind": "question"|"approval"|"human_step"|"check_approval", "id", "text"}],- "checks_summary": {"status","passed","failed","needs_approval","required_needs_approval","total"}}+ "checks_summary": {"status","passed","failed","waiting","needs_approval","required_needs_approval","total"}}// needs_you: question/approval/human_step while working or needs_you; check_approval (id = the-// check's id, approve it with POST /api/checks/:id/approve) while in review, for required checks only+// check's id, approve it with POST /api/checks/:id/approve) while in review, for required checks only;+// check_timed_out (id = the check's id, actions wait_more | verify) for a required check that waited too long// TaskDetail = {"task": Task, "checks": [Check], "evidence": [Evidence], "events": [Event]} (events oldest first, max 500)// MissionDetail = {"mission": Mission, "tasks": [Task]}@@ -502,13 +574,13 @@ acceptance, a routine) is only ever proposed; it applies when the person approve### Failures- `task_failures` (append-only): `id`, `task_id`, `attempt`, `source` (`check`, `turn`, `lease`, `budget`, `routine`, `handoff`), `class`, `summary`, `excerpt`, `checkpoint_id` (the last good `after_run`), `created_at`, and server-only `diagnostics_path`.-- `classify(source, status, text)` is deterministic. A check that failed is `check_failed`, or `bad_spec` when its command can't run (exit 127, "command not found"). A check that errored is `transient` for a timeout or 429/5xx (an `http` check whose connection was refused, dropped or timed out says "network error" by reqwest's error kind, not its wording), else `bad_spec`. A lease that ran out or a turn that ended without a review is `stalled`; over budget is `budget`; a denied action is `denied`; a task waiting on the person is `needs_input`. Other errors are `quota` (a usage limit or empty balance: Claude's "usage limit reached" / "hit your limit" / "5-hour limit reached", credit too low, insufficient_quota, 402, and kwant's own "is out of usage" / "Quota exceeded"), then `auth` (not logged in, 401, expired token, and kwant's own "signed out or its key was rejected" / "No account can run bots" / no other account on), then `transient` (rate limit, overloaded, timeouts, connection errors, 429/500/502/503/504/529 as whole numbers), else `unknown`.+- `classify(source, status, text)` is deterministic. A check that failed is `check_failed`, or `bad_spec` when its command can't run (exit 127, "command not found"). A check that errored is `transient` for a timeout or 429/5xx (an `http` check whose connection was refused, dropped or timed out says "network error" by reqwest's error kind, not its wording), else `bad_spec`. A lease that ran out or a turn that ended without a review is `stalled`; over budget is `budget`; a denied action is `denied`; a task waiting on the person is `needs_input`; a waiting check past its `wait_hours` is `waited_too_long`. Other errors are `quota` (a usage limit or empty balance: Claude's "usage limit reached" / "hit your limit" / "5-hour limit reached", credit too low, insufficient_quota, 402, and kwant's own "is out of usage" / "Quota exceeded"), then `auth` (not logged in, 401, expired token, and kwant's own "signed out or its key was rejected" / "No account can run bots" / no other account on), then `transient` (rate limit, overloaded, timeouts, connection errors, 429/500/502/503/504/529 as whole numbers), else `unknown`.- The text is redacted before it is stored. Labelled values are masked however short they are: `password=`/`token=`/`secret=`/`key=` and their `--flag value` / `--flag=value` forms (including `--…-key`), `"key": "…"`, `Authorization:` (the scheme is kept), the password in `user:pass@host`, and `-p`/`-a` only on a line that runs `mysql`, `mysqldump`, `mysqladmin`, `mariadb`, `sshpass` or `redis-cli`. A bare word is masked when it has a known key prefix (`sk-`, `xai-`, `ghp_`…) or reads as generated: 20+ letters and digits that break into short pieces (a hex or mixed-case key). Names built from words and a number, paths, URLs and UUIDs stay readable, and only the secret word itself is replaced. Masking is idempotent, so text masked twice is unchanged. A short bare password with no label can't be told from a word and is not masked. A check's spec is masked the same way wherever it is shown (task JSON, Needs-you text, failure excerpt, retry prompt, workflow changes); the stored spec keeps the real values, and a `workflow_propose` whose spec still holds `[redacted]` is refused. The excerpt is at most 2,000 characters. The full redacted output goes to `<data_dir>/autofix/<task_id>/<uuid>.log` (folder 0700, file 0600, 256 KB). No route returns that path.### Attempts- `autofix_attempts`: `id`, `task_id`, `failure_id`, `strategy`, `status` (`suggested`, `scheduled`, `running`, `succeeded`, `failed`, `skipped`), `not_before`, `reason`, `retry_task_id`, `tokens_spent`, `created_at`, `finished_at`, and server-only `idempotency_key` (unique: sha256 of task, failure and strategy, so a failure is never planned twice). At most one `scheduled`/`running` attempt per task (`autofix_one_live`), and a trigger refuses one past the task's `max_attempts`.-- Strategies: `transient` → `wait_and_retry` after 1, 5, then 25 minutes; `stalled` → `retry_from_checkpoint` (the folder is as the run left it) or `retry_same`; `check_failed` → `retry_with_diagnostics`; `bad_spec` → `propose_change` (a `check_spec` proposal making the check optional; the attempt stays `suggested` and never runs); `unknown` → `retry_same`, once per task. `auth`, `quota`, `budget` and `denied` are never retried: a `skipped` attempt (reason `not_retryable: <what to do>`) and a `fix_needed` Needs-you item saying what to do. Neither repeats the failure's summary, which the task already shows. `needs_input` and hand-off tasks get no attempt.+- Strategies: `transient` → `wait_and_retry` after 1, 5, then 25 minutes; `stalled` → `retry_from_checkpoint` (the folder is as the run left it) or `retry_same`; `check_failed` → `retry_with_diagnostics`; `bad_spec` → `propose_change` (a `check_spec` proposal making the check optional; the attempt stays `suggested` and never runs); `unknown` → `retry_same`, once per task. `auth`, `quota`, `budget`, `denied` and `waited_too_long` are never retried: a `skipped` attempt (reason `not_retryable: <what to do>`) and a `fix_needed` Needs-you item saying what to do (for `waited_too_long`, whose task stays in `review`, the `check_timed_out` item instead). Neither repeats the failure's summary, which the task already shows. `needs_input` and hand-off tasks get no attempt.- Limits, checked when planning and again when starting: a `blocked` task is never moved (`not_retryable`); no attempts left (`no_attempts_left`); `recovery_spent_tokens` plus the average spend per attempt over the recovery budget (`over_recovery_budget`). A limit makes the attempt `skipped` with that reason; a skip for `over_recovery_budget` also gives the failed task a `fix_needed` Needs-you item ("Retry budget used up: raise it or retry by hand.").- While attempts are left and AutoFix isn't off, a failure parks the task in `failed` instead of `ready` (no "failed" chat line). The retry moves it `failed → ready` as `Actor::AutoFix`, the only move that actor may make, with a task event of kind `autofix`. A routine run is retried as a new routine run; its task gets `forked_from` = the failed task and counts on from its attempts, and the failed task stays `failed`.- Recovery spend: a claim taken while an attempt runs carries its `autofix_id`, and that claim's spend (at hand-in and at turn end) also adds to `tasks.recovery_spent_tokens` and the attempt's `tokens_spent`. Plain runs never count as recovery. Token budgets (the task's and the recovery budget) count fresh input, cache writes and output, as Phase A spend does; cached input that is read again (`cache_read`) is left out. `model_usage.cost_usd` is the real-money figure.@@ -1395,7 +1467,7 @@ A bot's earlier tasks teach its next ones. Lessons are derived on read from kwan| `review` | the person's send-back with a reason | `rejected:<hash of the reason's content words>`; alike reasons (`router::team::alike`) share the first one's key || `goal` | a "Keep this true" goal made from a task the bot finished verified, confirmed not met after that (`goal_lapses_of_bot`) and still `not_met` now | `goal:<goal id>` (one per goal, its newest lapse) |-`quota`, `auth`, `budget`, `transient`, `bad_spec` and `needs_input` are not the bot's doing and never become a lesson. The window is the last 30 days.+`quota`, `auth`, `budget`, `transient`, `bad_spec`, `needs_input` and `waited_too_long` are not the bot's doing and never become a lesson. The window is the last 30 days.### Linesdiff --git a/src/db/autofix.rs b/src/db/autofix.rsindex dbee4028..6fb46311 100644--- a/src/db/autofix.rs+++ b/src/db/autofix.rs@@ -14,7 +14,10 @@ use sqlx::FromRow;use uuid::Uuid;pub const SOURCES: [&str; 6] = ["check", "turn", "lease", "budget", "routine", "handoff"];-pub const CLASSES: [&str; 10] = ["transient", "stalled", "check_failed", "auth", "quota", "budget", "denied", "bad_spec", "needs_input", "unknown"];+pub const CLASSES: [&str; 11] = ["transient", "stalled", "check_failed", "auth", "quota", "budget", "denied", "bad_spec", "needs_input", "unknown", "waited_too_long"];+/// `task_failures.class`'s CHECK before `waited_too_long`, and after (see `migrate_waiting_checks`).+pub(super) const OLD_CLASS_CHECK: &str = "CHECK (class IN ('transient', 'stalled', 'check_failed', 'auth', 'quota', 'budget', 'denied', 'bad_spec', 'needs_input', 'unknown'))";+pub(super) const NEW_CLASS_CHECK: &str = "CHECK (class IN ('transient', 'stalled', 'check_failed', 'auth', 'quota', 'budget', 'denied', 'bad_spec', 'needs_input', 'unknown', 'waited_too_long'))";pub const STRATEGIES: [&str; 6] = ["retry_same", "retry_with_diagnostics", "retry_from_checkpoint", "wait_and_retry", "propose_change", "none"];pub const TARGETS: [&str; 5] = ["routine_instructions", "routine_schedule", "check_spec", "task_acceptance", "max_attempts"];@@ -127,7 +130,7 @@ impl Database {task_id TEXT NOT NULL REFERENCES tasks(id),attempt INTEGER NOT NULL,source TEXT NOT NULL CHECK (source IN ('check', 'turn', 'lease', 'budget', 'routine', 'handoff')),- class TEXT NOT NULL CHECK (class IN ('transient', 'stalled', 'check_failed', 'auth', 'quota', 'budget', 'denied', 'bad_spec', 'needs_input', 'unknown')),+ class TEXT NOT NULL CHECK (class IN ('transient', 'stalled', 'check_failed', 'auth', 'quota', 'budget', 'denied', 'bad_spec', 'needs_input', 'unknown', 'waited_too_long')),summary TEXT NOT NULL,excerpt TEXT,diagnostics_path TEXT,diff --git a/src/db/lessons.rs b/src/db/lessons.rsindex 3b062232..b39b9c27 100644--- a/src/db/lessons.rs+++ b/src/db/lessons.rs@@ -9,7 +9,7 @@ use chrono::{DateTime, Utc};use sqlx::FromRow;/// The failure classes that are the bot's own doing. `quota`, `auth`, `budget`, `transient`,-/// `bad_spec` and `needs_input` are not, so they never become a lesson.+/// `bad_spec`, `needs_input` and `waited_too_long` are not, so they never become a lesson.pub const LESSON_CLASSES: [&str; 4] = ["check_failed", "stalled", "denied", "unknown"];/// One `task_failures` row of a task the bot owned and held a claim on.@@ -116,7 +116,7 @@ mod tests {assert!(super::super::autofix::CLASSES.contains(&c), "{c}");assert!(CLASSES_IN.contains(&format!("'{c}'")), "{c}");}- for c in ["quota", "auth", "budget", "transient", "bad_spec", "needs_input"] {+ for c in ["quota", "auth", "budget", "transient", "bad_spec", "needs_input", "waited_too_long"] {assert!(!LESSON_CLASSES.contains(&c), "{c}");}}diff --git a/src/db/missions.rs b/src/db/missions.rsindex e88db9db..77a4df87 100644--- a/src/db/missions.rs+++ b/src/db/missions.rs@@ -152,8 +152,42 @@ pub struct OutcomeCheck {pub created_at: DateTime<Utc>,pub started_at: Option<DateTime<Utc>>,pub finished_at: Option<DateTime<Utc>>,+ /// A `command` (exit 75) or `http` (`waiting_status` / `waiting_contains`) check that said "not+ /// yet": since when, in this round. Cleared when it passes or fails.+ pub waiting_since: Option<DateTime<Utc>>,+ /// When the missions tick runs a waiting check again.+ pub next_run_at: Option<DateTime<Utc>>,+ /// Its deadline: `waiting_since` + `wait_hours`, later after the person's "Wait 24 h more".+ pub wait_until: Option<DateTime<Utc>>,+ /// Runs in this round (KWANT_CHECK_RUN of the last run).+ pub runs: i64,+ /// The round (the task's attempt) `runs` counts in.+ #[serde(skip)]+ pub wait_round: i64,+ /// Set when it stopped waiting at its deadline (status `error`, failure class `waited_too_long`).+ pub timed_out_at: Option<DateTime<Utc>>,}+/// A command check's exit code for "not yet, check me again later" (EX_TEMPFAIL).+pub const WAITING_EXIT: i64 = 75;+pub const DEFAULT_RECHECK_MINS: i64 = 15;+pub const RECHECK_MINS: std::ops::RangeInclusive<i64> = 5..=1440;+pub const DEFAULT_WAIT_HOURS: i64 = 72;+pub const WAIT_HOURS: std::ops::RangeInclusive<i64> = 1..=336;+/// What the person's "Wait 24 h more" adds to a waiting check's deadline.+pub const WAIT_MORE_HOURS: i64 = 24;+/// The columns waiting checks added to `outcome_checks`, for databases made before them.+const WAITING_COLUMNS: [(&str, &str); 6] = [+ ("waiting_since", "TIMESTAMP"),+ ("next_run_at", "TIMESTAMP"),+ ("wait_until", "TIMESTAMP"),+ ("runs", "INTEGER NOT NULL DEFAULT 0"),+ ("wait_round", "INTEGER NOT NULL DEFAULT 0"),+ ("timed_out_at", "TIMESTAMP"),+];+const OLD_CHECK_STATUSES: &str = "CHECK (status IN ('pending', 'needs_approval', 'running', 'passed', 'failed', 'error'))";+const NEW_CHECK_STATUSES: &str = "CHECK (status IN ('pending', 'needs_approval', 'running', 'passed', 'failed', 'error', 'waiting'))";+impl OutcomeCheck {pub fn spec_value(&self) -> Value {serde_json::from_str(&self.spec).unwrap_or(Value::Null)@@ -416,7 +450,7 @@ impl Database {spec TEXT NOT NULL,required INTEGER NOT NULL DEFAULT 1,approved INTEGER NOT NULL DEFAULT 1,- status TEXT NOT NULL CHECK (status IN ('pending', 'needs_approval', 'running', 'passed', 'failed', 'error')),+ status TEXT NOT NULL CHECK (status IN ('pending', 'needs_approval', 'running', 'passed', 'failed', 'error', 'waiting')),output_excerpt TEXT,checked_by TEXT,requested_by TEXT NOT NULL,@@ -424,7 +458,13 @@ impl Database {evidence_id TEXT,created_at TIMESTAMP NOT NULL,started_at TIMESTAMP,- finished_at TIMESTAMP+ finished_at TIMESTAMP,+ waiting_since TIMESTAMP,+ next_run_at TIMESTAMP,+ wait_until TIMESTAMP,+ runs INTEGER NOT NULL DEFAULT 0,+ wait_round INTEGER NOT NULL DEFAULT 0,+ timed_out_at TIMESTAMP)","CREATE INDEX IF NOT EXISTS outcome_checks_task ON outcome_checks (task_id)",] {@@ -433,8 +473,15 @@ impl Database {for t in TRIGGERS {sqlx::query(t).execute(&self.pool).await?;}- // A restart stops every check that was running- sqlx::query("UPDATE outcome_checks SET status = 'error', output_excerpt = 'kwnt restarted while the check ran', finished_at = ? WHERE status = 'running'")+ for (col, ty) in WAITING_COLUMNS {+ let has: Option<(String,)> = sqlx::query_as("SELECT name FROM pragma_table_info('outcome_checks') WHERE name = ?").bind(col).fetch_optional(&self.pool).await?;+ if has.is_none() {+ sqlx::query(&format!("ALTER TABLE outcome_checks ADD COLUMN {col} {ty}")).execute(&self.pool).await?;+ }+ }+ // A restart stops every check that was running. One that was waiting goes back to+ // waiting in [`Database::migrate_waiting_checks`], once the table allows that status+ sqlx::query("UPDATE outcome_checks SET status = 'error', output_excerpt = 'kwnt restarted while the check ran', finished_at = ? WHERE status = 'running' AND waiting_since IS NULL").bind(Utc::now()).execute(&self.pool).await?;@@ -468,6 +515,38 @@ impl Database {result}+ /// Waiting checks (0.9.7): `outcome_checks.status` gains `waiting` and `task_failures.class`+ /// gains `waited_too_long`. Tables made before that are rebuilt once from their stored SQL,+ /// like [`Database::migrate_opt_in_budgets`]. Then a check that was waiting when kwnt stopped+ /// (running one of its re-runs) waits again, due at once: its schedule lives in the table.+ pub(super) async fn migrate_waiting_checks(&self) -> Result<(), DbError> {+ let mut conn = self.pool.acquire().await?;+ let mut old = Vec::new();+ for (table, from, to) in [+ ("outcome_checks", OLD_CHECK_STATUSES, NEW_CHECK_STATUSES),+ ("task_failures", super::autofix::OLD_CLASS_CHECK, super::autofix::NEW_CLASS_CHECK),+ ] {+ let sql: Option<(String,)> = sqlx::query_as("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?")+ .bind(table)+ .fetch_optional(&mut *conn)+ .await?;+ if let Some((sql,)) = sql.filter(|(sql,)| sql.contains(from)) {+ old.push((table, sql.replace(from, to)));+ }+ }+ if !old.is_empty() {+ sqlx::query("PRAGMA foreign_keys = OFF").execute(&mut *conn).await?;+ let result = rebuild_tables(&mut conn, &old).await;+ sqlx::query("PRAGMA foreign_keys = ON").execute(&mut *conn).await?;+ result?;+ }+ sqlx::query("UPDATE outcome_checks SET status = 'waiting', next_run_at = ? WHERE status = 'running' AND waiting_since IS NOT NULL")+ .bind(Utc::now())+ .execute(&mut *conn)+ .await?;+ Ok(())+ }+// Missionspub async fn create_mission(&self, space: &SpaceId, m: &NewMission) -> Result<Mission, DbError> {@@ -1105,15 +1184,19 @@ impl Database {pub async fn finish_check(&self, id: &str, status: &str, output: Option<&str>, checked_by: &str, evidence_id: Option<&str>) -> Result<(), DbError> {let mut tx = self.pool.begin().await?;- sqlx::query("UPDATE outcome_checks SET status = ?, output_excerpt = ?, checked_by = ?, evidence_id = ?, finished_at = ? WHERE id = ?")- .bind(status)- .bind(output)- .bind(checked_by)- .bind(evidence_id)- .bind(Utc::now())- .bind(id)- .execute(&mut *tx)- .await?;+ // A result ends any wait: the schedule and deadline go, `runs` stays for the record+ sqlx::query(+ "UPDATE outcome_checks SET status = ?, output_excerpt = ?, checked_by = ?, evidence_id = ?, finished_at = ?, \+ waiting_since = NULL, next_run_at = NULL, wait_until = NULL, timed_out_at = NULL WHERE id = ?",+ )+ .bind(status)+ .bind(output)+ .bind(checked_by)+ .bind(evidence_id)+ .bind(Utc::now())+ .bind(id)+ .execute(&mut *tx)+ .await?;let task: Option<(String,)> = sqlx::query_as("SELECT task_id FROM outcome_checks WHERE id = ?").bind(id).fetch_optional(&mut *tx).await?;if let Some((task_id,)) = task {insert_event(&mut tx, &task_id, None, "check_result", checked_by, None, None, &serde_json::json!({"check_id": id, "status": status})).await?;@@ -1122,6 +1205,122 @@ impl Database {Ok(())}+ /// How many times the task has gone to review: a waiting check's round. Unlike `attempts`,+ /// which the person's Retry resets, it only grows, so a round's idempotency key never repeats.+ pub async fn review_rounds(&self, task_id: &str) -> Result<i64, DbError> {+ let (n,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM task_events WHERE task_id = ? AND to_state = 'review'")+ .bind(task_id)+ .fetch_one(&self.pool)+ .await?;+ Ok(n)+ }++ /// Counts a run of a started check in `round` (the task's attempt): 1 in a new round, else+ /// one more. Returns the run number.+ pub async fn count_check_run(&self, id: &str, round: i64) -> Result<i64, DbError> {+ let (runs,): (i64,) = sqlx::query_as(+ "UPDATE outcome_checks SET runs = CASE WHEN wait_round = ?1 THEN runs + 1 ELSE 1 END, wait_round = ?1 WHERE id = ?2 RETURNING runs",+ )+ .bind(round)+ .bind(id)+ .fetch_one(&self.pool)+ .await?;+ Ok(runs)+ }++ /// Stores a "not yet" result: the check waits, to run again at `next_run_at`, until+ /// `wait_until`. A first run of the round starts the wait; later runs keep its start and+ /// deadline (which the person may have moved).+ #[allow(clippy::too_many_arguments)]+ pub async fn wait_check(+ &self,+ id: &str,+ output: Option<&str>,+ evidence_id: Option<&str>,+ now: DateTime<Utc>,+ next_run_at: DateTime<Utc>,+ wait_until: DateTime<Utc>,+ ) -> Result<(), DbError> {+ let mut tx = self.pool.begin().await?;+ sqlx::query(+ "UPDATE outcome_checks SET status = 'waiting', output_excerpt = ?1, checked_by = 'kwant', evidence_id = ?2, finished_at = ?3, \+ waiting_since = CASE WHEN runs <= 1 OR waiting_since IS NULL THEN ?3 ELSE waiting_since END, \+ wait_until = CASE WHEN runs <= 1 OR wait_until IS NULL THEN ?4 ELSE wait_until END, \+ next_run_at = ?5, timed_out_at = NULL WHERE id = ?6",+ )+ .bind(output)+ .bind(evidence_id)+ .bind(now)+ .bind(wait_until)+ .bind(next_run_at)+ .bind(id)+ .execute(&mut *tx)+ .await?;+ let task: Option<(String,)> = sqlx::query_as("SELECT task_id FROM outcome_checks WHERE id = ?").bind(id).fetch_optional(&mut *tx).await?;+ if let Some((task_id,)) = task {+ insert_event(&mut tx, &task_id, None, "check_result", "kwant", None, None, &serde_json::json!({"check_id": id, "status": "waiting"})).await?;+ }+ tx.commit().await?;+ Ok(())+ }++ /// Ends a wait at its deadline: `error`, with `timed_out_at`; its start and deadline stay so+ /// the person sees how long it waited.+ pub async fn time_out_check(&self, id: &str, output: Option<&str>, evidence_id: Option<&str>, now: DateTime<Utc>) -> Result<(), DbError> {+ let mut tx = self.pool.begin().await?;+ sqlx::query(+ "UPDATE outcome_checks SET status = 'error', output_excerpt = ?, checked_by = 'kwant', evidence_id = ?, finished_at = ?, \+ next_run_at = NULL, timed_out_at = ? WHERE id = ?",+ )+ .bind(output)+ .bind(evidence_id)+ .bind(now)+ .bind(now)+ .bind(id)+ .execute(&mut *tx)+ .await?;+ let task: Option<(String,)> = sqlx::query_as("SELECT task_id FROM outcome_checks WHERE id = ?").bind(id).fetch_optional(&mut *tx).await?;+ if let Some((task_id,)) = task {+ insert_event(&mut tx, &task_id, None, "check_result", "kwant", None, None, &serde_json::json!({"check_id": id, "status": "error", "timed_out": true})).await?;+ }+ tx.commit().await?;+ Ok(())+ }++ /// The person's "Wait 24 h more" on a waiting or timed-out check: the deadline moves to+ /// `hours` past the later of now and the old deadline, and it runs again at once. False when+ /// the check isn't waiting or timed out.+ pub async fn extend_wait(&self, id: &str, now: DateTime<Utc>, hours: i64) -> Result<bool, DbError> {+ let Some(c) = self.get_check(id).await? else { return Ok(false) };+ if !(c.status == "waiting" || (c.status == "error" && c.timed_out_at.is_some())) {+ return Ok(false);+ }+ let from = c.wait_until.map_or(now, |u| u.max(now));+ let r = sqlx::query(+ "UPDATE outcome_checks SET status = 'waiting', wait_until = ?, next_run_at = ?, timed_out_at = NULL, \+ waiting_since = COALESCE(waiting_since, ?) WHERE id = ? AND (status = 'waiting' OR (status = 'error' AND timed_out_at IS NOT NULL))",+ )+ .bind(from + chrono::Duration::hours(hours))+ .bind(now)+ .bind(now)+ .bind(id)+ .execute(&self.pool)+ .await?;+ Ok(r.rows_affected() == 1)+ }++ /// Waiting checks due by `now` on tasks in review, oldest due first, at most `limit`.+ pub async fn due_waiting_checks(&self, now: DateTime<Utc>, limit: i64) -> Result<Vec<OutcomeCheck>, DbError> {+ Ok(sqlx::query_as::<_, OutcomeCheck>(+ "SELECT c.* FROM outcome_checks c JOIN tasks t ON t.id = c.task_id \+ WHERE c.status = 'waiting' AND c.next_run_at <= ? AND t.state = 'review' ORDER BY c.next_run_at, c.rowid LIMIT ?",+ )+ .bind(now)+ .bind(limit)+ .fetch_all(&self.pool)+ .await?)+ }+// Eventspub async fn log_task_event(&self, task_id: &str, kind: &str, actor: &str, detail: &Value) -> Result<(), DbError> {@@ -1336,6 +1535,57 @@ async fn rebuild_budgets(conn: &mut sqlx::SqliteConnection, old: &[(&str, StringOk(())}+/// Rebuilds each `(table, new_sql)` from `new_sql` (its stored SQL with a CHECK list widened), in+/// one transaction, as [`rebuild_budgets`] does: create, copy every row (rowid too), drop,+/// rename, then its indexes and every trigger (dropped first: SQLite re-checks them on a rename).+async fn rebuild_tables(conn: &mut sqlx::SqliteConnection, tables: &[(&str, String)]) -> Result<(), DbError> {+ let mut tx = sqlx::Connection::begin(&mut *conn).await?;+ let before = fk_violations(&mut tx).await?;+ let triggers: Vec<(String, String)> =+ sqlx::query_as("SELECT name, sql FROM sqlite_master WHERE type = 'trigger' AND sql IS NOT NULL ORDER BY name").fetch_all(&mut *tx).await?;+ for (name, _) in &triggers {+ sqlx::query(&format!("DROP TRIGGER \"{name}\"")).execute(&mut *tx).await?;+ }+ for (table, sql) in tables {+ let new_table = format!("{table}__rebuild_new");+ let head = format!("CREATE TABLE {table} ");+ let quoted = format!("CREATE TABLE \"{table}\" ");+ let body = sql+ .strip_prefix(&head)+ .or_else(|| sql.strip_prefix("ed))+ .ok_or_else(|| DbError::Migration(format!("{table}: unexpected table SQL")))?;+ let indexes: Vec<(String,)> =+ sqlx::query_as("SELECT sql FROM sqlite_master WHERE tbl_name = ? AND type = 'index' AND sql IS NOT NULL ORDER BY name")+ .bind(table)+ .fetch_all(&mut *tx)+ .await?;+ sqlx::query(&format!("CREATE TABLE {new_table} {body}")).execute(&mut *tx).await?;+ let cols: Vec<(String,)> = sqlx::query_as("SELECT name FROM pragma_table_info(?) ORDER BY cid").bind(table).fetch_all(&mut *tx).await?;+ let list = cols.iter().map(|(c,)| format!("\"{c}\"")).collect::<Vec<_>>().join(", ");+ let copied = sqlx::query(&format!("INSERT INTO {new_table} (rowid, {list}) SELECT rowid, {list} FROM {table}"))+ .execute(&mut *tx)+ .await?+ .rows_affected();+ let (count,): (i64,) = sqlx::query_as(&format!("SELECT COUNT(*) FROM {table}")).fetch_one(&mut *tx).await?;+ if copied != count as u64 {+ return Err(DbError::Migration(format!("{table}: copied {copied} of {count} rows")));+ }+ sqlx::query(&format!("DROP TABLE {table}")).execute(&mut *tx).await?;+ sqlx::query(&format!("ALTER TABLE {new_table} RENAME TO {table}")).execute(&mut *tx).await?;+ for (stmt,) in &indexes {+ sqlx::query(stmt).execute(&mut *tx).await?;+ }+ }+ for (_, stmt) in &triggers {+ sqlx::query(stmt).execute(&mut *tx).await?;+ }+ if fk_violations(&mut tx).await? > before {+ return Err(DbError::Migration("foreign key check failed after a table rebuild".into()));+ }+ tx.commit().await?;+ Ok(())+}+async fn fk_violations(tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>) -> Result<usize, DbError> {let rows: Vec<(String, Option<i64>, String, i64)> = sqlx::query_as("PRAGMA foreign_key_check").fetch_all(&mut **tx).await?;Ok(rows.len())diff --git a/src/db/mod.rs b/src/db/mod.rsindex d6cb90c3..cefc3fb9 100644--- a/src/db/mod.rs+++ b/src/db/mod.rs@@ -265,6 +265,8 @@ impl Database {db.migrate_flight_school().await?;// Last: it rebuilds `tasks` and `missions` from their stored SQL, columns and triggers includeddb.migrate_opt_in_budgets().await?;+ // 0.9.7: waiting checks; rebuilds `outcome_checks` and `task_failures` once, triggers included+ db.migrate_waiting_checks().await?;db.migrate_chain_budget_default().await?;// After it: observes finished tasks once (their class comes from Flight School)db.migrate_performance().await?;diff --git a/src/server/auth.rs b/src/server/auth.rsindex 60b301c4..82b2c503 100644--- a/src/server/auth.rs+++ b/src/server/auth.rs@@ -1035,6 +1035,7 @@ mod tests {assert!(person_only(&post, "/api/tasks/t1/verify"));assert!(person_only(&post, "/api/tasks/t1/checks/run"));assert!(person_only(&post, "/api/checks/c1/approve"));+ assert!(person_only(&post, "/api/checks/c1/wait-more"));assert!(person_only(&post, "/api/tasks/t1/fork"));assert!(person_only(&post, "/api/tasks/t1/run"));assert!(person_only(&post, "/api/tasks/t1/checkpoints"));diff --git a/src/server/inbox.rs b/src/server/inbox.rsindex e372ea17..1245aeb1 100644--- a/src/server/inbox.rs+++ b/src/server/inbox.rs@@ -1081,6 +1081,12 @@ mod tests {created_at: at,started_at: None,finished_at: None,+ waiting_since: None,+ next_run_at: None,+ wait_until: None,+ runs: 0,+ wait_round: 0,+ timed_out_at: None,}}diff --git a/src/server/missions/autofix.rs b/src/server/missions/autofix.rsindex 555bb8ed..a6da0b0c 100644--- a/src/server/missions/autofix.rs+++ b/src/server/missions/autofix.rs@@ -146,6 +146,8 @@ fn is_transient(t: &str) -> bool {pub fn classify(source: &str, status: &str, text: &str) -> &'static str {let t = text.to_lowercase();match (source, status) {+ // A waiting check past its deadline: only the person can wait longer or verify by hand+ ("check", "waited_too_long") => "waited_too_long",("check", "failed") if t.contains("exit code 127") || t.contains("command not found") => "bad_spec",("check", "failed") => "check_failed",("check", _) if is_transient(&t) => "transient",@@ -221,6 +223,7 @@ fn fix_text(class: &str) -> Option<&'static str> {"quota" => Some("Usage limit reached: wait for it to reset or switch account, then retry."),"budget" => Some("Remove or raise the task's token limit, then retry it."),"denied" => Some("An action was denied during the run. Decide whether it may run, then retry."),+ "waited_too_long" => Some("The check didn't answer in time. Wait longer, or verify by hand."),_ => None,}}diff --git a/src/server/missions/checks.rs b/src/server/missions/checks.rsindex a03ae71a..18ace6fa 100644--- a/src/server/missions/checks.rs+++ b/src/server/missions/checks.rs@@ -3,7 +3,8 @@//! Each result is stored on the check and as `check_output` evidence; then the task is evaluated.use super::{evaluate, task_folder, MAX_EXCERPT};-use crate::db::missions::{NewEvidence, OutcomeCheck, Task, KWANT_CHECK_KINDS};+use crate::db::missions::{NewEvidence, OutcomeCheck, Task, DEFAULT_RECHECK_MINS, DEFAULT_WAIT_HOURS, KWANT_CHECK_KINDS, WAITING_EXIT};+use chrono::{DateTime, Duration, Utc};use crate::server::AppState;use serde_json::{json, Value};use sha2::{Digest, Sha256};@@ -111,9 +112,30 @@ pub struct Seen {pub sha256: Option<(String, String)>,}+/// What one run of a check said.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum Said {+ Pass,+ Fail,+ /// "Not yet": a command's exit 75, or an http check's `waiting_status` / `waiting_contains`.+ Wait,+}++impl From<bool> for Said {+ fn from(ok: bool) -> Self {+ if ok {+ Said::Pass+ } else {+ Said::Fail+ }+ }+}+/// Runs one check; returns `(status, output)` with status "passed", "failed" or "error"./// `person_ok`: the person added or approved it, so an `http` check may reach this computer or a/// private network; otherwise the URL must resolve to public addresses only, and is fetched from them.+/// A "not yet" (exit 75, `waiting_status`, `waiting_contains`) counts as "failed" here: only+/// Mission Control's own runs ([`run_check`]) wait.pub async fn run_spec(kind: &str, spec: &Value, folder: Option<&Path>, person_ok: bool) -> (String, String) {let (status, output, _) = run_spec_seen(kind, spec, folder, person_ok).await;(status, output)@@ -121,20 +143,32 @@ pub async fn run_spec(kind: &str, spec: &Value, folder: Option<&Path>, person_ok/// [`run_spec`], also returning what the run saw.pub async fn run_spec_seen(kind: &str, spec: &Value, folder: Option<&Path>, person_ok: bool) -> (String, String, Seen) {+ let (status, output, seen) = run_spec_env(kind, spec, folder, person_ok, &[]).await;+ (if status == "waiting" { "failed".into() } else { status }, output, seen)+}++/// [`run_spec_seen`] with extra environment for a command check, and status "waiting" for a+/// "not yet".+async fn run_spec_env(kind: &str, spec: &Value, folder: Option<&Path>, person_ok: bool, env: &[(String, String)]) -> (String, String, Seen) {let mut seen = Seen::default();let s = |k: &str| spec[k].as_str().map(str::trim).filter(|v| !v.is_empty());let need_folder = || folder.ok_or_else(|| "this task has no folder to check in".to_string());- let r: Result<(bool, String), String> = match kind {+ let r: Result<(Said, String), String> = match kind {"command" => match (s("command"), need_folder()) {(Some(cmd), Ok(dir)) => {let secs = spec["timeout_secs"].as_u64().unwrap_or(DEFAULT_COMMAND_SECS).clamp(1, MAX_COMMAND_SECS);- match crate::tools::shell::execute_shell(dir, &json!({"command": cmd, "timeout_secs": secs})).await {+ match crate::tools::shell::execute_shell_env(dir, &json!({"command": cmd, "timeout_secs": secs}), env).await {Ok(v) => {let code = v["exit_code"].as_i64().unwrap_or(-1);let out = format!("exit code {code}\n{}{}", v["stdout"].as_str().unwrap_or(""), v["stderr"].as_str().unwrap_or(""));seen.exit_code = Some(code);seen.stdout = Some(v["stdout"].as_str().unwrap_or("").to_string());- Ok((code == 0, out))+ let said = match code {+ 0 => Said::Pass,+ WAITING_EXIT => Said::Wait,+ _ => Said::Fail,+ };+ Ok((said, out))}Err(e) => Err(e.to_string()),}@@ -147,20 +181,21 @@ pub async fn run_spec_seen(kind: &str, spec: &Value, folder: Option<&Path>, persNone => Err("spec.url is missing".into()),},"file_exists" | "file_contains" | "file_sha256" => match (s("path"), need_folder()) {- (Some(rel), Ok(dir)) => file(kind, rel, spec, dir, &mut seen).await,+ (Some(rel), Ok(dir)) => file(kind, rel, spec, dir, &mut seen).await.map(|(ok, out)| (Said::from(ok), out)),(None, _) => Err("spec.path is missing".into()),(_, Err(e)) => Err(e),},other => Err(format!("kwant doesn't run {other} checks")),};match r {- Ok((true, out)) => ("passed".into(), excerpt(&out), seen),- Ok((false, out)) => ("failed".into(), excerpt(&out), seen),+ Ok((Said::Pass, out)) => ("passed".into(), excerpt(&out), seen),+ Ok((Said::Fail, out)) => ("failed".into(), excerpt(&out), seen),+ Ok((Said::Wait, out)) => ("waiting".into(), excerpt(&out), seen),Err(e) => ("error".into(), excerpt(&e), seen),}}-async fn http(url: &str, spec: &Value, person_ok: bool, seen: &mut Seen) -> Result<(bool, String), String> {+async fn http(url: &str, spec: &Value, person_ok: bool, seen: &mut Seen) -> Result<(Said, String), String> {let mut builder = reqwest::Client::builder();if !person_ok {let (host, addrs) = crate::mcp::fetch_risk::public_only(url).map_err(|why| format!("not fetched: {why}; the person can approve it"))?;@@ -198,10 +233,19 @@ async fn http(url: &str, spec: &Value, person_ok: bool, seen: &mut Seen) -> Resulet text = String::from_utf8_lossy(&body);let contains = spec["contains"].as_str().filter(|t| !t.is_empty());let has = contains.is_none_or(|t| text.contains(t));+ // "Not yet" wins over pass and fail: a 202 is a 2xx, and a "pending" page can still match `contains`+ let wait_status = spec["waiting_status"].as_u64().is_some_and(|w| u64::from(status) == w);+ let wait_text = spec["waiting_contains"].as_str().filter(|t| !t.is_empty()).filter(|t| text.contains(t));let mut out = format!("GET {url} → {status}");if let Some(t) = contains {out.push_str(&format!("; {} \"{t}\"", if has { "contains" } else { "does not contain" }));}+ if wait_status {+ out.push_str("; not ready yet (waiting status)");+ }+ if let Some(t) = wait_text {+ out.push_str(&format!("; not ready yet (contains \"{t}\")"));+ }if let Some(to) = &seen.redirect {out.push_str(&format!("; redirects to {}, which kwant doesn't follow",@@ -213,7 +257,8 @@ async fn http(url: &str, spec: &Value, person_ok: bool, seen: &mut Seen) -> Resu}seen.http_status = Some(status);seen.body = Some(text.into_owned());- Ok((ok_status && has, out))+ let said = if wait_status || wait_text.is_some() { Said::Wait } else { Said::from(ok_status && has) };+ Ok((said, out))}/// Why a GET didn't get a response. A refused or dropped connection and a timeout say so in@@ -289,14 +334,63 @@ pub fn hex(bytes: &[u8]) -> String {bytes.iter().map(|b| format!("{b:02x}")).collect()}+/// The key an outside service dedupes on: sha256 of the check's id and the round, so every run+/// of a round sends the same key, and the round after a fail sends a new one.+pub fn idempotency_key(check_id: &str, round: i64) -> String {+ hex(&Sha256::digest(format!("{check_id}:{round}").as_bytes()))+}++/// The environment a command check runs with (`KWANT_TASK_ID` and friends).+fn check_env(task: &Task, check: &OutcomeCheck, run: i64, round: i64) -> Vec<(String, String)> {+ vec![+ ("KWANT_TASK_ID".into(), task.id.clone()),+ ("KWANT_TASK_TITLE".into(), task.title.clone()),+ ("KWANT_TASK_ACCEPTANCE".into(), task.acceptance.clone()),+ ("KWANT_CHECK_ID".into(), check.id.clone()),+ ("KWANT_CHECK_RUN".into(), run.to_string()),+ ("KWANT_CHECK_ROUND".into(), round.to_string()),+ ("KWANT_IDEMPOTENCY_KEY".into(), idempotency_key(&check.id, round)),+ ]+}++/// A spec's whole-number field, or its default (validation keeps it in range; clamped anyway).+fn spec_num(spec: &Value, key: &str, default: i64, range: std::ops::RangeInclusive<i64>) -> i64 {+ spec[key].as_i64().unwrap_or(default).clamp(*range.start(), *range.end())+}++/// What a check is called to the person: its command or URL, cut short.+pub fn check_label(c: &OutcomeCheck) -> String {+ let spec = c.spec_value();+ let what = match c.kind.as_str() {+ "command" => spec["command"].as_str(),+ "http" => spec["url"].as_str(),+ _ => spec["path"].as_str(),+ };+ let what = super::autofix::redact(what.unwrap_or(&c.kind));+ let what = what.trim();+ if what.chars().count() > 80 {+ format!("{}…", what.chars().take(79).collect::<String>())+ } else {+ what.to_string()+ }+}+/// Runs `check` if kwant runs its kind and it is approved; stores the result and its evidence.pub async fn run_check(state: &AppState, task: &Task, check: &OutcomeCheck) -> OutcomeCheck {+ run_check_at(state, task, check, Utc::now()).await+}++/// [`run_check`] at `now`, which schedules a waiting check's next run and judges its deadline.+pub async fn run_check_at(state: &AppState, task: &Task, check: &OutcomeCheck, now: DateTime<Utc>) -> OutcomeCheck {if !KWANT_CHECK_KINDS.contains(&check.kind.as_str()) || !check.approved {return check.clone();}if !state.db.start_check(&check.id).await.unwrap_or(false) {return state.db.get_check(&check.id).await.ok().flatten().unwrap_or_else(|| check.clone());}+ // The round: how many times the task went to review (at least 1, for a run before the first)+ let round = state.db.review_rounds(&task.id).await.unwrap_or(0).max(1);+ let run = state.db.count_check_run(&check.id, round).await.unwrap_or(1);super::emit_task(state, task).await;let folder = task_folder(state, task).await;let spec = check.spec_value();@@ -310,12 +404,17 @@ pub async fn run_check(state: &AppState, task: &Task, check: &OutcomeCheck) -> O("command", Some(dir)) => state.db.host_command_refusal(dir).await,_ => None,};+ let env = check_env(task, check, run, round);let (status, output) = match refused {Some(why) => ("error".to_string(), why),- None => run_spec(&check.kind, &spec, folder.as_deref(), person_ok).await,+ None => {+ let (status, output, _) = run_spec_env(&check.kind, &spec, folder.as_deref(), person_ok, &env).await;+ (status, output)+ }};// The excerpt reaches bots and the API: credentials in the output never get storedlet output = super::autofix::redact(&output);+ let output = if status == "waiting" { format!("run {run}: not ready yet\n{output}") } else { output };let ev = state.db.add_evidence(&NewEvidence {@@ -329,10 +428,77 @@ pub async fn run_check(state: &AppState, task: &Task, check: &OutcomeCheck) -> O}).await.ok();- let _ = state.db.finish_check(&check.id, &status, Some(&output), "kwant", ev.as_ref().map(|e| e.id.as_str())).await;+ let ev_id = ev.as_ref().map(|e| e.id.as_str());+ if status != "waiting" {+ let _ = state.db.finish_check(&check.id, &status, Some(&output), "kwant", ev_id).await;+ return state.db.get_check(&check.id).await.ok().flatten().unwrap_or_else(|| check.clone());+ }+ // "Not yet": no failure, no AutoFix, no bot turn; the missions tick runs it again when due+ let wait_hours = spec_num(&spec, "wait_hours", DEFAULT_WAIT_HOURS, crate::db::missions::WAIT_HOURS);+ let recheck = spec_num(&spec, "recheck_mins", DEFAULT_RECHECK_MINS, crate::db::missions::RECHECK_MINS);+ // A later run keeps the round's deadline (the person may have moved it)+ let first = run <= 1 || check.wait_until.is_none() || check.wait_round != round;+ let deadline = if first { now + Duration::hours(wait_hours) } else { check.wait_until.unwrap_or(now) };+ if now >= deadline {+ let since = check.waiting_since.unwrap_or(now);+ let hours = ((deadline - since).num_minutes() as f64 / 60.0).round() as i64;+ let why = format!("{} didn't answer in {} h", check_label(check), hours.max(1));+ let out = format!("{why}. Wait longer, or verify by hand.\n{output}");+ let _ = state.db.time_out_check(&check.id, Some(&out), ev_id, now).await;+ // One failure row, class waited_too_long: AutoFix never retries it+ let text = format!("{} {}\n{}", check.kind, super::autofix::redact_value(&spec), out);+ super::autofix::record(state, &task.id, "check", "waited_too_long", &text, &why).await;+ } else {+ let next = (now + Duration::minutes(recheck)).min(deadline);+ let _ = state.db.wait_check(&check.id, Some(&output), ev_id, now, next, deadline).await;+ }state.db.get_check(&check.id).await.ok().flatten().unwrap_or_else(|| check.clone())}+/// Set while [`spawn_due`]'s run is going, so ticks don't stack runs of slow checks.+static DUE_RUNNING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);++/// [`run_due`] at now, in the background, unless the last one is still going.+pub fn spawn_due(state: &AppState) {+ use std::sync::atomic::Ordering;+ if DUE_RUNNING.swap(true, Ordering::AcqRel) {+ return;+ }+ let state = state.clone();+ tokio::spawn(async move {+ struct Done;+ impl Drop for Done {+ fn drop(&mut self) {+ DUE_RUNNING.store(false, std::sync::atomic::Ordering::Release);+ }+ }+ let _done = Done;+ run_due(&state, Utc::now()).await;+ });+}++/// Most waiting checks one tick runs; the rest are due on the next.+const DUE_PER_TICK: i64 = 8;++/// Runs the waiting checks due by `now` (tasks in review only), one after another, and evaluates+/// each task after. Returns how many ran. The missions tick calls it; tests pass their own `now`.+pub async fn run_due(state: &AppState, now: DateTime<Utc>) -> usize {+ let due = state.db.due_waiting_checks(now, DUE_PER_TICK).await.unwrap_or_default();+ let mut ran = 0;+ for c in due {+ let Ok(Some(task)) = state.db.get_task(&c.task_id).await else { continue };+ if task.state != "review" {+ continue;+ }+ run_check_at(state, &task, &c, now).await;+ ran += 1;+ if let Some(t) = evaluate(state, &task.id).await {+ super::emit_task(state, &t).await;+ }+ }+ ran+}+/// Whether the person approved `check` (`POST /api/checks/:id/approve`, or the mission it came in).async fn approved_by_person(state: &AppState, check: &OutcomeCheck) -> bool {let events = state.db.task_events(&check.task_id, 500).await.unwrap_or_default();@@ -409,4 +575,32 @@ mod tests {assert_eq!(run_spec("command", &json!({"command": "true"}), None, true).await.0, "error", "no folder");let _ = std::fs::remove_dir_all(&dir);}++ #[tokio::test]+ async fn exit_75_waits_only_for_mission_control() {+ let dir = std::env::temp_dir().join(format!("kwnt-mc-{}", uuid::Uuid::new_v4()));+ std::fs::create_dir_all(&dir).unwrap();+ let d = Some(dir.as_path());+ let spec = json!({"command": "echo queued; exit 75"});+ // The verifier, goals, Foundry and AutoFix read "not ready yet" as not passed+ assert_eq!(run_spec("command", &spec, d, true).await.0, "failed");+ let (status, out, _) = run_spec_env("command", &spec, d, true, &[]).await;+ assert_eq!(status, "waiting");+ assert!(out.contains("queued"), "{out}");+ let env = vec![("KWANT_CHECK_RUN".to_string(), "3".to_string())];+ let (status, out, _) = run_spec_env("command", &json!({"command": "echo run $KWANT_CHECK_RUN"}), d, true, &env).await;+ assert_eq!(status, "passed");+ assert!(out.contains("run 3"), "{out}");+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn the_idempotency_key_is_per_check_and_round() {+ let k = idempotency_key("c1", 1);+ assert_eq!(k.len(), 64);+ assert_eq!(k, idempotency_key("c1", 1), "stable across runs of a round");+ assert_ne!(k, idempotency_key("c1", 2), "a new round, a new key");+ assert_ne!(k, idempotency_key("c2", 1));+ assert_eq!(k, hex(&Sha256::digest(b"c1:1")));+ }}diff --git a/src/server/missions/lessons.rs b/src/server/missions/lessons.rsindex 3116b3ed..f070da4e 100644--- a/src/server/missions/lessons.rs+++ b/src/server/missions/lessons.rs@@ -631,6 +631,12 @@ mod tests {created_at: now(),started_at: None,finished_at: None,+ waiting_since: None,+ next_run_at: None,+ wait_until: None,+ runs: 0,+ wait_round: 0,+ timed_out_at: None,};let f = |c: &OutcomeCheck| FailureOfBot {id: "f1".into(),diff --git a/src/server/missions/mod.rs b/src/server/missions/mod.rsindex 1400d071..f95fb170 100644--- a/src/server/missions/mod.rs+++ b/src/server/missions/mod.rs@@ -382,8 +382,14 @@ pub fn counts(task: &Task, c: &OutcomeCheck) -> bool {pub fn verdict(task: &Task, checks: &[OutcomeCheck], since: Option<chrono::DateTime<chrono::Utc>>) -> Verdict {let owner = task.owner_kwant_id.as_deref().unwrap_or("");let required: Vec<&OutcomeCheck> = checks.iter().filter(|c| c.required).collect();- let live: Vec<&OutcomeCheck> = required.iter().copied().filter(|c| counts(task, c) && fresh(c, since)).collect();- if let Some(bad) = live.iter().find(|c| matches!(c.status.as_str(), "failed" | "error")) {+ let mut live: Vec<&OutcomeCheck> = required.iter().copied().filter(|c| counts(task, c) && fresh(c, since)).collect();+ // A check that is waiting on an outside service, or stopped waiting at its deadline, holds+ // the task in review (never a fail) until it answers, or the person verifies by hand+ let by_hand = live.iter().any(|c| c.kind == "person" && c.status == "passed");+ if by_hand {+ live.retain(|c| !waits(c));+ }+ if let Some(bad) = live.iter().find(|c| matches!(c.status.as_str(), "failed" | "error") && !timed_out(c)) {return Verdict::Fail(format!("{} check {}", bad.kind, bad.status));}if live.iter().any(|c| c.status != "passed") {@@ -401,6 +407,16 @@ pub fn verdict(task: &Task, checks: &[OutcomeCheck], since: Option<chrono::DateT}}+/// Whether `c` stopped waiting at its deadline (`error`, failure class `waited_too_long`).+pub fn timed_out(c: &OutcomeCheck) -> bool {+ c.status == "error" && c.timed_out_at.is_some()+}++/// Whether `c` is waiting on an outside service or stopped waiting at its deadline.+pub fn waits(c: &OutcomeCheck) -> bool {+ c.status == "waiting" || timed_out(c)+}+/// When the task last went to review.pub async fn review_since(state: &AppState, task_id: &str) -> Option<chrono::DateTime<chrono::Utc>> {let events = state.db.task_events(task_id, 500).await.ok()?;@@ -426,7 +442,8 @@ pub async fn evaluate(state: &AppState, task_id: &str) -> Option<Task> {let change = TaskChange { reason: Some(why.clone()), attempt: true, ..Default::default() };let moved = transition(state, task_id, "review", to, Actor::Kwant, "kwant", change).await.ok();if moved.is_some() {- let bad = checks.iter().filter(|c| matches!(c.status.as_str(), "failed" | "error")).find(|c| c.required).or_else(|| checks.iter().find(|c| matches!(c.status.as_str(), "failed" | "error")));+ let failed = |c: &&OutcomeCheck| matches!(c.status.as_str(), "failed" | "error") && !timed_out(c);+ let bad = checks.iter().filter(failed).find(|c| c.required).or_else(|| checks.iter().find(failed));if let Some(c) = bad {let text = format!("{} {}\n{}", c.kind, autofix::redact_value(&c.spec_value()), c.output_excerpt.as_deref().unwrap_or(""));autofix::record(state, task_id, "check", &c.status, &text, &why).await;@@ -443,14 +460,20 @@ pub async fn evaluate(state: &AppState, task_id: &str) -> Option<Task> {/// checks that count (see [`counts`]); `needs_approval` is how many wait for the person, and/// `required_needs_approval` how many of those are required, so hold the task.pub fn checks_summary(task: &Task, checks: &[OutcomeCheck]) -> Value {- let live: Vec<&OutcomeCheck> = checks.iter().filter(|c| counts(task, c)).collect();+ let mut live: Vec<&OutcomeCheck> = checks.iter().filter(|c| counts(task, c)).collect();+ // As in [`verdict`]: the person's Verify settles a check that waits on an outside service+ if live.iter().any(|c| c.required && c.kind == "person" && c.status == "passed") {+ live.retain(|c| !waits(c));+ }let waiting = checks.iter().filter(|c| !c.approved).count();// An optional check waiting for approval is listed but doesn't hold the task (see [`verdict`])let required_waiting = checks.iter().filter(|c| c.required && !c.approved).count();let holding = required_waiting > 0;let gating = |c: &&&OutcomeCheck| c.required;let passed = live.iter().filter(|c| c.status == "passed").count();- let failed = live.iter().filter(gating).filter(|c| matches!(c.status.as_str(), "failed" | "error")).count();+ let failed = live.iter().filter(gating).filter(|c| matches!(c.status.as_str(), "failed" | "error") && !timed_out(c)).count();+ // Waiting on an outside service (or stopped at its deadline): the summary stays pending+ let waiting_n = live.iter().filter(|c| waits(c)).count();let status = if live.is_empty() && waiting == 0 {"not_checked"} else if failed > 0 {@@ -466,6 +489,7 @@ pub fn checks_summary(task: &Task, checks: &[OutcomeCheck]) -> Value {"failed": failed,"needs_approval": waiting,"required_needs_approval": required_waiting,+ "waiting": waiting_n,"total": checks.len(),})}@@ -578,7 +602,9 @@ pub async fn needs_you(state: &AppState, task: &Task) -> Vec<Value> {async fn owner_needs_you(state: &AppState, task: &Task) -> Vec<Value> {if task.state == "review" {- return check_approvals(state, task).await;+ let mut items = check_approvals(state, task).await;+ items.extend(timed_out_checks(state, task).await);+ return items;}let Some(owner) = &task.owner_kwant_id else { return Vec::new() };if !matches!(task.state.as_str(), "working" | "needs_you") {@@ -626,6 +652,35 @@ pub async fn check_approvals(state: &AppState, task: &Task) -> Vec<Value> {.collect()}+/// A task in review waits on the person for each required check that stopped waiting at its+/// deadline (`{"kind": "check_timed_out", "id": <check id>, "text", "actions": ["wait_more",+/// "verify"]}`): "Wait 24 h more" (`POST /api/checks/:id/wait-more`) or Verify. A check still+/// waiting is never an item.+pub async fn timed_out_checks(state: &AppState, task: &Task) -> Vec<Value> {+ let checks = state.db.list_checks(&task.id).await.unwrap_or_default();+ if checks.iter().any(|c| c.kind == "person" && c.status == "passed" && c.required) {+ return Vec::new();+ }+ checks+ .iter()+ .filter(|c| c.required && counts(task, c) && timed_out(c))+ .map(|c| {+ let hours = match (c.waiting_since, c.wait_until) {+ (Some(s), Some(u)) => (((u - s).num_minutes() as f64) / 60.0).round().max(1.0) as i64,+ _ => crate::db::missions::DEFAULT_WAIT_HOURS,+ };+ let text = format!("{} didn't answer in {hours} h. Wait longer, or verify by hand.", checks::check_label(c));+ json!({+ "kind": "check_timed_out",+ "id": c.id,+ "text": text.chars().take(200).collect::<String>(),+ "actions": ["wait_more", "verify"],+ "wait_more_hours": crate::db::missions::WAIT_MORE_HOURS,+ })+ })+ .collect()+}+pub async fn task_json(state: &AppState, task: &Task) -> Value {let mut v = serde_json::to_value(task).unwrap_or(Value::Null);let deps = state.db.dependencies_of(&task.id).await.unwrap_or_default();@@ -871,6 +926,7 @@ pub fn validate_check(kind: &str, spec: &Value, person_ok: bool) -> Result<bool,if spec["timeout_secs"].as_u64().is_some_and(|t| !(1..=checks::MAX_COMMAND_SECS).contains(&t)) {return Err(format!("spec.timeout_secs must be 1–{}", checks::MAX_COMMAND_SECS));}+ validate_waiting(spec)?;Ok(person_ok)}"http" => {@@ -878,6 +934,13 @@ pub fn validate_check(kind: &str, spec: &Value, person_ok: bool) -> Result<bool,if !(url.starts_with("http://") || url.starts_with("https://")) {return Err("spec.url must start with http:// or https://".into());}+ validate_waiting(spec)?;+ if !spec["waiting_status"].is_null() && !spec["waiting_status"].as_u64().is_some_and(|s| (100..=599).contains(&s)) {+ return Err("spec.waiting_status must be an HTTP status, 100–599".into());+ }+ if !spec["waiting_contains"].is_null() && !spec["waiting_contains"].as_str().is_some_and(|t| !t.is_empty() && t.len() <= 500) {+ return Err("spec.waiting_contains must be text of 1–500 characters".into());+ }// Stricter than WebFetch: kwnt fetches it itself, so no local dev-server exemptionOk(person_ok || crate::mcp::fetch_risk::public_only(url).is_ok())}@@ -903,6 +966,19 @@ pub fn validate_check(kind: &str, spec: &Value, person_ok: bool) -> Result<bool,}}+/// A waiting check's `recheck_mins` (5–1440) and `wait_hours` (1–336), when given: whole numbers+/// in range. Left out, a "not yet" uses 15 minutes and 72 hours.+fn validate_waiting(spec: &Value) -> Result<(), String> {+ use crate::db::missions::{RECHECK_MINS, WAIT_HOURS};+ for (key, range) in [("recheck_mins", RECHECK_MINS), ("wait_hours", WAIT_HOURS)] {+ let v = &spec[key];+ if !v.is_null() && !v.as_i64().is_some_and(|n| range.contains(&n)) {+ return Err(format!("spec.{key} must be a whole number, {}–{}", range.start(), range.end()));+ }+ }+ Ok(())+}+/// Resolves a bot by id or name in `space`.pub async fn bot_in_space(state: &AppState, space: &SpaceId, who: &str) -> Option<crate::db::models::Kwant> {let who = who.trim().trim_start_matches('@');@@ -1132,6 +1208,35 @@ mod tests {use super::*;use chrono::Utc;+ #[test]+ fn wait_fields_have_bounds_and_defaults() {+ let cmd = |extra: Value| {+ let mut spec = json!({"command": "true"});+ for (k, v) in extra.as_object().unwrap() {+ spec[k] = v.clone();+ }+ validate_check("command", &spec, true)+ };+ assert!(cmd(json!({})).is_ok(), "both left out: the defaults");+ for ok in [json!({"recheck_mins": 5}), json!({"recheck_mins": 1440}), json!({"wait_hours": 1}), json!({"wait_hours": 336}), json!({"recheck_mins": null})] {+ assert!(cmd(ok.clone()).is_ok(), "{ok}");+ }+ for bad in [json!({"recheck_mins": 4}), json!({"recheck_mins": 1441}), json!({"wait_hours": 0}), json!({"wait_hours": 337}), json!({"wait_hours": 1.5}), json!({"recheck_mins": "15"})] {+ assert!(cmd(bad.clone()).is_err(), "{bad}");+ }+ let http = |extra: Value| {+ let mut spec = json!({"url": "https://example.com"});+ for (k, v) in extra.as_object().unwrap() {+ spec[k] = v.clone();+ }+ validate_check("http", &spec, true)+ };+ assert!(http(json!({"waiting_status": 202, "waiting_contains": "pending", "wait_hours": 24})).is_ok());+ assert!(http(json!({"waiting_status": 42})).is_err());+ assert!(http(json!({"waiting_contains": ""})).is_err());+ assert!(http(json!({"recheck_mins": 0})).is_err());+ }+#[test]fn a_blocked_task_says_what_stopped_and_how_to_carry_on() {assert_eq!(@@ -1216,6 +1321,12 @@ mod tests {created_at: Utc::now(),started_at: None,finished_at: Some(Utc::now()),+ waiting_since: None,+ next_run_at: None,+ wait_until: None,+ runs: 0,+ wait_round: 0,+ timed_out_at: None,}}diff --git a/src/server/missions/routes.rs b/src/server/missions/routes.rsindex f242efa9..2fefa8bd 100644--- a/src/server/missions/routes.rs+++ b/src/server/missions/routes.rs@@ -978,6 +978,34 @@ pub async fn approve_check(State(state): State<AppState>, RawQuery(q): RawQuery,Json(super::check_json(&t, &check, super::name_of(&state, check.checked_by.as_deref()).await)).into_response()}+/// `POST /api/checks/:id/wait-more` (person only): a check waiting on an outside service, or+/// stopped at its deadline, waits 24 h more and runs again on the next tick. The task must be in+/// review.+pub async fn wait_more(State(state): State<AppState>, RawQuery(q): RawQuery, Path(id): Path<String>) -> Response {+ let check = match state.db.get_check(&id).await {+ Ok(Some(c)) => c,+ Ok(None) => return not_found("check"),+ Err(e) => return internal(e),+ };+ let t = match load_task(&state, q.as_deref(), &check.task_id).await {+ Ok(t) => t,+ Err(r) => return r,+ };+ if t.state != "review" {+ return conflict(format!("only a task in review waits on its checks; this one is {}", t.state));+ }+ let hours = crate::db::missions::WAIT_MORE_HOURS;+ match state.db.extend_wait(&id, chrono::Utc::now(), hours).await {+ Ok(true) => {}+ Ok(false) => return conflict(format!("the check is {}, not waiting", check.status)),+ Err(e) => return internal(e),+ }+ let _ = state.db.log_task_event(&t.id, "check_wait_more", "person", &json!({"check_id": id, "hours": hours})).await;+ let check = state.db.get_check(&id).await.ok().flatten().unwrap_or(check);+ emit_task(&state, &t).await;+ Json(super::check_json(&t, &check, super::name_of(&state, check.checked_by.as_deref()).await)).into_response()+}+#[cfg(test)]mod tests {use super::*;diff --git a/src/server/missions/runner.rs b/src/server/missions/runner.rsindex 0017039e..77f013a3 100644--- a/src/server/missions/runner.rs+++ b/src/server/missions/runner.rs@@ -65,6 +65,8 @@ pub async fn tick(state: &AppState) {super::sweep_leases(state).await;// AutoFix retries whose time has come, before tasks are picked (Phase B3)super::autofix::run_due(state).await;+ // Waiting checks whose re-run is due; in the background, as a command may take minutes+ super::checks::spawn_due(state);for m in state.db.active_missions().await.unwrap_or_default() {// Evidence drift, at most every 10 minutes per mission (Phase B1)super::graph::scan_if_due(state, &m).await;diff --git a/src/server/missions/tools.rs b/src/server/missions/tools.rsindex d211593e..adc637e6 100644--- a/src/server/missions/tools.rs+++ b/src/server/missions/tools.rs@@ -31,7 +31,7 @@ fn check_schema() -> Value {"type": "object","properties": {"kind": {"type": "string", "enum": ["command", "http", "file_exists", "file_contains", "file_sha256"]},- "spec": {"type": "object", "description": "command: {command, timeout_secs?}; http: {url, expect_status?, contains?}; file_exists: {path}; file_contains: {path, text}; file_sha256: {path, sha256}. Paths are relative to the mission's folder."},+ "spec": {"type": "object", "description": "command: {command, timeout_secs?, recheck_mins?, wait_hours?}; http: {url, expect_status?, contains?, waiting_status?, waiting_contains?, recheck_mins?, wait_hours?}; file_exists: {path}; file_contains: {path, text}; file_sha256: {path, sha256}. Paths are relative to the mission's folder. A command that exits 75, or an http answer with waiting_status or containing waiting_contains, means not ready yet: kwant runs it again every recheck_mins (5–1440, default 15) for up to wait_hours (1–336, default 72), and the task stays in review meanwhile."},"required": {"type": "boolean"},},"required": ["kind", "spec"],@@ -130,7 +130,7 @@ pub fn tools() -> Vec<Value> {"task_id": {"type": "string"},"check_id": {"type": "string"},"kind": {"type": "string", "enum": ["command", "http", "file_exists", "file_contains", "file_sha256"]},- "spec": {"type": "object"},+ "spec": {"type": "object", "description": "As in mission_plan's checks: command {command, timeout_secs?, recheck_mins?, wait_hours?} (exit 75 = not ready yet, run again later); http {url, expect_status?, contains?, waiting_status?, waiting_contains?, recheck_mins?, wait_hours?}."},"required": {"type": "boolean"},},"required": ["task_id"],diff --git a/src/server/mod.rs b/src/server/mod.rsindex ccfb262f..b9043263 100644--- a/src/server/mod.rs+++ b/src/server/mod.rs@@ -566,6 +566,7 @@ pub fn create_router(state: AppState) -> Router {.route("/api/tasks/:id/checks", post(missions::routes::add_task_check)).route("/api/tasks/:id/checks/run", post(missions::routes::run_task_checks)).route("/api/checks/:id/approve", post(missions::routes::approve_check))+ .route("/api/checks/:id/wait-more", post(missions::routes::wait_more)).route("/api/questions/:id/cancel", post(questions::cancel)).route("/api/human-steps", get(human_steps::list)).route("/api/human-steps/:id", get(human_steps::get))diff --git a/src/tools/shell.rs b/src/tools/shell.rsindex 55628a55..d0fe0188 100644--- a/src/tools/shell.rs+++ b/src/tools/shell.rs@@ -9,6 +9,12 @@ use tokio::process::Command;use tokio::time::timeout;pub async fn execute_shell(workspace: &Path, args: &Value) -> Result<Value, ToolError> {+ execute_shell_env(workspace, args, &[]).await+}++/// [`execute_shell`] with extra environment variables, for kwant's own callers (outcome checks+/// pass KWANT_TASK_ID and friends). Bots reach only [`execute_shell`], which adds none.+pub async fn execute_shell_env(workspace: &Path, args: &Value, env: &[(String, String)]) -> Result<Value, ToolError> {let command_str = args["command"].as_str().ok_or_else(|| ToolError::InvalidArgs("Missing 'command' argument".into()))?;@@ -18,6 +24,9 @@ pub async fn execute_shell(workspace: &Path, args: &Value) -> Result<Value, Toollet mut cmd = Command::new(shell_program()?);cmd.arg("-c").arg(command_str);cmd.current_dir(workspace);+ for (k, v) in env {+ cmd.env(k, v);+ }cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());// A cancelled turn drops this future; neither bash nor anything it started may outlive itcmd.kill_on_drop(true);diff --git a/tests/waiting_checks_test.rs b/tests/waiting_checks_test.rsnew file mode 100644index 00000000..08f421cd--- /dev/null+++ b/tests/waiting_checks_test.rs@@ -0,0 +1,504 @@+//! Waiting checks: a `command` check that exits 75, or an `http` check that answers its+//! `waiting_status` / `waiting_contains`, means "not ready yet". The check waits (no failure,+//! no AutoFix, no bot turn), the missions tick runs it again when due, and past its `wait_hours`+//! it stops with failure class `waited_too_long` and one Needs-you item the person answers with+//! "Wait 24 h more" or Verify. Every run of a round shares an idempotency key; a new round after a+//! fail gets a new one.++use axum::{+ body::{to_bytes, Body},+ extract::State,+ http::{Request, StatusCode},+ routing::get,+ Router,+};+use chrono::{DateTime, Duration, Utc};+use kwnt::{+ broker::PermissionBroker,+ config::Config,+ db::{models::Kwant, spaces::SpaceId, Database},+ router::LayaRouter,+ server::{+ continuity::{SelfScope, TurnOrigin},+ create_router, mcp_runtime, missions, AppState,+ },+ tools::ToolRunner,+};+use serde_json::{json, Value};+use std::collections::VecDeque;+use std::sync::{Arc, Mutex};+use tempfile::{tempdir, TempDir};+use tower::ServiceExt;++struct Env {+ app: Router,+ state: AppState,+ bot: Kwant,+ general: String,+ tmp: TempDir,+}++async fn setup(autofix: &str) -> Env {+ let tmp = tempdir().unwrap();+ let db = Database::init(tmp.path()).await.unwrap();+ let config = Config { data_dir: tmp.path().to_path_buf(), ..Config::default() };+ let state = AppState::new(config.clone(), db, ToolRunner::new(tmp.path().join("workspace")), PermissionBroker::new(), LayaRouter::new(config.laya_url.clone()));+ let space = SpaceId::default_space();+ let kwants = state.db.list_kwants(&space).await.unwrap();+ let general = state.db.list_channels(&space).await.unwrap().into_iter().find(|c| c.name == "general").unwrap().id;+ let e = Env { app: create_router(state.clone()), bot: kwants[0].clone(), general, state, tmp };+ let (status, v) = call(&e.app, "POST", "/api/settings", None, Some(json!({"mission_board": true, "autofix": autofix, "verifier": "off"}))).await;+ assert_eq!(status, StatusCode::OK, "{v}");+ e+}++async fn call(app: &Router, method: &str, uri: &str, auth: Option<&str>, body: Option<Value>) -> (StatusCode, Value) {+ let mut req = Request::builder().method(method).uri(uri).header("content-type", "application/json");+ if let Some(token) = auth {+ req = req.header("authorization", format!("Bearer {token}"));+ }+ let body = body.map(|b| Body::from(b.to_string())).unwrap_or_else(Body::empty);+ let resp = app.clone().oneshot(req.body(body).unwrap()).await.unwrap();+ let status = resp.status();+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();+ (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))+}++async fn person(e: &Env, method: &str, uri: &str, body: Option<Value>) -> Value {+ let (status, v) = call(&e.app, method, uri, None, body).await;+ assert!(status.is_success(), "{method} {uri}: {status} {v}");+ v+}++async fn tool(e: &Env, token: &str, name: &str, args: Value) -> (bool, String) {+ let rpc = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": name, "arguments": args}});+ let (status, v) = call(&e.app, "POST", "/api/mcp/self", Some(token), Some(rpc)).await;+ assert_eq!(status, StatusCode::OK, "{v}");+ let text = v["result"]["content"][0]["text"].as_str().unwrap_or("").to_string();+ (!v["result"]["isError"].as_bool().unwrap_or(false), text)+}++async fn ok(e: &Env, token: &str, name: &str, args: Value) {+ let (fine, text) = tool(e, token, name, args.clone()).await;+ assert!(fine, "{name} {args} failed: {text}");+}++async fn turn(e: &Env, turn_id: &str) -> String {+ let origin = TurnOrigin { channel_id: Some(e.general.clone()), ..Default::default() };+ let scope = SelfScope { kwant_id: e.bot.id.clone(), kwant_name: e.bot.name.clone(), origin: Some(origin), turn_id: Some(turn_id.into()), ..Default::default() };+ mcp_runtime::prepare_turn_with_self(&e.state, &e.bot, Some(turn_id.into()), None, Some(scope)).await.unwrap().1+}++async fn task(e: &Env, id: &str) -> Value {+ person(e, "GET", &format!("/api/tasks/{id}"), None).await+}++fn check<'a>(t: &'a Value, id: &str) -> &'a Value {+ t["checks"].as_array().unwrap().iter().find(|c| c["id"] == id).unwrap_or_else(|| panic!("no check {id} in {t}"))+}++fn at(v: &Value) -> DateTime<Utc> {+ DateTime::parse_from_rfc3339(v.as_str().unwrap_or_else(|| panic!("not a time: {v}"))).unwrap().with_timezone(&Utc)+}++fn near(a: DateTime<Utc>, b: DateTime<Utc>) -> bool {+ (a - b).num_seconds().abs() < 60+}++/// A command that answers with the next exit code from `codes-<name>` (one per line, counted per+/// check) and logs the env it got: round, run, key, task id, check id.+fn scripted(name: &str) -> String {+ format!(+ "n=$(( $(cat .n-$KWANT_CHECK_ID 2>/dev/null || echo 0) + 1 )); echo $n > .n-$KWANT_CHECK_ID; \+ echo \"$KWANT_CHECK_ROUND $KWANT_CHECK_RUN $KWANT_IDEMPOTENCY_KEY $KWANT_TASK_ID $KWANT_CHECK_ID\" >> env-{name}.log; \+ echo \"poll $n of {name}\"; exit $(sed -n \"${{n}}p\" codes-{name})"+ )+}++/// The env lines a scripted check logged: `[round, run, key, task id, check id]` each.+fn env_log(dir: &std::path::Path, name: &str) -> Vec<Vec<String>> {+ std::fs::read_to_string(dir.join(format!("env-{name}.log"))).unwrap_or_default().lines().map(|l| l.split(' ').map(String::from).collect()).collect()+}++struct Task {+ id: String,+ dir: std::path::PathBuf,+ token: String,+}++/// A ready task owned by the bot, in a mission the person made; its folder exists.+async fn new_task(e: &Env) -> Task {+ let body = json!({"title": "Ship it", "goal": "a release", "lead_kwant_id": e.bot.id, "budget_tokens": 200_000,+ "channel_id": e.general, "tasks": [{"title": "Deploy", "owner": e.bot.id, "acceptance": "the deploy is live"}]});+ let m = person(e, "POST", "/api/missions", Some(body)).await;+ let mid = m["id"].as_str().unwrap().to_string();+ let detail = person(e, "GET", &format!("/api/missions/{mid}"), None).await;+ let id = detail["tasks"][0]["id"].as_str().unwrap().to_string();+ let mission = e.state.db.get_mission(&mid).await.unwrap().unwrap();+ let dir = std::path::PathBuf::from(mission.workspace_path);+ std::fs::create_dir_all(&dir).unwrap();+ let token = turn(e, &format!("t-{id}")).await;+ Task { id, dir, token }+}++/// The person adds a check to the task; returns its id.+async fn add_check(e: &Env, t: &Task, kind: &str, spec: Value) -> String {+ let c = person(e, "POST", &format!("/api/tasks/{}/checks", t.id), Some(json!({"kind": kind, "spec": spec}))).await;+ c["id"].as_str().or(c["check"]["id"].as_str()).unwrap_or_else(|| panic!("no check id in {c}")).to_string()+}++/// A scripted command check answering `codes` in turn.+async fn add_scripted(e: &Env, t: &Task, name: &str, codes: &[i32], extra: Value) -> String {+ std::fs::write(t.dir.join(format!("codes-{name}")), codes.iter().map(|c| format!("{c}\n")).collect::<String>()).unwrap();+ let mut spec = json!({"command": scripted(name)});+ for (k, v) in extra.as_object().cloned().unwrap_or_default() {+ spec[k] = v;+ }+ add_check(e, t, "command", spec).await+}++/// The bot claims the task and hands it in: kwant runs its checks.+async fn hand_in(e: &Env, t: &Task) {+ let token = turn(e, &format!("t-{}", uuid::Uuid::new_v4())).await;+ ok(e, &token, "task_claim", json!({"task_id": t.id})).await;+ ok(e, &token, "task_update", json!({"task_id": t.id, "status": "review"})).await;+}++#[tokio::test]+async fn exit_75_waits_in_review_with_no_failure_and_no_autofix() {+ let e = setup("on").await;+ let t = new_task(&e).await;+ let cid = add_scripted(&e, &t, "a", &[75], json!({})).await;+ let before = Utc::now();+ hand_in(&e, &t).await;++ let v = task(&e, &t.id).await;+ assert_eq!(v["task"]["state"], "review", "a waiting check holds the task in review: {v}");+ assert_eq!(v["task"]["attempts"], 0, "no attempt used: {v}");+ let c = check(&v, &cid);+ assert_eq!(c["status"], "waiting", "{c}");+ assert_eq!(c["runs"], 1);+ // No recheck_mins or wait_hours in the spec: the defaults, 15 minutes and 72 hours+ let since = at(&c["waiting_since"]);+ assert!(since >= before - Duration::seconds(1) && near(since, Utc::now()), "{c}");+ assert!(near(at(&c["next_run_at"]), since + Duration::minutes(15)), "{c}");+ assert!(near(at(&c["wait_until"]), since + Duration::hours(72)), "{c}");+ assert!(c["timed_out_at"].is_null());+ assert!(c["output_excerpt"].as_str().unwrap().contains("poll 1 of a"), "{c}");+ let summary = &v["task"]["checks_summary"];+ assert_eq!(summary["status"], "pending", "{summary}");+ assert_eq!(summary["waiting"], 1, "{summary}");+ assert_eq!(summary["failed"], 0, "{summary}");+ assert_eq!(v["task"]["needs_you"], json!([]), "waiting is never a Needs-you item: {v}");+ assert!(e.state.db.failures_of(&t.id).await.unwrap().is_empty(), "no failure row");+ assert!(e.state.db.attempts_of(&t.id).await.unwrap().is_empty(), "no AutoFix attempt");+ assert!(v["evidence"].as_array().unwrap().iter().any(|ev| ev["kind"] == "check_output" && ev["label"] == "command check: waiting"), "{v}");++ // The env: the task, the check, run 1 of round 1, the round's key+ let log = env_log(&t.dir, "a");+ assert_eq!(log.len(), 1);+ assert_eq!(log[0][0], "1");+ assert_eq!(log[0][1], "1");+ assert_eq!(log[0][2], missions::checks::idempotency_key(&cid, 1));+ assert_eq!(log[0][3], t.id);+ assert_eq!(log[0][4], cid);+}++#[tokio::test]+async fn the_tick_runs_only_due_checks_and_75_75_0_verifies() {+ let e = setup("on").await;+ let t = new_task(&e).await;+ let fast = add_scripted(&e, &t, "fast", &[75, 75, 0], json!({"recheck_mins": 5})).await;+ let slow = add_scripted(&e, &t, "slow", &[75, 0], json!({"recheck_mins": 60})).await;+ let now = Utc::now();+ hand_in(&e, &t).await;+ let v = task(&e, &t.id).await;+ assert_eq!(check(&v, &fast)["status"], "waiting");+ assert_eq!(check(&v, &slow)["status"], "waiting");+ assert_eq!(v["task"]["checks_summary"]["waiting"], 2);++ assert_eq!(missions::checks::run_due(&e.state, now + Duration::minutes(1)).await, 0, "nothing due yet");+ assert_eq!(missions::checks::run_due(&e.state, now + Duration::minutes(6)).await, 1, "only the 5-minute check");+ let v = task(&e, &t.id).await;+ assert_eq!(check(&v, &fast)["runs"], 2);+ assert_eq!(check(&v, &fast)["status"], "waiting");+ assert_eq!(check(&v, &slow)["runs"], 1, "not due: not run");+ assert!(near(at(&check(&v, &fast)["next_run_at"]), now + Duration::minutes(11)));+ // The wait started at the first run and keeps its deadline+ assert!(near(at(&check(&v, &fast)["waiting_since"]), now));++ assert_eq!(missions::checks::run_due(&e.state, now + Duration::minutes(12)).await, 1);+ let v = task(&e, &t.id).await;+ assert_eq!(check(&v, &fast)["status"], "passed", "75, 75, 0 passes: {v}");+ assert_eq!(check(&v, &fast)["runs"], 3);+ assert!(check(&v, &fast)["next_run_at"].is_null() && check(&v, &fast)["waiting_since"].is_null());+ assert_eq!(v["task"]["state"], "review", "the slow check still waits");++ assert_eq!(missions::checks::run_due(&e.state, now + Duration::minutes(61)).await, 1);+ let v = task(&e, &t.id).await;+ assert_eq!(check(&v, &slow)["status"], "passed");+ assert_eq!(v["task"]["state"], "verified", "{v}");+ assert_eq!(v["task"]["checks_summary"]["status"], "passed");+ assert_eq!(v["task"]["checks_summary"]["waiting"], 0);+ assert!(e.state.db.failures_of(&t.id).await.unwrap().is_empty());+ assert!(e.state.db.attempts_of(&t.id).await.unwrap().is_empty());++ // KWANT_CHECK_RUN counts up; the key stays the same for every run of the round+ let log = env_log(&t.dir, "fast");+ assert_eq!(log.iter().map(|l| l[1].as_str()).collect::<Vec<_>>(), ["1", "2", "3"]);+ assert!(log.iter().all(|l| l[0] == "1" && l[2] == log[0][2]), "{log:?}");+ assert_ne!(env_log(&t.dir, "slow")[0][2], log[0][2], "each check has its own key");+ // Every run's output is evidence+ let runs = v["evidence"].as_array().unwrap().iter().filter(|ev| ev["kind"] == "check_output").count();+ assert_eq!(runs, 5, "{v}");+}++#[tokio::test]+async fn a_fail_after_waiting_goes_to_the_bot_with_its_output_and_the_next_round_has_a_new_key() {+ // suggest: the retry waits for the person, so the next round is this test's to drive+ let e = setup("suggest").await;+ let t = new_task(&e).await;+ let cid = add_scripted(&e, &t, "a", &[75, 1, 0], json!({})).await;+ let now = Utc::now();+ hand_in(&e, &t).await;+ assert_eq!(check(&task(&e, &t.id).await, &cid)["status"], "waiting");+ assert_eq!(missions::checks::run_due(&e.state, now + Duration::minutes(16)).await, 1);++ let v = task(&e, &t.id).await;+ assert_eq!(check(&v, &cid)["status"], "failed", "{v}");+ assert_eq!(v["task"]["state"], "failed", "a fail leaves review: {v}");+ let failures = e.state.db.failures_of(&t.id).await.unwrap();+ assert_eq!(failures.len(), 1);+ assert_eq!(failures[0].class, "check_failed");+ assert!(failures[0].excerpt.as_deref().unwrap_or("").contains("poll 2 of a"), "the bot gets the output: {:?}", failures[0]);+ let attempts = e.state.db.attempts_of(&t.id).await.unwrap();+ assert_eq!(attempts.len(), 1);+ assert_eq!((attempts[0].strategy.as_str(), attempts[0].status.as_str()), ("retry_with_diagnostics", "suggested"));++ // The next round (the person retries; the bot hands in again): a new key+ person(&e, "POST", &format!("/api/tasks/{}/retry", t.id), None).await;+ hand_in(&e, &t).await;+ let v = task(&e, &t.id).await;+ assert_eq!(v["task"]["state"], "verified", "{v}");+ let log = env_log(&t.dir, "a");+ assert_eq!(log.len(), 3);+ assert_eq!((log[0][0].as_str(), log[0][1].as_str()), ("1", "1"));+ assert_eq!((log[1][0].as_str(), log[1][1].as_str()), ("1", "2"));+ assert_eq!((log[2][0].as_str(), log[2][1].as_str()), ("2", "1"), "a new round starts at run 1");+ assert_eq!(log[0][2], log[1][2]);+ assert_ne!(log[2][2], log[0][2], "the round after a fail has a new key");+ assert_eq!(log[2][2], missions::checks::idempotency_key(&cid, 2));+}++#[tokio::test]+async fn past_wait_hours_it_waited_too_long_once_and_wait_more_rearms_it() {+ let e = setup("on").await;+ let t = new_task(&e).await;+ let cid = add_scripted(&e, &t, "a", &[75, 75, 75, 0], json!({"wait_hours": 1, "recheck_mins": 5})).await;+ let now = Utc::now();+ hand_in(&e, &t).await;+ let deadline = at(&check(&task(&e, &t.id).await, &cid)["wait_until"]);+ assert!(near(deadline, now + Duration::hours(1)));++ assert_eq!(missions::checks::run_due(&e.state, now + Duration::hours(2)).await, 1);+ let v = task(&e, &t.id).await;+ let c = check(&v, &cid);+ assert_eq!(c["status"], "error", "{c}");+ assert!(!c["timed_out_at"].is_null(), "{c}");+ assert_eq!(v["task"]["state"], "review", "it stays in review for the person: {v}");+ assert_eq!(v["task"]["attempts"], 0);+ assert_eq!(v["task"]["checks_summary"]["status"], "pending", "{v}");+ assert_eq!(v["task"]["checks_summary"]["failed"], 0);+ let failures = e.state.db.failures_of(&t.id).await.unwrap();+ assert_eq!(failures.len(), 1, "{failures:?}");+ assert_eq!(failures[0].class, "waited_too_long");+ let attempts = e.state.db.attempts_of(&t.id).await.unwrap();+ assert!(attempts.iter().all(|a| a.status == "skipped" && a.reason.starts_with("not_retryable")), "never retried: {attempts:?}");+ let items = v["task"]["needs_you"].as_array().unwrap();+ assert_eq!(items.len(), 1, "one Needs-you item: {items:?}");+ assert_eq!(items[0]["kind"], "check_timed_out");+ assert_eq!(items[0]["id"], cid.as_str());+ let text = items[0]["text"].as_str().unwrap();+ assert!(text.contains("didn't answer in 1 h. Wait longer, or verify by hand."), "{text}");+ assert_eq!(items[0]["actions"], json!(["wait_more", "verify"]));+ // Not waiting any more: the tick leaves it alone+ assert_eq!(missions::checks::run_due(&e.state, now + Duration::hours(3)).await, 0);++ // "Wait 24 h more" is the person's+ let token = t.token.clone();+ let (status, _) = call(&e.app, "POST", &format!("/api/checks/{cid}/wait-more"), Some(&token), None).await;+ assert_eq!(status, StatusCode::FORBIDDEN);+ let c = person(&e, "POST", &format!("/api/checks/{cid}/wait-more"), None).await;+ assert_eq!(c["status"], "waiting", "{c}");+ assert!(near(at(&c["wait_until"]), deadline + Duration::hours(24)), "{c}");+ assert!(at(&c["next_run_at"]) <= Utc::now(), "due at once: {c}");+ assert_eq!(task(&e, &t.id).await["task"]["needs_you"], json!([]));++ assert_eq!(missions::checks::run_due(&e.state, now + Duration::hours(2)).await, 1);+ assert_eq!(check(&task(&e, &t.id).await, &cid)["status"], "waiting", "inside the new deadline");+ assert_eq!(missions::checks::run_due(&e.state, now + Duration::hours(2) + Duration::minutes(6)).await, 1);+ let v = task(&e, &t.id).await;+ assert_eq!(check(&v, &cid)["status"], "passed", "{v}");+ assert_eq!(v["task"]["state"], "verified");+ assert_eq!(e.state.db.failures_of(&t.id).await.unwrap().len(), 1, "still the one failure");+ // The key never changed: all four runs were round 1+ let log = env_log(&t.dir, "a");+ assert_eq!(log.len(), 4);+ assert!(log.iter().all(|l| l[0] == "1" && l[2] == log[0][2]), "{log:?}");+}++#[tokio::test]+async fn a_check_that_waited_too_long_can_be_verified_by_hand() {+ let e = setup("on").await;+ let t = new_task(&e).await;+ let cid = add_scripted(&e, &t, "a", &[75, 75], json!({"wait_hours": 1})).await;+ let now = Utc::now();+ hand_in(&e, &t).await;+ missions::checks::run_due(&e.state, now + Duration::hours(2)).await;+ assert!(!check(&task(&e, &t.id).await, &cid)["timed_out_at"].is_null());+ person(&e, "POST", &format!("/api/tasks/{}/verify", t.id), Some(json!({"note": "checked the dashboard"}))).await;+ let v = task(&e, &t.id).await;+ assert_eq!(v["task"]["state"], "verified", "{v}");+ assert_eq!(v["task"]["needs_you"], json!([]));+}++#[tokio::test]+async fn a_restart_keeps_a_waiting_check_and_its_schedule() {+ let e = setup("on").await;+ let t = new_task(&e).await;+ let cid = add_scripted(&e, &t, "a", &[75, 75], json!({"recheck_mins": 30})).await;+ let other = add_scripted(&e, &t, "b", &[75, 75], json!({})).await;+ hand_in(&e, &t).await;+ let before = e.state.db.get_check(&cid).await.unwrap().unwrap();+ assert_eq!(before.status, "waiting");+ // kwnt stops while `other` runs again+ assert!(e.state.db.start_check(&other).await.unwrap());++ let db = Database::init(e.tmp.path()).await.unwrap();+ let after = db.get_check(&cid).await.unwrap().unwrap();+ assert_eq!(after.status, "waiting");+ assert_eq!(after.next_run_at, before.next_run_at, "the schedule survives");+ assert_eq!(after.wait_until, before.wait_until);+ assert_eq!(after.waiting_since, before.waiting_since);+ assert_eq!(after.runs, 1);+ let cut = db.get_check(&other).await.unwrap().unwrap();+ assert_eq!(cut.status, "waiting", "a waiting check cut short by the restart waits again, not error");+ assert!(cut.next_run_at.unwrap() <= Utc::now(), "and is due at once");+ assert_eq!(db.due_waiting_checks(Utc::now(), 10).await.unwrap().len(), 1);+}++#[tokio::test]+async fn a_database_from_before_waiting_checks_is_rebuilt_with_its_rows_and_triggers() {+ use sqlx::sqlite::SqlitePoolOptions;+ let e = setup("off").await;+ let t = new_task(&e).await;+ let cid = add_check(&e, &t, "file_exists", json!({"path": "x"})).await;+ let url = format!("sqlite://{}", e.tmp.path().join("kwnt.db").display());+ let pool = SqlitePoolOptions::new().max_connections(1).connect(&url).await.unwrap();+ let triggers = || async {+ let (n,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM sqlite_master WHERE type = 'trigger'").fetch_one(&pool).await.unwrap();+ n+ };+ let count = triggers().await;+ // Put both CHECK lists back as an older kwant made them+ let mut conn = pool.acquire().await.unwrap();+ sqlx::query("PRAGMA foreign_keys = OFF").execute(&mut *conn).await.unwrap();+ sqlx::query("PRAGMA legacy_alter_table = ON").execute(&mut *conn).await.unwrap();+ for (table, new, old) in [+ ("outcome_checks", "'failed', 'error', 'waiting'))", "'failed', 'error'))"),+ ("task_failures", "'unknown', 'waited_too_long'))", "'unknown'))"),+ ] {+ let (sql,): (String,) = sqlx::query_as("SELECT sql FROM sqlite_master WHERE name = ?").bind(table).fetch_one(&mut *conn).await.unwrap();+ assert!(sql.contains(new), "{sql}");+ let old_sql = sql.replace(new, old).replacen(&format!("CREATE TABLE {table} "), &format!("CREATE TABLE {table}_old "), 1);+ sqlx::query(&old_sql).execute(&mut *conn).await.unwrap();+ sqlx::query(&format!("INSERT INTO {table}_old SELECT * FROM {table}")).execute(&mut *conn).await.unwrap();+ sqlx::query(&format!("DROP TABLE {table}")).execute(&mut *conn).await.unwrap();+ sqlx::query(&format!("ALTER TABLE {table}_old RENAME TO {table}")).execute(&mut *conn).await.unwrap();+ }+ let (sql,): (String,) = sqlx::query_as("SELECT sql FROM sqlite_master WHERE name = 'outcome_checks'").fetch_one(&mut *conn).await.unwrap();+ assert!(!sql.contains("'waiting'"));+ drop(conn);+ pool.close().await;++ let db = Database::init(e.tmp.path()).await.unwrap();+ let pool = SqlitePoolOptions::new().max_connections(1).connect(&url).await.unwrap();+ for (table, want) in [("outcome_checks", "'waiting'"), ("task_failures", "'waited_too_long'")] {+ let (sql,): (String,) = sqlx::query_as("SELECT sql FROM sqlite_master WHERE name = ?").bind(table).fetch_one(&pool).await.unwrap();+ assert!(sql.contains(want), "{table}: {sql}");+ }+ let (n,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM sqlite_master WHERE type = 'trigger'").fetch_one(&pool).await.unwrap();+ assert!(n >= count, "every trigger is back: {n} of {count}");+ assert_eq!(db.get_check(&cid).await.unwrap().unwrap().kind, "file_exists", "rows kept");+ pool.close().await;+}++/// A server whose `/job` and `/page` answer the next queued `(status, body)` each.+async fn server(job: Vec<(u16, &'static str)>, page: Vec<(u16, &'static str)>) -> String {+ type Q = Arc<Mutex<VecDeque<(u16, &'static str)>>>;+ async fn next(State(q): State<Q>) -> (StatusCode, &'static str) {+ let (s, b) = q.lock().unwrap().pop_front().unwrap_or((500, "empty"));+ (StatusCode::from_u16(s).unwrap(), b)+ }+ let app = Router::new()+ .route("/job", get(next).with_state(Arc::new(Mutex::new(VecDeque::from(job)))))+ .route("/page", get(next).with_state(Arc::new(Mutex::new(VecDeque::from(page)))));+ let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = l.local_addr().unwrap();+ tokio::spawn(async move { axum::serve(l, app).await.unwrap() });+ format!("http://{addr}")+}++#[tokio::test]+async fn http_waiting_status_and_waiting_contains() {+ let e = setup("on").await;+ let base = server(vec![(202, "queued"), (200, "ok")], vec![(200, "status: pending"), (200, "status: done")]).await;+ let t = new_task(&e).await;+ let job = add_check(&e, &t, "http", json!({"url": format!("{base}/job"), "waiting_status": 202})).await;+ let page = add_check(&e, &t, "http", json!({"url": format!("{base}/page"), "contains": "status", "waiting_contains": "pending"})).await;+ let now = Utc::now();+ hand_in(&e, &t).await;+ let v = task(&e, &t.id).await;+ assert_eq!(check(&v, &job)["status"], "waiting", "202 is a 2xx, but the waiting status: {v}");+ assert_eq!(check(&v, &page)["status"], "waiting", "contains matched, but so did waiting_contains: {v}");+ assert!(check(&v, &page)["output_excerpt"].as_str().unwrap().contains("not ready yet"));+ assert_eq!(v["task"]["state"], "review");+ assert!(e.state.db.failures_of(&t.id).await.unwrap().is_empty());++ assert_eq!(missions::checks::run_due(&e.state, now + Duration::minutes(16)).await, 2);+ let v = task(&e, &t.id).await;+ assert_eq!(check(&v, &job)["status"], "passed", "{v}");+ assert_eq!(check(&v, &page)["status"], "passed", "{v}");+ assert_eq!(v["task"]["state"], "verified");+}++#[tokio::test]+async fn bots_can_set_the_wait_fields_within_their_bounds() {+ let e = setup("off").await;+ let t = new_task(&e).await;+ for (spec, why) in [+ (json!({"command": "true", "recheck_mins": 4}), "recheck_mins"),+ (json!({"command": "true", "recheck_mins": 1441}), "recheck_mins"),+ (json!({"command": "true", "wait_hours": 0}), "wait_hours"),+ (json!({"command": "true", "wait_hours": 337}), "wait_hours"),+ (json!({"command": "true", "wait_hours": "a day"}), "wait_hours"),+ ] {+ let (fine, text) = tool(&e, &t.token, "task_request_check", json!({"task_id": t.id, "kind": "command", "spec": spec})).await;+ assert!(!fine && text.contains(why), "{spec}: {text}");+ }+ let (fine, text) = tool(&e, &t.token, "task_request_check", json!({"task_id": t.id, "kind": "http", "spec": {"url": "https://example.com", "waiting_status": 42}})).await;+ assert!(!fine && text.contains("waiting_status"), "{text}");+ // In range: accepted (a bot's command check still waits for the person's approval, as before)+ let (fine, text) = tool(&e, &t.token, "task_request_check", json!({"task_id": t.id, "kind": "command", "spec": {"command": "true", "recheck_mins": 5, "wait_hours": 336}})).await;+ assert!(fine, "{text}");+ let (fine, text) = tool(&e, &t.token, "mission_plan", json!({+ "title": "Gate", "goal": "wait on a job",+ "tasks": [{"key": "a", "title": "Job", "owner": e.bot.id, "checks": [{"kind": "command", "spec": {"command": "true", "recheck_mins": 2}}]}]+ })).await;+ assert!(!fine && text.contains("recheck_mins"), "{text}");+ let (fine, text) = tool(&e, &t.token, "mission_plan", json!({+ "title": "Gate", "goal": "wait on a job",+ "tasks": [{"key": "a", "title": "Job", "owner": e.bot.id, "checks": [{"kind": "command", "spec": {"command": "true", "recheck_mins": 1440, "wait_hours": 1}}]}]+ })).await;+ assert!(fine, "{text}");+}