Skip to content
10 changes: 10 additions & 0 deletions .github/workflows/daily-cli-performance.lock.yml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

32 changes: 32 additions & 0 deletions pkg/workflow/compiler_pre_activation_job.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ func (c *Compiler) buildPreActivationJob(data *WorkflowData, needsPermissionChec
steps = c.buildPreActivationSkipIfQuerySteps(data, steps, skipIfToken)
steps = c.buildPreActivationSkipIfCheckFailingStep(data, steps)
steps = c.buildPreActivationRolesBotsCmdSteps(data, steps)
steps = c.buildPreActivationMemoryRestoreSteps(data, steps)
steps, onStepIDs, err := c.injectPreActivationOnSteps(data, steps, customSteps)
if err != nil {
return nil, err
Expand Down Expand Up @@ -230,6 +231,37 @@ func (c *Compiler) buildPreActivationRolesBotsCmdSteps(data *WorkflowData, steps
return steps
}

// buildPreActivationMemoryRestoreSteps restores memory stores before on.steps run in pre-activation.
// This is a read-only surface: it restores/loads memory data but does not emit write-back or commit steps.
func (c *Compiler) buildPreActivationMemoryRestoreSteps(data *WorkflowData, steps []string) []string {
if len(data.OnSteps) == 0 {
return steps
}

var memorySteps strings.Builder

generateCacheMemorySteps(&memorySteps, data)

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] generateCacheMemorySteps is not purely read-only β€” when cache.RestoreOnly is false and threat detection is disabled, it emits actions/cache (not actions/cache/restore), which auto-saves via its post-action. This violates the stated read-only contract for pre-activation.

πŸ’‘ Suggested fix

Force restore-only when calling from the pre-activation context. Options:

  1. Add a dedicated generateCacheMemoryRestoreOnlySteps that always uses actions/cache/restore.
  2. Temporarily override each cache entry with RestoreOnly: true before delegating to generateCacheMemorySteps.

The test should also assert that actions/cache/restore (not actions/cache) appears in the pre_activation section to catch a regression here.

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

Bug: generateCacheMemorySteps may emit actions/cache (not actions/cache/restore) in pre-activation, breaking the read-only guarantee.

generateCacheMemorySteps selects between actions/cache and actions/cache/restore based on cache.RestoreOnly || IsDetectionJobEnabled(data.SafeOutputs) (see cache.go:568-569). When neither flag is set (the common case), it emits actions/cache, whose post-action hook auto-saves the cache at job end. Calling this function from buildPreActivationMemoryRestoreSteps therefore silently writes back the cache at the end of every pre_activation run β€” directly contradicting the comment on line 235 ("This is a read-only surface: it restores/loads memory data but does not emit write-back or commit steps").

This can corrupt the cache for the actual agent job (a pre-activation run that fails mid-step still saves a partial/stale cache) and wastes cache quota.

Suggested fix: Set cache.RestoreOnly = true on a shallow copy of each CacheMemoryEntry before delegating to generateCacheMemorySteps, or extract a dedicated generateCacheMemoryRestoreOnlySteps helper that always passes actions/cache/restore.

@copilot please address this.

generateRepoMemorySteps(&memorySteps, data)

if data.SafeOutputs != nil && data.SafeOutputs.CommentMemory != nil {
memorySteps.WriteString(" - name: Prepare comment memory files\n")
fmt.Fprintf(&memorySteps, " uses: %s\n", getCachedActionPin("actions/github-script", data))
memorySteps.WriteString(" with:\n")
fmt.Fprintf(&memorySteps, " github-token: %s\n", getEffectiveSafeOutputGitHubToken(data.SafeOutputs.CommentMemory.GitHubToken))
memorySteps.WriteString(" script: |\n")
memorySteps.WriteString(" const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs');\n")
memorySteps.WriteString(" setupGlobals(core, github, context, exec, io, getOctokit);\n")
memorySteps.WriteString(" const { main } = require('${{ runner.temp }}/gh-aw/actions/setup_comment_memory_files.cjs');\n")
memorySteps.WriteString(" await main();\n")
}

if memorySteps.Len() > 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.

[/codebase-design] All three memory types are accumulated into a single strings.Builder and then appended as one YAML block. If generateCacheMemorySteps or generateRepoMemorySteps emits content but the comment-memory block does not, the final append fires correctly β€” but if only comment-memory is configured (no cache/repo), this function silently skips even the comment-memory step because the Len() > 0 guard only fires if something was written. Wait β€” that is actually fine since comment-memory is written directly before the guard. But the design couples three independent memory types through a single builder with no per-type gating, making it harder to conditionally suppress one type later. Minor design note, not blocking.

πŸ’‘ Suggestion

Consider appending each memory type as a separate steps element (consistent with how other buildPreActivation* helpers work), so each is independently optional and individually traceable in the step list.

@copilot please address this.

steps = append(steps, memorySteps.String())

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.

Maintainability: entire multi-step content appended as one slice element, inconsistent with the rest of the codebase.

All other step-building helpers in this file (e.g., appendPreActivationSkipRolesStep, appendPreActivationSkipIfMatchStep) append each YAML line or logical step as an individual string entry in the []string slice. Here, all three memory sources are flushed into a single strings.Builder and appended as one large blob (line 259). The renderer at jobs.go:391-394 iterates over elements and writes each one verbatim, so the output is correct, but the deviation from convention makes the slice element count misleading (e.g., len(job.Steps) understates the actual step count logged in jobs.go:207).

Suggested fix: Follow the existing pattern β€” call helpers directly on the steps slice (or append each resulting block separately). This keeps len(job.Steps) accurate and makes ordering logic transparent.

@copilot please address this.

}

return steps
}

