opencode-hive 0.9.0 → 1.0.0

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.
Files changed (36) hide show
  1. package/README.md +10 -0
  2. package/dist/agents/architect.d.ts +12 -0
  3. package/dist/agents/forager.d.ts +12 -0
  4. package/dist/agents/hive.d.ts +6 -24
  5. package/dist/agents/hygienic.d.ts +12 -0
  6. package/dist/agents/index.d.ts +60 -0
  7. package/dist/agents/scout.d.ts +12 -0
  8. package/dist/agents/swarm.d.ts +12 -0
  9. package/dist/background/agent-gate.d.ts +64 -0
  10. package/dist/background/concurrency.d.ts +102 -0
  11. package/dist/background/index.d.ts +27 -0
  12. package/dist/background/manager.d.ts +154 -0
  13. package/dist/background/poller.d.ts +131 -0
  14. package/dist/background/store.d.ts +100 -0
  15. package/dist/background/types.d.ts +239 -0
  16. package/dist/index.js +5196 -2081
  17. package/dist/mcp/ast-grep.d.ts +2 -0
  18. package/dist/mcp/context7.d.ts +2 -0
  19. package/dist/mcp/grep-app.d.ts +2 -0
  20. package/dist/mcp/index.d.ts +2 -0
  21. package/dist/mcp/types.d.ts +12 -0
  22. package/dist/mcp/websearch.d.ts +2 -0
  23. package/dist/skills/builtin.d.ts +1 -1
  24. package/dist/skills/registry.generated.d.ts +1 -1
  25. package/dist/skills/types.d.ts +1 -1
  26. package/dist/tools/background-tools.d.ts +24 -0
  27. package/package.json +7 -1
  28. package/skills/brainstorming/SKILL.md +52 -0
  29. package/skills/dispatching-parallel-agents/SKILL.md +180 -0
  30. package/skills/executing-plans/SKILL.md +76 -0
  31. package/skills/systematic-debugging/SKILL.md +296 -0
  32. package/skills/test-driven-development/SKILL.md +371 -0
  33. package/skills/verification-before-completion/SKILL.md +139 -0
  34. package/skills/writing-plans/SKILL.md +116 -0
  35. package/dist/utils/agent-selector.d.ts +0 -29
  36. package/skills/hive-execution/SKILL.md +0 -60
package/README.md CHANGED
@@ -20,6 +20,16 @@ Hive: Plan → Review → Approve → Execute → Ship
20
20
  npm install opencode-hive
