diff --git a/.agents/plan/local-agent-profiles-and-cli-plan.md b/.agents/plan/local-agent-profiles-and-cli-plan.md deleted file mode 100644 index 27c82142b..000000000 --- a/.agents/plan/local-agent-profiles-and-cli-plan.md +++ /dev/null @@ -1,96 +0,0 @@ -# Subagent profiles and DevSpace agent CLI plan - -## Decision - -Subagent profiles describe roles over built-in coding-agent providers. -DevSpace owns provider invocation and lifecycle. Custom CLI-backed agents, -provider action objects, and model-visible backend details are out of scope for -v1. - -The model-facing workflow stays small: - -```bash -devspace agents ls -devspace agents run "" -devspace agents show -``` - -Profile discovery happens through the compact catalog returned by -`open_workspace`. `devspace agents ls` lists existing subagent sessions for the -current workspace; it does not list profile definitions. - -## Profile schema - -Profiles are discovered from: - -- `~/.devspace/agents/*.md` -- project `.devspace/agents/*.md` - -Supported frontmatter fields: - -```yaml -schema: devspace-agent/v1 -name: reviewer -description: Read-only reviewer for bugs, security risks, and missing tests. -provider: codex -model: gpt-5.4 -disabled: false -``` - -Supported providers: - -- `codex` -- `claude` -- `opencode` -- `pi` -- `cursor` -- `copilot` - -Removed from v1 profile schema: - -- `backend` -- `command` -- `mode` -- `permissions` -- `actions` - -## Provider mapping - -DevSpace maps provider ids to native integrations: - -- `codex`: Codex SDK -- `claude`: Claude Code SDK -- `opencode`: OpenCode SDK -- `pi`: Pi RPC mode -- `cursor`: ACP -- `copilot`: ACP - -The adapter registry is the internal seam future MCP tools can reuse if we move -from skill plus CLI guidance to first-class MCP agent tools. - -## Model exposure - -`open_workspace` exposes only compact profile metadata: - -```json -{ - "name": "reviewer", - "description": "Read-only reviewer for bugs, security risks, and missing tests.", - "provider": "codex", - "model": "gpt-5.4" -} -``` - -The profile body, provider protocol, raw provider transcript, and adapter -details stay outside the default model context. - -Shell calls launched through DevSpace receive `DEVSPACE_WORKSPACE_ID` and -`DEVSPACE_WORKSPACE_ROOT`, so `devspace agents ls` can scope itself without the -model passing workspace flags. - -## Non-goals - -- Custom or arbitrary subagent commands. -- Provider-specific action DSLs. -- Exposing raw provider transcripts by default. -- Tracking changed files or tests from provider output. diff --git a/.agents/skills/replay-qa/SKILL.md b/.agents/skills/replay-qa/SKILL.md deleted file mode 100644 index 647a26d65..000000000 --- a/.agents/skills/replay-qa/SKILL.md +++ /dev/null @@ -1,93 +0,0 @@ ---- -name: replay-qa -description: Replay scripted MCP tool calls against an isolated DevSpace server and inspect the rendered cards in a real MCP Apps host with agent-browser. Use to verify a change, reproduce an issue, review a PR's UI or tool behavior, or QA any checkout without manual testing. ---- - -# Replay QA - -`pnpm qa` replays scenario tool calls against a fresh DevSpace server, renders every card in a local MCP Apps host, and captures evidence with agent-browser. - -Each run is isolated: its own `HOME`, config, SQLite state, worktree root, allowed root, and Git fixture under `.devspace-dev/qa/runs///`. Ports are allocated dynamically, so runs never replace an existing process. - -## Run - -```bash -pnpm qa --list # scenarios and descriptions -pnpm qa # every scenario -pnpm qa codex-edit-review # one scenario -pnpm qa --theme dark codex-edit-review -pnpm qa --bare-host codex-edit-review # host sends a theme but no style variables -pnpm qa --checkout ../other-worktree # QA another checkout with this harness -pnpm qa --no-build ... # skip `pnpm build:app` in the target checkout -``` - -The exit code is non-zero when a step fails its expectations, a card does not initialize or render, or the page reports errors. - -Each run directory contains: - -- `report.md`: pass/fail per step, card state and height, failures, and screenshot paths. Read this first. -- `transcript.json`: the tool list, every request and response, UI resources, and calls the cards made back to the server. -- `server.log`: the DevSpace server's JSON log. -- `artifacts/`: a full-page screenshot, one screenshot per card, an accessibility snapshot, the browser console, and `errors.json`. - -Look at the screenshots before reporting UI behavior. A passing report means that cards rendered, not that they look right. - -## Interact with cards - -```bash -pnpm qa --serve --no-browser codex-edit-review # prints the host URL and keeps running -export AGENT_BROWSER_SESSION=devspace-qa -agent-browser open "" -agent-browser wait --fn "window.__devspaceQa?.settled === true" -agent-browser snapshot -i # card iframes appear inline with their buttons -agent-browser click @e12 # e.g. expand a file in the show_changes card -agent-browser screenshot "#step-3" /tmp/after.png -agent-browser close -``` - -Stop the serve process when finished. Card-initiated tool calls go through the host's same-origin `/api/call`, and are appended to `transcript.json` and shown under the card. - -## Write a scenario - -Add `scripts/qa/scenarios/.json`: - -```json -{ - "description": "What this proves.", - "config": { "tools": { "mode": "claude" } }, - "host": { "clientName": "ChatGPT", "userAgent": "openai-mcp/1.0.0" }, - "fixture": { - "files": { "README.md": "committed\n" }, - "dirty": { "README.md": "uncommitted\n" } - }, - "steps": [ - { "tool": "open_workspace", "arguments": { "path": "{{fixture}}" } }, - { - "tool": "exec_command", - "arguments": { "workspace_id": "{{workspace_id}}", "cmd": "git status --short" }, - "expect": { "text": ["README.md"] } - } - ] -} -``` - -- `config` is deep-merged into the generated `config.jsonc`, and `env` adds server environment variables. -- `host` sets the OAuth `client_name` and the HTTP `User-Agent` the simulated host presents. -- `{{workspace_id}}` is the most recent workspace returned by a step. -- Make each fixture change through tool calls whenever possible, so the scenario exercises the real path. - -## Comparing base and PR - -Create a worktree for each revision, then run the same scenario with `--checkout` pointing at each one. Report `reproduces on base`, `fixed on PR`, or `not reproduced`. Do not infer this from the diff. - -## Limits - -The local host follows the MCP Apps protocol: a separate sandbox origin, CSP taken from resource metadata, host context, and server tools. It is still not ChatGPT or Claude. Use the real host when a claim depends on host-specific behavior such as `window.openai` globals, connector caching, OAuth reconnects, or display modes the local host does not implement. - -## Attach evidence to a pull request - -```bash -scripts/qa/publish-evidence.sh /artifacts/page.png /artifacts/step-3-show_changes.png -``` - -This pushes the images to the orphan branch `qa-evidence/pr-` and prints Markdown image links. Paste them into the PR body or a comment with the scenario names and the pass/fail lines from `report.md`. diff --git a/.agents/skills/setup-qa/SKILL.md b/.agents/skills/setup-qa/SKILL.md deleted file mode 100644 index cafec386e..000000000 --- a/.agents/skills/setup-qa/SKILL.md +++ /dev/null @@ -1,50 +0,0 @@ ---- -name: setup-qa -description: Prepare the current DevSpace checkout or worktree for isolated local manual QA. Use when the user asks to set up QA, test a worktree locally, try an experiment in ChatGPT, or reset the local QA environment. ---- - -# Set up DevSpace manual QA - -Use the current checkout or worktree. DevSpace's repo-local QA state lives in `.devspace-dev/` and should be used instead of the user's normal DevSpace state. - -## Prepare the checkout - -If this checkout has not been initialized for QA yet: - -```bash -pnpm dev:seed -``` - -`dev:seed` forks the user's current DevSpace config, auth, local skills/agents, and SQLite state into this checkout's `.devspace-dev/` directory. - -For ChatGPT app, widget, CSS, or icon changes, build the UI assets before testing: - -```bash -pnpm build:app -``` - -The source server serves UI assets from `dist/ui`, not directly from `src/ui`. - -## Run QA - -Start the source server from this checkout with: - -```bash -pnpm dev -``` - -It uses `.devspace-dev/config` and runs the source server under `tsx watch`, so server-side TypeScript changes reload automatically. Frontend changes still need another `pnpm build:app`. - -The seeded QA state usually lets ChatGPT keep using the existing connector and tunnel while switching from the installed DevSpace server to this checkout's server. - -For UI work, trigger a fresh tool result after rebuilding so ChatGPT loads the new hashed Vite assets. - -## Reset the QA snapshot - -Only when a fresh fork of the normal DevSpace state is needed: - -```bash -pnpm dev:reset -``` - -Run this with `pnpm dev` stopped, then start `pnpm dev` again so the replaced snapshot is loaded. If the user's normal installation uses a custom `DEVSPACE_CONFIG_DIR`, preserve it while running `dev:seed` or `dev:reset`. diff --git a/.gitcms/AGENTS.md b/.gitcms/AGENTS.md deleted file mode 100644 index 46c1eb2a9..000000000 --- a/.gitcms/AGENTS.md +++ /dev/null @@ -1,9 +0,0 @@ -# GitCMS configuration - -GitCMS (https://gitcms.dev) reads this folder to edit the site's content. Prefer changing it in the GitCMS app; when you edit these files directly: - -- A collection exists because `sites//collections/.jsonc` exists, and site data because `sites//singletons/.jsonc` exists. To add, rename, or remove one, add, rename, or delete its file. -- Names are lowercase letters, numbers, `-`, and `_`. The file name is the name; don't put a `name` inside the file. -- `collections` and `singletons` in `config.jsonc` only set the order in the sidebar. Items they don't list come after, alphabetically. -- Don't change `version` by hand. To upgrade, run `npx create-gitcms migrate --write`. -- After editing, run `npx create-gitcms check` and fix anything it reports. diff --git a/.gitcms/README.md b/.gitcms/README.md index e0c13bbe3..54f95221a 100644 --- a/.gitcms/README.md +++ b/.gitcms/README.md @@ -6,4 +6,4 @@ This folder is managed by [GitCMS](https://gitcms.dev). - Per-site settings live in `sites//config.jsonc`. - Each collection is one file, `sites//collections/.jsonc`. - Each piece of site data is one file, `sites//singletons/.jsonc`. -- Change these with the GitCMS app or `npx create-gitcms`; agents, see `AGENTS.md`. +- Change these with the GitCMS app or `npx create-gitcms`. diff --git a/AGENTS.md b/AGENTS.md index fa9340585..835e7faa6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,118 +1,3 @@ # DevSpace -DevSpace is a local development execution layer for MCP hosts such as ChatGPT and Claude. It gives a remote host workspace-scoped tools for reading, editing, searching, running commands, managing Git worktrees, reviewing changes, and coordinating bounded subagents on the user's machine. - -Pi's SDK currently provides mature local coding primitives. DevSpace wraps those primitives in a Streamable HTTP MCP server and adds the product-specific boundaries around them: approved roots, workspace state, instructions, process sessions, worktrees, artifacts, review checkpoints, widgets, and subagent execution. - -DevSpace owns tooling mechanics. The model receives only meaningful and actionable choices. The user sees outcomes. Tool defination should not leak internal implementation or it shoudn't be giving unwanted options to model to choose from if tooling can handle this. - -## Product model - -These ideas should stay true as the project evolves: - -1. **The host is the orchestrator.** DevSpace exposes clear capabilities and execution state. It should not hide the workflow inside an opaque, uninspectable agent loop. -2. **Everything happens in a workspace.** A workspace represents one local project directory or worktree plus the instructions and state accumulated while operating in it. -3. **Local authority stays explicit.** DevSpace runs with access to the user's machine. Roots, paths, commands, processes, credentials, and destructive operations must be treated as product boundaries. -4. **Subagents are bounded workers.** A subagent should have an explicit task, profile, working context, lifecycle, and result that the host can inspect and coordinate. -5. **Adapters stay at the edges.** Pi, MCP hosts, and model providers each have their own terminology and capabilities. Provider-specific behavior should not become the core domain model. -6. **Prefer composable primitives.** Build a small set of reliable operations that can be combined into larger workflows instead of baking every workflow into the server. - -## Glossary - -- **Host** — the MCP client presenting the agent experience and coordinating work. -- **Server** — the local DevSpace MCP server. -- **Workspace** — one opened directory or worktree and its accumulated instruction context. -- **`workspace_id`** — the opaque handle returned by `open_workspace` and reused for calls in that workspace. -- **Allowed root** — a configured filesystem boundary within which a workspace may be opened. It is not itself necessarily a workspace. -- **Checkout mode** — operating on an existing checkout supplied by the user. -- **Worktree mode** — operating in an isolated Git worktree. -- **Tool surface** — the tools exposed by a configured mode, such as minimal, full, or Codex-compatible. -- **Process session** — a long-running command tracked for later input, output, or termination. -- **Instruction file** — an `AGENTS.md` or `CLAUDE.md` discovered while navigating a workspace. -- **Subagent** — a bounded model invocation delegated and coordinated by the host. -- **Agent profile** — the model, provider, tools, and instructions used for a subagent. -- **Artifact** — an output surfaced for the host or user to inspect. -- **Review checkpoint** — stored state representing a coherent set of changes. -- **Widget** — host-rendered UI/Cards attached to an MCP response. - -Use these terms precisely. In particular, do not use workspace, allowed root, checkout, and worktree interchangeably. - -## Security boundaries - -Filesystem tools enforce approved-root containment. Shell commands run with the local user's authority and are not a general sandbox. Never imply that shell execution is contained merely because file tools are contained. - -Resolve and validate paths before destructive actions. Do not broaden an allowed root, delete application state, expose a credential, or replace an existing process as a convenient fix. - -Keep tunnel ownership and credentials with the user. DevSpace may operate through a user-controlled tunnel, but it does not own tunnel lifecycle or configuration. - -## Diagnose the correct layer - -A failure may belong to the host, MCP transport, DevSpace, a Pi adapter, a provider, a model, a tool implementation, or the target project. Preserve the original error and identify the failing boundary before changing code. - -An adapter exception is not evidence that a model failed. A successful command is not evidence that a GUI opened, a host refreshed, or a user-visible workflow succeeded. - -Do not expand DevSpace's responsibility while fixing a local symptom. Host UI, provider model naming, tunnel management, and duplicated review experiences require an explicit product decision. - -## Verify the real path - -Determine how the user will consume the change and verify that path. Behavior may differ between: - -- the source checkout and the packaged `npm`/`npx` installation; -- a direct terminal client and a real MCP host; -- a fresh process and a server or host that needs restarting; -- checkout mode and worktree mode; -- Linux, macOS, and Windows Bash environments; -- minimal, full, and Codex-compatible tool surfaces; -- widgets enabled, disabled, or limited to change review. - -State clearly when only a narrower proxy was verified. For model-facing schemas, inspect what the host receives. For UI and artifacts, inspect the rendered result rather than inferring success from the producing command. - -## Trace affected contracts - -When changing a cross-cutting concept, check every surface it actually reaches: - -- MCP schema, handler, description, and response; -- workspace lifecycle and instruction loading; -- allowed-root and path-containment behavior; -- checkout and worktree modes; -- process and subagent lifecycle; -- tool-surface filtering; -- widgets, artifacts, and review checkpoints; -- persistence and migrations; -- packaged entry points, documentation, and examples. - -This is a map, not a requirement to touch every surface on every change. Avoid both incomplete contracts and speculative edits. - -## Pull requests - -Only create or update a PR when explicitly asked, and read `CONTRIBUTING.md` first. Keep a PR focused on one coherent concern and use a conventional title such as `fix:`, `feat:`, `docs:`, `refactor:`, or `chore:`. - -Write the body as a few natural paragraphs explaining the problem and solution. Include verification, risk, or migration context only when it helps the reviewer. Avoid generated boilerplate, commit inventories, file-by-file narration, generic checklists, and mandatory `Testing` sections. - -For UI changes, include before/after images and a short interaction video when behavior changes. Inspect the final diff before filing. When available, use the `file-pr` workflow to file the PR and `babysit-pr` to monitor CI and reviews. - -## Where code lives - -- `src/server.ts` — MCP server setup, tool registration, and response wiring. -- `src/workspaces.ts` — workspace lifecycle, instructions, skills, and profiles. -- `src/roots.ts` — allowed roots and path containment. -- `src/process-sessions.ts` — long-running process lifecycle. -- `src/git.ts` and `src/git-worktrees.ts` — Git and worktree operations. -- `src/local-agent-*.ts` — subagent configuration, providers, and execution. -- `src/artifact-*.ts` and `src/incoming-artifacts.ts` — artifact handling. -- `src/review-checkpoints.ts` — persisted change-review checkpoints. -- `src/ui/` — MCP widgets. -- `src/db/` — persisted local state and migrations. -- `test/` — behavior and regression tests. - -Start at the boundary named by the problem and follow the data. Keep policy in DevSpace, provider translation in adapters, and important behavior in schemas, types, checks, or explicit tool results rather than hidden prompt conventions. - -## Project taste - -- Prefer explicit lifecycle and state over hidden autonomy. -- Make tasks, inputs, outputs, failures, and ownership inspectable. -- Keep subagent execution composable and independently testable. -- Preserve host and provider data unless DevSpace has a concrete reason to normalize it. -- Add compatibility behavior only for an identified consumer with a real upgrade path. -- Reuse glossary terms in schemas, types, documentation, and errors. -- Keep the execution layer small, reliable, and unsurprising. +Verify changes with `pnpm typecheck`, `pnpm lint`, and `pnpm test` (or `npx tsx --test `). Run `pnpm build:app` after UI changes. diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index d8957db4d..fbc3d17c6 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -120,9 +120,7 @@ page errors, so install that command for browser QA. No seeded state or real host is needed. Read the generated report and inspect screenshots before claiming that the UI works; use a real host for host-specific behavior. -See [.agents/skills/replay-qa/SKILL.md](.agents/skills/replay-qa/SKILL.md) for -scenarios, interactive `--serve` mode, and attaching PR evidence. Stop the serve -process when finished. +Run `pnpm qa --help` for options (`--serve`, `--theme`, `--checkout`, `--no-build`) and `scripts/qa/publish-evidence.sh` for attaching PR evidence. Stop the serve process when finished. ## Build the website diff --git a/oxlint.config.ts b/oxlint.config.ts index b2ea45b62..0afdc083a 100644 --- a/oxlint.config.ts +++ b/oxlint.config.ts @@ -28,6 +28,7 @@ export default defineConfig({ { name: "anti-slop", specifier: "./tools/oxlint/anti-slop/index.ts" }, ], rules: { + "no-duplicate-imports": ["error", { allowSeparateTypeImports: true }], "oxc/no-accumulating-spread": "error", "anti-slop/no-array-filter-map": "error", "anti-slop/no-reduce-accumulator-copy": "error", diff --git a/scripts/qa/run.ts b/scripts/qa/run.ts index 71c82601e..16c2e71b0 100644 --- a/scripts/qa/run.ts +++ b/scripts/qa/run.ts @@ -42,12 +42,33 @@ const { values: options, positionals } = parseArgs({ theme: { type: "string", default: "light" }, "bare-host": { type: "boolean", default: false }, list: { type: "boolean", default: false }, + help: { type: "boolean", short: "h", default: false }, }, }); +const USAGE = `Usage: pnpm qa [options] [scenario...] + +Replay scripted MCP tool calls against an isolated DevSpace server and render cards in a local MCP Apps host. + +Options: + --list List available scenarios and exit + --theme Host theme (default: light) + --bare-host Send theme without host CSS style variables + --checkout QA another DevSpace checkout or worktree + --no-build Skip \`pnpm build:app\` in the target checkout + --no-browser Skip agent-browser rendering and screenshots + --serve Keep one scenario's server and host running for interactive inspection + -h, --help Show this help message`; + const cleanups: Array<() => Promise> = []; async function main(): Promise { + if (options.help) { + console.log(USAGE); + + return; + } + if (options.list) { for (const name of await listScenarioNames()) { const scenario = await loadScenario(name); diff --git a/src/db/migrations.ts b/src/db/migrations.ts index b00e2590b..5e9e1236d 100644 --- a/src/db/migrations.ts +++ b/src/db/migrations.ts @@ -114,6 +114,10 @@ const migrations: Migration[] = [ }, ]; +export function listMigrationManifest(): ReadonlyArray<{ version: number; name: string }> { + return migrations.map(({ version, name }) => ({ version, name })); +} + export function migrateDatabase(sqlite: SqliteDatabase): void { transaction(sqlite, () => { sqlite.exec(` diff --git a/src/git-worktrees.test.ts b/src/git-worktrees.test.ts index 02e4e4960..a44b386a6 100644 --- a/src/git-worktrees.test.ts +++ b/src/git-worktrees.test.ts @@ -2,8 +2,7 @@ import { isErrorValue } from "./json-value.js"; import assert from "node:assert/strict"; import { execFile, execFileSync } from "node:child_process"; import { mkdir, mkdtemp, rm, stat, symlink, writeFile } from "node:fs/promises"; -import { platform } from "node:os"; -import { tmpdir } from "node:os"; +import { platform, tmpdir } from "node:os"; import { join } from "node:path"; import test, { type TestContext } from "node:test"; import { promisify } from "node:util"; diff --git a/src/repo-contracts.test.ts b/src/repo-contracts.test.ts new file mode 100644 index 000000000..6bc906ea9 --- /dev/null +++ b/src/repo-contracts.test.ts @@ -0,0 +1,139 @@ +import assert from "node:assert/strict"; +import { existsSync, readdirSync, readFileSync } from "node:fs"; +import { basename, join, resolve } from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; +import { parse as parseJsonc, type ParseError } from "jsonc-parser"; +import { listMigrationManifest } from "./db/migrations.js"; +import { isJsonString, isObjectValue } from "./json-value.js"; +import { resolveSubagentsConfig, subagentsConfigSchema } from "./local-agent-config.js"; +import { loadLocalAgentProfiles } from "./local-agent-profiles.js"; + +const REPO_ROOT = resolve(fileURLToPath(new URL("..", import.meta.url))); + +test("database migrations are strictly sequential 1..N with unique non-empty names", () => { + const manifest = listMigrationManifest(); + assert.ok(manifest.length > 0, "expected at least one migration"); + + const seenNames = new Set(); + + for (let index = 0; index < manifest.length; index += 1) { + const entry = manifest[index]!; + assert.equal(entry.version, index + 1, `migration ${entry.name} must have version ${index + 1}`); + assert.ok(entry.name.trim().length > 0, `migration ${entry.version} must have a non-empty name`); + assert.ok(!seenNames.has(entry.name), `duplicate migration name: ${entry.name}`); + seenNames.add(entry.name); + } +}); + +test("GitCMS collection and singleton files use valid slug filenames and omit inner name fields", () => { + const sitesDir = join(REPO_ROOT, ".gitcms", "sites"); + + if (!existsSync(sitesDir)) return; + + const slugPattern = /^[a-z0-9_-]+$/; + + for (const siteEntry of readdirSync(sitesDir, { withFileTypes: true })) { + if (!siteEntry.isDirectory()) continue; + + for (const group of ["collections", "singletons"] as const) { + const groupDir = join(sitesDir, siteEntry.name, group); + + if (!existsSync(groupDir)) continue; + + for (const fileEntry of readdirSync(groupDir, { withFileTypes: true })) { + if (!fileEntry.isFile() || !fileEntry.name.endsWith(".jsonc")) continue; + + const stem = basename(fileEntry.name, ".jsonc"); + assert.match(stem, slugPattern, `${group}/${fileEntry.name} must match ${slugPattern}`); + + const raw = readFileSync(join(groupDir, fileEntry.name), "utf8"); + const errors: ParseError[] = []; + const parsed = parseJsonc(raw, errors); + + assert.equal(errors.length, 0, `${group}/${fileEntry.name} must be valid JSONC`); + assert.ok(isObjectValue(parsed), `${group}/${fileEntry.name} must parse to a JSON object`); + assert.equal("name" in parsed, false, `${group}/${fileEntry.name} must not define an inner "name" property`); + } + } + } +}); + +test("QA replay scenarios in scripts/qa/scenarios are valid and non-empty", () => { + const scenariosDir = join(REPO_ROOT, "scripts", "qa", "scenarios"); + const files = readdirSync(scenariosDir).filter((file) => file.endsWith(".json")).sort(); + assert.ok(files.length > 0, "expected at least one QA scenario"); + + for (const file of files) { + const parsed = JSON.parse(readFileSync(join(scenariosDir, file), "utf8")); + assert.ok(isObjectValue(parsed), `${file} must be a JSON object`); + assert.ok(isJsonString(parsed.description), `${file} must have a string description`); + assert.ok(isObjectValue(parsed.fixture) && isObjectValue(parsed.fixture.files), `${file} must define fixture.files`); + assert.ok(Array.isArray(parsed.steps) && parsed.steps.length > 0, `${file} must define at least one step`); + + for (const step of parsed.steps) { + assert.ok(isObjectValue(step), `${file} step must be an object`); + assert.ok(isJsonString(step.tool), `${file} step must name a tool`); + assert.ok(isObjectValue(step.arguments), `${file} step must provide arguments object`); + } + } +}); + +test("example agent profiles in examples/agents parse cleanly with the profile loader", async () => { + const examplesDir = join(REPO_ROOT, "examples", "agents"); + const expectedFiles = readdirSync(examplesDir).filter((file) => file.endsWith(".md")); + assert.ok(expectedFiles.length > 0, "expected at least one example profile"); + + const profiles = await loadLocalAgentProfiles( + { + devspaceAgentsDir: examplesDir, + subagents: resolveSubagentsConfig(subagentsConfigSchema.parse({ enabled: true, providers: [] })), + }, + REPO_ROOT, + { includeDisabled: true }, + ); + + assert.equal(profiles.length, expectedFiles.length, "every examples/agents/*.md file must load as a valid profile"); +}); + +test("bundled subagents skill documents only real CLI subcommands", () => { + const skillSource = readFileSync(join(REPO_ROOT, "skills", "subagents", "SKILL.md"), "utf8"); + const cliSource = readFileSync(join(REPO_ROOT, "src", "cli.ts"), "utf8"); + const matches = skillSource.matchAll(/devspace agents ([a-z][a-z-]*)/g); + const documentedSubcommands = new Set(); + + for (const match of matches) { + const subcommand = match[1]; + + if (subcommand) documentedSubcommands.add(subcommand); + } + + assert.ok(documentedSubcommands.size > 0, "expected subcommands in skills/subagents/SKILL.md"); + + for (const subcommand of documentedSubcommands) { + assert.ok( + cliSource.includes(`"${subcommand}"`), + `skills/subagents/SKILL.md references \`devspace agents ${subcommand}\`, which was not found in src/cli.ts`, + ); + } +}); + +test("MCP tool surface descriptions do not imply shell containment or leak internal engines", () => { + const toolSources = [ + readFileSync(join(REPO_ROOT, "src", "server.ts"), "utf8"), + readFileSync(join(REPO_ROOT, "src", "pi-tools.ts"), "utf8"), + ]; + + for (const source of toolSources) { + assert.doesNotMatch( + source, + /description:\s*["'`][^"'`]*(shell|command)[^"'`]*(sandboxed|contained to allowed roots)/i, + "shell tool descriptions must never imply shell execution is contained to allowed roots", + ); + assert.doesNotMatch( + source, + /description:\s*["'`][^"'`]*(pi-coding-agent|drizzle|koffi|quickjs)/i, + "model-facing tool descriptions must not leak internal implementation libraries", + ); + } +});