Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

Routines carry a class, acceptance and checks for each run's task (Automation Discovery step 1)

Lin (kwant bot)061ad1dfb8cb
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3ed98782..6ce7837c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,13 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
## Unreleased
+### Added
+- **Routines can say what a good run is.** A routine can carry a Flight School class, a description
+ of a good result and checks. Each run's board task gets them, with the checks already approved, so a
+ run that passes its checks is verified on its own. Only the person sets the class and the checks; a
+ bot that tries gets a 403. Routines without them run as before. This is the first step of
+ Automation Discovery (Mission Control Phase D4).
+
### Changed
- **kwant.si footer says "Made in Germany with ❤️".** The line sits under the trademark note on every
page; screen readers read it as "Made in Germany with love".
diff --git a/docs/mission-control.md b/docs/mission-control.md
index dba9336c..c32d0bbb 100644
--- a/docs/mission-control.md
+++ b/docs/mission-control.md
@@ -257,7 +257,7 @@ and when a task is verified or failed.
| `mission` | `mission_plan` / `POST /api/missions` | backlog → ready after approval |
| `person` | `POST /api/tasks` | ready (backlog if it has unverified deps) |
| `delegation` | a team lead hands work on (`delegate` tool or @mention in a team chat) | working (kwant holds the specialist's lease) → review when the hand-off completes, failed if it fails, cancelled if cancelled. Inside a mission task, it joins that mission. |
-| `routine` | a routine run starts | working → review when it completes, failed if it fails |
+| `routine` | a routine run starts | working → review when it completes, failed if it fails; with the routine's class, acceptance and checks (§20), verified when they pass |
| `zombie` | the person takes a Loose End on (`POST /api/tasks {source_kind:"zombie", source_id}`), or kwant starts its owner turn | ready, or working while the owner turn runs |
| `work_ahead` | a work-ahead run posts its message | review |
@@ -866,3 +866,33 @@ early ends its run `failed`. One Foundry turn runs at a time server-wide.
Not built yet: recording `skill_id@version` on a task's claim, and warning when a bot lost a listed
tool.
+
+## 20. Automation Discovery (Phase D4)
+
+Design note: `phase-d/automation-discovery.md`. v1 learns only from board tasks the person created.
+**Build step 1 (shipped): what a routine's runs are held to.** The scanner, offers and Accept come
+later.
+
+**Routine outcomes.** Every routine can carry, besides its instructions:
+- `task_class`: the Flight School class of each run's task (§14). `null`, `""` or `general` clear it.
+- `acceptance`: what a good result is, up to 4,000 characters. Without it, a run's task uses the
+ instructions, as before.
+- `checks`: up to 10 `[{kind, spec, required = true}]`, validated like task checks (no `person` or
+ `peer_review` checks). `null` or `[]` clear them.
+
+`POST`/`PATCH /api/routines` take them, and the routine views return them. Check specs are shown with
+secrets masked, and a spec containing `[redacted]` is refused, so a masked spec can't be saved back.
+When a run starts, its board task gets the class (event actor `person`), the acceptance and a copy of
+each check, already approved by the person. When the run ends `ok`, the checks run and can take the
+task to `verified`. A routine without these fields runs exactly as before.
+
+**The class and checks are the person's.** A bot's turn token on `POST`/`PATCH /api/routines`, or the
+bot's own routine tools, get a 403 when they set `task_class` or `checks`. Bots may still change
+everything else, the acceptance included, and their changes keep the person's class and checks. An
+undone delete brings back the class, the acceptance and the checks. The exception is a check whose spec
+held a secret: its stored spec is never shown, so the undo can't restore it.
+
+**Storage** (add-only, idempotent): `routines` gains nullable `origin` (`discovery` for an accepted
+offer), `suggestion_id`, `task_class`, `acceptance` and `checks` (JSON). `routine_suggestions` holds
+offers, with one live offer per `(space_id, cluster_key)`. `routine_suggestion_events` is their
+append-only history, enforced by triggers. Older binaries ignore all of it.
diff --git a/src/db/automation.rs b/src/db/automation.rs
new file mode 100644
index 00000000..336e386b
--- /dev/null
+++ b/src/db/automation.rs
@@ -0,0 +1,72 @@
+//! Mission Control Phase D4: Automation Discovery's storage, and what every routine can now carry
+//! for the board: a Flight School class, a description of a good result and checks, copied onto
+//! each run's task. Add-only: older binaries ignore all of it, and running it twice changes
+//! nothing. See docs/mission-control.md §20.
+
+use super::{Database, DbError};
+
+/// Routine columns this migration adds, all nullable: a routine without them runs as before.
+/// `origin` is `NULL` (made by hand or by a bot) or `discovery`; `checks` is JSON
+/// `[{kind, spec, required}]`.
+const ROUTINE_COLUMNS: [&str; 5] = ["origin", "suggestion_id", "task_class", "acceptance", "checks"];
+
+impl Database {
+ pub(super) async fn migrate_automation_discovery(&self) -> Result<(), DbError> {
+ let cols: Vec<(String,)> = sqlx::query_as("SELECT name FROM pragma_table_info('routines')").fetch_all(&self.pool).await?;
+ for column in ROUTINE_COLUMNS {
+ if !cols.iter().any(|(c,)| c == column) {
+ sqlx::query(&format!("ALTER TABLE routines ADD COLUMN {column} TEXT")).execute(&self.pool).await?;
+ }
+ }
+ for stmt in [
+ "CREATE TABLE IF NOT EXISTS routine_suggestions (
+ id TEXT PRIMARY KEY,
+ space_id TEXT NOT NULL,
+ cluster_key TEXT NOT NULL,
+ kwant_id TEXT NOT NULL,
+ name TEXT NOT NULL,
+ instructions TEXT NOT NULL,
+ schedule TEXT NOT NULL,
+ first_run_at TIMESTAMP NOT NULL,
+ delivery TEXT NOT NULL,
+ task_class TEXT NOT NULL DEFAULT 'general',
+ acceptance TEXT NOT NULL DEFAULT '',
+ checks TEXT NOT NULL DEFAULT '[]',
+ left_out_checks TEXT NOT NULL DEFAULT '[]',
+ chain TEXT NOT NULL DEFAULT '[]',
+ source_task_ids TEXT NOT NULL,
+ evidence TEXT NOT NULL,
+ status TEXT NOT NULL CHECK (status IN ('offered', 'accepted', 'dismissed', 'expired', 'superseded')),
+ routine_id TEXT,
+ cooldown_until TIMESTAMP,
+ routine_deleted_at TIMESTAMP,
+ retention TEXT CHECK (retention IS NULL OR retention IN ('retained', 'dropped')),
+ retention_at TIMESTAMP,
+ offered_at TIMESTAMP NOT NULL,
+ decided_at TIMESTAMP
+ )",
+ // One live offer per habit: racing scans insert with ON CONFLICT DO NOTHING
+ "CREATE UNIQUE INDEX IF NOT EXISTS routine_suggestions_one_live
+ ON routine_suggestions (space_id, cluster_key) WHERE status = 'offered'",
+ "CREATE INDEX IF NOT EXISTS routine_suggestions_key ON routine_suggestions (space_id, cluster_key, decided_at)",
+ "CREATE TABLE IF NOT EXISTS routine_suggestion_events (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ suggestion_id TEXT NOT NULL,
+ kind TEXT NOT NULL CHECK (kind IN ('offered', 'accepted', 'dismissed', 'expired', 'superseded',
+ 'enabled', 'disabled', 'deleted', 'retained', 'dropped')),
+ actor TEXT NOT NULL,
+ detail TEXT NOT NULL DEFAULT '{}',
+ created_at TIMESTAMP NOT NULL
+ )",
+ "CREATE INDEX IF NOT EXISTS routine_suggestion_events_by ON routine_suggestion_events (suggestion_id, id)",
+ // The history is append-only
+ "CREATE TRIGGER IF NOT EXISTS routine_suggestion_events_no_update BEFORE UPDATE ON routine_suggestion_events
+ BEGIN SELECT RAISE(ABORT, 'routine_suggestion_events is append-only'); END",
+ "CREATE TRIGGER IF NOT EXISTS routine_suggestion_events_no_delete BEFORE DELETE ON routine_suggestion_events
+ BEGIN SELECT RAISE(ABORT, 'routine_suggestion_events is append-only'); END",
+ ] {
+ sqlx::query(stmt).execute(&self.pool).await?;
+ }
+ Ok(())
+ }
+}
diff --git a/src/db/continuity.rs b/src/db/continuity.rs
index 176c6f50..37dc8a1f 100644
--- a/src/db/continuity.rs
+++ b/src/db/continuity.rs
@@ -199,6 +199,15 @@ pub struct RoutineRow {
pub thread_id: Option<String>,
/// A message in the delivery chat the routine follows up on; its run gets that exchange.
pub context_message_id: Option<String>,
+ /// `discovery` when Automation Discovery suggested it and the person accepted; else empty.
+ pub origin: Option<String>,
+ pub suggestion_id: Option<String>,
+ /// What each run's board task carries: its Flight School class, a good result, and its checks
+ /// (JSON `[{kind, spec, required}]`, set by the person only). Empty: as before, the
+ /// instructions are the acceptance and the task has no checks.
+ pub task_class: Option<String>,
+ pub acceptance: Option<String>,
+ pub checks: Option<String>,
}
#[derive(Debug, Clone, Serialize, FromRow, PartialEq)]
@@ -213,7 +222,7 @@ pub struct RoutineRun {
pub message_id: Option<String>,
}
-#[derive(Debug, Clone)]
+#[derive(Debug, Clone, Default)]
pub struct NewRoutine {
pub kwant_id: String,
pub channel_id: Option<String>,
@@ -225,10 +234,18 @@ pub struct NewRoutine {
pub next_run_at: Option<DateTime<Utc>>,
pub thread_id: Option<String>,
pub context_message_id: Option<String>,
+ /// Kept through edits; only Automation Discovery's accept sets them.
+ pub origin: Option<String>,
+ pub suggestion_id: Option<String>,
+ pub task_class: Option<String>,
+ pub acceptance: Option<String>,
+ /// Checks JSON, already validated.
+ pub checks: Option<String>,
}
const ROUTINE_SELECT: &str = "SELECT r.id, r.kwant_id, r.channel_id, r.name, r.instructions, r.schedule, r.enabled, \
r.next_run_at, r.last_run_at, r.created_at, r.space_id, r.thread_id, r.context_message_id, \
+ r.origin, r.suggestion_id, r.task_class, r.acceptance, r.checks, \
(SELECT status FROM routine_runs x WHERE x.routine_id = r.id ORDER BY x.started_at DESC, x.rowid DESC LIMIT 1) AS last_status \
FROM routines r";
@@ -698,7 +715,8 @@ impl Database {
let id = Uuid::new_v4().to_string();
sqlx::query(
"INSERT INTO routines (id, kwant_id, channel_id, name, instructions, schedule, enabled, next_run_at, created_at, space_id, \
- thread_id, context_message_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ thread_id, context_message_id, origin, suggestion_id, task_class, acceptance, checks) \
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
)
.bind(&id)
.bind(&input.kwant_id)
@@ -712,6 +730,11 @@ impl Database {
.bind(space.as_str())
.bind(&input.thread_id)
.bind(&input.context_message_id)
+ .bind(&input.origin)
+ .bind(&input.suggestion_id)
+ .bind(&input.task_class)
+ .bind(&input.acceptance)
+ .bind(&input.checks)
.execute(&self.pool)
.await?;
self.get_routine(&id)
@@ -740,7 +763,8 @@ impl Database {
let space = self.routine_space(input).await?;
let res = sqlx::query(
"UPDATE routines SET kwant_id = ?, channel_id = ?, name = ?, instructions = ?, schedule = ?, enabled = ?, \
- next_run_at = ?, space_id = ?, thread_id = ?, context_message_id = ? WHERE id = ?",
+ next_run_at = ?, space_id = ?, thread_id = ?, context_message_id = ?, task_class = ?, acceptance = ?, checks = ? \
+ WHERE id = ?",
)
.bind(&input.kwant_id)
.bind(&input.channel_id)
@@ -752,6 +776,9 @@ impl Database {
.bind(space.as_str())
.bind(&input.thread_id)
.bind(&input.context_message_id)
+ .bind(&input.task_class)
+ .bind(&input.acceptance)
+ .bind(&input.checks)
.bind(id)
.execute(&self.pool)
.await?;
diff --git a/src/db/mod.rs b/src/db/mod.rs
index 88ed003e..d990a641 100644
--- a/src/db/mod.rs
+++ b/src/db/mod.rs
@@ -32,6 +32,7 @@ pub mod flight_school;
pub mod performance;
pub mod auditor;
pub mod foundry;
+pub mod automation;
/// What a space's #general says about itself.
pub const GENERAL_DESCRIPTION: &str = "Everyone in this space. Laya picks who answers.";
@@ -194,6 +195,8 @@ impl Database {
// Phase D2: audits and their risks (add-only)
db.migrate_auditor().await?;
db.migrate_foundry().await?;
+ // Phase D4: routines carry class, acceptance and checks; suggestion storage (add-only)
+ db.migrate_automation_discovery().await?;
db.pool.close().await;
let pool = SqlitePoolOptions::new()
diff --git a/src/server/bot_actions.rs b/src/server/bot_actions.rs
index e70617ae..120e9ef2 100644
--- a/src/server/bot_actions.rs
+++ b/src/server/bot_actions.rs
@@ -10,7 +10,7 @@
#![allow(clippy::result_large_err)]
use super::continuity::SelfScope;
-use super::scheduler::RoutinePayload;
+use super::scheduler::{By, RoutinePayload};
use super::spaces::Scope;
use super::AppState;
use crate::db::bot_actions::{BotAction, NewBotAction, ACTION_STATUSES, MAX_PER_TURN};
@@ -786,14 +786,9 @@ impl Ctx<'_> {
enabled: Some(true),
thread_id: Some(thread_id),
context_message_id: Some(context_message_id),
+ ..Default::default()
};
- let resp = super::scheduler::create(
- State(self.state.clone()),
- Scope(self.space.clone()),
- space_uri("/api/routines", &self.space),
- Json(payload),
- )
- .await;
+ let resp = super::scheduler::create_by(self.state, self.space.clone(), space_uri("/api/routines", &self.space), payload, By::Bot).await;
let view = match read(resp).await {
Ok(v) => v,
Err(e) => return fail(format!("The routine was not created: {e}")),
@@ -868,14 +863,9 @@ impl Ctx<'_> {
enabled: Some(true),
thread_id: Some(thread),
context_message_id: Some(self.anchor().await),
+ ..Default::default()
};
- let resp = super::scheduler::create(
- State(self.state.clone()),
- Scope(self.space.clone()),
- space_uri("/api/routines", &self.space),
- Json(payload),
- )
- .await;
+ let resp = super::scheduler::create_by(self.state, self.space.clone(), space_uri("/api/routines", &self.space), payload, By::Bot).await;
let view = match read(resp).await {
Ok(v) => v,
Err(e) => return fail(format!("The follow-up was not scheduled: {e}")),
@@ -894,7 +884,7 @@ impl Ctx<'_> {
async fn routine_patch(&self, action: &str, row: crate::db::continuity::RoutineRow, payload: RoutinePayload, verb: &str) -> ToolResult {
let before = serde_json::to_value(super::scheduler::RoutineView::from(row.clone())).unwrap_or(Value::Null);
- let resp = super::scheduler::update(State(self.state.clone()), Path(row.id.clone()), Json(payload)).await;
+ let resp = super::scheduler::update_by(self.state, row.id.clone(), payload, By::Bot).await;
let view = match read(resp).await {
Ok(v) => v,
Err(e) => return fail(format!("The routine was not changed: {e}")),
@@ -1801,6 +1791,20 @@ fn routine_payload(before: &Value) -> Result<RoutinePayload, Response> {
enabled: before["enabled"].as_bool(),
thread_id: Some(before["thread_id"].as_str().map(str::to_string)),
context_message_id: Some(before["context_message_id"].as_str().map(str::to_string)),
+ // A bot never changes these, so an undone change keeps them; see `deleted_routine_payload`
+ ..Default::default()
+ })
+}
+
+/// What an undone delete recreates: [`routine_payload`] plus what each run's task carried. The
+/// snapshot shows checks masked, so a check with a masked secret can't come back and is left out.
+fn deleted_routine_payload(before: &Value) -> Result<RoutinePayload, Response> {
+ let checks: Vec<super::scheduler::RoutineCheck> = serde_json::from_value(before["checks"].clone()).unwrap_or_default();
+ Ok(RoutinePayload {
+ task_class: Some(before["task_class"].as_str().map(str::to_string)),
+ acceptance: Some(before["acceptance"].as_str().map(str::to_string)),
+ checks: Some(Some(checks.into_iter().filter(|c| !c.spec.to_string().contains("[redacted]")).collect())),
+ ..routine_payload(before)?
})
}
@@ -1815,12 +1819,12 @@ async fn undo_action(state: &AppState, a: &BotAction) -> Result<Option<String>,
}
"routine_update" | "routine_pause" | "routine_resume" => {
let p = routine_payload(&before)?;
- ok_or_conflict(super::scheduler::update(State(state.clone()), Path(target), Json(p)).await, "the routine can't be put back")
+ ok_or_conflict(super::scheduler::update_by(state, target, p, By::Person).await, "the routine can't be put back")
.await?;
}
"routine_delete" => {
- let p = routine_payload(&before)?;
- let resp = super::scheduler::create(State(state.clone()), Scope(space.clone()), space_uri("/api/routines", &space), Json(p)).await;
+ let p = deleted_routine_payload(&before)?;
+ let resp = super::scheduler::create_by(state, space.clone(), space_uri("/api/routines", &space), p, By::Person).await;
let created = ok_or_conflict(resp, "the routine can't be recreated").await?;
return Ok(created["id"].as_str().map(str::to_string));
}
diff --git a/src/server/missions/listener.rs b/src/server/missions/listener.rs
index 6ad74329..1887c484 100644
--- a/src/server/missions/listener.rs
+++ b/src/server/missions/listener.rs
@@ -6,7 +6,7 @@
use super::checks::run_task_checks;
use super::{lease_ms, transition, Actor};
-use crate::db::missions::{NewTask, Task, TaskChange};
+use crate::db::missions::{NewCheck, NewTask, Task, TaskChange};
use crate::db::spaces::SpaceId;
use crate::drivers::events::RuntimeEvent;
use crate::server::AppState;
@@ -95,6 +95,45 @@ async fn mission_of_holder(state: &AppState, kwant_id: &str) -> Option<String> {
}
/// Creates a working task held by kwant for `owner` (a hand-off or routine run), or `None`.
+#[allow(clippy::too_many_arguments)]
+/// What a routine gives each run's task besides its acceptance: a class and the checks the
+/// person set on the routine (approved by the person, who set them there).
+struct RunOutcome {
+ task_class: Option<String>,
+ checks: Vec<crate::server::scheduler::RoutineCheck>,
+}
+
+impl RunOutcome {
+ fn of(r: &crate::db::continuity::RoutineRow) -> Self {
+ Self {
+ task_class: r.task_class.clone(),
+ checks: r.checks.as_deref().and_then(|c| serde_json::from_str(c).ok()).unwrap_or_default(),
+ }
+ }
+
+ async fn apply(&self, state: &AppState, task_id: &str) {
+ if let Some(class) = self.task_class.as_deref().filter(|c| *c != crate::db::flight_school::DEFAULT_CLASS) {
+ if let Err(e) = state.db.set_task_class(task_id, class, "person").await {
+ tracing::warn!(error = %e, "could not set a routine task's class");
+ }
+ }
+ for c in &self.checks {
+ let nc = NewCheck {
+ task_id: task_id.into(),
+ kind: c.kind.clone(),
+ spec: c.spec.clone(),
+ required: c.required,
+ approved: true,
+ requested_by: "person".into(),
+ approved_by: Some("person".into()),
+ };
+ if let Err(e) = state.db.add_check(&nc).await {
+ tracing::warn!(error = %e, "could not add a routine task's check");
+ }
+ }
+ }
+}
+
#[allow(clippy::too_many_arguments)]
async fn start_held(
state: &AppState,
@@ -107,6 +146,7 @@ async fn start_held(
source_id: &str,
place: (Option<String>, Option<String>, Option<String>),
context_id: &str,
+ outcome: Option<&RunOutcome>,
) -> Option<Task> {
let budget_tokens = super::default_task_budget(state).await;
let new = |mission_id: Option<String>| NewTask {
@@ -135,6 +175,9 @@ async fn start_held(
return None;
}
};
+ if let Some(o) = outcome {
+ o.apply(state, &task.id).await;
+ }
hold(state, &task, owner, context_id).await;
state.db.get_task(&task.id).await.ok().flatten()
}
@@ -211,7 +254,7 @@ pub async fn on_delegation(state: &AppState, delegation_id: &str) {
let mission = mission_of_holder(state, &d.lead_kwant_id).await;
let title = if d.title.trim().is_empty() { d.task.lines().next().unwrap_or("Hand-off").to_string() } else { d.title.clone() };
let place = (None, None, Some(d.thread_id.clone()));
- task = start_held(state, &space, mission, &title, &d.task, &d.specialist_kwant_id, "delegation", &d.id, place, &d.thread_id).await;
+ task = start_held(state, &space, mission, &title, &d.task, &d.specialist_kwant_id, "delegation", &d.id, place, &d.thread_id, None).await;
if live || task.is_none() {
return;
}
@@ -474,7 +517,9 @@ pub async fn on_routine_run(state: &AppState, routine_id: &str, run_id: &str, st
let direct = if r.channel_id.is_none() && r.thread_id.is_none() { Some(r.kwant_id.clone()) } else { None };
let place = (r.channel_id.clone(), direct, r.thread_id.clone());
let title = format!("Routine: {}", r.name);
- start_held(state, &space, None, &title, &r.instructions, &r.kwant_id, "routine", run_id, place, &context).await;
+ let outcome = RunOutcome::of(&r);
+ let acceptance = r.acceptance.as_deref().unwrap_or(&r.instructions);
+ start_held(state, &space, None, &title, acceptance, &r.kwant_id, "routine", run_id, place, &context, Some(&outcome)).await;
}
(Some(t), "running") => {
let _ = state.db.refresh_claim(&t.id, lease_ms(state).await).await;
diff --git a/src/server/scheduler.rs b/src/server/scheduler.rs
index 9ec0a040..d55bdcdb 100644
--- a/src/server/scheduler.rs
+++ b/src/server/scheduler.rs
@@ -13,7 +13,7 @@ use crate::drivers::events::RuntimeEvent;
use crate::routines::Schedule;
use axum::{
extract::{Path, Query, State},
- http::StatusCode,
+ http::{HeaderMap, StatusCode},
response::{IntoResponse, Response},
Json,
};
@@ -27,6 +27,9 @@ use tokio_util::sync::CancellationToken;
pub const MAX_SLEEP: Duration = Duration::from_secs(30);
const MAX_NAME_CHARS: usize = 100;
const MAX_ROUTINE_INSTRUCTIONS_CHARS: usize = 4000;
+const MAX_ACCEPTANCE_CHARS: usize = 4000;
+/// Checks one routine copies onto each run's task.
+const MAX_ROUTINE_CHECKS: usize = 10;
fn error(status: StatusCode, message: impl Into<String>) -> Response {
(status, Json(json!({ "error": message.into() }))).into_response()
@@ -65,6 +68,16 @@ pub struct RoutineView {
pub thread_id: Option<String>,
/// The message it follows up on (in the chat it delivers to), when it is a follow-up.
pub context_message_id: Option<String>,
+ /// `"discovery"` when the person accepted an Automation Discovery suggestion; else `null`.
+ pub origin: Option<String>,
+ pub suggestion_id: Option<String>,
+ /// Each run's board task gets this Flight School class (`null`: `general`).
+ pub task_class: Option<String>,
+ /// Each run's board task's acceptance (`null`: the instructions, as before).
+ pub acceptance: Option<String>,
+ /// `[{kind, spec, required}]` each run's task gets, approved by the person; specs are shown
+ /// with secrets masked. `[]`: none.
+ pub checks: serde_json::Value,
}
impl From<RoutineRow> for RoutineView {
@@ -75,6 +88,11 @@ impl From<RoutineRow> for RoutineView {
schedule,
thread_id: r.thread_id,
context_message_id: r.context_message_id,
+ checks: shown_checks(r.checks.as_deref()),
+ origin: r.origin,
+ suggestion_id: r.suggestion_id,
+ task_class: r.task_class,
+ acceptance: r.acceptance,
id: r.id,
kwant_id: r.kwant_id,
channel_id: r.channel_id,
@@ -89,6 +107,33 @@ impl From<RoutineRow> for RoutineView {
}
}
+/// A routine's stored checks, specs masked as everywhere checks are shown.
+fn shown_checks(stored: Option<&str>) -> serde_json::Value {
+ let list: Vec<serde_json::Value> = stored.and_then(|c| serde_json::from_str(c).ok()).unwrap_or_default();
+ serde_json::Value::Array(
+ list.into_iter()
+ .map(|mut c| {
+ c["spec"] = super::missions::autofix::redact_value(&c["spec"]);
+ c
+ })
+ .collect(),
+ )
+}
+
+/// One check a routine copies onto each run's task.
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct RoutineCheck {
+ pub kind: String,
+ #[serde(default)]
+ pub spec: serde_json::Value,
+ #[serde(default = "yes")]
+ pub required: bool,
+}
+
+fn yes() -> bool {
+ true
+}
+
/// `POST /api/routines` body; `PATCH` takes the same fields, all optional.
#[derive(Debug, Deserialize, Default)]
pub struct RoutinePayload {
@@ -106,13 +151,77 @@ pub struct RoutinePayload {
/// A message in the delivery chat this routine follows up on.
#[serde(default, deserialize_with = "double_option")]
pub context_message_id: Option<Option<String>>,
+ /// The Flight School class each run's task gets; `null`, `""` or `"general"` clears it.
+ /// The person's only, like the checks.
+ #[serde(default, deserialize_with = "double_option")]
+ pub task_class: Option<Option<String>>,
+ /// What a good result is, for each run's task; `null` or `""`: the instructions.
+ #[serde(default, deserialize_with = "double_option")]
+ pub acceptance: Option<Option<String>>,
+ /// Checks each run's task gets, approved by the person; `null` or `[]` clears them. The
+ /// person's only: a bot's token gets a 403.
+ #[serde(default, deserialize_with = "double_option")]
+ pub checks: Option<Option<Vec<RoutineCheck>>>,
}
/// Tells a missing field (`None`) from an explicit `null` (`Some(None)`).
-fn double_option<'de, D: serde::Deserializer<'de>>(
- d: D,
-) -> Result<Option<Option<String>>, D::Error> {
- Ok(Some(Option::<String>::deserialize(d)?))
+fn double_option<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(d: D) -> Result<Option<Option<T>>, D::Error> {
+ Ok(Some(Option::<T>::deserialize(d)?))
+}
+
+/// Who sends a routine change: the class and checks a run's task gets are the person's to set.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum By {
+ Person,
+ Bot,
+}
+
+impl RoutinePayload {
+ fn sets_person_fields(&self) -> bool {
+ self.task_class.is_some() || self.checks.is_some()
+ }
+}
+
+/// Merges the class, acceptance and checks of `p` over `existing` and checks them: the JSON to
+/// store for each (`None`: not set).
+#[allow(clippy::type_complexity)]
+fn build_outcome(
+ p: &RoutinePayload,
+ existing: Option<&RoutineRow>,
+) -> Result<(Option<String>, Option<String>, Option<String>), Response> {
+ let bad = |m: &str| error(StatusCode::BAD_REQUEST, m);
+ let task_class = match &p.task_class {
+ Some(c) => c.as_deref().map(str::trim).filter(|c| !c.is_empty() && *c != crate::db::flight_school::DEFAULT_CLASS).map(str::to_string),
+ None => existing.and_then(|e| e.task_class.clone()),
+ };
+ if task_class.as_deref().is_some_and(|c| !crate::db::flight_school::valid_class(c)) {
+ return Err(bad("task_class must be 1–40 of a-z, 0-9 and -"));
+ }
+ let acceptance = match &p.acceptance {
+ Some(a) => a.as_deref().map(str::trim).filter(|a| !a.is_empty()).map(str::to_string),
+ None => existing.and_then(|e| e.acceptance.clone()),
+ };
+ if acceptance.as_deref().is_some_and(|a| a.chars().count() > MAX_ACCEPTANCE_CHARS) {
+ return Err(bad("acceptance must be at most 4000 characters"));
+ }
+ let checks = match &p.checks {
+ Some(list) => {
+ let list = list.as_deref().unwrap_or_default();
+ if list.len() > MAX_ROUTINE_CHECKS {
+ return Err(bad("at most 10 checks"));
+ }
+ for c in list {
+ // Shown masked; one sent back that way would check for the mask
+ if c.spec.to_string().contains("[redacted]") {
+ return Err(bad("a check spec has masked values ([redacted]); send the real ones"));
+ }
+ super::missions::validate_check(&c.kind, &c.spec, true).map_err(|m| bad(&m))?;
+ }
+ (!list.is_empty()).then(|| serde_json::to_string(list).unwrap_or_default())
+ }
+ None => existing.and_then(|e| e.checks.clone()),
+ };
+ Ok((task_class, acceptance, checks))
}
/// Merges `p` over `existing` and checks the result.
@@ -122,6 +231,7 @@ async fn build(
existing: Option<&RoutineRow>,
) -> Result<NewRoutine, Response> {
let bad = |m: &str| error(StatusCode::BAD_REQUEST, m);
+ let (task_class, acceptance, checks) = build_outcome(&p, existing)?;
let kwant_id = p
.kwant_id
.or_else(|| existing.map(|e| e.kwant_id.clone()))
@@ -217,6 +327,11 @@ async fn build(
schedule: serde_json::to_string(&schedule).unwrap_or_default(),
enabled,
next_run_at,
+ origin: existing.and_then(|e| e.origin.clone()),
+ suggestion_id: existing.and_then(|e| e.suggestion_id.clone()),
+ task_class,
+ acceptance,
+ checks,
})
}
@@ -243,9 +358,32 @@ pub async fn create(
State(state): State<AppState>,
Scope(space): Scope,
uri: axum::http::Uri,
+ headers: HeaderMap,
Json(p): Json<RoutinePayload>,
) -> Response {
- let input = match build(&state, p, None).await {
+ let by = caller(&state, &headers).await;
+ create_by(&state, space, uri, p, by).await
+}
+
+/// A bot's turn token, or a bearer that isn't the API token, is a bot; anything else is the person
+/// (auth already let the request in).
+async fn caller(state: &AppState, headers: &HeaderMap) -> By {
+ match super::mcp_suggest::refuse_agent_tokens(state, headers, "").await {
+ Ok(()) => By::Person,
+ Err(_) => By::Bot,
+ }
+}
+
+fn person_fields_refused() -> Response {
+ error(StatusCode::FORBIDDEN, "only the person sets a routine's class and checks")
+}
+
+/// [`create`] for in-process callers: a bot's own tools pass [`By::Bot`].
+pub async fn create_by(state: &AppState, space: crate::db::spaces::SpaceId, uri: axum::http::Uri, p: RoutinePayload, by: By) -> Response {
+ if by == By::Bot && p.sets_person_fields() {
+ return person_fields_refused();
+ }
+ let input = match build(state, p, None).await {
Ok(i) => i,
Err(r) => return r,
};
@@ -267,14 +405,24 @@ pub async fn create(
pub async fn update(
State(state): State<AppState>,
Path(id): Path<String>,
+ headers: HeaderMap,
Json(p): Json<RoutinePayload>,
) -> Response {
+ let by = caller(&state, &headers).await;
+ update_by(&state, id, p, by).await
+}
+
+/// [`update`] for in-process callers: a bot's own tools pass [`By::Bot`].
+pub async fn update_by(state: &AppState, id: String, p: RoutinePayload, by: By) -> Response {
+ if by == By::Bot && p.sets_person_fields() {
+ return person_fields_refused();
+ }
let existing = match state.db.get_routine(&id).await {
Ok(Some(r)) => r,
Ok(None) => return StatusCode::NOT_FOUND.into_response(),
Err(_) => return internal(),
};
- let input = match build(&state, p, Some(&existing)).await {
+ let input = match build(state, p, Some(&existing)).await {
Ok(i) => i,
Err(r) => return r,
};
diff --git a/tests/away_test.rs b/tests/away_test.rs
index 24d00b90..d8edbe34 100644
--- a/tests/away_test.rs
+++ b/tests/away_test.rs
@@ -213,6 +213,7 @@ async fn away_lists_every_kind_filters_caps_and_marks_seen() {
next_run_at: None,
thread_id: None,
context_message_id: None,
+ ..Default::default()
})
.await
.unwrap();
diff --git a/tests/continuity_test.rs b/tests/continuity_test.rs
index 20f449dc..0b5fc7fd 100644
--- a/tests/continuity_test.rs
+++ b/tests/continuity_test.rs
@@ -1301,6 +1301,7 @@ async fn add_routine(
next_run_at: Some(next),
thread_id: None,
context_message_id: None,
+ ..Default::default()
})
.await
.unwrap()
diff --git a/tests/mission_autofix_test.rs b/tests/mission_autofix_test.rs
index 3c0f1040..0d73d24d 100644
--- a/tests/mission_autofix_test.rs
+++ b/tests/mission_autofix_test.rs
@@ -583,6 +583,7 @@ async fn a_failed_routine_run_is_retried_as_a_new_linked_run() {
next_run_at: None,
thread_id: None,
context_message_id: None,
+ ..Default::default()
})
.await
.unwrap();
diff --git a/tests/routine_outcomes_test.rs b/tests/routine_outcomes_test.rs
new file mode 100644
index 00000000..87d900b3
--- /dev/null
+++ b/tests/routine_outcomes_test.rs
@@ -0,0 +1,340 @@
+//! Mission Control Phase D4, build step 1: a routine can carry what each run's board task gets,
+//! a Flight School class, a description of a good result and checks the person approved. The
+//! columns are add-only (a routine without them runs exactly as before), and the class and checks
+//! are the person's: a bot's token, or a bot's own routine tools, can't set them.
+
+use axum::{
+ body::{to_bytes, Body},
+ http::{Request, StatusCode},
+ Router,
+};
+use kwnt::{
+ broker::PermissionBroker,
+ config::Config,
+ db::{continuity::NewRoutine, missions::Task, models::Kwant, spaces::SpaceId, Database},
+ router::LayaRouter,
+ server::{
+ continuity::{SelfScope, TurnOrigin},
+ create_router, mcp_runtime,
+ missions::{self, listener},
+ AppState,
+ },
+ tools::ToolRunner,
+};
+use serde_json::{json, Value};
+use tempfile::{tempdir, TempDir};
+use tower::ServiceExt;
+
+struct Env {
+ app: Router,
+ state: AppState,
+ bot: Kwant,
+ general: String,
+ _tmp: TempDir,
+}
+
+async fn setup() -> Env {
+ let tmp = tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ let config = Config {
+ data_dir: tmp.path().to_path_buf(),
+ laya_url: "http://127.0.0.1:9".into(),
+ browser_cdp_url: Some("http://127.0.0.1:9".into()),
+ ..Config::default()
+ };
+ let state = AppState::new(
+ config.clone(),
+ db,
+ ToolRunner::new(tmp.path().join("workspace")),
+ PermissionBroker::new(),
+ LayaRouter::new(config.laya_url.clone()),
+ );
+ let app = create_router(state.clone());
+ let space = SpaceId::default_space();
+ let bot = state.db.list_kwants(&space).await.unwrap()[0].clone();
+ let general = state.db.list_channels(&space).await.unwrap().into_iter().find(|c| c.name == "general").unwrap().id;
+ let e = Env { app, state, bot, general, _tmp: tmp };
+ person(&e, "POST", "/api/settings", Some(json!({"mission_board": true}))).await;
+ e
+}
+
+async fn send(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) = send(&e.app, method, uri, None, body).await;
+ assert!(status.is_success(), "{method} {uri}: {status} {v}");
+ v
+}
+
+/// A turn of the bot in #general with its own tools; returns the turn token.
+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 tool(e: &Env, token: &str, name: &str, args: Value) -> (String, bool) {
+ let rpc = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": name, "arguments": args}});
+ let (status, v) = send(&e.app, "POST", "/api/mcp/self", Some(token), Some(rpc)).await;
+ assert_eq!(status, StatusCode::OK, "{v}");
+ (v["result"]["content"][0]["text"].as_str().unwrap_or("").to_string(), v["result"]["isError"].as_bool().unwrap_or(false))
+}
+
+fn routine_body(e: &Env, extra: Value) -> Value {
+ let mut body = json!({
+ "kwant_id": e.bot.id,
+ "channel_id": e.general,
+ "name": "Weekly sales report",
+ "instructions": "Write this week's sales report to report.md",
+ "schedule": {"type": "weekly", "time": "09:00", "weekdays": ["mon"], "tz": "UTC"},
+ "enabled": false,
+ });
+ for (k, v) in extra.as_object().unwrap() {
+ body[k] = v.clone();
+ }
+ body
+}
+
+async fn routine(e: &Env, id: &str) -> Value {
+ let list = person(e, "GET", "/api/routines", None).await;
+ list.as_array().unwrap().iter().find(|r| r["id"] == id).cloned().expect("the routine is listed")
+}
+
+/// One run of `rid`: its board task, as it is while the run works.
+async fn start_run(e: &Env, rid: &str) -> (String, Task) {
+ let run = e.state.db.start_routine_run(rid, "schedule", "running", None).await.unwrap();
+ listener::on_routine_run(&e.state, rid, &run.id, "running").await;
+ let task = e.state.db.task_by_source("routine", &run.id).await.unwrap().expect("each run has a task");
+ (run.id, task)
+}
+
+async fn finish_run(e: &Env, rid: &str, run_id: &str) -> Task {
+ e.state.db.finish_routine_run(run_id, "ok", None, None).await.unwrap();
+ listener::on_routine_run(&e.state, rid, run_id, "ok").await;
+ e.state.db.task_by_source("routine", run_id).await.unwrap().unwrap()
+}
+
+#[tokio::test]
+async fn the_migration_runs_twice_on_an_old_database_and_keeps_its_routines() {
+ let tmp = tempdir().unwrap();
+ let data = tmp.path().join("data");
+ let db = Database::init(&data).await.unwrap();
+ let bot = db.list_kwants(&SpaceId::default_space()).await.unwrap()[0].clone();
+ let old = db
+ .create_routine(&NewRoutine {
+ kwant_id: bot.id.clone(),
+ name: "Old routine".into(),
+ instructions: "Do the old thing".into(),
+ schedule: json!({"type": "interval", "every_minutes": 60}).to_string(),
+ enabled: true,
+ ..Default::default()
+ })
+ .await
+ .unwrap();
+ drop(db);
+ // Back to a database from before this migration: no new columns, no new tables
+ let pool = sqlx::SqlitePool::connect(&format!("sqlite://{}", data.join("kwnt.db").display())).await.unwrap();
+ for stmt in [
+ "DROP TABLE routine_suggestion_events",
+ "DROP TABLE routine_suggestions",
+ "ALTER TABLE routines DROP COLUMN origin",
+ "ALTER TABLE routines DROP COLUMN suggestion_id",
+ "ALTER TABLE routines DROP COLUMN task_class",
+ "ALTER TABLE routines DROP COLUMN acceptance",
+ "ALTER TABLE routines DROP COLUMN checks",
+ ] {
+ sqlx::query(stmt).execute(&pool).await.unwrap();
+ }
+ pool.close().await;
+
+ for _ in 0..2 {
+ let db = Database::init(&data).await.unwrap();
+ let r = db.get_routine(&old.id).await.unwrap().expect("the old routine survives");
+ assert_eq!((r.name.as_str(), r.instructions.as_str(), r.enabled), ("Old routine", "Do the old thing", true));
+ assert_eq!(r.schedule, old.schedule);
+ assert_eq!(r.next_run_at, old.next_run_at);
+ assert!(r.origin.is_none() && r.suggestion_id.is_none() && r.task_class.is_none() && r.acceptance.is_none() && r.checks.is_none(), "{r:?}");
+ }
+
+ let pool = sqlx::SqlitePool::connect(&format!("sqlite://{}", data.join("kwnt.db").display())).await.unwrap();
+ let cols: Vec<(String,)> = sqlx::query_as("SELECT name FROM pragma_table_info('routines')").fetch_all(&pool).await.unwrap();
+ for c in ["origin", "suggestion_id", "task_class", "acceptance", "checks"] {
+ assert_eq!(cols.iter().filter(|(n,)| n == c).count(), 1, "{c} is added once");
+ }
+ // One live offer per habit, and the history is append-only
+ let offer = "INSERT INTO routine_suggestions (id, space_id, cluster_key, kwant_id, name, instructions, schedule, first_run_at, delivery,
+ source_task_ids, evidence, status, offered_at) VALUES (?, 'default', 'k1', 'b', 'n', 'i', '{}', '2026-11-02T09:00:00Z', '{}', '[]', '{}', 'offered', '2026-10-31T00:00:00Z')";
+ sqlx::query(offer).bind("s1").execute(&pool).await.unwrap();
+ assert!(sqlx::query(offer).bind("s2").execute(&pool).await.is_err(), "a second live offer for the same habit");
+ sqlx::query("INSERT INTO routine_suggestion_events (suggestion_id, kind, actor, created_at) VALUES ('s1', 'offered', 'kwant', '2026-10-31T00:00:00Z')")
+ .execute(&pool)
+ .await
+ .unwrap();
+ assert!(sqlx::query("UPDATE routine_suggestion_events SET actor = 'x'").execute(&pool).await.is_err());
+ assert!(sqlx::query("DELETE FROM routine_suggestion_events").execute(&pool).await.is_err());
+}
+
+#[tokio::test]
+async fn a_routine_without_outcomes_runs_exactly_as_before() {
+ let e = setup().await;
+ let r = person(&e, "POST", "/api/routines", Some(routine_body(&e, json!({})))).await;
+ let rid = r["id"].as_str().unwrap().to_string();
+ assert!(r["task_class"].is_null() && r["acceptance"].is_null() && r["origin"].is_null(), "{r}");
+ assert_eq!(r["checks"], json!([]));
+
+ let (run_id, task) = start_run(&e, &rid).await;
+ assert_eq!(task.acceptance, "Write this week's sales report to report.md", "the instructions, as today");
+ assert_eq!(e.state.db.task_class(&task.id).await.unwrap(), "general");
+ assert!(e.state.db.list_checks(&task.id).await.unwrap().is_empty());
+ let done = finish_run(&e, &rid, &run_id).await;
+ assert_eq!(done.state, "review", "nothing to check: the person reviews it");
+}
+
+#[tokio::test]
+async fn a_run_task_gets_the_class_acceptance_and_approved_checks_and_can_be_verified() {
+ let e = setup().await;
+ let body = routine_body(
+ &e,
+ json!({
+ "task_class": "reporting",
+ "acceptance": "report.md exists and names this week's top seller",
+ "checks": [{"kind": "file_exists", "spec": {"path": "report.md"}}],
+ }),
+ );
+ let r = person(&e, "POST", "/api/routines", Some(body)).await;
+ let rid = r["id"].as_str().unwrap().to_string();
+ assert_eq!(r["task_class"], "reporting");
+ assert_eq!(r["checks"], json!([{"kind": "file_exists", "spec": {"path": "report.md"}, "required": true}]));
+ assert_eq!(routine(&e, &rid).await["acceptance"], "report.md exists and names this week's top seller");
+
+ let (run_id, task) = start_run(&e, &rid).await;
+ assert_eq!(task.acceptance, "report.md exists and names this week's top seller");
+ assert_eq!(e.state.db.task_class(&task.id).await.unwrap(), "reporting");
+ let checks = e.state.db.list_checks(&task.id).await.unwrap();
+ assert_eq!(checks.len(), 1);
+ assert_eq!(checks[0].kind, "file_exists");
+ assert!(checks[0].approved && checks[0].required);
+ assert_eq!(checks[0].approved_by.as_deref(), Some("person"));
+
+ // The run writes its report, then finishes: the check passes and the task is verified
+ let folder = missions::task_folder(&e.state, &task).await.expect("the run's task has a folder");
+ std::fs::create_dir_all(&folder).unwrap();
+ std::fs::write(folder.join("report.md"), "Top seller: Dune").unwrap();
+ let done = finish_run(&e, &rid, &run_id).await;
+ assert_eq!(done.state, "verified", "{done:?}");
+
+ // Every run gets its own copy: a run without the report doesn't pass
+ let (run_id, task) = start_run(&e, &rid).await;
+ assert_eq!(e.state.db.list_checks(&task.id).await.unwrap().len(), 1);
+ std::fs::remove_file(folder.join("report.md")).unwrap();
+ let done = finish_run(&e, &rid, &run_id).await;
+ assert_ne!(done.state, "verified");
+}
+
+#[tokio::test]
+async fn class_and_checks_are_the_persons_a_bot_gets_403() {
+ let e = setup().await;
+ let token = turn(&e, "t-bot").await;
+ let r = person(&e, "POST", "/api/routines", Some(routine_body(&e, json!({"checks": [{"kind": "file_exists", "spec": {"path": "a.md"}}]})))).await;
+ let rid = r["id"].as_str().unwrap().to_string();
+ let patch = format!("/api/routines/{rid}");
+
+ // Over HTTP with the bot's turn token
+ for body in [
+ json!({"checks": [{"kind": "command", "spec": {"command": "true"}}]}),
+ json!({"checks": null}),
+ json!({"task_class": "reporting"}),
+ ] {
+ let (status, v) = send(&e.app, "PATCH", &patch, Some(&token), Some(body.clone())).await;
+ assert_eq!(status, StatusCode::FORBIDDEN, "{body}: {v}");
+ let (status, v) = send(&e.app, "POST", "/api/routines", Some(&token), Some(routine_body(&e, body.clone()))).await;
+ assert_eq!(status, StatusCode::FORBIDDEN, "{body}: {v}");
+ }
+ let (status, v) = send(&e.app, "PATCH", &patch, Some("not-a-token"), Some(json!({"task_class": "reporting"}))).await;
+ assert!(matches!(status, StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED), "{status} {v}");
+ let after = routine(&e, &rid).await;
+ assert_eq!(after["checks"], r["checks"], "nothing changed");
+ assert!(after["task_class"].is_null());
+
+ // A bot may still edit the rest, and the acceptance, and the checks stay as the person set them
+ let (status, v) = send(&e.app, "PATCH", &patch, Some(&token), Some(json!({"name": "Renamed", "acceptance": "a.md exists"}))).await;
+ assert_eq!(status, StatusCode::OK, "{v}");
+ let after = routine(&e, &rid).await;
+ assert_eq!((after["name"].as_str(), after["acceptance"].as_str()), (Some("Renamed"), Some("a.md exists")));
+ assert_eq!(after["checks"], r["checks"]);
+
+ // Through the bot's own routine tools too: an update keeps them
+ let (text, err) = tool(&e, &token, "routine_update", json!({"routine": rid, "instructions": "Write a.md"})).await;
+ assert!(!err, "{text}");
+ assert_eq!(routine(&e, &rid).await["checks"], r["checks"]);
+}
+
+#[tokio::test]
+async fn bad_outcomes_are_refused() {
+ let e = setup().await;
+ let many: Vec<Value> = (0..11).map(|i| json!({"kind": "file_exists", "spec": {"path": format!("f{i}.md")}})).collect();
+ for (extra, needle) in [
+ (json!({"task_class": "Not A Class"}), "class"),
+ (json!({"acceptance": "x".repeat(4001)}), "acceptance"),
+ (json!({"checks": many}), "checks"),
+ (json!({"checks": [{"kind": "person"}]}), "person"),
+ (json!({"checks": [{"kind": "command", "spec": {"command": "curl -H 'Authorization: [redacted]' x"}}]}), "redacted"),
+ ] {
+ let (status, v) = send(&e.app, "POST", "/api/routines", None, Some(routine_body(&e, extra.clone()))).await;
+ assert_eq!(status, StatusCode::BAD_REQUEST, "{extra}: {v}");
+ assert!(v.to_string().to_lowercase().contains(needle), "{needle}: {v}");
+ }
+ assert!(person(&e, "GET", "/api/routines", None).await.as_array().unwrap().is_empty());
+
+ // "general" and blanks clear; an empty list clears the checks
+ let r = person(&e, "POST", "/api/routines", Some(routine_body(&e, json!({"task_class": "general", "acceptance": " ", "checks": []})))).await;
+ assert!(r["task_class"].is_null() && r["acceptance"].is_null(), "{r}");
+ assert_eq!(r["checks"], json!([]));
+}
+
+#[tokio::test]
+async fn secrets_in_check_specs_are_masked_when_shown() {
+ let e = setup().await;
+ let cmd = "curl -fsS -H 'Authorization: Bearer sk-ant-api03-abcdefghijklmnopqrstuvwxyz0123456789' https://example.com/health";
+ let r = person(&e, "POST", "/api/routines", Some(routine_body(&e, json!({"checks": [{"kind": "command", "spec": {"command": cmd}}]})))).await;
+ let shown = routine(&e, r["id"].as_str().unwrap()).await["checks"].to_string();
+ assert!(!shown.contains("sk-ant-api03-abcdefghij"), "{shown}");
+ assert!(shown.contains("[redacted]"), "{shown}");
+ // The stored spec is the real one: the run's task gets it
+ let (_, task) = start_run(&e, r["id"].as_str().unwrap()).await;
+ assert!(e.state.db.list_checks(&task.id).await.unwrap()[0].spec.contains("sk-ant-api03-abcdefghij"));
+}
+
+#[tokio::test]
+async fn undoing_a_bots_delete_brings_the_outcomes_back() {
+ let e = setup().await;
+ let token = turn(&e, "t-del").await;
+ let body = routine_body(&e, json!({"task_class": "reporting", "acceptance": "a.md exists", "checks": [{"kind": "file_exists", "spec": {"path": "a.md"}}]}));
+ let r = person(&e, "POST", "/api/routines", Some(body)).await;
+ let (text, err) = tool(&e, &token, "routine_delete", json!({"routine": r["id"]})).await;
+ assert!(!err, "{text}");
+ let actions = person(&e, "GET", "/api/bot-actions", None).await;
+ let del = actions.as_array().unwrap().iter().find(|a| a["action"] == "routine_delete").unwrap().clone();
+ let v = person(&e, "POST", &format!("/api/bot-actions/{}/undo", del["id"].as_str().unwrap()), None).await;
+ assert_eq!(v["status"], "undone", "{v}");
+ let back = person(&e, "GET", "/api/routines", None).await[0].clone();
+ assert_eq!(back["task_class"], "reporting");
+ assert_eq!(back["acceptance"], "a.md exists");
+ assert_eq!(back["checks"], r["checks"]);
+}