summaryrefslogtreecommitdiff
path: root/internal/storage
diff options
context:
space:
mode:
authorClaude Sonnet 5 <noreply@anthropic.com>2026-07-04 04:39:28 +0000
committerClaude Sonnet 5 <noreply@anthropic.com>2026-07-04 04:39:28 +0000
commit04b6e7eef473cb6eb69e345a4ea08243a8713077 (patch)
tree630ec202db1d27e65f8b7e57be30682f440e49c6 /internal/storage
parente4087a7dc133fe8c8523ca585b1841ff2b0be2d9 (diff)
feat(story,scheduler): add epic-proposal tool + AskUser-timeout escalation (Phase 7c)
Two independent pieces, completing Phase 7. Epic-proposal tool: AgentChannel gains a 5th method, ProposeEpic(ctx, EpicProposal{Name, Description, StoryIDs}) (epicID, err), implemented on storeChannel -- matches an existing epic by exact name or creates one (DiscoverySource: "agent"), sets epic_id on each resolvable story (skips, doesn't fail, on an unresolved ID), emits KindEpicProposed attached to the epic's own ID with payload {epic_id, name, story_ids}. Wired into both transports exactly like Phase 6 wired role into spawn_subtask: a new propose_epic tool in the native tool-use loop (internal/agentloop/tools.go) and the MCP transport (internal/executor/agentmcp.go). This is the mechanism for a discovery/planner-role agent to act on its own judgment that several stories it's been given form one cohesive initiative -- the judgment itself lives in the calling agent's instructions/model, not in this code. AskUser-timeout escalation: extends the existing Scheduler (Phase 5's retry-then-escalate watcher) rather than adding a new component, since "stuck task needs escalation" is exactly what it already does. Finds role-typed BLOCKED tasks whose question has been outstanding longer than SchedulerConfig.AskUserTimeoutSeconds (default 10 minutes) using task.UpdatedAt as the outstanding-since timestamp -- no new column needed, since UpdateTaskQuestion already stamps it the instant a question is recorded and nothing else touches the row while BLOCKED. Resolves the next ladder tier from the latest execution's EscalationRung, records the system-authored fallback answer as an audit-trail task.Interaction, clears the question, sets the new tasks.needs_review flag, emits KindEscalated (now carrying a trigger field: "failure" vs "ask_user_timeout" for the existing failure-retry path vs this one), and resumes via Pool.SubmitResume at the escalated tier -- degrading to same-tier resume with final:true if the ladder's exhausted or no role config exists, since unblocking the task takes priority over having somewhere higher to escalate to. GET /api/tasks?needs_review=true surfaces auto-decided tasks for human review. go build/vet/test -race -count=1 all pass, full suite (20 packages), run twice to rule out flakiness in the new tests. (One pre-existing, unrelated test -- TestHandleRunTask_CascadesRetryToFailedDeps, a tempdir-cleanup race -- appeared once under full-suite load per the implementing agent's report and did not reproduce in this verification's runs either; not a regression from this work.) Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01V1moSNCJRcP6kykA4tyUSs
Diffstat (limited to 'internal/storage')
-rw-r--r--internal/storage/db.go36
-rw-r--r--internal/storage/epic.go11
2 files changed, 41 insertions, 6 deletions
diff --git a/internal/storage/db.go b/internal/storage/db.go
index 8b563a6..51ea648 100644
--- a/internal/storage/db.go
+++ b/internal/storage/db.go
@@ -184,6 +184,11 @@ func (s *DB) migrate() error {
`CREATE INDEX IF NOT EXISTS idx_stories_status ON stories(status)`,
`CREATE INDEX IF NOT EXISTS idx_stories_epic_id ON stories(epic_id)`,
`CREATE INDEX IF NOT EXISTS idx_stories_root_task_id ON stories(root_task_id)`,
+ // needs_review (Phase 7c): flagged by internal/scheduler.Scheduler
+ // when it resumes a role-typed task past its ask_user-timeout with a
+ // system-authored fallback answer, so a human can find and double-check
+ // it later via GET /api/tasks?needs_review=true.
+ `ALTER TABLE tasks ADD COLUMN needs_review BOOLEAN NOT NULL DEFAULT 0`,
}
for _, m := range migrations {
if _, err := s.db.Exec(m); err != nil {
@@ -258,13 +263,13 @@ func (s *DB) CreateTask(t *task.Task) error {
// GetTask retrieves a task by ID.
func (s *DB) GetTask(id string) (*task.Task, error) {
- row := s.db.QueryRow(`SELECT id, name, description, elaboration_input, project, repository_url, config_json, priority, timeout_ns, retry_json, tags_json, depends_on_json, parent_task_id, state, created_at, updated_at, rejection_comment, question_json, summary, interactions_json FROM tasks WHERE id = ?`, id)
+ row := s.db.QueryRow(`SELECT id, name, description, elaboration_input, project, repository_url, config_json, priority, timeout_ns, retry_json, tags_json, depends_on_json, parent_task_id, state, created_at, updated_at, rejection_comment, question_json, summary, interactions_json, needs_review FROM tasks WHERE id = ?`, id)
return scanTask(row)
}
// ListTasks returns tasks matching the given filter.
func (s *DB) ListTasks(filter TaskFilter) ([]*task.Task, error) {
- query := `SELECT id, name, description, elaboration_input, project, repository_url, config_json, priority, timeout_ns, retry_json, tags_json, depends_on_json, parent_task_id, state, created_at, updated_at, rejection_comment, question_json, summary, interactions_json FROM tasks WHERE 1=1`
+ query := `SELECT id, name, description, elaboration_input, project, repository_url, config_json, priority, timeout_ns, retry_json, tags_json, depends_on_json, parent_task_id, state, created_at, updated_at, rejection_comment, question_json, summary, interactions_json, needs_review FROM tasks WHERE 1=1`
var args []interface{}
if filter.State != "" {
@@ -275,6 +280,10 @@ func (s *DB) ListTasks(filter TaskFilter) ([]*task.Task, error) {
query += " AND updated_at > ?"
args = append(args, filter.Since.UTC())
}
+ if filter.NeedsReview != nil {
+ query += " AND needs_review = ?"
+ args = append(args, *filter.NeedsReview)
+ }
query += " ORDER BY created_at DESC"
if filter.Limit > 0 {
query += " LIMIT ?"
@@ -300,7 +309,7 @@ func (s *DB) ListTasks(filter TaskFilter) ([]*task.Task, error) {
// ListSubtasks returns all tasks whose parent_task_id matches the given ID.
func (s *DB) ListSubtasks(parentID string) ([]*task.Task, error) {
- rows, err := s.db.Query(`SELECT id, name, description, elaboration_input, project, repository_url, config_json, priority, timeout_ns, retry_json, tags_json, depends_on_json, parent_task_id, state, created_at, updated_at, rejection_comment, question_json, summary, interactions_json FROM tasks WHERE parent_task_id = ? ORDER BY created_at ASC`, parentID)
+ rows, err := s.db.Query(`SELECT id, name, description, elaboration_input, project, repository_url, config_json, priority, timeout_ns, retry_json, tags_json, depends_on_json, parent_task_id, state, created_at, updated_at, rejection_comment, question_json, summary, interactions_json, needs_review FROM tasks WHERE parent_task_id = ? ORDER BY created_at ASC`, parentID)
if err != nil {
return nil, err
}
@@ -325,7 +334,7 @@ func (s *DB) ListSubtasks(parentID string) ([]*task.Task, error) {
// Only direct dependents are returned — callers that need the full
// transitive downstream subtree (e.g. cascade-cancellation) must recurse.
func (s *DB) ListDependents(taskID string) ([]*task.Task, error) {
- rows, err := s.db.Query(`SELECT id, name, description, elaboration_input, project, repository_url, config_json, priority, timeout_ns, retry_json, tags_json, depends_on_json, parent_task_id, state, created_at, updated_at, rejection_comment, question_json, summary, interactions_json FROM tasks`)
+ rows, err := s.db.Query(`SELECT id, name, description, elaboration_input, project, repository_url, config_json, priority, timeout_ns, retry_json, tags_json, depends_on_json, parent_task_id, state, created_at, updated_at, rejection_comment, question_json, summary, interactions_json, needs_review FROM tasks`)
if err != nil {
return nil, err
}
@@ -400,7 +409,7 @@ func (s *DB) ResetTaskForRetry(id string) (*task.Task, error) {
}
defer tx.Rollback() //nolint:errcheck
- t, err := scanTask(tx.QueryRow(`SELECT id, name, description, elaboration_input, project, repository_url, config_json, priority, timeout_ns, retry_json, tags_json, depends_on_json, parent_task_id, state, created_at, updated_at, rejection_comment, question_json, summary, interactions_json FROM tasks WHERE id = ?`, id))
+ t, err := scanTask(tx.QueryRow(`SELECT id, name, description, elaboration_input, project, repository_url, config_json, priority, timeout_ns, retry_json, tags_json, depends_on_json, parent_task_id, state, created_at, updated_at, rejection_comment, question_json, summary, interactions_json, needs_review FROM tasks WHERE id = ?`, id))
if err != nil {
if err == sql.ErrNoRows {
return nil, fmt.Errorf("task %q not found", id)
@@ -450,6 +459,18 @@ func (s *DB) UpdateTaskAgent(id string, agent task.AgentConfig) error {
return err
}
+// UpdateTaskNeedsReview sets tasks.needs_review. Used by
+// internal/scheduler.Scheduler to flag a task whose BLOCKED ask_user question
+// was resumed with a system-authored fallback answer after timing out,
+// rather than a real human answer, so a human can find it later via
+// GET /api/tasks?needs_review=true.
+func (s *DB) UpdateTaskNeedsReview(id string, needsReview bool) error {
+ now := time.Now().UTC()
+ _, err := s.db.Exec(`UPDATE tasks SET needs_review = ?, updated_at = ? WHERE id = ?`,
+ needsReview, now, id)
+ return err
+}
+
// RejectTask sets a task's state to PENDING and stores the rejection comment.
func (s *DB) RejectTask(id, comment string) error {
tx, err := s.db.Begin()
@@ -550,6 +571,9 @@ type TaskFilter struct {
State task.State
Limit int
Since time.Time
+ // NeedsReview, when non-nil, filters to tasks.needs_review == *NeedsReview.
+ // nil (the default) applies no filter. Backs GET /api/tasks?needs_review=true.
+ NeedsReview *bool
}
// GetMaxUpdatedAt returns the most recent updated_at timestamp across all tasks.
@@ -1156,7 +1180,7 @@ func scanTask(row scanner) (*task.Task, error) {
&t.ID, &t.Name, &t.Description, &elaborationInput, &project, &repositoryURL,
&configJSON, &priority, &timeoutNS, &retryJSON, &tagsJSON, &depsJSON,
&parentTaskID, &state, &t.CreatedAt, &t.UpdatedAt,
- &rejectionComment, &questionJSON, &summary, &interactionsJSON,
+ &rejectionComment, &questionJSON, &summary, &interactionsJSON, &t.NeedsReview,
)
t.ParentTaskID = parentTaskID.String
t.ElaborationInput = elaborationInput.String
diff --git a/internal/storage/epic.go b/internal/storage/epic.go
index 9f3863c..6d2b4d6 100644
--- a/internal/storage/epic.go
+++ b/internal/storage/epic.go
@@ -28,6 +28,17 @@ func (s *DB) GetEpic(id string) (*story.Epic, error) {
return scanEpic(row)
}
+// GetEpicByName retrieves an epic by exact name match (the earliest-created
+// one, if more than one somehow shares a name), or sql.ErrNoRows if none
+// exists. Used by internal/executor's ProposeEpic (Phase 7c) to decide
+// whether a discovery/planner agent's proposed epic name refers to an
+// existing epic or needs a new one — simplest reasonable matching, no fuzzy
+// dedup.
+func (s *DB) GetEpicByName(name string) (*story.Epic, error) {
+ row := s.db.QueryRow(`SELECT id, name, description, status, discovery_source, created_at, updated_at FROM epics WHERE name = ? ORDER BY created_at ASC LIMIT 1`, name)
+ return scanEpic(row)
+}
+
// ListEpics returns epics, optionally filtered by status. Pass an empty
// string to list all epics.
func (s *DB) ListEpics(status string) ([]*story.Epic, error) {