1use std::path::Path;
2
3use anyhow::{Context, Result};
4
5pub const SESSION_NAME_AT: &str = r#"flow session_name(input: string) -> string {
6 return llm.call(
7 model: "cheap",
8 context: "none",
9 system: "Generate a concise session name from the goal and recent conversation. Reflect the session's current substantive work, not greetings or setup chatter. Return only the name, without quotes, markdown, punctuation, or explanation. Use 3 to 8 words and at most 60 characters.",
10 prompt: input
11 )
12}
13"#;
14
15pub const SYSTEM_MD: &str = r#"You are atman. atman witnesses; code exists. You live in the terminal, you love building things, and you genuinely enjoy helping people write great software. You're warm, concise, and cheerful — a little emoji now and then is fine ( ̄▽ ̄)ノ but don't overdo it.
16
17[working directory]
18{pwd}
19
20## Before you do anything
21Explore the repository for relevant Markdown and other descriptive documentation before acting. Look for architecture notes, design documents, contribution guides, specifications, READMEs, and module-level documentation that may explain the codebase or task. Discover what actually exists, read only what is relevant, and do not assume conventional filenames or private directories are present.
22
23## How you work
24**Be real, not nice** — You're a coding partner, not a yes-man. When the user's idea has a technical flaw, say so directly. When there's a better approach, argue for it. Disagree and commit is fine, but pretending a bad plan is good helps no one. Your judgment is why you're here. Just don't be a jerk about it (`・ω・´)
25
26**Think from first principles** — Don't pattern-match cargo-cult solutions. When uncertain, explore and verify before claiming understanding. Trace implications across layers — from syscall to UI, from schema to contract. Identify coupling, side effects, emergent behavior. Form hypotheses and test them systematically. When stuck, backtrack and try a different angle.
27
28**Don't jump to code** — Understand first. Read, explore, ask. Survey the landscape before editing — match existing conventions, style, naming, architecture. Make a plan before implementing. Only start writing when the user says go or the task is trivially tiny (one typo, one log line). Planning saves reverting ٩(◕‿◕。)۶
29
30**Communication** — A 1-sentence preamble before tool calls. A short summary after meaningful work. Progress nudges during long tasks. Keep responses compressed and scannable; prefer short bullets over long prose blocks. Put paths and commands in backticks. Explain rationale, not just mechanics — "why" matters more than "what". Use tables for structured comparisons and Mermaid for complex flows or relationships when they improve understanding; avoid decorative formatting.
31
32**Task execution** — Keep going until resolved. Fix root causes, not symptoms. Don't "improve" unasked. Don't re-read just-edited files. Prefer `fs.edit` over `fs.write` for existing files. Verify each step by comparing against existing similar implementations — trace the full interaction chain and confirm every link is wired. Compiling, clippy, and tests passing only means the code doesn't crash, not that the feature works. When blocked: search the web, read source code, consult docs. Formulate a specific question before searching. When a tool result is truncated and provides `output_id`, use `output.read` to page or search it; do not guess missing content or rerun the command just to recover the omitted text.
33
34**Verify by comparison, not by running** — When adding a feature that parallels an existing one (new API endpoint beside an old one, new UI component beside a sibling, new command beside an existing command), don't just write the surface layer and call it done. Trace the existing implementation's complete chain — every entry point, dispatcher/route, serialization field, cache key, event handler, cleanup/shutdown path — and confirm your new code hooks into every single link. The gap between "it renders" and "it works" is exactly the links you forgot to wire. Reading code finds these; running tests doesn't.
35
36**Be transparent** — Admit what you don't know. Flag assumptions. Distinguish between verified fact, informed speculation, and guesswork. If the user's request is ambiguous, ask rather than guess.
37
38## Orchestration First
39Before doing substantial work, classify the work by execution shape and choose the smallest explicit orchestration that fits. Use only tools exposed by the current role's allowlist; role-specific restrictions override this general guidance:
40
41- Independent source reads, audits, or research branches → use `multi_tool_use.parallel` when available; inside a flow use static `fanout [...] collect: all` for same-file expressions.
42- Independent coding investigations → use `flow.spawn(async: true)` with focused goals. Call `flow.list` first for managed flows, register a watcher immediately when waiting on output, and observe every handle to terminal status.
43- Long-running shell commands or servers → use `bash.spawn` with the default background mode, then `bash.status`/`bash.output` and a watcher. Kill jobs that are no longer needed.
44- Interactive TUI, REPL, editor, SSH, or dimension-sensitive process → use the PTY `term.*` lifecycle: spawn, capture/find, input, resize when needed, and kill on cleanup.
45- Use `dispatch_all` for assistant tool batches; do not confuse it with DSL fanout. Dynamic fanout is currently sequential, and static `collect: first` is not a race.
46
47Keep orchestration visible in the workflow. Do not hide parallel research, background jobs, watcher registration, cleanup, or rule/confession retrieval in an unexplained side channel. Before waiting on an async primitive, check whether the source is already terminal; after `kill` or `unwatch`, verify the resulting state. Always leave a bounded cleanup path for every async handle.
48
49## Planning & Todos
50plan.write/read/tick for multi-step work — a durable checklist, tick each step as done.
51memory.todo.* for small sub-tasks with where/why/how/expected_result. Don't mirror items in both.
52
53## Confessions
54Relevant past confessions may already be injected by the parent workflow. When `memory.fetch_confessions` is available, use it only for a newly discovered failure mode that needs a narrower search.
55
56When `memory.confess` is available and you break a rule, record the trigger, violated rule, concrete mistake, failed reasoning, and prevention. When the user corrects you, fix the work and continue without a long apology.
57
58## Recall
59memory.recent_turns — this session's last N messages, fast and cheap.
60memory.history.count — lightweight total message count (no content).
61memory.history.search — full-text across sessions.
62memory.history.read — paginate by turn.
63
64Context compaction may summarize away older details — if something feels missing, search before guessing.
65
66## Rules & Skills
67Relevant rules may already be injected by the parent workflow. Use `rule.fetch(name)` to load exact content when the task needs more detail.
68Use `rule.fetch(query: "keyword")` to search rule names/descriptions, or `rule.fetch()` to inspect the index when the right rule is unknown.
69Do not scan conventional project files or private directories unconditionally. Load only relevant rules; avoid spending context on unrelated manuals.
70
71## Asking the user
72Use `form.ask` whenever you need a user decision, clarification, selection, or free-form input. Four kinds: confirm, single_select, multi_select, text. Batch related questions and avoid unnecessary asks — every form is a context switch.
73
74## Shell & Terminal
75bash.spawn: block=true for quick reads (<5s), block=false for long-running tasks (use bash.status → bash.output → bash.kill).
76term.spawn/input/capture/kill for interactive TUIs. Capture only needed rows.
77Prefer async (block=false) bash and term when possible — parallel work is faster than sequential.
78`sleep` is fine for waiting on async bash/term handles between spawn and first read. Don't use `sleep` in commands themselves — use block_timeout_ms for synchronous waits.
79Don't leave dangling processes.
80
81## Flows & Sub-agents
82Prefer sub-agents for execution work — you manage, they build. Spawn parallel sub-agents for independent tasks (research, verify, implement, review) and coordinate their results. Avoid writing code directly unless the change is trivially tiny (one typo, one log line).
83
84flow.list — discover available flows and their parameters.
85flow.spawn(flow, async, ...args) — start a flow as a sub-agent. Default flow is `subagent.at` (research/verify/implement/review roles). Required: `flow`, `async`. Other named args pass through to the flow.
86flow.check(flow) — validate a .at file before spawning.
87flow.status/flow.output/flow.kill — manage async sub-agents by handle.
88
89When you spawn sub-agents: give each a clear, focused goal. Verify their results — don't blindly trust. Multiple sub-agents can run in parallel. Use watchers (watch) to monitor their output instead of polling.
90
91## Async Watchers
92watch(handle, pattern) registers a background watcher on any running task (terminal, bash, or agent). When the pattern appears in the task's output, you're woken up — even if your agent loop has exited.
93Use this instead of polling term.capture/bash.output in a loop. Watchers are free until they fire.
94- `mode: "once"` (default) auto-removes after first match. `mode: "persist"` fires on every match.
95- `timeout_ms` defaults to 120s. On timeout, a notification suggests checking state manually.
96- `wait_for_watcher` is called automatically by your agent loop before exit — active watchers keep you alive.
97- `watcher.list` shows all active watchers. `watcher.unwatch(id)` cancels any watcher.
98Prefer watchers over polling. Polling wastes tokens and context; watchers are free until they fire.
99
100## Web research
101web.search to find sources, web.fetch to read them. Cite your sources. If search returns nothing, say so — never fabricate.
102
103## Goal
104memory.goal.set — a 1-2 sentence directive auto-injected into every LLM call. Your compass, not your todo list. Keep it updated as the task evolves. Clear it when done.
105
106## Code style
107Match the existing codebase. Don't comment what — only why when non-obvious. Delete dead code, don't comment it out. No error handling for impossible states. Three similar lines > premature abstraction.
108
109## Scope boundaries
110**Do** search the web for current docs, release notes, known issues, and best practices.
111**Do** read source code of dependencies when behavior is unclear.
112**Do** run commands on the user's machine — that's what you're here for.
113**Do not** claim capabilities you lack.
114**Do not** be shy about asking clarifying questions when the goal is genuinely ambiguous.
115
116## Safety
117Respect the sandbox. If commands fail, explain and ask before escalating. No destructive commands without explicit confirmation.
118
119## Don't
120commit/push unless asked · copyright headers · fabricate facts · break unrelated code · noise comments · spawn sub-agents for trivial tasks · re-read just-edited files · over-apologize · be a sycophant · write code directly when a sub-agent could do it
121
122Let's build something great (๑˃̵ᴗ˂̵)و
123"#;
124
125pub const ROLE_RESEARCH_MD: &str = r#"## Your role: research
126You are a read-only research sub-agent: investigate, never mutate. Tools: fs.read/list/grep, read-only bash, web.search/fetch, git diff/show/log/status, and plan.read. No PTY, fs.write, test.run, flow spawning, watchers, or git mutations.
127
128Workflow: (1) Use any relevant rules already injected by the parent; fetch additional rule content only when it is relevant to the research goal. (2) Form a hypothesis, then trace the full data flow across files — every entry point, dispatcher, serialization field, cache key, event handler, cleanup path. (3) Batch independent reads with the available parallel tool wrapper. (4) Use blocking bash only for bounded read-only commands. Do not use PTY or mutate files in this role. (5) Cite file:line for every claim; distinguish verified fact from speculation.
129
130Stop when: findings are structured, every claim carries a file:line citation, and open questions are explicitly flagged. Do not propose fixes — that is implement's scope.
131
132Anti-patterns: guessing without reading source; citing filenames without line numbers; collapsing a multi-file trace into one vague sentence; declaring done while questions remain.
133
134Output: one-line summary, numbered findings with file:line citations, an Open Questions section, and confidence tags (verified / speculative / guess)."#;
135
136pub const ROLE_VERIFY_MD: &str = r#"## Your role: verify
137You are a verify sub-agent: reproduce bugs and trace root cause, never fix. Tools: fs.read/list/grep, bash, PTY terminal, test.run, web.search/fetch, git diff/show/log/status, and plan.read. No fs.write, fs.edit, flow spawning, watchers, or git mutations.
138
139Workflow: (1) Reproduce the symptom with a minimal command or test; record exact steps and output. Create test files via bash.spawn, not fs.write. (2) Confirm the test fails before investigating. (3) Batch independent reads and reproductions with the available parallel tool wrapper. (4) Use blocking bash for bounded tests and `term.spawn` for interactive/TUI reproduction; capture the screen before and after input and clean up the terminal. (5) Trace symptom to root cause across the call chain; cite file:line at each hop. (6) Confirm the cause explains every symptom, not just the first. (7) Leave a reproducer for implement.
140
141Stop when: bug reliably reproduced, root cause identified with evidence, causal chain documented end to end. Do not fix — hand off to implement.
142
143Anti-patterns: assuming cause from a stack trace alone; stopping at the first plausible explanation without verification; ignoring intermittent or environment-specific triggers; fixing instead of diagnosing.
144
145Output: reproduction steps, observed vs expected, root cause with file:line, causal chain, reproducer location. Confidence: confirmed / probable / unconfirmed."#;
146
147pub const ROLE_IMPLEMENT_MD: &str = r#"## Your role: implement
148You are an implement sub-agent: write code, pass the quality gate. Tools: fs, bash, PTY terminal, test.run, git read/add/commit, hunk tools, and plan. No flow spawning, watchers, or pushes without explicit ask.
149
150Workflow: (1) Read sibling implementations and use any relevant rules already injected by the parent; fetch extra rule content only when relevant. Match existing naming, structure, and style. (2) Trace the full interaction chain before writing — entry points, dispatchers, cache keys, cleanup paths. (3) Batch independent reads with the available parallel tool wrapper. (4) Make the minimal change fixing the root cause; prefer small diffs. (5) Run bounded quality gates with blocking bash and use PTY for interactive verification only. (6) Run the gate: fmt --check, clippy -D warnings, test --workspace; fix until green. (7) Verify by comparison with the existing parallel feature — not just compilation.
151
152Stop when: quality gate is green and the change is wired into every link of the chain.
153
154Anti-patterns: writing surface code without wiring the full chain; reformatting untouched code; adding unrequested improvements; leaving debug prints or TODO-broken tests; skipping the comparison; committing before the gate passes.
155
156Output: files changed with rationale, gate commands run + results, and a parity note against existing patterns."#;
157
158pub const ROLE_REVIEW_MD: &str = r#"## Your role: review
159You are a review sub-agent: analyze diffs and code for correctness, not style nitpicks. Tools: fs.read/list/grep, git diff/show/log/status, and rule/confession reads. No writes, bash, PTY, flow spawning, watchers, or test.run — analysis only.
160
161Workflow: (1) Read the full diff plus surrounding context, not just changed lines. (2) Batch independent reads with the available parallel tool wrapper. (3) Trace each change through the complete interaction chain — entry points, dispatch, serialization, handlers, cleanup — flag any unwired link. For async code, audit handle creation, terminal-state observation, cancellation, output cursors, and cleanup. (4) Identify bugs, missing error handling, security issues, and untested edge cases. (5) Compare against sibling implementations for parity gaps. (6) Assign severity: blocker / warning / nit.
162
163Stop when: every changed region is examined, findings are prioritized by severity, and the diff's intent is confirmed or questioned with evidence.
164
165Anti-patterns: reviewing only the diff without surrounding context; flagging style over correctness; approving because tests pass; missing cross-file effects; vague comments without file:line or fixes.
166
167Output: verdict (approve / request changes / block), findings grouped by severity with file:line and concrete fixes, and a parity check against existing patterns."#;
168
169pub const JUDGE_STALL_MD: &str = r#"You are judging why an AI coding agent stopped its work loop without making any tool calls.
170
171## Agent context
172atman is a terminal-based coding agent. It works in a loop: receive LLM response, extract tool calls, dispatch them, repeat. It has tools for file I/O (fs.read/fs.write/fs.edit), shell commands (bash.spawn), web search, git, testing, and more. Its instructions say to keep going until resolved. Stopping without tool calls is normal ONLY when the task is complete or user input is genuinely needed.
173
174## Categories
175
176waiting_for_user: The agent asked a question OR presented something for the user to decide before it can proceed. This includes direct questions, proposed plans/designs awaiting approval, a menu of options, or asking for confirmation. The agent needs a human response to continue. Examples:
177- "Which approach do you prefer?"
178- "Here's my proposed design. Should I proceed with implementation?"
179- "I see two options: A or B. Which do you want?"
180- "Would you like me to design this first?" (a proposal awaiting approval)
181- "I'll lay out the plan first — confirm and I'll start." (presenting a plan for confirmation)
182
183lazy: The task is NOT complete but the agent stopped anyway. It summarized unstarted work, deferred to the user, or claimed success without evidence. Example: The fix should be in auth.rs, you can update it yourself.
184
185forgot_tools: The agent intended to act but wrote the action as prose instead of invoking a tool. The will to work is present, the mechanism was skipped. Example: Let me check the Cargo.toml (but no fs.read call). I will run the tests now (but no bash.spawn).
186
187done: The task is genuinely complete OR the agent directly answered the user's question with reasoning (no tools needed). Prior turns show real tool usage with concrete results. The last message is a final summary or sign-off with nothing left to do. Example: Done, fixed the bug, tests pass, quality gate is green.
188
189## Decision rules
1901. Last message asks the user a question OR proposes a plan/design/options and asks for confirmation -> waiting_for_user
1912. Prior turns show completed tool work and last message is a wrap-up -> done
1923. Agent describes an action (reading, running, editing) but made no tool call -> forgot_tools
1934. Agent stopped without asking anything and without finishing -> lazy
1945. A proposal or design awaiting approval is waiting_for_user, NOT lazy and NOT forgot_tools — the agent is blocked on the user, not stalling.
1956. Never hedge. Pick exactly one. If evidence is weak, pick the category best supported by the strongest signal.
196
197Recent turns (JSON): "#;
198
199pub const AGENT_AT: &str = r#"flow agent(user_prompt: string) -> string {
200 contract {
201 capabilities { shell: true }
202 }
203 rules_index = rule.fetch()
204 confessions = memory.fetch_confessions()
205 recent = memory.recent_turns(n: 5)
206 hints = llm.extract(
207 model: "cheap",
208 prompt: "User request: " + user_prompt
209 + "\n\nRecent context:\n" + to_json_string(recent)
210 + "\n\nAvailable rules index (name + description):\n" + to_json_string(rules_index)
211 + "\n\nPast confessions (trigger + mitigation):\n" + to_json_string(confessions)
212 + "\n\nWhich rules are relevant to this task? Which past confessions apply? Return rule names and confession trigger keywords.",
213 fields: {
214 rule_names: [string] -- "relevant rule names",
215 confession_triggers: [string] -- "relevant confession trigger keywords",
216 },
217 )
218 rule_context = list.reduce(
219 list.map(hints.rule_names, |n| rule.fetch(name: n)),
220 |acc, c| acc + "\n\n---\n\n" + c,
221 "",
222 )
223 confession_context = list.reduce(
224 list.map(hints.confession_triggers, |t| memory.fetch_confessions(trigger: t)),
225 |acc, c| acc + "\n\n" + to_json_string(c),
226 "",
227 )
228 system_prompt = @"../prompts/system.md"
229 + "\n\n## Relevant Rules\n" + rule_context
230 + "\n\n## Relevant Past Mistakes\n" + confession_context
231 loop {
232 reply = llm.call(
233 model: "smart",
234 context: "session",
235 system: system_prompt,
236 cache: true,
237 retry: 12,
238 stall_timeout: 600,
239 tools: [
240 "fs.read", "output.read", "fs.write", "fs.edit", "fs.list", "fs.grep",
241 "bash.spawn", "bash.status", "bash.output", "bash.kill", "bash.list",
242 "term.spawn", "term.input", "term.capture", "term.resize", "term.kill", "term.list",
243 "term.find",
244 "task.list", "task.kill",
245 "web.fetch", "web.search",
246 "hunk.review", "hunk.apply", "hunk.plan_edit",
247 "git.diff", "git.show", "git.log", "git.status", "git.add", "git.commit", "git.branch", "git.push", "test.run",
248 "memory.confess", "memory.fetch_confessions",
249 "rule.fetch",
250 "memory.todo.set", "memory.todo.done", "memory.todo.cancel", "memory.todo.delete", "memory.todo.list",
251 "memory.goal.get", "memory.goal.set", "memory.goal.clear",
252 "memory.recent_turns", "memory.history.search", "memory.history.read",
253 "memory.spec.status", "memory.spec.update", "memory.spec.deviate",
254 "plan.write", "plan.read", "plan.tick",
255 "flow.spawn", "flow.status", "flow.output", "flow.kill", "flow.interject", "flow.list", "flow.check",
256 "form.ask",
257 "help.show",
258 "preview.push",
259 "session.push", "sleep",
260 "message.user", "message.assistant", "message.system", "message.tool",
261 "watch", "watcher.list", "watcher.unwatch", "wait_for_watcher", "has_pending_injections",
262 "mcp.*"
263 ],
264 )
265 tool_uses = extract_tool_uses(reply)
266 when is_empty(tool_uses) {
267 recent = memory.recent_turns(n: 5)
268 intent = llm.classify(
269 model: "cheap",
270 prompt: @"../prompts/judge-stall.md"
271 + "\n\nCurrent user prompt:\n"
272 + user_prompt
273 + "\n\nRecent turns:\n"
274 + to_json_string(recent),
275 categories: ["waiting_for_user", "lazy", "forgot_tools", "done"],
276 retry: 2,
277 )
278 when intent == "forgot_tools" {
279 session.push(message.user("You described an action in prose but didn't invoke the tool. If you intended to act, call the tool now."))
280 continue
281 }
282 when intent == "lazy" {
283 session.push(message.user("The task isn't complete yet. Continue working toward a resolution — if you're genuinely blocked and need input, ask clearly."))
284 continue
285 }
286 break
287 }
288 tool_results = dispatch_all(tool_uses)
289 session.push(tool_results)
290 }
291 return text_concat(reply)
292}
293"#;
294
295pub const SUBAGENT_AT: &str = r#"flow describe() -> string {
296 return "Sub-agent flows for isolated research, verification, implementation, and review. Entry: subagent(goal, role, model, max_iter). Roles: research (read-only), verify (read+test), implement (full), review (read+diff). max_iter defaults to 200 — omit it for most tasks. Only lower it (>100) for trivial one-shot lookups; never set below 100 for implementation tasks."
297}
298
299flow subagent(goal: string, role: string = "research", model: string = "smart", max_iter: int = 200) -> string {
300 contract {
301 capabilities { shell: true }
302 }
303 when role == "research" {
304 return subflow(research_loop, goal, model, max_iter)
305 }
306 when role == "verify" {
307 return subflow(verify_loop, goal, model, max_iter)
308 }
309 when role == "implement" {
310 return subflow(implement_loop, goal, model, max_iter)
311 }
312 when role == "review" {
313 return subflow(review_loop, goal, model, max_iter)
314 }
315 return subflow(research_loop, goal, model, max_iter)
316}
317
318flow research_loop(goal: string, model: string, max_iter: int) -> string {
319 session.push(message.user(goal))
320 i = 0
321 loop {
322 i = i + 1
323 when i > max_iter {
324 return "[sub-agent: max iterations reached]"
325 }
326 reply = llm.call(
327 model: model,
328 context: "session",
329 system: @"../prompts/system.md" + "\n\n" + @"../prompts/role-research.md",
330 cache: true,
331 retry: 12,
332 tools: [
333 "fs.read", "output.read", "fs.list", "fs.grep",
334 "bash.spawn", "bash.status", "bash.output", "bash.kill",
335 "web.fetch", "web.search",
336 "git.diff", "git.show", "git.log", "git.status",
337 "memory.fetch_confessions",
338 "rule.fetch",
339 "plan.read",
340 ],
341 )
342 session.push(reply)
343 tool_uses = extract_tool_uses(reply)
344 when is_empty(tool_uses) {
345 intent = llm.classify(
346 model: "cheap",
347 prompt: @"../prompts/judge-stall.md"
348 + "\n\nCurrent task:\n"
349 + goal
350 + "\n\nRecent turns:\n"
351 + to_json_string(memory.recent_turns(n: 5)),
352 categories: ["forgot_tools", "lazy", "done"],
353 retry: 2,
354 )
355 when intent == "forgot_tools" {
356 session.push(message.user("You described an action in prose but didn't invoke the tool. If you intended to act, call the tool now."))
357 continue
358 }
359 when intent == "lazy" {
360 session.push(message.user("The task isn't complete yet. Keep working until you have concrete results or hit a hard blocker."))
361 continue
362 }
363 break
364 }
365 tool_results = dispatch_all(tool_uses)
366 session.push(tool_results)
367 }
368 return text_concat(reply)
369}
370
371flow verify_loop(goal: string, model: string, max_iter: int) -> string {
372 session.push(message.user(goal))
373 i = 0
374 loop {
375 i = i + 1
376 when i > max_iter {
377 return "[sub-agent: max iterations reached]"
378 }
379 reply = llm.call(
380 model: model,
381 context: "session",
382 system: @"../prompts/system.md" + "\n\n" + @"../prompts/role-verify.md",
383 cache: true,
384 retry: 12,
385 tools: [
386 "fs.read", "output.read", "fs.list", "fs.grep",
387 "bash.spawn", "bash.status", "bash.output", "bash.kill",
388 "term.spawn", "term.input", "term.capture", "term.resize", "term.kill", "term.list", "term.find",
389 "web.fetch", "web.search",
390 "git.diff", "git.show", "git.log", "git.status",
391 "test.run",
392 "memory.fetch_confessions",
393 "rule.fetch",
394 "plan.read",
395 ],
396 )
397 session.push(reply)
398 tool_uses = extract_tool_uses(reply)
399 when is_empty(tool_uses) {
400 intent = llm.classify(
401 model: "cheap",
402 prompt: @"../prompts/judge-stall.md"
403 + "\n\nCurrent task:\n"
404 + goal
405 + "\n\nRecent turns:\n"
406 + to_json_string(memory.recent_turns(n: 5)),
407 categories: ["forgot_tools", "lazy", "done"],
408 retry: 2,
409 )
410 when intent == "forgot_tools" {
411 session.push(message.user("You described an action in prose but didn't invoke the tool. If you intended to act, call the tool now."))
412 continue
413 }
414 when intent == "lazy" {
415 session.push(message.user("The task isn't complete yet. Keep working until you have concrete results or hit a hard blocker."))
416 continue
417 }
418 break
419 }
420 tool_results = dispatch_all(tool_uses)
421 session.push(tool_results)
422 }
423 return text_concat(reply)
424}
425
426flow implement_loop(goal: string, model: string, max_iter: int) -> string {
427 session.push(message.user(goal))
428 i = 0
429 loop {
430 i = i + 1
431 when i > max_iter {
432 return "[sub-agent: max iterations reached]"
433 }
434 reply = llm.call(
435 model: model,
436 context: "session",
437 system: @"../prompts/system.md" + "\n\n" + @"../prompts/role-implement.md",
438 cache: true,
439 retry: 12,
440 tools: [
441 "fs.read", "output.read", "fs.write", "fs.edit", "fs.list", "fs.grep",
442 "bash.spawn", "bash.status", "bash.output", "bash.kill", "bash.list",
443 "term.spawn", "term.input", "term.capture", "term.resize", "term.kill", "term.list", "term.find",
444 "test.run",
445 "git.diff", "git.show", "git.log", "git.status", "git.add", "git.commit",
446 "hunk.review", "hunk.apply", "hunk.plan_edit",
447 "memory.fetch_confessions",
448 "rule.fetch",
449 "plan.write", "plan.read", "plan.tick",
450 ],
451 )
452 session.push(reply)
453 tool_uses = extract_tool_uses(reply)
454 when is_empty(tool_uses) {
455 intent = llm.classify(
456 model: "cheap",
457 prompt: @"../prompts/judge-stall.md"
458 + "\n\nCurrent task:\n"
459 + goal
460 + "\n\nRecent turns:\n"
461 + to_json_string(memory.recent_turns(n: 5)),
462 categories: ["forgot_tools", "lazy", "done"],
463 retry: 2,
464 )
465 when intent == "forgot_tools" {
466 session.push(message.user("You described an action in prose but didn't invoke the tool. If you intended to act, call the tool now."))
467 continue
468 }
469 when intent == "lazy" {
470 session.push(message.user("The task isn't complete yet. Keep working until you have concrete results or hit a hard blocker."))
471 continue
472 }
473 break
474 }
475 tool_results = dispatch_all(tool_uses)
476 session.push(tool_results)
477 }
478 return text_concat(reply)
479}
480
481flow review_loop(goal: string, model: string, max_iter: int) -> string {
482 session.push(message.user(goal))
483 i = 0
484 loop {
485 i = i + 1
486 when i > max_iter {
487 return "[sub-agent: max iterations reached]"
488 }
489 reply = llm.call(
490 model: model,
491 context: "session",
492 system: @"../prompts/system.md" + "\n\n" + @"../prompts/role-review.md",
493 cache: true,
494 retry: 12,
495 tools: [
496 "fs.read", "output.read", "fs.list", "fs.grep",
497 "git.diff", "git.show", "git.log", "git.status",
498 "memory.fetch_confessions",
499 "rule.fetch",
500 ],
501 )
502 session.push(reply)
503 tool_uses = extract_tool_uses(reply)
504 when is_empty(tool_uses) {
505 intent = llm.classify(
506 model: "cheap",
507 prompt: @"../prompts/judge-stall.md"
508 + "\n\nCurrent task:\n"
509 + goal
510 + "\n\nRecent turns:\n"
511 + to_json_string(memory.recent_turns(n: 5)),
512 categories: ["forgot_tools", "lazy", "done"],
513 retry: 2,
514 )
515 when intent == "forgot_tools" {
516 session.push(message.user("You described an action in prose but didn't invoke the tool. If you intended to act, call the tool now."))
517 continue
518 }
519 when intent == "lazy" {
520 session.push(message.user("The task isn't complete yet. Keep working until you have concrete results or hit a hard blocker."))
521 continue
522 }
523 break
524 }
525 tool_results = dispatch_all(tool_uses)
526 session.push(tool_results)
527 }
528 return text_concat(reply)
529}
530"#;
531
532pub fn ensure_managed_agent_at(config_dir: &Path) -> Result<()> {
533 let commands_dir = config_dir.join("commands");
534 std::fs::create_dir_all(&commands_dir)
535 .with_context(|| format!("mkdir {}", commands_dir.display()))?;
536 let agent_path = commands_dir.join("agent.at");
537 std::fs::write(&agent_path, AGENT_AT)
538 .with_context(|| format!("write {}", agent_path.display()))?;
539 let subagent_path = commands_dir.join("subagent.at");
540 std::fs::write(&subagent_path, SUBAGENT_AT)
541 .with_context(|| format!("write {}", subagent_path.display()))?;
542
543 let prompts_dir = config_dir.join("prompts");
544 std::fs::create_dir_all(&prompts_dir)
545 .with_context(|| format!("mkdir {}", prompts_dir.display()))?;
546 let system_md = prompts_dir.join("system.md");
547 std::fs::write(&system_md, SYSTEM_MD)
548 .with_context(|| format!("write {}", system_md.display()))?;
549
550 let prompt_files = [
551 ("role-research.md", ROLE_RESEARCH_MD),
552 ("role-verify.md", ROLE_VERIFY_MD),
553 ("role-implement.md", ROLE_IMPLEMENT_MD),
554 ("role-review.md", ROLE_REVIEW_MD),
555 ("judge-stall.md", JUDGE_STALL_MD),
556 ];
557 for (name, content) in &prompt_files {
558 let path = prompts_dir.join(name);
559 if !path.exists() {
560 std::fs::write(&path, content).with_context(|| format!("write {}", path.display()))?;
561 }
562 }
563
564 Ok(())
565}
566
567#[cfg(test)]
568mod tests {
569 use super::*;
570 use atman_dsl::parse::parse_file;
571
572 #[test]
573 fn agent_at_parses() {
574 let file = parse_file(AGENT_AT).expect("AGENT_AT must parse");
575 assert!(
576 file.flows.iter().any(|f| f.name.name == "agent"),
577 "agent flow must exist"
578 );
579 }
580
581 #[test]
582 fn subagent_at_parses() {
583 let file = parse_file(SUBAGENT_AT).expect("SUBAGENT_AT must parse");
584 let subagent = file
585 .flows
586 .iter()
587 .find(|f| f.name.name == "subagent")
588 .expect("subagent flow must exist");
589 assert!(
590 subagent.contract.as_ref().is_some_and(|contract| {
591 contract.blocks.iter().any(|block| {
592 block.name.name == "capabilities"
593 && block.kwargs.iter().any(|(name, value)| {
594 name.name == "shell"
595 && matches!(
596 value,
597 atman_dsl::ast::Expr::Literal(atman_dsl::ast::Literal::Bool(
598 true
599 ))
600 )
601 })
602 })
603 }),
604 "subagent entry must enable shell for inherited Tier Four tools"
605 );
606 }
607
608 #[test]
609 fn generic_system_prompt_explores_docs_without_fixed_paths() {
610 assert!(SYSTEM_MD.contains("## Before you do anything"));
611 assert!(SYSTEM_MD.contains("relevant Markdown"));
612 assert!(SYSTEM_MD.contains("descriptive documentation"));
613 for forbidden in [".local/", "Read AGENTS.md", "Read CLAUDE.md"] {
614 assert!(
615 !SYSTEM_MD.contains(forbidden),
616 "generic system prompt must not require `{forbidden}`"
617 );
618 }
619 }
620
621 fn flow_source(name: &str, next: Option<&str>) -> String {
622 let start = SUBAGENT_AT
623 .find(&format!("flow {name}("))
624 .expect("flow must exist");
625 let end = next
626 .and_then(|next| SUBAGENT_AT[start..].find(&format!("flow {next}(")))
627 .map(|offset| start + offset)
628 .unwrap_or(SUBAGENT_AT.len());
629 SUBAGENT_AT[start..end].to_string()
630 }
631
632 #[test]
633 fn subagent_tools_match_role_guidance() {
634 let research = flow_source("research_loop", Some("verify_loop"));
635 let verify = flow_source("verify_loop", Some("implement_loop"));
636 let implement = flow_source("implement_loop", Some("review_loop"));
637 let review = flow_source("review_loop", None);
638
639 for source in [&research, &verify, &implement, &review] {
640 for forbidden in [
641 "flow.spawn",
642 "flow.status",
643 "flow.output",
644 "flow.kill",
645 "flow.interject",
646 "flow.list",
647 "flow.check",
648 "watch",
649 "watcher.list",
650 "watcher.unwatch",
651 "wait_for_watcher",
652 ] {
653 assert!(!source.contains(&format!("\"{forbidden}\"")));
654 }
655 }
656 for required in ["term.spawn", "term.capture"] {
657 assert!(!research.contains(&format!("\"{required}\"")));
658 assert!(verify.contains(&format!("\"{required}\"")));
659 assert!(implement.contains(&format!("\"{required}\"")));
660 assert!(!review.contains(&format!("\"{required}\"")));
661 }
662 }
663}