func (c *Compiler) appendPreActivationSkipRolesStep(data *WorkflowData, steps []string) []string {
steps = append(steps, " - name: Check skip-roles\n")
steps = append(steps, fmt.Sprintf(" id: %s\n", constants.CheckSkipRolesStepID))
Expand Down
79 changes: 79 additions & 0 deletions pkg/workflow/on_steps_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,85 @@ Test on.steps are appended after built-in checks
t.Error("Expected membership check step to appear before on.steps gate step in pre_activation job")
}
})

t.Run("on_steps_with_memory_stores_restored_in_pre_activation", func(t *testing.T) {
workflowContent := `---
on:
workflow_dispatch: null
roles: all
steps:
- name: Gate check
id: gate
run: echo "checking..."
tools:
cache-memory: true
repo-memory: true
comment-memory: true
engine: copilot
---

Test on.steps with memory stores restored in pre-activation
`
workflowFile := filepath.Join(tmpDir, "test-on-steps-memory-pre-activation.md")
if err := os.WriteFile(workflowFile, []byte(workflowContent), 0644); err != nil {
t.Fatal(err)
}

err := compiler.CompileWorkflow(workflowFile)
if err != nil {
t.Fatalf("CompileWorkflow() returned error: %v", err)
}

lockFile := stringutil.MarkdownToLockFile(workflowFile)
lockContent, err := os.ReadFile(lockFile)
if err != nil {
t.Fatalf("Failed to read lock file: %v", err)
}
lockContentStr := string(lockContent)
var preActivationSectionBuilder strings.Builder
inPreActivation := false
for line := range strings.SplitSeq(lockContentStr, "\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.

[/tdd] The pre_activation section extractor parses YAML by indentation heuristic rather than by a known job terminator. The termination condition (HasPrefix(" ") && !HasPrefix(" ") && HasSuffix(":")) will silently miss the end of the section if the next sibling job has a name that doesn't end in : at exactly 2-space indentation (e.g. if YAML comment lines or flow-style keys appear between jobs). This fragility could cause the section to grow beyond pre_activation and produce false-positive assertions.

πŸ’‘ Consider a more robust extractor

Use a known sibling job name to bound the search, or parse the full YAML with gopkg.in/yaml.v3 and extract the jobs map directly. A simpler short-term fix is to assert on the first occurrence of a known post-pre-activation job ID (e.g. agent: or push_repo_memory:) as the terminator.

@copilot please address this.

if strings.HasPrefix(line, " pre_activation:") {
inPreActivation = true
}
if inPreActivation {
// Next top-level job (2 spaces, not deeper indentation) ends pre_activation section.
if strings.HasPrefix(line, " ") &&
!strings.HasPrefix(line, " ") &&
strings.HasSuffix(line, ":") &&
!strings.HasPrefix(line, " pre_activation:") {
break
}
preActivationSectionBuilder.WriteString(line)
preActivationSectionBuilder.WriteByte('\n')
}
}
preActivationSection := preActivationSectionBuilder.String()
if preActivationSection == "" {
t.Fatalf("Expected pre_activation section in lock file. Lock file:\n%s", lockContentStr)
}

// Memory stores should be restored before on.steps run in pre-activation.
assert.Contains(t, preActivationSection, "Restore cache-memory file share data")
assert.Contains(t, preActivationSection, "Clone repo-memory branch (default)")
assert.Contains(t, preActivationSection, "Prepare comment memory files")
assert.Contains(t, preActivationSection, " id: gate")
Comment on lines +289 to +293

cacheRestoreIdx := strings.Index(preActivationSection, "Restore cache-memory file share data")
repoRestoreIdx := strings.Index(preActivationSection, "Clone repo-memory branch (default)")
commentMemoryIdx := strings.Index(preActivationSection, "Prepare comment memory files")
gateStepIdx := strings.Index(preActivationSection, " id: gate")
if cacheRestoreIdx == -1 || repoRestoreIdx == -1 || commentMemoryIdx == -1 || gateStepIdx == -1 {
t.Fatalf("Expected memory restore steps and gate step in pre_activation section. Section:\n%s", preActivationSection)
}
assert.Less(t, cacheRestoreIdx, gateStepIdx, "cache-memory should be restored before on.steps")
assert.Less(t, repoRestoreIdx, gateStepIdx, "repo-memory should be restored before on.steps")
assert.Less(t, commentMemoryIdx, gateStepIdx, "comment-memory should be restored before on.steps")

// Pre-activation must not include write-back/commit steps.
assert.NotContains(t, preActivationSection, "Commit cache-memory changes")

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] The write-back absence checks (NotContains) are named after the post-agent job steps ("Commit cache-memory changes", "Push repo-memory changes") β€” but the real silent write risk in pre-activation is actions/cache (not actions/cache/restore) auto-saving on its post-action. These two step-name checks would pass even if the wrong cache action were used.

πŸ’‘ Add the missing assertion
// Verify cache action is restore-only (not auto-saving)
assert.NotContains(t, preActivationSection, "actions/cache@",
    "pre_activation should use actions/cache/restore, not actions/cache")
assert.Contains(t, preActivationSection, "actions/cache/restore@",
    "pre_activation cache step should be restore-only")

This directly tests the read-only property the PR description promises.

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

Missing test coverage: no case exercises the actions/cache vs actions/cache/restore selection in pre-activation.

The test asserts that write-back steps (Commit cache-memory changes, Push repo-memory changes) are absent from pre_activation, but it does not assert that the cache restore step uses actions/cache/restore (and not the auto-saving actions/cache). This gap means the bug described on line 243 would not be caught by this test suite.

Suggested addition: add an assertion like:

assert.Contains(t, preActivationSection, "actions/cache/restore")
assert.NotContains(t, preActivationSection, "uses: actions/cache@")

(or the pinned variants returned by getActionPin). This would concretely enforce the read-only cache contract.

@copilot please address this.

assert.NotContains(t, preActivationSection, "Push repo-memory changes")
})
}

// TestExtractOnSteps tests the extractOnSteps function directly
Expand Down
Loading