package db import ( "context" "database/sql" "encoding/json" "fmt" "strings" "time" ) // Activity timestamps deliberately do not participate: an empty model response // is not a graph change and cannot reset the recovery allowance. // // Nodes the planner writes itself (origin 'planner') do not participate either, // so a failing planner cannot re-arm its own breaker by recording a fact or a // hint each round. A planner intent counts once it has left 'open': a worker, // a human or the scheduler moved it. Task scope and task assets do participate: // a scope row added or removed by a human or the system (source 'manual' or // 'auto'; the planner's add_task_scope writes 'agent'), and an asset linked to // or unlinked from the task, are new input that reopens planning. Asset field // updates are left out: a planner company-scope claim rewrites them too, and a // worker that changes an asset records a fact that counts. // // A task credential counts by its row, not its password: the password is // sealed with a fresh nonce on every save, so saving the same credential again // would otherwise look like new input and re-arm the breaker. type PlanningSnapshot struct { OpenGoals int `json:"open_goals"` Ready int `json:"ready"` Running int `json:"running"` Done int `json:"done"` Fingerprint string `json:"fingerprint"` } func (s *ExplorationStore) PlanningSnapshot(ctx context.Context) (PlanningSnapshot, error) { var out PlanningSnapshot err := s.db.QueryRowContext(ctx, `SELECT count(*) FILTER(WHERE kind='goal' AND state='open'), count(*) FILTER(WHERE kind='intent' AND state='open' AND `+intentReadySQL+`), count(*) FILTER(WHERE kind='intent' AND state='running'), count(*) FILTER(WHERE kind='intent' AND state='done'), md5(COALESCE(string_agg(id::text||':'||kind||':'||state||':'||md5(payload::text)||':'||COALESCE(blocked_reason,''),'|' ORDER BY id) FILTER(WHERE COALESCE(origin,'')<>'planner' OR (kind='intent' AND state<>'open')),'') ||COALESCE((SELECT goal||description||COALESCE(active_llm_profile_id::text,'')||llm_chain_revision::text FROM tasks WHERE exploration_id=$1),'') ||COALESCE((SELECT jsonb_agg(to_jsonb(c) ORDER BY c.id)::text FROM task_constraints c WHERE exploration_id=$1),'') ||COALESCE((SELECT jsonb_agg(jsonb_build_array(c.id,c.domain,c.username,c.source,c.note) ORDER BY c.id)::text FROM task_credentials c JOIN tasks t ON t.id=c.task_id WHERE t.exploration_id=$1),'') ||'|scope:'||COALESCE((SELECT jsonb_agg(jsonb_build_array(sc.id,sc.kind,sc.company_id,sc.domain,sc.net::text,sc.value,sc.source,sc.expanded) ORDER BY sc.id)::text FROM task_scope sc JOIN tasks t ON t.id=sc.task_id WHERE t.exploration_id=$1 AND sc.source<>'agent'),'') ||'|assets:'||COALESCE((SELECT count(*)::text FROM tasks t JOIN assets a ON a.task_ids @> ARRAY[t.id] WHERE t.exploration_id=$1),'') ||'|links:'||COALESCE((SELECT count(*)::text||':'||COALESCE(max(l.updated_at)::text,'') FROM task_asset_links l JOIN tasks t ON t.id=l.task_id WHERE t.exploration_id=$1),'')) FROM exploration_nodes WHERE exploration_id=$1 AND kind IN ('goal','intent','fact','finding','hint')`, s.expID). Scan(&out.OpenGoals, &out.Ready, &out.Running, &out.Done, &out.Fingerprint) return out, err } type PlanningProgress struct { State string `json:"state"` Reason string `json:"reason"` Fingerprint string `json:"fingerprint"` Failures int `json:"failures"` NextCheck *time.Time `json:"next_check,omitempty"` } func (s *ExplorationStore) PlanningProgress(ctx context.Context) (PlanningProgress, error) { var out PlanningProgress err := s.db.QueryRowContext(ctx, `SELECT state,reason,fingerprint,failures,next_check_at FROM planner_progress WHERE exploration_id=$1`, s.expID). Scan(&out.State, &out.Reason, &out.Fingerprint, &out.Failures, &out.NextCheck) if err == sql.ErrNoRows { err = nil } return out, err } func (s *ExplorationStore) ResetPlanningProgress(ctx context.Context) error { _, err := s.db.ExecContext(ctx, `DELETE FROM planner_progress WHERE exploration_id=$1`, s.expID) return err } // SavePlanningProgress records a round outcome. A provider, storage or timeout // error (retrying) is recorded by RecordPlanningRetry, which owns its backoff. func (s *ExplorationStore) SavePlanningProgress(ctx context.Context, snapshot PlanningSnapshot, state, reason string, next *time.Time) error { if state == "retrying" { return fmt.Errorf("a retrying round is recorded by RecordPlanningRetry") } if state != "active" && state != "waiting" && state != "stalled" && state != "needs_attention" { return fmt.Errorf("invalid planning progress state") } if _, err := s.upsertPlanningProgress(ctx, snapshot, state, reason, next); err != nil { return err } // At most MaxPlanningFailures failed recovery cycles for unchanged input. // Only actual new graph input or an explicit Resume resets this circuit; // never mark done. _, err := s.db.ExecContext(ctx, `UPDATE planner_progress SET state='needs_attention',next_check_at=NULL WHERE exploration_id=$1 AND state='stalled' AND failures>=$2`, s.expID, MaxPlanningFailures) return err } // RecordPlanningRetry records a round that failed with a provider, storage or // timeout error at now. The next attempt waits PlanningRetryDelay of the // failures now recorded on unchanged input: 30 s, then 5 min, then 30 min. // The failure after the 30 min wait moves the task to needs_attention, so a // persistent error costs MaxPlanningFailures+1 attempts in all, never more. func (s *ExplorationStore) RecordPlanningRetry(ctx context.Context, snapshot PlanningSnapshot, reason string, now time.Time) error { failures, err := s.upsertPlanningProgress(ctx, snapshot, "retrying", reason, nil) if err != nil { return err } if delay, ok := PlanningRetryDelay(failures); ok { _, err = s.db.ExecContext(ctx, `UPDATE planner_progress SET next_check_at=$2 WHERE exploration_id=$1`, s.expID, now.Add(delay)) return err } _, err = s.db.ExecContext(ctx, `UPDATE planner_progress SET state='needs_attention',next_check_at=NULL WHERE exploration_id=$1`, s.expID) return err } // upsertPlanningProgress writes the row and returns the failures it now holds. // Every failed round counts, an empty one (stalled) and a provider, storage or // timeout error (retrying) alike: a retrying upsert keeps counting rather than // resetting the circuit, so a persistent error cannot retry forever. func (s *ExplorationStore) upsertPlanningProgress(ctx context.Context, snapshot PlanningSnapshot, state, reason string, next *time.Time) (int, error) { var failures int err := s.db.QueryRowContext(ctx, `INSERT INTO planner_progress(exploration_id,state,reason,fingerprint,failures,next_check_at) VALUES($1,$2,$3,$4,CASE WHEN $2 IN ('stalled','needs_attention','retrying') THEN 1 ELSE 0 END,$5) ON CONFLICT(exploration_id) DO UPDATE SET state=EXCLUDED.state,reason=EXCLUDED.reason,fingerprint=EXCLUDED.fingerprint, failures=CASE WHEN EXCLUDED.state IN ('stalled','needs_attention','retrying') THEN CASE WHEN planner_progress.fingerprint=EXCLUDED.fingerprint THEN planner_progress.failures+1 ELSE 1 END ELSE 0 END, next_check_at=EXCLUDED.next_check_at,updated_at=now() RETURNING failures`, s.expID, state, reason, snapshot.Fingerprint, next).Scan(&failures) return failures, err } // MaxPlanningFailures bounds the consecutive failed planning cycles on // unchanged input before a task needs attention: empty rounds (stalled) stop // at the MaxPlanningFailures-th; provider, storage or timeout errors // (retrying) get MaxPlanningFailures retries with backoff, and stop at the // failure that follows the last wait. const MaxPlanningFailures = 3 // planningRetryBackoff is the wait after the 1st, 2nd and 3rd consecutive // retrying failure on unchanged input. var planningRetryBackoff = [MaxPlanningFailures]time.Duration{30 * time.Second, 5 * time.Minute, 30 * time.Minute} // PlanningRetryDelay returns the wait before the next attempt after failures // consecutive retrying failures, and false once the retries are spent. func PlanningRetryDelay(failures int) (time.Duration, bool) { if failures < 1 || failures > len(planningRetryBackoff) { return 0, false } return planningRetryBackoff[failures-1], true } func (s *ExplorationStore) PlanningAllowed(ctx context.Context, now time.Time) (bool, error) { p, err := s.PlanningProgress(ctx) if err != nil { return false, err } if p.State == "" || p.State == "active" { return true, nil } snap, err := s.PlanningSnapshot(ctx) if err != nil { return false, err } if snap.Fingerprint != p.Fingerprint || snap.Ready > 0 || snap.Running > 0 { return true, nil } return p.NextCheck != nil && !now.Before(*p.NextCheck), nil } // A wait declaration must cite real, same-task prerequisites. Prose alone never // constitutes a wait, and exhausted work is not a prerequisite or completion. // This checks the existence of the blocker; its relevance is still a planning // judgment, so waiting is periodically reconsidered even without graph changes. func (s *ExplorationStore) ValidatePlanningWait(ctx context.Context, ids []int64, reason string, now time.Time) (time.Time, error) { if strings.TrimSpace(reason) == "" || len(ids) == 0 || len(ids) > 32 { return time.Time{}, fmt.Errorf("waiting needs a reason and 1..32 prerequisite node IDs") } next := now.Add(10 * time.Minute) seen := map[int64]bool{} for _, id := range ids { if id <= 0 || seen[id] { return time.Time{}, fmt.Errorf("invalid or duplicate prerequisite %d", id) } seen[id] = true var kind, state, blocked string var raw []byte err := s.db.QueryRowContext(ctx, `SELECT kind,state,COALESCE(blocked_reason,''),payload FROM exploration_nodes WHERE exploration_id=$1 AND id=$2`, s.expID, id).Scan(&kind, &state, &blocked, &raw) if err != nil { return time.Time{}, fmt.Errorf("prerequisite %d not available in this task: %w", id, err) } var p struct { NotBefore string `json:"not_before"` NotBeforeUnix json.RawMessage `json:"not_before_unix"` Outcome string `json:"outcome"` Revisit string `json:"revisit_condition"` Evidence string `json:"evidence"` } if err = json.Unmarshal(raw, &p); err != nil { return time.Time{}, fmt.Errorf("invalid prerequisite metadata for %d", id) } switch { case kind == KindIntent && state == "paused": // A human/work-control pause may not be bypassed by a duplicate. case kind == KindIntent && state == "blocked" && strings.TrimSpace(blocked) != "": case kind == KindIntent && state == "open": due, err := time.Parse(time.RFC3339Nano, p.NotBefore) sec, e := json.Number(string(p.NotBeforeUnix)).Int64() expected := due.Unix() if due.Nanosecond() != 0 { expected++ } if err != nil || e != nil || sec != expected || !time.Unix(sec, 0).After(now) { return time.Time{}, fmt.Errorf("intent %d is not valid future work", id) } if d := time.Unix(sec, 0); d.Before(next) { next = d } case kind == KindFact && state == "confirmed" && p.Outcome == "blocked" && strings.TrimSpace(p.Revisit) != "" && strings.TrimSpace(p.Evidence) != "": default: return time.Time{}, fmt.Errorf("node %d is not a scheduled, paused, or evidenced blocked prerequisite", id) } } return next, nil }