From 0ce26d8d668636b9a279531e72bb3755f44b76c9 Mon Sep 17 00:00:00 2001 From: pgermishuys Date: Sun, 20 Sep 2026 16:31:18 +0000 Subject: [PATCH] test: populate the DSL and adapter buckets, fix the drift they exposed MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds 28 scenarios across the DSL and adapter buckets, and corrects the documentation they proved wrong. The adapter bucket was Claude Code only. `tests/support/adapter.ts` now drives any flush-based adapter from `.weave` source to the files a user would find on disk, so Copilot is covered by the same promises against a harness with different conventions — which is the point of the bucket. The OpenCode adapters register agents with a running harness rather than writing files, so they need a harness of their own and are not covered here. The DSL bucket gains tool policy resolution — declared, partial, absent, and a category tightening what its shuttle inherits — and prompt composition: plain prompts, template fields, append ordering, delegation loops, and the failure modes. Writing those against real behaviour surfaced documentation describing Weave as it no longer works: - `{{{delegation.section}}}` does not exist. ADR 0001 removed it and the automatic fallback append deliberately, and template-context.test.ts asserts both are absent from ALLOWED_TEMPLATE_PATHS — a prompt using the placeholder fails composition. AGENTS.md, CONTEXT.md, docs/dsl-reference.md, docs/cli.md and docs/prompt-composition.md all still documented it. So did packages/cli/src/prompts/self-modify.md, which is shipped guidance `weave prompt self-modify` prints: it told users to use a placeholder that breaks their config. - Object triggers are invalid. AGENTS.md still showed `triggers [{ domain "…" trigger "…" }]`; the schema takes quoted strings. - `{{domains}}` is not in the template context. Each is corrected, with a scenario pinning the real behaviour so it cannot drift again. Historical spec artifacts already carry SUPERSEDED annotations and are left alone. Refs #183 (task group 14) Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01DisVZW27sd6Pe7uhbjXNve --- .codesight/CODESIGHT.md | 4 +- .codesight/coverage.md | 2 +- AGENTS.md | 28 +-- CONTEXT.md | 2 +- docs/cli.md | 2 +- docs/dsl-reference.md | 2 - docs/prompt-composition.md | 2 +- docs/testing-strategy.md | 26 ++- packages/cli/src/prompts/self-modify.md | 11 +- tests/adapters/claude-code.scenario.test.ts | 90 +++----- tests/adapters/copilot.scenario.test.ts | 151 +++++++++++++ tests/dsl/prompt-composition.scenario.test.ts | 203 ++++++++++++++++++ tests/dsl/tool-policy.scenario.test.ts | 148 +++++++++++++ tests/support/adapter.ts | 101 +++++++++ 14 files changed, 680 insertions(+), 92 deletions(-) create mode 100644 tests/adapters/copilot.scenario.test.ts create mode 100644 tests/dsl/prompt-composition.scenario.test.ts create mode 100644 tests/dsl/tool-policy.scenario.test.ts create mode 100644 tests/support/adapter.ts diff --git a/.codesight/CODESIGHT.md b/.codesight/CODESIGHT.md index 8793d71e..e9f4af66 100644 --- a/.codesight/CODESIGHT.md +++ b/.codesight/CODESIGHT.md @@ -5,7 +5,7 @@ > 0 routes | 0 models | 0 components | 200 lib files | 25 env vars | 7 middleware | 1 events | 0% test coverage > **Token savings:** this file is ~18,200 tokens. Without it, AI exploration would cost ~66,400 tokens. **Saves ~48,200 tokens per conversation.** -> **Last scanned:** 2026-09-20 16:17 — re-run after significant changes +> **Last scanned:** 2026-09-20 16:31 — re-run after significant changes --- @@ -1024,7 +1024,7 @@ # Test Coverage > **0%** of routes and models are covered by tests -> 201 test files found +> 205 test files found --- diff --git a/.codesight/coverage.md b/.codesight/coverage.md index ef0f06b7..3f026d70 100644 --- a/.codesight/coverage.md +++ b/.codesight/coverage.md @@ -1,4 +1,4 @@ # Test Coverage > **0%** of routes and models are covered by tests -> 201 test files found +> 205 test files found diff --git a/AGENTS.md b/AGENTS.md index dea9f367..31e1c905 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -82,8 +82,8 @@ agent loom { } triggers [ - { domain "Orchestration" trigger "Complex multi-step tasks" } - { domain "Architecture" trigger "System design and planning" } + "Use for complex multi-step orchestration" + "Use for system design and planning" ] skills ["tdd", "code-review"] @@ -123,21 +123,28 @@ agent shuttle { - `models` — ordered model preference list for adapters to translate; concrete availability checks are adapter-owned - `mode` — adapter-facing context hint: `primary` (main/user-facing agent), `subagent` (delegated specialist), or `all` (usable in both contexts) - `tool_policy` — abstract capability map with `allow` / `deny` / `ask` permissions; adapters map to harness-specific tool names and permission models -- `triggers` — delegation metadata for router agents (e.g. Loom's delegation table) +- `triggers` — routing instructions for router agents (e.g. Loom's delegation table), as a non-empty list of quoted strings; object triggers are invalid #### Prompt Templates and Template Context Every `prompt`, `prompt_file`, `prompt_append`, and `prompt_append_file` value is a **Prompt Template** rendered by the engine with Mustache before adapters receive the final composed prompt. This lets prompt files reference engine-computed data without duplicating config. -**Key placeholder**: `{{{delegation.section}}}` — renders the full delegation guidance block (Mermaid diagram + compact bullets) at the location you choose. Use triple braces because the value contains Markdown. +**Delegation guidance is written explicitly.** There is no pre-rendered block and no automatic fallback: a router agent's prompt must loop over `delegation.targets` itself. ```md You are {{agent.name}}. -{{{delegation.section}}} +## Delegation + +{{#delegation.targets}} +- **{{name}}** — {{description}} +{{#triggers}} + - {{.}} +{{/triggers}} +{{/delegation.targets}} ``` -If the primary prompt source does not reference any `delegation.*` path, the engine appends `delegation.section` automatically as a fallback. Static prompts without Mustache tags are unaffected. +`delegation` is omitted from the context entirely when the agent has no eligible targets, so the section collapses to nothing rather than rendering an empty heading. **Available Template Context fields**: @@ -155,17 +162,12 @@ If the primary prompt source does not reference any `delegation.*` path, the eng | `{{toolPolicy.effective.execute}}` | `allow`\|`deny`\|`ask` | Resolved execute permission | | `{{toolPolicy.effective.delegate}}` | `allow`\|`deny`\|`ask` | Resolved delegate permission | | `{{toolPolicy.effective.network}}` | `allow`\|`deny`\|`ask` | Resolved network permission | -| `{{{delegation.section}}}` | string? | Full `## Delegation` Markdown block with Mermaid diagram and bullets | -| `{{{delegation.mermaid}}}` | string? | Mermaid diagram block only | | `{{#delegation.targets}}` | array | Iterate over eligible delegation targets | | `{{name}}` | string | Target agent name (inside `delegation.targets`) | | `{{description}}` | string? | Target description (inside `delegation.targets`) | -| `{{domains}}` | string[] | Deduplicated trigger domains (inside `delegation.targets`) | -| `{{#triggers}}` | array | Iterate over triggers (inside `delegation.targets`) | - -**Fallback suppression**: placing any real `delegation.*` reference in the primary prompt source (not in `prompt_append`) suppresses the automatic fallback. Use `\{{delegation.section}}` (backslash-escaped) to render the literal text `{{delegation.section}}` without triggering suppression. +| `{{#triggers}}` | array | Iterate over trigger strings with `{{.}}` (inside `delegation.targets`) | -**Unsupported features**: partials (`{{> footer}}`), delimiter changes, helpers, and lambdas are rejected at composition time with a typed `PromptTemplateError`. +**Unsupported paths and features**: the context is a closed allowlist — see `ALLOWED_TEMPLATE_PATHS` in [`packages/engine/src/template-context.ts`](packages/engine/src/template-context.ts). A tag naming anything outside it, as well as partials (`{{> footer}}`), delimiter changes, helpers and lambdas, is rejected at composition time with a typed `PromptTemplateError`. See [`docs/prompt-composition.md`](docs/prompt-composition.md) for the full specification and [`docs/adr/0001-prompt-composition-templates.md`](docs/adr/0001-prompt-composition-templates.md) for the design rationale. diff --git a/CONTEXT.md b/CONTEXT.md index db7834c8..edfe4264 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -263,7 +263,7 @@ _Avoid_: Public docs site, source of truth ## Prompt Composition Templates -Prompt composition templates are a first-class engine feature. Every agent `prompt`, `prompt_file`, and `prompt_append` value is a **Prompt Template** rendered with a bounded **Template Context** before adapters receive the final **Composed Prompt**. The Template Context exposes agent identity, effective tool policy, and generated delegation data — including `delegation.section` (a Mermaid diagram plus compact bullets) and `delegation.mermaid` (the diagram alone). Prompt authors use `{{{delegation.section}}}` to control where delegation guidance appears; prompts that omit any `delegation.*` reference receive the fallback delegation section automatically. Static prompts without Mustache tags are unaffected. +Prompt composition templates are a first-class engine feature. Every agent `prompt`, `prompt_file`, and `prompt_append` value is a **Prompt Template** rendered with a bounded **Template Context** before adapters receive the final **Composed Prompt**. The Template Context exposes agent identity, effective tool policy, and generated delegation data as `delegation.targets`, each target carrying its name, description and ordered trigger strings. Prompt authors write delegation guidance explicitly with a `{{#delegation.targets}}` loop; there is no pre-rendered `delegation.section` and no automatic fallback block. `delegation` is omitted entirely when an agent has no eligible targets, so the loop collapses. Static prompts without Mustache tags are unaffected. See [Prompt Composition Guide](docs/prompt-composition.md) and [ADR 0001](docs/adr/0001-prompt-composition-templates.md) for the full specification and rationale. diff --git a/docs/cli.md b/docs/cli.md index c7a66408..ffbc4d68 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -123,7 +123,7 @@ The printed guide includes: - Target-aware rules (global vs. local scope differences) - A step-by-step workflow: identify → read DSL section → edit config → place prompt files → validate → inspect - Common DSL patterns (override builtin, add agent, add category, disable agent) -- Prompt-specific rules (Mustache context fields, `{{{delegation.section}}}`, mutual exclusivity of `prompt`/`prompt_file`) +- Prompt-specific rules (Mustache context fields, `{{#delegation.targets}}` loops, mutual exclusivity of `prompt`/`prompt_file`) - Verification commands (`weave validate`, `weave prompt list`, `weave prompt inspect`) ### Canonical doc authority diff --git a/docs/dsl-reference.md b/docs/dsl-reference.md index 1311f905..99496bf8 100644 --- a/docs/dsl-reference.md +++ b/docs/dsl-reference.md @@ -475,8 +475,6 @@ You are {{agent.name}}. | `{{toolPolicy.effective.execute}}` | `allow`\|`deny`\|`ask` | Resolved execute permission | | `{{toolPolicy.effective.delegate}}` | `allow`\|`deny`\|`ask` | Resolved delegate permission | | `{{toolPolicy.effective.network}}` | `allow`\|`deny`\|`ask` | Resolved network permission | -| `{{{delegation.section}}}` | string? | Full `## Delegation` Markdown block with Mermaid diagram and bullets | -| `{{{delegation.mermaid}}}` | string? | Mermaid diagram block only | | `{{#delegation.targets}}` | array | Iterate over eligible delegation targets | | `{{name}}` | string | Target agent name (inside `delegation.targets`) | | `{{description}}` | string? | Target description (inside `delegation.targets`) | diff --git a/docs/prompt-composition.md b/docs/prompt-composition.md index fb3c1441..9a4dd3d2 100644 --- a/docs/prompt-composition.md +++ b/docs/prompt-composition.md @@ -37,7 +37,7 @@ Read this doc **before** making any change that touches: - `prompt` or `prompt_file` values in an agent or category block - `prompt_append` or `prompt_append_file` values in an agent, category, or workflow block - Mustache template tags in any prompt source -- Delegation section rendering (`{{{delegation.section}}}`, `{{#delegation.targets}}`) +- Delegation guidance written with `{{#delegation.targets}}` loops The `weave prompt self-modify` guide enforces this: it lists `docs/prompt-composition.md` as a required pre-read for prompt-related changes. See [CLI — `weave prompt self-modify`](cli.md#weave-prompt-self-modify). diff --git a/docs/testing-strategy.md b/docs/testing-strategy.md index 797a6463..bd81ae40 100644 --- a/docs/testing-strategy.md +++ b/docs/testing-strategy.md @@ -194,7 +194,7 @@ Every finding maps to a step; steps are ordered by value per unit of risk. | 3 | Make the 23 ambient-state tests hermetic | 2 | Suite becomes trustworthy locally | **done** — #185, #186 | | 8 | Thread an injected filesystem and environment through `run()` to every command | 10 | Prerequisite for the CLI bucket; `compose` gained a seam, `prompt` and `runtime` gained fs-backed config discovery | **done** | | 4 | Promote existing end-to-end coverage into `tests/`, starting with `claude-code/integration.test.ts` and the opencode/opencode2 translation tests | 1, 8 | Real scenarios, refactor-proof | open | -| 9 | Populate the buckets: DSL (workflows, `tool_policy`, prompt templates, config merge), CLI (the six uncovered commands), Adapters (opencode, opencode2, copilot) | 10 | The taxonomy stops being a scaffold | open | +| 9 | Populate the buckets | 10 | DSL: `tool_policy`, prompt composition. CLI: every command. Adapters: Copilot alongside Claude Code, on a shared harness. Still open: workflows, config merge, and the OpenCode adapters, which register with a running harness rather than writing files and need a harness of their own | **partly done** | | 6 | Consolidate duplicated factories into `tests/support/` and per-package `__tests__/support/` | 6 | Fixtures named after situations | open | | 10 | Replace ad-hoc inline DSL with named scenario fixtures | 7 | 88 anonymous snippets in `compose.test.ts` alone become readable situations | open | | 11 | Resolve or delete the 2 genuine `it.skip` cases | 9 | No silently-dead tests | open | @@ -215,6 +215,30 @@ beside their module are legitimate. It resolves as a side effect of steps 4 and 9: every promise that moves to `tests/` is one fewer reason for a unit test to reach into an internal module. +## What the buckets found + +Writing scenarios against real behaviour surfaced documentation that described +Weave as it no longer works. Each was corrected in the same pass, with a +scenario pinning the actual behaviour so it cannot drift again: + +- **`{{{delegation.section}}}` does not exist.** `AGENTS.md`, `CONTEXT.md`, + `docs/dsl-reference.md`, `docs/cli.md` and `docs/prompt-composition.md` all + documented a pre-rendered delegation block and an automatic fallback append. + [ADR 0001](adr/0001-prompt-composition-templates.md) removed both + deliberately, and `template-context.test.ts` asserts they are absent from + `ALLOWED_TEMPLATE_PATHS` — a prompt using the placeholder fails composition. + Worst of it was `packages/cli/src/prompts/self-modify.md`, shipped guidance + that `weave prompt self-modify` prints, telling users to do exactly that. +- **Object triggers are invalid.** `AGENTS.md` still showed + `triggers [{ domain "…" trigger "…" }]`; the schema takes quoted strings, + and `docs/dsl-reference.md` says object triggers are invalid outright. +- **`{{domains}}` is not in the template context.** + +The pattern is the same one that produced the `patterns` → `triggers` drift +fixed earlier: `docs/dsl-reference.md` and the specs were amended when the +engine changed, and the onboarding documents were not. A scenario that exercises +the documented behaviour is the cheapest guard against it. + ## See also - [`tests/README.md`](../tests/README.md) — the bucket contract and how to write a scenario diff --git a/packages/cli/src/prompts/self-modify.md b/packages/cli/src/prompts/self-modify.md index 4cfcad5a..0d70b385 100644 --- a/packages/cli/src/prompts/self-modify.md +++ b/packages/cli/src/prompts/self-modify.md @@ -133,10 +133,13 @@ This auto-generates a `shuttle-backend` agent descriptor. If you are editing prompt text or `prompt_file` / `prompt_append` values: -- [ ] Read `docs/prompt-composition.md` for Mustache template context fields, - delegation section rendering, and fallback suppression rules. -- [ ] Use `{{{delegation.section}}}` (triple braces) to embed the delegation - routing block — it contains Markdown. +- [ ] Read `docs/prompt-composition.md` for the Mustache template context + fields and how delegation guidance is composed. +- [ ] Write delegation guidance explicitly, as a Mustache section loop over + `delegation.targets`. There is no pre-rendered `delegation.section` and + no automatic fallback block. +- [ ] The template context is a closed allowlist; a tag naming anything outside + it fails composition rather than rendering empty. - [ ] `prompt` and `prompt_file` are mutually exclusive per agent. - [ ] `prompt_append` and `prompt_append_file` are mutually exclusive per agent. - [ ] Unsupported Mustache features (partials, helpers, lambdas) are rejected diff --git a/tests/adapters/claude-code.scenario.test.ts b/tests/adapters/claude-code.scenario.test.ts index 95801d4d..26032840 100644 --- a/tests/adapters/claude-code.scenario.test.ts +++ b/tests/adapters/claude-code.scenario.test.ts @@ -13,66 +13,22 @@ import { beforeAll, describe, expect, it } from "bun:test"; import { ClaudeCodeAdapter } from "../../packages/adapters/claude-code/src/adapter.js"; -import { whenMaterialized } from "../support/scenario.js"; +import { bundleFile, frontmatter, generateBundle } from "../support/adapter.js"; const PROJECT_ROOT = "/project"; const OUT_DIR = "/project/.weave/plugins/claude-code"; -/** - * Runs the pipeline a user triggers with `weave init --harness claude-code`: - * parse the config, resolve every agent, hand them to the adapter, flush. - * Returns the files the user would find in the generated plugin bundle. - */ -async function generatePluginBundle( - config: string, -): Promise> { - const written: Record = {}; - const adapter = new ClaudeCodeAdapter({ - projectRoot: PROJECT_ROOT, - homeDir: "/home/user", - outDir: OUT_DIR, - exists: async () => true, - readDir: async () => [], - readFile: async () => "", - mkdir: async () => {}, - writeFile: async (path, content) => { - written[path] = content; - }, - }); - - await adapter.init(); - - const plan = await whenMaterialized(config); - for (const entry of plan.agents) { - const result = await adapter.spawnSubagent(entry.descriptor); - expect(result.isOk()).toBe(true); - } - - const flushed = await adapter.flush(); - expect(flushed.isOk()).toBe(true); - - return written; -} - -/** Reads one generated file by its path inside the bundle. */ -function bundleFile( - files: Record, - relativePath: string, -): string { - const full = `${OUT_DIR}/${relativePath}`; - const content = files[full]; - if (content === undefined) { - expect(Object.keys(files).sort()).toContain(full); - throw new Error("unreachable"); - } - return content; -} - -/** The YAML frontmatter block at the top of a generated agent file. */ -function frontmatter(markdown: string): string { - const match = markdown.match(/^---\n([\s\S]*?)\n---/); - expect(match).not.toBeNull(); - return match?.[1] ?? ""; +function build(config: string): Promise> { + return generateBundle( + config, + (hooks) => + new ClaudeCodeAdapter({ + projectRoot: PROJECT_ROOT, + homeDir: "/home/user", + outDir: OUT_DIR, + ...hooks, + }), + ); } describe("a user configures an orchestrator and a specialist for Claude Code", () => { @@ -109,12 +65,12 @@ describe("a user configures an orchestrator and a specialist for Claude Code", ( let files: Record; beforeAll(async () => { - files = await generatePluginBundle(config); + files = await build(config); }); it("produces a plugin Claude Code can load", () => { const manifest = JSON.parse( - bundleFile(files, ".claude-plugin/plugin.json"), + bundleFile(files, `${OUT_DIR}/.claude-plugin/plugin.json`), ); expect(manifest).toMatchObject({ name: expect.any(String) }); @@ -132,23 +88,25 @@ describe("a user configures an orchestrator and a specialist for Claude Code", ( }); it("carries the prompt the user wrote into the agent Claude Code will run", () => { - expect(bundleFile(files, "agents/loom.md")).toContain( + expect(bundleFile(files, `${OUT_DIR}/agents/loom.md`)).toContain( "You are Loom. You route work to specialists.", ); }); it("lets the orchestrator delegate, because its policy allows it", () => { - expect(frontmatter(bundleFile(files, "agents/loom.md"))).toContain("Task"); + expect( + frontmatter(bundleFile(files, `${OUT_DIR}/agents/loom.md`)), + ).toContain("Task"); }); it("withholds delegation from the specialist, because its policy denies it", () => { - expect(frontmatter(bundleFile(files, "agents/shuttle.md"))).not.toContain( - "Task", - ); + expect( + frontmatter(bundleFile(files, `${OUT_DIR}/agents/shuttle.md`)), + ).not.toContain("Task"); }); it("makes the orchestrator the agent Claude Code starts in", () => { - const settings = JSON.parse(bundleFile(files, "settings.json")); + const settings = JSON.parse(bundleFile(files, `${OUT_DIR}/settings.json`)); expect(settings).toMatchObject({ agent: "loom" }); }); @@ -156,7 +114,7 @@ describe("a user configures an orchestrator and a specialist for Claude Code", ( describe("a user adds a category and expects a specialist for it", () => { it("ships a generated agent file for the category alongside the declared ones", async () => { - const files = await generatePluginBundle(` + const files = await build(` agent shuttle { description "Shuttle (Domain Specialist)" prompt "You are Shuttle." @@ -171,7 +129,7 @@ describe("a user adds a category and expects a specialist for it", () => { } `); - const backend = bundleFile(files, "agents/shuttle-backend.md"); + const backend = bundleFile(files, `${OUT_DIR}/agents/shuttle-backend.md`); expect(backend).toContain("You are Shuttle."); expect(backend).toContain( diff --git a/tests/adapters/copilot.scenario.test.ts b/tests/adapters/copilot.scenario.test.ts new file mode 100644 index 00000000..e2128ba4 --- /dev/null +++ b/tests/adapters/copilot.scenario.test.ts @@ -0,0 +1,151 @@ +/** + * Adapter scenarios — GitHub Copilot. + * + * Bucket: Adapters. A `.weave` file goes in, the Copilot plugin bundle a user + * would find on disk comes out. The same promises are checked here as for + * Claude Code, against a harness with different conventions — which is the + * point of the bucket: one config, many harnesses, the user's intent preserved + * in each. + */ + +import { beforeAll, describe, expect, it } from "bun:test"; +import { CopilotAdapter } from "../../packages/adapters/copilot/src/adapter.js"; +import { bundleFile, frontmatter, generateBundle } from "../support/adapter.js"; + +const PROJECT_ROOT = "/project"; +const OUT_DIR = "/project/.weave/plugins/copilot"; +const AGENTS_DIR = `${OUT_DIR}/com.github.copilot/agents`; + +function build(config: string): Promise> { + return generateBundle( + config, + (hooks) => + new CopilotAdapter({ + projectRoot: PROJECT_ROOT, + homeDir: "/home/user", + outDir: OUT_DIR, + ...hooks, + }), + ); +} + +describe("a user configures an orchestrator and a specialist for Copilot", () => { + const config = ` + agent loom { + description "Loom (Main Orchestrator)" + prompt "You are Loom. You route work to specialists." + models ["anthropic/claude-sonnet-4-5"] + mode primary + + tool_policy { + read allow + write allow + execute allow + delegate allow + } + } + + agent shuttle { + description "Shuttle (Domain Specialist)" + prompt "You are Shuttle. You do the work you are given." + models ["anthropic/claude-sonnet-4-5"] + mode subagent + + tool_policy { + read allow + write allow + execute allow + delegate deny + } + } + `; + + let files: Record; + + beforeAll(async () => { + files = await build(config); + }); + + it("produces a plugin manifest Copilot can load", () => { + const manifest = JSON.parse(bundleFile(files, `${OUT_DIR}/plugin.json`)); + + expect(manifest).toMatchObject({ name: expect.any(String) }); + }); + + it("produces one agent file per declared agent, under Copilot's namespace", () => { + const agentFiles = Object.keys(files) + .filter((path) => path.endsWith(".agent.md")) + .sort(); + + expect(agentFiles).toEqual([ + `${AGENTS_DIR}/loom.agent.md`, + `${AGENTS_DIR}/shuttle.agent.md`, + ]); + }); + + it("carries the prompt the user wrote into the agent Copilot will run", () => { + expect(bundleFile(files, `${AGENTS_DIR}/loom.agent.md`)).toContain( + "You are Loom. You route work to specialists.", + ); + }); + + it("gives every generated agent the frontmatter Copilot requires", () => { + for (const path of Object.keys(files).filter((p) => + p.endsWith(".agent.md"), + )) { + expect(frontmatter(bundleFile(files, path))).toContain("name:"); + } + }); +}); + +describe("a user adds a category and expects a Copilot specialist for it", () => { + it("ships a generated agent file carrying the category's own guidance", async () => { + const files = await build(` + agent shuttle { + description "Shuttle (Domain Specialist)" + prompt "You are Shuttle." + models ["anthropic/claude-sonnet-4-5"] + mode all + } + + category backend { + description "Backend APIs, services, persistence" + models ["anthropic/claude-opus-4-1"] + prompt_append "Guard API contracts and backwards compatibility." + } + `); + + const backend = bundleFile(files, `${AGENTS_DIR}/shuttle-backend.agent.md`); + + expect(backend).toContain("You are Shuttle."); + expect(backend).toContain( + "Guard API contracts and backwards compatibility.", + ); + }); +}); + +describe("a user disables an agent", () => { + it("leaves no file behind for it in the Copilot bundle", async () => { + const files = await build(` + agent loom { + prompt "You are Loom." + models ["anthropic/claude-sonnet-4-5"] + mode primary + } + + agent shuttle { + prompt "You are Shuttle." + models ["anthropic/claude-sonnet-4-5"] + mode subagent + } + + disable agents ["shuttle"] + `); + + const agentFiles = Object.keys(files).filter((p) => + p.endsWith(".agent.md"), + ); + + expect(agentFiles).toEqual([`${AGENTS_DIR}/loom.agent.md`]); + }); +}); diff --git a/tests/dsl/prompt-composition.scenario.test.ts b/tests/dsl/prompt-composition.scenario.test.ts new file mode 100644 index 00000000..4bb71b5c --- /dev/null +++ b/tests/dsl/prompt-composition.scenario.test.ts @@ -0,0 +1,203 @@ +/** + * DSL scenarios — prompt composition. + * + * Bucket: DSL. What a user writes in `prompt` / `prompt_append` is what the + * model eventually reads, after Weave renders it as a Mustache template and + * fills in what it knows about the agent. These are the promises behind + * "the prompt I wrote is the prompt that runs". + */ + +import { describe, expect, it } from "bun:test"; +import { parseConfig } from "@weaveio/weave-core"; +import { agent, dedent, whenMaterialized } from "../support/scenario.js"; + +describe("a user writes a plain prompt with no template tags", () => { + it("passes it through unchanged", async () => { + const plan = await whenMaterialized(` + agent plain { + prompt "You are plain. Do exactly this and nothing else." + models ["anthropic/claude-sonnet-4-5"] + mode subagent + } + `); + + expect(agent(plan, "plain").descriptor.composedPrompt).toContain( + "You are plain. Do exactly this and nothing else.", + ); + }); +}); + +describe("a user references the agent's own name in their prompt", () => { + it("fills it in, so the prompt does not have to repeat the config", async () => { + const plan = await whenMaterialized(` + agent weaver { + prompt "You are {{agent.name}}, and you work in {{agent.mode}} mode." + models ["anthropic/claude-sonnet-4-5"] + mode subagent + } + `); + + const composed = agent(plan, "weaver").descriptor.composedPrompt; + + expect(composed).toContain("You are weaver"); + expect(composed).toContain("subagent mode"); + expect(composed).not.toContain("{{agent.name}}"); + }); +}); + +describe("a user appends guidance to an agent's prompt", () => { + it("keeps the original prompt and adds the appended text after it", async () => { + const plan = await whenMaterialized(` + agent shuttle { + prompt "BASE PROMPT." + prompt_append "APPENDED GUIDANCE." + models ["anthropic/claude-sonnet-4-5"] + mode subagent + } + `); + + const composed = agent(plan, "shuttle").descriptor.composedPrompt; + + expect(composed).toContain("BASE PROMPT."); + expect(composed).toContain("APPENDED GUIDANCE."); + expect(composed.indexOf("BASE PROMPT.")).toBeLessThan( + composed.indexOf("APPENDED GUIDANCE."), + ); + }); +}); + +describe("a router agent lists what it can delegate to", () => { + const config = dedent(` + agent loom { + description "Loom (Main Orchestrator)" + prompt """ + You are Loom. + + ## Delegation + {{#delegation.targets}} + - {{name}}: {{description}} + {{#triggers}} + - {{.}} + {{/triggers}} + {{/delegation.targets}} + """ + models ["anthropic/claude-sonnet-4-5"] + mode primary + + tool_policy { + delegate allow + } + } + + agent shuttle { + description "Shuttle (Domain Specialist)" + prompt "You are Shuttle." + models ["anthropic/claude-sonnet-4-5"] + mode subagent + + triggers ["Use for writing and changing code"] + } + `); + + it("names each agent it may delegate to", async () => { + const plan = await whenMaterialized(config); + + expect(agent(plan, "loom").descriptor.composedPrompt).toContain( + "shuttle: Shuttle (Domain Specialist)", + ); + }); + + it("carries each target's triggers, so the model knows when to route there", async () => { + const plan = await whenMaterialized(config); + + expect(agent(plan, "loom").descriptor.composedPrompt).toContain( + "Use for writing and changing code", + ); + }); + + it("leaves the loop empty for an agent that may not delegate", async () => { + const plan = await whenMaterialized(config); + const shuttle = agent(plan, "shuttle").descriptor; + + expect(shuttle.delegationTargets).toEqual([]); + expect(shuttle.composedPrompt).not.toContain("Shuttle (Domain Specialist)"); + }); +}); + +describe("a user writes delegation guidance but has no targets", () => { + it("collapses the loop rather than leaving a stray placeholder", async () => { + const plan = await whenMaterialized(` + agent lonely { + prompt """ + You are lonely. + {{#delegation.targets}} + - {{name}} + {{/delegation.targets}} + """ + models ["anthropic/claude-sonnet-4-5"] + mode primary + + tool_policy { + delegate allow + } + } + `); + + const composed = agent(plan, "lonely").descriptor.composedPrompt; + + expect(composed).toContain("You are lonely."); + expect(composed).not.toContain("{{"); + }); +}); + +describe("a user references a template path Weave does not provide", () => { + it("fails composition instead of rendering an empty string", async () => { + const plan = await whenMaterialized(` + agent typo { + prompt "You are {{agent.nmae}}." + models ["anthropic/claude-sonnet-4-5"] + mode subagent + } + `); + + expect(plan.agents.map((entry) => entry.agentName)).not.toContain("typo"); + expect(plan.errors.length).toBeGreaterThan(0); + }); +}); + +describe("a user declares both an inline prompt and a prompt file", () => { + it("is rejected, rather than one silently winning", () => { + const result = parseConfig( + dedent(` + agent confused { + prompt "Inline." + prompt_file "confused.md" + models ["anthropic/claude-sonnet-4-5"] + mode subagent + } + `), + ); + + expect(result.isErr()).toBe(true); + }); +}); + +describe("a user declares an agent with no prompt at all", () => { + it("is reported as a failure for that agent while the others still resolve", async () => { + const plan = await whenMaterialized(` + agent good { + prompt "You are good." + models ["anthropic/claude-sonnet-4-5"] + mode subagent + } + + agent promptless { + models ["anthropic/claude-sonnet-4-5"] + mode subagent + } + `); + + expect(plan.agents.map((entry) => entry.agentName)).toContain("good"); + expect(plan.errors.length).toBeGreaterThan(0); + }); +}); diff --git a/tests/dsl/tool-policy.scenario.test.ts b/tests/dsl/tool-policy.scenario.test.ts new file mode 100644 index 00000000..530f0920 --- /dev/null +++ b/tests/dsl/tool-policy.scenario.test.ts @@ -0,0 +1,148 @@ +/** + * DSL scenarios — tool policy. + * + * Bucket: DSL. `tool_policy` is how a user says what an agent may do. Weave + * resolves it into the `effectiveToolPolicy` every adapter maps onto its own + * permission model, so these are the promises behind "this agent cannot write" + * no matter which harness runs it. + */ + +import { describe, expect, it } from "bun:test"; +import { agent, whenMaterialized } from "../support/scenario.js"; + +describe("a user restricts what a delegated specialist may do", () => { + const config = ` + agent auditor { + prompt "You review code. You do not change it." + models ["anthropic/claude-sonnet-4-5"] + mode subagent + + tool_policy { + read allow + write deny + execute ask + delegate deny + network deny + } + } + `; + + it("carries each capability through to the adapter exactly as declared", async () => { + const plan = await whenMaterialized(config); + + expect(agent(plan, "auditor").descriptor.effectiveToolPolicy).toEqual({ + read: "allow", + write: "deny", + execute: "ask", + delegate: "deny", + network: "deny", + }); + }); +}); + +describe("a user declares only some capabilities", () => { + it("still resolves every capability, so an adapter never sees a gap", async () => { + const plan = await whenMaterialized(` + agent partial { + prompt "You are partial." + models ["anthropic/claude-sonnet-4-5"] + mode subagent + + tool_policy { + write deny + } + } + `); + + const policy = agent(plan, "partial").descriptor.effectiveToolPolicy; + + expect(policy.write).toBe("deny"); + for (const capability of [ + "read", + "execute", + "delegate", + "network", + ] as const) { + expect(policy[capability]).toBeDefined(); + } + }); +}); + +describe("a user declares no tool policy at all", () => { + it("still gets a fully resolved policy", async () => { + const plan = await whenMaterialized(` + agent bare { + prompt "You are bare." + models ["anthropic/claude-sonnet-4-5"] + mode subagent + } + `); + + const policy = agent(plan, "bare").descriptor.effectiveToolPolicy; + + for (const capability of [ + "read", + "write", + "execute", + "delegate", + "network", + ] as const) { + expect(["allow", "deny", "ask"]).toContain(policy[capability]); + } + }); +}); + +describe("a category tightens the policy its shuttle inherits", () => { + it("applies the category's permissions over the base shuttle's", async () => { + const plan = await whenMaterialized(` + agent shuttle { + prompt "You are Shuttle." + models ["anthropic/claude-sonnet-4-5"] + mode all + + tool_policy { + read allow + write allow + execute allow + delegate allow + } + } + + category docs { + description "Documentation only" + + tool_policy { + write deny + execute deny + } + } + `); + + const base = agent(plan, "shuttle").descriptor.effectiveToolPolicy; + const docs = agent(plan, "shuttle-docs").descriptor.effectiveToolPolicy; + + expect(base.write).toBe("allow"); + expect(docs.write).toBe("deny"); + expect(docs.execute).toBe("deny"); + expect(docs.read).toBe("allow"); + }); +}); + +describe("a user gives an agent a policy the DSL does not define", () => { + it("is rejected rather than silently resolved to something permissive", async () => { + const source = ` + agent broken { + prompt "You are broken." + models ["anthropic/claude-sonnet-4-5"] + mode subagent + + tool_policy { + read maybe + } + } + `; + + const { parseConfig } = await import("@weaveio/weave-core"); + expect(parseConfig(source).isErr()).toBe(true); + }); +}); diff --git a/tests/support/adapter.ts b/tests/support/adapter.ts new file mode 100644 index 00000000..0a679d6d --- /dev/null +++ b/tests/support/adapter.ts @@ -0,0 +1,101 @@ +/** + * Shared harness for the adapter bucket. + * + * Drives a flush-based adapter the way `weave compose` does — parse a + * `.weave` config, resolve every agent, hand them over, flush — and hands back + * the files a user would find on disk. The adapter's own injectable I/O keeps + * everything in memory, so no bundle is created. + * + * Adapters that materialise by writing files (Claude Code, Copilot) share this + * shape. The OpenCode adapters register agents with a running harness instead, + * so they need a different harness of their own. + */ + +import { expect } from "bun:test"; +import type { AgentDescriptor } from "@weaveio/weave-engine"; +import type { ResultAsync } from "neverthrow"; +import { whenMaterialized } from "./scenario.js"; + +/** The subset of adapter surface this harness drives. */ +export interface FlushingAdapter { + init(): Promise; + spawnSubagent(descriptor: AgentDescriptor): ResultAsync; + flush(): ResultAsync; +} + +/** In-memory I/O hooks plus the map they write into. */ +export function memoryIO(): { + written: Record; + hooks: { + exists: (path: string) => Promise; + readDir: (path: string) => Promise; + readFile: (path: string) => Promise; + writeFile: (path: string, content: string) => Promise; + removeFile: (path: string) => Promise; + mkdir: (path: string) => Promise; + }; +} { + const written: Record = {}; + return { + written, + hooks: { + exists: async () => true, + readDir: async () => [], + readFile: async () => "", + writeFile: async (path, content) => { + written[path] = content; + }, + removeFile: async (path) => { + delete written[path]; + }, + mkdir: async () => {}, + }, + }; +} + +/** + * Runs config through an adapter and returns everything it wrote. + * + * `build` receives the in-memory I/O hooks and returns the adapter under test, + * so each bucket file supplies its own constructor without repeating the + * pipeline. + */ +export async function generateBundle( + config: string, + build: (hooks: ReturnType["hooks"]) => A, +): Promise> { + const { written, hooks } = memoryIO(); + const adapter = build(hooks); + + await adapter.init(); + + const plan = await whenMaterialized(config); + for (const entry of plan.agents) { + const spawned = await adapter.spawnSubagent(entry.descriptor); + expect(spawned.isOk()).toBe(true); + } + const flushed = await adapter.flush(); + expect(flushed.isOk()).toBe(true); + + return written; +} + +/** Reads one generated file, failing with the full listing when it is absent. */ +export function bundleFile( + files: Record, + path: string, +): string { + const content = files[path]; + if (content === undefined) { + expect(Object.keys(files).sort()).toContain(path); + throw new Error("unreachable"); + } + return content; +} + +/** The YAML frontmatter block at the top of a generated agent file. */ +export function frontmatter(markdown: string): string { + const match = markdown.match(/^---\n([\s\S]*?)\n---/); + expect(match).not.toBeNull(); + return match?.[1] ?? ""; +}