- Established a unified calling mechanism for agents, enabling streaming support and multi-turn conversations. - Developed input formatters for various phases, ensuring proper data preparation for assistant prompts. - Created test assistants for single and multi-turn interactions, along with comprehensive test cases for the AgentCaller and InputFormatter. - Updated the TODO.md to reflect the new structure and progress of the agent call infrastructure, including future phases for assistant setup and implementation.
32 KiB
Robot Agent - Implementation TODO
Based on DESIGN.md and TECHNICAL.md Test environment:
source yao/env.local.shTest assistants:yao-dev-app/assistants/robot/
Workflow: Human-AI Collaboration
Important: Follow this workflow strictly for each sub-task.
┌─────────────────────────────────────────────────────────────────┐
│ Implementation Workflow │
├─────────────────────────────────────────────────────────────────┤
│ 1. AI: Implement code for current sub-task │
│ 2. AI: Present code for review (DO NOT write tests yet) │
│ 3. Human: Review code, provide feedback │
│ 4. AI: Iterate based on feedback │
│ 5. Human: Confirm "LGTM" or "Approved" │
│ 6. AI: Write tests for the approved code │
│ 7. Human: Review tests │
│ 8. AI: Run tests, fix if needed │
│ 9. Human: Confirm sub-task complete, move to next │
└─────────────────────────────────────────────────────────────────┘
Rules:
| Rule | Description |
|---|---|
| One sub-task at a time | Focus only on current sub-task |
| No tests before approval | Wait for human "LGTM" before writing tests |
| No jumping ahead | Do not implement future phases |
| Ask if unclear | When in doubt, ask before proceeding |
Core Principle
- Phase 1-2: Types + Skeleton (code compiles)
- Phase 3: Complete scheduling system (Cache + Pool + Trigger + Dedup + Job), executor is stub
- Phase 4-9: Implement executor phases one by one (P0 → P5)
- Phase 10: API completion, end-to-end tests
- Monitoring: Provided by Job system, no separate implementation
Phase 1: Types & Interfaces ✅
Goal: Define all types, enums, interfaces. No logic, no external deps.
Status: Complete - 88.4% test coverage, all tests passing
1.1 Enums (types/enums.go)
Phase- execution phases (inspiration, goals, tasks, run, delivery, learning)ClockMode- clock trigger modes (times, interval, daemon)TriggerType- trigger sources (clock, human, event)ExecStatus- execution status (pending, running, completed, failed, cancelled)RobotStatus- robot status (idle, working, paused, error, maintenance)InterventionAction- human actions (task.add, goal.adjust, etc.)Priority- priority levels (high, normal, low)DeliveryType- delivery types (email, file, webhook, notify)DedupResult- dedup results (skip, merge, proceed)EventSource- event sources (webhook, database)LearningType- learning types (execution, feedback, insight)TaskSource- task sources (auto, human, event)ExecutorType- executor types (assistant, mcp, process)TaskStatus- task status (pending, running, completed, failed, skipped, cancelled)InsertPosition- insert positions (first, last, next, at)
1.2 Context (types/context.go)
Contextstruct - robot execution contextNewContext()- constructorUserID(),TeamID()- helper methods
1.3 Config Types (types/config.go)
Config- main config structTriggers,TriggerSwitch- trigger enable/disableClock- clock config with validationIdentity- role, duties, rulesQuota- concurrency limits with defaultsKB,DB- knowledge base and database configLearn- learning configResources,MCPConfig- available agents and toolsDelivery- output delivery configEvent- event trigger config
1.4 Core Types (types/robot.go)
Robotstruct - runtime robot representationRobotmethods -CanRun(),RunningCount(),AddExecution(),RemoveExecution(),GetExecution(),GetExecutions()Executionstruct - single execution instanceTriggerInput- stored trigger inputCurrentState- current executing stateGoals- P1 output (markdown)Task- planned task (structured)TaskResult- task execution resultDeliveryResult- delivery outputLearningEntry- knowledge to save
1.5 Clock Context (types/clock.go)
ClockContextstruct - time context for P0NewClockContext()- constructor
1.6 Inspiration (types/inspiration.go)
InspirationReportstruct - P0 output
1.7 Request/Response (types/request.go)
InterveneRequest- human intervention requestEventRequest- event trigger requestExecutionResult- trigger resultRobotState- robot status query result
1.8 Interfaces (types/interfaces.go)
ManagerinterfaceExecutorinterfacePoolinterfaceCacheinterfaceDedupinterfaceStoreinterface
1.9 Errors (types/errors.go)
- Config errors
- Runtime errors
- Phase errors
1.10 Tests
types/enums_test.go- enum validationtypes/config_test.go- config validationtypes/clock_test.go- clock context creationtypes/robot_test.go- robot methods
Phase 2: Skeleton Implementation ✅
Goal: Create all packages with empty/stub implementations. Code compiles.
Status: Complete - All packages compile successfully, no circular dependencies
2.1 Utils (utils/) ✅
utils/convert.go- JSON, map, struct conversions (implement)utils/time.go- time parsing, formatting, timezone (implement)utils/id.go- ID generation (nanoid) (implement)utils/validate.go- validation helpers (implement)- Test:
utils/utils_test.go
2.2 Package Skeletons ✅ (stubs only, implemented in Phase 3)
Create empty structs and stub methods that return nil/empty/success:
cache/cache.go- Cache struct, stub methodsdedup/dedup.go- Dedup struct, stub methodsstore/store.go- Store struct, stub methodspool/pool.go- Pool struct, stub methodsjob/job.go- job helper stubsplan/plan.go- Plan struct, stub methodstrigger/trigger.go- trigger dispatcher stubexecutor/executor.go- Executor struct, stubExecute()manager/manager.go- Manager struct, stub methods
2.3 API Skeletons ✅
api/api.go- Go API facade (all function signatures, return errors)api/process.go- Yao Process registration (all processes, return errors)api/jsapi.go- JSAPI registration (all methods, return errors)
2.4 Root ✅
robot.go- package entryInit()- placeholderShutdown()- placeholder
2.5 Compile Test ✅
- All packages compile without errors
- All imports resolve correctly
- No circular dependencies
Phase 3: Complete Scheduling System ✅
Goal: Implement complete scheduling system. Executor is stub (simulates success).
Status: Complete - All 7 sub-tasks done, 80+ integration tests passing
This phase delivers a fully working scheduling pipeline:
Trigger → Manager → Cache → Dedup → Pool → Worker → Executor(stub) → Job
✅ 3.1 Cache Implementation (COMPLETE)
cache/cache.go- Cache struct with thread-safe mapcache/load.go- load robots from__yao.memberwheremember_type='robot'andautonomous_mode=true- Implemented pagination (100 robots per page)
- Configurable model name via
SetMemberModel()
cache/refresh.go- refresh single robot, periodic full refresh (every hour)- Test: load/refresh with real DB
- Created comprehensive integration tests with real database
- Tests cover Load, LoadByID, Refresh, ListByTeam, GetByStatus
- All tests passing with proper cleanup
✅ 3.2 Pool Implementation (COMPLETE)
pool/pool.go- worker pool with configurable size (global limit)- Default config: 10 workers, 100 queue size
- Configurable via
pool.NewWithConfig()
pool/queue.go- priority queue (sorted by: robot priority, trigger type, wait time)- Two-level limit: global queue + per-robot queue
- Priority: Robot Priority × 1000 + Trigger Priority × 100
pool/worker.go- worker goroutines, dispatch to executor- Non-blocking quota check with re-enqueue
- Graceful shutdown support
- Test: submit jobs, verify execution order, verify concurrency limits
- 15 test cases covering all edge cases
- All tests passing
✅ 3.3 Manager Implementation (COMPLETE)
Note: Manager is the scheduling core, depends on completed Cache and Pool.
manager/manager.go- Manager structStart()- load cache, start pool, start ticker goroutineStop()- graceful shutdown (wait for running, drain queue)Tick()- main loop:- Get all cached robots
- For each robot with clock trigger enabled
- Check if should execute (times/interval/daemon modes)
- Submit to pool
TriggerManual()- manual trigger for testing/API- Clock modes: times, interval, daemon
- Day matching for times mode
- Timezone handling
- Skip paused/error/maintenance robots
- Test: manager start/stop, tick cycle, manual trigger, clock modes, goroutine leak
✅ 3.4 Trigger Implementation (COMPLETE)
trigger/trigger.go- validation and helper functionsValidateIntervention()- validate human intervention requestsValidateEvent()- validate event trigger requestsBuildEventInput()- build TriggerInput from event requestGetActionCategory()/GetActionDescription()- action helpers
trigger/clock.go- ClockMatcher for clock trigger matchingtimesmode: match specific times (09:00, 14:00)intervalmode: run every X duration (30m, 1h)daemonmode: restart immediately after completion- Timezone handling
- Day-of-week filtering
trigger/control.go- ExecutionController for pause/resume/stop- Track/Untrack executions
- Pause/Resume execution
- Stop execution (cancel context)
- WaitIfPaused() for executor integration
manager/manager.go- integrated trigger handlingIntervene()- human intervention handlerHandleEvent()- event trigger handlerPauseExecution()/ResumeExecution()/StopExecution()ListExecutions()/ListExecutionsByMember()
- Tests:
trigger/trigger_test.go,trigger/clock_test.go,trigger/control_test.go- Validation tests for intervention and event requests
- Clock matching tests for all modes
- ExecutionController lifecycle tests
- Manager integration tests for Intervene/HandleEvent
✅ 3.5 Job Integration (COMPLETE)
job/job.go- create jobjob_id:robot_exec_{execID}category_name:Autonomous Robot/自主机器人(localized)- Metadata: member_id, team_id, trigger_type, exec_id, display_name
Optionsstruct for extensibility (Priority, MaxRetryCount, DefaultTimeout, Metadata)Create(),Get(),Update(),Complete(),Fail(),Cancel()- Status mapping: ExecPending→queued, ExecRunning→running, etc.
- Localization support (en-US, zh-CN)
job/execution.go- execution lifecycleCreateOptionsstruct for extensibilityCreateExecution()- create both robot Execution and job.ExecutionUpdatePhase()- update phase with progress tracking (10%→25%→40%→60%→80%→95%)UpdateStatus()- update execution statusCompleteExecution()/FailExecution()/CancelExecution()- TriggerType → TriggerCategory mapping (clock→scheduled, human→manual, event→event)
- Duration calculation on completion/failure/cancellation
job/log.go- write phase logsLog()- base log function with contextLogPhaseStart()/LogPhaseEnd()/LogPhaseError()LogError()/LogInfo()/LogDebug()/LogWarn()LogTaskStart()/LogTaskEnd()LogDelivery()/LogLearning()- Localization support for all log messages
- Test: job creation, execution tracking, log writing
job/job_test.go- 17 test casesjob/execution_test.go- 26 test casesjob/log_test.go- 24 test cases- All tests passing with real database
✅ 3.6 Executor Stub Enhancement (COMPLETE)
executor/executor.go- enhanced stub implementationExecute()- simulate full execution with Job integration- Create Execution record + Job (via job package)
- Update phase: P0 → P1 → P2 → P3 → P4 → P5
- Log phase transitions
- Return success with mock data
Configstruct withSkipJobIntegration,OnPhaseStart,OnPhaseEndNewWithDelay(),NewWithCallback()for testing- Quota check with
robot.TryAcquireSlot() - Clock trigger: P0→P5, Human/Event trigger: P1→P5
- Phase-specific files (modular design for Phase 4+ replacement):
executor/inspiration.go-RunInspiration()P0 mockexecutor/goals.go-RunGoals()P1 mockexecutor/tasks.go-RunTasks()P2 mockexecutor/run.go-RunExecution()P3 mockexecutor/delivery.go-RunDelivery()P4 mockexecutor/learning.go-RunLearning()P5 mock
simulateStreamDelay()- 50ms hardcoded delay per phase- Test: smoke tests for basic flow verification
executor/executor_test.go- 6 test cases- Clock/Human/Event triggers, nil robot, simulated failure, counters
3.7 Integration Test (End-to-End Scheduling) ✅
- Create test robot in
__yao.memberwith clock config - Start manager
- Wait for clock trigger
- Verify:
- Robot loaded to cache
- Clock trigger matched
- Job submitted to pool
- Worker picked up job
- Executor stub called
- Job execution recorded
- Logs written
- Test human intervention trigger
- Test event trigger
- Test concurrent executions (multiple robots)
- Test quota enforcement (per-robot limit)
- Test pause/resume/stop
Test Files Created:
manager/integration_test.go- Core scheduling flow (Cache→Pool→Executor)manager/integration_clock_test.go- Clock trigger modes (times/interval/daemon)manager/integration_human_test.go- Human intervention trigger testsmanager/integration_event_test.go- Event trigger testsmanager/integration_concurrent_test.go- Concurrent execution & quota testsmanager/integration_control_test.go- Pause/Resume/Stop tests
Test Coverage:
- 27 top-level test functions
- 80+ sub-tests covering all verification points
- 3x run stability verified
Phase 4: Agent Call Infrastructure ✅
Goal: Implement unified Agent/Assistant calling mechanism. This is the foundation for all phase implementations (P0-P5).
Architecture Note:
- Prompt construction is handled by Assistant layer (
prompts.ymlin each assistant) - Executor only prepares input data (ClockContext, InspirationReport, etc.) and calls Assistant
- Assistant framework handles prompt rendering, LLM API calls, streaming
Implemented:
- A unified way to call assistants with streaming support
- Input data formatting for each phase
- Response parsing (markdown and structured data via
gou/text) - Multi-turn conversation support
4.1 Agent Caller Implementation ✅
executor/agent.go-AgentCallerstruct withSkipOutput,SkipHistory,SkipSearch,ChatIDexecutor/agent.go-Call(ctx, assistantID, messages)- basic call with full responseexecutor/agent.go-CallWithMessages(ctx, assistantID, userContent)- convenience methodexecutor/agent.go-CallWithSystemAndUser(ctx, assistantID, systemContent, userContent)executor/agent.go- handle assistant not found errorexecutor/agent.go- handle LLM API errors gracefullyexecutor/agent.go-CallResult.GetJSON()/GetJSONArray()- parse JSON response usinggou/textexecutor/agent.go-Conversationstruct for multi-turn dialoguesexecutor/agent.go-Conversation.Turn(),RunUntil(),Reset(),WithSystemPrompt()executor/agent.go- Useagentcontext.Noop()logger to suppress debug output
4.2 Input Formatters ✅
executor/input.go-FormatClockContext(clockCtx, robot)- format clock context as message contentexecutor/input.go-FormatInspirationReport(report)- format P0 output for P1 inputexecutor/input.go-FormatTriggerInput(input)- format Human/Event trigger for P1 inputexecutor/input.go-FormatGoals(goals, robot)- format P1 output for P2 inputexecutor/input.go-FormatTasks(tasks)- format P2 output for P3 inputexecutor/input.go-FormatTaskResults(results)- format P3 output for P4/P5 inputexecutor/input.go-FormatExecutionSummary(exec)- format full execution for P5 inputexecutor/input.go-BuildMessages(),BuildMessagesWithSystem()- helper methods
4.3 Test Assistants ✅
yao-dev-app/assistants/tests/robot-single/- Single-turn test assistantyao-dev-app/assistants/tests/robot-conversation/- Multi-turn conversation test assistant
4.4 Tests ✅
executor/agent_test.go- 22 test cases for AgentCaller and Conversationexecutor/input_test.go- 20 test cases for InputFormatter- Verify: assistant can be called and returns response
- Verify: multi-turn conversation maintains state
- Verify: input data is well-formatted for assistant prompts
- Verify: JSON/YAML extraction from LLM output works correctly
Phase 5: Test Scenario & Assistants Setup
Goal: Create a realistic test scenario with all required assistants.
Test Scenario: Sales Analyst Robot
A Sales Analyst robot that:
- Wakes up at 09:00 on weekdays
- Checks sales data and market news
- Generates daily goals based on findings
- Creates 2-3 actionable tasks
- (Future: executes tasks, delivers report, learns)
Example flow:
Clock: Monday 09:00
↓
P0 Inspiration:
- Clock: Monday morning, start of week
- Data: 15 new orders (+20% vs last week)
- News: Competitor launched new product
↓
P1 Goals:
1. [High] Analyze weekend sales spike
2. [Normal] Review competitor product launch
3. [Low] Update weekly forecast
↓
P2 Tasks:
Task 1: Query sales DB for weekend orders
Task 2: Search web for competitor news
Task 3: Generate forecast update
5.1 Test Assistant Directory Structure
Create yao-dev-app/assistants/robot/ directory:
assistants/robot/
├── inspiration/ # P0: Inspiration Agent
│ ├── package.yao # Assistant config
│ └── prompts.yml # System prompt & templates
├── goals/ # P1: Goal Generation Agent
│ ├── package.yao
│ └── prompts.yml
├── tasks/ # P2: Task Planning Agent
│ ├── package.yao
│ └── prompts.yml
├── validation/ # P3: Validation Agent (future)
│ ├── package.yao
│ └── prompts.yml
├── delivery/ # P4: Delivery Agent (future)
│ ├── package.yao
│ └── prompts.yml
└── learning/ # P5: Learning Agent (future)
├── package.yao
└── prompts.yml
5.2 Inspiration Assistant (P0)
robot/inspiration/package.yao- config with model, temperaturerobot/inspiration/prompts.yml- system prompt for P0:- Input: Clock context, robot identity, data sources
- Output: Markdown report with Summary, Highlights, Opportunities, Risks
5.3 Goals Assistant (P1)
robot/goals/package.yao- configrobot/goals/prompts.yml- system prompt for P1:- Input: Inspiration report, robot duties
- Output: Prioritized goals in markdown format
5.4 Tasks Assistant (P2)
robot/tasks/package.yao- configrobot/tasks/prompts.yml- system prompt for P2:- Input: Goals, available tools/agents
- Output: Structured task list (JSON)
Phase 6: P0 Inspiration Implementation
Goal: Implement P0 (Inspiration Agent). Clock trigger → P0 → stub P1-P5.
Depends on: Phase 4 (Agent Call Infrastructure), Phase 5 (Assistants Setup)
6.1 P0 Implementation
executor/inspiration.go-RunInspiration(ctx, exec, data)- real implementationexecutor/inspiration.go- build prompt usingPromptBuilderexecutor/inspiration.go- call Inspiration Agent usingAgentCallerexecutor/inspiration.go- parse response toInspirationReportexecutor/inspiration.go- handle streaming responseexecutor/inspiration.go- log phase progress to Job system
6.2 Tests
executor/inspiration_test.go- P0 with real LLM call- Test: clock context correctly formatted in prompt
- Test: robot identity included in system prompt
- Test: markdown report generated with expected sections
- Test: handles LLM errors gracefully
Phase 7: P1 Goals Implementation
Goal: Implement P1 (Goal Generation Agent). P0 → P1 → stub P2-P5.
Depends on: Phase 6 (P0 Inspiration)
7.1 P1 Implementation
executor/goals.go-RunGoals(ctx, exec, data)- real implementationexecutor/goals.go- build prompt with inspiration reportexecutor/goals.go- call Goals Agentexecutor/goals.go- parse response toGoalsstructexecutor/goals.go- handle Human/Event trigger (skip P0, use input directly)
7.2 Tests
executor/goals_test.go- P1 with real LLM call- Test: inspiration report in prompt (Clock trigger)
- Test: user input in prompt (Human trigger)
- Test: goals markdown generated with priorities
- Test: goals are actionable and measurable
Phase 8: P2 Tasks Implementation
Goal: Implement P2 (Task Planning Agent). P1 → P2 → stub P3-P5.
Depends on: Phase 7 (P1 Goals)
8.1 P2 Implementation
executor/tasks.go-RunTasks(ctx, exec, data)- real implementationexecutor/tasks.go- build prompt with goalsexecutor/tasks.go- include available tools/agents in promptexecutor/tasks.go- call Tasks Agentexecutor/tasks.go- parse response to[]Task(structured JSON)executor/tasks.go- validate task structure
8.2 Tests
executor/tasks_test.go- P2 with real LLM call- Test: goals included in prompt
- Test: available tools listed in prompt
- Test: structured tasks generated (2-3 tasks per goal)
- Test: each task has valid executor type and ID
Phase 9: P3 Run Implementation
Goal: Implement P3 (Task Execution). P2 → P3 → stub P4-P5.
Depends on: Phase 8 (P2 Tasks)
9.1 Implementation
executor/run.go-RunExecution(ctx, exec, data)- real implementationexecutor/run.go- iterate tasks in orderexecutor/run.go- dispatch to correct executor (assistant/mcp/process)executor/run.go- collect results with timingexecutor/run.go- handle task failures gracefullyexecutor/run.go- support pause/resume during execution
9.2 Validation Agent Setup
robot/validation/package.yao- Validation Agent configrobot/validation/prompts.yml- validation prompts
9.3 Tests
executor/run_test.go- P3 with real agent calls- Test: tasks executed in order
- Test: results collected with correct structure
- Test: task failure doesn't stop entire execution
- Test: pause/resume works during task execution
Phase 10: P4 Delivery Implementation
Goal: Implement P4 (Delivery). P3 → P4 → stub P5.
Depends on: Phase 9 (P3 Run)
10.1 Delivery Agent Setup
robot/delivery/package.yao- Delivery Agent configrobot/delivery/prompts.yml- delivery prompts
10.2 Implementation
executor/delivery.go-RunDelivery(ctx, exec, data)- real implementationexecutor/delivery.go- build delivery content from resultsexecutor/delivery.go- support email deliveryexecutor/delivery.go- support file deliveryexecutor/delivery.go- support webhook deliveryexecutor/delivery.go- support notify delivery
10.3 Tests
executor/delivery_test.go- P4 delivery- Test: delivery content generated correctly
- Test: email delivery (mock or real)
- Test: file delivery to configured path
Phase 11: P5 Learning Implementation
Goal: Implement P5 (Learning). Full execution flow complete.
Depends on: Phase 10 (P4 Delivery)
11.1 Learning Agent Setup
robot/learning/package.yao- Learning Agent configrobot/learning/prompts.yml- learning prompts
11.2 Store Implementation
store/store.go- Store interface and structstore/kb.go- KB operations (create, save, search)store/learning.go- save learning entries to private KB
11.3 Implementation
executor/learning.go-RunLearning(ctx, exec, data)- real implementationexecutor/learning.go- extract learnings from executionexecutor/learning.go- call Learning Agentexecutor/learning.go- save to private KB
11.4 Tests
executor/learning_test.go- P5 learning- Test: learnings extracted from execution
- Test: learnings saved to KB
- Test: KB can be queried for past learnings
Phase 12: API & Integration
Goal: Complete API implementation, end-to-end tests.
12.1 API Implementation
api/api.go- implement all Go API functionsapi/process.go- implement all Process handlersapi/jsapi.go- implement JSAPI
12.2 End-to-End Tests
- Full clock trigger flow (P0 → P5)
- Human intervention flow (P1 → P5)
- Event trigger flow (P1 → P5)
- Concurrent execution test
- Pause/Resume/Stop test
12.3 Integration with OpenAPI
- HTTP endpoints for human intervention
- Webhook endpoints for events
Phase 13: Advanced Features
Goal: Implement dedup, semantic dedup, plan queue.
13.1 Fast Dedup (Time-Window)
Note: Manager has
// TODO: dedup checkcomment placeholder. Integrate after implementation.
dedup/dedup.go- Dedup structdedup/fast.go- fast in-memory time-window dedup- Key:
memberID:triggerType:window - Check before submit
- Mark after submit
- Key:
- Integrate into Manager.Tick()
- Test: dedup check/mark, window expiry
13.2 Semantic Dedup
dedup/semantic.go- call Dedup Agent for goal/task level dedup- Dedup Agent setup (
assistants/robot/dedup/) - Test: semantic dedup with real LLM
13.3 Plan Queue
plan/plan.go- plan queue implementation- Store planned tasks/goals
- Execute at next cycle or specified time
plan/schedule.go- schedule for later- Test: plan queue operations
Note: Monitoring is provided by Job system (Activity Monitor UI). No separate implementation needed.
Test Assistants Structure
yao-dev-app/assistants/robot/
├── inspiration/ # P0: Inspiration Agent
│ ├── package.yao
│ └── prompts.yml
├── goals/ # P1: Goal Generation Agent
│ ├── package.yao
│ └── prompts.yml
├── tasks/ # P2: Task Planning Agent
│ ├── package.yao
│ └── prompts.yml
├── validation/ # P3: Validation Agent
│ ├── package.yao
│ └── prompts.yml
├── delivery/ # P4: Delivery Agent
│ ├── package.yao
│ └── prompts.yml
├── learning/ # P5: Learning Agent
│ ├── package.yao
│ └── prompts.yml
└── dedup/ # Deduplication Agent
├── package.yao
└── prompts.yml
Notes
Test Environment Setup
- Environment Variables: Run
source yao/env.local.shbefore tests - Test Preparation: Use
testutils.Prepare(t)to load config, KB, and agents
package robot_test
import (
"testing"
"github.com/yaoapp/yao/agent/testutils"
)
func TestExample(t *testing.T) {
// Load environment config (from YAO_TEST_APPLICATION)
// This loads: config, connectors, KB, agents, models, etc.
testutils.Prepare(t)
defer testutils.Clean(t)
// Your test code here
}
Test Conventions
- Black-box Tests: All tests in
*_testpackage (external package) - Real LLM Calls: Use
gpt-4oordeepseekconnectors for agent tests - Incremental: Each phase builds on previous, all tests must pass before next phase
- No Skip: Do NOT use
t.Skip()except fortesting.Short()(CI mode) - Must Assert: Every test MUST have result validation assertions
func TestWithLLM(t *testing.T) {
// Only allowed Skip: testing.Short() for CI
if testing.Short() {
t.Skip("Skipping integration test")
}
testutils.Prepare(t)
defer testutils.Clean(t)
// Your test code...
result, err := SomeFunction()
// MUST have assertions - no empty tests!
assert.NoError(t, err)
assert.NotNil(t, result)
assert.Equal(t, expected, result.Field)
}
Test Rules
| Rule | Description |
|---|---|
| No arbitrary Skip | Only testing.Short() skip allowed |
| Must assert | Every test must validate results |
| No empty tests | Tests without assertions will fail review |
| Real calls | LLM tests use real API calls, not mocks |
Key Environment Variables
| Variable | Description |
|---|---|
YAO_TEST_APPLICATION |
Test app path (yao-dev-app) |
OPENAI_TEST_KEY |
OpenAI API key |
DEEPSEEK_API_KEY |
DeepSeek API key |
YAO_DB_DRIVER |
Database driver (mysql/sqlite3) |
YAO_DB_PRIMARY |
Database connection string |
Progress Tracking
| Phase | Status | Description |
|---|---|---|
| 1. Types & Interfaces | ✅ | All types, enums, interfaces |
| 2. Skeleton | ✅ | Empty stubs, code compiles |
| 3. Scheduling System | 🟡 | Cache + Pool + Trigger + Job + Executor stub ✅, Integration test 🟡 |
| 4. P0 Inspiration | ⬜ | Inspiration Agent integration |
| 5. P1 Goals | ⬜ | Goal Generation Agent integration |
| 6. P2 Tasks | ⬜ | Task Planning Agent integration |
| 7. P3 Run | ⬜ | Task execution (assistant/mcp/process) |
| 8. P4 Delivery | ⬜ | Output delivery (email/file/webhook/notify) |
| 9. P5 Learning | ⬜ | Learning Agent + KB save |
| 10. API & Integration | ⬜ | Complete API, end-to-end tests |
| 11. Advanced | ⬜ | Semantic dedup, plan queue |
Legend: ⬜ Not started | 🟡 In progress | ✅ Complete
Quick Commands
# Setup environment
source yao/env.local.sh
# Run all robot tests
go test -v ./agent/robot/...
# Run specific phase tests
go test -v ./agent/robot/types/...
go test -v ./agent/robot/cache/...
go test -v ./agent/robot/pool/...
go test -v ./agent/robot/executor/...
# Run with coverage
go test -cover ./agent/robot/...