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.

request-parts: the done card names the part of the request with no check (#619)

Oleksandr Ivanchenko7e4809698bd9
diff --git a/src/server/inbox_done.rs b/src/server/inbox_done.rs
index a5a3282b..923ceff1 100644
--- a/src/server/inbox_done.rs
+++ b/src/server/inbox_done.rs
@@ -38,7 +38,7 @@ use crate::db::spaces::SpaceId;
use crate::db::DbError;
use crate::server::missions::autofix::{redact, redact_value};
use crate::server::missions::checkpoints::NO_EFFECT_TOOLS;
-use crate::server::missions::contract::{Contract, Criterion};
+use crate::server::missions::contract::{Contract, Criterion, Part};
use chrono::{DateTime, Duration, Utc};
use serde_json::{json, Value};
use std::collections::HashMap;
@@ -578,12 +578,13 @@ const CHECK_WHAT_CHARS: usize = 120;
const CHECK_EVIDENCE_CHARS: usize = 300;
const CHECK_LINE_CHARS: usize = 240;
-/// One task's stored checks: its outcome checks, its contract's criteria and the evidence still
-/// attached to it, and the names of the bots that reviewed it.
+/// One task's stored checks: its outcome checks, its contract's criteria and the parts of the
+/// request they prove, the evidence still attached to it, and the names of the bots that reviewed it.
#[derive(Debug, Default, Clone)]
pub struct TaskChecks {
pub checks: Vec<OutcomeCheck>,
pub criteria: Vec<Criterion>,
+ pub parts: Vec<Part>,
pub evidence: Vec<Evidence>,
pub names: HashMap<String, String>,
}
@@ -591,7 +592,8 @@ pub struct TaskChecks {
async fn task_checks(state: &AppState, task_id: &str) -> Result<TaskChecks, DbError> {
let checks = state.db.list_checks(task_id).await?;
let evidence = state.db.list_evidence(task_id).await?;
- let criteria = state.db.get_contract(task_id).await?.and_then(|r| serde_json::from_str::<Contract>(&r.body).ok()).map(|c| c.criteria).unwrap_or_default();
+ let contract = state.db.get_contract(task_id).await?.and_then(|r| serde_json::from_str::<Contract>(&r.body).ok()).unwrap_or_default();
+ let (criteria, parts) = (contract.criteria, contract.parts);
let mut names = HashMap::new();
for by in checks.iter().filter(|c| c.kind == "peer_review").filter_map(|c| c.checked_by.as_deref()) {
if !names.contains_key(by) {
@@ -600,7 +602,7 @@ async fn task_checks(state: &AppState, task_id: &str) -> Result<TaskChecks, DbEr
}
}
}
- Ok(TaskChecks { checks, criteria, evidence, names })
+ Ok(TaskChecks { checks, criteria, parts, evidence, names })
}
/// The checks of the task a routine run or hand-off made, if it made one.
@@ -833,8 +835,9 @@ fn state_of(items: &[CheckItem]) -> &'static str {
}
/// The card's one line: the state, then a short phrase per source (checks, criteria, delivery).
-fn checked_line(state: &str, items: &[CheckItem]) -> String {
- if items.is_empty() {
+/// With the request's parts written (`parts_lead`), they lead instead of the criteria.
+fn checked_line(state: &str, items: &[CheckItem], parts_lead: Option<String>) -> String {
+ if items.is_empty() && parts_lead.is_none() {
return "Not checked: nothing verified this result.".into();
}
let count = |of: &[&CheckItem], r: &str| of.iter().filter(|i| i.result == r).count();
@@ -864,6 +867,7 @@ fn checked_line(state: &str, items: &[CheckItem]) -> String {
let criteria: Vec<&CheckItem> = items.iter().filter(|i| i.from == Fed::Criterion).collect();
let (met, not_met, claims) = (count(&criteria, "passed"), count(&criteria, "failed"), criteria.iter().filter(|i| i.claim).count());
match criteria.len() {
+ _ if parts_lead.is_some() => {}
0 => {}
1 if not_met == 1 => parts.push("the criterion is not met".into()),
1 if met == 1 => parts.push("the criterion has evidence".into()),
@@ -885,7 +889,67 @@ fn checked_line(state: &str, items: &[CheckItem]) -> String {
"failed" => "Failed",
_ => "Not checked",
};
- cut(&format!("{prefix}: {}.", parts.join(", ")), CHECK_LINE_CHARS)
+ let body = match (parts_lead, parts.is_empty()) {
+ (Some(lead), true) => lead,
+ (Some(lead), false) => format!("{lead}; {}", parts.join(", ")),
+ (None, _) => parts.join(", "),
+ };
+ cut(&format!("{prefix}: {body}."), CHECK_LINE_CHARS)
+}
+
+/// One part of the request on the card (request-parts).
+#[derive(Debug, Clone)]
+struct PartRow {
+ text: String,
+ result: &'static str,
+ criteria: Vec<Value>,
+}
+
+/// A task's parts with their results, and whether the lead or the person wrote them. A written
+/// part passed only when every criterion linked to it passed by [`criterion_items`]' rules (so a
+/// claim never counts); one criterion not met fails it; no linked criterion leaves it
+/// `not_checked`. With no parts written each criterion is its own part, as before parts existed.
+fn part_rows(t: &TaskChecks) -> (Vec<PartRow>, bool) {
+ let rows: Vec<(&str, CheckItem)> = t.criteria.iter().map(|k| k.id.as_str()).zip(criterion_items(t)).collect();
+ let crit = |id: &str, i: &CheckItem| json!({"id": id, "text": i.what, "result": i.result});
+ if t.parts.is_empty() {
+ let parts = rows.iter().map(|(id, i)| PartRow { text: i.what.clone(), result: i.result, criteria: vec![crit(id, i)] }).collect();
+ return (parts, false);
+ }
+ let parts = t
+ .parts
+ .iter()
+ .map(|p| {
+ let linked: Vec<&(&str, CheckItem)> = p.criteria.iter().filter_map(|id| rows.iter().find(|(k, _)| k == id)).collect();
+ let result = if linked.iter().any(|(_, i)| i.result == "failed") {
+ "failed"
+ } else if !linked.is_empty() && linked.iter().all(|(_, i)| i.result == "passed") {
+ "passed"
+ } else {
+ "not_checked"
+ };
+ PartRow { text: masked_line(&p.text, CHECK_WHAT_CHARS), result, criteria: linked.iter().map(|(id, i)| crit(id, i)).collect() }
+ })
+ .collect();
+ (parts, true)
+}
+
+/// The line's lead when parts are written: "3 of 4 parts checked; "send it to Ana": no check",
+/// naming at most one part (a failed one first). `None` for a single part that passed: the
+/// sources say it.
+fn parts_phrase(parts: &[PartRow]) -> Option<String> {
+ let named = parts
+ .iter()
+ .find(|p| p.result == "failed")
+ .map(|p| format!("\"{}\": not met", cut(&p.text, 60)))
+ .or_else(|| parts.iter().find(|p| p.result != "passed").map(|p| format!("\"{}\": no check", cut(&p.text, 60))));
+ let passed = parts.iter().filter(|p| p.result == "passed").count();
+ match (parts.len(), named) {
+ (0, _) | (1, None) => None,
+ (1, Some(n)) => Some(n),
+ (total, None) => Some(format!("{passed} of {total} parts checked")),
+ (total, Some(n)) => Some(format!("{passed} of {total} parts checked; {n}")),
+ }
}
/// A done item's `checked`: `{state, items, items_dropped, line}`. `items` come only from what
@@ -893,22 +957,40 @@ fn checked_line(state: &str, items: &[CheckItem]) -> String {
/// check's verdict on the result message. `state` is `failed` when any item failed, `checked`
/// when all passed, `partly` when some did, else `not_checked` (also with no items at all). At
/// most [`CHECKED_MAX`] items, failed first; the state and line count them all.
+///
+/// With criteria there are also `parts` (`{text, result, criteria}`, in the request's order),
+/// `parts_checked`, `parts_total` and `parts_written`. A part of the request with no passing
+/// check keeps the state from `checked`; written parts lead the line.
pub fn checked(tasks: &[TaskChecks], result_meta: Option<&Value>) -> Value {
let mut items: Vec<CheckItem> = Vec::new();
+ let (mut parts, mut written) = (Vec::new(), false);
for t in tasks {
items.extend(check_items(t));
items.extend(criterion_items(t));
+ let (p, w) = part_rows(t);
+ parts.extend(p);
+ written |= w;
}
items.extend(result_meta.and_then(delivery_item));
- let state = state_of(&items);
- let line = checked_line(state, &items);
+ let mut state = state_of(&items);
+ if state == "checked" && parts.iter().any(|p| p.result != "passed") {
+ state = "partly";
+ }
+ let line = checked_line(state, &items, if written { parts_phrase(&parts) } else { None });
// Failed first, the rest in source order (a stable sort)
let mut shown = items;
shown.sort_by_key(|i| i.result != "failed");
let dropped = shown.len().saturating_sub(CHECKED_MAX);
shown.truncate(CHECKED_MAX);
let rows: Vec<Value> = shown.iter().map(|i| json!({"what": i.what, "how": i.how, "result": i.result, "evidence": i.evidence})).collect();
- json!({"state": state, "items": rows, "items_dropped": dropped, "line": line})
+ let mut out = json!({"state": state, "items": rows, "items_dropped": dropped, "line": line});
+ if !parts.is_empty() {
+ out["parts_checked"] = json!(parts.iter().filter(|p| p.result == "passed").count());
+ out["parts_total"] = json!(parts.len());
+ out["parts_written"] = json!(written);
+ out["parts"] = Value::Array(parts.into_iter().map(|p| json!({"text": p.text, "result": p.result, "criteria": p.criteria})).collect());
+ }
+ out
}
#[cfg(test)]
@@ -1253,4 +1335,97 @@ mod tests {
assert_eq!((v["items"][1]["what"].as_str(), v["items"][1]["how"].as_str()), (Some("Your own check"), Some("you checked it")));
assert_eq!(v["line"], "Checked: 2 of 2 checks passed.");
}
+
+ // ---- request-parts ----
+
+ fn part(id: &str, text: &str, criteria: &[&str]) -> Part {
+ Part { id: id.into(), text: text.into(), criteria: criteria.iter().map(|c| c.to_string()).collect() }
+ }
+
+ fn part_results(v: &Value) -> Vec<&str> {
+ v["parts"].as_array().unwrap().iter().map(|p| p["result"].as_str().unwrap()).collect()
+ }
+
+ #[test]
+ fn a_part_with_no_check_keeps_the_card_from_reading_checked() {
+ let t = TaskChecks {
+ criteria: vec![criterion("c1", "PDF is in the folder", "met", &["ev1"])],
+ parts: vec![part("p1", "make the PDF", &["c1"]), part("p2", "send it to Ana", &[])],
+ evidence: vec![evidence("ev1", "report.pdf", None)],
+ ..Default::default()
+ };
+ let v = checked(std::slice::from_ref(&t), None);
+ assert_eq!(v["state"], "partly", "every item passed, but a part has no check");
+ assert_eq!(v["line"], "Partly checked: 1 of 2 parts checked; \"send it to Ana\": no check.");
+ assert_eq!((v["parts_checked"].as_i64(), v["parts_total"].as_i64(), v["parts_written"].as_bool()), (Some(1), Some(2), Some(true)));
+ assert_eq!(v["parts"][0], json!({"text": "make the PDF", "result": "passed", "criteria": [{"id": "c1", "text": "PDF is in the folder", "result": "passed"}]}));
+ assert_eq!(v["parts"][1], json!({"text": "send it to Ana", "result": "not_checked", "criteria": []}));
+ // The same when part 2 has a criterion with no evidence yet, and the checks follow the parts
+ let mut t2 = t.clone();
+ t2.criteria.push(criterion("c2", "Ana has the email", "not_checked", &[]));
+ t2.parts[1].criteria = vec!["c2".into()];
+ t2.checks = vec![check("command", json!({"command": "test -f report.pdf"}), "passed", None)];
+ let v = checked(&[t2], None);
+ assert_eq!(v["state"], "partly");
+ assert_eq!(v["line"], "Partly checked: 1 of 2 parts checked; \"send it to Ana\": no check; test -f report.pdf passed.");
+ // Every part proved: checked
+ let mut t3 = t;
+ t3.criteria.push(criterion("c2", "Ana has the email", "met", &["ev2"]));
+ t3.evidence.push(evidence("ev2", "Sent mail", None));
+ t3.parts[1].criteria = vec!["c2".into()];
+ let v = checked(&[t3], None);
+ assert_eq!((v["state"].as_str(), v["line"].as_str()), (Some("checked"), Some("Checked: 2 of 2 parts checked.")));
+ }
+
+ #[test]
+ fn a_part_proved_only_by_a_claim_is_not_checked() {
+ let t = TaskChecks {
+ criteria: vec![criterion("c1", "PDF is in the folder", "met", &["ev1"]), criterion("c2", "Ana has the email", "met", &[])],
+ parts: vec![part("p1", "make the PDF", &["c1"]), part("p2", "send it to Ana", &["c2"])],
+ evidence: vec![evidence("ev1", "report.pdf", None)],
+ ..Default::default()
+ };
+ let v = checked(&[t], None);
+ assert_eq!(part_results(&v), ["passed", "not_checked"]);
+ assert_eq!(v["parts"][1]["criteria"][0]["result"], "not_checked");
+ assert_eq!(v["state"], "partly");
+ assert_eq!(v["line"], "Partly checked: 1 of 2 parts checked; \"send it to Ana\": no check.");
+ // Nothing passed at all: not checked
+ let t = TaskChecks { criteria: vec![criterion("c1", "Ana has the email", "met", &[])], parts: vec![part("p1", "make the PDF", &[]), part("p2", "send it to Ana", &["c1"])], ..Default::default() };
+ let v = checked(&[t], None);
+ assert_eq!((v["state"].as_str(), v["line"].as_str()), (Some("not_checked"), Some("Not checked: 0 of 2 parts checked; \"make the PDF\": no check.")));
+ }
+
+ #[test]
+ fn a_part_with_a_criterion_not_met_fails() {
+ let t = TaskChecks {
+ criteria: vec![criterion("c1", "PDF is in the folder", "met", &["ev1"]), criterion("c2", "Ana has the email", "met", &["ev1"]), criterion("c3", "Under 2 MB", "not_met", &[])],
+ parts: vec![part("p1", "make the PDF", &["c1", "c3"]), part("p2", "send it to Ana", &["c2"]), part("p3", "by Friday", &[])],
+ evidence: vec![evidence("ev1", "report.pdf", None)],
+ ..Default::default()
+ };
+ let v = checked(&[t], None);
+ assert_eq!(part_results(&v), ["failed", "passed", "not_checked"]);
+ assert_eq!(v["state"], "failed");
+ assert_eq!(v["line"], "Failed: 1 of 3 parts checked; \"make the PDF\": not met.");
+ // One written part: it is named, not counted
+ let t = TaskChecks { criteria: vec![criterion("c1", "PDF is in the folder", "met", &["ev1"])], parts: vec![part("p1", "make the PDF and send it to Ana", &[])], evidence: vec![evidence("ev1", "report.pdf", None)], ..Default::default() };
+ assert_eq!(checked(&[t], None)["line"], "Partly checked: \"make the PDF and send it to Ana\": no check.");
+ }
+
+ #[test]
+ fn no_parts_written_reads_one_part_per_criterion_and_the_same_line() {
+ let t = TaskChecks { criteria: vec![criterion("c1", "The site answers 200", "met", &["ev1"])], evidence: vec![evidence("ev1", "Status page", Some("https://booktun.ing/health"))], ..Default::default() };
+ let v = checked(&[t], None);
+ assert_eq!((v["state"].as_str(), v["line"].as_str()), (Some("checked"), Some("Checked: the criterion has evidence.")));
+ assert_eq!(v["parts"], json!([{"text": "The site answers 200", "result": "passed", "criteria": [{"id": "c1", "text": "The site answers 200", "result": "passed"}]}]));
+ assert_eq!((v["parts_checked"].as_i64(), v["parts_total"].as_i64(), v["parts_written"].as_bool()), (Some(1), Some(1), Some(false)));
+ let t = TaskChecks { criteria: vec![criterion("c1", "Tests pass", "met", &["ev1"]), criterion("c2", "Docs updated", "met", &[])], evidence: vec![evidence("ev1", "CI run", None)], ..Default::default() };
+ let v = checked(&[t], None);
+ assert_eq!(v["line"], "Partly checked: 1 of 2 criteria have evidence.");
+ assert_eq!(part_results(&v), ["passed", "not_checked"]);
+ // No contract at all: no parts keys
+ let v = checked(&[TaskChecks { checks: vec![check("command", json!({"command": "make"}), "passed", None)], ..Default::default() }], None);
+ assert!(v.get("parts").is_none() && v.get("parts_total").is_none(), "{v}");
+ }
}
diff --git a/src/server/missions/contract.rs b/src/server/missions/contract.rs
index 9f44d4e8..89e1effd 100644
--- a/src/server/missions/contract.rs
+++ b/src/server/missions/contract.rs
@@ -15,6 +15,8 @@ pub const MAX_ITEMS: usize = 20;
pub const MAX_FLAGS: usize = 8;
pub const MAX_TEXT: usize = 300;
pub const MAX_FLAG_CHARS: usize = 40;
+/// Parts of the person's request on one contract.
+pub const MAX_PARTS: usize = 12;
/// Criteria derived from the acceptance, one per line.
pub const MAX_FROM_ACCEPTANCE: usize = 8;
pub const TOOL: &str = "task_contract";
@@ -47,6 +49,18 @@ pub struct Issue {
pub by: String,
}
+/// One part of the person's request, in their own words, and the criteria that prove it
+/// (request-parts, roadmap Next 12a). The parts together cover every word of the request; a part
+/// with no criterion linked has no check.
+#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
+pub struct Part {
+ pub id: String,
+ pub text: String,
+ /// Ids of this contract's criteria.
+ #[serde(default)]
+ pub criteria: Vec<String>,
+}
+
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Contract {
#[serde(default)]
@@ -57,6 +71,10 @@ pub struct Contract {
pub open_issues: Vec<Issue>,
#[serde(default)]
pub risk_flags: Vec<String>,
+ /// Written by the lead or the person; stored before this field, a contract has none, and each
+ /// criterion reads as its own part.
+ #[serde(default)]
+ pub parts: Vec<Part>,
}
/// Who writes: the person, the lead (who handed it out or leads its mission), or the owner.
@@ -174,8 +192,23 @@ pub fn apply_in_round(mut c: Contract, body: &Value, role: Role, evidence_on_tas
}
fields.push("open_issues");
}
+ // A removed criterion is no longer linked to any part
+ let ids: Vec<String> = c.criteria.iter().map(|k| k.id.clone()).collect();
+ for p in &mut c.parts {
+ p.criteria.retain(|id| ids.contains(id));
+ }
+ if !body["parts"].is_null() {
+ let items = body["parts"].as_array().ok_or("parts must be a list")?;
+ for it in items {
+ part(&mut c, it, role)?;
+ }
+ if c.parts.len() > MAX_PARTS {
+ return Err(format!("at most {MAX_PARTS} parts"));
+ }
+ fields.push("parts");
+ }
if fields.is_empty() {
- return Err("Nothing to change: give must_not_change, criteria, open_issues or risk_flags.".into());
+ return Err("Nothing to change: give must_not_change, criteria, open_issues, risk_flags or parts.".into());
}
Ok((c, fields))
}
@@ -230,6 +263,72 @@ fn criterion(c: &mut Contract, it: &Value, role: Role, evidence_on_task: &[Strin
Ok(())
}
+/// A part write. The lead or the person adds, rewords, relinks or removes a part; the owner can
+/// only link more criteria to an existing part (never unlink, reword, add or remove one).
+fn part(c: &mut Contract, it: &Value, role: Role) -> Result<(), String> {
+ let id = it["id"].as_str().map(str::trim).filter(|s| !s.is_empty());
+ let text = it["text"].as_str().map(clip).filter(|s| !s.is_empty());
+ let remove = it["remove"].as_bool() == Some(true);
+ let links: Option<Vec<String>> = match it.get("criteria").filter(|v| !v.is_null()) {
+ None => None,
+ Some(v) => {
+ let arr = v.as_array().ok_or("a part's criteria must be a list of criterion ids")?;
+ let mut out: Vec<String> = Vec::new();
+ for x in arr {
+ let k = x.as_str().ok_or("a part's criteria must be a list of criterion ids")?.trim();
+ if k.is_empty() || out.iter().any(|o| o == k) {
+ continue;
+ }
+ if !c.criteria.iter().any(|cr| cr.id == k) {
+ return Err(format!("No criterion {k} to link to a part."));
+ }
+ out.push(k.to_string());
+ }
+ Some(out)
+ }
+ };
+ let owner = role == Role::Owner;
+ match id.and_then(|id| c.parts.iter().position(|p| p.id == id)) {
+ Some(i) => {
+ if remove {
+ if owner {
+ return Err(format!("You can't remove part {}; only the lead or the person can.", c.parts[i].id));
+ }
+ c.parts.remove(i);
+ return Ok(());
+ }
+ let cur = &mut c.parts[i];
+ if let Some(t) = text.filter(|t| *t != cur.text) {
+ if owner {
+ return Err(format!("You can't reword part {}; only the lead or the person can.", cur.id));
+ }
+ cur.text = t;
+ }
+ if let Some(links) = links {
+ if owner {
+ if let Some(gone) = cur.criteria.iter().find(|k| !links.contains(k)) {
+ return Err(format!("You can't unlink criterion {gone} from part {}; only the lead or the person can.", cur.id));
+ }
+ }
+ cur.criteria = links;
+ }
+ }
+ None => {
+ if owner {
+ return Err("Only the lead or the person can add a part of the request; you can link criteria to an existing part.".into());
+ }
+ if let Some(id) = id.filter(|_| text.is_none()) {
+ return Err(format!("No part {id}; give text to add a new one."));
+ }
+ let Some(text) = text else { return Err("A new part needs text: the person's own words for it.".into()) };
+ let used: Vec<&str> = c.parts.iter().map(|p| p.id.as_str()).collect();
+ let id = next_id('p', &used);
+ c.parts.push(Part { id, text, criteria: links.unwrap_or_default() });
+ }
+ }
+ Ok(())
+}
+
fn issue(c: &mut Contract, it: &Value, role: Role) -> Result<(), String> {
let id = it["id"].as_str().map(str::trim).filter(|s| !s.is_empty());
let text = it["text"].as_str().map(clip).filter(|s| !s.is_empty());
@@ -301,6 +400,7 @@ pub fn view(c: &Contract, evidence_on_task: &[String], updated_by: &str, updated
"criteria": criteria,
"open_issues": c.open_issues,
"risk_flags": c.risk_flags,
+ "parts": c.parts,
"complete": complete,
"missing": missing,
"updated_by": updated_by,
@@ -451,10 +551,23 @@ pub async fn add_send_back(state: &AppState, task: &Task, reason: &str) {
}
}
+/// What `parts` asks for, in `task_contract` and `mission_plan`.
+pub const PARTS_HELP: &str = "Cut the person's request into parts that together cover every word of it, in their words; link each part to the criteria that prove it.";
+
+/// One `parts` entry, for `task_contract` and `mission_plan`.
+pub fn part_schema() -> Value {
+ json!({"type": "object", "properties": {
+ "id": {"type": "string", "description": "An existing part's id (p1, p2…); leave out to add one."},
+ "text": {"type": "string", "description": "The person's own words for this part, e.g. \"send it to Ana\"."},
+ "criteria": {"type": "array", "items": {"type": "string"}, "description": "Ids of the criteria that prove this part (c1, c2…)."},
+ "remove": {"type": "boolean"}
+ }})
+}
+
pub fn tool() -> Value {
json!({
"name": TOOL,
- "description": "Write a task's contract: what must not change, its criteria (each met / not_met / not_checked, with evidence ids attached to the task), open issues or assumptions, and risk flags. The task's owner can add items and mark criteria with evidence, but can't remove or reword what the lead wrote; the lead of the hand-off or mission can set anything. A criterion marked met without evidence counts as a claim, not as met.",
+ "description": "Write a task's contract: what must not change, its criteria (each met / not_met / not_checked, with evidence ids attached to the task), open issues or assumptions, and risk flags. The task's owner can add items and mark criteria with evidence, but can't remove or reword what the lead wrote; the lead of the hand-off or mission can set anything. A criterion marked met without evidence counts as a claim, not as met. Parts: cut the person's request into parts that together cover every word of it, in their words; link each part to the criteria that prove it. Only the lead or the person writes parts; the owner can link more criteria to one. A part with no criterion linked shows the person it has no check.",
"inputSchema": {
"type": "object",
"properties": {
@@ -470,7 +583,8 @@ pub fn tool() -> Value {
"open_issues": {"type": "array", "items": {"type": "object", "properties": {
"id": {"type": "string"}, "kind": {"type": "string", "enum": ISSUE_KINDS}, "text": {"type": "string"}, "remove": {"type": "boolean"}
}}},
- "risk_flags": {"type": "array", "items": {"type": "string"}, "description": "The whole list: short tags like migration, auth, payments."}
+ "risk_flags": {"type": "array", "items": {"type": "string"}, "description": "The whole list: short tags like migration, auth, payments."},
+ "parts": {"type": "array", "maxItems": MAX_PARTS, "description": PARTS_HELP, "items": part_schema()}
},
"required": ["task_id"]
}
@@ -621,4 +735,58 @@ mod tests {
);
assert!(scope_status(&mnc, None).as_array().unwrap().iter().all(|e| e["status"] == "not_checked"));
}
+
+ // ---- request-parts ----
+
+ fn with_parts() -> Contract {
+ let body = json!({"criteria": [{"text": "the PDF is in the folder"}, {"text": "Ana has the email"}], "parts": [{"text": "make the PDF", "criteria": ["c1"]}, {"text": "send it to Ana"}]});
+ apply(Contract::default(), &body, Role::Lead, &ev()).unwrap().0
+ }
+
+ #[test]
+ fn parts_round_trip_and_an_old_body_has_none() {
+ let c = with_parts();
+ assert_eq!(c.parts, [Part { id: "p1".into(), text: "make the PDF".into(), criteria: vec!["c1".into()] }, Part { id: "p2".into(), text: "send it to Ana".into(), criteria: vec![] }]);
+ let back: Contract = serde_json::from_str(&serde_json::to_string(&c).unwrap()).unwrap();
+ assert_eq!(back, c);
+ let old: Contract = serde_json::from_str(r#"{"must_not_change": [], "criteria": [{"id": "c1", "text": "t", "status": "met", "by": "lead"}], "open_issues": [], "risk_flags": []}"#).unwrap();
+ assert!(old.parts.is_empty());
+ assert_eq!(view(&c, &ev(), "lead", chrono::Utc::now())["parts"][1]["text"], "send it to Ana");
+ }
+
+ #[test]
+ fn the_owner_can_link_criteria_to_a_part_but_not_change_parts() {
+ let c = with_parts();
+ let refuse = |body: Value, want: &str| {
+ let e = apply(c.clone(), &body, Role::Owner, &ev()).unwrap_err();
+ assert!(e.contains(want), "{e}");
+ };
+ refuse(json!({"parts": [{"id": "p2", "remove": true}]}), "can't remove part p2");
+ refuse(json!({"parts": [{"id": "p2", "text": "send it"}]}), "can't reword part p2");
+ refuse(json!({"parts": [{"text": "and tell Bob"}]}), "Only the lead or the person");
+ refuse(json!({"parts": [{"id": "p1", "criteria": []}]}), "can't unlink criterion c1");
+ // It may add its own criterion and link it
+ let (c2, fields) = apply(c.clone(), &json!({"criteria": [{"text": "sent, message id in evidence"}], "parts": [{"id": "p2", "criteria": ["c3"]}]}), Role::Owner, &ev()).unwrap();
+ assert_eq!(fields, ["criteria", "parts"]);
+ assert_eq!(c2.parts[1].criteria, ["c3"]);
+ // The person and the lead may do anything
+ let (c3, _) = apply(c, &json!({"parts": [{"id": "p1", "text": "make the PDF, A4", "criteria": []}, {"id": "p2", "remove": true}]}), Role::Person, &ev()).unwrap();
+ assert_eq!(c3.parts, [Part { id: "p1".into(), text: "make the PDF, A4".into(), criteria: vec![] }]);
+ }
+
+ #[test]
+ fn parts_link_only_existing_criteria_and_lose_removed_ones() {
+ let c = with_parts();
+ assert!(apply(c.clone(), &json!({"parts": [{"id": "p2", "criteria": ["c9"]}]}), Role::Lead, &ev()).unwrap_err().contains("c9"));
+ assert!(apply(c.clone(), &json!({"parts": [{"criteria": ["c1"]}]}), Role::Lead, &ev()).unwrap_err().contains("needs text"));
+ assert!(apply(c.clone(), &json!({"parts": "send it"}), Role::Lead, &ev()).is_err());
+ let many: Vec<Value> = (0..MAX_PARTS).map(|i| json!({"text": format!("part {i}")})).collect();
+ assert!(apply(c.clone(), &json!({"parts": many}), Role::Lead, &ev()).unwrap_err().contains("at most"));
+ let (c, _) = apply(c, &json!({"criteria": [{"id": "c1", "remove": true}]}), Role::Lead, &ev()).unwrap();
+ assert!(c.parts[0].criteria.is_empty(), "a removed criterion is unlinked");
+ // Parts in a plan: c1 is the first acceptance line
+ let start = Contract { criteria: from_acceptance("PDF in the folder\nAna has it"), ..Default::default() };
+ let (c, _) = apply(start, &json!({"parts": [{"text": "make the PDF", "criteria": ["c1"]}, {"text": "send it to Ana", "criteria": ["c2"]}]}), Role::Lead, &[]).unwrap();
+ assert_eq!(c.parts[1].criteria, ["c2"]);
+ }
}
diff --git a/src/server/missions/tools.rs b/src/server/missions/tools.rs
index adc637e6..f07924da 100644
--- a/src/server/missions/tools.rs
+++ b/src/server/missions/tools.rs
@@ -42,7 +42,7 @@ pub fn tools() -> Vec<Value> {
vec![
json!({
"name": "mission_plan",
- "description": "Propose a mission: a goal split into tasks with acceptance criteria and outcome checks. It is a draft until the person approves it on the board; nothing runs before that. Each task is verified only by its checks passing (or a teammate's review / the person), never by its owner saying it is done. Use it only when the person asks for a plan, project or tracked multi-step work, never on your own for an ordinary request or a quick answer.",
+ "description": "Propose a mission: a goal split into tasks with acceptance criteria and outcome checks. It is a draft until the person approves it on the board; nothing runs before that. Each task is verified only by its checks passing (or a teammate's review / the person), never by its owner saying it is done. Use it only when the person asks for a plan, project or tracked multi-step work, never on your own for an ordinary request or a quick answer. Each acceptance line becomes a criterion: c1 is the first line, c2 the second. Cut the person's request into parts that together cover every word of it, in their words; link each part to the criteria that prove it.",
"inputSchema": {
"type": "object",
"properties": {
@@ -64,6 +64,8 @@ pub fn tools() -> Vec<Value> {
"budget_tokens": {"type": "integer"},
"checks": {"type": "array", "items": check_schema()},
"task_class": {"type": "string", "description": "Kind of work, as a short slug (seo-audit, release…); sets how much freedom its bot gets. Leave it out for tasks you'd run yourself."},
+ "parts": {"type": "array", "maxItems": super::contract::MAX_PARTS, "items": super::contract::part_schema(),
+ "description": "The parts of the person's request this task does. Cut the person's request into parts that together cover every word of it, in their words; link each part to the criteria that prove it (c1 = the first acceptance line)."},
},
"required": ["title", "acceptance"],
},
@@ -248,6 +250,11 @@ async fn plan(state: &AppState, scope: &SelfScope, space: &SpaceId, args: &Value
return fail("A mission needs at least one task.");
}
let Ok(Some(lead)) = state.db.get_kwant(&scope.kwant_id).await else { return fail("Could not find you.") };
+ // Parts are checked before anything is written, like the rest of the plan
+ let parts = match plan_parts(&tasks, args) {
+ Ok(p) => p,
+ Err(e) => return fail(e),
+ };
let origin = scope.origin.clone().unwrap_or_default();
let workspace = scope.workspace.clone().unwrap_or_else(|| {
crate::tools::bot_workspace(&crate::db::spaces::space_data_dir(&state.config.data_dir, space), &scope.kwant_id)
@@ -264,6 +271,15 @@ async fn plan(state: &AppState, scope: &SelfScope, space: &SpaceId, args: &Value
let goal = args["goal"].as_str().unwrap_or("");
match super::create_plan(state, space, &lead, title, goal, budget, &tasks, by, place).await {
Ok((m, rows)) => {
+ // rows follow the plan's task order (a task it couldn't read back would shift them)
+ for (row, c) in rows.iter().zip(&parts).filter(|_| rows.len() == parts.len()) {
+ let Some(c) = c else { continue };
+ let event = json!({"by": "lead", "fields": ["parts"], "criteria": c.criteria.len(), "parts": c.parts.len()});
+ let body = serde_json::to_value(c).unwrap_or_default();
+ if let Err(e) = state.db.put_contract(&row.id, &body, &scope.kwant_id, &event).await {
+ tracing::warn!(task_id = %row.id, error = %e, "the plan's parts weren't stored");
+ }
+ }
super::mission_chat_line(
state,
&m,
@@ -281,6 +297,26 @@ async fn plan(state: &AppState, scope: &SelfScope, space: &SpaceId, args: &Value
}
}
+/// Each planned task's contract when the plan gives it parts: its acceptance lines as criteria
+/// (as a task with no stored contract reads them) plus the parts, written as the lead. `None` for
+/// a task without parts, so its contract stays unstored as before.
+fn plan_parts(tasks: &[PlanTask], args: &Value) -> Result<Vec<Option<super::contract::Contract>>, String> {
+ use super::contract::{apply, from_acceptance, Contract, Role};
+ tasks
+ .iter()
+ .enumerate()
+ .map(|(i, t)| {
+ let parts = &args["tasks"][i]["parts"];
+ if parts.is_null() || parts.as_array().is_some_and(|a| a.is_empty()) {
+ return Ok(None);
+ }
+ let key = t.key.clone().unwrap_or_else(|| (i + 1).to_string());
+ let start = Contract { criteria: from_acceptance(&t.acceptance), ..Default::default() };
+ apply(start, &json!({"parts": parts}), Role::Lead, &[]).map(|(c, _)| Some(c)).map_err(|e| format!("task {key}: {e}"))
+ })
+ .collect()
+}
+
fn brief(t: &Task) -> Value {
json!({
"id": t.id, "title": t.title, "state": t.state, "mission_id": t.mission_id, "priority": t.priority,