Agent Creator (Lean Playbook)
This file is the default workflow-building guide.
Read this file first. Route into references/* when the task pattern calls for it.
0) Default Mode (Important)
Use Lean Mode by default:
- Keep to the shortest executable path.
- Prefer local patch fixes over full-file rewrites.
- Validate after each Python edit.
- Prefer not to continue to the next gate while the current gate is failing.
- Report
completed / partial / blocked truthfully.
Keep the build lean, but do not skip a pattern reference when the request clearly matches it. The right reference is part of the shortest reliable path.
0.1) Reference Routing (Pattern Library)
Use references as early design aids, not last-resort repair manuals.
Before designing or coding, scan the user request for domain patterns:
| If the request mentions... |
Read before design |
Use it to choose... |
| SQL, NL2SQL, database Q&A, table, column, schema, analytics, dashboard data, log audit, compliance/audit report, scheduled data report |
references/nl2sql.md |
tool-based exploration vs. process-based workflow, schema discovery, SQL validation, execution/report gates |
If no pattern matches, stay in this file and load references only when a concrete missing detail blocks progress.
0.2) Agent Construction Mental Model
A good AgentClaw workflow is not just code that runs; it is a small evidence pipeline that turns user intent into safe action.
Design the workflow in layers:
- Input contract: define what the user supplies and what output they expect.
- Evidence/discovery: gather facts the agent should not guess: files, schemas, APIs, current state, configs, and user rules.
- Reasoning/generation: use
LLMNode for interpretation, synthesis, SQL/code/report drafting, natural-language explanation, and ambiguous mapping.
- Validation/gating: use deterministic checks before execution, mutation, file writing, scheduling, or final claims.
- Action/output: execute only validated actions; write files or call APIs in small deterministic nodes.
- Final response: tell the user what happened, what was verified, and what remains blocked.
Prefer this split:
- deterministic nodes collect, normalize, compute, validate, persist, and call APIs;
LLMNode handles judgment, language, synthesis, uncertainty, and human-facing narrative;
- use
agent_style="agentic" when the workflow benefits from flexible tool-driven exploration.
1) Scope
This skill covers:
- agent/workflow inspection and iteration
- prompt and persona updates
- node prompt, routing, tool/skill configuration changes
- workflow design
- workflow file edits
- bootstrap wiring
- registration and runtime validation
- runtime behavior fixes
Low-level edit mechanics belong to coding_skill.
For coding tool usage (search_code, read_code, syntax_check, replace_in_file, update_code, write_file, etc.), always consult coding_skill first:
read_skill_file(skill_name="coding_skill") — tool contracts, edit strategies, validation standards
1.1 Design the Evidence Flow
Before designing or coding any workflow, identify the facts the agent needs in order to act safely and accurately.
Use this as a construction habit for all task types, not only database tasks:
- Separate known inputs from facts that must be discovered at runtime.
- When the agent depends on external facts (schemas, APIs, files, project structure, business rules, credentials, current state, or third-party contracts), design an explicit discovery step or ask the user for the source.
- Treat unknown domain facts as part of the workflow design, not as blanks to fill from model memory.
- For tasks where wrong facts can produce invalid output, place a validation gate before execution or final reporting.
- Prefer a slightly longer evidence-backed workflow over a short workflow that can only succeed by guessing.
Common evidence gates:
- Code/project agents: inspect files and verified APIs before editing.
- API agents: inspect OpenAPI/docs/sample responses before calling or generating clients.
- Data agents: inspect schema/data contracts before generating queries or reports.
- Automation agents: inspect current state before changing resources.
2) Minimal Build Loop (Default)
- Inspect existing workflow files and bootstrap entry (
server.py, workflows/*, agent.py).
- Align path bases from runtime context (
cwd, project_dir, skill_tools_working_dir, coding_tools_project_dir).
- Identify task-specific evidence requirements:
- What facts must be known before the agent can act?
- Can the workflow discover those facts at runtime?
- What validation gate prevents fabricated or stale facts from reaching execution?
- Verify local API facts before coding:
agentclaw/__init__.py
agentclaw/node/__init__.py
- Implement with valid local APIs only; do not guess imports or symbols.
- After each Python edit:
- If you used
write_code, syntax is already validated by the pre-write check. Call syntax_check separately only for files edited with replace_in_file or update_code.
python -m py_compile ... can be used for import-level validation. On Windows, py -3 -m py_compile is also acceptable.
- Pre-registration validation (must pass before registration):
- Verify the workflow file can be imported without errors:
shell(command="python -c \"import importlib.util; spec = importlib.util.spec_from_file_location('_check', '<file_path>'); mod = importlib.util.module_from_spec(spec); spec.loader.exec_module(mod)\"")
- This catches missing dependencies, undefined variables, syntax errors, and invalid imports.
- If import fails, fix the issue first: install packages via the shell tool, fix code, or add delayed imports, then re-validate.
- Import validation must pass before registration.
- Register workflow via HTTP API (hot-register):
POST /_internal/admin/workflows/register-file with {"file_path": "workflows/my_workflow.py", "force_replace": true}.
- Use the local-only
internal_url from the relay config as {BASE_URL}. The /_internal/ relay auto-injects auth server-side, so no manual Bearer token or key is needed.
- Hot-register executes
exec_module() on the file, so any module-level import error will fail registration.
- Verify registration by checking that
registered_workflow_ids contains the expected workflow ID.
- API details:
read_skill_file(skill_name="agentclaw_api", file_name="references/workflow_admin.md")
- Verify workflow discovery:
GET /_internal/admin/workflows returns {"workflows": [...]}.
- Confirm the registered workflow ID appears in the list.
- After successful registration, ensure bootstrap wiring:
- Add
import workflows.my_workflow in server.py, or import it via workflows/__init__.py, so the workflow loads after server restart.
- Add this import only after registration succeeds. Registration is the primary mechanism; the bootstrap import is for persistence across restarts.
- Validate runtime using streaming mode to avoid timeouts:
shell(command="curl -s -N -X POST {BASE_URL}/_internal/api/workflow/run -H 'Content-Type: application/json' -d '{\"workflow_id\": \"my_workflow\", \"inputs\": {...}, \"response_mode\": \"streaming\"}'", timeout=300)
- Streaming mode returns SSE events line by line.
event: workflow_finished indicates success; event: error indicates failure.
- For simple workflows, blocking mode is acceptable: use
response_mode: "blocking" with timeout=300 in the shell tool.
- API details:
read_skill_file(skill_name="agentclaw_api", file_name="references/workflow.md")
- Report results with evidence.
2.1 Simple Workflow Default
For simple workflows (single-node or short linear flows), default to:
agent_style="default"
enable_builtin_tools=False
Only enable agentic mode or broad builtin tools when the task needs multi-step tool orchestration, such as dynamic code execution, external API/browser operations, or complex planning.
2.1.1 Builtin Skills and Builtin Tools Tradeoff
Treat enable_builtin_skills and enable_builtin_tools as capability switches, not defaults for every workflow.
enable_builtin_skills=True
What it provides:
- Injects built-in skill guidance such as
agent_creator, coding_skill, and API usage playbooks when relevant.
- Helps the model follow project conventions, validated workflow patterns, tool contracts, and registration/validation gates.
- Useful when the agent itself needs to create, inspect, modify, debug, or validate AgentClaw project artifacts.
Costs:
- Adds skill descriptions and protocols to the prompt, increasing token usage.
- Can make simple agents more verbose or over-cautious if the task does not need project-building guidance.
- Skill quality and relevance matter; irrelevant skills can distract the agent.
Use when:
- The workflow is a builder, developer assistant, code assistant, workflow maintainer, prompt/config editor, or debugging agent.
- The agent should know AgentClaw conventions, project APIs, validation gates, or reusable construction patterns.
- The task benefits from reading task-specific playbooks before acting.
Avoid or keep off when:
- The workflow is a simple fixed-purpose Q&A, classifier, summarizer, extractor, or report formatter.
- The agent does not need to inspect or modify project structure, workflows, prompts, tools, or code.
enable_builtin_tools=True
What it provides:
- Exposes built-in tools for planning, file operations, code reading/editing, shell execution, and project interaction, depending on runtime configuration.
- Enables flexible agentic exploration and repair loops when combined with
agent_style="agentic".
- Lets the agent gather missing evidence from the real project/runtime instead of guessing.
Costs:
- Increases prompt size because tool schemas are included.
- Adds latency and token usage through multi-turn tool calls and tool results.
- Expands the action surface; risky tools may require confirmation and careful validation.
- Depends on tool descriptions and result quality. Poor tool results can mislead the agent.
Use when:
- The agent must inspect files, run commands, edit code, call APIs, operate the browser/computer, or interact with the project environment.
- The task is exploratory, open-ended, repair-oriented, or requires runtime evidence before acting.
- You are building an agentic developer/ops assistant rather than a deterministic business workflow.
Avoid or keep off when:
- The workflow has a known deterministic sequence and does not need runtime exploration.
- The agent should only transform provided input into output.
- Low latency, predictable cost, strict permissions, or small context size matters more than flexibility.
Recommended combinations
- Simple LLM task:
agent_style="default"
enable_builtin_skills=False
enable_builtin_tools=False
- Project-building or workflow-maintenance agent:
agent_style="agentic"
enable_builtin_skills=True
enable_builtin_tools=True
- Domain agent with custom tools only:
agent_style="agentic" only if flexible tool choice is needed
enable_builtin_skills=False
enable_builtin_tools=False
- pass explicit
tools=[...] instead
- Reliable scheduled/report workflow:
- prefer deterministic custom nodes plus targeted
LLMNode report generation
- keep broad builtin tools off unless the workflow truly needs dynamic runtime exploration
2.1.2 Agentic Mode Tradeoff
Use agent_style="agentic" as a deliberate architecture choice, not as a default escape hatch.
Strengths:
- Flexible: the model can decide which tools to call and adapt to incomplete or changing information.
- Easy to implement: one small agentic node plus clear tool descriptions can replace a large hand-wired workflow.
- Strong capability: tool use plus iterative reasoning often works better than a rigid path for open-ended, exploratory, or messy tasks.
Costs:
- Tool-dependent: quality depends heavily on tool coverage, tool descriptions, and tool result shape.
- Slower: multi-turn model/tool loops add latency and can hit workflow timeouts.
- Higher token usage: tool definitions, tool results, intermediate turns, and repeated context all increase token consumption.
Prefer agentic mode when exploration and adaptability matter more than predictable latency and cost. Prefer a deterministic or gated process when the task has a known sequence, strict validation requirements, scheduled execution, or high-volume usage.
When using agent_style="agentic", recommend setting the workflow execution timeout to 240 seconds unless the user asks for a different value. Agentic runs may include multiple model/tool turns, and 240s is the preferred default balance for demos and normal tasks.
2.1.3 Domain Pattern Selection
Before coding, choose which pattern the task needs:
- Direct generation: enough facts are already present in user input or state; a simple
LLMNode is acceptable.
- Tool-driven exploration: facts must be gathered dynamically with tools; use
agent_style="agentic" with an explicit tool-use protocol.
- Gated process: wrong facts can cause invalid actions; use deterministic discovery/validation nodes before generation or execution.
Favor gated processes for database agents, API mutation agents, infrastructure agents, filesystem mutation agents, scheduler agents, payment agents, permission agents, and report-generation agents.
For NL2SQL / SQL / database Q&A / analytics agents, read references/nl2sql.md before designing or coding so the workflow starts from schema evidence and SQL validation rather than a one-step SQL guess.
2.1.4 Data, Audit, and Report Agents
For log audit, data analysis, monitoring summary, scheduled report, compliance report, or incident report agents, keep a clear split between evidence collection and report authorship.
Target shape:
discover_contract
-> collect_data
-> normalize_and_compute
-> generate_report
-> write_report? if file output is required
-> format_response
Construction guidance:
discover_contract is deterministic and inspects the real source contract: database schema, table columns, API response shape, log format, file headers, or user-provided spec.
collect_data queries only fields proven by discover_contract. If several timestamp/status/user fields are possible, discover the actual columns first and build the query from confirmed fields.
normalize_and_compute is a good place for counts, time windows, top-N lists, structured evidence, and explicit labels such as keyword_match or rule_match.
- Let
LLMNode produce the human-facing report from structured evidence. Reports, summaries, risk explanations, recommendations, and Markdown narratives belong in generate_report by default.
- If a Markdown/file report is required, have
generate_report produce report_markdown, then use a small deterministic write_report node to write that exact content to disk.
- Category/risk rules are strongest when they come from the user, source metadata, or explicit configuration. If no rules are provided, surface uncertainty in the LLM report instead of presenting keyword matches as verified business conclusions.
- A clean final file puts
workflow.publish() last, after helper functions, custom nodes, edges/routers, and report-writing nodes are defined.
Common failure shapes to avoid:
- A single custom node that queries data, classifies risks, generates recommendations, writes Markdown, and returns success.
- Hardcoded candidate field lists without schema filtering.
- Pure keyword matching presented as an intelligent audit conclusion.
- Claiming report generation is validated when runtime failed, output directory is missing, schema discovery failed, or no report file was produced.
2.2 Tool Registration — Two Patterns
There are exactly two patterns for registering tools. Choose one per workflow:
Pattern A: @workflow.tool (recommended for most cases)
workflow = Workflow(id="my_wf", name="My Workflow", ...)
@workflow.tool
def query_db(sql: str, limit: int = 100, **kwargs):
"""Execute SQL query.
Args:
sql: The SQL query string
limit: Max rows to return
"""
import psycopg2 # delayed import
conn = psycopg2.connect(host=os.getenv("DB_HOST", "localhost"), ...)
...
workflow.add_node(LLMNode(id="agent", tools=["query_db"], ...))
workflow.publish()
Pattern B: ToolKit() + @toolkit.tool (for shared/reusable toolkits)
toolkit = ToolKit()
@toolkit.tool
def query_db(sql: str, limit: int = 100, **kwargs):
"""Execute SQL query.
Args:
sql: The SQL query string
limit: Max rows to return
"""
import psycopg2 # delayed import
conn = psycopg2.connect(host=os.getenv("DB_HOST", "localhost"), ...)
...
workflow = Workflow(id="my_wf", name="My Workflow", ...)
workflow.register_toolkit(toolkit)
workflow.add_node(LLMNode(id="agent", tools=["query_db"], ...))
workflow.publish()
Rules:
@workflow.tool — define Workflow first, then decorate functions. Tools auto-attach.
ToolKit pattern — define toolkit = ToolKit() first, decorate with @toolkit.tool, then call workflow.register_toolkit(toolkit) after creating the Workflow.
register_toolkit() accepts only a ToolKit instance. Passing a bare function raises TypeError.
- The standalone
@tool decorator (from agentclaw import tool) only marks a function — it requires toolkit.register(fn) to attach. Prefer @toolkit.tool or @workflow.tool instead.
- Third-party imports used by tools must be delayed (inside function body), so the file can be loaded even if the dependency is not yet installed.
- Tool documentation is auto-extracted from function signatures and Google-style docstrings.
workflow = Workflow(id="my_wf", name="My Workflow", ...)
workflow.register_toolkit(toolkit)
workflow.publish()
### 2.3 Inputs Schema Requirement
When defining `user_input` parameter, `inputs` schema is **mandatory**:
```python
workflow = Workflow(
id="nl2sql",
name="NL2SQL",
user_input="user_query", # parameter name
inputs={"user_query": {"type": "string"}} # schema definition (key must match user_input)
)
Rules:
inputs key must match user_input value
- Type must be specified:
{"type": "string"} or str (shorthand)
- Missing
inputs causes registration failure
Shorthand:
inputs={"user_query": str} # equivalent to {"type": "string"}
2.4 Node Selection
LLMNode - Primary node for LLM-based tasks:
- LLM reasoning and generation
- Tool calling with
agent_style="agentic"
- Example: NL2SQL, code generation, Q&A
- When creating an
LLMNode, do not specify model_id by default; let it inherit the workflow/system default model unless the user explicitly asks for a specific model.
HumanNode - Human approval or input gates
CustomNode - Custom logic and data transformation
2.5 Workflow Wiring Canonical Pattern
Use the repository-native wiring pattern:
workflow = Workflow(id="...", name="...", ...)
- define nodes (
workflow.add_node(...) or decorators)
- connect start:
workflow.add_edge("__start__", "<first_node>")
- connect intermediate edges:
workflow.add_edge("a", "b")
- end edge is optional:
- explicit:
workflow.add_edge("<last_node>", "__end__")
- implicit: no outgoing edge on last node also ends execution
- publish:
workflow.publish()
2.6 Package Installation
When a workflow depends on third-party packages (e.g. psycopg2-binary, requests, pandas):
- Always use the
shell tool to install packages. The shell tool automatically activates the project venv (injects VIRTUAL_ENV and venv PATH), so pip install runs inside the correct environment.
- Use the
shell tool for pip install — the shell tool handles venv activation automatically, avoiding PEP 668 environment errors.
- Install before writing workflow code that imports the package.
Example:
shell(command="pip install psycopg2-binary")
Rules:
- Install packages one at a time or as a single
pip install pkg1 pkg2 command via the shell tool
- Verify installation success from the shell tool output before proceeding
- Use
-binary variants when available (e.g. psycopg2-binary instead of psycopg2) to avoid build dependencies
- Third-party package imports should use delayed imports inside function bodies (see §2.2)
Use only verified AgentClaw APIs:
- Workflow construction:
Workflow(id="...", name="...", inputs=..., user_input="...")
- Node management:
workflow.add_node(node_instance)
- Edge connection:
workflow.add_edge(from_node, to_node)
- Routing:
workflow.add_router(after="...", routes={...}, condition=...)
- Publishing:
workflow.publish()
- Node classes:
LLMNode, HumanNode, MCPNode, CustomNode
- Decorators:
@workflow.node(id), @workflow.tool
Before using any API, verify it exists in agentclaw/__init__.py or agentclaw/node/__init__.py.
3) API Fact Rule (No Fabricated Imports)
Before final write/register, confirm imports in local repo runtime:
- Prefer root imports:
from agentclaw import Workflow, LLMNode, ...
- If submodule imports are used, verify both module path and exported symbol.
- If uncertain, use
search_code / read_code first.
Always verify module paths in local repo runtime before use.
3.1) API Verification Checklist
Before generating workflow code, execute this verification sequence:
Read API fact sources:
read_code(path="agentclaw/__init__.py")
read_code(path="agentclaw/node/__init__.py")
Verify each class:
- Use
search_code to confirm class exists
- Confirm import path is correct
Verify each method:
- Confirm method signature and parameters
- Only use verified methods
Record verification:
- Before code generation, list all APIs to be used
- Confirm each API is verified and exists
Only proceed with code generation after all APIs are verified.
4) Path Rule (No Hardcoded Paths)
- Avoid hardcoded machine-specific absolute paths.
- Resolve path errors using current runtime path bases first.
- If
path_not_found appears, fix path base mismatch before retrying downstream steps.
5) Edit Rule (Patch-First)
- Existing file fix: patch local failing region first.
- Full-file rewrite: only when local fixes repeatedly fail or structure is corrupted.
- Syntax must pass before proceeding to register/runtime checks.
- For an existing file, avoid repeated
write_file loops; prefer replace_in_file / update_code for second and later edits in the same task.
6) Validation Gates
Execute gates in strict order. Each gate must pass before proceeding to the next.
Gate 1: Syntax Validation
- Tool:
syntax_check(path=...)
- Pass criteria:
ok=true
- On failure:
- Read
error_code and candidate_fixes from tool output
- Use
replace_in_file or update_code for local fix
- Re-run
syntax_check
- Must pass before proceeding to Gate 2
Gate 2: Compilation Validation
- Tool:
python -m py_compile <file>
- Pass criteria: exit code 0
- On failure:
- Analyze compilation error message
- Apply local fix
- Re-compile
- Must pass before proceeding to Gate 3
Gate 3: Registration Validation
- Tool call:
python(file="scripts/register_workflow.py", skill_name="agent_creator", args=["<file_path>"])
- Path rule:
skill_name="agent_creator" tells the python tool to resolve file relative to the agent_creator skill directory. Always pass skill_name.
- Pass criteria:
register_ok=true in JSON output
- On failure:
- Read
issues[].code from output
- Fix each issue by priority
- Re-run script
- Must pass before proceeding to Gate 4
Gate 4: Runtime Validation
- Tool call:
python(file="scripts/validate_workflow.py", skill_name="agent_creator", args=["<workflow_id>", "--inputs", "{...}"])
- Path rule: same as Gate 3; always pass
skill_name="agent_creator".
- Pass criteria:
all_ok=true in JSON output
- On failure:
- Check
register_ok, run_ok, api_ok fields
- Locate failure step
- Fix and re-validate
- Must pass to report
completed
Gate Execution Rules
- Execute gates in order (1 → 2 → 3 → 4)
- Each gate must pass before advancing
- All gates must pass to report
completed status
- Each gate must pass before advancing to the next
7) Structured Result Interpretation
For register_workflow.py and validate_workflow.py script output, read structured JSON fields first:
- registration:
register_ok, error_class, issues[].code, bootstrap_sync
- runtime:
ok, all_ok, runtime_access_ok, register_ok, run_ok, api_ok, root_cause_hint
Prefer structured fields over prose text when judging success.
8) Anti-Hardcoding
- Read secrets/tokens/passwords from environment variables.
- Prefer config/env values over in-source constants.
- Avoid environment-specific install guidance by default.
9) Output Contract
Final report should include:
changed_files
design_summary
validation (py_compile, bootstrap, register, runtime)
evidence (tool outcome facts)
status (completed / partial / blocked)
next_step
9.1) Status Determination Rules
completed - Report only when ALL criteria met:
- ✅ Gate 1 (syntax_check):
ok=true
- ✅ Gate 2 (py_compile): exit code 0
- ✅ Gate 3 (register_workflow.py):
register_ok=true
- ✅ Gate 4 (validate_workflow.py):
all_ok=true
- ✅ All modified files listed
- ✅ Validation evidence provided
partial - Report when:
- Gates 1-2 pass but Gates 3-4 fail
- Code generated but validation incomplete
- Known issues exist but basic functionality works
blocked - Report when:
- Gate 1 (syntax) fails repeatedly
- Path issues cannot be resolved
- API verification fails with no alternative
- User input required to proceed
Report status accurately with supporting evidence.
10) On-Demand References
Read only the minimum required file:
references/nl2sql.md: NL2SQL / SQL / database Q&A agent patterns, including tool-based and process-based designs
1---2name: agent-creator-23description: Create or modify AgentClaw workflows and agents from natural-language requirements. Use when changing workflow architecture, nodes, prompts, persona, routing, tool/skill configuration, runtime behavior, validation gates, registration, or project wiring.4---56# Agent Creator (Lean Playbook)78This file is the default workflow-building guide.9Read this file first. Route into `references/*` when the task pattern calls for it.1011## 0) Default Mode (Important)1213Use **Lean Mode** by default:14151. Keep to the shortest executable path.162. Prefer local patch fixes over full-file rewrites.173. Validate after each Python edit.184. Prefer not to continue to the next gate while the current gate is failing.195. Report `completed` / `partial` / `blocked` truthfully.2021Keep the build lean, but do not skip a pattern reference when the request clearly matches it. The right reference is part of the shortest reliable path.2223## 0.1) Reference Routing (Pattern Library)2425Use references as early design aids, not last-resort repair manuals.2627Before designing or coding, scan the user request for domain patterns:2829| If the request mentions... | Read before design | Use it to choose... |30| --- | --- | --- |31| SQL, NL2SQL, database Q&A, table, column, schema, analytics, dashboard data, log audit, compliance/audit report, scheduled data report | `references/nl2sql.md` | tool-based exploration vs. process-based workflow, schema discovery, SQL validation, execution/report gates |3233If no pattern matches, stay in this file and load references only when a concrete missing detail blocks progress.3435## 0.2) Agent Construction Mental Model3637A good AgentClaw workflow is not just code that runs; it is a small evidence pipeline that turns user intent into safe action.3839Design the workflow in layers:40411. **Input contract**: define what the user supplies and what output they expect.422. **Evidence/discovery**: gather facts the agent should not guess: files, schemas, APIs, current state, configs, and user rules.433. **Reasoning/generation**: use `LLMNode` for interpretation, synthesis, SQL/code/report drafting, natural-language explanation, and ambiguous mapping.444. **Validation/gating**: use deterministic checks before execution, mutation, file writing, scheduling, or final claims.455. **Action/output**: execute only validated actions; write files or call APIs in small deterministic nodes.466. **Final response**: tell the user what happened, what was verified, and what remains blocked.4748Prefer this split:49- deterministic nodes collect, normalize, compute, validate, persist, and call APIs;50- `LLMNode` handles judgment, language, synthesis, uncertainty, and human-facing narrative;51- use `agent_style="agentic"` when the workflow benefits from flexible tool-driven exploration.5253## 1) Scope5455This skill covers:56- agent/workflow inspection and iteration57- prompt and persona updates58- node prompt, routing, tool/skill configuration changes59- workflow design60- workflow file edits61- bootstrap wiring62- registration and runtime validation63- runtime behavior fixes6465Low-level edit mechanics belong to `coding_skill`.66For coding tool usage (`search_code`, `read_code`, `syntax_check`, `replace_in_file`, `update_code`, `write_file`, etc.), **always consult `coding_skill` first**:67- `read_skill_file(skill_name="coding_skill")` — tool contracts, edit strategies, validation standards6869### 1.1 Design the Evidence Flow7071Before designing or coding any workflow, identify the facts the agent needs in order to act safely and accurately.7273Use this as a construction habit for all task types, not only database tasks:74751. Separate **known inputs** from **facts that must be discovered at runtime**.762. When the agent depends on external facts (schemas, APIs, files, project structure, business rules, credentials, current state, or third-party contracts), design an explicit discovery step or ask the user for the source.773. Treat unknown domain facts as part of the workflow design, not as blanks to fill from model memory.784. For tasks where wrong facts can produce invalid output, place a validation gate before execution or final reporting.795. Prefer a slightly longer evidence-backed workflow over a short workflow that can only succeed by guessing.8081Common evidence gates:82- Code/project agents: inspect files and verified APIs before editing.83- API agents: inspect OpenAPI/docs/sample responses before calling or generating clients.84- Data agents: inspect schema/data contracts before generating queries or reports.85- Automation agents: inspect current state before changing resources.8687## 2) Minimal Build Loop (Default)88891. Inspect existing workflow files and bootstrap entry (`server.py`, `workflows/*`, `agent.py`).902. Align path bases from runtime context (`cwd`, `project_dir`, `skill_tools_working_dir`, `coding_tools_project_dir`).913. Identify task-specific evidence requirements:92 - What facts must be known before the agent can act?93 - Can the workflow discover those facts at runtime?94 - What validation gate prevents fabricated or stale facts from reaching execution?954. Verify local API facts before coding:96 - `agentclaw/__init__.py`97 - `agentclaw/node/__init__.py`985. Implement with valid local APIs only; do not guess imports or symbols.996. After each Python edit:100 - If you used `write_code`, syntax is already validated by the pre-write check. Call `syntax_check` separately only for files edited with `replace_in_file` or `update_code`.101 - `python -m py_compile ...` can be used for import-level validation. On Windows, `py -3 -m py_compile` is also acceptable.1027. **Pre-registration validation** (must pass before registration):103 - Verify the workflow file can be imported without errors:104 `shell(command="python -c \"import importlib.util; spec = importlib.util.spec_from_file_location('_check', '<file_path>'); mod = importlib.util.module_from_spec(spec); spec.loader.exec_module(mod)\"")`105 - This catches missing dependencies, undefined variables, syntax errors, and invalid imports.106 - If import fails, fix the issue first: install packages via the shell tool, fix code, or add delayed imports, then re-validate.107 - Import validation must pass before registration.1088. Register workflow via HTTP API (hot-register):109 - `POST /_internal/admin/workflows/register-file` with `{"file_path": "workflows/my_workflow.py", "force_replace": true}`.110 - Use the local-only `internal_url` from the relay config as `{BASE_URL}`. The `/_internal/` relay auto-injects auth server-side, so no manual Bearer token or key is needed.111 - Hot-register executes `exec_module()` on the file, so any module-level import error will fail registration.112 - Verify registration by checking that `registered_workflow_ids` contains the expected workflow ID.113 - API details: `read_skill_file(skill_name="agentclaw_api", file_name="references/workflow_admin.md")`1149. Verify workflow discovery:115 - `GET /_internal/admin/workflows` returns `{"workflows": [...]}`.116 - Confirm the registered workflow ID appears in the list.11710. **After successful registration**, ensure bootstrap wiring:118 - Add `import workflows.my_workflow` in `server.py`, or import it via `workflows/__init__.py`, so the workflow loads after server restart.119 - Add this import only after registration succeeds. Registration is the primary mechanism; the bootstrap import is for persistence across restarts.12011. Validate runtime using **streaming mode** to avoid timeouts:121 - `shell(command="curl -s -N -X POST {BASE_URL}/_internal/api/workflow/run -H 'Content-Type: application/json' -d '{\"workflow_id\": \"my_workflow\", \"inputs\": {...}, \"response_mode\": \"streaming\"}'", timeout=300)`122 - Streaming mode returns SSE events line by line. `event: workflow_finished` indicates success; `event: error` indicates failure.123 - For simple workflows, blocking mode is acceptable: use `response_mode: "blocking"` with `timeout=300` in the shell tool.124 - API details: `read_skill_file(skill_name="agentclaw_api", file_name="references/workflow.md")`12512. Report results with evidence.126127### 2.1 Simple Workflow Default128129For simple workflows (single-node or short linear flows), default to:1301311. `agent_style="default"`1322. `enable_builtin_tools=False`133134Only enable `agentic` mode or broad builtin tools when the task needs multi-step tool orchestration, such as dynamic code execution, external API/browser operations, or complex planning.135136### 2.1.1 Builtin Skills and Builtin Tools Tradeoff137138Treat `enable_builtin_skills` and `enable_builtin_tools` as capability switches, not defaults for every workflow.139140#### `enable_builtin_skills=True`141142What it provides:143- Injects built-in skill guidance such as `agent_creator`, `coding_skill`, and API usage playbooks when relevant.144- Helps the model follow project conventions, validated workflow patterns, tool contracts, and registration/validation gates.145- Useful when the agent itself needs to create, inspect, modify, debug, or validate AgentClaw project artifacts.146147Costs:148- Adds skill descriptions and protocols to the prompt, increasing token usage.149- Can make simple agents more verbose or over-cautious if the task does not need project-building guidance.150- Skill quality and relevance matter; irrelevant skills can distract the agent.151152Use when:153- The workflow is a builder, developer assistant, code assistant, workflow maintainer, prompt/config editor, or debugging agent.154- The agent should know AgentClaw conventions, project APIs, validation gates, or reusable construction patterns.155- The task benefits from reading task-specific playbooks before acting.156157Avoid or keep off when:158- The workflow is a simple fixed-purpose Q&A, classifier, summarizer, extractor, or report formatter.159- The agent does not need to inspect or modify project structure, workflows, prompts, tools, or code.160161#### `enable_builtin_tools=True`162163What it provides:164- Exposes built-in tools for planning, file operations, code reading/editing, shell execution, and project interaction, depending on runtime configuration.165- Enables flexible agentic exploration and repair loops when combined with `agent_style="agentic"`.166- Lets the agent gather missing evidence from the real project/runtime instead of guessing.167168Costs:169- Increases prompt size because tool schemas are included.170- Adds latency and token usage through multi-turn tool calls and tool results.171- Expands the action surface; risky tools may require confirmation and careful validation.172- Depends on tool descriptions and result quality. Poor tool results can mislead the agent.173174Use when:175- The agent must inspect files, run commands, edit code, call APIs, operate the browser/computer, or interact with the project environment.176- The task is exploratory, open-ended, repair-oriented, or requires runtime evidence before acting.177- You are building an agentic developer/ops assistant rather than a deterministic business workflow.178179Avoid or keep off when:180- The workflow has a known deterministic sequence and does not need runtime exploration.181- The agent should only transform provided input into output.182- Low latency, predictable cost, strict permissions, or small context size matters more than flexibility.183184#### Recommended combinations1851861. Simple LLM task:187 - `agent_style="default"`188 - `enable_builtin_skills=False`189 - `enable_builtin_tools=False`1902. Project-building or workflow-maintenance agent:191 - `agent_style="agentic"`192 - `enable_builtin_skills=True`193 - `enable_builtin_tools=True`1943. Domain agent with custom tools only:195 - `agent_style="agentic"` only if flexible tool choice is needed196 - `enable_builtin_skills=False`197 - `enable_builtin_tools=False`198 - pass explicit `tools=[...]` instead1994. Reliable scheduled/report workflow:200 - prefer deterministic custom nodes plus targeted `LLMNode` report generation201 - keep broad builtin tools off unless the workflow truly needs dynamic runtime exploration202203### 2.1.2 Agentic Mode Tradeoff204205Use `agent_style="agentic"` as a deliberate architecture choice, not as a default escape hatch.206207Strengths:208- Flexible: the model can decide which tools to call and adapt to incomplete or changing information.209- Easy to implement: one small agentic node plus clear tool descriptions can replace a large hand-wired workflow.210- Strong capability: tool use plus iterative reasoning often works better than a rigid path for open-ended, exploratory, or messy tasks.211212Costs:213- Tool-dependent: quality depends heavily on tool coverage, tool descriptions, and tool result shape.214- Slower: multi-turn model/tool loops add latency and can hit workflow timeouts.215- Higher token usage: tool definitions, tool results, intermediate turns, and repeated context all increase token consumption.216217Prefer agentic mode when exploration and adaptability matter more than predictable latency and cost. Prefer a deterministic or gated process when the task has a known sequence, strict validation requirements, scheduled execution, or high-volume usage.218219When using `agent_style="agentic"`, recommend setting the workflow execution timeout to `240` seconds unless the user asks for a different value. Agentic runs may include multiple model/tool turns, and `240s` is the preferred default balance for demos and normal tasks.220221### 2.1.3 Domain Pattern Selection222223Before coding, choose which pattern the task needs:2242251. **Direct generation**: enough facts are already present in user input or state; a simple `LLMNode` is acceptable.2262. **Tool-driven exploration**: facts must be gathered dynamically with tools; use `agent_style="agentic"` with an explicit tool-use protocol.2273. **Gated process**: wrong facts can cause invalid actions; use deterministic discovery/validation nodes before generation or execution.228229Favor gated processes for database agents, API mutation agents, infrastructure agents, filesystem mutation agents, scheduler agents, payment agents, permission agents, and report-generation agents.230231For NL2SQL / SQL / database Q&A / analytics agents, read `references/nl2sql.md` before designing or coding so the workflow starts from schema evidence and SQL validation rather than a one-step SQL guess.232233### 2.1.4 Data, Audit, and Report Agents234235For log audit, data analysis, monitoring summary, scheduled report, compliance report, or incident report agents, keep a clear split between evidence collection and report authorship.236237Target shape:238239```text240discover_contract241 -> collect_data242 -> normalize_and_compute243 -> generate_report244 -> write_report? if file output is required245 -> format_response246```247248Construction guidance:2491. `discover_contract` is deterministic and inspects the real source contract: database schema, table columns, API response shape, log format, file headers, or user-provided spec.2502. `collect_data` queries only fields proven by `discover_contract`. If several timestamp/status/user fields are possible, discover the actual columns first and build the query from confirmed fields.2513. `normalize_and_compute` is a good place for counts, time windows, top-N lists, structured evidence, and explicit labels such as `keyword_match` or `rule_match`.2524. Let `LLMNode` produce the human-facing report from structured evidence. Reports, summaries, risk explanations, recommendations, and Markdown narratives belong in `generate_report` by default.2535. If a Markdown/file report is required, have `generate_report` produce `report_markdown`, then use a small deterministic `write_report` node to write that exact content to disk.2546. Category/risk rules are strongest when they come from the user, source metadata, or explicit configuration. If no rules are provided, surface uncertainty in the LLM report instead of presenting keyword matches as verified business conclusions.2557. A clean final file puts `workflow.publish()` last, after helper functions, custom nodes, edges/routers, and report-writing nodes are defined.256257Common failure shapes to avoid:258- A single custom node that queries data, classifies risks, generates recommendations, writes Markdown, and returns success.259- Hardcoded candidate field lists without schema filtering.260- Pure keyword matching presented as an intelligent audit conclusion.261- Claiming report generation is validated when runtime failed, output directory is missing, schema discovery failed, or no report file was produced.262263### 2.2 Tool Registration — Two Patterns264265There are exactly **two** patterns for registering tools. Choose one per workflow:266267**Pattern A: `@workflow.tool` (recommended for most cases)**268269```python270workflow = Workflow(id="my_wf", name="My Workflow", ...)271272@workflow.tool273def query_db(sql: str, limit: int = 100, **kwargs):274 """Execute SQL query.275276 Args:277 sql: The SQL query string278 limit: Max rows to return279 """280 import psycopg2 # delayed import281 conn = psycopg2.connect(host=os.getenv("DB_HOST", "localhost"), ...)282 ...283284workflow.add_node(LLMNode(id="agent", tools=["query_db"], ...))285workflow.publish()286```287288**Pattern B: `ToolKit()` + `@toolkit.tool` (for shared/reusable toolkits)**289290```python291toolkit = ToolKit()292293@toolkit.tool294def query_db(sql: str, limit: int = 100, **kwargs):295 """Execute SQL query.296297 Args:298 sql: The SQL query string299 limit: Max rows to return300 """301 import psycopg2 # delayed import302 conn = psycopg2.connect(host=os.getenv("DB_HOST", "localhost"), ...)303 ...304305workflow = Workflow(id="my_wf", name="My Workflow", ...)306workflow.register_toolkit(toolkit)307workflow.add_node(LLMNode(id="agent", tools=["query_db"], ...))308workflow.publish()309```310311**Rules**:3121. `@workflow.tool` — define Workflow first, then decorate functions. Tools auto-attach.3132. `ToolKit` pattern — define `toolkit = ToolKit()` first, decorate with `@toolkit.tool`, then call `workflow.register_toolkit(toolkit)` after creating the Workflow.3143. `register_toolkit()` accepts only a `ToolKit` instance. Passing a bare function raises `TypeError`.3154. The standalone `@tool` decorator (from `agentclaw import tool`) only marks a function — it requires `toolkit.register(fn)` to attach. Prefer `@toolkit.tool` or `@workflow.tool` instead.3165. Third-party imports used by tools must be **delayed** (inside function body), so the file can be loaded even if the dependency is not yet installed.3176. Tool documentation is auto-extracted from function signatures and Google-style docstrings.318319workflow = Workflow(id="my_wf", name="My Workflow", ...)320workflow.register_toolkit(toolkit)321workflow.publish()322```323324### 2.3 Inputs Schema Requirement325326When defining `user_input` parameter, `inputs` schema is **mandatory**:327328```python329workflow = Workflow(330 id="nl2sql",331 name="NL2SQL",332 user_input="user_query", # parameter name333 inputs={"user_query": {"type": "string"}} # schema definition (key must match user_input)334)335```336337**Rules**:3381. `inputs` key must match `user_input` value3392. Type must be specified: `{"type": "string"}` or `str` (shorthand)3403. Missing `inputs` causes registration failure341342**Shorthand**:343```python344inputs={"user_query": str} # equivalent to {"type": "string"}345```346347### 2.4 Node Selection348349**LLMNode** - Primary node for LLM-based tasks:350- LLM reasoning and generation351- Tool calling with `agent_style="agentic"`352- Example: NL2SQL, code generation, Q&A353- When creating an `LLMNode`, do not specify `model_id` by default; let it inherit the workflow/system default model unless the user explicitly asks for a specific model.354355**HumanNode** - Human approval or input gates356357**CustomNode** - Custom logic and data transformation358359### 2.5 Workflow Wiring Canonical Pattern360361Use the repository-native wiring pattern:3623631. `workflow = Workflow(id="...", name="...", ...)`3642. define nodes (`workflow.add_node(...)` or decorators)3653. connect start: `workflow.add_edge("__start__", "<first_node>")`3664. connect intermediate edges: `workflow.add_edge("a", "b")`3675. end edge is optional:368 - explicit: `workflow.add_edge("<last_node>", "__end__")`369 - implicit: no outgoing edge on last node also ends execution3706. publish: `workflow.publish()`371372### 2.6 Package Installation373374When a workflow depends on third-party packages (e.g. `psycopg2-binary`, `requests`, `pandas`):3753761. **Always use the `shell` tool** to install packages. The shell tool automatically activates the project venv (injects `VIRTUAL_ENV` and venv `PATH`), so `pip install` runs inside the correct environment.3772. **Use the `shell` tool** for `pip install` — the shell tool handles venv activation automatically, avoiding PEP 668 environment errors.3783. Install **before** writing workflow code that imports the package.379380**Example**:381```382shell(command="pip install psycopg2-binary")383```384385**Rules**:3861. Install packages one at a time or as a single `pip install pkg1 pkg2` command via the shell tool3872. Verify installation success from the shell tool output before proceeding3883. Use `-binary` variants when available (e.g. `psycopg2-binary` instead of `psycopg2`) to avoid build dependencies3894. Third-party package imports should use delayed imports inside function bodies (see §2.2)390391Use only verified AgentClaw APIs:3923931. **Workflow construction**: `Workflow(id="...", name="...", inputs=..., user_input="...")`3942. **Node management**: `workflow.add_node(node_instance)`3953. **Edge connection**: `workflow.add_edge(from_node, to_node)`3964. **Routing**: `workflow.add_router(after="...", routes={...}, condition=...)`3975. **Publishing**: `workflow.publish()`3986. **Node classes**: `LLMNode`, `HumanNode`, `MCPNode`, `CustomNode`3997. **Decorators**: `@workflow.node(id)`, `@workflow.tool`400401Before using any API, verify it exists in `agentclaw/__init__.py` or `agentclaw/node/__init__.py`.402403## 3) API Fact Rule (No Fabricated Imports)404405Before final write/register, confirm imports in local repo runtime:4064071. Prefer root imports:408 - `from agentclaw import Workflow, LLMNode, ...`4092. If submodule imports are used, verify both module path and exported symbol.4103. If uncertain, use `search_code` / `read_code` first.411412Always verify module paths in local repo runtime before use.413414### 3.1) API Verification Checklist415416Before generating workflow code, execute this verification sequence:4174181. **Read API fact sources**:419 - `read_code(path="agentclaw/__init__.py")`420 - `read_code(path="agentclaw/node/__init__.py")`4214222. **Verify each class**:423 - Use `search_code` to confirm class exists424 - Confirm import path is correct4254263. **Verify each method**:427 - Confirm method signature and parameters428 - Only use verified methods4294304. **Record verification**:431 - Before code generation, list all APIs to be used432 - Confirm each API is verified and exists433434Only proceed with code generation after all APIs are verified.435436## 4) Path Rule (No Hardcoded Paths)4374381. Avoid hardcoded machine-specific absolute paths.4392. Resolve path errors using current runtime path bases first.4403. If `path_not_found` appears, fix path base mismatch before retrying downstream steps.441442## 5) Edit Rule (Patch-First)4434441. Existing file fix: patch local failing region first.4452. Full-file rewrite: only when local fixes repeatedly fail or structure is corrupted.4463. Syntax must pass before proceeding to register/runtime checks.4474. For an existing file, avoid repeated `write_file` loops; prefer `replace_in_file` / `update_code` for second and later edits in the same task.448449## 6) Validation Gates450451Execute gates in strict order. Each gate must pass before proceeding to the next.452453### Gate 1: Syntax Validation454- **Tool**: `syntax_check(path=...)`455- **Pass criteria**: `ok=true`456- **On failure**:457 1. Read `error_code` and `candidate_fixes` from tool output458 2. Use `replace_in_file` or `update_code` for local fix459 3. Re-run `syntax_check`460 4. Must pass before proceeding to Gate 2461462### Gate 2: Compilation Validation463- **Tool**: `python -m py_compile <file>`464- **Pass criteria**: exit code 0465- **On failure**:466 1. Analyze compilation error message467 2. Apply local fix468 3. Re-compile469 4. Must pass before proceeding to Gate 3470471### Gate 3: Registration Validation472- **Tool call**: `python(file="scripts/register_workflow.py", skill_name="agent_creator", args=["<file_path>"])`473- **Path rule**: `skill_name="agent_creator"` tells the python tool to resolve `file` relative to the agent_creator skill directory. Always pass `skill_name`.474- **Pass criteria**: `register_ok=true` in JSON output475- **On failure**:476 1. Read `issues[].code` from output477 2. Fix each issue by priority478 3. Re-run script479 4. Must pass before proceeding to Gate 4480481### Gate 4: Runtime Validation482- **Tool call**: `python(file="scripts/validate_workflow.py", skill_name="agent_creator", args=["<workflow_id>", "--inputs", "{...}"])`483- **Path rule**: same as Gate 3; always pass `skill_name="agent_creator"`.484- **Pass criteria**: `all_ok=true` in JSON output485- **On failure**:486 1. Check `register_ok`, `run_ok`, `api_ok` fields487 2. Locate failure step488 3. Fix and re-validate489 4. Must pass to report `completed`490491### Gate Execution Rules4921. Execute gates in order (1 → 2 → 3 → 4)4932. Each gate must pass before advancing4943. All gates must pass to report `completed` status4954. Each gate must pass before advancing to the next496497## 7) Structured Result Interpretation498499For `register_workflow.py` and `validate_workflow.py` script output, read structured JSON fields first:500501- registration: `register_ok`, `error_class`, `issues[].code`, `bootstrap_sync`502- runtime: `ok`, `all_ok`, `runtime_access_ok`, `register_ok`, `run_ok`, `api_ok`, `root_cause_hint`503504Prefer structured fields over prose text when judging success.505506## 8) Anti-Hardcoding5075081. Read secrets/tokens/passwords from environment variables.5092. Prefer config/env values over in-source constants.5103. Avoid environment-specific install guidance by default.511512## 9) Output Contract513514Final report should include:5155161. `changed_files`5172. `design_summary`5183. `validation` (`py_compile`, bootstrap, register, runtime)5194. `evidence` (tool outcome facts)5205. `status` (`completed` / `partial` / `blocked`)5216. `next_step`522523### 9.1) Status Determination Rules524525**completed** - Report only when ALL criteria met:5261. ✅ Gate 1 (syntax_check): `ok=true`5272. ✅ Gate 2 (py_compile): exit code 05283. ✅ Gate 3 (register_workflow.py): `register_ok=true`5294. ✅ Gate 4 (validate_workflow.py): `all_ok=true`5305. ✅ All modified files listed5316. ✅ Validation evidence provided532533**partial** - Report when:5341. Gates 1-2 pass but Gates 3-4 fail5352. Code generated but validation incomplete5363. Known issues exist but basic functionality works537538**blocked** - Report when:5391. Gate 1 (syntax) fails repeatedly5402. Path issues cannot be resolved5413. API verification fails with no alternative5424. User input required to proceed543544Report status accurately with supporting evidence.545546## 10) On-Demand References547548Read only the minimum required file:549550- `references/nl2sql.md`: NL2SQL / SQL / database Q&A agent patterns, including tool-based and process-based designs