Compare commits

...

21 Commits

Author SHA1 Message Date
RichardTang-Aden 505e1e30fd Merge branch 'main' into fix/session-resume-new-agent 2026-03-13 20:19:36 -07:00
Timothy 3fb2b285fb chore: add star history widget 2026-03-13 20:17:35 -07:00
RichardTang-Aden a76109840c Merge pull request #6345 from aden-hive/feat/gcu-updates
feat: GCU browser cleanup, draft loading state, and inner_turn message fix
2026-03-13 20:16:38 -07:00
RichardTang-Aden 39212350ba Merge pull request #6342 from aden-hive/ci/level-2-dummy-agent-testing
Add Level 2 dummy agent end-to-end tests
2026-03-13 19:42:34 -07:00
Richard Tang f3399fe95b chore: ruff lint 2026-03-13 19:39:44 -07:00
Richard Tang d02e1155ed feat: dummy agent tests 2026-03-13 19:39:14 -07:00
bryan 7ede3ba171 feat: queen upsert fix 2026-03-13 19:34:26 -07:00
Richard Tang 2272491cf5 chore: remove dead code 2026-03-13 18:10:43 -07:00
RichardTang-Aden bb38cb974f Merge pull request #6333 from aden-hive/fix/new-agent-resume
Fix: new agent resume and GCU browser improvements
2026-03-13 17:20:49 -07:00
bryan 635d2976f4 feat: show loading spinner in draft panel during planning phase 2026-03-13 16:40:33 -07:00
bryan 4e1525880d feat: clean up browser profile after top-level GCU node execution 2026-03-13 16:40:20 -07:00
RichardTang-Aden 08d93ef90a Merge pull request #6331 from RichardTang-Aden/main
fix: generate worker mcp.json correctly in initialize_agent_package
2026-03-13 15:35:18 -07:00
Richard Tang 22bf035522 chore: fix lint 2026-03-13 15:35:01 -07:00
Richard Tang 15944a42ab fix: generate worker mcp file correctly 2026-03-13 15:30:28 -07:00
Richard Tang 8440ec70ba chore: document the difference between runner mode run() and start() 2026-03-13 15:28:18 -07:00
Timothy eacf2520cf chore: skills prd 2026-03-13 15:22:09 -07:00
Richard Tang 20427e213a fix: update meta.json when loaded worker 2026-03-13 13:52:15 -07:00
Timothy @aden 1e74f194a1 Update authors in MCP Server Registry document 2026-03-13 12:15:50 -07:00
Timothy 08157d2bd6 chore(docs): bounty program - standard 2026-03-13 12:10:21 -07:00
Timothy ef036257a9 docs(mcp): MCP integration PRD 2026-03-13 11:56:33 -07:00
Timothy 16ce984c74 chore: add default context limit on windows quickstart 2026-03-13 10:04:49 -07:00
38 changed files with 3745 additions and 691 deletions
@@ -0,0 +1,78 @@
name: Standard Bounty
description: A bounty task for general framework contributions (not integration-specific)
title: "[Bounty]: "
labels: []
body:
- type: markdown
attributes:
value: |
## Standard Bounty
This issue is part of the [Bounty Program](../../docs/bounty-program/README.md).
**Claim this bounty** by commenting below — a maintainer will assign you within 24 hours.
- type: dropdown
id: bounty-size
attributes:
label: Bounty Size
options:
- "Small (10 pts)"
- "Medium (30 pts)"
- "Large (75 pts)"
- "Extreme (150 pts)"
validations:
required: true
- type: dropdown
id: difficulty
attributes:
label: Difficulty
options:
- Easy
- Medium
- Hard
validations:
required: true
- type: textarea
id: description
attributes:
label: Description
description: What needs to be done to complete this bounty.
placeholder: |
Describe the specific task, including:
- What the contributor needs to do
- Links to relevant files in the repo
- Any context or motivation for the change
validations:
required: true
- type: textarea
id: acceptance-criteria
attributes:
label: Acceptance Criteria
description: What "done" looks like. The PR must meet all criteria.
placeholder: |
- [ ] Criterion 1
- [ ] Criterion 2
- [ ] CI passes
validations:
required: true
- type: textarea
id: relevant-files
attributes:
label: Relevant Files
description: Links to files or directories related to this bounty.
placeholder: |
- `path/to/file.py`
- `path/to/directory/`
- type: textarea
id: resources
attributes:
label: Resources
description: Links to docs, issues, or external references that will help.
placeholder: |
- Related issue: #XXXX
- Docs: https://...
+10
View File
@@ -420,6 +420,16 @@ Visit [docs.adenhq.com](https://docs.adenhq.com/) for complete guides, API refer
Contributions are welcome! Fork the repository, create your feature branch, implement your changes, and submit a pull request. See [CONTRIBUTING.md](CONTRIBUTING.md) for detailed guidelines.
## Star History
<a href="https://star-history.com/#aden-hive/hive&Date">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=aden-hive/hive&type=Date&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=aden-hive/hive&type=Date" />
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=aden-hive/hive&type=Date" />
</picture>
</a>
---
<p align="center">
+12
View File
@@ -1920,6 +1920,11 @@ class EventLoopNode(NodeProtocol):
# Accumulate ALL tool calls across inner iterations for L3 logging.
# Unlike real_tool_results (reset each inner iteration), this persists.
logged_tool_calls: list[dict] = []
# Counter for LLM calls within a single iteration. Each pass through
# the inner tool loop starts a fresh LLM stream whose snapshot resets
# to "". Without this, all calls share the same message ID on the
# frontend and the second call's text silently replaces the first.
inner_turn = 0
# Inner tool loop: stream may produce tool calls requiring re-invocation
while True:
@@ -1960,6 +1965,7 @@ class EventLoopNode(NodeProtocol):
async def _do_stream(
_msgs: list = messages, # noqa: B006
_tc: list[ToolCallEvent] = tool_calls, # noqa: B006
inner_turn: int = inner_turn,
) -> None:
nonlocal accumulated_text, _stream_error
async for event in ctx.llm.stream(
@@ -1978,6 +1984,7 @@ class EventLoopNode(NodeProtocol):
ctx,
execution_id,
iteration=iteration,
inner_turn=inner_turn,
)
elif isinstance(event, ToolCallEvent):
@@ -2206,6 +2213,7 @@ class EventLoopNode(NodeProtocol):
ctx=ctx,
execution_id=execution_id,
iteration=iteration,
inner_turn=inner_turn,
)
result = ToolResult(
@@ -2659,6 +2667,7 @@ class EventLoopNode(NodeProtocol):
)
# Tool calls processed -- loop back to stream with updated conversation
inner_turn += 1
# -------------------------------------------------------------------
# Synthetic tools: set_output, ask_user, escalate
@@ -4344,6 +4353,7 @@ class EventLoopNode(NodeProtocol):
ctx: NodeContext,
execution_id: str = "",
iteration: int | None = None,
inner_turn: int = 0,
) -> None:
if self._event_bus:
if ctx.node_spec.client_facing:
@@ -4354,6 +4364,7 @@ class EventLoopNode(NodeProtocol):
snapshot=snapshot,
execution_id=execution_id,
iteration=iteration,
inner_turn=inner_turn,
)
else:
await self._event_bus.emit_llm_text_delta(
@@ -4362,6 +4373,7 @@ class EventLoopNode(NodeProtocol):
content=content,
snapshot=snapshot,
execution_id=execution_id,
inner_turn=inner_turn,
)
async def _publish_tool_started(
+30 -1
View File
@@ -27,12 +27,14 @@ from framework.graph.node import (
SharedMemory,
)
from framework.graph.validator import OutputValidator
from framework.llm.provider import LLMProvider, Tool
from framework.llm.provider import LLMProvider, Tool, ToolUse
from framework.observability import set_trace_context
from framework.runtime.core import Runtime
from framework.schemas.checkpoint import Checkpoint
from framework.storage.checkpoint_store import CheckpointStore
logger = logging.getLogger(__name__)
def _default_max_context_tokens() -> int:
"""Resolve max_context_tokens from global config, falling back to 32000."""
@@ -937,6 +939,33 @@ class GraphExecutor:
self.logger.info(" Executing...")
result = await node_impl.execute(ctx)
# GCU tab cleanup: stop the browser profile after a top-level GCU node
# finishes so tabs don't accumulate. Mirrors the subagent cleanup in
# EventLoopNode._execute_subagent().
if node_spec.node_type == "gcu" and self.tool_executor is not None:
try:
from gcu.browser.session import (
_active_profile as _gcu_profile_var,
)
_gcu_profile = _gcu_profile_var.get()
_stop_use = ToolUse(
id="gcu-cleanup",
name="browser_stop",
input={"profile": _gcu_profile},
)
_stop_result = self.tool_executor(_stop_use)
if asyncio.iscoroutine(_stop_result) or asyncio.isfuture(_stop_result):
await _stop_result
except ImportError:
pass # GCU not installed
except Exception as _gcu_exc:
logger.warning(
"GCU browser_stop failed for profile %r: %s",
_gcu_profile,
_gcu_exc,
)
# Emit node-completed event (skip event_loop nodes)
if self._event_bus and node_spec.node_type != "event_loop":
await self._event_bus.emit_node_loop_completed(
+26 -11
View File
@@ -1489,21 +1489,31 @@ class AgentRunner:
# Pass intro_message through for TUI display
self._agent_runtime.intro_message = self.intro_message
# ------------------------------------------------------------------
# Execution modes
#
# run() One-shot, blocking execution for worker agents
# (headless CLI via ``hive run``). Validates, runs
# the graph to completion, and returns the result.
#
# start() / trigger() Long-lived runtime for the frontend (queen).
# start() boots the runtime; trigger() sends
# non-blocking execution requests. Used by the
# server session manager and API routes.
# ------------------------------------------------------------------
async def run(
self,
input_data: dict | None = None,
session_state: dict | None = None,
entry_point_id: str | None = None,
) -> ExecutionResult:
"""
Execute the agent with given input data.
"""One-shot execution for worker agents (headless CLI).
Validates credentials before execution. If any required credentials
are missing, returns an error result with instructions on how to
provide them.
Validates credentials, runs the graph to completion, and returns
the result. Used by ``hive run`` and programmatic callers.
For single-entry-point agents, this is the standard execution path.
For multi-entry-point agents, you can optionally specify which entry point to use.
For the frontend (queen), use start() + trigger() instead.
Args:
input_data: Input data for the agent (e.g., {"lead_id": "123"})
@@ -1629,7 +1639,12 @@ class AgentRunner:
# === Runtime API ===
async def start(self) -> None:
"""Start the agent runtime."""
"""Boot the agent runtime for the frontend (queen).
Pair with trigger() to send execution requests. Used by the
server session manager. For headless worker agents, use run()
instead.
"""
if self._agent_runtime is None:
self._setup()
@@ -1646,10 +1661,10 @@ class AgentRunner:
input_data: dict[str, Any],
correlation_id: str | None = None,
) -> str:
"""
Trigger execution at a specific entry point (non-blocking).
"""Send a non-blocking execution request to a running runtime.
Returns execution ID for tracking.
Used by the server API routes after start(). For headless
worker agents, use run() instead.
Args:
entry_point_id: Which entry point to trigger
+7 -4
View File
@@ -262,7 +262,7 @@ class EventBus:
self._session_log: IO[str] | None = None
self._session_log_iteration_offset: int = 0
# Accumulator for client_output_delta snapshots — flushed on llm_turn_complete.
# Key: (stream_id, node_id, execution_id, iteration) → latest AgentEvent
# Key: (stream_id, node_id, execution_id, iteration, inner_turn) → latest AgentEvent
self._pending_output_snapshots: dict[tuple, AgentEvent] = {}
def set_session_log(self, path: Path, *, iteration_offset: int = 0) -> None:
@@ -328,6 +328,7 @@ class EventBus:
event.node_id,
event.execution_id,
event.data.get("iteration"),
event.data.get("inner_turn", 0),
)
self._pending_output_snapshots[key] = event
return
@@ -361,7 +362,7 @@ class EventBus:
to_flush: list[tuple] = []
for key, _evt in self._pending_output_snapshots.items():
if stream_id is not None:
k_stream, k_node, k_exec, _ = key
k_stream, k_node, k_exec, _, _ = key
if k_stream != stream_id or k_node != node_id or k_exec != execution_id:
continue
to_flush.append(key)
@@ -749,6 +750,7 @@ class EventBus:
content: str,
snapshot: str,
execution_id: str | None = None,
inner_turn: int = 0,
) -> None:
"""Emit LLM text delta event."""
await self.publish(
@@ -757,7 +759,7 @@ class EventBus:
stream_id=stream_id,
node_id=node_id,
execution_id=execution_id,
data={"content": content, "snapshot": snapshot},
data={"content": content, "snapshot": snapshot, "inner_turn": inner_turn},
)
)
@@ -873,9 +875,10 @@ class EventBus:
snapshot: str,
execution_id: str | None = None,
iteration: int | None = None,
inner_turn: int = 0,
) -> None:
"""Emit client output delta event (client_facing=True nodes)."""
data: dict = {"content": content, "snapshot": snapshot}
data: dict = {"content": content, "snapshot": snapshot, "inner_turn": inner_turn}
if iteration is not None:
data["iteration"] = iteration
await self.publish(
+31 -22
View File
@@ -73,7 +73,7 @@ function useDraftChromeColors() {
type DraftNodeStatus = "pending" | "running" | "complete" | "error";
interface DraftGraphProps {
draft: DraftGraphData;
draft: DraftGraphData | null;
onNodeClick?: (node: DraftNode) => void;
/** Runtime node ID → list of original draft node IDs (post-dissolution mapping). */
flowchartMap?: Record<string, string[]>;
@@ -83,6 +83,8 @@ interface DraftGraphProps {
onRuntimeNodeClick?: (runtimeNodeId: string) => void;
/** True while the queen is building the agent from the draft. */
building?: boolean;
/** True while the queen is designing the draft (no draft yet). Shows a spinner. */
loading?: boolean;
/** Called when the user clicks Run. */
onRun?: () => void;
/** Called when the user clicks Pause. */
@@ -355,7 +357,7 @@ function Tooltip({ node, style }: { node: DraftNode; style: React.CSSProperties
);
}
export default function DraftGraph({ draft, onNodeClick, flowchartMap, runtimeNodes, onRuntimeNodeClick, building, onRun, onPause, runState = "idle" }: DraftGraphProps) {
export default function DraftGraph({ draft, onNodeClick, flowchartMap, runtimeNodes, onRuntimeNodeClick, building, loading, onRun, onPause, runState = "idle" }: DraftGraphProps) {
const [hoveredNode, setHoveredNode] = useState<string | null>(null);
const [mousePos, setMousePos] = useState<{ x: number; y: number } | null>(null);
const containerRef = useRef<HTMLDivElement>(null);
@@ -463,7 +465,8 @@ export default function DraftGraph({ draft, onNodeClick, flowchartMap, runtimeNo
const hasStatusOverlay = Object.keys(nodeStatuses).length > 0;
const { nodes, edges } = draft;
const nodes = draft?.nodes ?? [];
const edges = draft?.edges ?? [];
const idxMap = useMemo(
() => Object.fromEntries(nodes.map((n, i) => [n.id, i])),
@@ -656,25 +659,6 @@ export default function DraftGraph({ draft, onNodeClick, flowchartMap, runtimeNo
return { layers, nodeW, firstColX, nodeXPositions, backEdgeOverflow, maxContentRight };
}, [nodes, forwardEdges, backEdges.length, containerW, flowchartMap, idxMap]);
if (nodes.length === 0) {
return (
<div className="flex flex-col h-full">
<div className="px-4 pt-4 pb-2">
<p className="text-[11px] text-muted-foreground font-medium uppercase tracking-wider">
Draft
</p>
</div>
<div className="flex-1 flex items-center justify-center px-4">
<p className="text-xs text-muted-foreground/60 text-center italic">
No draft graph yet.
<br />
Describe your workflow to get started.
</p>
</div>
</div>
);
}
const { layers, nodeW, nodeXPositions, backEdgeOverflow, maxContentRight } = layout;
const maxLayer = nodes.length > 0 ? Math.max(...layers) : 0;
@@ -982,6 +966,31 @@ export default function DraftGraph({ draft, onNodeClick, flowchartMap, runtimeNo
);
};
if (loading || !draft || nodes.length === 0) {
return (
<div className="flex flex-col h-full">
<div className="px-4 pt-3 pb-1.5 flex items-center gap-2">
<p className="text-[11px] text-muted-foreground font-medium uppercase tracking-wider">Draft</p>
<span className="text-[9px] font-mono font-medium rounded px-1 py-0.5 leading-none border text-amber-500/60 border-amber-500/20">planning</span>
</div>
<div className="flex-1 flex flex-col items-center justify-center gap-3">
{loading || !draft ? (
<>
<Loader2 className="w-5 h-5 animate-spin text-muted-foreground/40" />
<p className="text-xs text-muted-foreground/50">Designing flowchart</p>
</>
) : (
<p className="text-xs text-muted-foreground/60 text-center italic">
No draft graph yet.
<br />
Describe your workflow to get started.
</p>
)}
</div>
</div>
);
}
return (
<div className="flex flex-col h-full">
{/* Header */}
@@ -196,6 +196,102 @@ describe("sseEventToChatMessage", () => {
);
});
it("different inner_turn values produce different message IDs", () => {
const e1 = makeEvent({
type: "client_output_delta",
node_id: "queen",
execution_id: "exec-1",
data: { snapshot: "first response", iteration: 0, inner_turn: 0 },
});
const e2 = makeEvent({
type: "client_output_delta",
node_id: "queen",
execution_id: "exec-1",
data: { snapshot: "after tool call", iteration: 0, inner_turn: 1 },
});
const r1 = sseEventToChatMessage(e1, "t");
const r2 = sseEventToChatMessage(e2, "t");
expect(r1!.id).not.toBe(r2!.id);
});
it("same inner_turn produces same ID (streaming upsert within one LLM call)", () => {
const e1 = makeEvent({
type: "client_output_delta",
node_id: "queen",
execution_id: "exec-1",
data: { snapshot: "partial", iteration: 0, inner_turn: 1 },
});
const e2 = makeEvent({
type: "client_output_delta",
node_id: "queen",
execution_id: "exec-1",
data: { snapshot: "partial response", iteration: 0, inner_turn: 1 },
});
expect(sseEventToChatMessage(e1, "t")!.id).toBe(
sseEventToChatMessage(e2, "t")!.id,
);
});
it("absent inner_turn produces same ID as inner_turn=0 (backward compat)", () => {
const withField = makeEvent({
type: "client_output_delta",
node_id: "queen",
execution_id: "exec-1",
data: { snapshot: "hello", iteration: 2, inner_turn: 0 },
});
const withoutField = makeEvent({
type: "client_output_delta",
node_id: "queen",
execution_id: "exec-1",
data: { snapshot: "hello", iteration: 2 },
});
expect(sseEventToChatMessage(withField, "t")!.id).toBe(
sseEventToChatMessage(withoutField, "t")!.id,
);
});
it("inner_turn=0 produces no suffix (matches old ID format)", () => {
const event = makeEvent({
type: "client_output_delta",
node_id: "queen",
execution_id: "exec-1",
data: { snapshot: "hello", iteration: 3, inner_turn: 0 },
});
const result = sseEventToChatMessage(event, "t");
expect(result!.id).toBe("stream-exec-1-3-queen");
});
it("inner_turn>0 adds -t suffix to ID", () => {
const event = makeEvent({
type: "client_output_delta",
node_id: "queen",
execution_id: "exec-1",
data: { snapshot: "hello", iteration: 3, inner_turn: 2 },
});
const result = sseEventToChatMessage(event, "t");
expect(result!.id).toBe("stream-exec-1-3-t2-queen");
});
it("llm_text_delta also uses inner_turn for distinct IDs", () => {
const e1 = makeEvent({
type: "llm_text_delta",
node_id: "research",
execution_id: "exec-1",
data: { snapshot: "first", inner_turn: 0 },
});
const e2 = makeEvent({
type: "llm_text_delta",
node_id: "research",
execution_id: "exec-1",
data: { snapshot: "second", inner_turn: 1 },
});
const r1 = sseEventToChatMessage(e1, "t");
const r2 = sseEventToChatMessage(e2, "t");
expect(r1!.id).not.toBe(r2!.id);
expect(r1!.id).toBe("stream-exec-1-research");
expect(r2!.id).toBe("stream-exec-1-t1-research");
});
it("uses timestamp fallback when both turnId and execution_id are null", () => {
const event = makeEvent({
type: "client_output_delta",
+10 -2
View File
@@ -56,10 +56,15 @@ export function sseEventToChatMessage(
const iterTid = iter != null ? String(iter) : tid;
const iterIdKey = eid && iterTid ? `${eid}-${iterTid}` : eid || iterTid || `t-${Date.now()}`;
// Distinguish multiple LLM calls within the same iteration (inner tool loop).
// inner_turn=0 (or absent) produces no suffix for backward compat.
const innerTurn = event.data?.inner_turn as number | undefined;
const innerSuffix = innerTurn != null && innerTurn > 0 ? `-t${innerTurn}` : "";
const snapshot = (event.data?.snapshot as string) || (event.data?.content as string) || "";
if (!snapshot) return null;
return {
id: `stream-${iterIdKey}-${event.node_id}`,
id: `stream-${iterIdKey}${innerSuffix}-${event.node_id}`,
agent: agentDisplayName || event.node_id || "Agent",
agentColor: "",
content: snapshot,
@@ -91,10 +96,13 @@ export function sseEventToChatMessage(
}
case "llm_text_delta": {
const llmInnerTurn = event.data?.inner_turn as number | undefined;
const llmInnerSuffix = llmInnerTurn != null && llmInnerTurn > 0 ? `-t${llmInnerTurn}` : "";
const snapshot = (event.data?.snapshot as string) || (event.data?.content as string) || "";
if (!snapshot) return null;
return {
id: `stream-${idKey}-${event.node_id}`,
id: `stream-${idKey}${llmInnerSuffix}-${event.node_id}`,
agent: event.node_id || "Agent",
agentColor: "",
content: snapshot,
+3 -3
View File
@@ -2813,10 +2813,10 @@ export default function Workspace() {
<div className="flex flex-1 min-h-0">
{/* ── Pipeline graph + chat ──────────────────────────────────── */}
<div className={`${((activeAgentState?.queenPhase === "planning" || activeAgentState?.queenPhase === "building") && activeAgentState?.draftGraph) || activeAgentState?.originalDraft ? "w-[500px] min-w-[400px]" : "w-[300px] min-w-[240px]"} bg-card/30 flex flex-col border-r border-border/30 transition-[width] duration-200`}>
<div className={`${activeAgentState?.queenPhase === "planning" || activeAgentState?.queenPhase === "building" || activeAgentState?.originalDraft ? "w-[500px] min-w-[400px]" : "w-[300px] min-w-[240px]"} bg-card/30 flex flex-col border-r border-border/30 transition-[width] duration-200`}>
<div className="flex-1 min-h-0">
{(activeAgentState?.queenPhase === "planning" || activeAgentState?.queenPhase === "building") && activeAgentState?.draftGraph ? (
<DraftGraph draft={activeAgentState.draftGraph} building={activeAgentState?.queenBuilding} onRun={handleRun} onPause={handlePause} runState={activeAgentState?.workerRunState ?? "idle"} />
{activeAgentState?.queenPhase === "planning" || activeAgentState?.queenPhase === "building" ? (
<DraftGraph draft={activeAgentState?.draftGraph ?? null} loading={!activeAgentState?.draftGraph} building={activeAgentState?.queenBuilding} onRun={handleRun} onPause={handlePause} runState={activeAgentState?.workerRunState ?? "idle"} />
) : activeAgentState?.originalDraft ? (
<DraftGraph
draft={activeAgentState.originalDraft}
-140
View File
@@ -1,140 +0,0 @@
#!/usr/bin/env python3
"""
Setup script for Aden Hive Framework MCP Server
This script installs the framework and configures the MCP server.
"""
import json
import logging
import subprocess
import sys
from pathlib import Path
logger = logging.getLogger(__name__)
def setup_logger():
"""Configure logger for CLI usage with colored output."""
if not logger.handlers:
handler = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter("%(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.INFO)
class Colors:
"""ANSI color codes for terminal output."""
GREEN = "\033[0;32m"
YELLOW = "\033[1;33m"
RED = "\033[0;31m"
BLUE = "\033[0;34m"
NC = "\033[0m" # No Color
def log_step(message: str):
"""Log a colored step message."""
logger.info(f"{Colors.YELLOW}{message}{Colors.NC}")
def log_success(message: str):
"""Log a success message."""
logger.info(f"{Colors.GREEN}{message}{Colors.NC}")
def log_error(message: str):
"""Log an error message."""
logger.error(f"{Colors.RED}{message}{Colors.NC}")
def run_command(cmd: list, error_msg: str) -> bool:
"""Run a command and return success status."""
try:
subprocess.run(
cmd,
check=True,
capture_output=True,
text=True,
encoding="utf-8",
)
return True
except subprocess.CalledProcessError as e:
log_error(error_msg)
logger.error(f"Error output: {e.stderr}")
return False
def main():
"""Main setup function."""
setup_logger()
logger.info("=== Aden Hive Framework MCP Server Setup ===")
logger.info("")
# Get script directory
script_dir = Path(__file__).parent.absolute()
# Step 1: Install framework package
log_step("Step 1: Installing framework package...")
if not run_command(
[sys.executable, "-m", "pip", "install", "-e", str(script_dir)],
"Failed to install framework package",
):
sys.exit(1)
log_success("Framework package installed")
logger.info("")
# Step 2: Install MCP dependencies
log_step("Step 2: Installing MCP dependencies...")
if not run_command(
[sys.executable, "-m", "pip", "install", "mcp", "fastmcp"],
"Failed to install MCP dependencies",
):
sys.exit(1)
log_success("MCP dependencies installed")
logger.info("")
# Step 3: Verify MCP configuration
log_step("Step 3: Verifying MCP server configuration...")
mcp_config_path = script_dir / ".mcp.json"
if mcp_config_path.exists():
log_success("MCP configuration found at .mcp.json")
logger.info("Configuration:")
with open(mcp_config_path, encoding="utf-8") as f:
config = json.load(f)
logger.info(json.dumps(config, indent=2))
else:
log_success("No .mcp.json needed (MCP servers configured at repo root)")
logger.info("")
# Step 4: Test framework import
log_step("Step 4: Testing framework import...")
try:
subprocess.run(
[sys.executable, "-c", "import framework; print('OK')"],
check=True,
capture_output=True,
text=True,
encoding="utf-8",
)
log_success("Framework module verified")
except subprocess.CalledProcessError as e:
log_error("Failed to import framework module")
logger.error(f"Error: {e.stderr}")
sys.exit(1)
logger.info("")
# Success summary
logger.info(f"{Colors.GREEN}=== Setup Complete ==={Colors.NC}")
logger.info("")
logger.info("The framework is now ready to use!")
logger.info("")
logger.info(f"{Colors.BLUE}MCP Configuration location:{Colors.NC}")
logger.info(f" {mcp_config_path}")
logger.info("")
if __name__ == "__main__":
main()
+44
View File
@@ -0,0 +1,44 @@
# Dummy Agent Tests (Level 2)
End-to-end tests that run real LLM calls against deterministic graph structures. Not part of CI — run manually to verify the executor works with real providers.
## Quick Start
```bash
cd core
uv run python tests/dummy_agents/run_all.py
```
The script detects available credentials and prompts you to pick a provider. You need at least one of:
- `ANTHROPIC_API_KEY`
- `OPENAI_API_KEY`
- `GEMINI_API_KEY`
- `ZAI_API_KEY`
- Claude Code / Codex / Kimi subscription
## Verbose Mode
Show live LLM logs (tool calls, judge verdicts, node traversal):
```bash
uv run python tests/dummy_agents/run_all.py --verbose
```
## What's Tested
| Agent | Tests | What it covers |
|-------|-------|----------------|
| echo | 2 | Single-node lifecycle, basic set_output |
| pipeline | 4 | Multi-node traversal, input_mapping, conversation modes |
| branch | 3 | Conditional edges, LLM-driven routing |
| parallel_merge | 4 | Fan-out/fan-in, failure strategies |
| retry | 4 | Retry mechanics, exhaustion, ON_FAILURE edges |
| feedback_loop | 3 | Feedback cycles, max_node_visits |
| worker | 4 | Real MCP tools (example_tool, get_current_time, save_data/load_data) |
## Notes
- Tests are **auto-skipped** in regular `pytest` runs (no LLM configured)
- Worker tests start the `hive-tools` MCP server as a subprocess
- Typical runtime: ~1-3 min depending on provider
+3
View File
@@ -0,0 +1,3 @@
# Level 2: Dummy Agent Tests
# End-to-end graph execution tests with real LLM calls.
# NOT part of regular CI — run manually with: uv run python tests/dummy_agents/run_all.py
+140
View File
@@ -0,0 +1,140 @@
"""Shared fixtures for dummy agent end-to-end tests.
These tests use real LLM providers they are NOT part of regular CI.
Run via: cd core && uv run python tests/dummy_agents/run_all.py
"""
from __future__ import annotations
from pathlib import Path
import pytest
from framework.graph.executor import GraphExecutor, ParallelExecutionConfig
from framework.graph.goal import Goal
from framework.llm.litellm import LiteLLMProvider
from framework.runtime.core import Runtime
# ── module-level state set by run_all.py ─────────────────────────────
_selected_model: str | None = None
_selected_api_key: str | None = None
_selected_extra_headers: dict[str, str] | None = None
_selected_api_base: str | None = None
def set_llm_selection(
model: str,
api_key: str,
extra_headers: dict[str, str] | None = None,
api_base: str | None = None,
) -> None:
"""Called by run_all.py after user selects a provider."""
global _selected_model, _selected_api_key, _selected_extra_headers, _selected_api_base
_selected_model = model
_selected_api_key = api_key
_selected_extra_headers = extra_headers
_selected_api_base = api_base
# ── collection hook: skip entire directory when not configured ───────
def pytest_collection_modifyitems(config, items):
"""Skip all dummy_agents tests when no LLM is configured.
This prevents these tests from running in regular CI. They only run
when launched via run_all.py (which calls set_llm_selection first).
"""
if _selected_model is not None:
return # LLM configured, run normally
skip = pytest.mark.skip(
reason="Dummy agent tests require a real LLM. "
"Run via: cd core && uv run python tests/dummy_agents/run_all.py"
)
for item in items:
if "dummy_agents" in str(item.fspath):
item.add_marker(skip)
# ── fixtures ─────────────────────────────────────────────────────────
@pytest.fixture(scope="session")
def llm_provider():
"""Real LLM provider using the user-selected model."""
if _selected_model is None or _selected_api_key is None:
pytest.skip("No LLM selected — run via run_all.py")
kwargs = {"model": _selected_model, "api_key": _selected_api_key}
if _selected_extra_headers:
kwargs["extra_headers"] = _selected_extra_headers
if _selected_api_base:
kwargs["api_base"] = _selected_api_base
return LiteLLMProvider(**kwargs)
@pytest.fixture(scope="session")
def tool_registry():
"""Load hive-tools MCP server and return a ToolRegistry with real tools.
Session-scoped so the MCP server is started once and reused across tests.
"""
from framework.runner.tool_registry import ToolRegistry
registry = ToolRegistry()
# Resolve the tools directory relative to the repo root
repo_root = Path(__file__).resolve().parents[3] # core/tests/dummy_agents -> repo root
tools_dir = repo_root / "tools"
mcp_config = {
"name": "hive-tools",
"transport": "stdio",
"command": "uv",
"args": ["run", "python", "mcp_server.py", "--stdio"],
"cwd": str(tools_dir),
"description": "Hive tools MCP server",
}
registry.register_mcp_server(mcp_config)
yield registry
registry.cleanup()
@pytest.fixture
def runtime(tmp_path):
"""Real Runtime backed by a temp directory."""
return Runtime(storage_path=tmp_path / "runtime")
@pytest.fixture
def goal():
return Goal(id="dummy", name="Dummy Agent Test", description="Level 2 end-to-end testing")
def make_executor(
runtime: Runtime,
llm: LiteLLMProvider,
*,
enable_parallel: bool = True,
parallel_config: ParallelExecutionConfig | None = None,
loop_config: dict | None = None,
tool_registry=None,
storage_path: Path | None = None,
) -> GraphExecutor:
"""Factory that creates a GraphExecutor with a real LLM."""
tools = []
tool_executor = None
if tool_registry is not None:
tools = list(tool_registry.get_tools().values())
tool_executor = tool_registry.get_executor()
return GraphExecutor(
runtime=runtime,
llm=llm,
tools=tools,
tool_executor=tool_executor,
enable_parallel_execution=enable_parallel,
parallel_config=parallel_config,
loop_config=loop_config or {"max_iterations": 10},
storage_path=storage_path,
)
+64
View File
@@ -0,0 +1,64 @@
"""Minimal helper nodes for deterministic control-flow tests.
Most tests use real EventLoopNode with real LLM calls. These helpers
exist only for tests that need predictable failure/success patterns
(retry, feedback loop, parallel failure modes).
"""
from __future__ import annotations
from framework.graph.node import NodeContext, NodeProtocol, NodeResult
class SuccessNode(NodeProtocol):
"""Always succeeds with configurable output dict."""
def __init__(self, output: dict | None = None):
self._output = output or {"status": "ok"}
self.executed = False
self.execute_count = 0
async def execute(self, ctx: NodeContext) -> NodeResult:
self.executed = True
self.execute_count += 1
return NodeResult(success=True, output=self._output, tokens_used=1, latency_ms=1)
class FailNode(NodeProtocol):
"""Always fails with configurable error."""
def __init__(self, error: str = "node failed"):
self._error = error
self.attempt_count = 0
async def execute(self, ctx: NodeContext) -> NodeResult:
self.attempt_count += 1
return NodeResult(success=False, error=self._error)
class FlakyNode(NodeProtocol):
"""Fails N times then succeeds. For retry tests."""
def __init__(self, fail_times: int = 2, output: dict | None = None):
self.fail_times = fail_times
self._output = output or {"status": "recovered"}
self.attempt_count = 0
async def execute(self, ctx: NodeContext) -> NodeResult:
self.attempt_count += 1
if self.attempt_count <= self.fail_times:
return NodeResult(success=False, error=f"fail #{self.attempt_count}")
return NodeResult(success=True, output=self._output, tokens_used=1, latency_ms=1)
class StatefulNode(NodeProtocol):
"""Returns different outputs on successive calls. For feedback loop tests."""
def __init__(self, outputs: list[NodeResult]):
self._outputs = outputs
self.call_count = 0
async def execute(self, ctx: NodeContext) -> NodeResult:
idx = min(self.call_count, len(self._outputs) - 1)
self.call_count += 1
return self._outputs[idx]
+359
View File
@@ -0,0 +1,359 @@
#!/usr/bin/env python3
"""Runner for Level 2 dummy agent tests with interactive LLM provider selection.
This is NOT part of regular CI. It makes real LLM API calls.
Usage:
cd core && uv run python tests/dummy_agents/run_all.py
cd core && uv run python tests/dummy_agents/run_all.py --verbose
"""
from __future__ import annotations
import os
import sys
import time
import xml.etree.ElementTree as ET
from pathlib import Path
from tempfile import NamedTemporaryFile
TESTS_DIR = Path(__file__).parent
# ── provider registry ────────────────────────────────────────────────
# (env_var, display_name, default_model) — models match quickstart.sh defaults
API_KEY_PROVIDERS = [
("ANTHROPIC_API_KEY", "Anthropic (Claude)", "claude-sonnet-4-20250514"),
("OPENAI_API_KEY", "OpenAI", "gpt-5-mini"),
("GEMINI_API_KEY", "Google Gemini", "gemini/gemini-3-flash-preview"),
("ZAI_API_KEY", "ZAI (GLM)", "openai/glm-5"),
("GROQ_API_KEY", "Groq", "moonshotai/kimi-k2-instruct-0905"),
("MISTRAL_API_KEY", "Mistral", "mistral-large-latest"),
("CEREBRAS_API_KEY", "Cerebras", "cerebras/zai-glm-4.7"),
("TOGETHER_API_KEY", "Together AI", "together_ai/meta-llama/Llama-3.3-70B-Instruct-Turbo"),
("DEEPSEEK_API_KEY", "DeepSeek", "deepseek-chat"),
("MINIMAX_API_KEY", "MiniMax", "MiniMax-M2.5"),
]
def _detect_claude_code_token() -> str | None:
"""Check if Claude Code subscription credentials are available."""
try:
from framework.runner.runner import get_claude_code_token
return get_claude_code_token()
except Exception:
return None
def _detect_codex_token() -> str | None:
"""Check if Codex subscription credentials are available."""
try:
from framework.runner.runner import get_codex_token
return get_codex_token()
except Exception:
return None
def _detect_kimi_code_token() -> str | None:
"""Check if Kimi Code subscription credentials are available."""
try:
from framework.runner.runner import get_kimi_code_token
return get_kimi_code_token()
except Exception:
return None
def detect_available() -> list[dict]:
"""Detect all available LLM providers with valid credentials.
Returns list of dicts: {name, model, api_key, source}
"""
available = []
# Subscription-based providers
token = _detect_claude_code_token()
if token:
available.append(
{
"name": "Claude Code (subscription)",
"model": "claude-sonnet-4-20250514",
"api_key": token,
"source": "claude_code_sub",
"extra_headers": {"authorization": f"Bearer {token}"},
}
)
token = _detect_codex_token()
if token:
available.append(
{
"name": "Codex (subscription)",
"model": "gpt-5-mini",
"api_key": token,
"source": "codex_sub",
}
)
token = _detect_kimi_code_token()
if token:
available.append(
{
"name": "Kimi Code (subscription)",
"model": "moonshotai/kimi-k2-instruct-0905",
"api_key": token,
"source": "kimi_sub",
}
)
# API key providers (env vars)
for env_var, name, default_model in API_KEY_PROVIDERS:
key = os.environ.get(env_var)
if key:
entry = {
"name": f"{name} (${env_var})",
"model": default_model,
"api_key": key,
"source": env_var,
}
# ZAI requires an api_base (OpenAI-compatible endpoint)
if env_var == "ZAI_API_KEY":
entry["api_base"] = "https://api.z.ai/api/coding/paas/v4"
available.append(entry)
return available
def prompt_provider_selection() -> dict:
"""Interactive prompt to select an LLM provider. Returns the chosen provider dict."""
available = detect_available()
if not available:
print("\n No LLM credentials detected.")
print(" Set an API key environment variable, e.g.:")
print(" export ANTHROPIC_API_KEY=sk-...")
print(" export OPENAI_API_KEY=sk-...")
print(" Or authenticate with Claude Code: claude")
sys.exit(1)
if len(available) == 1:
choice = available[0]
print(f"\n Using: {choice['name']} ({choice['model']})")
return choice
print("\n Available LLM providers:\n")
for i, p in enumerate(available, 1):
print(f" {i}) {p['name']} [{p['model']}]")
print()
while True:
try:
raw = input(f" Select provider [1-{len(available)}]: ").strip()
idx = int(raw) - 1
if 0 <= idx < len(available):
choice = available[idx]
print(f"\n Using: {choice['name']} ({choice['model']})\n")
return choice
except (ValueError, EOFError):
pass
print(f" Please enter a number between 1 and {len(available)}")
# ── test runner ──────────────────────────────────────────────────────
def parse_junit_xml(xml_path: str) -> dict[str, dict]:
"""Parse JUnit XML and group results by agent (test file)."""
tree = ET.parse(xml_path)
root = tree.getroot()
agents: dict[str, dict] = {}
for testsuite in root.iter("testsuite"):
for testcase in testsuite.iter("testcase"):
classname = testcase.get("classname", "")
parts = classname.split(".")
agent_name = "unknown"
for part in parts:
if part.startswith("test_"):
agent_name = part[5:]
break
if agent_name not in agents:
agents[agent_name] = {
"total": 0,
"passed": 0,
"failed": 0,
"time": 0.0,
"tests": [],
}
agents[agent_name]["total"] += 1
test_time = float(testcase.get("time", "0"))
agents[agent_name]["time"] += test_time
failures = testcase.findall("failure")
errors = testcase.findall("error")
test_name = testcase.get("name", "")
if failures or errors:
agents[agent_name]["failed"] += 1
# Extract failure reason from the first failure/error element
fail_el = (failures or errors)[0]
reason = fail_el.get("message", "") or ""
# Also grab the text body for more detail
body = fail_el.text or ""
# Build a concise reason: prefer message, fall back to first line of body
if not reason and body:
reason = body.strip().split("\n")[0]
agents[agent_name]["tests"].append((test_name, "FAIL", reason))
else:
agents[agent_name]["passed"] += 1
agents[agent_name]["tests"].append((test_name, "PASS", ""))
return agents
def print_table(agents: dict[str, dict], total_time: float, verbose: bool = False) -> None:
"""Print summary table."""
col_agent = 20
col_tests = 6
col_passed = 8
col_time = 12
def sep(char: str = "") -> str:
return (
f"{char * (col_agent + 2)}{char * (col_tests + 2)}"
f"{char * (col_passed + 2)}{char * (col_time + 2)}"
)
header = (
f"{'Agent':<{col_agent}}{'Tests':>{col_tests}} "
f"{'Passed':>{col_passed}}{'Time (s)':>{col_time}}"
)
top = (
f"{'' * (col_agent + 2)}{'' * (col_tests + 2)}"
f"{'' * (col_passed + 2)}{'' * (col_time + 2)}"
)
bottom = (
f"{'' * (col_agent + 2)}{'' * (col_tests + 2)}"
f"{'' * (col_passed + 2)}{'' * (col_time + 2)}"
)
print()
print(top)
print(header)
print(sep())
total_tests = 0
total_passed = 0
for agent_name in sorted(agents.keys()):
data = agents[agent_name]
total_tests += data["total"]
total_passed += data["passed"]
marker = " " if data["failed"] == 0 else "!"
row = (
f"{marker}{agent_name:<{col_agent + 1}}{data['total']:>{col_tests}} "
f"{data['passed']:>{col_passed}}{data['time']:>{col_time}.2f}"
)
print(row)
if verbose:
for test_name, status, reason in data["tests"]:
icon = "" if status == "PASS" else ""
print(
f"{icon} {test_name:<{col_agent - 2}}"
f"{'':>{col_tests + 2}}{'':>{col_passed + 2}}{'':>{col_time + 2}}"
)
if status == "FAIL" and reason:
# Print failure reason wrapped to fit, indented under the test
reason_short = reason[:120] + ("..." if len(reason) > 120 else "")
print(f"{reason_short}")
print("")
print(sep())
all_pass = total_passed == total_tests
status = "ALL PASS" if all_pass else f"{total_tests - total_passed} FAILED"
totals = (
f"{status:<{col_agent}}{total_tests:>{col_tests}} "
f"{total_passed:>{col_passed}}{total_time:>{col_time}.2f}"
)
print(totals)
print(bottom)
# Always print failure details if any tests failed
if not all_pass:
print("\n Failure Details:")
print(" " + "" * 70)
for agent_name in sorted(agents.keys()):
for test_name, status, reason in agents[agent_name]["tests"]:
if status == "FAIL":
print(f"\n{agent_name}::{test_name}")
if reason:
# Wrap long reasons
for i in range(0, len(reason), 100):
print(f" {reason[i : i + 100]}")
print()
def main() -> int:
verbose = "--verbose" in sys.argv or "-v" in sys.argv
print("\n ╔═══════════════════════════════════════╗")
print(" ║ Level 2: Dummy Agent Tests (E2E) ║")
print(" ╚═══════════════════════════════════════╝")
# Step 1: detect credentials and let user pick
provider = prompt_provider_selection()
# Step 2: inject selection into conftest module state
from tests.dummy_agents.conftest import set_llm_selection
set_llm_selection(
model=provider["model"],
api_key=provider["api_key"],
extra_headers=provider.get("extra_headers"),
api_base=provider.get("api_base"),
)
# Step 3: run pytest
with NamedTemporaryFile(suffix=".xml", delete=False) as tmp:
xml_path = tmp.name
start = time.time()
import pytest as _pytest
pytest_args = [
str(TESTS_DIR),
f"--junitxml={xml_path}",
"--tb=short",
"--override-ini=asyncio_mode=auto",
"--log-cli-level=INFO", # Stream logs live to terminal
"-v",
]
if not verbose:
# In non-verbose mode, only show warnings and above
pytest_args[pytest_args.index("--log-cli-level=INFO")] = "--log-cli-level=WARNING"
pytest_args.remove("-v")
pytest_args.append("-q")
exit_code = _pytest.main(pytest_args)
elapsed = time.time() - start
# Step 4: print summary
try:
agents = parse_junit_xml(xml_path)
print_table(agents, elapsed, verbose=verbose)
except Exception as e:
print(f"\n Could not parse results: {e}")
# Clean up
Path(xml_path).unlink(missing_ok=True)
return exit_code
if __name__ == "__main__":
sys.exit(main())
+132
View File
@@ -0,0 +1,132 @@
"""Branch agent: LLM classifies input, conditional edges route to different paths.
Tests conditional edge evaluation with real LLM output.
"""
from __future__ import annotations
import pytest
from framework.graph.edge import EdgeCondition, EdgeSpec, GraphSpec
from framework.graph.node import NodeSpec
from .conftest import make_executor
SET_OUTPUT_INSTRUCTION = (
"You MUST call the set_output tool to provide your answer. "
"Do not just write text — call set_output with the correct key and value."
)
def _build_branch_graph() -> GraphSpec:
return GraphSpec(
id="branch-graph",
goal_id="dummy",
entry_node="classify",
entry_points={"start": "classify"},
terminal_nodes=["positive", "negative"],
conversation_mode="continuous",
nodes=[
NodeSpec(
id="classify",
name="Classify",
description="Classifies input sentiment",
node_type="event_loop",
input_keys=["text"],
output_keys=["score", "label"],
system_prompt=(
"You are a sentiment classifier. Read the 'text' input and determine "
"if the sentiment is positive or negative.\n\n"
"You MUST call set_output TWICE:\n"
"1. set_output(key='score', value='<number>') — a score between 0.0 "
"and 1.0 where >0.5 means positive\n"
"2. set_output(key='label', value='positive') or "
"set_output(key='label', value='negative')\n\n" + SET_OUTPUT_INSTRUCTION
),
),
NodeSpec(
id="positive",
name="Positive Handler",
description="Handles positive sentiment",
node_type="event_loop",
output_keys=["result"],
system_prompt=(
"The input was classified as positive. Call set_output with "
"key='result' and a brief one-sentence acknowledgment. "
+ SET_OUTPUT_INSTRUCTION
),
),
NodeSpec(
id="negative",
name="Negative Handler",
description="Handles negative sentiment",
node_type="event_loop",
output_keys=["result"],
system_prompt=(
"The input was classified as negative. Call set_output with "
"key='result' and a brief one-sentence acknowledgment. "
+ SET_OUTPUT_INSTRUCTION
),
),
],
edges=[
EdgeSpec(
id="classify-to-positive",
source="classify",
target="positive",
condition=EdgeCondition.CONDITIONAL,
condition_expr="output.get('label') == 'positive'",
priority=1,
),
EdgeSpec(
id="classify-to-negative",
source="classify",
target="negative",
condition=EdgeCondition.CONDITIONAL,
condition_expr="output.get('label') == 'negative'",
priority=0,
),
],
memory_keys=["text", "score", "label", "result"],
)
@pytest.mark.asyncio
async def test_branch_positive_path(runtime, goal, llm_provider):
graph = _build_branch_graph()
executor = make_executor(runtime, llm_provider)
result = await executor.execute(
graph, goal, {"text": "I love this product, it's amazing!"}, validate_graph=False
)
assert result.success
assert result.path == ["classify", "positive"]
@pytest.mark.asyncio
async def test_branch_negative_path(runtime, goal, llm_provider):
graph = _build_branch_graph()
executor = make_executor(runtime, llm_provider)
result = await executor.execute(
graph, goal, {"text": "This is terrible and broken, I hate it."}, validate_graph=False
)
assert result.success
assert result.path == ["classify", "negative"]
@pytest.mark.asyncio
async def test_branch_two_nodes_traversed(runtime, goal, llm_provider):
"""Regardless of which branch, exactly 2 nodes should execute."""
graph = _build_branch_graph()
executor = make_executor(runtime, llm_provider)
result = await executor.execute(
graph, goal, {"text": "The weather is nice today."}, validate_graph=False
)
assert result.success
assert result.steps_executed == 2
assert len(result.path) == 2
+66
View File
@@ -0,0 +1,66 @@
"""Echo agent: single-node worker that echoes input to output.
Tests basic node lifecycle with a real LLM call simplest possible worker.
"""
from __future__ import annotations
import pytest
from framework.graph.edge import GraphSpec
from framework.graph.node import NodeSpec
from .conftest import make_executor
def _build_echo_graph() -> GraphSpec:
return GraphSpec(
id="echo-graph",
goal_id="dummy",
entry_node="echo",
entry_points={"start": "echo"},
terminal_nodes=["echo"],
nodes=[
NodeSpec(
id="echo",
name="Echo",
description="Echoes input to output",
node_type="event_loop",
input_keys=["input"],
output_keys=["output"],
system_prompt=(
"You are an echo node. Your ONLY job is to read the 'input' value "
"provided in the user message, then immediately call the set_output "
"tool with key='output' and value set to the EXACT same string. "
"Do not add any text or explanation. Just call set_output."
),
),
],
edges=[],
memory_keys=["input", "output"],
conversation_mode="continuous",
)
@pytest.mark.asyncio
async def test_echo_basic(runtime, goal, llm_provider):
graph = _build_echo_graph()
executor = make_executor(runtime, llm_provider)
result = await executor.execute(graph, goal, {"input": "hello"}, validate_graph=False)
assert result.success
assert result.output.get("output") is not None
assert result.path == ["echo"]
assert result.steps_executed == 1
@pytest.mark.asyncio
async def test_echo_empty_input(runtime, goal, llm_provider):
graph = _build_echo_graph()
executor = make_executor(runtime, llm_provider)
result = await executor.execute(graph, goal, {"input": ""}, validate_graph=False)
assert result.success
assert "output" in result.output
@@ -0,0 +1,144 @@
"""Feedback loop agent: draft/review cycle with max_node_visits limit.
Uses StatefulNode for review to control loop iterations deterministically.
"""
from __future__ import annotations
import pytest
from framework.graph.edge import EdgeCondition, EdgeSpec, GraphSpec
from framework.graph.node import NodeResult, NodeSpec
from .conftest import make_executor
from .nodes import StatefulNode, SuccessNode
def _build_feedback_graph(max_visits: int = 3) -> GraphSpec:
return GraphSpec(
id="feedback-graph",
goal_id="dummy",
entry_node="draft",
terminal_nodes=["done"],
nodes=[
NodeSpec(
id="draft",
name="Draft",
description="Produces a draft",
node_type="event_loop",
output_keys=["draft_output"],
max_node_visits=max_visits,
),
NodeSpec(
id="review",
name="Review",
description="Reviews the draft",
node_type="event_loop",
input_keys=["draft_output"],
output_keys=["approved"],
),
NodeSpec(
id="done",
name="Done",
description="Final node",
node_type="event_loop",
output_keys=["final"],
),
],
edges=[
EdgeSpec(
id="draft-to-review",
source="draft",
target="review",
condition=EdgeCondition.ON_SUCCESS,
),
EdgeSpec(
id="review-to-draft",
source="review",
target="draft",
condition=EdgeCondition.CONDITIONAL,
condition_expr="output.get('approved') == False",
priority=1,
),
EdgeSpec(
id="review-to-done",
source="review",
target="done",
condition=EdgeCondition.CONDITIONAL,
condition_expr="output.get('approved') == True",
priority=0,
),
],
memory_keys=["draft_output", "approved", "final"],
)
@pytest.mark.asyncio
async def test_feedback_loop_terminates(runtime, goal, llm_provider):
"""Loop should terminate: draft visits are capped, review eventually approves."""
graph = _build_feedback_graph(max_visits=3)
executor = make_executor(runtime, llm_provider)
executor.register_node("draft", SuccessNode(output={"draft_output": "v1"}))
executor.register_node(
"review",
StatefulNode(
[
NodeResult(success=True, output={"approved": False}),
NodeResult(success=True, output={"approved": False}),
NodeResult(success=True, output={"approved": True}),
]
),
)
executor.register_node("done", SuccessNode(output={"final": "done"}))
result = await executor.execute(graph, goal, {}, validate_graph=False)
assert result.success
assert result.node_visit_counts.get("draft", 0) == 3
assert "done" in result.path
@pytest.mark.asyncio
async def test_feedback_loop_visit_counts(runtime, goal, llm_provider):
graph = _build_feedback_graph(max_visits=3)
executor = make_executor(runtime, llm_provider)
executor.register_node("draft", SuccessNode(output={"draft_output": "v1"}))
executor.register_node(
"review",
StatefulNode(
[
NodeResult(success=True, output={"approved": False}),
NodeResult(success=True, output={"approved": True}),
]
),
)
executor.register_node("done", SuccessNode(output={"final": "done"}))
result = await executor.execute(graph, goal, {}, validate_graph=False)
assert result.success
assert result.node_visit_counts.get("draft", 0) == 2
assert result.node_visit_counts.get("review", 0) == 2
@pytest.mark.asyncio
async def test_feedback_loop_early_exit(runtime, goal, llm_provider):
"""Review approves on first iteration — loop exits before max."""
graph = _build_feedback_graph(max_visits=5)
executor = make_executor(runtime, llm_provider)
executor.register_node("draft", SuccessNode(output={"draft_output": "perfect"}))
executor.register_node(
"review",
StatefulNode(
[
NodeResult(success=True, output={"approved": True}),
]
),
)
executor.register_node("done", SuccessNode(output={"final": "done"}))
result = await executor.execute(graph, goal, {}, validate_graph=False)
assert result.success
assert result.node_visit_counts.get("draft", 0) == 1
assert "done" in result.path
@@ -0,0 +1,179 @@
"""GCU subagent test: parent event_loop delegates to a GCU subagent.
Tests the subagent delegation pattern where a parent node uses
delegate_to_sub_agent to invoke a GCU (browser) node for a task.
The GCU node has access to browser tools via the GCU MCP server.
Note: This test requires the GCU MCP server (gcu.server) to be available.
If not installed, the test is skipped.
"""
from __future__ import annotations
from pathlib import Path
import pytest
from framework.graph.edge import GraphSpec
from framework.graph.goal import Goal
from framework.graph.node import NodeSpec
from .conftest import make_executor
def _has_gcu_server() -> bool:
"""Check if the GCU MCP server module is available."""
try:
import gcu.server # noqa: F401
return True
except ImportError:
return False
def _build_gcu_subagent_graph() -> GraphSpec:
"""Parent event_loop node with a GCU subagent for browser tasks.
Structure:
- parent (event_loop): orchestrator that decides when to delegate
- browser_worker (gcu): subagent with browser tools
- parent delegates to browser_worker via delegate_to_sub_agent tool
- browser_worker is NOT connected by edges (validation rule)
"""
return GraphSpec(
id="gcu-subagent-graph",
goal_id="gcu-test",
entry_node="parent",
entry_points={"start": "parent"},
terminal_nodes=["parent"],
nodes=[
NodeSpec(
id="parent",
name="Orchestrator",
description="Orchestrates browser tasks via subagent delegation",
node_type="event_loop",
input_keys=["task"],
output_keys=["result"],
sub_agents=["browser_worker"],
system_prompt=(
"You are an orchestrator. You have a browser subagent called "
"'browser_worker' available via delegate_to_sub_agent.\n\n"
"Read the 'task' input and delegate the browser work to "
"the browser_worker subagent. When the subagent completes, "
"summarize the result and call set_output with key='result'."
),
),
NodeSpec(
id="browser_worker",
name="Browser Worker",
description="GCU browser subagent for web tasks",
node_type="gcu",
output_keys=["browser_result"],
system_prompt=(
"You are a browser worker subagent. Complete the delegated "
"browser task using available browser tools. "
"When done, call set_output with key='browser_result' and "
"the information you found."
),
),
],
edges=[], # GCU subagents must NOT be connected by edges
memory_keys=["task", "result", "browser_result"],
conversation_mode="continuous",
)
def _gcu_goal() -> Goal:
return Goal(
id="gcu-test",
name="GCU Subagent Test",
description="Test browser subagent delegation",
)
@pytest.mark.asyncio
@pytest.mark.skipif(not _has_gcu_server(), reason="GCU server not installed")
async def test_gcu_subagent_delegation(runtime, llm_provider, tool_registry, tmp_path):
"""Parent delegates a simple browser task to GCU subagent."""
# Register GCU MCP server tools
from framework.graph.gcu import GCU_MCP_SERVER_CONFIG
repo_root = Path(__file__).resolve().parents[3]
gcu_config = dict(GCU_MCP_SERVER_CONFIG)
gcu_config["cwd"] = str(repo_root / "tools")
tool_registry.register_mcp_server(gcu_config)
# Expand GCU node tools (mirrors what runner._setup does)
graph = _build_gcu_subagent_graph()
gcu_tool_names = tool_registry.get_server_tool_names("gcu-tools")
if gcu_tool_names:
for node in graph.nodes:
if node.node_type == "gcu":
existing = set(node.tools)
for tool_name in sorted(gcu_tool_names):
if tool_name not in existing:
node.tools.append(tool_name)
executor = make_executor(
runtime,
llm_provider,
tool_registry=tool_registry,
storage_path=tmp_path / "storage",
)
result = await executor.execute(
graph,
_gcu_goal(),
{"task": "Use the browser to navigate to https://example.com and report the page title."},
validate_graph=False,
)
assert result.success
assert result.output.get("result") is not None
@pytest.mark.asyncio
@pytest.mark.skipif(not _has_gcu_server(), reason="GCU server not installed")
async def test_gcu_subagent_returns_data(runtime, llm_provider, tool_registry, tmp_path):
"""Verify the parent receives structured data from the GCU subagent."""
from framework.graph.gcu import GCU_MCP_SERVER_CONFIG
repo_root = Path(__file__).resolve().parents[3]
gcu_config = dict(GCU_MCP_SERVER_CONFIG)
gcu_config["cwd"] = str(repo_root / "tools")
# Only register if not already registered
if not tool_registry.get_server_tool_names("gcu-tools"):
tool_registry.register_mcp_server(gcu_config)
graph = _build_gcu_subagent_graph()
gcu_tool_names = tool_registry.get_server_tool_names("gcu-tools")
if gcu_tool_names:
for node in graph.nodes:
if node.node_type == "gcu":
existing = set(node.tools)
for tool_name in sorted(gcu_tool_names):
if tool_name not in existing:
node.tools.append(tool_name)
executor = make_executor(
runtime,
llm_provider,
tool_registry=tool_registry,
storage_path=tmp_path / "storage",
)
result = await executor.execute(
graph,
_gcu_goal(),
{
"task": "Use the browser to visit https://example.com and report "
"what domain the page is on."
},
validate_graph=False,
)
assert result.success
assert result.output.get("result") is not None
# The result should contain something from the browser
result_text = str(result.output["result"]).lower()
assert "example" in result_text
@@ -0,0 +1,166 @@
"""Parallel merge agent: fan-out to two branches, fan-in to merge node.
Tests parallel execution with real LLM at each branch.
"""
from __future__ import annotations
import pytest
from framework.graph.edge import EdgeCondition, EdgeSpec, GraphSpec
from framework.graph.executor import ParallelExecutionConfig
from framework.graph.node import NodeSpec
from .conftest import make_executor
from .nodes import FailNode
SET_OUTPUT_INSTRUCTION = (
"You MUST call the set_output tool to provide your answer. "
"Do not just write text — call set_output with the correct key and value."
)
def _build_parallel_graph() -> GraphSpec:
return GraphSpec(
id="parallel-graph",
goal_id="dummy",
entry_node="split",
entry_points={"start": "split"},
terminal_nodes=["merge"],
conversation_mode="continuous",
nodes=[
NodeSpec(
id="split",
name="Split",
description="Entry point that triggers parallel branches",
node_type="event_loop",
input_keys=["topic"],
output_keys=["split_done"],
system_prompt=(
"You are a dispatcher. Read the 'topic' input, then immediately "
"call set_output with key='split_done' and value='true'. "
+ SET_OUTPUT_INSTRUCTION
),
),
NodeSpec(
id="analyze_a",
name="Analyze Pros",
description="Analyzes positive aspects",
node_type="event_loop",
output_keys=["result_a"],
system_prompt=(
"Analyze the positive aspects of the topic. Then call set_output "
"with key='result_a' and a brief one-sentence analysis. "
+ SET_OUTPUT_INSTRUCTION
),
),
NodeSpec(
id="analyze_b",
name="Analyze Cons",
description="Analyzes negative aspects",
node_type="event_loop",
output_keys=["result_b"],
system_prompt=(
"Analyze the negative aspects of the topic. Then call set_output "
"with key='result_b' and a brief one-sentence analysis. "
+ SET_OUTPUT_INSTRUCTION
),
),
NodeSpec(
id="merge",
name="Merge",
description="Combines both analyses",
node_type="event_loop",
input_keys=["result_a", "result_b"],
output_keys=["merged"],
system_prompt=(
"Read 'result_a' and 'result_b' from the input, combine them into "
"a one-sentence summary, then call set_output with key='merged' "
"and the summary. " + SET_OUTPUT_INSTRUCTION
),
),
],
edges=[
EdgeSpec(
id="split-to-a",
source="split",
target="analyze_a",
condition=EdgeCondition.ON_SUCCESS,
),
EdgeSpec(
id="split-to-b",
source="split",
target="analyze_b",
condition=EdgeCondition.ON_SUCCESS,
),
EdgeSpec(
id="a-to-merge",
source="analyze_a",
target="merge",
condition=EdgeCondition.ON_SUCCESS,
),
EdgeSpec(
id="b-to-merge",
source="analyze_b",
target="merge",
condition=EdgeCondition.ON_SUCCESS,
),
],
memory_keys=["topic", "split_done", "result_a", "result_b", "merged"],
)
@pytest.mark.asyncio
async def test_parallel_both_succeed(runtime, goal, llm_provider):
graph = _build_parallel_graph()
config = ParallelExecutionConfig(on_branch_failure="fail_all")
executor = make_executor(runtime, llm_provider, parallel_config=config)
result = await executor.execute(graph, goal, {"topic": "remote work"}, validate_graph=False)
assert result.success
assert "split" in result.path
assert "merge" in result.path
assert result.output.get("merged") is not None
@pytest.mark.asyncio
async def test_parallel_branch_failure_fail_all(runtime, goal, llm_provider):
"""One branch fails with fail_all -> execution fails."""
graph = _build_parallel_graph()
config = ParallelExecutionConfig(on_branch_failure="fail_all")
executor = make_executor(runtime, llm_provider, parallel_config=config)
executor.register_node("analyze_b", FailNode(error="branch B failed"))
result = await executor.execute(graph, goal, {"topic": "remote work"}, validate_graph=False)
assert not result.success
@pytest.mark.asyncio
async def test_parallel_branch_failure_continue_others(runtime, goal, llm_provider):
"""One branch fails with continue_others -> surviving branch completes."""
graph = _build_parallel_graph()
config = ParallelExecutionConfig(on_branch_failure="continue_others")
executor = make_executor(runtime, llm_provider, parallel_config=config)
executor.register_node("analyze_b", FailNode(error="branch B failed"))
result = await executor.execute(graph, goal, {"topic": "remote work"}, validate_graph=False)
# With continue_others, execution can proceed past failed branches
assert result.output.get("merged") is not None or result.output.get("result_a") is not None
@pytest.mark.asyncio
async def test_parallel_disjoint_output_keys(runtime, goal, llm_provider):
"""Verify both branches write to separate memory keys without conflicts."""
graph = _build_parallel_graph()
executor = make_executor(runtime, llm_provider)
result = await executor.execute(
graph, goal, {"topic": "artificial intelligence"}, validate_graph=False
)
assert result.success
assert result.output.get("result_a") is not None
assert result.output.get("result_b") is not None
+134
View File
@@ -0,0 +1,134 @@
"""Pipeline agent: linear 3-node chain with real LLM at each step.
Tests input_mapping, conversation modes, and multi-node traversal.
"""
from __future__ import annotations
import pytest
from framework.graph.edge import EdgeCondition, EdgeSpec, GraphSpec
from framework.graph.node import NodeSpec
from .conftest import make_executor
SET_OUTPUT_INSTRUCTION = (
"You MUST call the set_output tool to provide your answer. "
"Do not just write text — call set_output with the correct key and value."
)
def _build_pipeline_graph(conversation_mode: str = "continuous") -> GraphSpec:
return GraphSpec(
id="pipeline-graph",
goal_id="dummy",
entry_node="intake",
entry_points={"start": "intake"},
terminal_nodes=["output"],
conversation_mode=conversation_mode,
nodes=[
NodeSpec(
id="intake",
name="Intake",
description="Captures raw input and passes it along",
node_type="event_loop",
input_keys=["raw"],
output_keys=["captured"],
system_prompt=(
"You are the intake node. Read the 'raw' input value from the user "
"message, then call set_output with key='captured' and the same value. "
+ SET_OUTPUT_INSTRUCTION
),
),
NodeSpec(
id="transform",
name="Transform",
description="Uppercases the input value",
node_type="event_loop",
input_keys=["value"],
output_keys=["transformed"],
system_prompt=(
"You are a transform node. Read the 'value' input from the user "
"message, convert it to UPPERCASE, then call set_output with "
"key='transformed' and the uppercased value. " + SET_OUTPUT_INSTRUCTION
),
),
NodeSpec(
id="output",
name="Output",
description="Formats final result",
node_type="event_loop",
input_keys=["value"],
output_keys=["result"],
system_prompt=(
"You are the output node. Read the 'value' input from the user "
"message, prefix it with 'Result: ', then call set_output with "
"key='result' and the prefixed value. " + SET_OUTPUT_INSTRUCTION
),
),
],
edges=[
EdgeSpec(
id="intake-to-transform",
source="intake",
target="transform",
condition=EdgeCondition.ON_SUCCESS,
input_mapping={"value": "captured"},
),
EdgeSpec(
id="transform-to-output",
source="transform",
target="output",
condition=EdgeCondition.ON_SUCCESS,
input_mapping={"value": "transformed"},
),
],
memory_keys=["raw", "captured", "value", "transformed", "result"],
)
@pytest.mark.asyncio
async def test_pipeline_linear_traversal(runtime, goal, llm_provider):
graph = _build_pipeline_graph()
executor = make_executor(runtime, llm_provider)
result = await executor.execute(graph, goal, {"raw": "hello"}, validate_graph=False)
assert result.success
assert result.path == ["intake", "transform", "output"]
assert result.steps_executed == 3
@pytest.mark.asyncio
async def test_pipeline_input_mapping(runtime, goal, llm_provider):
"""Verify input_mapping wires source output keys to target input keys."""
graph = _build_pipeline_graph()
executor = make_executor(runtime, llm_provider)
result = await executor.execute(graph, goal, {"raw": "test value"}, validate_graph=False)
assert result.success
assert result.steps_executed == 3
assert result.output.get("result") is not None
@pytest.mark.asyncio
async def test_pipeline_continuous_conversation(runtime, goal, llm_provider):
graph = _build_pipeline_graph(conversation_mode="continuous")
executor = make_executor(runtime, llm_provider)
result = await executor.execute(graph, goal, {"raw": "data"}, validate_graph=False)
assert result.success
assert len(result.path) == 3
@pytest.mark.asyncio
async def test_pipeline_isolated_conversation(runtime, goal, llm_provider):
graph = _build_pipeline_graph(conversation_mode="isolated")
executor = make_executor(runtime, llm_provider)
result = await executor.execute(graph, goal, {"raw": "data"}, validate_graph=False)
assert result.success
assert len(result.path) == 3
+131
View File
@@ -0,0 +1,131 @@
"""Retry agent: flaky node with retry limit and failure edges.
Uses deterministic FlakyNode (not LLM) since we need controlled failure patterns.
"""
from __future__ import annotations
import pytest
from framework.graph.edge import EdgeCondition, EdgeSpec, GraphSpec
from framework.graph.node import NodeSpec
from .conftest import make_executor
from .nodes import FlakyNode, SuccessNode
def _build_retry_graph(max_retries: int = 3, with_failure_edge: bool = False) -> GraphSpec:
nodes = [
NodeSpec(
id="flaky",
name="Flaky",
description="Fails then succeeds",
node_type="event_loop",
output_keys=["status"],
max_retries=max_retries,
),
NodeSpec(
id="done",
name="Done",
description="Terminal success node",
node_type="event_loop",
output_keys=["final"],
),
]
edges = [
EdgeSpec(
id="flaky-to-done",
source="flaky",
target="done",
condition=EdgeCondition.ON_SUCCESS,
),
]
terminal_nodes = ["done"]
if with_failure_edge:
nodes.append(
NodeSpec(
id="error_handler",
name="Error Handler",
description="Handles exhausted retries",
node_type="event_loop",
output_keys=["error_handled"],
)
)
edges.append(
EdgeSpec(
id="flaky-to-error",
source="flaky",
target="error_handler",
condition=EdgeCondition.ON_FAILURE,
)
)
terminal_nodes.append("error_handler")
return GraphSpec(
id="retry-graph",
goal_id="dummy",
entry_node="flaky",
terminal_nodes=terminal_nodes,
nodes=nodes,
edges=edges,
memory_keys=["status", "final", "error_handled"],
)
@pytest.mark.asyncio
async def test_retry_succeeds_within_limit(runtime, goal, llm_provider):
graph = _build_retry_graph(max_retries=3)
flaky = FlakyNode(fail_times=2, output={"status": "recovered"})
executor = make_executor(runtime, llm_provider)
executor.register_node("flaky", flaky)
executor.register_node("done", SuccessNode(output={"final": "complete"}))
result = await executor.execute(graph, goal, {}, validate_graph=False)
assert result.success
assert result.total_retries >= 2
assert flaky.attempt_count == 3 # 2 failures + 1 success
@pytest.mark.asyncio
async def test_retry_exhaustion(runtime, goal, llm_provider):
graph = _build_retry_graph(max_retries=3)
flaky = FlakyNode(fail_times=10, output={"status": "recovered"})
executor = make_executor(runtime, llm_provider)
executor.register_node("flaky", flaky)
executor.register_node("done", SuccessNode(output={"final": "complete"}))
result = await executor.execute(graph, goal, {}, validate_graph=False)
assert not result.success
@pytest.mark.asyncio
async def test_retry_with_on_failure_edge(runtime, goal, llm_provider):
graph = _build_retry_graph(max_retries=2, with_failure_edge=True)
flaky = FlakyNode(fail_times=10)
error_handler = SuccessNode(output={"error_handled": True})
executor = make_executor(runtime, llm_provider)
executor.register_node("flaky", flaky)
executor.register_node("done", SuccessNode(output={"final": "complete"}))
executor.register_node("error_handler", error_handler)
result = await executor.execute(graph, goal, {}, validate_graph=False)
assert "error_handler" in result.path
assert error_handler.executed
@pytest.mark.asyncio
async def test_retry_tracking(runtime, goal, llm_provider):
graph = _build_retry_graph(max_retries=3)
flaky = FlakyNode(fail_times=2)
executor = make_executor(runtime, llm_provider)
executor.register_node("flaky", flaky)
executor.register_node("done", SuccessNode(output={"final": "complete"}))
result = await executor.execute(graph, goal, {}, validate_graph=False)
assert result.success
assert result.retry_details.get("flaky", 0) >= 2
+139
View File
@@ -0,0 +1,139 @@
"""Worker agent: single-node event loop with real MCP tools.
Tests the core worker pattern a single EventLoopNode that uses real
hive-tools (example_tool, get_current_time, save_data/load_data) to
accomplish tasks, matching how real agents are structured.
"""
from __future__ import annotations
import pytest
from framework.graph.edge import GraphSpec
from framework.graph.goal import Goal
from framework.graph.node import NodeSpec
from .conftest import make_executor
def _build_worker_graph(tools: list[str]) -> GraphSpec:
"""Single-node worker agent with MCP tools — matches real agent structure."""
return GraphSpec(
id="worker-graph",
goal_id="worker-goal",
entry_node="worker",
entry_points={"start": "worker"},
terminal_nodes=["worker"],
nodes=[
NodeSpec(
id="worker",
name="Worker",
description="General-purpose worker with tools",
node_type="event_loop",
input_keys=["task"],
output_keys=["result"],
tools=tools,
system_prompt=(
"You are a worker agent with access to tools. "
"Read the 'task' input and complete it using the available tools. "
"When done, call set_output with key='result' and the final answer."
),
),
],
edges=[],
memory_keys=["task", "result"],
conversation_mode="continuous",
)
def _worker_goal() -> Goal:
return Goal(
id="worker-goal",
name="Worker Agent",
description="Complete a task using available tools",
)
@pytest.mark.asyncio
async def test_worker_example_tool(runtime, llm_provider, tool_registry):
"""Worker uses example_tool to process text."""
graph = _build_worker_graph(tools=["example_tool"])
executor = make_executor(runtime, llm_provider, tool_registry=tool_registry)
result = await executor.execute(
graph,
_worker_goal(),
{"task": "Use the example_tool to process the message 'hello world' with uppercase=true"},
validate_graph=False,
)
assert result.success
assert result.output.get("result") is not None
@pytest.mark.asyncio
async def test_worker_time_tool(runtime, llm_provider, tool_registry):
"""Worker uses get_current_time to check the current time."""
graph = _build_worker_graph(tools=["get_current_time"])
executor = make_executor(runtime, llm_provider, tool_registry=tool_registry)
result = await executor.execute(
graph,
_worker_goal(),
{
"task": "Use get_current_time to find the current time in UTC, "
"and report the day of the week as the result"
},
validate_graph=False,
)
assert result.success
assert result.output.get("result") is not None
@pytest.mark.asyncio
async def test_worker_data_tools(runtime, llm_provider, tool_registry, tmp_path):
"""Worker uses save_data and load_data to store and retrieve data."""
graph = _build_worker_graph(tools=["save_data", "load_data"])
executor = make_executor(
runtime,
llm_provider,
tool_registry=tool_registry,
storage_path=tmp_path / "storage",
)
result = await executor.execute(
graph,
_worker_goal(),
{
"task": f"Use save_data to save the text 'test payload' to a file called "
f"'test.txt' in the data_dir '{tmp_path}/data'. "
f"Then use load_data to read it back from the same data_dir. "
f"Report what you loaded as the result."
},
validate_graph=False,
)
assert result.success
assert result.output.get("result") is not None
@pytest.mark.asyncio
async def test_worker_multi_tool(runtime, llm_provider, tool_registry):
"""Worker uses multiple tools in sequence."""
graph = _build_worker_graph(tools=["example_tool", "get_current_time"])
executor = make_executor(runtime, llm_provider, tool_registry=tool_registry)
result = await executor.execute(
graph,
_worker_goal(),
{
"task": "First use get_current_time to find the current day of the week. "
"Then use example_tool to process that day name with uppercase=true. "
"Report the uppercased day name as the result."
},
validate_graph=False,
)
assert result.success
assert result.output.get("result") is not None
-171
View File
@@ -1,171 +0,0 @@
#!/usr/bin/env python3
"""
Verification script for Aden Hive Framework MCP Server
This script checks if the MCP server is properly installed and configured.
"""
import json
import logging
import subprocess
import sys
from pathlib import Path
logger = logging.getLogger(__name__)
def setup_logger():
"""Configure logger for CLI usage."""
if not logger.handlers:
handler = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter("%(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.INFO)
class Colors:
GREEN = "\033[0;32m"
YELLOW = "\033[1;33m"
RED = "\033[0;31m"
BLUE = "\033[0;34m"
NC = "\033[0m"
def check(description: str) -> bool:
"""Print check description and return a context manager for result."""
logger.info(f"Checking {description}... ", extra={"end": ""})
sys.stdout.flush()
return True
def success(msg: str = "OK"):
"""Log success message."""
logger.info(f"{Colors.GREEN}{msg}{Colors.NC}")
def warning(msg: str):
"""Log warning message."""
logger.warning(f"{Colors.YELLOW}{msg}{Colors.NC}")
def error(msg: str):
"""Log error message."""
logger.error(f"{Colors.RED}{msg}{Colors.NC}")
def main():
"""Run verification checks."""
setup_logger()
logger.info("=== MCP Server Verification ===")
logger.info("")
script_dir = Path(__file__).parent.absolute()
all_checks_passed = True
# Check 1: Framework package installed
check("framework package installation")
try:
result = subprocess.run(
[sys.executable, "-c", "import framework; print(framework.__file__)"],
capture_output=True,
text=True,
check=True,
encoding="utf-8",
)
framework_path = result.stdout.strip()
success(f"installed at {framework_path}")
except subprocess.CalledProcessError:
error("framework package not found")
logger.info(f" Run: uv pip install -e {script_dir}")
all_checks_passed = False
# Check 2: MCP dependencies
check("MCP dependencies")
missing_deps = []
for dep in ["mcp", "fastmcp"]:
try:
subprocess.run(
[sys.executable, "-c", f"import {dep}"],
capture_output=True,
check=True,
encoding="utf-8",
)
except subprocess.CalledProcessError:
missing_deps.append(dep)
if missing_deps:
error(f"missing: {', '.join(missing_deps)}")
logger.info(f" Run: uv pip install {' '.join(missing_deps)}")
all_checks_passed = False
else:
success("all installed")
# Check 3: MCP configuration file
check("MCP configuration file")
mcp_config = script_dir / ".mcp.json"
if mcp_config.exists():
try:
with open(mcp_config, encoding="utf-8") as f:
config = json.load(f)
if "mcpServers" in config:
success("found and valid")
for name, server_config in config.get("mcpServers", {}).items():
logger.info(f" Server: {name}")
logger.info(f" Command: {server_config.get('command')}")
logger.info(f" Args: {' '.join(server_config.get('args', []))}")
else:
warning("exists but missing mcpServers config")
all_checks_passed = False
except json.JSONDecodeError:
error("invalid JSON format")
all_checks_passed = False
else:
warning("not found (optional)")
logger.info(f" Location would be: {mcp_config}")
# Check 4: Framework modules
check("core framework modules")
modules_to_check = [
"framework.runtime.core",
"framework.graph.executor",
"framework.graph.node",
"framework.builder.query",
"framework.llm",
]
failed_modules = []
for module in modules_to_check:
try:
subprocess.run(
[sys.executable, "-c", f"import {module}"],
capture_output=True,
check=True,
encoding="utf-8",
)
except subprocess.CalledProcessError:
failed_modules.append(module)
if failed_modules:
error(f"failed to import: {', '.join(failed_modules)}")
all_checks_passed = False
else:
success(f"all {len(modules_to_check)} modules OK")
logger.info("")
logger.info("=" * 40)
if all_checks_passed:
logger.info(f"{Colors.GREEN}✓ All checks passed!{Colors.NC}")
logger.info("")
logger.info("Your framework is ready to use.")
else:
logger.info(f"{Colors.RED}✗ Some checks failed{Colors.NC}")
logger.info("")
logger.info("To fix issues, run:")
logger.info(f" uv run python {script_dir / 'setup_mcp.py'}")
logger.info("")
if __name__ == "__main__":
main()
-201
View File
@@ -1,201 +0,0 @@
# Antigravity IDE Setup
Use the Hive agent framework (MCP servers and skills) inside [Antigravity IDE](https://antigravity.google/) (Googles AI IDE).
---
## Quick start (3 steps)
**Repo root** = the folder that contains `core/`, `tools/`, and `.agent/` (where you cloned the project).
1. **Open a terminal** and go to the hive repo root (e.g. `cd ~/hive`).
2. **Run the setup script** (use `./` so the script runs from this repo; don't use `/scripts/...`):
```bash
./scripts/setup-antigravity-mcp.sh
```
3. **Restart Antigravity IDE.** You should see **coder-tools** and **tools** as available MCP servers.
> **Important:** Always restart/refresh Antigravity IDE after running the setup script or making any changes to MCP configuration. The IDE only loads MCP servers on startup.
Done. For details, prerequisites, and troubleshooting, read on.
---
## What you get after setup
- **coder-tools** Create and manage agents (scaffolding via `initialize_and_build_agent`, file I/O, tool discovery).
- **tools** File operations, web search, and other agent tools.
- **Documentation** Guided docs for building and testing agents.
---
## Prerequisites
- [Antigravity IDE](https://antigravity.google/) installed.
- **Python 3.11+** and project dependencies. If you havent set up the repo yet, from repo root run:
```bash
./quickstart.sh
```
- **MCP server dependencies** (one-time). From repo root:
```bash
cd core && ./setup_mcp.sh
```
---
## Full setup (step by step)
### Step 1: Install MCP dependencies (one-time)
From the **repo root**:
```bash
cd core
./setup_mcp.sh
```
This installs the framework and MCP packages and checks that the server can start.
### Step 2: Register MCP servers with Antigravity
Antigravity reads MCP config from your **user config file** (`~/.gemini/antigravity/mcp_config.json`), not from the project. The easiest way is to run the setup script from the **hive repo folder**:
```bash
./scripts/setup-antigravity-mcp.sh
```
The script finds the repo root, writes `~/.gemini/antigravity/mcp_config.json` with the right paths, and you don't edit any paths by hand.
> **Important:** Always restart/refresh Antigravity IDE after running the setup script. MCP servers are only loaded on IDE startup.
The **coder-tools** and **tools** servers should show up after restart.
**Using Claude Code instead?** Run:
```bash
./scripts/setup-antigravity-mcp.sh --claude
```
That writes `~/.claude/mcp.json` as well.
**Prefer to do it manually?** See [Manual MCP config](#manual-mcp-config-template) below. Youll create `~/.gemini/mcp.json` (or `~/.claude/mcp.json`) with absolute paths to your repos `core` and `tools` folders.
### Step 3: Use MCP tools + docs
Use the `coder-tools` and `tools` MCP servers in Antigravity, and use docs in `docs/` for workflow guidance.
---
## Whats in the repo (`.agent/`)
```
.agent/
├── mcp_config.json # Template for MCP servers (coder-tools, tools)
```
The **setup script** writes your **user** config (`~/.gemini/antigravity/mcp_config.json`) using paths from **this repo**. The file in `.agent/` is the template; Antigravity itself uses the file in your home directory.
---
## Troubleshooting
**MCP servers dont connect**
- Run the setup script again from the hive repo root: `./scripts/setup-antigravity-mcp.sh`, then restart Antigravity.
- Make sure Python and deps are installed: from repo root run `./quickstart.sh`.
- Check that the servers can start: from repo root run
`cd tools && uv run coder_tools_server.py --stdio` (Ctrl+C to stop), and in another terminal
`cd tools && uv run mcp_server.py --stdio` (Ctrl+C to stop).
If those fail, fix the errors first (e.g. install deps with `uv sync`).
**"Module not found" or import errors**
- Open the **repo root** as the project in the IDE (the folder that has `core/` and `tools/`).
- If you edited `~/.gemini/antigravity/mcp_config.json` by hand, make sure `--directory` paths are **absolute** (e.g. `/Users/you/hive/core` and `/Users/you/hive/tools`).
**MCP tools dont show up in the UI**
- Antigravity may need a restart. Use the files in `docs/` as documentation; the MCP tools (`coder-tools`, `tools`) are the required integration point.
---
## Verification prompt (optional)
Paste this into Antigravity to check that MCP is set up. It doesnt use your machines paths; anyone can use it.
```
Check the Hive + Antigravity integration:
1. MCP: List available MCP servers/tools. Confirm that "coder-tools" and "tools" (or equivalent) are connected. If not, tell the user to run ./scripts/setup-antigravity-mcp.sh from the hive repo root, then restart Antigravity (see docs/antigravity-setup.md).
2. Docs: Confirm that the project has `docs/` with setup/developer guides for the workflow.
3. Result: Reply with PASS (MCP OK), PARTIAL (some MCP tools missing), or FAIL (MCP unavailable), and one line on what to fix if not PASS.
```
If you get **PARTIAL** (e.g. MCP not connected), run `./scripts/setup-antigravity-mcp.sh` from the repo root and restart Antigravity.
---
## Manual MCP config template
Use this only if you dont want to run the setup script. Replace `/path/to/hive` with your actual repo root (e.g. the output of `pwd` when youre in the hive folder).
Save as `~/.gemini/antigravity/mcp_config.json` (Antigravity) or `~/.claude/mcp.json` (Claude Code), then **restart the IDE** to load the new configuration.
```json
{
"mcpServers": {
"coder-tools": {
"command": "uv",
"args": ["run", "--directory", "/path/to/hive/tools", "coder_tools_server.py", "--stdio"],
"disabled": false
},
"tools": {
"command": "uv",
"args": ["run", "--directory", "/path/to/hive/tools", "mcp_server.py", "--stdio"],
"disabled": false
}
}
}
```
Make sure `uv` is installed and available in your PATH. Note: Use `--directory` in args instead of `cwd` for Antigravity compatibility.
---
## Verify from the command line (optional)
From the **repo root**:
**Check that config exists**
```bash
test -f .agent/mcp_config.json && echo "OK: mcp_config.json" || echo "MISSING"
```
**Check that the config is valid JSON**
```bash
python3 -c "import json; json.load(open('.agent/mcp_config.json')); print('OK: valid JSON')"
```
**Test that MCP servers start** (two terminals)
```bash
# Terminal 1
cd tools && uv run coder_tools_server.py --stdio
# Terminal 2
cd tools && uv run mcp_server.py --stdio
```
If both start without errors, the config is fine.
---
## See also
- [Cursor IDE support](../README.md#cursor-ide-support) Same MCP servers and skills for Cursor
- [MCP Integration Guide](../core/MCP_INTEGRATION_GUIDE.md) How the framework MCP works
- [Environment setup](../ENVIRONMENT_SETUP.md) Repo and Python setup
+63 -2
View File
@@ -1,6 +1,6 @@
# Integration Bounty Program
# Bounty Program
Earn XP, Discord roles, and money by testing, documenting, and building integrations for the Aden agent framework.
Earn XP, Discord roles, and money by contributing to the Aden agent framework — from quick fixes to major features, plus integration testing and development.
## Why Contribute?
@@ -33,6 +33,10 @@ Lurkr auto-assigns the first two roles. Core Contributor requires sustained, qua
## Bounty Types
### Integration Bounties
Focused on the tool ecosystem — testing, documenting, and building integrations.
| Type | Label | Points | What You Do |
| --------------------- | ----------------- | ------ | -------------------------------------------------------------------------- |
| **Test a tool** | `bounty:test` | 20 | Test with a real API key, submit a report with logs |
@@ -42,6 +46,47 @@ Lurkr auto-assigns the first two roles. Core Contributor requires sustained, qua
Promoting a tool from unverified to verified is the final step — submit a PR moving it from `_register_unverified()` to `_register_verified()` after the [promotion checklist](promotion-checklist.md) is complete.
### Standard Bounties
General contributions to the framework, docs, tests, and infrastructure — not tied to a specific integration.
| Size | Label | Points | Scope |
| ------------ | ------------------ | ------ | ---------------------------------------------------------------------------------- |
| **Small** | `bounty:small` | 10 | Typo fixes, broken links, error message improvements, confirm/reproduce bug reports |
| **Medium** | `bounty:medium` | 30 | Bug fixes, new or improved unit tests, how-to guides, CLI UX improvements |
| **Large** | `bounty:large` | 75 | New features, performance optimizations with benchmarks, architecture docs |
| **Extreme** | `bounty:extreme` | 150 | Major subsystem work, security audits, cross-cutting refactors, new core capabilities |
#### Examples by size
**Small (10 pts):**
- Fix typos or broken links in documentation
- Improve an error message to include actionable guidance
- Add missing type annotations to a module
- Reproduce and confirm an open bug report with environment details
- Fix linting or CI warnings
**Medium (30 pts):**
- Fix a non-critical bug with a regression test
- Write a how-to guide or tutorial for a common workflow
- Add or significantly improve test coverage for a core module
- Improve CLI help text, argument validation, or UX
- Add structured logging or observability to a module
**Large (75 pts):**
- Implement a new user-facing feature end to end
- Performance optimization with before/after benchmarks
- Build a new CLI command or subcommand
- Write comprehensive architecture documentation for a subsystem
- Add a new credential adapter type
**Extreme (150 pts):**
- Design and implement a major subsystem (e.g., plugin system, caching layer)
- Security audit of a core module with findings and fixes
- Major refactor of core architecture (must have maintainer pre-approval)
- Build a complete example application or reference implementation
- End-to-end testing framework for agent workflows
## Quality Gates
- **PRs** must be merged by a maintainer (not self-merged)
@@ -52,12 +97,28 @@ Promoting a tool from unverified to verified is the final step — submit a PR m
## Labels
### Integration bounty labels
| Label | Color | Meaning |
| ------------------- | ------------------ | --------------------------------------- |
| `bounty:test` | `#1D76DB` (blue) | Test a tool with a real API key |
| `bounty:docs` | `#FBCA04` (yellow) | Write or improve documentation |
| `bounty:code` | `#D93F0B` (orange) | Health checker, bug fix, or improvement |
| `bounty:new-tool` | `#6F42C1` (purple) | Build a new integration from scratch |
### Standard bounty labels
| Label | Color | Meaning |
| ------------------- | ------------------ | -------------------------------------------------- |
| `bounty:small` | `#C2E0C6` (green) | Quick fix — typos, links, error messages |
| `bounty:medium` | `#0E8A16` (green) | Bug fix, tests, guides, CLI improvements |
| `bounty:large` | `#B60205` (red) | New feature, perf work, architecture docs |
| `bounty:extreme` | `#000000` (black) | Major subsystem, security audit, core refactor |
### Difficulty labels
| Label | Color | Meaning |
| ------------------- | ------------------ | --------------------------------------- |
| `difficulty:easy` | `#BFD4F2` | Good first contribution |
| `difficulty:medium` | `#D4C5F9` | Requires some familiarity |
| `difficulty:hard` | `#F9D0C4` | Significant effort or expertise needed |
+66 -6
View File
@@ -1,6 +1,6 @@
# Contributor Guide — Integration Bounty Program
# Contributor Guide — Bounty Program
Earn XP, Discord roles, and eventually real money by testing and building integrations for the Aden agent framework.
Earn XP, Discord roles, and eventually real money by contributing to the Aden agent framework — from quick fixes to major features and integration work.
## Getting Started
@@ -30,7 +30,13 @@ XP comes from GitHub bounties (auto-pushed on PR merge) and Discord activity in
## Bounty Types
### Test a Tool (20 pts)
There are two categories: **integration bounties** (tool-specific) and **standard bounties** (general contributions).
---
### Integration Bounties
#### Test a Tool (20 pts)
Test an unverified tool with a real API key and report what happens.
@@ -41,7 +47,7 @@ Test an unverified tool with a real API key and report what happens.
Report both successes and failures. Finding bugs is valuable.
### Write Docs (20 pts)
#### Write Docs (20 pts)
Write a README for a tool that's missing one.
@@ -52,7 +58,7 @@ Write a README for a tool that's missing one.
Function names and API URLs must match reality — no AI hallucinations.
### Code Contribution (30 pts)
#### Code Contribution (30 pts)
Add a health checker, fix a bug, or improve an integration.
@@ -66,7 +72,7 @@ Add a health checker, fix a bug, or improve an integration.
1. Find a bug during testing, file an issue
2. Fix it in a PR with a test covering the bug
### New Integration (75 pts)
#### New Integration (75 pts)
Build a complete integration from scratch.
@@ -77,6 +83,60 @@ Build a complete integration from scratch.
Expect multiple review rounds.
---
### Standard Bounties
General contributions to the framework — not tied to a specific integration. Sized by effort and impact.
#### Small (10 pts)
Quick, focused fixes. Great for first-time contributors.
- Fix typos or broken links in documentation
- Improve an error message to include actionable guidance
- Add missing type annotations to a module
- Reproduce and confirm a bug report with environment details
- Fix linting or CI warnings
**How:** Open a PR with the fix. Tag with `bounty:small`.
#### Medium (30 pts)
Meaningful improvements that require reading and understanding existing code.
- Fix a non-critical bug with a regression test
- Write a how-to guide or tutorial
- Add or significantly improve test coverage for a core module
- Improve CLI help text, argument validation, or UX
- Add structured logging or observability to a module
**How:** Claim the issue first. Submit a PR with tests where applicable. Tag with `bounty:medium`.
#### Large (75 pts)
Significant work that adds real capability or improves the project substantially.
- Implement a new user-facing feature end to end
- Performance optimization with before/after benchmarks
- Build a new CLI command or subcommand
- Write comprehensive architecture documentation for a subsystem
- Add a new credential adapter type
**How:** Claim the issue and discuss your approach in the issue before starting. Submit a PR. Tag with `bounty:large`.
#### Extreme (150 pts)
Major contributions that shape the project's direction. Requires maintainer pre-approval.
- Design and implement a major subsystem (e.g., plugin system, caching layer)
- Security audit of a core module with findings and fixes
- Major refactor of core architecture
- Build a complete example application or reference implementation
- End-to-end testing framework for agent workflows
**How:** Comment on the issue with a design proposal. Wait for maintainer approval before starting work. Tag with `bounty:extreme`.
## Rules
1. **Claim before you start** — comment on the issue, wait for assignment
+37 -1
View File
@@ -27,7 +27,7 @@ When someone comments "I'd like to work on this":
5. Merge — the GitHub Action auto-awards XP and posts to Discord
6. Close the linked bounty issue
### Quality Gates
### Quality Gates — Integration Bounties
**`bounty:docs`:**
- [ ] Follows the [tool README template](templates/tool-readme-template.md)
@@ -51,6 +51,31 @@ When someone comments "I'd like to work on this":
- [ ] `make check && make test` passes
- [ ] Registered in `_register_unverified()` (not verified)
### Quality Gates — Standard Bounties
**`bounty:small`:**
- [ ] Change is correct and doesn't introduce regressions
- [ ] CI passes
- [ ] Scope matches "small" — not padded into a bigger change
**`bounty:medium`:**
- [ ] CI passes
- [ ] Bug fixes include a regression test
- [ ] Docs/guides are accurate and follow existing style
- [ ] Not AI-generated without verification
**`bounty:large`:**
- [ ] Design was discussed in the issue before implementation
- [ ] CI passes, new tests cover the change
- [ ] Benchmarks included for performance work (before/after)
- [ ] Architecture docs reviewed by a second maintainer
**`bounty:extreme`:**
- [ ] Maintainer pre-approved the design proposal before work began
- [ ] CI passes, comprehensive test coverage
- [ ] Documentation updated to reflect the change
- [ ] Reviewed by at least two maintainers
### Rejecting Submissions
1. Leave specific, constructive feedback
@@ -78,6 +103,8 @@ If a Core Contributor is inactive 8+ weeks, reach out privately first, then remo
Post dollar values in `#bounty-payouts` (Core Contributors only):
### Integration bounties
| Bounty Type | Dollar Range |
|-------------|-------------|
| `bounty:test` | $1030 |
@@ -85,6 +112,15 @@ Post dollar values in `#bounty-payouts` (Core Contributors only):
| `bounty:code` | $2050 |
| `bounty:new-tool` | $50150 |
### Standard bounties
| Bounty Type | Dollar Range |
|-------------|-------------|
| `bounty:small` | $515 |
| `bounty:medium` | $2050 |
| `bounty:large` | $50150 |
| `bounty:extreme` | $150500 |
**Payout:** PR merged → verify quality → record in `#bounty-payouts` → process payment.
XP is always awarded regardless of budget. Money is a bonus layer.
+1 -1
View File
@@ -14,7 +14,7 @@ Complete setup from zero to running. Estimated time: 30 minutes.
./scripts/setup-bounty-labels.sh
```
This creates 7 labels: 4 bounty types (`bounty:test`, `bounty:docs`, `bounty:code`, `bounty:new-tool`) and 3 difficulty levels (`difficulty:easy`, `difficulty:medium`, `difficulty:hard`).
This creates 11 labels: 4 integration bounty types (`bounty:test`, `bounty:docs`, `bounty:code`, `bounty:new-tool`), 4 standard bounty sizes (`bounty:small`, `bounty:medium`, `bounty:large`, `bounty:extreme`), and 3 difficulty levels (`difficulty:easy`, `difficulty:medium`, `difficulty:hard`).
## Step 2: Create Discord Channels (3 min)
-4
View File
@@ -102,10 +102,6 @@ The repository includes a `.claude/settings.json` hook that automatically runs `
The `.cursorrules` file at the repo root tells Cursor's AI the project's style rules (line length, import order, quote style, etc.) so generated code follows convention.
### Antigravity IDE
Antigravity IDE (Google's AI-powered IDE) is supported via `.antigravity/mcp_config.json`. See [antigravity-setup.md](antigravity-setup.md) for setup and troubleshooting.
### Codex CLI
Codex CLI (OpenAI, v0.101.0+) is supported via `.codex/config.toml` (MCP server config). This file is tracked in git. Run `codex` in the repo root to use the configured MCP tools. See the [Codex CLI section in the README](../README.md#codex-cli) for details.
+580
View File
@@ -0,0 +1,580 @@
# MCP Server Registry — Product & Business Requirements Document
**Status**: Draft v2
**Last updated**: 2026-03-13
**Authors**: Timothy
**Reviewers**: Platform, Product, OSS/Community, Security
---
## 1. Executive Summary
This document proposes an **MCP Server Registry** system that enables open-source contributors and Hive users to discover, publish, install, and manage MCP (Model Context Protocol) servers for use with Hive agents.
Today, MCP server configuration is static, duplicated across agents, and limited to servers that Hive spawns as subprocesses. This makes it impractical for users who run their own MCP servers on the same host, and impossible for the community to contribute standalone MCP integrations without modifying Hive internals.
The registry consists of three components:
1. **A public GitHub repository** (`hive-mcp-registry`) — a curated index where contributors submit MCP server entries via pull request
2. **Local registry tooling** — CLI commands and a `~/.hive/mcp_registry/` directory for installing, managing, and connecting to MCP servers
3. **Framework integration** — changes to Hive's `ToolRegistry`, `MCPClient`, and agent runner so agents can flexibly select which registry servers they need
---
## 2. Problem Statement
### 2.1 Current State
- Each Hive agent has a static `mcp_servers.json` file that hardcodes MCP server connection details.
- All 150+ tools live in a single monolithic `mcp_server.py` — contributors add tools to this one server.
- There is no mechanism for standalone MCP servers (e.g., a Jira MCP, a Notion MCP, or a custom database MCP) to be discovered or used by Hive agents.
- Each agent spawns its own MCP subprocess — no connection sharing across agents.
- Only `stdio` and basic `http` transports are supported. No unix sockets, no SSE, no reconnection.
- External MCP servers already running on the host cannot be easily registered.
### 2.2 Who Is Affected
| Persona | Pain Point |
|---|---|
| **OSS contributor** | Wants to publish a standalone MCP server for the Hive ecosystem but has no pathway to do so without modifying Hive core |
| **Self-hosted user** | Runs multiple MCP servers on the same host (Slack, GitHub, database tools) and wants Hive agents to discover them |
| **Agent builder** | Copies the same `mcp_servers.json` boilerplate across every agent; no way to say "use whatever the user has installed" |
| **Platform team** | Cannot manage MCP servers centrally; each agent manages its own connections independently |
### 2.3 Impact of Not Solving
- The Hive MCP ecosystem remains closed — growth depends entirely on tools being added to the monolithic server.
- Users with existing MCP infrastructure (from Claude Desktop, Cursor, or other MCP-compatible tools) cannot leverage it with Hive.
- Resource waste from duplicate subprocess spawning across agents.
- No path to community-contributed integrations beyond the core tool set.
---
## 3. Goals & Success Criteria
### 3.1 Primary Goals
| # | Goal | Metric |
|---|---|---|
| G1 | A contributor can register a new MCP server in under 5 minutes | Time from fork to PR submission |
| G2 | A user can install and use a registry MCP server in under 2 minutes | Time from `hive mcp install X` to first tool call |
| G3 | Agents can dynamically select MCP servers by name or tag without hardcoding configs | Agents use `mcp_registry.json` selectors instead of full server configs |
| G4 | Multiple agents share MCP connections instead of duplicating them | One subprocess/connection per unique server, not per agent |
| G5 | External MCP servers already running on the host can be registered with a single command | `hive mcp add --name X --url http://...` works end-to-end |
| G6 | Zero breaking changes to existing agent configurations | All current `mcp_servers.json` files continue to work unchanged |
### 3.2 Developer Success Goals
| # | Goal | Metric |
|---|---|---|
| G7 | First-install success rate exceeds 90% | Successful `hive mcp install` / total attempts (tracked via CLI telemetry opt-in) |
| G8 | First-tool-call success rate exceeds 85% after install | Successful tool invocation within 5 minutes of install |
| G9 | Users can self-diagnose and resolve config/auth issues without filing support tickets | Median time from error to resolution <5 minutes; support ticket volume per server <1/month |
| G10 | Registry entries remain healthy over time | % of entries passing automated health validation at 30/60/90 days |
| G11 | Server upgrades do not silently break agents | Zero undetected tool-signature changes on upgrade |
### 3.3 Non-Goals (Explicit Exclusions)
- **Billing or monetization** — the registry is free and open-source.
- **Hosting MCP servers** — the registry only stores metadata; actual servers are installed/run by users.
- **Replacing `mcp_servers.json`** — the static config remains for backward compatibility and offline use.
- **Runtime agent-to-agent MCP sharing** — this is about discovery and connection, not inter-agent protocol.
- **Decomposing the monolithic `mcp_server.py`** — this is a future phase, not part of the initial build.
---
## 4. User Stories
### 4.1 Contributor: Publishing an MCP Server
> As an OSS contributor who has built a Jira MCP server, I want to register it in a public registry so that any Hive user can install and use it without modifying Hive code.
**Acceptance criteria:**
- `hive mcp init` scaffolds a manifest with my server's details pre-filled from introspection.
- `hive mcp validate ./manifest.json` passes locally before I open a PR.
- `hive mcp test ./manifest.json` starts my server, lists tools, calls a health check, and reports pass/fail.
- CI validates my manifest automatically (schema, naming, required fields, package existence).
- After merge, the server appears in `hive mcp search` for all users.
### 4.2 User: Installing an MCP Server from the Registry
> As a Hive user, I want to install a community MCP server and have my agents use it immediately.
**Acceptance criteria:**
- `hive mcp install jira` fetches the manifest and configures the server locally.
- If credentials are required, the CLI prompts me: "Jira requires JIRA_API_TOKEN (get one at https://...). Enter value:"
- `hive mcp health jira` confirms the server is reachable and tools are discoverable.
- My queen agent (with `auto_discover: true`) automatically picks up the new server's tools.
- `hive mcp info jira` shows trust tier, last health check, installed version, and loaded tools.
### 4.3 User: Registering a Local/Running MCP Server
> As a user running a custom database MCP server on `localhost:9090`, I want Hive agents to use it without publishing it to any public registry.
**Acceptance criteria:**
- `hive mcp add --name my-db --transport http --url http://localhost:9090` registers it.
- The server appears in `hive mcp list` and is available to agents that include it.
- If the server goes down, Hive logs a warning with actionable next steps and retries on next tool call.
### 4.4 Agent Builder: Selecting MCP Servers for a Worker
> As an agent builder, I want my worker agent to use specific MCP servers (e.g., Slack + Jira) without hardcoding connection details.
**Acceptance criteria:**
- I create `mcp_registry.json` in my agent directory with `{"include": ["slack", "jira"]}`.
- At runtime, the agent automatically connects to whatever Slack and Jira servers the user has installed.
- If a requested server isn't installed, startup logs explain: "Server 'jira' requested by mcp_registry.json but not installed. Run: hive mcp install jira"
### 4.5 Queen: Auto-Discovering Available MCP Servers
> As the queen agent, I want access to installed MCP servers so I can delegate tasks that require any tool.
**Acceptance criteria:**
- Queen's `mcp_registry.json` uses `{"profile": "all"}` to load all enabled servers.
- Startup logs list every loaded server and its tool count: "Loaded 3 registry servers: jira (4 tools), slack (6 tools), my-db (2 tools)"
- If tool names collide across servers, the resolution is deterministic and logged.
- Queen respects a configurable max tool budget to avoid prompt overload.
### 4.6 User: Diagnosing a Broken MCP Server
> As a user whose agent suddenly can't call Jira tools, I want to quickly find and fix the problem.
**Acceptance criteria:**
- `hive mcp doctor` checks all installed servers and reports: connection status, credential validity, tool discovery result, last error.
- `hive mcp doctor jira` gives detailed diagnostics: "jira: UNHEALTHY. Transport: stdio. Error: Process exited with code 1. Stderr: 'JIRA_API_TOKEN not set'. Fix: hive mcp config jira --set JIRA_API_TOKEN=your-token"
- `hive mcp inspect jira` shows the resolved config, override chain, and which agents include it.
- `hive mcp why-not jira --agent exports/my-agent` explains why a server was or was not loaded for an agent.
---
## 5. Requirements
### 5.1 Functional Requirements
#### 5.1.1 Registry Repository
| ID | Requirement | Priority |
|---|---|---|
| FR-1 | The registry is a public GitHub repo with a defined directory structure for server entries | P0 |
| FR-2 | Each server entry is a `manifest.json` file conforming to a JSON Schema | P0 |
| FR-3 | CI validates manifests on every PR (schema, naming, uniqueness, required fields) | P0 |
| FR-4 | A flat index (`registry_index.json`) is auto-generated on merge for client consumption | P0 |
| FR-5 | A `_template/` directory provides a starter manifest + README for contributors | P0 |
| FR-6 | `CONTRIBUTING.md` documents the 5-minute submission process with annotated examples for each transport type (stdio, http, unix, sse) | P0 |
| FR-7 | CI checks that `install.pip` packages exist on PyPI (if specified) | P1 |
| FR-8 | Tags follow a controlled taxonomy with new tags requiring maintainer approval | P1 |
| FR-9 | Canonical example manifests are provided for each transport type in `registry/_examples/` | P0 |
#### 5.1.2 Manifest Schema
The manifest has a **portable base layer** (framework-agnostic, usable by any MCP client) and an optional **hive extension block** (Hive-specific ergonomics).
| ID | Requirement | Priority |
|---|---|---|
| FR-10 | Manifest base includes: name, display_name, version, description, author, repository, license | P0 |
| FR-11 | Manifest declares supported transports (stdio, http, unix, sse) with default | P0 |
| FR-12 | Manifest includes install instructions (pip package name, docker image, npm package) | P0 |
| FR-13 | Manifest lists tool names and descriptions (for pre-connect filtering) | P0 |
| FR-14 | Manifest declares credential requirements (env_var, description, help_url, required flag) | P0 |
| FR-15 | Manifest includes tags and categories for discovery | P1 |
| FR-16 | Manifest supports template variables (`{port}`, `{socket_path}`, `{name}`) in commands | P1 |
| FR-17 | Manifest includes `hive` extension block for Hive-specific metadata (see 5.1.8) | P1 |
#### 5.1.3 Manifest Trust & Quality Metadata
| ID | Requirement | Priority |
|---|---|---|
| FR-80 | Manifest includes `status` field: `official`, `verified`, or `community` | P0 |
| FR-81 | Manifest includes `maintainer` contact (email or GitHub handle) | P0 |
| FR-82 | Manifest includes `docs_url` pointing to server documentation | P1 |
| FR-83 | Manifest includes `example_agent_url` linking to an example agent using this server | P2 |
| FR-84 | Manifest includes `supported_os` list (e.g., `["linux", "macos", "windows"]`) | P1 |
| FR-85 | Manifest includes `deprecated` boolean and `deprecated_by` field for superseded entries | P1 |
| FR-86 | Registry index includes `last_validated_at` timestamp per entry (from automated CI health runs) | P1 |
#### 5.1.4 Local Registry
| ID | Requirement | Priority |
|---|---|---|
| FR-20 | `~/.hive/mcp_registry/installed.json` tracks all installed/registered servers | P0 |
| FR-21 | Servers can be sourced from the remote registry (`"source": "registry"`) or local (`"source": "local"`) | P0 |
| FR-22 | Each installed server has: transport preference, enabled/disabled state, and env/header overrides | P0 |
| FR-23 | The remote registry index is cached locally with configurable refresh interval | P1 |
| FR-24 | Each installed server tracks operational state: `last_health_check_at`, `last_health_status`, `last_error`, `last_used_at`, `resolved_package_version` | P1 |
| FR-25 | Each installed server supports `pinned: true` to prevent auto-update and `auto_update: true` for automatic version tracking | P1 |
#### 5.1.5 CLI Commands — Management
| ID | Requirement | Priority |
|---|---|---|
| FR-30 | `hive mcp install <name> [--version X]` — install from registry, optionally pin version | P0 |
| FR-31 | `hive mcp add --name X --transport T --url U` — register a local server | P0 |
| FR-32 | `hive mcp add --from manifest.json` — register from a manifest file | P1 |
| FR-33 | `hive mcp remove <name>` — uninstall/unregister | P0 |
| FR-34 | `hive mcp list` — list installed servers with status, health, and trust tier | P0 |
| FR-35 | `hive mcp list --available` — list all servers in remote registry | P1 |
| FR-36 | `hive mcp search <query>` — search by name/tag/description/tool-name | P1 |
| FR-37 | `hive mcp enable/disable <name>` — toggle without removing | P0 |
| FR-38 | `hive mcp health [name]` — check server reachability and tool discovery | P1 |
| FR-39 | `hive mcp update [name]` — refresh index cache or update a specific server | P1 |
| FR-40 | `hive mcp config <name> --set KEY=VAL` — set credential/env overrides | P0 |
| FR-41 | `hive mcp info <name>` — show full details: trust tier, version, tools, health, which agents use it | P0 |
#### 5.1.6 CLI Commands — Contributor Tooling
| ID | Requirement | Priority |
|---|---|---|
| FR-42 | `hive mcp init [--server-url URL]` — scaffold a manifest; if URL provided, introspects server to pre-fill tools list | P0 |
| FR-43 | `hive mcp validate <path>` — validate a manifest against the JSON Schema locally | P0 |
| FR-44 | `hive mcp test <path>` — start the server per manifest config, list tools, run health check, report pass/fail | P1 |
#### 5.1.7 CLI Commands — Diagnostics
| ID | Requirement | Priority |
|---|---|---|
| FR-45 | `hive mcp doctor [name]` — check all or one server: connection, credentials, tool discovery, last error; output actionable fix suggestions | P0 |
| FR-46 | `hive mcp inspect <name>` — show resolved config including override chain, transport details, and which agents include/exclude this server | P1 |
| FR-47 | `hive mcp why-not <name> --agent <path>` — explain why a server was or was not loaded for a specific agent's `mcp_registry.json` | P1 |
#### 5.1.8 Hive Extension Block in Manifest
The optional `hive` block in the manifest carries Hive-specific metadata that doesn't belong in the portable base:
| ID | Requirement | Priority |
|---|---|---|
| FR-90 | `hive.min_version` — minimum Hive version required | P1 |
| FR-91 | `hive.max_version` — maximum compatible Hive version (optional, for deprecation) | P2 |
| FR-92 | `hive.example_agent` — path or URL to an example agent using this server | P2 |
| FR-93 | `hive.profiles` — list of profile tags this server belongs to (e.g., `["core", "productivity", "developer"]`) | P1 |
| FR-94 | `hive.tool_namespace` — optional prefix for tool names to avoid collisions (e.g., `jira_`) | P1 |
#### 5.1.9 Agent Selection
| ID | Requirement | Priority |
|---|---|---|
| FR-50 | Agents can declare MCP server preferences in `mcp_registry.json` | P0 |
| FR-51 | Selection supports: explicit `include` list, `tags` matching, `exclude` blacklist | P0 |
| FR-52 | `profile` field loads servers matching a named profile (e.g., `"all"`, `"core"`, `"productivity"`) | P0 |
| FR-53 | If `mcp_registry.json` does not exist, no registry servers are loaded (backward compatible) | P0 |
| FR-54 | Missing requested servers produce warnings with actionable install instructions, not errors | P0 |
| FR-55 | Agent startup logs a summary of loaded/skipped registry servers with reasons | P0 |
| FR-56 | `max_tools` field caps total tools loaded from registry servers (prevents prompt overload) | P1 |
#### 5.1.10 Tool Resolution & Namespacing
| ID | Requirement | Priority |
|---|---|---|
| FR-100 | When multiple servers expose a tool with the same name, the first server in include-order wins (deterministic) | P0 |
| FR-101 | Tool collisions are logged at startup: "Tool 'search' from 'brave-search' shadowed by 'google-search' (loaded first)" | P0 |
| FR-102 | If a server declares `hive.tool_namespace`, its tools are prefixed: `jira_create_issue` instead of `create_issue` | P1 |
| FR-103 | `hive mcp inspect <name>` shows which tools are active vs shadowed | P1 |
#### 5.1.11 Connection Management
| ID | Requirement | Priority |
|---|---|---|
| FR-60 | A process-level connection manager shares MCP connections across agents | P1 |
| FR-61 | Connections are reference-counted — disconnected when no agent uses them | P1 |
| FR-62 | HTTP/unix/SSE connections retry once on failure before raising an error | P1 |
#### 5.1.12 Transport Extensions
| ID | Requirement | Priority |
|---|---|---|
| FR-70 | `MCPClient` supports unix socket transport via `httpx` UDS | P1 |
| FR-71 | `MCPClient` supports SSE transport via the official MCP Python SDK | P1 |
| FR-72 | `MCPServerConfig` includes `socket_path` field for unix transport | P1 |
### 5.2 Version Compatibility & Upgrade Safety
| ID | Requirement | Priority |
|---|---|---|
| VC-1 | Manifest includes `version` (semver) for the registry entry and `mcp_protocol_version` for the MCP spec | P0 |
| VC-2 | Manifest `hive` block includes optional `min_version` / `max_version` constraints | P1 |
| VC-3 | `hive mcp install` installs latest by default; `--version X` pins a specific version | P0 |
| VC-4 | `installed.json` records `resolved_package_version` (actual pip/npm version installed) | P1 |
| VC-5 | `hive mcp update <name>` compares old and new tool lists; warns if tools were removed or signatures changed | P1 |
| VC-6 | Agents can pin a resolved server version in `mcp_registry.json` via `"versions": {"jira": "1.2.0"}` | P2 |
| VC-7 | If a pinned version is no longer available, the agent logs an error with rollback instructions | P2 |
| VC-8 | `hive mcp update --dry-run` shows what would change without applying | P1 |
| VC-9 | Tool names and parameter schemas from the manifest constitute a compatibility contract; breaking changes require a major version bump | P1 |
### 5.3 Failure Handling & Diagnostics
| ID | Requirement | Priority |
|---|---|---|
| DX-1 | All MCP errors use structured error codes (e.g., `MCP_INSTALL_FAILED`, `MCP_AUTH_MISSING`, `MCP_CONNECT_TIMEOUT`, `MCP_TOOL_NOT_FOUND`, `MCP_PROTOCOL_MISMATCH`) | P0 |
| DX-2 | Every error message includes: what failed, why, and a suggested fix command | P0 |
| DX-3 | `hive mcp doctor` checks: connection, credentials (are required env vars set?), tool discovery, protocol version compatibility, Hive version compatibility | P0 |
| DX-4 | Agent startup emits a structured log line per registry server: `{server, status, tools_loaded, skipped_reason}` | P0 |
| DX-5 | Failed tool calls from registry servers include the server name and transport in the error context | P1 |
| DX-6 | `hive mcp doctor` output is machine-parseable (JSON with `--json` flag) for CI/automation | P2 |
### 5.4 Non-Functional Requirements
| ID | Requirement | Priority |
|---|---|---|
| NFR-1 | Registry index fetch must complete in <5s on typical internet connections | P1 |
| NFR-2 | Installing a server from registry must not require a Hive restart | P0 |
| NFR-3 | Connection manager must be thread-safe (multiple agents in same process) | P0 |
| NFR-4 | All new code must have unit test coverage | P0 |
| NFR-5 | Registry repo CI must run in <60s | P1 |
| NFR-6 | Manifest base schema must be framework-agnostic (usable by non-Hive MCP clients); Hive-specific fields live in the `hive` extension block | P1 |
| NFR-7 | `hive mcp install` prints a security notice on first use: "Registry servers run code on your machine. Only install servers you trust." | P0 |
---
## 6. Architecture Overview
```
┌──────────────────────────────────┐
│ hive-mcp-registry (GitHub) │
│ │
│ registry/servers/jira/manifest │
│ registry/servers/slack/manifest │
│ ... │
│ registry_index.json (auto-built) │
└────────────────┬───────────────────┘
│ hive mcp update
│ (fetches index)
┌─────────────────────────────────────────────────────────────────────┐
│ ~/.hive/mcp_registry/ │
│ │
│ installed.json config.json cache/ │
│ (jira, slack, (preferences) registry_index.json │
│ my-custom-db) (cached remote) │
└─────────────────────────────┬───────────────────────────────────────┘
┌───────────────┼───────────────────┐
│ │ │
▼ ▼ ▼
┌─────────────┐ ┌─────────────┐ ┌──────────────┐
│ Queen Agent │ │Worker Agent │ │ hive mcp CLI │
│ │ │ │ │ │
│ mcp_registry │ │mcp_registry │ │ install │
│ .json: │ │.json: │ │ add / remove │
│ profile: all │ │include: │ │ doctor │
│ │ │ [jira] │ │ init / test │
└──────┬───────┘ └──────┬──────┘ └──────────────┘
│ │
▼ ▼
┌──────────────────────────────────┐
│ MCPConnectionManager │
│ (process singleton) │
│ │
│ jira → MCPClient (stdio, rc=2) │
│ slack → MCPClient (http, rc=1) │
│ my-db → MCPClient (unix, rc=1) │
└──────────────────────────────────┘
│ │ │
▼ ▼ ▼
┌──────────┐ ┌────────┐ ┌────────────┐
│ Jira MCP │ │Slack │ │ Custom DB │
│ (stdio) │ │MCP │ │ MCP (unix │
│ │ │(http) │ │ socket) │
└──────────┘ └────────┘ └────────────┘
```
### Component Responsibilities
| Component | Responsibility |
|---|---|
| **hive-mcp-registry** (GitHub repo) | Curated index of MCP server manifests; CI validates PRs; automated health checks |
| **~/.hive/mcp_registry/** | Local state: installed servers, cached index, user config, operational telemetry |
| **MCPRegistry** (Python module) | Core logic: install, remove, search, resolve for agent, doctor |
| **MCPConnectionManager** | Process-level connection pool with refcounting |
| **MCPClient** (extended) | Adds unix socket, SSE transports; retry on failure |
| **ToolRegistry** (extended) | New `load_registry_servers()` method with collision handling |
| **AgentRunner** (extended) | Loads `mcp_registry.json` alongside `mcp_servers.json`; logs resolution summary |
| **hive mcp CLI** | User-facing commands for management, diagnostics, and contributor tooling |
---
## 7. Data Models
### 7.1 Registry Manifest (`manifest.json`)
```json
{
"$schema": "https://raw.githubusercontent.com/aden-hive/hive-mcp-registry/main/schema/manifest.schema.json",
"name": "jira",
"display_name": "Jira MCP Server",
"version": "1.2.0",
"description": "Interact with Jira issues, boards, and sprints",
"author": {"name": "Jane Contributor", "github": "janedev", "url": "https://github.com/janedev"},
"maintainer": {"github": "janedev", "email": "jane@example.com"},
"repository": "https://github.com/janedev/jira-mcp-server",
"license": "MIT",
"status": "community",
"docs_url": "https://github.com/janedev/jira-mcp-server/blob/main/README.md",
"supported_os": ["linux", "macos", "windows"],
"deprecated": false,
"transport": {"supported": ["stdio", "http"], "default": "stdio"},
"install": {"pip": "jira-mcp-server", "docker": "ghcr.io/janedev/jira-mcp-server:latest", "npm": null},
"stdio": {"command": "uvx", "args": ["jira-mcp-server", "--stdio"]},
"http": {"default_port": 4010, "health_path": "/health", "command": "uvx", "args": ["jira-mcp-server", "--http", "--port", "{port}"]},
"unix": {"socket_template": "/tmp/mcp-{name}.sock", "command": "uvx", "args": ["jira-mcp-server", "--unix", "{socket_path}"]},
"tools": [
{"name": "jira_create_issue", "description": "Create a new Jira issue"},
{"name": "jira_search", "description": "Search Jira issues with JQL"},
{"name": "jira_update_issue", "description": "Update an existing issue"},
{"name": "jira_list_boards", "description": "List all Jira boards"}
],
"credentials": [
{"id": "jira_api_token", "env_var": "JIRA_API_TOKEN", "description": "Jira API token", "help_url": "https://id.atlassian.com/manage-profile/security/api-tokens", "required": true},
{"id": "jira_domain", "env_var": "JIRA_DOMAIN", "description": "Your Jira domain (e.g., mycompany.atlassian.net)", "required": true}
],
"tags": ["project-management", "atlassian", "issue-tracking"],
"categories": ["productivity"],
"mcp_protocol_version": "2024-11-05",
"hive": {
"min_version": "0.5.0",
"max_version": null,
"profiles": ["productivity", "developer"],
"tool_namespace": "jira",
"example_agent": "https://github.com/janedev/jira-mcp-server/tree/main/examples/hive-agent"
}
}
```
**Schema layering**:
- Everything outside `hive` is the **portable base** — usable by any MCP client.
- The `hive` block carries Hive-specific compatibility, profiles, namespacing, and examples.
### 7.2 Agent Selection (`mcp_registry.json`)
```json
{
"include": ["jira", "slack"],
"tags": ["crm"],
"exclude": ["github"],
"profile": "productivity",
"max_tools": 50,
"versions": {
"jira": "1.2.0"
}
}
```
**Selection precedence** (deterministic):
1. `profile` expands to a set of server names (union with `include` + `tags` matches).
2. `include` adds explicit servers.
3. `tags` adds servers whose tags overlap.
4. `exclude` removes from the final set (always wins).
5. Servers are loaded in `include`-order first, then alphabetically for tag/profile matches.
6. Tool collisions resolved by load order: first server wins.
### 7.3 Installed Server Entry (`installed.json` → `servers.<name>`)
```json
{
"source": "registry",
"manifest_version": "1.2.0",
"manifest": {},
"installed_at": "2026-03-13T10:00:00Z",
"installed_by": "hive mcp install",
"transport": "stdio",
"enabled": true,
"pinned": false,
"auto_update": false,
"resolved_package_version": "1.2.0",
"overrides": {"env": {"JIRA_DOMAIN": "mycompany.atlassian.net"}, "headers": {}},
"last_health_check_at": "2026-03-13T12:00:00Z",
"last_health_status": "healthy",
"last_error": null,
"last_used_at": "2026-03-13T11:30:00Z",
"last_validated_with_hive_version": "0.6.0"
}
```
---
## 8. Risks & Mitigations
| Risk | Impact | Likelihood | Mitigation |
|---|---|---|---|
| Low contributor adoption — nobody submits servers | Registry is empty, no value delivered | Medium | Seed with 5-10 popular MCP servers; `hive mcp init` makes submission trivial; canonical examples for every transport |
| High support burden from low-quality entries | Users install broken servers, file tickets against Hive | Medium | Trust tiers (official/verified/community); automated health checks in registry CI; `hive mcp doctor` for self-service debugging; quality gates beyond schema validation |
| Malicious MCP server in registry | User installs server that exfiltrates data or executes harmful code | Low | Maintainer review on all PRs; security notice on first install; servers run in user's trust boundary; verified tier requires code audit |
| Breaking changes to manifest schema | Existing manifests become invalid | Low | Schema versioning with `$schema` URL; CI validates backward compatibility; migration scripts |
| Server upgrades silently break agents | Tool signatures change, agents fail at runtime | Medium | `hive mcp update` diffs tool lists and warns on breaking changes; version pinning in `mcp_registry.json`; `--dry-run` flag |
| Connection manager concurrency bugs | Tool calls fail or deadlock under load | Medium | Thorough unit tests; reuse existing thread-safety patterns from `MCPClient._stdio_call_lock` |
| Registry index URL becomes unavailable | Users can't install new servers | Low | Local cache with TTL; fallback to last-known-good index; registry is a static file (cheap to host/mirror) |
| Name squatting in registry | Bad actors claim popular names | Low | Maintainer review on all PRs; naming guidelines in CONTRIBUTING.md |
| Auto-discover overloads agents with too many tools | Prompt bloat, confused tool selection, slower responses | Medium | `max_tools` cap in `mcp_registry.json`; profiles instead of blanket auto-discover; startup log shows tool count |
| Tool name collisions across servers | Wrong server handles a tool call | Medium | Deterministic load-order resolution; startup collision logging; optional tool namespacing via `hive.tool_namespace` |
---
## 9. Backward Compatibility
This system is **fully additive**:
- Existing `mcp_servers.json` files continue to work unchanged.
- Agents without `mcp_registry.json` load zero registry servers.
- The `MCPConnectionManager` is only used for registry-sourced connections; existing direct `MCPClient` usage is untouched.
- New CLI commands (`hive mcp ...`) don't conflict with existing commands.
- No existing files are modified in a breaking way.
- `mcp_servers.json` tools always take precedence over registry tools (they load first).
---
## 10. Documentation & Examples Strategy
Documentation is a first-class deliverable, not an afterthought. The following are required for launch:
| Doc | Audience | Deliverable |
|---|---|---|
| "Publish your first MCP server" | Contributors | Step-by-step guide from zero to merged registry entry, with screenshots |
| "Install and use your first registry server" | Users | Guide from `hive mcp install` to agent tool call |
| "Migration from mcp_servers.json" | Existing users | How to move static configs to registry-based selection |
| "Troubleshooting MCP servers" | Users | Common errors, `doctor` output examples, fix recipes |
| Manifest cookbook | Contributors | Annotated examples for stdio, http, unix, sse, multi-credential, no-credential |
| Example agents | Agent builders | 2-3 sample agents using `mcp_registry.json` with different selection strategies |
---
## 11. Phased Delivery
| Phase | Scope | Depends On |
|---|---|---|
| **Phase 1: Foundation** | MCPClient transport extensions (unix, SSE, retry); MCPConnectionManager; MCPRegistry module; CLI management commands; ToolRegistry `load_registry_servers()` with collision handling; AgentRunner `mcp_registry.json` loading with startup logging; structured error codes | -- |
| **Phase 2: Developer Tooling** | `hive mcp init`, `validate`, `test` (contributor flow); `doctor`, `inspect`, `why-not` (diagnostics); version pinning and `update --dry-run` | Phase 1 |
| **Phase 3: Registry Repo** | Create `hive-mcp-registry` GitHub repo with schema, validation CI, template, examples, CONTRIBUTING.md; seed with reference entries for built-in servers; automated health check CI | Phase 1 |
| **Phase 4: Docs & Launch** | All documentation deliverables from section 10; example agents; announcement | Phase 2, 3 |
| **Phase 5: Community Growth** | Trust tier promotion process; curated starter packs; popular/trending signals in registry | Phase 4 |
| **Phase 6: Monolith Decomposition** (future) | Extract tool groups from `mcp_server.py` into standalone servers; each becomes a registry entry | Phase 5 |
---
## 12. Open Questions
| # | Question | Owner | Status |
|---|---|---|---|
| Q1 | Should the registry repo live under `aden-hive` org or a new `hive-mcp` org? | Platform team | Open |
| Q2 | Should `hive mcp install` auto-prompt for required credentials interactively? | UX | Open |
| Q3 | Should the connection manager have a configurable max concurrent connections limit? | Engineering | Open |
| Q4 | Should we support a `docker` transport (Hive manages container lifecycle)? | Engineering | Open |
| Q5 | What is the process for promoting a `community` entry to `verified`? (e.g., code audit, usage threshold, maintainer SLA) | Platform + Security | Open |
| Q6 | Should the registry support private/enterprise indexes (e.g., `hive mcp config --index-url https://internal/...`)? | Platform | Open |
| Q7 | Should `hive mcp doctor` report telemetry (opt-in) to help identify systemic issues? | Product + Privacy | Open |
| Q8 | How should we handle MCP servers that require OAuth flows (not just static API keys)? | Engineering | Open |
---
## 13. Stakeholder Sign-Off
| Role | Name | Status |
|---|---|---|
| Engineering Lead | | Pending |
| Product | | Pending |
| OSS / Community | | Pending |
| Security | | Pending |
| Developer Experience | | Pending |
+907
View File
@@ -0,0 +1,907 @@
# Skill Registry — Product & Business Requirements Document
**Status**: Draft v1
**Last updated**: 2026-03-13
**Authors**: Timothy
**Reviewers**: Platform, Product, OSS/Community, Developer Experience
---
## 1. Executive Summary
This document proposes a **Skill System** for Hive — a portable implementation of the open [Agent Skills](https://agentskills.io) standard — combined with a community registry and a set of built-in default skills that give every worker agent runtime resiliency out of the box.
### 1.1 The Agent Skills Standard
Agent Skills is an open format, originally developed by Anthropic, for giving agents new capabilities and expertise. It has been adopted by 30+ products including Claude Code, Cursor, VS Code, GitHub Copilot, Gemini CLI, OpenHands, Goose, Roo Code, OpenAI Codex, and more.
A skill is a directory containing a `SKILL.md` file — YAML frontmatter (name, description) plus markdown instructions — optionally accompanied by scripts, reference docs, and assets. Agents discover skills at startup, load only the name and description into context (progressive disclosure tier 1), and activate the full instructions on demand when the task matches (tier 2). Supporting files are loaded only when the instructions reference them (tier 3).
```
my-skill/
├── SKILL.md # Required: metadata + instructions
├── scripts/ # Optional: executable code
├── references/ # Optional: documentation
├── assets/ # Optional: templates, resources
└── evals/ # Optional: test cases and assertions
```
### 1.2 What Hive Adds
Hive implements the Agent Skills standard faithfully — no forks, no proprietary extensions to the `SKILL.md` format. A skill written for Claude Code, Cursor, or any other compatible product works in Hive with zero changes, and vice versa.
On top of the standard, Hive adds two things:
1. **Default skills** — Six built-in skills shipped with the Hive framework that every worker agent loads automatically. These encode runtime operational discipline: structured note-taking, batch progress tracking, context preservation, quality self-assessment, error recovery protocols, and task decomposition. They are the "muscle memory" that makes agents reliable by default.
2. **Community registry** (`hive-skill-registry`) — A curated GitHub repository where contributors submit skill packages via pull request. Skills in the registry are standard Agent Skills packages. Includes CI validation, trust tiers, starter packs, and bounty program integration.
### 1.3 Abstraction Hierarchy
| Layer | What it is | Example |
| ----------------- | ------------------------------------------------------- | ------------------------------------------------- |
| **Tool** | A single function call via MCP | `web_search`, `gmail_send`, `jira_create_issue` |
| **Skill** | A `SKILL.md` with instructions, scripts, and references | "Deep Research", "Code Review", "Data Analysis" |
| **Default Skill** | A built-in skill for runtime resiliency | "Structured Note-Taking", "Batch Progress Ledger" |
| **Agent** | A complete goal-driven worker composed of skills | "Sales Outreach Agent", "Support Triage Agent" |
---
## 2. Problem Statement
### 2.1 Current State
- Worker agents have no skill system. There is no mechanism to discover, load, or follow reusable procedural instructions on demand.
- The 12 example templates in `examples/templates/` are copy-paste only — they cannot be composed, imported, versioned, or discovered at runtime.
- Agent builders must either hand-write all prompts and tool orchestration from scratch, or copy patterns from other agents manually.
- Skills written for Claude Code, Cursor, and other Agent Skills-compatible products do not work in Hive. Users who adopt Hive lose access to the growing ecosystem of community skills.
- Worker agents have no standardized operational discipline. The framework provides mechanical safeguards (stall detection, doom-loop fingerprinting, checkpoint/resume), but there is no cognitive protocol for how an agent should take structured notes when processing a 50-item batch, when to proactively save data before context pruning, or how to self-assess quality degradation. Each agent author either reinvents these patterns in their system prompts or — more commonly — skips them entirely.
- When a community member builds a battle-tested skill (research pattern, triage workflow, outreach playbook), there is no pathway to share it, no discovery mechanism, no versioning, and no quality signals.
### 2.2 Who Is Affected
| Persona | Pain Point |
| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **OSS contributor** | Built a great skill for another Agent Skills-compatible product; wants it to work in Hive too, or wants to share a Hive skill with the wider ecosystem |
| **Agent builder (beginner)** | Overwhelmed by framework concepts; wants to install a "deep research" skill and use it without understanding graph internals |
| **Agent builder (advanced)** | Copies the same prompt patterns and tool orchestration across agents; wants reusable, version-pinned building blocks |
| **Platform team** | Cannot codify best practices as reusable runtime primitives; every quality improvement is a docs change, not a skill update |
| **Enterprise user** | Wants an internal skill library so teams share proven patterns; needs cross-product compatibility |
### 2.3 Impact of Not Solving
- Hive is incompatible with the Agent Skills ecosystem — a growing open standard adopted by 30+ products. Users choosing Hive lose access to community skills; contributors targeting the ecosystem skip Hive.
- Agent quality depends entirely on individual author skill. No mechanism to propagate proven patterns.
- Worker agents are unreliable during long-running or batch processing sessions — no built-in operational discipline.
- The self-improvement loop's output (better prompts, better patterns) stays locked in individual deployments with no pathway to contribute back.
---
## 3. Goals & Success Criteria
### 3.1 Primary Goals
| # | Goal | Metric |
| --- | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ |
| G1 | Any `SKILL.md` from the Agent Skills ecosystem works in Hive with zero modifications | Compatibility test suite against `github.com/anthropics/skills` example skills |
| G2 | A Hive skill works in Claude Code, Cursor, and other compatible products with zero modifications | Cross-product verification on 5+ skills |
| G3 | A user can install and use a community skill in under 2 minutes | Time from `hive skill install X` to skill activating in a session |
| G4 | A contributor can publish a skill in under 10 minutes | Time from `hive skill init` to PR submission |
| G5 | Default skills measurably improve agent reliability on batch processing tasks | A/B comparison: agents with default skills vs. without on 10+ batch scenarios |
| G6 | Zero breaking changes to existing agent configurations | All current agents continue to work unchanged |
### 3.2 Community & Ecosystem Goals
| # | Goal | Metric |
| --- | -------------------------------------------------------------------------------------------- | --------------------------------------------------------------- |
| G7 | Registry has 100+ community skills within 30 days of launch | Skill count in registry |
| G8 | All registry skills are portable Agent Skills packages — usable in any compatible product | 100% of registry entries conform to the standard |
| G9 | Bounty program integrates with skill contributions | Skill submissions tracked in bounty-tracker |
| G10 | Contributors receive attribution when their skills are used | Skill metadata includes author; agent logs credit loaded skills |
| G11 | Existing skills from `github.com/anthropics/skills` are installable via `hive skill install` | All example skills pass validation and activate correctly |
### 3.3 Non-Goals (Explicit Exclusions)
- **Forking or extending the Agent Skills standard** — Hive implements the spec faithfully. No proprietary sidecar files, no Hive-specific schema extensions.
- **Runtime skill marketplace** — no billing, licensing, or monetization. The registry is free and open-source.
- **Hosting skill execution** — the registry stores packages; execution happens locally.
- **AI-generated skills** — automatic skill generation from natural language is a future phase.
- **Graph-level skill composition** — skills are instruction-following units, not graph fragments. Agents compose skills by activating multiple skills and following their combined instructions.
---
## 4. Agent Skills Standard — Implementation Spec
This section defines how Hive implements the open Agent Skills standard. The specification at [agentskills.io/specification](https://agentskills.io/specification) is authoritative; this section describes Hive's conforming implementation.
### 4.1 Skill Discovery
At session startup, Hive scans for skill directories containing a `SKILL.md` file. Both cross-client and Hive-specific locations are scanned:
| Scope | Path | Purpose |
| --------- | --------------------------------- | --------------------------------------------------- |
| Project | `<project>/.agents/skills/` | Cross-client interoperability (standard convention) |
| Project | `<project>/.hive/skills/` | Hive-specific project skills |
| User | `~/.agents/skills/` | Cross-client user-level skills |
| User | `~/.hive/skills/` | Hive-specific user-level skills |
| Framework | `<hive-install>/skills/defaults/` | Built-in default skills |
**Precedence** (deterministic): Project-level skills override user-level skills. Within the same scope, `.hive/skills/` overrides `.agents/skills/`. Framework-level default skills have lowest precedence and can be overridden at any scope.
**Scanning rules:**
- Skip `.git/`, `node_modules/`, `__pycache__/`, `.venv/` directories
- Max depth: 4 levels from the skills root
- Max directories: 2000 per scope
- Respect `.gitignore` in project scope
**Trust:** Project-level skills from untrusted repositories (not marked trusted by the user) require explicit user consent before loading.
### 4.2 `SKILL.md` Parsing
Each discovered `SKILL.md` is parsed per the standard:
1. Extract YAML frontmatter between `---` delimiters
2. Parse required fields: `name`, `description`
3. Parse optional fields: `license`, `compatibility`, `metadata`, `allowed-tools`
4. Everything after the closing `---` is the skill's markdown body (instructions)
**Validation (lenient):**
- Name doesn't match parent directory → warn, load anyway
- Name exceeds 64 characters → warn, load anyway
- Description missing or empty → skip the skill, log error
- YAML unparseable → try wrapping unquoted colon values in quotes as fallback; if still fails, skip and log
**In-memory record per skill:**
| Field | Source |
| -------------- | --------------------------------- |
| `name` | Frontmatter |
| `description` | Frontmatter |
| `location` | Absolute path to `SKILL.md` |
| `base_dir` | Parent directory of `SKILL.md` |
| `source_scope` | `project`, `user`, or `framework` |
### 4.3 Progressive Disclosure
Hive implements the standard three-tier loading model:
| Tier | What's loaded | When | Token cost |
| ------------------- | ---------------------------- | -------------------------------- | ------------------------ |
| **1. Catalog** | Name + description per skill | Session start | ~50-100 tokens per skill |
| **2. Instructions** | Full `SKILL.md` body | When skill is activated | <5000 tokens recommended |
| **3. Resources** | Scripts, references, assets | When instructions reference them | Varies |
**Catalog disclosure**: At session start, all discovered skill names and descriptions are injected into the system prompt:
```xml
<available_skills>
<skill>
<name>deep-research</name>
<description>Multi-step web research with source verification. Use when the task requires gathering and synthesizing information from multiple sources.</description>
<location>/home/user/.hive/skills/deep-research/SKILL.md</location>
</skill>
...
</available_skills>
```
**Behavioral instruction** injected alongside the catalog:
```
The following skills provide specialized instructions for specific tasks.
When a task matches a skill's description, read the SKILL.md at the listed
location to load the full instructions before proceeding.
When a skill references relative paths, resolve them against the skill's
directory (the parent of SKILL.md) and use absolute paths in tool calls.
```
### 4.4 Skill Activation
Skills are activated via two mechanisms:
**Model-driven**: The agent reads the skill catalog, decides a skill is relevant, and reads the `SKILL.md` file using its file-read tool. No special infrastructure needed — the agent's standard file-reading capability is sufficient.
**User-driven**: Users can activate skills explicitly via `@skill-name` mention syntax or via agent configuration that pre-activates specific skills for every session.
**What happens on activation:**
1. The full `SKILL.md` body is loaded into context
2. Bundled resources (scripts, references) are listed but NOT eagerly loaded
3. The skill directory is allowlisted for file access (no permission prompts for bundled files)
4. Activation is logged: `{skill_name, scope, timestamp}`
**Deduplication**: If a skill is already active in the current session, re-activation is skipped.
**Context protection**: Activated skill content is exempt from context pruning/compaction — skill instructions are durable behavioral guidance that must persist for the session duration.
### 4.5 Skill Execution
The agent follows the instructions in `SKILL.md`. It can:
- Execute bundled scripts from `scripts/`
- Read reference materials from `references/`
- Use assets from `assets/`
- Call any MCP tools available in the agent's tool registry
This is identical to how skills work in Claude Code, Cursor, or any other Agent Skills-compatible product.
### 4.6 Pre-Activated Skills
Agents can declare skills that should be activated at session start — bypassing model-driven activation. This is useful for skills that an agent always needs (e.g., a coding standards skill for a code review agent).
**In agent config (`agent.json`):**
```json
{
"skills": ["deep-research", "code-review"]
}
```
**In Python:**
```python
agent = Agent(
name="my-agent",
skills=["deep-research", "code-review"],
)
```
Pre-activated skills have their full `SKILL.md` body loaded into context at session start (tier 2), skipping the catalog-only tier 1 phase.
---
## 5. Default Skills
Default skills are **built-in skills shipped with the Hive framework** that every worker agent loads automatically. They use the Agent Skills format (`SKILL.md`) but live in the framework's install directory and serve as runtime operational protocols.
### 5.1 Why Default Skills
The framework provides mechanical safeguards: stall detection via n-gram similarity, doom-loop fingerprinting, checkpoint/resume, token budget pruning, and max iteration limits. But these are reactive — they trigger after something has gone wrong.
Default skills encode **proactive cognitive protocols**: how to take structured notes so you don't lose track of a 50-item batch, when to pause and summarize before you hit context limits, how to self-assess whether your output quality is degrading. They are the operational habits that experienced agent builders already encode in their system prompts — standardized so every agent benefits.
### 5.2 Integration Model
Default skills differ from community skills in how they integrate:
| Aspect | Default Skills | Community Skills |
| ------------ | ---------------------------------------------- | ----------------------------------------------------- |
| Loaded by | Framework automatically | Agent decides at runtime (or pre-activated in config) |
| Integration | System prompt injection + shared memory hooks | Instruction-following (standard Agent Skills) |
| Graph impact | No dedicated nodes — woven into existing nodes | None (just context) |
| Overridable | Yes (disable, configure, or replace) | N/A |
Default skills integrate at four injection points in the `EventLoopNode`:
1. **System prompt injection** (before first LLM call): Default skill protocols are appended to the node's system prompt
2. **Iteration boundary callbacks** (between iterations): Quality check, notes staleness warning, budget tracking
3. **Node completion hooks** (when node finishes): Batch completeness check, handoff summary
4. **Phase transition hooks** (on edge traversal): Context carry-over, notes persistence
### 5.3 Default Skill Catalog
Six default skills ship with Hive:
#### 5.3.1 Structured Note-Taking (`hive.note-taking`)
**Purpose:** Maintain a structured working document throughout execution so the agent never loses track of what it knows, what it's decided, and what's pending.
**Problem:** Without structured notes, agents processing long sessions rely entirely on conversation history. When context is pruned (automatically at 60% token usage), intermediate reasoning is lost. Agents repeat work, contradict earlier decisions, or silently drop items.
**Protocol (injected into system prompt):**
```markdown
## Operational Protocol: Structured Note-Taking
Maintain structured working notes in shared memory key `_working_notes`.
Update at these checkpoints:
- After completing each discrete subtask or batch item
- After receiving new information that changes your plan
- Before any tool call that will produce substantial output
Structure:
### Objective — restate the goal
### Current Plan — numbered steps, mark completed with ✓
### Key Decisions — decisions made and WHY
### Working Data — intermediate results, extracted values
### Open Questions — uncertainties to verify
### Blockers — anything preventing progress
Update incrementally — do not rewrite from scratch each time.
```
**Shared memory:** `_working_notes` (string), `_notes_updated_at` (timestamp)
**Config:** `enabled` (default true), `update_frequency` (default `per_subtask`), `max_notes_length` (default 4000 chars)
---
#### 5.3.2 Batch Progress Ledger (`hive.batch-ledger`)
**Purpose:** When processing a collection of items, maintain a structured ledger tracking each item's status so no item is skipped, duplicated, or silently dropped.
**Problem:** Agents processing batches lose track of which items they've handled, especially after context compaction or checkpoint resume. Without a ledger, agents re-process items (waste) or skip items (data loss).
**Protocol (injected into system prompt):**
```markdown
## Operational Protocol: Batch Progress Ledger
When processing a collection of items, maintain a batch ledger in `_batch_ledger`.
Initialize when you identify the batch:
- `_batch_total`: total item count
- `_batch_ledger`: JSON with per-item status
Per-item statuses: pending → in_progress → completed|failed|skipped
- Set `in_progress` BEFORE processing
- Set final status AFTER processing with 1-line result_summary
- Include error reason for failed/skipped items
- Update aggregate counts after each item
- NEVER remove items from the ledger
- If resuming, skip items already marked completed
```
**Shared memory:** `_batch_ledger` (dict), `_batch_total` (int), `_batch_completed` (int), `_batch_failed` (int)
**Config:** `enabled` (default true), `auto_detect_batch` (default true), `checkpoint_every_n` (default 5)
**Completion check:** At node completion, if `_batch_completed + _batch_failed + _batch_skipped < _batch_total`, emit warning.
---
#### 5.3.3 Context Preservation (`hive.context-preservation`)
**Purpose:** Proactively preserve critical information before automatic context pruning destroys it.
**Problem:** The framework's `prune_old_tool_results()` at 60% token usage removes content indiscriminately. Agents that don't proactively save important data into working notes lose it permanently.
**Protocol (injected into system prompt):**
```markdown
## Operational Protocol: Context Preservation
You operate under a finite context window. Important information WILL be pruned.
Save-As-You-Go: After any tool call producing information you'll need later,
immediately extract key data into `_working_notes` or `_preserved_data`.
Do NOT rely on referring back to old tool results.
What to extract: URLs and key snippets (not full pages), relevant API fields
(not raw JSON), specific lines/values (not entire files), analysis results
(not raw data).
Before transitioning to the next phase/node, write a handoff summary to
`_handoff_context` with everything the next phase needs to know.
```
**Shared memory:** `_handoff_context` (string), `_preserved_data` (dict)
**Config:** `enabled` (default true), `warn_at_usage_ratio` (default 0.45), `require_handoff` (default true)
---
#### 5.3.4 Quality Self-Assessment (`hive.quality-monitor`)
**Purpose:** Periodically prompt the agent to self-evaluate output quality, catching degradation before the judge does.
**Problem:** The judge system evaluates at node completion — once per node, not during execution. An agent can degrade gradually over many iterations without detection until the node completes.
**Protocol (injected into system prompt):**
```markdown
## Operational Protocol: Quality Self-Assessment
Every 5 iterations, self-assess:
1. On-task? Still working toward the stated objective?
2. Thorough? Cutting corners compared to earlier?
3. Non-repetitive? Producing new value or rehashing?
4. Consistent? Latest output contradict earlier decisions?
5. Complete? Tracking all items, or silently dropped some?
If degrading: write assessment to `_quality_log`, re-read `_working_notes`,
change approach explicitly. If acceptable: brief note in `_quality_log`.
```
**Shared memory:** `_quality_log` (list), `_quality_degradation_count` (int)
**Config:** `enabled` (default true), `assessment_interval` (default 5), `degradation_threshold` (default 3)
---
#### 5.3.5 Error Recovery Protocol (`hive.error-recovery`)
**Purpose:** When a tool call fails or returns unexpected results, follow a structured recovery protocol instead of blindly retrying or giving up.
**Problem:** The framework retries transient errors automatically. But non-transient failures (wrong input, business logic error, missing resource) are handed back to the agent with no guidance. Agents often retry the same call or abandon the task.
**Protocol (injected into system prompt):**
```markdown
## Operational Protocol: Error Recovery
When a tool call fails:
1. Diagnose — record error in notes, classify as transient or structural
2. Decide — transient: retry once. Structural fixable: fix and retry.
Structural unfixable: record as failed, move to next item.
Blocking all progress: record escalation note.
3. Adapt — if same tool failed 3+ times, stop using it and find alternative.
Update plan in notes. Never silently drop the failed item.
```
**Shared memory:** `_error_log` (list), `_failed_tools` (dict), `_escalation_needed` (bool)
**Config:** `enabled` (default true), `max_retries_per_tool` (default 3), `escalation_on_block` (default true)
---
#### 5.3.6 Task Decomposition (`hive.task-decomposition`)
**Purpose:** Decompose complex tasks into explicit subtasks before diving in. Maintain the decomposition as a living checklist.
**Problem:** Agents facing complex tasks start executing immediately without planning, leading to incomplete coverage and iteration budget exhaustion on the first sub-problem.
**Protocol (injected into system prompt):**
```markdown
## Operational Protocol: Task Decomposition
Before starting a complex task:
1. Decompose — break into numbered subtasks in `_working_notes` Current Plan
2. Estimate — relative effort per subtask (small/medium/large)
3. Execute — work through in order, mark ✓ when complete
4. Budget — if running low on iterations, prioritize by impact
5. Verify — before declaring done, every subtask must be ✓, skipped (with reason), or blocked
```
**Shared memory:** `_subtasks` (list), `_iteration_budget_remaining` (int)
**Config:** `enabled` (default true), `decomposition_threshold` (default `auto`), `budget_awareness` (default true)
---
### 5.4 Default Skill Configuration
Agents configure default skills via `default_skills` in their agent definition:
**Declarative (`agent.json`):**
```json
{
"default_skills": {
"hive.note-taking": { "enabled": true },
"hive.batch-ledger": { "enabled": true, "checkpoint_every_n": 10 },
"hive.context-preservation": {
"enabled": true,
"warn_at_usage_ratio": 0.4
},
"hive.quality-monitor": { "enabled": false },
"hive.error-recovery": { "enabled": true },
"hive.task-decomposition": { "enabled": true }
}
}
```
**Disable all:** `"default_skills": {"_all": {"enabled": false}}`
### 5.5 Prompt Budget
All default skill protocols combined must total under **2000 tokens** to minimize impact on the agent's domain reasoning budget. Protocols are terse operational checklists, not verbose documentation.
### 5.6 Shared Memory Convention
All default skill shared memory keys use the `_` prefix (`_working_notes`, `_batch_ledger`, etc.) to avoid collisions with domain-level keys. These keys are:
- Visible to the agent (for self-reference)
- Visible to the judge (for evaluation context)
- Excluded from the agent's declared output contract (operational, not domain output)
---
## 6. Community Registry
### 6.1 Registry Repository
A public GitHub repository (`hive-skill-registry`) serves as the curated community index. Every entry is a standard Agent Skills package — portable to any compatible product.
```
hive-skill-registry/
├── registry/
│ ├── skills/
│ │ ├── deep-research/
│ │ │ ├── SKILL.md
│ │ │ ├── scripts/
│ │ │ ├── references/
│ │ │ ├── evals/
│ │ │ └── README.md
│ │ ├── email-triage/
│ │ └── ...
│ ├── packs/
│ │ ├── research-pack.json
│ │ └── ...
│ └── _template/
├── skill_index.json (auto-generated)
├── CONTRIBUTING.md
└── README.md
```
### 6.2 Trust Tiers
| Tier | Meaning | Requirements |
| ----------- | ------------------------------ | --------------------------------------------- |
| `official` | Maintained by Hive team | Internal review |
| `verified` | Audited community contribution | Code audit, maintainer SLA, test coverage |
| `community` | Community-submitted | Passes CI validation, maintainer review on PR |
### 6.3 Registry Index
The registry auto-generates a `skill_index.json` on merge for client consumption:
```json
{
"name": "deep-research",
"description": "Multi-step web research with source verification...",
"status": "verified",
"author": { "name": "Alex Researcher", "github": "alexr" },
"maintainer": { "github": "alexr" },
"version": "1.2.0",
"license": "MIT",
"tags": ["research", "web", "synthesis"],
"categories": ["knowledge-work"],
"install_count": 342,
"last_validated_at": "2026-03-13T10:00:00Z",
"deprecated": false
}
```
### 6.4 Starter Packs
Themed collections of skills that work well together:
```json
{
"name": "research-pack",
"display_name": "Research & Analysis Pack",
"description": "Skills for research-heavy agents",
"skills": [
{ "name": "deep-research", "version": ">=1.0.0" },
{ "name": "synthesis", "version": ">=1.0.0" },
{ "name": "executive-summary", "version": ">=1.0.0" }
]
}
```
### 6.5 Evaluation Framework
Skills in the registry can include an `evals/` directory following the Agent Skills evaluation pattern:
```json
{
"skill_name": "deep-research",
"evals": [
{
"id": 1,
"prompt": "Research the current state of quantum computing and summarize the top 3 breakthroughs from the past year.",
"expected_output": "A structured summary with 3 breakthroughs, each with source citations.",
"assertions": [
"Output includes at least 3 distinct breakthroughs",
"Each breakthrough has at least one source URL",
"Sources are from the past 12 months"
]
}
]
}
```
CI runs these evals on submitted skills to validate quality.
### 6.6 Bounty Integration
| Contribution | Points |
| -------------------- | ------ |
| New skill | 75 |
| Skill improvement PR | 30 |
| Skill tests/evals | 20 |
| Skill docs | 20 |
---
## 7. Requirements
### 7.1 Functional Requirements — Agent Skills Standard
| ID | Requirement | Priority |
| ----- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- |
| AS-1 | Discover skills by scanning `.agents/skills/` and `.hive/skills/` at project and user scopes | P0 |
| AS-2 | Parse `SKILL.md` YAML frontmatter per the Agent Skills spec: `name`, `description` (required), `license`, `compatibility`, `metadata`, `allowed-tools` (optional) | P0 |
| AS-3 | Lenient validation: warn on non-critical issues, skip only on missing description or unparseable YAML | P0 |
| AS-4 | Progressive disclosure tier 1: skill catalog (name + description + location) injected into system prompt at session start | P0 |
| AS-5 | Progressive disclosure tier 2: full `SKILL.md` body loaded into context when agent or user activates a skill | P0 |
| AS-6 | Progressive disclosure tier 3: scripts, references, and assets loaded on demand when instructions reference them | P0 |
| AS-7 | Model-driven activation: agent reads `SKILL.md` via file-read tool when it decides a skill is relevant | P0 |
| AS-8 | User-driven activation: `@skill-name` mention syntax intercepted by harness | P1 |
| AS-9 | Skill directories allowlisted for file access — no permission prompts for bundled resources | P0 |
| AS-10 | Activated skill content protected from context pruning/compaction | P0 |
| AS-11 | Duplicate activations in the same session deduplicated | P1 |
| AS-12 | Name collisions resolved deterministically: project overrides user, `.hive/` overrides `.agents/`, log warning | P0 |
| AS-13 | Trust gating: project-level skills from untrusted repos require user consent | P1 |
| AS-14 | Compatibility with `github.com/anthropics/skills` example skills — all pass validation and activate correctly | P0 |
| AS-15 | Cross-client YAML compatibility: handle unquoted colon values via automatic fixup | P1 |
| AS-16 | Pre-activated skills via `skills` list in agent config (`agent.json` and Python API) | P0 |
| AS-17 | Subagent delegation: optionally run a skill's instructions in an isolated sub-session | P2 |
### 7.2 Functional Requirements — Default Skills
| ID | Requirement | Priority |
| ----- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- |
| DS-1 | Ship 6 default skills: `hive.note-taking`, `hive.batch-ledger`, `hive.context-preservation`, `hive.quality-monitor`, `hive.error-recovery`, `hive.task-decomposition` | P0 |
| DS-2 | Default skills are valid Agent Skills packages (`SKILL.md` format) in the framework install directory | P0 |
| DS-3 | All default skills loaded automatically for every worker agent unless explicitly disabled | P0 |
| DS-4 | Default skills integrate via system prompt injection — no additional graph nodes | P0 |
| DS-5 | Default skills use `_`-prefixed shared memory keys to avoid domain collisions | P0 |
| DS-6 | Each default skill independently configurable via `default_skills` in agent config | P0 |
| DS-7 | All defaults disableable at once: `{"_all": {"enabled": false}}` | P0 |
| DS-8 | Default skill protocols appended in a `## Operational Protocols` system prompt section | P0 |
| DS-9 | Iteration boundary callbacks for quality check and notes staleness | P0 |
| DS-10 | Node completion hooks for batch completeness and handoff write | P0 |
| DS-11 | Phase transition hooks for context carry-over and notes persistence | P1 |
| DS-12 | `hive.batch-ledger` auto-detects batch scenarios via heuristic | P1 |
| DS-13 | `hive.context-preservation` warns at 0.45 token usage (before 0.6 framework prune) | P0 |
| DS-14 | Combined default skill prompts total under 2000 tokens | P0 |
| DS-15 | Agent startup logs active default skills and config | P0 |
### 7.3 Functional Requirements — CLI
| ID | Requirement | Priority |
| ------ | ------------------------------------------------------------------------------------------------- | -------- |
| CLI-1 | `hive skill list` — list discovered skills (all scopes) with source and status | P0 |
| CLI-2 | `hive skill install <name> [--version X]` — install from registry to `~/.hive/skills/` | P0 |
| CLI-3 | `hive skill install --pack <name>` — install a starter pack | P1 |
| CLI-4 | `hive skill remove <name>` — uninstall | P0 |
| CLI-5 | `hive skill search <query>` — search registry by name, tag, description | P1 |
| CLI-6 | `hive skill info <name>` — show details: description, author, scripts, references | P0 |
| CLI-7 | `hive skill init [--name X]` — scaffold a skill directory with `SKILL.md` template | P0 |
| CLI-8 | `hive skill validate <path>` — validate `SKILL.md` against the Agent Skills spec | P0 |
| CLI-9 | `hive skill test <path> [--input <json>]` — run skill in isolation, execute evals if present | P1 |
| CLI-10 | `hive skill doctor [name]` — check health: SKILL.md parseable, scripts executable, deps available | P0 |
| CLI-11 | `hive skill doctor --defaults` — check all default skills operational | P1 |
| CLI-12 | `hive skill fork <name> [--name new-name]` — create local editable copy of a registry skill | P1 |
| CLI-13 | `hive skill update [name]` — update registry cache or specific skill | P1 |
### 7.4 Functional Requirements — Registry
| ID | Requirement | Priority |
| ------ | ------------------------------------------------------------------------------------------------ | -------- |
| REG-1 | Public GitHub repo with defined directory structure | P0 |
| REG-2 | CI validates `SKILL.md` on every PR using `skills-ref validate` | P0 |
| REG-3 | Flat index (`skill_index.json`) auto-generated on merge | P0 |
| REG-4 | `_template/` directory with starter skill for contributors | P0 |
| REG-5 | `CONTRIBUTING.md` with step-by-step submission guide | P0 |
| REG-6 | CI runs skill evals when `evals/` directory is present | P1 |
| REG-7 | Trust tiers: `official`, `verified`, `community` | P0 |
| REG-8 | Tags follow controlled taxonomy | P1 |
| REG-9 | Seed with 10+ skills: extract from existing templates + port from `github.com/anthropics/skills` | P0 |
| REG-10 | Starter pack definitions in `registry/packs/` | P1 |
### 7.5 Failure Handling & Diagnostics
| ID | Requirement | Priority |
| ---- | ----------------------------------------------------------------------------------------- | -------- |
| DX-1 | Structured error codes: `SKILL_NOT_FOUND`, `SKILL_PARSE_ERROR`, `SKILL_ACTIVATION_FAILED` | P0 |
| DX-2 | Every error includes: what failed, why, and suggested fix | P0 |
| DX-3 | Agent startup logs per-skill summary: `{name, scope, status}` | P0 |
| DX-4 | `hive skill doctor` machine-parseable with `--json` flag | P2 |
### 7.6 Non-Functional Requirements
| ID | Requirement | Priority |
| ----- | ---------------------------------------------------------------------------- | -------- |
| NFR-1 | Skill discovery (scanning + parsing) completes in <500ms for up to 50 skills | P1 |
| NFR-2 | Installing a skill does not require a Hive restart | P0 |
| NFR-3 | All new code has unit test coverage | P0 |
| NFR-4 | Registry CI runs in <120s | P1 |
| NFR-5 | `hive skill install` prints security notice on first use | P0 |
| NFR-6 | Skills loaded at runtime are read-only — modifications require forking | P0 |
---
## 8. Architecture Overview
```
┌─────────────────────────────────────┐
│ hive-skill-registry (GitHub) │
│ │
│ registry/skills/deep-research/ │
│ ├── SKILL.md │
│ ├── scripts/ │
│ └── evals/ │
│ registry/packs/research-pack.json │
│ skill_index.json (auto-built) │
└──────────────┬────────────────────────┘
│ hive skill install
┌──────────────────────────────────────────────────────────────────────┐
│ Skill Sources │
│ │
│ ~/.hive/skills/ .agents/skills/ <hive>/skills/ │
│ (user, Hive-specific) (project, cross- defaults/ │
│ client portable) (framework built- │
│ in defaults) │
└──────────────────────┬───────────────────────────────────────────────┘
┌────────────────────┐
│ SkillDiscovery │
│ │
│ scan() → catalog │
│ parse SKILL.md │
│ resolve collisions │
└────────┬───────────┘
┌───────────┴───────────┐
│ │
▼ ▼
┌──────────────────┐ ┌───────────────────────┐
│ Community Skills │ │ Default Skills │
│ │ │ │
│ Catalog injected │ │ DefaultSkillManager │
│ into system │ │ • prompt injection │
│ prompt (tier 1) │ │ • iteration hooks │
│ │ │ • completion hooks │
│ Activated on │ │ • transition hooks │
│ demand (tier 2) │ │ │
│ │ │ Always active │
│ Agent follows │ │ (unless disabled) │
│ SKILL.md │ │ │
│ instructions │ │ Protocols woven into │
│ │ │ existing node prompts │
└──────────────────┘ └───────────────────────┘
│ │
└───────────┬───────────┘
┌────────────────────┐
│ EventLoopNode │
│ │
│ System prompt = │
│ agent prompt │
│ + node prompt │
│ + default skill │
│ protocols │
│ + activated skill │
│ instructions │
│ │
│ Same iteration │
│ loop, tools, │
│ judges │
└────────────────────┘
```
### Component Responsibilities
| Component | Responsibility |
| -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| **SkillDiscovery** | Scan skill directories, parse `SKILL.md`, resolve collisions, build catalog |
| **SkillCatalog** | In-memory index of discovered skills; injected into system prompt at session start |
| **DefaultSkillManager** | Load, configure, and inject the 6 built-in default skills; manage prompt injection and hook registration |
| **EventLoopNode** (extended) | New hook points for default skills: iteration callbacks, completion hooks. Appends default protocols and activated skill content to system prompt. |
| **AgentRunner** (extended) | Resolve `skills` (pre-activation) and `default_skills` config; trigger discovery; log skill summary at startup |
| **hive skill CLI** | User-facing commands for install, search, validate, test, doctor |
| **hive-skill-registry** (GitHub) | Community-curated skill packages; CI validation; trust tiers; starter packs |
---
## 9. Risks & Mitigations
| Risk | Impact | Likelihood | Mitigation |
| ----------------------------------------------------- | -------------------------------------------------------- | ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Agent Skills spec evolves in breaking ways | Hive implementation falls out of sync | Low | Standard is backed by Anthropic and adopted by 30+ products; changes are conservative. Track spec repo; participate in governance. |
| Low community adoption — nobody submits skills | Registry empty, no value | Medium | Seed with 10+ skills from existing templates + ported from `github.com/anthropics/skills`; bounty program; `hive skill init` trivializes creation |
| Prompt injection via malicious skill instructions | Skill manipulates agent behavior | Medium | Trust gating for project-level skills; maintainer review on registry PRs; `verified` tier requires audit; security notice on install |
| Default skill prompts bloat system prompt | Reduced token budget for reasoning | Medium | Hard cap of 2000 tokens total; individually disableable; terse checklist format |
| Default skills create rigid behavior for simple tasks | Agent follows batch protocol on trivial single-item task | Medium | `auto_detect_batch` heuristic; `task_decomposition` threshold defaults to `auto`; all defaults individually disableable |
| Context window consumed by too many active skills | Multiple skills + default skills exhaust context | Medium | Progressive disclosure limits base cost (~100 tokens/skill); skills activated one-at-a-time on demand; skill body recommended <5000 tokens; default skills capped at 2000 tokens |
| Skill quality inconsistent across registry | Users install ineffective skills | Medium | Trust tiers; eval framework in CI; `hive skill test`; community signals (install count); `deprecated` flag |
---
## 10. Backward Compatibility
This system is **fully additive**:
- Existing agents without skills continue to work unchanged.
- Default skills are loaded automatically but are behaviorally non-breaking: they add operational instructions to system prompts but do not change graph structure, tool availability, or output contracts.
- Default skills can be fully disabled via `"default_skills": {"_all": {"enabled": false}}`.
- Agents without a `skills` list load zero community skills (model may still activate from catalog).
- The `GraphExecutor` is unchanged — no new execution model.
- Existing `tools.py`, `mcp_servers.json`, and `mcp_registry.json` work alongside skills.
- Skills from the Agent Skills ecosystem (Claude Code, Cursor, etc.) work without modification.
---
## 11. Interaction with MCP Registry
Skills and MCP servers are complementary:
| Concern | MCP Registry | Skill System |
| -------------- | ------------------------------------------ | ----------------------------------------------- |
| What it shares | Tool infrastructure (servers, connections) | Agent behavior (instructions, prompts, scripts) |
| Format | Manifest JSON (Hive-specific) | `SKILL.md` (open standard) |
| Granularity | Atomic tool functions | Multi-step behavioral patterns |
**Integration:** Skills reference tools by name in their `SKILL.md` instructions; the agent resolves them via the normal tool registry. If a skill requires a tool that isn't available, the agent will encounter an error at execution time — `hive skill doctor` can pre-check this.
---
## 12. Documentation & Examples Strategy
| Doc | Audience | Deliverable |
| -------------------------------------- | ----------------- | ------------------------------------------------------------------------------ |
| "Install and use your first skill" | Users | From `hive skill search` to skill activating in a session |
| "Write your first skill" | Contributors | Step-by-step: `hive skill init` → write SKILL.md → validate → submit PR |
| "Port a skill from Claude Code/Cursor" | Contributors | Usually just install it — guide explains verification |
| "Default skills reference" | All users | All 6 defaults: purpose, config, shared memory keys, tuning |
| "Tuning default skills" | Advanced builders | When to disable vs. configure; per-agent overrides; measuring impact |
| Skill cookbook | Contributors | Annotated examples: research, triage, draft, review, outreach, data extraction |
| "Evaluating skill quality" | Contributors | Setting up evals, writing assertions, iterating with the eval-driven loop |
| Starter pack guide | Users | Finding, installing, and customizing starter packs |
---
## 13. Phased Delivery
| Phase | Scope | Depends On |
| --------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- |
| **Phase 0: Default Skills** | Implement 6 default skills as `SKILL.md` packages; `DefaultSkillManager` with system prompt injection, iteration callbacks, node completion hooks, phase transition hooks; `DefaultSkillConfig` in Python API and `agent.json`; `_`-prefixed shared memory convention; startup logging | — |
| **Phase 1: Agent Skills Standard** | `SkillDiscovery` scanning `.agents/skills/` and `.hive/skills/`; `SKILL.md` parsing with lenient validation; progressive disclosure (catalog injection, activation, resource loading); model-driven and user-driven activation; context protection; deduplication; pre-activated skills config; compatibility tests against `github.com/anthropics/skills` | — |
| **Phase 2: CLI & Contributor Tooling** | `hive skill init`, `validate`, `test`, `fork`; `hive skill doctor`; `hive skill install/remove/list/search/info/update`; version pinning; `skills-ref` integration for validation | Phase 1 |
| **Phase 3: Registry Repo** | Create `hive-skill-registry` GitHub repo; CI validation using `skills-ref`; `_template/`; `CONTRIBUTING.md`; seed with 10+ skills (extracted from templates + ported from anthropics/skills); eval CI | Phase 1 |
| **Phase 4: Docs & Launch** | All documentation from section 12; example agents using skills; announcement; bounty program integration | Phase 2, 3 |
| **Phase 5: Community Growth** | Trust tier promotion process; starter packs; community signals (install counts); monthly skill spotlight; eval-driven quality ranking | Phase 4 |
| **Phase 6: Advanced Features** (future) | Subagent delegation for skill execution; skill-level telemetry; AI-assisted skill creation | Phase 5 |
Phase 0 and Phase 1 can proceed in parallel — default skills depend on the prompt injection pipeline, while Agent Skills standard depends on discovery/parsing/activation.
---
## 14. Open Questions
| # | Question | Owner | Status |
| --- | -------------------------------------------------------------------------------------------------------------------------------------- | ------------------- | ------ |
| Q1 | Should the registry repo live under `aden-hive` org or a shared `agentskills` org? | Platform | Open |
| Q2 | Should default skill protocols be adaptive (e.g., `hive.batch-ledger` adjusts checkpoint frequency based on item size)? | Engineering | Open |
| Q3 | Should default skills be tunable per-node (not just per-agent)? | Engineering | Open |
| Q4 | How should default skill protocols interact with existing `adapt.md` working memory? Should `_working_notes` replace or supplement it? | Engineering | Open |
| Q5 | Should `hive.quality-monitor` self-assessments feed into judge decisions (auto-trigger RETRY on self-reported degradation)? | Engineering | Open |
| Q6 | What is the right combined token budget for default skill prompts? 2000 tokens proposed — configurable or fixed? | Engineering | Open |
| Q7 | Should Hive support subagent delegation for skill execution (run skill in isolated session, return summary)? | Engineering | Open |
| Q8 | Should Hive also scan `.claude/skills/` for pragmatic compatibility with Claude Code's native skill location? | Engineering | Open |
| Q9 | What is the process for promoting a `community` skill to `verified`? | Platform + Security | Open |
| Q10 | Should the registry support private/enterprise skill indexes (`hive skill config --index-url`)? | Platform | Open |
| Q11 | Should `hive skill test` use the official `skills-ref` library or a Hive-native implementation? | Engineering | Open |
| Q12 | How should skill-level telemetry (activation counts, eval pass rates) be collected without compromising privacy? | Product + Privacy | Open |
---
## 15. Stakeholder Sign-Off
| Role | Name | Status |
| -------------------- | ---- | ------- |
| Engineering Lead | | Pending |
| Product | | Pending |
| OSS / Community | | Pending |
| Security | | Pending |
| Developer Experience | | Pending |
+50 -43
View File
@@ -802,26 +802,26 @@ $DefaultModels = @{
# Model choices: array of hashtables per provider
$ModelChoices = @{
anthropic = @(
@{ Id = "claude-haiku-4-5-20251001"; Label = "Haiku 4.5 - Fast + cheap (recommended)"; MaxTokens = 8192 },
@{ Id = "claude-sonnet-4-20250514"; Label = "Sonnet 4 - Fast + capable"; MaxTokens = 8192 },
@{ Id = "claude-sonnet-4-5-20250929"; Label = "Sonnet 4.5 - Best balance"; MaxTokens = 16384 },
@{ Id = "claude-opus-4-6"; Label = "Opus 4.6 - Most capable"; MaxTokens = 32768 }
@{ Id = "claude-haiku-4-5-20251001"; Label = "Haiku 4.5 - Fast + cheap (recommended)"; MaxTokens = 8192; MaxContextTokens = 180000 },
@{ Id = "claude-sonnet-4-20250514"; Label = "Sonnet 4 - Fast + capable"; MaxTokens = 8192; MaxContextTokens = 180000 },
@{ Id = "claude-sonnet-4-5-20250929"; Label = "Sonnet 4.5 - Best balance"; MaxTokens = 16384; MaxContextTokens = 180000 },
@{ Id = "claude-opus-4-6"; Label = "Opus 4.6 - Most capable"; MaxTokens = 32768; MaxContextTokens = 180000 }
)
openai = @(
@{ Id = "gpt-5-mini"; Label = "GPT-5 Mini - Fast + cheap (recommended)"; MaxTokens = 16384 },
@{ Id = "gpt-5.2"; Label = "GPT-5.2 - Most capable"; MaxTokens = 16384 }
@{ Id = "gpt-5-mini"; Label = "GPT-5 Mini - Fast + cheap (recommended)"; MaxTokens = 16384; MaxContextTokens = 120000 },
@{ Id = "gpt-5.2"; Label = "GPT-5.2 - Most capable"; MaxTokens = 16384; MaxContextTokens = 120000 }
)
gemini = @(
@{ Id = "gemini-3-flash-preview"; Label = "Gemini 3 Flash - Fast (recommended)"; MaxTokens = 8192 },
@{ Id = "gemini-3.1-pro-preview"; Label = "Gemini 3.1 Pro - Best quality"; MaxTokens = 8192 }
@{ Id = "gemini-3-flash-preview"; Label = "Gemini 3 Flash - Fast (recommended)"; MaxTokens = 8192; MaxContextTokens = 900000 },
@{ Id = "gemini-3.1-pro-preview"; Label = "Gemini 3.1 Pro - Best quality"; MaxTokens = 8192; MaxContextTokens = 900000 }
)
groq = @(
@{ Id = "moonshotai/kimi-k2-instruct-0905"; Label = "Kimi K2 - Best quality (recommended)"; MaxTokens = 8192 },
@{ Id = "openai/gpt-oss-120b"; Label = "GPT-OSS 120B - Fast reasoning"; MaxTokens = 8192 }
@{ Id = "moonshotai/kimi-k2-instruct-0905"; Label = "Kimi K2 - Best quality (recommended)"; MaxTokens = 8192; MaxContextTokens = 120000 },
@{ Id = "openai/gpt-oss-120b"; Label = "GPT-OSS 120B - Fast reasoning"; MaxTokens = 8192; MaxContextTokens = 120000 }
)
cerebras = @(
@{ Id = "zai-glm-4.7"; Label = "ZAI-GLM 4.7 - Best quality (recommended)"; MaxTokens = 8192 },
@{ Id = "qwen3-235b-a22b-instruct-2507"; Label = "Qwen3 235B - Frontier reasoning"; MaxTokens = 8192 }
@{ Id = "zai-glm-4.7"; Label = "ZAI-GLM 4.7 - Best quality (recommended)"; MaxTokens = 8192; MaxContextTokens = 120000 },
@{ Id = "qwen3-235b-a22b-instruct-2507"; Label = "Qwen3 235B - Frontier reasoning"; MaxTokens = 8192; MaxContextTokens = 120000 }
)
}
@@ -830,10 +830,10 @@ function Get-ModelSelection {
$choices = $ModelChoices[$ProviderId]
if (-not $choices -or $choices.Count -eq 0) {
return @{ Model = $DefaultModels[$ProviderId]; MaxTokens = 8192 }
return @{ Model = $DefaultModels[$ProviderId]; MaxTokens = 8192; MaxContextTokens = 120000 }
}
if ($choices.Count -eq 1) {
return @{ Model = $choices[0].Id; MaxTokens = $choices[0].MaxTokens }
return @{ Model = $choices[0].Id; MaxTokens = $choices[0].MaxTokens; MaxContextTokens = $choices[0].MaxContextTokens }
}
# Find default index from previous model (if same provider)
@@ -866,7 +866,7 @@ function Get-ModelSelection {
$sel = $choices[$num - 1]
Write-Host ""
Write-Ok "Model: $($sel.Id)"
return @{ Model = $sel.Id; MaxTokens = $sel.MaxTokens }
return @{ Model = $sel.Id; MaxTokens = $sel.MaxTokens; MaxContextTokens = $sel.MaxContextTokens }
}
}
Write-Color -Text "Invalid choice. Please enter 1-$($choices.Count)" -Color Red
@@ -883,11 +883,12 @@ Write-Step -Number "" -Text "Configuring LLM provider..."
$HiveConfigDir = Join-Path $env:USERPROFILE ".hive"
$HiveConfigFile = Join-Path $HiveConfigDir "configuration.json"
$SelectedProviderId = ""
$SelectedEnvVar = ""
$SelectedModel = ""
$SelectedMaxTokens = 8192
$SubscriptionMode = ""
$SelectedProviderId = ""
$SelectedEnvVar = ""
$SelectedModel = ""
$SelectedMaxTokens = 8192
$SelectedMaxContextTokens = 120000
$SubscriptionMode = ""
# ── Credential detection (silent — just set flags) ───────────
$ClaudeCredDetected = $false
@@ -1063,20 +1064,22 @@ switch ($num) {
Write-Host ""
exit 1
}
$SubscriptionMode = "claude_code"
$SelectedProviderId = "anthropic"
$SelectedModel = "claude-opus-4-6"
$SelectedMaxTokens = 32768
$SubscriptionMode = "claude_code"
$SelectedProviderId = "anthropic"
$SelectedModel = "claude-opus-4-6"
$SelectedMaxTokens = 32768
$SelectedMaxContextTokens = 180000
Write-Host ""
Write-Ok "Using Claude Code subscription"
}
2 {
# ZAI Code Subscription
$SubscriptionMode = "zai_code"
$SelectedProviderId = "openai"
$SelectedEnvVar = "ZAI_API_KEY"
$SelectedModel = "glm-5"
$SelectedMaxTokens = 32768
$SubscriptionMode = "zai_code"
$SelectedProviderId = "openai"
$SelectedEnvVar = "ZAI_API_KEY"
$SelectedModel = "glm-5"
$SelectedMaxTokens = 32768
$SelectedMaxContextTokens = 120000
Write-Host ""
Write-Ok "Using ZAI Code subscription"
Write-Color -Text " Model: glm-5 | API: api.z.ai" -Color DarkGray
@@ -1105,21 +1108,23 @@ switch ($num) {
}
}
if ($CodexCredDetected) {
$SubscriptionMode = "codex"
$SelectedProviderId = "openai"
$SelectedModel = "gpt-5.3-codex"
$SelectedMaxTokens = 16384
$SubscriptionMode = "codex"
$SelectedProviderId = "openai"
$SelectedModel = "gpt-5.3-codex"
$SelectedMaxTokens = 16384
$SelectedMaxContextTokens = 120000
Write-Host ""
Write-Ok "Using OpenAI Codex subscription"
}
}
4 {
# Kimi Code Subscription
$SubscriptionMode = "kimi_code"
$SelectedProviderId = "kimi"
$SelectedEnvVar = "KIMI_API_KEY"
$SelectedModel = "kimi-k2.5"
$SelectedMaxTokens = 32768
$SubscriptionMode = "kimi_code"
$SelectedProviderId = "kimi"
$SelectedEnvVar = "KIMI_API_KEY"
$SelectedModel = "kimi-k2.5"
$SelectedMaxTokens = 32768
$SelectedMaxContextTokens = 120000
Write-Host ""
Write-Ok "Using Kimi Code subscription"
Write-Color -Text " Model: kimi-k2.5 | API: api.kimi.com/coding" -Color DarkGray
@@ -1341,8 +1346,9 @@ if ($SubscriptionMode -eq "kimi_code") {
# Prompt for model if not already selected (manual provider path)
if ($SelectedProviderId -and -not $SelectedModel) {
$modelSel = Get-ModelSelection $SelectedProviderId
$SelectedModel = $modelSel.Model
$SelectedMaxTokens = $modelSel.MaxTokens
$SelectedModel = $modelSel.Model
$SelectedMaxTokens = $modelSel.MaxTokens
$SelectedMaxContextTokens = $modelSel.MaxContextTokens
}
# Save configuration
@@ -1359,9 +1365,10 @@ if ($SelectedProviderId) {
$config = @{
llm = @{
provider = $SelectedProviderId
model = $SelectedModel
max_tokens = $SelectedMaxTokens
provider = $SelectedProviderId
model = $SelectedModel
max_tokens = $SelectedMaxTokens
max_context_tokens = $SelectedMaxContextTokens
}
created_at = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss+00:00")
}
+11 -1
View File
@@ -68,10 +68,16 @@ interface LeaderboardEntry {
// ---------------------------------------------------------------------------
const POINTS: Record<string, number> = {
// Integration bounties
"bounty:test": 20,
"bounty:docs": 20,
"bounty:code": 30,
"bounty:new-tool": 75,
// Standard bounties
"bounty:small": 10,
"bounty:medium": 30,
"bounty:large": 75,
"bounty:extreme": 150,
};
// ---------------------------------------------------------------------------
@@ -276,6 +282,10 @@ function formatBountyNotification(bounty: BountyResult): string {
docs: "\u{1F4DD}",
code: "\u{1F527}",
"new-tool": "\u{2B50}",
small: "\u{1F4A1}",
medium: "\u{1F6E0}",
large: "\u{1F680}",
extreme: "\u{1F525}",
};
const emoji = typeEmoji[bounty.bountyType] ?? "\u{1F3AF}";
@@ -301,7 +311,7 @@ function formatLeaderboard(entries: LeaderboardEntry[]): string {
const medals = ["\u{1F947}", "\u{1F948}", "\u{1F949}"];
let msg = "**\u{1F3C6} Integration Bounty Leaderboard**\n\n";
let msg = "**\u{1F3C6} Bounty Leaderboard**\n\n";
for (let i = 0; i < top10.length; i++) {
const entry = top10[i];
-61
View File
@@ -1,61 +0,0 @@
#!/usr/bin/env bash
#
# setup-antigravity-mcp.sh - Write Antigravity/Claude MCP config with auto-detected paths
#
# Run from anywhere inside the hive repo. Generates ~/.gemini/antigravity/mcp_config.json
# based on .agent/mcp_config.json template, with absolute paths so the IDE can
# connect to tools MCP servers without manual path editing.
#
set -e
# Find repo root
REPO_ROOT=""
if git rev-parse --show-toplevel &>/dev/null; then
REPO_ROOT="$(git rev-parse --show-toplevel)"
elif [ -f ".agent/mcp_config.json" ]; then
REPO_ROOT="$(pwd)"
else
d="$(pwd)"
while [ -n "$d" ] && [ "$d" != "/" ]; do
[ -f "$d/.agent/mcp_config.json" ] && REPO_ROOT="$d" && break
d="$(dirname "$d")"
done
fi
if [ -z "$REPO_ROOT" ] || [ ! -d "$REPO_ROOT/core" ] || [ ! -d "$REPO_ROOT/tools" ]; then
echo "Error: Run this script from inside the hive repo (could not find repo root with core/ and tools/)." >&2
exit 1
fi
TEMPLATE="$REPO_ROOT/.agent/mcp_config.json"
if [ ! -f "$TEMPLATE" ]; then
echo "Error: Template not found at $TEMPLATE" >&2
exit 1
fi
CORE_DIR="$(cd "$REPO_ROOT/core" && pwd)"
TOOLS_DIR="$(cd "$REPO_ROOT/tools" && pwd)"
mkdir -p "$HOME/.gemini/antigravity"
# Generate config from template with absolute paths
# Replace relative "core" and "tools" with absolute paths in --directory args
sed -e "s|\"--directory\", \"core\"|\"--directory\", \"$CORE_DIR\"|g" \
-e "s|\"--directory\", \"tools\"|\"--directory\", \"$TOOLS_DIR\"|g" \
"$TEMPLATE" > "$HOME/.gemini/antigravity/mcp_config.json"
echo "Wrote $HOME/.gemini/antigravity/mcp_config.json (from $TEMPLATE)"
echo " core -> $CORE_DIR"
echo " tools -> $TOOLS_DIR"
if [ "$1" = "--claude" ]; then
mkdir -p "$HOME/.claude"
cp "$HOME/.gemini/antigravity/mcp_config.json" "$HOME/.claude/mcp.json"
echo "Wrote $HOME/.claude/mcp.json"
fi
echo ""
echo "Next: Restart Antigravity IDE so it loads the MCP config."
echo " Then open this repo; tools should appear."
echo ""
echo "For Claude Code, run: $0 --claude"
+8 -2
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env bash
# Creates GitHub labels for the Integration Bounty Program.
# Creates GitHub labels for the Bounty Program.
# Usage: ./scripts/setup-bounty-labels.sh [owner/repo]
# Requires: gh CLI authenticated
@@ -9,12 +9,18 @@ REPO="${1:-adenhq/hive}"
echo "Setting up bounty labels for $REPO..."
# Bounty type labels
# Integration bounty labels
gh label create "bounty:test" --repo "$REPO" --color "1D76DB" --description "Bounty: test a tool with real API key (20 pts)" --force
gh label create "bounty:docs" --repo "$REPO" --color "FBCA04" --description "Bounty: write or improve documentation (20 pts)" --force
gh label create "bounty:code" --repo "$REPO" --color "D93F0B" --description "Bounty: health checker, bug fix, or improvement (30 pts)" --force
gh label create "bounty:new-tool" --repo "$REPO" --color "6F42C1" --description "Bounty: build a new integration from scratch (75 pts)" --force
# Standard bounty labels
gh label create "bounty:small" --repo "$REPO" --color "C2E0C6" --description "Bounty: quick fix — typos, links, error messages (10 pts)" --force
gh label create "bounty:medium" --repo "$REPO" --color "0E8A16" --description "Bounty: bug fix, tests, guides, CLI improvements (30 pts)" --force
gh label create "bounty:large" --repo "$REPO" --color "B60205" --description "Bounty: new feature, perf work, architecture docs (75 pts)" --force
gh label create "bounty:extreme" --repo "$REPO" --color "000000" --description "Bounty: major subsystem, security audit, core refactor (150 pts)" --force
# Difficulty labels
gh label create "difficulty:easy" --repo "$REPO" --color "BFD4F2" --description "Good first contribution" --force
gh label create "difficulty:medium" --repo "$REPO" --color "D4C5F9" --description "Requires some familiarity" --force
+18 -15
View File
@@ -2257,21 +2257,24 @@ if __name__ == "__main__":
)
# -- mcp_servers.json --
_write(
"mcp_servers.json",
json.dumps(
{
"hive-tools": {
"transport": "stdio",
"command": "uv",
"args": ["run", "python", "mcp_server.py", "--stdio"],
"cwd": "../../tools",
"description": "Hive tools MCP server",
}
},
indent=2,
),
)
mcp_config: dict = {
"hive-tools": {
"transport": "stdio",
"command": "uv",
"args": ["run", "python", "mcp_server.py", "--stdio"],
"cwd": "../../tools",
"description": "Hive tools MCP server",
},
"gcu-tools": {
"transport": "stdio",
"command": "uv",
"args": ["run", "python", "-m", "gcu.server", "--stdio"],
"cwd": "../../tools",
"description": "GCU browser automation tools",
},
}
_write("mcp_servers.json", json.dumps(mcp_config, indent=2))
# -- tests/conftest.py --
_write(