diff --git a/crates/tinyhivemind-lang/examples/broken/README.md b/crates/tinyhivemind-lang/examples/broken/README.md index 864f1fd3..dfd25949 100644 --- a/crates/tinyhivemind-lang/examples/broken/README.md +++ b/crates/tinyhivemind-lang/examples/broken/README.md @@ -6,7 +6,9 @@ exercise, so the report a host or editor sees is pinned by a test. | Directory | Findings | | --- | --- | | `integrations/` | The `integrations` example with an undeclared seat model (`reference`), `tools/word_count.py` removed (`missing_document`), a delegated profile that sets a model, an `argv` placeholder naming no argument, and `sqlite` sessions without a workspace (`integration`). Its [README](integrations/README.md) lists each fault and where it is located | +| `harnesses/` | The `mixed-harnesses` example with an undeclared harness (`reference`), a duplicate harness id (`identity`), and `integration` findings for `deployment` isolation on `codex`, a harness on a delegated profile, subagents on `codex`, a provider credential, a runtime sandbox and a tool argument named `call` (ten findings: two faults are reported once per rejecting kind). Its [README](harnesses/README.md) lists each one | ```sh cargo run -p tinyhivemind-lang --example hive_check -- crates/tinyhivemind-lang/examples/broken/integrations +cargo run -p tinyhivemind-lang --example hive_check -- crates/tinyhivemind-lang/examples/broken/harnesses ``` diff --git a/crates/tinyhivemind-lang/examples/broken/harnesses/README.md b/crates/tinyhivemind-lang/examples/broken/harnesses/README.md new file mode 100644 index 00000000..9be8c0b2 --- /dev/null +++ b/crates/tinyhivemind-lang/examples/broken/harnesses/README.md @@ -0,0 +1,27 @@ +# broken/harnesses + +The [`mixed-harnesses`](../../hives/mixed-harnesses/README.md) package with +eight deliberate faults, one per harness diagnostic. `hive_check` reports ten +findings: the provider credential and the runtime sandbox are each rejected +twice, once by the openclaw seat and once by the codex seat, with that kind's +reason. The report is pinned by +`the_broken_harnesses_package_reports_each_harness_finding_once` in +`../../hive_check/test.rs`. + +| Fault | Where | Rule | +| --- | --- | --- | +| Seat `lead` names the undeclared harness `ghost` | `hive.json` `/seats/0/harness` | `reference` | +| The harness id `codex` is declared twice | `hive.json` `/harnesses/2/id` | `identity` | +| The `codex` harness asks for `isolation: deployment`, which only `openclaw` accepts | `hive.json` `/harnesses/1/isolation` | `integration` | +| The delegated `helper` profile names a harness | `hive.json` `/profiles/1/harness` | `integration` | +| The `coder` profile delegates to `helper`, and `codex` rejects subagents | `hive.json` `/profiles/0/subagents` | `integration` | +| The `local` provider carries a `credential`, rejected on every kind until a conformance test proves it | `hive.json` `/providers/0/credential` | `integration` | +| `runtime.sandbox` is `read_only`, which no harness can apply to the host's executable tools | `hive.json` `/runtime/sandbox` | `integration` | +| `word_count` declares an argument named `call`, which the host adds to every served tool | `hive.json` `/tools/0/args/properties/call` | `integration` | + +| Path | Purpose | +| --- | --- | +| `hive.json` | The faulty manifest | +| `constitution.json`, `memory.json` | As in `mixed-harnesses` | +| `roles/`, `seats/` | Charters and prompts | +| `tools/` | `word_count.py` | diff --git a/crates/tinyhivemind-lang/examples/broken/harnesses/constitution.json b/crates/tinyhivemind-lang/examples/broken/harnesses/constitution.json new file mode 100644 index 00000000..a50f7ca2 --- /dev/null +++ b/crates/tinyhivemind-lang/examples/broken/harnesses/constitution.json @@ -0,0 +1,12 @@ +{ + "hard_constraints": [], + "max_turns": 60, + "max_width": 8, + "permitted_edits": [], + "read_only_memories": [], + "protected_namespaces": [], + "contamination_canaries": [], + "evaluation": null, + "acceptance": null, + "telemetry": null +} diff --git a/crates/tinyhivemind-lang/examples/broken/harnesses/hive.json b/crates/tinyhivemind-lang/examples/broken/harnesses/hive.json new file mode 100644 index 00000000..7835d886 --- /dev/null +++ b/crates/tinyhivemind-lang/examples/broken/harnesses/hive.json @@ -0,0 +1,406 @@ +{ + "$schema": "https://tinyhumans.ai/schemas/hive/v1", + "version": 1, + "id": "broken-harnesses", + "name": "Mixed harnesses", + "roles": [ + { + "id": "lead", + "charter": "roles/lead.md" + }, + { + "id": "researcher", + "charter": "roles/researcher.md" + }, + { + "id": "builder", + "charter": "roles/builder.md" + } + ], + "seats": [ + { + "id": "lead", + "label": "Lead", + "role": "lead", + "prompt": "seats/lead.md", + "template": "default", + "config": {}, + "model": null, + "tools": { + "allow": [], + "deny": [] + }, + "mcp": [], + "skills": [], + "profile": null, + "agent_id": null, + "toolpacks": [], + "hooks": [], + "permissions": null, + "limits": { + "timeout_ms": null, + "iterations": null, + "budget_usd": null + }, + "context": [], + "harness": "ghost" + }, + { + "id": "scout", + "label": "Scout", + "role": "researcher", + "prompt": "seats/scout.md", + "template": "default", + "config": {}, + "model": null, + "tools": { + "allow": [], + "deny": [] + }, + "mcp": [], + "skills": [], + "profile": null, + "agent_id": null, + "toolpacks": [], + "hooks": [], + "permissions": null, + "limits": { + "timeout_ms": null, + "iterations": null, + "budget_usd": null + }, + "context": [], + "harness": "claw" + }, + { + "id": "builder", + "label": "Builder", + "role": "builder", + "prompt": "seats/builder.md", + "template": "default", + "config": {}, + "model": null, + "tools": { + "allow": [], + "deny": [] + }, + "mcp": [], + "skills": [], + "profile": "coder", + "agent_id": null, + "toolpacks": [], + "hooks": [], + "permissions": null, + "limits": { + "timeout_ms": null, + "iterations": null, + "budget_usd": null + }, + "context": [] + } + ], + "desks": [ + { + "id": "floor", + "name": "Floor", + "description": null, + "members": [ + "lead", + "scout", + "builder" + ] + } + ], + "goals": [], + "missions": [], + "topology": [], + "referrals": [], + "context": [], + "policies": { + "episode": { + "turn_budget": 12, + "round_width": 1, + "revealed_width": 1, + "blind_round": true, + "dominance_cap": 50, + "repetition_cap": 3, + "distance": "sequence", + "quorum": { + "threshold": 2, + "window": 30, + "require_grounded": true + }, + "weights": { + "recency": 5, + "importance": 30, + "relevance": 20, + "half_life": 20 + } + }, + "routing": { + "minimum_confidence": 0, + "high_impact_minimum_confidence": 0, + "clarification_threshold": 0, + "high_impact_threshold": 0, + "round_width": 1, + "choice_option_limit": 8 + }, + "approval": { + "enabled": false, + "default": "deny", + "rules": [], + "approver": { + "kind": "absent" + }, + "allow_grants": false, + "max_grant_ttl": null + }, + "aside": { + "enabled": false, + "max_members": 0, + "max_messages": 0, + "must_surface": false, + "require_thread": false + }, + "referral": { + "enabled": false, + "max_hops": 0, + "reach": "local", + "returns": false + }, + "digest": { + "keep_live": 30, + "fold_after": 20, + "fold_after_chars": 400000, + "input_limit": 60, + "budget_chars": 4000 + }, + "brevity": { + "message_chars": 600, + "window": 30 + }, + "directory": { + "half_life": 20, + "specialisation": 30, + "credibility": 20, + "prior": 10, + "discredit": 20, + "window": 30, + "floor": 1000 + }, + "exchange": { + "enabled": false, + "contact_cap": 0, + "round_cap": 0 + }, + "division": { + "round_width": 2, + "follow_directory": true + }, + "conduct": { + "child_turn_wall": 6, + "turn_wall": 60 + } + }, + "coordinator": { + "round_width": 1, + "conduct_policy": { + "child_turn_wall": 6, + "turn_wall": 60 + }, + "broadcast_budget": null, + "retention": { + "settled_episodes": null, + "delivered": null, + "interrupted": null, + "pending_per_agent": null + } + }, + "runtime": { + "deployment_id": null, + "workspace": null, + "session_store": "memory", + "memory_engine": "disabled", + "autonomy": "supervised", + "sandbox": "read_only", + "concurrency": 4, + "max_agents": null, + "include_user_skills": false, + "start_scheduler": false, + "provider": "local", + "model": "default", + "permissions": "careful", + "toolpacks": [ + "text" + ], + "limits": { + "timeout_ms": 120000, + "iterations": null, + "budget_usd": null + } + }, + "providers": [ + { + "id": "local", + "kind": "openai", + "endpoint": "http://127.0.0.1:8080/v1", + "credential": { + "env": "LOCAL_API_KEY" + } + } + ], + "models": [ + { + "id": "default", + "provider": "local", + "name": "local-model", + "temperature": null, + "max_tokens": null, + "limits": { + "timeout_ms": null, + "iterations": null, + "budget_usd": null + } + } + ], + "mcp": [], + "skills": [], + "tools": [ + { + "id": "word_count", + "description": "Count the words, lines and characters of a text", + "command": [ + "python3", + "tools/word_count.py" + ], + "args": { + "properties": { + "text": { + "type": "string" + }, + "call": { + "type": "string" + } + }, + "required": [ + "text" + ], + "type": "object" + }, + "argv": [], + "stdin": "json", + "output": "json", + "timeout_ms": 60000, + "env": {}, + "side_effects": "read", + "cwd": "package" + } + ], + "toolpacks": [ + { + "id": "text", + "description": "Measure a text", + "tools": [ + "word_count" + ], + "mcp": [], + "skills": [], + "groups": {} + } + ], + "permissions": [ + { + "id": "careful", + "access": "supervised", + "sandbox": "none", + "allow_tools": null, + "deny_tools": [], + "send_destinations": null, + "send_operations": null, + "tool_rules": null + } + ], + "profiles": [ + { + "id": "coder", + "model": null, + "permissions": null, + "toolpacks": [], + "tools": { + "allow": [], + "deny": [] + }, + "mcp": [], + "skills": [], + "hooks": [], + "context": [], + "limits": { + "timeout_ms": null, + "iterations": null, + "budget_usd": null + }, + "subagents": [ + "helper" + ], + "bare_prompt": false, + "definition_base": null, + "harness": "codex" + }, + { + "id": "helper", + "model": null, + "permissions": null, + "toolpacks": [], + "tools": { + "allow": [], + "deny": [] + }, + "mcp": [], + "skills": [], + "hooks": [], + "context": [], + "limits": { + "timeout_ms": null, + "iterations": null, + "budget_usd": null + }, + "subagents": [], + "bare_prompt": false, + "definition_base": null, + "harness": "codex" + } + ], + "hooks": [], + "session": { + "compact_context": null, + "max_history_messages": null, + "tool_result_budget_bytes": null, + "max_tool_iterations": null, + "parallel_tools": null, + "agents_md": null + }, + "jev": { + "ranker": "jev", + "route": "auto", + "base_url": null, + "top_k": 3 + }, + "features": {}, + "workflows": [], + "harnesses": [ + { + "id": "claw", + "kind": "openclaw", + "isolation": "deployment" + }, + { + "id": "codex", + "kind": "codex", + "isolation": "deployment" + }, + { + "id": "codex", + "kind": "codex" + } + ] +} diff --git a/crates/tinyhivemind-lang/examples/broken/harnesses/memory.json b/crates/tinyhivemind-lang/examples/broken/harnesses/memory.json new file mode 100644 index 00000000..334b4f84 --- /dev/null +++ b/crates/tinyhivemind-lang/examples/broken/harnesses/memory.json @@ -0,0 +1,5 @@ +{ + "root": "team:mixed-harnesses", + "identities": [], + "bindings": [] +} diff --git a/crates/tinyhivemind-lang/examples/broken/harnesses/roles/README.md b/crates/tinyhivemind-lang/examples/broken/harnesses/roles/README.md new file mode 100644 index 00000000..b56e85b8 --- /dev/null +++ b/crates/tinyhivemind-lang/examples/broken/harnesses/roles/README.md @@ -0,0 +1,7 @@ +# roles + +| File | Purpose | +| --- | --- | +| `lead.md` | Charter of the lead role | +| `researcher.md` | Charter of the researcher role | +| `builder.md` | Charter of the builder role | diff --git a/crates/tinyhivemind-lang/examples/broken/harnesses/roles/builder.md b/crates/tinyhivemind-lang/examples/broken/harnesses/roles/builder.md new file mode 100644 index 00000000..1c4eaffc --- /dev/null +++ b/crates/tinyhivemind-lang/examples/broken/harnesses/roles/builder.md @@ -0,0 +1,2 @@ +Turns the lead's decision into a concrete draft and says what it did not +cover. diff --git a/crates/tinyhivemind-lang/examples/broken/harnesses/roles/lead.md b/crates/tinyhivemind-lang/examples/broken/harnesses/roles/lead.md new file mode 100644 index 00000000..8e9259cd --- /dev/null +++ b/crates/tinyhivemind-lang/examples/broken/harnesses/roles/lead.md @@ -0,0 +1,2 @@ +Frames the question, assigns the research and the build, and decides when +the answer is good enough to ship. diff --git a/crates/tinyhivemind-lang/examples/broken/harnesses/roles/researcher.md b/crates/tinyhivemind-lang/examples/broken/harnesses/roles/researcher.md new file mode 100644 index 00000000..10267b47 --- /dev/null +++ b/crates/tinyhivemind-lang/examples/broken/harnesses/roles/researcher.md @@ -0,0 +1,2 @@ +Finds the facts the lead asked for and reports each with where it came +from. Never changes anything. diff --git a/crates/tinyhivemind-lang/examples/broken/harnesses/seats/README.md b/crates/tinyhivemind-lang/examples/broken/harnesses/seats/README.md new file mode 100644 index 00000000..4f8ec85f --- /dev/null +++ b/crates/tinyhivemind-lang/examples/broken/harnesses/seats/README.md @@ -0,0 +1,7 @@ +# seats + +| File | Purpose | +| --- | --- | +| `lead.md` | The lead, on the default `openhuman` harness | +| `scout.md` | The scout, on the shared `claw` OpenClaw harness | +| `builder.md` | The builder, on `codex` through its `coder` profile | diff --git a/crates/tinyhivemind-lang/examples/broken/harnesses/seats/builder.md b/crates/tinyhivemind-lang/examples/broken/harnesses/seats/builder.md new file mode 100644 index 00000000..1fb29f04 --- /dev/null +++ b/crates/tinyhivemind-lang/examples/broken/harnesses/seats/builder.md @@ -0,0 +1,2 @@ +You are the builder. Draft what the lead decided and measure it with +`word_count` before you post it. diff --git a/crates/tinyhivemind-lang/examples/broken/harnesses/seats/lead.md b/crates/tinyhivemind-lang/examples/broken/harnesses/seats/lead.md new file mode 100644 index 00000000..348f4270 --- /dev/null +++ b/crates/tinyhivemind-lang/examples/broken/harnesses/seats/lead.md @@ -0,0 +1,2 @@ +You are the lead. Ask the scout for facts and the builder for a draft, then +post the decision to the floor. diff --git a/crates/tinyhivemind-lang/examples/broken/harnesses/seats/scout.md b/crates/tinyhivemind-lang/examples/broken/harnesses/seats/scout.md new file mode 100644 index 00000000..df7be8b1 --- /dev/null +++ b/crates/tinyhivemind-lang/examples/broken/harnesses/seats/scout.md @@ -0,0 +1,2 @@ +You are the scout. Answer the lead's questions and use `word_count` when a +length matters. Quote what you found. diff --git a/crates/tinyhivemind-lang/examples/broken/harnesses/tools/README.md b/crates/tinyhivemind-lang/examples/broken/harnesses/tools/README.md new file mode 100644 index 00000000..213f6afe --- /dev/null +++ b/crates/tinyhivemind-lang/examples/broken/harnesses/tools/README.md @@ -0,0 +1,5 @@ +# tools + +| File | Purpose | +| --- | --- | +| `word_count.py` | The `word_count` tool: counts the words, lines and characters of the JSON `text` on stdin | diff --git a/crates/tinyhivemind-lang/examples/broken/harnesses/tools/word_count.py b/crates/tinyhivemind-lang/examples/broken/harnesses/tools/word_count.py new file mode 100644 index 00000000..906a2715 --- /dev/null +++ b/crates/tinyhivemind-lang/examples/broken/harnesses/tools/word_count.py @@ -0,0 +1,9 @@ +"""Count words, lines and characters of the text passed as JSON on stdin.""" +import json +import sys + +text = json.load(sys.stdin)["text"] +json.dump( + {"words": len(text.split()), "lines": len(text.splitlines()), "chars": len(text)}, + sys.stdout, +) diff --git a/crates/tinyhivemind-lang/examples/hive_check/test.rs b/crates/tinyhivemind-lang/examples/hive_check/test.rs index 12e537ac..6466943f 100644 --- a/crates/tinyhivemind-lang/examples/hive_check/test.rs +++ b/crates/tinyhivemind-lang/examples/hive_check/test.rs @@ -119,3 +119,31 @@ fn the_broken_integrations_package_reports_each_rule_once() { } assert_eq!(found.len(), 5, "{located:?}"); } + +#[test] +fn the_broken_harnesses_package_reports_each_harness_finding_once() { + let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("examples/broken/harnesses"); + let (found, _) = findings(&load(&dir).expect("the broken package loads"), None); + let mut located: Vec<(String, &str)> = found + .iter() + .map(|d| (d.pointer.clone().unwrap_or_default(), d.rule.name())) + .collect(); + located.sort(); + let mut expected = [ + ("/seats/0/harness", "reference"), + ("/harnesses/2/id", "identity"), + ("/harnesses/1/isolation", "integration"), + ("/profiles/1/harness", "integration"), + ("/profiles/0/subagents", "integration"), + // Rejected by both the openclaw and the codex seat, each with its + // own kind's reason. + ("/providers/0/credential", "integration"), + ("/providers/0/credential", "integration"), + ("/runtime/sandbox", "integration"), + ("/runtime/sandbox", "integration"), + ("/tools/0/args/properties/call", "integration"), + ] + .map(|(pointer, rule)| (pointer.to_owned(), rule)); + expected.sort(); + assert_eq!(located, expected); +} diff --git a/crates/tinyhivemind-lang/examples/hives/README.md b/crates/tinyhivemind-lang/examples/hives/README.md index cab0ff53..e8e12e2a 100644 --- a/crates/tinyhivemind-lang/examples/hives/README.md +++ b/crates/tinyhivemind-lang/examples/hives/README.md @@ -15,6 +15,7 @@ part of the language; each one's `README.md` opens with what it demonstrates. | `math-panel/` | 5 | 1 | Five unreliable seats solving exact problems (`sim.json`) | | `math-swarm/` | 50 | 5 | Fifty seats in five linked desks on the same problems, rounds of ten | | `integrations/` | 2 | 1 | Every integration section: runtime, provider, models, an MCP server, a skill, bash and Python tools, a toolpack, permissions, profiles, a script hook, session, Jev, features and a workflow. `hive_check` accepts it; `broken/integrations` is the same package with five faults | +| `mixed-harnesses/` | 3 | 1 | A `harnesses` section: one seat on the default `openhuman`, one on a shared OpenClaw instance, one on Codex through its profile, with only settings every kind honours. `hive_check` accepts it; `broken/harnesses` is the same package with eight faults (ten findings) | | `euler-hive/` | 14 | 5 | A live, problem-agnostic hive: per-seat tool access (web search on research only, Python on compute and verify only), referrals, an agent memory per seat and a shared verified pool. Its own test is `tests/euler_hive_package.rs`. | `sim.json` and `script.json` are neither canonical nor Markdown, so `parse` diff --git a/crates/tinyhivemind-lang/examples/hives/mixed-harnesses/README.md b/crates/tinyhivemind-lang/examples/hives/mixed-harnesses/README.md new file mode 100644 index 00000000..78d3793b --- /dev/null +++ b/crates/tinyhivemind-lang/examples/hives/mixed-harnesses/README.md @@ -0,0 +1,35 @@ +# mixed-harnesses + +One floor of three seats, each on a different harness, that `check` accepts +under the [harness capability rules](../../../../../docs/specs/harnesses.md#capabilities). +It is the smallest package a process deployment could run: everything it +sets is a `yes` row of the table, and nothing it sets is rejected. + +| Path | Purpose | +| --- | --- | +| `hive.json` | The roster, a `harnesses` section, and integration settings every kind honours | +| `constitution.json` | Default caps; `permitted_edits` is empty | +| `memory.json` | No memory | +| `roles/` | Lead, researcher and builder charters | +| `seats/` | One prompt per seat | +| `tools/` | `word_count.py`, the one executable tool | + +What it shows: + +- `harnesses` declares `claw`, an OpenClaw harness shared by the deployment + (`isolation: deployment`), and `codex`, which takes its default of one + instance per seat. +- `lead` names no harness, so it is an `openhuman` seat; `scout` names + `claw` itself; `builder` gets `codex` from its `coder` profile. A seat's own + `harness` beats its profile's, which beats `runtime.harness`. +- The one provider is `openai` with an explicit loopback `endpoint` and no + `credential`, the only provider shape every kind is known to run. The + runtime sandbox is `none`, the toolpack turns no built-in tool group on, + and `session`, `jev`, `deployment_id` and `concurrency` are left at their + defaults. Seats carry no tool deny lists, which no harness enforces yet: + they stay off the web because no built-in tool can be turned on. + +Because it declares harnesses, every seat, the implicit `openhuman` one +included, is held to the capability table. The linked OpenHuman adapter +refuses to deploy it: until the process deployment exists, a seat on any +harness but `openhuman` cannot start. diff --git a/crates/tinyhivemind-lang/examples/hives/mixed-harnesses/constitution.json b/crates/tinyhivemind-lang/examples/hives/mixed-harnesses/constitution.json new file mode 100644 index 00000000..a50f7ca2 --- /dev/null +++ b/crates/tinyhivemind-lang/examples/hives/mixed-harnesses/constitution.json @@ -0,0 +1,12 @@ +{ + "hard_constraints": [], + "max_turns": 60, + "max_width": 8, + "permitted_edits": [], + "read_only_memories": [], + "protected_namespaces": [], + "contamination_canaries": [], + "evaluation": null, + "acceptance": null, + "telemetry": null +} diff --git a/crates/tinyhivemind-lang/examples/hives/mixed-harnesses/hive.json b/crates/tinyhivemind-lang/examples/hives/mixed-harnesses/hive.json new file mode 100644 index 00000000..ddef54ce --- /dev/null +++ b/crates/tinyhivemind-lang/examples/hives/mixed-harnesses/hive.json @@ -0,0 +1,370 @@ +{ + "$schema": "https://tinyhumans.ai/schemas/hive/v1", + "version": 1, + "id": "mixed-harnesses", + "name": "Mixed harnesses", + "roles": [ + { + "id": "lead", + "charter": "roles/lead.md" + }, + { + "id": "researcher", + "charter": "roles/researcher.md" + }, + { + "id": "builder", + "charter": "roles/builder.md" + } + ], + "seats": [ + { + "id": "lead", + "label": "Lead", + "role": "lead", + "prompt": "seats/lead.md", + "template": "default", + "config": {}, + "model": null, + "tools": { + "allow": [], + "deny": [] + }, + "mcp": [], + "skills": [], + "profile": null, + "agent_id": null, + "toolpacks": [], + "hooks": [], + "permissions": null, + "limits": { + "timeout_ms": null, + "iterations": null, + "budget_usd": null + }, + "context": [] + }, + { + "id": "scout", + "label": "Scout", + "role": "researcher", + "prompt": "seats/scout.md", + "template": "default", + "config": {}, + "model": null, + "tools": { + "allow": [], + "deny": [] + }, + "mcp": [], + "skills": [], + "profile": null, + "agent_id": null, + "toolpacks": [], + "hooks": [], + "permissions": null, + "limits": { + "timeout_ms": null, + "iterations": null, + "budget_usd": null + }, + "context": [], + "harness": "claw" + }, + { + "id": "builder", + "label": "Builder", + "role": "builder", + "prompt": "seats/builder.md", + "template": "default", + "config": {}, + "model": null, + "tools": { + "allow": [], + "deny": [] + }, + "mcp": [], + "skills": [], + "profile": "coder", + "agent_id": null, + "toolpacks": [], + "hooks": [], + "permissions": null, + "limits": { + "timeout_ms": null, + "iterations": null, + "budget_usd": null + }, + "context": [] + } + ], + "desks": [ + { + "id": "floor", + "name": "Floor", + "description": null, + "members": [ + "lead", + "scout", + "builder" + ] + } + ], + "goals": [], + "missions": [], + "topology": [], + "referrals": [], + "context": [], + "policies": { + "episode": { + "turn_budget": 12, + "round_width": 1, + "revealed_width": 1, + "blind_round": true, + "dominance_cap": 50, + "repetition_cap": 3, + "distance": "sequence", + "quorum": { + "threshold": 2, + "window": 30, + "require_grounded": true + }, + "weights": { + "recency": 5, + "importance": 30, + "relevance": 20, + "half_life": 20 + } + }, + "routing": { + "minimum_confidence": 0, + "high_impact_minimum_confidence": 0, + "clarification_threshold": 0, + "high_impact_threshold": 0, + "round_width": 1, + "choice_option_limit": 8 + }, + "approval": { + "enabled": false, + "default": "deny", + "rules": [], + "approver": { + "kind": "absent" + }, + "allow_grants": false, + "max_grant_ttl": null + }, + "aside": { + "enabled": false, + "max_members": 0, + "max_messages": 0, + "must_surface": false, + "require_thread": false + }, + "referral": { + "enabled": false, + "max_hops": 0, + "reach": "local", + "returns": false + }, + "digest": { + "keep_live": 30, + "fold_after": 20, + "fold_after_chars": 400000, + "input_limit": 60, + "budget_chars": 4000 + }, + "brevity": { + "message_chars": 600, + "window": 30 + }, + "directory": { + "half_life": 20, + "specialisation": 30, + "credibility": 20, + "prior": 10, + "discredit": 20, + "window": 30, + "floor": 1000 + }, + "exchange": { + "enabled": false, + "contact_cap": 0, + "round_cap": 0 + }, + "division": { + "round_width": 2, + "follow_directory": true + }, + "conduct": { + "child_turn_wall": 6, + "turn_wall": 60 + } + }, + "coordinator": { + "round_width": 1, + "conduct_policy": { + "child_turn_wall": 6, + "turn_wall": 60 + }, + "broadcast_budget": null, + "retention": { + "settled_episodes": null, + "delivered": null, + "interrupted": null, + "pending_per_agent": null + } + }, + "runtime": { + "deployment_id": null, + "workspace": null, + "session_store": "memory", + "memory_engine": "disabled", + "autonomy": "supervised", + "sandbox": "none", + "concurrency": 4, + "max_agents": null, + "include_user_skills": false, + "start_scheduler": false, + "provider": "local", + "model": "default", + "permissions": "careful", + "toolpacks": [ + "text" + ], + "limits": { + "timeout_ms": 120000, + "iterations": null, + "budget_usd": null + } + }, + "providers": [ + { + "id": "local", + "kind": "openai", + "endpoint": "http://127.0.0.1:8080/v1", + "credential": null + } + ], + "models": [ + { + "id": "default", + "provider": "local", + "name": "local-model", + "temperature": null, + "max_tokens": null, + "limits": { + "timeout_ms": null, + "iterations": null, + "budget_usd": null + } + } + ], + "mcp": [], + "skills": [], + "tools": [ + { + "id": "word_count", + "description": "Count the words, lines and characters of a text", + "command": [ + "python3", + "tools/word_count.py" + ], + "args": { + "properties": { + "text": { + "type": "string" + } + }, + "required": [ + "text" + ], + "type": "object" + }, + "argv": [], + "stdin": "json", + "output": "json", + "timeout_ms": 60000, + "env": {}, + "side_effects": "read", + "cwd": "package" + } + ], + "toolpacks": [ + { + "id": "text", + "description": "Measure a text", + "tools": [ + "word_count" + ], + "mcp": [], + "skills": [], + "groups": {} + } + ], + "permissions": [ + { + "id": "careful", + "access": "supervised", + "sandbox": "none", + "allow_tools": null, + "deny_tools": [], + "send_destinations": null, + "send_operations": null, + "tool_rules": null + } + ], + "profiles": [ + { + "id": "coder", + "model": null, + "permissions": null, + "toolpacks": [], + "tools": { + "allow": [], + "deny": [] + }, + "mcp": [], + "skills": [], + "hooks": [], + "context": [], + "limits": { + "timeout_ms": null, + "iterations": null, + "budget_usd": null + }, + "subagents": [], + "bare_prompt": false, + "definition_base": null, + "harness": "codex" + } + ], + "hooks": [], + "session": { + "compact_context": null, + "max_history_messages": null, + "tool_result_budget_bytes": null, + "max_tool_iterations": null, + "parallel_tools": null, + "agents_md": null + }, + "jev": { + "ranker": "jev", + "route": "auto", + "base_url": null, + "top_k": 3 + }, + "features": {}, + "workflows": [], + "harnesses": [ + { + "id": "claw", + "kind": "openclaw", + "isolation": "deployment" + }, + { + "id": "codex", + "kind": "codex" + } + ] +} diff --git a/crates/tinyhivemind-lang/examples/hives/mixed-harnesses/memory.json b/crates/tinyhivemind-lang/examples/hives/mixed-harnesses/memory.json new file mode 100644 index 00000000..334b4f84 --- /dev/null +++ b/crates/tinyhivemind-lang/examples/hives/mixed-harnesses/memory.json @@ -0,0 +1,5 @@ +{ + "root": "team:mixed-harnesses", + "identities": [], + "bindings": [] +} diff --git a/crates/tinyhivemind-lang/examples/hives/mixed-harnesses/roles/README.md b/crates/tinyhivemind-lang/examples/hives/mixed-harnesses/roles/README.md new file mode 100644 index 00000000..b56e85b8 --- /dev/null +++ b/crates/tinyhivemind-lang/examples/hives/mixed-harnesses/roles/README.md @@ -0,0 +1,7 @@ +# roles + +| File | Purpose | +| --- | --- | +| `lead.md` | Charter of the lead role | +| `researcher.md` | Charter of the researcher role | +| `builder.md` | Charter of the builder role | diff --git a/crates/tinyhivemind-lang/examples/hives/mixed-harnesses/roles/builder.md b/crates/tinyhivemind-lang/examples/hives/mixed-harnesses/roles/builder.md new file mode 100644 index 00000000..1c4eaffc --- /dev/null +++ b/crates/tinyhivemind-lang/examples/hives/mixed-harnesses/roles/builder.md @@ -0,0 +1,2 @@ +Turns the lead's decision into a concrete draft and says what it did not +cover. diff --git a/crates/tinyhivemind-lang/examples/hives/mixed-harnesses/roles/lead.md b/crates/tinyhivemind-lang/examples/hives/mixed-harnesses/roles/lead.md new file mode 100644 index 00000000..8e9259cd --- /dev/null +++ b/crates/tinyhivemind-lang/examples/hives/mixed-harnesses/roles/lead.md @@ -0,0 +1,2 @@ +Frames the question, assigns the research and the build, and decides when +the answer is good enough to ship. diff --git a/crates/tinyhivemind-lang/examples/hives/mixed-harnesses/roles/researcher.md b/crates/tinyhivemind-lang/examples/hives/mixed-harnesses/roles/researcher.md new file mode 100644 index 00000000..10267b47 --- /dev/null +++ b/crates/tinyhivemind-lang/examples/hives/mixed-harnesses/roles/researcher.md @@ -0,0 +1,2 @@ +Finds the facts the lead asked for and reports each with where it came +from. Never changes anything. diff --git a/crates/tinyhivemind-lang/examples/hives/mixed-harnesses/seats/README.md b/crates/tinyhivemind-lang/examples/hives/mixed-harnesses/seats/README.md new file mode 100644 index 00000000..4f8ec85f --- /dev/null +++ b/crates/tinyhivemind-lang/examples/hives/mixed-harnesses/seats/README.md @@ -0,0 +1,7 @@ +# seats + +| File | Purpose | +| --- | --- | +| `lead.md` | The lead, on the default `openhuman` harness | +| `scout.md` | The scout, on the shared `claw` OpenClaw harness | +| `builder.md` | The builder, on `codex` through its `coder` profile | diff --git a/crates/tinyhivemind-lang/examples/hives/mixed-harnesses/seats/builder.md b/crates/tinyhivemind-lang/examples/hives/mixed-harnesses/seats/builder.md new file mode 100644 index 00000000..1fb29f04 --- /dev/null +++ b/crates/tinyhivemind-lang/examples/hives/mixed-harnesses/seats/builder.md @@ -0,0 +1,2 @@ +You are the builder. Draft what the lead decided and measure it with +`word_count` before you post it. diff --git a/crates/tinyhivemind-lang/examples/hives/mixed-harnesses/seats/lead.md b/crates/tinyhivemind-lang/examples/hives/mixed-harnesses/seats/lead.md new file mode 100644 index 00000000..348f4270 --- /dev/null +++ b/crates/tinyhivemind-lang/examples/hives/mixed-harnesses/seats/lead.md @@ -0,0 +1,2 @@ +You are the lead. Ask the scout for facts and the builder for a draft, then +post the decision to the floor. diff --git a/crates/tinyhivemind-lang/examples/hives/mixed-harnesses/seats/scout.md b/crates/tinyhivemind-lang/examples/hives/mixed-harnesses/seats/scout.md new file mode 100644 index 00000000..df7be8b1 --- /dev/null +++ b/crates/tinyhivemind-lang/examples/hives/mixed-harnesses/seats/scout.md @@ -0,0 +1,2 @@ +You are the scout. Answer the lead's questions and use `word_count` when a +length matters. Quote what you found. diff --git a/crates/tinyhivemind-lang/examples/hives/mixed-harnesses/tools/README.md b/crates/tinyhivemind-lang/examples/hives/mixed-harnesses/tools/README.md new file mode 100644 index 00000000..213f6afe --- /dev/null +++ b/crates/tinyhivemind-lang/examples/hives/mixed-harnesses/tools/README.md @@ -0,0 +1,5 @@ +# tools + +| File | Purpose | +| --- | --- | +| `word_count.py` | The `word_count` tool: counts the words, lines and characters of the JSON `text` on stdin | diff --git a/crates/tinyhivemind-lang/examples/hives/mixed-harnesses/tools/word_count.py b/crates/tinyhivemind-lang/examples/hives/mixed-harnesses/tools/word_count.py new file mode 100644 index 00000000..906a2715 --- /dev/null +++ b/crates/tinyhivemind-lang/examples/hives/mixed-harnesses/tools/word_count.py @@ -0,0 +1,9 @@ +"""Count words, lines and characters of the text passed as JSON on stdin.""" +import json +import sys + +text = json.load(sys.stdin)["text"] +json.dump( + {"words": len(text.split()), "lines": len(text.splitlines()), "chars": len(text)}, + sys.stdout, +) diff --git a/crates/tinyhivemind-lang/src/README.md b/crates/tinyhivemind-lang/src/README.md index 3bde240a..6c90332d 100644 --- a/crates/tinyhivemind-lang/src/README.md +++ b/crates/tinyhivemind-lang/src/README.md @@ -17,7 +17,7 @@ paths. | `check` | `check` and `check_packages`: direct edits checked against the original and the constitution, every finding collected; `Review` on success. | | `diagnostic` | `Diagnostic` and `Rule`, and the collector every rule reports into. | | `document` | `Package` and `Manifest` wire types, the integration sections (`document/integration/`), `parse` and `diagnose_documents` over a caller-supplied document map. | -| `harness` | `HarnessKind`: the harnesses a package may name. | +| `harness` | Harness kinds, the `harnesses` section's entries, seat resolution and the capability table. | | `memory` | `Constitution` and `MemorySpec`: caps, protected namespaces, identities, lifecycles, reaches and recall settings. | | `validation` | `validate`, `diagnose`, `validate_path`, `validate_namespace`: references, paths, frontmatter agreement, goal acyclicity, policy bounds, memory access and the integration sections. | | `lowering` | `lower`: core desks, routing candidates, host seat creation inputs and each seat's resolved integration. | diff --git a/crates/tinyhivemind-lang/src/check/rules.rs b/crates/tinyhivemind-lang/src/check/rules.rs index 4ae3d827..689c35f0 100644 --- a/crates/tinyhivemind-lang/src/check/rules.rs +++ b/crates/tinyhivemind-lang/src/check/rules.rs @@ -339,6 +339,19 @@ pub(super) fn classify( Some(class) => owned.push((class, operation)), } } + if !permitted.contains(&PatchClass::Integration) { + for pointer in crate::harness::resolve::moves(&base.manifest, &edit.manifest) { + let message = "moving a seat to another harness needs the integration class as \ + well as roster, and the constitution does not permit integration edits" + .to_owned(); + out.push(diagnostic( + HIVE, + Some(pointer), + Rule::ForbiddenClass, + message, + )); + } + } owned } diff --git a/crates/tinyhivemind-lang/src/check/test/README.md b/crates/tinyhivemind-lang/src/check/test/README.md index d0a8a185..98e24f77 100644 --- a/crates/tinyhivemind-lang/src/check/test/README.md +++ b/crates/tinyhivemind-lang/src/check/test/README.md @@ -6,6 +6,7 @@ | `support.rs` | A valid fixture touching every edit class, file-map helpers, and assertions | | `guards.rs` | Each edit rule reported at its file and pointer | | `files.rs` | Document-map checks: an invalid original, non-package files, an undecodable edit | +| `harness.rs` | `harnesses` and `runtime.harness` are integration edits; a roster edit cannot move a seat to another harness, by its own field or its profile, unless integration is permitted too | | `integration.rs` | The integration class: a tool source, skill file and section edited under a constitution that permits or withholds it | | `sequence.rs` | Per-class changes, their order, and the `sequence` finding | | `locations.rs` | First-difference pointers, operation locations, and the `Review` wire | diff --git a/crates/tinyhivemind-lang/src/check/test/harness.rs b/crates/tinyhivemind-lang/src/check/test/harness.rs new file mode 100644 index 00000000..715591a3 --- /dev/null +++ b/crates/tinyhivemind-lang/src/check/test/harness.rs @@ -0,0 +1,154 @@ +//! Editing what a seat runs on: `harnesses` and `runtime.harness` are +//! integration edits, and moving a seat to another harness needs the +//! integration class as well as roster. +use crate::{patch::PatchClass, *}; +use serde_json::{Value, json}; +use std::collections::BTreeMap; + +/// `mixed-harnesses`, its constitution permitting exactly `permitted`. +fn original(permitted: &[PatchClass]) -> BTreeMap { + let mut docs = crate::validation::test_example("mixed-harnesses"); + let mut constitution: Constitution = + serde_json::from_str(&docs["constitution.json"]).expect("constitution decodes"); + constitution.permitted_edits = permitted.to_vec(); + docs.insert( + "constitution.json".into(), + serde_json::to_string(&constitution).expect("constitution encodes"), + ); + docs +} + +/// `base` with its manifest rewritten by `edit`. +fn edited( + base: &BTreeMap, + edit: impl FnOnce(&mut Value), +) -> BTreeMap { + let mut docs = base.clone(); + let mut manifest: Value = serde_json::from_str(&docs["hive.json"]).expect("manifest decodes"); + edit(&mut manifest); + docs.insert("hive.json".into(), manifest.to_string()); + docs +} + +fn refusals(found: &[Diagnostic]) -> Vec<(Rule, Option<&str>)> { + found + .iter() + .map(|d| (d.rule, d.pointer.as_deref())) + .collect() +} + +#[test] +fn harnesses_and_runtime_harness_are_integration_edits() { + let base = original(&[PatchClass::Roster]); + let edit = edited(&base, |m| m["harnesses"][1]["kind"] = json!("openclaw")); + let refused = check(&base, &edit).expect_err("integration is not permitted"); + assert_eq!( + refusals(&refused), + [(Rule::ForbiddenClass, Some("/harnesses/1/kind"))] + ); + let edit = edited(&base, |m| m["runtime"]["harness"] = json!("codex")); + let refused = check(&base, &edit).expect_err("integration is not permitted"); + // One finding, though the edit moves the lead and touches every seat. + assert_eq!( + refusals(&refused), + [(Rule::ForbiddenClass, Some("/runtime/harness"))] + ); + let moved = crate::harness::resolve::moves( + &parse(&base).expect("the original parses").manifest, + &crate::diagnose_documents(&edit) + .0 + .expect("the edit decodes") + .manifest, + ); + assert_eq!(moved, ["/runtime/harness"]); + let base = original(&[PatchClass::Integration]); + let edit = edited(&base, |m| m["runtime"]["harness"] = json!("codex")); + let review = check(&base, &edit).expect("integration is permitted"); + assert_eq!(review.changes.len(), 1); + assert_eq!(review.changes[0].class, PatchClass::Integration); +} + +#[test] +fn a_roster_only_edit_cannot_move_a_seat_to_another_harness() { + let base = original(&[PatchClass::Roster]); + for (edit, pointer) in [ + (json!(["seats", 1, "harness", "codex"]), "/seats/1/harness"), + (json!(["seats", 0, "harness", "claw"]), "/seats/0/harness"), + // Through a profile that names another harness. + (json!(["seats", 0, "profile", "coder"]), "/seats/0/profile"), + ] { + let path = edit.as_array().expect("an edit path"); + let edit = edited(&base, |m| { + m[path[0].as_str().expect("a key")] + [usize::try_from(path[1].as_u64().expect("an index")).expect("an index")] + [path[2].as_str().expect("a key")] = path[3].clone(); + }); + let refused = check(&base, &edit).expect_err("a roster edit cannot move a seat"); + assert!( + refusals(&refused).contains(&(Rule::ForbiddenClass, Some(pointer))), + "{pointer}: {refused:?}" + ); + } + // Dropping a seat's harness moves it to `openhuman`. + let edit = edited(&base, |m| { + m["seats"][1] + .as_object_mut() + .expect("a seat") + .remove("harness"); + }); + let refused = check(&base, &edit).expect_err("a roster edit cannot move a seat"); + assert!(refusals(&refused).contains(&(Rule::ForbiddenClass, Some("/seats/1/harness")))); + // A roster edit that leaves every harness alone is a roster edit. + let edit = edited(&base, |m| m["seats"][1]["label"] = json!("Field scout")); + let review = check(&base, &edit).expect("a plain roster edit"); + assert_eq!(review.changes[0].class, PatchClass::Roster); +} + +#[test] +fn a_new_seat_may_take_the_default_harness_but_not_name_another() { + let base = original(&[PatchClass::Roster]); + let seat = |harness: Option<&str>| { + let base = base.clone(); + let mut edit = edited(&base, |m| { + let mut seat = json!({"id": "second", "role": "builder", + "prompt": "seats/second.md", "template": "default"}); + if let Some(harness) = harness { + seat["harness"] = json!(harness); + } + m["seats"].as_array_mut().expect("seats").push(seat); + }); + edit.insert("seats/second.md".into(), "Draft a second option.\n".into()); + check(&base, &edit) + }; + assert!(seat(None).is_ok()); + let refused = seat(Some("codex")).expect_err("naming a harness needs integration"); + assert!(refusals(&refused).contains(&(Rule::ForbiddenClass, Some("/seats/3/harness")))); +} + +#[test] +fn with_integration_permitted_a_roster_edit_may_move_a_seat() { + let base = original(&[PatchClass::Roster, PatchClass::Integration]); + let edit = edited(&base, |m| m["seats"][1]["harness"] = json!("codex")); + let review = check(&base, &edit).expect("both classes are permitted"); + assert_eq!(review.changes.len(), 1); + assert_eq!(review.changes[0].class, PatchClass::Roster); + assert_eq!( + review.candidate.manifest.seats[1].harness.as_deref(), + Some("codex") + ); +} + +#[test] +fn a_recorded_roster_patch_that_moves_a_seat_is_refused_without_integration() { + let original_docs = original(&[PatchClass::Roster]); + let base = parse(&original_docs).expect("the original parses"); + let mut moved = base.clone(); + moved.manifest.seats[1].harness = Some("codex".into()); + assert!(matches!( + patch::diff(&base, &moved, PatchClass::Roster), + Err(patch::Error::ForbiddenClass) + )); + let mut renamed = base.clone(); + renamed.manifest.seats[1].label = "Field scout".into(); + assert!(patch::diff(&base, &renamed, PatchClass::Roster).is_ok()); +} diff --git a/crates/tinyhivemind-lang/src/check/test/mod.rs b/crates/tinyhivemind-lang/src/check/test/mod.rs index b9f05114..850a4d45 100644 --- a/crates/tinyhivemind-lang/src/check/test/mod.rs +++ b/crates/tinyhivemind-lang/src/check/test/mod.rs @@ -4,6 +4,7 @@ mod files; mod guards; +mod harness; mod integration; mod locations; mod sequence; diff --git a/crates/tinyhivemind-lang/src/document/README.md b/crates/tinyhivemind-lang/src/document/README.md index 59021911..89424bc8 100644 --- a/crates/tinyhivemind-lang/src/document/README.md +++ b/crates/tinyhivemind-lang/src/document/README.md @@ -20,7 +20,10 @@ three cases plain `#[serde(default)]` cannot express. `policies` is decoded as an overlay on `Policies::default()` (objects merge key by key, anything else replaces), a desk's `description` defaults to `None` without relaxing core's own `Desk` wire form, and a seat's `label` defaults to its `id`. -Serialization still writes every field. The integration sections default to +Serialization still writes every field but the harness ones (`harnesses`, +and `harness` on runtime, profile and seat), which are omitted when absent so +older packages keep their content ids; `present` and `nonempty` in +`defaults.rs` therefore refuse `null` and `[]` for them. The integration sections default to empty (or to the defaults listed in [`integration/`](integration/README.md)), so a package that predates them is unchanged. Because serde reads a struct from an array of its fields, and an empty array as all defaults, a JSON array where diff --git a/crates/tinyhivemind-lang/src/document/defaults.rs b/crates/tinyhivemind-lang/src/document/defaults.rs index 8ce7f104..bac5a271 100644 --- a/crates/tinyhivemind-lang/src/document/defaults.rs +++ b/crates/tinyhivemind-lang/src/document/defaults.rs @@ -6,11 +6,43 @@ //! field of the same seat. Each decodes leniently into the same complete //! value, so serialization, and with it the round-trip unknown-field check in //! `document/mod.rs`, is unchanged. +//! +//! The harness fields go the other way: absent, they are not serialized, so +//! a package that predates them keeps its content id. [`present`] and +//! [`nonempty`] therefore refuse the two inputs that would decode to the +//! absent value and so vanish on the round trip, `null` and `[]`. use super::{Limits, Policies, Seat, ToolAccess}; use serde::{Deserialize, Deserializer, de::Error as _}; use serde_json::Value; use tinyhivemind_core::desk::{Desk, ResponderMode}; +/// Decode an optional field that is omitted when absent: present means a +/// value, so `null` is a decode error rather than a key the round trip drops. +pub(crate) fn present<'de, D, T>(deserializer: D) -> Result, D::Error> +where + D: Deserializer<'de>, + T: Deserialize<'de>, +{ + T::deserialize(deserializer).map(Some) +} + +/// Decode a list that is omitted when empty: present means at least one +/// entry, so `[]` is a decode error rather than a key the round trip drops. +pub(crate) fn nonempty<'de, D, T>(deserializer: D) -> Result, D::Error> +where + D: Deserializer<'de>, + T: Deserialize<'de>, +{ + let list = Vec::::deserialize(deserializer)?; + if list.is_empty() { + return Err(D::Error::invalid_length( + 0, + &"at least one entry; omit the section instead", + )); + } + Ok(list) +} + /// Decode `policies` as an overlay on [`Policies::default`]. /// /// Objects merge key by key, recursively; arrays, scalars and `null` replace @@ -105,6 +137,8 @@ pub(super) struct SeatWire { limits: Limits, #[serde(default)] context: Vec, + #[serde(default, deserialize_with = "present")] + harness: Option, } impl From for Seat { @@ -127,6 +161,7 @@ impl From for Seat { permissions: wire.permissions, limits: wire.limits, context: wire.context, + harness: wire.harness, } } } diff --git a/crates/tinyhivemind-lang/src/document/integration/README.md b/crates/tinyhivemind-lang/src/document/integration/README.md index 1564bc0c..3dd7f7e1 100644 --- a/crates/tinyhivemind-lang/src/document/integration/README.md +++ b/crates/tinyhivemind-lang/src/document/integration/README.md @@ -4,7 +4,8 @@ The wire types for what a hive's agents run with. `hive.json` carries these as the sections `runtime`, `providers`, `models`, `mcp`, `skills`, `tools`, `toolpacks`, `permissions`, `profiles`, `hooks`, `session`, `jev`, `features` and `workflows`, plus the integration fields of a seat (`profile`, `agent_id`, -`toolpacks`, `hooks`, `permissions`, `limits`, `context`). The vocabulary is +`toolpacks`, `hooks`, `permissions`, `limits`, `context`, `harness`). The +`harnesses` section's entries are `crate::Harness`, in `src/harness/`. The vocabulary is OpenHuman's, since every setting must lower to something OpenHuman can run, but no type here names a harness type. diff --git a/crates/tinyhivemind-lang/src/document/integration/types.rs b/crates/tinyhivemind-lang/src/document/integration/types.rs index 77de7bf0..80da9075 100644 --- a/crates/tinyhivemind-lang/src/document/integration/types.rs +++ b/crates/tinyhivemind-lang/src/document/integration/types.rs @@ -132,6 +132,13 @@ pub struct RuntimeSettings { pub toolpacks: Vec, /// Default turn limits. pub limits: Limits, + /// Default [`crate::Harness`] id for every seat; `None` is `openhuman`. + /// Not serialized when `None`, and an explicit `null` does not decode. + #[serde( + skip_serializing_if = "Option::is_none", + deserialize_with = "crate::document::present" + )] + pub harness: Option, } impl Default for RuntimeSettings { @@ -152,6 +159,7 @@ impl Default for RuntimeSettings { permissions: None, toolpacks: Vec::new(), limits: Limits::default(), + harness: None, } } } @@ -368,6 +376,14 @@ pub struct Profile { /// A harness built-in agent definition to start from. #[serde(default)] pub definition_base: Option, + /// [`crate::Harness`] id; a delegated profile may not set one. Not + /// serialized when `None`, and an explicit `null` does not decode. + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "crate::document::present" + )] + pub harness: Option, } /// The event a hook runs on. diff --git a/crates/tinyhivemind-lang/src/document/mod.rs b/crates/tinyhivemind-lang/src/document/mod.rs index 2830c634..1fe4a779 100644 --- a/crates/tinyhivemind-lang/src/document/mod.rs +++ b/crates/tinyhivemind-lang/src/document/mod.rs @@ -12,6 +12,7 @@ use crate::{ Diagnostic, Error, Result, diagnostic::{CONSTITUTION, Findings, HIVE, MEMORY, escape}, }; +pub(crate) use defaults::present; pub use integration::*; use std::collections::BTreeMap; pub use types::*; diff --git a/crates/tinyhivemind-lang/src/document/split/README.md b/crates/tinyhivemind-lang/src/document/split/README.md index 42f57259..cae9acb0 100644 --- a/crates/tinyhivemind-lang/src/document/split/README.md +++ b/crates/tinyhivemind-lang/src/document/split/README.md @@ -6,7 +6,7 @@ manifest's top-level sections under their usual keys: | File | May hold | | --- | --- | -| `agents.json` | `roles`, `seats`, `profiles` | +| `agents.json` | `roles`, `seats`, `profiles`, `harnesses` | | `tools.json` | `tools`, `toolpacks`, `mcp`, `skills`, `hooks` | | `desks.json` | `desks`, `topology`, `referrals` | diff --git a/crates/tinyhivemind-lang/src/document/split/mod.rs b/crates/tinyhivemind-lang/src/document/split/mod.rs index 6918c44a..6444aeda 100644 --- a/crates/tinyhivemind-lang/src/document/split/mod.rs +++ b/crates/tinyhivemind-lang/src/document/split/mod.rs @@ -21,7 +21,7 @@ use serde_json::{Map, Value}; use std::collections::BTreeMap; use tinyhivemind_core::desk::Desk; -/// `agents.json`: who the hive's agents are. +/// `agents.json`: who the hive's agents are, and what they run on. pub(crate) const AGENTS: &str = "agents.json"; /// `tools.json`: what the agents can run. pub(crate) const TOOLS: &str = "tools.json"; @@ -30,7 +30,7 @@ pub(crate) const DESKS: &str = "desks.json"; /// Each split file and the manifest sections it may hold. pub(crate) const SPLITS: [(&str, &[&str]); 3] = [ - (AGENTS, &["roles", "seats", "profiles"]), + (AGENTS, &["roles", "seats", "profiles", "harnesses"]), (TOOLS, &["tools", "toolpacks", "mcp", "skills", "hooks"]), (DESKS, &["desks", "topology", "referrals"]), ]; @@ -46,6 +46,12 @@ struct AgentsFile { seats: Vec, #[serde(default)] profiles: Vec, + #[serde( + default, + skip_serializing_if = "Vec::is_empty", + deserialize_with = "super::defaults::nonempty" + )] + harnesses: Vec, } /// The typed form of `tools.json`. diff --git a/crates/tinyhivemind-lang/src/document/split/test.rs b/crates/tinyhivemind-lang/src/document/split/test.rs index f6783375..1eab0326 100644 --- a/crates/tinyhivemind-lang/src/document/split/test.rs +++ b/crates/tinyhivemind-lang/src/document/split/test.rs @@ -25,7 +25,9 @@ fn sections(file: &str) -> Vec { #[test] fn each_typed_split_file_holds_exactly_its_sections() { let empty = "{}"; - let agents: AgentsFile = serde_json::from_str(empty).expect("decodes"); + // `harnesses` is written only when it holds an entry. + let agents: AgentsFile = + serde_json::from_str(r#"{"harnesses": [{"id": "c", "kind": "codex"}]}"#).expect("decodes"); let tools: ToolsFile = serde_json::from_str(empty).expect("decodes"); let desks: DesksFile = serde_json::from_str(empty).expect("decodes"); assert_eq!(keys(&agents), sections(AGENTS)); @@ -35,7 +37,13 @@ fn each_typed_split_file_holds_exactly_its_sections() { #[test] fn every_split_section_is_a_manifest_section_owned_by_one_file() { - let manifest = keys(&super::super::Manifest::default()); + let mut manifest = super::super::Manifest::default(); + manifest.harnesses.push(crate::Harness { + id: "c".into(), + kind: crate::HarnessKind::Codex, + isolation: None, + }); + let manifest = keys(&manifest); let mut all: Vec<&str> = SPLITS.iter().flat_map(|(_, s)| s.iter().copied()).collect(); let count = all.len(); all.sort_unstable(); @@ -55,3 +63,34 @@ fn a_finding_moves_only_into_a_present_split_file_that_owns_its_section() { assert_eq!(home(HIVE, None, &present), None); assert_eq!(home("memory.json", Some("/seats"), &present), None); } + +#[test] +fn harnesses_live_in_agents_json_and_are_reported_there() { + let mut documents = crate::validation::test_example("mixed-harnesses"); + let mut hive: serde_json::Value = + serde_json::from_str(&documents[HIVE]).expect("the manifest decodes"); + let mut harnesses = hive + .as_object_mut() + .expect("an object") + .remove("harnesses") + .expect("the example declares harnesses"); + let whole = crate::parse(&documents).expect("the example parses"); + documents.insert(HIVE.into(), hive.to_string()); + documents.insert( + AGENTS.into(), + serde_json::json!({ "harnesses": harnesses }).to_string(), + ); + assert_eq!(crate::parse(&documents).expect("the split parses"), whole); + harnesses[1]["isolation"] = "deployment".into(); + documents.insert( + AGENTS.into(), + serde_json::json!({ "harnesses": harnesses }).to_string(), + ); + let (_, found) = crate::diagnose_documents(&documents); + assert!( + found + .iter() + .any(|d| d.file == AGENTS && d.pointer.as_deref() == Some("/harnesses/1/isolation")), + "{found:?}" + ); +} diff --git a/crates/tinyhivemind-lang/src/document/types.rs b/crates/tinyhivemind-lang/src/document/types.rs index c0f229a9..d143b105 100644 --- a/crates/tinyhivemind-lang/src/document/types.rs +++ b/crates/tinyhivemind-lang/src/document/types.rs @@ -8,7 +8,7 @@ use super::integration::{ ExecTool, Hook, JevSettings, Limits, McpServer, Model, PermissionSet, Profile, Provider, RuntimeSettings, SessionSettings, Skill, Toolpack, Workflow, }; -use crate::{Constitution, MemorySpec}; +use crate::{Constitution, Harness, MemorySpec}; use serde::{Deserialize, Serialize}; use serde_json::Value; use std::collections::BTreeMap; @@ -151,6 +151,14 @@ pub struct Manifest { /// Scheduled prompts. #[serde(default)] pub workflows: Vec, + /// Harnesses seats may run on. Empty, it is not serialized, and every + /// seat is an `openhuman` seat; written, it holds at least one entry. + #[serde( + default, + skip_serializing_if = "Vec::is_empty", + deserialize_with = "super::defaults::nonempty" + )] + pub harnesses: Vec, } impl Default for Manifest { fn default() -> Self { @@ -183,6 +191,7 @@ impl Default for Manifest { jev: JevSettings::default(), features: BTreeMap::new(), workflows: vec![], + harnesses: vec![], } } } @@ -206,7 +215,8 @@ pub struct Role { /// On the wire only `id`, `role`, `prompt` and `template` are required: /// `label` defaults to the seat's `id`, `config` to `{}`, `model`, `profile`, /// `agent_id` and `permissions` to `null`, `limits` to no limits, and every -/// list to empty. Unknown fields are rejected. +/// list to empty. `harness` is omitted when absent, on input and output alike. +/// Unknown fields are rejected. #[derive(Clone, Debug, Deserialize, PartialEq, Serialize, Default)] #[serde(from = "super::defaults::SeatWire")] pub struct Seat { @@ -258,6 +268,11 @@ pub struct Seat { pub limits: Limits, /// Extra `context/*.md` paths composed into the seat's prompt. pub context: Vec, + /// Id of the [`Harness`] the seat runs on; `None` inherits the profile's, + /// then the runtime's, and absent everywhere is an `openhuman` seat. Not + /// serialized when `None`, and an explicit `null` does not decode. + #[serde(skip_serializing_if = "Option::is_none")] + pub harness: Option, } /// A seat's tool access, enforced by the host; this crate only carries it. /// diff --git a/crates/tinyhivemind-lang/src/harness/README.md b/crates/tinyhivemind-lang/src/harness/README.md index 57f3462d..68921de5 100644 --- a/crates/tinyhivemind-lang/src/harness/README.md +++ b/crates/tinyhivemind-lang/src/harness/README.md @@ -1,10 +1,39 @@ # Harness kinds -`HarnessKind`: the harnesses a package may name, and their wire names. The -`harnesses` section, the capability table and the diagnostics of the -[harness spec](../../../../docs/specs/harnesses.md) are not here yet. +What a seat runs on, per the [harness spec](../../../../docs/specs/harnesses.md): +the kinds, the `harnesses` section's entries, how a seat resolves to one, and +the capability table every later crate queries. + +Public surface: `HarnessKind` (with `ALL`, `default_isolation`, `support`, +`model_api` and `iteration_cap`), `Harness` and `Isolation` (the wire +types), and `Capability`, `Support`, `Unlock` and `ModelApi`. + +The table is data, queried by `(kind, capability)`: `check` asks it for every +setting a seat resolves to, a process runner asks it before writing a harness +config, and plan step 6's gate enumerates `Capability::ALL` against +`HarnessKind::ALL`. A rejected row carries its `Unlock`, so the rows only a +conformance test can move (`Unlock::Conformance`) are named in code. Moving a +row means editing `Capability::row` and the literal table pinned in `test.rs` +in the change that proves it. + +`fields.rs` is the default-deny half: every field of every integration type +maps to a capability, to `Structure` (identities, references, labels, the +seat's `template`, the roster, desks, goals and coordinator policies), to a +nested owner, or to a by-value rule. `test.rs` reads each type's field list +from its decoder (so fields skipped when absent are included) and fails when +one has no entry; a field the walker still finds unmapped is rejected as +`Capability::Undecided`. + +`resolve.rs` is crate-private: a seat's own `harness`, else its profile's, +else `runtime.harness`, and where it came from. Lowering, validation and the +edit rules all resolve through it. `moves` finds the seats an edit moves to +another harness, which needs the `integration` class. | File | Purpose | | --- | --- | -| `mod.rs` | The type. | -| `test.rs` | Pins the wire names. | +| `mod.rs` | `HarnessKind` and the module surface | +| `types.rs` | `Harness` and `Isolation` | +| `capability.rs` | The capability table, model API and iteration cap per kind | +| `fields.rs` | Every field of every integration type and the capability that decides it: the default-deny map `check` walks | +| `resolve.rs` | Resolution by precedence, and harness moves between two manifests | +| `test.rs` | Wire names and forms, absent-field omission, and the pinned table | diff --git a/crates/tinyhivemind-lang/src/harness/capability.rs b/crates/tinyhivemind-lang/src/harness/capability.rs new file mode 100644 index 00000000..128c1316 --- /dev/null +++ b/crates/tinyhivemind-lang/src/harness/capability.rs @@ -0,0 +1,348 @@ +//! What each harness kind can honour: the capability table of the +//! [harness spec](../../../../docs/specs/harnesses.md#capabilities), as data. +//! +//! `check` asks [`HarnessKind::support`] for every setting a seat resolves to +//! and reports a [`Support::Rejected`] one at the field's location. The +//! process runners ask the same question before they write a harness config, +//! so a setting the table rejects is never accepted and dropped. A row moves +//! only with the evidence its [`Unlock`] names. +use super::HarnessKind; +use std::fmt; + +/// One row of the capability table: a setting, or a family of settings a +/// package may ask of a harness. +#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] +pub enum Capability { + /// The prompt, a model name, hive and executable tools, and + /// `limits.timeout_ms`. + Essentials, + /// Provider `openai` with an explicit `endpoint` and no `credential`. + OpenaiEndpoint, + /// Provider `openai` without an `endpoint`. + OpenaiDefaultEndpoint, + /// Provider `openrouter`. + Openrouter, + /// Provider `anthropic`. + Anthropic, + /// Provider `inherit`, or no provider at all: a child process has none + /// to inherit. + InheritedProvider, + /// A provider `credential`. + ProviderCredential, + /// Hooks and permissions on hive and executable tools. + ServedToolPolicy, + /// `sandbox` `none` or absent, on `runtime` and permission sets. + NoSandbox, + /// `sandbox` `read_only` or `sandboxed`. + Sandbox, + /// `autonomy` and `permissions.access`. + Autonomy, + /// A built-in tool group turned on (`advertised` or `withheld`). + BuiltinToolGroups, + /// `tool_rules` on built-in tools. + BuiltinToolRules, + /// Hooks on built-in tools. + BuiltinToolHooks, + /// The package's MCP servers. + McpServers, + /// `session_store = "host"`. + HostSessionStore, + /// `memory_engine = "host"`. + HostMemoryEngine, + /// A profile's `subagents`. + Subagents, + /// A profile's `definition_base`. + DefinitionBase, + /// A `jev` section other than the default. + Jev, + /// Any `session` setting. + SessionTuning, + /// `workflows`. + Workflows, + /// Skills: a seat's, a profile's or a toolpack's. + Skills, + /// `runtime.include_user_skills`. + UserSkills, + /// `limits.budget_usd`. + Budget, + /// `limits.iterations`; `OpenHuman`'s own cap is + /// [`HarnessKind::iteration_cap`]. + IterationLimit, + /// A model's `temperature`. + Temperature, + /// A model's `max_tokens`. + MaxTokens, + /// A profile's `bare_prompt`. + BarePrompt, + /// Tool allow and deny lists: `tools` on a seat or profile, and a + /// permission set's `allow_tools` and `deny_tools`. + ToolLists, + /// A permission set's `send_destinations` and `send_operations`. + SendPolicy, + /// A `stop` hook. + StopHooks, + /// A seat's factory `config`. + FactoryConfig, + /// A seat's harness `agent_id`. + AgentId, + /// `runtime.workspace`. + Workspace, + /// `runtime.deployment_id`. + DeploymentId, + /// `runtime.concurrency` other than its default. + Concurrency, + /// `runtime.max_agents`. + MaxAgents, + /// `session_store = "sqlite"`. + SqliteSessions, + /// `memory_engine = "memory"`. + InProcessMemory, + /// A field with no decision at all: the default-deny fallback, which the + /// field map's own test keeps unreachable for the language's types. + Undecided, +} + +/// How one kind honours one [`Capability`]. +#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] +pub enum Support { + /// The harness does it. + Harness, + /// The host does it, outside the harness: through its MCP server, its + /// approver or the coordinator's schedule. + Host, + /// `check` rejects it until the evidence named moves the row. + Rejected(Unlock), +} + +/// What it takes to move a rejected row. +#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] +pub enum Unlock { + /// Only a conformance test on the pinned binary, which shows the setting + /// reaches the harness and is enforced. + Conformance, + /// A harness release that has the setting, then a conformance test. + Release, + /// A change of the spec, and usually host work: the spec rejects the + /// setting on this path, or does not decide it, so no test alone moves + /// it. + Spec, +} + +/// The model API a kind speaks to an `openai` provider's endpoint. +#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] +pub enum ModelApi { + /// `POST /chat/completions`. + ChatCompletions, + /// `POST /responses`. + Responses, +} + +impl Support { + /// Whether a package may ask for it. + #[must_use] + pub const fn is_supported(self) -> bool { + !matches!(self, Self::Rejected(_)) + } +} + +impl Capability { + /// Every capability, in the order of the spec's table. + pub const ALL: [Self; 41] = [ + Self::Essentials, + Self::OpenaiEndpoint, + Self::OpenaiDefaultEndpoint, + Self::Openrouter, + Self::Anthropic, + Self::InheritedProvider, + Self::ProviderCredential, + Self::ServedToolPolicy, + Self::NoSandbox, + Self::Sandbox, + Self::Autonomy, + Self::BuiltinToolGroups, + Self::BuiltinToolRules, + Self::BuiltinToolHooks, + Self::McpServers, + Self::HostSessionStore, + Self::HostMemoryEngine, + Self::Subagents, + Self::DefinitionBase, + Self::Jev, + Self::SessionTuning, + Self::Workflows, + Self::Skills, + Self::UserSkills, + Self::Budget, + Self::IterationLimit, + Self::Temperature, + Self::MaxTokens, + Self::BarePrompt, + Self::ToolLists, + Self::SendPolicy, + Self::StopHooks, + Self::FactoryConfig, + Self::AgentId, + Self::Workspace, + Self::DeploymentId, + Self::Concurrency, + Self::MaxAgents, + Self::SqliteSessions, + Self::InProcessMemory, + Self::Undecided, + ]; + + /// The row: support for `openhuman`, `openclaw` and `codex`, in that + /// order ([`HarnessKind::ALL`]). + const fn row(self) -> [Support; 3] { + use Support::{Harness as H, Host}; + const T: Support = Support::Rejected(Unlock::Conformance); + const R: Support = Support::Rejected(Unlock::Release); + const D: Support = Support::Rejected(Unlock::Spec); + match self { + Self::Essentials | Self::OpenaiEndpoint | Self::NoSandbox => [H, H, H], + Self::ServedToolPolicy | Self::Autonomy | Self::McpServers | Self::Workflows => { + [Host, Host, Host] + } + // The spike ran one provider shape per kind; every other one + // waits for a conformance test, `credential` for one whose + // endpoint refuses a call without the right key. + Self::OpenaiDefaultEndpoint + | Self::Openrouter + | Self::Anthropic + | Self::ProviderCredential => [T, T, T], + // No fallback: a process harness never uses its own default. + Self::InheritedProvider + // Executable tools run from the host's MCP server, where nothing + // confines them, and a harness sandbox does not reach them. + | Self::Sandbox + // Built-in tools stay off until their permissions are enforced + // and the instance is contained, so nothing can hook them. + | Self::BuiltinToolGroups + | Self::BuiltinToolHooks + | Self::HostSessionStore + | Self::HostMemoryEngine + // The spec's first table does not decide these, so they start + // rejected: a setting nothing on the process path enforces must + // not be accepted. The tool lists and send policy are enforced + // by the linked adapter's permission gate, not by the host. + | Self::Skills + | Self::UserSkills + | Self::Budget + | Self::Temperature + | Self::MaxTokens + | Self::BarePrompt + | Self::ToolLists + | Self::SendPolicy + | Self::StopHooks + | Self::FactoryConfig + | Self::AgentId + | Self::Workspace + | Self::DeploymentId + | Self::Concurrency + | Self::MaxAgents + | Self::SqliteSessions + | Self::InProcessMemory + | Self::Undecided => [D, D, D], + Self::BuiltinToolRules => [R, D, D], + // OpenHuman honours a limit up to its fixed cap. + Self::IterationLimit => [H, D, D], + Self::Subagents | Self::DefinitionBase | Self::Jev | Self::SessionTuning => [T, D, D], + } + } +} + +impl HarnessKind { + /// How this kind honours `capability`. + #[must_use] + pub const fn support(self, capability: Capability) -> Support { + let row = capability.row(); + match self { + Self::OpenHuman => row[0], + Self::OpenClaw => row[1], + Self::Codex => row[2], + } + } + + /// The API this kind speaks to an `openai` provider. The language cannot + /// tell which one an endpoint serves, so `check` cannot see a mismatch; + /// the turn fails instead. + #[must_use] + pub const fn model_api(self) -> ModelApi { + match self { + Self::OpenHuman | Self::OpenClaw => ModelApi::ChatCompletions, + Self::Codex => ModelApi::Responses, + } + } + + /// The model iterations a turn stops at, when the released harness fixes + /// them: `OpenHuman` ends a custom agent after eight and reports a normal + /// end, so a package asking for more is rejected until it is + /// configurable. + #[must_use] + pub const fn iteration_cap(self) -> Option { + match self { + Self::OpenHuman => Some(8), + Self::OpenClaw | Self::Codex => None, + } + } +} + +impl fmt::Display for Capability { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Self::Essentials => "the prompt, model name, hive and executable tools and timeout", + Self::OpenaiEndpoint => "provider openai with an endpoint and no credential", + Self::OpenaiDefaultEndpoint => "provider openai without an endpoint", + Self::Openrouter => "provider openrouter", + Self::Anthropic => "provider anthropic", + Self::InheritedProvider => "an inherited provider, or none", + Self::ProviderCredential => "a provider credential", + Self::ServedToolPolicy => "hooks and permissions on hive and executable tools", + Self::NoSandbox => "no sandbox", + Self::Sandbox => "a sandbox", + Self::Autonomy => "autonomy and access", + Self::BuiltinToolGroups => "a built-in tool group turned on", + Self::BuiltinToolRules => "tool rules on built-in tools", + Self::BuiltinToolHooks => "hooks on built-in tools", + Self::McpServers => "package mcp servers", + Self::HostSessionStore => "a host session store", + Self::HostMemoryEngine => "a host memory engine", + Self::Subagents => "subagents", + Self::DefinitionBase => "a definition base", + Self::Jev => "jev settings", + Self::SessionTuning => "session tuning", + Self::Workflows => "workflows", + Self::Skills => "skills", + Self::UserSkills => "the operator's own skills", + Self::Budget => "a turn budget", + Self::IterationLimit => "an iteration limit", + Self::Temperature => "a model temperature", + Self::MaxTokens => "a model token limit", + Self::BarePrompt => "a bare prompt", + Self::ToolLists => "tool allow and deny lists", + Self::SendPolicy => "send destination and operation limits", + Self::StopHooks => "stop hooks", + Self::FactoryConfig => "a factory config", + Self::AgentId => "a harness agent id", + Self::Workspace => "a runtime workspace", + Self::DeploymentId => "a deployment id", + Self::Concurrency => "a runtime concurrency", + Self::MaxAgents => "an agent limit", + Self::SqliteSessions => "sqlite sessions", + Self::InProcessMemory => "an in-process memory engine", + Self::Undecided => "a setting the harness spec has not decided", + }) + } +} + +impl fmt::Display for Unlock { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Self::Conformance => "rejected until a conformance test on the pinned binary proves it", + Self::Release => { + "rejected until a harness release has it and a conformance test proves it" + } + Self::Spec => "rejected by the harness spec", + }) + } +} diff --git a/crates/tinyhivemind-lang/src/harness/fields.rs b/crates/tinyhivemind-lang/src/harness/fields.rs new file mode 100644 index 00000000..1f057ebc --- /dev/null +++ b/crates/tinyhivemind-lang/src/harness/fields.rs @@ -0,0 +1,292 @@ +//! Every field of every integration type, and the capability that decides +//! it: the default-deny half of the capability table. +//! +//! When a package is judged, a field set to anything but its default is +//! reported unless its kind supports the field's [`Capability`]. A field the +//! spec's table does not list has a row that starts rejected, so nothing a +//! package says is accepted and left unenforced. A test serializes each type +//! and fails when a field has no entry here, so a field added later must be +//! decided before it can be written. +use super::Capability as C; + +/// How one field is judged. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum Field { + /// Language structure with no setting of its own: an identity, a + /// reference whose target is judged where it is declared, prose, or a + /// coordinator policy the coordinator runs whatever the harness. + Structure, + /// An object judged field by field under another owner. + Nested(&'static str), + /// Any value but the default asks for this capability. + Judged(C), + /// Judged by value in `validation/capability.rs` (a provider's shape, a + /// sandbox, a store, tool rules, tool groups, a hook's event, the + /// iteration limit). + Special, +} + +use Field::{Judged as J, Nested as N, Special as X, Structure as S}; + +/// Each owner's fields, in wire order. +const FIELDS: &[(&str, &[(&str, Field)])] = &[ + ( + "manifest", + &[ + // The hive's structure and deliberation are the coordinator's. + ("$schema", S), + ("version", S), + ("id", S), + ("name", S), + ("roles", S), + ("seats", S), + ("desks", S), + ("goals", S), + ("missions", S), + ("topology", S), + ("referrals", S), + ("context", J(C::Essentials)), + ("policies", S), + ("coordinator", S), + // Sections are judged entry by entry, where a seat reaches them. + ("runtime", S), + ("providers", S), + ("models", S), + ("mcp", S), + ("skills", S), + ("tools", S), + ("toolpacks", S), + ("permissions", S), + ("profiles", S), + ("hooks", S), + ("session", S), + ("jev", S), + // Switches empty an integration in lowering; every flag reaches + // executable tools as `THM_FEATURE_*` through `tinyhivemind-exec`. + ("features", J(C::Essentials)), + ("workflows", J(C::Workflows)), + ("harnesses", S), + ], + ), + ( + "runtime", + &[ + ("deployment_id", J(C::DeploymentId)), + ("workspace", J(C::Workspace)), + ("session_store", X), + ("memory_engine", X), + ("autonomy", J(C::Autonomy)), + ("sandbox", X), + ("concurrency", J(C::Concurrency)), + ("max_agents", J(C::MaxAgents)), + ("include_user_skills", J(C::UserSkills)), + ("start_scheduler", J(C::Workflows)), + ("provider", S), + ("model", S), + ("permissions", S), + ("toolpacks", S), + ("limits", N("limits")), + ("harness", S), + ], + ), + ( + "limits", + &[ + ("timeout_ms", J(C::Essentials)), + ("iterations", X), + ("budget_usd", J(C::Budget)), + ], + ), + ( + "provider", + &[("id", S), ("kind", X), ("endpoint", X), ("credential", X)], + ), + ( + "model", + &[ + ("id", S), + ("provider", S), + ("name", J(C::Essentials)), + ("temperature", J(C::Temperature)), + ("max_tokens", J(C::MaxTokens)), + ("limits", N("limits")), + ], + ), + ( + "mcp", + &[ + ("id", S), + ("transport", J(C::McpServers)), + ("endpoint", J(C::McpServers)), + ("args", J(C::McpServers)), + ("env", J(C::McpServers)), + ("headers", J(C::McpServers)), + ("tools", J(C::McpServers)), + ("deny_tools", J(C::McpServers)), + ], + ), + ("skill", &[("id", J(C::Skills))]), + ( + "tool", + &[ + ("id", S), + ("description", J(C::Essentials)), + ("command", J(C::Essentials)), + ("args", X), + ("argv", J(C::Essentials)), + ("stdin", J(C::Essentials)), + ("output", J(C::Essentials)), + ("timeout_ms", J(C::Essentials)), + ("env", J(C::Essentials)), + ("side_effects", J(C::Essentials)), + ("cwd", J(C::Essentials)), + ], + ), + ( + "toolpack", + &[ + ("id", S), + ("description", S), + ("tools", J(C::Essentials)), + ("mcp", J(C::McpServers)), + ("skills", J(C::Skills)), + ("groups", X), + ], + ), + ( + "permissions", + &[ + ("id", S), + ("access", J(C::Autonomy)), + ("sandbox", X), + ("allow_tools", J(C::ToolLists)), + ("deny_tools", J(C::ToolLists)), + ("send_destinations", J(C::SendPolicy)), + ("send_operations", J(C::SendPolicy)), + ("tool_rules", X), + ], + ), + ( + "profile", + &[ + ("id", S), + ("model", S), + ("permissions", S), + ("toolpacks", S), + ("tools", N("tools")), + ("mcp", J(C::McpServers)), + ("skills", J(C::Skills)), + ("hooks", S), + ("context", J(C::Essentials)), + ("limits", N("limits")), + ("subagents", J(C::Subagents)), + ("bare_prompt", J(C::BarePrompt)), + ("definition_base", J(C::DefinitionBase)), + ("harness", S), + ], + ), + ( + "tools", + &[("allow", J(C::ToolLists)), ("deny", J(C::ToolLists))], + ), + ( + "hook", + &[ + ("id", S), + ("event", X), + ("matcher", J(C::ServedToolPolicy)), + ("run", J(C::ServedToolPolicy)), + ("fail_closed", J(C::ServedToolPolicy)), + ("timeout_ms", J(C::ServedToolPolicy)), + ], + ), + ( + "session", + &[ + ("compact_context", J(C::SessionTuning)), + ("max_history_messages", J(C::SessionTuning)), + ("tool_result_budget_bytes", J(C::SessionTuning)), + ("max_tool_iterations", J(C::SessionTuning)), + ("parallel_tools", J(C::SessionTuning)), + ("agents_md", J(C::SessionTuning)), + ], + ), + ( + "jev", + &[ + ("ranker", J(C::Jev)), + ("route", J(C::Jev)), + ("base_url", J(C::Jev)), + ("top_k", J(C::Jev)), + ], + ), + ( + "workflow", + &[ + ("id", S), + ("schedule", J(C::Workflows)), + ("target", J(C::Workflows)), + ("prompt", J(C::Workflows)), + ("enabled", J(C::Workflows)), + ("retries", J(C::Workflows)), + ("single_flight", J(C::Workflows)), + ], + ), + ( + "seat", + &[ + ("id", S), + ("label", S), + ("role", S), + ("prompt", J(C::Essentials)), + // The host's name for the factory that creates the agent. It + // carries no setting a harness applies; what the seat runs on + // is its `harness`, judged on its own. + ("template", S), + ("config", J(C::FactoryConfig)), + ("model", S), + ("tools", N("tools")), + ("mcp", J(C::McpServers)), + ("skills", J(C::Skills)), + ("profile", S), + ("agent_id", J(C::AgentId)), + ("toolpacks", S), + ("hooks", S), + ("permissions", S), + ("limits", N("limits")), + ("context", J(C::Essentials)), + ("harness", S), + ], + ), + // The harness entry is the decision itself. + ("harness", &[("id", S), ("kind", S), ("isolation", S)]), +]; + +/// The decision for `owner`'s field `key`, if it has one. +pub(crate) fn field(owner: &str, key: &str) -> Option { + FIELDS + .iter() + .find(|(name, _)| *name == owner)? + .1 + .iter() + .find(|(name, _)| *name == key) + .map(|(_, field)| *field) +} + +#[cfg(test)] +/// Every owner, in table order. +pub(crate) fn owners() -> Vec<&'static str> { + FIELDS.iter().map(|(owner, _)| *owner).collect() +} + +#[cfg(test)] +/// `owner`'s field names, sorted. +pub(crate) fn keys(owner: &str) -> Vec { + let mut keys: Vec = FIELDS + .iter() + .find(|(name, _)| *name == owner) + .map(|(_, fields)| fields.iter().map(|(key, _)| (*key).to_owned()).collect()) + .unwrap_or_default(); + keys.sort(); + keys +} diff --git a/crates/tinyhivemind-lang/src/harness/mod.rs b/crates/tinyhivemind-lang/src/harness/mod.rs index d34bb90b..8c278303 100644 --- a/crates/tinyhivemind-lang/src/harness/mod.rs +++ b/crates/tinyhivemind-lang/src/harness/mod.rs @@ -1,6 +1,12 @@ //! Which harness a seat runs on. +mod capability; +pub(crate) mod fields; +pub(crate) mod resolve; +mod types; +pub use capability::{Capability, ModelApi, Support, Unlock}; use serde::{Deserialize, Serialize}; use std::fmt; +pub use types::{Harness, Isolation}; /// A harness, by the name a package gives it. /// @@ -17,6 +23,22 @@ pub enum HarnessKind { Codex, } +impl HarnessKind { + /// Every kind, in the order the capability table lists them. + pub const ALL: [Self; 3] = [Self::OpenHuman, Self::OpenClaw, Self::Codex]; + + /// How instances of this kind are shared when a harness entry does not + /// say: one per deployment for `openclaw`, whose instance costs + /// gigabytes, one per seat otherwise. + #[must_use] + pub const fn default_isolation(self) -> Isolation { + match self { + Self::OpenClaw => Isolation::Deployment, + Self::OpenHuman | Self::Codex => Isolation::Seat, + } + } +} + impl fmt::Display for HarnessKind { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(match self { diff --git a/crates/tinyhivemind-lang/src/harness/resolve.rs b/crates/tinyhivemind-lang/src/harness/resolve.rs new file mode 100644 index 00000000..29fa42f3 --- /dev/null +++ b/crates/tinyhivemind-lang/src/harness/resolve.rs @@ -0,0 +1,111 @@ +//! Which harness a seat resolves to, and which field named it. +//! +//! `harness` resolves like `model`: the seat's own, else its profile's, else +//! the runtime's. Lowering, validation and the edit rules all resolve through +//! here, so they cannot disagree about a seat's harness. +use crate::{Harness, Manifest, Seat}; + +/// The field a seat's harness came from. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum Origin { + /// The seat's own `harness`. + Seat, + /// `harness` on the profile at this index of `profiles`. + Profile(usize), + /// `runtime.harness`. + Runtime, +} + +impl Origin { + /// The JSON Pointer of the naming field, for the seat at `seat`. + pub(crate) fn pointer(self, seat: usize) -> String { + match self { + Self::Seat => format!("/seats/{seat}/harness"), + Self::Profile(k) => format!("/profiles/{k}/harness"), + Self::Runtime => "/runtime/harness".into(), + } + } +} + +/// The harness id `seat` names, most specific first, and where it was +/// named; `None` when nothing names one and the seat is an `openhuman` seat. +pub(crate) fn named<'a>(manifest: &'a Manifest, seat: &'a Seat) -> Option<(&'a str, Origin)> { + if let Some(id) = &seat.harness { + return Some((id, Origin::Seat)); + } + let profile = seat.profile.as_ref().and_then(|id| { + manifest + .profiles + .iter() + .position(|profile| &profile.id == id) + }); + if let Some(k) = profile + && let Some(id) = &manifest.profiles[k].harness + { + return Some((id, Origin::Profile(k))); + } + manifest + .runtime + .harness + .as_deref() + .map(|id| (id, Origin::Runtime)) +} + +/// Whether the capability table judges `manifest`: it declares a harness, +/// or names one anywhere. One that does neither is deployed by the linked +/// adapter under its own limits. +pub(crate) fn judged(manifest: &Manifest) -> bool { + !manifest.harnesses.is_empty() + || manifest.runtime.harness.is_some() + || manifest.profiles.iter().any(|p| p.harness.is_some()) + || manifest.seats.iter().any(|s| s.harness.is_some()) +} + +/// The declared harness `id`, if the `harnesses` section has it. +pub(crate) fn declared<'a>(manifest: &'a Manifest, id: &str) -> Option<&'a Harness> { + manifest.harnesses.iter().find(|harness| harness.id == id) +} + +/// The declared harness `seat` resolves to; `None` for an `openhuman` seat +/// that names none, or a reference validation reports as unresolved. +pub(crate) fn resolve<'a>(manifest: &'a Manifest, seat: &'a Seat) -> Option<&'a Harness> { + named(manifest, seat).and_then(|(id, _)| declared(manifest, id)) +} + +/// Where `edit` moves a seat of `base` to another harness, as JSON Pointers +/// into `edit`'s manifest. +/// +/// A seat moves when its own `harness` field changes (a new seat counts from +/// no field), or when the harness it resolves to changes: an existing seat +/// against what it resolved to in `base`, a new one against `runtime.harness`. +/// A change of `runtime.harness` or a profile's `harness` is itself an +/// integration edit; one through a seat's `profile` is located there. +pub(crate) fn moves(base: &Manifest, edit: &Manifest) -> Vec { + let mut found = Vec::new(); + for (i, seat) in edit.seats.iter().enumerate() { + let before = base.seats.iter().find(|s| s.id == seat.id); + let was = before.and_then(|s| s.harness.as_ref()); + let resolved = named(edit, seat); + let baseline = match before { + Some(before) => named(base, before).map(|(id, _)| id), + None => edit.runtime.harness.as_deref(), + }; + let at = if seat.harness.as_ref() != was { + Origin::Seat.pointer(i) + } else if resolved.map(|(id, _)| id) != baseline { + let profile_changed = before.is_none_or(|before| before.profile != seat.profile); + match resolved { + Some((_, origin)) if !profile_changed => origin.pointer(i), + _ => format!("/seats/{i}/profile"), + } + } else { + continue; + }; + // Every seat that inherits a changed `runtime.harness` moves at one + // field, and is one finding. + if !found.contains(&at) { + found.push(at); + } + } + found +} diff --git a/crates/tinyhivemind-lang/src/harness/test.rs b/crates/tinyhivemind-lang/src/harness/test.rs index 09580b92..59bfbd87 100644 --- a/crates/tinyhivemind-lang/src/harness/test.rs +++ b/crates/tinyhivemind-lang/src/harness/test.rs @@ -1,5 +1,8 @@ -//! The names a package gives harnesses. -use super::HarnessKind; +//! The names a package gives harnesses, and the wire form of the `harnesses` +//! section and the `harness` fields. +#![allow(clippy::unwrap_used)] // Tests fail loudly on unexpected results. +use super::{Capability, Harness, HarnessKind, Isolation, ModelApi, Support, Unlock}; +use crate::{Manifest, Profile, RuntimeSettings, Seat}; use serde_json::json; #[test] @@ -18,3 +21,324 @@ fn each_kind_has_the_name_a_package_uses() -> Result<(), serde_json::Error> { } Ok(()) } + +#[test] +fn a_harness_entry_is_an_id_a_kind_and_an_optional_isolation() { + let shared: Harness = serde_json::from_value( + json!({"id": "claw", "kind": "openclaw", "isolation": "deployment"}), + ) + .unwrap(); + assert_eq!( + shared, + Harness { + id: "claw".into(), + kind: HarnessKind::OpenClaw, + isolation: Some(Isolation::Deployment), + } + ); + assert_eq!( + serde_json::to_value(&shared).unwrap(), + json!({"id": "claw", "kind": "openclaw", "isolation": "deployment"}) + ); + // An omitted isolation is not written back, and takes the kind's default. + let codex: Harness = serde_json::from_value(json!({"id": "codex", "kind": "codex"})).unwrap(); + assert_eq!(codex.isolation, None); + assert_eq!( + serde_json::to_value(&codex).unwrap(), + json!({"id": "codex", "kind": "codex"}) + ); + assert_eq!(codex.resolved_isolation(), Isolation::Seat); + let claw: Harness = serde_json::from_value(json!({"id": "c", "kind": "openclaw"})).unwrap(); + assert_eq!(claw.resolved_isolation(), Isolation::Deployment); + let seat = Harness { + isolation: Some(Isolation::Seat), + ..claw + }; + assert_eq!(seat.resolved_isolation(), Isolation::Seat); + assert_eq!( + serde_json::to_value(Isolation::Seat).unwrap(), + json!("seat") + ); +} + +#[test] +fn a_harness_entry_rejects_unknown_fields_a_missing_kind_and_null() { + for bad in [ + json!({"id": "c", "kind": "codex", "program": "/usr/bin/codex"}), + json!({"id": "c"}), + json!({"id": "c", "kind": "codex", "isolation": null}), + json!({"id": "c", "kind": "codex", "isolation": "process"}), + ] { + assert!( + serde_json::from_value::(bad.clone()).is_err(), + "{bad}" + ); + } +} + +/// A minimal manifest with one seat, extended by `extra`. +fn manifest(extra: &serde_json::Value) -> serde_json::Value { + let mut manifest = json!({ + "$schema": "https://tinyhumans.ai/schemas/hive/v1", + "version": 1, + "id": "h", + "name": "H", + "seats": [{"id": "a", "role": "r", "prompt": "seats/a.md", "template": "t"}] + }); + for (key, value) in extra.as_object().unwrap() { + manifest[key] = value.clone(); + } + manifest +} + +#[test] +fn an_absent_harness_is_not_serialized_anywhere() { + let decoded: Manifest = serde_json::from_value(manifest(&json!({}))).unwrap(); + let wire = serde_json::to_value(&decoded).unwrap(); + assert!(wire.get("harnesses").is_none()); + assert!(wire["runtime"].get("harness").is_none()); + assert!(wire["seats"][0].get("harness").is_none()); + let profile: Profile = serde_json::from_value(json!({"id": "p"})).unwrap(); + assert!( + serde_json::to_value(&profile) + .unwrap() + .get("harness") + .is_none() + ); + assert!( + serde_json::to_value(RuntimeSettings::default()) + .unwrap() + .get("harness") + .is_none() + ); +} + +#[test] +fn a_named_harness_is_carried_on_runtime_profile_and_seat() { + let mut input = manifest(&json!({ + "harnesses": [{"id": "codex", "kind": "codex"}], + "runtime": {"harness": "codex"}, + "profiles": [{"id": "p", "harness": "codex"}] + })); + input["seats"][0]["harness"] = json!("codex"); + let decoded: Manifest = serde_json::from_value(input).unwrap(); + assert_eq!(decoded.harnesses[0].kind, HarnessKind::Codex); + assert_eq!(decoded.runtime.harness.as_deref(), Some("codex")); + assert_eq!(decoded.profiles[0].harness.as_deref(), Some("codex")); + assert_eq!(decoded.seats[0].harness.as_deref(), Some("codex")); + let wire = serde_json::to_value(&decoded).unwrap(); + assert_eq!(wire["harnesses"], json!([{"id": "codex", "kind": "codex"}])); + assert_eq!(wire["runtime"]["harness"], "codex"); + assert_eq!(wire["profiles"][0]["harness"], "codex"); + assert_eq!(wire["seats"][0]["harness"], "codex"); + let seat: Seat = serde_json::from_value(wire["seats"][0].clone()).unwrap(); + assert_eq!(seat, decoded.seats[0]); +} + +/// A written value must survive the round trip, so the two spellings of +/// "nothing" that would not, `null` and an empty list, are decode errors +/// rather than a silent omission. +#[test] +fn an_explicit_null_harness_or_an_empty_harnesses_list_does_not_decode() { + let mut seat_null = manifest(&json!({})); + seat_null["seats"][0]["harness"] = json!(null); + for bad in [ + manifest(&json!({"harnesses": []})), + manifest(&json!({"runtime": {"harness": null}})), + manifest(&json!({"profiles": [{"id": "p", "harness": null}]})), + seat_null, + ] { + assert!( + serde_json::from_value::(bad.clone()).is_err(), + "{bad}" + ); + } +} + +/// The table as the spec writes it, one row per capability and one column +/// per kind. Moving a row is a deliberate change to this literal, made in the +/// same change as the conformance test (or the decision) that moves it. +#[test] +fn the_capability_table_is_the_spec_table() { + use Capability as C; + use Support::{Harness as H, Host, Rejected}; + const T: Support = Rejected(Unlock::Conformance); + const R: Support = Rejected(Unlock::Release); + const D: Support = Rejected(Unlock::Spec); + let table = [ + (C::Essentials, [H, H, H]), + (C::OpenaiEndpoint, [H, H, H]), + (C::OpenaiDefaultEndpoint, [T, T, T]), + (C::Openrouter, [T, T, T]), + (C::Anthropic, [T, T, T]), + (C::InheritedProvider, [D, D, D]), + (C::ProviderCredential, [T, T, T]), + (C::ServedToolPolicy, [Host, Host, Host]), + (C::NoSandbox, [H, H, H]), + (C::Sandbox, [D, D, D]), + (C::Autonomy, [Host, Host, Host]), + (C::BuiltinToolGroups, [D, D, D]), + (C::BuiltinToolRules, [R, D, D]), + (C::BuiltinToolHooks, [D, D, D]), + (C::McpServers, [Host, Host, Host]), + (C::HostSessionStore, [D, D, D]), + (C::HostMemoryEngine, [D, D, D]), + (C::Subagents, [T, D, D]), + (C::DefinitionBase, [T, D, D]), + (C::Jev, [T, D, D]), + (C::SessionTuning, [T, D, D]), + (C::Workflows, [Host, Host, Host]), + (C::Skills, [D, D, D]), + (C::UserSkills, [D, D, D]), + (C::Budget, [D, D, D]), + (C::IterationLimit, [H, D, D]), + (C::Temperature, [D, D, D]), + (C::MaxTokens, [D, D, D]), + (C::BarePrompt, [D, D, D]), + (C::ToolLists, [D, D, D]), + (C::SendPolicy, [D, D, D]), + (C::StopHooks, [D, D, D]), + (C::FactoryConfig, [D, D, D]), + (C::AgentId, [D, D, D]), + (C::Workspace, [D, D, D]), + (C::DeploymentId, [D, D, D]), + (C::Concurrency, [D, D, D]), + (C::MaxAgents, [D, D, D]), + (C::SqliteSessions, [D, D, D]), + (C::InProcessMemory, [D, D, D]), + (C::Undecided, [D, D, D]), + ]; + assert_eq!( + table.iter().map(|(c, _)| *c).collect::>(), + Capability::ALL + ); + for (capability, row) in table { + for (kind, support) in HarnessKind::ALL.into_iter().zip(row) { + assert_eq!(kind.support(capability), support, "{kind} {capability}"); + } + } +} + +#[test] +fn only_a_rejected_row_is_unsupported_and_each_row_reads_as_prose() { + assert!(Support::Harness.is_supported()); + assert!(Support::Host.is_supported()); + assert!(!Support::Rejected(Unlock::Conformance).is_supported()); + for capability in Capability::ALL { + let prose = capability.to_string(); + assert!( + !prose.is_empty() && prose == prose.to_lowercase(), + "{prose}" + ); + } + assert_eq!( + Capability::OpenaiDefaultEndpoint.to_string(), + "provider openai without an endpoint" + ); + assert_eq!( + Unlock::Conformance.to_string(), + "rejected until a conformance test on the pinned binary proves it" + ); +} + +#[test] +fn each_kind_names_its_model_api_and_iteration_cap() { + assert_eq!( + HarnessKind::OpenHuman.model_api(), + ModelApi::ChatCompletions + ); + assert_eq!(HarnessKind::OpenClaw.model_api(), ModelApi::ChatCompletions); + assert_eq!(HarnessKind::Codex.model_api(), ModelApi::Responses); + assert_eq!(HarnessKind::OpenHuman.iteration_cap(), Some(8)); + assert_eq!(HarnessKind::OpenClaw.iteration_cap(), None); + assert_eq!(HarnessKind::Codex.iteration_cap(), None); + assert_eq!( + HarnessKind::OpenClaw.default_isolation(), + Isolation::Deployment + ); + assert_eq!(HarnessKind::Codex.default_isolation(), Isolation::Seat); +} + +/// Every field `T` declares, read from the decoder rather than from a +/// serialized value, so a field skipped when absent is still listed: a +/// `deny_unknown_fields` struct names them all when it refuses a stray key. +fn declared_fields() -> Vec { + let message = serde_json::from_value::(json!({"__probe__": 0})) + .err() + .unwrap() + .to_string(); + let list = message + .split_once("expected one of ") + .or_else(|| message.split_once("expected ")) + .unwrap() + .1; + let mut fields: Vec = list + .split(", ") + .flat_map(|part| part.split(" or ")) + .map(|name| name.trim_matches('`').to_owned()) + .collect(); + fields.sort(); + fields +} + +/// Every field of every integration type has a capability decision. The +/// field lists come from each type's decoder, so a field added to one of +/// these types without an entry in `fields.rs` fails here, whether or not +/// it serializes when absent. +#[test] +fn every_field_the_language_has_has_a_capability_decision() { + use crate::*; + let samples: Vec<(&str, Vec)> = vec![ + ("manifest", declared_fields::()), + ("runtime", declared_fields::()), + ("limits", declared_fields::()), + ("provider", declared_fields::()), + ("model", declared_fields::()), + ("mcp", declared_fields::()), + ("skill", declared_fields::()), + ("tool", declared_fields::()), + ("toolpack", declared_fields::()), + ("permissions", declared_fields::()), + ("profile", declared_fields::()), + ("tools", declared_fields::()), + ("hook", declared_fields::()), + ("session", declared_fields::()), + ("jev", declared_fields::()), + ("workflow", declared_fields::()), + ("seat", declared_fields::()), + ("harness", declared_fields::()), + ]; + let owners: Vec<&str> = samples.iter().map(|(owner, _)| *owner).collect(); + assert_eq!(super::fields::owners(), owners); + for (owner, keys) in samples { + assert_eq!(super::fields::keys(owner), keys, "{owner}"); + for key in &keys { + if let Some(super::fields::Field::Nested(inner)) = super::fields::field(owner, key) { + assert!(owners.contains(&inner), "{owner}.{key} nests {inner}"); + } + } + } + // The harness fields, skipped when absent, are among them. + assert!(declared_fields::().contains(&"harness".to_owned())); +} + +#[test] +fn a_runtime_harness_change_is_one_move_however_many_seats_inherit_it() { + let mut base: crate::Manifest = serde_json::from_value(json!({ + "$schema": "https://tinyhumans.ai/schemas/hive/v1", "version": 1, "id": "h", "name": "H", + "harnesses": [{"id": "codex", "kind": "codex"}], + "seats": [ + {"id": "a", "role": "r", "prompt": "seats/a.md", "template": "t"}, + {"id": "b", "role": "r", "prompt": "seats/b.md", "template": "t"} + ] + })) + .unwrap(); + let mut edit = base.clone(); + edit.runtime.harness = Some("codex".into()); + assert_eq!(super::resolve::moves(&base, &edit), ["/runtime/harness"]); + base.runtime.harness = Some("codex".into()); + assert_eq!( + super::resolve::moves(&base, &base.clone()), + Vec::::new() + ); +} diff --git a/crates/tinyhivemind-lang/src/harness/types.rs b/crates/tinyhivemind-lang/src/harness/types.rs new file mode 100644 index 00000000..3f21e9df --- /dev/null +++ b/crates/tinyhivemind-lang/src/harness/types.rs @@ -0,0 +1,47 @@ +//! Wire types of the `harnesses` section. +use super::HarnessKind; +use serde::{Deserialize, Serialize}; + +/// Whether a harness instance serves one seat or a whole deployment. +#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum Isolation { + /// One supervised instance per seat. + Seat, + /// One instance every seat of the deployment on this harness shares. + /// Only `openclaw` accepts it, and it is that kind's default. + Deployment, +} + +/// One entry of the `harnesses` section: a harness seats may name. +/// +/// A package names only the kind and how instances are shared. It never +/// names an executable, port, state path or harness configuration: the host +/// maps a kind to a program, so a package edit cannot reach the process +/// that enforces its permissions. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(deny_unknown_fields)] +pub struct Harness { + /// Identity runtime, profiles and seats refer to. + pub id: String, + /// The harness kind. + pub kind: HarnessKind, + /// Instance sharing; `None` takes the kind's default + /// ([`Harness::resolved_isolation`]). Omitted when `None`; an explicit + /// `null` is a decode error. + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "crate::document::present" + )] + pub isolation: Option, +} + +impl Harness { + /// The isolation in force: the declared one, else the kind's default. + #[must_use] + pub fn resolved_isolation(&self) -> Isolation { + self.isolation + .unwrap_or_else(|| self.kind.default_isolation()) + } +} diff --git a/crates/tinyhivemind-lang/src/lib.rs b/crates/tinyhivemind-lang/src/lib.rs index 118aaa9f..ad77f041 100644 --- a/crates/tinyhivemind-lang/src/lib.rs +++ b/crates/tinyhivemind-lang/src/lib.rs @@ -30,7 +30,10 @@ //! seat's profile next, and the seat last. Every section is optional and //! defaults to empty, so a package without them is unchanged. The vocabulary //! is exactly what the `OpenHuman` harness can run: a setting it cannot honour -//! is a located diagnostic, never silently dropped. Credentials are +//! is a located diagnostic, never silently dropped. A seat may also name a +//! [`Harness`] from the `harnesses` section, resolved the same way; naming +//! one holds the package to that kind's column of the capability table +//! ([`HarnessKind::support`]). Credentials are //! [`SecretRef`]s (`{"env": "NAME"}` or `{"store": "key"}`), never values. //! //! An [`ExecTool`] declares a tool as a program plus an argument schema. The @@ -238,7 +241,7 @@ pub use check::{Review, check, check_packages}; pub use diagnostic::{Diagnostic, Rule}; pub use document::*; pub use error::{Error, Result}; -pub use harness::HarnessKind; +pub use harness::{Capability, Harness, HarnessKind, Isolation, ModelApi, Support, Unlock}; pub use lowering::{ LoweredHive, LoweredHook, LoweredIntegrations, LoweredMemoryBinding, LoweredModel, LoweredSeat, LoweredSeatIntegration, lower, diff --git a/crates/tinyhivemind-lang/src/lowering/README.md b/crates/tinyhivemind-lang/src/lowering/README.md index c2e65865..d2dbc9f9 100644 --- a/crates/tinyhivemind-lang/src/lowering/README.md +++ b/crates/tinyhivemind-lang/src/lowering/README.md @@ -20,7 +20,13 @@ runtime); `tools.allow` is the most specific non-empty list. A toolpack expands into its tools, MCP servers, skills and tool groups first, and a toolpack is the only way a seat is given an executable tool; a hook's tool needs no toolpack. Setting the feature `mcp`, `skills`, -`script_tools` or `hooks` to `false` empties that integration. Lowering runs +`script_tools` or `hooks` to `false` empties that integration. +`harness` resolves like `model` (seat, then profile, then runtime) to the +declared `Harness`; `None`, which `harness_kind` reports as `openhuman`, means +no layer names one, and lowers exactly as before the field existed. +`unlisted_groups` is `Some(Off)` in a package that names a harness, so every +tool group its toolpacks do not list is off, and `None` otherwise, which +keeps the harness's own group defaults. Lowering runs on a validated package, so an id that does not resolve is skipped, not reported; call `validate` first. diff --git a/crates/tinyhivemind-lang/src/lowering/integration.rs b/crates/tinyhivemind-lang/src/lowering/integration.rs index 8c38a422..8e129fb4 100644 --- a/crates/tinyhivemind-lang/src/lowering/integration.rs +++ b/crates/tinyhivemind-lang/src/lowering/integration.rs @@ -173,12 +173,14 @@ pub(super) fn seat(package: &Package, seat: &Seat) -> LoweredSeatIntegration { programs, hooks, groups, + unlisted_groups: crate::harness::resolve::judged(m).then_some(GroupMode::Off), permissions, limits, context, subagents: p.subagents.clone(), bare_prompt: p.bare_prompt, definition_base: p.definition_base.clone(), + harness: crate::harness::resolve::resolve(m, seat).cloned(), } } diff --git a/crates/tinyhivemind-lang/src/lowering/test.rs b/crates/tinyhivemind-lang/src/lowering/test.rs index 68660934..79a2a67a 100644 --- a/crates/tinyhivemind-lang/src/lowering/test.rs +++ b/crates/tinyhivemind-lang/src/lowering/test.rs @@ -167,3 +167,86 @@ fn seat_context_documents_lower_with_their_contents() { assert_eq!(context[0].0, "context/style.md"); assert!(context[0].1.contains("imperative")); } + +/// The `integrations` package with harnesses `oh` (`openhuman`), `claw` +/// (`openclaw`) and `codex` declared. +fn with_harnesses() -> Package { + let mut package = integrations(); + package.manifest.harnesses = [ + ("oh", crate::HarnessKind::OpenHuman), + ("claw", crate::HarnessKind::OpenClaw), + ("codex", crate::HarnessKind::Codex), + ] + .into_iter() + .map(|(id, kind)| crate::Harness { + id: id.into(), + kind, + isolation: None, + }) + .collect(); + package +} + +/// Each seat's resolved harness id, without the capability check `lower` +/// would run first. +fn harnesses(package: &Package) -> Vec> { + package + .manifest + .seats + .iter() + .map(|seat| { + super::integration::seat(package, seat) + .harness + .map(|harness| harness.id) + }) + .collect() +} + +#[test] +fn a_seat_with_no_harness_anywhere_is_an_openhuman_seat() { + let hive = lower(&integrations()).unwrap(); + for seat in &hive.seats { + assert_eq!(seat.integration.harness, None); + assert_eq!( + seat.integration.harness_kind(), + crate::HarnessKind::OpenHuman + ); + } + // Declaring harnesses names none for a seat. + assert_eq!(harnesses(&with_harnesses()), [None, None]); +} + +#[test] +fn the_most_specific_harness_wins() { + let mut package = with_harnesses(); + package.manifest.runtime.harness = Some("oh".into()); + assert_eq!(harnesses(&package), [Some("oh".into()), Some("oh".into())]); + // The `editor` profile is the lead's; the scout names its own. + package.manifest.profiles[0].harness = Some("claw".into()); + package.manifest.seats[1].harness = Some("codex".into()); + assert_eq!( + harnesses(&package), + [Some("claw".into()), Some("codex".into())] + ); + // The seat beats its profile. + package.manifest.profiles[1].harness = Some("claw".into()); + assert_eq!(harnesses(&package)[1].as_deref(), Some("codex")); + let lead = super::integration::seat(&package, &package.manifest.seats[0]); + assert_eq!(lead.harness_kind(), crate::HarnessKind::OpenClaw); + assert_eq!(lead.harness, Some(package.manifest.harnesses[1].clone())); +} + +#[test] +fn a_judged_package_lowers_every_unlisted_tool_group_to_off() { + // No harness named: the harness keeps its own group defaults. + for seat in &lower(&integrations()).unwrap().seats { + assert_eq!(seat.integration.unlisted_groups, None); + } + let package = with_harnesses(); + for seat in &package.manifest.seats { + let lowered = super::integration::seat(&package, seat); + assert_eq!(lowered.unlisted_groups, Some(crate::GroupMode::Off)); + // The groups a toolpack lists are still carried as listed. + assert_eq!(lowered.groups["web3"], crate::GroupMode::Off); + } +} diff --git a/crates/tinyhivemind-lang/src/lowering/types.rs b/crates/tinyhivemind-lang/src/lowering/types.rs index c4d36244..a6474f0b 100644 --- a/crates/tinyhivemind-lang/src/lowering/types.rs +++ b/crates/tinyhivemind-lang/src/lowering/types.rs @@ -1,8 +1,8 @@ //! Translate validated packages into existing core values and host requests. use crate::{ - CoordinatorSettings, ExecTool, Goal, GroupMode, Hook, JevSettings, Limits, Link, McpServer, - MemorySpec, Mission, Model, PermissionSet, Policies, Provider, RuntimeSettings, SeatMemory, - SessionSettings, Skill, ToolAccess, Workflow, + CoordinatorSettings, ExecTool, Goal, GroupMode, Harness, HarnessKind, Hook, JevSettings, + Limits, Link, McpServer, MemorySpec, Mission, Model, PermissionSet, Policies, Provider, + RuntimeSettings, SeatMemory, SessionSettings, Skill, ToolAccess, Workflow, }; use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; @@ -106,6 +106,11 @@ pub struct LoweredSeatIntegration { pub hooks: Vec, /// Harness tool group modes from its toolpacks. pub groups: BTreeMap, + /// The mode of every harness tool group `groups` does not list: `None` + /// keeps the harness's own defaults, which only a package that names no + /// harness gets; a package that names one lowers to `Some(Off)`, since + /// no built-in tool may be on. + pub unlisted_groups: Option, /// Permission sets that all apply, broadest first: runtime, profile, /// seat. pub permissions: Vec, @@ -119,6 +124,20 @@ pub struct LoweredSeatIntegration { pub bare_prompt: bool, /// A harness built-in definition to start from. pub definition_base: Option, + /// The declared harness the seat runs on: the seat's `harness`, else its + /// profile's, else the runtime's. `None` when none is named, which is an + /// `openhuman` seat ([`Self::harness_kind`]). + pub harness: Option, +} + +impl LoweredSeatIntegration { + /// The kind of harness the seat runs on; `openhuman` when it names none. + #[must_use] + pub fn harness_kind(&self) -> HarnessKind { + self.harness + .as_ref() + .map_or(HarnessKind::OpenHuman, |harness| harness.kind) + } } /// Resolved identity plus runtime memory configuration retained for the host. #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] diff --git a/crates/tinyhivemind-lang/src/patch/README.md b/crates/tinyhivemind-lang/src/patch/README.md index b087b504..c335157e 100644 --- a/crates/tinyhivemind-lang/src/patch/README.md +++ b/crates/tinyhivemind-lang/src/patch/README.md @@ -20,7 +20,9 @@ The library opens no store and never embeds learned entries in the package. Context item bodies end with a newline. Deltas preserve text outside item boundaries. Prompt edits preserve JSON frontmatter. The `integration` class owns the -integration sections of the manifest, a seat's integration fields, and every +integration sections of the manifest (`harnesses` included), a seat's integration fields, and every file under `tools/` and `skills/`; those files are edited whole, so the leading-`---` frontmatter rule for prompts does not apply to them. Constitution controls permitted classes, canaries, pinned read-only memory and package invariants. +A patch that moves a seat to another harness is refused unless the +constitution also permits `integration`, whatever the patch's own class. diff --git a/crates/tinyhivemind-lang/src/patch/mod.rs b/crates/tinyhivemind-lang/src/patch/mod.rs index 40415351..b7a449dc 100644 --- a/crates/tinyhivemind-lang/src/patch/mod.rs +++ b/crates/tinyhivemind-lang/src/patch/mod.rs @@ -20,7 +20,7 @@ pub(crate) fn whole(path: &str) -> bool { } /// The manifest sections the integration class owns. -const INTEGRATION: [&str; 14] = [ +const INTEGRATION: [&str; 15] = [ "runtime", "providers", "models", @@ -35,6 +35,7 @@ const INTEGRATION: [&str; 14] = [ "jev", "features", "workflows", + "harnesses", ]; fn boundary(class: PatchClass, op: &Operation) -> bool { @@ -329,7 +330,15 @@ pub fn apply(package: &Package, patch: &Patch) -> Result { /// Rejects a forged candidate, forbidden class, immutable settings, read-only /// memory changes, canaries, or invalid package invariants and memory reaches. pub fn guard(original: &Package, proposed: &Package, patch: &Patch) -> Result<()> { - if !original.constitution.permitted_edits.contains(&patch.class) { + let permitted = &original.constitution.permitted_edits; + if !permitted.contains(&patch.class) { + return Err(Error::ForbiddenClass); + } + // A seat's `harness` is a roster field, but moving a seat to another + // harness changes what it can reach: it needs the integration class too. + if !permitted.contains(&PatchClass::Integration) + && !crate::harness::resolve::moves(&original.manifest, &proposed.manifest).is_empty() + { return Err(Error::ForbiddenClass); } if original.constitution != proposed.constitution { diff --git a/crates/tinyhivemind-lang/src/patch/types.rs b/crates/tinyhivemind-lang/src/patch/types.rs index 75c86215..8747a6b7 100644 --- a/crates/tinyhivemind-lang/src/patch/types.rs +++ b/crates/tinyhivemind-lang/src/patch/types.rs @@ -23,8 +23,9 @@ pub enum PatchClass { Goal, /// What the agents run with: the runtime, providers, models, MCP /// servers, skills, tools, toolpacks, permissions, profiles, hooks, - /// session, Jev, features and workflows, and the files under `tools/` - /// and `skills/`. + /// session, Jev, features, workflows and harnesses, and the files under + /// `tools/` and `skills/`. Moving a seat to another harness needs this + /// class as well as [`PatchClass::Roster`]. Integration, } diff --git a/crates/tinyhivemind-lang/src/validation/README.md b/crates/tinyhivemind-lang/src/validation/README.md index ee55acff..dfda0806 100644 --- a/crates/tinyhivemind-lang/src/validation/README.md +++ b/crates/tinyhivemind-lang/src/validation/README.md @@ -19,6 +19,8 @@ frontmatter and context markers on the Markdown file, memory findings in | `bounds.rs` | Policy and coordinator bounds against the constitution's caps | | `memory.rs` | Memory identities, bindings and reaches | | `integration.rs` | The integration sections: identities, references, shipped skill and tool files, bounds, and settings OpenHuman cannot run as written | +| `harness.rs` | The `harnesses` section and `harness` fields: identities, references, isolation, and whether the capability table judges the package | +| `capability/` | The capability table judged per seat, default-deny; see [`capability/README.md`](capability/README.md) | | `test/` | Fail-fast regressions and finding locations; see [`test/README.md`](test/README.md) | ## Integration rules @@ -36,3 +38,26 @@ cannot run (`integration`): `sqlite` sessions with no workspace, a tool in both `allow_tools` and `deny_tools`, a delegated profile that sets what only an agent can, a `matcher` on a `stop` hook, an `argv` placeholder naming no argument, and a feature name outside `[a-z0-9_]+`. + +## Harness rules + +`harness.rs` reports a blank or duplicate harness id (`identity`), a +`harness` on the runtime, a profile or a seat naming no declared harness +(`reference`), and `isolation: deployment` on a kind other than `openclaw` +(`integration`); `integration.rs` reports a harness on a delegated profile. +Once a package declares or names a harness, `capability.rs` judges every seat +against its kind's column of the capability table and reports each rejected +setting once, at the field that sets it. It is default-deny: the runtime, the +seat, its profile, model, permission sets, toolpacks and hooks, and `session` +and `jev`, are walked field by field, and any field set away from its default +asks for the capability `harness/fields.rs` gives it. By value it also +judges the resolved provider's `kind`, `endpoint` or `credential` (or the +`provider` field that should name one), a sandbox on the runtime or an +applying permission set, `tool_rules`, a toolpack group turned on, a +`sqlite` or host session store, an in-process or host memory engine, a +`stop` hook, and `limits.iterations` at the layer that set it (rejected but +on OpenHuman, and there above its cap). Seats +sharing one OpenClaw instance must resolve to one provider (reported at the +harness's `isolation`), and a tool a judged seat receives may not declare an +argument named `turn` or `call`. A package naming no harness is not judged: +the linked adapter deploys it under its own limits. diff --git a/crates/tinyhivemind-lang/src/validation/capability/README.md b/crates/tinyhivemind-lang/src/validation/capability/README.md new file mode 100644 index 00000000..e466789c --- /dev/null +++ b/crates/tinyhivemind-lang/src/validation/capability/README.md @@ -0,0 +1,10 @@ +# validation/capability + +The capability table judged seat by seat, default-deny: every field a seat +runs with is walked against its default through `harness/fields.rs`, and a +field with no decision is rejected. + +| File | Purpose | +| --- | --- | +| `mod.rs` | The walker, the by-value rules, the shared-OpenClaw provider rule and the reserved `turn`/`call` arguments | +| `test.rs` | A field with no capability decision is rejected on every kind | diff --git a/crates/tinyhivemind-lang/src/validation/capability/mod.rs b/crates/tinyhivemind-lang/src/validation/capability/mod.rs new file mode 100644 index 00000000..e3a164b7 --- /dev/null +++ b/crates/tinyhivemind-lang/src/validation/capability/mod.rs @@ -0,0 +1,547 @@ +//! The capability table, judged seat by seat: every setting a seat resolves +//! to that its harness kind rejects is an [`Error::Integration`] at the +//! field that sets it. +//! +//! The judgement is default-deny. Every object a seat runs with (the +//! runtime, the seat, its profile, model, permission sets, toolpacks and +//! hooks, and the session and Jev settings) is walked field by field against +//! its default, and a field set to anything else asks for the capability +//! `harness/fields.rs` assigns it; the table is [`HarnessKind::support`]. A +//! row that moves to supported stops being reported with no change here. The +//! fields judged by value (provider shape, sandbox, stores, tool rules and +//! groups, a hook's event, the iteration limit) are handled by hand. A seat +//! whose harness reference does not resolve is skipped: `harness.rs` has +//! already reported it. +use crate::{ + Capability, Error, GroupMode, HarnessKind, HookEvent, Manifest, MemoryEngine, Package, + ProviderKind, Sandbox, Seat, SessionStore, Support, + diagnostic::{Findings, HIVE, escape}, + harness::{ + fields::{Field, field}, + resolve, + }, +}; +use serde_json::Value; +use std::collections::{BTreeMap, BTreeSet}; + +/// Arguments the host adds to every served tool for call identity. +const RESERVED_ARGUMENTS: [&str; 2] = ["turn", "call"]; + +/// Judge every seat of `package`, then every shared instance. +pub(super) fn capabilities(package: &Package, found: &mut Findings) { + let m = &package.manifest; + let mut providers: BTreeMap> = BTreeMap::new(); + let mut out = Out::default(); + for (i, seat) in m.seats.iter().enumerate() { + let kind = match resolve::named(m, seat) { + None => HarnessKind::OpenHuman, + Some((id, _)) => match m.harnesses.iter().position(|h| h.id == id) { + Some(h) => { + if let Some(provider) = provider_id(m, seat) { + providers.entry(h).or_default().insert(provider); + } + m.harnesses[h].kind + } + None => continue, + }, + }; + let mut judge = Judge { + m, + kind, + found: &mut out, + }; + judge.provider(seat); + judge.layers(seat, i); + judge.hive(); + } + for (h, seen) in providers { + let harness = &m.harnesses[h]; + if harness.kind == HarnessKind::OpenClaw + && harness.resolved_isolation() == crate::Isolation::Deployment + && seen.len() > 1 + { + // At the isolation that shares the instance, or at the entry + // when it is the kind's default and has no field of its own. + let at = if harness.isolation.is_some() { + format!("/harnesses/{h}/isolation") + } else { + format!("/harnesses/{h}") + }; + out.push( + Error::Integration { + field: format!("harnesses.{}.isolation", harness.id), + reason: "seats sharing one openclaw instance must resolve to one provider; \ + use isolation seat" + .into(), + }, + at, + ); + } + } + for (error, at) in out.findings { + found.push(error, HIVE, at); + } +} + +/// Findings in the order met, one per location and message: a setting +/// several seats share is reported once per harness kind that rejects it, +/// each with its own kind's reason. +#[derive(Default)] +struct Out { + seen: BTreeSet<(String, String)>, + findings: Vec<(Error, String)>, +} + +impl Out { + fn push(&mut self, error: Error, at: String) { + if self.seen.insert((at.clone(), error.to_string())) { + self.findings.push((error, at)); + } + } +} + +/// The model id `seat` resolves to: its own, its profile's, the runtime's. +fn model_id<'a>(m: &'a Manifest, seat: &'a Seat) -> Option<&'a String> { + seat.model + .as_ref() + .or_else(|| profile(m, seat).and_then(|k| m.profiles[k].model.as_ref())) + .or(m.runtime.model.as_ref()) +} + +/// The provider id `seat` resolves to: its model's, else the runtime's. +fn provider_id<'a>(m: &'a Manifest, seat: &'a Seat) -> Option<&'a str> { + let model = model_id(m, seat).and_then(|id| m.models.iter().find(|v| &v.id == id)); + model + .and_then(|model| model.provider.as_ref()) + .or(m.runtime.provider.as_ref()) + .map(String::as_str) +} + +/// The index of `seat`'s profile in `profiles`. +fn profile(m: &Manifest, seat: &Seat) -> Option { + let id = seat.profile.as_ref()?; + m.profiles.iter().position(|p| &p.id == id) +} + +/// The indices of the declarations `ids` name, skipping unresolved ones. +fn indices<'a, T>( + items: &[T], + ids: impl IntoIterator, + key: impl Fn(&T) -> &str, +) -> BTreeSet { + ids.into_iter() + .filter_map(|id| items.iter().position(|item| key(item) == id)) + .collect() +} + +/// One seat's judgement against its kind's column of the table. +struct Judge<'a, 'f> { + m: &'a Manifest, + kind: HarnessKind, + found: &'f mut Out, +} + +impl Judge<'_, '_> { + /// Report `capability` at `at` when the kind rejects it. + fn reject(&mut self, capability: Capability, field: String, at: String) { + if let Support::Rejected(unlock) = self.kind.support(capability) { + let reason = format!( + "the {} harness cannot honour {capability}: {unlock}", + self.kind + ); + self.found.push(Error::Integration { field, reason }, at); + } + } + + /// The provider rows: the seat's resolved provider, or the field that + /// should have named one. + fn provider(&mut self, seat: &Seat) { + let m = self.m; + let (named, at, field) = match model_id(m, seat) { + None => ( + m.runtime.provider.as_ref(), + "/runtime/provider".to_owned(), + "runtime.provider".to_owned(), + ), + Some(id) => { + let Some(k) = m.models.iter().position(|model| &model.id == id) else { + return; + }; + ( + m.models[k] + .provider + .as_ref() + .or(m.runtime.provider.as_ref()), + format!("/models/{k}/provider"), + format!("models.{id}.provider"), + ) + } + }; + let Some(named) = named else { + self.reject(Capability::InheritedProvider, field, at); + return; + }; + let Some(p) = m.providers.iter().position(|v| &v.id == named) else { + return; + }; + let provider = &m.providers[p]; + let at = |key: &str| format!("/providers/{p}/{key}"); + let field = |key: &str| format!("providers.{named}.{key}"); + match provider.kind { + ProviderKind::Inherit => { + self.reject(Capability::InheritedProvider, field("kind"), at("kind")); + } + ProviderKind::Openrouter => { + self.reject(Capability::Openrouter, field("kind"), at("kind")); + } + ProviderKind::Anthropic => { + self.reject(Capability::Anthropic, field("kind"), at("kind")); + } + ProviderKind::Openai if provider.endpoint.is_none() => self.reject( + Capability::OpenaiDefaultEndpoint, + field("endpoint"), + at("endpoint"), + ), + ProviderKind::Openai => {} + } + if provider.credential.is_some() { + self.reject( + Capability::ProviderCredential, + field("credential"), + at("credential"), + ); + } + } + + /// Walk `value` against `default` as `owner`'s fields: a judged field + /// that differs asks for its capability, a nested one is walked in turn. + fn walk(&mut self, owner: &str, value: &Value, default: &Value, at: &str, name: &str) { + let Some(fields) = value.as_object() else { + return; + }; + for (key, value) in fields { + let base = default.get(key).unwrap_or(&Value::Null); + let (at, name) = (format!("{at}/{}", escape(key)), format!("{name}.{key}")); + match field(owner, key) { + Some(Field::Nested(inner)) => self.walk(inner, value, base, &at, &name), + Some(Field::Judged(capability)) if value != base => { + self.reject(capability, name, at); + } + // Default-deny: a field with no decision is never passed. + None => self.reject(Capability::Undecided, name, at), + Some(Field::Judged(_) | Field::Structure | Field::Special) => {} + } + } + } + + /// Walk one declaration of `owner` against its default. + fn declared( + &mut self, + owner: &str, + value: &T, + base: &T, + at: &str, + name: &str, + ) { + let (value, base) = (wire(value), wire(base)); + self.walk(owner, &value, &base, at, name); + } + + /// What the runtime, the seat's profile and the seat layer onto it: + /// every field of each, permission sets, toolpacks and the tools they + /// grant, hooks, and the iteration limit. + fn layers(&mut self, seat: &Seat, i: usize) { + let m = self.m; + let p = profile(m, seat); + let from_profile = p.map(|k| &m.profiles[k]); + let seat_default = Seat { + config: Value::Object(serde_json::Map::new()), + ..Seat::default() + }; + self.declared( + "seat", + seat, + &seat_default, + &format!("/seats/{i}"), + &format!("seats.{}", seat.id), + ); + if let (Some(k), Some(declared)) = (p, from_profile) { + let name = format!("profiles.{}", declared.id); + self.declared( + "profile", + declared, + &crate::Profile::default(), + &format!("/profiles/{k}"), + &name, + ); + } + if let Some(k) = model_id(m, seat).and_then(|id| m.models.iter().position(|v| &v.id == id)) + { + let model = &m.models[k]; + let name = format!("models.{}", model.id); + self.declared( + "model", + model, + &crate::Model::default(), + &format!("/models/{k}"), + &name, + ); + } + let permissions = indices( + &m.permissions, + [ + m.runtime.permissions.as_ref(), + from_profile.and_then(|p| p.permissions.as_ref()), + seat.permissions.as_ref(), + ] + .into_iter() + .flatten(), + |v| &v.id, + ); + for k in permissions { + self.permission_set(k); + } + let packs = indices( + &m.toolpacks, + m.runtime + .toolpacks + .iter() + .chain(from_profile.into_iter().flat_map(|p| &p.toolpacks)) + .chain(&seat.toolpacks), + |v| &v.id, + ); + for k in &packs { + self.toolpack(*k); + } + let packs: Vec<&crate::Toolpack> = packs.into_iter().map(|k| &m.toolpacks[k]).collect(); + let mcp: Vec<&String> = from_profile + .into_iter() + .flat_map(|p| &p.mcp) + .chain(&seat.mcp) + .chain(packs.iter().flat_map(|pack| &pack.mcp)) + .collect(); + let skills: Vec<&String> = from_profile + .into_iter() + .flat_map(|p| &p.skills) + .chain(&seat.skills) + .chain(packs.iter().flat_map(|pack| &pack.skills)) + .collect(); + self.reached(&mcp, &skills); + self.hooks( + from_profile + .into_iter() + .flat_map(|p| &p.hooks) + .chain(&seat.hooks), + ); + self.iterations(seat, i, p); + } + + /// The hooks that run on the seat's turns, each walked at its + /// declaration; a `stop` hook is rejected. + fn hooks<'h>(&mut self, ids: impl IntoIterator) { + let m = self.m; + for k in indices(&m.hooks, ids, |v| &v.id) { + let hook = &m.hooks[k]; + let name = format!("hooks.{}", hook.id); + let at = format!("/hooks/{k}"); + self.declared("hook", hook, &crate::Hook::default(), &at, &name); + if hook.event == HookEvent::Stop { + let (field, at) = (format!("{name}.event"), format!("{at}/event")); + self.reject(Capability::StopHooks, field, at); + } + } + } + + /// One permission set that applies to the seat. + fn permission_set(&mut self, k: usize) { + let layer = &self.m.permissions[k]; + let name = format!("permissions.{}", layer.id); + let at = format!("/permissions/{k}"); + self.declared( + "permissions", + layer, + &crate::PermissionSet::default(), + &at, + &name, + ); + if layer.sandbox != Sandbox::None { + self.reject( + Capability::Sandbox, + format!("{name}.sandbox"), + format!("{at}/sandbox"), + ); + } + if !layer.tool_rules.is_null() { + let (field, at) = (format!("{name}.tool_rules"), format!("{at}/tool_rules")); + self.reject(Capability::BuiltinToolRules, field, at); + } + } + + /// One toolpack the seat receives, and the tools it grants. + fn toolpack(&mut self, k: usize) { + let m = self.m; + let pack = &m.toolpacks[k]; + let name = format!("toolpacks.{}", pack.id); + self.declared( + "toolpack", + pack, + &crate::Toolpack::default(), + &format!("/toolpacks/{k}"), + &name, + ); + for (group, mode) in &pack.groups { + if *mode != GroupMode::Off { + let field = format!("{name}.groups.{group}"); + let at = format!("/toolpacks/{k}/groups/{}", escape(group)); + self.reject(Capability::BuiltinToolGroups, field, at); + } + } + for t in indices(&m.tools, &pack.tools, |v| &v.id) { + let tool = &m.tools[t]; + let name = format!("tools.{}", tool.id); + self.declared("tool", tool, tool, &format!("/tools/{t}"), &name); + self.reserved(t); + } + } + + /// The MCP servers and skills a seat reaches, by id, each walked at its + /// declaration. + fn reached(&mut self, mcp: &[&String], skills: &[&String]) { + let m = self.m; + for k in indices(&m.mcp, mcp.iter().copied(), |v| &v.id) { + let server = &m.mcp[k]; + let name = format!("mcp.{}", server.id); + self.declared( + "mcp", + server, + &crate::McpServer::default(), + &format!("/mcp/{k}"), + &name, + ); + } + for k in indices(&m.skills, skills.iter().copied(), |v| &v.id) { + let skill = &m.skills[k]; + let name = format!("skills.{}", skill.id); + self.declared( + "skill", + skill, + &crate::Skill::default(), + &format!("/skills/{k}"), + &name, + ); + } + } + + /// An executable tool whose own arguments use a name the host reserves. + fn reserved(&mut self, t: usize) { + let tool = &self.m.tools[t]; + let Some(properties) = tool.args.get("properties").and_then(|p| p.as_object()) else { + return; + }; + for name in RESERVED_ARGUMENTS { + if properties.contains_key(name) { + self.found.push( + Error::Integration { + field: format!("tools.{}.args.{name}", tool.id), + reason: "turn and call are added by the host to every served tool".into(), + }, + format!("/tools/{t}/args/properties/{name}"), + ); + } + } + } + + /// The seat's resolved `limits.iterations`, reported at whichever layer + /// set it: rejected where the kind has no iteration limit, and above the + /// kind's fixed cap where it has one. + fn iterations(&mut self, seat: &Seat, i: usize, p: Option) { + let m = self.m; + let model = model_id(m, seat).and_then(|id| m.models.iter().position(|v| &v.id == id)); + let layers = [ + Some((&seat.limits, format!("/seats/{i}"))), + p.map(|k| (&m.profiles[k].limits, format!("/profiles/{k}"))), + model.map(|k| (&m.models[k].limits, format!("/models/{k}"))), + Some((&m.runtime.limits, "/runtime".to_owned())), + ]; + let Some((iterations, at)) = layers + .into_iter() + .flatten() + .find_map(|(limits, at)| Some((limits.iterations?, format!("{at}/limits/iterations")))) + else { + return; + }; + let field = format!("seats.{}.limits.iterations", seat.id); + self.reject(Capability::IterationLimit, field.clone(), at.clone()); + if let Some(cap) = self.kind.iteration_cap() + && iterations > cap + { + let reason = format!( + "the {} harness ends a turn after {cap} model iterations", + self.kind + ); + self.found.push(Error::Integration { field, reason }, at); + } + } + + /// Hive-wide settings every seat runs under. + fn hive(&mut self) { + let m = self.m; + let r = &m.runtime; + self.declared( + "runtime", + r, + &crate::RuntimeSettings::default(), + "/runtime", + "runtime", + ); + if r.sandbox != Sandbox::None { + self.reject( + Capability::Sandbox, + "runtime.sandbox".into(), + "/runtime/sandbox".into(), + ); + } + let store = match r.session_store { + SessionStore::Memory => None, + SessionStore::Sqlite => Some(Capability::SqliteSessions), + SessionStore::Host => Some(Capability::HostSessionStore), + }; + if let Some(capability) = store { + let at = "/runtime/session_store".to_owned(); + self.reject(capability, "runtime.session_store".into(), at); + } + let engine = match r.memory_engine { + MemoryEngine::Disabled => None, + MemoryEngine::Memory => Some(Capability::InProcessMemory), + MemoryEngine::Host => Some(Capability::HostMemoryEngine), + }; + if let Some(capability) = engine { + let at = "/runtime/memory_engine".to_owned(); + self.reject(capability, "runtime.memory_engine".into(), at); + } + self.declared( + "session", + &m.session, + &crate::SessionSettings::default(), + "/session", + "session", + ); + self.declared("jev", &m.jev, &crate::JevSettings::default(), "/jev", "jev"); + // The manifest's own fields (context, features, workflows), then + // each workflow; the sections are walked where a seat reaches them. + self.declared("manifest", m, &Manifest::default(), "", "hive"); + for (k, job) in m.workflows.iter().enumerate() { + let name = format!("workflows.{}", job.id); + self.declared("workflow", job, job, &format!("/workflows/{k}"), &name); + } + } +} + +/// A package value as wire JSON; the wire types serialize infallibly, and a +/// failure would only skip the walk. +fn wire(value: &T) -> Value { + serde_json::to_value(value).unwrap_or(Value::Null) +} + +#[cfg(test)] +mod test; diff --git a/crates/tinyhivemind-lang/src/validation/capability/test.rs b/crates/tinyhivemind-lang/src/validation/capability/test.rs new file mode 100644 index 00000000..09381d1d --- /dev/null +++ b/crates/tinyhivemind-lang/src/validation/capability/test.rs @@ -0,0 +1,34 @@ +//! The walker itself: a field with no capability decision is rejected, +//! never passed. +use super::{Judge, Out}; +use crate::{HarnessKind, Manifest}; +use serde_json::json; + +#[test] +fn a_field_with_no_capability_decision_is_rejected() { + let manifest = Manifest::default(); + for kind in HarnessKind::ALL { + let mut out = Out::default(); + let mut judge = Judge { + m: &manifest, + kind, + found: &mut out, + }; + judge.walk( + "seat", + &json!({"id": "a", "brand_new": 1}), + &json!({}), + "/seats/0", + "seats.a", + ); + judge.walk( + "ghost_owner", + &json!({"x": true}), + &json!({}), + "/ghost", + "ghost", + ); + let at: Vec<&str> = out.findings.iter().map(|(_, at)| at.as_str()).collect(); + assert_eq!(at, ["/seats/0/brand_new", "/ghost/x"], "{kind}"); + } +} diff --git a/crates/tinyhivemind-lang/src/validation/harness.rs b/crates/tinyhivemind-lang/src/validation/harness.rs new file mode 100644 index 00000000..5aa6038b --- /dev/null +++ b/crates/tinyhivemind-lang/src/validation/harness.rs @@ -0,0 +1,61 @@ +//! The `harnesses` section and the `harness` fields: identities, references +//! and isolation, then the capability table once a package names a harness. +//! +//! A package that declares no harness and names none is deployed by the +//! linked `OpenHuman` adapter, which keeps its own limits, so the capability +//! table does not judge it. One that does is judged whole, its implicit +//! `openhuman` seats included: those run as a process too. +use super::{capability, identities, reference}; +use crate::{ + Error, HarnessKind, Isolation, Package, + diagnostic::{Findings, HIVE}, +}; + +/// Push every harness finding for `package`. +pub(super) fn harnesses(package: &Package, found: &mut Findings) { + let m = &package.manifest; + let declared = identities( + found, + HIVE, + "harness", + m.harnesses.iter().map(|h| &h.id), + |i| format!("/harnesses/{i}/id"), + ); + let mut named = vec![(m.runtime.harness.as_ref(), "/runtime/harness".to_owned())]; + named.extend( + m.profiles + .iter() + .enumerate() + .map(|(k, p)| (p.harness.as_ref(), format!("/profiles/{k}/harness"))), + ); + named.extend( + m.seats + .iter() + .enumerate() + .map(|(i, s)| (s.harness.as_ref(), format!("/seats/{i}/harness"))), + ); + for (id, at) in named { + if let Some(id) = id { + found.check(reference("harness", id, &declared), HIVE, at); + } + } + for (i, harness) in m.harnesses.iter().enumerate() { + if harness.isolation == Some(Isolation::Deployment) && harness.kind != HarnessKind::OpenClaw + { + found.push( + Error::Integration { + field: format!("harnesses.{}.isolation", harness.id), + reason: format!( + "only an openclaw harness shares one instance across a deployment, not {}", + harness.kind + ), + }, + HIVE, + format!("/harnesses/{i}/isolation"), + ); + } + } + if crate::harness::resolve::judged(m) { + capability::capabilities(package, found); + } +} diff --git a/crates/tinyhivemind-lang/src/validation/integration.rs b/crates/tinyhivemind-lang/src/validation/integration.rs index 14a0dab8..ec55ae29 100644 --- a/crates/tinyhivemind-lang/src/validation/integration.rs +++ b/crates/tinyhivemind-lang/src/validation/integration.rs @@ -589,7 +589,7 @@ fn tool_shape(tool: &ExecTool, i: usize, found: &mut Findings) { /// A profile another profile delegates to runs inside its parent's agent, so /// it cannot bring an agent's own model, connections, skills, hooks, -/// delegates, timeout or budget. +/// delegates, timeout, budget or harness. fn delegates(m: &Manifest, found: &mut Findings) { let delegated: BTreeSet<&str> = m .profiles @@ -609,6 +609,7 @@ fn delegates(m: &Manifest, found: &mut Findings) { (!p.subagents.is_empty(), "subagents"), (p.limits.timeout_ms.is_some(), "limits"), (p.limits.budget_usd.is_some(), "limits"), + (p.harness.is_some(), "harness"), ] { if set { invalid( diff --git a/crates/tinyhivemind-lang/src/validation/mod.rs b/crates/tinyhivemind-lang/src/validation/mod.rs index 47f35274..7c330937 100644 --- a/crates/tinyhivemind-lang/src/validation/mod.rs +++ b/crates/tinyhivemind-lang/src/validation/mod.rs @@ -8,6 +8,8 @@ //! the frontmatter of a document that is missing, is skipped rather than //! reported twice. mod bounds; +mod capability; +mod harness; mod integration; mod memory; use crate::{ @@ -94,6 +96,7 @@ pub(crate) fn rules(package: &Package, found: &mut Findings) { bounds::bounds(package, found); memory::memory(package, &seats, found); integration::integration(package, &seats, found); + harness::harnesses(package, found); } /// Roles, seats and desk membership. @@ -412,4 +415,4 @@ fn frontmatter(package: &Package, seat: &crate::Seat) -> Result<()> { #[cfg(test)] mod test; #[cfg(test)] -pub(crate) use test::integration::documents as test_documents; +pub(crate) use test::integration::{documents as test_documents, example as test_example}; diff --git a/crates/tinyhivemind-lang/src/validation/test/README.md b/crates/tinyhivemind-lang/src/validation/test/README.md index caee9782..b2628c08 100644 --- a/crates/tinyhivemind-lang/src/validation/test/README.md +++ b/crates/tinyhivemind-lang/src/validation/test/README.md @@ -5,4 +5,5 @@ | `mod.rs` | Module doc and submodule wiring | | `rules.rs` | Wire contracts and fail-fast validation and parsing regressions | | `integration.rs` | The shipped `integrations` package checks clean; each integration rule reports its own finding at its own pointer | +| `harness.rs` | The `mixed-harnesses` package checks clean; every harness reference, identity, isolation, delegation and capability finding at its pointer; scoping to packages that name a harness; frontmatter restating a harness | | `locations.rs` | Where `diagnose` locates each finding, and agreement with `validate` | diff --git a/crates/tinyhivemind-lang/src/validation/test/harness.rs b/crates/tinyhivemind-lang/src/validation/test/harness.rs new file mode 100644 index 00000000..e0da943d --- /dev/null +++ b/crates/tinyhivemind-lang/src/validation/test/harness.rs @@ -0,0 +1,542 @@ +//! The `harnesses` section and the `harness` fields: references, identities +//! and isolation, and the capability table judged at each field's location. +#![allow(clippy::unwrap_used)] // Tests fail loudly on unexpected results. + +use super::integration::{example, has}; +use crate::*; +use serde_json::{Value, json}; + +/// The diagnostics of example `name` after `edit` rewrites its manifest. +fn after(name: &str, edit: impl FnOnce(&mut Value)) -> Vec { + let mut docs = example(name); + let mut manifest: Value = serde_json::from_str(&docs["hive.json"]).unwrap(); + edit(&mut manifest); + docs.insert("hive.json".into(), manifest.to_string()); + diagnose_documents(&docs).1 +} + +/// The diagnostics of `mixed-harnesses` after `edit`. +fn mixed(edit: impl FnOnce(&mut Value)) -> Vec { + after("mixed-harnesses", edit) +} + +/// The pointers of every `integration` finding, each once, in order: one +/// setting may be reported once per harness kind that rejects it. +fn integration_pointers(found: &[Diagnostic]) -> Vec<&str> { + let mut pointers: Vec<&str> = Vec::new(); + for pointer in found + .iter() + .filter(|d| d.rule == Rule::Integration) + .filter_map(|d| d.pointer.as_deref()) + { + if !pointers.contains(&pointer) { + pointers.push(pointer); + } + } + pointers +} + +#[test] +fn the_mixed_harnesses_package_checks_clean_with_a_harness_per_seat() { + let (package, found) = diagnose_documents(&example("mixed-harnesses")); + assert_eq!(found, vec![]); + let hive = lower(&package.unwrap()).unwrap(); + let kinds: Vec<_> = hive + .seats + .iter() + .map(|seat| (seat.id.as_str(), seat.integration.harness_kind())) + .collect(); + assert_eq!( + kinds, + [ + ("lead", HarnessKind::OpenHuman), + ("scout", HarnessKind::OpenClaw), + ("builder", HarnessKind::Codex), + ] + ); + assert_eq!(hive.seats[0].integration.harness, None); + let claw = hive.seats[1].integration.harness.as_ref().unwrap(); + assert_eq!(claw.resolved_isolation(), Isolation::Deployment); +} + +#[test] +fn an_undeclared_harness_is_an_unresolved_reference() { + let found = mixed(|m| m["runtime"]["harness"] = json!("ghost")); + assert!( + has(&found, Rule::Reference, "/runtime/harness"), + "{found:?}" + ); + let found = mixed(|m| m["profiles"][0]["harness"] = json!("ghost")); + assert!(has(&found, Rule::Reference, "/profiles/0/harness")); + let found = mixed(|m| m["seats"][1]["harness"] = json!("ghost")); + assert!(has(&found, Rule::Reference, "/seats/1/harness")); + // With no `harnesses` section at all, a named harness still resolves + // nowhere. + let found = after("integrations", |m| { + m["seats"][0]["harness"] = json!("codex"); + }); + assert!(has(&found, Rule::Reference, "/seats/0/harness")); +} + +#[test] +fn harness_ids_are_unique_and_named() { + let found = mixed(|m| { + let copy = m["harnesses"][1].clone(); + m["harnesses"].as_array_mut().unwrap().push(copy); + }); + assert!(has(&found, Rule::Identity, "/harnesses/2/id"), "{found:?}"); + let found = mixed(|m| m["harnesses"][0]["id"] = json!(" ")); + assert!(has(&found, Rule::Identity, "/harnesses/0/id")); +} + +#[test] +fn only_openclaw_shares_an_instance_across_a_deployment() { + for kind in ["codex", "openhuman"] { + let found = mixed(|m| { + m["harnesses"][1] = json!({"id": "codex", "kind": kind, "isolation": "deployment"}); + }); + assert!( + has(&found, Rule::Integration, "/harnesses/1/isolation"), + "{kind}: {found:?}" + ); + } + let found = mixed(|m| m["harnesses"][1]["isolation"] = json!("seat")); + assert_eq!(found, vec![]); + let found = mixed(|m| m["harnesses"][0]["isolation"] = json!("seat")); + assert_eq!(found, vec![]); +} + +#[test] +fn a_delegated_profile_may_not_name_a_harness() { + let found = after("integrations", |m| { + m["harnesses"] = json!([{"id": "oh", "kind": "openhuman"}]); + m["profiles"][2]["harness"] = json!("oh"); + }); + assert!( + has(&found, Rule::Integration, "/profiles/2/harness"), + "{found:?}" + ); +} + +#[test] +fn capabilities_are_judged_only_once_a_package_names_a_harness() { + // `integrations` sets a hosted provider with a credential, a sandbox, + // session tuning, Jev and a delegate: all fine on the linked adapter. + assert_eq!(after("integrations", |_| {}), vec![]); + let found = after("integrations", |m| { + m["harnesses"] = json!([{"id": "oh", "kind": "openhuman"}]); + }); + let pointers = integration_pointers(&found); + for pointer in [ + "/providers/0/kind", + "/providers/0/credential", + "/permissions/0/sandbox", + "/session/compact_context", + "/jev/top_k", + "/profiles/0/subagents", + "/runtime/deployment_id", + "/seats/0/tools/deny", + ] { + assert!(pointers.contains(&pointer), "{pointer}: {found:?}"); + } +} + +#[test] +fn every_rejected_provider_row_is_reported_at_the_provider() { + for (edit, pointer) in [ + (json!({"endpoint": null}), "/providers/0/endpoint"), + (json!({"kind": "openrouter"}), "/providers/0/kind"), + (json!({"kind": "anthropic"}), "/providers/0/kind"), + (json!({"kind": "inherit"}), "/providers/0/kind"), + ( + json!({"credential": {"env": "KEY"}}), + "/providers/0/credential", + ), + ] { + let found = mixed(|m| { + for (key, value) in edit.as_object().unwrap() { + m["providers"][0][key] = value.clone(); + } + }); + assert_eq!(integration_pointers(&found), [pointer], "{edit}"); + } +} + +#[test] +fn a_seat_that_resolves_to_no_provider_is_rejected() { + let found = mixed(|m| { + m["models"][0]["provider"] = json!(null); + m["runtime"]["provider"] = json!(null); + }); + assert_eq!(integration_pointers(&found), ["/models/0/provider"]); + let found = mixed(|m| { + m["runtime"]["model"] = json!(null); + m["runtime"]["provider"] = json!(null); + }); + assert_eq!(integration_pointers(&found), ["/runtime/provider"]); + // Without a model, the runtime's provider is the seat's. + let found = mixed(|m| m["runtime"]["model"] = json!(null)); + assert_eq!(found, vec![]); +} + +#[test] +fn a_sandbox_and_built_in_tool_settings_are_rejected() { + for (edit, pointer) in [ + ( + json!(["runtime", "sandbox", "read_only"]), + "/runtime/sandbox", + ), + ( + json!(["permissions", 0, "sandbox", "sandboxed"]), + "/permissions/0/sandbox", + ), + ( + json!(["permissions", 0, "tool_rules", {"shell": "deny"}]), + "/permissions/0/tool_rules", + ), + ( + json!(["toolpacks", 0, "groups", {"web3": "advertised"}]), + "/toolpacks/0/groups/web3", + ), + ( + json!(["runtime", "session_store", "host"]), + "/runtime/session_store", + ), + ( + json!(["runtime", "memory_engine", "host"]), + "/runtime/memory_engine", + ), + ( + json!(["profiles", 0, "definition_base", "coder"]), + "/profiles/0/definition_base", + ), + (json!(["jev", "top_k", 5]), "/jev/top_k"), + ( + json!(["session", "max_tool_iterations", 4]), + "/session/max_tool_iterations", + ), + ] { + let path = edit.as_array().unwrap(); + let found = mixed(|m| { + let (value, keys) = path.split_last().unwrap(); + let mut at = &mut *m; + for key in keys { + at = match key { + Value::String(key) => &mut at[key.as_str()], + Value::Number(i) => &mut at[usize::try_from(i.as_u64().unwrap()).unwrap()], + _ => unreachable!(), + }; + } + *at = value.clone(); + }); + assert_eq!(integration_pointers(&found), [pointer], "{edit}"); + } + // A group turned off is the state every kind is already in. + let found = mixed(|m| m["toolpacks"][0]["groups"] = json!({"web3": "off"})); + assert_eq!(found, vec![]); +} + +#[test] +fn a_delegate_is_rejected_on_the_profile_that_names_it() { + let found = mixed(|m| { + m["profiles"] + .as_array_mut() + .unwrap() + .push(json!({"id": "helper"})); + m["profiles"][0]["subagents"] = json!(["helper"]); + }); + assert_eq!(integration_pointers(&found), ["/profiles/0/subagents"]); +} + +#[test] +fn openhuman_rejects_more_iterations_than_its_fixed_cap() { + let found = mixed(|m| m["seats"][0]["limits"]["iterations"] = json!(9)); + assert_eq!(integration_pointers(&found), ["/seats/0/limits/iterations"]); + // The cap is OpenHuman's: the runtime default reaches every seat, and + // only the `openhuman` one reports it. + let found = mixed(|m| m["runtime"]["limits"]["iterations"] = json!(20)); + assert_eq!(integration_pointers(&found), ["/runtime/limits/iterations"]); + let found = mixed(|m| m["seats"][0]["limits"]["iterations"] = json!(8)); + assert_eq!(found, vec![]); +} + +#[test] +fn a_shared_openclaw_instance_runs_one_provider() { + let found = mixed(|m| { + m["providers"] + .as_array_mut() + .unwrap() + .push(json!({"id": "other", "kind": "openai", "endpoint": "http://127.0.0.1:9090/v1"})); + m["models"] + .as_array_mut() + .unwrap() + .push(json!({"id": "second", "provider": "other", "name": "second-model"})); + m["seats"][0]["harness"] = json!("claw"); + m["seats"][0]["model"] = json!("second"); + }); + assert_eq!(integration_pointers(&found), ["/harnesses/0/isolation"]); + let found = mixed(|m| { + m["providers"] + .as_array_mut() + .unwrap() + .push(json!({"id": "other", "kind": "openai", "endpoint": "http://127.0.0.1:9090/v1"})); + m["models"] + .as_array_mut() + .unwrap() + .push(json!({"id": "second", "provider": "other", "name": "second-model"})); + m["seats"][0]["harness"] = json!("claw"); + m["seats"][0]["model"] = json!("second"); + m["harnesses"][0]["isolation"] = json!("seat"); + }); + assert_eq!(found, vec![]); +} + +#[test] +fn an_executable_tool_may_not_declare_the_reserved_turn_or_call_arguments() { + for name in ["turn", "call"] { + let found = mixed(|m| { + m["tools"][0]["args"]["properties"][name] = json!({"type": "string"}); + }); + let pointer = format!("/tools/0/args/properties/{name}"); + assert_eq!(integration_pointers(&found), [pointer.as_str()]); + } +} + +#[test] +fn a_seat_prompt_frontmatter_may_restate_its_own_harness_only() { + let with = |frontmatter: &str| { + let mut docs = example("mixed-harnesses"); + let body = docs["seats/scout.md"].clone(); + docs.insert( + "seats/scout.md".into(), + format!("---\n{frontmatter}\n---\n{body}"), + ); + diagnose_documents(&docs).1 + }; + assert_eq!(with(r#"{"id": "scout", "harness": "claw"}"#), vec![]); + for wrong in [ + r#"{"harness": "codex"}"#, + // The seat has a harness; frontmatter cannot unset it. + r#"{"harness": null}"#, + ] { + let found = with(wrong); + assert!( + found + .iter() + .any(|d| d.rule == Rule::Frontmatter && d.file == "seats/scout.md"), + "{wrong}: {found:?}" + ); + } + // A seat without a harness has no `harness` key to restate, not even null. + let mut docs = example("mixed-harnesses"); + let body = docs["seats/lead.md"].clone(); + docs.insert( + "seats/lead.md".into(), + format!("---\n{{\"harness\": null}}\n---\n{body}"), + ); + let found = diagnose_documents(&docs).1; + assert!( + found.iter().any(|d| d.rule == Rule::Frontmatter), + "{found:?}" + ); +} + +/// `mixed-harnesses` with the JSON at `path` (keys and indices, then the +/// value) set. +fn mixed_at(path: &Value) -> Vec { + let path = path.as_array().unwrap(); + mixed(|m| { + let (value, keys) = path.split_last().unwrap(); + let mut at = &mut *m; + for key in keys { + at = match key { + Value::String(key) => &mut at[key.as_str()], + Value::Number(i) => &mut at[usize::try_from(i.as_u64().unwrap()).unwrap()], + _ => unreachable!(), + }; + } + *at = value.clone(); + }) +} + +/// A field the spec's table does not list is rejected on every kind, at +/// its own pointer: nothing is accepted and left unenforced. +#[test] +fn every_field_the_spec_does_not_decide_is_rejected_where_it_is_set() { + for (edit, pointer) in [ + ( + json!(["runtime", "include_user_skills", true]), + "/runtime/include_user_skills", + ), + ( + json!(["runtime", "limits", "budget_usd", 1.0]), + "/runtime/limits/budget_usd", + ), + ( + json!(["models", 0, "temperature", 0.2]), + "/models/0/temperature", + ), + ( + json!(["models", 0, "max_tokens", 100]), + "/models/0/max_tokens", + ), + ( + json!(["profiles", 0, "bare_prompt", true]), + "/profiles/0/bare_prompt", + ), + ( + json!(["permissions", 0, "allow_tools", ["word_count"]]), + "/permissions/0/allow_tools", + ), + ( + json!(["permissions", 0, "deny_tools", ["word_count"]]), + "/permissions/0/deny_tools", + ), + ( + json!(["permissions", 0, "send_destinations", ["floor"]]), + "/permissions/0/send_destinations", + ), + ( + json!(["permissions", 0, "send_operations", ["post"]]), + "/permissions/0/send_operations", + ), + ( + json!(["seats", 0, "tools", "deny", ["web_search"]]), + "/seats/0/tools/deny", + ), + ( + json!(["profiles", 0, "tools", "allow", ["word_count"]]), + "/profiles/0/tools/allow", + ), + ( + json!(["seats", 1, "limits", "iterations", 4]), + "/seats/1/limits/iterations", + ), + ( + json!(["seats", 0, "config", {"flavour": "plain"}]), + "/seats/0/config", + ), + ( + json!(["seats", 0, "agent_id", "lead-agent"]), + "/seats/0/agent_id", + ), + ( + json!(["runtime", "workspace", "/srv/hive"]), + "/runtime/workspace", + ), + ( + json!(["runtime", "deployment_id", "mixed"]), + "/runtime/deployment_id", + ), + (json!(["runtime", "concurrency", 2]), "/runtime/concurrency"), + (json!(["runtime", "max_agents", 3]), "/runtime/max_agents"), + ( + json!(["runtime", "memory_engine", "memory"]), + "/runtime/memory_engine", + ), + ] { + assert_eq!(integration_pointers(&mixed_at(&edit)), [pointer], "{edit}"); + } + // Skills are rejected wherever a seat receives them, even unresolved. + let found = mixed_at(&json!(["seats", 0, "skills", ["notes"]])); + assert!( + integration_pointers(&found).contains(&"/seats/0/skills"), + "{found:?}" + ); + let found = mixed_at(&json!(["toolpacks", 0, "skills", ["notes"]])); + assert!( + integration_pointers(&found).contains(&"/toolpacks/0/skills"), + "{found:?}" + ); + let found = mixed(|m| { + m["runtime"]["session_store"] = json!("sqlite"); + m["runtime"]["workspace"] = json!("/srv/hive"); + }); + assert!( + integration_pointers(&found).contains(&"/runtime/session_store"), + "{found:?}" + ); + // OpenHuman honours an iteration limit up to its cap. + assert_eq!( + mixed_at(&json!(["seats", 0, "limits", "iterations", 4])), + vec![] + ); +} + +#[test] +fn a_stop_hook_is_rejected_and_a_tool_hook_is_the_hosts() { + let with_hook = |event: &str| { + mixed(|m| { + m["hooks"] = json!([{"id": "done", "event": event, "run": "word_count"}]); + if event == "stop" { + m["hooks"][0]["matcher"] = json!(null); + } + m["seats"][0]["hooks"] = json!(["done"]); + }) + }; + assert_eq!(integration_pointers(&with_hook("stop")), ["/hooks/0/event"]); + assert_eq!(with_hook("pre_tool_use"), vec![]); +} + +#[test] +fn one_setting_rejected_by_several_kinds_keeps_each_kinds_reason() { + let found = mixed_at(&json!(["providers", 0, "credential", {"env": "KEY"}])); + let reasons: Vec<&str> = found + .iter() + .filter(|d| d.pointer.as_deref() == Some("/providers/0/credential")) + .map(|d| d.message.as_str()) + .collect(); + assert_eq!(reasons.len(), 3, "{reasons:?}"); + for kind in ["openhuman", "openclaw", "codex"] { + assert!( + reasons + .iter() + .any(|r| r.contains(&format!("the {kind} harness"))), + "{kind}" + ); + } +} + +#[test] +fn the_sections_a_seat_reaches_are_walked_too() { + let mut docs = example("mixed-harnesses"); + let mut manifest: Value = serde_json::from_str(&docs["hive.json"]).unwrap(); + manifest["skills"] = json!([{"id": "notes"}]); + manifest["toolpacks"][0]["skills"] = json!(["notes"]); + manifest["mcp"] = + json!([{"id": "issues", "transport": "http", "endpoint": "https://mcp.example.com"}]); + manifest["toolpacks"][0]["mcp"] = json!(["issues"]); + manifest["workflows"] = json!([{"id": "nightly", "schedule": "0 3 * * *", + "target": {"hive": "mixed-harnesses"}, "prompt": "Summarise the day"}]); + docs.insert("hive.json".into(), manifest.to_string()); + docs.insert("skills/notes/SKILL.md".into(), "Take notes.\n".into()); + let found = diagnose_documents(&docs).1; + // The skill is rejected at its declaration as well as where it is + // granted; the MCP server and the workflow are the host's. + assert_eq!( + integration_pointers(&found), + ["/toolpacks/0/skills", "/skills/0/id"], + "{found:?}" + ); +} + +#[test] +fn a_shared_instance_without_an_explicit_isolation_is_reported_at_its_entry() { + let found = mixed(|m| { + m["providers"] + .as_array_mut() + .unwrap() + .push(json!({"id": "other", "kind": "openai", "endpoint": "http://127.0.0.1:9090/v1"})); + m["models"] + .as_array_mut() + .unwrap() + .push(json!({"id": "second", "provider": "other", "name": "second-model"})); + m["seats"][0]["harness"] = json!("claw"); + m["seats"][0]["model"] = json!("second"); + m["harnesses"][0] + .as_object_mut() + .unwrap() + .remove("isolation"); + }); + assert_eq!(integration_pointers(&found), ["/harnesses/0"]); +} diff --git a/crates/tinyhivemind-lang/src/validation/test/integration.rs b/crates/tinyhivemind-lang/src/validation/test/integration.rs index 1469a43c..06ddeacd 100644 --- a/crates/tinyhivemind-lang/src/validation/test/integration.rs +++ b/crates/tinyhivemind-lang/src/validation/test/integration.rs @@ -8,7 +8,15 @@ use std::collections::BTreeMap; /// The `integrations` example package, every file keyed by relative path. pub(crate) fn documents() -> BTreeMap { - let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("examples/hives/integrations"); + example("integrations") +} + +/// The example package `examples/hives/`, every file keyed by +/// relative path. +pub(crate) fn example(name: &str) -> BTreeMap { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("examples/hives") + .join(name); let mut files = BTreeMap::new(); let mut pending = vec![(root, String::new())]; while let Some((dir, prefix)) = pending.pop() { @@ -34,7 +42,7 @@ fn after(edit: impl FnOnce(&mut Value)) -> Vec { diagnose_documents(&docs).1 } -fn has(found: &[Diagnostic], rule: Rule, pointer: &str) -> bool { +pub(super) fn has(found: &[Diagnostic], rule: Rule, pointer: &str) -> bool { found .iter() .any(|d| d.rule == rule && d.pointer.as_deref() == Some(pointer)) diff --git a/crates/tinyhivemind-lang/src/validation/test/mod.rs b/crates/tinyhivemind-lang/src/validation/test/mod.rs index 4f8700f9..9b230a55 100644 --- a/crates/tinyhivemind-lang/src/validation/test/mod.rs +++ b/crates/tinyhivemind-lang/src/validation/test/mod.rs @@ -1,5 +1,6 @@ //! Package validation: the fail-fast regressions, and every finding's //! location when the rules collect instead of stopping. +mod harness; pub(crate) mod integration; mod locations; mod rules; diff --git a/crates/tinyhivemind-lang/tests/README.md b/crates/tinyhivemind-lang/tests/README.md index b889be85..86b801e4 100644 --- a/crates/tinyhivemind-lang/tests/README.md +++ b/crates/tinyhivemind-lang/tests/README.md @@ -6,6 +6,7 @@ This directory owns tests for the portable hive language. | --- | --- | | example_packages.rs | Behavior regression tests. | | gallery_packages.rs | Every package under `examples/hives/` parses and lowers, with its desks, seats, links, memory bindings and constitution pinned; no seat reaches the web except `web_search` on `euler-hive`'s research desk. | +| content_ids.rs | Every shipped package without a harness hashes to the literal content id it had before the harness fields existed. | | direct_edits.rs | Direct edits to the gallery's `self-improving` package checked by `check`: accepted, refused with located diagnostics, and reproduced through derived patches. | | euler_hive_package.rs | The `euler-hive` package parses and lowers from disk: five linked desks with referral enabled, web search only on research seats, `run_python` only on compute and verify, distinct personas, an agent memory binding per seat that reads the verified pool, and a placeholder problem. | | minimal_packages.rs | A `hive.json` that omits every defaulted section parses, validates and lowers; partial policy blocks keep their other defaults; defaults still answer to the constitution; unknown fields and arrays in place of objects are still rejected; and every shipped package re-serializes to exactly its contents. | diff --git a/crates/tinyhivemind-lang/tests/content_ids.rs b/crates/tinyhivemind-lang/tests/content_ids.rs new file mode 100644 index 00000000..61aff324 --- /dev/null +++ b/crates/tinyhivemind-lang/tests/content_ids.rs @@ -0,0 +1,105 @@ +//! Every shipped package keeps the content id it had before the language +//! learnt about harnesses. +//! +//! [`content_id`] hashes the package's whole serialization, so a new field +//! that serialized when absent would change every id a host has recorded in +//! its lineage. These literals were computed from `main` before the +//! `harnesses` section and the `harness` fields existed; a package that +//! declares neither must hash to exactly them. +use std::{collections::BTreeMap, fs, path::Path}; +use tinyhivemind_lang::{MemoryLifecycle, lineage::content_id, parse}; + +type Result = std::result::Result>; + +/// Every file under `dir`, keyed by package-relative path. +fn documents(dir: &Path) -> Result> { + let mut files = BTreeMap::new(); + let mut pending = vec![(dir.to_path_buf(), String::new())]; + while let Some((dir, prefix)) = pending.pop() { + for entry in fs::read_dir(dir)? { + let entry = entry?; + let key = format!("{prefix}{}", entry.file_name().to_string_lossy()); + if entry.file_type()?.is_dir() { + pending.push((entry.path(), format!("{key}/"))); + } else { + files.insert(key, fs::read_to_string(entry.path())?); + } + } + } + Ok(files) +} + +/// The content id of the package in `dir`, every persistent memory at +/// watermark zero. +fn id_of(dir: &str) -> Result { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join(dir); + let package = parse(&documents(&root)?)?; + let watermarks = package + .memory + .identities + .iter() + .filter(|identity| identity.lifecycle == MemoryLifecycle::Hive) + .map(|identity| (identity.id.clone(), 0)) + .collect(); + Ok(content_id(&package, &watermarks)?) +} + +#[test] +fn packages_without_a_harness_keep_their_content_ids() -> Result<()> { + let pinned = [ + ( + "examples/hives/review-board", + "sha256:9ce4a1dd15d31acf69e8d6eddfd050a4eceb8fa083a2b3679cd74fa7a60a8488", + ), + ( + "examples/hives/research-debate", + "sha256:00f5a62cc6ba43bd30a08e64eb7a486222d075c3570006e98b8f5bf0282763f5", + ), + ( + "examples/hives/incident-response", + "sha256:d67a63ce6992b418dc40412e8e17f2c35591dffd1fae5ed70813d68d740b4ffa", + ), + ( + "examples/hives/memory-guild", + "sha256:71ed8edf6e03d6d4f39643c1c1e077b2fa5680e2444687af9793823eb048e867", + ), + ( + "examples/hives/self-improving", + "sha256:9bc13bc144458208cf05a3b9fb7712eb7246da311f5e1b85355eaf17d19c9b37", + ), + ( + "examples/hives/math-panel", + "sha256:f819b3f021d11395c5229c23c29b3b9fb5b6c54423bbf6013d8ad21bde127661", + ), + ( + "examples/hives/math-swarm", + "sha256:d2bbe36d39974e0d26390b8325acc2d35d4e7f0769bfef975371ba4b2211cacc", + ), + ( + "examples/hives/integrations", + "sha256:7cd70afd74951dcb2d174da71f7229b735c2025fa99b089bbb6a90bcfb498268", + ), + ( + "examples/hives/euler-hive", + "sha256:eca2fd31927bd9132b3cc748b03fcab206718cb7c265ed0e1bf26a0a031489ff", + ), + ( + "tests/fixtures/deepswe", + "sha256:aace3549f9fa4870dd862c34717a875b863e40cc9fc00586b94e478bc963d62b", + ), + ( + "tests/fixtures/pe1006", + "sha256:17973e67b5fb89a67183a71d28d4ba4ffbca05c9c83b9a14b7698cb823852767", + ), + ]; + let actual = pinned + .iter() + .map(|(dir, _)| Ok((*dir, id_of(dir)?))) + .collect::>>()?; + let expected: Vec<_> = pinned + .iter() + .map(|(dir, id)| (*dir, (*id).to_owned())) + .collect(); + assert_eq!(actual, expected); + Ok(()) +} diff --git a/crates/tinyhivemind-lang/tests/gallery_packages.rs b/crates/tinyhivemind-lang/tests/gallery_packages.rs index 6ffde10b..43d550cf 100644 --- a/crates/tinyhivemind-lang/tests/gallery_packages.rs +++ b/crates/tinyhivemind-lang/tests/gallery_packages.rs @@ -281,7 +281,10 @@ const WEB_RESEARCH_DESK: &str = "research"; /// Every package directory under `examples/hives/`, read from disk the way a /// host loads it, so a package added later is checked without being listed. -fn gallery_from_disk() -> Result> { +/// +/// The flag says whether the package names a harness, which holds it to the +/// capability table. +fn gallery_from_disk() -> Result> { let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("examples/hives"); let mut dirs: Vec<_> = std::fs::read_dir(&root)? .map(|entry| entry.map(|entry| entry.path())) @@ -297,8 +300,8 @@ fn gallery_from_disk() -> Result> { .ok_or("package directory has a name")? .to_string_lossy() .into_owned(); - let (_, hive) = lowered(&documents).map_err(|error| format!("{name}: {error}"))?; - packages.push((name, hive)); + let (package, hive) = lowered(&documents).map_err(|error| format!("{name}: {error}"))?; + packages.push((name, hive, !package.manifest.harnesses.is_empty())); } Ok(packages) } @@ -337,11 +340,11 @@ fn no_gallery_seat_may_reach_the_web_outside_euler_hives_research_desk() -> Resu "self-improving", ] { assert!( - packages.iter().any(|(name, _)| name == listed), + packages.iter().any(|(name, _, _)| name == listed), "{listed} is read" ); } - for (name, hive) in &packages { + for (name, hive, judged) in &packages { assert!(!hive.seats.is_empty(), "{name}"); let researchers: Vec<&str> = if name == WEB_RESEARCH_PACKAGE { hive.desks @@ -372,6 +375,20 @@ fn no_gallery_seat_may_reach_the_web_outside_euler_hives_research_desk() -> Resu } else { assert!(allowed.is_empty(), "{name}/{} allows {allowed:?}", seat.id); } + // A package that names a harness may not carry a deny list (the + // capability table rejects one); its seats stay off the web + // because no built-in tool group can be turned on. + if *judged { + assert!( + seat.integration + .groups + .values() + .all(|mode| *mode == tinyhivemind_lang::GroupMode::Off), + "{name}/{} turns a built-in tool group on", + seat.id + ); + continue; + } for tool in WEB_TOOLS { if allowed.contains(&tool) { continue; diff --git a/crates/tinyhivemind-openhuman/src/deploy/README.md b/crates/tinyhivemind-openhuman/src/deploy/README.md index 089d1c5c..243275d1 100644 --- a/crates/tinyhivemind-openhuman/src/deploy/README.md +++ b/crates/tinyhivemind-openhuman/src/deploy/README.md @@ -21,6 +21,19 @@ classifier. `stop` script hooks are run by `hooks::wrap_turn` on a finished repl and only observe it: a turn is authorized by the coordinator's round, so a stop hook cannot start another. +Before anything is built, `packages::harnesses` refuses a seat whose resolved +harness is not `openhuman` (`DeployError::UnsupportedHarness`): only a process +deployment can start another kind, and this adapter would otherwise accept the +field and ignore it. Two packages declaring one harness id differently are a +`ConflictingDeclaration` unless they name the same kind and the same +resolved isolation; a shared seat's harness is part of the seat +integration that must already agree. + +A seat of a package that names a harness lowers with `unlisted_groups = Off`; +`profile::seat_groups` then registers it with every tool group its toolpacks +do not list turned off, rather than the runtime's defaults (which withhold +them, leaving them callable through `use_skill`). + A toolpack's tool groups apply under the runtime's ceiling (`profile::groups`): an agent may narrow the runtime's disclosure of a group but a mode more exposed than the runtime's is refused, as is an unknown group id. diff --git a/crates/tinyhivemind-openhuman/src/deploy/mod.rs b/crates/tinyhivemind-openhuman/src/deploy/mod.rs index 694be836..784d6775 100644 --- a/crates/tinyhivemind-openhuman/src/deploy/mod.rs +++ b/crates/tinyhivemind-openhuman/src/deploy/mod.rs @@ -172,8 +172,9 @@ impl HiveDeployment { for seat in &config.seats { let mut spec = profile::seat(&config, seat, secrets.as_ref(), permissions.clone())?; let groups = &config.profile_for(seat)?.groups; - if !groups.is_empty() { - spec = spec.tool_groups(profile::groups(runtime.tool_groups(), groups)?); + let unlisted = extras.get(&seat.id).and_then(|exec| exec.unlisted_groups); + if let Some(groups) = profile::seat_groups(runtime.tool_groups(), groups, unlisted)? { + spec = spec.tool_groups(groups); } if let Some(exec) = extras.get(&seat.id).filter(|exec| !exec.hooks.is_empty()) { spec = spec.tool_hook(Arc::new(packages::ScriptHooks(exec.hooks.clone()))); diff --git a/crates/tinyhivemind-openhuman/src/deploy/packages.rs b/crates/tinyhivemind-openhuman/src/deploy/packages.rs index 2dae108a..4830e047 100644 --- a/crates/tinyhivemind-openhuman/src/deploy/packages.rs +++ b/crates/tinyhivemind-openhuman/src/deploy/packages.rs @@ -44,6 +44,9 @@ pub(super) struct SeatExec { pub(super) context: Arc, pub(super) programs: Vec, pub(super) hooks: Arc, + /// The mode of every tool group the seat's toolpacks do not list, as + /// lowered: `Some(Off)` when its package names a harness. + pub(super) unlisted_groups: Option, } /// Executable tools and hooks, by seat id. @@ -56,6 +59,7 @@ pub(super) fn prepare( secrets: &Arc, native: &mut openhuman_embed::RuntimeConfig, ) -> DeployResult<(HiveConfig, Extras)> { + harnesses(packages)?; let Plan { mut config, seats, @@ -65,6 +69,16 @@ pub(super) fn prepare( apply_session(native, &session); apply_jev(native, &jev); let exec_secrets: Arc = Arc::new(ExecSecrets(secrets.clone())); + // A seat several packages share has one lowered integration (the plan + // requires them to agree), so the first package's is the seat's. + let mut unlisted = BTreeMap::new(); + for source in packages { + for seat in &source.lowered().seats { + unlisted + .entry(seat.id.clone()) + .or_insert(seat.integration.unlisted_groups); + } + } let mut extras = Extras::new(); for (seat, plan) in &seats { if let Some(dir) = skills_dir(&config.runtime.deployment_id, seat, plan)? { @@ -91,12 +105,50 @@ pub(super) fn prepare( context, programs: plan.programs.clone(), hooks, + unlisted_groups: unlisted.get(seat).copied().flatten(), }, ); } Ok((config, extras)) } +/// Refuse what this adapter would otherwise accept and ignore: a seat whose +/// resolved harness is not `openhuman`, which only a process deployment can +/// start, and two packages declaring one harness id differently. +pub(super) fn harnesses(packages: &[PackageSource]) -> DeployResult<()> { + let mut declared = BTreeMap::<&str, &lang::Harness>::new(); + for source in packages { + for harness in &source.package().manifest.harnesses { + // Two entries agree when they start the same kind the same way; + // an omitted isolation is the kind's default. + let same = |earlier: &&lang::Harness| { + earlier.kind == harness.kind + && earlier.resolved_isolation() == harness.resolved_isolation() + }; + if declared + .insert(&harness.id, harness) + .is_some_and(|earlier| !same(&earlier)) + { + return Err(ConfigError::ConflictingDeclaration { + section: "harnesses".into(), + id: harness.id.clone(), + } + .into()); + } + } + for seat in &source.lowered().seats { + let kind = seat.integration.harness_kind(); + if kind != lang::HarnessKind::OpenHuman { + return Err(DeployError::UnsupportedHarness { + seat: seat.id.clone(), + kind, + }); + } + } + } + Ok(()) +} + fn apply_session(native: &mut openhuman_embed::RuntimeConfig, session: &lang::SessionSettings) { let agent = &mut native.agent; if let Some(value) = session.compact_context { diff --git a/crates/tinyhivemind-openhuman/src/deploy/profile.rs b/crates/tinyhivemind-openhuman/src/deploy/profile.rs index bf47cd0b..72341227 100644 --- a/crates/tinyhivemind-openhuman/src/deploy/profile.rs +++ b/crates/tinyhivemind-openhuman/src/deploy/profile.rs @@ -255,3 +255,32 @@ pub(super) fn groups( } Ok(groups) } + +/// The tool groups a seat registers with, or `None` to keep the runtime's. +/// +/// `unlisted` is the lowered mode of every group the seat's toolpacks do not +/// list: `None` for a package that names no harness, which keeps the +/// runtime's defaults, and `Some(Off)` for one that does, whose seats may run +/// no built-in tool. The listed groups apply under the runtime's ceiling as +/// [`groups`] does. +/// +/// # Errors +/// An unknown group, or one more exposed than the runtime allows. +pub(super) fn seat_groups( + runtime: &openhuman_embed::ToolGroups, + listed: &std::collections::BTreeMap, + unlisted: Option, +) -> DeployResult> { + if unlisted.is_none() && listed.is_empty() { + return Ok(None); + } + let mut seat = groups(runtime, listed)?; + if unlisted == Some(tinyhivemind_lang::GroupMode::Off) { + for id in openhuman_embed::ToolGroups::ids() { + if !listed.contains_key(id) { + seat = seat.with(id, openhuman_embed::GroupMode::Off); + } + } + } + Ok(Some(seat)) +} diff --git a/crates/tinyhivemind-openhuman/src/deploy/test/packages.rs b/crates/tinyhivemind-openhuman/src/deploy/test/packages.rs index 44bef77d..4ba54f68 100644 --- a/crates/tinyhivemind-openhuman/src/deploy/test/packages.rs +++ b/crates/tinyhivemind-openhuman/src/deploy/test/packages.rs @@ -202,3 +202,187 @@ fn a_package_seat_runs_a_shell_tool_and_an_unknown_group_is_refused() -> anyhow: Ok(()) }) } + +/// A package from `examples/hives/` of the language crate. +fn example(name: &str) -> anyhow::Result { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../tinyhivemind-lang/examples/hives") + .join(name); + let package = PackageSource::read(&root)?; + Ok(PackageSource::new(root, &package)?) +} + +/// `mixed-harnesses` with its one remaining harness, `claw`, made an +/// `openhuman` harness every seat but the lead names. +fn openhuman_only() -> anyhow::Result { + let source = example("mixed-harnesses")?; + let mut package = source.package().clone(); + package.manifest.harnesses.truncate(1); + package.manifest.harnesses[0].kind = tinyhivemind_lang::HarnessKind::OpenHuman; + package.manifest.harnesses[0].isolation = None; + package.manifest.seats[2].harness = Some("claw".into()); + package.manifest.profiles[0].harness = None; + Ok(PackageSource::new(source.root(), &package)?) +} + +#[test] +fn a_seat_on_any_harness_but_openhuman_is_refused_before_deployment() -> anyhow::Result<()> { + let refused = crate::deploy::packages::harnesses(&[example("mixed-harnesses")?]); + assert!( + matches!( + &refused, + Err(DeployError::UnsupportedHarness { seat, kind }) + if seat == "scout" && *kind == tinyhivemind_lang::HarnessKind::OpenClaw + ), + "{refused:?}" + ); + assert_eq!( + refused.err().map(|error| error.to_string()).as_deref(), + Some("seat scout runs on the openclaw harness, which the linked adapter cannot start") + ); + // No harness anywhere, or an explicit `openhuman` one, deploys as today. + crate::deploy::packages::harnesses(&[example("integrations")?])?; + crate::deploy::packages::harnesses(&[openhuman_only()?])?; + Ok(()) +} + +#[test] +fn packages_must_agree_on_a_harness_declared_under_one_id() -> anyhow::Result<()> { + let one = openhuman_only()?; + let mut package = one.package().clone(); + package.manifest.harnesses[0].kind = tinyhivemind_lang::HarnessKind::Codex; + let other = PackageSource::new(one.root(), &package)?; + crate::deploy::packages::harnesses(&[one.clone(), one.clone()])?; + let refused = crate::deploy::packages::harnesses(&[one, other]); + assert!( + matches!( + &refused, + Err(DeployError::Config(crate::config::ConfigError::ConflictingDeclaration { section, id })) + if section == "harnesses" && id == "claw" + ), + "{refused:?}" + ); + Ok(()) +} + +#[test] +fn packages_that_mean_the_same_isolation_agree() -> anyhow::Result<()> { + let one = openhuman_only()?; + let mut package = one.package().clone(); + // `seat` is what an `openhuman` harness takes when it says nothing. + package.manifest.harnesses[0].isolation = Some(tinyhivemind_lang::Isolation::Seat); + let explicit = PackageSource::new(one.root(), &package)?; + crate::deploy::packages::harnesses(&[one, explicit])?; + Ok(()) +} + +#[test] +fn from_packages_refuses_a_seat_on_another_harness_before_starting_anything() -> anyhow::Result<()> +{ + let _lock = crate::RUNTIME_LOCK + .lock() + .unwrap_or_else(PoisonError::into_inner); + run(async { + let (options, _backend, _model) = build_options().await; + let refused = Box::pin(HiveDeployment::from_packages( + vec![example("mixed-harnesses")?], + Arc::new(Secrets), + options, + )) + .await; + assert!( + matches!(refused, Err(DeployError::UnsupportedHarness { ref seat, .. }) if seat == "scout"), + "{refused:?}" + ); + Ok(()) + }) +} + +#[test] +fn a_judged_seat_turns_every_tool_group_its_toolpacks_do_not_list_off() -> anyhow::Result<()> { + use openhuman_embed::{GroupMode, ToolGroups}; + let runtime = ToolGroups::advertised(); + let listed = std::collections::BTreeMap::from([( + ToolGroups::ids().next().unwrap_or_default().to_owned(), + tinyhivemind_lang::GroupMode::Withheld, + )]); + let judged = crate::deploy::profile::seat_groups( + &runtime, + &listed, + Some(tinyhivemind_lang::GroupMode::Off), + )? + .ok_or_else(|| anyhow::anyhow!("a judged seat sets its groups"))?; + for id in ToolGroups::ids() { + let expected = if listed.contains_key(id) { + GroupMode::Withheld + } else { + GroupMode::Off + }; + assert_eq!(judged.mode(id), expected, "{id}"); + } + // A seat of a package that names no harness keeps today's behaviour. + let unjudged = + crate::deploy::profile::seat_groups(&runtime, &std::collections::BTreeMap::new(), None)?; + assert_eq!(unjudged, None); + Ok(()) +} + +#[test] +fn a_judged_openhuman_seat_deploys_with_no_built_in_tool_group() -> anyhow::Result<()> { + let _lock = crate::RUNTIME_LOCK + .lock() + .unwrap_or_else(PoisonError::into_inner); + run(async { + let (options, _backend, model) = build_options().await; + mount(&model, Script::default()).await; + let source = openhuman_only()?; + let mut package = source.package().clone(); + // The check judges the provider each seat's model names; the linked + // adapter uses the runtime's, so leaving that one to the fixture's + // injected provider deploys the same judged seats offline. + package.manifest.runtime.provider = None; + let deployment = Box::pin(HiveDeployment::from_packages( + vec![PackageSource::new(source.root(), &package)?], + Arc::new(Secrets), + options, + )) + .await?; + deployment + .host() + .coordinator() + .send_as_host(SendMessage { + message_id: "tools".into(), + sender: String::new(), + destination: Destination::Hive("mixed-harnesses".into()), + body: "Say hello".into(), + thread: None, + only_for: Vec::new(), + starters: vec!["lead".into()], + }) + .await?; + let report = deployment.host().coordinator().run_until_idle().await?; + assert_eq!(report.failed, 0, "{report:?}"); + let mut offered = std::collections::BTreeSet::new(); + for request in model.received_requests().await.unwrap_or_default() { + let body: Value = serde_json::from_slice(&request.body).unwrap_or_default(); + for tool in body["tools"].as_array().into_iter().flatten() { + if let Some(name) = tool["function"]["name"].as_str() { + offered.insert(name.to_owned()); + } + } + } + assert!(offered.contains("word_count"), "{offered:?}"); + let none = openhuman_embed::ToolGroups::none(); + let built_in: Vec<_> = offered + .iter() + .filter(|name| { + *name == "use_skill" || none.mode_for_tool(name) == openhuman_embed::GroupMode::Off + }) + .collect(); + assert!( + built_in.is_empty(), + "built-in tools reached the model: {built_in:?}" + ); + Ok(()) + }) +} diff --git a/crates/tinyhivemind-openhuman/src/deploy/types.rs b/crates/tinyhivemind-openhuman/src/deploy/types.rs index 0f41801f..a9e637b2 100644 --- a/crates/tinyhivemind-openhuman/src/deploy/types.rs +++ b/crates/tinyhivemind-openhuman/src/deploy/types.rs @@ -24,6 +24,15 @@ pub enum DeployError { /// A workflow could not be registered or triggered. #[error("workflow operation failed for {0}")] Workflow(String), + /// A seat resolves to a harness this adapter cannot start: it links + /// `OpenHuman` and runs no harness process. + #[error("seat {seat} runs on the {kind} harness, which the linked adapter cannot start")] + UnsupportedHarness { + /// The seat. + seat: String, + /// The kind it resolves to. + kind: tinyhivemind_lang::HarnessKind, + }, } /// Deployment result, with credential-safe errors. pub type DeployResult = std::result::Result; diff --git a/docs/specs/harnesses.md b/docs/specs/harnesses.md index aab73c61..20739a9d 100644 --- a/docs/specs/harnesses.md +++ b/docs/specs/harnesses.md @@ -5,12 +5,14 @@ Boundary: [ADR 0035](../adr/0035-a-harness-is-a-process.md), [ADR 0036](../adr/0036-hive-tools-are-served-over-loopback-mcp.md). Evidence: [the harness spike](../experiments/2026-11-25-process-harnesses.md). -Implemented so far, by step 1 of the plan: the harness-neutral host crate, the -harness port with the seat rules below, start verification, process supervision -on Linux, and a conformance suite that a scripted fake harness passes. No client -for a real harness, no MCP server and no `harnesses` section exist yet. Until the -plan's removal phase lands, the linked OpenHuman adapter remains the way a -package is deployed. +Implemented so far, by steps 1 and 3 of the plan: the harness-neutral host +crate, the harness port with the seat rules below, start verification, process +supervision on Linux, a conformance suite that a scripted fake harness passes, +and the package schema: the `harnesses` section, `harness` on runtime, profile +and seat, the capability table in `tinyhivemind-lang` and its `check` +diagnostics. No client for a real harness and no MCP server exist yet. Until +the plan's removal phase lands, the linked OpenHuman adapter remains the way a +package is deployed, and it refuses a seat whose harness is not `openhuman`. ## Problem @@ -82,7 +84,9 @@ in it, and opens an MCP session for each of them on every run. executable tools; this rule keeps the process that *enforces* permissions out of reach of a package edit. - An absent field is not serialized, so an existing package keeps its content - id. A test pins one. + id. A test pins one. Written, `harness` is a string and `harnesses` holds at + least one entry: `null` and `[]` would not survive the round trip, so they + are decode errors. In a split package `harnesses` lives in `agents.json`. - `harnesses` and `runtime.harness` are in the `integration` edit class. A change to a seat's `harness` requires `integration` as well as `roster`, so a hive allowed to edit its roster cannot move a seat to another harness. @@ -95,6 +99,36 @@ in it, and opens an MCP session for each of them on every run. the resolved harness cannot honour under the existing `integration` rule, at the field's location. +The last nine rows are fields this table did not originally decide. The check +is default-deny: every field of every integration type has a row, a field the +table does not support is rejected, and a test fails when a field is added to +the language without one. The send limits and tool lists are enforced today by +the linked adapter's permission gate, not by the host, so they start rejected +like the rest. Only language structure is exempt: identities, references +(whose target is judged where it is declared), labels, a seat's `template` (a +name the host maps to how it creates the agent), the hive's roster, desks, +goals and policies, which the coordinator runs whatever the harness, and the +harness entries themselves. Feature flags and `context` count with executable +tools and the prompt: lowering applies the switches, and `tinyhivemind-exec` +passes every flag to a tool. + +The table judges a package once it declares a harness or names one anywhere, +and then every seat, the implicit `openhuman` ones included. A package that +does neither is deployed by the linked adapter, which keeps its own limits +(below), so the table does not judge it and every existing package stays +valid. A field the map has no decision for is rejected too, so even a field +added to the language before its row is rejected rather than passed. Plan step 6 flips this: with the link gone, every package is judged. + +In the table as data (`HarnessKind::support`), each rejected row also says +what moves it: only a conformance test (provider shapes, `credential`, and +OpenHuman's subagents, `definition_base`, `jev` and `session` tuning), a +harness release then a test (OpenHuman's `tool_rules`), or a spec decision +(everything else rejected). The OpenHuman eight-iteration cap below is a +per-kind rule beside the table (`HarnessKind::iteration_cap`), reported at the +layer that sets `limits.iterations`. No built-in tool can be turned on, so no +hook can match one; `check` does not inspect hook matchers for built-in tool +names. + | Field | openhuman | openclaw | codex | | --- | --- | --- | --- | | prompt, model name, hive and executable tools, limits.timeout_ms | yes | yes | yes | @@ -107,16 +141,30 @@ field's location. | `sandbox` `none` or absent, on `runtime` and `permissions` | yes | yes | yes | | `sandbox` `read_only` or `sandboxed` | rejected | rejected | rejected | | `autonomy` and `permissions.access` | yes, host side | yes, host side | yes, host side | -| built-in tool groups | exact allowlist | off | off | +| built-in tool groups | off | off | off | | `tool_rules` on built-in tools | rejected until a release has them | rejected | rejected | | hooks on built-in tools | rejected | rejected | rejected | | package MCP servers | through the host server | through the host server | through the host server | | `session_store = "host"`, `memory_engine = "host"` | rejected | rejected | rejected | | subagents, `definition_base`, `jev`, `session` tuning | rejected at first | rejected | rejected | | workflows | coordinator schedule | coordinator schedule | coordinator schedule | +| `limits.iterations` | up to the cap below | rejected | rejected | +| skills, `include_user_skills` | rejected | rejected | rejected | +| `limits.budget_usd`, a model's `temperature` and `max_tokens` | rejected | rejected | rejected | +| `bare_prompt`, a seat's `config` and `agent_id` | rejected | rejected | rejected | +| tool allow and deny lists (`tools`, `allow_tools`, `deny_tools`) | rejected | rejected | rejected | +| `send_destinations`, `send_operations` | rejected | rejected | rejected | +| `stop` hooks | rejected | rejected | rejected | +| `runtime` `workspace`, `deployment_id`, `max_agents`, a non-default `concurrency` | rejected | rejected | rejected | +| `session_store = "sqlite"`, `memory_engine = "memory"` | rejected | rejected | rejected | Built-in tools start **off** for every kind. Turning one on is a later change -that must first show its permissions are enforced. "Rejected" is the starting +that must first show its permissions are enforced. "Off" is the rule for every +group a package does not list, too: a judged package lowers each seat with +`unlisted_groups = Off`, so no harness default can switch a group on, and the +linked adapter registers a judged `openhuman` seat with every unlisted group +off. (The OpenHuman process runner will configure that as an exact +`tool_allowlist`; that is how it is enforced, not a permission.) "Rejected" is the starting point, not a promise: a row moves when a conformance test proves the setting. A `sandbox` is rejected because executable tools on this path run from the host's @@ -367,3 +415,10 @@ or tool environment. Live tests (`live_*`, opt-in) run the same cases on the pinned binaries, then a mixed hive reaches a decision with every message in the coordinator transcript. + +## Open questions + +- A roster edit may still change a seat's other integration fields (`model`, + `toolpacks`, `permissions` and the rest) without the `integration` class; + only `harness` needs both today. Whether those fields move to the same + two-class rule is undecided. diff --git a/docs/specs/hive-language-integrations.md b/docs/specs/hive-language-integrations.md index a252d04f..650fc2a9 100644 --- a/docs/specs/hive-language-integrations.md +++ b/docs/specs/hive-language-integrations.md @@ -70,6 +70,7 @@ so scripts take part in the package's content identity and lineage. | `jev` | `{ranker, route, base_url?, top_k}` | native `agent.tool_search` | | `features` | `{name: bool}` | integration switches and tool environment | | `workflows` | `[{id, schedule, target, prompt, enabled, retries, single_flight}]` | native cron jobs | +| `harnesses` | `[{id, kind, isolation?}]` | the harness each seat runs on ([harnesses](harnesses.md)); the linked adapter starts only `openhuman` | `runtime` fields: `deployment_id?`, `workspace?`, `session_store` (`memory` \| `sqlite` \| `host`, default `memory`), `memory_engine` @@ -77,7 +78,8 @@ so scripts take part in the package's content identity and lineage. (`read_only` \| `supervised` \| `autonomous`, default `supervised`), `sandbox` (`none` \| `read_only` \| `sandboxed`), `concurrency` (default 4), `max_agents?`, `include_user_skills`, `start_scheduler`, and the defaults every -seat inherits: `provider?`, `model?`, `permissions?`, `toolpacks`, `limits`. +seat inherits: `provider?`, `model?`, `permissions?`, `toolpacks`, `limits`, +`harness?`. `limits` is `{timeout_ms?, iterations?, budget_usd?}` wherever it appears. @@ -161,7 +163,12 @@ identical. `subagents`) that sets a model, MCP servers, skills, toolpacks, hooks, subagents, a timeout or a budget, a `matcher` on a `stop` hook (stop has no tool), an `argv` placeholder that names no argument, and a - feature name outside `[a-z0-9_]+` (`integration`). + feature name outside `[a-z0-9_]+` (`integration`); +- for harnesses: an undeclared harness (`reference`), a duplicate harness id + (`identity`), `deployment` isolation on a kind other than `openclaw`, a + harness on a delegated profile, and, once a package names a harness, every + setting the [capability table](harnesses.md#capabilities) rejects and an + executable tool argument named `turn` or `call` (`integration`). Permission narrowing (a hive overlay never widens the seat) and MCP agreement across packages are deployment checks in the adapter, because they need every @@ -171,8 +178,11 @@ package at once. A new patch class, `integration`, owns `runtime`, `providers`, `models`, `mcp`, `skills`, `tools`, `toolpacks`, `permissions`, `profiles`, `hooks`, -`session`, `jev`, `features`, `workflows`, the files under `tools/` and -`skills/`, and the integration fields of a seat. A constitution that does not +`session`, `jev`, `features`, `workflows`, `harnesses`, the files under +`tools/` and `skills/`, and the integration fields of a seat. A seat's +`harness` is recorded as a roster change, but moving a seat to another +harness (its own field, or a `profile` that resolves elsewhere) also needs +`integration` permitted. A constitution that does not list `integration` in `permitted_edits` forbids a self-edit from changing what its agents can run or reach. Prompts, roster and policies keep their classes. diff --git a/docs/specs/hive-language.md b/docs/specs/hive-language.md index 508973a4..42654d86 100644 --- a/docs/specs/hive-language.md +++ b/docs/specs/hive-language.md @@ -43,7 +43,7 @@ under their usual keys: | File | May hold | | --- | --- | -| `agents.json` | `roles`, `seats`, `profiles` | +| `agents.json` | `roles`, `seats`, `profiles`, `harnesses` | | `tools.json` | `tools`, `toolpacks`, `mcp`, `skills`, `hooks` | | `desks.json` | `desks`, `topology`, `referrals` | @@ -68,7 +68,11 @@ writes one `hive.json`. Only what has no safe default is required. Omitting any other field is the same as writing its default, and serializing a package always writes every field, so a stored package is complete and its content identity does not -depend on how tersely it was written. +depend on how tersely it was written. The one exception is the harness +vocabulary (`harnesses`, and `harness` on the runtime, a profile and a seat): +absent, it is not written, so a package that predates it keeps its content +id, and its two spellings of "nothing" that would not survive the round trip, +`null` and an empty `harnesses` list, are decode errors. | File | Required | Omitted field → default | | --- | --- | --- |