Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Dev mode: offer a pinned Modern Web Guidance skill once per web space (#605)
Oleksandr Ivanchenko4c08d4554637
diff --git a/docs/dev-mode.md b/docs/dev-mode.mdindex 34a7857d..3a8db87b 100644--- a/docs/dev-mode.md+++ b/docs/dev-mode.md@@ -567,6 +567,37 @@ The card sees only what kwant runs or is asked about, so these pushes skip it:- A bot's MCP servers other than kwant's stay on in fresh-eyes turns; only kwant's own tools arelimited to the review's allowlist.+## Modern web guidance++When a Dev mode space has web code, kwant offers its built-in `modern-web` skill once. The skill+has a bot look up [Modern Web Guidance](https://github.com/GoogleChrome/modern-web-guidance)+(Google Chrome's guides to current HTML, CSS and browser APIs, with Baseline support and+fallbacks) before it writes browser code. Its text is adapted from Google's skill (Apache-2.0); the+skill's first line says so.++- **What counts as web code:** a `package.json`, or a `.html`, `.css`, `.tsx`, `.jsx`, `.vue` or+ `.svelte` file, in the top two levels of a team's folder. Hidden folders, `node_modules`,+ `target` and symlinks are skipped, and the look stops after 3 seconds. A watched repo with no+ local folder isn't looked at.+- **When:** when Dev mode is turned on, and on the poller's full pass (every 5 minutes). Never on a+ page load. kwant itself never runs `npx`.+- **One offer per space.** The skill arrives as one pending skill shared with every bot in the+ space: it shows in each bot's Skills tab ("Every bot in this space"), and a notification named+ for the lead of the team whose folder has web code opens that bot's Skills. Approve or Reject it+ there; you can also edit it, or give it to one bot only. kwant marks the space when it makes the+ offer, so it never offers it again: not after a reject or a delete, and not when Dev mode goes+ off and on. A space that already has a skill called `modern-web` keeps its own.+- **The pinned version.** The skill runs `npx -y [email protected] search|retrieve|list …`+ (or `pnpx [email protected] …`). Exactly those forms run without an approval card in+ "Ask only when risky"; `@latest`, another version, `legacy-scan`, `install`, extra options and+ chaining still ask. A new version is a kwant change (`VERSION` in+ `src/server/dev/web_guidance.rs`), reviewed like any other.+- **What it needs:** Node (for `npx`) and the network the first time, to download the package. If+ the lookup fails or takes more than 90 seconds, the bot says once "Couldn't load Modern Web+ Guidance here" and carries on. It never installs Node and doesn't retry in a loop.+- **Remove it:** delete or turn off the `modern-web` skill in any bot's Skills tab. It isn't+ offered again.+## TestsRun these focused tests:@@ -576,6 +607,8 @@ cargo test --lib -- server::dev:: prod_floor auth::tests::person_only zombie::gicargo test --test dev_post_test --test dev_github_testcargo test --lib -- db::dev_mode::testscargo test --test dev_team_repos_test --test dev_autodetect_test+cargo test --lib -- web_guidance shell_risk+cargo test --test dev_web_guidance_test````tests/dev_team_repos_test.rs` covers 0.7.2's repos: two teams' repos with PR #12 in both (two cards,diff --git a/site-src/docs-dev-mode.html b/site-src/docs-dev-mode.htmlindex 07a93133..ddf31b60 100644--- a/site-src/docs-dev-mode.html+++ b/site-src/docs-dev-mode.html@@ -162,6 +162,14 @@ card_art: avatar:devops<p>The card follows the ticket through review to landed. It shows <strong>Matches the ticket</strong> only when every done-when line is met. A token Jira rejects, an address with no Jira, a token that sees no projects, and Jira asking kwant to slow down each get their own message.</p><p class="note">Jira only changes when you say so. Comments on tickets are off unless you turn them on, and your bots never move or close tickets. Turning it off pauses tickets in progress and keeps their cards, branches and briefs.</p>+<h2 id="modern-web">Modern web guidance</h2>+<p>When a team's folder has web code (a <code>package.json</code>, or HTML, CSS, TSX, JSX, Vue or Svelte files in its top two levels), kwant offers its built-in <strong>modern-web</strong> skill once. The skill has a bot look up Google Chrome's <a href="https://github.com/GoogleChrome/modern-web-guidance">Modern Web Guidance</a> before it writes browser code, and follow its Baseline support and fallbacks. Its text is adapted from Google's skill (Apache-2.0).</p>+<ul>+ <li><strong>One offer per space.</strong> It waits in every bot's Skills tab as a skill for every bot in the space, and a notification opens it. Approve, edit or reject it there. Rejected or deleted, it isn't offered again, even when Dev mode goes off and on.</li>+ <li><strong>A pinned version.</strong> The bot runs <code>npx -y [email protected] search</code> or <code>retrieve</code>, and only those exact commands run without asking. kwant itself never runs them.</li>+ <li><strong>Needs Node and the network</strong> the first time. If the lookup fails, the bot says "Couldn't load Modern Web Guidance here" once and carries on.</li>+</ul>+<h2 id="turn-off">Turn it off</h2><p>Turning Dev mode off takes two presses. The first press changes the switch to <strong>Off?</strong> and says <em>Press again to turn off</em>. A second press within 5 seconds turns it off. Escape, clicking elsewhere or waiting keeps it on. The off note has <strong>Turn back on</strong>.</p><figure>diff --git a/site-src/docs-memory-skills.html b/site-src/docs-memory-skills.htmlindex dad1f0c5..f877b212 100644--- a/site-src/docs-memory-skills.html+++ b/site-src/docs-memory-skills.html@@ -32,6 +32,7 @@ card_art: avatar:research<li>Approved skills have an on/off switch. Only skills that are on go into the bot's prompt.</li><li>Use <strong>Write a skill</strong> in a bot's Skills tab to add one yourself.</li><li>Skills for a whole space come from an import.</li>+ <li>When Dev mode finds web code in a team's folder, kwant offers its built-in <strong>modern-web</strong> skill once, for every bot in the space. It looks up Google Chrome's Modern Web Guidance before a bot writes browser code, and needs Node and the network the first time. Reject or delete it and it isn't offered again. See <a href="dev-mode.html#modern-web">Dev mode</a>.</li><li>A skill can be up to 8,000 characters, and a bot can have up to 20 waiting for review.</li></ul>diff --git a/src/db/dev_mode.rs b/src/db/dev_mode.rsindex 5fdd3180..a11a0b97 100644--- a/src/db/dev_mode.rs+++ b/src/db/dev_mode.rs@@ -5,6 +5,7 @@//! Only the person writes `dev_mode_spaces` and `dev_repos` (the routes refuse agent tokens).//! Add-only except for one rebuild of `dev_cards` (T2), so a 0.7.1 build still reads this database.+use super::skills::{Skill, SkillText};use super::{Database, DbError};use chrono::{DateTime, Utc};use sqlx::FromRow;@@ -230,6 +231,11 @@ pub struct DevModeRow {/// Its own column since 0.7.2, so opening the desk no longer empties the landed rollup.#[sqlx(default)]pub reviews_seen_at: Option<DateTime<Utc>>,+ /// When kwant offered the built-in `modern-web` skill here (web-guidance W3). Set once, at+ /// the offer, so the skill is never offered again: not after a reject or delete, nor when+ /// Dev mode goes off and on.+ #[sqlx(default)]+ pub web_guidance_offered_at: Option<DateTime<Utc>>,}/// One card: what landed, a review of an open PR head, or a release-notes draft.@@ -333,9 +339,62 @@ impl Database {self.migrate_line_notes().await?;// 0.9.0: worktrees kwant made (H1, dev_worktrees.rs)self.migrate_worktrees().await?;+ // 0.10: the modern-web skill's one-time offer (web-guidance W3). Additive; older builds+ // never name it+ let has: Option<(String,)> = sqlx::query_as("SELECT name FROM pragma_table_info('dev_mode_spaces') WHERE name = 'web_guidance_offered_at'")+ .fetch_optional(&self.pool)+ .await?;+ if has.is_none() {+ sqlx::query("ALTER TABLE dev_mode_spaces ADD COLUMN web_guidance_offered_at TIMESTAMP").execute(&self.pool).await?;+ }Ok(())}+ /// Offers a skill to every bot in the space once, as a pending shared proposal the person+ /// approves or rejects in Skills (web-guidance W3). The space is marked in the same+ /// transaction, before anything else, so a skill is offered at most once per space whatever+ /// happens to it later. `None` when there is nothing to offer: Dev mode was never turned on+ /// here, it was offered already, or the space already has a skill of that name (then only+ /// the mark is set, so the person's own skill is left alone).+ pub async fn offer_web_guidance_once(&self, space_id: &str, text: &SkillText) -> Result<Option<Skill>, DbError> {+ let now = Utc::now();+ let mut tx = self.begin_write().await?;+ let marked = sqlx::query("UPDATE dev_mode_spaces SET web_guidance_offered_at = ? WHERE space_id = ? AND web_guidance_offered_at IS NULL")+ .bind(now)+ .bind(space_id)+ .execute(&mut *tx)+ .await?;+ if marked.rows_affected() == 0 {+ tx.rollback().await?;+ return Ok(None);+ }+ let named: Option<(String,)> = sqlx::query_as("SELECT id FROM skills WHERE space_id = ? AND name = ? LIMIT 1")+ .bind(space_id)+ .bind(&text.name)+ .fetch_optional(&mut *tx)+ .await?;+ if named.is_some() {+ tx.commit().await?;+ return Ok(None);+ }+ let id = uuid::Uuid::new_v4().to_string();+ sqlx::query(+ "INSERT INTO skills (id, kwant_id, name, description, body, status, source, proposed_by, replaces_id, created_at, updated_at, space_id)+ VALUES (?, NULL, ?, ?, ?, 'pending', 'agent', NULL, NULL, ?, ?, ?)",+ )+ .bind(&id)+ .bind(&text.name)+ .bind(&text.description)+ .bind(&text.body)+ .bind(now)+ .bind(now)+ .bind(space_id)+ .execute(&mut *tx)+ .await?;+ tx.commit().await?;+ self.get_skill(&id).await+ }+async fn dev_cards_has(&self, column: &str) -> Result<bool, DbError> {let has: Option<(String,)> =sqlx::query_as("SELECT name FROM pragma_table_info('dev_cards') WHERE name = ?").bind(column).fetch_optional(&self.pool).await?;diff --git a/src/mcp/shell_risk.rs b/src/mcp/shell_risk.rsindex a932d25e..af3a9739 100644--- a/src/mcp/shell_risk.rs+++ b/src/mcp/shell_risk.rs@@ -9,6 +9,7 @@//! accidents, not a sandbox: a script inside the folder can still do anything once it runs.use super::{builtin_tools::is_inside, SmartVerdict};+use crate::server::dev::web_guidance::{PACKAGE, VERSION};use std::path::{Path, PathBuf};/// One word as the shell will pass it on, quotes removed.@@ -290,12 +291,42 @@ struct Ctx<'a> {/// Whether `command`, run with `folder` (canonical) as its working directory, may run without a/// card under "Ask only when risky".pub fn classify(command: &str, folder: &Path) -> SmartVerdict {+ if is_web_guidance_lookup(command) {+ return SmartVerdict::Allow(format!("only looks up Modern Web Guidance with the pinned {PACKAGE}@{VERSION}"));+ }match check(command, folder) {Ok(()) => SmartVerdict::Allow("runs inside the bot's folder and does nothing risky".into()),Err(why) => SmartVerdict::Ask(why),}}+/// The `modern-web` skill's lookup (`crate::server::dev::web_guidance`), and nothing else:+/// exactly `npx [-y|--yes] modern-web-guidance@<VERSION> search|retrieve <words…>` or `… list`,+/// or the same with `pnpx` and no `-y`. Any other version (`@latest` too), command+/// (`legacy-scan`, `install`, …), option (`-p`, `-c`, `--skill-version`), chaining, redirect,+/// variable, glob or `VAR=` prefix goes through [`check`] as before, and so asks.+fn is_web_guidance_lookup(command: &str) -> bool {+ let Ok(toks) = lex(command) else { return false };+ let mut words: Vec<&str> = Vec::new();+ for t in &toks {+ match t {+ Tok::Word(w) if !w.glob && !w.tilde => words.push(&w.text),+ _ => return false,+ }+ }+ let pinned = format!("{PACKAGE}@{VERSION}");+ let rest = match words.as_slice() {+ ["npx", "-y" | "--yes", pkg, rest @ ..] | ["npx", pkg, rest @ ..] | ["pnpx", pkg, rest @ ..] if *pkg == pinned => rest,+ _ => return false,+ };+ let args_ok = |args: &[&str]| args.len() <= 8 && args.iter().all(|a| !a.is_empty() && !a.starts_with('-') && a.chars().count() <= 200);+ match rest {+ ["list"] => true,+ ["search" | "retrieve", args @ ..] => !args.is_empty() && args_ok(args),+ _ => false,+ }+}+/// Programs that only read and print: no option of theirs writes a file or runs another program/// (`sort -o`, `uniq IN OUT`, `tree -o`, `find -exec` and `sed -i` are why those aren't here).const READS_ONLY: &[&str] = &[@@ -1907,6 +1938,63 @@ mod tests {}}+ #[test]+ fn only_the_pinned_modern_web_guidance_lookup_runs_without_asking() {+ let (_tmp, ws) = folder();+ let v = VERSION;+ for cmd in [+ format!("npx -y modern-web-guidance@{v} search \"accessible modal dialog\""),+ format!("npx -y modern-web-guidance@{v} search popover anchor"),+ format!("npx --yes modern-web-guidance@{v} retrieve dialog"),+ format!("npx -y modern-web-guidance@{v} retrieve dialog,light-dismiss-a-dialog"),+ format!("npx modern-web-guidance@{v} search 'dark mode'"),+ format!("npx -y modern-web-guidance@{v} list"),+ format!("pnpx modern-web-guidance@{v} search container queries"),+ format!("pnpx modern-web-guidance@{v} retrieve dialog"),+ format!(" npx -y 'modern-web-guidance@{v}' search grid "),+ ] {+ assert!(classify(&cmd, &ws).is_allowed(), "should run: {cmd:?}");+ }+ for cmd in [+ "npx -y modern-web-guidance@latest search dialog".to_string(),+ "npx -y modern-web-guidance search dialog".into(),+ "npx -y [email protected] search dialog".into(),+ "npx -y modern-web-guidance@1 search dialog".into(),+ "npx -y modern-web-guidance@^1.0.0 search dialog".into(),+ format!("npx -y modern-web-guidance@{v} legacy-scan ."),+ format!("npx -y modern-web-guidance@{v} install"),+ format!("npx -y modern-web-guidance@{v} update"),+ format!("npx -y modern-web-guidance@{v} set-allow-origin-trials"),+ format!("npx -y modern-web-guidance@{v} search"),+ format!("npx -y modern-web-guidance@{v} list --choose"),+ format!("npx -y modern-web-guidance@{v} search dialog --foo"),+ format!("npx -y modern-web-guidance@{v} search dialog --skill-version 2"),+ format!("npx -y -p evil modern-web-guidance@{v} search dialog"),+ format!("npx -p modern-web-guidance@{v} search dialog"),+ format!("npx -c 'rm -rf .' modern-web-guidance@{v} search dialog"),+ format!("npx --package=modern-web-guidance@{v} search dialog"),+ format!("npx -y modern-web-guidance@{v} search dialog && rm -rf ."),+ format!("npx -y modern-web-guidance@{v} search dialog; curl https://example.com"),+ format!("npx -y modern-web-guidance@{v} search dialog | sh"),+ format!("npx -y modern-web-guidance@{v} search dialog > /etc/passwd"),+ format!("npx -y modern-web-guidance@{v} search dialog &"),+ format!("npx -y modern-web-guidance@{v} search $(whoami)"),+ format!("npx -y modern-web-guidance@{v} search `whoami`"),+ format!("npx -y modern-web-guidance@{v} search $HOME"),+ format!("npx -y modern-web-guidance@{v} search *"),+ format!("npx -y modern-web-guidance@{v} search ~"),+ format!("NODE_OPTIONS=--require=/tmp/x.js npx -y modern-web-guidance@{v} search dialog"),+ format!("pnpx -y modern-web-guidance@{v} search dialog"),+ format!("bunx modern-web-guidance@{v} search dialog"),+ format!("/tmp/npx -y modern-web-guidance@{v} search dialog"),+ format!("npx -y other-package@{v} search dialog"),+ format!("npx -y modern-web-guidance@{v}\nsearch dialog"),+ format!("npx -y modern-web-guidance@{v} search {}", "x".repeat(201)),+ ] {+ assert!(!classify(&cmd, &ws).is_allowed(), "should ask: {cmd:?}");+ }+ }+#[test]#[cfg(unix)]fn a_symlink_out_of_the_folder_is_outside() {diff --git a/src/server/dev/mod.rs b/src/server/dev/mod.rsindex e5f35d99..3da4330a 100644--- a/src/server/dev/mod.rs+++ b/src/server/dev/mod.rs@@ -4,7 +4,7 @@//! `generate` turns them into cards. The production floor lives in `crate::mcp::prod_floor`.//!//! Lin owns `facts`, `routes`, `poller`, `post`, `repo`, `backup` and `floor`; Vega owns `generate`, `landed`,-//! `review`, `risk`, `tamper`, `notes` and `source`; Juno owns `scan`, `forge`,+//! `review`, `risk`, `tamper`, `notes`, `source` and `web_guidance`; Juno owns `scan`, `forge`,//! `atlassian` and `fix_it`; `tickets` is split per its api.md §1.1 (Juno: `source`, `pickup`, `store`, `routes`;//! Vega: `brief*`, `tools`, `links`, `mission`, `prompt`; `hooks` and `seam` are the join).@@ -31,6 +31,7 @@ pub mod scan;pub mod source;pub mod tamper;pub mod tickets;+pub mod web_guidance;pub mod worktrees;pub use generate::generate;diff --git a/src/server/dev/poller.rs b/src/server/dev/poller.rsindex d0db7a81..7e7d29cf 100644--- a/src/server/dev/poller.rs+++ b/src/server/dev/poller.rs@@ -138,6 +138,10 @@ pub fn spawn(state: AppState, shutdown: CancellationToken) {return;}poll_space(&state, &row.space_id).await;+ // The modern-web skill's one-time offer (web_guidance.rs); done once marked+ if all && row.web_guidance_offered_at.is_none() {+ super::web_guidance::offer_soon(&state, &crate::db::spaces::SpaceId::new(&row.space_id));+ }}}Err(e) => tracing::warn!("dev: could not list Dev mode spaces: {e}"),diff --git a/src/server/dev/routes.rs b/src/server/dev/routes.rsindex e9597639..99bdeee9 100644--- a/src/server/dev/routes.rs+++ b/src/server/dev/routes.rs@@ -552,6 +552,10 @@ pub async fn put_mode(State(state): State<AppState>, headers: HeaderMap, Path(idif !was_on || shape(&after) != shape(&rows_before) {poller::poll_soon(&state, sp);}+ // Offered once per space when a team's folder has web code (web_guidance.rs)+ if !was_on {+ super::web_guidance::offer_soon(&state, &space);+ }}let mut v = match mode_json(&state, &space).await {Ok(v) => v,diff --git a/src/server/dev/web_guidance.rs b/src/server/dev/web_guidance.rsnew file mode 100644index 00000000..85466131--- /dev/null+++ b/src/server/dev/web_guidance.rs@@ -0,0 +1,300 @@+//! Modern web guidance (web-guidance brief): when a Dev mode space's team folder has web code,+//! kwant offers the built-in `modern-web` skill once, as a pending skill shared with every bot in+//! the space, through the usual Skills review. The skill has a bot look up Google Chrome's Modern+//! Web Guidance with a pinned `npx` command before it writes browser code.+//!+//! kwant itself never runs `npx`: it only reads the team folders' top two levels, on the poller's+//! full pass and when Dev mode is turned on, never on a page load. The offer is marked on+//! `dev_mode_spaces.web_guidance_offered_at` when it is made, so it is never made again in that+//! space. The one `npx` form the skill runs is let through without a question by+//! `crate::mcp::shell_risk` (see [`VERSION`]).++use crate::db::skills::{clean_skill_text, SkillText};+use crate::db::spaces::SpaceId;+use crate::server::continuity::{notify, Notification};+use crate::server::AppState;+use std::path::{Path, PathBuf};+use std::time::Duration;++/// The `modern-web-guidance` package version the skill runs, pinned: a new version is a new+/// review. `crate::mcp::shell_risk` lets through only this one.+pub const VERSION: &str = "1.0.0";+/// The npm package the skill runs.+pub const PACKAGE: &str = "modern-web-guidance";+pub const SKILL_NAME: &str = "modern-web";+/// What the relevance matcher reads (`crate::server::skills::relevance`): words a request for+/// browser UI work uses, and none a backend one does.+pub const SKILL_DESCRIPTION: &str = "Modern web UI work: HTML, CSS and JavaScript in the browser: layout, responsive mobile page, form, button, menu, dialog, modal, popover, dark mode, animation, accessibility, frontend performance.";+/// The skill's body stays under this, so it costs little in a turn's prompt.+pub const MAX_BODY_CHARS: usize = 2_500;++/// How long the look at a team folder may take before kwant gives up on it.+const SCAN_LIMIT: Duration = Duration::from_secs(3);+/// At most this many directory entries are looked at per folder.+const MAX_ENTRIES: usize = 4_000;+/// Files that mean web code: a `package.json`, or one of these extensions.+const WEB_EXTENSIONS: [&str; 6] = ["html", "css", "tsx", "jsx", "vue", "svelte"];+/// Folders never looked into: dependencies and build output.+const SKIPPED_DIRS: [&str; 2] = ["node_modules", "target"];++/// The skill's body; `{v}` is [`VERSION`].+const BODY: &str = r#"Adapted from Google Chrome's Modern Web Guidance (Apache-2.0, github.com/GoogleChrome/modern-web-guidance). Offered by kwant's Dev mode.++Use this before you write or change web UI code that runs in a browser: HTML, CSS, client-side JavaScript or TypeScript, and components (React, Vue, Svelte). Not for backend, SQL, infra, CI, scripts, build config or tests.++1. Search the guides with 2 to 5 words about the feature:+ npx -y modern-web-guidance@{v} search "accessible modal dialog"+ If nothing fits, rephrase once.+2. Retrieve the best match by its id:+ npx -y modern-web-guidance@{v} retrieve <id>+ When it says the guide was saved to a file under /tmp, read that file in full before going on.+3. Follow the guide: use the platform features it recommends, check their Baseline support, and keep the fallbacks it gives for browsers without them. Where it clashes with the project's own conventions or browser targets, follow the project and say why.+4. End your reply with one line per guide you used:+ Modern Web Guidance: <id>, <what it changed>++Rules+- Run only these exact forms, each on its own: `npx -y modern-web-guidance@{v} search|retrieve|list ...`, or `pnpx modern-web-guidance@{v} ...` in a pnpm project. Never @latest or another version, never legacy-scan, no extra flags, no chaining with &&, ; or |. Anything else asks the person first.+- It needs Node and the network the first time. Give the command a 90-second limit if your shell tool takes one.+- If it fails, is missing or takes more than 90 seconds, say once "Couldn't load Modern Web Guidance here" and carry on with the task. Don't retry in a loop, and never install Node."#;++/// The skill's checked text.+pub fn skill_text() -> SkillText {+ clean_skill_text(SKILL_NAME, SKILL_DESCRIPTION, &BODY.replace("{v}", VERSION)).expect("the built-in modern-web skill is valid")+}++/// Whether `dir` has web code in its top two levels: a `package.json` or a file with one of+/// [`WEB_EXTENSIONS`]. Hidden entries, [`SKIPPED_DIRS`] and symlinks are skipped, and at most+/// [`MAX_ENTRIES`] entries are read. Blocking; see [`has_web_code_limited`].+pub fn has_web_code(dir: &Path) -> bool {+ let mut seen = 0usize;+ let mut subdirs: Vec<PathBuf> = Vec::new();+ if scan_level(dir, &mut seen, Some(&mut subdirs)) {+ return true;+ }+ subdirs.into_iter().any(|d| scan_level(&d, &mut seen, None))+}++/// One folder's entries: true on a web file; its subfolders go to `subdirs` when given.+fn scan_level(dir: &Path, seen: &mut usize, mut subdirs: Option<&mut Vec<PathBuf>>) -> bool {+ let Ok(entries) = std::fs::read_dir(dir) else { return false };+ for entry in entries.flatten() {+ *seen += 1;+ if *seen > MAX_ENTRIES {+ return false;+ }+ let name = entry.file_name();+ let Some(name) = name.to_str() else { continue };+ if name.starts_with('.') {+ continue;+ }+ // The entry's own type: a symlink is neither a file nor a folder here+ let Ok(kind) = entry.file_type() else { continue };+ if kind.is_dir() {+ if let Some(out) = subdirs.as_deref_mut() {+ if !SKIPPED_DIRS.contains(&name) {+ out.push(entry.path());+ }+ }+ } else if kind.is_file() && is_web_file(name) {+ return true;+ }+ }+ false+}++fn is_web_file(name: &str) -> bool {+ if name == "package.json" {+ return true;+ }+ match name.rsplit_once('.') {+ Some((stem, ext)) if !stem.is_empty() => WEB_EXTENSIONS.contains(&ext.to_ascii_lowercase().as_str()),+ _ => false,+ }+}++/// [`has_web_code`] off the async threads, giving up (false) after [`SCAN_LIMIT`].+pub async fn has_web_code_limited(dir: PathBuf) -> bool {+ let scan = tokio::task::spawn_blocking(move || has_web_code(&dir));+ matches!(tokio::time::timeout(SCAN_LIMIT, scan).await, Ok(Ok(true)))+}++/// Offers the `modern-web` skill to `space` once, when Dev mode is on there and a team's folder+/// has web code. The person sees a `skill_proposed` notification named for that team's lead+/// (its Review opens that bot's Skills), and the pending skill in every bot's Skills, where they+/// approve or reject it. Never offered twice in a space, and kwant runs nothing here.+pub async fn offer_if_web(state: &AppState, space: &SpaceId) {+ match state.db.dev_mode(space.as_str()).await {+ Ok(Some(row)) if row.on && row.web_guidance_offered_at.is_none() => {}+ _ => return,+ }+ let teams = state.db.list_teams(space).await.unwrap_or_default();+ let space_dir = crate::db::spaces::space_data_dir(&state.config.data_dir, space);+ let mut found = None;+ for team in &teams {+ let link = team.repo_url.as_deref().map(str::trim).filter(|s| !s.is_empty());+ let folder = crate::tools::team_workspace_path(&space_dir, &team.name, team.workspace_path.as_deref(), link);+ if has_web_code_limited(folder).await {+ found = Some(team);+ break;+ }+ }+ let Some(team) = found else { return };+ let skill = match state.db.offer_web_guidance_once(space.as_str(), &skill_text()).await {+ Ok(Some(s)) => s,+ Ok(None) => return,+ Err(e) => {+ tracing::warn!(space = %space, "dev: could not offer the modern-web skill: {e}");+ return;+ }+ };+ tracing::info!(space = %space, team = %team.name, skill = %skill.id, "dev: offered the modern-web skill");+ crate::server::skills::changed(state, &skill).await;+ let lead = state.db.get_kwant(&team.lead_kwant_id).await.ok().flatten();+ if let Some(lead) = lead {+ notify(+ state,+ Notification {+ kind: "skill_proposed",+ kwant_id: lead.id.clone(),+ kwant_name: lead.name.clone(),+ channel_id: None,+ title: "A skill for web work".into(),+ body: format!(+ "{}'s folder has web code. Review the {SKILL_NAME} skill in Skills: it has every bot in this space look up Modern Web Guidance before writing browser code.",+ team.name+ ),+ thread_id: None,+ card_id: None,+ },+ )+ .await;+ }+}++/// [`offer_if_web`] in its own task, so neither a request nor the poll waits on the folder look.+pub fn offer_soon(state: &AppState, space: &SpaceId) {+ let (state, space) = (state.clone(), space.clone());+ tokio::spawn(async move { offer_if_web(&state, &space).await });+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::db::skills::{Skill, MAX_SKILL_DESCRIPTION_CHARS};+ use crate::server::skills::{prompt_block_for, select};++ fn as_skill() -> Skill {+ let t = skill_text();+ let now = chrono::Utc::now();+ Skill {+ id: "s1".into(),+ kwant_id: None,+ name: t.name,+ description: t.description,+ body: t.body,+ status: "enabled".into(),+ source: "agent".into(),+ proposed_by: None,+ replaces_id: None,+ created_at: now,+ updated_at: now,+ reviewed_at: None,+ space_id: "default".into(),+ }+ }++ #[test]+ fn the_skill_text_is_within_its_limits_and_pins_one_version() {+ let t = skill_text();+ assert_eq!(t.name, SKILL_NAME);+ assert!(t.description.chars().count() <= MAX_SKILL_DESCRIPTION_CHARS, "{}", t.description.chars().count());+ assert!(t.body.chars().count() <= MAX_BODY_CHARS, "body is {} chars", t.body.chars().count());+ assert!(t.body.starts_with("Adapted from Google Chrome's Modern Web Guidance (Apache-2.0"));+ assert!(!t.body.contains("{v}"));+ assert!(t.body.contains(&format!("npx -y {PACKAGE}@{VERSION} search")));+ assert!(t.body.contains(&format!("npx -y {PACKAGE}@{VERSION} retrieve")));+ assert!(t.body.contains("Couldn't load Modern Web Guidance here"));+ assert!(t.body.contains("Modern Web Guidance: <id>"));+ // Every package mention is the pinned one+ for (i, _) in t.body.match_indices(&format!("{PACKAGE}@")) {+ assert!(t.body[i..].starts_with(&format!("{PACKAGE}@{VERSION} ")), "unpinned at {i}");+ }+ }++ const WEB_PROMPTS: [&str; 5] = [+ "Add a modal dialog with a form to the settings page",+ "Make the CSS layout responsive on mobile",+ "Fix accessibility of the dropdown menu in the web UI",+ "Add an animation to the popover in the browser",+ "Write the HTML and JavaScript for a dark mode toggle button",+ ];+ const OTHER_PROMPTS: [&str; 3] = [+ "Add a SQL migration for the users table",+ "Fix the Rust compile error in the parser module",+ "Set up the Docker deploy to the VPS with GitHub Actions",+ ];++ #[test]+ fn web_prompts_get_the_skill_and_others_do_not() {+ let skills = vec![as_skill()];+ for p in WEB_PROMPTS {+ assert_eq!(select(&skills, p).len(), 1, "not picked for: {p}");+ assert!(prompt_block_for(&skills, p, false).contains("modern-web-guidance@"), "not injected for: {p}");+ }+ for p in OTHER_PROMPTS {+ assert!(select(&skills, p).is_empty(), "picked for: {p}");+ assert!(!prompt_block_for(&skills, p, false).contains("modern-web-guidance@"), "injected for: {p}");+ }+ }++ fn touch(dir: &Path, rel: &str) {+ let p = dir.join(rel);+ std::fs::create_dir_all(p.parent().unwrap()).unwrap();+ std::fs::write(p, "x").unwrap();+ }++ #[test]+ fn a_web_repo_has_web_code_and_a_rust_one_does_not() {+ let rust = tempfile::tempdir().unwrap();+ for f in ["Cargo.toml", "README.md", "src/main.rs", "src/lib.rs", "tests/a_test.rs", ".github/workflows/ci.yml"] {+ touch(rust.path(), f);+ }+ assert!(!has_web_code(rust.path()));++ for web in ["package.json", "index.html", "web/package.json", "src/App.tsx", "ui/Button.jsx", "app/Page.vue", "lib/Nav.svelte", "static/site.CSS"] {+ let d = tempfile::tempdir().unwrap();+ touch(d.path(), "Cargo.toml");+ touch(d.path(), web);+ assert!(has_web_code(d.path()), "{web}");+ }+ }++ #[test]+ fn deeper_hidden_dependency_and_odd_names_are_not_web_code() {+ let d = tempfile::tempdir().unwrap();+ for f in [+ "a/b/index.html",+ ".hidden/index.html",+ "node_modules/package.json",+ "target/doc.html",+ "node_modules/x/index.css",+ ".css",+ "notes.html.txt",+ ] {+ touch(d.path(), f);+ }+ assert!(!has_web_code(d.path()));+ assert!(!has_web_code(&d.path().join("missing")));+ }++ #[cfg(unix)]+ #[test]+ fn a_symlink_is_not_followed() {+ let web = tempfile::tempdir().unwrap();+ touch(web.path(), "index.html");+ let d = tempfile::tempdir().unwrap();+ std::os::unix::fs::symlink(web.path(), d.path().join("linked")).unwrap();+ std::os::unix::fs::symlink(web.path().join("index.html"), d.path().join("page.html")).unwrap();+ assert!(!has_web_code(d.path()));+ }+}diff --git a/src/server/skills.rs b/src/server/skills.rsindex 90481351..bf4f6cd4 100644--- a/src/server/skills.rs+++ b/src/server/skills.rs@@ -49,7 +49,7 @@ fn skill_error(e: SkillError) -> Response {}/// Sends `skill_updated`; a shown draft carries its `shown` facts (see `super::show_once`).-async fn changed(state: &AppState, skill: &Skill) {+pub(crate) async fn changed(state: &AppState, skill: &Skill) {let skill = super::show_once::skill_json(state, skill).await;let _ = state.event_sender.send(RuntimeEvent::SkillUpdated { skill });}diff --git a/tests/dev_web_guidance_test.rs b/tests/dev_web_guidance_test.rsnew file mode 100644index 00000000..0a93d03a--- /dev/null+++ b/tests/dev_web_guidance_test.rs@@ -0,0 +1,170 @@+//! Modern web guidance (web-guidance brief W3): a Dev mode space whose team folder has web code+//! is offered the built-in `modern-web` skill once, as one pending skill every bot in the space+//! sees in Skills. Never again after a reject, a delete, or Dev mode going off and on; never for+//! a Rust-only folder; never while Dev mode is off. kwant runs no `npx` here.++mod common;++use common::*;+use kwnt::db::models::NewTeam;+use kwnt::db::skills::clean_skill_text;+use kwnt::db::spaces::SpaceId;+use kwnt::server::dev::web_guidance::{offer_if_web, SKILL_NAME, VERSION};+use serde_json::json;+use std::path::{Path, PathBuf};++fn space() -> SpaceId {+ SpaceId::default_space()+}++async fn team(env: &Env, name: &str, folder: &Path) {+ let t = NewTeam {+ name: name.into(),+ description: None,+ icon: None,+ lead_kwant_id: env.a.clone(),+ member_kwants: vec![env.a.clone()],+ workspace_path: Some(folder.to_string_lossy().to_string()),+ repo_url: None,+ };+ env.state.db.create_team(&space(), &t).await.unwrap();+}++fn folder(env: &Env, name: &str, files: &[&str]) -> PathBuf {+ let dir = env.tmp.path().join("wg-folders").join(name);+ for f in files {+ let p = dir.join(f);+ std::fs::create_dir_all(p.parent().unwrap()).unwrap();+ std::fs::write(p, "x").unwrap();+ }+ dir+}++async fn dev_mode(env: &Env, on: bool) {+ let (s, v) = call(&env.app, "PUT", &format!("/api/spaces/{}/dev_mode", space().as_str()), Some(json!({"on": on}))).await;+ assert_eq!(s.as_u16(), 200, "{v}");+}++/// Every skill in the space called modern-web, any status.+async fn offered(env: &Env) -> Vec<kwnt::db::skills::Skill> {+ let all = env.state.db.list_skills(&space(), None, None).await.unwrap();+ all.into_iter().filter(|s| s.name == SKILL_NAME).collect()+}++async fn marked(env: &Env) -> bool {+ env.state.db.dev_mode(space().as_str()).await.unwrap().is_some_and(|r| r.web_guidance_offered_at.is_some())+}++/// The offer turning on starts runs in its own task; wait for it (at most 5 s).+async fn wait_for_offer(env: &Env) -> Vec<kwnt::db::skills::Skill> {+ for _ in 0..50 {+ let got = offered(env).await;+ if !got.is_empty() {+ return got;+ }+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;+ }+ offered(env).await+}++#[tokio::test]+async fn a_web_folder_gets_one_space_wide_offer_and_never_another() {+ let env = setup().await;+ let web = folder(&env, "site", &["package.json", "src/App.tsx"]);+ team(&env, "Site", &web).await;+ assert!(offered(&env).await.is_empty(), "nothing before Dev mode is on");++ dev_mode(&env, true).await;+ let got = wait_for_offer(&env).await;+ assert_eq!(got.len(), 1, "one offer");+ let skill = &got[0];+ assert_eq!((skill.status.as_str(), skill.source.as_str()), ("pending", "agent"));+ assert_eq!(skill.kwant_id, None, "shared with every bot in the space: one card, not one per bot");+ assert!(skill.body.contains(&format!("modern-web-guidance@{VERSION} search")));+ assert!(marked(&env).await);++ // Both bots see the same pending skill in their Skills+ for k in [&env.a, &env.b] {+ let (s, v) = call(&env.app, "GET", &format!("/api/skills?kwant_id={k}&status=pending"), None).await;+ assert_eq!(s.as_u16(), 200, "{v}");+ let ids: Vec<&str> = v.as_array().unwrap().iter().filter_map(|x| x["id"].as_str()).collect();+ assert_eq!(ids, vec![skill.id.as_str()], "{v}");+ }++ // A second pass (the poller's) offers nothing more+ offer_if_web(&env.state, &space()).await;+ assert_eq!(offered(&env).await.len(), 1);++ // Rejected: kept for the record, never offered again+ let (s, v) = call(&env.app, "POST", &format!("/api/skills/{}/reject", skill.id), Some(json!({}))).await;+ assert_eq!(s.as_u16(), 200, "{v}");+ offer_if_web(&env.state, &space()).await;+ let got = offered(&env).await;+ assert_eq!(got.iter().map(|s| s.status.as_str()).collect::<Vec<_>>(), vec!["rejected"]);++ // Deleted: still never offered again+ let (s, _) = call(&env.app, "DELETE", &format!("/api/skills/{}", skill.id), None).await;+ assert!(s.is_success(), "{s}");+ offer_if_web(&env.state, &space()).await;+ assert!(offered(&env).await.is_empty());++ // Dev mode off and on again: no new offer+ dev_mode(&env, false).await;+ dev_mode(&env, true).await;+ tokio::time::sleep(std::time::Duration::from_millis(500)).await;+ offer_if_web(&env.state, &space()).await;+ assert!(offered(&env).await.is_empty(), "turning Dev mode off and on doesn't offer it again");+ assert!(marked(&env).await);+}++#[tokio::test]+async fn a_rust_only_folder_gets_no_offer_until_web_code_appears() {+ let env = setup().await;+ let rust = folder(&env, "engine", &["Cargo.toml", "src/main.rs", "tests/a_test.rs", "README.md"]);+ team(&env, "Engine", &rust).await;+ dev_mode(&env, true).await;+ tokio::time::sleep(std::time::Duration::from_millis(500)).await;+ offer_if_web(&env.state, &space()).await;+ assert!(offered(&env).await.is_empty());+ assert!(!marked(&env).await, "no offer made, so none is marked");++ // The team adds a web front end: the next pass offers it+ std::fs::create_dir_all(rust.join("web")).unwrap();+ std::fs::write(rust.join("web/index.html"), "<!doctype html>").unwrap();+ offer_if_web(&env.state, &space()).await;+ assert_eq!(offered(&env).await.len(), 1);+}++#[tokio::test]+async fn nothing_is_offered_while_dev_mode_is_off() {+ let env = setup().await;+ let web = folder(&env, "site", &["index.html"]);+ team(&env, "Site", &web).await;+ offer_if_web(&env.state, &space()).await;+ assert!(offered(&env).await.is_empty());++ dev_mode(&env, true).await;+ dev_mode(&env, false).await;+ tokio::time::sleep(std::time::Duration::from_millis(500)).await;+ // Whatever the switch-on task did, a pass while off adds nothing+ let before = offered(&env).await.len();+ offer_if_web(&env.state, &space()).await;+ assert_eq!(offered(&env).await.len(), before);+}++#[tokio::test]+async fn the_persons_own_modern_web_skill_is_left_alone() {+ let env = setup().await;+ let web = folder(&env, "site", &["package.json"]);+ team(&env, "Site", &web).await;+ let mine = clean_skill_text(SKILL_NAME, "My own web notes", "Use our design system.").unwrap();+ let own = env.state.db.create_user_skill(&space(), None, mine).await.unwrap();++ dev_mode(&env, true).await;+ tokio::time::sleep(std::time::Duration::from_millis(500)).await;+ offer_if_web(&env.state, &space()).await;+ let got = offered(&env).await;+ assert_eq!(got.len(), 1);+ assert_eq!((got[0].id.as_str(), got[0].body.as_str()), (own.id.as_str(), "Use our design system."));+ assert!(marked(&env).await, "marked, so it isn't checked again");+}