Merge main (findings ledger, loop continuation) into usage-limit branch

Keeps the findings ledger, extra visits and on_exhausted=decide alongside the
run budget, failure classes, quota parking and error-loop backoff.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-03 14:35:54 +00:00
66 changed files with 3565 additions and 148 deletions
+21 -1
View File
@@ -61,6 +61,9 @@ type ClaudeStageClient struct {
Policy ToolPolicy
OnOwnership func(string, string, bool) error
WorkStarted bool
// ResumeSessionID, when set, resumes that earlier session of this stage
// (resume_session=true on a loop visit) instead of starting a new one.
ResumeSessionID string
// operatorPlugins are this visit's generated skills-only plugin roots for
// the operator's own skills (see OperatorSkills).
@@ -275,6 +278,12 @@ func (c *ClaudeStageClient) Generate(ctx context.Context, config ModelConfig, pr
}
}
env := claudeStageEnvironment(c.environment(ctx), c.ArtifactsDir)
// resume_session: continue the stage's previous session when Claude Code
// still has it; otherwise this visit starts fresh.
resumeFirst := false
if adopted == nil && c.ResumeSessionID != "" && claudeSessionExists(claudeConfigDir(env), c.ResumeSessionID) {
c.SessionID, resumeFirst = c.ResumeSessionID, true
}
// User settings are not loaded, so the operator's skills are offered as
// skills-only plugins generated for this visit, never their plugins. A
// re-adopted visit keeps the ones its first process generated.
@@ -325,7 +334,7 @@ func (c *ClaudeStageClient) Generate(ctx context.Context, config ModelConfig, pr
return "", err
}
}
if text, err = c.invoke(ctx, env, c.args(config, tools, effort, false), 0, config.Model, prompt, adopted); err != nil {
if text, err = c.invoke(ctx, env, c.args(config, tools, effort, resumeFirst), 0, config.Model, prompt, adopted); err != nil {
return "", err
}
// One outcome repair follow-up in the same session.
@@ -409,6 +418,17 @@ func claudeConfigDir(env []string) string {
return ""
}
// claudeSessionExists reports whether Claude Code keeps a transcript for the
// session (projects/<project>/<id>.jsonl under its config directory), so a
// resume cannot fail on a session that was cleaned up.
func claudeSessionExists(configDir, id string) bool {
if configDir == "" || id == "" || strings.ContainsAny(id, `/\*?[`) {
return false
}
matches, _ := filepath.Glob(filepath.Join(configDir, "projects", "*", id+".jsonl"))
return len(matches) > 0
}
func newClaudeSessionID() (string, error) {
var b [16]byte
if _, err := rand.Read(b[:]); err != nil {
+77
View File
@@ -0,0 +1,77 @@
package stage
import (
"context"
"fmt"
"git.a-wan.net/alan/pipelines/internal/findings"
)
// FindingsType is the mechanical triage stage: it routes on the run's findings
// ledger instead of asking a model. Outcome `open` when any open finding is at
// or above `severity` (default important) with a matching `origin` (default
// introduced; `pre-existing` or `any`), otherwise `clear`.
const FindingsType = "findings"
// Findings gate outcomes.
const (
FindingsOpen = "open"
FindingsClear = "clear"
)
type FindingsStage struct{}
func (FindingsStage) Validate(def Definition) error {
if EffectiveType(def.Type) != FindingsType {
return fmt.Errorf("expected findings stage")
}
for name := range def.Blocks {
switch name {
case "configs", "edges", "output", "prompt", "limits":
case "skills":
return errSkillsModelOnly("findings")
default:
return fmt.Errorf("unexpected block %q for findings stage", name)
}
}
if _, err := FindingsGate(def); err != nil {
return err
}
for outcome := range def.Edges {
switch outcome {
case FindingsOpen, FindingsClear, "error":
default:
return fmt.Errorf("findings stage outcomes are open and clear, not %q", outcome)
}
}
for _, outcome := range []string{FindingsOpen, FindingsClear} {
if _, ok := def.Edges[outcome]; !ok {
return fmt.Errorf("findings stage requires an edge for outcome %s", outcome)
}
}
return nil
}
// FindingsGate reads a findings stage's severity and origin configs.
func FindingsGate(def Definition) (findings.Gate, error) {
gate := findings.Gate{MinSeverity: "important", Origin: "introduced"}
for key, value := range def.Configs {
switch key {
case "severity":
if gate.MinSeverity = findings.NormalizeSeverity(value); gate.MinSeverity == "" {
return gate, fmt.Errorf("severity must be critical, important, minor or nit")
}
case "origin":
if gate.Origin = findings.NormalizeOrigin(value); gate.Origin == "" {
return gate, fmt.Errorf("origin must be introduced, pre-existing or any")
}
default:
return gate, fmt.Errorf("unknown findings config %q", key)
}
}
return gate, nil
}
func (FindingsStage) Run(context.Context, Definition, Values) (Result, error) {
return Result{}, fmt.Errorf("findings stage is resolved by the runner from the run's ledger, not executed")
}
+6 -1
View File
@@ -84,7 +84,7 @@ func (ModelStage) Spec(def Definition) (ModelSpec, error) {
}
for key := range def.Configs {
switch key {
case "provider", "model", "reasoning_effort", "retries", "timeout", "budget_usd", "budget_tokens", "harness", "delivery", "auto_skip", "allow_workspace_changes":
case "provider", "model", "reasoning_effort", "retries", "timeout", "budget_usd", "budget_tokens", "harness", "delivery", "auto_skip", "allow_workspace_changes", "resume_session":
default:
return ModelSpec{}, fmt.Errorf("unknown config %q", key)
}
@@ -111,6 +111,11 @@ func (ModelStage) Spec(def Definition) (ModelSpec, error) {
if value := def.Configs["auto_skip"]; value != "" && value != "true" && value != "false" {
return ModelSpec{}, fmt.Errorf("auto_skip must be true or false")
}
// resume_session=true resumes the stage's previous harness session on a
// loop visit (Claude only; other harnesses start fresh). The runner reads it.
if value := def.Configs["resume_session"]; value != "" && value != "true" && value != "false" {
return ModelSpec{}, fmt.Errorf("resume_session must be true or false")
}
// allow_workspace_changes=true lets a stage with shell but no edit leave file changes
// in the run directory; by default the runner fails such a visit.
if value := def.Configs["allow_workspace_changes"]; value != "" && value != "true" && value != "false" {
+5 -1
View File
@@ -10,6 +10,7 @@ import (
"time"
"unicode/utf8"
"git.a-wan.net/alan/pipelines/internal/findings"
"git.a-wan.net/alan/pipelines/internal/turn"
)
@@ -75,7 +76,7 @@ func modelPrompt(def Definition, spec ModelSpec, input Values) (string, error) {
case !canRead:
b.WriteString("The read tool is not enabled, so the server included the turn files below. Use this supplied context; no extra filesystem access is needed.\n\n")
}
writeTurnFile(&b, "memory.md", def.Turn.Memory, capInline(string(memory), turn.EssentialCap, def.Turn.Memory))
writeTurnFile(&b, "memory.md", def.Turn.Memory, capInline(string(memory), turn.EssentialMax, def.Turn.Memory))
if canRead {
b.WriteString("Rely on this essential memory first. Read on demand only, when you need more detail:\n")
fmt.Fprintf(&b, "- Input (full run task and previous stage output): %s\n", def.Turn.Input)
@@ -110,6 +111,9 @@ func modelPrompt(def Definition, spec ModelSpec, input Values) (string, error) {
b.WriteString(" The next stage receives only the handoff as essential memory. For example:\n\n# outcome\n")
b.WriteString(preferredOutcome(outcomes))
b.WriteString("\n\n# handoff\nWhat you did, files changed, open issues for the next stage.\n\n# details\n...\n")
b.WriteString("\n")
b.WriteString(findings.Syntax)
b.WriteString("\n")
fmt.Fprintf(&b, "\nExecution time: %s. Timezone: %s.\n", time.Now().Format(time.RFC3339), time.Local.String())
if def.Turn.Public != "" {
fmt.Fprintf(&b, "\nShared artifacts go to %s; files there are visible to every later stage. That absolute path is the shared folder: a relative public/ inside the workspace is a different, unshared directory. Turn-local work goes to %s and is not handed to later stages.\n", def.Turn.Public, def.Turn.Private)
+2 -2
View File
@@ -19,7 +19,7 @@ func TestModelPromptInlinesEssentialMemoryAndPointsAtHistory(t *testing.T) {
def.Blocks["tools"] = toolset
def.Turn.History = filepath.Join(def.Turn.Dir, "history.md")
files := map[string]string{
def.Turn.Memory: "# Essential memory\n\nreviewer finding: lock leak\n" + strings.Repeat("m", 2*turn.EssentialCap),
def.Turn.Memory: "# Essential memory\n\nreviewer finding: lock leak\n" + strings.Repeat("m", 2*turn.EssentialMax),
def.Turn.Input: "full previous output\n",
def.Turn.History: "FULL HISTORY BODY\n",
}
@@ -39,7 +39,7 @@ func TestModelPromptInlinesEssentialMemoryAndPointsAtHistory(t *testing.T) {
if !strings.Contains(prompt, "reviewer finding: lock leak") || !strings.Contains(prompt, "_[truncated: ") {
t.Fatalf("essential memory not inlined with its cap: %q", prompt)
}
if strings.Contains(prompt, strings.Repeat("m", turn.EssentialCap+1)) {
if strings.Contains(prompt, strings.Repeat("m", turn.EssentialMax+1)) {
t.Fatal("inlined memory exceeded its cap")
}
if strings.Contains(prompt, "FULL HISTORY BODY") {
+1 -1
View File
@@ -75,7 +75,7 @@ func NewRegistry(types map[string]Stage) *Registry {
}
func DefaultRegistry() *Registry {
return NewRegistry(map[string]Stage{ModelType: ModelStage{}, NtfyType: NtfyStage{}, HumanType: HumanStage{}, CheckType: CheckStage{}})
return NewRegistry(map[string]Stage{ModelType: ModelStage{}, NtfyType: NtfyStage{}, HumanType: HumanStage{}, CheckType: CheckStage{}, FindingsType: FindingsStage{}})
}
func EffectiveType(name string) string {