Skip to content

armgit / kwant

Public Imported from GitHub
0

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

Approvals off wins in turns kwant starts on its own (#569)

Oleksandr Ivanchenko506c6eccdc94
diff --git a/frontend/src/components/ModernApprovalCard.tsx b/frontend/src/components/ModernApprovalCard.tsx
index 29be6efa..42ede829 100644
--- a/frontend/src/components/ModernApprovalCard.tsx
+++ b/frontend/src/components/ModernApprovalCard.tsx
@@ -135,6 +135,43 @@ export const paymentReason = (approval: PendingApproval) => {
return why.trim().replace(/[.\s]+$/, '') || 'it looks like paying';
};
+/**
+ * Who started a turn, as the card names it after "Started by": the server's raw label
+ * (`details.started_by`) mapped to a name people know (Mira's table, #569). Internal names
+ * nobody sees on screen become plain nouns; a label not listed shows its part before the first ":".
+ */
+const STARTED_BY_NAMES: Record<string, string> = {
+ 'Loose ends: prepare drafts and next steps': 'Loose ends',
+ Watch: 'Watch',
+ Verify: 'a task check',
+ Audit: 'an audit',
+ 'Goal draft': 'a goal draft',
+ 'Skill Foundry': 'a skill draft',
+ 'Skill Foundry replay': 'a skill draft’s test run',
+ 'Idea jar': 'Idea jar',
+ 'Show it once': 'Show it once',
+ 'Dev mode card': 'Dev mode',
+};
+
+export const startedByName = (label: string) => {
+ const raw = label.trim();
+ return STARTED_BY_NAMES[raw] ?? (raw.split(':')[0].trim() || raw);
+};
+
+/**
+ * Why a card asks although nobody typed a request: kwant started the turn on its own (the
+ * server's `details.started_by`). A strict turn (`details.strict_ask`, a Skill Foundry draft)
+ * asks even on Don’t ask, so it says so instead. Null on an ordinary turn's card.
+ */
+export const startedByNote = (approval: PendingApproval) => {
+ const label = approval.details?.started_by;
+ if (typeof label !== 'string' || !label.trim()) return null;
+ const who = startedByName(label);
+ return approval.details?.strict_ask === true
+ ? `Started by ${who}, not by you. Skill drafts always ask, even on Don’t ask.`
+ : `Started by ${who}, not by you, so each change asks first. Bots on Don’t ask (Settings › This space) run these without a card.`;
+};
+
/** The line under a still-open card's heading. */
export const waitingNote = (bot: string | null) =>
`${bot ?? 'The bot'} stopped waiting for an answer and nothing ran. Allow starts it again to make this call; Deny closes the card.`;
@@ -228,8 +265,12 @@ export const ModernApprovalCard: React.FC<ModernApprovalCardProps> = ({
const botName = name ?? mcp?.kwant ?? null;
const payment = paymentReason(approval);
const tier = payment ? null : tierReason(approval.details);
+ const startedBy = payment || tier ? null : startedByNote(approval);
const time = localClock(approval.asked_at);
- const offerAlways = !shell && !waiting && !payment;
+ // A session allow doesn't count in a turn kwant started on its own (the server asks again),
+ // so those cards don't offer one.
+ const alwaysAsk = approval.details?.always_ask === true;
+ const offerAlways = !shell && !waiting && !payment && !alwaysAsk;
const bot = botName ? <strong className="font-semibold text-zinc-50">{botName}</strong> : 'A bot';
// "<Bot> wants to open a pull request on <Server>", the server in bold.
@@ -315,6 +356,11 @@ export const ModernApprovalCard: React.FC<ModernApprovalCardProps> = ({
<p className="mt-2.5 text-base leading-6 text-zinc-200 break-words" data-approval-summary="">
{bot} wants to {what}
</p>
+ {startedBy && (
+ <p role="note" data-started-by className="mt-1 text-xs leading-[18px] text-zinc-400 break-words">
+ {startedBy}
+ </p>
+ )}
{(shell || builtin?.kind === 'shell') && (
<>
@@ -369,8 +415,8 @@ export const ModernApprovalCard: React.FC<ModernApprovalCardProps> = ({
{/* Allow on a row of its own, first; Deny and Always allow share the row under it. On a wider
screen they sit in one row, right-aligned, with Allow last. Local shell approvals are never
- remembered, a late answer only lets that one call run, and a payment always asks again,
- so none of them gets an "always". */}
+ remembered, a late answer only lets that one call run, and a payment or a turn kwant
+ started on its own always asks again, so none of them gets an "always". */}
<div data-approval-actions className="mt-3 flex flex-col gap-2 sm:flex-row-reverse sm:items-center sm:justify-start">
<button
type="button"
diff --git a/frontend/tests/approvalCard.test.mjs b/frontend/tests/approvalCard.test.mjs
index 6866c038..0c335904 100644
--- a/frontend/tests/approvalCard.test.mjs
+++ b/frontend/tests/approvalCard.test.mjs
@@ -6,7 +6,7 @@ import { loadBundled } from './bundle.mjs';
globalThis.localStorage ??= { getItem: () => null, setItem: () => {} };
const m = await loadBundled(`
- export { ModernApprovalCard, localShellView } from './src/components/ModernApprovalCard';
+ export { ModernApprovalCard, localShellView, startedByNote } from './src/components/ModernApprovalCard';
export { renderToStaticMarkup } from 'react-dom/server.browser';
export { createElement } from 'react';
`);
@@ -133,3 +133,68 @@ test('a payment card in its summary form (after a reload) shows the reason and n
const plain = render({ id: 'n4', tool_name: 'Bash', details: { source: 'summary', tool: 'Bash', summary: 'command: ls' } });
assert.match(plain, /Always this session/);
});
+
+// Shaped like BrokerApprover::classified for a turn kwant started on its own (loose ends, Watch).
+const startedTicket = (extra = {}) => ({
+ id: 's1',
+ tool_name: 'Bash',
+ details: { source: 'claude_builtin', tool: 'Bash', arguments: { command: 'touch x' }, kwant_name: 'Lin', always_ask: true, ...extra },
+});
+
+test('a card from a turn kwant started says who started it, in one line under the summary', () => {
+ const html = render(startedTicket({ started_by: 'Loose ends: prepare drafts and next steps' }));
+ assert.match(
+ html,
+ /data-started-by[^>]*>Started by Loose ends, not by you, so each change asks first\. Bots on Don’t ask \(Settings › This space\) run these without a card\.<\/p>/,
+ );
+ // Read order: summary, then this line, then the command
+ const summary = html.indexOf('data-approval-summary');
+ const line = html.indexOf('data-started-by');
+ const command = html.indexOf('aria-label="Command"');
+ assert.ok(summary < line && line < command, 'summary → started by → command');
+ assert.match(html, /data-started-by[^>]*class="mt-1 /);
+ assert.doesNotMatch(render(startedTicket()), /data-started-by/, 'no label, no line');
+ assert.equal(m.startedByNote(startedTicket({ started_by: ' ' })), null);
+ assert.equal(m.startedByNote({ id: 'x', tool_name: 'Bash', details: { started_by: 3 } }), null);
+ // A payment card keeps its own reason and doesn't add this line
+ assert.doesNotMatch(render(stripeTicket({ always_ask: true, started_by: 'Loose ends' })), /data-started-by/);
+});
+
+test('internal labels map to the names people know; an unknown one shows the part before ":"', () => {
+ const name = (started_by, extra = {}) => m.startedByNote(startedTicket({ started_by, ...extra }));
+ assert.match(name('Verify'), /^Started by a task check, not by you, so each change asks first\./);
+ assert.match(name('Audit'), /^Started by an audit, not by you/);
+ assert.match(name('Goal draft'), /^Started by a goal draft, not by you/);
+ assert.match(name('Watch'), /^Started by Watch, not by you/);
+ assert.match(name('Something new: details'), /^Started by Something new, not by you, so each change asks first\./);
+ assert.doesNotMatch(name('Loose ends: prepare drafts and next steps'), /prepare drafts/);
+});
+
+test('a strict turn (details.strict_ask) says skill drafts always ask, even on Don’t ask', () => {
+ assert.equal(
+ m.startedByNote(startedTicket({ started_by: 'Skill Foundry replay', strict_ask: true })),
+ 'Started by a skill draft’s test run, not by you. Skill drafts always ask, even on Don’t ask.',
+ );
+ assert.equal(
+ m.startedByNote(startedTicket({ started_by: 'Skill Foundry', strict_ask: true })),
+ 'Started by a skill draft, not by you. Skill drafts always ask, even on Don’t ask.',
+ );
+ // The sentence comes from the server's flag, not from the label
+ assert.match(m.startedByNote(startedTicket({ started_by: 'Skill Foundry' })), /so each change asks first/);
+});
+
+test('a card from a turn kwant started offers no "always"; an ordinary card still does', () => {
+ const write = (extra = {}) => ({
+ id: 'w1',
+ tool_name: 'Write',
+ details: { source: 'claude_builtin', tool: 'Write', arguments: { file_path: '/tmp/x', content: 'x' }, kwant_name: 'Lin', ...extra },
+ });
+ const plain = render(write());
+ assert.match(plain, /Always this session|Always allow/);
+ const started = render(write({ always_ask: true, started_by: 'Watch' }));
+ assert.doesNotMatch(started, /Always this session|Always allow/);
+ assert.match(started, /Allow once/);
+ assert.match(started, />Deny</);
+ assert.match(started, /grid-cols-1/);
+ assert.doesNotMatch(render(startedTicket({ started_by: 'Watch' })), /Always this session|Always allow/);
+});
diff --git a/src/mcp/shell_risk.rs b/src/mcp/shell_risk.rs
index 1d7ebda9..a932d25e 100644
--- a/src/mcp/shell_risk.rs
+++ b/src/mcp/shell_risk.rs
@@ -296,6 +296,68 @@ pub fn classify(command: &str, folder: &Path) -> SmartVerdict {
}
}
+/// 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] = &[
+ "cd", "ls", "cat", "head", "tail", "wc", "echo", "printf", "true", "false", "pwd", "diff", "cmp", "cut", "tr", "file",
+ "stat", "du", "basename", "dirname", "realpath", "readlink", "which", "date", "test", "[", "nl", "rev", "tac", "strings",
+ "md5sum", "sha1sum", "sha256sum", "sha512sum", "jq", "grep", "egrep", "fgrep", "rg", "git",
+];
+/// git subcommands that only read the repository.
+const GIT_READS: &[&str] = &[
+ "status", "diff", "log", "show", "rev-parse", "blame", "ls-files", "grep", "describe", "shortlog", "cat-file", "rev-list",
+ "merge-base", "show-ref", "ls-tree", "diff-tree", "name-rev",
+];
+
+/// Whether `command` only reads, inside `folder`: "Ask only when risky" lets it through even in a
+/// turn kwnt started on its own. Stricter than [`classify`] (which it must pass first): every
+/// program is one in [`READS_ONLY`], git runs only a subcommand in [`GIT_READS`] with no option
+/// that writes a file or runs a program, there are no `VAR=` assignments, and output goes nowhere
+/// but `/dev/null`. Anything else is `false` (and goes on to ask).
+pub fn reads_only(command: &str, folder: &Path) -> bool {
+ if check(command, folder).is_err() {
+ return false;
+ }
+ let Ok(toks) = lex(command) else { return false };
+ let mut simple: Vec<Word> = Vec::new();
+ let mut iter = toks.into_iter();
+ while let Some(tok) = iter.next() {
+ match tok {
+ Tok::Word(w) => simple.push(w),
+ Tok::Dup => {}
+ Tok::Redirect => match iter.next() {
+ Some(Tok::Word(target)) if target.text == "/dev/null" => {}
+ _ => return false,
+ },
+ Tok::Sep => {
+ if !simple_reads_only(&std::mem::take(&mut simple)) {
+ return false;
+ }
+ }
+ }
+ }
+ simple_reads_only(&simple)
+}
+
+/// One command of [`reads_only`]; an empty one (after a trailing `;`) reads nothing.
+fn simple_reads_only(words: &[Word]) -> bool {
+ let Some(first) = words.first() else { return true };
+ let name = first.text.as_str();
+ if !READS_ONLY.contains(&name) {
+ return false;
+ }
+ if name != "git" {
+ return true;
+ }
+ // `git <subcommand>`, with no global options before it
+ let Some(sub) = words.get(1) else { return false };
+ let writes = |a: &Word| {
+ let t = a.text.as_str();
+ t == "-o" || t.starts_with("--output") || t == "--ext-diff" || t.starts_with("--open-files-in-pager") || t == "-O"
+ };
+ GIT_READS.contains(&sub.text.as_str()) && !words[2..].iter().any(writes)
+}
+
fn check(command: &str, folder: &Path) -> Verdict {
if command.trim().is_empty() {
return Err("the command is empty".into());
@@ -1988,4 +2050,62 @@ mod tests {
);
assert_eq!(classify("npm create vite@latest", &ws), SmartVerdict::Ask("`npm create vite@latest` downloads a starter package and runs it".into()));
}
+
+ /// 0.9.7: what a turn kwnt started on its own may run under "Ask only when risky" without a
+ /// card. Oleks's command (Nov 13) is the first one.
+ #[test]
+ fn reads_only_lets_through_only_commands_that_read() {
+ let (_tmp, ws) = folder();
+ for cmd in [
+ "cd src && git rev-parse --short HEAD && git show --stat HEAD | head -20 && grep -rn 'placeMaker' --include=*.go . | head -30",
+ "git log --oneline -5",
+ "git status",
+ "git diff HEAD~1 -- src/main.rs",
+ "git blame src/main.rs",
+ "ls -la src",
+ "cat run.sh",
+ "rg -n foo src 2>/dev/null",
+ "wc -l run.sh; pwd",
+ "ls",
+ "git status --short && ls",
+ ] {
+ assert!(reads_only(cmd, &ws), "{cmd} only reads");
+ assert!(classify(cmd, &ws).is_allowed(), "{cmd} passes classify first");
+ }
+ for cmd in [
+ "rm -rf x",
+ "touch x",
+ "mkdir y",
+ "git add -A",
+ "git commit -m x",
+ "git checkout -b x",
+ "git show HEAD --output=out.txt",
+ "git diff --ext-diff",
+ "git -C src log",
+ "git",
+ "cat run.sh > copy.sh",
+ "echo hi >> run.sh",
+ "sort -o out run.sh",
+ "sed -i s/a/b/ run.sh",
+ "find . -delete",
+ "cargo test",
+ "RUST_LOG=1 cat run.sh",
+ "cat /etc/passwd",
+ "curl https://example.com",
+ "ls && rm x",
+ // Must-hold 4 (#569): each of these asks in a kwant-started turn
+ "rm -rf src",
+ "git add .",
+ "echo x > f",
+ "git -C . status",
+ "git diff --output=f",
+ "git diff --output f",
+ "rg --pre cat x",
+ "rg --pre=cat x",
+ "LC_ALL=C ls",
+ "GIT_EXTERNAL_DIFF=./x git diff",
+ ] {
+ assert!(!reads_only(cmd, &ws), "{cmd} must not count as read-only");
+ }
+ }
}
diff --git a/src/server/delegation.rs b/src/server/delegation.rs
index 12eae277..da5ad33c 100644
--- a/src/server/delegation.rs
+++ b/src/server/delegation.rs
@@ -571,7 +571,7 @@ async fn run(state: AppState, job: super::turns::JobGuard, d: Delegation, lead:
// boxed, so the retry loop around the turn adds no stack to it
async move {
let outcome = Box::pin(try_kwant_turn(scope, specialist, p, opts)).await;
- Box::pin(continue_once_if_capped_into(scope, specialist, outcome, false, Some(&slot))).await
+ Box::pin(continue_once_if_capped_into(scope, specialist, outcome, None, Some(&slot))).await
}
})
.await;
@@ -949,7 +949,7 @@ pub async fn resume_after_answer(state: &AppState, d: Delegation, question_id: &
Err(_) => return,
};
let outcome = try_kwant_turn(&scope, &specialist, prompt, TurnOpts::default()).await;
- let outcome = continue_once_if_capped(&scope, &specialist, outcome, false).await;
+ let outcome = continue_once_if_capped(&scope, &specialist, outcome, None).await;
let stopped = job.token.is_cancelled();
drop(job);
let reply = match outcome {
diff --git a/src/server/loose_ends_owner.rs b/src/server/loose_ends_owner.rs
index 18ae8235..2b5a4608 100644
--- a/src/server/loose_ends_owner.rs
+++ b/src/server/loose_ends_owner.rs
@@ -240,10 +240,12 @@ async fn start(state: &AppState, space: &SpaceId, events: &[(Event, Vec<CaseRow>
let id = kwant.id.clone();
tokio::spawn(async move {
let _job = job;
- // Nobody asked for this turn: anything that could change something asks, approvals off or not
- let opts = TurnOpts::always_asking("Loose ends: prepare drafts and next steps");
+ // Nobody asked for this turn: under Ask or "Ask only when risky" anything that could change
+ // something asks, and the card says why; approvals off still means off (0.9.7)
+ const LABEL: &str = "Loose ends: prepare drafts and next steps";
+ let opts = TurnOpts::always_asking(LABEL);
let reply = try_kwant_turn(&scope, &kwant, text, opts).await;
- let _ = continue_once_if_capped(&scope, &kwant, reply, true).await;
+ let _ = continue_once_if_capped(&scope, &kwant, reply, Some(LABEL)).await;
});
Some(id)
}
diff --git a/src/server/mcp_runtime.rs b/src/server/mcp_runtime.rs
index dbf0d2fc..c7f51a95 100644
--- a/src/server/mcp_runtime.rs
+++ b/src/server/mcp_runtime.rs
@@ -130,10 +130,18 @@ pub struct BrokerApprover {
/// The chat a card left unanswered resumes in after a late Allow (see [`turn_chat`]);
/// `None` resumes in the bot's direct chat.
pub chat: Option<Value>,
- /// Ask even when the bot's approvals are off, and don't use "always allow" answers: for
- /// turns kwnt starts on its own that nobody asked for (the loose-ends owner). A call the
- /// person allowed on a card (late Allow) still runs once.
+ /// kwnt started this turn on its own, nobody asked for it (the loose-ends owner, Watch,
+ /// Verify, an audit…): "always allow" answers don't count and, under Ask or "Ask only when
+ /// risky", every call that could change something asks, with the card saying why
+ /// (`details.started_by`). Approvals off still runs everything (0.9.7): only
+ /// [`BrokerApprover::strict_ask`] turns ask then. A call the person allowed on a card (late
+ /// Allow) still runs once.
pub always_ask: bool,
+ /// Asks even when the bot's approvals are off: a turn that runs something the person hasn't
+ /// reviewed (a Skill Foundry draft). Only with `always_ask`.
+ pub strict_ask: bool,
+ /// What kwnt started the turn for (its label, "Watch"), shown on an `always_ask` turn's card.
+ pub started_by: Option<String>,
/// Where task folders resolve, for the side-effect ledger (`turn_tool_calls`).
pub data_dir: PathBuf,
}
@@ -202,6 +210,23 @@ impl ToolApprover for BrokerApprover {
}
}
+/// One of claude's plain read tools (Read, Glob, Grep).
+fn plain_read(req: &ToolApprovalRequest) -> bool {
+ req.builtin.is_some() && matches!(req.tool.as_str(), "Read" | "Glob" | "Grep")
+}
+
+/// A claude Bash call whose command only reads, in the bot's folder (see
+/// [`mcp::shell_risk::reads_only`]).
+fn shell_reads_only(req: &ToolApprovalRequest) -> bool {
+ let Some(cwd) = req.builtin.as_ref().and_then(|b| b.cwd.as_deref()) else { return false };
+ let Some(command) = req.arguments.get("command").and_then(Value::as_str) else { return false };
+ if req.tool != "Bash" {
+ return false;
+ }
+ let folder = std::path::Path::new(cwd).canonicalize().unwrap_or_else(|_| PathBuf::from(cwd));
+ mcp::shell_risk::reads_only(command, &folder)
+}
+
impl BrokerApprover {
/// A push the person's Retry or Override covers (0.9.7): uses the grant up and records the call
/// as approved by it (`Some(approval id)`), with no card. `None` when it must ask as usual: the
@@ -262,15 +287,19 @@ impl BrokerApprover {
// follow approvals off even in an always-asking audit turn; its other tools still ask
let audit_call = req.server == mcp::SELF_SERVER_NAME
&& (super::missions::auditor::TOOL_NAMES.contains(&req.tool.as_str()) || req.tool == super::missions::verifier::TOOL);
- let off = !forced && (!self.always_ask || audit_call) && mode.as_ref().is_some_and(|m| m.is_off());
+ // Approvals off means off in a turn kwant started on its own too (0.9.7): only a strict one
+ // (it runs something the person hasn't reviewed) still asks.
+ let strict = self.always_ask && self.strict_ask;
+ let off = !forced && (!strict || audit_call) && mode.as_ref().is_some_and(|m| m.is_off());
// "Ask only when risky": what the caller made of this call; nothing known asks. A turn that
- // always asks (kwant started it on its own) still lets claude's plain read tools through.
+ // always asks (kwant started it on its own) still lets claude's plain read tools through,
+ // and a shell command that only reads (`git show`, `grep`) unless the turn is strict.
let smart = mode
.as_ref()
.is_some_and(|m| m.is_smart())
.then(|| req.smart.clone())
.flatten()
- .filter(|_| !self.always_ask || (req.builtin.is_some() && matches!(req.tool.as_str(), "Read" | "Glob" | "Grep")))
+ .filter(|_| !self.always_ask || plain_read(&req) || (!strict && shell_reads_only(&req)))
.filter(|_| !forced);
let mut details = match &req.builtin {
Some(b) => json!({
@@ -311,6 +340,13 @@ impl BrokerApprover {
}
if self.always_ask {
details["always_ask"] = json!(true);
+ // The card picks its sentence from this, not from the label (Ada, #569 round 2)
+ if self.strict_ask {
+ details["strict_ask"] = json!(true);
+ }
+ if let Some(label) = self.started_by.as_deref().map(str::trim).filter(|l| !l.is_empty()) {
+ details["started_by"] = json!(label);
+ }
}
let record = NewApproval {
turn_id: req.turn_id.clone(),
@@ -716,9 +752,12 @@ pub struct TurnApprovalOpts {
/// The turn's (agent, effort): a card it leaves unanswered resumes on the same ones after a
/// late Allow.
pub routed: Option<(String, String)>,
- /// Every call that could change something asks, approvals off or not (see
- /// [`BrokerApprover::always_ask`]).
+ /// kwnt started the turn on its own (see [`BrokerApprover::always_ask`]).
pub always_ask: bool,
+ /// Asks even with approvals off (see [`BrokerApprover::strict_ask`]).
+ pub strict_ask: bool,
+ /// The turn's label, for its cards (see [`BrokerApprover::started_by`]).
+ pub started_by: Option<String>,
/// 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`]).
@@ -877,6 +916,8 @@ pub async fn prepare_turn_with_opts(
conversation: turn_conversation(state, &turn_id),
chat,
always_ask: opts.always_ask,
+ strict_ask: opts.strict_ask,
+ started_by: opts.started_by.clone(),
data_dir: state.config.data_dir.clone(),
});
let approver: Arc<dyn ToolApprover> = if let Some(log) = opts.rehearse.clone() {
@@ -899,11 +940,17 @@ pub async fn prepare_turn_with_opts(
permission_url: Some(format!("{}/api/mcp/permission/{token}", local_base_url(state))),
gateway: Some(GatewayAccess { url: format!("{}/api/mcp/gateway", local_base_url(state)), token: token.clone() }),
max_tool_iterations: max_tool_iterations(setting),
- approvals: if opts.always_ask || opts.purpose.as_deref() == Some(super::dev::tickets::BRIEF_PURPOSE) {
- // An audit turn asks whatever the setting says, and a Dev mode brief only reads: never tell either to just go ahead
- Approvals::Ask
- } else {
- state.db.kwant_approvals(&kwant.id).await.map(|m| Approvals::from_mode(&m.effective)).unwrap_or_default()
+ approvals: {
+ let mode = state.db.kwant_approvals(&kwant.id).await.map(|m| Approvals::from_mode(&m.effective)).unwrap_or_default();
+ if (opts.always_ask && opts.strict_ask) || opts.purpose.as_deref() == Some(super::dev::tickets::BRIEF_PURPOSE) {
+ // A strict turn asks whatever the setting says, and a Dev mode brief only reads: never tell either to just go ahead
+ Approvals::Ask
+ } else if opts.always_ask && mode != Approvals::Off {
+ // A turn kwant started on its own asks under "Ask only when risky" too
+ Approvals::Ask
+ } else {
+ mode
+ }
},
records: Default::default(),
};
diff --git a/src/server/missions/foundry.rs b/src/server/missions/foundry.rs
index 35adde44..72988110 100644
--- a/src/server/missions/foundry.rs
+++ b/src/server/missions/foundry.rs
@@ -216,7 +216,7 @@ pub async fn drive_draft(state: &AppState, run: &FoundryRun) {
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");
+ let mut opts = TurnOpts::strict_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 {
@@ -722,7 +722,7 @@ async fn replay_one(state: &AppState, run: &FoundryRun, skill: &Skill, meta: &Sk
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");
+ let mut opts = TurnOpts::strict_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());
diff --git a/src/server/routes.rs b/src/server/routes.rs
index 9c25a95f..7d25c1c9 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -1103,13 +1103,13 @@ async fn run_turn_with(
// boxed, so the retry loop around the turn adds no stack to it
async move {
let reply = Box::pin(try_kwant_turn(scope, kwant, p, o)).await;
- Box::pin(continue_once_if_capped_into(scope, kwant, reply, false, Some(&slot))).await
+ Box::pin(continue_once_if_capped_into(scope, kwant, reply, None, Some(&slot))).await
}
})
.await
} else {
let reply = try_kwant_turn(&scope, kwant, prompt.clone(), opts()).await;
- continue_once_if_capped(&scope, kwant, reply, false).await
+ continue_once_if_capped(&scope, kwant, reply, None).await
};
match reply {
Ok(text) => {
@@ -1145,14 +1145,15 @@ This is your one automatic continuation: pick up where you left off, finish the
/// For turns nobody is watching (routines, delegations): a turn that stopped at the model-call
/// cap gets one more turn to finish, never more. Returns both replies joined, so a delegation's
/// result has all of it. A turn that didn't hit the cap, or failed, is returned as it is.
-/// `always_ask` carries [`TurnOpts::always_ask`] over to the continuation.
+/// `started_by` is the label of a turn kwnt started on its own: the continuation is one too
+/// ([`TurnOpts::always_ask`], its cards say what started it). `None` for any other turn.
pub(super) async fn continue_once_if_capped(
scope: &TurnScope,
kwant: &Kwant,
first: Result<String, String>,
- always_ask: bool,
+ started_by: Option<&str>,
) -> Result<String, String> {
- continue_once_if_capped_into(scope, kwant, first, always_ask, None).await
+ continue_once_if_capped_into(scope, kwant, first, started_by, None).await
}
/// [`continue_once_if_capped`] for an unwatched turn: the continuation, when there is one, is the
@@ -1161,7 +1162,7 @@ pub(super) async fn continue_once_if_capped_into(
scope: &TurnScope,
kwant: &Kwant,
first: Result<String, String>,
- always_ask: bool,
+ started_by: Option<&str>,
busy_slot: Option<&super::busy_retry::Slot>,
) -> Result<String, String> {
let Ok(text) = &first else {
@@ -1176,7 +1177,8 @@ pub(super) async fn continue_once_if_capped_into(
}
let opts = TurnOpts {
label: Some("Automatic continuation (once): the last turn ran out of model calls".into()),
- always_ask,
+ always_ask: started_by.is_some(),
+ started_by: started_by.map(str::to_string),
busy_slot: busy_slot.cloned(),
..Default::default()
};
@@ -2018,9 +2020,17 @@ pub(super) struct TurnOpts {
/// (agent, effort) to run on instead of asking Laya: a turn resumed after a late Allow
/// keeps those of the turn that asked.
routed: Option<(String, String)>,
- /// Every call that could change something asks the person, even with approvals off (an
- /// owner turn kwnt starts on its own; see [`super::loose_ends_owner`]).
+ /// kwnt started this turn on its own, nobody asked for it (the loose-ends owner, Watch,
+ /// Verify…): under Ask or "Ask only when risky" every call that could change something asks,
+ /// and the card says why. With approvals off it runs like any turn (0.9.7) unless
+ /// `strict_ask` (see [`super::mcp_runtime::BrokerApprover::always_ask`]).
pub(super) always_ask: bool,
+ /// An `always_ask` turn that asks even with approvals off: it runs something the person
+ /// hasn't reviewed (a Skill Foundry draft or replay).
+ pub(super) strict_ask: bool,
+ /// What kwnt started an `always_ask` turn for, on its cards (`details.started_by`). Its
+ /// label, kept by its continuations, whose own label is kwnt's.
+ pub(super) started_by: Option<String>,
/// Shared with the save step: holds a reply with open choices, and gets the saved message
/// (see [`super::decide`]).
pub(super) hook: Option<super::decide::HookSlot>,
@@ -2131,7 +2141,12 @@ impl TurnOpts {
/// Options for a turn nobody asked for, saved under `label`: every call that could change
/// something asks (see [`TurnOpts::always_ask`]).
pub(super) fn always_asking(label: &str) -> Self {
- TurnOpts { label: Some(label.to_string()), always_ask: true, ..Default::default() }
+ TurnOpts { label: Some(label.to_string()), always_ask: true, started_by: Some(label.to_string()), ..Default::default() }
+ }
+
+ /// [`TurnOpts::always_asking`] that asks even with approvals off (see [`TurnOpts::strict_ask`]).
+ pub(super) fn strict_asking(label: &str) -> Self {
+ TurnOpts { strict_ask: true, ..TurnOpts::always_asking(label) }
}
/// The delivery check (see [`super::delivery_check`]) looks at this turn's reply: not a
@@ -2290,6 +2305,8 @@ pub(super) fn is_reply_by(m: &Message, bot: &str) -> bool {
/// it was routed, so a routed turn's continuation runs on the same agent, effort and tier.
struct Carried {
always_ask: bool,
+ strict_ask: bool,
+ started_by: Option<String>,
delegation_id: Option<String>,
routed: Option<(String, String)>,
routing: Option<serde_json::Value>,
@@ -2309,6 +2326,8 @@ impl Carried {
fn of(o: &TurnOpts) -> Self {
Carried {
always_ask: o.always_ask,
+ strict_ask: o.strict_ask,
+ started_by: o.started_by.clone(),
delegation_id: o.delegation_id.clone(),
routed: o.routed.clone(),
routing: o.routing.clone(),
@@ -2322,8 +2341,8 @@ impl Carried {
}
fn into_opts(self) -> TurnOpts {
- let Carried { always_ask, delegation_id, routed, routing, tier, purpose, task, beside_running, delivery_seen: _, source } = self;
- TurnOpts { always_ask, delegation_id, routed, routing, tier, purpose, task, beside_running, source, ..Default::default() }
+ let Carried { always_ask, strict_ask, started_by, delegation_id, routed, routing, tier, purpose, task, beside_running, delivery_seen: _, source } = self;
+ TurnOpts { always_ask, strict_ask, started_by, delegation_id, routed, routing, tier, purpose, task, beside_running, source, ..Default::default() }
}
/// The delivery check's continuation of the turn: checked against the first turn's `plan`
@@ -3122,6 +3141,8 @@ 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,
+ strict_ask: opts.strict_ask,
+ started_by: opts.started_by.clone(),
rehearse: opts.rehearse.clone(),
purpose: opts.purpose.clone(),
};
@@ -7230,6 +7251,8 @@ mod tests {
purpose: Some("routine".into()),
task: Some(Default::default()),
always_ask: true,
+ strict_ask: true,
+ started_by: Some("Watch".into()),
delegation_id: Some("d1".into()),
nav_prompt: Some("open https://example.org".into()),
fresh_eyes: false,
@@ -7244,6 +7267,8 @@ mod tests {
assert_eq!(next.purpose, first.purpose);
assert_eq!(next.task, first.task);
assert!(next.always_ask);
+ assert!(next.strict_ask, "a strict turn's continuation stays strict");
+ assert_eq!(next.started_by.as_deref(), Some("Watch"), "and its cards still say what started it");
assert_eq!(next.delegation_id.as_deref(), Some("d1"));
assert!(next.nav_prompt.is_none(), "the continuation's prompt is kwnt's, it never moves the browser");
}
diff --git a/src/server/telegram/mod.rs b/src/server/telegram/mod.rs
index 812a271b..bd9ecf90 100644
--- a/src/server/telegram/mod.rs
+++ b/src/server/telegram/mod.rs
@@ -103,7 +103,7 @@ pub fn link_only_reason(details: &Value) -> Option<&'static str> {
}
// A turn kwant started on its own (loose ends, a mission): nobody asked for this step
if details["always_ask"] == true {
- return Some("kwant started this turn on its own, not from your message.");
+ return Some("Started on its own, not by you, so each change asks first.");
}
let kind = ApprovalKind::of(details);
if !TELEGRAM_APPROVABLE.contains(&kind) {
@@ -622,8 +622,8 @@ mod tests {
(json!({"source": "mcp", "tool": "no_server"}), "This is one of kwant's own tools."),
(json!({"source": "mcp", "server": "files", "tool": "x", "tainted": true}), "This bot read text from outside in this turn."),
(json!({"source": "claude_builtin", "tool": "Write", "outside_folder": false, "tainted": true}), "This bot read text from outside in this turn."),
- (json!({"source": "mcp", "server": "files", "tool": "x", "always_ask": true}), "kwant started this turn on its own, not from your message."),
- (json!({"source": "claude_builtin", "tool": "Write", "outside_folder": false, "always_ask": true}), "kwant started this turn on its own, not from your message."),
+ (json!({"source": "mcp", "server": "files", "tool": "x", "always_ask": true}), "Started on its own, not by you, so each change asks first."),
+ (json!({"source": "claude_builtin", "tool": "Write", "outside_folder": false, "always_ask": true}), "Started on its own, not by you, so each change asks first."),
// Both: the outside text is the sharper reason
(json!({"source": "mcp", "server": "files", "tool": "x", "always_ask": true, "tainted": true}), "This bot read text from outside in this turn."),
];
diff --git a/tests/agents_connect_test.rs b/tests/agents_connect_test.rs
index 5ba47a13..c754c030 100644
--- a/tests/agents_connect_test.rs
+++ b/tests/agents_connect_test.rs
@@ -367,6 +367,8 @@ async fn an_approval_card_or_a_question_returns_waiting_on_person() {
conversation: thread_id.clone(),
chat: Some(json!({"thread_id": thread_id})),
always_ask: false,
+ strict_ask: false,
+ started_by: None,
});
let req = ToolApprovalRequest {
kwant_id: env.a.clone(),
diff --git a/tests/approvals_off_test.rs b/tests/approvals_off_test.rs
index b0195d71..bd1964ff 100644
--- a/tests/approvals_off_test.rs
+++ b/tests/approvals_off_test.rs
@@ -86,11 +86,22 @@ async fn put(e: &Env, uri: &str, approvals: &str) -> Value {
/// A live turn of `bot` in the general channel with its own tools; returns its token.
async fn turn(e: &Env, bot: &Kwant) -> (String, String, TempDir) {
- turn_with(e, bot, false).await
+ turn_with(e, bot, Default::default()).await
}
-/// [`turn`]; `always_ask` makes it a turn like the loose-ends owner's.
-async fn turn_with(e: &Env, bot: &Kwant, always_ask: bool) -> (String, String, TempDir) {
+/// A turn kwant started on its own (`always_ask`), labelled like loose-ends' owner's.
+fn kwant_started() -> mcp_runtime::TurnApprovalOpts {
+ mcp_runtime::TurnApprovalOpts { always_ask: true, started_by: Some("Loose ends".into()), ..Default::default() }
+}
+
+/// [`kwant_started`], strict like Skill Foundry's: it still asks with approvals off.
+fn strict_started() -> mcp_runtime::TurnApprovalOpts {
+ mcp_runtime::TurnApprovalOpts { always_ask: true, strict_ask: true, started_by: Some("Skill Foundry".into()), ..Default::default() }
+}
+
+/// [`turn`] with the routed turn's approval options (`always_ask`: a turn like the loose-ends
+/// owner's; `strict_ask`: Skill Foundry's).
+async fn turn_with(e: &Env, bot: &Kwant, opts: mcp_runtime::TurnApprovalOpts) -> (String, String, TempDir) {
let turn_id = uuid::Uuid::new_v4().to_string();
let folder = tempdir().unwrap();
let scope = SelfScope {
@@ -100,7 +111,6 @@ async fn turn_with(e: &Env, bot: &Kwant, always_ask: bool) -> (String, String, T
turn_id: Some(turn_id.clone()),
..Default::default()
};
- let opts = mcp_runtime::TurnApprovalOpts { always_ask, ..Default::default() };
let (_, token) =
mcp_runtime::prepare_turn_with_opts(&e.state, bot, Some(turn_id.clone()), Some(folder.path().to_path_buf()), Some(scope), opts)
.await
@@ -120,12 +130,13 @@ async fn turn_with(e: &Env, bot: &Kwant, always_ask: bool) -> (String, String, T
/// What claude's permission prompt gets back for `Bash {command}`: `Some(allowed)` when kwnt
/// answers without a card, `None` when it shows one (the card is then denied, to end the wait).
async fn ask_bash(e: &Env, bot: &Kwant, command: &str) -> Option<bool> {
- ask_tool(e, bot, "Bash", json!({"command": command}), false).await
+ ask_with(e, bot, "Bash", json!({"command": command}), Default::default()).await.ok()
}
-/// [`ask_bash`] for any tool, in a turn that may be `always_ask`.
-async fn ask_tool(e: &Env, bot: &Kwant, tool: &str, input: Value, always_ask: bool) -> Option<bool> {
- let (turn_id, token, _folder) = turn_with(e, bot, always_ask).await;
+/// [`ask_bash`] for any tool, in a turn with `opts`: `Ok(allowed)` when kwnt answers without a card,
+/// `Err(details)` with the card's details when it shows one (then denied, to end the wait).
+async fn ask_with(e: &Env, bot: &Kwant, tool: &str, input: Value, opts: mcp_runtime::TurnApprovalOpts) -> Result<bool, Value> {
+ let (turn_id, token, _folder) = turn_with(e, bot, opts).await;
let mut events = e.state.event_sender.subscribe();
let ask = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "approve",
"arguments": {"tool_name": tool, "input": input, "tool_use_id": "tu_1"}}});
@@ -147,12 +158,12 @@ async fn ask_tool(e: &Env, bot: &Kwant, tool: &str, input: Value, always_ask: bo
(true, None) => {
let (status, v) = (&mut prompt).await.unwrap();
assert_eq!(status, StatusCode::OK, "{v}");
- Some(v["result"]["content"][0]["text"].as_str().unwrap().contains(r#""behavior":"allow""#))
+ Ok(v["result"]["content"][0]["text"].as_str().unwrap().contains(r#""behavior":"allow""#))
}
- (false, Some(id)) => {
+ (false, Some((id, details))) => {
assert!(e.state.broker.resolve(&id, ApprovalDecision::Deny).await);
prompt.await.unwrap();
- None
+ Err(details)
}
(answered, carded) => panic!("answered {answered} with card {carded:?} (15 s)"),
};
@@ -161,12 +172,12 @@ async fn ask_tool(e: &Env, bot: &Kwant, tool: &str, input: Value, always_ask: bo
outcome
}
-/// The id of an approval card among the events received so far, if one was shown.
-fn card_in(events: &mut tokio::sync::broadcast::Receiver<RuntimeEvent>) -> Option<String> {
+/// The id and details of an approval card among the events received so far, if one was shown.
+fn card_in(events: &mut tokio::sync::broadcast::Receiver<RuntimeEvent>) -> Option<(String, Value)> {
use tokio::sync::broadcast::error::TryRecvError;
loop {
match events.try_recv() {
- Ok(RuntimeEvent::ApprovalRequired { id, .. }) => return Some(id),
+ Ok(RuntimeEvent::ApprovalRequired { id, details, .. }) => return Some((id, details)),
Ok(_) | Err(TryRecvError::Lagged(_)) => continue,
Err(_) => return None,
}
@@ -249,29 +260,70 @@ async fn space_off_runs_bash_without_a_card_and_records_it() {
assert_eq!(ask_bash(&e, &e.bot, "touch y").await, None);
}
-/// The loose-ends owner's turn (nobody asked for it) asks before anything that could change
-/// something, even with approvals off; tools that only read still run.
+/// Oleks's report (0.9.5): with approvals off, a bot's loose-ends turn (kwant started it, nobody
+/// asked) still asked to run `git show`. Off now wins there too: a read-only command, a change in
+/// the folder, a write outside it and kwnt's own changing tools run without a card, on record.
#[tokio::test]
-async fn an_always_ask_turn_asks_even_with_approvals_off() {
+async fn approvals_off_wins_in_a_turn_kwant_started_on_its_own() {
let e = setup().await;
put(&e, "/api/spaces/spc_default/approvals", "off").await;
put(&e, &format!("/api/kwants/{}/approvals", e.bot.id), "off").await;
- assert_eq!(ask_tool(&e, &e.bot, "Bash", json!({"command": "touch x"}), false).await, Some(true), "an ordinary turn runs it");
let self_tool = |name: &str| format!("mcp__{}__{name}", kwnt::mcp::SELF_SERVER_NAME);
+ let oleks = "git show --stat HEAD 2>/dev/null | head -40; grep -rn \"TODO\" . | head -20";
for (tool, input) in [
+ ("Bash".to_string(), json!({"command": oleks})),
("Bash".to_string(), json!({"command": "touch x"})),
("Write".to_string(), json!({"file_path": "/tmp/kwnt-owner-test", "content": "x"})),
(self_tool("routine_create"), json!({"name": "r", "instructions": "x", "schedule": {"type": "daily", "time": "09:00"}})),
(self_tool("delegate"), json!({"to": "Other", "task": "send it"})),
(self_tool("memory_add"), json!({"text": "x"})),
+ (self_tool("search_history"), json!({})),
] {
- assert_eq!(ask_tool(&e, &e.bot, &tool, input, true).await, None, "{tool} must ask in an owner turn");
- }
- for tool in ["search_history", "routine_list", "delegation_status"] {
- assert_eq!(ask_tool(&e, &e.bot, &self_tool(tool), json!({}), true).await, Some(true), "{tool} only reads");
+ assert_eq!(ask_with(&e, &e.bot, &tool, input, kwant_started()).await, Ok(true), "{tool} runs with approvals off");
}
- // "Always allow" for the conversation doesn't carry into an owner turn either
+ let ran = get(&e, "/api/approvals?space=spc_default&status=auto_allowed").await;
+ let bash = ran.as_array().unwrap().iter().find(|r| r["details"]["arguments"]["command"] == oleks).expect("on record");
+ assert_eq!(bash["details"]["always_ask"], true, "{bash}");
+ assert_eq!(bash["details"]["started_by"], "Loose ends", "{bash}");
+ let away = get(&e, "/api/away").await;
+ assert!(away["waiting"].as_array().unwrap().iter().all(|i| i["kind"] != "approval"), "{away}");
+}
+
+/// A strict turn (Skill Foundry's draft: it runs steps the person hasn't reviewed) still asks
+/// with approvals off, and says who started it.
+#[tokio::test]
+async fn a_strict_turn_still_asks_with_approvals_off() {
+ let e = setup().await;
+ put(&e, &format!("/api/kwants/{}/approvals", e.bot.id), "off").await;
+ let card = ask_with(&e, &e.bot, "Bash", json!({"command": "touch x"}), strict_started()).await.expect_err("strict asks");
+ assert_eq!(card["always_ask"], true, "{card}");
+ assert_eq!(card["started_by"], "Skill Foundry", "{card}");
+ // The card says "Skill drafts always ask" from this flag, not from the label
+ assert_eq!(card["strict_ask"], true, "{card}");
+ // Reads still run (claude's own Read never reaches the approver), and so do kwnt's read tools
+ let tool = format!("mcp__{}__search_history", kwnt::mcp::SELF_SERVER_NAME);
+ assert_eq!(ask_with(&e, &e.bot, &tool, json!({}), strict_started()).await, Ok(true));
+}
+
+/// With approvals on, a kwant-started turn still asks, and its card says why: `started_by`.
+/// "Always allow" for the conversation doesn't carry into it either.
+#[tokio::test]
+async fn with_approvals_on_a_kwant_started_turn_asks_and_says_who_started_it() {
+ let e = setup().await;
+ let card = ask_with(&e, &e.bot, "Bash", json!({"command": "touch x"}), kwant_started()).await.expect_err("asks");
+ assert_eq!(card["always_ask"], true, "{card}");
+ assert_eq!(card["started_by"], "Loose ends", "{card}");
+ // Not strict: the card points to Don’t ask instead
+ assert!(card.get("strict_ask").is_none(), "{card}");
+ // An ordinary turn's card has none of them
+ let card = ask_with(&e, &e.bot, "Bash", json!({"command": "touch x"}), Default::default()).await.expect_err("asks");
+ assert!(card.get("always_ask").is_none() && card.get("started_by").is_none() && card.get("strict_ask").is_none(), "{card}");
+ // A blank label adds no line
+ let blank = mcp_runtime::TurnApprovalOpts { started_by: Some(" ".into()), ..kwant_started() };
+ let card = ask_with(&e, &e.bot, "Bash", json!({"command": "touch x"}), blank).await.expect_err("asks");
+ assert!(card.get("started_by").is_none(), "{card}");
+
e.state.broker.allow_for_session(&e.bot.id, &e.general, "Bash").await;
for (always_ask, want) in [(false, ApprovalOutcome::Allowed), (true, ApprovalOutcome::Unanswered)] {
let approver = mcp_runtime::BrokerApprover {
@@ -283,6 +335,8 @@ async fn an_always_ask_turn_asks_even_with_approvals_off() {
conversation: e.general.clone(),
chat: None,
always_ask,
+ strict_ask: false,
+ started_by: None,
};
let req = ToolApprovalRequest {
kwant_id: e.bot.id.clone(),
@@ -296,11 +350,127 @@ async fn an_always_ask_turn_asks_even_with_approvals_off() {
smart: None,
payment: None,
};
- put(&e, &format!("/api/kwants/{}/approvals", e.bot.id), "ask").await;
assert_eq!(approver.decide(req).await, want, "always_ask {always_ask}");
}
}
+/// "Ask only when risky" in a kwant-started turn: a command that only reads runs; anything that
+/// changes something asks. A strict turn asks for both.
+#[tokio::test]
+async fn smart_lets_a_read_only_command_through_in_a_kwant_started_turn() {
+ let e = setup().await;
+ e.state.db.set_kwant_approvals(&e.bot.id, "smart").await.unwrap();
+ let bash = |c: &str| json!({"command": c});
+ assert_eq!(ask_with(&e, &e.bot, "Bash", bash("git show --stat HEAD"), kwant_started()).await, Ok(true));
+ assert_eq!(ask_with(&e, &e.bot, "Bash", bash("grep -rn TODO . | head -20"), kwant_started()).await, Ok(true));
+ for command in ["rm -rf x", "touch x", "git add -A", "git show HEAD > out.txt"] {
+ assert!(ask_with(&e, &e.bot, "Bash", bash(command), kwant_started()).await.is_err(), "{command} asks");
+ }
+ assert!(ask_with(&e, &e.bot, "Bash", bash("git show --stat HEAD"), strict_started()).await.is_err(), "strict asks");
+ // An ordinary turn: smart's own rules, unchanged (an in-folder `touch` is not risky)
+ assert_eq!(ask_with(&e, &e.bot, "Bash", bash("touch x"), Default::default()).await, Ok(true));
+}
+
+// ── Must-hold 2 (#569, 0.9.8): "Don't ask" still asks at the floors in a kwant-started turn ──
+// Each runs through the real permission route in a turn started like Loose ends' (not strict):
+// approvals off lets an ordinary change through, and the floor still raises a card that says
+// who started the turn. Flight School's is in flight_school_test.rs (it needs a claimed task).
+
+#[tokio::test]
+async fn dont_ask_still_asks_for_a_payment_in_a_kwant_started_turn() {
+ let e = setup().await;
+ put(&e, &format!("/api/kwants/{}/approvals", e.bot.id), "off").await;
+ let bash = |c: &str| json!({"command": c});
+ assert_eq!(ask_with(&e, &e.bot, "Bash", bash("touch x"), kwant_started()).await, Ok(true), "off runs an ordinary change");
+ let stripe = "curl -X POST https://api.stripe.com/v1/charges -u sk_test_x: -d amount=100 -d currency=usd";
+ let card = ask_with(&e, &e.bot, "Bash", bash(stripe), kwant_started()).await.expect_err("a payment asks");
+ assert!(card["payment_reason"].as_str().is_some_and(|r| r.contains("stripe.com")), "{card}");
+ assert_eq!(card["started_by"], "Loose ends", "{card}");
+}
+
+#[tokio::test]
+async fn dont_ask_still_asks_at_the_production_floor_in_a_kwant_started_turn() {
+ let e = setup().await;
+ put(&e, &format!("/api/kwants/{}/approvals", e.bot.id), "off").await;
+ let space = e.state.db.get_kwant(&e.bot.id).await.unwrap().unwrap().space_id;
+ e.state.db.put_dev_mode(&space, true, "demo-org/demo-app", "main", None, None).await.unwrap();
+ let bash = |c: &str| json!({"command": c});
+ assert_eq!(ask_with(&e, &e.bot, "Bash", bash("touch notes.txt"), kwant_started()).await, Ok(true), "off runs an ordinary change");
+ for command in ["git push origin main", "sqlite3 demo.db 'DROP TABLE demo_auto'"] {
+ let card = ask_with(&e, &e.bot, "Bash", bash(command), kwant_started()).await.expect_err(command);
+ assert!(card["prod_floor"].is_object(), "{command}: {card}");
+ assert_eq!(card["started_by"], "Loose ends", "{command}: {card}");
+ }
+}
+
+// ── Must-hold 4 (#569, 0.9.8): "Ask only when risky" in a kwant-started turn ──
+// Only a shell command that just reads runs without a card; each of these asks, even where an
+// ordinary turn's smart check alone would let it through (it is in the bot's folder).
+
+/// The card `command` raises under "Ask only when risky" in a turn kwant started on its own.
+async fn smart_card(command: &str) -> Value {
+ let e = setup().await;
+ e.state.db.set_kwant_approvals(&e.bot.id, "smart").await.unwrap();
+ let card = match ask_with(&e, &e.bot, "Bash", json!({"command": command}), kwant_started()).await {
+ Err(card) => card,
+ Ok(allowed) => panic!("`{command}` must ask in a kwant-started turn, answered without a card (allowed {allowed})"),
+ };
+ assert_eq!(card["always_ask"], true, "{command}: {card}");
+ assert_eq!(card["started_by"], "Loose ends", "{command}: {card}");
+ card
+}
+
+#[tokio::test]
+async fn risky_only_runs_git_status_and_ls_without_a_card_in_a_kwant_started_turn() {
+ let e = setup().await;
+ e.state.db.set_kwant_approvals(&e.bot.id, "smart").await.unwrap();
+ for command in ["git status", "ls", "ls -la", "git status --short && ls"] {
+ assert_eq!(ask_with(&e, &e.bot, "Bash", json!({"command": command}), kwant_started()).await, Ok(true), "{command}");
+ }
+ let ran = get(&e, "/api/approvals?space=spc_default&status=auto_allowed").await;
+ let row = ran.as_array().unwrap().iter().find(|r| r["details"]["arguments"]["command"] == "git status").expect("on record");
+ assert_eq!(row["details"]["started_by"], "Loose ends", "{row}");
+}
+
+#[tokio::test]
+async fn risky_only_asks_for_rm_rf_in_a_kwant_started_turn() {
+ smart_card("rm -rf build").await;
+}
+
+#[tokio::test]
+async fn risky_only_asks_for_git_add_dot_in_a_kwant_started_turn() {
+ smart_card("git add .").await;
+}
+
+#[tokio::test]
+async fn risky_only_asks_for_echo_into_a_file_in_a_kwant_started_turn() {
+ smart_card("echo x > f").await;
+}
+
+#[tokio::test]
+async fn risky_only_asks_for_git_dash_c_in_a_kwant_started_turn() {
+ // A global option before the subcommand: `-C` points git at another repository
+ smart_card("git -C . status").await;
+}
+
+#[tokio::test]
+async fn risky_only_asks_for_git_diff_output_in_a_kwant_started_turn() {
+ smart_card("git diff --output=f").await;
+}
+
+#[tokio::test]
+async fn risky_only_asks_for_rg_pre_in_a_kwant_started_turn() {
+ // `--pre` runs a program on every file it searches
+ smart_card("rg --pre cat x").await;
+}
+
+#[tokio::test]
+async fn risky_only_asks_for_a_var_prefix_in_a_kwant_started_turn() {
+ // LC_ALL is one smart's own check allows, so this is the read-only rule asking
+ smart_card("LC_ALL=C ls").await;
+ smart_card("GIT_EXTERNAL_DIFF=./x git diff").await;
+}
+
#[tokio::test]
async fn a_bot_override_beats_the_space_both_ways() {
let e = setup().await;
diff --git a/tests/auditor_test.rs b/tests/auditor_test.rs
index 83b2b634..c6ff944e 100644
--- a/tests/auditor_test.rs
+++ b/tests/auditor_test.rs
@@ -826,6 +826,8 @@ async fn in_audit_turn(e: &Env, bot: &Kwant, tool: &str, args: Value) -> Approva
conversation: e.general.clone(),
chat: None,
always_ask: true,
+ strict_ask: false,
+ started_by: None,
};
let approver = SelfToolsApprover { inner: std::sync::Arc::new(broker), always_ask: true, browser: None };
let req = ToolApprovalRequest {
@@ -850,7 +852,7 @@ async fn approval_rows(e: &Env) -> Vec<(String, String)> {
}
/// With Approvals off, `audit_challenge` and `audit_rebut` run without a card (logged
-/// `auto_allowed`); every other tool of an audit turn still asks. With approvals on or "Ask only
+/// `auto_allowed`), and so does every other tool of an audit turn (0.9.7). With approvals on or "Ask only
/// when risky", each audit call asks.
#[tokio::test]
async fn audit_calls_follow_the_approval_mode() {
@@ -879,8 +881,9 @@ async fn audit_calls_follow_the_approval_mode() {
let auto = |tool: &str| (tool.to_string(), "auto_allowed".to_string());
assert_eq!(approval_rows(&e).await, vec![auto("audit_challenge"), auto("audit_rebut")], "no card, both on record");
- // Every other tool of an audit turn still asks, approvals off or not
- assert_eq!(in_audit_turn(&e, &challenger, "memory_add", json!({"text": "x"})).await, ApprovalOutcome::Unanswered);
+ // Every other tool of an audit turn follows approvals off too (0.9.7: off means off, also in
+ // a turn kwnt started on its own)
+ assert_eq!(in_audit_turn(&e, &challenger, "memory_add", json!({"text": "x"})).await, ApprovalOutcome::Allowed);
// Approvals on, or "Ask only when risky": one card per audit call, as before
for mode in ["ask", "smart"] {
@@ -890,7 +893,7 @@ async fn audit_calls_follow_the_approval_mode() {
}
let rows = approval_rows(&e).await;
let cards: Vec<&str> = rows.iter().filter(|(_, s)| s != "auto_allowed").map(|(t, _)| t.as_str()).collect();
- assert_eq!(cards, ["memory_add", "audit_challenge", "audit_challenge"], "{rows:?}");
+ assert_eq!(cards, ["audit_challenge", "audit_challenge"], "{rows:?}");
}
#[tokio::test]
diff --git a/tests/browser_pay_gate_test.rs b/tests/browser_pay_gate_test.rs
index 20216de6..8efa77f0 100644
--- a/tests/browser_pay_gate_test.rs
+++ b/tests/browser_pay_gate_test.rs
@@ -247,6 +247,8 @@ async fn approvals_off_still_cards_a_card_form_click_and_the_shell_api_refuses_i
conversation: "c-pay".into(),
chat: None,
always_ask: false,
+ strict_ask: false,
+ started_by: None,
};
let approver = SelfToolsApprover {
inner: Arc::new(inner),
diff --git a/tests/dev_floor_test.rs b/tests/dev_floor_test.rs
index 546c8e65..1e0c8485 100644
--- a/tests/dev_floor_test.rs
+++ b/tests/dev_floor_test.rs
@@ -23,6 +23,8 @@ fn approver(env: &Env) -> Arc<BrokerApprover> {
conversation: env.a.clone(),
chat: Some(json!({"direct_kwant_id": env.a})),
always_ask: false,
+ strict_ask: false,
+ started_by: None,
})
}
@@ -160,3 +162,35 @@ async fn turning_dev_mode_on_applies_the_floor_at_once() {
assert!(!db.any_dev_mode_on());
assert!(floor_of(7).await.is_none());
}
+
+/// Approvals off now wins in a turn kwant started on its own (0.9.7), but not over the floor:
+/// a push to the watched branch still asks there, while an ordinary command runs.
+#[tokio::test]
+async fn the_floor_still_asks_with_approvals_off_in_a_kwant_started_turn() {
+ let env = setup().await;
+ let space = space_of_a(&env).await;
+ env.state.db.set_kwant_approvals(&env.a, "off").await.unwrap();
+ env.state.db.put_dev_mode(&space, true, "demo-org/demo-app", "main", None, None).await.unwrap();
+ let started = BrokerApprover {
+ db: env.state.db.clone(),
+ data_dir: env.state.config.data_dir.clone(),
+ broker: env.state.broker.clone(),
+ events: env.state.event_sender.clone(),
+ timeout: Duration::from_millis(200),
+ conversation: env.a.clone(),
+ chat: Some(json!({"direct_kwant_id": env.a})),
+ always_ask: true,
+ strict_ask: false,
+ started_by: Some("Loose ends".into()),
+ };
+
+ assert_eq!(started.decide(request(&env, "touch notes.txt")).await, ApprovalOutcome::Allowed);
+ for command in ["git push origin main", "sqlite3 demo.db 'DROP TABLE demo_auto'"] {
+ assert_eq!(started.decide(request(&env, command)).await, ApprovalOutcome::Unanswered, "{command}");
+ let rows = env.state.db.list_approvals(&kwnt::db::spaces::SpaceId::default_space(), Some("waiting"), Some(&env.a)).await.unwrap();
+ let row = rows.into_iter().find(|r| r.parameters.contains(command)).expect("a waiting card");
+ let details: Value = serde_json::from_str(&row.parameters).unwrap();
+ assert!(details["prod_floor"].is_object(), "{command}: {details}");
+ assert_eq!(details["started_by"], "Loose ends");
+ }
+}
diff --git a/tests/flight_school_test.rs b/tests/flight_school_test.rs
index de447b50..b6c095de 100644
--- a/tests/flight_school_test.rs
+++ b/tests/flight_school_test.rs
@@ -209,6 +209,8 @@ fn approver(e: &Env) -> mcp_runtime::BrokerApprover {
conversation: e.general.clone(),
chat: None,
always_ask: false,
+ strict_ask: false,
+ started_by: None,
}
}
@@ -405,6 +407,32 @@ async fn approvals_off_and_smart_allow_still_card_in_sandbox_but_always_allow_co
assert_eq!(strict.decide(request(&e, "github", "create_issue", json!({}))).await, ApprovalOutcome::Unanswered);
}
+/// Must-hold 2 (#569, 0.9.8): with "Don't ask", a turn kwant started on its own (not strict, like
+/// Loose ends') follows Off for ordinary calls but still asks at the bot's Flight School tier, and
+/// the card says who started the turn.
+#[tokio::test]
+async fn dont_ask_still_asks_under_flight_school_in_a_kwant_started_turn() {
+ let e = setup().await;
+ set_approvals(&e, "off").await;
+ let (_tid, _dir) = claimed_task(&e, "general", true).await;
+ let started = mcp_runtime::BrokerApprover { always_ask: true, started_by: Some("Loose ends".into()), ..approver(&e) };
+ // No tier yet: Off wins in this turn
+ assert_eq!(started.decide(request(&e, "github", "create_issue", json!({}))).await, ApprovalOutcome::Allowed);
+ flight_school(&e, true).await;
+ set_tier(&e, "*", "sandbox").await;
+ assert_eq!(started.decide(request(&e, "github", "create_issue", json!({}))).await, ApprovalOutcome::Unanswered);
+ assert_eq!(started.decide(bash(&e, "touch x")).await, ApprovalOutcome::Unanswered);
+ let (_, rows) = call(&e.app, "GET", "/api/approvals", None, None).await;
+ let row = rows
+ .as_array()
+ .unwrap()
+ .iter()
+ .find(|r| r["details"]["tool"] == "create_issue" && r["details"]["tier_reason"].is_string())
+ .expect("the tier card is on record");
+ assert_eq!(row["details"]["started_by"], "Loose ends", "{row}");
+ assert!(row["details"].get("strict_ask").is_none(), "{row}");
+}
+
#[tokio::test]
async fn observe_cards_an_in_folder_write_that_ask_mode_lets_through() {
let e = setup().await;
diff --git a/tests/late_approval_test.rs b/tests/late_approval_test.rs
index 82198f3d..de440d98 100644
--- a/tests/late_approval_test.rs
+++ b/tests/late_approval_test.rs
@@ -21,6 +21,8 @@ fn approver(env: &Env, timeout: Duration) -> Arc<BrokerApprover> {
conversation: env.a.clone(),
chat: Some(json!({"direct_kwant_id": env.a})),
always_ask: false,
+ strict_ask: false,
+ started_by: None,
})
}
@@ -102,6 +104,8 @@ async fn a_grant_runs_once_only_in_its_own_conversation() {
conversation: "some-other-thread".into(),
chat: Some(json!({"thread_id": "some-other-thread"})),
always_ask: false,
+ strict_ask: false,
+ started_by: None,
};
assert_eq!(elsewhere.decide(request(&env, args.clone())).await, ApprovalOutcome::Unanswered);
// Its own conversation can, once (a new description is fine), and only that call
@@ -201,6 +205,8 @@ async fn a_late_allow_on_an_audit_card_runs_nothing() {
conversation: env.a.clone(),
chat: Some(chat),
always_ask: true,
+ strict_ask: false,
+ started_by: None,
});
let mut req = request(&env, json!({"command": "ls AUDIT_LATE_MARK", "description": "list"}));
(req.tool_name, req.tool) = (tool.into(), tool.into());
diff --git a/tests/mcp_gateway_test.rs b/tests/mcp_gateway_test.rs
index 9d650981..5aaec7c2 100644
--- a/tests/mcp_gateway_test.rs
+++ b/tests/mcp_gateway_test.rs
@@ -186,6 +186,8 @@ async fn gateway_calls_wait_for_the_approval_card() {
conversation: "conv-test".into(),
chat: None,
always_ask: false,
+ strict_ask: false,
+ started_by: None,
});
register(&state, "card-tok", approver).await;
let mut events = state.event_sender.subscribe();
@@ -246,6 +248,8 @@ async fn ending_the_turn_cancels_a_call_waiting_for_its_card() {
conversation: "conv-test".into(),
chat: None,
always_ask: false,
+ strict_ask: false,
+ started_by: None,
});
let marker = format!("KWNT_TEST_MARK_{}", uuid::Uuid::new_v4().simple());
let mut server = echo_server();
diff --git a/tests/mcp_runtime_test.rs b/tests/mcp_runtime_test.rs
index cef615a2..5a870113 100644
--- a/tests/mcp_runtime_test.rs
+++ b/tests/mcp_runtime_test.rs
@@ -117,6 +117,8 @@ fn approver(state: &AppState, timeout: Duration) -> Arc<BrokerApprover> {
conversation: "conv-test".into(),
chat: None,
always_ask: false,
+ strict_ask: false,
+ started_by: None,
})
}
diff --git a/tests/payment_floor_test.rs b/tests/payment_floor_test.rs
index 65f51b18..9892f063 100644
--- a/tests/payment_floor_test.rs
+++ b/tests/payment_floor_test.rs
@@ -170,6 +170,8 @@ fn approver(e: &Env, timeout: Duration) -> mcp_runtime::BrokerApprover {
conversation: e.general.clone(),
chat: None,
always_ask: false,
+ strict_ask: false,
+ started_by: None,
}
}
@@ -249,6 +251,19 @@ async fn smart_allow_and_always_allow_never_skip_a_payment() {
}
}
+/// Approvals off wins in a turn kwant started on its own (0.9.7), but never over a payment.
+#[tokio::test]
+async fn a_payment_still_asks_with_approvals_off_in_a_kwant_started_turn() {
+ let e = setup().await;
+ set_approvals(&e, "off").await;
+ let a = mcp_runtime::BrokerApprover { always_ask: true, started_by: Some("Loose ends".into()), ..approver(&e, Duration::from_millis(200)) };
+ assert_eq!(a.decide(bash(&e, "touch x")).await, ApprovalOutcome::Allowed);
+ assert_eq!(a.decide(bash(&e, STRIPE_POST)).await, ApprovalOutcome::Unanswered);
+ let (_, rows) = call(&e.app, "GET", "/api/approvals", None, None).await;
+ let row = rows.as_array().unwrap().iter().find(|r| r["details"]["payment_reason"].is_string()).expect("the card is on record");
+ assert_eq!(row["details"]["started_by"], "Loose ends", "{row}");
+}
+
#[tokio::test]
async fn always_allow_on_a_payment_card_covers_that_one_call() {
let e = setup().await;
diff --git a/tests/restart_cards_test.rs b/tests/restart_cards_test.rs
index c0d183b2..fa6230ab 100644
--- a/tests/restart_cards_test.rs
+++ b/tests/restart_cards_test.rs
@@ -45,6 +45,8 @@ async fn card_from_before_the_restart(env: &Env, args: Value) -> String {
conversation: env.a.clone(),
chat: Some(json!({"direct_kwant_id": env.a})),
always_ask: false,
+ strict_ask: false,
+ started_by: None,
};
let req = ToolApprovalRequest {
kwant_id: env.a.clone(),
@@ -230,6 +232,8 @@ async fn card_by(env: &Env, kwant: &str) -> String {
conversation: kwant.to_string(),
chat: Some(json!({"direct_kwant_id": kwant})),
always_ask: false,
+ strict_ask: false,
+ started_by: None,
};
let req = ToolApprovalRequest {
kwant_id: kwant.to_string(),
diff --git a/tests/telegram_test.rs b/tests/telegram_test.rs
index 09b51c9c..bf7548df 100644
--- a/tests/telegram_test.rs
+++ b/tests/telegram_test.rs
@@ -738,6 +738,8 @@ fn ask_through_the_approver(env: &Env, turn: &str, tool: &str, always_ask: bool)
conversation: env.a.clone(),
chat: Some(json!({"direct_kwant_id": env.a})),
always_ask,
+ strict_ask: false,
+ started_by: None,
};
let req = kwnt::mcp::ToolApprovalRequest {
kwant_id: env.a.clone(),
@@ -780,7 +782,7 @@ async fn a_turn_that_read_outside_text_or_that_kwant_started_has_no_allow_once()
let started = ask_through_the_approver(&env, "turn-tg-started", "started_lookup", true);
let k = tg.wait_send(&bot, |c| c.text().contains("<code>started_lookup</code>")).await;
assert!(k.callbacks().is_empty(), "{:?}", k.buttons());
- assert!(k.text().contains("kwant started this turn on its own, not from your message. Approve it in kwant."), "{}", k.text());
+ assert!(k.text().contains("Started on its own, not by you, so each change asks first. Approve it in kwant."), "{}", k.text());
assert!(!k.text().contains("read text from outside"), "{}", k.text());
kwnt::server::missions::truth_ledger::end_turn("turn-tg-taint");