Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .codesight/CODESIGHT.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

---

Expand Down Expand Up @@ -1024,7 +1024,7 @@
# Test Coverage

> **0%** of routes and models are covered by tests
> 201 test files found
> 205 test files found

---

Expand Down
2 changes: 1 addition & 1 deletion .codesight/coverage.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Test Coverage

> **0%** of routes and models are covered by tests
> 201 test files found
> 205 test files found
28 changes: 15 additions & 13 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
Expand Down Expand Up @@ -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**:

Expand All @@ -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.

Expand Down
2 changes: 1 addition & 1 deletion CONTEXT.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
2 changes: 1 addition & 1 deletion docs/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 0 additions & 2 deletions docs/dsl-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`) |
Expand Down
2 changes: 1 addition & 1 deletion docs/prompt-composition.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).

Expand Down
26 changes: 25 additions & 1 deletion docs/testing-strategy.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand All @@ -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
Expand Down
11 changes: 7 additions & 4 deletions packages/cli/src/prompts/self-modify.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
90 changes: 24 additions & 66 deletions tests/adapters/claude-code.scenario.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Record<string, string>> {
const written: Record<string, string> = {};
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<string, string>,
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<Record<string, string>> {
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", () => {
Expand Down Expand Up @@ -109,12 +65,12 @@ describe("a user configures an orchestrator and a specialist for Claude Code", (
let files: Record<string, string>;

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) });
Expand All @@ -132,31 +88,33 @@ 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" });
});
});

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."
Expand All @@ -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(
Expand Down
Loading
Loading