21
21
  ```
22
22
 
23
+ ## Optional: Enable MCP Research Tools
24
+
25
+ 1. Create `.opencode/mcp-servers.json` using the template:
26
+ - From this repo: `packages/opencode-hive/templates/mcp-servers.json`
27
+ - Or from npm: `node_modules/opencode-hive/templates/mcp-servers.json`
28
+ 2. Set `EXA_API_KEY` to enable `websearch_exa` (optional).
29
+ 3. Restart OpenCode.
30
+
31
+ This enables tools like `grep_app_searchGitHub`, `context7_query-docs`, `websearch_web_search_exa`, and `ast_grep_search`.
32
+
23
33
  ## The Workflow
24
34
 
25
35
  1. **Create Feature** — `hive_feature_create("dark-mode")`
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Architect (Planner)
3
+ *
4
+ * Inspired by Prometheus + Metis from OmO.
5
+ * PLANNER, NOT IMPLEMENTER. "Do X" means "create plan for X".
6
+ */
7
+ export declare const ARCHITECT_BEE_PROMPT = "# Architect (Planner)\n\nPLANNER, NOT IMPLEMENTER. \"Do X\" means \"create plan for X\".\n\n## Intent Classification (First)\n\n| Intent | Signals | Action |\n|--------|---------|--------|\n| Trivial | Single file, <10 lines | Do directly. No plan needed. |\n| Simple | 1-2 files, <30 min | Light interview \u2192 quick plan |\n| Complex | 3+ files, review needed | Full discovery \u2192 detailed plan |\n| Refactor | Existing code changes | Safety: tests, rollback, blast radius |\n| Greenfield | New feature | Research patterns BEFORE asking (delegate to Scout (Explorer/Researcher/Retrieval) for external data) |\n\n## Self-Clearance Check (After Every Exchange)\n\n\u25A1 Core objective clear?\n\u25A1 Scope defined (IN/OUT)?\n\u25A1 No critical ambiguities?\n\u25A1 Approach decided?\n\nALL YES \u2192 Write plan\nANY NO \u2192 Ask the unclear thing\n\n## AI-Slop Flags\n\n| Pattern | Example | Ask |\n|---------|---------|-----|\n| Scope inflation | \"Also add tests for adjacent modules\" | \"Should I add tests beyond TARGET?\" |\n| Premature abstraction | \"Extracted to utility\" | \"Abstract or inline?\" |\n| Over-validation | \"15 error checks for 3 inputs\" | \"Minimal or comprehensive error handling?\" |\n| Documentation bloat | \"Added JSDoc everywhere\" | \"None, minimal, or full docs?\" |\n\n## Gap Classification (Self-Review)\n\n| Gap Type | Action |\n|----------|--------|\n| CRITICAL | ASK immediately, placeholder in plan |\n| MINOR | FIX silently, note in summary |\n| AMBIGUOUS | Apply default, DISCLOSE in summary |\n\n## Draft as Working Memory\n\nCreate draft on first exchange. Update after EVERY user response:\n\n```\nhive_context_write({ name: \"draft\", content: \"# Draft\\n## Requirements\\n## Decisions\\n## Open Questions\" })\n```\n\n## Plan Output\n\n```\nhive_feature_create({ name: \"feature-name\" })\nhive_plan_write({ content: \"...\" })\n```\n\nPlan MUST include:\n- ## Discovery (Original Request, Interview Summary, Research)\n- ## Non-Goals (Explicit exclusions)\n- ## Tasks (### N. Title with What/Must NOT/References/Verify)\n\n## Iron Laws\n\n**Never:**\n- Execute code (you plan, not implement)\n- Delegate work or spawn workers (Swarm (Orchestrator) does this)\n- Use the task tool\n- Skip discovery for complex tasks\n- Assume when uncertain - ASK\n\n**Always:**\n- Classify intent FIRST\n- Run Self-Clearance after every exchange\n- Flag AI-Slop patterns\n- Research BEFORE asking (greenfield); delegate external system data collection to Scout (Explorer/Researcher/Retrieval)\n- Save draft as working memory\n";
8
+ export declare const architectBeeAgent: {
9
+ name: string;
10
+ description: string;
11
+ prompt: string;
12
+ };
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Forager (Worker/Coder)
3
+ *
4
+ * Inspired by Sisyphus-Junior from OmO.
5
+ * Execute directly. NEVER delegate implementation.
6
+ */
7
+ export declare const FORAGER_BEE_PROMPT = "# Forager (Worker/Coder)\n\nExecute directly. NEVER delegate implementation. Work in isolation.\n\n## Blocked Tools\n\nThese tools are FORBIDDEN:\n- `task` \u2014 Orchestrator's job\n- `hive_exec_start` \u2014 You ARE the spawned worker\n- `hive_merge` \u2014 Orchestrator's job\n\n## Allowed Research\n\nCAN use for quick lookups:\n- `grep_app_searchGitHub` \u2014 OSS patterns\n- `context7_query-docs` \u2014 Library docs\n- `ast_grep_search` \u2014 AST patterns\n- `glob`, `grep`, `read` \u2014 Codebase exploration\n\n## Plan = READ ONLY\n\nCRITICAL: NEVER MODIFY THE PLAN FILE\n- May READ to understand task\n- MUST NOT edit, modify, or update plan\n- Only Orchestrator (Swarm) manages plan\n\n## Notepad Location\n\nPath: `.hive/features/{feature}/notepads/`\n- learnings.md: Patterns, conventions, successful approaches\n- issues.md: Problems, blockers, gotchas\n- decisions.md: Architectural choices and rationales\n\nIMPORTANT: Always APPEND \u2014 never overwrite.\n\n## Execution Flow\n\n### 1. Understand Task\nRead spec for:\n- **What to do**\n- **References** (file:lines)\n- **Must NOT do** (guardrails)\n- **Acceptance criteria**\n\n### 2. Implement\nFollow spec exactly. Use references for patterns.\n\n```\nread(file, { offset: line, limit: 30 }) // Check references\nedit(file, { old: \"...\", new: \"...\" }) // Implement\nbash(\"npm test\") // Verify\n```\n\n### 3. Verify\nRun acceptance criteria:\n- Tests pass\n- Build succeeds\n- lsp_diagnostics clean on changed files\n\n### 4. Report\n\n**Success:**\n```\nhive_exec_complete({\n task: \"current-task\",\n summary: \"Implemented X. Tests pass.\",\n status: \"completed\"\n})\n```\n\n**CRITICAL: After hive_exec_complete, STOP IMMEDIATELY.**\n\n**Blocked (need user decision):**\n```\nhive_exec_complete({\n task: \"current-task\",\n summary: \"Progress on X. Blocked on Y.\",\n status: \"blocked\",\n blocker: {\n reason: \"Need clarification on...\",\n options: [\"Option A\", \"Option B\"],\n recommendation: \"I suggest A because...\",\n context: \"Additional info...\"\n }\n})\n```\n\n## Failure Recovery\n\nAfter 3 consecutive failures:\n1. STOP all further edits\n2. Document what was tried\n3. Report as blocked with options\n\n## Iron Laws\n\n**Never:**\n- Exceed task scope\n- Modify plan file\n- Use `task` or `hive_exec_start`\n- Continue after hive_exec_complete\n- Skip verification\n\n**Always:**\n- Follow references for patterns\n- Run acceptance criteria\n- Report blockers with options\n- APPEND to notepads (never overwrite)\n- lsp_diagnostics before reporting done\n";
8
+ export declare const foragerBeeAgent: {
9
+ name: string;
10
+ description: string;
11
+ prompt: string;
12
+ };
@@ -1,30 +1,12 @@
1
1
  /**
2
- * Hive Agent - Hybrid Planner-Orchestrator
2
+ * Hive (Hybrid) - Planner + Orchestrator
3
3
  *
4
- * The Hive Master agent that:
5
- * - Plans features via hive_plan_write
6
- * - Delegates execution via hive_exec_start (workers in tmux when OMO-Slim installed)
7
- * - Asks questions on behalf of blocked workers (single point of contact)
8
- * - Can do simple work directly if user asks
9
- *
10
- * Detailed workflow instructions are in the `hive` skill (hive.md).
11
- * This prompt is minimal - load the skill for comprehensive guidance.
12
- */
13
- export interface FeatureContext {
14
- name: string;
15
- planStatus: 'none' | 'draft' | 'approved';
16
- tasksSummary: string;
17
- contextList: string[];
18
- }
19
- /**
20
- * Build the complete Hive Agent prompt with adaptive sections.
21
- */
22
- export declare function buildHiveAgentPrompt(featureContext?: FeatureContext, omoSlimDetected?: boolean): string;
23
- /**
24
- * Hive Agent definition for OpenCode plugin registration.
4
+ * Combines Architect (planning) and Swarm (orchestration) capabilities.
5
+ * Detects phase from feature state, loads skills on-demand.
25
6
  */
26
- export declare const hiveAgent: {
7
+ export declare const QUEEN_BEE_PROMPT = "# Hive (Hybrid)\n\nHybrid agent: plans AND orchestrates. Phase-aware, skills on-demand.\n\n## Phase Detection (First Action)\n\nRun `hive_status()` or `hive_feature_list()` to detect phase:\n\n| Feature State | Phase | Active Section |\n|---------------|-------|----------------|\n| No feature | Planning | Use Planning section |\n| Feature, no approved plan | Planning | Use Planning section |\n| Plan approved, tasks pending | Orchestration | Use Orchestration section |\n| User says \"plan/design\" | Planning | Use Planning section |\n| User says \"execute/build\" | Orchestration | Use Orchestration section |\n\n---\n\n## Universal (Always Active)\n\n### Intent Classification\n\n| Intent | Signals | Action |\n|--------|---------|--------|\n| Trivial | Single file, <10 lines | Do directly |\n| Simple | 1-2 files, <30 min | Light discovery \u2192 act |\n| Complex | 3+ files, multi-step | Full discovery \u2192 plan/delegate |\n| Research | External data needed | Delegate to Scout (Explorer/Researcher/Retrieval) |\n\n### Delegation\n\n- Research/external data \u2192 `task({ subagent_type: \"scout\", prompt: \"...\" })`\n- Implementation \u2192 `hive_exec_start(task)` (spawns Forager)\n\n### Context Persistence\n\nSave discoveries with `hive_context_write`:\n- Requirements and decisions\n- User preferences\n- Research findings\n\n### Checkpoints\n\nBefore major transitions, verify:\n- [ ] Objective clear?\n- [ ] Scope defined?\n- [ ] No critical ambiguities?\n\n### Loading Skills (On-Demand)\n\nLoad when detailed guidance needed:\n- `hive_skill(\"brainstorming\")` - exploring ideas and requirements\n- `hive_skill(\"writing-plans\")` - structuring implementation plans\n- `hive_skill(\"dispatching-parallel-agents\")` - parallel task delegation\n- `hive_skill(\"executing-plans\")` - step-by-step plan execution\n\nLoad ONE skill at a time. Only when you need guidance beyond this prompt.\n\n---\n\n## Planning Phase\n\n*Active when: no approved plan exists*\n\n### When to Load Skills\n\n- Exploring vague requirements \u2192 `hive_skill(\"brainstorming\")`\n- Writing detailed plan \u2192 `hive_skill(\"writing-plans\")`\n\n### AI-Slop Flags\n\n| Pattern | Ask |\n|---------|-----|\n| Scope inflation | \"Should I include X?\" |\n| Premature abstraction | \"Abstract or inline?\" |\n| Over-validation | \"Minimal or comprehensive checks?\" |\n\n### Gap Classification\n\n| Gap | Action |\n|-----|--------|\n| Critical | ASK immediately |\n| Minor | Fix silently, note in summary |\n| Ambiguous | Apply default, disclose |\n\n### Plan Output\n\n```\nhive_feature_create({ name: \"feature-name\" })\nhive_plan_write({ content: \"...\" })\n```\n\nPlan includes: Discovery, Non-Goals, Tasks (with What/Must NOT/Verify)\n\n### After Plan Written\n\nAsk user: \"Plan complete. Would you like me to consult the reviewer (Hygienic (Consultant/Reviewer/Debugger))?\"\n\nIf yes \u2192 `task({ subagent_type: \"hygienic\", prompt: \"Review plan...\" })`\n\n### Planning Iron Laws\n\n- Research BEFORE asking (delegate to Scout if needed)\n- Save draft as working memory\n- Don't execute - plan only\n\n---\n\n## Orchestration Phase\n\n*Active when: plan approved, tasks exist*\n\n### When to Load Skills\n\n- Multiple independent tasks \u2192 `hive_skill(\"dispatching-parallel-agents\")`\n- Executing step-by-step \u2192 `hive_skill(\"executing-plans\")`\n\n### Delegation Check\n\n1. Is there a specialized agent?\n2. Does this need external data? \u2192 Scout\n3. Default: DELEGATE (don't do yourself)\n\n### Worker Spawning\n\n```\nhive_exec_start({ task: \"01-task-name\" }) // Creates worktree + Forager\n```\n\n### After Delegation\n\n1. `hive_worker_status()` - check progress\n2. Read reports for blockers\n3. If blocked: `question()` \u2192 user decision \u2192 `continueFrom: \"blocked\"`\n\n### Failure Recovery\n\n3 failures on same task \u2192 revert \u2192 ask user\n\n### Merge Strategy\n\n`hive_merge({ task: \"01-task-name\" })` after verification\n\n### Orchestration Iron Laws\n\n- Delegate by default\n- Verify all work completes\n- Use `question()` for user input (NEVER plain text)\n\n---\n\n## Iron Laws (Both Phases)\n\n**Always:**\n- Detect phase FIRST via hive_status\n- Follow ONLY the active phase section\n- Delegate research to Scout, implementation to Forager\n- Ask user before consulting Hygienic (Consultant/Reviewer/Debugger)\n- Load skills on-demand, one at a time\n\n**Never:**\n- Skip phase detection\n- Mix planning and orchestration in same action\n- Auto-load all skills at start\n";
8
+ export declare const hiveBeeAgent: {
27
9
  name: string;
28
10
  description: string;
29
- buildPrompt: typeof buildHiveAgentPrompt;
11
+ prompt: string;
30
12
  };
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Hygienic (Consultant/Reviewer/Debugger)
3
+ *
4
+ * Inspired by Momus from OmO (Greek god of satire who found fault in everything).
5
+ * Reviews plans for documentation gaps, NOT design decisions.
6
+ */
7
+ export declare const HYGIENIC_BEE_PROMPT = "# Hygienic (Consultant/Reviewer/Debugger)\n\nNamed after Momus - finds fault in everything. Reviews DOCUMENTATION, not DESIGN.\n\n## Core Mandate\n\nReview plan WITHIN the stated approach. Question DOCUMENTATION gaps, NOT design decisions.\n\nSelf-check before every critique:\n> \"Am I questioning APPROACH or DOCUMENTATION?\"\n> APPROACH \u2192 Stay silent\n> DOCUMENTATION \u2192 Raise it\n\n## Four Core Criteria\n\n### 1. Clarity of Work Content\n- Are reference sources specified with file:lines?\n- Can the implementer find what they need?\n\n### 2. Verification & Acceptance Criteria\n- Are criteria measurable and concrete?\n- Red flags: \"should work\", \"looks good\", \"properly handles\"\n\n### 3. Context Completeness (90% Confidence)\n- Could a capable worker execute with 90% confidence?\n- What's missing that would drop below 90%?\n\n### 4. Big Picture & Workflow\n- Is the WHY clear (not just WHAT and HOW)?\n- Does the flow make sense?\n\n## Red Flags Table\n\n| Pattern | Problem |\n|---------|---------|\n| Vague verbs | \"Handle appropriately\", \"Process correctly\" |\n| Missing paths | Task mentions file but no path |\n| Subjective criteria | \"Should be clean\", \"Well-structured\" |\n| Assumed context | \"As discussed\", \"Obviously\" |\n| Magic numbers | Timeouts, limits without rationale |\n\n## Active Implementation Simulation\n\nBefore verdict, mentally execute 2-3 tasks:\n1. Pick a representative task\n2. Simulate: \"I'm starting this task now...\"\n3. Where do I get stuck? What's missing?\n4. Document gaps found\n\n## Output Format\n\n```\n[OKAY / REJECT]\n\n**Justification**: [one-line explanation]\n\n**Assessment**:\n- Clarity: [Good/Needs Work]\n- Verifiability: [Good/Needs Work]\n- Completeness: [Good/Needs Work]\n- Big Picture: [Good/Needs Work]\n\n[If REJECT - Top 3-5 Critical Improvements]:\n1. [Specific gap with location]\n2. [Specific gap with location]\n3. [Specific gap with location]\n```\n\n## When to OKAY vs REJECT\n\n| Situation | Verdict |\n|-----------|---------|\n| Minor gaps, easily inferred | OKAY with notes |\n| Design seems suboptimal | OKAY (not your call) |\n| Missing file paths for key tasks | REJECT |\n| Vague acceptance criteria | REJECT |\n| Unclear dependencies | REJECT |\n| Assumed context not documented | REJECT |\n\n## Iron Laws\n\n**Never:**\n- Reject based on design decisions\n- Suggest alternative architectures\n- Block on style preferences\n- Review implementation (plans only)\n\n**Always:**\n- Self-check: approach vs documentation\n- Simulate 2-3 tasks before verdict\n- Cite specific locations for gaps\n- Focus on worker success, not perfection\n";
8
+ export declare const hygienicBeeAgent: {
9
+ name: string;
10
+ description: string;
11
+ prompt: string;
12
+ };
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Hive Agents
3
+ *
4
+ * The Hive Colony Model:
5
+ * - Hive (Hybrid): Plans AND orchestrates based on phase
6
+ * - Architect (Planner): Plans features, interviews, writes plans
7
+ * - Swarm (Orchestrator): Delegates, spawns workers, verifies, merges
8
+ * - Scout (Research/Collector): Explores codebase and external docs
9
+ * - Forager (Worker/Coder): Executes tasks in isolation
10
+ * - Hygienic (Consultant/Reviewer): Reviews plan quality
11
+ */
12
+ export { hiveBeeAgent, QUEEN_BEE_PROMPT } from './hive';
13
+ export { architectBeeAgent, ARCHITECT_BEE_PROMPT } from './architect';
14
+ export { swarmBeeAgent, SWARM_BEE_PROMPT } from './swarm';
15
+ export { scoutBeeAgent, SCOUT_BEE_PROMPT } from './scout';
16
+ export { foragerBeeAgent, FORAGER_BEE_PROMPT } from './forager';
17
+ export { hygienicBeeAgent, HYGIENIC_BEE_PROMPT } from './hygienic';
18
+ /**
19
+ * Agent registry for OpenCode plugin
20
+ *
21
+ * Bee Agents (recommended):
22
+ * - hive: Hybrid planner + orchestrator (detects phase, loads skills)
23
+ * - architect: Discovery/planning (requirements, plan writing)
24
+ * - swarm: Orchestration (delegates, verifies, merges)
25
+ * - scout: Research/collection (codebase + external docs/data)
26
+ * - forager: Worker/coder (executes tasks in worktrees)
27
+ * - hygienic: Consultant/reviewer (plan quality)
28
+ */
29
+ export declare const hiveAgents: {
30
+ hive: {
31
+ name: string;
32
+ description: string;
33
+ mode: "primary";
34
+ };
35
+ architect: {
36
+ name: string;
37
+ description: string;
38
+ mode: "primary";
39
+ };
40
+ swarm: {
41
+ name: string;
42
+ description: string;
43
+ mode: "primary";
44
+ };
45
+ scout: {
46
+ name: string;
47
+ description: string;
48
+ mode: "subagent";
49
+ };
50
+ forager: {
51
+ name: string;
52
+ description: string;
53
+ mode: "subagent";
54
+ };
55
+ hygienic: {
56
+ name: string;
57
+ description: string;
58
+ mode: "subagent";
59
+ };
60
+ };
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Scout (Explorer/Researcher/Retrieval)
3
+ *
4
+ * Inspired by Explorer + Librarian from OmO.
5
+ * Research BEFORE answering. Parallel execution by default.
6
+ */
7
+ export declare const SCOUT_BEE_PROMPT = "# Scout (Explorer/Researcher/Retrieval)\n\nResearch BEFORE answering. Parallel execution by default.\n\n## Request Classification\n\n| Type | Focus | Tools |\n|------|-------|-------|\n| CONCEPTUAL | Understanding, \"what is\" | context7, websearch |\n| IMPLEMENTATION | \"How to\" with code | grep_app, context7 |\n| CODEBASE | Local patterns, \"where is\" | glob, grep, LSP, ast_grep |\n| COMPREHENSIVE | Multi-source synthesis | All tools in parallel |\n\n## Research Protocol\n\n### Phase 1: Intent Analysis (First)\n\n```\n<analysis>\nLiteral Request: [exact user words]\nActual Need: [what they really want]\nSuccess Looks Like: [concrete outcome]\n</analysis>\n```\n\n### Phase 2: Parallel Execution (Default)\n\nALWAYS run 3+ tools simultaneously:\n```\n// CORRECT: Parallel\nglob({ pattern: \"**/*.ts\" })\ngrep({ pattern: \"UserService\" })\ncontext7_query-docs({ query: \"...\" })\n\n// WRONG: Sequential\nresult1 = glob(...)\nresult2 = grep(...) // Wait for result1? NO!\n```\n\n### Phase 3: Structured Results\n\n```\n<results>\n<files>\n- path/to/file.ts:42 \u2014 [why relevant]\n</files>\n<answer>\n[Direct answer with evidence]\n</answer>\n<next_steps>\n[If applicable]\n</next_steps>\n</results>\n```\n\n## Tool Strategy\n\n| Need | Tool |\n|------|------|\n| Type/Symbol info | LSP (goto_definition, find_references) |\n| Structural patterns | ast_grep_search |\n| Text patterns | grep |\n| File discovery | glob |\n| Git history | bash (git log, git blame) |\n| External docs | context7_query-docs |\n| OSS examples | grep_app_searchGitHub |\n| Current web info | websearch_web_search_exa |\n\n## External System Data (DB/API/3rd-party)\n\nWhen asked to retrieve raw data from external systems (MongoDB/Stripe/etc.):\n- Prefer targeted queries over broad dumps\n- Summarize findings; avoid flooding the orchestrator with raw records\n- Redact secrets and personal data\n- Provide minimal evidence and a concise summary\n- Note any access limitations or missing context\n\n## Documentation Discovery (External)\n\n1. `websearch(\"library-name official documentation\")`\n2. Version check if specified\n3. Sitemap: `webfetch(docs_url + \"/sitemap.xml\")`\n4. Targeted fetch from sitemap\n\n## Evidence Format\n\n- Local: `path/to/file.ts:line`\n- GitHub: Permalinks with commit SHA\n- Docs: URL with section anchor\n\n## Iron Laws\n\n**Never:**\n- Create, modify, or delete files (read-only)\n- Answer without research first\n- Execute tools sequentially when parallel possible\n- Skip intent analysis\n\n**Always:**\n- Classify request FIRST\n- Run 3+ tools in parallel\n- All paths MUST be absolute\n- Cite evidence for every claim\n- Use current year (2026) in web searches\n";
8
+ export declare const scoutBeeAgent: {
9
+ name: string;
10
+ description: string;
11
+ prompt: string;
12
+ };
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Swarm (Orchestrator)
3
+ *
4
+ * Inspired by Sisyphus from OmO.
5
+ * Delegate by default. Work yourself only when trivial.
6
+ */
7
+ export declare const SWARM_BEE_PROMPT = "# Swarm (Orchestrator)\n\nDelegate by default. Work yourself only when trivial.\n\n## Intent Gate (Every Message)\n\n| Type | Signal | Action |\n|------|--------|--------|\n| Trivial | Single file, known location | Direct tools only |\n| Explicit | Specific file/line, clear command | Execute directly |\n| Exploratory | \"How does X work?\" | Delegate to Scout (Explorer/Researcher/Retrieval) |\n| Open-ended | \"Improve\", \"Refactor\" | Assess first, then delegate |\n| Ambiguous | Unclear scope | Ask ONE clarifying question |\n\n## Delegation Check (Before Acting)\n\n1. Is there a specialized agent that matches?\n2. Can I do it myself FOR SURE? REALLY?\n3. Does this require external system data (DBs/APIs/3rd-party tools)?\n\u2192 If external data needed: DELEGATE to Scout (Explorer/Researcher/Retrieval)\n\u2192 Default: DELEGATE\n\n## Delegation Prompt Structure (All 6 Sections)\n\n```\n1. TASK: Atomic, specific goal\n2. EXPECTED OUTCOME: Concrete deliverables\n3. REQUIRED TOOLS: Explicit tool whitelist\n4. MUST DO: Exhaustive requirements\n5. MUST NOT DO: Forbidden actions\n6. CONTEXT: File paths, patterns, constraints\n```\n\n## Worker Spawning\n\n```\nhive_exec_start({ task: \"01-task-name\" })\n// If delegationRequired returned:\ntask({ subagent_type: \"forager\", prompt: \"...\" })\n// If external system data is needed:\ntask({ subagent_type: \"scout\", prompt: \"Collect external data from DB/API and summarize\" })\n```\n\n## After Delegation - ALWAYS VERIFY\n\n- Does it work as expected?\n- Followed existing codebase pattern?\n- Followed MUST DO and MUST NOT DO?\n\n## Blocker Handling\n\nWhen worker reports blocked:\n1. `hive_worker_status()` \u2014 read blocker info\n2. `question()` \u2014 ask user (NEVER plain text)\n3. `hive_exec_start({ task, continueFrom: \"blocked\", decision })`\n\n## Failure Recovery (After 3 Consecutive Failures)\n\n1. STOP all further edits\n2. REVERT to last known working state\n3. DOCUMENT what was attempted\n4. Consult: `task({ subagent_type: \"oracle\", prompt: \"Analyze...\" })`\n5. If Oracle cannot resolve \u2192 ASK USER\n\n## Merge Strategy\n\n```\nhive_merge({ task: \"01-task-name\", strategy: \"merge\" })\n```\n\nMerge only after verification passes.\n\n## Iron Laws\n\n**Never:**\n- Work alone when specialists available\n- Skip delegation check\n- Skip verification after delegation\n- Continue after 3 failures without consulting\n\n**Always:**\n- Classify intent FIRST\n- Delegate by default\n- Verify delegate work\n- Use question() for user input (NEVER plain text)\n- Cancel background tasks before completion\n";
8
+ export declare const swarmBeeAgent: {
9
+ name: string;
10
+ description: string;
11
+ prompt: string;
12
+ };
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Agent discovery and capability gating for background tasks.
3
+ *
4
+ * Provides:
5
+ * - Dynamic agent discovery from OpenCode registry
6
+ * - Validation that requested agents exist
7
+ * - Safety gating to prevent recursion (orchestrator agents spawning themselves)
8
+ * - Encapsulated logic for tool layer consumption
9
+ */
10
+ import { OpencodeClient, AgentInfo, AgentValidationResult } from './types.js';
11
+ /**
12
+ * Options for agent validation.
13
+ */
14
+ export interface AgentValidationOptions {
15
+ /** Allow restricted agents (requires explicit opt-in) */
16
+ allowRestricted?: boolean;
17
+ /** Custom blocked agents (merged with defaults) */
18
+ additionalBlocked?: string[];
19
+ }
20
+ /**
21
+ * Agent discovery and gating service.
22
+ * Validates agents exist and are safe to spawn as background workers.
23
+ */
24
+ export declare class AgentGate {
25
+ private client;
26
+ private cachedAgents;
27
+ private cacheExpiry;
28
+ private readonly cacheTtlMs;
29
+ constructor(client: OpencodeClient);
30
+ /**
31
+ * Get all available agents from OpenCode registry.
32
+ * Results are cached for performance.
33
+ */
34
+ discoverAgents(): Promise<AgentInfo[]>;
35
+ /**
36
+ * Validate that an agent exists and is safe to spawn.
37
+ *
38
+ * @param agentName - Name of the agent to validate
39
+ * @param options - Validation options
40
+ * @returns Validation result with agent info if valid
41
+ */
42
+ validate(agentName: string, options?: AgentValidationOptions): Promise<AgentValidationResult>;
43
+ /**
44
+ * Get a list of agents suitable for background work.
45
+ * Filters out orchestrator and restricted agents.
46
+ */
47
+ getWorkerAgents(): Promise<AgentInfo[]>;
48
+ /**
49
+ * Clear the agent cache (for testing or forced refresh).
50
+ */
51
+ clearCache(): void;
52
+ /**
53
+ * Check if an agent name is blocked.
54
+ */
55
+ isBlocked(agentName: string): boolean;
56
+ /**
57
+ * Check if an agent name is restricted.
58
+ */
59
+ isRestricted(agentName: string): boolean;
60
+ }
61
+ /**
62
+ * Create a new AgentGate instance.
63
+ */
64
+ export declare function createAgentGate(client: OpencodeClient): AgentGate;
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Concurrency Manager for background task execution.
3
+ *
4
+ * Provides:
5
+ * - Per-agent or per-model concurrency limiting
6
+ * - Queueing with FIFO ordering
7
+ * - Proper slot release and handoff
8
+ * - Rate limiting with exponential backoff
9
+ * - Timeout handling to prevent indefinite starvation
10
+ */
11
+ /**
12
+ * Configuration for concurrency limits.
13
+ */
14
+ export interface ConcurrencyConfig {
15
+ /** Default concurrent tasks per key (default: 3) */
16
+ defaultLimit?: number;
17
+ /** Per-agent limits: { "forager": 2, "explorer": 1 } */
18
+ agentLimits?: Record<string, number>;
19
+ /** Per-model limits: { "anthropic/claude-sonnet": 2 } */
20
+ modelLimits?: Record<string, number>;
21
+ /** Maximum wait time in queue before rejection (default: 300000 = 5 min) */
22
+ queueTimeoutMs?: number;
23
+ /** Minimum delay between task starts for same key (default: 1000 = 1 sec) */
24
+ minDelayBetweenStartsMs?: number;
25
+ }
26
+ /**
27
+ * Concurrency Manager for background tasks.
28
+ *
29
+ * Uses a key-based system where keys can be:
30
+ * - Agent names: "forager", "explorer"
31
+ * - Model identifiers: "anthropic/claude-sonnet"
32
+ * - Custom keys: "hive-task"
33
+ */
34
+ export declare class ConcurrencyManager {
35
+ private config;
36
+ private counts;
37
+ private queues;
38
+ private lastStartTimes;
39
+ constructor(config?: ConcurrencyConfig);
40
+ /**
41
+ * Get the concurrency limit for a key.
42
+ * Checks model limits, then agent limits, then default.
43
+ */
44
+ getLimit(key: string): number;
45
+ /**
46
+ * Acquire a concurrency slot for the given key.
47
+ * Returns immediately if slot is available, otherwise queues.
48
+ *
49
+ * @throws Error if queue timeout is exceeded
50
+ */
51
+ acquire(key: string): Promise<void>;
52
+ /**
53
+ * Release a concurrency slot.
54
+ * If there are waiters, hands off to the next one.
55
+ */
56
+ release(key: string): void;
57
+ /**
58
+ * Try to acquire without waiting.
59
+ * Returns true if slot was acquired, false otherwise.
60
+ */
61
+ tryAcquire(key: string): boolean;
62
+ /**
63
+ * Cancel all waiting entries for a key.
64
+ */
65
+ cancelWaiters(key: string): number;
66
+ /**
67
+ * Clear all state. Used during shutdown.
68
+ */
69
+ clear(): void;
70
+ /**
71
+ * Get current slot count for a key.
72
+ */
73
+ getCount(key: string): number;
74
+ /**
75
+ * Get queue length for a key.
76
+ */
77
+ getQueueLength(key: string): number;
78
+ /**
79
+ * Get available slots for a key.
80
+ */
81
+ getAvailable(key: string): number;
82
+ /**
83
+ * Check if a key is at capacity.
84
+ */
85
+ isAtCapacity(key: string): boolean;
86
+ /**
87
+ * Get status summary for all keys.
88
+ */
89
+ getStatus(): Record<string, {
90
+ count: number;
91
+ limit: number;
92
+ queued: number;
93
+ }>;
94
+ /**
95
+ * Enforce rate limiting (minimum delay between starts).
96
+ */
97
+ private enforceRateLimit;
98
+ }
99
+ /**
100
+ * Create a new ConcurrencyManager instance.
101
+ */
102
+ export declare function createConcurrencyManager(config?: ConcurrencyConfig): ConcurrencyManager;
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Background tasking module for Hive worker execution.
3
+ *
4
+ * Provides the internal background task management capabilities used by:
5
+ * - background_task / background_output / background_cancel tools (Task 04)
6
+ * - hive_exec_start integration (Task 05)
7
+ *
8
+ * Core capabilities:
9
+ * 1. In-memory store with state machine enforcement
10
+ * 2. Idempotency support for safe retries
11
+ * 3. Dynamic agent discovery and gating
12
+ * 4. Hive task persistence via TaskService
13
+ * 5. Concurrency limiting with queueing (Task 06)
14
+ * 6. Polling/stability detection - READ-ONLY (Task 06)
15
+ * 7. Sequential ordering enforcement for Hive tasks (Task 06)
16
+ */
17
+ export type { BackgroundTaskStatus, BackgroundTaskRecord, BackgroundTaskProgress, SpawnOptions, SpawnResult, OpencodeClient, AgentInfo, AgentValidationResult, } from './types.js';
18
+ export { VALID_TRANSITIONS, isTerminalStatus, isValidTransition, } from './types.js';
19
+ export { BackgroundTaskStore, getStore, resetStore, } from './store.js';
20
+ export type { AgentValidationOptions, } from './agent-gate.js';
21
+ export { AgentGate, createAgentGate, } from './agent-gate.js';
22
+ export type { ConcurrencyConfig, } from './concurrency.js';
23
+ export { ConcurrencyManager, createConcurrencyManager, } from './concurrency.js';
24
+ export type { PollerConfig, TaskObservation, } from './poller.js';
25
+ export { BackgroundPoller, createPoller, } from './poller.js';
26
+ export type { BackgroundManagerOptions, } from './manager.js';
27
+ export { BackgroundManager, createBackgroundManager, } from './manager.js';
@@ -0,0 +1,154 @@
1
+ /**
2
+ * Background task manager for Hive worker execution.
3
+ *
4
+ * Provides the main API for:
5
+ * - Spawning background tasks with idempotency
6
+ * - Managing task lifecycle (start, complete, cancel)
7
+ * - Persisting Hive-linked task metadata via TaskService
8
+ * - Querying task status
9
+ * - Concurrency limiting with queueing
10
+ * - Polling/stability detection (read-only)
11
+ * - Sequential ordering enforcement for Hive tasks
12
+ */
13
+ import { BackgroundTaskStore } from './store.js';
14
+ import { AgentGate } from './agent-gate.js';
15
+ import { ConcurrencyManager, ConcurrencyConfig } from './concurrency.js';
16
+ import { BackgroundPoller, PollerConfig, TaskObservation } from './poller.js';
17
+ import { BackgroundTaskRecord, BackgroundTaskStatus, OpencodeClient, SpawnOptions, SpawnResult } from './types.js';
18
+ /**
19
+ * Options for creating a BackgroundManager.
20
+ */
21
+ export interface BackgroundManagerOptions {
22
+ /** OpenCode client for session management */
23
+ client: OpencodeClient;
24
+ /** Project root directory for TaskService */
25
+ projectRoot: string;
26
+ /** Optional custom store (defaults to global singleton) */
27
+ store?: BackgroundTaskStore;
28
+ /** Concurrency configuration */
29
+ concurrency?: ConcurrencyConfig;
30
+ /** Poller configuration */
31
+ poller?: PollerConfig;
32
+ /** Enforce sequential execution for Hive tasks (default: true) */
33
+ enforceHiveSequential?: boolean;
34
+ }
35
+ /**
36
+ * Background task manager.
37
+ * Coordinates between in-memory store, agent validation, Hive persistence,
38
+ * concurrency limiting, and polling/stability detection.
39
+ */
40
+ export declare class BackgroundManager {
41
+ private store;
42
+ private agentGate;
43
+ private client;
44
+ private taskService;
45
+ private concurrencyManager;
46
+ private poller;
47
+ private enforceHiveSequential;
48
+ constructor(options: BackgroundManagerOptions);
49
+ /**
50
+ * Spawn a new background task.
51
+ *
52
+ * Handles idempotency:
53
+ * - If idempotencyKey is provided and exists, returns existing task
54
+ * - Otherwise creates new task
55
+ *
56
+ * For Hive-linked tasks (hiveFeature + hiveTaskFolder provided):
57
+ * - Enforces sequential ordering (blocks if earlier tasks pending)
58
+ * - Persists idempotencyKey and workerSession to .hive task status.json
59
+ *
60
+ * @param options - Spawn options
61
+ * @returns Spawn result with task record
62
+ */
63
+ spawn(options: SpawnOptions): Promise<SpawnResult>;
64
+ /**
65
+ * Check if a Hive task can be started based on sequential ordering.
66
+ * Returns error if earlier tasks are still pending/in_progress.
67
+ */
68
+ private checkHiveTaskOrdering;
69
+ /**
70
+ * Get a task by ID.
71
+ */
72
+ getTask(taskId: string): BackgroundTaskRecord | undefined;
73
+ /**
74
+ * Get a task by idempotency key.
75
+ */
76
+ getTaskByIdempotencyKey(key: string): BackgroundTaskRecord | undefined;
77
+ /**
78
+ * Get a task by Hive feature and task folder.
79
+ */
80
+ getTaskByHiveTask(feature: string, taskFolder: string): BackgroundTaskRecord | undefined;
81
+ /**
82
+ * Update task status.
83
+ */
84
+ updateStatus(taskId: string, status: BackgroundTaskStatus, options?: {
85
+ errorMessage?: string;
86
+ }): BackgroundTaskRecord;
87
+ /**
88
+ * Notify the parent session that a background task completed.
89
+ *
90
+ * This intentionally uses session.prompt() so the parent agent "wakes up"
91
+ * and can continue the workflow (e.g., call background_output).
92
+ */
93
+ private notifyParentSession;
94
+ /**
95
+ * Cancel a task.
96
+ */
97
+ cancel(taskId: string): Promise<BackgroundTaskRecord>;
98
+ /**
99
+ * Cancel all active tasks for a parent session.
100
+ */
101
+ cancelAll(parentSessionId: string): Promise<BackgroundTaskRecord[]>;
102
+ /**
103
+ * List all tasks, optionally filtered.
104
+ */
105
+ list(filter?: {
106
+ status?: BackgroundTaskStatus | BackgroundTaskStatus[];
107
+ parentSessionId?: string;
108
+ hiveFeature?: string;
109
+ }): BackgroundTaskRecord[];
110
+ /**
111
+ * Get all active tasks.
112
+ */
113
+ getActive(): BackgroundTaskRecord[];
114
+ /**
115
+ * Handle session idle event (task completion).
116
+ */
117
+ handleSessionIdle(sessionId: string): void;
118
+ /**
119
+ * Handle message event (progress update).
120
+ */
121
+ handleMessageEvent(sessionId: string, messageText?: string): void;
122
+ /**
123
+ * Get the agent gate for direct access.
124
+ */
125
+ getAgentGate(): AgentGate;
126
+ /**
127
+ * Get the concurrency manager for direct access.
128
+ */
129
+ getConcurrencyManager(): ConcurrencyManager;
130
+ /**
131
+ * Get the poller for direct access.
132
+ */
133
+ getPoller(): BackgroundPoller;
134
+ /**
135
+ * Get observations for all active tasks from the poller.
136
+ */
137
+ getObservations(): TaskObservation[];
138
+ /**
139
+ * Get observation for a specific task.
140
+ */
141
+ getTaskObservation(taskId: string): TaskObservation | null;
142
+ /**
143
+ * Get task counts by status.
144
+ */
145
+ getCounts(): Record<BackgroundTaskStatus, number>;
146
+ /**
147
+ * Shutdown the manager and clean up resources.
148
+ */
149
+ shutdown(): void;
150
+ }
151
+ /**
152
+ * Create a new BackgroundManager.
153
+ */
154
+ export declare function createBackgroundManager(options: BackgroundManagerOptions): BackgroundManager;