diff --git a/docs/harnesses.md b/docs/harnesses.md index bd484d91..32464916 100644 --- a/docs/harnesses.md +++ b/docs/harnesses.md @@ -161,11 +161,22 @@ default model with `opencode api get /api/model/default`. turn runs is stored in the server's durable queue (up to 8 per chat) and sent in order when the turn ends, also after a server restart. -**Skills in stages:** the stage service is shared and discovers skills per -location, not per session, so a stage cannot be given private skills through -OpenCode's skill discovery; its own `skill` tool stays denied by the stage's -deny-all permission rules, which keeps ambient skills unusable. A stage's -`skills` block is attached to each new session before its prompt as one +**Skills in stages:** OpenCode (2.4.1) discovers the operator's Claude Code +skills itself: `~/.claude/skills//` and the synced +`~/.claude/skills/synced///` folders (unless the service runs +with `OPENCODE_DISABLE_CLAUDE_CODE` or `OPENCODE_DISABLE_CLAUDE_CODE_SKILLS`). +A tool-using stage session allows OpenCode's `skill` tool for exactly those +skill names (one `skill` allow rule per name, discovered afresh for each +visit), plus `external_directory` reads of their folders (link and resolved +path) when the stage declares `read`/`glob`/`grep`. Every other skill OpenCode +finds (its built-in ones, `~/.agents/skills`, `~/.config/opencode/skills`, +project folders in the run directory) stays denied by the deny-all rules. A +live V2 session (free `opencode/big-pickle`) with these rules loaded +`omarchy` through the `skill` tool; the same session without them had no skill +tool, and asking for the built-in `opencode` skill was refused. Claude Code's +bundled skills and Claude plugin skills are not available (OpenCode does not +discover them), and a text-only stage (empty `tools` block) has no skill tool. +Skills are not inlined into instructions. A stage's `skills` block is attached to each new session before its prompt as one `PUT /api/experimental/session//instructions/entries/pipelines-skill-` entry carrying the skill's `SKILL.md` and the read-only directory of its bundled files (readable when the stage declares `read`/`glob`/`grep`). This needs @@ -183,11 +194,20 @@ refused unless that profile exists on the server. **Launched as:** `pi --mode rpc --provider P --model M --session-dir --no-approve --no-extensions --no-skills --no-context-files --no-prompt-templates --no-themes --extension policy.js`, plus one `--skill -` per skill in the stage's `skills` block (Pi documents that explicit -`--skill` paths still load under `--no-skills`; a skills stage must declare -`read`, which the policy also allows inside the visit's skills directory). The -policy extension enforces the stage's tool and edit permissions. `reasoning_effort` maps to Pi's -thinking level and is verified before the task is sent. +` per skill in the stage's `skills` block and then one per folder-based +Claude Code skill of the operator (personal, synced and enabled-plugin skills, +found as for Claude stages). Pi documents that explicit `--skill` paths still +load under `--no-skills`, which keeps Pi's own skill discovery (`~/.pi`, +`~/.agents/skills`, project `.pi`/`.agents` folders in the run directory) out; +on a name clash Pi keeps the first, so a `skills` block entry wins. Pi loads +`SKILL.md` folders natively (Agent Skills format; Pi 1.6.0 listed all 24 of the +operator's skills through `get_commands`). The model reads a skill's +`SKILL.md` by path, so a stage needs `read` to use one (a `skills` block +requires it); the policy allows reads inside the visit's skills directory and +each operator skill folder (by resolved path). Claude Code's bundled skills +have no folder and are not available to Pi. The policy extension enforces the +stage's tool and edit permissions. `reasoning_effort` maps to Pi's thinking +level and is verified before the task is sent. **Install and sign in:** @@ -254,21 +274,36 @@ directory that chooses its own account keeps it). - **Not supported; the stage or run is refused, never widened:** a `permissions` block, a run launched with `--write-path`, `delivery=true` (landing stays on OpenCode), and `reasoning_effort` `none` or `minimal`. -- **Isolation.** User, project and local Claude Code settings, hooks, MCP - servers, plugins and slash commands are not loaded. A `CLAUDE.md` in the run - directory is still read by the CLI. -- **Skills.** With a `skills` block the visit's private copy is loaded as a - session-only plugin (`--plugin-dir`, skills named `pipelines-stage:`), - `Skill` is added to `--tools` with one `Skill(pipelines-stage:)` allow - rule per skill, and `--disable-slash-commands` (which also disables plugin - skills) is replaced by `--settings - '{"disableBundledSkills":true,"enabledPlugins":{"cc-plugin-plugin-authoring@builtin":false}}'`. - Claude Code 2.1.332 then lists only the configured skills plus the - user-only `design` and `doctor` commands, which the model cannot invoke (a - live haiku session saw only `pipelines-stage:`; `dataviz` and - `plugin-authoring` were "Unknown skill"). If a Skill call nevertheless loads - any other skill, the visit fails; a refused call is harmless. Without a - `skills` block the arguments are unchanged. +- **Isolation.** User, project and local Claude Code settings are not loaded + (`--setting-sources ""`): no hooks, permission rules, env, MCP servers or + plugins from them. A `CLAUDE.md` in the run directory is still read by the + CLI. +- **Skills.** Every stage gets the `Skill` tool (added to `--tools` and + approved with a bare `Skill` rule) and can load any skill it sees: + - Claude Code's bundled skills (`code-review`, `dataviz`, `simplify`, + `claude-api`, ...), which ship with the CLI. + - The operator's own skills, found afresh for each visit (no import step) in + the CLI's configuration directory (`CLAUDE_CONFIG_DIR`, else + `~/.claude`): `skills//` (symlinked folders included) as + `user:`, claude.ai synced skills `skills/synced///` as + `anthropic-skills:`, and the skills of each plugin enabled in + `settings.json` and installed per `plugins/installed_plugins.json` (its + `skills/` folder and manifest `skills` paths) as `:`. + Because user settings stay unloaded, each source becomes a generated + session-only plugin under the visit's evidence directory + (`operator-skills//`: a `plugin.json` plus `skills/` + symlinks to the skill folders, nothing else), passed with `--plugin-dir`; + a plugin's hooks, MCP servers, agents and commands are never loaded. + - A `skills` block's private copy, loaded first as the session-only plugin + `pipelines-stage` (skills named `pipelines-stage:`). + + `--disable-slash-commands` is no longer passed (it also disables skills). + Live check with Claude Code 2.1.332 (haiku, the exact stage flags): the + init event listed 44 skills including `code-review`, `dataviz`, + `user:omarchy`, `user:diagnose-crash` and `anthropic-skills:docx`, and + `code-review` and `user:diagnose-crash` both loaded via the Skill tool. A + skill with `context: fork` (for example `code-review`) runs as a forked + sub-session limited to the same tools. - **Usage.** Cost and tokens come from the CLI's final result and count toward stage and run budgets; a result without usage fails a budgeted stage. - **Failures.** Diagnostics are fixed text. A billing, quota or rate-limit diff --git a/docs/skills.md b/docs/skills.md index 74c987bc..44437aaf 100644 --- a/docs/skills.md +++ b/docs/skills.md @@ -16,9 +16,26 @@ starts (`stage_skills` on the run, `skills` on each step) and `retry` reuses those versions, so importing a newer version never changes a run or its retries. Each visit copies exactly the resolved bundles, read-only, into `//skills/-/skills//` (outside the workspace -and the inventoried turn directory) and gives the harness only those skills: -see the Skills section of `internal/author/skill/references/format.md` and the +and the inventoried turn directory) and gives them to the harness: see the +Skills section of `internal/author/skill/references/format.md` and the per-harness notes in [harnesses.md](harnesses.md). +Library skills are not the only ones a stage sees. Without any import or +`skills` block, every model stage can also use the execution user's own Claude +Code skills, found afresh for each visit in `CLAUDE_CONFIG_DIR` (else +`~/.claude`): personal `skills//` folders (symlinks included), claude.ai +synced `skills/synced///` folders, and the skill folders of +plugins enabled in `settings.json`. Only skill folders are offered, never a +plugin's hooks, MCP servers or commands, and user settings stay unloaded. + +| Harness | Bundled Claude Code skills | Operator skills | Library (`skills` block) | +| --- | --- | --- | --- | +| claude | yes (`code-review`, `dataviz`, ...) | personal `user:`, synced `anthropic-skills:`, plugin `:` | `pipelines-stage:` | +| pi | no (no folder) | `--skill ` each; needs `read` | `--skill `, listed first | +| opencode | no (no folder) | personal and synced, via OpenCode's own `skill` tool; not plugin skills; not text-only stages | instruction entries (V2) | + +A library skill with the same name as an operator skill wins on Pi; on Claude +both are listed under their own plugin names. + Use `pipelines skills list` and `pipelines skills show NAME [--version N]` to inspect imported versions. diff --git a/internal/author/skill/references/format.md b/internal/author/skill/references/format.md index 031c84ba..c6c38939 100644 --- a/internal/author/skill/references/format.md +++ b/internal/author/skill/references/format.md @@ -161,12 +161,24 @@ When a run starts every entry is resolved to `name@N` and recorded on the run (shown on each step), so a later import never changes a running stage; `retry` (resume and restart) reuses the recorded versions for unpinned names. Each visit gets a private read-only copy of exactly those bundles under the run's artifact -directory and only those skills: every other (user, project, bundled) skill -stays off. Harness notes: Claude loads them as a session plugin (`Skill` tool, -listed as `pipelines-stage:`; a call that loads any other skill fails the visit); -Pi loads them with `--skill` and needs `read` in `tools` to open `SKILL.md`; -OpenCode attaches each `SKILL.md` as a session instruction entry (V2 service -only; bundled `references/` are readable with `read`). +directory. Harness notes: Claude loads them as a session plugin (`Skill` tool, +listed as `pipelines-stage:`); Pi loads them with `--skill` and needs +`read` in `tools` to open `SKILL.md`; OpenCode attaches each `SKILL.md` as a +session instruction entry (V2 service only; bundled `references/` are readable +with `read`). + +A skills block is not needed for the execution user's own Claude Code skills: +every model stage can use them with no import. Claude stages see Claude Code's +bundled skills (`code-review`, `dataviz`, ...), the personal `~/.claude/skills` +folders as `user:`, claude.ai synced skills as `anthropic-skills:` +and enabled plugins' skills as `:` (skill folders only; user +settings, hooks and MCP servers stay off). Pi stages get every folder-based one +with `--skill` (after the block's, which win a name clash) and need `read` to +use them. OpenCode tool-using stages may load the personal and synced ones with +OpenCode's own `skill` tool. Bundled skills have no folder, so Pi and OpenCode +stages cannot use them; OpenCode also cannot use plugin skills or give a +text-only stage a skill tool. Name a skill in the prompt when a stage must use +it. ## Checks diff --git a/internal/author/skill/references/harnesses.md b/internal/author/skill/references/harnesses.md index e995f16d..91683074 100644 --- a/internal/author/skill/references/harnesses.md +++ b/internal/author/skill/references/harnesses.md @@ -38,26 +38,31 @@ overridden), apply to that run only, and are recorded so `retry` reproduces them The effective provider/model is stamped on the step. Pi stages start a new retained session per visit with explicit tools and a -Pipelines permission extension; ambient extensions, skills, context files, prompt -templates, automatic retries and compaction are disabled. Tool gates are not an +Pipelines permission extension; ambient extensions, Pi's own skill discovery, +context files, prompt templates, automatic retries and compaction are disabled. Tool gates are not an OS sandbox: approved shell can have broad side effects. Usage accumulates across attempts and visits; missing required accounting fails closed. Session/RPC audit lives in the execution user's cache under `pipelines/pi-sessions`; unconfirmed cleanup blocks continuation and retry. -A `skills` block (`references/format.md`, Skills) is supported by all three -stage harnesses. Claude stages drop `--disable-slash-commands` only when skills -are configured and instead pass `--plugin-dir `, a -`--settings` layer with `disableBundledSkills` and the builtin -plugin-authoring plugin off, `Skill` in `--tools` and one -`Skill(pipelines-stage:)` allow rule per skill; user/project skills stay -unloaded by `--setting-sources ""`. Pi keeps `--no-skills` (it disables every -discovered and configured skill) and adds `--skill ` per skill. OpenCode -stages share one service whose skill discovery is not per session, and its own -skill tool stays denied by the stage's deny-all permissions; the configured -skills are attached as per-session instruction entries instead, which needs the -OpenCode V2 service (a V1 backend fails the visit) and a SKILL.md small enough -for one 64 KiB request. +Every model stage can use the execution user's own Claude Code skills with no +import, and a `skills` block (`references/format.md`, Skills) adds library +skills on all three stage harnesses. Claude stages always offer the `Skill` +tool (in `--tools`, approved by a bare `Skill` rule) and no longer pass +`--disable-slash-commands`, so Claude Code's bundled skills are available; +`--setting-sources ""` still keeps user/project settings, hooks, MCP servers +and plugins off, so the operator's personal (`~/.claude/skills`), synced and +enabled-plugin skill folders are passed as generated skills-only session +plugins (`--plugin-dir`, named `user:`, `anthropic-skills:`, `:`), +after the block's own `--plugin-dir ` +(`pipelines-stage:`). Pi keeps `--no-skills` (Pi's own discovery stays +off) and adds `--skill ` per block skill, then per operator skill folder. +OpenCode discovers `~/.claude/skills` (including synced) itself; a tool-using +stage session allows its `skill` tool for exactly those names, while its other +skills stay denied. Block skills are attached as per-session instruction +entries instead, which needs the OpenCode V2 service (a V1 backend fails the +visit) and a SKILL.md small enough for one 64 KiB request. Bundled Claude Code +skills have no folder and are unavailable to Pi and OpenCode. Claude stages may additionally allow named MCP servers/tools in the `tools` block. These are Claude-only, exact allowlist entries; other MCP tools remain diff --git a/internal/stage/agent.go b/internal/stage/agent.go index 7c1b6097..d5c0c445 100644 --- a/internal/stage/agent.go +++ b/internal/stage/agent.go @@ -5,8 +5,10 @@ import ( "encoding/json" "errors" "fmt" - "git.a-wan.net/alan/pipelines/internal/opencode" + "os" "strings" + + "git.a-wan.net/alan/pipelines/internal/opencode" "time" ) @@ -25,6 +27,10 @@ type AgentClient struct { Transcript string Policy ToolPolicy WorkStarted bool + // operatorSkills are the operator's folder-based Claude Code skills, which + // the session may load with OpenCode's own skill tool (see + // permissionRules). + operatorSkills []OperatorSkillGroup } // resumeConnection reopens the retained execution service a previous server @@ -124,6 +130,8 @@ func (c *AgentClient) Generate(ctx context.Context, config ModelConfig, prompt s } } } + // The service discovers ~/.claude/skills itself, as the same user. + c.operatorSkills = OperatorSkills(claudeConfigDir(os.Environ())) rules := c.permissionRules() model, err := openCodeModelSelection(config, c.Backend) if err != nil { diff --git a/internal/stage/claude_stage.go b/internal/stage/claude_stage.go index 4eb3006a..6d659863 100644 --- a/internal/stage/claude_stage.go +++ b/internal/stage/claude_stage.go @@ -40,23 +40,29 @@ var ( // ClaudeStageClient runs one stage visit with the Claude Code CLI in print // mode: the prompt on stdin, the final assistant text out. Only the stage's -// declared tools exist for the session (`--tools`), and nothing outside them -// is approved (`--permission-mode dontAsk`): an undeclared tool is absent, and -// an edit outside the run directory or the stage's artifacts directory is -// refused by the CLI, not merely discouraged. User, project and local settings -// (hooks, plugins, MCP servers, slash commands) are not loaded. +// declared tools (plus the Skill tool) exist for the session (`--tools`), and +// nothing outside them is approved (`--permission-mode dontAsk`): an +// undeclared tool is absent, and an edit outside the run directory or the +// stage's artifacts directory is refused by the CLI, not merely discouraged. +// User, project and local settings (hooks, plugins, MCP servers, permissions, +// env) are not loaded; the operator's skills are offered as generated +// skills-only plugins instead. type ClaudeStageClient struct { Executable, Directory, SessionID, Reference, Transcript string Tools []string WritePaths []string ArtifactsDir string // Skills are the visit's configured skills, loaded as a session-only - // plugin; nil keeps every skill and slash command disabled. + // plugin beside Claude Code's bundled skills and the operator's skills. Skills *SkillSet Policy ToolPolicy OnOwnership func(string, string, bool) error WorkStarted bool + // operatorPlugins are this visit's generated skills-only plugin roots for + // the operator's own skills (see OperatorSkills). + operatorPlugins []string + budget *Budget // Session totals across the visit's invocations (the prompt and one // outcome follow-up share a session and report per invocation). @@ -148,24 +154,13 @@ func claudeAllowRules(tools []string, directory, artifactsDir string) []string { return rules } -// claudeSkillSettings is the flag-settings layer of a Claude stage with -// configured skills. --disable-slash-commands would also disable the plugin -// skills, so ambient skills are turned off individually instead: user, project -// and local settings (and their skills directories) are already not loaded, -// disableBundledSkills turns off the skills that ship with Claude Code, and -// the builtin plugin that contributes a model-invocable skill is disabled. The -// stream guard (claudeSkillGuard) fails the visit if any other skill is -// still invoked. -const claudeSkillSettings = `{"disableBundledSkills":true,"enabledPlugins":{"cc-plugin-plugin-authoring@builtin":false}}` - func (c *ClaudeStageClient) args(config ModelConfig, tools []string, effort string, resume bool) []string { - skilled := !c.Skills.Empty() - // Permission rules come from the declared tools only: a bare Skill rule - // would approve every skill, so each configured skill is approved by name. + // The Skill tool is always offered and approved: every skill the session + // sees (Claude Code's bundled skills, the operator's skills and the stage's + // skills block) may be loaded. A skill only adds instructions; the declared + // tools and their rules still bound what the session can do. + tools = append(append([]string(nil), tools...), "Skill") rules := claudeAllowRules(tools, c.Directory, c.ArtifactsDir) - if skilled { - tools = append(append([]string(nil), tools...), "Skill") - } args := []string{"-p", "--output-format", "stream-json", "--verbose", "--model", config.Model, "--permission-mode", "dontAsk", @@ -174,18 +169,14 @@ func (c *ClaudeStageClient) args(config ModelConfig, tools []string, effort stri if len(mcpRules) == 0 { args = append(args, "--strict-mcp-config") } - if skilled { - args = append(args, "--settings", claudeSkillSettings, "--plugin-dir", c.Skills.Root) - } else { - args = append(args, "--disable-slash-commands") + if !c.Skills.Empty() { + args = append(args, "--plugin-dir", c.Skills.Root) + } + for _, root := range c.operatorPlugins { + args = append(args, "--plugin-dir", root) } args = append(args, "--tools", strings.Join(tools, ",")) rules = append(rules, mcpRules...) - if skilled { - for _, bundle := range c.Skills.Bundles { - rules = append(rules, "Skill("+ClaudeSkillPlugin+":"+bundle.Name+")") - } - } if len(rules) > 0 { args = append(args, "--allowedTools") args = append(args, rules...) @@ -254,6 +245,11 @@ func (c *ClaudeStageClient) Generate(ctx context.Context, config ModelConfig, pr return "", err } env := claudeStageEnvironment(c.environment(ctx), c.ArtifactsDir) + // User settings are not loaded, so the operator's skills are offered as + // skills-only plugins generated for this visit, never their plugins. + if c.operatorPlugins, err = writeOperatorSkillPlugins(filepath.Join(c.Reference, "operator-skills"), OperatorSkills(claudeConfigDir(env))); err != nil { + return "", err + } owned := false defer func() { // Quiescence is proven per invocation (see run); only then is the @@ -329,6 +325,26 @@ func claudeStageEnvironment(inherited []string, artifactsDir string) []string { return env } +// claudeConfigDir is the Claude Code configuration directory the stage's CLI +// will use: the environment's CLAUDE_CONFIG_DIR, else $HOME/.claude. +func claudeConfigDir(env []string) string { + lookup := func(name string) string { + for i := len(env) - 1; i >= 0; i-- { + if key, value, ok := strings.Cut(env[i], "="); ok && key == name { + return strings.TrimSpace(value) + } + } + return "" + } + if dir := lookup("CLAUDE_CONFIG_DIR"); dir != "" { + return dir + } + if home := lookup("HOME"); filepath.IsAbs(home) { + return filepath.Join(home, ".claude") + } + return "" +} + func newClaudeSessionID() (string, error) { var b [16]byte if _, err := rand.Read(b[:]); err != nil { @@ -365,55 +381,9 @@ type claudeStreamRecord struct { } `json:"rate_limit_info"` Message *struct { Error string `json:"error"` - // Content stays raw: a string content must not make the record - // undecodable (it would drop the line from the evidence stream). - Content json.RawMessage `json:"content"` } `json:"message"` } -// claudeContent is the part of a message content item the skill guard reads. -type claudeContent struct { - Type string `json:"type"` - ID string `json:"id"` - Name string `json:"name"` - ToolUseID string `json:"tool_use_id"` - IsError bool `json:"is_error"` - Input struct { - Skill string `json:"skill"` - } `json:"input"` -} - -// claudeSkillGuard tracks Skill tool calls for skills the visit did not -// configure. A call Claude Code refuses (an unknown or disabled skill) is -// harmless; one whose tool result succeeded loaded an ambient skill, which -// fails the visit. -type claudeSkillGuard struct { - configured *SkillSet - pending map[string]bool - violated bool -} - -func (g *claudeSkillGuard) observe(record claudeStreamRecord) { - if record.Message == nil || len(record.Message.Content) == 0 || record.Message.Content[0] != '[' { - return - } - var items []claudeContent - if json.Unmarshal(record.Message.Content, &items) != nil { - return - } - for _, item := range items { - switch { - case record.Type == "assistant" && item.Type == "tool_use" && item.Name == "Skill" && !g.configured.claudeAllowed(item.Input.Skill): - if g.pending == nil { - g.pending = map[string]bool{} - } - g.pending[item.ID] = true - case record.Type == "user" && item.Type == "tool_result" && g.pending[item.ToolUseID] && !item.IsError: - g.violated = true - } - } -} - func (c *ClaudeStageClient) run(ctx context.Context, env, args []string, model, prompt string) (text string, err error) { cmd := exec.Command(c.Executable, args...) cmd.Dir = c.Directory @@ -450,7 +420,6 @@ func (c *ClaudeStageClient) run(ctx context.Context, env, args []string, model, var refusal, limited bool var resetsAt int64 var authFailed, sessionMismatch, modelMismatch bool - skills := &claudeSkillGuard{configured: c.Skills} scanned := make(chan error, 1) go func() { scanner := bufio.NewScanner(out) @@ -478,10 +447,7 @@ func (c *ClaudeStageClient) run(ctx context.Context, env, args []string, model, limited = true resetsAt = record.RateLimit.ResetsAt } - case "user": - skills.observe(record) case "assistant": - skills.observe(record) if record.Message != nil { switch record.Message.Error { case "billing_error", "rate_limit": @@ -555,8 +521,6 @@ func (c *ClaudeStageClient) run(ctx context.Context, env, args []string, model, return "", fmt.Errorf("%w: %w; the Claude usage limit resets at %s", ErrHarnessTransport, opencode.ErrProviderQuota, time.Unix(resetsAt, 0).Format("15:04 on 2 Jan")) } return "", fmt.Errorf("%w: %w", ErrHarnessTransport, opencode.ErrProviderQuota) - case skills.violated: - return "", fmt.Errorf("Claude Code invoked a skill that is not configured for this stage; only the stage's skills block may be used") case sessionMismatch || modelMismatch: return "", fmt.Errorf("%w: Claude Code did not start the requested session and model", ErrHarnessTransport) case final == nil: diff --git a/internal/stage/claude_stage_test.go b/internal/stage/claude_stage_test.go index f8e9c20a..c7f247bf 100644 --- a/internal/stage/claude_stage_test.go +++ b/internal/stage/claude_stage_test.go @@ -84,14 +84,13 @@ case "$FAKE_CLAUDE_CASE" in init "$session" "$model" echo '{"type":"result","subtype":"error_max_turns","is_error":true,"result":"PROVIDER-BODY-SECRET","session_id":"'"$session"'",'"$usage"'}' ;; - skill|ambientskill|refusedskill) + skill) init "$session" "$model" - name=pipelines-stage:hello; failed=false - if [ "$FAKE_CLAUDE_CASE" != skill ]; then name=dataviz; fi - if [ "$FAKE_CLAUDE_CASE" = refusedskill ]; then failed=true; fi echo '{"type":"user","session_id":"'"$session"'","message":{"role":"user","content":"a plain string content"}}' - echo '{"type":"assistant","session_id":"'"$session"'","message":{"role":"assistant","content":[{"type":"tool_use","id":"t1","name":"Skill","input":{"skill":"'"$name"'"}}]}}' - echo '{"type":"user","session_id":"'"$session"'","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","content":"Launching skill: '"$name"'","is_error":'"$failed"'}]}}' + for name in pipelines-stage:hello dataviz user:omarchy; do + echo '{"type":"assistant","session_id":"'"$session"'","message":{"role":"assistant","content":[{"type":"tool_use","id":"'"$name"'","name":"Skill","input":{"skill":"'"$name"'"}}]}}' + echo '{"type":"user","session_id":"'"$session"'","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"'"$name"'","content":"Launching skill: '"$name"'"}]}}' + done echo '{"type":"result","subtype":"success","is_error":false,"result":"done","session_id":"'"$session"'",'"$usage"'}' ;; othermodel) @@ -109,6 +108,8 @@ func fakeClaudeClient(t *testing.T, which string) (*ClaudeStageClient, string, * } t.Setenv("XDG_CACHE_HOME", root) t.Setenv("HOME", root) + // The operator's real skills stay out unless a test plants some. + t.Setenv("CLAUDE_CONFIG_DIR", "") t.Setenv("FAKE_CLAUDE_OUT", root) t.Setenv("FAKE_CLAUDE_CASE", which) // The fake needs no account; keep the developer's own out of the test. @@ -192,13 +193,13 @@ func TestClaudeStageDeclaredToolsAreTheOnlyTools(t *testing.T) { want func(work, artifacts string) []string }{ {"none", []string{}, false, func(_, _ string) []string { - return []string{"--tools", ""} + return []string{"--tools", "Skill", "--allowedTools", "Skill"} }}, {"read only", []string{"read", "glob", "grep"}, false, func(_, _ string) []string { - return []string{"--tools", "Read,Glob,Grep", "--allowedTools", "Read", "Glob", "Grep"} + return []string{"--tools", "Read,Glob,Grep,Skill", "--allowedTools", "Read", "Glob", "Grep", "Skill"} }}, {"edit and shell", []string{"read", "edit", "shell"}, true, func(work, artifacts string) []string { - return []string{"--tools", "Read,Edit,Write,Bash", "--allowedTools", "Read", "Bash", "Edit(/" + work + "/**)", "Edit(/" + artifacts + "/**)", "--add-dir", artifacts} + return []string{"--tools", "Read,Edit,Write,Bash,Skill", "--allowedTools", "Read", "Bash", "Skill", "Edit(/" + work + "/**)", "Edit(/" + artifacts + "/**)", "--add-dir", artifacts} }}, } { t.Run(test.name, func(t *testing.T) { @@ -217,7 +218,7 @@ func TestClaudeStageDeclaredToolsAreTheOnlyTools(t *testing.T) { t.Fatal(calls) } want := append([]string{"-p", "--output-format", "stream-json", "--verbose", "--model", "claude-haiku-5-5", - "--permission-mode", "dontAsk", "--setting-sources", "", "--strict-mcp-config", "--disable-slash-commands"}, + "--permission-mode", "dontAsk", "--setting-sources", "", "--strict-mcp-config"}, test.want(client.Directory, artifacts)...) want = append(want, "--session-id", client.SessionID) if !slices.Equal(calls[0], want) { diff --git a/internal/stage/operator_skills.go b/internal/stage/operator_skills.go new file mode 100644 index 00000000..bfd79ce3 --- /dev/null +++ b/internal/stage/operator_skills.go @@ -0,0 +1,251 @@ +package stage + +import ( + "encoding/json" + "os" + "path/filepath" + "regexp" + "slices" + "strings" +) + +// Model stages may use the operator's own folder-based Claude Code skills +// without any import step. They are discovered afresh for every visit from the +// execution user's Claude Code configuration directory: +// +// - personal skills, /skills//SKILL.md (symlinked folders +// included); +// - claude.ai synced skills, /skills/synced///SKILL.md; +// - the skills of every plugin enabled in /settings.json and +// installed per /plugins/installed_plugins.json (its skills/ +// folder and any skills paths in its manifest). +// +// Only skill folders are offered. A plugin's hooks, MCP servers, agents, +// commands and settings are never loaded. Claude Code's bundled skills have no +// folder; Claude stages get them from the CLI itself, Pi and OpenCode cannot. + +// Plugin names a Claude stage offers each group under. A Claude stage loads +// every group as a session-only plugin, so its skills are named +// :. +const ( + OperatorSkillPlugin = "user" + SyncedSkillPlugin = "anthropic-skills" +) + +// OperatorSkill is one folder-based Claude Code skill of the operator. Dir is +// the folder as found (a symlink is not resolved). +type OperatorSkill struct { + Name string + Dir string +} + +// OperatorSkillGroup is the skills of one source, under the plugin name a +// Claude stage loads them as. +type OperatorSkillGroup struct { + Plugin string + Skills []OperatorSkill +} + +// operatorSkillName is a skill folder name that is safe as one path element +// of a generated plugin directory. +var operatorSkillName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$`) + +// operatorPluginName is an installed plugin name usable as a plugin root. +var operatorPluginName = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]{0,63}$`) + +// OperatorSkills discovers the operator's folder-based Claude Code skills +// below config (Claude Code's configuration directory). Unreadable or +// malformed sources are skipped: a missing skill never fails a visit. Within a +// group a name appears once; groups are personal, synced, then plugins in +// name order. +func OperatorSkills(config string) []OperatorSkillGroup { + if config == "" { + return nil + } + var groups []OperatorSkillGroup + add := func(plugin string, skills []OperatorSkill) { + if len(skills) > 0 { + groups = append(groups, OperatorSkillGroup{Plugin: plugin, Skills: skills}) + } + } + root := filepath.Join(config, "skills") + add(OperatorSkillPlugin, skillFolders(root, map[string]bool{"synced": true})) + var synced []OperatorSkill + seen := map[string]bool{} + if buckets, err := os.ReadDir(filepath.Join(root, "synced")); err == nil { + for _, bucket := range buckets { + if strings.HasPrefix(bucket.Name(), ".") { + continue + } + for _, skill := range skillFolders(filepath.Join(root, "synced", bucket.Name()), nil) { + if !seen[skill.Name] { + seen[skill.Name] = true + synced = append(synced, skill) + } + } + } + } + add(SyncedSkillPlugin, synced) + for _, plugin := range enabledPlugins(config) { + add(plugin.name, plugin.skills()) + } + return groups +} + +// skillFolders lists the direct children of dir that hold a SKILL.md file, +// following symlinks, in name order. +func skillFolders(dir string, skip map[string]bool) []OperatorSkill { + entries, err := os.ReadDir(dir) + if err != nil { + return nil + } + var skills []OperatorSkill + for _, entry := range entries { + name := entry.Name() + if skip[name] || !operatorSkillName.MatchString(name) { + continue + } + path := filepath.Join(dir, name) + if isSkillFolder(path) { + skills = append(skills, OperatorSkill{Name: name, Dir: path}) + } + } + return skills +} + +func isSkillFolder(dir string) bool { + if info, err := os.Stat(dir); err != nil || !info.IsDir() { + return false + } + info, err := os.Stat(filepath.Join(dir, "SKILL.md")) + return err == nil && info.Mode().IsRegular() +} + +type enabledPlugin struct { + name, root string + manifest []string +} + +// enabledPlugins are the user-enabled installed plugins, in key order. A +// plugin name that collides with a generated group, or with an earlier +// plugin, is skipped. +func enabledPlugins(config string) []enabledPlugin { + var settings struct { + EnabledPlugins map[string]bool `json:"enabledPlugins"` + } + var installed struct { + Plugins map[string][]struct { + InstallPath string `json:"installPath"` + } `json:"plugins"` + } + if !readJSON(filepath.Join(config, "settings.json"), &settings) || !readJSON(filepath.Join(config, "plugins", "installed_plugins.json"), &installed) { + return nil + } + taken := map[string]bool{OperatorSkillPlugin: true, SyncedSkillPlugin: true, ClaudeSkillPlugin: true} + var keys []string + for key, on := range settings.EnabledPlugins { + if on { + keys = append(keys, key) + } + } + slices.Sort(keys) + var plugins []enabledPlugin + for _, key := range keys { + name, _, _ := strings.Cut(key, "@") + installs := installed.Plugins[key] + if !operatorPluginName.MatchString(name) || taken[name] || len(installs) == 0 || !filepath.IsAbs(installs[0].InstallPath) { + continue + } + plugin := enabledPlugin{name: name, root: filepath.Clean(installs[0].InstallPath)} + var manifest struct { + Skills json.RawMessage `json:"skills"` + } + if readJSON(filepath.Join(plugin.root, ".claude-plugin", "plugin.json"), &manifest) && len(manifest.Skills) > 0 { + var one string + if json.Unmarshal(manifest.Skills, &one) == nil { + plugin.manifest = []string{one} + } else { + _ = json.Unmarshal(manifest.Skills, &plugin.manifest) + } + } + taken[name] = true + plugins = append(plugins, plugin) + } + return plugins +} + +// skills are the plugin's skill folders: skills// and each manifest +// skills path, which is a skill folder itself or a folder of skills. A path +// that leaves the plugin root is ignored. +func (p enabledPlugin) skills() []OperatorSkill { + var skills []OperatorSkill + seen := map[string]bool{} + add := func(list []OperatorSkill) { + for _, skill := range list { + if !seen[skill.Name] { + seen[skill.Name] = true + skills = append(skills, skill) + } + } + } + add(skillFolders(filepath.Join(p.root, "skills"), nil)) + for _, rel := range p.manifest { + path := filepath.Join(p.root, rel) + if inside, err := filepath.Rel(p.root, path); err != nil || inside == ".." || strings.HasPrefix(inside, "../") || filepath.IsAbs(rel) { + continue + } + if name := filepath.Base(path); isSkillFolder(path) && operatorSkillName.MatchString(name) { + add([]OperatorSkill{{Name: name, Dir: path}}) + } else { + add(skillFolders(path, nil)) + } + } + return skills +} + +func readJSON(path string, value any) bool { + data, err := os.ReadFile(path) + return err == nil && json.Unmarshal(data, value) == nil +} + +// operatorSkillDirs flattens the groups' skill folders in group order. +func operatorSkillDirs(groups []OperatorSkillGroup) []string { + var dirs []string + for _, group := range groups { + for _, skill := range group.Skills { + dirs = append(dirs, skill.Dir) + } + } + return dirs +} + +// writeOperatorSkillPlugins materialises every group as a Claude Code plugin +// root below dir: .claude-plugin/plugin.json plus skills/ symlinks to +// the skill folders, nothing else. It returns the plugin roots in group order. +func writeOperatorSkillPlugins(dir string, groups []OperatorSkillGroup) ([]string, error) { + var roots []string + for _, group := range groups { + root := filepath.Join(dir, group.Plugin) + if err := os.MkdirAll(filepath.Join(root, ".claude-plugin"), 0o700); err != nil { + return nil, err + } + if err := os.MkdirAll(filepath.Join(root, "skills"), 0o700); err != nil { + return nil, err + } + manifest, _ := json.Marshal(map[string]string{"name": group.Plugin, "description": "The operator's Claude Code skills, offered to a pipeline stage (skills only)."}) + if err := os.WriteFile(filepath.Join(root, ".claude-plugin", "plugin.json"), manifest, 0o600); err != nil { + return nil, err + } + for _, skill := range group.Skills { + target, err := filepath.Abs(skill.Dir) + if err != nil { + return nil, err + } + if err := os.Symlink(target, filepath.Join(root, "skills", skill.Name)); err != nil { + return nil, err + } + } + roots = append(roots, root) + } + return roots, nil +} diff --git a/internal/stage/operator_skills_test.go b/internal/stage/operator_skills_test.go new file mode 100644 index 00000000..8a013cb1 --- /dev/null +++ b/internal/stage/operator_skills_test.go @@ -0,0 +1,271 @@ +package stage + +import ( + "context" + "os" + "path/filepath" + "slices" + "strings" + "testing" +) + +func writeSkill(t *testing.T, dir string) { + t.Helper() + if err := os.MkdirAll(dir, 0o700); err != nil { + t.Fatal(err) + } + name := filepath.Base(dir) + if err := os.WriteFile(filepath.Join(dir, "SKILL.md"), []byte("---\nname: "+name+"\ndescription: Test skill "+name+".\n---\nBody.\n"), 0o600); err != nil { + t.Fatal(err) + } +} + +func writeFile(t *testing.T, path, text string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(text), 0o600); err != nil { + t.Fatal(err) + } +} + +// plantOperatorSkills builds a Claude Code configuration directory with +// personal, synced and plugin skills plus entries that must be ignored. +func plantOperatorSkills(t *testing.T, config string) { + t.Helper() + outside := filepath.Join(filepath.Dir(config), "outside") + writeSkill(t, filepath.Join(outside, "omarchy")) + if err := os.MkdirAll(filepath.Join(config, "skills"), 0o700); err != nil { + t.Fatal(err) + } + if err := os.Symlink(filepath.Join(outside, "omarchy"), filepath.Join(config, "skills", "omarchy")); err != nil { + t.Fatal(err) + } + writeSkill(t, filepath.Join(config, "skills", "diagnose-crash")) + writeFile(t, filepath.Join(config, "skills", "notes", "README.md"), "not a skill") + writeSkill(t, filepath.Join(config, "skills", ".trash")) + writeSkill(t, filepath.Join(config, "skills", "synced", "bucket-a", "docx")) + writeSkill(t, filepath.Join(config, "skills", "synced", "bucket-b", "docx")) + writeSkill(t, filepath.Join(config, "skills", "synced", "bucket-b", "pdf")) + writeFile(t, filepath.Join(config, "skills", "synced", ".bucket-a"), "") + plugin := filepath.Join(config, "plugins", "cache", "market", "lint-kit", "1.0.0") + writeSkill(t, filepath.Join(plugin, "skills", "lint")) + writeSkill(t, filepath.Join(plugin, "extra", "fmt")) + writeSkill(t, filepath.Join(plugin, "single")) + writeFile(t, filepath.Join(plugin, "hooks", "hooks.json"), `{"hooks":{}}`) + writeFile(t, filepath.Join(plugin, ".mcp.json"), `{"mcpServers":{}}`) + writeFile(t, filepath.Join(plugin, ".claude-plugin", "plugin.json"), `{"name":"lint-kit","skills":["./extra","./single","../../escape"]}`) + off := filepath.Join(config, "plugins", "cache", "market", "off-kit", "1.0.0") + writeSkill(t, filepath.Join(off, "skills", "hidden")) + writeFile(t, filepath.Join(config, "settings.json"), `{"enabledPlugins":{"lint-kit@market":true,"off-kit@market":false,"user@market":true,"missing@market":true}}`) + writeFile(t, filepath.Join(config, "plugins", "installed_plugins.json"), `{"version":2,"plugins":{`+ + `"lint-kit@market":[{"scope":"user","installPath":"`+plugin+`"}],`+ + `"off-kit@market":[{"scope":"user","installPath":"`+off+`"}],`+ + `"user@market":[{"scope":"user","installPath":"`+off+`"}]}}`) +} + +func groupNames(groups []OperatorSkillGroup) []string { + var names []string + for _, group := range groups { + for _, skill := range group.Skills { + names = append(names, group.Plugin+":"+skill.Name) + } + } + return names +} + +func TestOperatorSkillsDiscoversPersonalSyncedAndEnabledPluginSkills(t *testing.T) { + config := filepath.Join(t.TempDir(), ".claude") + plantOperatorSkills(t, config) + groups := OperatorSkills(config) + want := []string{"user:diagnose-crash", "user:omarchy", "anthropic-skills:docx", "anthropic-skills:pdf", "lint-kit:lint", "lint-kit:fmt", "lint-kit:single"} + if got := groupNames(groups); !slices.Equal(got, want) { + t.Fatalf("got %q\nwant %q", got, want) + } + // A symlinked skill keeps its path as found; the first synced copy wins. + if groups[0].Skills[1].Dir != filepath.Join(config, "skills", "omarchy") || groups[1].Skills[0].Dir != filepath.Join(config, "skills", "synced", "bucket-a", "docx") { + t.Fatal(groups) + } + if OperatorSkills("") != nil || OperatorSkills(filepath.Join(t.TempDir(), "absent")) != nil { + t.Fatal("a missing configuration has no skills") + } +} + +func TestOperatorSkillPluginsHoldOnlySkillLinks(t *testing.T) { + config := filepath.Join(t.TempDir(), ".claude") + plantOperatorSkills(t, config) + dir := filepath.Join(t.TempDir(), "operator-skills") + roots, err := writeOperatorSkillPlugins(dir, OperatorSkills(config)) + if err != nil { + t.Fatal(err) + } + if !slices.Equal(roots, []string{filepath.Join(dir, "user"), filepath.Join(dir, "anthropic-skills"), filepath.Join(dir, "lint-kit")}) { + t.Fatal(roots) + } + var files []string + _ = filepath.Walk(filepath.Join(dir, "lint-kit"), func(path string, info os.FileInfo, err error) error { + rel, _ := filepath.Rel(filepath.Join(dir, "lint-kit"), path) + files = append(files, rel) + return err + }) + // No hooks, MCP servers or other plugin parts; skill folders are links. + if !slices.Equal(files, []string{".", ".claude-plugin", ".claude-plugin/plugin.json", "skills", "skills/fmt", "skills/lint", "skills/single"}) { + t.Fatal(files) + } + if target, err := os.Readlink(filepath.Join(dir, "user", "skills", "omarchy")); err != nil || target != filepath.Join(config, "skills", "omarchy") { + t.Fatal(target, err) + } + if data, err := os.ReadFile(filepath.Join(dir, "user", "skills", "omarchy", "SKILL.md")); err != nil || !strings.Contains(string(data), "name: omarchy") { + t.Fatal(string(data), err) + } +} + +func TestClaudeStageOffersEverySkill(t *testing.T) { + client, root, _ := fakeClaudeClient(t, "skill") + plantOperatorSkills(t, filepath.Join(root, ".claude")) + client.Skills = testSkillSet(t) + if _, err := client.Generate(context.Background(), claudeConfig(nil), "task"); err != nil { + t.Fatal("bundled, operator and configured skill loads must all succeed:", err) + } + plugins := filepath.Join(client.Reference, "operator-skills") + calls := fakeClaudeArgs(t, root) + want := []string{"-p", "--output-format", "stream-json", "--verbose", "--model", "claude-haiku-5-5", + "--permission-mode", "dontAsk", "--setting-sources", "", "--strict-mcp-config", + "--plugin-dir", client.Skills.Root, + "--plugin-dir", filepath.Join(plugins, "user"), + "--plugin-dir", filepath.Join(plugins, "anthropic-skills"), + "--plugin-dir", filepath.Join(plugins, "lint-kit"), + "--tools", "Read,Skill", "--allowedTools", "Read", "Skill", "--session-id", client.SessionID} + if len(calls) != 1 || !slices.Equal(calls[0], want) { + t.Fatalf("args\n got %q\nwant %q", calls, want) + } + if slices.Contains(calls[0], "--disable-slash-commands") || slices.Contains(calls[0], "--settings") { + t.Fatal("skills must not be disabled", calls[0]) + } + // String message content stays in the evidence stream. + if !strings.Contains(client.Transcript, "a plain string content") { + t.Fatal("string-content record dropped from the transcript") + } + // CLAUDE_CONFIG_DIR selects the configuration the CLI itself uses. + client, root, _ = fakeClaudeClient(t, "success") + other := filepath.Join(root, "isolated") + writeSkill(t, filepath.Join(other, "skills", "only-here")) + t.Setenv("CLAUDE_CONFIG_DIR", other) + if _, err := client.Generate(context.Background(), claudeConfig(nil), "task"); err != nil { + t.Fatal(err) + } + if target, err := os.Readlink(filepath.Join(client.Reference, "operator-skills", "user", "skills", "only-here")); err != nil || target != filepath.Join(other, "skills", "only-here") { + t.Fatal(target, err) + } +} + +func TestPiSkillArgsAndReadScope(t *testing.T) { + if args := piSkillArgs(nil, nil); args != nil { + t.Fatal(args) + } + set := testSkillSet(t) + operator := []OperatorSkillGroup{{Plugin: OperatorSkillPlugin, Skills: []OperatorSkill{{Name: "omarchy", Dir: "/home/u/.claude/skills/omarchy"}}}} + if args := piSkillArgs(set, operator); !slices.Equal(args, []string{"--skill", set.Bundles[0].Dir, "--skill", "/home/u/.claude/skills/omarchy"}) { + t.Fatal(args) + } + client := &PiClient{Directory: "/work", ArtifactAccess: ArtifactAccess{Read: []string{"/runs/1/stages/01-a"}}} + if read := piPolicyMap(client, nil)["artifact_read"].([]string); len(read) != 1 { + t.Fatal("no skills widened reads", read) + } + client.Skills = set + client.operatorSkills = operator + if read := piPolicyMap(client, nil)["artifact_read"].([]string); !slices.Equal(read, []string{"/runs/1/stages/01-a", set.Root, "/home/u/.claude/skills/omarchy"}) { + t.Fatal(read) + } + if len(client.ArtifactAccess.Read) != 1 { + t.Fatal("caller's read list mutated") + } +} + +func TestPiLaunchesWithConfiguredThenOperatorSkills(t *testing.T) { + for _, skilled := range []bool{false, true} { + root := t.TempDir() + t.Setenv("XDG_CACHE_HOME", root) + t.Setenv("HOME", root) + t.Setenv("CLAUDE_CONFIG_DIR", "") + t.Setenv("PIPELINES_PI_FIXTURE", "1") + t.Setenv("PI_FIXTURE_CASE", "success") + if skilled { + writeSkill(t, filepath.Join(root, ".claude", "skills", "omarchy")) + } + executable, err := os.Executable() + if err != nil { + t.Fatal(err) + } + wrapper := filepath.Join(root, "pi") + script := "#!/bin/sh\nprintf '%s\\n' \"$@\" > '" + filepath.Join(root, "args") + "'\nexec '" + executable + "' -test.run=^TestPiRPCFixture$\n" + if err := os.WriteFile(wrapper, []byte(script), 0o700); err != nil { + t.Fatal(err) + } + client := &PiClient{Executable: wrapper, Directory: root, Tools: []string{"read"}} + if skilled { + client.Skills = testSkillSet(t) + } + if _, err := client.Generate(context.Background(), ModelConfig{Provider: "fixture", Model: "model", Budget: NewBudget(0, 100)}, "task"); err != nil { + t.Fatal(err) + } + data, err := os.ReadFile(filepath.Join(root, "args")) + if err != nil { + t.Fatal(err) + } + args := strings.Split(strings.TrimSpace(string(data)), "\n") + if !slices.Contains(args, "--no-skills") { + t.Fatal("--no-skills must stay: Pi's own skill discovery is not the operator's Claude skills", args) + } + var skills []string + for i, arg := range args { + if arg == "--skill" { + skills = append(skills, args[i+1]) + } + } + var want []string + if skilled { + want = []string{client.Skills.Bundles[0].Dir, filepath.Join(root, ".claude", "skills", "omarchy")} + } + if !slices.Equal(skills, want) { + t.Fatalf("skilled=%v skills %q want %q", skilled, skills, want) + } + } +} + +func TestOpenCodeAgentAllowsOperatorSkillsByName(t *testing.T) { + config := filepath.Join(t.TempDir(), ".claude") + plantOperatorSkills(t, config) + client := &AgentClient{Tools: []string{"read"}, operatorSkills: OperatorSkills(config)} + client.Directory = "/work" + var skills, dirs []string + for _, rule := range client.permissionRules() { + if rule["effect"] != "allow" { + continue + } + switch rule["action"] { + case "skill": + skills = append(skills, rule["resource"]) + case "external_directory": + dirs = append(dirs, rule["resource"]) + } + } + // OpenCode discovers personal and synced skills itself, not plugins. + if !slices.Equal(skills, []string{"diagnose-crash", "omarchy", "docx", "pdf"}) { + t.Fatal(skills) + } + real := filepath.Join(filepath.Dir(config), "outside", "omarchy") + for _, want := range []string{filepath.Join(config, "skills", "omarchy", "*"), real + "/*", filepath.Join(config, "skills", "synced", "bucket-b", "pdf", "*")} { + if !slices.Contains(dirs, want) { + t.Fatalf("missing read grant %s in %q", want, dirs) + } + } + // Without read tools the skill tool is still allowed; no directory grants. + client.Tools = []string{"shell"} + for _, rule := range client.permissionRules() { + if rule["action"] == "external_directory" && rule["effect"] == "allow" { + t.Fatal("no read tools, no directory grants", rule) + } + } +} diff --git a/internal/stage/pi.go b/internal/stage/pi.go index c59a34da..7f05b3e8 100644 --- a/internal/stage/pi.go +++ b/internal/stage/pi.go @@ -31,9 +31,11 @@ type PiClient struct { // PIPELINES_ARTIFACTS_DIR so its tools can write stage artifacts. ArtifactsDir string ArtifactAccess ArtifactAccess - // Skills are loaded with --skill while --no-skills keeps every discovered - // and configured skill out; nil loads none. + // Skills are loaded with --skill, before the operator's folder-based + // Claude Code skills (see OperatorSkills); --no-skills keeps Pi's own + // discovered and configured skills out. Skills *SkillSet + operatorSkills []OperatorSkillGroup Policy ToolPolicy OnSession func(string, bool) error OnOwnership func(string, string, bool) error @@ -74,11 +76,12 @@ func piPolicyMap(c *PiClient, tools []string) map[string]any { if paths == nil { paths = []string{} } - read := c.ArtifactAccess.Read + // The model reads each skill's SKILL.md and bundled files by path. + read := append([]string(nil), c.ArtifactAccess.Read...) if !c.Skills.Empty() { - // The model reads each skill's SKILL.md and bundled files by path. - read = append(append([]string(nil), read...), c.Skills.Root) + read = append(read, c.Skills.Root) } + read = append(read, operatorSkillDirs(c.operatorSkills)...) return map[string]any{ "directory": c.Directory, "tools": tools, @@ -153,6 +156,8 @@ func (c *PiClient) Generate(ctx context.Context, config ModelConfig, prompt stri if err != nil { return "", err } + env := piEnvironmentFrom(workenv.CommandEnv(ctx, c.Directory), c.Reference, c.ArtifactsDir) + c.operatorSkills = OperatorSkills(claudeConfigDir(env)) policy := piPolicyMap(c, tools) data, _ := json.Marshal(policy) for name, data := range map[string][]byte{"policy.js": piPolicy, "policy.json": data, "lease": []byte("owned")} { @@ -167,7 +172,7 @@ func (c *PiClient) Generate(ctx context.Context, config ModelConfig, prompt stri if thinking != "" { args = append(args, "--thinking", thinking) } - args = append(args, piSkillArgs(c.Skills)...) + args = append(args, piSkillArgs(c.Skills, c.operatorSkills)...) if len(tools) == 0 { args = append(args, "--no-tools") } else { @@ -176,7 +181,7 @@ func (c *PiClient) Generate(ctx context.Context, config ModelConfig, prompt stri c.cmd = exec.Command(c.Executable, args...) c.cmd.Dir = c.Directory c.cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} - c.cmd.Env = piEnvironmentFrom(workenv.CommandEnv(ctx, c.Directory), c.Reference, c.ArtifactsDir) + c.cmd.Env = env stderr, err := os.OpenFile(filepath.Join(c.Reference, "stderr.log"), os.O_CREATE|os.O_WRONLY, 0600) if err != nil { return "", err @@ -662,16 +667,20 @@ func PiEvidence(reference string) (string, error) { return RedactEvidence(string(data)), err } -// piSkillArgs loads exactly the visit's configured skills. Pi documents that -// explicit --skill paths still load under --no-skills, which keeps disabling -// every discovered (user, project) and settings-configured skill. -func piSkillArgs(set *SkillSet) []string { - if set.Empty() { - return nil +// piSkillArgs loads the visit's configured skills, then the operator's +// folder-based Claude Code skills. Pi documents that explicit --skill paths +// still load under --no-skills, which keeps disabling Pi's own discovered +// (user, project) and settings-configured skills; on a name collision Pi keeps +// the first, so a configured skill wins over an operator skill. +func piSkillArgs(set *SkillSet, operator []OperatorSkillGroup) []string { + var args []string + if !set.Empty() { + for _, bundle := range set.Bundles { + args = append(args, "--skill", bundle.Dir) + } } - args := make([]string, 0, 2*len(set.Bundles)) - for _, bundle := range set.Bundles { - args = append(args, "--skill", bundle.Dir) + for _, dir := range operatorSkillDirs(operator) { + args = append(args, "--skill", dir) } return args } diff --git a/internal/stage/skills.go b/internal/stage/skills.go index dd592162..1a9a577e 100644 --- a/internal/stage/skills.go +++ b/internal/stage/skills.go @@ -112,19 +112,3 @@ func (s *SkillSet) Names() []string { } return names } - -// claudeAllowed reports whether a Claude Code Skill tool call names one of the -// configured skills. Only the plugin-qualified name counts: a bare name could -// be an ambient skill of the same name. -func (s *SkillSet) claudeAllowed(name string) bool { - if s.Empty() { - return false - } - name = strings.TrimPrefix(strings.TrimSpace(name), "/") - for _, b := range s.Bundles { - if name == ClaudeSkillPlugin+":"+b.Name { - return true - } - } - return false -} diff --git a/internal/stage/skills_test.go b/internal/stage/skills_test.go index 9bb31fbe..1d9b8d89 100644 --- a/internal/stage/skills_test.go +++ b/internal/stage/skills_test.go @@ -95,108 +95,6 @@ func testSkillSet(t *testing.T) *SkillSet { return &SkillSet{Root: root, Bundles: []SkillBundle{{Name: "hello", Version: 2, Dir: dir}}} } -func TestClaudeStageSkillsLoadAsSessionPlugin(t *testing.T) { - client, root, _ := fakeClaudeClient(t, "skill") - client.Skills = testSkillSet(t) - if _, err := client.Generate(context.Background(), claudeConfig(nil), "task"); err != nil { - t.Fatal(err) - } - calls := fakeClaudeArgs(t, root) - want := []string{"-p", "--output-format", "stream-json", "--verbose", "--model", "claude-haiku-5-5", - "--permission-mode", "dontAsk", "--setting-sources", "", "--strict-mcp-config", - "--settings", claudeSkillSettings, "--plugin-dir", client.Skills.Root, - "--tools", "Read,Skill", "--allowedTools", "Read", "Skill(pipelines-stage:hello)", "--session-id", client.SessionID} - if len(calls) != 1 || !slices.Equal(calls[0], want) { - t.Fatalf("args\n got %q\nwant %q", calls, want) - } - var settings map[string]any - if err := json.Unmarshal([]byte(claudeSkillSettings), &settings); err != nil || settings["disableBundledSkills"] != true { - t.Fatal("settings", settings, err) - } -} - -func TestClaudeStageAmbientSkillFailsTheVisit(t *testing.T) { - client, _, _ := fakeClaudeClient(t, "ambientskill") - client.Skills = testSkillSet(t) - if _, err := client.Generate(context.Background(), claudeConfig(nil), "task"); err == nil || !strings.Contains(err.Error(), "not configured for this stage") { - t.Fatal(err) - } - // Without configured skills any loaded skill is a violation too. - client, _, _ = fakeClaudeClient(t, "skill") - if _, err := client.Generate(context.Background(), claudeConfig(nil), "task"); err == nil { - t.Fatal("a skill call without configured skills must fail") - } - // A call Claude Code refused (unknown or disabled skill) loaded nothing. - client, _, _ = fakeClaudeClient(t, "refusedskill") - client.Skills = testSkillSet(t) - if _, err := client.Generate(context.Background(), claudeConfig(nil), "task"); err != nil { - t.Fatal("a refused ambient skill call must not fail the visit:", err) - } - // String message content stays in the evidence stream. - if !strings.Contains(client.Transcript, "a plain string content") { - t.Fatal("string-content record dropped from the transcript") - } -} - -func TestPiSkillArgsAndReadScope(t *testing.T) { - if args := piSkillArgs(nil); args != nil { - t.Fatal(args) - } - set := testSkillSet(t) - if args := piSkillArgs(set); !slices.Equal(args, []string{"--skill", set.Bundles[0].Dir}) { - t.Fatal(args) - } - client := &PiClient{Directory: "/work", ArtifactAccess: ArtifactAccess{Read: []string{"/runs/1/stages/01-a"}}} - if read := piPolicyMap(client, nil)["artifact_read"].([]string); len(read) != 1 { - t.Fatal("no skills widened reads", read) - } - client.Skills = set - if read := piPolicyMap(client, nil)["artifact_read"].([]string); !slices.Equal(read, []string{"/runs/1/stages/01-a", set.Root}) { - t.Fatal(read) - } - if len(client.ArtifactAccess.Read) != 1 { - t.Fatal("caller's read list mutated") - } -} - -func TestPiLaunchesWithExplicitSkillsOnly(t *testing.T) { - for _, skilled := range []bool{false, true} { - root := t.TempDir() - t.Setenv("XDG_CACHE_HOME", root) - t.Setenv("HOME", root) - t.Setenv("PIPELINES_PI_FIXTURE", "1") - t.Setenv("PI_FIXTURE_CASE", "success") - executable, err := os.Executable() - if err != nil { - t.Fatal(err) - } - wrapper := filepath.Join(root, "pi") - script := "#!/bin/sh\nprintf '%s\\n' \"$@\" > '" + filepath.Join(root, "args") + "'\nexec '" + executable + "' -test.run=^TestPiRPCFixture$\n" - if err := os.WriteFile(wrapper, []byte(script), 0o700); err != nil { - t.Fatal(err) - } - client := &PiClient{Executable: wrapper, Directory: root, Tools: []string{"read"}} - if skilled { - client.Skills = testSkillSet(t) - } - if _, err := client.Generate(context.Background(), ModelConfig{Provider: "fixture", Model: "model", Budget: NewBudget(0, 100)}, "task"); err != nil { - t.Fatal(err) - } - data, err := os.ReadFile(filepath.Join(root, "args")) - if err != nil { - t.Fatal(err) - } - args := strings.Split(strings.TrimSpace(string(data)), "\n") - if !slices.Contains(args, "--no-skills") { - t.Fatal("--no-skills must stay", args) - } - index := slices.Index(args, "--skill") - if skilled != (index >= 0) || (skilled && args[index+1] != client.Skills.Bundles[0].Dir) { - t.Fatalf("skilled=%v args %q", skilled, args) - } - } -} - func TestOpenCodeSkillsAttachAsSessionInstructionEntries(t *testing.T) { set := testSkillSet(t) var calls [][]string @@ -226,6 +124,8 @@ func TestOpenCodeSkillsAttachAsSessionInstructionEntries(t *testing.T) { } func TestOpenCodeAgentSkillsAttachBeforePromptAndGrantReads(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + t.Setenv("CLAUDE_CONFIG_DIR", "") client := &AgentClient{Tools: []string{"read"}} client.Directory = "/work" client.Backend = "v2" @@ -236,7 +136,7 @@ func TestOpenCodeAgentSkillsAttachBeforePromptAndGrantReads(t *testing.T) { allowed = true } if rule["action"] == "skill" && rule["effect"] == "allow" { - t.Fatal("OpenCode's own skill tool must stay denied") + t.Fatal("without operator skills OpenCode's skill tool stays denied") } } if !allowed { diff --git a/internal/stage/tools.go b/internal/stage/tools.go index 75fe5993..e935d2c3 100644 --- a/internal/stage/tools.go +++ b/internal/stage/tools.go @@ -303,6 +303,31 @@ func (c *AgentClient) permissionRules() []map[string]string { allow("external_directory", filepath.ToSlash(filepath.Join(directory, "*"))) } } + // The operator's skill folders, for their bundled files; a symlinked + // folder also by its resolved path (OpenCode checks the real file). + for _, directory := range operatorSkillDirs(openCodeSkillGroups(c.operatorSkills)) { + dirs := []string{directory} + if real, err := filepath.EvalSymlinks(directory); err == nil && real != directory { + dirs = append(dirs, real) + } + for _, d := range dirs { + if artifactDirectory(d) { + allow("external_directory", filepath.ToSlash(filepath.Join(d, "*"))) + } + } + } + } + // OpenCode discovers the operator's folder-based Claude Code skills + // (~/.claude/skills, including synced skills) itself; its skill tool may + // load exactly those, by name. Its other skill sources stay denied. + seen := map[string]bool{} + for _, group := range openCodeSkillGroups(c.operatorSkills) { + for _, skill := range group.Skills { + if !seen[skill.Name] && !strings.ContainsAny(skill.Name, "*?") { + seen[skill.Name] = true + allow("skill", skill.Name) + } + } } if writeArtifacts && artifactDirectory(c.ArtifactAccess.Write) { allow("external_directory", filepath.ToSlash(filepath.Join(c.ArtifactAccess.Write, "*"))) @@ -325,6 +350,18 @@ func (c *AgentClient) permissionRules() []map[string]string { return rules } +// openCodeSkillGroups are the operator skill groups OpenCode discovers on its +// own: personal and synced Claude Code skills, not Claude Code plugins. +func openCodeSkillGroups(groups []OperatorSkillGroup) []OperatorSkillGroup { + var kept []OperatorSkillGroup + for _, group := range groups { + if group.Plugin == OperatorSkillPlugin || group.Plugin == SyncedSkillPlugin { + kept = append(kept, group) + } + } + return kept +} + func artifactDirectory(directory string) bool { return directory != "" && filepath.IsAbs(directory) && filepath.Clean(directory) == directory && !strings.ContainsAny(directory, "*?\\") }