Skip to content
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
ddeaeca
feat(#6681): inject harness skills into agent frontmatter for always-…
fullsend-ai-coder[bot] Sep 1, 2026
89e6c6f
fix: address review feedback on PR #6859
fullsend-ai-coder[bot] Sep 1, 2026
7c0e284
fix: address review feedback on PR #6859
fullsend-ai-coder[bot] Sep 1, 2026
1b5de86
fix: block scalar false match, multi-line flow corruption, skill name…
ascerra Sep 2, 2026
4b7c78a
fix: improve error messages in frontmatter skill injection
fullsend-ai-coder[bot] Sep 2, 2026
dbffe21
fix: use uppercase BOM hex escapes to match pi_agent.go convention
fullsend-ai-coder[bot] Sep 2, 2026
a1f19db
fix: flow-style misclassification, shared isFence, CRLF handling, tem…
fullsend-ai-coder[bot] Sep 2, 2026
b95bc4d
fix: flow-comment bracket scan and YAML anchor duplication
ascerra Sep 2, 2026
addafdf
fix: handle blank lines in flow-style skills
ascerra Sep 9, 2026
7419758
fix: validate existing frontmatter skills
ascerra Sep 9, 2026
80ffc8a
fix: parse frontmatter skills with yaml nodes
ascerra Sep 10, 2026
06d59a5
Merge remote-tracking branch 'origin/main' into agent/6681-inject-fro…
ascerra Sep 10, 2026
2900ff1
fix: validate rewritten frontmatter
ascerra Sep 11, 2026
676f087
Merge remote-tracking branch 'origin/main' into agent/6681-inject-fro…
ascerra Sep 11, 2026
acdc7f8
fix: preserve merged frontmatter skills
ascerra Sep 11, 2026
de0dbbd
fix: harden frontmatter skill injection
ascerra Sep 12, 2026
7aee05d
Merge remote-tracking branch 'origin/main' into agent/6681-inject-fro…
ascerra Sep 12, 2026
1600566
fix: handle null frontmatter documents
ascerra Sep 14, 2026
73608be
Merge remote-tracking branch 'origin/main' into agent/6681-inject-fro…
ascerra Sep 14, 2026
e7bd3c2
docs: qualify skill activation claims
ascerra Sep 14, 2026
b2616c4
Merge remote-tracking branch 'origin/main' into agent/6681-inject-fro…
ascerra Sep 14, 2026
4700af5
Merge remote-tracking branch 'origin/main' into agent/6681-inject-fro…
ascerra Sep 25, 2026
1552ae4
fix: restore upload workaround and add round-trip safety check
ascerra Sep 25, 2026
e7f5ece
fix: make safety assertion fail closed on unmarshal error
ascerra Sep 25, 2026
cab47ce
fix: stop validating existing skill names in frontmatter
ascerra Sep 25, 2026
d36c1bf
Merge remote-tracking branch 'origin/main' into agent/6681-inject-fro…
ascerra Sep 25, 2026
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
26 changes: 18 additions & 8 deletions internal/runtime/claude.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,20 +48,31 @@ func (r ClaudeRuntime) Bootstrap(input BootstrapInput) error {
return fmt.Errorf("agent path is required")
}

agentData, err := os.ReadFile(agentPath)
if err != nil {
return fmt.Errorf("reading agent definition: %w", err)
}

// Validate the frontmatter name: field against the requested agent name.
// Claude Code resolves --agent by frontmatter name, not filename, so a
// mismatch means the runtime silently falls back to the default agent,
// producing an unconstrained run (#6764).
if agentName := input.AgentName(); agentName != "" {
if data, readErr := os.ReadFile(agentPath); readErr == nil {
if def, parseErr := parsePiAgent(data); parseErr != nil {
fmt.Fprintf(os.Stderr, "Agent name validation: skipped for %s: %v\n", agentPath, parseErr)
} else if err := validateAgentNameMatch(agentName, def.Name); err != nil {
return err
}
if def, parseErr := parsePiAgent(agentData); parseErr != nil {
fmt.Fprintf(os.Stderr, "Agent name validation: skipped for %s: %v\n", agentPath, parseErr)
} else if err := validateAgentNameMatch(agentName, def.Name); err != nil {
return err
}
}

// Inject harness-listed skill names into the agent frontmatter so
// the runtime loads them without requiring an explicit Skill tool
// call in the prompt body (#6681).
agentData, err = injectFrontmatterSkills(agentData, input.SkillDirs())
if err != nil {
return fmt.Errorf("injecting frontmatter skills: %w", err)
}

sandboxName := input.SandboxName()
configDir := r.ConfigDir()

Expand All @@ -73,8 +84,7 @@ func (r ClaudeRuntime) Bootstrap(input BootstrapInput) error {

agentDest := agentDestName(input.AgentName(), agentPath)

if err := sandbox.UploadFile(sandboxName, agentPath,
fmt.Sprintf("%s/agents/%s", configDir, agentDest)); err != nil {
if err := uploadBytes(sandboxName, fmt.Sprintf("%s/agents/%s", configDir, agentDest), agentData); err != nil {
Comment thread
ascerra marked this conversation as resolved.
Resolved
return fmt.Errorf("copying agent definition: %w", err)
}

Expand Down
5 changes: 3 additions & 2 deletions internal/runtime/claude_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -615,11 +615,12 @@ func TestClaudeRuntime_Bootstrap_OpenshellNotInPath(t *testing.T) {
t.Setenv("PATH", "")

agentDir := t.TempDir()
require.NoError(t, os.WriteFile(filepath.Join(agentDir, "agent.md"), []byte("test"), 0o644))
agentFile := filepath.Join(agentDir, "agent.md")
require.NoError(t, os.WriteFile(agentFile, []byte("test"), 0o644))

err := ClaudeRuntime{}.Bootstrap(bootstrapInput{
sandboxName: "test-sandbox",
agentPath: agentDir,
agentPath: agentFile,
})
assert.Error(t, err)
assert.Contains(t, err.Error(), "creating runtime config dirs")
Expand Down
259 changes: 259 additions & 0 deletions internal/runtime/frontmatter_skills.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,259 @@
package runtime

import (
"bytes"
"fmt"
"path/filepath"
"sort"
"strings"

"gopkg.in/yaml.v3"
)

// frontmatterSkills is the subset of agent YAML frontmatter used for
// skill injection. We unmarshal only the `skills` field to avoid
// disturbing any other frontmatter keys.
type frontmatterSkills struct {
Skills []string `yaml:"skills,omitempty"`
Comment thread
ascerra marked this conversation as resolved.
Resolved
}

// isFrontmatterFence reports whether line is a YAML frontmatter fence
// ("---", possibly followed by trailing whitespace or CRLF). Shared by
// parsePiAgent and injectFrontmatterSkills.
func isFrontmatterFence(line []byte) bool {
return strings.TrimRight(string(line), " \t\r\n") == "---"
}

// isValidSkillName reports whether name contains only characters safe for
// use as a bare YAML scalar: alphanumeric, hyphens, underscores, dots.
func isValidSkillName(name string) bool {
if name == "" {
return false
}
for _, c := range name {
if !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '_' || c == '.') {
return false
}
}
return true
}

// rewriteFrontmatterSkills updates the skills sequence in a parsed YAML
// document and marshals the complete frontmatter back to bytes. Using the
// YAML node tree keeps flow-style continuations, quoted keys, and spacing
// variants out of the reconstruction logic.
func rewriteFrontmatterSkills(frontBytes []byte, existing, added []string, eol string) ([]byte, error) {
var doc yaml.Node
if err := yaml.Unmarshal(frontBytes, &doc); err != nil {
return nil, fmt.Errorf("parsing frontmatter: %w", err)
}
if len(doc.Content) != 1 || doc.Content[0].Kind != yaml.MappingNode {
Comment thread
ascerra marked this conversation as resolved.
Resolved
return nil, fmt.Errorf("frontmatter must be a YAML mapping")
}

mapping := doc.Content[0]
skillsIdx := -1
for i := 0; i+1 < len(mapping.Content); i += 2 {
if mapping.Content[i].Value == "skills" {
// Keep the last occurrence to match YAML's last-key-wins behavior.
skillsIdx = i
}
}

var sequence *yaml.Node
if skillsIdx >= 0 {
value := mapping.Content[skillsIdx+1]
if value.Kind == yaml.ScalarNode && value.Tag == "!!null" {
sequence = &yaml.Node{
Kind: yaml.SequenceNode,
Tag: "!!seq",
HeadComment: value.HeadComment,
LineComment: value.LineComment,
}
mapping.Content[skillsIdx+1] = sequence
} else if value.Kind != yaml.SequenceNode {
return nil, fmt.Errorf("skills field must be a YAML list")
} else {
sequence = value
}
sequence.Style = 0 // Always emit the injected result in block form.
} else {
sequence = &yaml.Node{Kind: yaml.SequenceNode, Tag: "!!seq"}
for _, name := range existing {
sequence.Content = append(sequence.Content, &yaml.Node{
Kind: yaml.ScalarNode,
Tag: "!!str",
Value: name,
})
}
mapping.Content = append(mapping.Content,
&yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: "skills"},
sequence,
)
}

for _, name := range added {
sequence.Content = append(sequence.Content, &yaml.Node{
Kind: yaml.ScalarNode,
Tag: "!!str",
Value: name,
})
}

var marshaledBuffer bytes.Buffer
encoder := yaml.NewEncoder(&marshaledBuffer)
encoder.SetIndent(2)
err := encoder.Encode(&doc)
closeErr := encoder.Close()
if err != nil {
return nil, fmt.Errorf("marshaling frontmatter: %w", err)
}
if closeErr != nil {
return nil, fmt.Errorf("closing frontmatter encoder: %w", closeErr)
}
marshaled := marshaledBuffer.Bytes()
if eol == "\r\n" {
marshaled = bytes.ReplaceAll(marshaled, []byte("\n"), []byte("\r\n"))
}
var validated yaml.Node
if err := yaml.Unmarshal(marshaled, &validated); err != nil {
return nil, fmt.Errorf("validating rewritten frontmatter: %w", err)
}
return marshaled, nil
}

// injectFrontmatterSkills adds skill names derived from skillDirs into the
// agent definition's YAML frontmatter `skills:` section. Existing entries
// are preserved; new names are appended with deduplication by basename.
// If the agent has no frontmatter, one is created. If skillDirs is empty,
// the data is returned unchanged.
//
// This ensures harness-listed skills reliably activate: Claude Code loads
// skills listed in the agent frontmatter without requiring an explicit
// Skill tool call in the prompt body.
func injectFrontmatterSkills(data []byte, skillDirs []string) ([]byte, error) {
if len(skillDirs) == 0 {
return data, nil
}

// Collect basenames from skill directories — these are the names
// the runtime uses to identify skills in the sandbox.
seen := make(map[string]bool, len(skillDirs))
newNames := make([]string, 0, len(skillDirs))
for _, d := range skillDirs {
if d == "" {
continue
}
name := filepath.Base(d)
if !isValidSkillName(name) {
Comment thread
ascerra marked this conversation as resolved.
Resolved
return nil, fmt.Errorf("invalid skill name %q from %q: must match [a-zA-Z0-9._-]+", name, d)
}
if seen[name] {
continue
}
Comment thread
ascerra marked this conversation as resolved.
Resolved
seen[name] = true
newNames = append(newNames, name)
}
if len(newNames) == 0 {
return data, nil
}
sort.Strings(newNames)

content := bytes.TrimPrefix(data, []byte("\xEF\xBB\xBF"))

// Detect line ending style so injected lines match existing content.
eol := "\n"
if bytes.Contains(content, []byte("\r\n")) {
eol = "\r\n"
}

// Check for existing frontmatter.
lines := bytes.SplitAfter(content, []byte("\n"))
if bytes.HasPrefix(content, []byte("---")) && !isFrontmatterFence(lines[0]) {
return nil, fmt.Errorf("agent definition: first line starts with --- but is not a frontmatter fence: %q", strings.TrimRight(string(lines[0]), "\r\n"))
}

hasFrontmatter := len(lines) > 0 && isFrontmatterFence(lines[0])

if !hasFrontmatter {
Comment thread
ascerra marked this conversation as resolved.
Resolved
// No frontmatter — create one with just the skills list.
var buf bytes.Buffer
fmt.Fprintf(&buf, "---%s", eol)
fmt.Fprintf(&buf, "skills:%s", eol)
for _, name := range newNames {
fmt.Fprintf(&buf, " - %s%s", name, eol)
Comment thread
ascerra marked this conversation as resolved.
Resolved
}
fmt.Fprintf(&buf, "---%s", eol)
buf.Write(content)
return buf.Bytes(), nil
Comment thread
ascerra marked this conversation as resolved.
Resolved
}

// Find the closing fence.
var frontBytes []byte
closingIdx := -1
for i := 1; i < len(lines); i++ {
if isFrontmatterFence(lines[i]) {
frontBytes = bytes.Join(lines[1:i], nil)
closingIdx = i
break
}
}
if closingIdx < 0 {
Comment thread
ascerra marked this conversation as resolved.
Resolved
return nil, fmt.Errorf("unterminated frontmatter")
}

// Parse existing skills from frontmatter.
Comment thread
ascerra marked this conversation as resolved.
Resolved
var fm frontmatterSkills
if err := yaml.Unmarshal(frontBytes, &fm); err != nil {
// When the skills field has an unexpected type (e.g., scalar
// string instead of a list), produce a more specific message.
var probe struct {
Skills interface{} `yaml:"skills"`
}
if yaml.Unmarshal(frontBytes, &probe) == nil && probe.Skills != nil {
if _, isList := probe.Skills.([]interface{}); !isList {
return nil, fmt.Errorf("skills field must be a YAML list: %w", err)
}
}
return nil, fmt.Errorf("parsing frontmatter: %w", err)
}

// Deduplicate: build a set of existing skill names.
existing := make(map[string]bool, len(fm.Skills))
for _, s := range fm.Skills {
if !isValidSkillName(s) {
return nil, fmt.Errorf("invalid existing skill name %q: must match [a-zA-Z0-9._-]+", s)
}
existing[s] = true
}

Comment thread
ascerra marked this conversation as resolved.
Resolved
// Append only new names that are not already present.
added := make([]string, 0, len(newNames))
for _, name := range newNames {
if !existing[name] {
existing[name] = true
Comment thread
ascerra marked this conversation as resolved.
Resolved
added = append(added, name)
}
}

if len(added) == 0 {
Comment thread
ascerra marked this conversation as resolved.
Resolved
// All skills already present — return BOM-stripped content for consistency
// with the injection path (which always operates on BOM-stripped data).
return content, nil
}

updatedFrontmatter, err := rewriteFrontmatterSkills(frontBytes, fm.Skills, added, eol)
if err != nil {
return nil, err
}
var result bytes.Buffer
result.Write(lines[0])
result.Write(updatedFrontmatter)

// Write the closing fence and everything after it.
for i := closingIdx; i < len(lines); i++ {
result.Write(lines[i])
}

return result.Bytes(), nil
}
Loading
Loading