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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions actions/setup/sh/base_github_folders_test.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,23 @@ test("save: external skill targets are materialized; internal links and modes su
assert.equal(execution.stdout.trim(), "ok");
});

test("save: materializes skills linked outside agent folders before PR checkout", t => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[/tdd] This test drives only save_base_github_folders.sh, and this PR does not change that script. It would also pass against the base commit, so it does not guard the Go checkout change. The Go test TestActivationSnapshotCheckoutIncludesSymlinkTargets is the real regression test.

💡 Suggested fix

Remove this test, or rename it so it reads as a save-script behavior spec and does not claim to cover checkout ordering.

@copilot please address this.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in e618556: the shell test is named as a save-and-restore behavior test; checkout regression coverage remains in the Go test.

const f = fixture(t);
f.write("skills/mui-renovate-fix/SKILL.md", "trusted base skill");
fs.mkdirSync(path.join(f.workspace, ".agents/skills"), { recursive: true });
f.link(".agents/skills/mui-renovate-fix", "../../skills/mui-renovate-fix");
fs.mkdirSync(path.join(f.workspace, ".claude/skills"), { recursive: true });
f.link(".claude/skills/mui-renovate-fix", "../../.agents/skills/mui-renovate-fix");
f.run("save");
f.write("skills/mui-renovate-fix/SKILL.md", "untrusted PR skill");
f.run("restore");
for (const folder of [".agents", ".claude"]) {
const skill = `${folder}/skills/mui-renovate-fix`;
assert.equal(f.read(`${skill}/SKILL.md`), "trusted base skill");
assert.equal(fs.lstatSync(path.join(f.workspace, skill)).isSymbolicLink(), false);
}
});

