claude-flow-novice 2.5.2 → 2.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude/adaptive-context/cfn-v3-reflection.json +21 -0
- package/.claude/agents/AGENT_LIFECYCLE.md +495 -0
- package/.claude/agents/CLAUDE.md +1002 -1233
- package/.claude/agents/accessibility-advocate.md +457 -0
- package/.claude/agents/agent-principles/README.md +226 -226
- package/.claude/agents/agent-principles/agent-type-guidelines.md +10 -0
- package/.claude/agents/agent-principles/format-selection.md +10 -0
- package/.claude/agents/agent-principles/phase4-template-optimization.md +502 -494
- package/.claude/agents/agent-principles/prompt-engineering.md +8 -0
- package/.claude/agents/agent-principles/quality-metrics.md +8 -0
- package/.claude/agents/analysis/code-analyzer.md +7 -17
- package/.claude/agents/analysis/code-review/analyze-code-quality.md +2 -104
- package/.claude/agents/analysis/perf-analyzer.md +2 -196
- package/.claude/agents/context/context-curator.md +78 -84
- package/.claude/agents/context/context-reflector.md +27 -81
- package/.claude/agents/coordinators/README.md +42 -0
- package/.claude/agents/coordinators/cfn-v3-coordinator.md +440 -0
- package/.claude/agents/{product-owner-team → coordinators}/cto-agent.md +154 -187
- package/.claude/agents/coordinators/multi-sprint-coordinator.md +50 -0
- package/.claude/agents/{product-owner-team → coordinators}/product-owner-agent.md +6 -39
- package/.claude/agents/{cfn-loop → coordinators}/product-owner.md +72 -17
- package/.claude/agents/core-agents/reviewer.md +114 -135
- package/.claude/agents/custom/agent-builder.md +637 -0
- package/.claude/agents/developers/README.md +69 -0
- package/.claude/agents/developers/backend-dev.md +77 -0
- package/.claude/agents/{core-agents → developers}/coder.md +131 -26
- package/.claude/agents/developers/react-frontend-engineer.md +121 -0
- package/.claude/agents/{frontend → developers}/state-architect.md +1 -0
- package/.claude/agents/{frontend → developers}/ui-designer.md +1 -0
- package/.claude/agents/development/backend/dev-backend-api.md +0 -29
- package/.claude/agents/development/npm-package-specialist.md +355 -347
- package/.claude/agents/documentation/api-docs/docs-api-openapi.md +8 -0
- package/.claude/agents/documentation/api-docs.md +8 -0
- package/.claude/agents/github/github-commit-agent.md +125 -117
- package/.claude/agents/goal/goal-planner.md +8 -0
- package/.claude/agents/infrastructure/README.md +100 -0
- package/.claude/agents/{specialized → infrastructure}/devops-engineer.md +131 -150
- package/.claude/agents/planners/README.md +94 -0
- package/.claude/agents/{core-agents → planners}/analyst.md +1 -22
- package/.claude/agents/{planning-team → planners}/api-designer-persona.md +8 -0
- package/.claude/agents/{core-agents → planners}/architect.md +7 -20
- package/.claude/agents/{core-agents → planners}/planner.md +0 -21
- package/.claude/agents/{planning-team → planners}/security-architect-persona.md +8 -28
- package/.claude/agents/{planning-team → planners}/system-architect-persona.md +6 -38
- package/.claude/agents/{architecture → planners}/system-architect.md +12 -17
- package/.claude/agents/product-owner-team/accessibility-advocate-persona.md +132 -161
- package/.claude/agents/product-owner-team/power-user-persona.md +149 -182
- package/.claude/agents/retrospective-analyst.md +84 -0
- package/.claude/agents/reviewers/README.md +58 -0
- package/.claude/agents/{analysis → reviewers}/code-quality-validator.md +8 -17
- package/.claude/agents/reviewers/reviewer.md +181 -0
- package/.claude/agents/sparc/architecture.md +6 -25
- package/.claude/agents/sparc/pseudocode.md +6 -0
- package/.claude/agents/sparc/refinement.md +6 -0
- package/.claude/agents/sparc/specification.md +1 -0
- package/.claude/agents/specialists/README.md +60 -0
- package/.claude/agents/{core-agents → specialists}/base-template-generator.md +8 -21
- package/.claude/agents/{specialized → specialists}/cli-agent-optimizer.md +1 -1
- package/.claude/agents/{specialized → specialists}/code-booster.md +1 -0
- package/.claude/agents/{consensus → specialists}/consensus-builder.md +1 -17
- package/.claude/agents/{specialized/mobile → specialists}/mobile-dev.md +0 -20
- package/.claude/agents/{core-agents → specialists}/performance-benchmarker.md +134 -148
- package/.claude/agents/{specialized → specialists}/rust-developer.md +1 -20
- package/.claude/agents/{specialized → specialists}/rust-enterprise-developer.md +1 -20
- package/.claude/agents/{specialized → specialists}/rust-mvp-developer.md +1 -20
- package/.claude/agents/{core-agents → specialists}/security-manager.md +68 -88
- package/.claude/agents/{security → specialists}/security-specialist-existing.md +6 -57
- package/.claude/agents/{security → specialists}/security-specialist.md +6 -30
- package/.claude/agents/{specialized/mobile → specialists}/spec-mobile-react-native.md +2 -21
- package/.claude/agents/testers/README.md +94 -0
- package/.claude/agents/{testing → testers}/e2e/playwright-agent.md +1 -20
- package/.claude/agents/{testing → testers}/interaction-tester.md +1 -20
- package/.claude/agents/{testing → testers}/playwright-tester.md +1 -1
- package/.claude/agents/testers/tester.md +139 -0
- package/.claude/agents/testers/unit/tdd-london-swarm.md +49 -0
- package/.claude/agents/testers/validation/production-validator.md +33 -0
- package/.claude/agents-ignore/cfn-loop-coordinator.md +157 -0
- package/.claude/agents-ignore/cfn-loop-coordinator.md.backup +156 -0
- package/.claude/agents-ignore/coordinator.md.backup +182 -0
- package/.claude/agents-ignore/cost-savings-cfn-loop-coordinator.md +760 -0
- package/.claude/agents-ignore/cost-savings-coordinator.md +173 -0
- package/.claude/artifacts/ace-reflections/REFLECT-001-summary.json +39 -0
- package/.claude/artifacts/ace-reflections/sprint-7_$(date -u +/"%Y%m%d_%H%M%S/").json" +47 -0
- package/.claude/artifacts/reflection-merge-logs/cli-agent-spawning-v2.5.2-merge-report.md +61 -0
- package/.claude/commands/CFN_COORDINATOR_PARAMETERS.md +10 -10
- package/.claude/commands/cfn-loop-epic.md +43 -19
- package/.claude/commands/cfn-loop-single.md +3 -3
- package/.claude/commands/cfn-loop-sprints.md +1 -1
- package/.claude/commands/cfn-loop.md +45 -32
- package/.claude/commands/cfn-mode.md +20 -0
- package/.claude/commands/custom-routing-activate.md +37 -123
- package/.claude/commands/custom-routing-deactivate.md +27 -124
- package/.claude/commands/switch-api.md +41 -16
- package/.claude/commands/write-plan.md +104 -0
- package/.claude/data/cfn-loop.db +0 -0
- package/.claude/data/cfn_loop_logs.db +0 -0
- package/.claude/hooks/BACKUP_USAGE.md +243 -0
- package/.claude/hooks/post-edit-cfn-retrospective.sh +79 -0
- package/.claude/hooks/post-edit.sh +21 -0
- package/.claude/hooks/pre-edit-backup.sh +71 -0
- package/.claude/hooks/restore-from-backup.sh +37 -0
- package/.claude/prompts/cfn-loop-context.md +115 -0
- package/.claude/prompts/loop-specific/loop2.md +50 -0
- package/.claude/prompts/loop-specific/loop3.md +43 -0
- package/.claude/prompts/loop-specific/loop4.md +54 -0
- package/.claude/root-claude-distribute/CLAUDE.md +76 -2
- package/.claude/skills/ace-system/sprint-7-lessons.json +46 -0
- package/.claude/skills/ace-system/store-reflection.sh +33 -136
- package/.claude/skills/agent-discovery/SKILL.md +40 -0
- package/.claude/skills/agent-discovery/agents-registry-clean.json +0 -0
- package/.claude/skills/agent-discovery/agents-registry-fixed.json +19 -0
- package/.claude/skills/agent-discovery/agents-registry.json +718 -0
- package/.claude/skills/agent-discovery/discover-agents.py +175 -0
- package/.claude/skills/agent-discovery/discover-agents.sh +87 -0
- package/.claude/skills/agent-discovery/invoke-registry.sh +11 -0
- package/.claude/skills/agent-discovery/temp_script.py +0 -0
- package/.claude/skills/agent-execution/execute-agent.sh +126 -0
- package/.claude/skills/agent-output-processing/SKILL.md +359 -0
- package/.claude/skills/agent-selector/SKILL.md +90 -0
- package/.claude/skills/agent-selector/select-agents.sh +96 -0
- package/.claude/skills/agent-spawning/agent-selection-guide.md +1 -1
- package/.claude/skills/agent-swap/SKILL.md +36 -0
- package/.claude/skills/agent-swap/recommend-swap.sh +60 -0
- package/.claude/skills/api-validation/test-endpoints.sh +54 -0
- package/.claude/skills/automatic-memory-persistence/SKILL.md +73 -0
- package/.claude/skills/automatic-memory-persistence/persist-agent-output.sh +49 -0
- package/.claude/skills/automatic-memory-persistence/query-agent-history.sh +35 -0
- package/.claude/skills/automatic-memory-persistence/test-memory-persistence.sh +235 -0
- package/.claude/skills/cfn-loop-orchestration/README.md +41 -0
- package/.claude/skills/cfn-loop-orchestration/SKILL.md +299 -0
- package/.claude/skills/cfn-loop-orchestration/helpers/auto-tune-timeouts.sh +228 -0
- package/.claude/skills/cfn-loop-orchestration/helpers/consensus.sh +84 -0
- package/.claude/skills/cfn-loop-orchestration/helpers/deliverable-verifier.sh +71 -0
- package/.claude/skills/cfn-loop-orchestration/helpers/gate-check.sh +90 -0
- package/.claude/skills/cfn-loop-orchestration/helpers/iteration-manager.sh +87 -0
- package/.claude/skills/cfn-loop-orchestration/helpers/timeout-calculator.sh +51 -0
- package/.claude/skills/cfn-loop-orchestration/inject-loop-context.sh +41 -0
- package/.claude/skills/cfn-loop-orchestration/monitor-execution.sh +156 -0
- package/.claude/skills/cfn-loop-orchestration/orchestrate.sh +840 -0
- package/.claude/skills/cfn-loop-orchestration/security_utils.sh +99 -0
- package/.claude/skills/cfn-loop-orchestration/test-cfn-orchestration.sh +281 -0
- package/.claude/skills/cfn-loop-orchestration/test-edge-cases.sh +188 -0
- package/.claude/skills/cfn-loop-validation/SKILL.md +307 -217
- package/.claude/skills/complexity-estimator/SKILL.md +96 -0
- package/.claude/skills/complexity-estimator/estimate-complexity.sh +144 -0
- package/.claude/skills/context-pruner/SKILL.md +75 -0
- package/.claude/skills/context-pruner/prune-context.sh +73 -0
- package/.claude/skills/defense-in-depth/SKILL.md +133 -0
- package/.claude/skills/dependency-extractor/SKILL.md +35 -0
- package/.claude/skills/dependency-extractor/extract-dependencies.sh +66 -0
- package/.claude/skills/epic-decomposer/SKILL.md +44 -0
- package/.claude/skills/epic-decomposer/decompose-epic.sh +104 -0
- package/.claude/skills/improvement-recommender/SKILL.md +33 -0
- package/.claude/skills/improvement-recommender/recommend-improvements.sh +92 -0
- package/.claude/skills/intervention-detector/SKILL.md +39 -0
- package/.claude/skills/intervention-detector/detect-intervention.sh +111 -0
- package/.claude/skills/intervention-orchestrator/SKILL.md +43 -0
- package/.claude/skills/intervention-orchestrator/execute-intervention.sh +59 -0
- package/.claude/skills/loop2-output-processing/SKILL.md +163 -0
- package/.claude/skills/loop2-output-processing/execute-and-extract.sh +77 -0
- package/.claude/skills/loop2-output-processing/execute-and-extract.sh.backup +36 -0
- package/.claude/skills/loop2-output-processing/parse-feedback.sh +147 -0
- package/.claude/skills/loop2-output-processing/process-validator-output.sh +275 -0
- package/.claude/skills/loop2-output-processing/test-bug27-fix.sh +200 -0
- package/.claude/skills/loop2-output-processing/test-loop2-processing.sh +113 -0
- package/.claude/skills/loop3-output-processing/AGENT_COMPLETION_PROTOCOL.md +206 -0
- package/.claude/skills/loop3-output-processing/SKILL.md +421 -0
- package/.claude/skills/loop3-output-processing/calculate-confidence.sh +28 -0
- package/.claude/skills/loop3-output-processing/execute-and-extract.sh +85 -0
- package/.claude/skills/loop3-output-processing/parse-confidence.sh +31 -0
- package/.claude/skills/loop3-output-processing/test-agent-timeout.sh +327 -0
- package/.claude/skills/loop3-output-processing/test-loop3-processing.sh +155 -0
- package/.claude/skills/loop3-output-processing/verify-deliverables.sh +42 -0
- package/.claude/skills/pattern-extraction/SKILL.md +30 -0
- package/.claude/skills/pattern-extraction/extract-patterns.sh +80 -0
- package/.claude/skills/playbook/SKILL.md +113 -0
- package/.claude/skills/playbook/init-playbook.sh +54 -0
- package/.claude/skills/playbook/playbook.db +0 -0
- package/.claude/skills/playbook/query-playbook.sh +79 -0
- package/.claude/skills/playbook/update-playbook.sh +69 -0
- package/.claude/skills/playbook-auto-update/SKILL.md +29 -0
- package/.claude/skills/playbook-auto-update/auto-update-playbook.sh +86 -0
- package/.claude/skills/product-owner-decision/SKILL.md +332 -0
- package/.claude/skills/product-owner-decision/execute-decision.sh +176 -0
- package/.claude/skills/product-owner-decision/parse-decision.sh +66 -0
- package/.claude/skills/product-owner-decision/validate-deliverables.sh +82 -0
- package/.claude/skills/redis-coordination/AGENT_LOGGING.md +280 -0
- package/.claude/skills/redis-coordination/LOGGING.md +260 -0
- package/.claude/skills/redis-coordination/README.md +30 -29
- package/.claude/skills/redis-coordination/SKILL.md +685 -83
- package/.claude/skills/redis-coordination/agent-log.sh +124 -0
- package/.claude/skills/redis-coordination/analyze-task-complexity.sh +277 -0
- package/.claude/skills/redis-coordination/cfn-loop-exec.sh +468 -0
- package/.claude/skills/redis-coordination/collect-confidence-scores.sh +179 -0
- package/.claude/skills/redis-coordination/collect-results.sh +75 -0
- package/.claude/skills/redis-coordination/data/cfn-loop.db +0 -0
- package/.claude/skills/redis-coordination/demos/test-iteration-feedback.sh +320 -0
- package/.claude/skills/redis-coordination/{test-orchestrator.sh → demos/test-orchestrator.sh} +25 -0
- package/.claude/skills/redis-coordination/execute-product-owner-decision.sh +258 -0
- package/.claude/skills/redis-coordination/get-agent-timeout.sh +176 -176
- package/.claude/skills/redis-coordination/init-swarm.sh +6 -1
- package/.claude/skills/redis-coordination/invoke-waiting-mode.sh +106 -183
- package/.claude/skills/redis-coordination/invoke-waiting-mode.sh.backup-p7 +423 -0
- package/.claude/skills/redis-coordination/log-event.sh +109 -0
- package/.claude/skills/redis-coordination/monitor-cfn-violations.sh +391 -0
- package/.claude/skills/redis-coordination/orchestrate-cfn-loop-v3.sh +141 -0
- package/.claude/skills/redis-coordination/orchestrate-cfn-loop.sh +31 -933
- package/.claude/skills/redis-coordination/orchestrate-cfn-loop.sh.backup +38 -0
- package/.claude/skills/redis-coordination/orchestrate-cfn-loop.sh.backup-1761167675 +1672 -0
- package/.claude/skills/redis-coordination/orchestrate-cfn-loop.sh.backup-p5 +1604 -0
- package/.claude/skills/redis-coordination/orchestrate-cfn-loop.sh.backup-phase1 +1550 -0
- package/.claude/skills/redis-coordination/orchestrate-cfn-loop.sh.backup-phase2 +1621 -0
- package/.claude/skills/redis-coordination/orchestrate-cfn-loop.sh.backup-phase3 +1621 -0
- package/.claude/skills/redis-coordination/orchestrate-cfn-loop.sh.bak +0 -0
- package/.claude/skills/redis-coordination/orchestrate-cfn-loop.sh.broken +1627 -0
- package/.claude/skills/redis-coordination/orchestrate-cfn-loop.sh.corrupted +80 -0
- package/.claude/skills/redis-coordination/orchestrate-cfn-loop.sh.deprecated +1864 -0
- package/.claude/skills/redis-coordination/query-logs.sh +103 -0
- package/.claude/skills/redis-coordination/retrieve-context.sh +58 -0
- package/.claude/skills/redis-coordination/select-specialist-agent.sh +371 -0
- package/.claude/skills/redis-coordination/semantic-match-tfidf.py +252 -0
- package/.claude/skills/redis-coordination/send-heartbeat.sh +164 -72
- package/.claude/skills/redis-coordination/signal.sh +38 -0
- package/.claude/skills/redis-coordination/store-context.sh +86 -0
- package/.claude/skills/redis-coordination/store-epic-context.sh +123 -0
- package/.claude/skills/redis-coordination/test-context-injection.sh +354 -0
- package/.claude/skills/redis-coordination/test-timeout-enforcement.sh +513 -0
- package/.claude/skills/redis-coordination/tests/convert-line-endings.sh +15 -0
- package/.claude/skills/redis-coordination/tests/dlq-functionality-test.sh +101 -101
- package/.claude/skills/redis-coordination/tests/edge-cases-test.sh +98 -98
- package/.claude/skills/redis-coordination/tests/integration-test.sh +169 -169
- package/.claude/skills/redis-coordination/tests/retry-mechanism-test.sh +81 -81
- package/.claude/skills/redis-coordination/tests/run-test-suite.sh +91 -91
- package/.claude/skills/redis-coordination/tests/run-tests.sh +4 -0
- package/.claude/skills/redis-coordination/tests/test-primitives.sh +166 -0
- package/.claude/skills/redis-coordination/tests/test-utils.sh +53 -121
- package/.claude/skills/redis-coordination/tests/test_coordination_primitives.sh.deprecated +20 -0
- package/.claude/skills/redis-coordination/tests/test_utils.sh +49 -0
- package/.claude/skills/redis-coordination/v2_modularization/core_orchestration.sh +76 -0
- package/.claude/skills/redis-coordination/validate-parameters.sh +492 -0
- package/.claude/skills/retrospective-report/SKILL.md +31 -0
- package/.claude/skills/retrospective-report/generate-report.sh +101 -0
- package/.claude/skills/run-all-skill-tests.sh +124 -0
- package/.claude/skills/scope-simplifier/SKILL.md +37 -0
- package/.claude/skills/scope-simplifier/simplify-scope.sh +68 -0
- package/.claude/skills/simplified-agent-lifecycle/COST_ANALYSIS.md +49 -0
- package/.claude/skills/simplified-agent-lifecycle/DESIGN.md +98 -0
- package/.claude/skills/simplified-agent-lifecycle/MIGRATION_PLAN.md +74 -0
- package/.claude/skills/skill-builder/SKILL.md +910 -0
- package/.claude/skills/specialist-injection/SKILL.md +41 -0
- package/.claude/skills/specialist-injection/recommend-specialist.sh +57 -0
- package/.claude/skills/sprint-execution/SKILL.md +27 -0
- package/.claude/skills/sprint-execution/execute-sprint-task.sh +59 -0
- package/.claude/skills/sprint-execution/execute-sprint.sh +65 -0
- package/.claude/skills/sprint-planner/SKILL.md +37 -0
- package/.claude/skills/sprint-planner/plan-sprint.sh +85 -0
- package/.claude/skills/standardized-error-handling/SKILL.md +56 -0
- package/.claude/skills/standardized-error-handling/capture-agent-error.sh +87 -0
- package/.claude/skills/standardized-error-handling/test-error-handling.sh +166 -0
- package/.claude/skills/task-classifier/SKILL.md +94 -0
- package/.claude/skills/task-classifier/classify-task.sh +115 -0
- package/.claude/skills/validation-templates/SKILL.md +47 -0
- package/.claude/skills/validation-templates/content.json +38 -0
- package/.claude/skills/validation-templates/data.json +38 -0
- package/.claude/skills/validation-templates/design.json +38 -0
- package/.claude/skills/validation-templates/infrastructure.json +38 -0
- package/.claude/skills/validation-templates/research.json +38 -0
- package/.claude/skills/validation-templates/software.json +38 -0
- package/.claude/skills/webapp-testing/README.md +142 -0
- package/.claude/skills/webapp-testing/SCREENSHOT_NAMING_CONVENTION.md +547 -0
- package/.claude/skills/webapp-testing/SKILL.md +877 -0
- package/.claude/skills/webapp-testing/capture-screenshot.sh +238 -0
- package/.claude/skills/webapp-testing/cfn-loop-integration.sh +265 -0
- package/.claude/skills/webapp-testing/compare-screenshots.sh +199 -0
- package/.claude/skills/webapp-testing/init-storage.sh +150 -0
- package/.claude/skills/webapp-testing/set-baseline.sh +196 -0
- package/.claude/skills/webapp-testing/test-webapp-testing.sh +233 -0
- package/.claude/spawn-pattern-examples.md +3 -3
- package/CLAUDE.md +364 -16
- package/README.md +598 -251
- package/dist/agents/agent-loader.js +146 -165
- package/dist/agents/agent-loader.js.map +1 -1
- package/dist/cli/agent-command.js +153 -0
- package/dist/cli/agent-command.js.map +1 -0
- package/dist/cli/agent-definition-parser.js +183 -0
- package/dist/cli/agent-definition-parser.js.map +1 -0
- package/dist/cli/agent-executor.js +310 -0
- package/dist/cli/agent-executor.js.map +1 -0
- package/dist/cli/agent-prompt-builder.js +268 -0
- package/dist/cli/agent-prompt-builder.js.map +1 -0
- package/dist/cli/agent-spawn.js +56 -2
- package/dist/cli/agent-spawn.js.map +1 -1
- package/dist/cli/anthropic-client.js +421 -0
- package/dist/cli/anthropic-client.js.map +1 -0
- package/dist/cli/cfn-context.js +150 -0
- package/dist/cli/cfn-context.js.map +1 -1
- package/dist/cli/cfn-fork.js +159 -0
- package/dist/cli/cfn-fork.js.map +1 -0
- package/dist/cli/cli-agent-context.js +358 -0
- package/dist/cli/cli-agent-context.js.map +1 -0
- package/dist/cli/config-manager.js +109 -91
- package/dist/cli/config-manager.js.map +1 -1
- package/dist/cli/conversation-fork.js +201 -0
- package/dist/cli/conversation-fork.js.map +1 -0
- package/dist/cli/index.js +119 -2
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/iteration-history.js +188 -0
- package/dist/cli/iteration-history.js.map +1 -0
- package/dist/cli/tool-definitions.js +263 -0
- package/dist/cli/tool-definitions.js.map +1 -0
- package/dist/cli/tool-executor.js +247 -0
- package/dist/cli/tool-executor.js.map +1 -0
- package/dist/hello.js +8 -0
- package/dist/hello.js.map +1 -0
- package/package.json +16 -6
- package/scripts/README.md +68 -0
- package/scripts/cfn-intervention-example.sh +21 -0
- package/scripts/migrate-test-infrastructure.sh +40 -0
- package/scripts/switch-api.sh +233 -0
- package/scripts/validate-test-migration.sh +49 -0
- package/scripts/verify-no-secrets.sh +55 -0
- package/.claude/agents/architecture/system-architect.md.backup +0 -603
- package/.claude/agents/code-booster.md +0 -131
- package/.claude/agents/consensus/performance-benchmarker.md +0 -101
- package/.claude/agents/consensus/security-manager.md +0 -107
- package/.claude/agents/context-curator.md +0 -167
- package/.claude/agents/context-reflector.md +0 -65
- package/.claude/agents/core-agents/cfn-loop-coordinator.md +0 -134
- package/.claude/agents/core-agents/code-quality-validator.md +0 -149
- package/.claude/agents/core-agents/context-curator.md +0 -452
- package/.claude/agents/core-agents/context-reflector.md +0 -273
- package/.claude/agents/core-agents/cost-savings-cfn-loop-coordinator.md +0 -190
- package/.claude/agents/core-agents/tester.md +0 -170
- package/.claude/agents/development/backend-dev.md +0 -165
- package/.claude/agents/devops/devops-engineer.md +0 -148
- package/.claude/agents/frontend/interaction-tester.md +0 -139
- package/.claude/agents/frontend/react-frontend-engineer.md +0 -9
- package/.claude/agents/personas/accessibility-advocate-persona.md +0 -107
- package/.claude/agents/testing/production-validator.md +0 -179
- package/.claude/agents/testing/tdd-london-swarm.md +0 -209
- package/.claude/agents/testing/unit/tdd-london-swarm.md +0 -43
- package/.claude/agents/testing/validation/production-validator.md +0 -43
- package/dist/coordination/fleet-manager.test.js +0 -141
- package/dist/coordination/fleet-manager.test.js.map +0 -1
- package/dist/middleware/transparency-middleware.test.js +0 -184
- package/dist/middleware/transparency-middleware.test.js.map +0 -1
- /package/.claude/agents/{core-agents → developers}/researcher.md +0 -0
- /package/.claude/agents/{consensus → specialists}/crdt-synchronizer.md +0 -0
- /package/.claude/agents/{consensus → specialists}/quorum-manager.md +0 -0
- /package/.claude/agents/{consensus → specialists}/raft-manager.md +0 -0
- /package/.claude/{agents/core-agents → agents-ignore}/coordinator.md +0 -0
- /package/.claude/{agents/core-agents/cost-savings-coordinator.md → agents-ignore/cost-savings-coordinator.md.backup} +0 -0
- /package/.claude/skills/redis-coordination/{phase4-wake-queue-test-report.md → demos/phase4-wake-queue-test-report.md} +0 -0
- /package/.claude/skills/redis-coordination/{test-bzpopmin-fix.sh → demos/test-bzpopmin-fix.sh} +0 -0
- /package/.claude/skills/redis-coordination/{test-cancel-swarm.sh → demos/test-cancel-swarm.sh} +0 -0
- /package/.claude/skills/redis-coordination/{test-dlq.sh → demos/test-dlq.sh} +0 -0
- /package/.claude/skills/redis-coordination/{test-priority-wake-phase4-unix.sh → demos/test-priority-wake-phase4-unix.sh} +0 -0
- /package/.claude/skills/redis-coordination/{test-priority-wake-phase4.sh → demos/test-priority-wake-phase4.sh} +0 -0
- /package/.claude/skills/redis-coordination/{test-priority-wake.sh → demos/test-priority-wake.sh} +0 -0
- /package/.claude/skills/redis-coordination/{test-quick-fix.sh → demos/test-quick-fix.sh} +0 -0
- /package/.claude/skills/redis-coordination/{test-quorum-absolute.sh → demos/test-quorum-absolute.sh} +0 -0
- /package/.claude/skills/redis-coordination/{test-quorum-fallback.sh → demos/test-quorum-fallback.sh} +0 -0
- /package/.claude/skills/redis-coordination/{test-quorum-percentage.sh → demos/test-quorum-percentage.sh} +0 -0
- /package/.claude/skills/redis-coordination/{test-quorum-with-retry.sh → demos/test-quorum-with-retry.sh} +0 -0
- /package/.claude/skills/redis-coordination/{test-quorum.sh → demos/test-quorum.sh} +0 -0
- /package/.claude/skills/redis-coordination/{test-shutdown-handling.sh → demos/test-shutdown-handling.sh} +0 -0
- /package/.claude/skills/redis-coordination/{test-shutdown.sh → demos/test-shutdown.sh} +0 -0
- /package/.claude/skills/redis-coordination/{test-utils-unix.sh → demos/test-utils-unix.sh} +0 -0
- /package/.claude/skills/redis-coordination/{test-utils.sh → demos/test-utils.sh} +0 -0
- /package/.claude/skills/redis-coordination/{test-waiting-mode.sh → demos/test-waiting-mode.sh} +0 -0
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Agent Executor
|
|
3
|
+
*
|
|
4
|
+
* Executes CLI-spawned agents by:
|
|
5
|
+
* 1. Checking custom routing configuration (z.ai vs Anthropic)
|
|
6
|
+
* 2. Invoking the appropriate API
|
|
7
|
+
* 3. Managing agent lifecycle and output
|
|
8
|
+
*/ import { spawn } from 'child_process';
|
|
9
|
+
import { exec } from 'child_process';
|
|
10
|
+
import { promisify } from 'util';
|
|
11
|
+
import { getAgentId } from './agent-prompt-builder.js';
|
|
12
|
+
import { buildCLIAgentSystemPrompt, loadContextFromEnv } from './cli-agent-context.js';
|
|
13
|
+
import { loadMessages, storeMessage, getCurrentFork, formatMessagesForAPI } from './conversation-fork.js';
|
|
14
|
+
import { convertToolNames } from './tool-definitions.js';
|
|
15
|
+
import fs from 'fs/promises';
|
|
16
|
+
import path from 'path';
|
|
17
|
+
import os from 'os';
|
|
18
|
+
const execAsync = promisify(exec);
|
|
19
|
+
/**
|
|
20
|
+
* Extract confidence score from agent output
|
|
21
|
+
* Looks for patterns like:
|
|
22
|
+
* - "confidence: 0.85"
|
|
23
|
+
* - "Confidence: 0.90"
|
|
24
|
+
* - "confidence score: 0.95"
|
|
25
|
+
* - "self-confidence: 0.88"
|
|
26
|
+
*/ function extractConfidence(output) {
|
|
27
|
+
if (!output) return 0.85;
|
|
28
|
+
// Try multiple patterns
|
|
29
|
+
const patterns = [
|
|
30
|
+
/confidence:\s*([0-9.]+)/i,
|
|
31
|
+
/confidence\s+score:\s*([0-9.]+)/i,
|
|
32
|
+
/self-confidence:\s*([0-9.]+)/i,
|
|
33
|
+
/my\s+confidence:\s*([0-9.]+)/i
|
|
34
|
+
];
|
|
35
|
+
for (const pattern of patterns){
|
|
36
|
+
const match = output.match(pattern);
|
|
37
|
+
if (match && match[1]) {
|
|
38
|
+
const score = parseFloat(match[1]);
|
|
39
|
+
if (score >= 0 && score <= 1) {
|
|
40
|
+
return score;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
// Default to 0.85 if not found
|
|
45
|
+
return 0.85;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Execute CFN Loop protocol after agent completes work
|
|
49
|
+
*
|
|
50
|
+
* Steps:
|
|
51
|
+
* 1. Signal completion to orchestrator
|
|
52
|
+
* 2. Report confidence score
|
|
53
|
+
* 3. Enter waiting mode (if iterations enabled)
|
|
54
|
+
*/ async function executeCFNProtocol(taskId, agentId, output, iteration, enableIterations = false, maxIterations = 10) {
|
|
55
|
+
console.log(`\n[CFN Protocol] Starting for agent ${agentId}`);
|
|
56
|
+
console.log(`[CFN Protocol] Task ID: ${taskId}, Iteration: ${iteration}`);
|
|
57
|
+
try {
|
|
58
|
+
// Step 1: Signal completion
|
|
59
|
+
console.log('[CFN Protocol] Step 1: Signaling completion...');
|
|
60
|
+
await execAsync(`redis-cli lpush "swarm:${taskId}:${agentId}:done" "complete"`);
|
|
61
|
+
console.log('[CFN Protocol] ✓ Completion signaled');
|
|
62
|
+
// Step 2: Extract and report confidence
|
|
63
|
+
const confidence = extractConfidence(output);
|
|
64
|
+
console.log(`[CFN Protocol] Step 2: Reporting confidence (${confidence})...`);
|
|
65
|
+
const reportCmd = `./.claude/skills/redis-coordination/invoke-waiting-mode.sh report \
|
|
66
|
+
--task-id "${taskId}" \
|
|
67
|
+
--agent-id "${agentId}" \
|
|
68
|
+
--confidence ${confidence} \
|
|
69
|
+
--iteration ${iteration}`;
|
|
70
|
+
await execAsync(reportCmd);
|
|
71
|
+
console.log('[CFN Protocol] ✓ Confidence reported');
|
|
72
|
+
// Step 3: Exit cleanly (BUG #18 FIX - removed waiting mode)
|
|
73
|
+
// Orchestrator will spawn appropriate specialist agent for next iteration
|
|
74
|
+
// This enables adaptive agent specialization based on feedback type
|
|
75
|
+
console.log('[CFN Protocol] Step 3: Exiting cleanly (iteration complete)');
|
|
76
|
+
console.log('[CFN Protocol] Protocol complete\n');
|
|
77
|
+
} catch (error) {
|
|
78
|
+
console.error('[CFN Protocol] Error:', error);
|
|
79
|
+
throw error;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Check if custom routing (z.ai) is enabled
|
|
84
|
+
*/ async function isCustomRoutingEnabled() {
|
|
85
|
+
// Check environment variable
|
|
86
|
+
if (process.env.CLAUDE_API_PROVIDER === 'zai') {
|
|
87
|
+
return true;
|
|
88
|
+
}
|
|
89
|
+
// Check config file (.claude/config/api-provider.json)
|
|
90
|
+
try {
|
|
91
|
+
const configPath = path.join('.claude', 'config', 'api-provider.json');
|
|
92
|
+
const config = JSON.parse(await fs.readFile(configPath, 'utf-8'));
|
|
93
|
+
return config.provider === 'zai' || config.provider === 'z.ai';
|
|
94
|
+
} catch {
|
|
95
|
+
return false;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Get API provider configuration
|
|
100
|
+
*/ async function getAPIProvider() {
|
|
101
|
+
const customEnabled = await isCustomRoutingEnabled();
|
|
102
|
+
return customEnabled ? 'zai' : 'anthropic';
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Execute agent using direct API calls
|
|
106
|
+
*/ async function executeViaAPI(definition, prompt, context) {
|
|
107
|
+
const agentId = getAgentId(definition, context);
|
|
108
|
+
console.log(`[agent-executor] Executing agent via API: ${definition.name}`);
|
|
109
|
+
console.log(`[agent-executor] Agent ID: ${agentId}`);
|
|
110
|
+
console.log(`[agent-executor] Model: ${definition.model}`);
|
|
111
|
+
console.log('');
|
|
112
|
+
try {
|
|
113
|
+
// Check for conversation fork (Sprint 4 enhancement)
|
|
114
|
+
const forkId = process.env.FORK_ID || await getCurrentFork(context.taskId || '', agentId);
|
|
115
|
+
const iteration = context.iteration || 1;
|
|
116
|
+
let systemPrompt;
|
|
117
|
+
let messages = [];
|
|
118
|
+
if (forkId && iteration > 1) {
|
|
119
|
+
// Continue from fork (iterations 2+)
|
|
120
|
+
console.log(`[agent-executor] Continuing from fork: ${forkId}`);
|
|
121
|
+
// Load fork messages
|
|
122
|
+
const forkMessages = await loadMessages(context.taskId || '', agentId, forkId);
|
|
123
|
+
console.log(`[agent-executor] Loaded ${forkMessages.length} messages from fork`);
|
|
124
|
+
// Extract system prompt from first message (it's always the system message)
|
|
125
|
+
// The fork messages are assistant/user pairs, we need to add system separately
|
|
126
|
+
systemPrompt = forkMessages[0]?.content || '';
|
|
127
|
+
// Format remaining messages for API
|
|
128
|
+
messages = formatMessagesForAPI(forkMessages.slice(1));
|
|
129
|
+
// Add new user message with feedback
|
|
130
|
+
messages.push({
|
|
131
|
+
role: 'user',
|
|
132
|
+
content: prompt
|
|
133
|
+
});
|
|
134
|
+
console.log(`[agent-executor] Fork continuation: ${messages.length} messages`);
|
|
135
|
+
} else {
|
|
136
|
+
// New conversation (iteration 1)
|
|
137
|
+
console.log('[agent-executor] Starting new conversation');
|
|
138
|
+
console.log('[agent-executor] Building system prompt with context...');
|
|
139
|
+
const contextOptions = loadContextFromEnv();
|
|
140
|
+
contextOptions.agentType = definition.name;
|
|
141
|
+
if (context.taskId) contextOptions.taskId = context.taskId;
|
|
142
|
+
if (context.iteration) contextOptions.iteration = context.iteration;
|
|
143
|
+
systemPrompt = await buildCLIAgentSystemPrompt(contextOptions);
|
|
144
|
+
console.log('[agent-executor] System prompt built successfully');
|
|
145
|
+
// Initial user message
|
|
146
|
+
messages = [
|
|
147
|
+
{
|
|
148
|
+
role: 'user',
|
|
149
|
+
content: prompt
|
|
150
|
+
}
|
|
151
|
+
];
|
|
152
|
+
}
|
|
153
|
+
console.log('');
|
|
154
|
+
// Dynamic import to avoid bundling issues
|
|
155
|
+
const { executeAgentAPI } = await import('./anthropic-client.js');
|
|
156
|
+
// Convert agent tool names to Anthropic API format
|
|
157
|
+
const tools = definition.tools && definition.tools.length > 0 ? convertToolNames(definition.tools) : undefined;
|
|
158
|
+
const result = await executeAgentAPI(definition.name, agentId, definition.model, prompt, systemPrompt, messages.length > 1 ? messages : undefined, undefined, tools // Pass converted tools
|
|
159
|
+
);
|
|
160
|
+
// Store messages in conversation history (for future forking)
|
|
161
|
+
if (context.taskId) {
|
|
162
|
+
// Store user message
|
|
163
|
+
const userMessage = {
|
|
164
|
+
role: 'user',
|
|
165
|
+
content: prompt,
|
|
166
|
+
iteration,
|
|
167
|
+
timestamp: new Date().toISOString()
|
|
168
|
+
};
|
|
169
|
+
await storeMessage(context.taskId, agentId, userMessage);
|
|
170
|
+
// Store assistant response
|
|
171
|
+
if (result.output) {
|
|
172
|
+
const assistantMessage = {
|
|
173
|
+
role: 'assistant',
|
|
174
|
+
content: result.output,
|
|
175
|
+
iteration,
|
|
176
|
+
timestamp: new Date().toISOString()
|
|
177
|
+
};
|
|
178
|
+
await storeMessage(context.taskId, agentId, assistantMessage);
|
|
179
|
+
}
|
|
180
|
+
console.log(`[agent-executor] Stored messages for iteration ${iteration}`);
|
|
181
|
+
// Execute CFN Loop protocol (signal completion, report confidence, enter waiting mode)
|
|
182
|
+
// Iterations are enabled for CFN Loop tasks (indicated by presence of taskId)
|
|
183
|
+
try {
|
|
184
|
+
const maxIterations = 10; // Default max iterations
|
|
185
|
+
const enableIterations = true; // Enable iterations for all CFN Loop tasks
|
|
186
|
+
await executeCFNProtocol(context.taskId, agentId, result.output, iteration, enableIterations, maxIterations);
|
|
187
|
+
} catch (error) {
|
|
188
|
+
console.error('[agent-executor] CFN Protocol execution failed:', error);
|
|
189
|
+
// Don't fail the entire agent execution if CFN protocol fails
|
|
190
|
+
// This allows agents to complete even if Redis coordination has issues
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
return {
|
|
194
|
+
success: result.success,
|
|
195
|
+
agentId,
|
|
196
|
+
output: result.output,
|
|
197
|
+
error: result.error,
|
|
198
|
+
exitCode: result.success ? 0 : 1
|
|
199
|
+
};
|
|
200
|
+
} catch (error) {
|
|
201
|
+
console.error('[agent-executor] API execution failed:', error);
|
|
202
|
+
return {
|
|
203
|
+
success: false,
|
|
204
|
+
agentId,
|
|
205
|
+
error: error instanceof Error ? error.message : String(error),
|
|
206
|
+
exitCode: 1
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* Execute agent using shell script (fallback/simulation)
|
|
212
|
+
*/ async function executeViaScript(definition, prompt, context) {
|
|
213
|
+
const agentId = getAgentId(definition, context);
|
|
214
|
+
// Write prompt to temporary file
|
|
215
|
+
const tmpDir = os.tmpdir();
|
|
216
|
+
const promptFile = path.join(tmpDir, `agent-${agentId}-${Date.now()}.md`);
|
|
217
|
+
await fs.writeFile(promptFile, prompt, 'utf-8');
|
|
218
|
+
console.log(`[agent-executor] Executing agent via script: ${definition.name}`);
|
|
219
|
+
console.log(`[agent-executor] Agent ID: ${agentId}`);
|
|
220
|
+
console.log(`[agent-executor] Model: ${definition.model}`);
|
|
221
|
+
console.log(`[agent-executor] Prompt file: ${promptFile}`);
|
|
222
|
+
return new Promise((resolve)=>{
|
|
223
|
+
const scriptPath = path.join('.claude', 'skills', 'agent-execution', 'execute-agent.sh');
|
|
224
|
+
// Build environment variables
|
|
225
|
+
const env = {
|
|
226
|
+
...process.env,
|
|
227
|
+
AGENT_TYPE: definition.name,
|
|
228
|
+
AGENT_ID: agentId,
|
|
229
|
+
AGENT_MODEL: definition.model,
|
|
230
|
+
AGENT_TOOLS: definition.tools.join(','),
|
|
231
|
+
TASK_ID: context.taskId || '',
|
|
232
|
+
ITERATION: String(context.iteration || 1),
|
|
233
|
+
MODE: context.mode || 'cli',
|
|
234
|
+
PROMPT_FILE: promptFile
|
|
235
|
+
};
|
|
236
|
+
// Check if execute script exists
|
|
237
|
+
fs.access(scriptPath).then(()=>{
|
|
238
|
+
// Use execution script
|
|
239
|
+
const proc = spawn('bash', [
|
|
240
|
+
scriptPath
|
|
241
|
+
], {
|
|
242
|
+
env,
|
|
243
|
+
stdio: 'inherit'
|
|
244
|
+
});
|
|
245
|
+
proc.on('exit', (code)=>{
|
|
246
|
+
resolve({
|
|
247
|
+
success: code === 0,
|
|
248
|
+
agentId,
|
|
249
|
+
exitCode: code || 0
|
|
250
|
+
});
|
|
251
|
+
});
|
|
252
|
+
proc.on('error', (err)=>{
|
|
253
|
+
resolve({
|
|
254
|
+
success: false,
|
|
255
|
+
agentId,
|
|
256
|
+
error: err.message,
|
|
257
|
+
exitCode: 1
|
|
258
|
+
});
|
|
259
|
+
});
|
|
260
|
+
}).catch(()=>{
|
|
261
|
+
// Fallback: Print prompt
|
|
262
|
+
console.log('\n=== Agent Prompt ===');
|
|
263
|
+
console.log(prompt.substring(0, 500) + '...');
|
|
264
|
+
console.log('\n[agent-executor] Execution script not found');
|
|
265
|
+
console.log('[agent-executor] Using simulation mode\n');
|
|
266
|
+
resolve({
|
|
267
|
+
success: true,
|
|
268
|
+
agentId,
|
|
269
|
+
output: prompt,
|
|
270
|
+
exitCode: 0
|
|
271
|
+
});
|
|
272
|
+
});
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
/**
|
|
276
|
+
* Main agent execution function
|
|
277
|
+
*/ export async function executeAgent(definition, prompt, context, options = {}) {
|
|
278
|
+
const method = options.method || 'auto';
|
|
279
|
+
// Auto-select execution method
|
|
280
|
+
if (method === 'auto') {
|
|
281
|
+
// Try API execution first, fallback to script if API key not available
|
|
282
|
+
try {
|
|
283
|
+
return await executeViaAPI(definition, prompt, context);
|
|
284
|
+
} catch (error) {
|
|
285
|
+
if (error instanceof Error && error.message.includes('API key not found')) {
|
|
286
|
+
console.log('[agent-executor] API key not found, using script fallback');
|
|
287
|
+
return executeViaScript(definition, prompt, context);
|
|
288
|
+
}
|
|
289
|
+
throw error;
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
if (method === 'api') {
|
|
293
|
+
return executeViaAPI(definition, prompt, context);
|
|
294
|
+
}
|
|
295
|
+
return executeViaScript(definition, prompt, context);
|
|
296
|
+
}
|
|
297
|
+
/**
|
|
298
|
+
* Write agent output to file for debugging
|
|
299
|
+
*/ export async function saveAgentOutput(agentId, output, outputDir = '.claude/tmp/agent-output') {
|
|
300
|
+
await fs.mkdir(outputDir, {
|
|
301
|
+
recursive: true
|
|
302
|
+
});
|
|
303
|
+
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
|
|
304
|
+
const filename = `${agentId}-${timestamp}.txt`;
|
|
305
|
+
const filepath = path.join(outputDir, filename);
|
|
306
|
+
await fs.writeFile(filepath, output, 'utf-8');
|
|
307
|
+
return filepath;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
//# sourceMappingURL=agent-executor.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/cli/agent-executor.ts"],"sourcesContent":["/**\r\n * Agent Executor\r\n *\r\n * Executes CLI-spawned agents by:\r\n * 1. Checking custom routing configuration (z.ai vs Anthropic)\r\n * 2. Invoking the appropriate API\r\n * 3. Managing agent lifecycle and output\r\n */\r\n\r\nimport { spawn } from 'child_process';\r\nimport { exec } from 'child_process';\r\nimport { promisify } from 'util';\r\nimport { AgentDefinition } from './agent-definition-parser.js';\r\nimport { TaskContext, getAgentId } from './agent-prompt-builder.js';\r\nimport { buildCLIAgentSystemPrompt, loadContextFromEnv } from './cli-agent-context.js';\r\nimport {\r\n loadMessages,\r\n storeMessage,\r\n getCurrentFork,\r\n formatMessagesForAPI,\r\n type Message\r\n} from './conversation-fork.js';\r\nimport { convertToolNames } from './tool-definitions.js';\r\nimport fs from 'fs/promises';\r\nimport path from 'path';\r\nimport os from 'os';\r\n\r\nconst execAsync = promisify(exec);\r\n\r\nexport interface AgentExecutionResult {\r\n success: boolean;\r\n agentId: string;\r\n output?: string;\r\n error?: string;\r\n exitCode: number;\r\n}\r\n\r\n/**\r\n * Extract confidence score from agent output\r\n * Looks for patterns like:\r\n * - \"confidence: 0.85\"\r\n * - \"Confidence: 0.90\"\r\n * - \"confidence score: 0.95\"\r\n * - \"self-confidence: 0.88\"\r\n */\r\nfunction extractConfidence(output: string | undefined): number {\r\n if (!output) return 0.85;\r\n\r\n // Try multiple patterns\r\n const patterns = [\r\n /confidence:\\s*([0-9.]+)/i,\r\n /confidence\\s+score:\\s*([0-9.]+)/i,\r\n /self-confidence:\\s*([0-9.]+)/i,\r\n /my\\s+confidence:\\s*([0-9.]+)/i,\r\n ];\r\n\r\n for (const pattern of patterns) {\r\n const match = output.match(pattern);\r\n if (match && match[1]) {\r\n const score = parseFloat(match[1]);\r\n if (score >= 0 && score <= 1) {\r\n return score;\r\n }\r\n }\r\n }\r\n\r\n // Default to 0.85 if not found\r\n return 0.85;\r\n}\r\n\r\n/**\r\n * Execute CFN Loop protocol after agent completes work\r\n *\r\n * Steps:\r\n * 1. Signal completion to orchestrator\r\n * 2. Report confidence score\r\n * 3. Enter waiting mode (if iterations enabled)\r\n */\r\nasync function executeCFNProtocol(\r\n taskId: string,\r\n agentId: string,\r\n output: string | undefined,\r\n iteration: number,\r\n enableIterations: boolean = false,\r\n maxIterations: number = 10\r\n): Promise<void> {\r\n console.log(`\\n[CFN Protocol] Starting for agent ${agentId}`);\r\n console.log(`[CFN Protocol] Task ID: ${taskId}, Iteration: ${iteration}`);\r\n\r\n try {\r\n // Step 1: Signal completion\r\n console.log('[CFN Protocol] Step 1: Signaling completion...');\r\n await execAsync(`redis-cli lpush \"swarm:${taskId}:${agentId}:done\" \"complete\"`);\r\n console.log('[CFN Protocol] ✓ Completion signaled');\r\n\r\n // Step 2: Extract and report confidence\r\n const confidence = extractConfidence(output);\r\n console.log(`[CFN Protocol] Step 2: Reporting confidence (${confidence})...`);\r\n\r\n const reportCmd = `./.claude/skills/redis-coordination/invoke-waiting-mode.sh report \\\r\n --task-id \"${taskId}\" \\\r\n --agent-id \"${agentId}\" \\\r\n --confidence ${confidence} \\\r\n --iteration ${iteration}`;\r\n\r\n await execAsync(reportCmd);\r\n console.log('[CFN Protocol] ✓ Confidence reported');\r\n\r\n // Step 3: Exit cleanly (BUG #18 FIX - removed waiting mode)\r\n // Orchestrator will spawn appropriate specialist agent for next iteration\r\n // This enables adaptive agent specialization based on feedback type\r\n console.log('[CFN Protocol] Step 3: Exiting cleanly (iteration complete)');\r\n console.log('[CFN Protocol] Protocol complete\\n');\r\n } catch (error) {\r\n console.error('[CFN Protocol] Error:', error);\r\n throw error;\r\n }\r\n}\r\n\r\n/**\r\n * Check if custom routing (z.ai) is enabled\r\n */\r\nasync function isCustomRoutingEnabled(): Promise<boolean> {\r\n // Check environment variable\r\n if (process.env.CLAUDE_API_PROVIDER === 'zai') {\r\n return true;\r\n }\r\n\r\n // Check config file (.claude/config/api-provider.json)\r\n try {\r\n const configPath = path.join('.claude', 'config', 'api-provider.json');\r\n const config = JSON.parse(await fs.readFile(configPath, 'utf-8'));\r\n return config.provider === 'zai' || config.provider === 'z.ai';\r\n } catch {\r\n return false;\r\n }\r\n}\r\n\r\n/**\r\n * Get API provider configuration\r\n */\r\nasync function getAPIProvider(): Promise<'anthropic' | 'zai'> {\r\n const customEnabled = await isCustomRoutingEnabled();\r\n return customEnabled ? 'zai' : 'anthropic';\r\n}\r\n\r\n/**\r\n * Execute agent using direct API calls\r\n */\r\nasync function executeViaAPI(\r\n definition: AgentDefinition,\r\n prompt: string,\r\n context: TaskContext\r\n): Promise<AgentExecutionResult> {\r\n const agentId = getAgentId(definition, context);\r\n\r\n console.log(`[agent-executor] Executing agent via API: ${definition.name}`);\r\n console.log(`[agent-executor] Agent ID: ${agentId}`);\r\n console.log(`[agent-executor] Model: ${definition.model}`);\r\n console.log('');\r\n\r\n try {\r\n // Check for conversation fork (Sprint 4 enhancement)\r\n const forkId = process.env.FORK_ID || await getCurrentFork(context.taskId || '', agentId);\r\n const iteration = context.iteration || 1;\r\n\r\n let systemPrompt: string;\r\n let messages: Array<{role: string, content: string}> = [];\r\n\r\n if (forkId && iteration > 1) {\r\n // Continue from fork (iterations 2+)\r\n console.log(`[agent-executor] Continuing from fork: ${forkId}`);\r\n\r\n // Load fork messages\r\n const forkMessages = await loadMessages(context.taskId || '', agentId, forkId);\r\n console.log(`[agent-executor] Loaded ${forkMessages.length} messages from fork`);\r\n\r\n // Extract system prompt from first message (it's always the system message)\r\n // The fork messages are assistant/user pairs, we need to add system separately\r\n systemPrompt = forkMessages[0]?.content || '';\r\n\r\n // Format remaining messages for API\r\n messages = formatMessagesForAPI(forkMessages.slice(1));\r\n\r\n // Add new user message with feedback\r\n messages.push({\r\n role: 'user',\r\n content: prompt\r\n });\r\n\r\n console.log(`[agent-executor] Fork continuation: ${messages.length} messages`);\r\n } else {\r\n // New conversation (iteration 1)\r\n console.log('[agent-executor] Starting new conversation');\r\n console.log('[agent-executor] Building system prompt with context...');\r\n\r\n const contextOptions = loadContextFromEnv();\r\n contextOptions.agentType = definition.name;\r\n if (context.taskId) contextOptions.taskId = context.taskId;\r\n if (context.iteration) contextOptions.iteration = context.iteration;\r\n\r\n systemPrompt = await buildCLIAgentSystemPrompt(contextOptions);\r\n console.log('[agent-executor] System prompt built successfully');\r\n\r\n // Initial user message\r\n messages = [{\r\n role: 'user',\r\n content: prompt\r\n }];\r\n }\r\n\r\n console.log('');\r\n\r\n // Dynamic import to avoid bundling issues\r\n const { executeAgentAPI } = await import('./anthropic-client.js');\r\n\r\n // Convert agent tool names to Anthropic API format\r\n const tools = definition.tools && definition.tools.length > 0\r\n ? convertToolNames(definition.tools)\r\n : undefined;\r\n\r\n const result = await executeAgentAPI(\r\n definition.name,\r\n agentId,\r\n definition.model,\r\n prompt,\r\n systemPrompt,\r\n messages.length > 1 ? messages : undefined,\r\n undefined, // maxTokens (use default)\r\n tools // Pass converted tools\r\n );\r\n\r\n // Store messages in conversation history (for future forking)\r\n if (context.taskId) {\r\n // Store user message\r\n const userMessage: Message = {\r\n role: 'user',\r\n content: prompt,\r\n iteration,\r\n timestamp: new Date().toISOString()\r\n };\r\n await storeMessage(context.taskId, agentId, userMessage);\r\n\r\n // Store assistant response\r\n if (result.output) {\r\n const assistantMessage: Message = {\r\n role: 'assistant',\r\n content: result.output,\r\n iteration,\r\n timestamp: new Date().toISOString()\r\n };\r\n await storeMessage(context.taskId, agentId, assistantMessage);\r\n }\r\n\r\n console.log(`[agent-executor] Stored messages for iteration ${iteration}`);\r\n\r\n // Execute CFN Loop protocol (signal completion, report confidence, enter waiting mode)\r\n // Iterations are enabled for CFN Loop tasks (indicated by presence of taskId)\r\n try {\r\n const maxIterations = 10; // Default max iterations\r\n const enableIterations = true; // Enable iterations for all CFN Loop tasks\r\n\r\n await executeCFNProtocol(\r\n context.taskId,\r\n agentId,\r\n result.output,\r\n iteration,\r\n enableIterations,\r\n maxIterations\r\n );\r\n } catch (error) {\r\n console.error('[agent-executor] CFN Protocol execution failed:', error);\r\n // Don't fail the entire agent execution if CFN protocol fails\r\n // This allows agents to complete even if Redis coordination has issues\r\n }\r\n }\r\n\r\n return {\r\n success: result.success,\r\n agentId,\r\n output: result.output,\r\n error: result.error,\r\n exitCode: result.success ? 0 : 1,\r\n };\r\n } catch (error) {\r\n console.error('[agent-executor] API execution failed:', error);\r\n return {\r\n success: false,\r\n agentId,\r\n error: error instanceof Error ? error.message : String(error),\r\n exitCode: 1,\r\n };\r\n }\r\n}\r\n\r\n/**\r\n * Execute agent using shell script (fallback/simulation)\r\n */\r\nasync function executeViaScript(\r\n definition: AgentDefinition,\r\n prompt: string,\r\n context: TaskContext\r\n): Promise<AgentExecutionResult> {\r\n const agentId = getAgentId(definition, context);\r\n\r\n // Write prompt to temporary file\r\n const tmpDir = os.tmpdir();\r\n const promptFile = path.join(tmpDir, `agent-${agentId}-${Date.now()}.md`);\r\n await fs.writeFile(promptFile, prompt, 'utf-8');\r\n\r\n console.log(`[agent-executor] Executing agent via script: ${definition.name}`);\r\n console.log(`[agent-executor] Agent ID: ${agentId}`);\r\n console.log(`[agent-executor] Model: ${definition.model}`);\r\n console.log(`[agent-executor] Prompt file: ${promptFile}`);\r\n\r\n return new Promise((resolve) => {\r\n const scriptPath = path.join('.claude', 'skills', 'agent-execution', 'execute-agent.sh');\r\n\r\n // Build environment variables\r\n const env = {\r\n ...process.env,\r\n AGENT_TYPE: definition.name,\r\n AGENT_ID: agentId,\r\n AGENT_MODEL: definition.model,\r\n AGENT_TOOLS: definition.tools.join(','),\r\n TASK_ID: context.taskId || '',\r\n ITERATION: String(context.iteration || 1),\r\n MODE: context.mode || 'cli',\r\n PROMPT_FILE: promptFile,\r\n };\r\n\r\n // Check if execute script exists\r\n fs.access(scriptPath)\r\n .then(() => {\r\n // Use execution script\r\n const proc = spawn('bash', [scriptPath], { env, stdio: 'inherit' });\r\n\r\n proc.on('exit', (code) => {\r\n resolve({\r\n success: code === 0,\r\n agentId,\r\n exitCode: code || 0,\r\n });\r\n });\r\n\r\n proc.on('error', (err) => {\r\n resolve({\r\n success: false,\r\n agentId,\r\n error: err.message,\r\n exitCode: 1,\r\n });\r\n });\r\n })\r\n .catch(() => {\r\n // Fallback: Print prompt\r\n console.log('\\n=== Agent Prompt ===');\r\n console.log(prompt.substring(0, 500) + '...');\r\n console.log('\\n[agent-executor] Execution script not found');\r\n console.log('[agent-executor] Using simulation mode\\n');\r\n\r\n resolve({\r\n success: true,\r\n agentId,\r\n output: prompt,\r\n exitCode: 0,\r\n });\r\n });\r\n });\r\n}\r\n\r\n/**\r\n * Main agent execution function\r\n */\r\nexport async function executeAgent(\r\n definition: AgentDefinition,\r\n prompt: string,\r\n context: TaskContext,\r\n options: {\r\n method?: 'auto' | 'api' | 'script';\r\n } = {}\r\n): Promise<AgentExecutionResult> {\r\n const method = options.method || 'auto';\r\n\r\n // Auto-select execution method\r\n if (method === 'auto') {\r\n // Try API execution first, fallback to script if API key not available\r\n try {\r\n return await executeViaAPI(definition, prompt, context);\r\n } catch (error) {\r\n if (error instanceof Error && error.message.includes('API key not found')) {\r\n console.log('[agent-executor] API key not found, using script fallback');\r\n return executeViaScript(definition, prompt, context);\r\n }\r\n throw error;\r\n }\r\n }\r\n\r\n if (method === 'api') {\r\n return executeViaAPI(definition, prompt, context);\r\n }\r\n\r\n return executeViaScript(definition, prompt, context);\r\n}\r\n\r\n/**\r\n * Write agent output to file for debugging\r\n */\r\nexport async function saveAgentOutput(\r\n agentId: string,\r\n output: string,\r\n outputDir: string = '.claude/tmp/agent-output'\r\n): Promise<string> {\r\n await fs.mkdir(outputDir, { recursive: true });\r\n\r\n const timestamp = new Date().toISOString().replace(/[:.]/g, '-');\r\n const filename = `${agentId}-${timestamp}.txt`;\r\n const filepath = path.join(outputDir, filename);\r\n\r\n await fs.writeFile(filepath, output, 'utf-8');\r\n\r\n return filepath;\r\n}\r\n"],"names":["spawn","exec","promisify","getAgentId","buildCLIAgentSystemPrompt","loadContextFromEnv","loadMessages","storeMessage","getCurrentFork","formatMessagesForAPI","convertToolNames","fs","path","os","execAsync","extractConfidence","output","patterns","pattern","match","score","parseFloat","executeCFNProtocol","taskId","agentId","iteration","enableIterations","maxIterations","console","log","confidence","reportCmd","error","isCustomRoutingEnabled","process","env","CLAUDE_API_PROVIDER","configPath","join","config","JSON","parse","readFile","provider","getAPIProvider","customEnabled","executeViaAPI","definition","prompt","context","name","model","forkId","FORK_ID","systemPrompt","messages","forkMessages","length","content","slice","push","role","contextOptions","agentType","executeAgentAPI","tools","undefined","result","userMessage","timestamp","Date","toISOString","assistantMessage","success","exitCode","Error","message","String","executeViaScript","tmpDir","tmpdir","promptFile","now","writeFile","Promise","resolve","scriptPath","AGENT_TYPE","AGENT_ID","AGENT_MODEL","AGENT_TOOLS","TASK_ID","ITERATION","MODE","mode","PROMPT_FILE","access","then","proc","stdio","on","code","err","catch","substring","executeAgent","options","method","includes","saveAgentOutput","outputDir","mkdir","recursive","replace","filename","filepath"],"mappings":"AAAA;;;;;;;CAOC,GAED,SAASA,KAAK,QAAQ,gBAAgB;AACtC,SAASC,IAAI,QAAQ,gBAAgB;AACrC,SAASC,SAAS,QAAQ,OAAO;AAEjC,SAAsBC,UAAU,QAAQ,4BAA4B;AACpE,SAASC,yBAAyB,EAAEC,kBAAkB,QAAQ,yBAAyB;AACvF,SACEC,YAAY,EACZC,YAAY,EACZC,cAAc,EACdC,oBAAoB,QAEf,yBAAyB;AAChC,SAASC,gBAAgB,QAAQ,wBAAwB;AACzD,OAAOC,QAAQ,cAAc;AAC7B,OAAOC,UAAU,OAAO;AACxB,OAAOC,QAAQ,KAAK;AAEpB,MAAMC,YAAYZ,UAAUD;AAU5B;;;;;;;CAOC,GACD,SAASc,kBAAkBC,MAA0B;IACnD,IAAI,CAACA,QAAQ,OAAO;IAEpB,wBAAwB;IACxB,MAAMC,WAAW;QACf;QACA;QACA;QACA;KACD;IAED,KAAK,MAAMC,WAAWD,SAAU;QAC9B,MAAME,QAAQH,OAAOG,KAAK,CAACD;QAC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prompts for CLI-spawned agents by combining:
|
|
5
|
+
* - Agent definition (YAML + markdown)
|
|
6
|
+
* - Task context (taskId, iteration, mode)
|
|
7
|
+
* - CFN Loop protocol (if applicable)
|
|
8
|
+
* - Iteration history (Sprint 3 - Phase 2)
|
|
9
|
+
* - Environment variables
|
|
10
|
+
*/ import { hasCFNLoopProtocol } from './agent-definition-parser.js';
|
|
11
|
+
import { loadIterationHistory, formatIterationHistory } from './iteration-history.js';
|
|
12
|
+
/**
|
|
13
|
+
* Build CFN Loop protocol instructions
|
|
14
|
+
*/ function buildCFNLoopProtocol(taskId, agentId) {
|
|
15
|
+
return `
|
|
16
|
+
## CFN Loop Redis Completion Protocol
|
|
17
|
+
|
|
18
|
+
You are participating in a CFN Loop workflow. Follow this protocol EXACTLY:
|
|
19
|
+
|
|
20
|
+
### Step 1: Complete Work
|
|
21
|
+
Execute your assigned task (implementation, review, testing, etc.)
|
|
22
|
+
|
|
23
|
+
### Step 2: Signal Completion
|
|
24
|
+
\`\`\`bash
|
|
25
|
+
redis-cli lpush "swarm:${taskId}:\${AGENT_ID}:done" "complete"
|
|
26
|
+
\`\`\`
|
|
27
|
+
|
|
28
|
+
### Step 3: Report Confidence Score
|
|
29
|
+
\`\`\`bash
|
|
30
|
+
./.claude/skills/redis-coordination/invoke-waiting-mode.sh report \\
|
|
31
|
+
--task-id "${taskId}" \\
|
|
32
|
+
--agent-id "\${AGENT_ID}" \\
|
|
33
|
+
--confidence [0.0-1.0] \\
|
|
34
|
+
--iteration ${taskId.includes('iteration') ? 'CURRENT_ITERATION' : '1'}
|
|
35
|
+
\`\`\`
|
|
36
|
+
|
|
37
|
+
### Step 4: Enter Waiting Mode (for potential iteration)
|
|
38
|
+
\`\`\`bash
|
|
39
|
+
./.claude/skills/redis-coordination/invoke-waiting-mode.sh enter \\
|
|
40
|
+
--task-id "${taskId}" \\
|
|
41
|
+
--agent-id "\${AGENT_ID}" \\
|
|
42
|
+
--context "iteration-complete"
|
|
43
|
+
\`\`\`
|
|
44
|
+
|
|
45
|
+
**Critical Context Variables:**
|
|
46
|
+
- TASK_ID: ${taskId}
|
|
47
|
+
- AGENT_ID: ${agentId} (your unique identifier)
|
|
48
|
+
- Confidence: Your self-assessment score (0.0-1.0)
|
|
49
|
+
|
|
50
|
+
**Why This Matters:**
|
|
51
|
+
- Zero-token blocking coordination (BLPOP waits without API calls)
|
|
52
|
+
- Orchestrator collects confidence/consensus scores automatically
|
|
53
|
+
- Supports autonomous iteration based on quality gates
|
|
54
|
+
- Agent woken instantly (<100ms) if iteration needed
|
|
55
|
+
|
|
56
|
+
**IMPORTANT:** You MUST complete all 4 steps in order. The orchestrator is waiting for your completion signal.
|
|
57
|
+
`;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Parse and enrich JSON context into natural language instructions
|
|
61
|
+
*/ function enrichJSONContext(jsonObj) {
|
|
62
|
+
const sections = [];
|
|
63
|
+
// Extract task description
|
|
64
|
+
if (jsonObj.task) {
|
|
65
|
+
sections.push(`**Task:** ${jsonObj.task}`);
|
|
66
|
+
}
|
|
67
|
+
// Parse files - convert comma-separated string to bullet list
|
|
68
|
+
if (jsonObj.files) {
|
|
69
|
+
const fileList = typeof jsonObj.files === 'string' ? jsonObj.files.split(',').map((f)=>f.trim()).filter((f)=>f) : Array.isArray(jsonObj.files) ? jsonObj.files : [];
|
|
70
|
+
if (fileList.length > 0) {
|
|
71
|
+
sections.push('\n**Files to process:**');
|
|
72
|
+
fileList.forEach((file)=>sections.push(`- ${file}`));
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
// Add requirements/deliverables
|
|
76
|
+
if (jsonObj.requirements) {
|
|
77
|
+
const reqs = Array.isArray(jsonObj.requirements) ? jsonObj.requirements : [
|
|
78
|
+
jsonObj.requirements
|
|
79
|
+
];
|
|
80
|
+
sections.push('\n**Requirements:**');
|
|
81
|
+
reqs.forEach((req, i)=>sections.push(`${i + 1}. ${req}`));
|
|
82
|
+
}
|
|
83
|
+
if (jsonObj.deliverables) {
|
|
84
|
+
const delivs = Array.isArray(jsonObj.deliverables) ? jsonObj.deliverables : [
|
|
85
|
+
jsonObj.deliverables
|
|
86
|
+
];
|
|
87
|
+
sections.push('\n**Deliverables:**');
|
|
88
|
+
delivs.forEach((deliv)=>sections.push(`- ${deliv}`));
|
|
89
|
+
}
|
|
90
|
+
// Add batch information
|
|
91
|
+
if (jsonObj.batch) {
|
|
92
|
+
sections.push(`\n**Batch:** ${jsonObj.batch}`);
|
|
93
|
+
}
|
|
94
|
+
// Add directory context
|
|
95
|
+
if (jsonObj.directory) {
|
|
96
|
+
sections.push(`\n**Working Directory:** ${jsonObj.directory}`);
|
|
97
|
+
}
|
|
98
|
+
// Add acceptance criteria
|
|
99
|
+
if (jsonObj.acceptanceCriteria) {
|
|
100
|
+
const criteria = Array.isArray(jsonObj.acceptanceCriteria) ? jsonObj.acceptanceCriteria : [
|
|
101
|
+
jsonObj.acceptanceCriteria
|
|
102
|
+
];
|
|
103
|
+
sections.push('\n**Acceptance Criteria:**');
|
|
104
|
+
criteria.forEach((criterion)=>sections.push(`- ${criterion}`));
|
|
105
|
+
}
|
|
106
|
+
// Add explicit instructions if present
|
|
107
|
+
if (jsonObj.instructions) {
|
|
108
|
+
sections.push('\n**Instructions:**');
|
|
109
|
+
const instrs = Array.isArray(jsonObj.instructions) ? jsonObj.instructions : [
|
|
110
|
+
jsonObj.instructions
|
|
111
|
+
];
|
|
112
|
+
instrs.forEach((instr, i)=>sections.push(`${i + 1}. ${instr}`));
|
|
113
|
+
}
|
|
114
|
+
return sections.join('\n');
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Build task description from context
|
|
118
|
+
*/ function buildTaskDescription(agentType, context) {
|
|
119
|
+
let desc = '';
|
|
120
|
+
if (context.context) {
|
|
121
|
+
// Try to parse as JSON first
|
|
122
|
+
let contextStr = context.context.trim();
|
|
123
|
+
// Check if context looks like JSON
|
|
124
|
+
if (contextStr.startsWith('{') && contextStr.endsWith('}') || contextStr.startsWith('[') && contextStr.endsWith(']')) {
|
|
125
|
+
try {
|
|
126
|
+
const jsonObj = JSON.parse(contextStr);
|
|
127
|
+
desc = enrichJSONContext(jsonObj);
|
|
128
|
+
// Add instruction footer for structured tasks
|
|
129
|
+
if (jsonObj.files || jsonObj.deliverables) {
|
|
130
|
+
desc += '\n\n**Process each item systematically and report confidence when complete.**';
|
|
131
|
+
}
|
|
132
|
+
} catch (e) {
|
|
133
|
+
// Not valid JSON, treat as plain text
|
|
134
|
+
desc = context.context;
|
|
135
|
+
}
|
|
136
|
+
} else {
|
|
137
|
+
// Plain text context
|
|
138
|
+
desc = context.context;
|
|
139
|
+
}
|
|
140
|
+
} else {
|
|
141
|
+
desc = `Execute task as ${agentType} agent`;
|
|
142
|
+
}
|
|
143
|
+
// Add metadata fields
|
|
144
|
+
if (context.taskId) {
|
|
145
|
+
desc += `\n\n**Task ID:** ${context.taskId}`;
|
|
146
|
+
}
|
|
147
|
+
if (context.iteration) {
|
|
148
|
+
desc += `\n**Iteration:** ${context.iteration}`;
|
|
149
|
+
}
|
|
150
|
+
if (context.mode) {
|
|
151
|
+
desc += `\n**Mode:** ${context.mode}`;
|
|
152
|
+
}
|
|
153
|
+
if (context.priority) {
|
|
154
|
+
desc += `\n**Priority:** ${context.priority}`;
|
|
155
|
+
}
|
|
156
|
+
if (context.parentTaskId) {
|
|
157
|
+
desc += `\n**Parent Task:** ${context.parentTaskId}`;
|
|
158
|
+
}
|
|
159
|
+
return desc;
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Build environment context section
|
|
163
|
+
*/ function buildEnvironmentContext(context) {
|
|
164
|
+
const env = [];
|
|
165
|
+
if (context.taskId) env.push(`TASK_ID=${context.taskId}`);
|
|
166
|
+
if (context.iteration) env.push(`ITERATION=${context.iteration}`);
|
|
167
|
+
if (context.mode) env.push(`MODE=${context.mode}`);
|
|
168
|
+
if (context.priority) env.push(`PRIORITY=${context.priority}`);
|
|
169
|
+
if (context.parentTaskId) env.push(`PARENT_TASK_ID=${context.parentTaskId}`);
|
|
170
|
+
if (env.length === 0) return '';
|
|
171
|
+
return `
|
|
172
|
+
## Environment Variables
|
|
173
|
+
|
|
174
|
+
\`\`\`bash
|
|
175
|
+
${env.join('\n')}
|
|
176
|
+
\`\`\`
|
|
177
|
+
`;
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Build complete prompt for agent execution (async for iteration history)
|
|
181
|
+
*/ export async function buildAgentPrompt(definition, context) {
|
|
182
|
+
const agentId = `${definition.name}-${context.iteration || 1}`;
|
|
183
|
+
const sections = [];
|
|
184
|
+
// 1. Agent definition header
|
|
185
|
+
sections.push(`# Agent: ${definition.name}`);
|
|
186
|
+
sections.push('');
|
|
187
|
+
sections.push(definition.description);
|
|
188
|
+
sections.push('');
|
|
189
|
+
// 2. Task description
|
|
190
|
+
sections.push('## Task');
|
|
191
|
+
sections.push('');
|
|
192
|
+
sections.push(buildTaskDescription(definition.name, context));
|
|
193
|
+
sections.push('');
|
|
194
|
+
// 3. Iteration history (Sprint 3 - Phase 2)
|
|
195
|
+
// Load and format previous iterations if iteration > 1
|
|
196
|
+
if (context.taskId && context.iteration && context.iteration > 1) {
|
|
197
|
+
try {
|
|
198
|
+
const history = await loadIterationHistory(context.taskId, agentId, context.iteration);
|
|
199
|
+
const historyText = formatIterationHistory(history, context.iteration);
|
|
200
|
+
sections.push(historyText);
|
|
201
|
+
sections.push('');
|
|
202
|
+
} catch (err) {
|
|
203
|
+
console.warn(`[agent-prompt-builder] Failed to load iteration history:`, err);
|
|
204
|
+
// Continue without history
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
// 4. Agent definition content (from markdown file)
|
|
208
|
+
sections.push('## Agent Definition');
|
|
209
|
+
sections.push('');
|
|
210
|
+
sections.push(definition.content);
|
|
211
|
+
sections.push('');
|
|
212
|
+
// 5. CFN Loop protocol (if agent supports it AND task context includes taskId)
|
|
213
|
+
if (context.taskId && hasCFNLoopProtocol(definition)) {
|
|
214
|
+
sections.push(buildCFNLoopProtocol(context.taskId, agentId));
|
|
215
|
+
sections.push('');
|
|
216
|
+
}
|
|
217
|
+
// 6. Environment context
|
|
218
|
+
const envContext = buildEnvironmentContext(context);
|
|
219
|
+
if (envContext) {
|
|
220
|
+
sections.push(envContext);
|
|
221
|
+
sections.push('');
|
|
222
|
+
}
|
|
223
|
+
// 7. Execution instructions
|
|
224
|
+
sections.push('## Execution Instructions');
|
|
225
|
+
sections.push('');
|
|
226
|
+
sections.push('1. Read and understand the task requirements');
|
|
227
|
+
if (context.iteration && context.iteration > 1) {
|
|
228
|
+
sections.push('2. Review iteration history and feedback from validators');
|
|
229
|
+
sections.push('3. Address specific feedback points from previous iteration');
|
|
230
|
+
sections.push('4. Execute your core responsibilities as defined above');
|
|
231
|
+
} else {
|
|
232
|
+
sections.push('2. Execute your core responsibilities as defined above');
|
|
233
|
+
sections.push('3. Follow any protocol steps (CFN Loop, validation hooks, etc.)');
|
|
234
|
+
}
|
|
235
|
+
sections.push('4. Provide clear, concise output');
|
|
236
|
+
sections.push('5. Report confidence score if applicable');
|
|
237
|
+
sections.push('');
|
|
238
|
+
// 8. Tool reminder
|
|
239
|
+
if (definition.tools && definition.tools.length > 0) {
|
|
240
|
+
sections.push('## Available Tools');
|
|
241
|
+
sections.push('');
|
|
242
|
+
sections.push(`You have access to: ${definition.tools.join(', ')}`);
|
|
243
|
+
sections.push('');
|
|
244
|
+
}
|
|
245
|
+
return sections.join('\n');
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* Extract agent ID from context
|
|
249
|
+
* If agentId is explicitly provided in context, use it; otherwise generate from name + iteration
|
|
250
|
+
*/ export function getAgentId(definition, context) {
|
|
251
|
+
if (context.agentId) {
|
|
252
|
+
return context.agentId;
|
|
253
|
+
}
|
|
254
|
+
return `${definition.name}-${context.iteration || 1}`;
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* Build system prompt for agent (optional, for structured agent behavior)
|
|
258
|
+
*/ export function buildSystemPrompt(definition) {
|
|
259
|
+
return `You are ${definition.name}, a specialized AI agent.
|
|
260
|
+
|
|
261
|
+
Type: ${definition.type || 'specialist'}
|
|
262
|
+
Model: ${definition.model}
|
|
263
|
+
Tools: ${definition.tools.join(', ')}
|
|
264
|
+
|
|
265
|
+
Follow your agent definition exactly and complete assigned tasks with high quality.`;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
//# sourceMappingURL=agent-prompt-builder.js.map
|