package agent import ( "context" "encoding/json" "errors" "fmt" "iter" "strings" "sync" "sync/atomic" "time" "github.com/Autumn-27/artex/db" "github.com/Autumn-27/norma/harness" "github.com/Autumn-27/norma/llm" actool "github.com/Autumn-27/norma/tool" ) type planningWait struct { IDs []int64 `json:"prerequisite_ids"` Reason string `json:"reason"` } type planningOutcome struct { mu sync.Mutex wait *planningWait } func (o *planningOutcome) set(w planningWait) { o.mu.Lock(); defer o.mu.Unlock(); o.wait = &w } func (o *planningOutcome) get() *planningWait { o.mu.Lock(); defer o.mu.Unlock(); return o.wait } type PlanningNoProgressError struct { Detail string Retryable bool } func (e *PlanningNoProgressError) Error() string { return "planning made no dispatchable progress: " + e.Detail } // The wrapper observes explicit provider refusal flags, without interpreting // natural-language refusal text or retrying it on a different provider. When a // planner budget meter is attached, it also enforces the lifetime hard ceiling // before sending any further LLM requests. type planningProvider struct { llm.Provider refused atomic.Bool budget *PlannerMeter } func (p *planningProvider) observe(stop string) { if stop == "refusal" || stop == "content_filter" { p.refused.Store(true) } } func (p *planningProvider) Complete(ctx context.Context, req llm.CompletionRequest) (llm.Message, string, llm.Usage, error) { if p.budget != nil && p.budget.HardExhausted() { return llm.Message{}, "", llm.Usage{}, ErrTaskBudgetExhausted } m, s, u, e := p.Provider.Complete(ctx, req) p.observe(s) return m, s, u, e } func (p *planningProvider) Stream(ctx context.Context, req llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] { return func(yield func(llm.StreamEvent, error) bool) { if p.budget != nil && p.budget.HardExhausted() { yield(llm.StreamEvent{}, ErrTaskBudgetExhausted) return } for ev, err := range p.Provider.Stream(ctx, req) { p.observe(ev.StopReason) if !yield(ev, err) { return } } } } func (t *ToolSet) reportPlanningWait() actool.CoreTool { return t.writeExpTool("report_planning_wait", "When no ready or running work remains, report why ALL remaining useful steps depend on specific existing prerequisites. Cite same-task delayed/paused/blocked intents, or confirmed blocked facts with evidence and revisit_condition. This records a wait only, never goal completion; ordinary prose is insufficient.", obj(map[string]any{ "prerequisite_ids": map[string]any{"type": "array", "items": map[string]any{"type": "integer"}, "minItems": 1, "maxItems": 32}, "reason": str("Explain which unmet goal needs each cited prerequisite and why no independent authorized step can run now."), }, "prerequisite_ids", "reason"), func(ctx context.Context, in json.RawMessage) (actool.Result, error) { var w planningWait if err := json.Unmarshal(in, &w); err != nil { return actool.Errorf("invalid waiting declaration"), nil } if _, err := t.ts.ValidatePlanningWait(ctx, w.IDs, w.Reason, time.Now()); err != nil { return actool.Errorf(err.Error()), nil } t.planningOutcome.set(w) return actool.Text("Prerequisites validated. Waiting will be rechecked when this round ends; the task remains unfinished."), nil }) } // Plan validates the resulting queue, not the model's final text. One immediate // recovery is allowed. Engine scheduling supplies later bounded recovery cycles. func (p *Planner) Plan(ctx context.Context, taskID int64, as *db.AssetStore, ts *db.ExplorationStore, goal string, triggers []TriggerEvent, hooks harness.HookRunner, emit func(db.Activity)) (bool, string, error) { if ts == nil { return p.planOnce(ctx, taskID, as, ts, goal, triggers, hooks, emit) } if err := ctx.Err(); err != nil { return false, "", err } budgetRound := budgetRoundFrom(ctx) if budgetRound.Meter != nil { defer budgetRound.Meter.Finish() } p.compactor.OnPlannerRound(ctx, ts) if taskClockFrom(ctx).Final || budgetRound.WrapUp { return p.planOnce(ctx, taskID, as, ts, goal, triggers, hooks, emit) } parentCtx := ctx if p.runTimeout > 0 { var cancel context.CancelFunc grace := p.settlementGrace if grace <= 0 { grace = 2 * time.Minute } ctx, cancel = context.WithTimeout(ctx, p.runTimeout+grace) defer cancel() } // A failed round is recorded against the input it was given. Input that // arrives while it runs (a goal edit, a hint, a worker fact) then differs // from the recorded fingerprint and reopens planning, instead of being // absorbed into the failure. start, err := ts.PlanningSnapshot(ctx) if err != nil { return false, "", err } var reason string for attempt := 0; attempt < 2; attempt++ { var met bool met, reason, err = p.planOnce(ctx, taskID, as, ts, goal, triggers, hooks, emit) if parentCtx.Err() != nil { return false, reason, parentCtx.Err() } if err == nil || met { return met, reason, err } if errors.Is(err, ErrTaskBudgetExhausted) || (budgetRound.Meter != nil && budgetRound.Meter.Exhausted()) { return false, reason, err } if ctx.Err() != nil { err = ctx.Err() break } var empty *PlanningNoProgressError if !errors.As(err, &empty) || !empty.Retryable || attempt == 1 { break } if emit != nil { emit(db.Activity{Worker: "planner", Kind: "text", IsError: true, Summary: "Empty planning round detected; retrying once with the observed queue and tool failures", Detail: err.Error()}) } triggers = append(append([]TriggerEvent(nil), triggers...), TriggerEvent{Kind: "planning_recovery", Detail: err.Error()}) } if parentCtx.Err() != nil { return false, reason, parentCtx.Err() } // A per-round timeout is recoverable; a human/task cancellation is not. // Use the still-live task context to persist the failed round before exit. if ctx.Err() != nil { ctx = parentCtx } snap, queryErr := ts.PlanningSnapshot(ctx) if queryErr != nil { return false, reason, errors.Join(err, queryErr) } // A worker/human may have supplied runnable work just after the last check. if snap.Ready > 0 || snap.Running > 0 { var empty *PlanningNoProgressError if errors.As(err, &empty) && empty.Retryable { return false, "work became available", ts.SavePlanningProgress(ctx, snap, "active", "Work became available after the empty-round check", nil) } return false, reason, err // Do not hide provider/storage errors because unrelated work exists. } now := time.Now() state := "retrying" next := now.Add(30 * time.Second) var nextPtr *time.Time = &next var empty *PlanningNoProgressError if errors.As(err, &empty) { state = "stalled" if !empty.Retryable { state = "needs_attention" nextPtr = nil } } snap.Fingerprint = start.Fingerprint var saveErr error if state == "retrying" { // A provider, storage or timeout error: the store schedules the backoff // from the failures already recorded, then needs_attention. saveErr = ts.RecordPlanningRetry(ctx, snap, err.Error(), now) } else { saveErr = ts.SavePlanningProgress(ctx, snap, state, err.Error(), nextPtr) } if saveErr != nil { return false, reason, errors.Join(err, saveErr) } if emit != nil { progress, readErr := ts.PlanningProgress(ctx) if readErr != nil { return false, reason, errors.Join(err, readErr) } raw, _ := json.Marshal(progress) emit(db.Activity{Worker: "planner", Kind: "text", IsError: true, Summary: "Planning " + progress.State + ": goal unfinished and no executable work; " + err.Error(), Detail: string(raw)}) } return false, reason, err } func (p *Planner) checkPlanningProgress(ctx context.Context, ts *db.ExplorationStore, tools *ToolSet, before db.PlanningSnapshot, terminal harness.TerminalReason, refused bool, toolErrors []string) error { after, err := ts.PlanningSnapshot(ctx) if err != nil { return err } // No open goals: preserve direct/goalless callers without inventing work or declaring completion. if after.OpenGoals == 0 { return nil } if after.Ready > 0 || after.Running > 0 || after.Done > before.Done { return ts.SavePlanningProgress(ctx, after, "active", "Verified runnable/running work or worker completion", nil) } if w := tools.planningOutcome.get(); w != nil { next, err := ts.ValidatePlanningWait(ctx, w.IDs, w.Reason, time.Now()) if err == nil { return ts.SavePlanningProgress(ctx, after, "waiting", w.Reason, &next) } toolErrors = append(toolErrors, "waiting declaration became invalid: "+err.Error()) } detail := fmt.Sprintf("open_goals=%d ready=%d running=%d; terminal=%s. No valid wait was registered. Use add_intent for a useful non-duplicate authorized step, or report_planning_wait with existing prerequisite IDs. Do not mark unmet goals complete.", after.OpenGoals, after.Ready, after.Running, terminal) if len(toolErrors) > 0 { detail += " Tool failures: " + strings.Join(toolErrors, "; ") } if refused { detail = "provider refused the request; do not automatically retry. " + detail } return &PlanningNoProgressError{Detail: detail, Retryable: !refused && terminal == harness.ReasonCompleted && after.OpenGoals > 0} } const planningRoundContract = ` Large-graph planning contract: - Open goals take precedence over recent met goals. Use list_goals pagination when open_goals_total exceeds the visible list. - planning_continuations and list_planning_continuations search old checkpoints and blocker facts beyond recent windows. Read node_detail and validate current relevance before continuing; a candidate is not permission to repeat work. - Round acceptance: when an unmet goal has no ready/running work, dispatch useful authorized non-duplicate work or call report_planning_wait with existing prerequisite IDs. A normal response alone is not progress. Never duplicate paused or scheduled work to satisfy a dispatch count. - If all remaining steps depend on a real prerequisite, explain why no independent step is available. Waiting never proves completion. Do not mark an unmet goal done to end a round. - Record incomplete work with checkpoint, and externally blocked work with evidence and revisit_condition. Budget exhaustion is incomplete work, not a negative result. The planner dispatches remaining execution through add_intent. `