From 4d03d3412bbd8d56cd453ad2ae1ae9f3ef6c3e70 Mon Sep 17 00:00:00 2001 From: renaesop <5894477+renaesop@users.noreply.github.com> Date: Sat, 28 Nov 2026 20:50:53 +0000 Subject: [PATCH] fix: recover empty planning rounds in large graphs (#676) --- agent/data_envelope.go | 4 +- agent/data_envelope_test.go | 6 + agent/fact_input.go | 22 +- agent/goals_contract_test.go | 4 + agent/intent_context.go | 69 ++++ agent/intent_context_test.go | 103 ++++++ agent/p43_adversarial_bench_test.go | 6 +- agent/planner.go | 47 ++- agent/planner_focus.go | 79 ++++ agent/planner_focus_test.go | 140 ++++++++ agent/planner_progress.go | 214 +++++++++++ agent/planner_progress_regression_test.go | 339 ++++++++++++++++++ agent/planning_compatibility_extra_test.go | 104 ++++++ agent/planning_compatibility_test.go | 116 ++++++ agent/toolcatalog.go | 3 + agent/tools.go | 111 +++++- agent/tools_insert.go | 1 + agent/worker.go | 17 +- db/exploration.go | 15 +- db/exploration_sources.go | 17 +- db/intent_context.go | 40 +++ db/intent_schedule.go | 75 ++++ db/intent_schedule_test.go | 86 +++++ db/planner_focus.go | 65 ++++ db/planner_progress.go | 149 ++++++++ db/planner_progress_test.go | 84 +++++ db/schema.sql | 13 + db/task_archives_restore.go | 1 + intercept/target_extract.go | 1 + scripts/sql/inspect-planning-index.sql | 12 + scripts/sql/planning-continuations-index.sql | 20 ++ .../rollback-planning-continuations-index.sql | 3 + server/engine.go | 65 +++- server/planner_progress_test.go | 168 +++++++++ server/task_credentials.go | 6 + 35 files changed, 2146 insertions(+), 59 deletions(-) create mode 100644 agent/intent_context.go create mode 100644 agent/intent_context_test.go create mode 100644 agent/planner_focus.go create mode 100644 agent/planner_focus_test.go create mode 100644 agent/planner_progress.go create mode 100644 agent/planner_progress_regression_test.go create mode 100644 agent/planning_compatibility_extra_test.go create mode 100644 agent/planning_compatibility_test.go create mode 100644 db/intent_context.go create mode 100644 db/intent_schedule.go create mode 100644 db/intent_schedule_test.go create mode 100644 db/planner_focus.go create mode 100644 db/planner_progress.go create mode 100644 db/planner_progress_test.go create mode 100644 scripts/sql/inspect-planning-index.sql create mode 100644 scripts/sql/planning-continuations-index.sql create mode 100644 scripts/sql/rollback-planning-continuations-index.sql create mode 100644 server/planner_progress_test.go diff --git a/agent/data_envelope.go b/agent/data_envelope.go index 8d81f20f..491808f2 100644 --- a/agent/data_envelope.go +++ b/agent/data_envelope.go @@ -77,12 +77,12 @@ func FrameTriggerData(content string) string { // overviewDerivedFields are the graph_overview keys whose content is derived // from agent or target text; renderOverviewSections frames each of them. -var overviewDerivedFields = []string{"recent_facts", "finding_list", "cold_digests", "related_tasks"} +var overviewDerivedFields = []string{"recent_facts", "finding_list", "cold_digests", "related_tasks", "planning_continuations"} // intentSummaryKeys are the graph_overview intent lists whose summary is written // by a planner: the structured fields stay in the plain JSON, every summary goes // into one frame (#124, F3). -var intentSummaryKeys = []string{"open_intents", "running_intents", "recent_done_intents"} +var intentSummaryKeys = []string{"open_intents", "running_intents", "recent_done_intents", "paused_intents"} // renderWorkerIntentAssets formats intent-anchored target assets for the worker's // launch user message, framed inside env's data envelope (#124). Target-controlled diff --git a/agent/data_envelope_test.go b/agent/data_envelope_test.go index 80fe0236..032022cf 100644 --- a/agent/data_envelope_test.go +++ b/agent/data_envelope_test.go @@ -178,6 +178,12 @@ func TestWorkerOverviewEnvelopeSplit(t *testing.T) { env := newDataEnvelope() out := renderWorkerGraphOverview(envelopeOverview(), env) for _, field := range overviewDerivedFields { + if field == "planning_continuations" { + if strings.Contains(out, "planning_continuations") { + t.Error("planner continuation search leaked into worker overview") + } + continue + } if !strings.Contains(out, dataOpenPrefix+env.nonce+" field="+field+"]]") { t.Errorf("no frame for derived field %s", field) } diff --git a/agent/fact_input.go b/agent/fact_input.go index eb84910e..97313ea9 100644 --- a/agent/fact_input.go +++ b/agent/fact_input.go @@ -23,14 +23,18 @@ func factAssetIDSchema() map[string]any { // which the handler still accepts but the published schema no longer shows. func factItemSchema() map[string]any { schema := obj(map[string]any{ - "summary": str("Required: a non-empty one-sentence summary of this conclusion."), - "intent_id": idp("The intent that produced this fact. Omit it to link the fact to the intent this worker is running; a batch may name a different intent per item."), - "detail": str("Details of this fact, including all related observations."), - "evidence": str("One line of key evidence: the command and the most proving output lines. Put longer output in detail."), - "confidence": str("observed (seen directly in output) | inferred (inferred from phenomena). Label negative conclusions honestly."), - "source": map[string]any{"type": "string", "enum": factSources, "description": "where the content came from: target_response | tool_output | third_party_intel | operator_input | inference (default when omitted)"}, - "asset_ids": map[string]any{"type": "array", "items": factAssetIDSchema(), "description": "Asset IDs explicitly involved in this fact. Use asset_ids as the canonical field; tested_asset_ids is accepted as an alias. If both are provided, they must name the same set. Do not infer IDs from the intent."}, - "tested_asset_ids": map[string]any{"type": "array", "items": factAssetIDSchema(), "description": "Compatibility alias for asset_ids, not an additional list. When both are provided their sets must match. Only include assets actually involved in this conclusion."}, + "outcome": str("Optional: verified, negative, blocked or incomplete. A checkpoint or blocker is not goal completion."), + "checkpoint": str("Remaining steps and already-observed progress for incomplete work."), + "revisit_condition": str("Concrete external prerequisite needed to revisit blocked work."), + "test_dimension": str("Specific dimension actually tested."), + "summary": str("Required: a non-empty one-sentence summary of this conclusion."), + "intent_id": idp("The intent that produced this fact. Omit it to link the fact to the intent this worker is running; a batch may name a different intent per item."), + "detail": str("Details of this fact, including all related observations."), + "evidence": str("One line of key evidence: the command and the most proving output lines. Put longer output in detail."), + "confidence": str("observed (seen directly in output) | inferred (inferred from phenomena). Label negative conclusions honestly."), + "source": map[string]any{"type": "string", "enum": factSources, "description": "where the content came from: target_response | tool_output | third_party_intel | operator_input | inference (default when omitted)"}, + "asset_ids": map[string]any{"type": "array", "items": factAssetIDSchema(), "description": "Asset IDs explicitly involved in this fact. Use asset_ids as the canonical field; tested_asset_ids is accepted as an alias. If both are provided, they must name the same set. Do not infer IDs from the intent."}, + "tested_asset_ids": map[string]any{"type": "array", "items": factAssetIDSchema(), "description": "Compatibility alias for asset_ids, not an additional list. When both are provided their sets must match. Only include assets actually involved in this conclusion."}, }, "summary") summary := schema["properties"].(map[string]any)["summary"].(map[string]any) summary["minLength"] = 1 @@ -180,7 +184,7 @@ func exactFactFields(in json.RawMessage, topLevel bool) (map[string]json.RawMess } for name := range fields { switch name { - case "summary", "detail", "evidence", "confidence", "source", "intent_id", "asset_ids", "tested_asset_ids": + case "summary", "detail", "evidence", "confidence", "source", "intent_id", "asset_ids", "tested_asset_ids", "outcome", "checkpoint", "revisit_condition", "test_dimension": case "facts": if !topLevel { return nil, fmt.Errorf("unknown field %q", name) diff --git a/agent/goals_contract_test.go b/agent/goals_contract_test.go index 5bb691d9..cc26b30c 100644 --- a/agent/goals_contract_test.go +++ b/agent/goals_contract_test.go @@ -255,6 +255,10 @@ func TestPlannerRefusesEmptyContextAndOverviewOmitsEmptyFields(t *testing.T) { if len(goals) != 1 || goals[0]["text"] != "Audit /admin" { t.Fatalf("expected 1 non-empty goal in overview, got %+v", overview["goals"]) } + // Existing executable work makes this a valid no-dispatch planning round. + if _, err := ts.AddIntent(map[string]any{"summary": "Audit the fixture admin endpoint"}, 0, nil, "fixture"); err != nil { + t.Fatal(err) + } // With a valid goal node present, Planner.Plan proceeds even if the explicit // goal arg was empty. if _, _, err := planner.Plan(t.Context(), task.ID, nil, ts, "", nil, nil, nil); err != nil { diff --git a/agent/intent_context.go b/agent/intent_context.go new file mode 100644 index 00000000..43851345 --- /dev/null +++ b/agent/intent_context.go @@ -0,0 +1,69 @@ +package agent + +import ( + "context" + "encoding/json" + "fmt" + "github.com/Autumn-27/artex/db" + actool "github.com/Autumn-27/norma/tool" + "time" +) + +func (t *ToolSet) intentContext(ctx context.Context, id, before int64, limit int) (map[string]any, error) { + if id <= 0 { + id = t.ownerNode + } + intent, err := t.ts.GetNodeContext(ctx, id) + if err != nil || intent == nil || intent.Kind != db.KindIntent { + return nil, fmt.Errorf("intent_id must refer to an intent in this task") + } + ids, total, more, err := t.ts.IntentReferenceIDs(ctx, id, before, limit) + if err != nil { + return nil, err + } + refs := make([]map[string]any, 0, len(ids)) + for _, ref := range ids { + // This resolver enforces the same direct-source read boundary as node_detail. + n, err := t.ts.GetNodeWithSourcesContext(ctx, ref) + if err != nil || n == nil { + refs = append(refs, map[string]any{"id": ref, "unavailable": true}) + continue + } + refs = append(refs, compactPlanningContinuation(n)) + } + out := map[string]any{"intent_id": id, "references": refs, "total": total, "has_more": more, "instruction": "These are the existing evidence/checkpoint nodes explicitly referenced by your assigned intent, fetched independently of the global graph window. Read their complete node_detail before relying on summaries. If a file Read is truncated, that is not proof the source is absent: use the referenced full graph evidence or an available authorized paginated reader. Do not guess alternate filenames, repeat the same truncated read, invent missing input, or broaden scope. Superseded/dismissed evidence needs current validation."} + if more && len(ids) > 0 { + out["next_before"] = ids[len(ids)-1] + } + return out, nil +} +func (t *ToolSet) renderIntentReferences(ctx context.Context, id int64) string { + if t.ts == nil { + return "" + } + ctx, cancel := context.WithTimeout(ctx, 2*time.Second) + defer cancel() + out, err := t.intentContext(ctx, id, 0, 16) + if err != nil { + return "\n\n[Referenced intent evidence unavailable: " + err.Error() + ". Do not infer that the input is missing; retry get_intent_context before making that claim.]" + } + raw, _ := json.Marshal(out) + return "\n\n[Evidence explicitly handed to this intent; read without broadening your assigned work]:\n" + string(raw) +} +func (t *ToolSet) getIntentContext() actool.CoreTool { + return t.readExpTool("get_intent_context", "Read the same-task intent's explicitly linked source facts/checkpoints, independently of the large global graph window. Defaults to your assigned intent; use before/limit to page. Full evidence is available through node_detail.", obj(map[string]any{"intent_id": idp("optional intent ID, defaults to your assigned intent"), "before": idp("older reference ID cursor"), "limit": intp("default 16, maximum 50")}), func(ctx context.Context, raw json.RawMessage) (actool.Result, error) { + var a struct { + ID int64 `json:"intent_id"` + Before int64 + Limit int + } + if err := json.Unmarshal(raw, &a); err != nil { + return actool.Errorf("invalid intent context query"), nil + } + out, err := t.intentContext(ctx, a.ID, a.Before, a.Limit) + if err != nil { + return actool.Errorf(err.Error()), nil + } + return jsonResult(out) + }) +} diff --git a/agent/intent_context_test.go b/agent/intent_context_test.go new file mode 100644 index 00000000..9705362b --- /dev/null +++ b/agent/intent_context_test.go @@ -0,0 +1,103 @@ +package agent + +import ( + "encoding/json" + "github.com/Autumn-27/artex/db" + "strings" + "testing" +) + +func TestIntentContextSurvivesLargeGraphAndPaginates(t *testing.T) { + d := testDB(t) + defer d.Close() + task, err := d.CreateTask("large handover", "complete referenced work", nil, 0, 0) + if err != nil { + t.Fatal(err) + } + defer d.DeleteTask(task.ID) + s := d.Exploration(task.ExplorationID) + source, err := s.AddNode("fact", map[string]any{"summary": "original input", "evidence": strings.Repeat("raw", 1000)}, 0, "confirmed", "fixture", nil) + if err != nil { + t.Fatal(err) + } + _, err = d.Exec(`WITH nodes AS (INSERT INTO exploration_nodes(exploration_id,kind,state,payload) SELECT $1,'fact','confirmed','{"summary":"older noise"}'::jsonb FROM generate_series(1,6000) RETURNING id) INSERT INTO exploration_edges(exploration_id,src_id,rel,dst_id) SELECT $1,$2,'derived_from',id FROM nodes`, s.ID(), source) + if err != nil { + t.Fatal(err) + } + intent, err := s.AddIntent(map[string]any{"summary": "use original input"}, 1, nil, "planner") + if err != nil { + t.Fatal(err) + } + if err = s.Link(source, db.RelDerivedFrom, intent); err != nil { + t.Fatal(err) + } + for i := 0; i < 20; i++ { + id, err := s.AddNode("fact", map[string]any{"summary": "additional reference"}, 0, "confirmed", "fixture", nil) + if err != nil { + t.Fatal(err) + } + if err = s.Link(id, db.RelDerivedFrom, intent); err != nil { + t.Fatal(err) + } + } + tools := NewToolSet(s, "work#1") + tools.SetOwnerNode(intent) + seen := map[int64]bool{} + before := int64(0) + for { + raw, _ := json.Marshal(map[string]any{"before": before, "limit": 5}) + res, err := tools.getIntentContext().Call(t.Context(), raw, nil) + if err != nil || res.IsError { + t.Fatal(res, err) + } + var page struct { + References []struct{ ID int64 } + Total int + More bool `json:"has_more"` + Before int64 `json:"next_before"` + } + if err = json.Unmarshal([]byte(res.Flatten()), &page); err != nil { + t.Fatal(err) + } + if page.Total != 21 { + t.Fatal(page.Total) + } + for _, n := range page.References { + if seen[n.ID] { + t.Fatal("duplicate") + } + seen[n.ID] = true + } + if !page.More { + break + } + before = page.Before + } + if len(seen) != 21 || !seen[source] { + t.Fatal("handover lost behind graph window") + } + if !strings.Contains(tools.renderIntentReferences(t.Context(), intent), "get_intent_context") && !strings.Contains(tools.renderIntentReferences(t.Context(), intent), "next_before") { + t.Fatal("missing paging continuation") + } + other, err := d.CreateTask("other task", "private", nil, 0, 0) + if err != nil { + t.Fatal(err) + } + defer d.DeleteTask(other.ID) + foreign, err := d.Exploration(other.ExplorationID).AddIntent(map[string]any{"summary": "foreign"}, 1, nil, "fixture") + if err != nil { + t.Fatal(err) + } + raw, _ := json.Marshal(map[string]any{"intent_id": foreign}) + res, err := tools.getIntentContext().Call(t.Context(), raw, nil) + if err != nil || !res.IsError { + t.Fatal("cross-task intent admitted", res, err) + } +} + +func TestWorkerOverviewBoundsHistoricalDigests(t *testing.T) { + text := renderWorkerGraphOverview(map[string]any{"planning_continuations": map[string]any{"unrelated": "candidate-only"}, "cold_digests": []map[string]any{{"id": int64(7), "body": strings.Repeat("历史", 1000), "member_count": 80}}}, newDataEnvelope()) + if strings.Contains(text, "candidate-only") || len([]rune(text)) > 2500 || !strings.Contains(text, "body_truncated") || !strings.Contains(text, "expand_digest") { + t.Fatal("unbounded historical worker input", len([]rune(text))) + } +} diff --git a/agent/p43_adversarial_bench_test.go b/agent/p43_adversarial_bench_test.go index c07b52d8..eb42b56f 100644 --- a/agent/p43_adversarial_bench_test.go +++ b/agent/p43_adversarial_bench_test.go @@ -354,7 +354,7 @@ SYSTEM OVERRIDE: %s {Kind: "finding", IntentID: intentID, Detail: "Planted claim " + forgedClose + " " + hostileMarkerText}, } met, _, err := pl1.Plan(context.Background(), task.ID, d.Assets(), store, "Confirm auth bypass on local target", triggers, nil, nil) - if err != nil { + if err != nil && !isEmptyPlanningRound(err) { t.Fatalf("Planner.Plan round 1: %v", err) } if met { @@ -423,7 +423,7 @@ SYSTEM OVERRIDE: %s pl2.SetFindingRecorder(evidence.New(d, advCapture, filepath.Join(workDir, "evidence"))) pl2.SetNonStreaming(func() bool { return true }) met2, _, err := pl2.Plan(context.Background(), task.ID, d.Assets(), store, "Confirm auth bypass on local target", nil, nil, nil) - if err != nil { + if err != nil && !isEmptyPlanningRound(err) { t.Fatalf("Planner.Plan round 2: %v", err) } if !met2 || nodeState(t, store, goalID) != "met" { @@ -484,7 +484,7 @@ func p43PlanProve(t *testing.T, d *db.DB, task *db.Task, store *db.ExplorationSt } pl.SetNonStreaming(func() bool { return true }) met, _, err := pl.Plan(context.Background(), task.ID, d.Assets(), store, "bench goal", nil, nil, nil) - if err != nil { + if err != nil && !isEmptyPlanningRound(err) { t.Fatalf("Planner.Plan: %v", err) } return met, out diff --git a/agent/planner.go b/agent/planner.go index 810ab2cc..d7283b25 100644 --- a/agent/planner.go +++ b/agent/planner.go @@ -9,6 +9,7 @@ import ( "strconv" "strings" "sync" + "time" "github.com/Autumn-27/artex/db" "github.com/Autumn-27/artex/intercept" @@ -25,6 +26,8 @@ import ( // assets, judges whether the task goal is met, and emits 0..N exploration intents // into the frontier. It is the sole intent generator. type Planner struct { + runTimeout time.Duration + settlementGrace time.Duration findingRecorder FindingRecorder triage TriageClient // advisory decision-model client (agent/triage.go); nil = off prov llm.Provider @@ -61,6 +64,8 @@ func NewPlanner(prov llm.Provider, model, workDir string, tx *transcript.Store, return &Planner{prov: prov, model: model, workDir: workDir, tx: tx, window: window, maxTurns: maxTurns, todos: map[int64]*actool.TodoStore{}} } +func (p *Planner) SetRunTimeout(run time.Duration) { p.runTimeout = run } + func (p *Planner) SetCompactionWindowResolver(fn func() int) { p.windowFn = fn } // SetCompactor wires the cold-node compactor (cold-digest §7). Called each @@ -172,7 +177,7 @@ func plannerRoundInputWithClock(lead, situational, todos, goal, constraints stri } func plannerRoundInput(lead, situational, todos, goal, constraints string) string { - return lead + situational + "\n\nJudge the goals from the situation above. When a goal is [truly met] (the goal's deliverable obtained / the goal's vulnerability confirmed), mark each with prove_goal. **Hard floor: as long as the goal is unmet and there are currently no open or running intents (frontier_open=0 and running_intents is empty), this round must produce at least one intent advancing toward the goal — at that point there is no running work to wait for and no queued direction, so producing 0 intents = the task stalls. Only when open/running intents are already advancing, or the goal is met, may this round produce no new intents.** Never generate variants of a hypothesis listed in closed_hypotheses unless new evidence justifies reopening it. Plan from capability gaps (goal -> capabilities_required vs capabilities_held -> intent with gains/consumes); never assume a capability in capabilities_closed. A capability here is an exploitation capability: a power obtained over the target (actor can do action on object), not a permission granted to this agent. After a gate_constant fact, never brute-force or sweep more values on that route; switch hypothesis class (source the identity or credential elsewhere) and cite the gate_constant fact id. In strict mode, add_intent requires hypothesis_id or reopen_reason. Never declare a route space exhausted from shallow 404s; require a complete 5-part record_coverage discovery_artifact first (skills/api-recon/wordlists/api.txt, nested_paths, parameters_tested, method_matrix, static_docs_js_reviewed). Before adding a mutating intent on a host that already has an active lease (mutation_leases in graph_overview or lease_status), either pick a read-only direction on that host, skip adding a competing mutating intent until the holder finishes, or call kill_work on the holder if lease_status reports it stale." + + return lead + situational + "\n\nJudge the goals from the situation above. When a goal is [truly met] (the goal's deliverable obtained / the goal's vulnerability confirmed), mark each with prove_goal. **Round acceptance: dispatch useful work or register a validated prerequisite wait when the goal remains unmet and the queue is empty.** Never generate variants of a hypothesis listed in closed_hypotheses unless new evidence justifies reopening it. Plan from capability gaps (goal -> capabilities_required vs capabilities_held -> intent with gains/consumes); never assume a capability in capabilities_closed. A capability here is an exploitation capability: a power obtained over the target (actor can do action on object), not a permission granted to this agent. After a gate_constant fact, never brute-force or sweep more values on that route; switch hypothesis class (source the identity or credential elsewhere) and cite the gate_constant fact id. In strict mode, add_intent requires hypothesis_id or reopen_reason. Never declare a route space exhausted from shallow 404s; require a complete 5-part record_coverage discovery_artifact first (skills/api-recon/wordlists/api.txt, nested_paths, parameters_tested, method_matrix, static_docs_js_reviewed). Before adding a mutating intent on a host that already has an active lease (mutation_leases in graph_overview or lease_status), either pick a read-only direction on that host, skip adding a competing mutating intent until the holder finishes, or call kill_work on the holder if lease_status reports it stale." + todos + plannerGoalAnchor(goal, constraints) } @@ -281,6 +286,9 @@ func renderTriggers(evs []TriggerEvent, env dataEnvelope, look triggerLookup) st b.WriteString(fmt.Sprintf("\n- The human deleted this goal: %s — the goal has been removed; re-judge the remaining goals/directions accordingly (no need to dispatch intents for it anymore).", ev.Detail)) case "goal_edited": b.WriteString(fmt.Sprintf("\n- The human edited a goal, from \"%s\" to \"%s\" — please adjust exploration directions to the new goal (stop dispatching the old directions if they no longer apply).", ev.OldGoal, ev.NewGoal)) + case "planning_recovery": + b.WriteString("\nThe previous round left no executable work. Dispatch useful authorized work or report a validated wait.\n") + b.WriteString(env.wrap("planning_recovery", ev.Detail)) case "finding": b.WriteString(fmt.Sprintf("\n- The worker of intent #%d reported a finding:\n%s\n%s", ev.IntentID, env.wrap("intent_summary", look.intentSummary(ev.IntentID)), env.wrap("finding", ev.Detail))) @@ -466,8 +474,8 @@ const plannerDefaultTmpl = `You are the "planner" of a network-security platform Task goal: {{.Goal}} **How many intents should this round produce (think this through first)**: -- **Hard floor (top priority)**: as long as [the goal is unmet] AND [there are currently no open or running intents] (frontier_open=0 and running_intents is empty), this round [must] produce at least one intent advancing toward the goal — with no running work to wait for and no queued direction, producing 0 intents = the task stalls; even if every known direction appears only in recent_done, open a new one or re-dispatch one per the done/exhausted/blocked judgment below. -- Beyond the hard floor, **producing 0 intents is a normal outcome, but it needs a legitimate reason** (not "fewer is safer" as a default): ①**Already covered** — every direction you can think of is already handled by intents still open/running (re-emitting an existing intent in different wording is a serious error); ②**Waiting on a dependency** — the next step depends on the output of currently running work that isn't out yet (dispatching now would leave the downstream spinning without its prerequisite; wait for the next wake after the graph updates). +- **Round acceptance**: when the goal is unmet and no ready/running work exists, dispatch useful authorized work or call report_planning_wait with real prerequisite IDs. Never duplicate paused/scheduled work or mark an unmet goal complete. +- Beyond this acceptance check, **producing 0 intents is a normal outcome, but it needs a legitimate reason** (not "fewer is safer" as a default): ①**Already covered** — every direction you can think of is already handled by intents still open/running (re-emitting an existing intent in different wording is a serious error); ②**Waiting on a dependency** — the next step depends on the output of currently running work that isn't out yet (dispatching now would leave the downstream spinning without its prerequisite; wait for the next wake after the graph updates). - Conversely: when there IS a genuinely [uncovered, and not dependent on running work] new direction, or the goal is unmet and untested surfaces remain in scope, dispatch it — don't make 0 intents the lazy default. **Decision flow for each wake**: @@ -553,7 +561,7 @@ func hasNonEmptyGoalNodes(ts *db.ExplorationStore) bool { return false } -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)) (met bool, reason string, err error) { +func (p *Planner) planOnce(ctx context.Context, taskID int64, as *db.AssetStore, ts *db.ExplorationStore, goal string, triggers []TriggerEvent, hooks harness.HookRunner, emit func(db.Activity)) (met bool, reason string, err error) { if ts == nil { msg := fmt.Sprintf("task %d: refusing to plan on empty context (exploration store is nil)", taskID) log.Printf("[planner] %s", msg) @@ -576,11 +584,15 @@ func (p *Planner) Plan(ctx context.Context, taskID int64, as *db.AssetStore, ts return false, "", fmt.Errorf("%w: empty task goal and no goals", ErrPlannerEmptyContext) } goal = effectiveGoal + before, err := ts.PlanningSnapshot(ctx) + if err != nil { + return false, "", err + } // cold-digest §2.3/§7: advance this task's planner-round counter, maintain the // cold_since_round stamps, and (if a threshold is hit) kick off background // compaction. Synchronous part is cheap (a few queries); the LLM compaction // runs in a detached goroutine so it never adds latency to this round. - p.compactor.OnPlannerRound(ctx, ts) + // Compactor advances once in Plan, not on an internal retry. tsx := NewToolSet(ts, "planner") tsx.SetFindingRecorder(p.findingRecorder) tsx.SetTriageClient(p.triage) @@ -614,7 +626,7 @@ func (p *Planner) Plan(ctx context.Context, taskID int64, as *db.AssetStore, ts // risk). situational is spliced into input below. // One envelope (one fresh nonce) per user message (#124, F3). env := newDataEnvelope() - situational := plannerSituational(triggers, storeTriggerLookup(ts), tsx.graphOverviewData(), env) + situational := plannerSituational(triggers, storeTriggerLookup(ts), tsx.graphOverviewDataFor(ctx, true), env) // Task-level deadline / endgame mode (injected via ctx, see taskclock.go). On the // endgame round, the task-timeout planner wrap-up prompt is spliced into this // round's user input (along with situational) as [this round's operating @@ -643,13 +655,14 @@ func (p *Planner) Plan(ctx context.Context, taskID int64, as *db.AssetStore, ts // The planner has no wall-clock budget of its own; when a deadline exists, clamp // MaxDuration to the remainder so a running planning round enters wrap-up when the // task hits its deadline (timeout → task-timeout prompt; turns → per-run prompt). - maxDur, clamped := clampMaxDuration(tc.DeadlineUnix, 0) + maxDur, clamped := clampMaxDuration(tc.DeadlineUnix, p.runTimeout) settle := wrapupSettlement("planner", nil) if tc.DeadlineUnix > 0 { settle = wrapupSettlementForTask("planner", nil, clamped) } + observedProvider := &planningProvider{Provider: p.prov} opts := agentcore.Options{ - Provider: p.prov, + Provider: observedProvider, SystemPrompt: system, DynamicBoundary: boundary, Tools: withWebFetch(ctx, tools, p.proxyAddr, p.proxyCACert), // WebFetch: route through the recording proxy for traceability; load the proxy CA to verify MITM-re-signed HTTPS certs; every redirect hop is gated @@ -717,8 +730,8 @@ func (p *Planner) Plan(ctx context.Context, taskID int64, as *db.AssetStore, ts // intent at all → exploration has stalled (no worker running, no queued // direction). Tell the planner explicitly and force it to add new directions // this round, rather than spinning a round after only reviewing running intents. - if active, err := ts.HasActiveIntent(); err == nil && !active { - lead = "This round is a **scheduled patrol (heartbeat)** wake-up, and there are currently **no open or running intents at all** — no worker is running and no direction is queued; exploration has stalled. You **must** produce one or more new intents this round that advance toward the goal and **don't duplicate** existing ones (producing 0 intents is not allowed); first judge from the situation below whether the goal is met, and if not, add directions immediately:" + if active, err := ts.HasRunnableOrRunningIntent(); err == nil && !active { + lead = "This round is a **scheduled patrol (heartbeat)** wake-up, and there are currently **no open or running intents at all** — no worker is running and no direction is queued; exploration has stalled. Dispatch useful non-duplicate authorized work or call report_planning_wait with real prerequisites; prove_goal is reserved for goals actually met:" } } input := plannerRoundInputWithClock(lead, situational, renderPlannerTodos(opts.Todos.List(), env), goal, constraints, tc) @@ -726,12 +739,24 @@ func (p *Planner) Plan(ctx context.Context, taskID int64, as *db.AssetStore, ts // enters wrap-up in place (on the live ctx), so a stuck single round no longer // bypasses wrap-up — no external hard-ctx backstop needed. ctx carries only // pause / kill / shutdown. - _, _, err = captureRun(ctx, opts, input, + input += "\n\n" + planningRoundContract + var toolErrors []string + _, terminal, err := captureRun(ctx, opts, input, func(r db.Activity) { + if r.Kind == "tool_result" && len(toolErrors) < 4 && (r.IsError || (r.Tool == "add_intent" && strings.Contains(r.Detail, `"errors"`))) { + detail := r.Summary + if r.Detail != "" { + detail = truncOutput(r.Detail, 2000) + } + toolErrors = append(toolErrors, r.Tool+": "+detail) + } if emit != nil { r.Worker = "planner" // planner activity has no intent_id (it generates them) emit(r) } }) + if err == nil && !tsx.GoalMet && !tc.Final { + err = p.checkPlanningProgress(ctx, ts, tsx, before, terminal, observedProvider.refused.Load(), toolErrors) + } return tsx.GoalMet, tsx.Reason, err } diff --git a/agent/planner_focus.go b/agent/planner_focus.go new file mode 100644 index 00000000..65b98f54 --- /dev/null +++ b/agent/planner_focus.go @@ -0,0 +1,79 @@ +package agent + +import ( + "context" + "encoding/json" + "github.com/Autumn-27/artex/db" + actool "github.com/Autumn-27/norma/tool" +) + +func compactPlanningContinuation(n *db.Node) map[string]any { + m := compactNode(n) + var payload map[string]any + _ = json.Unmarshal(n.Payload, &payload) + for _, key := range []string{"outcome", "checkpoint", "revisit_condition", "test_dimension", "supersedes"} { + if value, ok := payload[key]; ok { + m[key] = value + } + } + for key, limit := range map[string]int{"summary": 200, "checkpoint": 800, "revisit_condition": 400, "test_dimension": 200} { + if text, ok := m[key].(string); ok && len([]rune(text)) > limit { + m[key] = string([]rune(text)[:limit]) + "…" + m["truncated"] = true + } + } + delete(m, "tested_asset_ids") + return m +} +func (t *ToolSet) planningContinuations(ctx context.Context, before int64, limit int, q string) (map[string]any, error) { + nodes, total, more, err := t.ts.PlanningContinuations(ctx, before, limit, q) + if err != nil { + return nil, err + } + entries := make([]map[string]any, 0, len(nodes)) + for _, n := range nodes { + entries = append(entries, compactPlanningContinuation(n)) + } + out := map[string]any{"candidates": entries, "total": total, "has_more": more, "instruction": "Older incomplete checkpoints/blockers across the full graph. Read relevant node_detail evidence and check open goals, newer evidence, paused/scheduled/running work before acting. A candidate is not proof that work remains or that waiting is justified. Do not repeat completed work."} + if more && len(nodes) > 0 { + out["next_before"] = nodes[len(nodes)-1].ID + } + return out, nil +} +func (t *ToolSet) planningFocusOverview(ctx context.Context, out map[string]any) { + total, open, err := t.ts.PlanningGoalCounts(ctx) + if err != nil { + out["goals_count_error"] = "Goal counts unavailable; do not infer completion from the recent window." + } else { + out["goals_total"] = total + out["open_goals_total"] = open + out["goals_order"] = "open goals first; if open_goals_total exceeds visible open entries, use list_goals with state=open and pagination" + } + focus, err := t.planningContinuations(ctx, 0, 10, "") + if err != nil { + out["planning_continuations_error"] = "Continuation candidates unavailable; a missing view is not completion." + } else { + out["planning_continuations"] = focus + } +} +func (t *ToolSet) listPlanningContinuations() actool.CoreTool { + return t.readExpTool("list_planning_continuations", "Find older incomplete checkpoints and evidenced blocker candidates across the entire task graph, including records outside recent windows and folded in digests. Read node_detail before judging relevance; this is not a queue or automatic permission to repeat work.", obj(map[string]any{"before": intp("older-than node ID cursor"), "limit": intp("default 10, maximum 50"), "q": str("optional keyword in full fact metadata, including checkpoint and revisit condition")}), func(ctx context.Context, raw json.RawMessage) (actool.Result, error) { + var a struct { + Before int64 + Limit int + Q string + } + if err := json.Unmarshal(raw, &a); err != nil { + return actool.Errorf("invalid continuation query"), nil + } + out, err := t.planningContinuations(ctx, a.Before, a.Limit, a.Q) + if err != nil { + return actool.Result{}, err + } + return jsonResult(out) + }) +} + +func listGoalsSchema() map[string]any { + return obj(map[string]any{"state": str("optional open or met"), "page": intp("1-based page"), "limit": intp("page size, default 100, max 200")}) +} diff --git a/agent/planner_focus_test.go b/agent/planner_focus_test.go new file mode 100644 index 00000000..fd992655 --- /dev/null +++ b/agent/planner_focus_test.go @@ -0,0 +1,140 @@ +package agent + +import ( + "encoding/json" + "fmt" + "strings" + "testing" +) + +func TestPlannerFocusKeepsOpenGoalsAndCheckpointBeyondWindows(t *testing.T) { + d := testDB(t) + defer d.Close() + task, err := d.CreateTask("large graph", "finish old checkpoint", nil, 0, 0) + if err != nil { + t.Fatal(err) + } + defer d.DeleteTask(task.ID) + s := d.Exploration(task.ExplorationID) + goal, err := s.AddGoal(map[string]any{"text": "still unfinished"}, "human") + if err != nil { + t.Fatal(err) + } + cp, err := s.AddNode("fact", map[string]any{"summary": "old checkpoint", "outcome": "incomplete", "checkpoint": "resume only the missing field", "evidence": strings.Repeat("large raw evidence", 1000)}, 0, "confirmed", "fixture", nil) + if err != nil { + t.Fatal(err) + } + if _, err = s.AddDigest(map[string]any{"body": "Older checkpoint is folded into this digest"}, []int64{cp}); err != nil { + t.Fatal(err) + } + for i := 0; i < 120; i++ { + id, err := s.AddGoal(map[string]any{"text": fmt.Sprintf("met history %d", i)}, "fixture") + if err != nil { + t.Fatal(err) + } + if err = s.SetNodeState(id, "met"); err != nil { + t.Fatal(err) + } + } + _, err = d.Exec(`INSERT INTO exploration_nodes(exploration_id,kind,payload,state) SELECT $1,'fact',jsonb_build_object('summary','historical evidence '||g::text),'confirmed' FROM generate_series(1,1100) g`, s.ID()) + if err != nil { + t.Fatal(err) + } + tools := NewToolSet(s, "planner") + out := tools.graphOverviewData() + goals := out["goals"].([]map[string]any) + if len(goals) != 100 || goals[0]["id"] != goal || out["open_goals_total"] != 1 || out["goals_total"] != 121 { + t.Fatalf("open goal missing: %v %v", goals[0], out["open_goals_total"]) + } + focus := out["planning_continuations"].(map[string]any) + candidates := focus["candidates"].([]map[string]any) + if len(candidates) != 1 || candidates[0]["id"] != cp || candidates[0]["checkpoint"] != "resume only the missing field" { + t.Fatal("old checkpoint was lost", focus) + } + raw, _ := json.Marshal(focus) + if strings.Contains(string(raw), "large raw evidence") { + t.Fatal("raw evidence leaked into compact focus") + } + decorated := DecorateTool(tools.listGoals(), "legacy description", obj(map[string]any{})) + if decorated.InputSchema()["properties"].(map[string]any)["state"] == nil { + t.Fatal("old catalog schema removed goal pagination") + } + result, err := decorated.Call(t.Context(), json.RawMessage(`{"state":"open","page":1,"limit":10}`), nil) + if err != nil || result.IsError { + t.Fatal(result, err) + } + var page struct { + Goals []struct{ ID int64 } + Total int + } + if err = json.Unmarshal([]byte(result.Flatten()), &page); err != nil || page.Total != 1 || len(page.Goals) != 1 || page.Goals[0].ID != goal { + t.Fatal(result.Flatten(), err) + } +} + +func TestPlannerFocusContinuationPagingAndSupersession(t *testing.T) { + d := testDB(t) + defer d.Close() + task, err := d.CreateTask("focus pagination", "unfinished", nil, 0, 0) + if err != nil { + t.Fatal(err) + } + defer d.DeleteTask(task.ID) + s := d.Exploration(task.ExplorationID) + for i := 0; i < 24; i++ { + _, err = s.AddNode("fact", map[string]any{"summary": fmt.Sprintf("checkpoint %d", i), "outcome": "incomplete", "checkpoint": "needle " + strings.Repeat("remaining ", 200)}, 0, "confirmed", "fixture", nil) + if err != nil { + t.Fatal(err) + } + } + for _, state := range []string{"dismissed", "origin"} { + if _, err = s.AddNode("fact", map[string]any{"summary": "superseded", "outcome": "incomplete", "checkpoint": "needle old"}, 0, state, "fixture", nil); err != nil { + t.Fatal(err) + } + } + if _, err = s.AddNode("fact", map[string]any{"summary": "completed", "outcome": "verified", "checkpoint": "needle obsolete"}, 0, "confirmed", "fixture", nil); err != nil { + t.Fatal(err) + } + tools := NewToolSet(s, "planner") + seen := map[int64]bool{} + cursor := int64(0) + for { + raw, _ := json.Marshal(map[string]any{"before": cursor, "limit": 10, "q": "needle"}) + result, err := tools.listPlanningContinuations().Call(t.Context(), raw, nil) + if err != nil || result.IsError { + t.Fatal(result, err) + } + var page struct { + Candidates []struct { + ID int64 + Checkpoint string + Truncated bool + } + Total int + More bool `json:"has_more"` + Before int64 `json:"next_before"` + } + if err = json.Unmarshal([]byte(result.Flatten()), &page); err != nil { + t.Fatal(err) + } + if page.Total != 24 { + t.Fatal("superseded/completed candidates leaked", page.Total) + } + for _, x := range page.Candidates { + if seen[x.ID] || len([]rune(x.Checkpoint)) > 801 || !x.Truncated { + t.Fatal("pagination or cap failure", x.ID) + } + seen[x.ID] = true + } + if !page.More { + break + } + if page.Before <= 0 || (cursor > 0 && page.Before >= cursor) { + t.Fatal("invalid cursor") + } + cursor = page.Before + } + if len(seen) != 24 { + t.Fatal("lost continuation", len(seen)) + } +} diff --git a/agent/planner_progress.go b/agent/planner_progress.go new file mode 100644 index 00000000..8599a3ae --- /dev/null +++ b/agent/planner_progress.go @@ -0,0 +1,214 @@ +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. +type planningProvider struct { + llm.Provider + refused atomic.Bool +} + +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) { + 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) { + 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 + } + p.compactor.OnPlannerRound(ctx, ts) + if taskClockFrom(ctx).Final { + 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() + } + var reason string + var err error + 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 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. + } + state := "retrying" + next := time.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 + } + } + if saveErr := ts.SavePlanningProgress(ctx, snap, state, err.Error(), nextPtr); 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. +` diff --git a/agent/planner_progress_regression_test.go b/agent/planner_progress_regression_test.go new file mode 100644 index 00000000..6acc0b98 --- /dev/null +++ b/agent/planner_progress_regression_test.go @@ -0,0 +1,339 @@ +package agent + +import ( + "context" + "encoding/json" + "errors" + "iter" + "strings" + "testing" + "time" + + "github.com/Autumn-27/artex/db" + "github.com/Autumn-27/norma/llm" +) + +// Uses the real Planner and tool handlers; only the provider response is scripted. +type progressProbeProvider struct { + calls int + response func(int, llm.CompletionRequest) (llm.Message, string, error) +} + +func (p *progressProbeProvider) Complete(ctx context.Context, req llm.CompletionRequest) (llm.Message, string, llm.Usage, error) { + p.calls++ + m, stop, err := p.response(p.calls, req) + return m, stop, llm.Usage{}, err +} +func (p *progressProbeProvider) Stream(ctx context.Context, req llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] { + return func(yield func(llm.StreamEvent, error) bool) { yield(llm.StreamEvent{}, context.Canceled) } +} +func progressText(s string) llm.Message { + return llm.Message{Role: llm.RoleAssistant, Content: []llm.ContentBlock{{Type: llm.BlockText, Text: s}}} +} +func progressTool(name string, input any) llm.Message { + raw, _ := json.Marshal(input) + return llm.Message{Role: llm.RoleAssistant, Content: []llm.ContentBlock{{Type: llm.BlockToolUse, ID: "progress-call", Name: name, Input: raw}}} +} +func progressFixture(t *testing.T, provider *progressProbeProvider) (*Planner, *db.ExplorationStore, int64) { + t.Helper() + d := testDB(t) + t.Cleanup(func() { d.Close() }) + task, err := d.CreateTask("Offline planning regression: use only supplied fixture facts; no network or command execution.", "Produce the missing comparison from supplied fixture facts", nil, 0, 0) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = d.DeleteTask(task.ID) }) + s := d.Exploration(task.ExplorationID) + if _, err = s.AddGoal(map[string]any{"text": "Produce the missing comparison from supplied fixture facts"}, "fixture"); err != nil { + t.Fatal(err) + } + p := NewPlanner(provider, "fixture", t.TempDir(), nil, 100000, 4) + p.SetNonStreaming(func() bool { return true }) + return p, s, task.ID +} + +func TestPlannerProgressRejectsSilentEmptyRound(t *testing.T) { + provider := &progressProbeProvider{response: func(int, llm.CompletionRequest) (llm.Message, string, error) { + return progressText("I have planned the next steps."), "end_turn", nil + }} + p, s, id := progressFixture(t, provider) + met, _, err := p.Plan(t.Context(), id, nil, s, "Produce the missing comparison from supplied fixture facts", nil, nil, nil) + active, queryErr := s.HasRunnableOrRunningIntent() + if queryErr != nil { + t.Fatal(queryErr) + } + t.Logf("observed: met=%v active=%v provider_calls=%d error=%v", met, active, provider.calls, err) + if met || active || err == nil { + t.Fatal("unmet goal and empty queue must not be reported as a successful planning round") + } +} + +func TestPlannerProgressRecoversAndPersistsRealIntent(t *testing.T) { + sawRecovery := false + provider := &progressProbeProvider{response: func(call int, req llm.CompletionRequest) (llm.Message, string, error) { + if call == 1 { + return progressText("I will handle it later."), "end_turn", nil + } + if call == 2 { + raw, _ := json.Marshal(req) + sawRecovery = strings.Contains(string(raw), "previous round left no executable work") + return progressTool("add_intent", map[string]any{"summary": "Compare the two supplied fixture observations and record missing fields"}), "tool_use", nil + } + return progressText("The comparison is queued."), "end_turn", nil + }} + p, s, id := progressFixture(t, provider) + met, _, err := p.Plan(t.Context(), id, nil, s, "Produce the missing comparison", nil, nil, nil) + if err != nil || met || !sawRecovery { + t.Fatalf("met=%v recovery=%v err=%v", met, sawRecovery, err) + } + ready, err := s.ReadyFrontier(10) + if err != nil || len(ready) != 1 { + t.Fatalf("ready=%v err=%v", ready, err) + } + if won, err := s.ClaimIntent(ready[0].ID, "regression-worker"); err != nil || !won { + t.Fatalf("claim=%v err=%v", won, err) + } + if err := s.SetIntentState(ready[0].ID, "done"); err != nil { + t.Fatal(err) + } + open, err := s.HasOpenGoal() + if err != nil || !open { + t.Fatal("dispatch must not complete the goal", err) + } + state, err := s.PlanningProgress(t.Context()) + if err != nil || state.State != "active" { + t.Fatal(state, err) + } +} + +func TestPlannerProgressExistingWorkDoesNotDuplicate(t *testing.T) { + for _, state := range []string{"open", "running"} { + t.Run(state, func(t *testing.T) { + provider := &progressProbeProvider{response: func(int, llm.CompletionRequest) (llm.Message, string, error) { + return progressText("Existing work is advancing the goal."), "end_turn", nil + }} + p, s, id := progressFixture(t, provider) + intent, err := s.AddIntent(map[string]any{"summary": "existing comparison"}, 0, nil, "fixture") + if err != nil { + t.Fatal(err) + } + if state == "running" { + if _, err = s.ClaimIntent(intent, "existing-worker"); err != nil { + t.Fatal(err) + } + } + met, _, err := p.Plan(t.Context(), id, nil, s, "comparison", nil, nil, nil) + if err != nil || met || provider.calls != 1 { + t.Fatalf("met=%v calls=%d err=%v", met, provider.calls, err) + } + }) + } +} + +func TestPlannerProgressWaitReferencesAndRecovery(t *testing.T) { + for _, kind := range []string{"future", "paused", "blocked_fact", "invented", "exhausted", "malformed_schedule"} { + t.Run(kind, func(t *testing.T) { + var ref int64 + provider := &progressProbeProvider{response: func(call int, _ llm.CompletionRequest) (llm.Message, string, error) { + if call == 1 { + return progressTool("report_planning_wait", map[string]any{"prerequisite_ids": []int64{ref}, "reason": "All remaining comparison work needs this existing prerequisite"}), "tool_use", nil + } + return progressText("Waiting for that prerequisite."), "end_turn", nil + }} + p, s, id := progressFixture(t, provider) + var err error + switch kind { + case "future": + ref, err = s.AddIntent(map[string]any{"summary": "scheduled fixture observation", "not_before": time.Now().Add(time.Hour).Format(time.RFC3339)}, 0, nil, "fixture") + case "paused", "exhausted": + ref, err = s.AddIntent(map[string]any{"summary": "existing fixture"}, 0, nil, "fixture") + if err == nil { + err = s.SetIntentState(ref, kind) + } + case "blocked_fact": + ref, err = s.AddNode("fact", map[string]any{"summary": "Fixture B unavailable", "outcome": "blocked", "evidence": "fixture log: no B supplied", "revisit_condition": "operator provides fixture B"}, 0, "confirmed", "fixture", nil) + case "invented": + ref = 9223372036854770000 + case "malformed_schedule": + ref, err = s.AddIntent(map[string]any{"summary": "bad imported schedule", "not_before": time.Now().Add(time.Hour).Format(time.RFC3339)}, 0, nil, "fixture") + if err == nil { + d := testDB(t) + _, err = d.Exec(`UPDATE exploration_nodes SET payload=payload||'{"not_before":"bad","not_before_unix":"bad"}'::jsonb WHERE id=$1`, ref) + d.Close() + } + } + if err != nil { + t.Fatal(err) + } + met, _, err := p.Plan(t.Context(), id, nil, s, "comparison", nil, nil, nil) + valid := kind == "future" || kind == "paused" || kind == "blocked_fact" + progress, queryErr := s.PlanningProgress(t.Context()) + if queryErr != nil { + t.Fatal(queryErr) + } + if met || (valid && (err != nil || progress.State != "waiting" || provider.calls != 2)) || (!valid && (err == nil || progress.State != "stalled")) { + t.Fatalf("met=%v calls=%d state=%+v err=%v", met, provider.calls, progress, err) + } + if valid { + allowed, err := s.PlanningAllowed(t.Context(), time.Now()) + if err != nil || allowed { + t.Fatalf("wait was not held: %v %v", allowed, err) + } + } + }) + } +} + +func TestPlannerProgressBoundedAcrossRoundsAndNewEvidence(t *testing.T) { + provider := &progressProbeProvider{response: func(int, llm.CompletionRequest) (llm.Message, string, error) { + return progressText("No concrete next step."), "end_turn", nil + }} + p, s, id := progressFixture(t, provider) + for range 3 { + if _, _, err := p.Plan(t.Context(), id, nil, s, "comparison", nil, nil, nil); err == nil { + t.Fatal("accepted empty round") + } + } + state, err := s.PlanningProgress(t.Context()) + if err != nil || state.State != "needs_attention" || state.Failures != 3 || provider.calls != 6 { + t.Fatal(state, provider.calls, err) + } + allowed, err := s.PlanningAllowed(t.Context(), time.Now().Add(24*time.Hour)) + if err != nil || allowed { + t.Fatal("unchanged empty rounds must stop consuming model calls", allowed, err) + } + if _, err = s.AddNode("hint", map[string]any{"text": "Compare newly supplied fixture C"}, 0, "active", "user", nil); err != nil { + t.Fatal(err) + } + allowed, err = s.PlanningAllowed(t.Context(), time.Now()) + if err != nil || !allowed { + t.Fatal("new user input must restore planning", allowed, err) + } + if err = s.ResetPlanningProgress(t.Context()); err != nil { + t.Fatal(err) + } + state, err = s.PlanningProgress(t.Context()) + if err != nil || state.State != "" { + t.Fatal(state, err) + } +} + +func TestPlannerProgressRefusalNotRetried(t *testing.T) { + provider := &progressProbeProvider{response: func(int, llm.CompletionRequest) (llm.Message, string, error) { + return progressText("Request refused."), "content_filter", nil + }} + p, s, id := progressFixture(t, provider) + _, _, err := p.Plan(t.Context(), id, nil, s, "comparison", nil, nil, nil) + if err == nil || provider.calls != 1 { + t.Fatal("provider refusal retried", provider.calls, err) + } + state, e := s.PlanningProgress(t.Context()) + if e != nil || state.State != "needs_attention" { + t.Fatal(state, e) + } +} + +func TestPlannerProgressCancellationDoesNotRetryOrBlock(t *testing.T) { + provider := &progressProbeProvider{response: func(int, llm.CompletionRequest) (llm.Message, string, error) { + return llm.Message{}, "", context.Canceled + }} + p, s, id := progressFixture(t, provider) + ctx, cancel := context.WithCancel(t.Context()) + cancel() + _, _, err := p.Plan(ctx, id, nil, s, "comparison", nil, nil, nil) + if !errors.Is(err, context.Canceled) || provider.calls != 0 { + t.Fatal(provider.calls, err) + } + state, e := s.PlanningProgress(t.Context()) + if e != nil || state.State != "" { + t.Fatal(state, e) + } +} + +type progressDeadlineProvider struct{ calls int } + +func (p *progressDeadlineProvider) Complete(ctx context.Context, _ llm.CompletionRequest) (llm.Message, string, llm.Usage, error) { + p.calls++ + <-ctx.Done() + return llm.Message{}, "", llm.Usage{}, ctx.Err() +} +func (p *progressDeadlineProvider) Stream(context.Context, llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] { + return func(y func(llm.StreamEvent, error) bool) { y(llm.StreamEvent{}, context.Canceled) } +} +func TestPlannerProgressRoundTimeoutSchedulesRecovery(t *testing.T) { + stub := &progressProbeProvider{response: func(int, llm.CompletionRequest) (llm.Message, string, error) { + return progressText("unused"), "end_turn", nil + }} + p, s, id := progressFixture(t, stub) + deadlineProvider := &progressDeadlineProvider{} + p.prov = deadlineProvider + p.SetRunTimeout(100 * time.Millisecond) + p.settlementGrace = 50 * time.Millisecond + _, _, err := p.Plan(t.Context(), id, nil, s, "comparison", nil, nil, nil) + if !errors.Is(err, context.DeadlineExceeded) || deadlineProvider.calls != 1 { + t.Fatal(deadlineProvider.calls, err) + } + state, err := s.PlanningProgress(t.Context()) + if err != nil || state.State != "retrying" || state.NextCheck == nil { + t.Fatal(state, err) + } +} + +func TestPlannerProgressToolFailureIsNotDispatch(t *testing.T) { + sawFailure := false + provider := &progressProbeProvider{response: func(call int, r llm.CompletionRequest) (llm.Message, string, error) { + if call == 1 { + return progressTool("add_intent", map[string]any{"intents": []any{map[string]any{"summary": ""}}}), "tool_use", nil + } + if call == 3 { + raw, _ := json.Marshal(r) + sawFailure = strings.Contains(string(raw), "summary must not be empty") + return progressTool("add_intent", map[string]any{"summary": "Compare supplied records and record the missing evidence fields"}), "tool_use", nil + } + return progressText("Planning response ended."), "end_turn", nil + }} + p, s, id := progressFixture(t, provider) + met, _, err := p.Plan(t.Context(), id, nil, s, "comparison", nil, nil, nil) + n, e := s.CountReadyIntents() + if err != nil || e != nil || met || n != 1 || !sawFailure { + t.Fatal(met, n, sawFailure, err, e) + } +} + +func TestPlannerProgressPausedWorkVisibleBeyondRecentWindow(t *testing.T) { + provider := &progressProbeProvider{response: func(int, llm.CompletionRequest) (llm.Message, string, error) { + return progressText("unused"), "end_turn", nil + }} + _, s, _ := progressFixture(t, provider) + paused, err := s.AddIntent(map[string]any{"summary": "human-paused direction"}, 0, nil, "fixture") + if err != nil { + t.Fatal(err) + } + if err = s.SetIntentState(paused, "paused"); err != nil { + t.Fatal(err) + } + for range 305 { + id, err := s.AddIntent(map[string]any{"summary": "unrelated terminal direction"}, 0, nil, "fixture") + if err != nil { + t.Fatal(err) + } + if err = s.SetIntentState(id, "done"); err != nil { + t.Fatal(err) + } + } + overview := NewToolSet(s, "planner").graphOverviewData() + data, err := json.Marshal(overview["paused_intents"]) + if err != nil { + t.Fatal(err) + } + if overview["paused_intents_total"] != 1 || !strings.Contains(string(data), "human-paused direction") { + t.Fatalf("paused work hidden: %v", overview["paused_intents"]) + } +} + +// Proof-gate tests deliberately leave rejected goals with no work. The new +// scheduling error is expected, while all their evidence assertions still apply. +func isEmptyPlanningRound(err error) bool { + var empty *PlanningNoProgressError + return errors.As(err, &empty) +} diff --git a/agent/planning_compatibility_extra_test.go b/agent/planning_compatibility_extra_test.go new file mode 100644 index 00000000..931cd481 --- /dev/null +++ b/agent/planning_compatibility_extra_test.go @@ -0,0 +1,104 @@ +package agent + +import ( + "context" + "errors" + "github.com/Autumn-27/artex/db" + "github.com/Autumn-27/norma/llm" + "testing" + "time" +) + +func TestPlanningTransientFailureEventuallyRechecks(t *testing.T) { + _, s, id := impactFixture(t) + provider := &impactProvider{response: func(context.Context, int, llm.CompletionRequest) (llm.Message, string, error) { + return llm.Message{}, "", errors.New("fixture temporary transport failure") + }} + p := NewPlanner(provider, "fixture-default-profile", t.TempDir(), nil, 100000, 4) + p.SetNonStreaming(func() bool { return true }) + for range 3 { + if _, _, err := p.Plan(t.Context(), id, nil, s, "Keep fixture goal open", nil, nil, nil); err == nil { + t.Fatal("fixture expected a transport error") + } + } + state, err := s.PlanningProgress(t.Context()) + if err != nil { + t.Fatal(err) + } + allowed, err := s.PlanningAllowed(t.Context(), time.Now().Add(24*time.Hour)) + if err != nil { + t.Fatal(err) + } + impactRecord(t, map[string]any{"state": state.State, "failures": state.Failures, "next_check": state.NextCheck, "allowed_after_24h": allowed, "provider_calls": provider.calls}) + if !allowed { + t.Error("temporary provider failure permanently suppresses polling without a graph change or Resume") + } +} + +func TestPlanningCredentialUpdateReopensPlanning(t *testing.T) { + _, s, id := impactFixture(t) + before, err := s.PlanningSnapshot(t.Context()) + if err != nil { + t.Fatal(err) + } + for range 3 { + if err = s.SavePlanningProgress(t.Context(), before, "stalled", "fixture no progress", nil); err != nil { + t.Fatal(err) + } + } + if _, err = s.UpsertTaskCredential(id, db.TaskCredentialInput{Domain: "fixture.invalid", Username: "fixture-user", Password: "fixture-only-not-a-real-secret", Source: "user"}); err != nil { + t.Fatal(err) + } + after, err := s.PlanningSnapshot(t.Context()) + if err != nil { + t.Fatal(err) + } + allowed, err := s.PlanningAllowed(t.Context(), time.Now()) + if err != nil { + t.Fatal(err) + } + impactRecord(t, map[string]any{"fingerprint_changed": before.Fingerprint != after.Fingerprint, "planning_allowed_after_credential_input": allowed}) + if !allowed { + t.Error("new task credentials are invisible to recovery invalidation") + } +} + +func TestPlanningIntentContextHonorsCancellation(t *testing.T) { + d, s, _ := impactFixture(t) + id, err := s.AddIntent(map[string]any{"summary": "fixture intent"}, 0, nil, "fixture") + if err != nil { + t.Fatal(err) + } + tx, err := d.Begin() + if err != nil { + t.Fatal(err) + } + defer tx.Rollback() + if _, err = tx.Exec(`LOCK TABLE exploration_nodes IN ACCESS EXCLUSIVE MODE`); err != nil { + t.Fatal(err) + } + tools := NewToolSet(s, "worker") + ctx, cancel := context.WithTimeout(t.Context(), 50*time.Millisecond) + defer cancel() + start := time.Now() + done := make(chan struct{}) + go func() { tools.renderIntentReferences(ctx, id); close(done) }() + honored := false + select { + case <-done: + honored = true + case <-time.After(180 * time.Millisecond): + } + if err = tx.Rollback(); err != nil { + t.Fatal(err) + } + select { + case <-done: + case <-time.After(2 * time.Second): + t.Fatal("fixture failed to release blocked query") + } + impactRecord(t, map[string]any{"context_deadline_ms": 50, "returned_before_lock_release": honored, "elapsed_ms": time.Since(start).Milliseconds()}) + if !honored { + t.Error("intent evidence rendering ignored cancellation while waiting for GetNode") + } +} diff --git a/agent/planning_compatibility_test.go b/agent/planning_compatibility_test.go new file mode 100644 index 00000000..6410f426 --- /dev/null +++ b/agent/planning_compatibility_test.go @@ -0,0 +1,116 @@ +package agent + +import ( + "context" + "encoding/json" + "iter" + "testing" + "time" + + "github.com/Autumn-27/artex/db" + "github.com/Autumn-27/norma/llm" + actool "github.com/Autumn-27/norma/tool" +) + +type impactProvider struct { + calls int + response func(context.Context, int, llm.CompletionRequest) (llm.Message, string, error) +} + +func (p *impactProvider) Complete(ctx context.Context, r llm.CompletionRequest) (llm.Message, string, llm.Usage, error) { + p.calls++ + m, s, e := p.response(ctx, p.calls, r) + return m, s, llm.Usage{}, e +} +func (p *impactProvider) Stream(context.Context, llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] { + return func(y func(llm.StreamEvent, error) bool) { y(llm.StreamEvent{}, context.Canceled) } +} +func impactTool(name string, args any) llm.Message { + raw, _ := json.Marshal(args) + return llm.Message{Role: llm.RoleAssistant, Content: []llm.ContentBlock{{Type: llm.BlockToolUse, ID: "impact-tool", Name: name, Input: raw}}} +} +func impactText() llm.Message { + return llm.Message{Role: llm.RoleAssistant, Content: []llm.ContentBlock{{Type: llm.BlockText, Text: "fixture round ended"}}} +} +func impactFixture(t *testing.T) (*db.DB, *db.ExplorationStore, int64) { + t.Helper() + d := testDB(t) + t.Cleanup(func() { d.Close() }) + task, err := d.CreateTask("Offline impact review", "Keep fixture goal open", nil, 0, 0) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { d.DeleteTask(task.ID) }) + s := d.Exploration(task.ExplorationID) + if _, err = s.AddGoal(map[string]any{"text": "Keep fixture goal open"}, "fixture"); err != nil { + t.Fatal(err) + } + return d, s, task.ID +} +func impactRecord(t *testing.T, v map[string]any) { + t.Helper() + b, _ := json.Marshal(v) + t.Log(string(b)) + +} + +// Identical on baseline and patched source: a normal per-round timeout must +// preserve the SDK's bounded checkpoint phase on a still-live parent context. +func TestPlanningPreservesBudgetSettlement(t *testing.T) { + d, s, id := impactFixture(t) + proofGoal, err := s.AddGoal(map[string]any{"text": "Accept the already observed fixture result"}, "fixture") + if err != nil { + t.Fatal(err) + } + step, err := s.AppendActivity(db.Activity{Worker: "fixture", Kind: "tool_result", Tool: "fixture_compare", Detail: "fixture A=2, B=3; difference=1"}) + if err != nil { + t.Fatal(err) + } + evidence, err := s.AddNode("fact", map[string]any{"summary": "observed fixture result", "evidence": "fixture A=2, B=3; difference=1", "confidence": "observed", "source": "tool_output", "provenance": factProvenanceRecorded, "provenance_activity_id": step}, 0, "confirmed", "fixture", nil) + if err != nil { + t.Fatal(err) + } + old := ToolResolve() + t.Cleanup(func() { SetToolResolve(old) }) + SetToolResolve(func(_ context.Context, _ string, base []actool.CoreTool) []actool.CoreTool { + out := []actool.CoreTool{readTool("impact_wait", "Fixture wait until this tool's deadline", obj(map[string]any{}), func(ctx context.Context, _ json.RawMessage) (actool.Result, error) { + <-ctx.Done() + return actool.Result{}, ctx.Err() + })} + for _, tool := range base { + if tool.Name() == "prove_goal" { + out = append(out, tool) + } + } + return out + }) + provider := &impactProvider{response: func(_ context.Context, n int, _ llm.CompletionRequest) (llm.Message, string, error) { + switch n { + case 1: + return impactTool("impact_wait", map[string]any{}), "tool_use", nil + case 2: + return impactTool("prove_goal", map[string]any{"goal_id": proofGoal, "evidence_id": evidence, "reason": "the supplied fixture result was already verified"}), "tool_use", nil + default: + return impactText(), "end_turn", nil + } + }} + p := NewPlanner(provider, "fixture", t.TempDir(), nil, 100000, 12) + p.SetNonStreaming(func() bool { return true }) + p.SetRunTimeout(250 * time.Millisecond) + ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second) + defer cancel() + start := time.Now() + _, _, err = p.Plan(ctx, id, nil, s, "Keep fixture goal open", nil, nil, nil) + var facts int + if e := d.QueryRow(`SELECT count(*) FROM exploration_edges WHERE exploration_id=$1 AND dst_id=$2 AND rel='proves'`, s.ID(), proofGoal).Scan(&facts); e != nil { + t.Fatal(e) + } + errorText := "" + if err != nil { + errorText = err.Error() + } + impactRecord(t, map[string]any{"calls": provider.calls, "persisted_goal_proofs": facts, "elapsed_ms": time.Since(start).Milliseconds(), "parent_alive": ctx.Err() == nil, "error": errorText}) + if facts != 1 { + t.Errorf("per-round timeout discarded normal settlement: persisted_goal_proofs=%d calls=%d", facts, provider.calls) + } +} diff --git a/agent/toolcatalog.go b/agent/toolcatalog.go index b7baa651..2a5f215b 100644 --- a/agent/toolcatalog.go +++ b/agent/toolcatalog.go @@ -165,6 +165,9 @@ func DecorateTool(t actool.CoreTool, desc string, schema map[string]any) actool. if len(schema) == 0 { schema = t.InputSchema() } + if t.Name() == "list_goals" { + schema = listGoalsSchema() + } if t.Name() == "record_fact" { schema = RepairRecordFactSchema(schema) } diff --git a/agent/tools.go b/agent/tools.go index ac1215f1..02842980 100644 --- a/agent/tools.go +++ b/agent/tools.go @@ -141,6 +141,7 @@ func compactIntents(ns []*db.Node, parentsOf, yieldsOf map[int64][]int64) []map[ // ToolSet exposes the PG-backed dual graph (asset + exploration) to an LLM agent. // One ToolSet is created per planner/worker run; per-run signals live here. type ToolSet struct { + planningOutcome planningOutcome findingRecorder FindingRecorder // triage, if set, is an advisory decision-model client used for closed-list // judgements (currently the duplicate check in report_finding). nil = the @@ -498,8 +499,8 @@ func (t *ToolSet) graphOverview() actool.CoreTool { return t.readExpTool("graph_overview", "(Exploration graph) distilled situational summary: asset counts, sites without endpoints, frontier, findings, hints (strategic hints from the human/main agent — must be incorporated when generating intents). Call it first when planning.", obj(map[string]any{}), - func(context.Context, json.RawMessage) (actool.Result, error) { - return jsonResult(t.graphOverviewData()) + func(ctx context.Context, _ json.RawMessage) (actool.Result, error) { + return jsonResult(t.graphOverviewDataFor(ctx, true)) }) } @@ -508,9 +509,13 @@ func (t *ToolSet) graphOverview() actool.CoreTool { // the model needn't spend a turn calling the tool — every plan round starts with // an empty context and always needs this first). func (t *ToolSet) graphOverviewData() map[string]any { + return t.graphOverviewDataFor(context.Background(), true) +} + +func (t *ToolSet) graphOverviewDataFor(ctx context.Context, planning bool) map[string]any { out := map[string]any{} // goals summary folded in so the planner needn't call list_goals each round. - goals, _ := t.ts.ListByKind(db.KindGoal, 100) + goals, _ := t.ts.PlanningGoalsContext(ctx, 100) gsum := make([]map[string]any, 0, len(goals)) for _, g := range goals { var p map[string]any @@ -523,6 +528,12 @@ func (t *ToolSet) graphOverviewData() map[string]any { gsum = append(gsum, map[string]any{"id": g.ID, "state": g.State, "text": text}) } out["goals"] = gsum + if ready, err := t.ts.CountReadyIntents(); err == nil { + out["frontier_ready"] = ready + } + if planning { + t.planningFocusOverview(ctx, out) + } // hints: strategic hints attached to the graph by the human/main agent via // add_hint; folded in so the planner reads them every round when generating // intents (otherwise they'd be write-only). @@ -589,6 +600,17 @@ func (t *ToolSet) graphOverviewData() map[string]any { } } out["running_intents"] = compactIntents(running, parentsOf, yieldsOf) + // Paused work used to disappear from open/running/recent_done altogether, + // making the planner unable to cite the human hold and prone to redispatch. + // Filter in SQL, so an old paused intent is not hidden by newer terminal work. + paused, pausedTotal, pausedErr := t.ts.NodesPage(db.NodeFilter{Kinds: []string{db.KindIntent}, States: []string{"paused"}}, 1, 100) + if pausedErr != nil { + out["paused_intents_error"] = "Paused work could not be read; do not infer that the queue is empty." + } else { + out["paused_intents"] = compactIntents(paused, parentsOf, yieldsOf) + out["paused_intents_total"] = pausedTotal + out["paused_work_instruction"] = "Human-paused work must not be duplicated or silently resumed. If remaining work depends on it, report_planning_wait using its ID. A pause is not completion." + } // done_intents_total: the total number of finished intents (done/blocked/exhausted), // named in parallel with recent_done_intents — the latter is just its newest windowed // view. Side by side the two keys are self-describing: "you're seeing N of total", so @@ -1349,6 +1371,7 @@ func (t *ToolSet) nodeDetail() actool.CoreTool { // intentItem is one exploration direction of an add_intent batch/single call. type intentItem struct { + NotBefore string `json:"not_before"` Summary string `json:"summary"` AssetIDs []json.RawMessage `json:"asset_ids"` ParentIDs []json.RawMessage `json:"parent_ids"` @@ -1418,6 +1441,9 @@ func (t *ToolSet) addOneIntent(it intentItem) (int64, error) { } } payload := map[string]any{"summary": it.Summary} + if it.NotBefore != "" { + payload["not_before"] = it.NotBefore + } if len(anchors) > 0 { payload["asset_ids"] = anchors } @@ -1464,6 +1490,7 @@ func (t *ToolSet) addIntent() actool.CoreTool { "intents": map[string]any{"type": "array", "description": "[Prefer this] array of exploration directions to add, processed in order. Each element has the same fields as the top-level ones below (summary/asset_ids/parent_ids/priority). The returned ids match this array in length and order.", "items": map[string]any{"type": "object"}}, "summary": str("[single] one sentence describing this exploration direction: what to do + why. Just write the direction clearly; asset ids are not required."), "asset_ids": map[string]any{"type": "array", "items": map[string]any{"type": "integer"}, "description": "the [target asset ids] this direction tests/attacks (**pass whenever possible**, 0/1/many; these are asset ids from list_assets, not exploration node ids): which assets (sites/endpoints/parameters/hosts etc.) this direction targets. Whenever the direction revolves around concrete assets, be sure to pass them — it is the structured marker of 'which targets this exploration hits', used for coverage dedup and linking the intent into the asset lineage. Leave empty only for pure global recon with truly no concrete target assets."}, + "not_before": str("Optional RFC3339 time; do not execute this intent before it is due."), "parent_ids": map[string]any{"type": "array", "items": map[string]any{"type": "integer"}, "description": "upstream anchor ids (optional, 0/1/many): which [confirmed fact/finding] nodes this direction is synthesized from. **Only existing fact/finding node ids may be passed — not intents/goals/hints** — an intent must anchor on confirmed knowledge, finding-driven rather than planned out of thin air. Pass several when multiple facts jointly produce one new intent; leave empty for a top-level brand-new recon direction (it is automatically attached to the task's origin fact)."}, "priority": intp("priority 0-10, default 5"), "hypothesis_id": idp("optional: hypothesis node id this intent tests"), @@ -1524,11 +1551,49 @@ func (t *ToolSet) addIntent() actool.CoreTool { } func (t *ToolSet) listGoals() actool.CoreTool { - return t.readExpTool("list_goals", "List this task's goal nodes and their states (open/met), for judging whether they are met.", - obj(map[string]any{}), - func(context.Context, json.RawMessage) (actool.Result, error) { - g, _ := t.ts.ListByKind(db.KindGoal, 100) - return jsonResult(g) + return t.readExpTool("list_goals", "List task goal nodes. With no arguments, returns up to 100 goals with open goals first. For all older/open goals use state=open, page and limit; that paginated form returns goals,total,has_more,next_page.", + listGoalsSchema(), + func(_ context.Context, in json.RawMessage) (actool.Result, error) { + var a struct { + State string + Page, Limit int + } + if err := json.Unmarshal(in, &a); err != nil { + return actool.Errorf("invalid goal query"), nil + } + if a.State == "" && a.Page == 0 && a.Limit == 0 { + g, err := t.ts.PlanningGoals(100) + if err != nil { + return actool.Result{}, err + } + return jsonResult(g) + } + if a.State != "" && a.State != "open" && a.State != "met" { + return actool.Errorf("state must be open or met"), nil + } + if a.Page < 1 { + a.Page = 1 + } + if a.Limit <= 0 { + a.Limit = 100 + } + if a.Limit > 200 { + a.Limit = 200 + } + filter := db.NodeFilter{Kinds: []string{db.KindGoal}} + if a.State != "" { + filter.States = []string{a.State} + } + goals, total, err := t.ts.NodesPage(filter, a.Page, a.Limit) + if err != nil { + return actool.Result{}, err + } + more := a.Page*a.Limit < total + out := map[string]any{"goals": goals, "total": total, "has_more": more} + if more { + out["next_page"] = a.Page + 1 + } + return jsonResult(out) }) } @@ -1878,14 +1943,18 @@ func (t *ToolSet) addFinding() actool.CoreTool { // must NOT be stuffed into the asset graph via upsert_asset. // factItem is one fact of a record_fact batch/single call. type factItem struct { - Summary string `json:"summary"` - Detail string `json:"detail"` - Evidence string `json:"evidence"` // one line of key evidence (command + key output lines) supporting the conclusion, for later verification - Confidence string `json:"confidence"` // observed (seen directly) | inferred (inferred from phenomena) - Source string `json:"source"` // where the content came from, one of factSources; empty = inference - IntentID json.RawMessage `json:"intent_id"` - AssetIDs []json.RawMessage `json:"asset_ids"` - TestedAssetIDs []json.RawMessage `json:"tested_asset_ids"` + Outcome string `json:"outcome"` + Checkpoint string `json:"checkpoint"` + RevisitCondition string `json:"revisit_condition"` + TestDimension string `json:"test_dimension"` + Summary string `json:"summary"` + Detail string `json:"detail"` + Evidence string `json:"evidence"` // one line of key evidence (command + key output lines) supporting the conclusion, for later verification + Confidence string `json:"confidence"` // observed (seen directly) | inferred (inferred from phenomena) + Source string `json:"source"` // where the content came from, one of factSources; empty = inference + IntentID json.RawMessage `json:"intent_id"` + AssetIDs []json.RawMessage `json:"asset_ids"` + TestedAssetIDs []json.RawMessage `json:"tested_asset_ids"` } // Fact sources (#124, F4): where a fact's content came from, as declared by the @@ -2039,6 +2108,14 @@ func (t *ToolSet) recordOneFact(it factItem, defaultIntent int64) (int64, error) } } payload := map[string]any{"summary": it.Summary, "source": source, "provenance": prov} + if it.Outcome != "" && it.Outcome != "verified" && it.Outcome != "negative" && it.Outcome != "blocked" && it.Outcome != "incomplete" { + return 0, fmt.Errorf("invalid fact outcome") + } + for key, value := range map[string]string{"outcome": it.Outcome, "checkpoint": it.Checkpoint, "revisit_condition": it.RevisitCondition, "test_dimension": it.TestDimension} { + if strings.TrimSpace(value) != "" { + payload[key] = value + } + } if it.Detail != "" { payload["detail"] = it.Detail } @@ -2789,7 +2866,7 @@ func (t *ToolSet) PlannerTools() []actool.CoreTool { t.graphOverview(), t.leaseStatus(), t.waitForLease(), t.listFindings(), t.listFacts(), t.nodeDetail(), t.knowledgeLookup(), // cold-digest §6.1: restore folded cold nodes (digest body → members → detail). t.expandDigest(), - t.getWorkerOutput(), t.getWorkerTrace(), t.searchAllWorkerTraces(), t.listGoals(), t.upsertHypothesis(), t.recordCapability(), t.addIntent(), t.proveGoal(), t.goalMet(), + t.getWorkerOutput(), t.getWorkerTrace(), t.searchAllWorkerTraces(), t.listGoals(), t.upsertHypothesis(), t.recordCapability(), t.addIntent(), t.reportPlanningWait(), t.listPlanningContinuations(), t.proveGoal(), t.goalMet(), t.killWorkTool(), t.steerWorkTool(), // report_finding: if the planner itself has confirmed a finding during // situational assessment, it can register it directly (same tool as the worker's). diff --git a/agent/tools_insert.go b/agent/tools_insert.go index d80c8dd3..d5043682 100644 --- a/agent/tools_insert.go +++ b/agent/tools_insert.go @@ -711,6 +711,7 @@ func splitLines(s string) []string { // WorkerTools returns the tool set for a work agent. func (t *ToolSet) WorkerTools() []actool.CoreTool { return []actool.CoreTool{ + t.getIntentContext(), // list_findings stays: check the task's confirmed findings before reporting, to // avoid reporting the same finding twice. t.listFindings(), diff --git a/agent/worker.go b/agent/worker.go index 6645ea0e..d72f6357 100644 --- a/agent/worker.go +++ b/agent/worker.go @@ -502,6 +502,20 @@ func renderWorkerGraphOverview(data map[string]any, env dataEnvelope) string { // worker view. data is a fresh map dedicated to this worker, so deleting the key // doesn't affect the planner. delete(data, "coverage") + // Continuation candidates belong to planning; a worker receives the evidence + // directly referenced by its own intent below, independently of graph windows. + delete(data, "planning_continuations") + delete(data, "planning_continuations_error") + if digests, ok := data["cold_digests"].([]map[string]any); ok { + for _, digest := range digests { + if body, ok := digest["body"].(string); ok && len([]rune(body)) > 300 { + digest["body"] = string([]rune(body)[:300]) + "…" + digest["body_truncated"] = true + } + } + data["cold_digest_instruction"] = "Historical digest previews are bounded. Use expand_digest(id) and node_detail(member_id) only when relevant to your assigned intent. Referenced intent evidence is supplied separately." + } + sections := renderOverviewSections(data, env) if sections == "" { return "" // fall back silently: the worker just won't have the global context @@ -605,7 +619,8 @@ func (w *Worker) execute(ctx context.Context, name string, taskID int64, as *db. // inherit a parent run's background into the action reviewer. ctx = intercept.WithReviewContext(ctx, runDir, intercept.ReviewBackground{}) workerEnv := newDataEnvelope() - overview := renderWorkerGraphOverview(tsx.graphOverviewData(), workerEnv) + overview := renderWorkerGraphOverview(tsx.graphOverviewDataFor(ctx, false), workerEnv) + overview += workerEnv.wrap("intent_references", tsx.renderIntentReferences(ctx, intent.ID)) if brief := renderWorkerTaskBrief(tsx.taskBriefData(ctx), workerEnv); brief != "" { if strings.TrimSpace(overview) == "" { overview = workerEnv.intro() + brief diff --git a/db/exploration.go b/db/exploration.go index a58f080d..4c61d2a3 100644 --- a/db/exploration.go +++ b/db/exploration.go @@ -2,6 +2,7 @@ package db import ( "bytes" + "context" "crypto/rand" "database/sql" "encoding/hex" @@ -291,7 +292,11 @@ func (s *ExplorationStore) AddIntent(payload map[string]any, priority int, ancho if origin == "" { origin = "planner" } - return s.AddNode("intent", payload, priority, "open", origin, anchors) + normalized, err := normalizeIntentSchedule(payload) + if err != nil { + return 0, err + } + return s.AddNode("intent", normalized, priority, "open", origin, anchors) } // AddGoal writes a goal node (state open). @@ -922,7 +927,11 @@ WHERE exploration_id=$1 AND kind='intent' AND state='open'`, s.expID).Scan(&n) // GetNode returns one node of this exploration by id (nil, nil if not found). func (s *ExplorationStore) GetNode(id int64) (*Node, error) { - n, err := scanNode(s.db.QueryRow(`SELECT `+nodeCols+` FROM exploration_nodes WHERE id=$1 AND exploration_id=$2`, id, s.expID)) + return s.GetNodeContext(context.Background(), id) +} + +func (s *ExplorationStore) GetNodeContext(ctx context.Context, id int64) (*Node, error) { + n, err := scanNode(s.db.QueryRowContext(ctx, `SELECT `+nodeCols+` FROM exploration_nodes WHERE id=$1 AND exploration_id=$2`, id, s.expID)) if err == sql.ErrNoRows { return nil, nil } @@ -1367,7 +1376,7 @@ func (s *ExplorationStore) ClaimIntentToken(id int64, owner string) (string, err return "", err } res, err := s.db.Exec(`UPDATE exploration_nodes SET state='running', owner=$1, unclaim_token=$4, last_heartbeat_at=now() -WHERE id=$2 AND exploration_id=$3 AND kind='intent' AND state='open'`, owner, id, s.expID, token) +WHERE id=$2 AND exploration_id=$3 AND kind='intent' AND state='open' AND `+intentReadySQL, owner, id, s.expID, token) if err != nil { return "", err } diff --git a/db/exploration_sources.go b/db/exploration_sources.go index c12d5ba1..a9b98399 100644 --- a/db/exploration_sources.go +++ b/db/exploration_sources.go @@ -1,6 +1,7 @@ package db import ( + "context" "database/sql" "sort" ) @@ -18,7 +19,11 @@ type DirectSourceStore struct { // a source task is deleted, and inherited context must not retain stale rows. // Sources of a source are never expanded. func (s *ExplorationStore) DirectSourceStores() ([]DirectSourceStore, error) { - rows, err := s.db.Query(` + return s.DirectSourceStoresContext(context.Background()) +} + +func (s *ExplorationStore) DirectSourceStoresContext(ctx context.Context) ([]DirectSourceStore, error) { + rows, err := s.db.QueryContext(ctx, ` SELECT source.id, source.exploration_id, source.description, source.goal, source.status FROM tasks owner JOIN task_relations relation ON relation.task_id=owner.id @@ -159,16 +164,20 @@ func (s *ExplorationStore) ListByKindPageWithSources(kind string, before int64, // one of its direct sources. Inherited nodes are tagged so tool callers can keep // them read-only and show their provenance. func (s *ExplorationStore) GetNodeWithSources(id int64) (*Node, error) { - node, err := s.GetNode(id) + return s.GetNodeWithSourcesContext(context.Background(), id) +} + +func (s *ExplorationStore) GetNodeWithSourcesContext(ctx context.Context, id int64) (*Node, error) { + node, err := s.GetNodeContext(ctx, id) if err != nil || node != nil { return node, err } - sources, err := s.DirectSourceStores() + sources, err := s.DirectSourceStoresContext(ctx) if err != nil { return nil, err } for _, source := range sources { - node, err = source.Store.GetNode(id) + node, err = source.Store.GetNodeContext(ctx, id) if err != nil { return nil, err } diff --git a/db/intent_context.go b/db/intent_context.go new file mode 100644 index 00000000..a666fb2b --- /dev/null +++ b/db/intent_context.go @@ -0,0 +1,40 @@ +package db + +import "context" + +// IntentReferenceIDs follows the claimed intent's own incoming references. The +// global graph visualization limit must never truncate execution handovers. +func (s *ExplorationStore) IntentReferenceIDs(ctx context.Context, intent, before int64, limit int) (ids []int64, total int, more bool, err error) { + if limit <= 0 { + limit = 16 + } + if limit > 50 { + limit = 50 + } + const where = `exploration_id=$1 AND dst_id=$2 AND rel='derived_from'` + err = s.db.QueryRowContext(ctx, `SELECT count(*) FROM exploration_edges WHERE `+where, s.expID, intent).Scan(&total) + if err != nil { + return + } + rows, e := s.db.QueryContext(ctx, `SELECT src_id FROM exploration_edges WHERE `+where+` AND ($3<=0 OR src_id<$3) ORDER BY src_id DESC LIMIT $4`, s.expID, intent, before, limit+1) + if e != nil { + err = e + return + } + defer rows.Close() + for rows.Next() { + var id int64 + if err = rows.Scan(&id); err != nil { + return + } + ids = append(ids, id) + } + if err = rows.Err(); err != nil { + return + } + more = len(ids) > limit + if more { + ids = ids[:limit] + } + return +} diff --git a/db/intent_schedule.go b/db/intent_schedule.go new file mode 100644 index 00000000..410c7e66 --- /dev/null +++ b/db/intent_schedule.go @@ -0,0 +1,75 @@ +package db + +import ( + "fmt" + "time" +) + +// Scheduling lives in the node payload so archives and checkpoints preserve it. +// not_before_unix is derived by the application, never accepted from callers. +func normalizeIntentSchedule(payload map[string]any) (map[string]any, error) { + out := make(map[string]any, len(payload)+1) + for k, v := range payload { + out[k] = v + } + delete(out, "not_before_unix") + raw, present := payload["not_before"] + if !present { + return out, nil + } + s, ok := raw.(string) + if !ok || s == "" { + return nil, fmt.Errorf("not_before must be an RFC3339 timestamp with timezone") + } + due, err := time.Parse(time.RFC3339Nano, s) + if err != nil { + return nil, fmt.Errorf("not_before must be an RFC3339 timestamp with timezone: %w", err) + } + // Round up: fractional timestamps must never become eligible early. + sec := due.Unix() + if due.Nanosecond() != 0 { + sec++ + } + out["not_before"] = due.UTC().Format(time.RFC3339Nano) + out["not_before_unix"] = sec + return out, nil +} + +// JSONB comparisons avoid unsafe casts on imported/malformed metadata. An +// incomplete or invalid schedule remains unclaimable rather than running early. +const intentReadySQL = `(NOT (payload ? 'not_before') OR + (jsonb_typeof(payload->'not_before_unix') = 'number' + AND payload->'not_before_unix' <= to_jsonb(extract(epoch FROM now()))))` + +// ReadyFrontier filters before LIMIT so delayed high-priority entries cannot +// starve ordinary work. Frontier still includes them for UI/planner visibility. +func (s *ExplorationStore) ReadyFrontier(limit int) ([]*Node, error) { + if limit <= 0 { + limit = 50 + } + rows, err := s.db.Query(`SELECT `+nodeCols+` FROM exploration_nodes + WHERE exploration_id=$1 AND kind='intent' AND state='open' AND `+intentReadySQL+` + ORDER BY priority DESC,id ASC LIMIT $2`, s.expID, limit) + if err != nil { + return nil, err + } + defer rows.Close() + return scanNodes(rows) +} + +func (s *ExplorationStore) CountReadyIntents() (int, error) { + var n int + err := s.db.QueryRow(`SELECT count(*) FROM exploration_nodes WHERE exploration_id=$1 + AND kind='intent' AND state='open' AND `+intentReadySQL, s.expID).Scan(&n) + return n, err +} + +// HasRunnableOrRunningIntent reports whether workers can make progress now. +// HasActiveIntent also includes delayed work and is used when deciding completion. +func (s *ExplorationStore) HasRunnableOrRunningIntent() (bool, error) { + var exists bool + err := s.db.QueryRow(`SELECT EXISTS(SELECT 1 FROM exploration_nodes +WHERE exploration_id=$1 AND kind='intent' +AND (state='running' OR (state='open' AND `+intentReadySQL+`)))`, s.expID).Scan(&exists) + return exists, err +} diff --git a/db/intent_schedule_test.go b/db/intent_schedule_test.go new file mode 100644 index 00000000..aada4f9d --- /dev/null +++ b/db/intent_schedule_test.go @@ -0,0 +1,86 @@ +package db + +import ( + "testing" + "time" +) + +func TestIntentScheduleValidation(t *testing.T) { + for _, raw := range []any{"tomorrow", "2026-11-14T11:12:00", "", nil, 123} { + if _, err := normalizeIntentSchedule(map[string]any{"not_before": raw}); err == nil { + t.Fatalf("accepted %v", raw) + } + } + p := map[string]any{"not_before": "2026-11-14T11:12:00.5+08:00", "not_before_unix": 0} + n, err := normalizeIntentSchedule(p) + if err != nil { + t.Fatal(err) + } + due, _ := time.Parse(time.RFC3339Nano, "2026-11-14T03:12:00.5Z") + if n["not_before_unix"] != due.Unix()+1 || n["not_before"] != "2026-11-14T03:12:00.5Z" { + t.Fatal(n) + } + if p["not_before_unix"] != 0 { + t.Fatal("mutated caller") + } +} + +func TestDelayedIntentCannotBeClaimedOrStarveReadyWork(t *testing.T) { + d, err := Open(testDSN(t)) + if err != nil { + t.Fatal(err) + } + defer d.Close() + exp, err := d.CreateExploration("schedule regression", "") + if err != nil { + t.Fatal(err) + } + defer d.Exec(`DELETE FROM explorations WHERE id=$1`, exp) + s := d.Exploration(exp) + var delayed int64 + for range 25 { + delayed, err = s.AddIntent(map[string]any{"summary": "future observation", "not_before": time.Now().Add(time.Hour).Format(time.RFC3339)}, 10, nil, "planner") + if err != nil { + t.Fatal(err) + } + } + ready, err := s.AddIntent(map[string]any{"summary": "ready now"}, 1, nil, "planner") + if err != nil { + t.Fatal(err) + } + fr, err := s.ReadyFrontier(1) + if err != nil || len(fr) != 1 || fr[0].ID != ready { + t.Fatalf("ready frontier %v %v", fr, err) + } + if ok, err := s.ClaimIntent(delayed, "worker"); err != nil || ok { + t.Fatalf("claimed early: %v %v", ok, err) + } + if n, err := s.CountOpenIntents(); err != nil || n != 26 { + t.Fatalf("pending lost: %d %v", n, err) + } + if active, err := s.HasActiveIntent(); err != nil || !active { + t.Fatal("delayed work must keep task active", err) + } + if n, err := s.CountReadyIntents(); err != nil || n != 1 { + t.Fatalf("ready count: %d %v", n, err) + } + // Simulate time becoming due without sleeping or involving a model. + _, err = d.Exec(`UPDATE exploration_nodes SET payload=jsonb_set(payload,'{not_before_unix}',to_jsonb(extract(epoch FROM now())-1)) WHERE id=$1`, delayed) + if err != nil { + t.Fatal(err) + } + if ok, err := s.ClaimIntent(delayed, "worker"); err != nil || !ok { + t.Fatalf("not claimed when due: %v %v", ok, err) + } + if ok, _ := s.ClaimIntent(delayed, "other"); ok { + t.Fatal("double claimed") + } + // Imported malformed schedules fail closed without breaking the whole queue. + _, err = d.Exec(`UPDATE exploration_nodes SET payload=payload || '{"not_before":"bad","not_before_unix":"bad"}'::jsonb WHERE id=$1`, ready) + if err != nil { + t.Fatal(err) + } + if fr, err = s.ReadyFrontier(20); err != nil || len(fr) != 0 { + t.Fatalf("malformed schedule %v %v", fr, err) + } +} diff --git a/db/planner_focus.go b/db/planner_focus.go new file mode 100644 index 00000000..0e9dc864 --- /dev/null +++ b/db/planner_focus.go @@ -0,0 +1,65 @@ +package db + +import ( + "context" + "strings" +) + +// PlanningGoals cannot let newly met goals evict an older unmet goal from the +// planner's view. History remains available after the open goals. +func (s *ExplorationStore) PlanningGoals(limit int) ([]*Node, error) { + return s.PlanningGoalsContext(context.Background(), limit) +} + +func (s *ExplorationStore) PlanningGoalsContext(ctx context.Context, limit int) ([]*Node, error) { + if limit <= 0 || limit > 1000 { + limit = 100 + } + rows, err := s.db.QueryContext(ctx, `SELECT `+nodeCols+` FROM exploration_nodes WHERE exploration_id=$1 AND kind='goal' ORDER BY (state='open') DESC,id DESC LIMIT $2`, s.expID, limit) + if err != nil { + return nil, err + } + defer rows.Close() + return scanNodes(rows) +} + +func (s *ExplorationStore) PlanningGoalCounts(ctx context.Context) (total, open int, err error) { + err = s.db.QueryRowContext(ctx, `SELECT count(*),count(*) FILTER(WHERE state='open') FROM exploration_nodes WHERE exploration_id=$1 AND kind='goal'`, s.expID).Scan(&total, &open) + return +} + +// PlanningContinuations searches all live fact nodes, independently of recent +// windows or cold-digest membership. Dismissed/superseded facts are excluded. +// These are candidates: only the planner can judge relevance to an open goal. +func (s *ExplorationStore) PlanningContinuations(ctx context.Context, before int64, limit int, q string) (nodes []*Node, total int, more bool, err error) { + if limit <= 0 { + limit = 10 + } + if limit > 50 { + limit = 50 + } + where := `exploration_id=$1 AND kind='fact' AND state='confirmed' + AND ((COALESCE(payload->>'outcome','') NOT IN ('verified','negative') AND length(btrim(COALESCE(payload->>'checkpoint','')))>0) + OR (payload->>'outcome'='blocked' AND length(btrim(COALESCE(payload->>'revisit_condition','')))>0)) + AND ($2='' OR payload::text ILIKE '%'||$2||'%')` + q = strings.TrimSpace(q) + err = s.db.QueryRowContext(ctx, `SELECT count(*) FROM exploration_nodes WHERE `+where, s.expID, q).Scan(&total) + if err != nil { + return + } + rows, e := s.db.QueryContext(ctx, `SELECT `+nodeCols+` FROM exploration_nodes WHERE `+where+` AND ($3<=0 OR id<$3) ORDER BY id DESC LIMIT $4`, s.expID, q, before, limit+1) + if e != nil { + err = e + return + } + defer rows.Close() + nodes, err = scanNodes(rows) + if err != nil { + return + } + more = len(nodes) > limit + if more { + nodes = nodes[:limit] + } + return +} diff --git a/db/planner_progress.go b/db/planner_progress.go new file mode 100644 index 00000000..24ae02fb --- /dev/null +++ b/db/planner_progress.go @@ -0,0 +1,149 @@ +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. +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),'') + ||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,md5(c.password),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),'')) + 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 +} +func (s *ExplorationStore) SavePlanningProgress(ctx context.Context, snapshot PlanningSnapshot, state, reason string, next *time.Time) error { + if state != "active" && state != "waiting" && state != "stalled" && state != "needs_attention" && state != "retrying" { + return fmt.Errorf("invalid planning progress state") + } + _, err := s.db.ExecContext(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') 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') 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()`, s.expID, state, reason, snapshot.Fingerprint, next) + if err != nil { + return err + } + // At most three 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>=3`, s.expID) + return err +} +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 +} diff --git a/db/planner_progress_test.go b/db/planner_progress_test.go new file mode 100644 index 00000000..4efbad99 --- /dev/null +++ b/db/planner_progress_test.go @@ -0,0 +1,84 @@ +package db + +import ( + "testing" + "time" +) + +func TestPlanningProgressWaitValidationAndRestart(t *testing.T) { + d, err := Open(testDSN(t)) + if err != nil { + t.Fatal(err) + } + defer d.Close() + task, err := d.CreateTask("isolated wait validation", "unfinished comparison", nil, 0, 0) + if err != nil { + t.Fatal(err) + } + defer d.DeleteTask(task.ID) + s := d.Exploration(task.ExplorationID) + if _, err = s.AddGoal(map[string]any{"text": "unfinished comparison"}, "fixture"); err != nil { + t.Fatal(err) + } + now := time.Now() + due := now.Add(time.Hour) + intent, err := s.AddIntent(map[string]any{"summary": "future observation", "not_before": due.Format(time.RFC3339)}, 0, nil, "fixture") + if err != nil { + t.Fatal(err) + } + next, err := s.ValidatePlanningWait(t.Context(), []int64{intent}, "requires future observation", now) + if err != nil || !next.After(now) { + t.Fatal(next, err) + } + for _, ids := range [][]int64{nil, {intent, intent}, {-1}, {999999999}} { + if _, err = s.ValidatePlanningWait(t.Context(), ids, "waiting", now); err == nil { + t.Fatal("accepted invalid references", ids) + } + } + if _, err = s.ValidatePlanningWait(t.Context(), []int64{intent}, "waiting", due.Add(time.Second)); err == nil { + t.Fatal("due work cannot justify waiting") + } + _, err = d.Exec(`UPDATE exploration_nodes SET payload=jsonb_set(payload,'{not_before_unix}',to_jsonb((payload->>'not_before_unix')::text)) WHERE id=$1`, intent) + if err != nil { + t.Fatal(err) + } + if _, err = s.ValidatePlanningWait(t.Context(), []int64{intent}, "waiting", now); err == nil { + t.Fatal("string encoded due time cannot be claimed and must not justify waiting") + } + snap, err := s.PlanningSnapshot(t.Context()) + if err != nil { + t.Fatal(err) + } + for range 3 { + if err = s.SavePlanningProgress(t.Context(), snap, "stalled", "empty", &next); err != nil { + t.Fatal(err) + } + } + reopened := d.Exploration(task.ExplorationID) + status, err := reopened.PlanningProgress(t.Context()) + if err != nil || status.State != "needs_attention" || status.Failures != 3 { + t.Fatal(status, err) + } + if _, err = reopened.AppendActivity(Activity{Worker: "planner", Kind: "text", Summary: "another empty response"}); err != nil { + t.Fatal(err) + } + allowed, err := reopened.PlanningAllowed(t.Context(), now.Add(24*time.Hour)) + if err != nil || allowed { + t.Fatal("activity must not reset recovery", allowed, err) + } + if err = reopened.UpdateGoalPayload(mustPlanningGoal(t, d, task.ExplorationID), "updated user goal", ""); err != nil { + t.Fatal(err) + } + allowed, err = reopened.PlanningAllowed(t.Context(), now) + if err != nil || !allowed { + t.Fatal("goal edit must reopen recovery", allowed, err) + } +} +func mustPlanningGoal(t *testing.T, d *DB, exp int64) int64 { + t.Helper() + var id int64 + if err := d.QueryRow(`SELECT id FROM exploration_nodes WHERE exploration_id=$1 AND kind='goal'`, exp).Scan(&id); err != nil { + t.Fatal(err) + } + return id +} diff --git a/db/schema.sql b/db/schema.sql index 62331a3e..bfe9d9d1 100644 --- a/db/schema.sql +++ b/db/schema.sql @@ -554,6 +554,19 @@ CREATE TABLE IF NOT EXISTS tasks ( ); CREATE INDEX IF NOT EXISTS idx_tasks_alive ON tasks(created_at DESC) WHERE deleted_at IS NULL; CREATE INDEX IF NOT EXISTS idx_tasks_status ON tasks(status) WHERE deleted_at IS NULL; +-- Round outcomes are independent of task completion. Failed empty planning +-- retains the unmet goal and survives process restart without an infinite loop. +CREATE TABLE IF NOT EXISTS planner_progress ( + exploration_id BIGINT PRIMARY KEY REFERENCES explorations(id) ON DELETE CASCADE, + state TEXT NOT NULL CHECK(state IN ('active','waiting','stalled','needs_attention','retrying')), + reason TEXT NOT NULL, + fingerprint TEXT NOT NULL, + failures INTEGER NOT NULL DEFAULT 0, + next_check_at TIMESTAMPTZ, + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +ALTER TABLE planner_progress DROP CONSTRAINT IF EXISTS planner_progress_state_check; +ALTER TABLE planner_progress ADD CONSTRAINT planner_progress_state_check CHECK(state IN ('active','waiting','stalled','needs_attention','retrying')); DROP TRIGGER IF EXISTS trg_tasks_upd ON tasks; CREATE TRIGGER trg_tasks_upd BEFORE UPDATE ON tasks FOR EACH ROW EXECUTE FUNCTION set_updated_at(); diff --git a/db/task_archives_restore.go b/db/task_archives_restore.go index ba8d103e..23dd1be7 100644 --- a/db/task_archives_restore.go +++ b/db/task_archives_restore.go @@ -92,6 +92,7 @@ WHERE relation.source_task_id=$1 LIMIT 1`, taskID).Scan(&dependent) {`DELETE FROM task_asset_links WHERE task_id=$1`, []any{taskID}}, {`DELETE FROM task_llm_profiles WHERE task_id=$1`, []any{taskID}}, {`DELETE FROM task_scope WHERE task_id=$1`, []any{taskID}}, + {`DELETE FROM planner_progress WHERE exploration_id=$1`, []any{expID}}, {`DELETE FROM task_constraints WHERE exploration_id=$1`, []any{expID}}, {`DELETE FROM activity WHERE exploration_id=$1`, []any{expID}}, {`DELETE FROM exploration_nodes WHERE exploration_id=$1`, []any{expID}}, diff --git a/intercept/target_extract.go b/intercept/target_extract.go index 3e365eaf..3d92cfc3 100644 --- a/intercept/target_extract.go +++ b/intercept/target_extract.go @@ -22,6 +22,7 @@ var noTargetTools = toolSet( "Read", "Write", "Edit", "MultiEdit", "LS", "Glob", "Grep", "TodoWrite", "sleep", "TaskOutput", "TaskStop", "TaskList", // exploration graph, assets, findings, goals (agent.ToolSet) + "report_planning_wait", "list_planning_continuations", "get_intent_context", "graph_overview", "lease_status", "wait_for_lease", "task_brief", "list_findings", "list_facts", "node_detail", "expand_digest", "get_worker_output", "get_worker_trace", "search_all_worker_traces", "add_hint", "add_intent", "upsert_hypothesis", "record_capability", "steer_work", "kill_work", diff --git a/scripts/sql/inspect-planning-index.sql b/scripts/sql/inspect-planning-index.sql new file mode 100644 index 00000000..17966f54 --- /dev/null +++ b/scripts/sql/inspect-planning-index.sql @@ -0,0 +1,12 @@ +-- Read-only: verify the database/schema and inspect existing indexes. +SELECT current_database(), current_schema(), + to_regclass('exploration_nodes') AS target_table; + +SELECT i.indexrelid::regclass AS index_name, + i.indisvalid, + i.indisready, + pg_size_pretty(pg_relation_size(i.indexrelid)) AS index_size, + pg_get_indexdef(i.indexrelid) AS definition +FROM pg_index i +WHERE i.indrelid = to_regclass('exploration_nodes') +ORDER BY i.indexrelid::regclass::text; diff --git a/scripts/sql/planning-continuations-index.sql b/scripts/sql/planning-continuations-index.sql new file mode 100644 index 00000000..72def84d --- /dev/null +++ b/scripts/sql/planning-continuations-index.sql @@ -0,0 +1,20 @@ +-- PostgreSQL 16; run against the intended ARTEX database/schema. +-- Standalone migration: autocommit ON. Do not wrap in BEGIN or use psql -1. +-- Before and after execution, run inspect-planning-index.sql. +-- Deliberately no IF NOT EXISTS: a matching name does not prove a valid, +-- equivalent index. Investigate an existing or INVALID index before retrying. +-- The predicate matches db/planner_focus.go: PlanningContinuations. +CREATE INDEX CONCURRENTLY idx_expnodes_planning_continuations +ON exploration_nodes (exploration_id, id DESC) +WHERE kind = 'fact' + AND state = 'confirmed' + AND ( + ( + COALESCE(payload->>'outcome', '') NOT IN ('verified', 'negative') + AND length(btrim(COALESCE(payload->>'checkpoint', ''))) > 0 + ) + OR ( + payload->>'outcome' = 'blocked' + AND length(btrim(COALESCE(payload->>'revisit_condition', ''))) > 0 + ) + ); diff --git a/scripts/sql/rollback-planning-continuations-index.sql b/scripts/sql/rollback-planning-continuations-index.sql new file mode 100644 index 00000000..9f4f4fc7 --- /dev/null +++ b/scripts/sql/rollback-planning-continuations-index.sql @@ -0,0 +1,3 @@ +-- Standalone rollback; autocommit ON, outside a transaction. +-- Verify the intended database/schema and index definition before executing. +DROP INDEX CONCURRENTLY idx_expnodes_planning_continuations; diff --git a/server/engine.go b/server/engine.go index aa50f74a..d1f5e62e 100644 --- a/server/engine.go +++ b/server/engine.go @@ -385,6 +385,13 @@ func (e *Engine) Resume(t *Task) { return } e.paused.Delete(t.ID) + if t.Store != nil { + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + if err := t.Store.ResetPlanningProgress(ctx); err != nil { + log.Printf("[planner] task %s could not clear recovery state on resume: %v", t.ID, err) + } + cancel() + } t.Notify() } @@ -874,7 +881,7 @@ func (e *Engine) Run(ctx context.Context, t *Task) { // worker just started above has claimed it as running first — both count as "work // exists", so skip the first planner round: the worker runs the seed intent directly and NotifyDone/heartbeat wakes the planner when done. // ⚠️ Do not use Frontier (counts only open): a worker claiming (open→running) races with this check and would kick spuriously. After a restart-driven auto-recovery only running intents may remain — skip then too. - if has, _ := t.Store.HasActiveIntent(); !has { + if has, _ := t.Store.HasRunnableOrRunningIntent(); !has { t.Notify() // kick the first planning round (acted on once LLM is ready) } } @@ -912,7 +919,7 @@ func (e *Engine) quietSkipEdge(t *Task) bool { if last, ok := e.goalFP.Load(t.ID); !ok || last != fp { return false } - active, err := t.Store.HasActiveIntent() + active, err := t.Store.HasRunnableOrRunningIntent() return err == nil && active } @@ -934,11 +941,32 @@ func (e *Engine) plannerGateContext(ctx context.Context, t *Task, wait time.Dura func (e *Engine) plannerLoop(ctx context.Context, t *Task) { interval := plannerHeartbeatInterval(t) - // Arming the heartbeat timer at loop entry = counting from the task start: even a - // seed task that skips the first planner round (Run does not kick the first round - // when the frontier is non-empty) and blocks here gets its first planning round at "task start + interval". Every later wake-up (edge/heartbeat) re-arms it = time since the last planning trigger of any kind. - heartbeat := time.NewTimer(interval) + // Heartbeat deadlines are independent of edge traffic. Quiet-mode skips + // cannot keep postponing the periodic supervision of an otherwise idle task. + heartbeat := time.NewTicker(interval) defer heartbeat.Stop() + recovery := time.NewTimer(time.Hour) + recovery.Stop() + defer recovery.Stop() + var recoveryC <-chan time.Time + armRecovery := func() { + recovery.Stop() + recoveryC = nil + if e.IsPaused(t.ID) || e.IsDeleting(t.ID) || isTerminalStatus(t.lifecycleSnapshot().Status) { + return + } + state, err := t.Store.PlanningProgress(ctx) + if err != nil || state.NextCheck == nil { + return + } + delay := time.Until(*state.NextCheck) + if delay < time.Second { + delay = time.Second + } + resetPlannerTimer(recovery, delay) + recoveryC = recovery.C + } + armRecovery() // runRound runs one planning round (with debounce coalescing + the guards). src is only used to tell the trigger source apart in logs. runRound := func(src string) { @@ -947,6 +975,9 @@ func (e *Engine) plannerLoop(ctx context.Context, t *Task) { drain: for { select { + case <-ctx.Done(): + timer.Stop() + return case <-t.notify: case <-timer.C: break drain @@ -996,6 +1027,14 @@ func (e *Engine) plannerLoop(ctx context.Context, t *Task) { if e.budgetStop(ctx, t) { return } + allowed, progressErr := t.Store.PlanningAllowed(ctx, time.Now()) + if progressErr != nil { + log.Printf("[planner] task %s cannot validate recovery state: %v", t.ID, progressErr) + return + } + if !allowed { + return + } // quiet-mode (#79): an edge round is redundant while work is in flight // and the open-goal set is unchanged since the last completed round — // there is no new decision for the plan to make. Drain the triggers so @@ -1026,6 +1065,11 @@ func (e *Engine) plannerLoop(ctx context.Context, t *Task) { // what fired this round (worker done / finding; may be several — debounce // coalesces a burst; empty for time/heartbeat wakes). triggers := t.drainTriggers() + if src == "recovery" { + if state, err := t.Store.PlanningProgress(ectx); err == nil && state.State == "stalled" { + triggers = append(triggers, agent.TriggerEvent{Kind: "planning_recovery", Detail: state.Reason}) + } + } taskIDInt, _ := strconv.ParseInt(t.ID, 10, 64) pctx := e.budgetRoundCtx(e.plannerGateContext(ectx, t, intercept.DefaultTargetWaitBound), t, false) e.BeginLLMCall(t.ID) @@ -1068,9 +1112,12 @@ func (e *Engine) plannerLoop(ctx context.Context, t *Task) { case <-heartbeat.C: // Periodic safety net: deadlock fallback + wake up to supervise in-flight workers (steer/kill) + periodic recheck. runRound("heartbeat") + case <-recoveryC: + runRound("recovery") } - // Re-arm the heartbeat after every wake-up (edge or heartbeat): any planning trigger restarts this idle timer. - resetPlannerTimer(heartbeat, interval) + // Recovery follows a persisted deadline. Edge traffic cannot postpone + // either it or the independent heartbeat indefinitely. + armRecovery() } } @@ -1546,7 +1593,7 @@ func sleepCtx(ctx context.Context, d time.Duration) (done bool) { } func (e *Engine) claimNext(t *Task, name string) (*db.Node, string) { - fr, _ := t.Store.Frontier(20) + fr, _ := t.Store.ReadyFrontier(20) for _, in := range fr { if token, _ := t.Store.ClaimIntentToken(in.ID, name); token != "" { return in, token diff --git a/server/planner_progress_test.go b/server/planner_progress_test.go new file mode 100644 index 00000000..19337728 --- /dev/null +++ b/server/planner_progress_test.go @@ -0,0 +1,168 @@ +package server + +import ( + "context" + "encoding/json" + "github.com/Autumn-27/artex/agent" + "github.com/Autumn-27/artex/db" + "github.com/Autumn-27/norma/llm" + "iter" + "sync/atomic" + "testing" + "time" +) + +type planningLoopProvider struct { + calls atomic.Int32 + response func(int, llm.CompletionRequest) (llm.Message, string, error) +} + +func (p *planningLoopProvider) Complete(ctx context.Context, r llm.CompletionRequest) (llm.Message, string, llm.Usage, error) { + m, s, e := p.response(int(p.calls.Add(1)), r) + return m, s, llm.Usage{}, e +} +func (p *planningLoopProvider) Stream(context.Context, llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] { + return func(y func(llm.StreamEvent, error) bool) { y(llm.StreamEvent{}, context.Canceled) } +} +func planningText(text string) llm.Message { + return llm.Message{Role: llm.RoleAssistant, Content: []llm.ContentBlock{{Type: llm.BlockText, Text: text}}} +} +func planningTool(name string, input any) llm.Message { + raw, _ := json.Marshal(input) + return llm.Message{Role: llm.RoleAssistant, Content: []llm.ContentBlock{{Type: llm.BlockToolUse, ID: "loop-tool", Name: name, Input: raw}}} +} +func planningLoopFixture(t *testing.T) (*Manager, *Task, *Engine) { + t.Helper() + m, err := NewManager(t.TempDir(), "") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { m.Close() }) + task, err := m.CreateTaskWithOptions("Offline regression: compare supplied fixtures, no network or commands.", "Compare fixture A and B; keep goal open until comparison is checked", db.TaskCreateOptions{}) + if err != nil { + t.Fatal(err) + } + if _, err = task.Store.AddGoal(map[string]any{"text": task.Goal}, "fixture"); err != nil { + t.Fatal(err) + } + if err = m.SetTaskStatus(task.ID, "running"); err != nil { + t.Fatal(err) + } + if err = m.SetWorkers(1); err != nil { + t.Fatal(err) + } + e := NewEngine(m) + e.debounce = time.Millisecond + t.Cleanup(func() { e.StopTask(task.ID); m.pg.DeleteTask(mustTaskID(t, task.ID)) }) + return m, task, e +} +func fixtureWorker(t *testing.T) (*agent.Worker, *planningLoopProvider) { + t.Helper() + p := &planningLoopProvider{response: func(call int, _ llm.CompletionRequest) (llm.Message, string, error) { + if call == 1 { + return planningTool("record_fact", map[string]any{"summary": "Fixture worker executed the queued comparison", "evidence": "fixture A=2, fixture B=3; difference=1", "checkpoint": "Comparison recorded; final acceptance still pending"}), "tool_use", nil + } + return planningText("Fixture comparison recorded; final goal acceptance is still pending."), "end_turn", nil + }} + w := agent.NewWorker(p, "fixture-worker", t.TempDir(), nil, 100000, 4) + w.SetNonStreaming(func() bool { return true }) + return w, p +} +func waitPlanning(t *testing.T, limit time.Duration, check func() bool) { + t.Helper() + until := time.Now().Add(limit) + for time.Now().Before(until) { + if check() { + return + } + time.Sleep(20 * time.Millisecond) + } + t.Fatal("planning condition did not become true before timeout") +} + +func TestPlannerProgressEngineDispatchClaimExecute(t *testing.T) { + m, task, e := planningLoopFixture(t) + provider := &planningLoopProvider{response: func(call int, _ llm.CompletionRequest) (llm.Message, string, error) { + if call == 1 { + return planningText("I will arrange the comparison."), "end_turn", nil + } + if call == 2 { + return planningTool("add_intent", map[string]any{"summary": "Compare supplied fixture A=2 and B=3, record difference without external access"}), "tool_use", nil + } + return planningText("Comparison has been queued."), "end_turn", nil + }} + p := agent.NewPlanner(provider, "fixture", t.TempDir(), nil, 100000, 4) + p.SetNonStreaming(func() bool { return true }) + w, workerProvider := fixtureWorker(t) + e.SetAuthoritativeAgentResolver(func(*Task) (*agent.Planner, *agent.Worker) { return p, w }) + e.Run(t.Context(), task) + waitPlanning(t, 5*time.Second, func() bool { + snap, err := task.Store.PlanningSnapshot(t.Context()) + return err == nil && snap.Done == 1 + }) + e.StopTask(task.ID) + var facts int + if err := m.pg.QueryRow(`SELECT count(*) FROM exploration_nodes WHERE exploration_id=$1 AND kind='fact' AND payload->>'summary'='Fixture worker executed the queued comparison'`, task.Store.ID()).Scan(&facts); err != nil { + t.Fatal(err) + } + if workerProvider.calls.Load() < 2 || facts != 1 || m.TaskStatus(task.ID) != "running" { + t.Fatalf("calls=%d facts=%d status=%s", workerProvider.calls.Load(), facts, m.TaskStatus(task.ID)) + } + t.Logf("actual engine: planner=%d worker=%d persisted_worker_facts=%d task=%s", provider.calls.Load(), workerProvider.calls.Load(), facts, m.TaskStatus(task.ID)) +} + +func TestPlannerProgressEngineRestartAndResume(t *testing.T) { + _, task, e := planningLoopFixture(t) + provider := &planningLoopProvider{response: func(int, llm.CompletionRequest) (llm.Message, string, error) { + return planningText("No step generated."), "end_turn", nil + }} + p := agent.NewPlanner(provider, "fixture", t.TempDir(), nil, 100000, 4) + p.SetNonStreaming(func() bool { return true }) + w, _ := fixtureWorker(t) + e.SetAuthoritativeAgentResolver(func(*Task) (*agent.Planner, *agent.Worker) { return p, w }) + snap, err := task.Store.PlanningSnapshot(t.Context()) + if err != nil { + t.Fatal(err) + } + for range 3 { + if err = task.Store.SavePlanningProgress(t.Context(), snap, "stalled", "persisted empty rounds", nil); err != nil { + t.Fatal(err) + } + } + e.Run(t.Context(), task) + time.Sleep(150 * time.Millisecond) + if provider.calls.Load() != 0 { + t.Fatal("restart ignored durable stalled state") + } + e.Resume(task) + waitPlanning(t, 3*time.Second, func() bool { return provider.calls.Load() >= 2 }) + e.StopTask(task.ID) +} + +func TestPlannerProgressEngineRecoveryDeadline(t *testing.T) { + _, task, e := planningLoopFixture(t) + provider := &planningLoopProvider{response: func(call int, _ llm.CompletionRequest) (llm.Message, string, error) { + if call == 1 { + return planningTool("add_intent", map[string]any{"summary": "Perform the supplied offline comparison"}), "tool_use", nil + } + return planningText("queued"), "end_turn", nil + }} + p := agent.NewPlanner(provider, "fixture", t.TempDir(), nil, 100000, 4) + p.SetNonStreaming(func() bool { return true }) + w, _ := fixtureWorker(t) + e.SetAuthoritativeAgentResolver(func(*Task) (*agent.Planner, *agent.Worker) { return p, w }) + snap, err := task.Store.PlanningSnapshot(t.Context()) + if err != nil { + t.Fatal(err) + } + due := time.Now().Add(100 * time.Millisecond) + if err = task.Store.SavePlanningProgress(t.Context(), snap, "stalled", "retry due shortly", &due); err != nil { + t.Fatal(err) + } + e.Run(t.Context(), task) + waitPlanning(t, 5*time.Second, func() bool { + snap, err := task.Store.PlanningSnapshot(t.Context()) + return err == nil && snap.Done == 1 + }) + e.StopTask(task.ID) +} diff --git a/server/task_credentials.go b/server/task_credentials.go index ca1210db..133c7954 100644 --- a/server/task_credentials.go +++ b/server/task_credentials.go @@ -82,6 +82,9 @@ func (s *Server) addTaskCredential(w http.ResponseWriter, r *http.Request) { writeErr(w, 400, err.Error()) return } + if task, ok := s.m.Task(r.PathValue("id")); ok { + task.Notify() + } writeJSON(w, 201, taskCredentialDTO(c)) } @@ -99,5 +102,8 @@ func (s *Server) deleteTaskCredential(w http.ResponseWriter, r *http.Request) { writeErr(w, 404, err.Error()) return } + if task, ok := s.m.Task(r.PathValue("id")); ok { + task.Notify() + } writeJSON(w, 200, map[string]any{"ok": true}) }