#[cfg(feature = "skills")]
use std::future::Future;
use std::path::PathBuf;
use askama::Template;
use super::source::{Block, ContextSource};
use crate::working_docs::{self, AnyTaskBlockerResolver, WorkingDocsSnapshot};
#[derive(Template)]
#[template(path = "tasks_document.txt", escape = "none")]
struct TasksDocumentTemplate {
tasks: Option<String>,
changes: Option<String>,
}
#[derive(Template)]
#[template(path = "tasks_stale.txt", escape = "none")]
struct TasksStaleTemplate {
content: String,
}
#[derive(Template)]
#[template(path = "tasks_continue.txt", escape = "none")]
struct TasksContinueTemplate;
#[derive(Template)]
#[template(path = "system_reminder.txt", escape = "none")]
struct SystemReminderTemplate {
content: String,
}
fn block(tag: &str, template: &impl Template) -> Block {
Block::new(
tag,
template
.render()
.expect("context block template must render"),
)
}
#[derive(Debug)]
pub struct TasksDocument {
sandbox_dir: PathBuf,
stale_after_turns: usize,
shown: Option<WorkingDocsSnapshot>,
last_content: Option<String>,
seen: bool,
stale_turns: usize,
alerted: bool,
blocker_resolver: Option<AnyTaskBlockerResolver>,
}
impl TasksDocument {
#[must_use]
pub fn new(sandbox_dir: impl Into<PathBuf>, stale_after_turns: usize) -> Self {
Self {
sandbox_dir: sandbox_dir.into(),
stale_after_turns,
shown: None,
last_content: None,
seen: false,
stale_turns: 0,
alerted: false,
blocker_resolver: None,
}
}
#[must_use]
pub fn with_blocker_resolver(mut self, resolver: AnyTaskBlockerResolver) -> Self {
self.blocker_resolver = Some(resolver);
self
}
}
impl ContextSource for TasksDocument {
async fn on_request(&mut self, reassembled: bool) -> Option<Block> {
let docs = working_docs::read_snapshot(&self.sandbox_dir).await;
let (tasks, changes) = match self.shown.as_ref() {
Some(shown) if !reassembled => (None, working_docs::tasks_md_diff(shown, &docs)),
_ => (docs.tasks_md.clone(), None),
};
self.shown = Some(docs);
if tasks.is_none() && changes.is_none() {
return None;
}
Some(block(
"tasks_document",
&TasksDocumentTemplate { tasks, changes },
))
}
async fn on_tool_turn_end(&mut self) -> Option<Block> {
let docs = working_docs::read_snapshot(&self.sandbox_dir).await;
let threshold = self.stale_after_turns;
if !self.seen {
self.seen = true;
self.last_content = docs.tasks_md;
return None;
}
if self.last_content != docs.tasks_md {
self.last_content = docs.tasks_md;
self.stale_turns = 0;
self.alerted = false;
return None;
}
let missing = match &docs.tasks_md {
Some(content) => {
if working_docs::has_unblocked_markdown_tasks(
content,
self.blocker_resolver.as_ref(),
)
.await
{
false
} else {
self.stale_turns = 0;
self.alerted = false;
return None;
}
}
None => true,
};
self.stale_turns += 1;
if self.stale_turns < threshold || self.alerted {
return None;
}
self.alerted = true;
let content = if missing {
format!(
"{threshold} tool turns have run without a tasks.md. For multi-step work, create tasks.md in the sandbox root with a checklist of the plan — it is the canonical task document and survives context compaction."
)
} else {
format!(
"tasks.md has unchecked items but has not been updated for {threshold} tool turns. Mark finished items and keep the checklist in sync with actual progress."
)
};
Some(block("tasks_stale", &TasksStaleTemplate { content }))
}
async fn on_final_turn(&mut self) -> Option<Block> {
let docs = working_docs::read_snapshot(&self.sandbox_dir).await;
if !docs
.has_unblocked_items(self.blocker_resolver.as_ref())
.await
{
return None;
}
Some(block(
"system_reminder",
&SystemReminderTemplate {
content: TasksContinueTemplate
.render()
.expect("tasks continue template must render"),
},
))
}
}
#[derive(Debug)]
pub struct BackgroundJobs {
registry: aither_sandbox::JobRegistry,
}
impl BackgroundJobs {
#[must_use]
pub const fn new(registry: aither_sandbox::JobRegistry) -> Self {
Self { registry }
}
}
impl ContextSource for BackgroundJobs {
async fn render(&self) -> Option<Block> {
let running = self.registry.format_running_jobs().await;
if running.is_empty() {
return None;
}
Some(block(
"system_reminder",
&SystemReminderTemplate {
content: format!(
"Running background terminals:\n{running}Use terminal_read for incremental output, read redirected output files via terminal commands like head/tail/grep/cat when needed, terminal_input for stdin, and terminal_kill to stop tasks."
),
},
))
}
}
#[cfg(feature = "skills")]
#[derive(Template)]
#[template(path = "skill_instruction.txt", escape = "none")]
struct SkillInstructionTemplate<'a> {
name: &'a str,
description: &'a str,
instructions: &'a str,
allowed_tools: Option<&'a [String]>,
resource_paths: Option<&'a [String]>,
}
#[cfg(feature = "skills")]
#[derive(Debug, Default)]
pub struct ActiveSkills {
skills: Vec<aither_skills::Skill>,
}
#[cfg(feature = "skills")]
impl ActiveSkills {
#[must_use]
pub const fn new() -> Self {
Self { skills: Vec::new() }
}
pub fn set(&mut self, skills: Vec<aither_skills::Skill>) {
self.skills = skills;
}
#[must_use]
pub fn skills(&self) -> &[aither_skills::Skill] {
&self.skills
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.skills.is_empty()
}
}
#[cfg(feature = "skills")]
impl ContextSource for ActiveSkills {
fn render(&self) -> impl Future<Output = Option<Block>> + Send {
std::future::ready(self.render_skills())
}
}
#[cfg(feature = "skills")]
impl ActiveSkills {
fn render_skills(&self) -> Option<Block> {
if self.skills.is_empty() {
return None;
}
let mut rendered = String::new();
for skill in &self.skills {
let mut resource_paths = skill.resources.keys().cloned().collect::<Vec<_>>();
resource_paths.sort();
let instruction = SkillInstructionTemplate {
name: &skill.name,
description: &skill.description,
instructions: &skill.instructions,
allowed_tools: skill.allowed_tools.as_deref(),
resource_paths: (!resource_paths.is_empty()).then_some(resource_paths.as_slice()),
}
.render()
.expect("skill instruction template must render");
if !rendered.is_empty() {
rendered.push('\n');
}
rendered.push_str(&instruction);
}
Some(Block::new("skill_instructions", rendered))
}
}
#[cfg(test)]
mod tests {
use super::*;
async fn write_tasks(root: &std::path::Path, content: &str) {
async_fs::write(root.join("tasks.md"), content)
.await
.expect("write tasks.md");
}
#[tokio::test]
async fn an_absent_tasks_document_renders_nothing() {
let root = tempfile::tempdir().expect("tempdir");
let source = TasksDocument::new(root.path(), 4);
assert!(source.render().await.is_none());
}
#[tokio::test]
async fn the_document_is_never_rendered_into_the_tail() {
let root = tempfile::tempdir().expect("tempdir");
write_tasks(root.path(), "- [ ] first\n").await;
let source = TasksDocument::new(root.path(), 4);
assert!(source.render().await.is_none());
}
#[tokio::test]
async fn the_session_start_carries_the_whole_document() {
let root = tempfile::tempdir().expect("tempdir");
write_tasks(root.path(), "- [ ] first\n").await;
let mut source = TasksDocument::new(root.path(), 4);
let block = source.on_request(false).await.expect("shows the document");
assert!(block.content().contains("Contents of tasks.md"));
assert!(block.content().contains("- [ ] first"));
assert!(!block.content().contains("Changes to tasks.md"));
}
#[tokio::test]
async fn an_unchanged_document_adds_nothing_after_the_start() {
let root = tempfile::tempdir().expect("tempdir");
write_tasks(root.path(), "- [ ] first\n").await;
let mut source = TasksDocument::new(root.path(), 4);
assert!(source.on_request(false).await.is_some());
assert!(source.on_request(false).await.is_none());
assert!(source.on_request(false).await.is_none());
}
#[tokio::test]
async fn a_change_is_shown_once_as_its_diff() {
let root = tempfile::tempdir().expect("tempdir");
write_tasks(root.path(), "- [ ] first\n").await;
let mut source = TasksDocument::new(root.path(), 4);
source.on_request(false).await.expect("session start");
write_tasks(root.path(), "- [x] first\n- [ ] second\n").await;
let block = source.on_request(false).await.expect("shows the diff");
assert!(block.content().contains("Changes to tasks.md"));
assert!(block.content().contains("+ - [ ] second"));
assert!(
!block.content().contains("Contents of tasks.md"),
"a change must not resend the document: {}",
block.content()
);
assert!(source.on_request(false).await.is_none());
}
#[tokio::test]
async fn a_reassembly_shows_the_whole_document_again() {
let root = tempfile::tempdir().expect("tempdir");
write_tasks(root.path(), "- [ ] first\n").await;
let mut source = TasksDocument::new(root.path(), 4);
source.on_request(false).await.expect("session start");
let block = source.on_request(true).await.expect("shows the document");
assert!(block.content().contains("Contents of tasks.md"));
assert!(source.on_request(false).await.is_none());
}
#[tokio::test]
async fn an_absent_document_is_never_shown() {
let root = tempfile::tempdir().expect("tempdir");
let mut source = TasksDocument::new(root.path(), 4);
assert!(source.on_request(false).await.is_none());
assert!(source.on_request(true).await.is_none());
}
#[tokio::test]
async fn staleness_alerts_once_per_episode_and_resets_on_change() {
let root = tempfile::tempdir().expect("tempdir");
write_tasks(root.path(), "- [ ] work\n").await;
let mut source = TasksDocument::new(root.path(), 2);
assert!(source.on_tool_turn_end().await.is_none());
assert!(source.on_tool_turn_end().await.is_none());
let alert = source.on_tool_turn_end().await.expect("alert fires");
assert!(alert.content().contains("has unchecked items"));
assert!(
source.on_tool_turn_end().await.is_none(),
"the alert must not repeat within one episode"
);
write_tasks(root.path(), "- [x] work\n- [ ] more\n").await;
assert!(source.on_tool_turn_end().await.is_none());
assert!(source.on_tool_turn_end().await.is_none());
assert!(
source.on_tool_turn_end().await.is_some(),
"a new stale episode must alert again"
);
}
#[tokio::test]
async fn a_complete_checklist_is_never_stale() {
let root = tempfile::tempdir().expect("tempdir");
write_tasks(root.path(), "- [x] done\n").await;
let mut source = TasksDocument::new(root.path(), 1);
assert!(source.on_tool_turn_end().await.is_none());
for _ in 0..5 {
assert!(source.on_tool_turn_end().await.is_none());
}
}
#[tokio::test]
async fn a_missing_document_is_reported_differently() {
let root = tempfile::tempdir().expect("tempdir");
let mut source = TasksDocument::new(root.path(), 1);
assert!(source.on_tool_turn_end().await.is_none());
let alert = source.on_tool_turn_end().await.expect("alert fires");
assert!(alert.content().contains("without a tasks.md"));
}
#[tokio::test]
async fn unchecked_items_block_the_final_turn() {
let root = tempfile::tempdir().expect("tempdir");
write_tasks(root.path(), "- [ ] work\n").await;
let mut source = TasksDocument::new(root.path(), 4);
assert!(source.on_final_turn().await.is_some());
write_tasks(root.path(), "- [x] work\n").await;
assert!(source.on_final_turn().await.is_none());
}
#[tokio::test]
async fn blocked_items_hold_no_turn_open() {
let root = tempfile::tempdir().expect("tempdir");
write_tasks(
root.path(),
"- [ ] ship it BLOCKING req-123\n- [ ] pick a topic BLOCKING waiting on the user\n",
)
.await;
let mut source = TasksDocument::new(root.path(), 4);
assert!(source.on_final_turn().await.is_none());
}
#[tokio::test]
async fn a_bare_blocking_word_is_not_a_mark() {
let root = tempfile::tempdir().expect("tempdir");
write_tasks(root.path(), "- [ ] work BLOCKING\n").await;
let mut source = TasksDocument::new(root.path(), 4);
assert!(source.on_final_turn().await.is_some());
}
#[tokio::test]
async fn a_blocked_item_among_runnable_ones_still_objects() {
let root = tempfile::tempdir().expect("tempdir");
write_tasks(root.path(), "- [ ] work\n- [ ] ship it BLOCKING req-123\n").await;
let mut source = TasksDocument::new(root.path(), 4);
assert!(source.on_final_turn().await.is_some());
}
#[tokio::test]
async fn blocked_items_are_never_stale() {
let root = tempfile::tempdir().expect("tempdir");
write_tasks(root.path(), "- [ ] ship it BLOCKING req-123\n").await;
let mut source = TasksDocument::new(root.path(), 1);
assert!(source.on_tool_turn_end().await.is_none());
for _ in 0..5 {
assert!(source.on_tool_turn_end().await.is_none());
}
}
struct TestResolver;
impl crate::working_docs::TaskBlockerResolver for TestResolver {
fn is_open(&self, mark: &str) -> impl std::future::Future<Output = bool> + Send {
std::future::ready(!matches!(mark, "req-answered" | "req-withdrawn"))
}
}
fn resolved() -> AnyTaskBlockerResolver {
AnyTaskBlockerResolver::new(TestResolver)
}
#[tokio::test]
async fn a_dead_mark_leaves_the_item_runnable() {
let root = tempfile::tempdir().expect("tempdir");
write_tasks(root.path(), "- [ ] pick a db BLOCKING req-answered\n").await;
let mut source = TasksDocument::new(root.path(), 4).with_blocker_resolver(resolved());
assert!(source.on_final_turn().await.is_some());
}
#[tokio::test]
async fn a_live_mark_and_free_text_still_hold() {
let root = tempfile::tempdir().expect("tempdir");
write_tasks(
root.path(),
"- [ ] pick a db BLOCKING req-open\n- [ ] write poem BLOCKING waiting on the user\n",
)
.await;
let mut source = TasksDocument::new(root.path(), 4).with_blocker_resolver(resolved());
assert!(source.on_final_turn().await.is_none());
}
#[tokio::test]
async fn a_dead_mark_counts_toward_staleness() {
let root = tempfile::tempdir().expect("tempdir");
write_tasks(root.path(), "- [ ] pick a db BLOCKING req-withdrawn\n").await;
let mut source = TasksDocument::new(root.path(), 1).with_blocker_resolver(resolved());
assert!(source.on_tool_turn_end().await.is_none());
assert!(source.on_tool_turn_end().await.is_some());
}
#[tokio::test]
async fn the_continue_alert_holds_work_an_open_question_blocks() {
let root = tempfile::tempdir().expect("tempdir");
write_tasks(root.path(), "- [ ] work\n").await;
let mut source = TasksDocument::new(root.path(), 4);
let alert = source.on_final_turn().await.expect("alert fires");
assert_eq!(
alert.content(),
"<system_reminder>tasks.md still has unblocked unchecked items; continue with them. An item waiting on an open ask_user answer — or on anything else the run cannot resolve — is marked BLOCKING <request_id or reason>: blocked items wait for what they name instead of holding the turn open. A mark naming a request that is no longer open does not hold.</system_reminder>"
);
}
}