Files
archie/internal/domain/workflow/implement.go
T
sam 44237b448b
deploy / plan (push) Successful in 6s
deploy / archied-image (push) Canceled after 0s
deploy / agent-image (push) Canceled after 0s
deploy / dist-zip (push) Canceled after 0s
ci/woodpecker/push/deploy Pipeline was canceled
deploy / gate (push) Canceled after 2m58s
refactor(prompts): every model prompt is a file in internal/prompts
2026-11-11 00:01:43 +11:00

142 lines
5.2 KiB
Go

package workflow
import (
"context"
"fmt"
"os/exec"
"strings"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/agentrun"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/prompts"
)
// Byte limits on failing gate output: the tail logged, what the builder sees,
// and what the park reason keeps.
const (
baselineWarnLogBytes = 2048
baselineMissionBytes = 3000
baselineParkOutputBytes = 2048
)
// StageBaselineGate verifies the repo's gate is green at the base commit.
// If the gate is red due to pre-existing failures, the builder attempts to
// fix them via TDD before proceeding. Only parks if the builder cannot fix
// the failures.
func StageBaselineGate() Stage {
return Stage{Name: "baseline", Run: stageBaselineGateRun}
}
// stageBaselineGateRun is StageBaselineGate's body, extracted to keep the
// composition's own length off the gate; the auto-fix agent it may dispatch
// records itself under the stage's step.
func stageBaselineGateRun(ctx context.Context, tc *TaskContext) error {
for _, argv := range tc.Repo.Gate {
if len(argv) == 0 {
continue
}
cmd := exec.CommandContext(ctx, argv[0], argv[1:]...)
cmd.Dir = tc.Dir
raw, err := cmd.CombinedOutput()
if err == nil {
continue
}
out := []byte(trimGateProgress(string(raw)))
// An environment failure cannot be repaired in the worktree, so park.
if cause := gateEnvironmentCause(string(out), err); cause != "" {
return baselineEnvironmentError(argv, string(out), cause)
}
tc.Log.WarnContext(ctx, "baseline red -- auto-fixing pre-existing gate failure",
"cmd", strings.Join(argv, " "),
"err", clipTail(string(out), baselineWarnLogBytes))
if fixErr := repairBaselineOnce(ctx, tc, argv, out); fixErr != nil {
return fixErr
}
}
return nil
}
// runBaselineFix dispatches the builder to repair one pre-existing gate
// failure via TDD and commits the result. It is reached only for a code
// failure: an environment failure is parked by the caller before it runs.
func runBaselineFix(ctx context.Context, tc *TaskContext, argv []string, out []byte) error {
mission := prompts.BaselineFix(strings.Join(argv, " "), tc.Repo.FullName(), clip(extractFailingGateOutput(string(out)), baselineMissionBytes))
modelRef, err := config.ResolveModel(tc.Cfg.Models, "", config.PurposeAgent)
if err != nil {
return err
}
req := agentrun.Request{
Version: agentrun.ProtocolVersion,
TaskID: tc.Task.ID,
Attempt: tc.Task.Attempt,
Stage: "baseline-fix",
Workflow: tc.Task.Workflow,
Model: modelRef,
ContextWindow: modelContextBudget(tc.Cfg, modelRef),
Mission: mission,
ExtraRules: tc.withInstructions(""),
Budget: agentrun.Budget{
MaxSteps: tc.Cfg.Budgets.MaxSteps,
WallClock: tc.Cfg.Budgets.WallClock.Std(),
},
Gate: GateFromRepo(tc.Repo, tc.Cfg.Budgets),
Protection: agentrun.Protection{Suffixes: append([]string(nil), tc.Repo.Protect...)},
}
res, agentErr := tc.RunAgentChild(ctx, "baseline-fix", "", modelRef, func() (agentrun.Result, error) {
return tc.Agent.Run(ctx, tc.Dir, req, tc.reporter(ctx, "baseline-fix"))
})
if agentErr != nil && res.Version == 0 {
return baselineFixFailedError(argv, string(out), fmt.Sprintf("the builder could not run: %v", agentErr))
}
tc.Task.TokensUsed += res.TokensUsed
tc.Task.Iterations += res.Iterations
accumulateUsage(&tc.RunUsage, res.Usage)
if emitErr := tc.EmitDurable(ctx, events.KindAgentFinish, "baseline-fix", res.Summary, agentFinishData(res, modelRef)); emitErr != nil {
return fmt.Errorf("persist baseline-fix agent finish: %w", emitErr)
}
if agentErr != nil {
return baselineFixFailedError(argv, string(out), fmt.Sprintf("the builder could not run: %v", agentErr))
}
if res.Status != agentrun.StatusPassed {
return baselineFixFailedError(argv, string(out), "builder status "+res.Status)
}
// Commit the baseline fix.
changed, commitErr := tc.Trees.CommitAll(ctx, tc.Dir,
fmt.Sprintf("fix: baseline gate repair (%s)", strings.Join(argv, " ")))
if commitErr != nil {
tc.Log.WarnContext(ctx, "baseline fix commit failed", "err", commitErr)
}
if changed {
tc.BuildSummary = res.Summary
tc.BaselineFixed = true
tc.captureChanges(ctx, capturedAfterBaselineFix)
if err := publishBaselineRepair(ctx, tc, argv); err != nil {
return baselineFixFailedError(argv, string(out), fmt.Sprintf("the repair could not be published: %v", err))
}
}
return nil
}
// publishBaselineRepair pushes the repair and opens its PR before the task
// goes on, so the repair survives this task parking or being deleted. The
// task's own PR later reuses this one.
func publishBaselineRepair(ctx context.Context, tc *TaskContext, argv []string) error {
if err := tc.Trees.Push(ctx, tc.Dir, tc.Branch); err != nil {
return err
}
cmd := strings.Join(argv, " ")
body := fmt.Sprintf("The baseline gate `%s` failed on %s before any feature work; this repairs it.",
cmd, tc.Repo.BaseBranch())
num, err := tc.Forge.CreatePR(ctx, tc.Task.Owner, tc.Task.Repo,
fmt.Sprintf("fix: baseline gate repair (%s)", cmd), tc.Branch, tc.Repo.BaseBranch(), body)
if err != nil {
return err
}
tc.BaselinePR = num
return nil
}