test("save: invalid candidates fail closed in both lists", t => {
const f = fixture(t);
for (const item of ["../sentinel", "/etc/passwd", ".", "..", ".github//skills", ".github/../sentinel", "--checkpoint-action=exec=echo"]) {
Expand Down
2 changes: 1 addition & 1 deletion docs/src/content/docs/reference/checkout.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ The `checkout:` frontmatter field controls how `actions/checkout` runs in the ag

By default, the agent checks out the workflow's repository with a shallow fetch (`fetch-depth: 1`). On `pull_request` events it also checks out the PR's selected commit (see [PR Revision Binding](#pr-revision-binding)). On `pull_request_target` events, automatic PR checkout is **disabled by default**, and `pull-request-floating-head` does not enable it. Most workflows need no `checkout:` configuration.

Activation separately checks out workflow configuration to load runtime imports and skills. On `pull_request`, `pull_request_review`, and `pull_request_review_comment` events, this sparse checkout uses the PR **base SHA**. On other events it uses the normal activation ref. `checkout:` options do not override this activation checkout. For reusable `workflow_call` workflows, it uses the resolved callee SHA when no PR event is active, and skips cross-repository checkout if authentication may fall back to the caller's `GITHUB_TOKEN`.
Activation separately checks out workflow configuration to load runtime imports and skills. When it saves a trusted base configuration snapshot, it uses a full, shallow checkout so symlink targets anywhere in the repository are available; otherwise it uses a sparse checkout. On `pull_request`, `pull_request_review`, and `pull_request_review_comment` events, this checkout uses the PR **base SHA**. On other events it uses the normal activation ref. `checkout:` options do not override this activation checkout. For reusable `workflow_call` workflows, it uses the resolved callee SHA when no PR event is active, and skips cross-repository checkout if authentication may fall back to the caller's `GITHUB_TOKEN`.

Use `checkout:` to check out additional branches or repositories, or set `checkout: false` for workflows that access code only through GitHub tools.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -189,13 +189,13 @@ silently turn a single entry into a repository list:

### 3.3 Job-specific Checkout Generation

- **Activation job** MUST use sparse checkout for `.github` and `.agents`, with `persist-credentials: false`.
- **Activation job** MUST use a full, shallow checkout when saving a trusted base configuration snapshot, so symlink targets elsewhere in the repository are available. Otherwise it MUST use sparse checkout for `.github` and `.agents`. Both use `persist-credentials: false`.
- **Agent job** MUST generate default checkout plus additional checkouts from `CheckoutManager`, with `persist-credentials: false` by default.
- **safe_outputs job** MUST reuse the same checkout generators but set keep-credentials mode for push/fetch use and inject a `Configure Git credentials` step.

For activation checkouts, the compiler MUST select `github.event.pull_request.base.sha` when the active event is `pull_request`, `pull_request_review`, or `pull_request_review_comment`, provided the pull-request payload exists. The expression MUST guard access to the pull-request payload by event name and nullability. Trigger detection MUST match exact names: `pull_request_target` alone MUST NOT enable this pin. On other events, including non-PR events in a mixed-trigger workflow, checkout MUST retain its existing ref (`github.sha` for the standard activation checkout or the resolved callee checkout SHA for `workflow_call`). This checkout occurs before runtime imports and skills are loaded; restoring agent configuration after the PR checkout is not a substitute for pinning activation.

For cross-repository `workflow_call`, activation MUST retain the same-repository checkout condition whenever its token can resolve to the repository-scoped `GITHUB_TOKEN`, including the `on.github-app.ignore-if-missing` fallback. A missing optional App credential MUST NOT cause a cross-repository sparse checkout attempt with `GITHUB_TOKEN`.
For cross-repository `workflow_call`, activation MUST retain the same-repository checkout condition whenever its token can resolve to the repository-scoped `GITHUB_TOKEN`, including the `on.github-app.ignore-if-missing` fallback. A missing optional App credential MUST NOT cause a cross-repository checkout attempt with `GITHUB_TOKEN`.

### 3.4 Checkout Manifest

Expand Down
24 changes: 17 additions & 7 deletions pkg/workflow/checkout_step_generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -251,10 +251,18 @@ func (cm *CheckoutManager) checkoutManifestEntries() ([]checkoutManifestEntry, [
//
// Returns a slice of YAML lines (each ending with \n).
func (cm *CheckoutManager) GenerateGitHubFolderCheckoutStep(repository, ref, token string, getActionPin func(string) string, extraPaths ...string) []string {
return cm.generateActivationCheckoutStep(repository, ref, token, getActionPin, false, extraPaths...)
}

func (cm *CheckoutManager) generateActivationCheckoutStep(repository, ref, token string, getActionPin func(string) string, fullCheckout bool, extraPaths ...string) []string {
checkoutManagerLog.Printf("Generating .github/.agents folder checkout: repository=%q ref=%q", repository, ref)
var sb strings.Builder

sb.WriteString(" - name: Checkout .github and .agents folders\n")
if fullCheckout {
sb.WriteString(" - name: Checkout repository for base branch snapshot\n")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in e618556: the activation checkout has a distinct name. The pre-step and checkout optimization tests pass.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[/diagnosing-bugs] This PR changes compiler output for every activation job, but none of the 370 committed .lock.yml files are regenerated. Compiling ab-testing-advisor.md on this head rewrites its lock: the step name changes and the sparse-checkout block is removed. CI check-workflow-drift will fail on push to main until make recompile is run and the locks are committed.

💡 Verification

I compiled all workflows on this head and 370 tracked lock files changed. The PR touches no lock files, so the stored output is stale.

@copilot please address this.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Regenerated in e618556 and verified again after merging main in c1e1ce84. Full package validation is currently blocked by npm registry DNS; compilation without that external validation succeeded.

} else {
sb.WriteString(" - name: Checkout .github and .agents folders\n")
}
fmt.Fprintf(&sb, " uses: %s\n", getActionPin("actions/checkout"))
sb.WriteString(" with:\n")
sb.WriteString(" persist-credentials: false\n")
Expand All @@ -267,13 +275,15 @@ func (cm *CheckoutManager) GenerateGitHubFolderCheckoutStep(repository, ref, tok
if token != "" && token != "${{ secrets.GITHUB_TOKEN }}" {
fmt.Fprintf(&sb, " token: %s\n", token)
}
sb.WriteString(" sparse-checkout: |\n")
sb.WriteString(" .github\n")
sb.WriteString(" .agents\n")
for _, p := range extraPaths {
fmt.Fprintf(&sb, " %s\n", p)
if !fullCheckout {
sb.WriteString(" sparse-checkout: |\n")
sb.WriteString(" .github\n")
sb.WriteString(" .agents\n")
for _, p := range extraPaths {
fmt.Fprintf(&sb, " %s\n", p)
}
sb.WriteString(" sparse-checkout-cone-mode: true\n")
}
sb.WriteString(" sparse-checkout-cone-mode: true\n")
sb.WriteString(" fetch-depth: 1\n")

return []string{sb.String()}
Expand Down
24 changes: 8 additions & 16 deletions pkg/workflow/compiler_activation_checkout_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package workflow
import (
"os"
"path/filepath"
"strings"
"testing"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -65,8 +66,8 @@ strict: false
// validateDangerousPermissions), but safe-outputs such as create-pull-request require
// contents: write in their own downstream job. This case verifies that even when the
// workflow needs write-capable safe-outputs, the activation job itself still only
// performs the sparse .github checkout - it never checks out the full repository.
name: "workflow with write-capable safe-outputs still has no full checkout in activation",
// uses a read-only activation checkout.
name: "workflow with write-capable safe-outputs uses read-only activation checkout",
frontmatter: `---
on:
issues:
Expand Down Expand Up @@ -113,20 +114,11 @@ safe-outputs:
activationJobSection := extractJobSection(lockContentStr, "activation")
require.NotEmpty(t, activationJobSection, "Activation job section should not be empty")

// The activation job always sparse-checks-out .github/.agents (and, in dev mode,
// actions/setup) so it can load helper scripts and engine config - this is
// unaffected by the workflow's permissions or triggers (including contents: write,
// via write-capable safe-outputs). What must never happen is a full checkout of
// the repository, or a checkout of .github/workflows for timestamp checking -
// that always uses the GitHub API instead.

// Verify the activation checkout is the sparse .github/.agents checkout
assert.Contains(t, activationJobSection, "name: Checkout .github and .agents folders", "Should use the sparse .github/.agents checkout step")
assert.Contains(t, activationJobSection, "sparse-checkout: |", "Sparse checkout should be configured")
assert.Contains(t, activationJobSection, "sparse-checkout-cone-mode: true", "Sparse checkout cone mode should be enabled")

// Verify it does NOT perform a full repository checkout
assert.NotContains(t, activationJobSection, "name: Checkout repository", "Should not have a full repository checkout step")
// The trusted snapshot needs the complete base tree to resolve symlink targets.
require.Contains(t, activationJobSection, "name: Checkout repository for base branch snapshot")
checkout := strings.SplitN(strings.SplitN(activationJobSection, "name: Checkout repository for base branch snapshot", 2)[1], "\n - name:", 2)[0]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[/tdd] Splitting the job text on the step-name marker and the next - name: depends on exact YAML indentation and step order. A reformat or an extra step breaks this assertion even without a real regression.

Parse the activation job YAML and select the step by its name instead.

@copilot please address this.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in e618556: the test parses the workflow YAML and selects the activation step by name.

assert.NotContains(t, checkout, "sparse-checkout:")
assert.Contains(t, checkout, "persist-credentials: false")

// Verify it does NOT checkout .github/workflows for timestamp checking
assert.NotContains(t, activationJobSection, "Checkout workflows", "Should not have 'Checkout workflows' step - uses GitHub API for timestamp checking")
Expand Down
20 changes: 9 additions & 11 deletions pkg/workflow/compiler_activation_job.go
Original file line number Diff line number Diff line change
Expand Up @@ -386,12 +386,12 @@ func (c *Compiler) generateResolveHostRepoStep(data *WorkflowData) string {
return step.String()
}

// generateCheckoutGitHubFolderForActivation generates the checkout step for .github and .agents folders
// specifically for the activation job. Unlike generateCheckoutGitHubFolder, this method doesn't skip
// generateCheckoutGitHubFolderForActivation generates the activation checkout.
// Unlike generateCheckoutGitHubFolder, this method doesn't skip
// the checkout when the agent job will have a full repository checkout, because the activation job
// runs before the agent job and needs independent access to workflow files for runtime imports during
// prompt generation.
func (c *Compiler) generateCheckoutGitHubFolderForActivation(data *WorkflowData) []string {
func (c *Compiler) generateCheckoutGitHubFolderForActivation(data *WorkflowData, fullCheckout bool) []string {
// Check if action-tag is specified - if so, skip checkout
if activationCheckoutDisabledByActionTag(data) {
compilerActivationJobLog.Print("Skipping .github checkout in activation: action-tag specified")
Expand Down Expand Up @@ -426,11 +426,12 @@ func (c *Compiler) generateCheckoutGitHubFolderForActivation(data *WorkflowData)
} else if prCheckoutRef := activationCheckoutRef(data, "steps.resolve-host-repo.outputs.target_checkout_ref"); prCheckoutRef != "" {
checkoutRef = prCheckoutRef
}
checkoutSteps := cm.GenerateGitHubFolderCheckoutStep(
checkoutSteps := cm.generateActivationCheckoutStep(
cm.GetCrossRepoTargetRepo(),
checkoutRef,
activationToken,
c.getActionPin,
fullCheckout,
extraPaths...,
)
// When no custom token is configured, GITHUB_TOKEN is scoped to the calling
Expand All @@ -446,19 +447,16 @@ func (c *Compiler) generateCheckoutGitHubFolderForActivation(data *WorkflowData)
return checkoutSteps
}

// For activation job, sparse checkout .github, .agents, and engine-specific config directories
// (plus actions/setup in dev mode). Root instruction files are excluded as they are not needed
// during activation. sparse-checkout-cone-mode: true ensures subdirectories are recursively included.
compilerActivationJobLog.Print("Adding .github, .agents, and engine-specific dirs to sparse checkout for activation job")
return cm.GenerateGitHubFolderCheckoutStep("", activationCheckoutRef(data, "github.sha"), activationToken, c.getActionPin, extraPaths...)
compilerActivationJobLog.Printf("Adding activation checkout: full=%t", fullCheckout)
return cm.generateActivationCheckoutStep("", activationCheckoutRef(data, "github.sha"), activationToken, c.getActionPin, fullCheckout, extraPaths...)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[/codebase-design] resolveSymlinkExtraPaths still scans only .github/agents, .github/skills, and .github/prompts. The sparse path (saveBase == false) therefore still misses symlink targets outside those folders, such as per-skill links inside a real .agents/skills/ tree. The new comment says symlink targets must be fetched, but this branch does not do that.

💡 Suggested fix

Either route symlink-bearing configs through the full checkout, or extend the scan to every symlink under the sparse-checked folders. If activation never reads those targets on this path, document that in the comment.

@copilot please address this.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in e618556: sparse checkout scans nested symlinks in configuration and extra paths, with repository confinement and regression coverage.

}

func needsActivationHostRepoCheckout(data *WorkflowData) bool {
return data != nil && hasWorkflowCallTrigger(data.On) && (!data.InlinedImports || (data.EngineConfig != nil && data.EngineConfig.CopilotSDK))
}

// activationCheckoutDisabledByActionTag reports whether action-tag supplies setup
// assets outside the workspace, making the activation sparse checkout unnecessary.
// assets outside the workspace, making the activation checkout unnecessary.
func activationCheckoutDisabledByActionTag(data *WorkflowData) bool {
if data == nil || data.Features == nil {
return false
Expand Down Expand Up @@ -506,7 +504,7 @@ func (c *Compiler) activationSparseCheckoutExtraPaths(data *WorkflowData) []stri
return resolveSymlinkExtraPaths(repoRoot, extraPaths)
}

// activationCheckoutRef returns the ref expression for activation sparse checkout.
// activationCheckoutRef returns the ref expression for activation checkout.
// It returns an empty string when the workflow has no pull-request event whose payload
// includes a pull request. fallbackExpression must be a raw GitHub Actions expression
// without a ${{ }} wrapper.
Expand Down
53 changes: 45 additions & 8 deletions pkg/workflow/compiler_activation_job_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,43 @@ func TestClaudeWorkflowsNotSavedWhenDynamicWorkflowsDisabled(t *testing.T) {
assert.NotContains(t, strings.Join(job.Steps, ""), "Save agent config folders for base branch restoration")
}

func TestActivationSnapshotCheckoutIncludesSymlinkTargets(t *testing.T) {
disabled := false
for _, tt := range []struct {
name string
data *WorkflowData
wantFull bool
wantRepoRef bool
}{
{name: "default snapshot", data: &WorkflowData{Name: "test", AI: "claude"}, wantFull: true},
{name: "no snapshot", data: &WorkflowData{Name: "test", AI: "claude", CheckoutConfigs: []*CheckoutConfig{{PullRequest: &disabled}}, EngineConfig: &EngineConfig{ID: "claude", DynamicWorkflows: &disabled}}},
{name: "reusable workflow", data: &WorkflowData{Name: "test", AI: "claude", On: `"on":
workflow_call:`}, wantFull: true, wantRepoRef: true},
} {
t.Run(tt.name, func(t *testing.T) {
job, err := NewCompiler().buildActivationJob(tt.data, false, "", "test.lock.yml")
require.NoError(t, err)
steps := strings.Join(job.Steps, "")
if tt.wantFull {
checkout := extractWorkflowStepByName(t, steps, "Checkout repository for base branch snapshot")
assert.NotContains(t, checkout, "sparse-checkout:")
assert.Contains(t, checkout, "persist-credentials: false")
assert.Contains(t, checkout, "fetch-depth: 1")
assert.Less(t, strings.Index(steps, checkout), strings.Index(steps, "Save agent config folders for base branch restoration"))
if tt.wantRepoRef {
assert.Contains(t, checkout, "repository: "+workflowCallRepo)
assert.Contains(t, checkout, "ref: "+workflowCallRef)
assert.Contains(t, checkout, sameRepoCondition)
}
} else {
checkout := extractWorkflowStepByName(t, steps, "Checkout .github and .agents folders")
assert.Contains(t, checkout, "sparse-checkout:")
assert.NotContains(t, steps, "Save agent config folders for base branch restoration")
}
})
}
}

func TestCopilotDynamicWorkflowsSnapshotWithPRCheckoutDisabled(t *testing.T) {
enabled, disabled := true, false
for _, tt := range []struct {
Expand Down Expand Up @@ -360,7 +397,7 @@ func TestGenerateCheckoutGitHubFolderForActivation_WorkflowCall(t *testing.T) {
InlinedImports: tt.inlinedImports,
}

result := c.generateCheckoutGitHubFolderForActivation(data)
result := c.generateCheckoutGitHubFolderForActivation(data, false)

if tt.wantNil {
assert.Nil(t, result, "expected nil checkout steps for action-tag case")
Expand Down Expand Up @@ -517,7 +554,7 @@ func TestCheckoutDoesNotUseEventNameExpression(t *testing.T) {
workflow_call:`,
}

result := c.generateCheckoutGitHubFolderForActivation(data)
result := c.generateCheckoutGitHubFolderForActivation(data, false)
combined := strings.Join(result, "")

// Must use the step output, not the broken expression
Expand Down Expand Up @@ -843,7 +880,7 @@ func TestActivationJobTargetRefIsDispatchCompatible(t *testing.T) {
"target_checkout_ref should be the immutable SHA for checkout pinning")

// The checkout step itself must use target_checkout_ref (SHA), not target_ref
checkoutSteps := compiler.generateCheckoutGitHubFolderForActivation(data)
checkoutSteps := compiler.generateCheckoutGitHubFolderForActivation(data, false)
combined := strings.Join(checkoutSteps, "")
assert.Contains(t, combined, "ref: ${{ steps.resolve-host-repo.outputs.target_checkout_ref }}",
"activation checkout must use target_checkout_ref (SHA) for exact-revision pinning")
Expand Down Expand Up @@ -973,7 +1010,7 @@ func TestCheckoutGitHubFolderIncludesRef(t *testing.T) {
InlinedImports: tt.inlinedImports,
}

result := c.generateCheckoutGitHubFolderForActivation(data)
result := c.generateCheckoutGitHubFolderForActivation(data, false)
combined := strings.Join(result, "")

if tt.wantRef {
Expand Down Expand Up @@ -1030,7 +1067,7 @@ func TestGenerateCheckoutGitHubFolderForActivation_ActionsModeSetupPath(t *testi
types: [opened]`,
}

result := c.generateCheckoutGitHubFolderForActivation(data)
result := c.generateCheckoutGitHubFolderForActivation(data, false)
require.NotNil(t, result, "should return checkout steps")
combined := strings.Join(result, "")

Expand Down Expand Up @@ -1060,7 +1097,7 @@ func TestGenerateCheckoutGitHubFolderForActivation_LocalSkillSparseCheckout(t *t
},
}

steps := c.generateCheckoutGitHubFolderForActivation(data)
steps := c.generateCheckoutGitHubFolderForActivation(data, false)
combined := strings.Join(steps, "")

assert.Contains(t, combined, "\n skills\n", "local skill dirs outside .github/.agents should be included in sparse checkout")
Expand Down Expand Up @@ -1191,7 +1228,7 @@ func TestCheckoutTokenPropagatedToActivation(t *testing.T) {
ActivationGitHubToken: tt.activationToken,
}

result := c.generateCheckoutGitHubFolderForActivation(data)
result := c.generateCheckoutGitHubFolderForActivation(data, false)
combined := strings.Join(result, "")

if tt.wantTokenInStep {
Expand Down Expand Up @@ -1280,7 +1317,7 @@ func TestCheckoutSameRepoGuardWithCustomToken(t *testing.T) {
ActivationGitHubApp: tt.activationApp,
}

result := c.generateCheckoutGitHubFolderForActivation(data)
result := c.generateCheckoutGitHubFolderForActivation(data, false)
combined := strings.Join(result, "")

if tt.wantSameRepoCondition {
Expand Down
Loading
Loading