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
Skill Foundry (Phase D3): drafted skills, dry-run replays, rollback (#136)
Lin (kwant bot)8abebec28751
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a2ae3407..0374aa9a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -31,6 +31,14 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).Board cards show how many risks are still open. While an audit waits on one of your approval cards,the task says "Audit waiting for your answer" with a link to it. Settings has the Auditor switch andits daily limit.+- **Skill Foundry (off by default).** With `skill_foundry` on in Settings, when a bot has 3 or more+ verified tasks of one kind of work (70% of them verified, in 60 days), it drafts a skill from them:+ the steps, the inputs, checks that judge the result, the example tasks and the tools it uses. Each+ draft is replayed as a dry run on up to 3 of its examples in a scratch copy of their folder, where+ nothing outside that folder runs, and the report sits on the draft for you to enable, edit or reject.+ Listed tools are shown, never granted. Versions of a skill can be rolled back.+ `GET /api/skills/foundry`, `POST /api/skills/foundry/:cluster/draft`, `POST /api/skills/:id/replay`,+ `POST /api/skills/:id/rollback`, `GET /api/skills/:id/foundry`. At most 2 drafts a day by default.### Changed- **Audits run on the fast model by default.** The Swarm Auditor's challenge and rebuttal turns now usediff --git a/docs/mission-control.md b/docs/mission-control.mdindex 65290f53..f9031b98 100644--- a/docs/mission-control.md+++ b/docs/mission-control.md@@ -745,3 +745,80 @@ off. A driver that stops early (a panic) ends its audit `failed`.challenge.- `POST /api/tasks/:id/risks/:risk_id/resolve {resolution: "resolved" | "dismissed", note?}` (persononly); 409 when already closed.++## 19. Skill Foundry (Phase D3)++When a bot has finished the same class of work well several times, kwant asks that bot to write the+procedure down as a skill draft, replays the draft as a dry run on a few of those tasks, and shows both+to the person, who enables, edits or rejects it. **A Foundry skill is text only, like every skill**: the+tools it lists are shown, never granted, and enabling it changes no tool, server or approval. Design+note: `phase-d/skill-foundry.md`.++**Settings** (app-wide): `skill_foundry` = `off` (default) | `on`; `skill_foundry_model` = `balanced`+(default) | `fast` | `deep` | `bot` (as `auditor_model`); `skill_foundry_daily_drafts` 1–20 (default+2) draft runs started per UTC day; `skill_foundry_replays` 0–5 (default 3) examples each draft is+replayed on (0: no replays); `skill_foundry_replay_tokens` 5,000–500,000 (default 60,000) fresh tokens+one replay turn may use.++**Clusters** (the miner, hourly while on): one space, one bot, one `task_class` other than `general`,+from Performance Market rows of the last 60 days, with ≥ 3 ended `verified` (Verified Outcomes: only a+check that counts and isn't the owner's verifies) and ≥ 70% of the class's rows verified. A cluster gets+no draft while one waits for review (`has_draft`), while the bot has a live Foundry skill for the class+(`has_skill`; the person can still ask for a new version), for 30 days after one was rejected+(`rejected`), or for 7 days after its last draft run (`cooling_off`).++**Draft.** One hidden turn of the owner bot, `always_ask`, capped at 20 minutes, with up to 5 verified+and 2 failed tasks of the cluster (title, acceptance, checks with secrets redacted, evidence, the+side-effect ledger's actions). The bot calls `skill_draft {run_id, name, description, body, inputs?,+checks?, examples, tools?}` once; the tool is listed only while that bot has a draft run open, and needs+no card (it only stores a pending skill). Server-side: name, description and body as `skill_propose`;+≤ 8 inputs `{name, description, example?}` (≤ 300 chars each); ≤ 5 checks that pass the task-check+validator (no `person` checks); 2–5 distinct examples, each a verified task of the cluster; ≤ 30 tools,+each a built-in tool, one of kwant's own tools the bot is offered, or `mcp__<server>__<tool>` of one of+the bot's active servers (only the server is checked: kwant can't list a server's tools without starting+it). The draft is a `pending` skill (`source = agent`) with a `skill_meta` row (class, inputs, checks,+examples, tools, replay report, `version`, `lineage_id`). When the bot has a live skill for the class,+the draft is its next version (`replaces_id`). A turn without a draft ends the run `failed`.++**Replay** (after each draft, or `POST /api/skills/:id/replay`): for up to `skill_foundry_replays`+examples, one hidden turn of the owner with the draft in its prompt, in a private scratch folder+(`<data>/foundry/<run>/<n>`, 0700) holding a copy of the task's first checkpoint (empty without one).+The turn's approvals are a dry run: in-folder file tools and web reads run, kwant's read-only tools run,+and every other call that reaches the approver (Bash, files outside the folder, other servers' tools,+kwant tools that change something, the browser) is refused with "dry run" and recorded as what the bot+would have done; subagents are refused. Only Claude's permission hook holds every call to this, so on+another engine the replay is refused before any model runs. Each turn is capped at 15 minutes and is+stopped once it reports more fresh tokens than `skill_foundry_replay_tokens`. After the turn, the+draft's file checks run on the scratch folder; `command` and `http` checks are `not_replayable`, never+passed. The scratch folder is then deleted. Per example the report has the verdict (`passed`: every+replayable check passed; `failed`; `not_checked`: nothing replayable; `error`: the turn didn't run), the+checks, the "would have…" lines next to what the original task did, tokens and seconds. A replay is+evidence, not a gate, and never changes the draft's status.++**Versions and rollback.** Enabling, editing and rejecting are the usual skill routes. `POST+/api/skills/:id/rollback` (person only; works with the Foundry off) makes a `superseded` version live+again and the lineage's live version `superseded`, in one transaction; 409 for a version that isn't+superseded or whose name clashes with another live skill, 404 for a skill without Foundry history.++**Ledger.** Skill events: `skill_drafted`, `skill_replayed`, `skill_rolled_back`. Task events:+`skill_drafted_from` on each example.++**Restarts.** Runs (`foundry_runs`: `queued | drafting | replaying | done | failed | interrupted`) are+never left running: at startup a `drafting` or `replaying` one becomes `interrupted`; a `queued` one+runs now, or fails ("the Skill Foundry was turned off") when the Foundry is off. A driver that stops+early ends its run `failed`. One Foundry turn runs at a time server-wide.++**API** (all person only)++- `GET /api/skills/foundry?space=` → `{enabled, settings, drafts_today, clusters: [{id, kwant_id,+ task_class, verified, total, block}], skills: [skill + foundry meta], runs}`.+- `POST /api/skills/foundry/:cluster/draft` (`:cluster` = `<bot id>~<class>`) → 202 with the run; 409+ when off, at the cap, a draft waits for review or one is being written; 404 when the cluster doesn't+ pass the thresholds.+- `POST /api/skills/:id/replay` → 202; 409 when off, replays are 0, the draft isn't pending or a replay+ of it runs.+- `POST /api/skills/:id/rollback` → the skill.+- `GET /api/skills/:id/foundry` → `{skill, versions, events, runs}`.++Not built yet: recording `skill_id@version` on a task's claim, and warning when a bot lost a listed+tool.diff --git a/src/db/foundry.rs b/src/db/foundry.rsnew file mode 100644index 00000000..0bcbc138--- /dev/null+++ b/src/db/foundry.rs@@ -0,0 +1,625 @@+//! Mission Control Phase D3: the Skill Foundry's records. A Foundry draft is an ordinary `pending`+//! skill plus a `skill_meta` row (the cluster it came from, its inputs, checks, examples, the tools+//! it uses, its replay report, its version and lineage). Draft and replay runs live in+//! `foundry_runs`; `skill_events` is each skill's history. A skill stays text only: the tools listed+//! in its meta are shown, never granted. See docs/mission-control.md §19.++use super::skills::{Skill, SkillError, SkillText, MAX_PENDING_PER_KWANT};+use super::{Database, DbError};+use chrono::{DateTime, Duration, Utc};+use serde::Serialize;+use serde_json::Value;+use sqlx::FromRow;++pub const RUN_KINDS: [&str; 2] = ["draft", "replay"];+pub const RUN_STATUSES: [&str; 6] = ["queued", "drafting", "replaying", "done", "failed", "interrupted"];+/// The miner's window, thresholds and cool-offs (design §3).+pub const WINDOW_DAYS: i64 = 60;+pub const MIN_VERIFIED: i64 = 3;+pub const MIN_RATE_PCT: i64 = 70;+pub const REJECT_COOL_OFF_DAYS: i64 = 30;+pub const DRAFT_COOL_OFF_DAYS: i64 = 7;++/// What a Foundry draft adds to its skill.+#[derive(Debug, Clone, Serialize, FromRow, PartialEq)]+pub struct SkillMeta {+ pub skill_id: String,+ pub space_id: String,+ pub kwant_id: String,+ pub task_class: String,+ /// JSON: `[{name, description, example}]`.+ pub inputs: String,+ /// JSON: `[{kind, spec}]`.+ pub checks: String,+ /// JSON: `[task_id]`.+ pub examples: String,+ /// JSON: `[tool_name]`. Shown on the card; never granted.+ pub tools: String,+ /// JSON replay report, `None` until one ran.+ pub replay: Option<String>,+ pub version: i64,+ /// The first version's skill id.+ pub lineage_id: String,+ pub created_at: DateTime<Utc>,+}++impl SkillMeta {+ pub fn json(&self) -> Value {+ let parse = |s: &str| serde_json::from_str::<Value>(s).unwrap_or(Value::Array(vec![]));+ serde_json::json!({+ "skill_id": self.skill_id,+ "kwant_id": self.kwant_id,+ "task_class": self.task_class,+ "inputs": parse(&self.inputs),+ "checks": parse(&self.checks),+ "examples": parse(&self.examples),+ "tools": parse(&self.tools),+ "replay": self.replay.as_deref().map(parse),+ "version": self.version,+ "lineage_id": self.lineage_id,+ "created_at": self.created_at,+ })+ }++ pub fn examples(&self) -> Vec<String> {+ serde_json::from_str(&self.examples).unwrap_or_default()+ }++ pub fn checks(&self) -> Vec<Value> {+ serde_json::from_str(&self.checks).unwrap_or_default()+ }+}++#[derive(Debug, Clone, Serialize, FromRow, PartialEq)]+pub struct FoundryRun {+ pub id: String,+ /// `draft` or `replay`.+ pub kind: String,+ pub space_id: String,+ pub kwant_id: String,+ pub task_class: String,+ /// The draft a replay runs (and, once drafted, the draft a draft run made).+ pub skill_id: Option<String>,+ pub status: String,+ pub reason: Option<String>,+ pub tokens: i64,+ pub created_at: DateTime<Utc>,+ pub finished_at: Option<DateTime<Utc>>,+}++impl FoundryRun {+ pub fn live(&self) -> bool {+ matches!(self.status.as_str(), "queued" | "drafting" | "replaying")+ }+}++#[derive(Debug, Clone, Serialize, FromRow, PartialEq)]+pub struct SkillEvent {+ pub id: i64,+ pub skill_id: String,+ pub kind: String,+ pub actor: String,+ #[serde(skip)]+ pub detail: String,+ pub created_at: DateTime<Utc>,+}++/// Same space, same class (not `general`), same owner bot: verified work the miner counts.+#[derive(Debug, Clone, Serialize, FromRow, PartialEq)]+pub struct Cluster {+ pub space_id: String,+ pub kwant_id: String,+ pub task_class: String,+ pub verified: i64,+ pub total: i64,+}++impl Cluster {+ /// `{kwant_id}~{class}`: the id the routes take.+ pub fn id(&self) -> String {+ cluster_id(&self.kwant_id, &self.task_class)+ }+}++pub fn cluster_id(kwant_id: &str, class: &str) -> String {+ format!("{kwant_id}~{class}")+}++/// `(kwant_id, class)` of a cluster id.+pub fn split_cluster(id: &str) -> Option<(&str, &str)> {+ id.split_once('~').filter(|(k, c)| !k.is_empty() && !c.is_empty())+}++/// A Foundry draft before it's stored.+#[derive(Debug, Clone, PartialEq)]+pub struct NewDraft {+ pub kwant_id: String,+ pub task_class: String,+ pub text: SkillText,+ pub inputs: Value,+ pub checks: Value,+ pub examples: Vec<String>,+ pub tools: Vec<String>,+}++fn in_list(list: &[&str]) -> String {+ list.iter().map(|s| format!("'{s}'")).collect::<Vec<_>>().join(", ")+}++impl Database {+ pub(super) async fn migrate_foundry(&self) -> Result<(), DbError> {+ let runs = format!(+ "CREATE TABLE IF NOT EXISTS foundry_runs (+ id TEXT PRIMARY KEY,+ kind TEXT NOT NULL CHECK (kind IN ({})),+ space_id TEXT NOT NULL,+ kwant_id TEXT NOT NULL,+ task_class TEXT NOT NULL,+ skill_id TEXT,+ status TEXT NOT NULL CHECK (status IN ({})),+ reason TEXT,+ tokens INTEGER NOT NULL DEFAULT 0,+ created_at TIMESTAMP NOT NULL,+ finished_at TIMESTAMP+ )",+ in_list(&RUN_KINDS),+ in_list(&RUN_STATUSES)+ );+ for stmt in [+ "CREATE TABLE IF NOT EXISTS skill_meta (+ skill_id TEXT PRIMARY KEY REFERENCES skills(id) ON DELETE CASCADE,+ space_id TEXT NOT NULL,+ kwant_id TEXT NOT NULL,+ task_class TEXT NOT NULL,+ inputs TEXT NOT NULL DEFAULT '[]',+ checks TEXT NOT NULL DEFAULT '[]',+ examples TEXT NOT NULL DEFAULT '[]',+ tools TEXT NOT NULL DEFAULT '[]',+ replay TEXT,+ version INTEGER NOT NULL CHECK (version >= 1),+ lineage_id TEXT NOT NULL,+ created_at TIMESTAMP NOT NULL+ )",+ "CREATE INDEX IF NOT EXISTS skill_meta_owner ON skill_meta (kwant_id, task_class)",+ "CREATE INDEX IF NOT EXISTS skill_meta_lineage ON skill_meta (lineage_id, version)",+ runs.as_str(),+ "CREATE INDEX IF NOT EXISTS foundry_runs_status ON foundry_runs (status, created_at)",+ "CREATE INDEX IF NOT EXISTS foundry_runs_cluster ON foundry_runs (kwant_id, task_class, kind, created_at)",+ "CREATE TABLE IF NOT EXISTS skill_events (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ skill_id TEXT NOT NULL,+ kind TEXT NOT NULL,+ actor TEXT NOT NULL,+ detail TEXT NOT NULL DEFAULT '{}',+ created_at TIMESTAMP NOT NULL+ )",+ "CREATE INDEX IF NOT EXISTS skill_events_skill ON skill_events (skill_id, id)",+ ] {+ sqlx::query(stmt).execute(&self.pool).await?;+ }+ // A restart cuts off a draft or replay turn: it never finishes, so say so. Queued runs+ // had no turn yet: the server runs them again (`foundry::resume_after_restart`).+ sqlx::query(+ "UPDATE foundry_runs SET status = 'interrupted', reason = 'kwant restarted during the run', finished_at = ?+ WHERE status IN ('drafting', 'replaying')",+ )+ .bind(Utc::now())+ .execute(&self.pool)+ .await?;+ Ok(())+ }++ /// Clusters in the miner's window that pass its thresholds (≥ 3 verified, ≥ 70% verified),+ /// in `space_id` when given. Blocks and cool-offs are checked by [`Self::foundry_block`].+ pub async fn foundry_clusters(&self, space_id: Option<&str>, now: DateTime<Utc>) -> Result<Vec<Cluster>, DbError> {+ Ok(sqlx::query_as::<_, Cluster>(+ "SELECT space_id, kwant_id, task_class, SUM(result = 'verified') AS verified, COUNT(*) AS total+ FROM performance_observations+ WHERE finished_at >= ?1 AND task_class <> 'general' AND (?2 IS NULL OR space_id = ?2)+ GROUP BY space_id, kwant_id, task_class+ HAVING SUM(result = 'verified') >= ?3 AND SUM(result = 'verified') * 100 >= COUNT(*) * ?4+ ORDER BY verified DESC, kwant_id, task_class",+ )+ .bind(now - Duration::days(WINDOW_DAYS))+ .bind(space_id)+ .bind(MIN_VERIFIED)+ .bind(MIN_RATE_PCT)+ .fetch_all(&self.pool)+ .await?)+ }++ /// The cluster's task ids in the window, newest first: verified ones, then failed ones.+ pub async fn cluster_tasks(&self, space_id: &str, kwant_id: &str, class: &str, result: &str, now: DateTime<Utc>, limit: i64) -> Result<Vec<String>, DbError> {+ let rows: Vec<(String,)> = sqlx::query_as(+ "SELECT task_id FROM performance_observations+ WHERE space_id = ? AND kwant_id = ? AND task_class = ? AND result = ? AND finished_at >= ?+ ORDER BY finished_at DESC, id DESC LIMIT ?",+ )+ .bind(space_id)+ .bind(kwant_id)+ .bind(class)+ .bind(result)+ .bind(now - Duration::days(WINDOW_DAYS))+ .bind(limit)+ .fetch_all(&self.pool)+ .await?;+ Ok(rows.into_iter().map(|r| r.0).collect())+ }++ /// Why the miner offers no draft for (bot, class) now: `has_draft` (one is waiting for+ /// review), `has_skill` (a live Foundry skill exists; the person can still ask for a new+ /// version), `rejected` (one was rejected in the last 30 days), `cooling_off` (a draft run in+ /// the last 7 days). `None` when a draft may be offered.+ pub async fn foundry_block(&self, kwant_id: &str, class: &str, now: DateTime<Utc>) -> Result<Option<&'static str>, DbError> {+ let statuses: Vec<(String, Option<DateTime<Utc>>)> = sqlx::query_as(+ "SELECT s.status, s.reviewed_at FROM skills s JOIN skill_meta m ON m.skill_id = s.id WHERE m.kwant_id = ? AND m.task_class = ?",+ )+ .bind(kwant_id)+ .bind(class)+ .fetch_all(&self.pool)+ .await?;+ if statuses.iter().any(|(s, _)| s == "pending") {+ return Ok(Some("has_draft"));+ }+ if statuses.iter().any(|(s, _)| s == "enabled" || s == "disabled") {+ return Ok(Some("has_skill"));+ }+ let cutoff = now - Duration::days(REJECT_COOL_OFF_DAYS);+ if statuses.iter().any(|(s, at)| s == "rejected" && at.is_some_and(|t| t >= cutoff)) {+ return Ok(Some("rejected"));+ }+ if let Some(last) = self.last_draft_run(kwant_id, class).await? {+ if last >= now - Duration::days(DRAFT_COOL_OFF_DAYS) {+ return Ok(Some("cooling_off"));+ }+ }+ Ok(None)+ }++ pub async fn last_draft_run(&self, kwant_id: &str, class: &str) -> Result<Option<DateTime<Utc>>, DbError> {+ let (at,): (Option<DateTime<Utc>>,) =+ sqlx::query_as("SELECT MAX(created_at) FROM foundry_runs WHERE kind = 'draft' AND kwant_id = ? AND task_class = ?")+ .bind(kwant_id)+ .bind(class)+ .fetch_one(&self.pool)+ .await?;+ Ok(at)+ }++ /// Draft runs started since `since` (the daily cap counts these).+ pub async fn draft_runs_since(&self, since: DateTime<Utc>) -> Result<i64, DbError> {+ let (n,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM foundry_runs WHERE kind = 'draft' AND created_at >= ?")+ .bind(since)+ .fetch_one(&self.pool)+ .await?;+ Ok(n)+ }++ pub async fn create_foundry_run(&self, kind: &str, space_id: &str, kwant_id: &str, class: &str, skill_id: Option<&str>) -> Result<FoundryRun, DbError> {+ Ok(sqlx::query_as::<_, FoundryRun>(+ "INSERT INTO foundry_runs (id, kind, space_id, kwant_id, task_class, skill_id, status, created_at)+ VALUES (?, ?, ?, ?, ?, ?, 'queued', ?) RETURNING *",+ )+ .bind(uuid::Uuid::new_v4().to_string())+ .bind(kind)+ .bind(space_id)+ .bind(kwant_id)+ .bind(class)+ .bind(skill_id)+ .bind(Utc::now())+ .fetch_one(&self.pool)+ .await?)+ }++ pub async fn get_foundry_run(&self, id: &str) -> Result<Option<FoundryRun>, DbError> {+ Ok(sqlx::query_as::<_, FoundryRun>("SELECT * FROM foundry_runs WHERE id = ?").bind(id).fetch_optional(&self.pool).await?)+ }++ /// Runs in `status`, oldest first.+ pub async fn foundry_runs_in(&self, status: &str) -> Result<Vec<FoundryRun>, DbError> {+ Ok(sqlx::query_as::<_, FoundryRun>("SELECT * FROM foundry_runs WHERE status = ? ORDER BY created_at, rowid")+ .bind(status)+ .fetch_all(&self.pool)+ .await?)+ }++ /// Recent runs of a space, newest first.+ pub async fn foundry_runs_of_space(&self, space_id: &str, limit: i64) -> Result<Vec<FoundryRun>, DbError> {+ Ok(sqlx::query_as::<_, FoundryRun>("SELECT * FROM foundry_runs WHERE space_id = ? ORDER BY created_at DESC, rowid DESC LIMIT ?")+ .bind(space_id)+ .bind(limit)+ .fetch_all(&self.pool)+ .await?)+ }++ /// The draft run `kwant_id` is in now, if any: the only time it is offered `skill_draft`.+ pub async fn drafting_run_of(&self, kwant_id: &str) -> Result<Option<FoundryRun>, DbError> {+ Ok(sqlx::query_as::<_, FoundryRun>("SELECT * FROM foundry_runs WHERE kind = 'draft' AND status = 'drafting' AND kwant_id = ? ORDER BY created_at DESC LIMIT 1")+ .bind(kwant_id)+ .fetch_optional(&self.pool)+ .await?)+ }++ /// A live (queued or running) run of `kind` for this cluster or skill.+ pub async fn live_foundry_run(&self, kind: &str, kwant_id: &str, class: &str, skill_id: Option<&str>) -> Result<Option<FoundryRun>, DbError> {+ Ok(sqlx::query_as::<_, FoundryRun>(+ "SELECT * FROM foundry_runs WHERE kind = ? AND kwant_id = ? AND task_class = ? AND (?4 IS NULL OR skill_id = ?4)+ AND status IN ('queued', 'drafting', 'replaying') LIMIT 1",+ )+ .bind(kind)+ .bind(kwant_id)+ .bind(class)+ .bind(skill_id)+ .fetch_optional(&self.pool)+ .await?)+ }++ /// Moves a run from `from` to `to`; false when it wasn't in `from` any more. A final status+ /// sets `finished_at`.+ pub async fn move_foundry_run(&self, id: &str, from: &str, to: &str, reason: Option<&str>) -> Result<bool, DbError> {+ let finished = matches!(to, "done" | "failed" | "interrupted").then(Utc::now);+ let r = sqlx::query("UPDATE foundry_runs SET status = ?, reason = COALESCE(?, reason), finished_at = COALESCE(?, finished_at) WHERE id = ? AND status = ?")+ .bind(to)+ .bind(reason)+ .bind(finished)+ .bind(id)+ .bind(from)+ .execute(&self.pool)+ .await?;+ Ok(r.rows_affected() == 1)+ }++ pub async fn add_foundry_tokens(&self, id: &str, tokens: i64) -> Result<(), DbError> {+ sqlx::query("UPDATE foundry_runs SET tokens = tokens + ? WHERE id = ?").bind(tokens.max(0)).bind(id).execute(&self.pool).await?;+ Ok(())+ }++ pub async fn set_foundry_run_skill(&self, id: &str, skill_id: &str) -> Result<(), DbError> {+ sqlx::query("UPDATE foundry_runs SET skill_id = ? WHERE id = ?").bind(skill_id).bind(id).execute(&self.pool).await?;+ Ok(())+ }++ pub async fn skill_meta(&self, skill_id: &str) -> Result<Option<SkillMeta>, DbError> {+ Ok(sqlx::query_as::<_, SkillMeta>("SELECT * FROM skill_meta WHERE skill_id = ?").bind(skill_id).fetch_optional(&self.pool).await?)+ }++ pub async fn set_skill_replay(&self, skill_id: &str, report: &Value) -> Result<(), DbError> {+ sqlx::query("UPDATE skill_meta SET replay = ? WHERE skill_id = ?").bind(report.to_string()).bind(skill_id).execute(&self.pool).await?;+ Ok(())+ }++ /// Every version of a lineage, oldest first, with its skill.+ pub async fn lineage(&self, lineage_id: &str) -> Result<Vec<(Skill, SkillMeta)>, DbError> {+ let metas = sqlx::query_as::<_, SkillMeta>("SELECT * FROM skill_meta WHERE lineage_id = ? ORDER BY version, created_at")+ .bind(lineage_id)+ .fetch_all(&self.pool)+ .await?;+ let mut out = Vec::new();+ for m in metas {+ if let Some(s) = self.get_skill(&m.skill_id).await? {+ out.push((s, m));+ }+ }+ Ok(out)+ }++ /// Foundry skills of a space (`pending` ones, or all), newest first.+ pub async fn foundry_skills(&self, space_id: &str, status: Option<&str>) -> Result<Vec<(Skill, SkillMeta)>, DbError> {+ let ids: Vec<(String,)> = sqlx::query_as(+ "SELECT s.id FROM skills s JOIN skill_meta m ON m.skill_id = s.id+ WHERE m.space_id = ? AND (?2 IS NULL OR s.status = ?2) ORDER BY s.created_at DESC LIMIT 200",+ )+ .bind(space_id)+ .bind(status)+ .fetch_all(&self.pool)+ .await?;+ let mut out = Vec::new();+ for (id,) in ids {+ if let (Some(s), Some(m)) = (self.get_skill(&id).await?, self.skill_meta(&id).await?) {+ out.push((s, m));+ }+ }+ Ok(out)+ }++ pub async fn log_skill_event(&self, skill_id: &str, kind: &str, actor: &str, detail: &Value) -> Result<(), DbError> {+ sqlx::query("INSERT INTO skill_events (skill_id, kind, actor, detail, created_at) VALUES (?, ?, ?, ?, ?)")+ .bind(skill_id)+ .bind(kind)+ .bind(actor)+ .bind(detail.to_string())+ .bind(Utc::now())+ .execute(&self.pool)+ .await?;+ Ok(())+ }++ pub async fn skill_events(&self, skill_ids: &[String]) -> Result<Vec<SkillEvent>, DbError> {+ let mut out = Vec::new();+ for id in skill_ids {+ out.extend(+ sqlx::query_as::<_, SkillEvent>("SELECT * FROM skill_events WHERE skill_id = ? ORDER BY id")+ .bind(id)+ .fetch_all(&self.pool)+ .await?,+ );+ }+ out.sort_by_key(|e| e.id);+ Ok(out)+ }++ /// Stores a Foundry draft as a `pending` skill with its meta and a `skill_drafted` event, in+ /// one transaction. When the bot has a live Foundry skill for the class, the draft is its next+ /// version: same lineage, and approving it supersedes the live one.+ pub async fn insert_foundry_draft(&self, space_id: &str, d: &NewDraft, run_id: &str) -> Result<(Skill, SkillMeta), SkillError> {+ let now = Utc::now();+ let mut tx = self.pool.begin().await?;+ let (pending,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM skills WHERE status = 'pending' AND kwant_id = ?")+ .bind(&d.kwant_id)+ .fetch_one(&mut *tx)+ .await?;+ if pending >= MAX_PENDING_PER_KWANT {+ return Err(SkillError::TooManyPending);+ }+ let waiting: Option<(String,)> = sqlx::query_as(+ "SELECT s.id FROM skills s JOIN skill_meta m ON m.skill_id = s.id WHERE m.kwant_id = ? AND m.task_class = ? AND s.status = 'pending'",+ )+ .bind(&d.kwant_id)+ .bind(&d.task_class)+ .fetch_optional(&mut *tx)+ .await?;+ if waiting.is_some() {+ return Err(SkillError::Conflict("a Foundry draft for this class is already waiting for review".into()));+ }+ let live: Option<(String, String)> = sqlx::query_as(+ "SELECT s.id, m.lineage_id FROM skills s JOIN skill_meta m ON m.skill_id = s.id+ WHERE m.kwant_id = ? AND m.task_class = ? AND s.status IN ('enabled', 'disabled') ORDER BY m.version DESC LIMIT 1",+ )+ .bind(&d.kwant_id)+ .bind(&d.task_class)+ .fetch_optional(&mut *tx)+ .await?;+ let id = uuid::Uuid::new_v4().to_string();+ let (replaces, lineage, version) = match &live {+ Some((live_id, lineage)) => {+ let (v,): (i64,) = sqlx::query_as("SELECT IFNULL(MAX(version), 0) FROM skill_meta WHERE lineage_id = ?")+ .bind(lineage)+ .fetch_one(&mut *tx)+ .await?;+ (Some(live_id.clone()), lineage.clone(), v + 1)+ }+ None => (None, id.clone(), 1),+ };+ sqlx::query(+ "INSERT INTO skills (id, kwant_id, name, description, body, status, source, proposed_by, replaces_id, created_at, updated_at, space_id)+ VALUES (?, ?, ?, ?, ?, 'pending', 'agent', ?, ?, ?, ?, ?)",+ )+ .bind(&id)+ .bind(&d.kwant_id)+ .bind(&d.text.name)+ .bind(&d.text.description)+ .bind(&d.text.body)+ .bind(&d.kwant_id)+ .bind(&replaces)+ .bind(now)+ .bind(now)+ .bind(space_id)+ .execute(&mut *tx)+ .await?;+ sqlx::query(+ "INSERT INTO skill_meta (skill_id, space_id, kwant_id, task_class, inputs, checks, examples, tools, version, lineage_id, created_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",+ )+ .bind(&id)+ .bind(space_id)+ .bind(&d.kwant_id)+ .bind(&d.task_class)+ .bind(d.inputs.to_string())+ .bind(d.checks.to_string())+ .bind(serde_json::to_string(&d.examples).unwrap_or_else(|_| "[]".into()))+ .bind(serde_json::to_string(&d.tools).unwrap_or_else(|_| "[]".into()))+ .bind(version)+ .bind(&lineage)+ .bind(now)+ .execute(&mut *tx)+ .await?;+ let detail = serde_json::json!({"run_id": run_id, "version": version, "replaces": replaces, "examples": d.examples});+ sqlx::query("INSERT INTO skill_events (skill_id, kind, actor, detail, created_at) VALUES (?, 'skill_drafted', ?, ?, ?)")+ .bind(&id)+ .bind(&d.kwant_id)+ .bind(detail.to_string())+ .bind(now)+ .execute(&mut *tx)+ .await?;+ tx.commit().await?;+ let skill = self.get_skill(&id).await?.ok_or(SkillError::NotFound)?;+ let meta = self.skill_meta(&id).await?.ok_or(SkillError::NotFound)?;+ Ok((skill, meta))+ }++ /// Rolls a lineage back to `target_id`, a `superseded` version of it: the lineage's live+ /// version becomes `superseded` and the target `enabled`, with a `skill_rolled_back` event, in+ /// one transaction. Only within a Foundry lineage; a live skill outside it with the target's+ /// name blocks it.+ pub async fn rollback_skill(&self, target_id: &str, actor: &str) -> Result<Skill, SkillError> {+ let now = Utc::now();+ let mut tx = self.pool.begin().await?;+ let target = sqlx::query_as::<_, Skill>("SELECT * FROM skills WHERE id = ?").bind(target_id).fetch_optional(&mut *tx).await?.ok_or(SkillError::NotFound)?;+ let meta: Option<(String,)> = sqlx::query_as("SELECT lineage_id FROM skill_meta WHERE skill_id = ?").bind(target_id).fetch_optional(&mut *tx).await?;+ let Some((lineage,)) = meta else {+ return Err(SkillError::Conflict("only a Foundry skill version can be rolled back to".into()));+ };+ if target.status != "superseded" {+ return Err(SkillError::Conflict(format!("only an earlier (superseded) version can be rolled back to; this one is {}", target.status)));+ }+ let current: Vec<(String,)> = sqlx::query_as(+ "SELECT s.id FROM skills s JOIN skill_meta m ON m.skill_id = s.id WHERE m.lineage_id = ? AND s.status IN ('enabled', 'disabled')",+ )+ .bind(&lineage)+ .fetch_all(&mut *tx)+ .await?;+ for (id,) in ¤t {+ sqlx::query("UPDATE skills SET status = 'superseded', updated_at = ? WHERE id = ?").bind(now).bind(id).execute(&mut *tx).await?;+ }+ let clash: Option<(String,)> = sqlx::query_as(+ "SELECT id FROM skills WHERE space_id = ? AND IFNULL(kwant_id, '') = IFNULL(?, '') AND name = ? AND status IN ('enabled', 'disabled') AND id != ?",+ )+ .bind(&target.space_id)+ .bind(&target.kwant_id)+ .bind(&target.name)+ .bind(target_id)+ .fetch_optional(&mut *tx)+ .await?;+ if clash.is_some() {+ return Err(SkillError::Conflict(format!("another skill called {} is live; rename or disable it first", target.name)));+ }+ sqlx::query("UPDATE skills SET status = 'enabled', updated_at = ?, reviewed_at = ? WHERE id = ?")+ .bind(now)+ .bind(now)+ .bind(target_id)+ .execute(&mut *tx)+ .await?;+ let from: Vec<&String> = current.iter().map(|c| &c.0).collect();+ let detail = serde_json::json!({"from": from, "to": target_id});+ for id in current.iter().map(|c| c.0.as_str()).chain([target_id]) {+ sqlx::query("INSERT INTO skill_events (skill_id, kind, actor, detail, created_at) VALUES (?, 'skill_rolled_back', ?, ?, ?)")+ .bind(id)+ .bind(actor)+ .bind(detail.to_string())+ .bind(now)+ .execute(&mut *tx)+ .await?;+ }+ tx.commit().await?;+ self.get_skill(target_id).await?.ok_or(SkillError::NotFound)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ async fn db() -> (Database, tempfile::TempDir) {+ let tmp = tempfile::tempdir().unwrap();+ (Database::init(tmp.path()).await.unwrap(), tmp)+ }++ #[test]+ fn cluster_ids_round_trip() {+ assert_eq!(split_cluster(&cluster_id("k1", "release-notes")), Some(("k1", "release-notes")));+ assert_eq!(split_cluster("nope"), None);+ assert_eq!(split_cluster("~x"), None);+ }++ #[tokio::test]+ async fn a_restart_marks_running_runs_interrupted_and_keeps_queued_ones() {+ let (db, _t) = db().await;+ let a = db.create_foundry_run("draft", "spc_default", "k", "c", None).await.unwrap();+ assert!(db.move_foundry_run(&a.id, "queued", "drafting", None).await.unwrap());+ let q = db.create_foundry_run("replay", "spc_default", "k", "c", Some("s")).await.unwrap();+ db.migrate_foundry().await.unwrap();+ let a = db.get_foundry_run(&a.id).await.unwrap().unwrap();+ assert_eq!((a.status.as_str(), a.finished_at.is_some()), ("interrupted", true));+ assert_eq!(db.get_foundry_run(&q.id).await.unwrap().unwrap().status, "queued");+ }+}diff --git a/src/db/mod.rs b/src/db/mod.rsindex 10ddba09..c3e70875 100644--- a/src/db/mod.rs+++ b/src/db/mod.rs@@ -31,6 +31,7 @@ pub mod autofix;pub mod flight_school;pub mod performance;pub mod auditor;+pub mod foundry;/// What a space's #general says about itself.pub const GENERAL_DESCRIPTION: &str = "Everyone in this space. Laya picks who answers.";@@ -189,6 +190,7 @@ impl Database {db.migrate_performance().await?;// Phase D2: audits and their risks (add-only)db.migrate_auditor().await?;+ db.migrate_foundry().await?;db.pool.close().await;let pool = SqlitePoolOptions::new()diff --git a/src/mcp/builtin_tools.rs b/src/mcp/builtin_tools.rsindex 3dd4c059..55d5719b 100644--- a/src/mcp/builtin_tools.rs+++ b/src/mcp/builtin_tools.rs@@ -31,6 +31,15 @@ const READ_TOOLS: &[&str] = &["Read", "Glob", "Grep", "LS", "NotebookRead"];/// Tools that write files: free inside the working folder.const WRITE_TOOLS: &[&str] = &["Write", "Edit", "MultiEdit", "NotebookEdit"];+/// Whether `tool` is a built-in tool kwnt knows (a Skill Foundry draft may list only those).+pub fn known(tool: &str) -> bool {+ LOOKUP_TOOLS.contains(&tool) || READ_TOOLS.contains(&tool) || WRITE_TOOLS.contains(&tool) || matches!(tool, "Bash" | "KillShell")+}++/// Built-ins that start another agent: a Skill Foundry replay refuses them, as their own calls+/// aren't checked against the replay's scratch folder.+pub const SUBAGENT_TOOLS: &[&str] = &["Task", "Agent"];+/// The policy for `tool` with `input`, for a bot working in `folder` (canonical, or `None`).pub fn decide(tool: &str, input: &Value, folder: Option<&Path>) -> BuiltinDecision {if tool == "WebFetch" && fetches_kwnt(input) {diff --git a/src/mcp/mod.rs b/src/mcp/mod.rsindex a0e065c2..dec7b8bd 100644--- a/src/mcp/mod.rs+++ b/src/mcp/mod.rs@@ -336,6 +336,9 @@ pub enum ApprovalOutcome {/// Nobody answered before the wait ran out. The card stays open, and a late Allow starts a/// new turn to continue.Unanswered,+ /// A Skill Foundry replay (a dry run): the call didn't run and was recorded as what the bot+ /// would have done.+ Rehearsed,}/// What the bot is told when the person refused a call.@@ -344,6 +347,11 @@ pub const DENIED_TEXT: &str = "The user denied this tool call.";pub const UNANSWERED_TEXT: &str = "No one has answered the approval card for this call yet, so it did not run. \The card stays open: if the person allows it later, you will be started again to make this same call and continue. \Don't retry it now. Finish what you can without it, then end your turn saying what you were about to do and why.";+/// What the bot is told in a Skill Foundry replay when a call could change something.+pub const REHEARSED_TEXT: &str = "This is a dry run on a scratch copy of an earlier task: calls that could change \+anything outside the scratch folder (send, publish, sign in, pay, run commands, write elsewhere, other servers' tools) \+don't run. kwant recorded this one as what you would have done. Don't retry it; carry on with what you can do in \+the scratch folder, then end your turn saying what you would have done.";impl ApprovalOutcome {pub fn allowed(self) -> bool {@@ -354,6 +362,7 @@ impl ApprovalOutcome {pub fn refusal_text(self) -> &'static str {match self {ApprovalOutcome::Unanswered => UNANSWERED_TEXT,+ ApprovalOutcome::Rehearsed => REHEARSED_TEXT,_ => DENIED_TEXT,}}@@ -364,6 +373,7 @@ impl ApprovalOutcome {ApprovalOutcome::Allowed => "allowed",ApprovalOutcome::Denied => "denied",ApprovalOutcome::Unanswered => "unanswered",+ ApprovalOutcome::Rehearsed => "rehearsed",}}}diff --git a/src/serve.rs b/src/serve.rsindex d66aae5d..00ff94c6 100644--- a/src/serve.rs+++ b/src/serve.rs@@ -56,6 +56,7 @@ pub async fn run(config: Config, shutdown: impl Future<Output = ()>) -> Result<(crate::server::routes::interrupt_running_turns(&state).await;// Audits that were waiting their turn when kwant stopped run now (the cut-off ones ended)crate::server::missions::auditor::resume_after_restart(&state).await;+ crate::server::missions::foundry::resume_after_restart(&state).await;crate::server::scheduler::spawn_background(state.clone(), cancel.clone());crate::server::engine_routes::spawn_startup_check(state.clone());crate::server::parallel_routes::spawn_startup_sweep(state.clone());diff --git a/src/server/auth.rs b/src/server/auth.rsindex 7dcb92a5..573a418e 100644--- a/src/server/auth.rs+++ b/src/server/auth.rs@@ -369,6 +369,8 @@ pub fn person_only(method: &Method, path: &str) -> bool {["", "api", "kwants", _, "memories", ..] => *method != Method::GET && *method != Method::HEAD,// Skills go into prompts. A skill made or switched on here is live at once, and approving// or rejecting one is the person's call: bots only propose (`skill_propose`)+ // Skill Foundry clusters and drafts: the person's review queue, read too+ ["", "api", "skills", "foundry", ..] | ["", "api", "skills", _, "foundry"] => true,["", "api", "skills", ..] => *method != Method::GET && *method != Method::HEAD,["", "api", "bot-actions" | "imports", _, "undo"] => *method == Method::POST,_ => false,@@ -859,6 +861,12 @@ mod tests {assert!(person_only(&get, "/api/passwords/store"));assert!(person_only(&post, "/api/messages/m1/decisions/0/change"));assert!(person_only(&post, "/api/work-ahead/run"));+ assert!(person_only(&get, "/api/skills/foundry"));+ assert!(person_only(&post, "/api/skills/foundry/k1~release/draft"));+ assert!(person_only(&get, "/api/skills/s1/foundry"));+ assert!(person_only(&post, "/api/skills/s1/rollback"));+ assert!(person_only(&post, "/api/skills/s1/replay"));+ assert!(!person_only(&get, "/api/skills/s1"));assert!(person_only(&post, "/api/missions"));assert!(person_only(&post, "/api/missions/m1/approve"));assert!(person_only(&post, "/api/missions/m1/run"));diff --git a/src/server/continuity.rs b/src/server/continuity.rsindex d3cc8ed9..a0f67f1c 100644--- a/src/server/continuity.rs+++ b/src/server/continuity.rs@@ -381,6 +381,12 @@ impl ToolApprover for SelfToolsApprover {return self.inner.decide(req).await;}}+ // Skill Foundry: a draft only stores a pending skill for the person to review, and is+ // offered only in kwant's own draft turn, so it never needs its own card+ if req.server == SELF_SERVER_NAME && req.tool == super::missions::foundry::TOOL {+ self.inner.note(&req, "allowed", None).await;+ return crate::mcp::ApprovalOutcome::Allowed;+ }// The corrected retry of an audit call the person allowed and the tool refused: one card// for one challenge (see `auditor::take_retry`)let free = !self.always_ask@@ -413,6 +419,24 @@ async fn page_url(state: &AppState, target: &str) -> Option<String> {url}+/// The tools a turn's kwant server lists: `skill_draft` only while the bot has a Skill Foundry+/// draft run open.+async fn offered_tools(state: &AppState, scope: &SelfScope) -> Value {+ let mut tools = tool_list(scope, super::missions::enabled(state).await);+ if super::missions::foundry::enabled(state).await && matches!(state.db.drafting_run_of(&scope.kwant_id).await, Ok(Some(_))) {+ if let Some(list) = tools.as_array_mut() {+ list.push(super::missions::foundry::tool());+ }+ }+ tools+}++/// The names of the kwant tools `scope`'s turns are offered (without `skill_draft`).+pub(crate) async fn self_tool_names(state: &AppState, scope: &SelfScope) -> Vec<String> {+ let tools = tool_list(scope, super::missions::enabled(state).await);+ tools.as_array().map(|a| a.iter().filter_map(|t| t["name"].as_str().map(String::from)).collect()).unwrap_or_default()+}+fn tool_list(scope: &SelfScope, board: bool) -> Value {let mut tools = memory_tools();if let Some(list) = tools.as_array_mut() {@@ -731,7 +755,7 @@ pub async fn self_endpoint(}),),"ping" => rpc_result(id, json!({})),- "tools/list" => rpc_result(id, json!({ "tools": tool_list(&scope, super::missions::enabled(&state).await) })),+ "tools/list" => rpc_result(id, json!({ "tools": offered_tools(&state, &scope).await })),"tools/call" => {let args = &msg["params"]["arguments"];let name = msg["params"]["name"].as_str().unwrap_or("");@@ -878,6 +902,7 @@ async fn call_tool(None => (format!("Unknown tool {name}."), true),},"skill_propose" => super::skills::tool_propose(state, scope, args).await,+ super::missions::foundry::TOOL => super::missions::foundry::call(state, scope, args).await,"skill_get" => super::skills::tool_get(state, scope, args).await,"ask_user" => super::questions::tool_ask(state, scope, args).await,super::human_steps::TOOL => super::human_steps::tool_request(state, scope, args).await,diff --git a/src/server/mcp_runtime.rs b/src/server/mcp_runtime.rsindex 96c46c6e..42c4fcb8 100644--- a/src/server/mcp_runtime.rs+++ b/src/server/mcp_runtime.rs@@ -506,6 +506,50 @@ pub struct TurnApprovalOpts {/// Every call that could change something asks, approvals off or not (see/// [`BrokerApprover::always_ask`]).pub always_ask: bool,+ /// A Skill Foundry replay: nothing that could change anything outside the scratch folder+ /// runs, and every such call is logged here as what the bot would have done (see+ /// [`RehearseApprover`]).+ pub rehearse: Option<RehearseLog>,+}++/// The "would have…" lines of a replay turn.+pub type RehearseLog = Arc<std::sync::Mutex<Vec<Value>>>;++/// A Skill Foundry replay's approver: no cards and no grants. kwant's own read-only tools and+/// in-folder file tools run (the permission hook allows those on its own); every other call is+/// refused as [`ApprovalOutcome::Rehearsed`] and logged.+pub struct RehearseApprover {+ pub log: RehearseLog,+}++#[async_trait]+impl ToolApprover for RehearseApprover {+ async fn approve(&self, req: ToolApprovalRequest) -> bool {+ self.decide(req).await.allowed()+ }++ async fn decide(&self, req: ToolApprovalRequest) -> ApprovalOutcome {+ if req.server == mcp::SELF_SERVER_NAME && super::continuity::READ_ONLY_SELF_TOOLS.contains(&req.tool.as_str()) {+ return ApprovalOutcome::Allowed;+ }+ let line = json!({+ "tool": req.tool_name,+ "would_have": super::missions::checkpoints::summary(&req.tool_name, &req.arguments),+ "outside_folder": req.builtin.as_ref().is_some_and(|b| b.outside_folder),+ });+ if let Ok(mut log) = self.log.lock() {+ // A runaway turn can't grow it without bound+ if log.len() < 200 {+ log.push(line);+ }+ }+ ApprovalOutcome::Rehearsed+ }++ /// Subagents are refused too: their own calls aren't held to the scratch folder.+ async fn tier_gate(&self, req: &ToolApprovalRequest) -> Option<String> {+ mcp::builtin_tools::SUBAGENT_TOOLS.contains(&req.tool_name.as_str()).then(|| "a replay starts no subagents".into())+ }}/// [`prepare_turn_with_self`] with [`TurnApprovalOpts`].@@ -557,7 +601,9 @@ pub async fn prepare_turn_with_opts(});let ctx = McpTurnContext {servers,- approver: if self_tools {+ approver: if let Some(log) = opts.rehearse.clone() {+ Arc::new(RehearseApprover { log })+ } else if self_tools {Arc::new(super::continuity::SelfToolsApprover { inner: broker_approver, always_ask: opts.always_ask, browser })} else {broker_approverdiff --git a/src/server/missions/checkpoints.rs b/src/server/missions/checkpoints.rsindex c9719090..0eb0ba61 100644--- a/src/server/missions/checkpoints.rs+++ b/src/server/missions/checkpoints.rs@@ -317,6 +317,35 @@ fn write_manifest(dir: &FsPath, id: &str, m: &Manifest) -> std::io::Result<(PathOk((path, hex(&<sha2::Sha256 as sha2::Digest>::digest(&body))))}+/// Writes `task_id`'s first checkpoint (its folder before its first run) into `dest`, an empty+/// scratch folder, for a Skill Foundry replay. `Ok(0)` when the task has no usable checkpoint.+/// Never touches the task's own folder.+pub async fn materialize_first(state: &AppState, task_id: &str, dest: &FsPath) -> Result<usize, String> {+ let first = state.db.checkpoints_of(task_id).await.map_err(|e| e.to_string())?.into_iter().find(|c| !c.failed());+ let Some(first) = first else { return Ok(0) };+ let _store = STORE.lock().await;+ let (blobs, dest) = (root(state).join("blobs"), dest.to_path_buf());+ tokio::task::spawn_blocking(move || {+ let manifest = read_manifest(&first).ok_or("the checkpoint's manifest is gone")?;+ private_dir(&dest).map_err(|e| e.to_string())?;+ let mut n = 0;+ for e in manifest.files.iter().filter(|e| safe_rel(&e.path)) {+ let to = dest.join(&e.path);+ if let Some(parent) = to.parent() {+ std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;+ }+ // A missing blob is skipped: the replay sees less, never something else+ if std::fs::copy(blobs.join(&e.sha256), &to).is_ok() {+ let _ = std::fs::set_permissions(&to, std::fs::Permissions::from_mode((e.mode & 0o700) | 0o600));+ n += 1;+ }+ }+ Ok(n)+ })+ .await+ .map_err(|e| e.to_string())?+}+/// The manifest of `c`, if it is still on disk.pub fn read_manifest(c: &Checkpoint) -> Option<Manifest> {if c.failed() || c.manifest_path.is_empty() {diff --git a/src/server/missions/foundry.rs b/src/server/missions/foundry.rsnew file mode 100644index 00000000..81233544--- /dev/null+++ b/src/server/missions/foundry.rs@@ -0,0 +1,968 @@+//! Mission Control Phase D3: the Skill Foundry. When a bot has finished the same class of work+//! well several times (a cluster: ≥ 3 verified tasks of one class, ≥ 70% verified, in 60 days),+//! kwant asks that bot, in one hidden turn, to draft a skill from those tasks with `skill_draft`.+//! The draft is an ordinary `pending` skill plus its inputs, checks, examples and the tools it+//! uses. Each draft is then replayed as a dry run on a scratch copy of up to 3 of its examples:+//! nothing outside the scratch folder runs, and the report goes on the draft card. The person+//! enables, edits or rejects it, and can roll a lineage back to an earlier version. The tools a+//! draft lists are shown, never granted. Off by default. See docs/mission-control.md §19.++use super::routes::{bad, conflict, internal, not_found};+use crate::db::foundry::{cluster_id, split_cluster, Cluster, FoundryRun, NewDraft, SkillMeta};+use crate::db::models::Kwant;+use crate::db::skills::{clean_skill_text, Skill, SkillError};+use crate::drivers::engines::Tier;+use crate::server::continuity::SelfScope;+use crate::server::mcp_runtime::RehearseLog;+use crate::server::routes::{scope_for, turn_once, TurnOpts};+use crate::server::spaces::Scope;+use crate::server::AppState;+use axum::{+ extract::{Path, State},+ http::StatusCode,+ response::{IntoResponse, Response},+ Json,+};+use chrono::{DateTime, Duration, Utc};+use serde_json::{json, Value};+use std::path::{Path as FsPath, PathBuf};+use std::sync::LazyLock;+use tokio_util::sync::CancellationToken;++pub const SETTING: &str = "skill_foundry";+pub const MODES: [&str; 2] = ["off", "on"];+pub const MODEL_SETTING: &str = "skill_foundry_model";+pub const MODEL_MODES: [&str; 4] = ["fast", "balanced", "deep", "bot"];+pub const DEFAULT_MODEL: &str = "balanced";+pub const DRAFTS_SETTING: &str = "skill_foundry_daily_drafts";+pub const DEFAULT_DRAFTS: i64 = 2;+pub const DRAFTS_RANGE: (i64, i64) = (1, 20);+pub const REPLAYS_SETTING: &str = "skill_foundry_replays";+pub const DEFAULT_REPLAYS: i64 = 3;+/// 0 turns replays off: drafts are then shown without a report.+pub const REPLAYS_RANGE: (i64, i64) = (0, 5);+pub const REPLAY_TOKENS_SETTING: &str = "skill_foundry_replay_tokens";+pub const DEFAULT_REPLAY_TOKENS: i64 = 60_000;+pub const REPLAY_TOKENS_RANGE: (i64, i64) = (5_000, 500_000);++pub const TOOL: &str = "skill_draft";+pub const DRAFT_PURPOSE: &str = "foundry_draft";+pub const REPLAY_PURPOSE: &str = "foundry_replay";+pub const MAX_INPUTS: usize = 8;+pub const MAX_CHECKS: usize = 5;+pub const MIN_EXAMPLES: usize = 2;+pub const MAX_EXAMPLES: usize = 5;+pub const MAX_TOOLS: usize = 30;+const MAX_FIELD_CHARS: usize = 300;+/// Tasks a draft prompt shows: verified ones, and failed ones for contrast.+const PROMPT_VERIFIED: i64 = 5;+const PROMPT_FAILED: i64 = 2;+const DRAFT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(20 * 60);+const REPLAY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15 * 60);+/// How often a replay's token cap is checked while its turn runs.+const CAP_POLL: std::time::Duration = std::time::Duration::from_secs(2);+const TICK: std::time::Duration = std::time::Duration::from_secs(60 * 60);+/// What the original task did, listed next to a replay's "would have…" lines.+const MAX_ORIGINAL_ACTIONS: usize = 20;++/// One Foundry turn at a time, server-wide.+static ONE: LazyLock<tokio::sync::Mutex<()>> = LazyLock::new(|| tokio::sync::Mutex::new(()));++pub async fn enabled(state: &AppState) -> bool {+ matches!(state.db.get_setting(SETTING).await.ok().flatten().as_deref().map(str::trim), Some("on"))+}++pub async fn model_mode(state: &AppState) -> &'static str {+ let saved = state.db.get_setting(MODEL_SETTING).await.ok().flatten();+ MODEL_MODES.into_iter().find(|m| Some(*m) == saved.as_deref().map(str::trim)).unwrap_or(DEFAULT_MODEL)+}++pub async fn daily_drafts(state: &AppState) -> i64 {+ super::int_setting(state, DRAFTS_SETTING, DRAFTS_RANGE, DEFAULT_DRAFTS).await+}++pub async fn replays(state: &AppState) -> i64 {+ super::int_setting(state, REPLAYS_SETTING, REPLAYS_RANGE, DEFAULT_REPLAYS).await+}++pub async fn replay_tokens(state: &AppState) -> i64 {+ super::int_setting(state, REPLAY_TOKENS_SETTING, REPLAY_TOKENS_RANGE, DEFAULT_REPLAY_TOKENS).await+}++pub fn tier_of(mode: &str) -> Option<Tier> {+ super::auditor::tier_of(mode)+}++pub fn settings_error(mode: Option<&str>, model: Option<&str>, drafts: Option<i64>, replays: Option<i64>, tokens: Option<i64>) -> Option<String> {+ if let Some(m) = mode.filter(|m| !MODES.contains(m)) {+ return Some(format!("skill_foundry must be off or on (got {m})"));+ }+ if let Some(m) = model.filter(|m| !MODEL_MODES.contains(m)) {+ return Some(format!("skill_foundry_model must be fast, balanced, deep or bot (got {m})"));+ }+ for (key, value, (lo, hi)) in [(DRAFTS_SETTING, drafts, DRAFTS_RANGE), (REPLAYS_SETTING, replays, REPLAYS_RANGE), (REPLAY_TOKENS_SETTING, tokens, REPLAY_TOKENS_RANGE)] {+ if let Some(n) = value.filter(|n| !(lo..=hi).contains(n)) {+ return Some(format!("{key} must be {lo}–{hi} (got {n})"));+ }+ }+ None+}++fn midnight() -> DateTime<Utc> {+ Utc::now().date_naive().and_hms_opt(0, 0, 0).map(|d| d.and_utc()).unwrap_or_else(Utc::now)+}++fn clip(s: &str, n: usize) -> String {+ let s = s.trim();+ if s.chars().count() <= n {+ s.to_string()+ } else {+ format!("{}…", s.chars().take(n).collect::<String>())+ }+}++async fn skill_event(state: &AppState, skill_id: &str, kind: &str, actor: &str, detail: Value) {+ if let Err(e) = state.db.log_skill_event(skill_id, kind, actor, &detail).await {+ tracing::warn!(skill_id, kind, error = %e, "skill event not logged");+ }+}++fn changed(state: &AppState, skill: &Skill) {+ let _ = state.event_sender.send(crate::drivers::events::RuntimeEvent::SkillUpdated {+ skill: serde_json::to_value(skill).unwrap_or(Value::Null),+ });+}++// The miner++/// The hourly tick: while the Foundry is on, offers one draft for each cluster with no block, up+/// to the daily cap.+pub fn spawn(state: AppState, shutdown: CancellationToken) {+ tokio::spawn(async move {+ loop {+ tokio::select! {+ _ = shutdown.cancelled() => return,+ _ = tokio::time::sleep(TICK) => {}+ }+ if enabled(&state).await {+ tick(&state).await;+ }+ }+ });+}++/// One pass of the miner; the runs it started.+pub async fn tick(state: &AppState) -> Vec<FoundryRun> {+ let now = Utc::now();+ let mut started = Vec::new();+ for c in state.db.foundry_clusters(None, now).await.unwrap_or_default() {+ if !matches!(state.db.foundry_block(&c.kwant_id, &c.task_class, now).await, Ok(None)) {+ continue;+ }+ match begin_draft(state, &c, "kwant").await {+ Ok(run) => started.push(run),+ // The cap: no other cluster gets one today either+ Err(why) if why.contains("daily") => break,+ Err(why) => tracing::info!(cluster = %c.id(), why, "no Foundry draft"),+ }+ }+ started+}++/// Opens a draft run for `cluster` (`queued`) and drives it in the background. Refused when the+/// Foundry is off, the daily cap is reached, a draft for the class waits for review, or a draft+/// run for it is already live.+pub async fn begin_draft(state: &AppState, cluster: &Cluster, actor: &str) -> Result<FoundryRun, String> {+ let run = start_draft(state, cluster, actor).await?;+ let (s, r) = (state.clone(), run.clone());+ tokio::spawn(async move { drive_draft(&s, &r).await });+ Ok(run)+}++pub async fn start_draft(state: &AppState, cluster: &Cluster, actor: &str) -> Result<FoundryRun, String> {+ if !enabled(state).await {+ return Err("the Skill Foundry is off in Settings".into());+ }+ let cap = daily_drafts(state).await;+ if state.db.draft_runs_since(midnight()).await.map_err(|e| e.to_string())? >= cap {+ return Err(format!("the daily Foundry draft cap ({cap}) is reached"));+ }+ if matches!(state.db.foundry_block(&cluster.kwant_id, &cluster.task_class, Utc::now()).await, Ok(Some("has_draft"))) {+ return Err("a draft for this class is already waiting for review".into());+ }+ if let Ok(Some(_)) = state.db.live_foundry_run("draft", &cluster.kwant_id, &cluster.task_class, None).await {+ return Err("a draft for this class is already being written".into());+ }+ let run = state.db.create_foundry_run("draft", &cluster.space_id, &cluster.kwant_id, &cluster.task_class, None).await.map_err(|e| e.to_string())?;+ tracing::info!(run_id = %run.id, cluster = %cluster.id(), actor, "Foundry draft queued");+ Ok(run)+}++/// The draft turn: the owner bot, always asking, is asked to call `skill_draft` once. A turn that+/// ends without a draft ends the run `failed`; a draft queues its replay.+pub async fn drive_draft(state: &AppState, run: &FoundryRun) {+ let _unstick = Unstick(state.clone(), run.id.clone());+ let _one = ONE.lock().await;+ if !state.db.move_foundry_run(&run.id, "queued", "drafting", None).await.unwrap_or(false) {+ return;+ }+ let Ok(Some(owner)) = state.db.get_kwant(&run.kwant_id).await else {+ let _ = state.db.move_foundry_run(&run.id, "drafting", "failed", Some("the bot no longer exists")).await;+ return;+ };+ let prompt = draft_prompt(state, run).await;+ let job = state.turns.start_job([owner.id.clone()]);+ let started = Utc::now();+ let reply = match scope_for(state, &owner, None, None, &job, 0).await {+ Ok(scope) => {+ let mut opts = TurnOpts::always_asking("Skill Foundry");+ (opts.unsaved, opts.quiet_failure, opts.purpose) = (true, true, Some(DRAFT_PURPOSE.into()));+ opts.tier = tier_of(model_mode(state).await);+ match tokio::time::timeout(DRAFT_TIMEOUT, turn_once(&scope, &owner, prompt, opts)).await {+ Ok(r) => r,+ Err(_) => Err("the draft turn took longer than 20 minutes".into()),+ }+ }+ Err(e) => Err(e),+ };+ drop(job);+ let tokens = state.db.tokens_between(&owner.id, started - Duration::seconds(1), Utc::now() + Duration::seconds(1)).await.unwrap_or(0);+ let _ = state.db.add_foundry_tokens(&run.id, tokens).await;+ let skill_id = state.db.get_foundry_run(&run.id).await.ok().flatten().and_then(|r| r.skill_id);+ match skill_id {+ Some(skill_id) => {+ let _ = state.db.move_foundry_run(&run.id, "drafting", "done", None).await;+ drop(_one);+ if replays(state).await > 0 {+ if let Err(why) = begin_replay(state, &skill_id, "kwant").await {+ tracing::info!(skill_id, why, "no replay for the Foundry draft");+ }+ }+ }+ None => {+ let why = match reply.err() {+ Some(e) => format!("the bot's turn ended without a draft: {}", clip(e.lines().next().unwrap_or(&e), 300)),+ None => "the bot's turn ended without a draft".into(),+ };+ let _ = state.db.move_foundry_run(&run.id, "drafting", "failed", Some(&why)).await;+ }+ }+}++/// Ends a run `failed` if its driver stops while it is still live (a panic, a dropped task).+struct Unstick(AppState, String);++impl Drop for Unstick {+ fn drop(&mut self) {+ let (state, id) = (self.0.clone(), std::mem::take(&mut self.1));+ if let Ok(rt) = tokio::runtime::Handle::try_current() {+ rt.spawn(async move { end_if_live(&state, &id, "the run stopped before it finished").await });+ }+ }+}++pub async fn end_if_live(state: &AppState, id: &str, reason: &str) -> bool {+ let Ok(Some(r)) = state.db.get_foundry_run(id).await else { return false };+ if !r.live() {+ return false;+ }+ let ended = state.db.move_foundry_run(id, &r.status, "failed", Some(reason)).await.unwrap_or(false);+ if ended {+ tracing::warn!(run_id = id, reason, "Foundry run ended");+ }+ ended+}++/// At startup, after the database marked runs a restart cut off `interrupted`: queued ones run+/// now, or fail if the Foundry was turned off.+pub async fn resume_after_restart(state: &AppState) {+ let on = enabled(state).await;+ for r in state.db.foundry_runs_in("queued").await.unwrap_or_default() {+ if !on {+ let _ = state.db.move_foundry_run(&r.id, "queued", "failed", Some("the Skill Foundry was turned off")).await;+ continue;+ }+ let s = state.clone();+ tokio::spawn(async move {+ match r.kind.as_str() {+ "draft" => drive_draft(&s, &r).await,+ _ => drive_replay(&s, &r).await,+ }+ });+ }+}++/// What a task looked like, for a prompt: title, acceptance, checks, evidence, what it did.+async fn task_brief(state: &AppState, task_id: &str) -> Option<String> {+ let task = state.db.get_task(task_id).await.ok().flatten()?;+ let checks: Vec<String> = state+ .db+ .list_checks(task_id)+ .await+ .unwrap_or_default()+ .iter()+ .map(|c| format!("{} {} ({})", c.kind, super::autofix::redact_value(&c.spec_value()), c.status))+ .collect();+ let evidence: Vec<String> = state+ .db+ .list_evidence(task_id)+ .await+ .unwrap_or_default()+ .iter()+ .take(5)+ .map(|e| format!("{} \"{}\" {}", e.kind, clip(&e.label, 120), clip(e.excerpt.as_deref().unwrap_or(""), 200)))+ .collect();+ let did = original_actions(state, task_id).await;+ Some(format!(+ "- task {id} \"{title}\"\n acceptance: {acc}\n checks: {ch}\n evidence: {ev}\n what it did: {did}",+ id = task.id,+ title = clip(&task.title, 200),+ acc = if task.acceptance.trim().is_empty() { "(none)".into() } else { clip(&task.acceptance, 600) },+ ch = if checks.is_empty() { "(none)".into() } else { checks.join("; ") },+ ev = if evidence.is_empty() { "(none)".into() } else { evidence.join("; ") },+ did = if did.is_empty() { "(no tool calls recorded)".into() } else { did.iter().take(10).cloned().collect::<Vec<_>>().join("; ") },+ ))+}++/// What the task's turns did that the side-effect ledger recorded, oldest first.+async fn original_actions(state: &AppState, task_id: &str) -> Vec<String> {+ state+ .db+ .tool_calls_of(task_id)+ .await+ .unwrap_or_default()+ .into_iter()+ .filter(|c| c.effect != "read")+ .take(MAX_ORIGINAL_ACTIONS)+ .map(|c| format!("{} ({})", clip(&c.summary, 200), c.decision))+ .collect()+}++async fn draft_prompt(state: &AppState, run: &FoundryRun) -> String {+ let now = Utc::now();+ let verified = state.db.cluster_tasks(&run.space_id, &run.kwant_id, &run.task_class, "verified", now, PROMPT_VERIFIED).await.unwrap_or_default();+ let failed = state.db.cluster_tasks(&run.space_id, &run.kwant_id, &run.task_class, "failed", now, PROMPT_FAILED).await.unwrap_or_default();+ let mut ok = Vec::new();+ for t in &verified {+ ok.extend(task_brief(state, t).await);+ }+ let mut bad = Vec::new();+ for t in &failed {+ bad.extend(task_brief(state, t).await);+ }+ format!(+ "[Skill Foundry] You finished several \"{class}\" tasks that an outside check verified. Write the \+ procedure you followed as a skill another run of you can reuse.\nVerified tasks:\n{ok}\nFailed tasks \+ of the same class, for contrast:\n{bad}\n\+ Call {tool} once with run_id {run}: a name (lowercase-with-dashes), a one-line description, a body \+ with the steps (what to check first, what to do, how to know it's done), the inputs a task must give \+ for it to apply, up to {mc} checks (the same kinds as a task's checks) that judge the result, 2–{mx} of \+ the verified task ids above as examples, and the tools the steps use (names you already have). \+ Listing a tool grants nothing. Change nothing else now. If the tasks don't share a procedure, \+ don't call {tool}; say why instead.",+ class = run.task_class,+ ok = if ok.is_empty() { "- none found".into() } else { ok.join("\n") },+ bad = if bad.is_empty() { "- none".into() } else { bad.join("\n") },+ tool = TOOL,+ run = run.id,+ mc = MAX_CHECKS,+ mx = MAX_EXAMPLES,+ )+}++// The tool++type ToolResult = (String, bool);++fn fail(msg: impl Into<String>) -> ToolResult {+ (msg.into(), true)+}++fn ok(v: Value) -> ToolResult {+ (serde_json::to_string_pretty(&v).unwrap_or_default(), false)+}++pub fn tool() -> Value {+ json!({+ "name": TOOL,+ "description": "Only when kwant asked you to draft a skill (Skill Foundry): store the procedure you followed in the listed tasks as a skill draft, for the person to review. Call it once. Listing tools grants nothing.",+ "inputSchema": {+ "type": "object",+ "properties": {+ "run_id": {"type": "string"},+ "name": {"type": "string", "description": "lowercase-with-dashes, like release-notes"},+ "description": {"type": "string", "description": "One line: when to use it."},+ "body": {"type": "string", "description": "The steps."},+ "inputs": {"type": "array", "maxItems": MAX_INPUTS, "items": {"type": "object", "properties": {+ "name": {"type": "string"}, "description": {"type": "string"}, "example": {"type": "string"}}, "required": ["name", "description"]}},+ "checks": {"type": "array", "maxItems": MAX_CHECKS, "items": {"type": "object", "properties": {+ "kind": {"type": "string", "enum": crate::db::missions::KWANT_CHECK_KINDS},+ "spec": {"type": "object", "description": "As a task's check: command {command}; http {url}; file_exists {path}; file_contains {path, text}; file_sha256 {path, sha256}."}},+ "required": ["kind", "spec"]}},+ "examples": {"type": "array", "minItems": MIN_EXAMPLES, "maxItems": MAX_EXAMPLES, "items": {"type": "string"}, "description": "Ids of the verified tasks above."},+ "tools": {"type": "array", "maxItems": MAX_TOOLS, "items": {"type": "string"}, "description": "Tools the steps use, by the names you have them under."},+ },+ "required": ["run_id", "name", "description", "body", "examples"],+ },+ })+}++fn field(v: &Value, what: &str, required: bool) -> Result<Option<String>, String> {+ let s = v.as_str().map(str::trim).unwrap_or("");+ if s.is_empty() {+ return if required { Err(format!("{what} is empty")) } else { Ok(None) };+ }+ if s.chars().count() > MAX_FIELD_CHARS {+ return Err(format!("{what} is longer than {MAX_FIELD_CHARS} characters"));+ }+ Ok(Some(s.to_string()))+}++/// Checks a draft's inputs, checks and tools. `held` is every tool name the bot has now.+pub fn validate_parts(inputs: &Value, checks: &Value, tools: &Value, held: &[String]) -> Result<(Value, Value, Vec<String>), String> {+ let inputs = match inputs {+ Value::Null => Vec::new(),+ Value::Array(a) => a.clone(),+ _ => return Err("inputs must be a list".into()),+ };+ if inputs.len() > MAX_INPUTS {+ return Err(format!("at most {MAX_INPUTS} inputs"));+ }+ let mut clean_inputs = Vec::new();+ for (i, x) in inputs.iter().enumerate() {+ let n = i + 1;+ let name = field(&x["name"], &format!("input {n} name"), true)?;+ let description = field(&x["description"], &format!("input {n} description"), true)?;+ let example = field(&x["example"], &format!("input {n} example"), false)?;+ clean_inputs.push(json!({"name": name, "description": description, "example": example}));+ }+ let checks = match checks {+ Value::Null => Vec::new(),+ Value::Array(a) => a.clone(),+ _ => return Err("checks must be a list".into()),+ };+ if checks.len() > MAX_CHECKS {+ return Err(format!("at most {MAX_CHECKS} checks"));+ }+ let mut clean_checks = Vec::new();+ for (i, c) in checks.iter().enumerate() {+ let n = i + 1;+ let kind = c["kind"].as_str().unwrap_or("");+ if !crate::db::missions::KWANT_CHECK_KINDS.contains(&kind) {+ return Err(format!("check {n}: kind must be one of {}", crate::db::missions::KWANT_CHECK_KINDS.join(", ")));+ }+ if !c["spec"].is_object() {+ return Err(format!("check {n}: spec must be an object"));+ }+ super::validate_check(kind, &c["spec"], false).map_err(|e| format!("check {n}: {e}"))?;+ clean_checks.push(json!({"kind": kind, "spec": c["spec"]}));+ }+ let tools = match tools {+ Value::Null => Vec::new(),+ Value::Array(a) => a.clone(),+ _ => return Err("tools must be a list".into()),+ };+ if tools.len() > MAX_TOOLS {+ return Err(format!("at most {MAX_TOOLS} tools"));+ }+ let mut clean_tools: Vec<String> = Vec::new();+ for t in &tools {+ let Some(name) = t.as_str().map(str::trim).filter(|s| !s.is_empty()) else {+ return Err("each tool must be a name".into());+ };+ if !crate::mcp::builtin_tools::known(name) && !held.iter().any(|h| h == name) {+ return Err(format!("you don't have a tool called {name}; list only tools you have now (a skill can't ask for new ones)"));+ }+ if !clean_tools.iter().any(|c| c == name) {+ clean_tools.push(name.to_string());+ }+ }+ Ok((Value::Array(clean_inputs), Value::Array(clean_checks), clean_tools))+}++/// Every tool name `scope`'s bot holds now, past built-ins and server tools: kwant's own tools,+/// bare and as `mcp__<kwant server>__…`; and the bot's active servers.+async fn held_tools(state: &AppState, scope: &SelfScope) -> (Vec<String>, Vec<String>) {+ let mut held = Vec::new();+ for t in crate::server::continuity::self_tool_names(state, scope).await {+ held.push(format!("mcp__{}__{t}", crate::mcp::SELF_SERVER_NAME));+ held.push(t);+ }+ let servers: Vec<String> = state.db.list_active_mcp_servers_for_kwant(&scope.kwant_id).await.unwrap_or_default().into_iter().map(|s| s.name).collect();+ (held, servers)+}++/// `name` is a tool of one of `servers` (`mcp__server__tool`): kwant can't list a server's tools+/// without starting it, so the server is what's checked.+fn on_server(name: &str, servers: &[String]) -> bool {+ crate::mcp::split_tool_name(name).is_some_and(|(server, tool)| !tool.is_empty() && servers.iter().any(|s| s == server))+}++pub async fn call(state: &AppState, scope: &SelfScope, args: &Value) -> ToolResult {+ if !enabled(state).await {+ return fail("The Skill Foundry is off in Settings.");+ }+ let run = match args["run_id"].as_str() {+ Some(id) => state.db.get_foundry_run(id).await.ok().flatten(),+ None => None,+ };+ let Some(run) = run.filter(|r| r.kind == "draft" && r.kwant_id == scope.kwant_id) else {+ return fail("No such Skill Foundry draft run for you.");+ };+ if run.status != "drafting" || run.skill_id.is_some() {+ return fail("This draft run isn't waiting for a draft (call skill_draft once).");+ }+ let text = match clean_skill_text(args["name"].as_str().unwrap_or(""), args["description"].as_str().unwrap_or(""), args["body"].as_str().unwrap_or("")) {+ Ok(t) => t,+ Err(e) => return fail(format!("{e}")),+ };+ let examples: Vec<String> = match args["examples"].as_array() {+ Some(a) => a.iter().filter_map(|v| v.as_str().map(|s| s.trim().to_string())).collect(),+ None => return fail("examples must be a list of task ids."),+ };+ if !(MIN_EXAMPLES..=MAX_EXAMPLES).contains(&examples.len()) {+ return fail(format!("Give {MIN_EXAMPLES}–{MAX_EXAMPLES} example task ids."));+ }+ let cluster = state.db.cluster_tasks(&run.space_id, &run.kwant_id, &run.task_class, "verified", Utc::now(), 1000).await.unwrap_or_default();+ let mut seen = Vec::new();+ for e in &examples {+ if !cluster.contains(e) {+ return fail(format!("Example {e} isn't one of your verified \"{}\" tasks.", run.task_class));+ }+ if seen.contains(e) {+ return fail(format!("Example {e} is listed twice."));+ }+ seen.push(e.clone());+ }+ let (held, servers) = held_tools(state, scope).await;+ let tools_arg = match &args["tools"] {+ Value::Array(a) => Value::Array(a.iter().filter(|t| !t.as_str().is_some_and(|n| on_server(n, &servers))).cloned().collect()),+ other => other.clone(),+ };+ let (inputs, checks, mut tools) = match validate_parts(&args["inputs"], &args["checks"], &tools_arg, &held) {+ Ok(p) => p,+ Err(e) => return fail(format!("{e}.")),+ };+ // Server tools (checked by server above) keep their place after the others+ if let Some(a) = args["tools"].as_array() {+ for n in a.iter().filter_map(Value::as_str).map(str::trim).filter(|n| on_server(n, &servers)) {+ if !tools.iter().any(|t| t == n) {+ tools.push(n.to_string());+ }+ }+ }+ let draft = NewDraft { kwant_id: run.kwant_id.clone(), task_class: run.task_class.clone(), text, inputs, checks, examples: examples.clone(), tools };+ match state.db.insert_foundry_draft(&run.space_id, &draft, &run.id).await {+ Ok((skill, meta)) => {+ let _ = state.db.set_foundry_run_skill(&run.id, &skill.id).await;+ for t in &examples {+ if let Err(e) = state.db.log_task_event(t, "skill_drafted_from", &scope.kwant_id, &json!({"skill_id": skill.id, "version": meta.version})).await {+ tracing::warn!(task_id = %t, error = %e, "skill_drafted_from not logged");+ }+ }+ changed(state, &skill);+ ok(json!({+ "skill_id": skill.id,+ "version": meta.version,+ "next": "Stored as a draft for the person to review. A dry-run replay on its examples runs after your turn; you don't need to do anything else.",+ }))+ }+ Err(SkillError::TooManyPending) => fail("You have too many skills waiting for review; the person needs to review some first."),+ Err(e) => fail(format!("Could not store the draft: {e}")),+ }+}++// Replay++/// Opens a replay run of draft `skill_id` (`queued`) and drives it in the background.+pub async fn begin_replay(state: &AppState, skill_id: &str, actor: &str) -> Result<FoundryRun, String> {+ if !enabled(state).await {+ return Err("the Skill Foundry is off in Settings".into());+ }+ let (skill, meta) = match (state.db.get_skill(skill_id).await, state.db.skill_meta(skill_id).await) {+ (Ok(Some(s)), Ok(Some(m))) => (s, m),+ _ => return Err("only a Skill Foundry draft can be replayed".into()),+ };+ if skill.status != "pending" {+ return Err(format!("only a draft waiting for review is replayed (this one is {})", skill.status));+ }+ if replays(state).await == 0 {+ return Err("replays are off (skill_foundry_replays = 0)".into());+ }+ if let Ok(Some(_)) = state.db.live_foundry_run("replay", &meta.kwant_id, &meta.task_class, Some(skill_id)).await {+ return Err("a replay of this draft is already running".into());+ }+ let run = state.db.create_foundry_run("replay", &meta.space_id, &meta.kwant_id, &meta.task_class, Some(skill_id)).await.map_err(|e| e.to_string())?;+ tracing::info!(run_id = %run.id, skill_id, actor, "Foundry replay queued");+ let (s, r) = (state.clone(), run.clone());+ tokio::spawn(async move { drive_replay(&s, &r).await });+ Ok(run)+}++/// The scratch folder of a replay's example `n`, under the data dir.+pub fn scratch_dir(state: &AppState, run_id: &str, n: usize) -> PathBuf {+ state.config.data_dir.join("foundry").join(run_id).join(n.to_string())+}++fn private_dir(dir: &FsPath) -> std::io::Result<()> {+ use std::os::unix::fs::PermissionsExt;+ if let Some(parent) = dir.parent() {+ std::fs::create_dir_all(parent)?;+ std::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o700))?;+ }+ std::fs::create_dir_all(dir)?;+ std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))+}++/// Runs a draft's checks on a replay's scratch folder: file checks run there; command and http+/// checks would reach outside it, so they are `not_replayable`, never passed.+pub async fn scratch_checks(checks: &[Value], scratch: &FsPath) -> Vec<Value> {+ let mut out = Vec::new();+ for c in checks {+ let kind = c["kind"].as_str().unwrap_or("");+ let spec = super::autofix::redact_value(&c["spec"]);+ if kind.starts_with("file_") {+ let (status, output) = super::checks::run_spec(kind, &c["spec"], Some(scratch), false).await;+ out.push(json!({"kind": kind, "spec": spec, "status": status, "output": output}));+ } else {+ out.push(json!({"kind": kind, "spec": spec, "status": "not_replayable", "output": "reaches outside the scratch folder; not run in a replay"}));+ }+ }+ out+}++/// One example's verdict: `passed` (every replayable check passed, and there was one),+/// `failed`, or `not_checked`.+pub fn example_verdict(checks: &[Value]) -> &'static str {+ let ran: Vec<&str> = checks.iter().filter_map(|c| c["status"].as_str()).filter(|s| *s != "not_replayable").collect();+ if ran.is_empty() {+ "not_checked"+ } else if ran.iter().all(|s| *s == "passed") {+ "passed"+ } else {+ "failed"+ }+}++/// Replays a draft on up to `skill_foundry_replays` of its examples, one dry-run turn each, then+/// stores the report on the draft. A failed replay never touches the draft itself.+pub async fn drive_replay(state: &AppState, run: &FoundryRun) {+ let _unstick = Unstick(state.clone(), run.id.clone());+ let _one = ONE.lock().await;+ if !state.db.move_foundry_run(&run.id, "queued", "replaying", None).await.unwrap_or(false) {+ return;+ }+ let skill_id = run.skill_id.clone().unwrap_or_default();+ let (Ok(Some(skill)), Ok(Some(meta)), Ok(Some(owner))) = (state.db.get_skill(&skill_id).await, state.db.skill_meta(&skill_id).await, state.db.get_kwant(&run.kwant_id).await) else {+ let _ = state.db.move_foundry_run(&run.id, "replaying", "failed", Some("the draft or its bot no longer exists")).await;+ return;+ };+ let n = replays(state).await.max(0) as usize;+ let cap = replay_tokens(state).await.max(0) as u64;+ let mut examples = Vec::new();+ let mut tokens_total = 0;+ for (i, task_id) in meta.examples().into_iter().take(n).enumerate() {+ let r = replay_one(state, run, &skill, &meta, &owner, &task_id, i, cap).await;+ tokens_total += r["tokens"].as_i64().unwrap_or(0);+ examples.push(r);+ }+ let count = |v: &str| examples.iter().filter(|e| e["verdict"] == v).count();+ let report = json!({+ "run_id": run.id,+ "at": Utc::now(),+ "examples": examples,+ "passed": count("passed"),+ "failed": count("failed"),+ "not_checked": count("not_checked"),+ "errors": count("error"),+ "tokens": tokens_total,+ });+ let _ = state.db.add_foundry_tokens(&run.id, tokens_total).await;+ let _ = state.db.set_skill_replay(&skill_id, &report).await;+ skill_event(state, &skill_id, "skill_replayed", "kwant", json!({"run_id": run.id, "passed": report["passed"], "failed": report["failed"], "not_checked": report["not_checked"], "errors": report["errors"], "tokens": tokens_total})).await;+ let all_errors = !report["examples"].as_array().is_some_and(|a| a.iter().any(|e| e["verdict"] != "error"));+ let (to, why) = if all_errors { ("failed", Some("no example could be replayed")) } else { ("done", None) };+ let _ = state.db.move_foundry_run(&run.id, "replaying", to, why).await;+ if let Ok(Some(s)) = state.db.get_skill(&skill_id).await {+ changed(state, &s);+ }+}++#[allow(clippy::too_many_arguments)]+async fn replay_one(state: &AppState, run: &FoundryRun, skill: &Skill, meta: &SkillMeta, owner: &Kwant, task_id: &str, i: usize, cap: u64) -> Value {+ let began = std::time::Instant::now();+ let Ok(Some(task)) = state.db.get_task(task_id).await else {+ return json!({"task_id": task_id, "verdict": "error", "error": "the task no longer exists", "tokens": 0});+ };+ let scratch = scratch_dir(state, &run.id, i);+ let mut out = json!({"task_id": task.id, "title": task.title, "original_actions": original_actions(state, task_id).await});+ let result = async {+ let dir = scratch.clone();+ tokio::task::spawn_blocking(move || private_dir(&dir)).await.map_err(|e| e.to_string())?.map_err(|e| format!("the scratch folder can't be made: {e}"))?;+ let restored = super::checkpoints::materialize_first(state, task_id, &scratch).await?;+ let log: RehearseLog = Default::default();+ let prompt = replay_prompt(skill, &task, restored);+ let job = state.turns.start_job([owner.id.clone()]);+ // The cap: cancel this job's turn once it reports more fresh tokens than allowed+ let over = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));+ let watcher = {+ let (turns, token, kwant, over) = (state.turns.clone(), job.token.clone(), owner.id.clone(), over.clone());+ tokio::spawn(async move {+ loop {+ tokio::time::sleep(CAP_POLL).await;+ if turns.usage_of(&kwant, REPLAY_PURPOSE) > cap {+ over.store(true, std::sync::atomic::Ordering::SeqCst);+ token.cancel();+ return;+ }+ }+ })+ };+ let started = Utc::now();+ let reply = match scope_for(state, owner, None, None, &job, 0).await {+ Ok(mut scope) => {+ scope.workspace_dir = Some(scratch.clone());+ let mut opts = TurnOpts::always_asking("Skill Foundry replay");+ (opts.unsaved, opts.quiet_failure, opts.purpose) = (true, true, Some(REPLAY_PURPOSE.into()));+ opts.tier = tier_of(model_mode(state).await);+ opts.rehearse = Some(log.clone());+ match tokio::time::timeout(REPLAY_TIMEOUT, turn_once(&scope, owner, prompt, opts)).await {+ Ok(r) => r,+ Err(_) => Err("the replay took longer than 15 minutes".into()),+ }+ }+ Err(e) => Err(e),+ };+ watcher.abort();+ drop(job);+ let tokens = state.db.tokens_between(&owner.id, started - Duration::seconds(1), Utc::now() + Duration::seconds(1)).await.unwrap_or(0);+ let would_have: Vec<Value> = log.lock().map(|l| l.clone()).unwrap_or_default();+ let checks = scratch_checks(&meta.checks(), &scratch).await;+ let capped = over.load(std::sync::atomic::Ordering::SeqCst);+ Ok::<_, String>((restored, reply, tokens, would_have, checks, capped))+ }+ .await;+ // The scratch copy never outlives its replay+ let dir = scratch.clone();+ let _ = tokio::task::spawn_blocking(move || std::fs::remove_dir_all(dir)).await;+ if let Some(parent) = scratch.parent() {+ let _ = std::fs::remove_dir(parent);+ }+ match result {+ Ok((restored, reply, tokens, would_have, checks, capped)) => {+ let error = if capped {+ Some(format!("stopped at the replay token cap ({cap})"))+ } else {+ reply.err().map(|e| clip(e.lines().next().unwrap_or(&e), 300))+ };+ // A turn that never ran (no Claude, an engine error) is an error, not a failed check+ let verdict = match &error {+ Some(_) if tokens == 0 && would_have.is_empty() => "error",+ _ => example_verdict(&checks),+ };+ out["files_restored"] = json!(restored);+ out["would_have"] = json!(would_have);+ out["checks"] = json!(checks);+ out["verdict"] = json!(verdict);+ out["error"] = json!(error);+ out["tokens"] = json!(tokens);+ }+ Err(e) => {+ out["verdict"] = json!("error");+ out["error"] = json!(e);+ out["tokens"] = json!(0);+ }+ }+ out["seconds"] = json!(began.elapsed().as_secs());+ out+}++fn replay_prompt(skill: &Skill, task: &crate::db::missions::Task, restored: usize) -> String {+ format!(+ "[Skill Foundry replay] This is a dry run of an earlier task, to test a drafted skill. Your folder is a \+ scratch copy{files}; nothing you do here is kept or sent. Calls that could change anything outside \+ this folder (send, publish, sign in, pay, run commands, other servers' tools) don't run: kwant records \+ them as what you would have done.\nTask \"{title}\"\nAcceptance: {acc}\n\nFollow this skill:\n\+ --- skill {name} ---\n{body}\n--- end of skill ---\n\nDo the task in this folder as far as you can, then \+ end your turn with a short summary of what you did and what you would have done outside it.",+ files = if restored > 0 { format!(" of its folder before it started ({restored} files)") } else { " (empty: the task had no snapshot)".into() },+ title = clip(&task.title, 300),+ acc = if task.acceptance.trim().is_empty() { "(none given)".into() } else { clip(&task.acceptance, 2000) },+ name = skill.name,+ body = skill.body,+ )+}++// Routes++fn skill_error(e: SkillError) -> Response {+ match e {+ SkillError::NotFound => not_found("skill"),+ SkillError::Conflict(why) => conflict(why),+ SkillError::Db(detail) => internal(detail),+ other => bad(other.to_string()),+ }+}++/// The candidate clusters of a space, each with why no draft is offered now (`block`).+async fn clusters_json(state: &AppState, space: &str) -> Vec<Value> {+ let now = Utc::now();+ let mut out = Vec::new();+ for c in state.db.foundry_clusters(Some(space), now).await.unwrap_or_default() {+ let block = state.db.foundry_block(&c.kwant_id, &c.task_class, now).await.ok().flatten();+ out.push(json!({"id": c.id(), "kwant_id": c.kwant_id, "task_class": c.task_class, "verified": c.verified, "total": c.total, "block": block}));+ }+ out+}++fn skill_json(skill: &Skill, meta: &SkillMeta) -> Value {+ let mut j = serde_json::to_value(skill).unwrap_or_default();+ j["foundry"] = meta.json();+ j+}++/// `GET /api/skills/foundry?space=` (person only): settings, candidate clusters, drafts and+/// versions with their replay reports, and recent runs.+pub async fn overview(State(state): State<AppState>, Scope(space): Scope) -> Response {+ let skills = match state.db.foundry_skills(space.as_str(), None).await {+ Ok(s) => s,+ Err(e) => return internal(e),+ };+ let runs = state.db.foundry_runs_of_space(space.as_str(), 20).await.unwrap_or_default();+ Json(json!({+ "enabled": enabled(&state).await,+ "settings": {+ "model": model_mode(&state).await,+ "daily_drafts": daily_drafts(&state).await,+ "replays": replays(&state).await,+ "replay_tokens": replay_tokens(&state).await,+ },+ "drafts_today": state.db.draft_runs_since(midnight()).await.unwrap_or(0),+ "clusters": clusters_json(&state, space.as_str()).await,+ "skills": skills.iter().map(|(s, m)| skill_json(s, m)).collect::<Vec<_>>(),+ "runs": runs,+ }))+ .into_response()+}++/// `POST /api/skills/foundry/:cluster/draft` (person only): draft a skill for the cluster now,+/// without waiting for the hourly tick. A bot's live skill for the class gets a new version.+pub async fn draft_now(State(state): State<AppState>, Scope(space): Scope, Path(cluster): Path<String>) -> Response {+ if !enabled(&state).await {+ return conflict("The Skill Foundry is off in Settings.");+ }+ let Some((kwant, class)) = split_cluster(&cluster) else { return bad("cluster must be <bot id>~<class>") };+ let found = state.db.foundry_clusters(Some(space.as_str()), Utc::now()).await.unwrap_or_default().into_iter().find(|c| c.kwant_id == kwant && c.task_class == class);+ let Some(c) = found else {+ return not_found("cluster (it needs 3 or more verified tasks of one class, 70% of them verified, in 60 days)");+ };+ match begin_draft(&state, &c, "person").await {+ Ok(run) => (StatusCode::ACCEPTED, Json(json!({"run": run, "cluster": cluster_id(&c.kwant_id, &c.task_class)}))).into_response(),+ Err(why) => conflict(why),+ }+}++async fn foundry_skill(state: &AppState, space: &str, id: &str) -> Result<(Skill, SkillMeta), Box<Response>> {+ match (state.db.get_skill(id).await, state.db.skill_meta(id).await) {+ (Ok(Some(s)), Ok(Some(m))) if m.space_id == space => Ok((s, m)),+ (Err(e), _) | (_, Err(e)) => Err(Box::new(internal(e))),+ _ => Err(Box::new(not_found("Skill Foundry skill"))),+ }+}++/// `POST /api/skills/:id/replay` (person only): replay a draft again (after an edit, say).+pub async fn replay(State(state): State<AppState>, Scope(space): Scope, Path(id): Path<String>) -> Response {+ if let Err(r) = foundry_skill(&state, space.as_str(), &id).await {+ return *r;+ }+ match begin_replay(&state, &id, "person").await {+ Ok(run) => (StatusCode::ACCEPTED, Json(json!({"run": run}))).into_response(),+ Err(why) => conflict(why),+ }+}++/// `POST /api/skills/:id/rollback` (person only): make `id`, an earlier version of its lineage,+/// the live one again. Works with the Foundry off: a rollback only ever goes back.+pub async fn rollback(State(state): State<AppState>, Scope(space): Scope, Path(id): Path<String>) -> Response {+ if let Err(r) = foundry_skill(&state, space.as_str(), &id).await {+ return *r;+ }+ let before = state.db.skill_meta(&id).await.ok().flatten().map(|m| m.lineage_id);+ match state.db.rollback_skill(&id, "person").await {+ Ok(skill) => {+ if let Some(lineage) = before {+ for (s, _) in state.db.lineage(&lineage).await.unwrap_or_default() {+ changed(&state, &s);+ }+ }+ Json(skill).into_response()+ }+ Err(e) => skill_error(e),+ }+}++/// `GET /api/skills/:id/foundry`: a Foundry skill with its versions, history and runs.+pub async fn detail(State(state): State<AppState>, Scope(space): Scope, Path(id): Path<String>) -> Response {+ let (skill, meta) = match foundry_skill(&state, space.as_str(), &id).await {+ Ok(p) => p,+ Err(r) => return *r,+ };+ let versions = state.db.lineage(&meta.lineage_id).await.unwrap_or_default();+ let ids: Vec<String> = versions.iter().map(|(s, _)| s.id.clone()).collect();+ let events = state.db.skill_events(&ids).await.unwrap_or_default();+ let runs: Vec<FoundryRun> = state.db.foundry_runs_of_space(space.as_str(), 200).await.unwrap_or_default().into_iter().filter(|r| r.skill_id.as_ref().is_some_and(|s| ids.contains(s))).collect();+ Json(json!({+ "skill": skill_json(&skill, &meta),+ "versions": versions.iter().map(|(s, m)| json!({"id": s.id, "version": m.version, "status": s.status, "name": s.name, "created_at": s.created_at, "reviewed_at": s.reviewed_at})).collect::<Vec<_>>(),+ "events": events.iter().map(|e| json!({"skill_id": e.skill_id, "kind": e.kind, "actor": e.actor, "detail": serde_json::from_str::<Value>(&e.detail).unwrap_or_default(), "at": e.created_at})).collect::<Vec<_>>(),+ "runs": runs,+ }))+ .into_response()+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn settings_are_checked() {+ assert!(settings_error(Some("on"), Some("balanced"), Some(2), Some(3), Some(60_000)).is_none());+ assert!(settings_error(Some("auto"), None, None, None, None).is_some());+ assert!(settings_error(None, Some("opus"), None, None, None).is_some());+ assert!(settings_error(None, None, Some(0), None, None).is_some());+ assert!(settings_error(None, None, None, Some(6), None).is_some());+ assert!(settings_error(None, None, None, Some(0), None).is_none());+ assert!(settings_error(None, None, None, None, Some(1_000)).is_some());+ }++ #[test]+ fn verdicts_never_count_unreplayable_checks_as_passed() {+ let c = |s: &str| json!({"status": s});+ assert_eq!(example_verdict(&[c("not_replayable")]), "not_checked");+ assert_eq!(example_verdict(&[]), "not_checked");+ assert_eq!(example_verdict(&[c("passed"), c("not_replayable")]), "passed");+ assert_eq!(example_verdict(&[c("passed"), c("failed")]), "failed");+ assert_eq!(example_verdict(&[c("error")]), "failed");+ }++ #[test]+ fn drafts_list_only_tools_the_bot_holds() {+ let held = vec!["Read".to_string(), "task_list".to_string()];+ assert!(validate_parts(&Value::Null, &Value::Null, &json!(["Read", "task_list", "Read"]), &held).is_ok_and(|(_, _, t)| t == ["Read", "task_list"]));+ assert!(validate_parts(&Value::Null, &Value::Null, &json!(["NotATool"]), &held).unwrap_err().contains("don't have a tool called NotATool"));+ assert!(validate_parts(&Value::Null, &Value::Null, &json!([7]), &held).is_err());+ }++ #[test]+ fn draft_checks_pass_the_task_check_validator() {+ let none: Vec<String> = Vec::new();+ assert!(validate_parts(&Value::Null, &json!([{"kind": "file_exists", "spec": {"path": "NOTES.md"}}]), &Value::Null, &none).is_ok());+ assert!(validate_parts(&Value::Null, &json!([{"kind": "person", "spec": {}}]), &Value::Null, &none).is_err());+ assert!(validate_parts(&Value::Null, &json!([{"kind": "http", "spec": {"url": "ftp://x"}}]), &Value::Null, &none).is_err());+ let six = Value::Array(vec![json!({"kind": "file_exists", "spec": {"path": "a"}}); 6]);+ assert!(validate_parts(&Value::Null, &six, &Value::Null, &none).is_err());+ let nine = Value::Array(vec![json!({"name": "n", "description": "d"}); 9]);+ assert!(validate_parts(&nine, &Value::Null, &Value::Null, &none).is_err());+ assert!(validate_parts(&json!([{"name": "n"}]), &Value::Null, &Value::Null, &none).is_err());+ }+}diff --git a/src/server/missions/mod.rs b/src/server/missions/mod.rsindex e3693ab7..9d7de88f 100644--- a/src/server/missions/mod.rs+++ b/src/server/missions/mod.rs@@ -17,6 +17,7 @@ pub mod autofix;pub mod checkpoints;pub mod checks;pub mod flight_school;+pub mod foundry;pub mod graph;pub mod listener;pub mod performance;diff --git a/src/server/mod.rs b/src/server/mod.rsindex 24716b58..bffbb3e4 100644--- a/src/server/mod.rs+++ b/src/server/mod.rs@@ -404,6 +404,11 @@ pub fn create_router(state: AppState) -> Router {.route("/api/human-steps/:id", get(human_steps::get)).route("/api/human-steps/:id/done", post(human_steps::done)).route("/api/human-steps/:id/decline", post(human_steps::decline))+ .route("/api/skills/foundry", get(missions::foundry::overview))+ .route("/api/skills/foundry/:cluster/draft", post(missions::foundry::draft_now))+ .route("/api/skills/:id/foundry", get(missions::foundry::detail))+ .route("/api/skills/:id/replay", post(missions::foundry::replay))+ .route("/api/skills/:id/rollback", post(missions::foundry::rollback)).route("/api/skills", get(skills::list).post(skills::create)).route("/api/skills/:id", get(skills::get).patch(skills::update).delete(skills::remove)).route("/api/skills/:id/diff", get(skills::diff))diff --git a/src/server/routes.rs b/src/server/routes.rsindex 661451e4..72c41792 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -1497,6 +1497,9 @@ pub(super) struct TurnOpts {pub(super) purpose: Option<String>,/// The model tier this turn runs on whatever Laya's effort says (see [`crate::router::with_tier`]).pub(super) tier: Option<crate::drivers::engines::Tier>,+ /// A Skill Foundry replay (a dry run, see [`super::mcp_runtime::RehearseApprover`]): runs only+ /// on Claude with kwant's permission hook, opens no page, and logs refused calls here.+ pub(super) rehearse: Option<super::mcp_runtime::RehearseLog>,}impl TurnOpts {@@ -1928,7 +1931,8 @@ async fn run_kwant_turn_inner(let mut final_prompt = prompt.clone();let nav_prompt = opts.nav_prompt.as_deref().unwrap_or(&prompt);- let target_url_opt = detect_url_with_context(nav_prompt, active_browser_url.as_deref());+ // A replay opens no page: the bot's browser isn't its scratch folder+ let target_url_opt = if opts.rehearse.is_some() { None } else { detect_url_with_context(nav_prompt, active_browser_url.as_deref()) };if let Some(target_url) = target_url_opt {event_broadcast.send(RuntimeEvent::ThinkingDelta(format!(@@ -2043,6 +2047,7 @@ async fn run_kwant_turn_inner(let card_opts = super::mcp_runtime::TurnApprovalOpts {routed: Some((target_model.clone(), effort_level.clone())),always_ask: opts.always_ask,+ rehearse: opts.rehearse.clone(),};let mcp_turn = super::mcp_runtime::prepare_turn_with_opts(state,@@ -2109,12 +2114,20 @@ async fn run_kwant_turn_inner(// Saved with the gave-up reply, so a client can offer Retry without reading its wordinglet mut gave_up_meta: Option<serde_json::Value> = None;let mut ran_on: Option<RanOn> = None;+ // Only Claude's permission hook holds every call of a replay to the scratch folder+ let rehearse_blocked = opts.rehearse.is_some()+ && (engine != Some(crate::profiles::Engine::Claude) || mcp_turn.is_none());+ let attempts = if rehearse_blocked { Vec::new() } else { attempts };if attempts.is_empty() {- let text = format!(- "⚠️ [{}] This machine is off in this space and no other {} account is on.",- target_kwant.name,- engine.map(|e| e.as_str()).unwrap_or("model")- );+ let text = if rehearse_blocked {+ format!("⚠️ [{}] A skill replay runs only on Claude, with kwant's tool checks on.", target_kwant.name)+ } else {+ format!(+ "⚠️ [{}] This machine is off in this space and no other {} account is on.",+ target_kwant.name,+ engine.map(|e| e.as_str()).unwrap_or("model")+ )+ };event_broadcast.send(RuntimeEvent::TextDelta(text.clone()));event_broadcast.send(RuntimeEvent::TurnComplete {tokens: 0,@@ -3330,6 +3343,16 @@ pub struct SettingsResponse {pub auditor_daily_cap: i64,/// The model tier of audit turns: `fast` (default), `balanced`, `deep` or `bot` (its usual one).pub auditor_model: String,+ /// Skill Foundry: `off` (default) or `on` (see `super::missions::foundry`).+ pub skill_foundry: String,+ /// The model tier of Foundry draft and replay turns: `balanced` (default), `fast`, `deep` or `bot`.+ pub skill_foundry_model: String,+ /// Drafts started per UTC day (1–20).+ pub skill_foundry_daily_drafts: i64,+ /// Past examples each draft is replayed on (0–5; 0 turns replays off).+ pub skill_foundry_replays: i64,+ /// Fresh tokens one replay turn may use before it is stopped (5,000–500,000).+ pub skill_foundry_replay_tokens: i64,}/// Unknown keys are refused, so a typo or a key from another version fails loudly instead of@@ -3376,6 +3399,11 @@ pub struct SaveSettingsPayload {pub auditor: Option<String>,pub auditor_daily_cap: Option<i64>,pub auditor_model: Option<String>,+ pub skill_foundry: Option<String>,+ pub skill_foundry_model: Option<String>,+ pub skill_foundry_daily_drafts: Option<i64>,+ pub skill_foundry_replays: Option<i64>,+ pub skill_foundry_replay_tokens: Option<i64>,}pub async fn get_settings(State(state): State<AppState>) -> Result<Json<SettingsResponse>, StatusCode> {@@ -3431,6 +3459,11 @@ pub async fn get_settings(State(state): State<AppState>) -> Result<Json<Settingsauditor: if super::missions::auditor::enabled(&state).await { "on" } else { "off" }.into(),auditor_daily_cap: super::missions::auditor::daily_cap(&state).await,auditor_model: super::missions::auditor::model_mode(&state).await.into(),+ skill_foundry: if super::missions::foundry::enabled(&state).await { "on" } else { "off" }.into(),+ skill_foundry_model: super::missions::foundry::model_mode(&state).await.into(),+ skill_foundry_daily_drafts: super::missions::foundry::daily_drafts(&state).await,+ skill_foundry_replays: super::missions::foundry::replays(&state).await,+ skill_foundry_replay_tokens: super::missions::foundry::replay_tokens(&state).await,}))}@@ -3492,6 +3525,15 @@ pub async fn save_settings(if let Some(e) = super::missions::auditor::settings_error(payload.auditor.as_deref(), payload.auditor_daily_cap, payload.auditor_model.as_deref()) {return bad(e);}+ if let Some(e) = super::missions::foundry::settings_error(+ payload.skill_foundry.as_deref(),+ payload.skill_foundry_model.as_deref(),+ payload.skill_foundry_daily_drafts,+ payload.skill_foundry_replays,+ payload.skill_foundry_replay_tokens,+ ) {+ return bad(e);+ }if payload.chain_token_budget.is_some_and(|n| n > super::budget::MAX) {return bad(format!("chain_token_budget must be 0–{}", super::budget::MAX));}@@ -3623,6 +3665,20 @@ pub async fn save_settings(if let Some(m) = &payload.auditor_model {let _ = state.db.set_setting(super::missions::auditor::MODEL_SETTING, m).await;}+ {+ use super::missions::foundry as f;+ if let Some(m) = &payload.skill_foundry {+ let _ = state.db.set_setting(f::SETTING, m).await;+ }+ if let Some(m) = &payload.skill_foundry_model {+ let _ = state.db.set_setting(f::MODEL_SETTING, m).await;+ }+ for (key, value) in [(f::DRAFTS_SETTING, payload.skill_foundry_daily_drafts), (f::REPLAYS_SETTING, payload.skill_foundry_replays), (f::REPLAY_TOKENS_SETTING, payload.skill_foundry_replay_tokens)] {+ if let Some(n) = value {+ let _ = state.db.set_setting(key, &n.to_string()).await;+ }+ }+ }if let Some(on) = payload.agent_tools {let _ = state.db.set_setting("agent_tools", if on { "on" } else { "off" }).await;}diff --git a/src/server/scheduler.rs b/src/server/scheduler.rsindex 4bc7a295..9ec0a040 100644--- a/src/server/scheduler.rs+++ b/src/server/scheduler.rs@@ -684,5 +684,6 @@ pub fn spawn_background(state: AppState, shutdown: CancellationToken) {crate::zombie::hunt::spawn(state.clone(), shutdown.clone());crate::documents::reminders::spawn(state.clone(), shutdown.clone());super::missions::listener::spawn(state.clone(), shutdown.clone());+ super::missions::foundry::spawn(state.clone(), shutdown.clone());spawn(state, shutdown);}diff --git a/src/server/turns.rs b/src/server/turns.rsindex 9fcbfcf5..3534fcef 100644--- a/src/server/turns.rs+++ b/src/server/turns.rs@@ -181,6 +181,19 @@ impl TurnRegistry {m.seen = m.seen.max(fresh);}+ /// Fresh tokens `kwant_id`'s running turns with `purpose` reported so far (a Skill Foundry+ /// replay's cap watches this mid-turn).+ pub fn usage_of(&self, kwant_id: &str, purpose: &str) -> u64 {+ let inner = self.lock();+ inner+ .turns+ .values()+ .filter(|t| t.kwant_id == kwant_id && t.purpose.as_deref() == Some(purpose))+ .filter_map(|t| inner.meters.get(&t.turn_id))+ .map(|m| m.seen)+ .sum()+ }+/// Fresh tokens of the turn not booked yet, now marked booked: what a task the bot hands in/// mid-turn pays for at that moment.pub fn book_usage(&self, turn_id: &str) -> u64 {@@ -395,6 +408,29 @@ impl Limiter {#[cfg(test)]mod tests {+ #[test]+ fn usage_of_sums_a_bots_running_turns_with_a_purpose() {+ let reg = super::TurnRegistry::default();+ let turn = |id: &str, kwant: &str, purpose: Option<&str>| super::ActiveTurn {+ turn_id: id.into(),+ kwant_id: kwant.into(),+ context_id: "c".into(),+ thread_id: None,+ state: "running".into(),+ since: chrono::Utc::now(),+ purpose: purpose.map(String::from),+ };+ reg.set_turn(turn("a", "k", Some("foundry")));+ reg.set_turn(turn("b", "k", None));+ reg.set_turn(turn("c", "other", Some("foundry")));+ for (id, n) in [("a", 70), ("b", 1000), ("c", 1000)] {+ reg.saw_usage(id, n);+ }+ assert_eq!(reg.usage_of("k", "foundry"), 70);+ reg.end_turn("a");+ assert_eq!(reg.usage_of("k", "foundry"), 0);+ }+#[test]fn usage_booked_mid_turn_is_counted_once() {let reg = TurnRegistry::default();diff --git a/tests/foundry_test.rs b/tests/foundry_test.rsnew file mode 100644index 00000000..5ae9257d--- /dev/null+++ b/tests/foundry_test.rs@@ -0,0 +1,640 @@+//! The Skill Foundry (Phase D3): which clusters get a draft, `skill_draft` validation, replays as+//! dry runs on a scratch copy, rollback within a lineage, restarts, and that a Foundry skill+//! never grants tools or approvals. Off by default. No test here runs a model turn.+//! Contract: docs/mission-control.md §19.++use axum::{+ body::{to_bytes, Body},+ http::{Request, StatusCode},+ Router,+};+use kwnt::{+ broker::PermissionBroker,+ config::Config,+ db::{+ foundry::NewDraft,+ missions::{NewTask, Task},+ models::{Kwant, NewKwant},+ performance::NewObservation,+ skills::clean_skill_text,+ spaces::SpaceId,+ Database,+ },+ mcp::{ApprovalOutcome, BuiltinCall, ToolApprovalRequest, ToolApprover, SELF_SERVER_NAME},+ router::LayaRouter,+ server::{+ continuity::{SelfScope, TurnOrigin},+ create_router, mcp_runtime,+ missions::foundry,+ AppState,+ },+ tools::ToolRunner,+};+use serde_json::{json, Value};+use std::time::Duration;+use tempfile::{tempdir, TempDir};+use tower::ServiceExt;++struct Env {+ app: Router,+ state: AppState,+ general: String,+ _tmp: TempDir,+}++async fn setup() -> Env {+ let tmp = tempdir().unwrap();+ let data = tmp.path().join("data");+ let db = Database::init(&data).await.unwrap();+ let config = Config {+ data_dir: data.clone(),+ 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(data.join("workspace")),+ PermissionBroker::new(),+ LayaRouter::new(config.laya_url.clone()),+ );+ let space = SpaceId::default_space();+ 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()), state, general, _tmp: tmp };+ person(&e, "POST", "/api/settings", Some(json!({"mission_board": true}))).await;+ 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 foundry_on(e: &Env, drafts: i64) {+ person(e, "POST", "/api/settings", Some(json!({"skill_foundry": "on", "skill_foundry_daily_drafts": drafts}))).await;+}++/// A bot of the default space. Its engine is Codex, so a replay of it is refused before any+/// model runs (replays need Claude's permission hook), and no test here starts a real turn.+async fn bot(e: &Env, name: &str) -> Kwant {+ let input = NewKwant {+ name: name.into(),+ title: "Tester".into(),+ persona_prompt: String::new(),+ soul: String::new(),+ avatar_sprite: "s".into(),+ driver_type: "cli".into(),+ preferred_model: "codex".into(),+ };+ e.state.db.create_kwant(&SpaceId::default_space(), &input).await.unwrap()+}++async fn task(e: &Env, owner: &Kwant, title: &str) -> Task {+ let t = NewTask {+ title: title.into(),+ acceptance: "The notes file lists every change".into(),+ state: "ready".into(),+ priority: 1,+ owner_kwant_id: Some(owner.id.clone()),+ budget_tokens: 0,+ max_attempts: 3,+ source_kind: "person".into(),+ created_by: "person".into(),+ ..Default::default()+ };+ e.state.db.create_task(&SpaceId::default_space(), &t).await.unwrap()+}++/// A Performance Market row: `bot` ended task `task_id` of `class` with `result`, `days_ago`.+async fn observe(e: &Env, bot: &Kwant, task_id: &str, class: &str, result: &'static str, days_ago: i64) {+ let o = NewObservation {+ task_id: task_id.into(),+ space_id: bot.space_id.clone(),+ mission_id: None,+ task_class: class.into(),+ kwant_id: bot.id.clone(),+ engine: "cli".into(),+ model: "m".into(),+ started_at: None,+ finished_at: chrono::Utc::now() - chrono::Duration::days(days_ago),+ latency_ms: 0,+ runs: 1,+ fresh_tokens: 0,+ cost_usd: None,+ result,+ approvals: 0,+ check_approvals: 0,+ unblocks: 0,+ retries: 0,+ autofix_attempts: 0,+ };+ e.state.db.store_observation(&o, "live").await.unwrap();+}++/// `n` verified tasks of `class` by `bot`, as real tasks; returns their ids.+async fn verified(e: &Env, bot: &Kwant, class: &str, n: usize) -> Vec<String> {+ let mut ids = Vec::new();+ for i in 0..n {+ let t = task(e, bot, &format!("{class} {i}")).await;+ observe(e, bot, &t.id, class, "verified", 1).await;+ ids.push(t.id);+ }+ ids+}++async fn token(e: &Env, bot: &Kwant) -> String {+ let turn_id = format!("t-{}", uuid::Uuid::new_v4());+ let origin = TurnOrigin { channel_id: Some(e.general.clone()), ..Default::default() };+ let scope = SelfScope {+ kwant_id: bot.id.clone(),+ kwant_name: bot.name.clone(),+ origin: Some(origin),+ turn_id: Some(turn_id.clone()),+ ..Default::default()+ };+ mcp_runtime::prepare_turn_with_self(&e.state, bot, Some(turn_id), None, Some(scope)).await.unwrap().1+}++async fn rpc(e: &Env, bot: &Kwant, method: &str, params: Value) -> Value {+ let t = token(e, bot).await;+ let body = json!({"jsonrpc": "2.0", "id": 1, "method": method, "params": params});+ let (status, v) = call(&e.app, "POST", "/api/mcp/self", Some(&t), Some(body)).await;+ assert_eq!(status, StatusCode::OK, "{v}");+ v+}++async fn listed(e: &Env, bot: &Kwant) -> Vec<String> {+ let v = rpc(e, bot, "tools/list", json!({})).await;+ v["result"]["tools"].as_array().unwrap().iter().map(|t| t["name"].as_str().unwrap().to_string()).collect()+}++async fn tool(e: &Env, bot: &Kwant, name: &str, args: Value) -> (Value, bool, String) {+ let v = rpc(e, bot, "tools/call", json!({"name": name, "arguments": args})).await;+ let text = v["result"]["content"][0]["text"].as_str().unwrap_or("").to_string();+ (serde_json::from_str(&text).unwrap_or(Value::Null), v["result"]["isError"].as_bool().unwrap_or(false), text)+}++fn cluster(bot: &Kwant, class: &str) -> kwnt::db::foundry::Cluster {+ kwnt::db::foundry::Cluster { space_id: bot.space_id.clone(), kwant_id: bot.id.clone(), task_class: class.into(), verified: 3, total: 3 }+}++/// A draft run of `bot` for `class` waiting for `skill_draft`, opened without running its turn.+async fn drafting(e: &Env, bot: &Kwant, class: &str) -> kwnt::db::foundry::FoundryRun {+ let run = foundry::start_draft(&e.state, &cluster(bot, class), "test").await.unwrap();+ assert!(e.state.db.move_foundry_run(&run.id, "queued", "drafting", None).await.unwrap());+ run+}++fn draft_args(run_id: &str, examples: &[String]) -> Value {+ json!({+ "run_id": run_id,+ "name": "release-notes",+ "description": "Write release notes from the merged changes",+ "body": "1. List merged changes.\n2. Write NOTES.md.\n3. Check every change is listed.",+ "inputs": [{"name": "range", "description": "The commits to cover", "example": "v1.2..main"}],+ "checks": [{"kind": "file_exists", "spec": {"path": "NOTES.md"}}],+ "examples": examples,+ "tools": ["Read", "Write", "task_list"],+ })+}++/// A Foundry draft stored straight in the database (no turn), as version `n` of `bot`'s class.+async fn stored_draft(e: &Env, bot: &Kwant, class: &str, body: &str, examples: &[String]) -> (kwnt::db::skills::Skill, kwnt::db::foundry::SkillMeta) {+ let run = e.state.db.create_foundry_run("draft", &bot.space_id, &bot.id, class, None).await.unwrap();+ let draft = NewDraft {+ kwant_id: bot.id.clone(),+ task_class: class.into(),+ text: clean_skill_text("release-notes", "Write release notes", body).unwrap(),+ inputs: json!([]),+ checks: json!([{"kind": "file_exists", "spec": {"path": "NOTES.md"}}, {"kind": "http", "spec": {"url": "https://example.com/health"}}]),+ examples: examples.to_vec(),+ tools: vec!["Read".into()],+ };+ e.state.db.insert_foundry_draft(&bot.space_id, &draft, &run.id).await.unwrap()+}++#[tokio::test]+async fn the_foundry_is_off_by_default() {+ let e = setup().await;+ let s = person(&e, "GET", "/api/settings", None).await;+ assert_eq!(s["skill_foundry"], "off", "{s}");+ assert_eq!(+ (&s["skill_foundry_model"], &s["skill_foundry_daily_drafts"], &s["skill_foundry_replays"], &s["skill_foundry_replay_tokens"]),+ (&json!("balanced"), &json!(2), &json!(3), &json!(60_000)),+ "{s}"+ );+ let owner = bot(&e, "Owner").await;+ verified(&e, &owner, "release", 3).await;++ // Clusters are shown, but no draft is started, by the tick or the person+ let o = person(&e, "GET", "/api/skills/foundry", None).await;+ assert_eq!((o["enabled"].as_bool(), o["clusters"].as_array().unwrap().len()), (Some(false), 1), "{o}");+ assert!(foundry::tick(&e.state).await.is_empty());+ let uri = format!("/api/skills/foundry/{}/draft", o["clusters"][0]["id"].as_str().unwrap());+ let (status, v) = call(&e.app, "POST", &uri, None, None).await;+ assert_eq!(status, StatusCode::CONFLICT, "{v}");+ assert!(foundry::start_draft(&e.state, &cluster(&owner, "release"), "test").await.unwrap_err().contains("off"));+ assert!(e.state.db.foundry_runs_of_space(&owner.space_id, 10).await.unwrap().is_empty());+ // The bot is never offered skill_draft, and calling it is refused+ assert!(!listed(&e, &owner).await.contains(&foundry::TOOL.to_string()));+ let (_, err, text) = tool(&e, &owner, foundry::TOOL, json!({"run_id": "x"})).await;+ assert!(err && text.contains("off"), "{text}");+}++#[tokio::test]+async fn settings_are_validated() {+ let e = setup().await;+ for bad in [+ json!({"skill_foundry": "auto"}),+ json!({"skill_foundry_model": "opus"}),+ json!({"skill_foundry_daily_drafts": 0}),+ json!({"skill_foundry_replays": 6}),+ json!({"skill_foundry_replay_tokens": 100}),+ ] {+ let (status, v) = call(&e.app, "POST", "/api/settings", None, Some(bad.clone())).await;+ assert_eq!(status, StatusCode::BAD_REQUEST, "{bad} {v}");+ }+ person(&e, "POST", "/api/settings", Some(json!({"skill_foundry": "on", "skill_foundry_model": "fast", "skill_foundry_replays": 0}))).await;+ let s = person(&e, "GET", "/api/settings", None).await;+ assert_eq!((&s["skill_foundry"], &s["skill_foundry_model"], &s["skill_foundry_replays"]), (&json!("on"), &json!("fast"), &json!(0)), "{s}");+}++#[tokio::test]+async fn the_miner_needs_three_verified_tasks_of_one_class_at_seventy_percent_in_sixty_days() {+ let e = setup().await;+ let (a, b, c, d, f) = (bot(&e, "A").await, bot(&e, "B").await, bot(&e, "C").await, bot(&e, "D").await, bot(&e, "F").await);+ // A: 3 verified, 1 failed (75%): a cluster+ verified(&e, &a, "release", 3).await;+ observe(&e, &a, "a-failed", "release", "failed", 2).await;+ // B: only 2 verified+ verified(&e, &b, "release", 2).await;+ // C: 3 verified of 5 (60%)+ verified(&e, &c, "release", 3).await;+ observe(&e, &c, "c-f1", "release", "failed", 1).await;+ observe(&e, &c, "c-f2", "release", "failed", 1).await;+ // D: `general` is never a cluster+ verified(&e, &d, "general", 5).await;+ // F: 3 verified, but one of them 61 days ago+ verified(&e, &f, "release", 2).await;+ observe(&e, &f, "f-old", "release", "verified", 61).await;++ let clusters = e.state.db.foundry_clusters(None, chrono::Utc::now()).await.unwrap();+ let ids: Vec<(String, String)> = clusters.iter().map(|c| (c.kwant_id.clone(), c.task_class.clone())).collect();+ assert_eq!(ids, vec![(a.id.clone(), "release".to_string())], "{clusters:?}");+ assert_eq!((clusters[0].verified, clusters[0].total), (3, 4));+ // Another space sees none of them+ assert!(e.state.db.foundry_clusters(Some("other-space"), chrono::Utc::now()).await.unwrap().is_empty());+}++#[tokio::test]+async fn drafts_are_capped_and_a_class_cools_off() {+ let e = setup().await;+ foundry_on(&e, 1).await;+ let (a, b) = (bot(&e, "A").await, bot(&e, "B").await);+ let now = chrono::Utc::now();+ assert_eq!(e.state.db.foundry_block(&a.id, "release", now).await.unwrap(), None);++ let run = foundry::start_draft(&e.state, &cluster(&a, "release"), "test").await.unwrap();+ assert_eq!((run.kind.as_str(), run.status.as_str()), ("draft", "queued"));+ // A second live draft for the class is refused; the daily cap stops other classes too+ assert!(foundry::start_draft(&e.state, &cluster(&a, "release"), "test").await.is_err());+ assert!(foundry::start_draft(&e.state, &cluster(&b, "release"), "test").await.unwrap_err().contains("daily"));+ // The tick offers nothing more today, and the class cools off for a week+ assert!(foundry::tick(&e.state).await.is_empty());+ assert_eq!(e.state.db.foundry_block(&a.id, "release", now).await.unwrap(), Some("cooling_off"));+ assert_eq!(e.state.db.foundry_block(&a.id, "release", now + chrono::Duration::days(8)).await.unwrap(), None);+}++#[tokio::test]+async fn a_rejected_draft_is_not_offered_again_for_thirty_days() {+ let e = setup().await;+ let a = bot(&e, "A").await;+ let ex = verified(&e, &a, "release", 3).await;+ let (s, _) = stored_draft(&e, &a, "release", "Steps.", &ex[..2]).await;+ let now = chrono::Utc::now();+ assert_eq!(e.state.db.foundry_block(&a.id, "release", now).await.unwrap(), Some("has_draft"));+ person(&e, "POST", &format!("/api/skills/{}/reject", s.id), Some(json!({}))).await;+ // The draft run itself was today: past its week, the rejection still blocks+ let later = now + chrono::Duration::days(10);+ assert_eq!(e.state.db.foundry_block(&a.id, "release", later).await.unwrap(), Some("rejected"));+ assert_eq!(e.state.db.foundry_block(&a.id, "release", now + chrono::Duration::days(31)).await.unwrap(), None);+}++#[tokio::test]+async fn skill_draft_stores_a_pending_draft_and_refuses_bad_parts() {+ let e = setup().await;+ foundry_on(&e, 5).await;+ let (owner, other) = (bot(&e, "Owner").await, bot(&e, "Other").await);+ let ex = verified(&e, &owner, "release", 3).await;+ let foreign = verified(&e, &owner, "invoices", 1).await;+ let others = verified(&e, &other, "release", 1).await;+ assert!(!listed(&e, &owner).await.contains(&foundry::TOOL.to_string()));+ let run = drafting(&e, &owner, "release").await;+ // Offered only to the bot with the open draft run+ assert!(listed(&e, &owner).await.contains(&foundry::TOOL.to_string()));+ assert!(!listed(&e, &other).await.contains(&foundry::TOOL.to_string()));++ let refused = |args: Value, why: &'static str| {+ let (e, owner) = (&e, &owner);+ async move {+ let (_, err, text) = tool(e, owner, foundry::TOOL, args).await;+ assert!(err && text.contains(why), "{why}: {text}");+ }+ };+ let good = draft_args(&run.id, &ex[..2]);+ // Examples must be the cluster's own verified tasks, 2–5, no repeats+ let mut a = good.clone();+ a["examples"] = json!([ex[0], foreign[0]]);+ refused(a, "isn't one of your verified").await;+ let mut a = good.clone();+ a["examples"] = json!([ex[0], others[0]]);+ refused(a, "isn't one of your verified").await;+ let mut a = good.clone();+ a["examples"] = json!([ex[0]]);+ refused(a, "2–5").await;+ let mut a = good.clone();+ a["examples"] = json!([ex[0], ex[0]]);+ refused(a, "twice").await;+ // Tools must be ones the bot holds now+ let mut a = good.clone();+ a["tools"] = json!(["Read", "mcp__github__create_issue"]);+ refused(a, "don't have a tool called mcp__github__create_issue").await;+ let mut a = good.clone();+ a["tools"] = json!(["TotallyNew"]);+ refused(a, "don't have a tool called TotallyNew").await;+ // Checks pass the task-check validator+ let mut a = good.clone();+ a["checks"] = json!([{"kind": "person", "spec": {}}]);+ refused(a, "kind must be one of").await;+ let mut a = good.clone();+ a["checks"] = json!([{"kind": "http", "spec": {"url": "file:///etc/passwd"}}]);+ refused(a, "check 1").await;+ // Someone else's run+ let mut a = good.clone();+ a["run_id"] = json!("nope");+ refused(a, "No such").await;+ let (_, err, _) = tool(&e, &other, foundry::TOOL, good.clone()).await;+ assert!(err);++ let (v, err, text) = tool(&e, &owner, foundry::TOOL, good.clone()).await;+ assert!(!err, "{text}");+ let skill_id = v["skill_id"].as_str().unwrap().to_string();+ let s = e.state.db.get_skill(&skill_id).await.unwrap().unwrap();+ assert_eq!((s.status.as_str(), s.name.as_str(), s.kwant_id.as_deref()), ("pending", "release-notes", Some(owner.id.as_str())));+ let m = e.state.db.skill_meta(&skill_id).await.unwrap().unwrap();+ assert_eq!((m.version, m.lineage_id.as_str(), m.task_class.as_str()), (1, skill_id.as_str(), "release"));+ assert_eq!(serde_json::from_str::<Value>(&m.tools).unwrap(), json!(["Read", "Write", "task_list"]));+ assert_eq!(m.examples(), ex[..2].to_vec());+ // The run holds the draft; a second call is refused+ assert_eq!(e.state.db.get_foundry_run(&run.id).await.unwrap().unwrap().skill_id.as_deref(), Some(skill_id.as_str()));+ refused(good, "isn't waiting").await;+ // Each example's history links to the draft; the draft has its own event+ let kinds: Vec<String> = e.state.db.task_events(&ex[0], 50).await.unwrap().into_iter().map(|ev| ev.kind).collect();+ assert!(kinds.contains(&"skill_drafted_from".to_string()), "{kinds:?}");+ let events = e.state.db.skill_events(std::slice::from_ref(&skill_id)).await.unwrap();+ assert_eq!(events.iter().map(|ev| ev.kind.as_str()).collect::<Vec<_>>(), ["skill_drafted"]);+ // And the card shows it+ let o = person(&e, "GET", "/api/skills/foundry", None).await;+ assert_eq!(o["skills"][0]["foundry"]["tools"], json!(["Read", "Write", "task_list"]), "{o}");+ assert_eq!(o["clusters"][0]["block"], "has_draft", "{o}");+}++#[tokio::test]+async fn a_foundry_skill_grants_no_tools_or_approvals() {+ let e = setup().await;+ foundry_on(&e, 5).await;+ let owner = bot(&e, "Owner").await;+ let ex = verified(&e, &owner, "release", 3).await;+ let before_tools = listed(&e, &owner).await;+ let before_bot = serde_json::to_value(e.state.db.get_kwant(&owner.id).await.unwrap().unwrap()).unwrap();+ let before_servers = e.state.db.list_active_mcp_servers_for_kwant(&owner.id).await.unwrap().len();++ let run = drafting(&e, &owner, "release").await;+ let mut args = draft_args(&run.id, &ex[..2]);+ args["tools"] = json!(["Read", "Write", "Bash", "WebFetch"]);+ let (v, err, text) = tool(&e, &owner, foundry::TOOL, args).await;+ assert!(!err, "{text}");+ let id = v["skill_id"].as_str().unwrap().to_string();+ let _ = e.state.db.move_foundry_run(&run.id, "drafting", "done", None).await;+ person(&e, "POST", &format!("/api/skills/{id}/approve"), Some(json!({}))).await;+ assert_eq!(e.state.db.get_skill(&id).await.unwrap().unwrap().status, "enabled");++ assert_eq!(listed(&e, &owner).await, before_tools);+ let after_bot = serde_json::to_value(e.state.db.get_kwant(&owner.id).await.unwrap().unwrap()).unwrap();+ assert_eq!(after_bot, before_bot);+ assert_eq!(e.state.db.list_active_mcp_servers_for_kwant(&owner.id).await.unwrap().len(), before_servers);+}++#[tokio::test]+async fn replay_mode_refuses_every_outward_call_and_records_it() {+ let log: mcp_runtime::RehearseLog = Default::default();+ let approver = mcp_runtime::RehearseApprover { log: log.clone() };+ let req = |server: &str, tool: &str, args: Value, builtin: Option<BuiltinCall>| ToolApprovalRequest {+ kwant_id: "k".into(),+ kwant_name: "K".into(),+ turn_id: "t".into(),+ tool_name: if builtin.is_some() { tool.to_string() } else { format!("mcp__{server}__{tool}") },+ server: server.into(),+ tool: tool.into(),+ arguments: args,+ builtin,+ smart: None,+ payment: None,+ };+ let inside = || Some(BuiltinCall { cwd: Some("/scratch".into()), outside_folder: false });+ let outside = || Some(BuiltinCall { cwd: Some("/scratch".into()), outside_folder: true });++ // Reading kwant's own records is allowed+ assert!(matches!(approver.decide(req(SELF_SERVER_NAME, "task_list", json!({}), None)).await, ApprovalOutcome::Allowed));+ // Everything else that reaches the approver is refused as rehearsed, never asked+ for r in [+ req("", "Bash", json!({"command": "git push"}), inside()),+ req("", "Write", json!({"file_path": "/home/x/.ssh/config", "content": "x"}), outside()),+ req("gmail", "send_email", json!({"to": "[email protected]"}), None),+ req(SELF_SERVER_NAME, "task_update", json!({"task_id": "t1", "status": "done"}), None),+ req(SELF_SERVER_NAME, "browser_act", json!({"action": "click"}), None),+ ] {+ let name = r.tool_name.clone();+ let outcome = approver.decide(r).await;+ assert!(matches!(outcome, ApprovalOutcome::Rehearsed), "{name}: {outcome:?}");+ assert!(!outcome.allowed());+ }+ let lines = log.lock().unwrap().clone();+ assert_eq!(lines.len(), 5, "{lines:?}");+ assert_eq!(lines[0]["tool"], "Bash");+ assert_eq!(lines[1]["outside_folder"], true);+ assert_eq!(lines[2]["tool"], "mcp__gmail__send_email");+ // Subagents are gated even where the hook would allow them+ assert!(approver.tier_gate(&req("", "Task", json!({}), inside())).await.is_some());+ assert!(approver.tier_gate(&req("", "Read", json!({}), inside())).await.is_none());+ // The refusal tells the bot it was a dry run+ assert!(ApprovalOutcome::Rehearsed.refusal_text().contains("dry run"));+}++#[tokio::test]+async fn scratch_checks_run_file_checks_and_mark_network_ones_not_replayable() {+ let e = setup().await;+ let lead = bot(&e, "Lead").await;+ let m = person(+ &e,+ "POST",+ "/api/missions",+ Some(json!({"title": "Ship it", "goal": "a release", "lead_kwant_id": lead.id, "budget_tokens": 900_000,+ "channel_id": e.general, "tasks": [{"title": "Notes", "owner": lead.id}]})),+ )+ .await;+ let mid = m["id"].as_str().or(m["mission"]["id"].as_str()).unwrap().to_string();+ let detail = person(&e, "GET", &format!("/api/missions/{mid}"), None).await;+ let tid = detail["tasks"][0]["id"].as_str().unwrap().to_string();+ let folder = std::path::PathBuf::from(e.state.db.get_mission(&mid).await.unwrap().unwrap().workspace_path);+ std::fs::create_dir_all(&folder).unwrap();+ std::fs::write(folder.join("NOTES.md"), "v1.2: export fixed").unwrap();+ person(&e, "POST", &format!("/api/tasks/{tid}/checkpoints"), Some(json!({}))).await;+ // The live folder moves on; the replay sees the snapshot+ std::fs::write(folder.join("NOTES.md"), "changed later").unwrap();++ let scratch = foundry::scratch_dir(&e.state, "run1", 0);+ let n = kwnt::server::missions::checkpoints::materialize_first(&e.state, &tid, &scratch).await.unwrap();+ assert_eq!(n, 1);+ assert_eq!(std::fs::read_to_string(scratch.join("NOTES.md")).unwrap(), "v1.2: export fixed");+ use std::os::unix::fs::PermissionsExt;+ assert_eq!(std::fs::metadata(&scratch).unwrap().permissions().mode() & 0o777, 0o700);++ let checks = vec![+ json!({"kind": "file_exists", "spec": {"path": "NOTES.md"}}),+ json!({"kind": "file_contains", "spec": {"path": "NOTES.md", "text": "export fixed"}}),+ json!({"kind": "http", "spec": {"url": "https://example.com/health"}}),+ json!({"kind": "command", "spec": {"command": "curl https://example.com"}}),+ ];+ let out = foundry::scratch_checks(&checks, &scratch).await;+ let statuses: Vec<&str> = out.iter().map(|c| c["status"].as_str().unwrap()).collect();+ assert_eq!(statuses, ["passed", "passed", "not_replayable", "not_replayable"], "{out:?}");+ assert_eq!(foundry::example_verdict(&out), "passed");+ let missing = foundry::scratch_checks(&[json!({"kind": "file_exists", "spec": {"path": "OTHER.md"}})], &scratch).await;+ assert_eq!(foundry::example_verdict(&missing), "failed");+ // A task with no checkpoint replays on an empty folder+ assert_eq!(kwnt::server::missions::checkpoints::materialize_first(&e.state, "no-such-task", &scratch.join("x")).await.unwrap(), 0);+}++#[tokio::test]+async fn a_replay_off_claude_is_reported_as_an_error_and_leaves_no_scratch_copy() {+ let e = setup().await;+ foundry_on(&e, 5).await;+ let owner = bot(&e, "Owner").await;+ let ex = verified(&e, &owner, "release", 3).await;+ let (s, _) = stored_draft(&e, &owner, "release", "Steps.", &ex[..2]).await;++ let run = foundry::begin_replay(&e.state, &s.id, "test").await.unwrap();+ // A second replay of the same draft waits for the first+ assert!(foundry::begin_replay(&e.state, &s.id, "test").await.is_err());+ let mut done = None;+ for _ in 0..100 {+ tokio::time::sleep(Duration::from_millis(100)).await;+ let r = e.state.db.get_foundry_run(&run.id).await.unwrap().unwrap();+ if !r.live() {+ done = Some(r);+ break;+ }+ }+ let r = done.expect("the replay never ended");+ assert_eq!((r.status.as_str(), r.reason.as_deref()), ("failed", Some("no example could be replayed")), "{r:?}");+ let report: Value = serde_json::from_str(&e.state.db.skill_meta(&s.id).await.unwrap().unwrap().replay.unwrap()).unwrap();+ assert_eq!(report["examples"].as_array().unwrap().len(), 2, "{report}");+ assert_eq!(report["errors"], 2, "{report}");+ // Refused before any model ran: "only on Claude" here, or "no account" on a host without one+ let ex0 = &report["examples"][0];+ assert_eq!((ex0["verdict"].as_str(), ex0["tokens"].as_u64()), (Some("error"), Some(0)), "{report}");+ assert!(!ex0["error"].as_str().unwrap_or("").is_empty(), "{report}");+ // The draft is untouched, and its scratch copies are gone+ assert_eq!(e.state.db.get_skill(&s.id).await.unwrap().unwrap().status, "pending");+ assert!(!e.state.config.data_dir.join("foundry").join(&run.id).exists());+ let kinds: Vec<String> = e.state.db.skill_events(std::slice::from_ref(&s.id)).await.unwrap().into_iter().map(|ev| ev.kind).collect();+ assert_eq!(kinds, ["skill_drafted", "skill_replayed"]);+ // Only a draft waiting for review is replayed+ person(&e, "POST", &format!("/api/skills/{}/approve", s.id), Some(json!({}))).await;+ let (status, v) = call(&e.app, "POST", &format!("/api/skills/{}/replay", s.id), None, None).await;+ assert_eq!(status, StatusCode::CONFLICT, "{v}");+}++#[tokio::test]+async fn rollback_moves_one_lineage_back_in_one_step() {+ let e = setup().await;+ let (a, b) = (bot(&e, "A").await, bot(&e, "B").await);+ let ex = verified(&e, &a, "release", 3).await;+ let (v1, m1) = stored_draft(&e, &a, "release", "Version one.", &ex[..2]).await;+ person(&e, "POST", &format!("/api/skills/{}/approve", v1.id), Some(json!({}))).await;+ let (v2, m2) = stored_draft(&e, &a, "release", "Version two.", &ex[..2]).await;+ assert_eq!((m2.version, m2.lineage_id.as_str(), v2.replaces_id.as_deref()), (2, m1.lineage_id.as_str(), Some(v1.id.as_str())));+ person(&e, "POST", &format!("/api/skills/{}/approve", v2.id), Some(json!({}))).await;+ assert_eq!(e.state.db.get_skill(&v1.id).await.unwrap().unwrap().status, "superseded");+ // Another bot's live skill of the same class is another lineage+ let exb = verified(&e, &b, "release", 3).await;+ let (other, _) = stored_draft(&e, &b, "release", "B's way.", &exb[..2]).await;+ person(&e, "POST", &format!("/api/skills/{}/approve", other.id), Some(json!({}))).await;++ // A bot can't roll back+ let t = token(&e, &a).await;+ let (status, _) = call(&e.app, "POST", &format!("/api/skills/{}/rollback", v1.id), Some(&t), None).await;+ assert_eq!(status, StatusCode::FORBIDDEN);+ // The live version can't be "rolled back" to+ let (status, v) = call(&e.app, "POST", &format!("/api/skills/{}/rollback", v2.id), None, None).await;+ assert_eq!(status, StatusCode::CONFLICT, "{v}");++ let r = person(&e, "POST", &format!("/api/skills/{}/rollback", v1.id), None).await;+ assert_eq!(r["status"], "enabled", "{r}");+ let status = |id: String| {+ let e = &e;+ async move { e.state.db.get_skill(&id).await.unwrap().unwrap().status }+ };+ assert_eq!(status(v2.id.clone()).await, "superseded");+ assert_eq!(status(other.id.clone()).await, "enabled");+ let d = person(&e, "GET", &format!("/api/skills/{}/foundry", v1.id), None).await;+ assert_eq!(d["versions"].as_array().unwrap().len(), 2, "{d}");+ assert!(d["events"].as_array().unwrap().iter().any(|ev| ev["kind"] == "skill_rolled_back"), "{d}");+ // And forward again+ person(&e, "POST", &format!("/api/skills/{}/rollback", v2.id), None).await;+ assert_eq!((status(v1.id.clone()).await, status(v2.id.clone()).await), ("superseded".into(), "enabled".into()));+ // A skill without Foundry history isn't the Foundry's to roll back+ let plain = person(&e, "POST", "/api/skills", Some(json!({"name": "plain", "description": "d", "body": "b"}))).await;+ let (status, _) = call(&e.app, "POST", &format!("/api/skills/{}/rollback", plain["id"].as_str().unwrap()), None, None).await;+ assert_eq!(status, StatusCode::NOT_FOUND);+}++#[tokio::test]+async fn reads_of_the_review_queue_are_person_only() {+ let e = setup().await;+ let a = bot(&e, "A").await;+ let t = token(&e, &a).await;+ for (method, uri) in [("GET", "/api/skills/foundry"), ("POST", "/api/skills/foundry/x~y/draft"), ("GET", "/api/skills/s1/foundry"), ("POST", "/api/skills/s1/replay")] {+ let (status, _) = call(&e.app, method, uri, Some(&t), None).await;+ assert_eq!(status, StatusCode::FORBIDDEN, "{method} {uri}");+ }+}++#[tokio::test]+async fn queued_runs_fail_at_startup_when_the_foundry_was_turned_off() {+ let e = setup().await;+ let a = bot(&e, "A").await;+ let queued = e.state.db.create_foundry_run("draft", &a.space_id, &a.id, "release", None).await.unwrap();+ foundry::resume_after_restart(&e.state).await;+ let r = e.state.db.get_foundry_run(&queued.id).await.unwrap().unwrap();+ assert_eq!((r.status.as_str(), r.reason.as_deref()), ("failed", Some("the Skill Foundry was turned off")));+ // A run whose driver stops ends failed+ let live = e.state.db.create_foundry_run("draft", &a.space_id, &a.id, "invoices", None).await.unwrap();+ assert!(foundry::end_if_live(&e.state, &live.id, "stopped").await);+ assert!(!foundry::end_if_live(&e.state, &live.id, "stopped").await);+}