From 18516c8f8b03a1ddd9cd96a5a0c26cd0bb0c2625 Mon Sep 17 00:00:00 2001 From: Henry Date: Fri, 18 Sep 2026 17:35:16 +0800 Subject: [PATCH] feat(office): let a scheduled coordinator agent see the board and flag blockers (#3723) Co-authored-by: nova28 <17953305+nova28@users.noreply.github.com> Co-authored-by: Carlos Florencio --- apps/backend/cmd/agentctl/kandev.go | 30 +- apps/backend/cmd/agentctl/kandev_agents.go | 13 +- apps/backend/cmd/agentctl/kandev_approvals.go | 9 +- apps/backend/cmd/agentctl/kandev_budget.go | 5 +- apps/backend/cmd/agentctl/kandev_memory.go | 13 +- apps/backend/cmd/agentctl/kandev_routines.go | 3 +- apps/backend/cmd/agentctl/kandev_tasks.go | 71 +- .../backend/cmd/agentctl/kandev_tasks_test.go | 126 ++++ .../internal/office/dashboard/handler.go | 28 + .../dashboard/handler_tasks_security_test.go | 254 +++++++ .../office/repository/sqlite/runner_set.go | 51 ++ .../sqlite/runner_set_query_count_test.go | 149 ++++ .../repository/sqlite/runner_set_test.go | 129 ++++ .../office/repository/sqlite/tasks.go | 34 +- .../repository/sqlite/tasks_filtered_test.go | 175 +++++ .../office/repository/sqlite/tasks_test.go | 11 +- apps/backend/internal/office/routes.go | 1 + .../internal/office/runtime/actions.go | 43 +- .../office/runtime/actions_annotation_test.go | 271 +++++++ .../internal/office/runtime/actions_test.go | 28 + .../internal/office/runtime/capabilities.go | 22 +- .../office/runtime/capabilities_test.go | 127 ++++ .../internal/office/runtime/context.go | 23 +- .../office/runtime/context_builder.go | 312 +++++++- .../office/runtime/context_builder_test.go | 118 ++- .../internal/office/runtime/context_test.go | 22 + .../backend/internal/office/runtime/errors.go | 6 + .../internal/office/runtime/handler.go | 10 +- .../handler_taskless_annotation_test.go | 133 ++++ .../internal/office/runtime/handler_test.go | 1 + .../office/runtime/scope_derivation_test.go | 691 ++++++++++++++++++ .../internal/office/runtime/tasks_list.go | 267 +++++++ .../office/runtime/tasks_list_query_test.go | 187 +++++ .../office/runtime/tasks_list_test.go | 284 +++++++ .../office/service/budget_admission.go | 6 +- .../office/service/budget_admission_test.go | 1 + .../office/service/scheduler_integration.go | 17 +- .../service/scheduler_taskless_launch_test.go | 56 ++ .../internal/runs/repository/sqlite/runs.go | 32 + .../sqlite/runs_snapshot_cas_test.go | 81 ++ .../plan.md | 165 +++++ ...mplement-taskless-coordinator-authority.md | 166 +++++ docs/public/automation-and-mcp.md | 13 + .../taskless-coordinator-authority.md | 322 ++++++++ .../taskless-coordinator-authority-01.md | 533 ++++++++++++++ .../taskless-coordinator-authority-02.md | 218 ++++++ 46 files changed, 5175 insertions(+), 82 deletions(-) create mode 100644 apps/backend/cmd/agentctl/kandev_tasks_test.go create mode 100644 apps/backend/internal/office/dashboard/handler_tasks_security_test.go create mode 100644 apps/backend/internal/office/repository/sqlite/runner_set.go create mode 100644 apps/backend/internal/office/repository/sqlite/runner_set_query_count_test.go create mode 100644 apps/backend/internal/office/repository/sqlite/runner_set_test.go create mode 100644 apps/backend/internal/office/runtime/actions_annotation_test.go create mode 100644 apps/backend/internal/office/runtime/context_test.go create mode 100644 apps/backend/internal/office/runtime/handler_taskless_annotation_test.go create mode 100644 apps/backend/internal/office/runtime/scope_derivation_test.go create mode 100644 apps/backend/internal/office/runtime/tasks_list.go create mode 100644 apps/backend/internal/office/runtime/tasks_list_query_test.go create mode 100644 apps/backend/internal/office/runtime/tasks_list_test.go create mode 100644 apps/backend/internal/runs/repository/sqlite/runs_snapshot_cas_test.go create mode 100644 docs/plans/office-taskless-coordinator-authority/plan.md create mode 100644 docs/plans/office-taskless-coordinator-authority/task-01-implement-taskless-coordinator-authority.md create mode 100644 docs/specs/office/requirements/taskless-coordinator-authority.md create mode 100644 docs/specs/office/system-design/taskless-coordinator-authority-01.md create mode 100644 docs/specs/office/system-design/taskless-coordinator-authority-02.md diff --git a/apps/backend/cmd/agentctl/kandev.go b/apps/backend/cmd/agentctl/kandev.go index 18b47b9b8e..085807593f 100644 --- a/apps/backend/cmd/agentctl/kandev.go +++ b/apps/backend/cmd/agentctl/kandev.go @@ -99,24 +99,26 @@ func handleResponse(body []byte, status int, err error) int { return 1 } -// getWithParams performs a GET request with query parameters. It handles -// client creation, required env var check, path building, and response output. -func getWithParams(basePath, requiredEnvName, requiredEnvVal string, params map[string]string) int { - client, err := newKandevClient() - if err != nil { - cliError("%v", err) - return 1 - } +// getWithParams performs a GET request with query parameters, requiring +// requiredEnvVal to be set first. See getWithQuery for the variant with no +// required-env check. +func getWithParams(basePath, requiredEnvName, requiredEnvVal string, values url.Values) int { if requiredEnvVal == "" { cliError("%s must be set", requiredEnvName) return 1 } - values := url.Values{} - for k, v := range params { - if v == "" { - continue - } - values.Set(k, v) + return getWithQuery(basePath, values) +} + +// getWithQuery performs a GET request with query parameters. It handles +// client creation, path building, and response output. values is carried +// as url.Values (built with Add) rather than a map so a repeatable +// parameter can hold more than one value for the same key. +func getWithQuery(basePath string, values url.Values) int { + client, err := newKandevClient() + if err != nil { + cliError("%v", err) + return 1 } q := "" if encoded := values.Encode(); encoded != "" { diff --git a/apps/backend/cmd/agentctl/kandev_agents.go b/apps/backend/cmd/agentctl/kandev_agents.go index f56865e06c..5265445362 100644 --- a/apps/backend/cmd/agentctl/kandev_agents.go +++ b/apps/backend/cmd/agentctl/kandev_agents.go @@ -4,6 +4,7 @@ import ( "flag" "fmt" "net/http" + "net/url" "os" ) @@ -39,10 +40,14 @@ func agentsList(args []string) int { wsID := os.Getenv("KANDEV_WORKSPACE_ID") path := fmt.Sprintf("/api/v1/office/workspaces/%s/agents", wsID) - return getWithParams(path, "KANDEV_WORKSPACE_ID", wsID, map[string]string{ - "role": *roleFlag, - "status": *statusFlag, - }) + values := url.Values{} + if *roleFlag != "" { + values.Set("role", *roleFlag) + } + if *statusFlag != "" { + values.Set("status", *statusFlag) + } + return getWithParams(path, "KANDEV_WORKSPACE_ID", wsID, values) } // agentsCreate hires a new agent for the current workspace. The diff --git a/apps/backend/cmd/agentctl/kandev_approvals.go b/apps/backend/cmd/agentctl/kandev_approvals.go index 381acd99f1..d1b69f2432 100644 --- a/apps/backend/cmd/agentctl/kandev_approvals.go +++ b/apps/backend/cmd/agentctl/kandev_approvals.go @@ -4,6 +4,7 @@ import ( "flag" "fmt" "net/http" + "net/url" "os" ) @@ -35,9 +36,11 @@ func approvalsList(args []string) int { } wsID := os.Getenv("KANDEV_WORKSPACE_ID") path := fmt.Sprintf("/api/v1/office/workspaces/%s/approvals", wsID) - return getWithParams(path, "KANDEV_WORKSPACE_ID", wsID, map[string]string{ - "status": *status, - }) + values := url.Values{} + if *status != "" { + values.Set("status", *status) + } + return getWithParams(path, "KANDEV_WORKSPACE_ID", wsID, values) } // approvalsDecide flips an approval to approved or rejected. The diff --git a/apps/backend/cmd/agentctl/kandev_budget.go b/apps/backend/cmd/agentctl/kandev_budget.go index 64581c9d5f..b51bcfcdfd 100644 --- a/apps/backend/cmd/agentctl/kandev_budget.go +++ b/apps/backend/cmd/agentctl/kandev_budget.go @@ -3,6 +3,7 @@ package main import ( "flag" "fmt" + "net/url" "os" ) @@ -41,9 +42,9 @@ func budgetGet(args []string) int { if *agentID == "" { return getWithParams( fmt.Sprintf("/api/v1/office/workspaces/%s/costs/summary", wsID), - "KANDEV_WORKSPACE_ID", wsID, nil) + "KANDEV_WORKSPACE_ID", wsID, url.Values{}) } return getWithParams( fmt.Sprintf("/api/v1/office/workspaces/%s/costs/by-agent", wsID), - "KANDEV_WORKSPACE_ID", wsID, map[string]string{"agent_id": *agentID}) + "KANDEV_WORKSPACE_ID", wsID, url.Values{"agent_id": {*agentID}}) } diff --git a/apps/backend/cmd/agentctl/kandev_memory.go b/apps/backend/cmd/agentctl/kandev_memory.go index 9dfede36f7..fb7c973730 100644 --- a/apps/backend/cmd/agentctl/kandev_memory.go +++ b/apps/backend/cmd/agentctl/kandev_memory.go @@ -4,6 +4,7 @@ import ( "flag" "fmt" "net/http" + "net/url" "os" ) @@ -38,10 +39,14 @@ func memoryGet(args []string) int { agentID := os.Getenv("KANDEV_AGENT_ID") path := fmt.Sprintf("/api/v1/office/agents/%s/memory", agentID) - return getWithParams(path, "KANDEV_AGENT_ID", agentID, map[string]string{ - "layer": *layerFlag, - "key": *keyFlag, - }) + values := url.Values{} + if *layerFlag != "" { + values.Set("layer", *layerFlag) + } + if *keyFlag != "" { + values.Set("key", *keyFlag) + } + return getWithParams(path, "KANDEV_AGENT_ID", agentID, values) } // memorySet upserts a memory entry for the current agent. diff --git a/apps/backend/cmd/agentctl/kandev_routines.go b/apps/backend/cmd/agentctl/kandev_routines.go index 8e4241d23c..72236cc865 100644 --- a/apps/backend/cmd/agentctl/kandev_routines.go +++ b/apps/backend/cmd/agentctl/kandev_routines.go @@ -5,6 +5,7 @@ import ( "flag" "fmt" "net/http" + "net/url" "os" ) @@ -41,7 +42,7 @@ func routinesList(args []string) int { } wsID := os.Getenv("KANDEV_WORKSPACE_ID") path := fmt.Sprintf("/api/v1/office/workspaces/%s/routines", wsID) - return getWithParams(path, "KANDEV_WORKSPACE_ID", wsID, nil) + return getWithParams(path, "KANDEV_WORKSPACE_ID", wsID, url.Values{}) } // routinesCreate provisions a routine + cron trigger in two diff --git a/apps/backend/cmd/agentctl/kandev_tasks.go b/apps/backend/cmd/agentctl/kandev_tasks.go index ac7b189234..e3c325f418 100644 --- a/apps/backend/cmd/agentctl/kandev_tasks.go +++ b/apps/backend/cmd/agentctl/kandev_tasks.go @@ -4,9 +4,28 @@ import ( "flag" "fmt" "net/http" - "os" + "net/url" + "strings" ) +// repeatableFlag collects one or more occurrences of a repeatable CLI flag +// (e.g. --status todo --status in_progress) into an ordered slice, so a +// caller can reach the board-read endpoint's per-value union semantics for +// a repeatable parameter. +type repeatableFlag []string + +func (f *repeatableFlag) String() string { + if f == nil { + return "" + } + return strings.Join(*f, ",") +} + +func (f *repeatableFlag) Set(value string) error { + *f = append(*f, value) + return nil +} + // runTasksCmd dispatches `agentctl kandev tasks `. The // singular `agentctl kandev task ` group (get/update/create) // remains the back-compat path; this plural group adds the verbs @@ -33,25 +52,53 @@ func runTasksCmd(args []string) int { } } -// tasksList returns workspace tasks, optionally filtered by status -// or assignee. Hits the office dashboard list endpoint so the -// returned shape matches what the Tasks page sees. +// tasksList returns the board a run may act on: it calls the signed +// runtime board-read endpoint (GET /api/v1/office/runtime/tasks), which +// resolves its workspace from the run token's claim rather than +// KANDEV_WORKSPACE_ID, so it succeeds even when that variable is unset. +// One flag per query parameter the endpoint accepts; --status and +// --priority are repeatable and reach the endpoint as repeated query +// values with union semantics. func tasksList(args []string) int { fs := flag.NewFlagSet("tasks list", flag.ContinueOnError) - status := fs.String("status", "", "Filter by status (todo, in_progress, done, …)") + var status repeatableFlag + var priority repeatableFlag + fs.Var(&status, "status", "Filter by status (repeatable)") + fs.Var(&priority, "priority", "Filter by priority (repeatable)") assignee := fs.String("assignee", "", "Filter by assignee agent ID") project := fs.String("project", "", "Filter by project ID") + sortField := fs.String("sort", "", "Sort column: updated_at | created_at | priority") + order := fs.String("order", "", "Sort direction: asc | desc (default desc)") + limit := fs.String("limit", "", "Page size, up to 500 (default 100)") + cursor := fs.String("cursor", "", "Continuation cursor value from a prior page") + cursorID := fs.String("cursor-id", "", "Continuation cursor id from a prior page") + includeSystem := fs.String("include-system", "", "Include kandev-managed system-workflow tasks: true | false") if err := fs.Parse(args); err != nil { cliError("parse flags: %v", err) return 1 } - wsID := os.Getenv("KANDEV_WORKSPACE_ID") - path := fmt.Sprintf("/api/v1/office/workspaces/%s/tasks", wsID) - return getWithParams(path, "KANDEV_WORKSPACE_ID", wsID, map[string]string{ - "status": *status, - "assignee": *assignee, - "project": *project, - }) + values := url.Values{} + for _, v := range status { + values.Add("status", v) + } + for _, v := range priority { + values.Add("priority", v) + } + setQueryIfNonEmpty(values, "assignee", *assignee) + setQueryIfNonEmpty(values, "project", *project) + setQueryIfNonEmpty(values, "sort", *sortField) + setQueryIfNonEmpty(values, "order", *order) + setQueryIfNonEmpty(values, "limit", *limit) + setQueryIfNonEmpty(values, "cursor", *cursor) + setQueryIfNonEmpty(values, "cursor_id", *cursorID) + setQueryIfNonEmpty(values, "include_system", *includeSystem) + return getWithQuery("/api/v1/office/runtime/tasks", values) +} + +func setQueryIfNonEmpty(values url.Values, key, value string) { + if value != "" { + values.Set(key, value) + } } // tasksMove fails closed because Office runs do not have a signed runtime diff --git a/apps/backend/cmd/agentctl/kandev_tasks_test.go b/apps/backend/cmd/agentctl/kandev_tasks_test.go new file mode 100644 index 0000000000..0c839655ee --- /dev/null +++ b/apps/backend/cmd/agentctl/kandev_tasks_test.go @@ -0,0 +1,126 @@ +package main + +import ( + "net/http" + "net/url" + "testing" +) + +func TestTasksList_CallsBoardReadEndpoint(t *testing.T) { + srv, captured := setupMockServer(t, http.StatusOK, `{"tasks":[],"next_cursor":"","next_id":""}`) + setEnvVars(t, srv) + + code := runKandevCLI([]string{"tasks", "list"}) + if code != 0 { + t.Fatalf("expected exit 0, got %d", code) + } + if captured.Method != http.MethodGet { + t.Errorf("expected GET, got %s", captured.Method) + } + if captured.Path != "/api/v1/office/runtime/tasks" { + t.Errorf("unexpected path: %s", captured.Path) + } + assertAuthHeader(t, captured) +} + +// TestTasksList_DoesNotRequireWorkspaceID pins the board-read endpoint's +// authority model: the workspace comes from the run token's claim, not the +// KANDEV_WORKSPACE_ID environment variable, so a taskless run with that +// variable unset must still succeed. +func TestTasksList_DoesNotRequireWorkspaceID(t *testing.T) { + srv, captured := setupMockServer(t, http.StatusOK, `{"tasks":[]}`) + setEnvVars(t, srv) + t.Setenv("KANDEV_WORKSPACE_ID", "") + + code := runKandevCLI([]string{"tasks", "list"}) + if code != 0 { + t.Fatalf("expected exit 0, got %d", code) + } + if captured.Path != "/api/v1/office/runtime/tasks" { + t.Fatalf("request path = %q, want runtime board-read endpoint", captured.Path) + } +} + +func TestTasksList_RepeatableStatusAndPriorityReachServerAsMultipleValues(t *testing.T) { + srv, captured := setupMockServer(t, http.StatusOK, `{"tasks":[]}`) + setEnvVars(t, srv) + + code := runKandevCLI([]string{ + "tasks", "list", + "--status", "TODO", "--status", "IN_PROGRESS", + "--priority", "high", "--priority", "medium", + }) + if code != 0 { + t.Fatalf("expected exit 0, got %d", code) + } + parsed, err := url.ParseQuery(captured.Query) + if err != nil { + t.Fatalf("parse query %q: %v", captured.Query, err) + } + gotStatus := parsed["status"] + if len(gotStatus) != 2 || gotStatus[0] != "TODO" || gotStatus[1] != "IN_PROGRESS" { + t.Fatalf("status query values = %v, want [TODO IN_PROGRESS]", gotStatus) + } + gotPriority := parsed["priority"] + if len(gotPriority) != 2 || gotPriority[0] != "high" || gotPriority[1] != "medium" { + t.Fatalf("priority query values = %v, want [high medium]", gotPriority) + } +} + +func TestTasksList_SingleValuedFlagsReachServer(t *testing.T) { + srv, captured := setupMockServer(t, http.StatusOK, `{"tasks":[]}`) + setEnvVars(t, srv) + + code := runKandevCLI([]string{ + "tasks", "list", + "--assignee", "agent-1", "--project", "project-1", + "--sort", "priority", "--order", "asc", + "--limit", "50", "--cursor", "v1", "--cursor-id", "task-9", + "--include-system", "true", + }) + if code != 0 { + t.Fatalf("expected exit 0, got %d", code) + } + parsed, err := url.ParseQuery(captured.Query) + if err != nil { + t.Fatalf("parse query %q: %v", captured.Query, err) + } + want := map[string]string{ + "assignee": "agent-1", + "project": "project-1", + "sort": "priority", + "order": "asc", + "limit": "50", + "cursor": "v1", + "cursor_id": "task-9", + "include_system": "true", + } + for key, value := range want { + if got := parsed.Get(key); got != value { + t.Errorf("query[%s] = %q, want %q (raw=%q)", key, got, value, captured.Query) + } + } +} + +func TestTasksList_OmittedFlagsAreAbsentFromQuery(t *testing.T) { + srv, captured := setupMockServer(t, http.StatusOK, `{"tasks":[]}`) + setEnvVars(t, srv) + + code := runKandevCLI([]string{"tasks", "list"}) + if code != 0 { + t.Fatalf("expected exit 0, got %d", code) + } + if captured.Query != "" { + t.Fatalf("query = %q, want empty when no flags are passed", captured.Query) + } +} + +func TestTasksList_PropagatesRuntimeScopeDenial(t *testing.T) { + srv, _ := setupMockServer(t, http.StatusForbidden, `{"error":"capability denied"}`) + setEnvVars(t, srv) + + code := runKandevCLI([]string{"tasks", "list"}) + if code != 1 { + t.Fatalf("tasks list exit = %d, want 1 for HTTP 403", code) + } +} diff --git a/apps/backend/internal/office/dashboard/handler.go b/apps/backend/internal/office/dashboard/handler.go index 200113d112..9b3a5cebce 100644 --- a/apps/backend/internal/office/dashboard/handler.go +++ b/apps/backend/internal/office/dashboard/handler.go @@ -8,6 +8,7 @@ import ( "github.com/gin-gonic/gin" "github.com/kandev/kandev/internal/common/logger" + "github.com/kandev/kandev/internal/office/agents" "github.com/kandev/kandev/internal/office/configloader" "github.com/kandev/kandev/internal/office/models" "github.com/kandev/kandev/internal/office/repository/sqlite" @@ -307,6 +308,10 @@ func (h *Handler) getAgentRunDetail(c *gin.Context) { // -- Task search -- func (h *Handler) searchTasks(c *gin.Context) { + if rejectAgentTaskReader(c) { + return + } + wsID := c.Param("wsId") query := c.Query("q") @@ -359,7 +364,30 @@ func (h *Handler) searchTasks(c *gin.Context) { // -- Tasks -- +// rejectAgentTaskReader answers true (after writing a 403 response) for an +// agent JWT caller on a dashboard task-read route. Every such route sits +// under the same Office group and inherits only AgentAuthMiddleware (token +// and workspace-claim validation, no capability check and no runtime audit +// event) — so without this guard an agent whose capability snapshot lacks +// list_tasks, or a taskless run with no board-read grant at all, could reach +// the workspace's task list here regardless of what the capability-checked, +// audited GET /runtime/tasks endpoint would have said. Mirrors the existing +// createComment agent-caller guard in this same file. +func rejectAgentTaskReader(c *gin.Context) bool { + if agents.CallerFromContext(c) == nil { + return false + } + c.JSON(http.StatusForbidden, gin.H{ + "error": "agent callers must use the runtime tasks endpoint", + }) + return true +} + func (h *Handler) listTasks(c *gin.Context) { + if rejectAgentTaskReader(c) { + return + } + ctx := c.Request.Context() wsID := c.Param("wsId") diff --git a/apps/backend/internal/office/dashboard/handler_tasks_security_test.go b/apps/backend/internal/office/dashboard/handler_tasks_security_test.go new file mode 100644 index 0000000000..c52848900f --- /dev/null +++ b/apps/backend/internal/office/dashboard/handler_tasks_security_test.go @@ -0,0 +1,254 @@ +package dashboard_test + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" + + "github.com/gin-gonic/gin" + "github.com/jmoiron/sqlx" + _ "github.com/mattn/go-sqlite3" + + settingsstore "github.com/kandev/kandev/internal/agent/settings/store" + "github.com/kandev/kandev/internal/common/logger" + "github.com/kandev/kandev/internal/office/agents" + "github.com/kandev/kandev/internal/office/dashboard" + officemodels "github.com/kandev/kandev/internal/office/models" + "github.com/kandev/kandev/internal/office/repository/sqlite" + "github.com/kandev/kandev/internal/office/shared" + workflowrepo "github.com/kandev/kandev/internal/workflow/repository" +) + +// tasksSecurityFixture wires the authenticated dashboard stack for the +// GET /workspaces/:wsId/tasks route. An agent JWT must not reach this +// route: it carries no list_tasks capability check and no audit event, +// unlike GET /runtime/tasks, so an agent caller here would bypass both. +type tasksSecurityFixture struct { + router *gin.Engine + agentsSvc *agents.AgentService + repo *sqlite.Repository +} + +func newTasksSecurityFixture(t *testing.T) *tasksSecurityFixture { + t.Helper() + gin.SetMode(gin.TestMode) + + db, err := sqlx.Open("sqlite3", ":memory:") + if err != nil { + t.Fatalf("open sqlite: %v", err) + } + db.SetMaxOpenConns(1) + t.Cleanup(func() { _ = db.Close() }) + + if _, _, err := settingsstore.Provide(db, db, nil); err != nil { + t.Fatalf("settings store: %v", err) + } + + repo, err := sqlite.NewWithDB(db, db, nil) + if err != nil { + t.Fatalf("new repo: %v", err) + } + + _, err = db.Exec(` + CREATE TABLE IF NOT EXISTS tasks ( + id TEXT PRIMARY KEY, + workspace_id TEXT NOT NULL DEFAULT '', + title TEXT NOT NULL DEFAULT '', + description TEXT DEFAULT '', + state TEXT DEFAULT 'todo', + priority TEXT NOT NULL DEFAULT 'medium' CHECK (priority IN ('critical','high','medium','low')), + position INTEGER DEFAULT 0, + parent_id TEXT DEFAULT '', + project_id TEXT DEFAULT '', + assignee_agent_profile_id TEXT DEFAULT '', + assignee_user_id TEXT NOT NULL DEFAULT '', + assignment_generation INTEGER NOT NULL DEFAULT 0, + labels TEXT DEFAULT '[]', + metadata TEXT DEFAULT '{}', + identifier TEXT DEFAULT '', + is_ephemeral INTEGER DEFAULT 0, + origin TEXT DEFAULT 'manual', + execution_policy TEXT DEFAULT '', + execution_state TEXT DEFAULT '', + workflow_id TEXT NOT NULL DEFAULT '', + workflow_step_id TEXT DEFAULT '', + archived_at TIMESTAMP, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP + ) + `) + if err != nil { + t.Fatalf("create tasks table: %v", err) + } + _, err = db.Exec(`CREATE TABLE IF NOT EXISTS workspaces ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL DEFAULT '', + description TEXT DEFAULT '', + owner_id TEXT DEFAULT '', + default_executor_id TEXT DEFAULT '', + default_environment_id TEXT DEFAULT '', + default_agent_profile_id TEXT DEFAULT '', + default_config_agent_profile_id TEXT DEFAULT '', + office_workflow_id TEXT DEFAULT '', + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP + )`) + if err != nil { + t.Fatalf("create workspaces table: %v", err) + } + _, err = db.Exec(`CREATE TABLE IF NOT EXISTS workflows ( + id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL DEFAULT '', + workflow_template_id TEXT DEFAULT '', name TEXT NOT NULL, + description TEXT DEFAULT '', created_at TIMESTAMP NOT NULL, updated_at TIMESTAMP NOT NULL + )`) + if err != nil { + t.Fatalf("create workflows: %v", err) + } + if _, err := workflowrepo.NewWithDB(db, db, nil); err != nil { + t.Fatalf("workflow repo: %v", err) + } + + log := logger.Default() + activity := shared.NewActivityLogger(repo, log) + agentsSvc := agents.NewAgentService(repo, log, nil) + agentsSvc.SetAuth(agents.NewAgentAuth("test-key")) + svc := dashboard.NewDashboardService(repo, log, activity, agentsSvc, &stubCostChecker{}) + + r := gin.New() + r.Use(agents.AgentAuthMiddleware(agentsSvc)) + group := r.Group("/api/v1/office") + dashboard.RegisterRoutes(group, svc, repo, nil, nil, nil, log) + + return &tasksSecurityFixture{router: r, agentsSvc: agentsSvc, repo: repo} +} + +func seedTasksWorkspace(t *testing.T, repo *sqlite.Repository, id string) { + t.Helper() + _, err := repo.ExecRaw(context.Background(), + `INSERT OR IGNORE INTO workspaces (id, name) VALUES (?, ?)`, id, id, + ) + if err != nil { + t.Fatalf("seed workspace %q: %v", id, err) + } +} + +func seedTasksAgent(t *testing.T, svc *agents.AgentService, repo *sqlite.Repository, id, workspaceID string) *officemodels.AgentInstance { + t.Helper() + seedTasksWorkspace(t, repo, workspaceID) + a := &officemodels.AgentInstance{ + ID: id, + WorkspaceID: workspaceID, + Name: id, + Role: officemodels.AgentRoleWorker, + Status: officemodels.AgentStatusIdle, + Permissions: shared.DefaultPermissions(shared.AgentRoleWorker), + } + if err := svc.CreateAgentInstance(context.Background(), a); err != nil { + t.Fatalf("create agent %q: %v", id, err) + } + return a +} + +func listTasksReq(wsID, token string) *http.Request { + req := httptest.NewRequest( + http.MethodGet, + "/api/v1/office/workspaces/"+wsID+"/tasks", + nil, + ) + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + return req +} + +func searchTasksReq(wsID, token string) *http.Request { + req := httptest.NewRequest( + http.MethodGet, + "/api/v1/office/workspaces/"+wsID+"/tasks/search", + nil, + ) + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + return req +} + +// TestListTasks_AgentCallerMustUseRuntimeEndpoint proves the fix for the +// bypass an agent JWT had of the list_tasks capability gate: GET +// /workspaces/:wsId/tasks sits under the same Office route group as GET +// /runtime/tasks and inherits AgentAuthMiddleware, which only validates the +// token — it does not check any runtime capability. Before this fix, an +// agent whose capability snapshot lacked list_tasks (or a taskless run with +// no board-read grant at all) could still reach the whole workspace's task +// list through this route, ungated and unaudited. +func TestListTasks_AgentCallerMustUseRuntimeEndpoint(t *testing.T) { + f := newTasksSecurityFixture(t) + agent := seedTasksAgent(t, f.agentsSvc, f.repo, "agent-a", "ws-1") + + // A run token with an explicit empty capabilities snapshot ({}), which + // denies every capability including list_tasks. + token, err := f.agentsSvc.MintRuntimeJWT(agent.ID, "", agent.WorkspaceID, "run-1", "sess-1", "{}") + if err != nil { + t.Fatalf("mint jwt: %v", err) + } + + rec := httptest.NewRecorder() + f.router.ServeHTTP(rec, listTasksReq("ws-1", token)) + + if rec.Code != http.StatusForbidden { + t.Fatalf("status = %d, want 403; body=%s", rec.Code, rec.Body.String()) + } +} + +// TestListTasks_UICallerWithoutTokenSucceeds proves the fix is scoped to +// agent callers only: a browser/UI request with no bearer token keeps +// working exactly as before. +func TestListTasks_UICallerWithoutTokenSucceeds(t *testing.T) { + f := newTasksSecurityFixture(t) + seedTasksWorkspace(t, f.repo, "ws-1") + + rec := httptest.NewRecorder() + f.router.ServeHTTP(rec, listTasksReq("ws-1", "")) + + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String()) + } +} + +// TestSearchTasks_AgentCallerMustUseRuntimeEndpoint proves the same fix for +// the sibling GET /workspaces/:wsId/tasks/search route: an empty query +// invokes the same unbounded ListTasks read as the plain list route, and a +// nonempty query searches the same workspace, so this route needs the +// identical agent-caller guard. +func TestSearchTasks_AgentCallerMustUseRuntimeEndpoint(t *testing.T) { + f := newTasksSecurityFixture(t) + agent := seedTasksAgent(t, f.agentsSvc, f.repo, "agent-a", "ws-1") + + token, err := f.agentsSvc.MintRuntimeJWT(agent.ID, "", agent.WorkspaceID, "run-1", "sess-1", "{}") + if err != nil { + t.Fatalf("mint jwt: %v", err) + } + + rec := httptest.NewRecorder() + f.router.ServeHTTP(rec, searchTasksReq("ws-1", token)) + + if rec.Code != http.StatusForbidden { + t.Fatalf("status = %d, want 403; body=%s", rec.Code, rec.Body.String()) + } +} + +// TestSearchTasks_UICallerWithoutTokenSucceeds proves the fix is scoped to +// agent callers only: a browser/UI request with no bearer token keeps +// working exactly as before. +func TestSearchTasks_UICallerWithoutTokenSucceeds(t *testing.T) { + f := newTasksSecurityFixture(t) + seedTasksWorkspace(t, f.repo, "ws-1") + + rec := httptest.NewRecorder() + f.router.ServeHTTP(rec, searchTasksReq("ws-1", "")) + + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String()) + } +} diff --git a/apps/backend/internal/office/repository/sqlite/runner_set.go b/apps/backend/internal/office/repository/sqlite/runner_set.go new file mode 100644 index 0000000000..c8fb450ae1 --- /dev/null +++ b/apps/backend/internal/office/repository/sqlite/runner_set.go @@ -0,0 +1,51 @@ +package sqlite + +import "context" + +// ListRunnerSetTaskIDs returns the ordered, capped ids of tasks the given +// agent is currently responsible for within one workspace — the "runner +// set" a taskless run's task scope materializes from +// (docs/specs/office/system-design/taskless-coordinator-authority-01.md#task-scope-derivation) +// — plus the true total before capping, so a caller can detect truncation. +// Ordered by (updated_at DESC, id DESC). The total is read from the same +// query snapshot as the ids via a window function, not a second query, so a +// concurrent board mutation between two separate reads cannot desync them. +// +// Shares CountActionableTasksForAgent's four clauses (runner projection +// equals the agent, actionable state, not archived, not automation-origin) +// plus a workspace_id filter CountActionableTasksForAgent does not have: +// this scope is a write authority, so it is filtered explicitly rather +// than relying on agent profiles happening to be workspace-unique. +func (r *Repository) ListRunnerSetTaskIDs( + ctx context.Context, agentID, workspaceID string, capAt int, +) ([]string, int, error) { + rows, err := r.ro.QueryxContext(ctx, r.ro.Rebind(` + SELECT t.id, COUNT(*) OVER() AS total FROM tasks t + WHERE `+RunnerProjection("t")+` = ? + AND t.workspace_id = ? + AND t.state IN ('TODO', 'IN_PROGRESS') + AND t.archived_at IS NULL`+andNotAutomationOriginT+` + ORDER BY t.updated_at DESC, t.id DESC + LIMIT ? + `), agentID, workspaceID, capAt) + if err != nil { + return nil, 0, err + } + defer func() { _ = rows.Close() }() + + ids := make([]string, 0) + total := 0 + for rows.Next() { + var id string + var rowTotal int + if err := rows.Scan(&id, &rowTotal); err != nil { + return nil, 0, err + } + ids = append(ids, id) + total = rowTotal + } + if err := rows.Err(); err != nil { + return nil, 0, err + } + return ids, total, nil +} diff --git a/apps/backend/internal/office/repository/sqlite/runner_set_query_count_test.go b/apps/backend/internal/office/repository/sqlite/runner_set_query_count_test.go new file mode 100644 index 0000000000..e4b9edfdf4 --- /dev/null +++ b/apps/backend/internal/office/repository/sqlite/runner_set_query_count_test.go @@ -0,0 +1,149 @@ +package sqlite_test + +import ( + "context" + "database/sql" + "database/sql/driver" + "strings" + "sync" + "sync/atomic" + "testing" + + "github.com/jmoiron/sqlx" + settingsstore "github.com/kandev/kandev/internal/agent/settings/store" + "github.com/kandev/kandev/internal/office/repository/sqlite" + sqlite3 "github.com/mattn/go-sqlite3" +) + +// runnerSetQueryCounter counts how many times a query matching +// isRunnerSetQuery reaches the driver. It has no synchronization needs (no +// concurrency scenario, unlike commentWindowDriver) — just a counter plus +// the last matched query text, so a test can assert not only how many +// queries matched but that the surviving one is still the right shape. +type runnerSetQueryCounter struct { + count int32 + lastText string +} + +func (c *runnerSetQueryCounter) inc(query string) { + atomic.AddInt32(&c.count, 1) + c.lastText = query +} +func (c *runnerSetQueryCounter) load() int32 { return atomic.LoadInt32(&c.count) } + +// isRunnerSetQuery matches any query against the tasks table, not just the +// exact expected shape — a regression that adds a second, differently +// shaped query (e.g. a separate pre-count) must be caught too, not only a +// wholesale removal of the `COUNT(*) OVER()` clause. +func isRunnerSetQuery(query string) bool { + return strings.Contains(strings.ToUpper(query), "FROM TASKS") +} + +var runnerSetCounterGlobal struct { + mu sync.Mutex + counter *runnerSetQueryCounter +} + +func init() { + sql.Register("sqlite3_runner_set_count_test", runnerSetCountDriver{}) +} + +type runnerSetCountDriver struct{} + +func (runnerSetCountDriver) Open(name string) (driver.Conn, error) { + conn, err := (&sqlite3.SQLiteDriver{}).Open(name) + if err != nil { + return nil, err + } + runnerSetCounterGlobal.mu.Lock() + counter := runnerSetCounterGlobal.counter + runnerSetCounterGlobal.mu.Unlock() + return &runnerSetCountConn{Conn: conn, counter: counter}, nil +} + +type runnerSetCountConn struct { + driver.Conn + counter *runnerSetQueryCounter +} + +func (c *runnerSetCountConn) QueryContext( + ctx context.Context, query string, args []driver.NamedValue, +) (driver.Rows, error) { + queryer, ok := c.Conn.(driver.QueryerContext) + if !ok { + return nil, driver.ErrSkip + } + if c.counter != nil && isRunnerSetQuery(query) { + c.counter.inc(query) + } + return queryer.QueryContext(ctx, query, args) +} + +func (c *runnerSetCountConn) ExecContext( + ctx context.Context, query string, args []driver.NamedValue, +) (driver.Result, error) { + execer, ok := c.Conn.(driver.ExecerContext) + if !ok { + return nil, driver.ErrSkip + } + return execer.ExecContext(ctx, query, args) +} + +func newCountingRunnerSetRepo(t *testing.T, counter *runnerSetQueryCounter) *sqlite.Repository { + t.Helper() + runnerSetCounterGlobal.mu.Lock() + runnerSetCounterGlobal.counter = counter + runnerSetCounterGlobal.mu.Unlock() + t.Cleanup(func() { + runnerSetCounterGlobal.mu.Lock() + runnerSetCounterGlobal.counter = nil + runnerSetCounterGlobal.mu.Unlock() + }) + + db, err := sqlx.Open("sqlite3_runner_set_count_test", ":memory:") + if err != nil { + t.Fatalf("open: %v", err) + } + db.SetMaxOpenConns(1) + t.Cleanup(func() { _ = db.Close() }) + + if _, _, err := settingsstore.Provide(db, db, nil); err != nil { + t.Fatalf("settings store init: %v", err) + } + repo, err := sqlite.NewWithDB(db, db, nil) + if err != nil { + t.Fatalf("new repo: %v", err) + } + createSearchTestSchema(t, repo) + return repo +} + +// TestListRunnerSetTaskIDs_IssuesExactlyOneQuery is the Review round 3 +// regression test (R3REV-04). The round-2 atomicity fix replaced a +// count-then-list pair with a single `COUNT(*) OVER()` query so the runner +// set can't change between the two reads; nothing pinned that shape, so a +// regression back to two queries would ship silently. +func TestListRunnerSetTaskIDs_IssuesExactlyOneQuery(t *testing.T) { + counter := &runnerSetQueryCounter{} + repo := newCountingRunnerSetRepo(t, counter) + ctx := context.Background() + + insertRunnerSetTask(t, repo, ctx, "task-a", "ws-1", "agent-1", "TODO", "2025-01-01 00:00:00") + insertRunnerSetTask(t, repo, ctx, "task-b", "ws-1", "agent-1", "TODO", "2025-01-02 00:00:00") + + ids, total, err := repo.ListRunnerSetTaskIDs(ctx, "agent-1", "ws-1", 500) + if err != nil { + t.Fatalf("ListRunnerSetTaskIDs: %v", err) + } + if total != 2 || len(ids) != 2 { + t.Fatalf("ids/total = %v/%d, want 2 ids/2", ids, total) + } + if got := counter.load(); got != 1 { + t.Fatalf("query count = %d, want 1 — ListRunnerSetTaskIDs must issue a single "+ + "query against tasks, not a count-then-list pair", got) + } + if !strings.Contains(strings.ToUpper(counter.lastText), "COUNT(*) OVER()") { + t.Fatalf("surviving query = %q, want it to contain COUNT(*) OVER() — the single "+ + "query permitted must still be the atomic window-function shape", counter.lastText) + } +} diff --git a/apps/backend/internal/office/repository/sqlite/runner_set_test.go b/apps/backend/internal/office/repository/sqlite/runner_set_test.go new file mode 100644 index 0000000000..0c22ccf835 --- /dev/null +++ b/apps/backend/internal/office/repository/sqlite/runner_set_test.go @@ -0,0 +1,129 @@ +package sqlite_test + +import ( + "context" + "testing" + + "github.com/kandev/kandev/internal/office/repository/sqlite" +) + +// insertRunnerSetTask inserts an actionable task assigned to agentID via a +// runner participant row, with an explicit updated_at so ordering tests are +// deterministic. +func insertRunnerSetTask( + t *testing.T, repo *sqlite.Repository, ctx context.Context, + id, wsID, agentID, state, updatedAt string, +) { + t.Helper() + stepID := "step-" + id + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO tasks (id, workspace_id, workflow_step_id, state, title, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?) + `, id, wsID, stepID, state, id, updatedAt, updatedAt); err != nil { + t.Fatalf("insert task %s: %v", id, err) + } + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO workflow_step_participants + (id, step_id, task_id, role, agent_profile_id, decision_required, position) + VALUES (?, ?, ?, 'runner', ?, 0, 0) + `, "p-"+id, stepID, id, agentID); err != nil { + t.Fatalf("insert runner participant for %s: %v", id, err) + } +} + +func TestListRunnerSetTaskIDs_OrdersByUpdatedAtThenIDDescending(t *testing.T) { + repo := newSearchTestRepo(t) + ctx := context.Background() + + insertRunnerSetTask(t, repo, ctx, "task-a", "ws-1", "agent-1", "TODO", "2025-01-01 00:00:00") + insertRunnerSetTask(t, repo, ctx, "task-b", "ws-1", "agent-1", "TODO", "2025-01-02 00:00:00") + // Same updated_at as task-b: tie-break on id descending. + insertRunnerSetTask(t, repo, ctx, "task-c", "ws-1", "agent-1", "IN_PROGRESS", "2025-01-02 00:00:00") + + ids, total, err := repo.ListRunnerSetTaskIDs(ctx, "agent-1", "ws-1", 500) + if err != nil { + t.Fatalf("ListRunnerSetTaskIDs: %v", err) + } + if total != 3 { + t.Fatalf("total = %d, want 3", total) + } + want := []string{"task-c", "task-b", "task-a"} + if len(ids) != len(want) { + t.Fatalf("ids = %v, want %v", ids, want) + } + for i, id := range want { + if ids[i] != id { + t.Fatalf("ids = %v, want %v", ids, want) + } + } +} + +func TestListRunnerSetTaskIDs_FiltersByWorkspace(t *testing.T) { + repo := newSearchTestRepo(t) + ctx := context.Background() + + insertRunnerSetTask(t, repo, ctx, "task-ws1", "ws-1", "agent-1", "TODO", "2025-01-01 00:00:00") + insertRunnerSetTask(t, repo, ctx, "task-ws2", "ws-2", "agent-1", "TODO", "2025-01-01 00:00:00") + + ids, total, err := repo.ListRunnerSetTaskIDs(ctx, "agent-1", "ws-1", 500) + if err != nil { + t.Fatalf("ListRunnerSetTaskIDs: %v", err) + } + if total != 1 || len(ids) != 1 || ids[0] != "task-ws1" { + t.Fatalf("ids/total = %v/%d, want [task-ws1]/1", ids, total) + } +} + +func TestListRunnerSetTaskIDs_ExcludesArchivedAndInactiveStates(t *testing.T) { + repo := newSearchTestRepo(t) + ctx := context.Background() + + insertRunnerSetTask(t, repo, ctx, "task-todo", "ws-1", "agent-1", "TODO", "2025-01-01 00:00:00") + insertRunnerSetTask(t, repo, ctx, "task-done", "ws-1", "agent-1", "DONE", "2025-01-01 00:00:00") + insertRunnerSetTask(t, repo, ctx, "task-archived", "ws-1", "agent-1", "TODO", "2025-01-01 00:00:00") + if _, err := repo.ExecRaw(ctx, `UPDATE tasks SET archived_at = ? WHERE id = 'task-archived'`, "2025-01-02 00:00:00"); err != nil { + t.Fatalf("archive task: %v", err) + } + + ids, total, err := repo.ListRunnerSetTaskIDs(ctx, "agent-1", "ws-1", 500) + if err != nil { + t.Fatalf("ListRunnerSetTaskIDs: %v", err) + } + if total != 1 || len(ids) != 1 || ids[0] != "task-todo" { + t.Fatalf("ids/total = %v/%d, want [task-todo]/1", ids, total) + } +} + +func TestListRunnerSetTaskIDs_ReportsTrueTotalWhenCapped(t *testing.T) { + repo := newSearchTestRepo(t) + ctx := context.Background() + + for i := 0; i < 5; i++ { + id := "task-" + string(rune('a'+i)) + insertRunnerSetTask(t, repo, ctx, id, "ws-1", "agent-1", "TODO", "2025-01-01 00:00:00") + } + + ids, total, err := repo.ListRunnerSetTaskIDs(ctx, "agent-1", "ws-1", 2) + if err != nil { + t.Fatalf("ListRunnerSetTaskIDs: %v", err) + } + if total != 5 { + t.Fatalf("total = %d, want 5", total) + } + if len(ids) != 2 { + t.Fatalf("ids = %v, want len 2", ids) + } +} + +func TestListRunnerSetTaskIDs_ReturnsEmptyForNoTasks(t *testing.T) { + repo := newSearchTestRepo(t) + ctx := context.Background() + + ids, total, err := repo.ListRunnerSetTaskIDs(ctx, "agent-none", "ws-1", 500) + if err != nil { + t.Fatalf("ListRunnerSetTaskIDs: %v", err) + } + if total != 0 || len(ids) != 0 { + t.Fatalf("ids/total = %v/%d, want empty/0", ids, total) + } +} diff --git a/apps/backend/internal/office/repository/sqlite/tasks.go b/apps/backend/internal/office/repository/sqlite/tasks.go index 09a0b53e46..37c24e8efe 100644 --- a/apps/backend/internal/office/repository/sqlite/tasks.go +++ b/apps/backend/internal/office/repository/sqlite/tasks.go @@ -418,7 +418,7 @@ type ListTasksFilteredResult struct { func (r *Repository) ListTasksFiltered( ctx context.Context, workspaceID string, opts ListTasksOptions, ) (*ListTasksFilteredResult, error) { - resolved, err := resolveListTasksOptions(opts) + resolved, err := resolveListTasksOptions(opts, r.ro.DriverName()) if err != nil { return nil, err } @@ -479,10 +479,11 @@ type resolvedListTasksOptions struct { limit int sortField TaskListSortField sortCol string + cursorCol string dir string } -func resolveListTasksOptions(opts ListTasksOptions) (resolvedListTasksOptions, error) { +func resolveListTasksOptions(opts ListTasksOptions, driver string) (resolvedListTasksOptions, error) { limit := opts.Limit if limit <= 0 || limit > 500 { limit = 100 @@ -495,11 +496,33 @@ func resolveListTasksOptions(opts ListTasksOptions) (resolvedListTasksOptions, e if !ok { return resolvedListTasksOptions{}, fmt.Errorf("invalid sort field: %s", sortField) } + cursorCol := "?" + if sortField == TaskSortUpdatedAt || sortField == TaskSortCreatedAt { + sortCol = dialect.NormalizedMicrosecond(driver, sortCol) + // Use the same canonical microsecond key for the bound cursor. The + // SQLite expression repeats its input internally, so bind the value + // once in a subquery and reference that alias instead of expanding + // one placeholder per expression occurrence. + if dialect.IsPostgres(driver) { + cursorCol = "CAST(? AS timestamp)" + } else { + cursorCol = fmt.Sprintf( + "(SELECT %s FROM (SELECT ? AS cursor_value) AS cursor_bind)", + dialect.NormalizedMicrosecond(driver, "cursor_value"), + ) + } + } dir := "DESC" if !opts.SortDesc { dir = "ASC" } - return resolvedListTasksOptions{limit: limit, sortField: sortField, sortCol: sortCol, dir: dir}, nil + return resolvedListTasksOptions{ + limit: limit, + sortField: sortField, + sortCol: sortCol, + cursorCol: cursorCol, + dir: dir, + }, nil } func buildTaskWhereClause( @@ -539,8 +562,9 @@ func buildTaskWhereClause( op = ">" } parts = append(parts, fmt.Sprintf( - "(%s %s ? OR (%s = ? AND t.id %s ?))", - resolved.sortCol, op, resolved.sortCol, op, + "(%s %s %s OR (%s = %s AND t.id %s ?))", + resolved.sortCol, op, resolved.cursorCol, + resolved.sortCol, resolved.cursorCol, op, )) args = append(args, opts.CursorValue, opts.CursorValue, opts.CursorID) } diff --git a/apps/backend/internal/office/repository/sqlite/tasks_filtered_test.go b/apps/backend/internal/office/repository/sqlite/tasks_filtered_test.go index edef812d17..0d523b1687 100644 --- a/apps/backend/internal/office/repository/sqlite/tasks_filtered_test.go +++ b/apps/backend/internal/office/repository/sqlite/tasks_filtered_test.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "testing" + "time" "github.com/kandev/kandev/internal/office/repository/sqlite" ) @@ -136,6 +137,68 @@ func TestListTasksFiltered_Pagination(t *testing.T) { } } +func TestListTasksFiltered_ProductionTimestampsPaginate(t *testing.T) { + for _, sortField := range []sqlite.TaskListSortField{ + sqlite.TaskSortUpdatedAt, + sqlite.TaskSortCreatedAt, + } { + for _, descending := range []bool{true, false} { + name := string(sortField) + if descending { + name += "-desc" + } else { + name += "-asc" + } + t.Run(name, func(t *testing.T) { + repo := newTestRepo(t) + ensureTasksTable(t, repo) + ctx := context.Background() + ts := time.Date(2026, time.April, 1, 12, 0, 0, 123456789, time.UTC) + for _, id := range []string{"task-a", "task-b", "task-c"} { + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO tasks + (id, workspace_id, title, state, priority, created_at, updated_at, is_ephemeral) + VALUES (?, ?, ?, 'TODO', 'medium', ?, ?, 0) + `, id, "ws-1", id, ts, ts); err != nil { + t.Fatalf("insert task %s: %v", id, err) + } + } + + page, err := repo.ListTasksFiltered(ctx, "ws-1", sqlite.ListTasksOptions{ + SortField: sortField, SortDesc: descending, Limit: 2, + }) + if err != nil { + t.Fatalf("list first page: %v", err) + } + if len(page.Tasks) != 2 || page.NextCursor == "" { + t.Fatalf("first page = %v, cursor=%q; want two rows and a cursor", taskIDs(page.Tasks), page.NextCursor) + } + + page2, err := repo.ListTasksFiltered(ctx, "ws-1", sqlite.ListTasksOptions{ + SortField: sortField, SortDesc: descending, Limit: 2, + CursorValue: page.NextCursor, CursorID: page.NextID, + }) + if err != nil { + t.Fatalf("list second page: %v", err) + } + if len(page2.Tasks) != 1 || page2.NextCursor != "" { + t.Fatalf("second page = %v, cursor=%q; want one final row", taskIDs(page2.Tasks), page2.NextCursor) + } + seen := map[string]bool{} + for _, task := range append(page.Tasks, page2.Tasks...) { + if seen[task.ID] { + t.Fatalf("task %s appeared more than once", task.ID) + } + seen[task.ID] = true + } + if len(seen) != 3 { + t.Fatalf("paged task IDs = %v, want all three tasks", seen) + } + }) + } + } +} + func TestListTasksFiltered_StatusAndPriorityFilters(t *testing.T) { repo := newTestRepo(t) ensureTasksTable(t, repo) @@ -382,6 +445,118 @@ func TestListTasksFiltered_ClampsLimit(t *testing.T) { } } +// AC-002.8: board-read excludes archived, ephemeral, automation-origin, and +// system-workflow tasks by default. The first three are provenance +// exclusions with no toggle; only the system-workflow task reappears when +// IncludeSystem is set. +func TestListTasksFiltered_ExcludesArchivedEphemeralAutomationAndSystemByDefault(t *testing.T) { + repo := newTestRepo(t) + ensureTasksTable(t, repo) + ctx := context.Background() + + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO workflows (id, workspace_id, workflow_template_id, name) + VALUES ('wf-system', 'ws-1', 'routine', 'Routine') + `); err != nil { + t.Fatalf("seed system workflow: %v", err) + } + + insertTaskRow(t, repo, "visible", "ws-1", "TODO", "medium", "2026-04-01T12:00:00Z") + + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO tasks (id, workspace_id, title, state, priority, created_at, updated_at, archived_at) + VALUES ('archived-1', 'ws-1', 'archived-1-title', 'TODO', 'medium', + '2026-04-02T12:00:00Z', '2026-04-02T12:00:00Z', '2026-04-02T13:00:00Z') + `); err != nil { + t.Fatalf("seed archived task: %v", err) + } + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO tasks (id, workspace_id, title, state, priority, created_at, updated_at, is_ephemeral) + VALUES ('ephemeral-1', 'ws-1', 'ephemeral-1-title', 'TODO', 'medium', + '2026-04-03T12:00:00Z', '2026-04-03T12:00:00Z', 1) + `); err != nil { + t.Fatalf("seed ephemeral task: %v", err) + } + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO tasks (id, workspace_id, title, state, priority, created_at, updated_at, origin) + VALUES ('automation-1', 'ws-1', 'automation-1-title', 'TODO', 'medium', + '2026-04-04T12:00:00Z', '2026-04-04T12:00:00Z', 'automation_run') + `); err != nil { + t.Fatalf("seed automation task: %v", err) + } + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO tasks (id, workspace_id, workflow_id, title, state, priority, created_at, updated_at) + VALUES ('system-1', 'ws-1', 'wf-system', 'system-1-title', 'TODO', 'medium', + '2026-04-05T12:00:00Z', '2026-04-05T12:00:00Z') + `); err != nil { + t.Fatalf("seed system task: %v", err) + } + + page, err := repo.ListTasksFiltered(ctx, "ws-1", sqlite.ListTasksOptions{SortDesc: true}) + if err != nil { + t.Fatalf("list default: %v", err) + } + if got := taskIDs(page.Tasks); len(got) != 1 || got[0] != "visible" { + t.Fatalf("default list = %v, want [visible]", got) + } + + page, err = repo.ListTasksFiltered(ctx, "ws-1", sqlite.ListTasksOptions{IncludeSystem: true, SortDesc: true}) + if err != nil { + t.Fatalf("list IncludeSystem: %v", err) + } + if got := taskIDs(page.Tasks); len(got) != 2 || got[0] != "system-1" || got[1] != "visible" { + t.Fatalf("IncludeSystem list = %v, want [system-1 visible]", got) + } +} + +// AC-002.1: when multiple rows tie on the sort column's value, the keyset +// cursor must tie-break on id so pagination partitions the set instead of +// skipping or repeating rows. Regression for a cursor predicate that +// compared only the sort value. +func TestListTasksFiltered_TiesBrokenByIDAcrossPages(t *testing.T) { + repo := newTestRepo(t) + ensureTasksTable(t, repo) + ctx := context.Background() + + const sharedTS = "2026-04-01T12:00:00Z" + ids := []string{"tie-a", "tie-b", "tie-c"} + for _, id := range ids { + insertTaskRow(t, repo, id, "ws-1", "TODO", "medium", sharedTS) + } + + seen := map[string]int{} + var order []string + cursorValue, cursorID := "", "" + for pages := 0; pages < 10; pages++ { + page, err := repo.ListTasksFiltered(ctx, "ws-1", sqlite.ListTasksOptions{ + Limit: 2, SortDesc: true, CursorValue: cursorValue, CursorID: cursorID, + }) + if err != nil { + t.Fatalf("page %d: %v", pages, err) + } + if len(page.Tasks) == 0 { + t.Fatalf("page %d returned no rows before exhausting %d ids (order so far=%v)", pages, len(ids), order) + } + for _, task := range page.Tasks { + seen[task.ID]++ + order = append(order, task.ID) + } + if page.NextCursor == "" { + break + } + cursorValue, cursorID = page.NextCursor, page.NextID + } + + if len(order) != len(ids) { + t.Fatalf("paged through %d rows total, want %d (got %v)", len(order), len(ids), order) + } + for _, id := range ids { + if seen[id] != 1 { + t.Errorf("id %s seen %d times across pages, want exactly 1 (order=%v)", id, seen[id], order) + } + } +} + func taskIDs(tasks []*sqlite.TaskRow) []string { out := make([]string, len(tasks)) for i, t := range tasks { diff --git a/apps/backend/internal/office/repository/sqlite/tasks_test.go b/apps/backend/internal/office/repository/sqlite/tasks_test.go index c76bf8ebf0..8bffe18159 100644 --- a/apps/backend/internal/office/repository/sqlite/tasks_test.go +++ b/apps/backend/internal/office/repository/sqlite/tasks_test.go @@ -17,6 +17,16 @@ import ( func newSearchTestRepo(t *testing.T) *sqlite.Repository { t.Helper() repo := newTestRepo(t) + createSearchTestSchema(t, repo) + return repo +} + +// createSearchTestSchema applies the same minimal search-test schema to a +// repo built on a caller-supplied *sqlx.DB (e.g. one wrapping a custom +// counting driver), so tests needing driver-level introspection don't need +// their own copy of this schema. +func createSearchTestSchema(t *testing.T, repo *sqlite.Repository) { + t.Helper() ctx := context.Background() if _, err := repo.ExecRaw(ctx, ` @@ -113,7 +123,6 @@ func newSearchTestRepo(t *testing.T) *sqlite.Repository { `); err != nil { t.Fatalf("create workflow_step_decisions table: %v", err) } - return repo } func insertTask(t *testing.T, repo *sqlite.Repository, ctx context.Context, id, wsID, title, desc, identifier string) { diff --git a/apps/backend/internal/office/routes.go b/apps/backend/internal/office/routes.go index 573152dc42..c7f7bf36de 100644 --- a/apps/backend/internal/office/routes.go +++ b/apps/backend/internal/office/routes.go @@ -45,6 +45,7 @@ func RegisterAllRoutes(router *gin.RouterGroup, svcs *Services, handoff *taskser svcs.Workspaces, newRuntimeDecisionRecorder(svcs.Dashboard), log, + svcs.Dashboard, )) skillsHandler := skills.NewHandler(svcs.Skills) diff --git a/apps/backend/internal/office/runtime/actions.go b/apps/backend/internal/office/runtime/actions.go index 6bd8175587..d98c1fabb5 100644 --- a/apps/backend/internal/office/runtime/actions.go +++ b/apps/backend/internal/office/runtime/actions.go @@ -391,15 +391,52 @@ func (a *Actions) authorizeTaskWorkspace(ctx context.Context, runCtx RunContext, return nil } +// canAnnotateTask is the annotation scope predicate: a task-bound run may +// annotate only its own (already-trimmed) task; a taskless run may annotate +// any task that resolves to its own workspace claim. The two checks never +// interact — a task-bound run never consults a workspace lookup, and a +// taskless run never falls back to its (absent) task id. A cross-workspace +// target and a nonexistent one refuse with the same sentinel so annotation +// cannot be used as an existence oracle; a failed lookup is returned as-is +// so an outage is not read as a refusal. The wildcard sentinel is never a +// real task id, so it is refused outright before either branch — otherwise +// a run whose own TaskID is the sentinel would self-match against it. +func (a *Actions) canAnnotateTask(ctx context.Context, runCtx RunContext, taskID string) error { + if taskID == WildcardTaskScope { + return ErrTaskOutOfScope + } + if strings.TrimSpace(runCtx.TaskID) != "" { + if taskID != runCtx.TaskID { + return ErrTaskOutOfScope + } + return nil + } + if strings.TrimSpace(runCtx.WorkspaceID) == "" { + return ErrWorkspaceOutOfScope + } + if a.deps.Tasks == nil { + return fmt.Errorf("%w: tasks", ErrRuntimeDependencyMissing) + } + workspaceID, err := a.deps.Tasks.GetTaskWorkspaceID(ctx, taskID) + if err != nil { + return err + } + if workspaceID == "" || workspaceID != runCtx.WorkspaceID { + return ErrTaskOutOfScope + } + return nil +} + // PostComment records an agent-authored task comment when the run is scoped for it. func (a *Actions) PostComment(ctx context.Context, runCtx RunContext, taskID, body string) error { if !runCtx.Capabilities.Allows(CapabilityPostComment) { return ErrCapabilityDenied } - if !runCtx.CanMutateTask(taskID) { - return ErrTaskOutOfScope + if strings.TrimSpace(body) == "" { + return ErrCommentBodyRequired } - if err := a.authorizeTaskWorkspace(ctx, runCtx, taskID); err != nil { + taskID = strings.TrimSpace(taskID) + if err := a.canAnnotateTask(ctx, runCtx, taskID); err != nil { return err } if a.deps.Comments == nil { diff --git a/apps/backend/internal/office/runtime/actions_annotation_test.go b/apps/backend/internal/office/runtime/actions_annotation_test.go new file mode 100644 index 0000000000..271d6fb4fa --- /dev/null +++ b/apps/backend/internal/office/runtime/actions_annotation_test.go @@ -0,0 +1,271 @@ +package runtime + +import ( + "context" + "errors" + "testing" + + "github.com/kandev/kandev/internal/office/shared" +) + +// annotationTaskCreator is a minimal TaskCreator fake for the annotation +// predicate: it can report a task's workspace and, unlike +// recordingTaskCreator, can distinguish "no such task" from "lookup +// failed". +type annotationTaskCreator struct { + workspaces map[string]string + lookupErr error + lookups []string +} + +func (c *annotationTaskCreator) GetTaskWorkspaceID(_ context.Context, taskID string) (string, error) { + c.lookups = append(c.lookups, taskID) + if c.lookupErr != nil { + return "", c.lookupErr + } + return c.workspaces[taskID], nil +} + +func (c *annotationTaskCreator) GetTaskProjectID(context.Context, string) (string, error) { + return "", nil +} +func (c *annotationTaskCreator) CreateOfficeTaskAsAgent( + context.Context, string, string, string, string, string, string, +) (string, error) { + return "", nil +} +func (c *annotationTaskCreator) CreateOfficeSubtaskAsAgent( + context.Context, string, string, string, string, string, +) (string, error) { + return "", nil +} + +func tasklessAnnotationRunCtx(workspaceID string, tasks *annotationTaskCreator) (RunContext, *Actions) { + runCtx, actions, _ := tasklessAnnotationRunCtxWithWriter(workspaceID, tasks) + return runCtx, actions +} + +func tasklessAnnotationRunCtxWithWriter( + workspaceID string, tasks *annotationTaskCreator, +) (RunContext, *Actions, *recordingCommentWriter) { + runCtx := RunContext{ + AgentID: "agent-1", + WorkspaceID: workspaceID, + TaskID: "", + RunID: "run-1", + Capabilities: Capabilities{ + CanPostComments: true, + }, + } + writer := &recordingCommentWriter{} + actions := NewActions(ActionDependencies{Comments: writer, Tasks: tasks}) + return runCtx, actions, writer +} + +func TestPostComment_TasklessRunAnnotatesTaskInWorkspace(t *testing.T) { + tasks := &annotationTaskCreator{workspaces: map[string]string{"task-x": "ws-1"}} + runCtx, actions := tasklessAnnotationRunCtx("ws-1", tasks) + + if err := actions.PostComment(context.Background(), runCtx, "task-x", "blocker found"); err != nil { + t.Fatalf("PostComment: %v", err) + } +} + +func TestPostComment_TasklessRunRefusesCrossWorkspaceTarget(t *testing.T) { + tasks := &annotationTaskCreator{workspaces: map[string]string{"task-x": "ws-2"}} + runCtx, actions, writer := tasklessAnnotationRunCtxWithWriter("ws-1", tasks) + + err := actions.PostComment(context.Background(), runCtx, "task-x", "blocker found") + if !errors.Is(err, ErrTaskOutOfScope) { + t.Fatalf("error = %v, want ErrTaskOutOfScope", err) + } + if len(writer.comments) != 0 { + t.Fatalf("expected no comment recorded on refusal, got %v", writer.comments) + } +} + +func TestPostComment_TasklessRunRefusesNonexistentTargetWithSameSentinelAsCrossWorkspace(t *testing.T) { + tasks := &annotationTaskCreator{workspaces: map[string]string{}} + runCtx, actions, writer := tasklessAnnotationRunCtxWithWriter("ws-1", tasks) + + err := actions.PostComment(context.Background(), runCtx, "no-such-task", "blocker found") + if !errors.Is(err, ErrTaskOutOfScope) { + t.Fatalf("error = %v, want ErrTaskOutOfScope (anti-oracle: same sentinel as cross-workspace)", err) + } + if len(writer.comments) != 0 { + t.Fatalf("expected no comment recorded on refusal, got %v", writer.comments) + } +} + +func TestPostComment_TasklessRunFailedLookupReturnsErrorNotRefusal(t *testing.T) { + lookupErr := errors.New("db unavailable") + tasks := &annotationTaskCreator{lookupErr: lookupErr} + runCtx, actions := tasklessAnnotationRunCtx("ws-1", tasks) + + err := actions.PostComment(context.Background(), runCtx, "task-x", "blocker found") + if !errors.Is(err, lookupErr) { + t.Fatalf("error = %v, want the raw lookup error surfaced (not a 403 refusal)", err) + } + if errors.Is(err, shared.ErrForbidden) { + t.Fatalf("a failed lookup must not be reported as a forbidden refusal: %v", err) + } +} + +func TestPostComment_TasklessRunEmptyWorkspaceClaimRefusesBeforeResolvingTarget(t *testing.T) { + tasks := &annotationTaskCreator{workspaces: map[string]string{"task-x": ""}} + runCtx, actions, writer := tasklessAnnotationRunCtxWithWriter("", tasks) + + err := actions.PostComment(context.Background(), runCtx, "task-x", "blocker found") + if !errors.Is(err, ErrWorkspaceOutOfScope) { + t.Fatalf("error = %v, want ErrWorkspaceOutOfScope", err) + } + if len(tasks.lookups) != 0 { + t.Fatalf("target should not be resolved when the run's own workspace claim is empty: %v", tasks.lookups) + } + if len(writer.comments) != 0 { + t.Fatalf("expected no comment recorded on refusal, got %v", writer.comments) + } +} + +func TestPostComment_TaskBoundRunUnaffectedByEmptyWorkspaceClaim(t *testing.T) { + // A task-bound run's annotation predicate never reads runCtx.WorkspaceID, + // so an empty claim (which would refuse a taskless run) has no effect. + comments := &recordingCommentWriter{} + actions := NewActions(ActionDependencies{Comments: comments}) + runCtx := RunContext{ + AgentID: "agent-1", + WorkspaceID: "", + TaskID: "task-1", + RunID: "run-1", + Capabilities: Capabilities{CanPostComments: true}, + } + + if err := actions.PostComment(context.Background(), runCtx, "task-1", "status update"); err != nil { + t.Fatalf("PostComment: %v", err) + } + if len(comments.comments) != 1 { + t.Fatalf("expected 1 comment, got %d", len(comments.comments)) + } +} + +func TestPostComment_TaskBoundRunRefusesAnyOtherTarget(t *testing.T) { + tasks := &annotationTaskCreator{workspaces: map[string]string{"task-2": "ws-1"}} + comments := &recordingCommentWriter{} + actions := NewActions(ActionDependencies{Comments: comments, Tasks: tasks}) + runCtx := RunContext{ + AgentID: "agent-1", + WorkspaceID: "ws-1", + TaskID: "task-1", + RunID: "run-1", + Capabilities: Capabilities{CanPostComments: true}, + } + + err := actions.PostComment(context.Background(), runCtx, "task-2", "hello") + if !errors.Is(err, ErrTaskOutOfScope) { + t.Fatalf("error = %v, want ErrTaskOutOfScope", err) + } + if len(tasks.lookups) != 0 { + t.Fatalf("task-bound annotation must not consult workspace lookups: %v", tasks.lookups) + } + if len(comments.comments) != 0 { + t.Fatalf("expected no comment recorded on refusal, got %v", comments.comments) + } +} + +func TestPostComment_EmptyBodyRefusedBeforeBranch(t *testing.T) { + tasks := &annotationTaskCreator{} + comments := &recordingCommentWriter{} + actions := NewActions(ActionDependencies{Comments: comments, Tasks: tasks}) + runCtx := RunContext{ + AgentID: "agent-1", + WorkspaceID: "ws-1", + RunID: "run-1", + Capabilities: Capabilities{CanPostComments: true}, + } + + err := actions.PostComment(context.Background(), runCtx, "task-x", " ") + if !errors.Is(err, ErrCommentBodyRequired) { + t.Fatalf("error = %v, want ErrCommentBodyRequired", err) + } + if len(tasks.lookups) != 0 { + t.Fatalf("body validation must precede target resolution: %v", tasks.lookups) + } + if len(comments.comments) != 0 { + t.Fatalf("expected no comment recorded on refusal, got %v", comments.comments) + } +} + +func TestPostComment_NoTargetAndNoBoundTaskRefuses(t *testing.T) { + tasks := &annotationTaskCreator{workspaces: map[string]string{}} + runCtx, actions, writer := tasklessAnnotationRunCtxWithWriter("ws-1", tasks) + + err := actions.PostComment(context.Background(), runCtx, "", "blocker found") + if !errors.Is(err, ErrTaskOutOfScope) { + t.Fatalf("error = %v, want ErrTaskOutOfScope", err) + } + if len(writer.comments) != 0 { + t.Fatalf("expected no comment recorded on refusal, got %v", writer.comments) + } +} + +func TestPostComment_TaskBoundRunPaddedTargetMatchingOwnTaskSucceeds(t *testing.T) { + comments := &recordingCommentWriter{} + actions := NewActions(ActionDependencies{Comments: comments}) + runCtx := RunContext{ + AgentID: "agent-1", + WorkspaceID: "ws-1", + TaskID: "task-1", + RunID: "run-1", + Capabilities: Capabilities{CanPostComments: true}, + } + + if err := actions.PostComment(context.Background(), runCtx, " task-1 ", "status update"); err != nil { + t.Fatalf("PostComment: %v", err) + } + if len(comments.comments) != 1 { + t.Fatalf("expected 1 comment, got %d", len(comments.comments)) + } + if comments.comments[0].TaskID != "task-1" { + t.Fatalf("TaskID = %q, want trimmed task-1", comments.comments[0].TaskID) + } +} + +func TestPostComment_WildcardBoundRunRefusesSelfMatchTarget(t *testing.T) { + // A run whose payload injected task_id="*" stays task-bound with + // RunContext.TaskID == WildcardTaskScope (context_builder.go#build). An + // omitted request task_id defaults to runCtx.TaskID (handler.go), so + // the resolved target here is the sentinel itself — the self-match must + // still refuse rather than treat "*" as an ordinary bound task id. + tasks := &annotationTaskCreator{} + comments := &recordingCommentWriter{} + actions := NewActions(ActionDependencies{Comments: comments, Tasks: tasks}) + runCtx := RunContext{ + AgentID: "agent-1", + WorkspaceID: "ws-1", + TaskID: WildcardTaskScope, + RunID: "run-1", + Capabilities: Capabilities{CanPostComments: true}, + } + + err := actions.PostComment(context.Background(), runCtx, WildcardTaskScope, "hello") + if !errors.Is(err, ErrTaskOutOfScope) { + t.Fatalf("error = %v, want ErrTaskOutOfScope — a wildcard-bound run must never self-match", err) + } + if len(comments.comments) != 0 { + t.Fatalf("expected no comment recorded on refusal, got %v", comments.comments) + } +} + +func TestPostComment_AnnotationIsNotIdempotent(t *testing.T) { + tasks := &annotationTaskCreator{workspaces: map[string]string{"task-x": "ws-1"}} + runCtx, actions, writer := tasklessAnnotationRunCtxWithWriter("ws-1", tasks) + + for i := 0; i < 2; i++ { + if err := actions.PostComment(context.Background(), runCtx, "task-x", "same body"); err != nil { + t.Fatalf("PostComment call %d: %v", i, err) + } + } + if len(writer.comments) != 2 { + t.Fatalf("expected 2 recorded comments (no dedup), got %d", len(writer.comments)) + } +} diff --git a/apps/backend/internal/office/runtime/actions_test.go b/apps/backend/internal/office/runtime/actions_test.go index 83a6c87dff..d95c711aec 100644 --- a/apps/backend/internal/office/runtime/actions_test.go +++ b/apps/backend/internal/office/runtime/actions_test.go @@ -125,6 +125,34 @@ func TestActionsCreateSubtaskDeniesWithoutCapability(t *testing.T) { } } +func TestActionsCreateSubtaskRefusesWildcardBoundRunDefaultParent(t *testing.T) { + // An omitted ParentTaskID defaults to runCtx.TaskID. A run whose payload + // injected task_id="*" stays task-bound with TaskID == WildcardTaskScope + // (context_builder.go#build), so the default here resolves to the + // sentinel itself and must be refused rather than treated as an + // ordinary bound parent task. + creator := &recordingTaskCreator{taskID: "created-task"} + actions := NewActions(ActionDependencies{Tasks: creator}) + runCtx := RunContext{ + AgentID: "agent-1", + WorkspaceID: "ws-1", + TaskID: WildcardTaskScope, + Capabilities: Capabilities{ + CanCreateSubtasks: true, + }, + } + + _, err := actions.CreateSubtask(context.Background(), runCtx, CreateSubtaskInput{ + Title: "child", + }) + if !errors.Is(err, ErrTaskOutOfScope) { + t.Fatalf("error = %v, want ErrTaskOutOfScope — a wildcard-bound run must not create a subtask under the sentinel", err) + } + if len(creator.calls) != 0 { + t.Fatal("task creator should not be called when the resolved parent is the wildcard sentinel") + } +} + func TestActionsCreateSubtaskPreservesCallerIdentity(t *testing.T) { creator := &recordingTaskCreator{ taskID: "created-task", diff --git a/apps/backend/internal/office/runtime/capabilities.go b/apps/backend/internal/office/runtime/capabilities.go index 3b3ec6425b..aa2f0f7999 100644 --- a/apps/backend/internal/office/runtime/capabilities.go +++ b/apps/backend/internal/office/runtime/capabilities.go @@ -1,6 +1,8 @@ package runtime import ( + "strings" + "github.com/kandev/kandev/internal/office/models" "github.com/kandev/kandev/internal/office/shared" ) @@ -25,6 +27,7 @@ const ( CapabilitySpawnAgentRun = "spawn_agent_run" CapabilityModifyAgents = "modify_agents" CapabilityDeleteSkills = "delete_skills" + CapabilityListTasks = "list_tasks" ) // AvailableActionRecordStepDecision identifies the advisory runtime decision @@ -47,6 +50,8 @@ func (c Capabilities) Allows(key string) bool { return c.CanCreateAgents case CapabilityListProjects: return c.CanListProjects + case CapabilityListTasks: + return c.CanListTasks case CapabilityCreateProject: return c.CanCreateProjects case CapabilityRequestApproval: @@ -68,10 +73,21 @@ func (c Capabilities) Allows(key string) bool { } } -// WithTaskScope returns a copy of the capabilities with the given task scope. +// WithTaskScope returns a copy of the capabilities with the given task +// scope, discarding empty, whitespace-only, and reserved-sentinel +// identifiers so the scope never contains an entry that can never match a +// real task id, and never grants the wildcard scope from a task identifier +// an untrusted source supplied. func (c Capabilities) WithTaskScope(taskIDs ...string) Capabilities { next := c - next.AllowedTaskIDs = append([]string(nil), taskIDs...) + filtered := make([]string, 0, len(taskIDs)) + for _, id := range taskIDs { + trimmed := strings.TrimSpace(id) + if trimmed != "" && trimmed != WildcardTaskScope { + filtered = append(filtered, trimmed) + } + } + next.AllowedTaskIDs = filtered return next } @@ -84,6 +100,7 @@ func (c Capabilities) AllowedKeys() []string { CapabilityCreateSubtask, CapabilityCreateAgent, CapabilityListProjects, + CapabilityListTasks, CapabilityCreateProject, CapabilityRequestApproval, CapabilityReadMemory, @@ -116,6 +133,7 @@ func FromAgent(agent *models.AgentInstance) Capabilities { CanCreateSubtasks: shared.HasPermission(perms, shared.PermCanCreateTasks), CanCreateAgents: shared.HasPermission(perms, shared.PermCanCreateAgents), CanListProjects: true, + CanListTasks: true, CanCreateProjects: shared.HasPermission(perms, shared.PermCanCreateProjects), CanRequestApproval: shared.HasPermission(perms, shared.PermCanApprove), CanReadMemory: true, diff --git a/apps/backend/internal/office/runtime/capabilities_test.go b/apps/backend/internal/office/runtime/capabilities_test.go index bbd8f35d9d..eb16f265dc 100644 --- a/apps/backend/internal/office/runtime/capabilities_test.go +++ b/apps/backend/internal/office/runtime/capabilities_test.go @@ -18,6 +18,41 @@ func TestDecisionToolIsNotRuntimeCapability(t *testing.T) { } } +func TestCapabilities_AllowsListTasks(t *testing.T) { + if (Capabilities{}).Allows(CapabilityListTasks) { + t.Fatal("Allows(list_tasks) = true for zero-value capabilities, want false") + } + if !(Capabilities{CanListTasks: true}).Allows(CapabilityListTasks) { + t.Fatal("Allows(list_tasks) = false with CanListTasks set, want true") + } +} + +func TestCapabilities_AllowsUnknownKeyDefaultsFalse(t *testing.T) { + if (Capabilities{ + CanPostComments: true, CanUpdateTaskStatus: true, CanCreateTasks: true, + CanCreateSubtasks: true, CanCreateAgents: true, CanListProjects: true, + CanListTasks: true, CanCreateProjects: true, CanRequestApproval: true, + CanReadMemory: true, CanWriteMemory: true, CanListSkills: true, + CanSpawnAgentRun: true, CanModifyAgents: true, CanDeleteSkills: true, + }).Allows("not_a_real_capability") { + t.Fatal("Allows(unknown key) = true, want false even with every other capability granted") + } +} + +func TestCapabilities_AllowedKeysIncludesListTasksInStableOrder(t *testing.T) { + caps := Capabilities{CanListProjects: true, CanListTasks: true, CanPostComments: true} + keys := caps.AllowedKeys() + want := []string{CapabilityPostComment, CapabilityListProjects, CapabilityListTasks} + if len(keys) != len(want) { + t.Fatalf("keys = %v, want %v", keys, want) + } + for i, k := range want { + if keys[i] != k { + t.Fatalf("keys = %v, want %v", keys, want) + } + } +} + func TestFromAgentNeverGrantsRecordStepDecision(t *testing.T) { ceo := &models.AgentInstance{ ID: "agent-ceo", @@ -29,3 +64,95 @@ func TestFromAgentNeverGrantsRecordStepDecision(t *testing.T) { t.Fatal("Allows must not authorize the decision tool") } } + +func TestCapabilities_AllowedKeysOmitsDisabledListTasks(t *testing.T) { + caps := Capabilities{CanListTasks: false, CanListProjects: true} + for _, k := range caps.AllowedKeys() { + if k == CapabilityListTasks { + t.Fatalf("AllowedKeys() = %v, want list_tasks omitted when CanListTasks is false", caps.AllowedKeys()) + } + } +} + +func TestFromAgent_GrantsListTasksForEveryRole(t *testing.T) { + roles := []models.AgentRole{ + models.AgentRoleCEO, models.AgentRoleWorker, models.AgentRoleSpecialist, + models.AgentRoleAssistant, models.AgentRoleSecurity, models.AgentRoleQA, models.AgentRoleDevOps, + } + for _, role := range roles { + agent := &models.AgentInstance{ID: "agent-1", WorkspaceID: "ws-1", Role: role} + caps := FromAgent(agent) + if !caps.CanListTasks { + t.Fatalf("role %v: CanListTasks = false, want true", role) + } + if !caps.Allows(CapabilityListTasks) { + t.Fatalf("role %v: Allows(list_tasks) = false, want true", role) + } + } +} + +func TestFromAgent_NilAgentGrantsNothing(t *testing.T) { + caps := FromAgent(nil) + if caps.CanListTasks || caps.Allows(CapabilityListTasks) { + t.Fatal("FromAgent(nil) granted list_tasks, want a zero-value Capabilities") + } +} + +func TestWithTaskScope_FiltersEmptyAndWhitespaceIDs(t *testing.T) { + caps := Capabilities{}.WithTaskScope("task-1", "", " ", "task-2") + want := []string{"task-1", "task-2"} + if len(caps.AllowedTaskIDs) != len(want) { + t.Fatalf("AllowedTaskIDs = %v, want %v", caps.AllowedTaskIDs, want) + } + for i, id := range want { + if caps.AllowedTaskIDs[i] != id { + t.Fatalf("AllowedTaskIDs = %v, want %v", caps.AllowedTaskIDs, want) + } + } +} + +func TestWithTaskScope_NoArgumentsYieldsEmptyNotWildcard(t *testing.T) { + caps := Capabilities{}.WithTaskScope() + if len(caps.AllowedTaskIDs) != 0 { + t.Fatalf("AllowedTaskIDs = %v, want empty", caps.AllowedTaskIDs) + } + for _, id := range caps.AllowedTaskIDs { + if id == WildcardTaskScope { + t.Fatal("WithTaskScope() with no args produced a wildcard scope") + } + } +} + +func TestWithTaskScope_AllWhitespaceArgumentsYieldEmptyScope(t *testing.T) { + caps := Capabilities{}.WithTaskScope("", " ", "\t") + if len(caps.AllowedTaskIDs) != 0 { + t.Fatalf("AllowedTaskIDs = %v, want empty", caps.AllowedTaskIDs) + } +} + +func TestWithTaskScope_TrimsSurvivingEntries(t *testing.T) { + caps := Capabilities{}.WithTaskScope(" task-1 ", "\ttask-2\t") + want := []string{"task-1", "task-2"} + if len(caps.AllowedTaskIDs) != len(want) { + t.Fatalf("AllowedTaskIDs = %v, want %v", caps.AllowedTaskIDs, want) + } + for i, id := range want { + if caps.AllowedTaskIDs[i] != id { + t.Fatalf( + "AllowedTaskIDs = %q, want %q — a surviving entry must be stored trimmed so it can still match the real task id", + caps.AllowedTaskIDs, want, + ) + } + } +} + +func TestWithTaskScope_RejectsWildcardSentinel(t *testing.T) { + caps := Capabilities{}.WithTaskScope(WildcardTaskScope, "task-1") + want := []string{"task-1"} + if len(caps.AllowedTaskIDs) != len(want) || caps.AllowedTaskIDs[0] != want[0] { + t.Fatalf( + "AllowedTaskIDs = %v, want %v — the reserved wildcard sentinel must never be assignable from external input", + caps.AllowedTaskIDs, want, + ) + } +} diff --git a/apps/backend/internal/office/runtime/context.go b/apps/backend/internal/office/runtime/context.go index e2046ac445..07a2706be2 100644 --- a/apps/backend/internal/office/runtime/context.go +++ b/apps/backend/internal/office/runtime/context.go @@ -18,9 +18,24 @@ type Capabilities struct { CanSpawnAgentRun bool `json:"spawn_agent_run"` CanModifyAgents bool `json:"modify_agents"` CanDeleteSkills bool `json:"delete_skills"` + CanListTasks bool `json:"list_tasks"` AllowedTaskIDs []string `json:"allowed_task_ids"` + // TaskScopeSource marks which source produced AllowedTaskIDs — "payload" + // or "runner_set" (both final), or "unavailable" (provisional). Empty for + // a snapshot persisted before this marker existed. See + // docs/specs/office/system-design/taskless-coordinator-authority-01.md#snapshot-semantics. + TaskScopeSource string `json:"task_scope_source,omitempty"` } +// Task scope source markers. "payload" and "runner_set" are final: a build +// reads a final marker back verbatim rather than re-deriving the scope. +// "unavailable" is provisional and is retried on the next build. +const ( + TaskScopeSourcePayload = "payload" + TaskScopeSourceRunnerSet = "runner_set" + TaskScopeSourceUnavailable = "unavailable" +) + // RunContext is the identity, runtime-permission, and advertised-action // envelope for one agent execution. AvailableActions only describes tools the // prompt can advertise. The backend performs live authorization when a tool is @@ -36,9 +51,13 @@ type RunContext struct { AvailableActions []string `json:"available_actions,omitempty"` } -// CanMutateTask reports whether the run may mutate the given task. +// CanMutateTask reports whether the run may mutate the given task. The +// wildcard sentinel is never a real task id, so a target of exactly +// WildcardTaskScope is refused outright — otherwise a run whose own TaskID +// is the sentinel (a payload that injected task_id="*" stays task-bound, +// see context_builder.go#build) would self-match against it. func (c RunContext) CanMutateTask(taskID string) bool { - if taskID == "" { + if taskID == "" || taskID == WildcardTaskScope { return false } if taskID == c.TaskID { diff --git a/apps/backend/internal/office/runtime/context_builder.go b/apps/backend/internal/office/runtime/context_builder.go index f151a0da05..208797fe79 100644 --- a/apps/backend/internal/office/runtime/context_builder.go +++ b/apps/backend/internal/office/runtime/context_builder.go @@ -4,11 +4,34 @@ import ( "context" "encoding/json" "fmt" + "strings" "github.com/kandev/kandev/internal/office/models" "github.com/kandev/kandev/internal/office/shared" ) +// scopeRunnerSetCap bounds a taskless run's materialized task scope. +const scopeRunnerSetCap = 500 + +// maxScopeSwapAttempts bounds the derive-and-swap retry loop in +// persistWithCAS at three total compare-and-swap attempts (the first plus +// two retries), after which BuildAndPersist returns an error and the +// caller's own retry (a later launch attempt) starts over. +const maxScopeSwapAttempts = 3 + +// Scope-derivation run event payload keys, shared by appendScopeEvent's two +// event kinds. +const ( + scopeEventAgent = "agent_id" + scopeEventRunKey = "run_id" + scopeEventError = "error" +) + +// errRunnerSetUnderivable marks a scope that could not even attempt the +// runner-set query (no lister configured, or an empty run workspace) as +// distinct from one whose query failed. +var errRunnerSetUnderivable = fmt.Errorf("runner set unavailable: no reader configured or run workspace is empty") + // RunSnapshotStore persists runtime metadata on a run row. type RunSnapshotStore interface { UpdateRunRuntimeSnapshot( @@ -18,6 +41,37 @@ type RunSnapshotStore interface { inputSnapshot string, sessionID string, ) error + // UpdateRunRuntimeSnapshotCAS is the compare-and-swap sibling used to + // decide first-write-wins when two processors build context for the + // same run concurrently. prevCapabilities is the exact capabilities + // string Build read when it checked the run's task_scope_source marker. + UpdateRunRuntimeSnapshotCAS( + ctx context.Context, + id string, + prevCapabilities string, + capabilities string, + inputSnapshot string, + sessionID string, + ) (bool, error) + // GetRunByID re-reads a run so the losing side of a CAS race can adopt + // the winner's persisted scope. + GetRunByID(ctx context.Context, id string) (*models.Run, error) +} + +// RunnerTaskLister resolves a taskless run's task scope: the ordered, +// capped ids of tasks the agent is already responsible for in one +// workspace (the "runner set"), plus the true total before capping so +// truncation is detectable without a second query. A nil lister is not an +// empty runner set: the two report through different derivation outcomes. +type RunnerTaskLister interface { + ListRunnerSetTaskIDs(ctx context.Context, agentID, workspaceID string, capAt int) ([]string, int, error) +} + +// ScopeEventAppender records a scope-derivation run event +// (runtime.scope_truncated / runtime.scope_unavailable). A nil appender +// skips the event and never fails the build. +type ScopeEventAppender interface { + AppendRunEvent(ctx context.Context, runID, eventType, level string, payload map[string]interface{}) } // DecisionSeatResolver reports whether an agent currently holds a decision @@ -31,30 +85,58 @@ type DecisionSeatResolver interface { // ContextBuilder builds the runtime context for a claimed run. type ContextBuilder struct { - Agents shared.AgentReader - Runs RunSnapshotStore - Seats DecisionSeatResolver + Agents shared.AgentReader + Runs RunSnapshotStore + Seats DecisionSeatResolver + RunnerLister RunnerTaskLister + ScopeEvents ScopeEventAppender +} + +// scopeDerivation carries the internal detail behind a build's task scope: +// the ids, the true total, whether the cap truncated them, the query error +// (if any), the resulting marker, and whether the scope was reused +// verbatim from a persisted final marker rather than freshly derived. +type scopeDerivation struct { + taskIDs []string + total int + truncated bool + err error + marker string + reused bool } // Build resolves the agent identity and capabilities for a run. func (b *ContextBuilder) Build(ctx context.Context, run *models.Run) (RunContext, error) { + runCtx, _, err := b.build(ctx, run) + return runCtx, err +} + +// build is Build's unexported counterpart: it additionally returns the +// scopeDerivation so BuildAndPersist can choose the right event and CAS +// path after the persistence swap decides which build actually won. +func (b *ContextBuilder) build(ctx context.Context, run *models.Run) (RunContext, scopeDerivation, error) { if run == nil { - return RunContext{}, fmt.Errorf("run is required") + return RunContext{}, scopeDerivation{}, fmt.Errorf("run is required") } if b.Agents == nil { - return RunContext{}, fmt.Errorf("%w: agents", ErrRuntimeDependencyMissing) + return RunContext{}, scopeDerivation{}, fmt.Errorf("%w: agents", ErrRuntimeDependencyMissing) } agent, err := b.Agents.GetAgentInstance(ctx, run.AgentProfileID) if err != nil { - return RunContext{}, fmt.Errorf("resolve runtime agent: %w", err) + return RunContext{}, scopeDerivation{}, fmt.Errorf("resolve runtime agent: %w", err) } payload := parsePayload(run.Payload) - taskID := payload["task_id"] + // A wildcard payload task_id stays task-bound rather than becoming + // taskless. WithTaskScope strips the sentinel from AllowedTaskIDs, and + // CanMutateTask/canAnnotateTask refuse the sentinel as a target outright, + // so the run ends up with no mutation or annotation authority at all. + taskID := strings.TrimSpace(payload["task_id"]) sessionID := firstNonEmpty(run.SessionID, payload["session_id"]) - caps := FromAgent(agent).WithTaskScope(taskID) + + caps, derivation := b.deriveScope(ctx, run, agent, taskID) availableActions, err := b.resolveAvailableActions(ctx, taskID, agent.ID) if err != nil { - return RunContext{}, err + return RunContext{}, scopeDerivation{}, err } runCtx := RunContext{ WorkspaceID: agent.WorkspaceID, @@ -66,7 +148,7 @@ func (b *ContextBuilder) Build(ctx context.Context, run *models.Run) (RunContext Capabilities: caps, AvailableActions: availableActions, } - return runCtx, nil + return runCtx, derivation, nil } // resolveAvailableActions reports advisory tools for the run prompt. A @@ -87,30 +169,204 @@ func (b *ContextBuilder) resolveAvailableActions(ctx context.Context, taskID, ag return []string{AvailableActionRecordStepDecision}, nil } -// BuildAndPersist builds context and stores its serialized snapshot on the run. +// deriveScope decides a run's task scope: a task-bound run's is always its +// own trimmed task id (no reuse, no workspace filter); a taskless run's is +// reused verbatim from a final persisted marker or, failing that, freshly +// derived from the runner set. +func (b *ContextBuilder) deriveScope( + ctx context.Context, run *models.Run, agent *models.AgentInstance, taskID string, +) (Capabilities, scopeDerivation) { + caps := FromAgent(agent) + if taskID != "" { + derivation := scopeDerivation{taskIDs: []string{taskID}, marker: TaskScopeSourcePayload} + return withScope(caps, derivation), derivation + } + if persisted, ok := reusePersistedTaskScope(run); ok { + derivation := scopeDerivation{ + taskIDs: persisted.AllowedTaskIDs, + marker: persisted.TaskScopeSource, + reused: true, + } + return withScope(caps, derivation), derivation + } + derivation := b.deriveRunnerSet(ctx, agent.ID, agent.WorkspaceID) + return withScope(caps, derivation), derivation +} + +// deriveRunnerSet issues the runner-set query for a taskless run. Failure +// is closed: no lister, an empty workspace, or a query error each yield an +// empty scope with the provisional unavailable marker rather than an +// empty final one, so the next build retries instead of freezing the gap. +func (b *ContextBuilder) deriveRunnerSet(ctx context.Context, agentID, workspaceID string) scopeDerivation { + if b.RunnerLister == nil || strings.TrimSpace(workspaceID) == "" { + return scopeDerivation{marker: TaskScopeSourceUnavailable, err: errRunnerSetUnderivable} + } + ids, total, err := b.RunnerLister.ListRunnerSetTaskIDs(ctx, agentID, workspaceID, scopeRunnerSetCap) + if err != nil { + return scopeDerivation{marker: TaskScopeSourceUnavailable, err: err} + } + return scopeDerivation{ + taskIDs: ids, + total: total, + truncated: total > len(ids), + marker: TaskScopeSourceRunnerSet, + } +} + +// reusePersistedTaskScope reads a run's persisted capabilities and reports +// whether they carry a final task_scope_source marker. An absent, +// provisional, unrecognized, or unparseable snapshot all report false, so +// the caller derives a fresh scope instead of reusing a stale or partial one. +func reusePersistedTaskScope(run *models.Run) (Capabilities, bool) { + if run == nil || run.Capabilities == "" { + return Capabilities{}, false + } + var persisted Capabilities + if err := json.Unmarshal([]byte(run.Capabilities), &persisted); err != nil { + return Capabilities{}, false + } + switch persisted.TaskScopeSource { + case TaskScopeSourcePayload, TaskScopeSourceRunnerSet: + return persisted, true + default: + return Capabilities{}, false + } +} + +func withScope(caps Capabilities, derivation scopeDerivation) Capabilities { + next := caps.WithTaskScope(derivation.taskIDs...) + next.TaskScopeSource = derivation.marker + return next +} + +// BuildAndPersist builds context and stores its serialized snapshot on the +// run. It owns the ScopeEventAppender call site outright: Build derives +// the scope and never appends, so a build that loses the CAS race, has no +// appender, or persists nothing (no Runs store) appends no scope event and +// still returns a context. func (b *ContextBuilder) BuildAndPersist(ctx context.Context, run *models.Run) (RunContext, error) { - runCtx, err := b.Build(ctx, run) + runCtx, derivation, err := b.build(ctx, run) if err != nil { return RunContext{}, err } + prevCapabilities := run.Capabilities if b.Runs == nil { return runCtx, nil } - caps, err := MarshalCapabilities(runCtx.Capabilities) - if err != nil { - return RunContext{}, err + if derivation.reused || derivation.marker == TaskScopeSourcePayload { + if err := b.persistUnconditional(ctx, run, runCtx); err != nil { + return RunContext{}, err + } + return runCtx, nil } - input, err := MarshalRunContext(runCtx) + return b.persistWithCAS(ctx, run, runCtx, derivation, prevCapabilities) +} + +// persistUnconditional performs the ordinary unconditional snapshot write +// used whenever this build's task scope needs no concurrency guard: a +// task-bound run's scope is a pure function of its payload, and a reused +// final scope is, by construction, already the scope every concurrent +// build would agree on. +func (b *ContextBuilder) persistUnconditional(ctx context.Context, run *models.Run, runCtx RunContext) error { + caps, input, err := marshalSnapshot(runCtx) if err != nil { - return RunContext{}, err + return err } if err := b.Runs.UpdateRunRuntimeSnapshot(ctx, run.ID, caps, input, runCtx.SessionID); err != nil { - return RunContext{}, fmt.Errorf("persist runtime snapshot: %w", err) + return fmt.Errorf("persist runtime snapshot: %w", err) } run.Capabilities = caps run.InputSnapshot = input run.SessionID = runCtx.SessionID - return runCtx, nil + return nil +} + +// persistWithCAS guards a freshly-derived taskless scope (runner_set or +// unavailable) with a compare-and-swap so that when two processors build +// context for one run concurrently, the first persisted final marker wins. +// The loser re-reads the run; if it now carries a final marker, the loser +// adopts that scope verbatim and emits no scope event; otherwise it retries +// the derive-and-swap, up to maxScopeSwapAttempts total attempts. +func (b *ContextBuilder) persistWithCAS( + ctx context.Context, + run *models.Run, + runCtx RunContext, + derivation scopeDerivation, + prevCapabilities string, +) (RunContext, error) { + for attempt := 1; ; attempt++ { + caps, input, err := marshalSnapshot(runCtx) + if err != nil { + return RunContext{}, err + } + won, err := b.Runs.UpdateRunRuntimeSnapshotCAS(ctx, run.ID, prevCapabilities, caps, input, runCtx.SessionID) + if err != nil { + return RunContext{}, fmt.Errorf("persist runtime snapshot: %w", err) + } + if won { + run.Capabilities = caps + run.InputSnapshot = input + run.SessionID = runCtx.SessionID + b.appendScopeEvent(ctx, runCtx, derivation) + return runCtx, nil + } + + current, err := b.Runs.GetRunByID(ctx, run.ID) + if err != nil { + return RunContext{}, fmt.Errorf("re-read run after lost scope race: %w", err) + } + if _, ok := reusePersistedTaskScope(current); ok { + if adopted, ok := unmarshalRunContext(current.InputSnapshot); ok { + run.Capabilities = current.Capabilities + run.InputSnapshot = current.InputSnapshot + run.SessionID = current.SessionID + return adopted, nil + } + } + if attempt >= maxScopeSwapAttempts { + return RunContext{}, fmt.Errorf("scope snapshot race: exceeded %d attempts", maxScopeSwapAttempts) + } + prevCapabilities = current.Capabilities + derivation = b.deriveRunnerSet(ctx, runCtx.AgentID, runCtx.WorkspaceID) + runCtx.Capabilities = withScope(runCtx.Capabilities, derivation) + } +} + +func (b *ContextBuilder) appendScopeEvent(ctx context.Context, runCtx RunContext, derivation scopeDerivation) { + if b.ScopeEvents == nil { + return + } + switch { + case derivation.marker == TaskScopeSourceRunnerSet && derivation.truncated: + b.ScopeEvents.AppendRunEvent(ctx, runCtx.RunID, "runtime.scope_truncated", "warn", map[string]interface{}{ + "cap": scopeRunnerSetCap, + "total": derivation.total, + scopeEventAgent: runCtx.AgentID, + scopeEventRunKey: runCtx.RunID, + }) + case derivation.marker == TaskScopeSourceUnavailable: + errMsg := "" + if derivation.err != nil { + errMsg = derivation.err.Error() + } + b.ScopeEvents.AppendRunEvent(ctx, runCtx.RunID, "runtime.scope_unavailable", "warn", map[string]interface{}{ + scopeEventError: errMsg, + scopeEventAgent: runCtx.AgentID, + scopeEventRunKey: runCtx.RunID, + }) + } +} + +func marshalSnapshot(runCtx RunContext) (capabilities string, inputSnapshot string, err error) { + caps, err := MarshalCapabilities(runCtx.Capabilities) + if err != nil { + return "", "", err + } + input, err := MarshalRunContext(runCtx) + if err != nil { + return "", "", err + } + return caps, input, nil } // MarshalCapabilities serializes capabilities for run snapshots and JWT claims. @@ -131,6 +387,24 @@ func MarshalRunContext(runCtx RunContext) (string, error) { return string(body), nil } +// unmarshalRunContext parses a persisted input_snapshot back into a +// RunContext. The losing side of a scope CAS race uses this to adopt the +// winner's complete snapshot verbatim, rather than re-marshaling its own +// build's RunContext with only the task scope patched in — the latter +// would silently overwrite winner-owned fields (capabilities, session id) +// with this build's own values if they diverged from the winner's, for +// example when agent permissions changed between the two builds' reads. +func unmarshalRunContext(inputSnapshot string) (RunContext, bool) { + var runCtx RunContext + if inputSnapshot == "" { + return RunContext{}, false + } + if err := json.Unmarshal([]byte(inputSnapshot), &runCtx); err != nil { + return RunContext{}, false + } + return runCtx, true +} + func parsePayload(payload string) map[string]string { raw := map[string]any{} if payload != "" { diff --git a/apps/backend/internal/office/runtime/context_builder_test.go b/apps/backend/internal/office/runtime/context_builder_test.go index e9d588e4f8..58178eef1b 100644 --- a/apps/backend/internal/office/runtime/context_builder_test.go +++ b/apps/backend/internal/office/runtime/context_builder_test.go @@ -74,7 +74,12 @@ func (r *recordingAgentReader) ListAgentInstancesByIDs( } type recordingRunSnapshotStore struct { - calls []snapshotCall + calls []snapshotCall + casCalls []snapshotCall + runs map[string]*models.Run + casWins bool + casErr error + getErr error } type snapshotCall struct { @@ -82,6 +87,10 @@ type snapshotCall struct { Capabilities string InputSnapshot string SessionID string + // PrevCapabilities is recorded only on a CAS call — it is the value the + // compare-and-swap guarantee rests on, so an assertion on it can tell a + // correctly-fed CAS from one seeded with the wrong prior value. + PrevCapabilities string } func (s *recordingRunSnapshotStore) UpdateRunRuntimeSnapshot( @@ -245,3 +254,110 @@ func TestContextBuilderPersistsSeatActionAsAdvisoryMetadata(t *testing.T) { t.Fatalf("record_step_decision must not be serialized as a runtime capability: %s", store.calls[0].Capabilities) } } + +// TestContextBuilderLostCASRaceAdoptsWinnerSnapshotVerbatim proves a build +// that loses the scope CAS race adopts the winner's exact persisted +// input_snapshot instead of re-marshaling its own RunContext with only the +// task scope patched in. Before this fix, the loser's own (possibly +// different, e.g. after a concurrent agent permission change) capabilities +// and session id would silently overwrite the winner's already-persisted +// values via a second, unguarded write. +func TestContextBuilderLostCASRaceAdoptsWinnerSnapshotVerbatim(t *testing.T) { + winnerCtx := RunContext{ + WorkspaceID: "ws-1", + AgentID: "agent-1", + RunID: "run-1", + SessionID: "winner-session", + Capabilities: Capabilities{ + CanCreateTasks: true, + AllowedTaskIDs: []string{"task-9"}, + TaskScopeSource: TaskScopeSourceRunnerSet, + }, + } + winnerCaps, err := MarshalCapabilities(winnerCtx.Capabilities) + if err != nil { + t.Fatalf("marshal winner capabilities: %v", err) + } + winnerInput, err := MarshalRunContext(winnerCtx) + if err != nil { + t.Fatalf("marshal winner run context: %v", err) + } + + store := &recordingRunSnapshotStore{ + casWins: false, + runs: map[string]*models.Run{ + "run-1": { + ID: "run-1", + Capabilities: winnerCaps, + InputSnapshot: winnerInput, + SessionID: winnerCtx.SessionID, + }, + }, + } + builder := ContextBuilder{ + Agents: &recordingAgentReader{ + // This build's own agent read disagrees with the winner's + // snapshot (CanCreateTasks=false here vs. true above), modeling + // a concurrent permission change between the two builds. + agent: &models.AgentInstance{ID: "agent-1", WorkspaceID: "ws-1", Role: models.AgentRoleWorker}, + }, + Runs: store, + } + run := &models.Run{ID: "run-1", AgentProfileID: "agent-1", Reason: "heartbeat", Payload: "{}"} + + runCtx, err := builder.BuildAndPersist(context.Background(), run) + if err != nil { + t.Fatalf("BuildAndPersist: %v", err) + } + + if runCtx.SessionID != winnerCtx.SessionID { + t.Fatalf("session id = %q, want winner's %q", runCtx.SessionID, winnerCtx.SessionID) + } + if !runCtx.Capabilities.CanCreateTasks { + t.Fatal("expected winner's CanCreateTasks=true to survive, not this build's own false") + } + if len(runCtx.Capabilities.AllowedTaskIDs) != 1 || runCtx.Capabilities.AllowedTaskIDs[0] != "task-9" { + t.Fatalf("unexpected allowed task ids: %v", runCtx.Capabilities.AllowedTaskIDs) + } + if len(store.calls) != 0 { + t.Fatalf("expected no additional snapshot write after adopting winner's snapshot, got %d", len(store.calls)) + } + if run.Capabilities != winnerCaps || run.InputSnapshot != winnerInput || run.SessionID != winnerCtx.SessionID { + t.Fatal("expected run's in-memory fields to mirror the winner's persisted snapshot") + } +} + +func (s *recordingRunSnapshotStore) UpdateRunRuntimeSnapshotCAS( + _ context.Context, + id string, + prevCapabilities string, + capabilities string, + inputSnapshot string, + sessionID string, +) (bool, error) { + s.casCalls = append(s.casCalls, snapshotCall{ + RunID: id, + Capabilities: capabilities, + InputSnapshot: inputSnapshot, + SessionID: sessionID, + PrevCapabilities: prevCapabilities, + }) + if s.casErr != nil { + return false, s.casErr + } + win := s.casWins + if win { + s.calls = append(s.calls, s.casCalls[len(s.casCalls)-1]) + } + return win, nil +} + +func (s *recordingRunSnapshotStore) GetRunByID(_ context.Context, id string) (*models.Run, error) { + if s.getErr != nil { + return nil, s.getErr + } + if run, ok := s.runs[id]; ok { + return run, nil + } + return &models.Run{ID: id}, nil +} diff --git a/apps/backend/internal/office/runtime/context_test.go b/apps/backend/internal/office/runtime/context_test.go new file mode 100644 index 0000000000..3aa1611d6b --- /dev/null +++ b/apps/backend/internal/office/runtime/context_test.go @@ -0,0 +1,22 @@ +package runtime + +import "testing" + +// TestRunContext_CanMutateTask_RefusesWildcardSentinelTarget covers a run +// whose own TaskID is the wildcard sentinel (a payload injecting +// task_id="*" stays task-bound per WithTaskScope's fail-closed narrowing, +// see context_builder.go#build). The sentinel must never satisfy the +// self-match check, since a caller can trivially reach that target by +// omitting an explicit task_id and letting it default to runCtx.TaskID. +func TestRunContext_CanMutateTask_RefusesWildcardSentinelTarget(t *testing.T) { + ctx := RunContext{ + TaskID: WildcardTaskScope, + Capabilities: Capabilities{ + CanUpdateTaskStatus: true, + }, + } + + if ctx.CanMutateTask(WildcardTaskScope) { + t.Fatal("a run whose own TaskID is the wildcard sentinel must not gain authority over a target literally named \"*\"") + } +} diff --git a/apps/backend/internal/office/runtime/errors.go b/apps/backend/internal/office/runtime/errors.go index d08f4c3823..56049d9765 100644 --- a/apps/backend/internal/office/runtime/errors.go +++ b/apps/backend/internal/office/runtime/errors.go @@ -26,4 +26,10 @@ var ( // office_run_dedup_keyless_total expvar maps, which never evict entries; // an unbounded value lets a caller grow those maps without limit. ErrReasonTooLong = fmt.Errorf("reason exceeds max length of %d characters", maxSpawnAgentRunReasonLength) + // ErrInvalidListParams is returned when a board-read query parameter + // fails validation. + ErrInvalidListParams = fmt.Errorf("invalid list parameters") + // ErrCommentBodyRequired is returned when a comment body is empty or + // whitespace-only. + ErrCommentBodyRequired = fmt.Errorf("comment body is required") ) diff --git a/apps/backend/internal/office/runtime/handler.go b/apps/backend/internal/office/runtime/handler.go index 2d779c4026..6f97a6fb3e 100644 --- a/apps/backend/internal/office/runtime/handler.go +++ b/apps/backend/internal/office/runtime/handler.go @@ -27,6 +27,7 @@ type Handler struct { runEvents RunEventAppender decisions DecisionRecorder logger *commonlogger.Logger + taskLister TaskFilteredLister } // RunEventAppender records runtime behavior against a run. @@ -42,6 +43,7 @@ func NewHandler( runEvents RunEventAppender, decisions DecisionRecorder, log *commonlogger.Logger, + taskLister TaskFilteredLister, ) *Handler { if log == nil { log = commonlogger.Default() @@ -53,6 +55,7 @@ func NewHandler( runEvents: runEvents, decisions: decisions, logger: log, + taskLister: taskLister, } } @@ -62,6 +65,7 @@ func RegisterRoutes(group *gin.RouterGroup, h *Handler) { group.POST("/runtime/task/decision", h.recordAgentDecision) group.POST("/runtime/tasks/:id/status", h.updateTaskStatus) group.POST("/runtime/tasks/:id/subtasks", h.createSubtask) + group.GET("/runtime/tasks", h.listTasks) group.POST("/runtime/tasks", h.createTask) group.POST("/runtime/agents", h.createAgent) group.GET("/runtime/projects", h.listProjects) @@ -177,7 +181,7 @@ func (h *Handler) postComment(c *gin.Context) { if !bindJSON(c, &req) { return } - taskID := firstNonEmpty(req.TaskID, runCtx.TaskID) + taskID := strings.TrimSpace(firstNonEmpty(req.TaskID, runCtx.TaskID)) if err := h.actions.PostComment(c.Request.Context(), runCtx, taskID, req.Body); err != nil { h.respondRuntimeError(c, runCtx, "post_comment", "task", taskID, err) return @@ -478,7 +482,9 @@ func (h *Handler) respondRuntimeError( targetID string, err error, ) { - if errors.Is(err, errTaskTitleRequired) || errors.Is(err, ErrProjectRequired) || errors.Is(err, ErrReasonTooLong) { + if errors.Is(err, errTaskTitleRequired) || errors.Is(err, ErrProjectRequired) || + errors.Is(err, ErrReasonTooLong) || errors.Is(err, ErrInvalidListParams) || + errors.Is(err, ErrCommentBodyRequired) { h.appendDeniedRunEvent(c.Request.Context(), runCtx, action, targetType, targetID, err) c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return diff --git a/apps/backend/internal/office/runtime/handler_taskless_annotation_test.go b/apps/backend/internal/office/runtime/handler_taskless_annotation_test.go new file mode 100644 index 0000000000..c740293fb7 --- /dev/null +++ b/apps/backend/internal/office/runtime/handler_taskless_annotation_test.go @@ -0,0 +1,133 @@ +package runtime + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "github.com/gin-gonic/gin" + "github.com/jmoiron/sqlx" + _ "github.com/mattn/go-sqlite3" + + settingsstore "github.com/kandev/kandev/internal/agent/settings/store" + "github.com/kandev/kandev/internal/common/logger" + "github.com/kandev/kandev/internal/office/agents" + "github.com/kandev/kandev/internal/office/models" + "github.com/kandev/kandev/internal/office/repository/sqlite" +) + +// tasklessAnnotationHandlerHarness wires the runtime handler around a +// taskless run (empty task_id claim) with comment/task dependencies, so +// POST /runtime/comments can be exercised over HTTP rather than by calling +// Actions.PostComment directly — the wire path has its own request parsing +// and audit-event logging that the Actions-level tests never reach. +type tasklessAnnotationHandlerHarness struct { + router *gin.Engine + token string + comments *handlerCommentWriter + tasks *handlerTaskCreator + runEvents *recordingRunEvents +} + +func newTasklessAnnotationHandlerHarness(t *testing.T, claimWorkspaceID string) *tasklessAnnotationHandlerHarness { + t.Helper() + gin.SetMode(gin.TestMode) + db, err := sqlx.Open("sqlite3", ":memory:") + if err != nil { + t.Fatalf("open sqlite: %v", err) + } + t.Cleanup(func() { _ = db.Close() }) + if _, _, err := settingsstore.Provide(db, db, nil); err != nil { + t.Fatalf("settings store init: %v", err) + } + repo, err := sqlite.NewWithDB(db, db, nil) + if err != nil { + t.Fatalf("new repo: %v", err) + } + agentSvc := agents.NewAgentService(repo, logger.Default(), nil) + agentSvc.SetAuth(agents.NewAgentAuth("taskless-annotation-test-key")) + agent := &models.AgentInstance{ + ID: "agent-1", + WorkspaceID: "ws-agent-home", + Name: "Coordinator", + Role: models.AgentRoleCEO, + } + if err := repo.CreateAgentInstance(context.Background(), agent); err != nil { + t.Fatalf("create agent: %v", err) + } + capabilityJSON, err := MarshalCapabilities(Capabilities{CanPostComments: true}) + if err != nil { + t.Fatalf("marshal capabilities: %v", err) + } + token, err := agentSvc.MintRuntimeJWT("agent-1", "", claimWorkspaceID, "run-1", "sess-1", capabilityJSON) + if err != nil { + t.Fatalf("mint runtime token: %v", err) + } + comments := &handlerCommentWriter{} + tasks := &handlerTaskCreator{} + runEvents := &recordingRunEvents{} + router := gin.New() + RegisterRoutes(router.Group(""), NewHandler( + agentSvc, + NewActions(ActionDependencies{Comments: comments, Tasks: tasks, Agents: agentSvc}), + nil, + runEvents, + nil, + nil, + nil, + )) + return &tasklessAnnotationHandlerHarness{ + router: router, token: token, comments: comments, tasks: tasks, runEvents: runEvents, + } +} + +func (h *tasklessAnnotationHandlerHarness) postComment(t *testing.T, taskID, body string) *httptest.ResponseRecorder { + t.Helper() + payload, err := json.Marshal(map[string]string{"task_id": taskID, "body": body}) + if err != nil { + t.Fatalf("marshal payload: %v", err) + } + req := httptest.NewRequest(http.MethodPost, "/runtime/comments", bytes.NewReader(payload)) + req.Header.Set("Authorization", "Bearer "+h.token) + req.Header.Set("Content-Type", "application/json") + resp := httptest.NewRecorder() + h.router.ServeHTTP(resp, req) + return resp +} + +func TestRuntimeHandler_TasklessRunAnnotatesWorkspaceTaskOverHTTP(t *testing.T) { + h := newTasklessAnnotationHandlerHarness(t, "ws-1") + + resp := h.postComment(t, "task-x", "blocker found") + + if resp.Code != http.StatusCreated { + t.Fatalf("status = %d, want %d; body=%s", resp.Code, http.StatusCreated, resp.Body.String()) + } + if len(h.comments.comments) != 1 { + t.Fatalf("comments = %d, want 1", len(h.comments.comments)) + } + comment := h.comments.comments[0] + if comment.TaskID != "task-x" || comment.AuthorID != "agent-1" || comment.AuthorType != "agent" { + t.Fatalf("comment identity = %#v", comment) + } + assertActionRunEvent(t, h.runEvents, "post_comment", "task", "task-x") +} + +func TestRuntimeHandler_PostCommentAuditEventNamesTrimmedTarget(t *testing.T) { + h := newTasklessAnnotationHandlerHarness(t, "ws-1") + + resp := h.postComment(t, " task-x ", "blocker found") + + if resp.Code != http.StatusCreated { + t.Fatalf("status = %d, want %d; body=%s", resp.Code, http.StatusCreated, resp.Body.String()) + } + if len(h.comments.comments) != 1 || h.comments.comments[0].TaskID != "task-x" { + t.Fatalf("comments = %#v, want one comment on trimmed task-x", h.comments.comments) + } + // The audit event must name the task the comment actually landed on, + // not the padded value the caller supplied. + assertActionRunEvent(t, h.runEvents, "post_comment", "task", "task-x") +} diff --git a/apps/backend/internal/office/runtime/handler_test.go b/apps/backend/internal/office/runtime/handler_test.go index 394307a57c..06183e25be 100644 --- a/apps/backend/internal/office/runtime/handler_test.go +++ b/apps/backend/internal/office/runtime/handler_test.go @@ -893,6 +893,7 @@ func newRuntimeHandlerHarnessWithProjectManagerAndLogger( runEvents, decisions, log, + nil, )) return &handlerHarness{ router: router, diff --git a/apps/backend/internal/office/runtime/scope_derivation_test.go b/apps/backend/internal/office/runtime/scope_derivation_test.go new file mode 100644 index 0000000000..5d6d831029 --- /dev/null +++ b/apps/backend/internal/office/runtime/scope_derivation_test.go @@ -0,0 +1,691 @@ +package runtime + +import ( + "context" + "encoding/json" + "errors" + "strings" + "testing" + + "github.com/kandev/kandev/internal/office/models" +) + +type stubRunnerLister struct { + ids []string + total int + err error + calls int + + // gotAgentID, gotWorkspaceID, and gotCapAt record the arguments passed to + // the most recent call, so tests can assert ListRunnerSetTaskIDs is + // invoked with the run's own agent/workspace and the package's cap + // rather than some other value that happens to still compile. + gotAgentID string + gotWorkspaceID string + gotCapAt int +} + +func (s *stubRunnerLister) ListRunnerSetTaskIDs( + _ context.Context, agentID, workspaceID string, capAt int, +) ([]string, int, error) { + s.calls++ + s.gotAgentID = agentID + s.gotWorkspaceID = workspaceID + s.gotCapAt = capAt + if s.err != nil { + return nil, 0, s.err + } + return s.ids, s.total, nil +} + +func taskAgent() *models.AgentInstance { + return &models.AgentInstance{ID: "agent-1", WorkspaceID: "ws-1", Role: models.AgentRoleCEO} +} + +func TestBuild_TaskBoundRunScopesToTrimmedPayloadTaskID(t *testing.T) { + builder := ContextBuilder{Agents: &recordingAgentReader{agent: taskAgent()}} + run := &models.Run{ID: "run-1", AgentProfileID: "agent-1", Payload: `{"task_id":" task-1 "}`} + + runCtx, err := builder.Build(context.Background(), run) + if err != nil { + t.Fatalf("Build: %v", err) + } + if runCtx.TaskID != "task-1" { + t.Fatalf("TaskID = %q, want trimmed task-1", runCtx.TaskID) + } + if runCtx.Capabilities.TaskScopeSource != TaskScopeSourcePayload { + t.Fatalf("TaskScopeSource = %q, want payload", runCtx.Capabilities.TaskScopeSource) + } + if len(runCtx.Capabilities.AllowedTaskIDs) != 1 || runCtx.Capabilities.AllowedTaskIDs[0] != "task-1" { + t.Fatalf("AllowedTaskIDs = %v, want [task-1]", runCtx.Capabilities.AllowedTaskIDs) + } +} + +func TestBuild_WhitespaceOnlyPayloadTaskIDIsTaskless(t *testing.T) { + lister := &stubRunnerLister{ids: []string{"t1"}, total: 1} + builder := ContextBuilder{Agents: &recordingAgentReader{agent: taskAgent()}, RunnerLister: lister} + run := &models.Run{ID: "run-1", AgentProfileID: "agent-1", Payload: `{"task_id":" "}`} + + runCtx, err := builder.Build(context.Background(), run) + if err != nil { + t.Fatalf("Build: %v", err) + } + if runCtx.TaskID != "" { + t.Fatalf("TaskID = %q, want empty (taskless)", runCtx.TaskID) + } + if runCtx.Capabilities.TaskScopeSource != TaskScopeSourceRunnerSet { + t.Fatalf("TaskScopeSource = %q, want runner_set", runCtx.Capabilities.TaskScopeSource) + } +} + +func TestBuild_TasklessRunMaterializesRunnerSet(t *testing.T) { + lister := &stubRunnerLister{ids: []string{"t1", "t2"}, total: 2} + builder := ContextBuilder{Agents: &recordingAgentReader{agent: taskAgent()}, RunnerLister: lister} + run := &models.Run{ID: "run-1", AgentProfileID: "agent-1", Payload: `{}`} + + runCtx, err := builder.Build(context.Background(), run) + if err != nil { + t.Fatalf("Build: %v", err) + } + if got := runCtx.Capabilities.AllowedTaskIDs; len(got) != 2 || got[0] != "t1" || got[1] != "t2" { + t.Fatalf("AllowedTaskIDs = %v, want [t1 t2]", got) + } + if lister.calls != 1 { + t.Fatalf("expected 1 runner-set query, got %d", lister.calls) + } + if lister.gotAgentID != "agent-1" { + t.Fatalf("gotAgentID = %q, want %q — the query must scope to the run's own agent, "+ + "not an arbitrary one", lister.gotAgentID, "agent-1") + } + if lister.gotWorkspaceID != "ws-1" { + t.Fatalf("gotWorkspaceID = %q, want %q — the query must scope to the agent's own "+ + "workspace, not an arbitrary one", lister.gotWorkspaceID, "ws-1") + } + if lister.gotCapAt != scopeRunnerSetCap { + t.Fatalf("gotCapAt = %d, want %d — the query must use the package's runner-set cap", + lister.gotCapAt, scopeRunnerSetCap) + } +} + +func TestBuild_NilListerYieldsUnavailableProvisionalScope(t *testing.T) { + builder := ContextBuilder{Agents: &recordingAgentReader{agent: taskAgent()}} + run := &models.Run{ID: "run-1", AgentProfileID: "agent-1", Payload: `{}`} + + runCtx, err := builder.Build(context.Background(), run) + if err != nil { + t.Fatalf("Build: %v", err) + } + if len(runCtx.Capabilities.AllowedTaskIDs) != 0 { + t.Fatalf("AllowedTaskIDs = %v, want empty", runCtx.Capabilities.AllowedTaskIDs) + } + if runCtx.Capabilities.TaskScopeSource != TaskScopeSourceUnavailable { + t.Fatalf("TaskScopeSource = %q, want unavailable", runCtx.Capabilities.TaskScopeSource) + } +} + +func TestBuild_EmptyRunWorkspaceIssuesNoQuery(t *testing.T) { + lister := &stubRunnerLister{ids: []string{"t1"}, total: 1} + builder := ContextBuilder{ + Agents: &recordingAgentReader{agent: &models.AgentInstance{ID: "agent-1", WorkspaceID: ""}}, + RunnerLister: lister, + } + run := &models.Run{ID: "run-1", AgentProfileID: "agent-1", Payload: `{}`} + + runCtx, err := builder.Build(context.Background(), run) + if err != nil { + t.Fatalf("Build: %v", err) + } + if lister.calls != 0 { + t.Fatalf("expected no query for empty workspace, got %d calls", lister.calls) + } + if runCtx.Capabilities.TaskScopeSource != TaskScopeSourceUnavailable { + t.Fatalf("TaskScopeSource = %q, want unavailable", runCtx.Capabilities.TaskScopeSource) + } +} + +func TestBuild_RunnerSetQueryErrorFailsClosed(t *testing.T) { + lister := &stubRunnerLister{err: errors.New("db down")} + builder := ContextBuilder{Agents: &recordingAgentReader{agent: taskAgent()}, RunnerLister: lister} + run := &models.Run{ID: "run-1", AgentProfileID: "agent-1", Payload: `{}`} + + runCtx, err := builder.Build(context.Background(), run) + if err != nil { + t.Fatalf("Build: %v", err) + } + if len(runCtx.Capabilities.AllowedTaskIDs) != 0 { + t.Fatalf("AllowedTaskIDs = %v, want empty on query failure", runCtx.Capabilities.AllowedTaskIDs) + } + if runCtx.Capabilities.TaskScopeSource != TaskScopeSourceUnavailable { + t.Fatalf("TaskScopeSource = %q, want unavailable", runCtx.Capabilities.TaskScopeSource) + } +} + +// TestBuild_WildcardPayloadTaskIDStaysTaskBoundWithEmptyScope is the Review +// round 3 regression test (R3REV-03). A run injecting task_id="*" must NOT +// be reclassified as taskless: doing so would grant it the runner-set +// mutation scope (up to 500 tasks) plus workspace-wide annotation, which is +// strictly MORE authority than the correct outcome — staying task-bound +// with an empty, permanently-non-matching scope, since WithTaskScope +// already strips the sentinel from AllowedTaskIDs. No AC sanctions +// promoting a wildcard payload to the wider taskless class; AC-003.10 only +// forbids assigning the wildcard scope, which the fail-closed empty scope +// here satisfies without needing the reclassification. +func TestBuild_WildcardPayloadTaskIDStaysTaskBoundWithEmptyScope(t *testing.T) { + lister := &stubRunnerLister{ids: []string{"t1"}, total: 1} + builder := ContextBuilder{Agents: &recordingAgentReader{agent: taskAgent()}, RunnerLister: lister} + run := &models.Run{ID: "run-1", AgentProfileID: "agent-1", Payload: `{"task_id":"*"}`} + + runCtx, err := builder.Build(context.Background(), run) + if err != nil { + t.Fatalf("Build: %v", err) + } + if runCtx.Capabilities.TaskScopeSource != TaskScopeSourcePayload { + t.Fatalf( + "TaskScopeSource = %q, want %q — a wildcard payload must stay task-bound, not fall "+ + "through to the taskless runner-set derivation", + runCtx.Capabilities.TaskScopeSource, TaskScopeSourcePayload, + ) + } + if lister.calls != 0 { + t.Fatalf("expected no runner-set query for a wildcard payload task_id, got %d calls", lister.calls) + } + for _, id := range runCtx.Capabilities.AllowedTaskIDs { + if id == WildcardTaskScope { + t.Fatalf( + "a wildcard payload task_id must never grant workspace-wide mutation authority: %v", + runCtx.Capabilities.AllowedTaskIDs, + ) + } + } + if len(runCtx.Capabilities.AllowedTaskIDs) != 0 { + t.Fatalf("AllowedTaskIDs = %v, want empty — the stripped wildcard must not be replaced "+ + "by any wider grant", runCtx.Capabilities.AllowedTaskIDs) + } + if runCtx.CanMutateTask("some-other-task") { + t.Fatal("a run injecting task_id=\"*\" must not gain authority over an arbitrary task") + } + if runCtx.CanMutateTask("t1") { + t.Fatal("a run injecting task_id=\"*\" must not gain authority over the agent's own runner-set tasks either") + } +} + +func TestBuild_RunnerSetScopeExcludesWildcard(t *testing.T) { + lister := &stubRunnerLister{ids: []string{"t1"}, total: 1} + builder := ContextBuilder{Agents: &recordingAgentReader{agent: taskAgent()}, RunnerLister: lister} + run := &models.Run{ID: "run-1", AgentProfileID: "agent-1", Payload: `{}`} + + runCtx, err := builder.Build(context.Background(), run) + if err != nil { + t.Fatalf("Build: %v", err) + } + for _, id := range runCtx.Capabilities.AllowedTaskIDs { + if id == WildcardTaskScope { + t.Fatalf("taskless run must never receive the wildcard scope: %v", runCtx.Capabilities.AllowedTaskIDs) + } + } +} + +// -- BuildAndPersist / snapshot reuse -- + +func TestBuildAndPersist_FinalRunnerSetMarkerIsReusedWithoutQuery(t *testing.T) { + lister := &stubRunnerLister{ids: []string{"fresh"}, total: 1} + store := &recordingRunSnapshotStore{casWins: true} + builder := ContextBuilder{ + Agents: &recordingAgentReader{agent: taskAgent()}, + Runs: store, + RunnerLister: lister, + } + persistedCaps, err := MarshalCapabilities(Capabilities{ + AllowedTaskIDs: []string{"persisted-1", "persisted-2"}, + TaskScopeSource: TaskScopeSourceRunnerSet, + }) + if err != nil { + t.Fatalf("marshal: %v", err) + } + run := &models.Run{ID: "run-1", AgentProfileID: "agent-1", Payload: `{}`, Capabilities: persistedCaps} + + runCtx, err := builder.BuildAndPersist(context.Background(), run) + if err != nil { + t.Fatalf("BuildAndPersist: %v", err) + } + if lister.calls != 0 { + t.Fatalf("expected no runner-set query on reuse, got %d", lister.calls) + } + got := runCtx.Capabilities.AllowedTaskIDs + if len(got) != 2 || got[0] != "persisted-1" || got[1] != "persisted-2" { + t.Fatalf("AllowedTaskIDs = %v, want reused persisted scope", got) + } +} + +func TestBuildAndPersist_ProvisionalUnavailableMarkerDerivesAgain(t *testing.T) { + lister := &stubRunnerLister{ids: []string{"fresh"}, total: 1} + store := &recordingRunSnapshotStore{casWins: true} + builder := ContextBuilder{ + Agents: &recordingAgentReader{agent: taskAgent()}, + Runs: store, + RunnerLister: lister, + } + persistedCaps, err := MarshalCapabilities(Capabilities{TaskScopeSource: TaskScopeSourceUnavailable}) + if err != nil { + t.Fatalf("marshal: %v", err) + } + run := &models.Run{ID: "run-1", AgentProfileID: "agent-1", Payload: `{}`, Capabilities: persistedCaps} + + runCtx, err := builder.BuildAndPersist(context.Background(), run) + if err != nil { + t.Fatalf("BuildAndPersist: %v", err) + } + if lister.calls != 1 { + t.Fatalf("expected a fresh runner-set query, got %d calls", lister.calls) + } + if len(runCtx.Capabilities.AllowedTaskIDs) != 1 || runCtx.Capabilities.AllowedTaskIDs[0] != "fresh" { + t.Fatalf("AllowedTaskIDs = %v, want [fresh]", runCtx.Capabilities.AllowedTaskIDs) + } +} + +func TestBuildAndPersist_UnrecognizedMarkerDerivesFresh(t *testing.T) { + lister := &stubRunnerLister{ids: []string{"fresh"}, total: 1} + store := &recordingRunSnapshotStore{casWins: true} + builder := ContextBuilder{ + Agents: &recordingAgentReader{agent: taskAgent()}, + Runs: store, + RunnerLister: lister, + } + run := &models.Run{ + ID: "run-1", AgentProfileID: "agent-1", Payload: `{}`, + Capabilities: `{"task_scope_source":"something-else"}`, + } + + runCtx, err := builder.BuildAndPersist(context.Background(), run) + if err != nil { + t.Fatalf("BuildAndPersist: %v", err) + } + if lister.calls != 1 { + t.Fatalf("expected a fresh derive for an unrecognized marker, got %d", lister.calls) + } + if len(runCtx.Capabilities.AllowedTaskIDs) != 1 || runCtx.Capabilities.AllowedTaskIDs[0] != "fresh" { + t.Fatalf("AllowedTaskIDs = %v, want [fresh]", runCtx.Capabilities.AllowedTaskIDs) + } +} + +func TestBuildAndPersist_UnparseableSnapshotDerivesFresh(t *testing.T) { + lister := &stubRunnerLister{ids: []string{"fresh"}, total: 1} + store := &recordingRunSnapshotStore{casWins: true} + builder := ContextBuilder{ + Agents: &recordingAgentReader{agent: taskAgent()}, + Runs: store, + RunnerLister: lister, + } + run := &models.Run{ID: "run-1", AgentProfileID: "agent-1", Payload: `{}`, Capabilities: `not json`} + + runCtx, err := builder.BuildAndPersist(context.Background(), run) + if err != nil { + t.Fatalf("BuildAndPersist: %v", err) + } + if lister.calls != 1 { + t.Fatalf("expected a fresh derive for unparseable capabilities, got %d", lister.calls) + } + if len(runCtx.Capabilities.AllowedTaskIDs) != 1 || runCtx.Capabilities.AllowedTaskIDs[0] != "fresh" { + t.Fatalf("AllowedTaskIDs = %v, want [fresh]", runCtx.Capabilities.AllowedTaskIDs) + } +} + +func TestBuildAndPersist_CapabilityBooleansAlwaysRederiveOnReuse(t *testing.T) { + lister := &stubRunnerLister{} + store := &recordingRunSnapshotStore{casWins: true} + agent := taskAgent() + agent.Permissions = `{"can_create_tasks":true}` + builder := ContextBuilder{Agents: &recordingAgentReader{agent: agent}, Runs: store, RunnerLister: lister} + persistedCaps, err := MarshalCapabilities(Capabilities{ + AllowedTaskIDs: []string{"t1"}, + TaskScopeSource: TaskScopeSourceRunnerSet, + }) + if err != nil { + t.Fatalf("marshal: %v", err) + } + run := &models.Run{ID: "run-1", AgentProfileID: "agent-1", Payload: `{}`, Capabilities: persistedCaps} + + runCtx, err := builder.BuildAndPersist(context.Background(), run) + if err != nil { + t.Fatalf("BuildAndPersist: %v", err) + } + if !runCtx.Capabilities.Allows(CapabilityCreateAgent) { + t.Fatal("expected capability booleans to re-derive from the agent even on scope reuse") + } +} + +func TestBuildAndPersist_TruncationEmitsScopeTruncatedEvent(t *testing.T) { + ids := make([]string, scopeRunnerSetCap) + for i := range ids { + ids[i] = "t" + } + lister := &stubRunnerLister{ids: ids, total: scopeRunnerSetCap + 7} + store := &recordingRunSnapshotStore{casWins: true} + events := &recordingRunEvents{} + builder := ContextBuilder{ + Agents: &recordingAgentReader{agent: taskAgent()}, + Runs: store, + RunnerLister: lister, + ScopeEvents: events, + } + run := &models.Run{ID: "run-1", AgentProfileID: "agent-1", Payload: `{}`} + + if _, err := builder.BuildAndPersist(context.Background(), run); err != nil { + t.Fatalf("BuildAndPersist: %v", err) + } + if len(events.events) != 1 || events.events[0].eventType != "runtime.scope_truncated" { + t.Fatalf("events = %+v, want one runtime.scope_truncated", events.events) + } + if events.events[0].payload["total"] != scopeRunnerSetCap+7 { + t.Fatalf("payload total = %v, want %d", events.events[0].payload["total"], scopeRunnerSetCap+7) + } +} + +// TestBuildAndPersist_EmptyRunnerSetIsFinalAndNotReDerived is the Review +// round 3 regression test (R3REV-06, AC-003.7/AC-003.9): an agent with no +// tasks in its runner set at all is a legitimate, final outcome — the +// resulting empty AllowedTaskIDs marked TaskScopeSourceRunnerSet must be +// treated the same as any other final scope (reused verbatim on the next +// build, not re-queried), not conflated with the provisional "unavailable" +// marker that legitimately retries. +func TestBuildAndPersist_EmptyRunnerSetIsFinalAndNotReDerived(t *testing.T) { + lister := &stubRunnerLister{ids: nil, total: 0} + store := &recordingRunSnapshotStore{casWins: true} + builder := ContextBuilder{Agents: &recordingAgentReader{agent: taskAgent()}, Runs: store, RunnerLister: lister} + run := &models.Run{ID: "run-1", AgentProfileID: "agent-1", Payload: `{}`} + + runCtx, err := builder.BuildAndPersist(context.Background(), run) + if err != nil { + t.Fatalf("BuildAndPersist: %v", err) + } + if runCtx.Capabilities.TaskScopeSource != TaskScopeSourceRunnerSet { + t.Fatalf("TaskScopeSource = %q, want %q — an empty runner set is still a final "+ + "derivation, not unavailable", runCtx.Capabilities.TaskScopeSource, TaskScopeSourceRunnerSet) + } + if len(runCtx.Capabilities.AllowedTaskIDs) != 0 { + t.Fatalf("AllowedTaskIDs = %v, want empty", runCtx.Capabilities.AllowedTaskIDs) + } + if runCtx.CanMutateTask("any-task") { + t.Fatal("an empty runner set must refuse mutation authority over any task") + } + if lister.calls != 1 { + t.Fatalf("expected exactly 1 runner-set query for the first build, got %d", lister.calls) + } + + // A second build on the same (now-persisted) run must reuse the final + // empty scope rather than re-querying the runner set. + runCtx2, err := builder.BuildAndPersist(context.Background(), run) + if err != nil { + t.Fatalf("second BuildAndPersist: %v", err) + } + if lister.calls != 1 { + t.Fatalf("expected no additional runner-set query on reuse, got %d total calls", lister.calls) + } + if runCtx2.Capabilities.TaskScopeSource != TaskScopeSourceRunnerSet { + t.Fatalf("reused TaskScopeSource = %q, want %q", runCtx2.Capabilities.TaskScopeSource, TaskScopeSourceRunnerSet) + } + if len(runCtx2.Capabilities.AllowedTaskIDs) != 0 { + t.Fatalf("reused AllowedTaskIDs = %v, want empty", runCtx2.Capabilities.AllowedTaskIDs) + } +} + +func TestBuildAndPersist_UnavailableEmitsScopeUnavailableEvent(t *testing.T) { + lister := &stubRunnerLister{err: errors.New("db down")} + store := &recordingRunSnapshotStore{casWins: true} + events := &recordingRunEvents{} + builder := ContextBuilder{ + Agents: &recordingAgentReader{agent: taskAgent()}, + Runs: store, + RunnerLister: lister, + ScopeEvents: events, + } + run := &models.Run{ID: "run-1", AgentProfileID: "agent-1", Payload: `{}`} + + if _, err := builder.BuildAndPersist(context.Background(), run); err != nil { + t.Fatalf("BuildAndPersist: %v", err) + } + if len(events.events) != 1 || events.events[0].eventType != "runtime.scope_unavailable" { + t.Fatalf("events = %+v, want one runtime.scope_unavailable", events.events) + } +} + +func TestBuildAndPersist_TaskBoundRunEmitsNoScopeEvent(t *testing.T) { + store := &recordingRunSnapshotStore{casWins: true} + events := &recordingRunEvents{} + builder := ContextBuilder{Agents: &recordingAgentReader{agent: taskAgent()}, Runs: store, ScopeEvents: events} + run := &models.Run{ID: "run-1", AgentProfileID: "agent-1", Payload: `{"task_id":"task-1"}`} + + if _, err := builder.BuildAndPersist(context.Background(), run); err != nil { + t.Fatalf("BuildAndPersist: %v", err) + } + if len(events.events) != 0 { + t.Fatalf("expected no scope event for a task-bound run, got %+v", events.events) + } +} + +func TestBuildAndPersist_NoRunsStorePersistsAndEmitsNothing(t *testing.T) { + lister := &stubRunnerLister{ids: []string{"t1"}, total: 1} + events := &recordingRunEvents{} + builder := ContextBuilder{Agents: &recordingAgentReader{agent: taskAgent()}, RunnerLister: lister, ScopeEvents: events} + run := &models.Run{ID: "run-1", AgentProfileID: "agent-1", Payload: `{}`} + + runCtx, err := builder.BuildAndPersist(context.Background(), run) + if err != nil { + t.Fatalf("BuildAndPersist: %v", err) + } + if len(events.events) != 0 { + t.Fatalf("expected no events with no Runs store, got %+v", events.events) + } + if len(runCtx.Capabilities.AllowedTaskIDs) != 1 { + t.Fatalf("expected a built context even with no Runs store: %+v", runCtx) + } +} + +func TestBuildAndPersist_NoAppenderSkipsEventButStillPersists(t *testing.T) { + lister := &stubRunnerLister{ids: []string{"t1"}, total: 1} + store := &recordingRunSnapshotStore{casWins: true} + builder := ContextBuilder{Agents: &recordingAgentReader{agent: taskAgent()}, Runs: store, RunnerLister: lister} + run := &models.Run{ID: "run-1", AgentProfileID: "agent-1", Payload: `{}`} + + if _, err := builder.BuildAndPersist(context.Background(), run); err != nil { + t.Fatalf("BuildAndPersist: %v", err) + } + if len(store.calls) != 1 { + t.Fatalf("expected persistence even with no appender, got %d calls", len(store.calls)) + } +} + +// -- Concurrency: CAS first-write-wins -- + +func TestBuildAndPersist_CASLoserAdoptsPersistedFinalScopeAndEmitsNoEvent(t *testing.T) { + lister := &stubRunnerLister{ids: []string{"mine"}, total: 1} + winnerRunCtx := RunContext{ + WorkspaceID: "ws-1", + AgentID: "agent-1", + RunID: "run-1", + Capabilities: Capabilities{ + AllowedTaskIDs: []string{"winner-task"}, + TaskScopeSource: TaskScopeSourceRunnerSet, + }, + } + winnerCaps, err := MarshalCapabilities(winnerRunCtx.Capabilities) + if err != nil { + t.Fatalf("marshal: %v", err) + } + winnerInput, err := MarshalRunContext(winnerRunCtx) + if err != nil { + t.Fatalf("marshal: %v", err) + } + store := &recordingRunSnapshotStore{ + casWins: false, + runs: map[string]*models.Run{ + "run-1": {ID: "run-1", Capabilities: winnerCaps, InputSnapshot: winnerInput}, + }, + } + events := &recordingRunEvents{} + builder := ContextBuilder{ + Agents: &recordingAgentReader{agent: taskAgent()}, + Runs: store, + RunnerLister: lister, + ScopeEvents: events, + } + run := &models.Run{ID: "run-1", AgentProfileID: "agent-1", Payload: `{}`} + + runCtx, err := builder.BuildAndPersist(context.Background(), run) + if err != nil { + t.Fatalf("BuildAndPersist: %v", err) + } + if got := runCtx.Capabilities.AllowedTaskIDs; len(got) != 1 || got[0] != "winner-task" { + t.Fatalf("AllowedTaskIDs = %v, want the winner's persisted scope", got) + } + if len(events.events) != 0 { + t.Fatalf("loser must emit no scope event, got %+v", events.events) + } + // The loser adopts the winner's already-persisted snapshot verbatim + // instead of performing a second, unguarded write that could clobber it. + if len(store.calls) != 0 { + t.Fatalf("expected no additional write once the winner's snapshot is adopted, got %d calls", len(store.calls)) + } +} + +func TestBuildAndPersist_CASExhaustsAttemptsWithNoFinalMarker(t *testing.T) { + lister := &stubRunnerLister{ids: []string{"t1"}, total: 1} + store := &recordingRunSnapshotStore{ + casWins: false, + runs: map[string]*models.Run{"run-1": {ID: "run-1", Capabilities: `{}`}}, + } + builder := ContextBuilder{ + Agents: &recordingAgentReader{agent: taskAgent()}, + Runs: store, + RunnerLister: lister, + } + run := &models.Run{ID: "run-1", AgentProfileID: "agent-1", Payload: `{}`} + + _, err := builder.BuildAndPersist(context.Background(), run) + if err == nil { + t.Fatal("expected an error after exhausting CAS attempts") + } + if lister.calls != maxScopeSwapAttempts { + t.Fatalf("expected %d derive attempts, got %d", maxScopeSwapAttempts, lister.calls) + } + if len(store.casCalls) != maxScopeSwapAttempts { + t.Fatalf("expected %d CAS attempts, got %d", maxScopeSwapAttempts, len(store.casCalls)) + } + // The first attempt must compare against the run's own capabilities as + // Build originally read them (empty here, since run.Capabilities is + // unset); every retry after a lost race must compare against the + // re-read run's capabilities, not the scope this attempt is about to + // write — otherwise the CAS predicate could never observe a real prior + // value and would lose every race forever. + if store.casCalls[0].PrevCapabilities != "" { + t.Fatalf("first CAS attempt PrevCapabilities = %q, want empty", store.casCalls[0].PrevCapabilities) + } + for i := 1; i < len(store.casCalls); i++ { + if store.casCalls[i].PrevCapabilities != store.runs["run-1"].Capabilities { + t.Fatalf( + "CAS attempt %d PrevCapabilities = %q, want the re-read run's capabilities %q", + i, store.casCalls[i].PrevCapabilities, store.runs["run-1"].Capabilities, + ) + } + if store.casCalls[i].PrevCapabilities == store.casCalls[i].Capabilities { + t.Fatalf( + "CAS attempt %d compared the scope it is about to write against itself: %q", + i, store.casCalls[i].Capabilities, + ) + } + } +} + +func TestBuildAndPersist_CASErrorReturnsError(t *testing.T) { + lister := &stubRunnerLister{ids: []string{"t1"}, total: 1} + store := &recordingRunSnapshotStore{casErr: errors.New("db down")} + builder := ContextBuilder{Agents: &recordingAgentReader{agent: taskAgent()}, Runs: store, RunnerLister: lister} + run := &models.Run{ID: "run-1", AgentProfileID: "agent-1", Payload: `{}`} + + if _, err := builder.BuildAndPersist(context.Background(), run); err == nil { + t.Fatal("expected the CAS error to propagate") + } +} + +func TestBuildAndPersist_NilRunReturnsErrorNotPanic(t *testing.T) { + builder := ContextBuilder{} + + if _, err := builder.BuildAndPersist(context.Background(), nil); err == nil { + t.Fatal("expected an error for a nil run, not a panic") + } +} + +func TestBuildAndPersist_CASLoserReadFailureReturnsError(t *testing.T) { + lister := &stubRunnerLister{ids: []string{"mine"}, total: 1} + store := &recordingRunSnapshotStore{casWins: false, getErr: errors.New("db down")} + builder := ContextBuilder{ + Agents: &recordingAgentReader{agent: taskAgent()}, + Runs: store, + RunnerLister: lister, + } + run := &models.Run{ID: "run-1", AgentProfileID: "agent-1", Payload: `{}`} + + _, err := builder.BuildAndPersist(context.Background(), run) + if err == nil { + t.Fatal("expected the re-read failure to propagate") + } + if !strings.Contains(err.Error(), "re-read run after lost scope race") { + t.Fatalf("error = %v, want it to mention the re-read failure", err) + } +} + +func TestBuildAndPersist_PersistsSerializedRunnerSetScope(t *testing.T) { + lister := &stubRunnerLister{ids: []string{"t1", "t2"}, total: 2} + store := &recordingRunSnapshotStore{casWins: true} + builder := ContextBuilder{Agents: &recordingAgentReader{agent: taskAgent()}, Runs: store, RunnerLister: lister} + run := &models.Run{ID: "run-1", AgentProfileID: "agent-1", Payload: `{}`} + + if _, err := builder.BuildAndPersist(context.Background(), run); err != nil { + t.Fatalf("BuildAndPersist: %v", err) + } + if len(store.calls) != 1 { + t.Fatalf("expected 1 snapshot write, got %d", len(store.calls)) + } + if len(store.casCalls) != 1 || store.casCalls[0].PrevCapabilities != "" { + t.Fatalf( + "a fresh run with no persisted capabilities must CAS against an empty prior value: %+v", + store.casCalls, + ) + } + if run.Capabilities == "" { + t.Fatal("BuildAndPersist must mutate run.Capabilities in place — the JWT is minted from it") + } + + var persistedCaps Capabilities + if err := json.Unmarshal([]byte(store.calls[0].Capabilities), &persistedCaps); err != nil { + t.Fatalf("decode persisted capabilities: %v", err) + } + if got := persistedCaps.AllowedTaskIDs; len(got) != 2 || got[0] != "t1" || got[1] != "t2" { + t.Fatalf("persisted AllowedTaskIDs = %v, want [t1 t2]", got) + } + if persistedCaps.TaskScopeSource != TaskScopeSourceRunnerSet { + t.Fatalf("persisted TaskScopeSource = %q, want runner_set", persistedCaps.TaskScopeSource) + } + + var persistedRunCtx RunContext + if err := json.Unmarshal([]byte(store.calls[0].InputSnapshot), &persistedRunCtx); err != nil { + t.Fatalf("decode persisted input snapshot: %v", err) + } + if got := persistedRunCtx.Capabilities.AllowedTaskIDs; len(got) != 2 || got[0] != "t1" || got[1] != "t2" { + t.Fatalf("persisted input snapshot AllowedTaskIDs = %v, want [t1 t2]", got) + } + + // run.Capabilities is the third carrier of the derived scope — the run + // token minted for this execution is marshalled from it, not from the + // DB row or the returned RunContext, so it must reflect the same scope. + var mutatedRunCaps Capabilities + if err := json.Unmarshal([]byte(run.Capabilities), &mutatedRunCaps); err != nil { + t.Fatalf("decode run.Capabilities: %v", err) + } + if got := mutatedRunCaps.AllowedTaskIDs; len(got) != 2 || got[0] != "t1" || got[1] != "t2" { + t.Fatalf("run.Capabilities AllowedTaskIDs = %v, want [t1 t2]", got) + } + if mutatedRunCaps.TaskScopeSource != TaskScopeSourceRunnerSet { + t.Fatalf("run.Capabilities TaskScopeSource = %q, want runner_set", mutatedRunCaps.TaskScopeSource) + } +} diff --git a/apps/backend/internal/office/runtime/tasks_list.go b/apps/backend/internal/office/runtime/tasks_list.go new file mode 100644 index 0000000000..bd890e451e --- /dev/null +++ b/apps/backend/internal/office/runtime/tasks_list.go @@ -0,0 +1,267 @@ +package runtime + +import ( + "context" + "net/http" + "net/url" + "strconv" + "strings" + + "github.com/gin-gonic/gin" + + "github.com/kandev/kandev/internal/office/repository/sqlite" +) + +// TaskFilteredLister lists one workspace's tasks, ordered and paginated. +// Satisfied by internal/office/dashboard.DashboardService, which already +// implements this exact signature for the dashboard's own filtered list. +type TaskFilteredLister interface { + ListTasksFiltered( + ctx context.Context, workspaceID string, opts sqlite.ListTasksOptions, + ) (*sqlite.ListTasksFilteredResult, error) +} + +// TaskListItem is one row in a runtime board-read response. +type TaskListItem struct { + ID string `json:"id"` + WorkspaceID string `json:"workspace_id"` + Identifier string `json:"identifier"` + Title string `json:"title"` + Description string `json:"description,omitempty"` + Status string `json:"status"` + Priority string `json:"priority"` + ParentID string `json:"parent_id,omitempty"` + ProjectID string `json:"project_id,omitempty"` + AssigneeID string `json:"assignee_agent_profile_id,omitempty"` + Labels string `json:"labels,omitempty"` + CreatedAt string `json:"created_at"` + UpdatedAt string `json:"updated_at"` + IsSystem bool `json:"is_system,omitempty"` +} + +// listTasks handles GET /runtime/tasks: board read scoped to the run +// token's workspace claim, never a caller-supplied one. Evaluation order is +// capability, workspace claim, parameter validation, then the query — so a +// run lacking the capability learns nothing about which parameters would +// have been accepted. +func (h *Handler) listTasks(c *gin.Context) { + runCtx, _, ok := h.contextFromRequest(c) + if !ok { + return + } + if !runCtx.Capabilities.Allows(CapabilityListTasks) { + h.respondRuntimeError(c, runCtx, "list_tasks", "workspace", runCtx.WorkspaceID, ErrCapabilityDenied) + return + } + if strings.TrimSpace(runCtx.WorkspaceID) == "" { + h.respondRuntimeError(c, runCtx, "list_tasks", "workspace", runCtx.WorkspaceID, ErrWorkspaceOutOfScope) + return + } + query, err := url.ParseQuery(c.Request.URL.RawQuery) + if err != nil { + h.respondRuntimeError(c, runCtx, "list_tasks", "workspace", runCtx.WorkspaceID, ErrInvalidListParams) + return + } + opts, err := parseListTasksQuery(query) + if err != nil { + h.respondRuntimeError(c, runCtx, "list_tasks", "workspace", runCtx.WorkspaceID, err) + return + } + if h.taskLister == nil { + h.respondRuntimeError(c, runCtx, "list_tasks", "workspace", runCtx.WorkspaceID, ErrRuntimeDependencyMissing) + return + } + page, err := h.taskLister.ListTasksFiltered(c.Request.Context(), runCtx.WorkspaceID, opts) + if err != nil { + h.respondRuntimeError(c, runCtx, "list_tasks", "workspace", runCtx.WorkspaceID, err) + return + } + h.appendActionRunEvent(c.Request.Context(), runCtx, "list_tasks", "workspace", runCtx.WorkspaceID) + c.JSON(http.StatusOK, gin.H{ + "tasks": toTaskListItems(page.Tasks), + "next_cursor": page.NextCursor, + "next_id": page.NextID, + }) +} + +func toTaskListItems(rows []*sqlite.TaskRow) []TaskListItem { + items := make([]TaskListItem, 0, len(rows)) + for _, r := range rows { + items = append(items, TaskListItem{ + ID: r.ID, + WorkspaceID: r.WorkspaceID, + Identifier: r.Identifier, + Title: r.Title, + Description: r.Description, + Status: r.Status, + Priority: r.Priority, + ParentID: r.ParentID, + ProjectID: r.ProjectID, + AssigneeID: r.AssigneeAgentProfileID, + Labels: r.Labels, + CreatedAt: r.CreatedAt, + UpdatedAt: r.UpdatedAt, + IsSystem: r.IsSystem, + }) + } + return items +} + +// parseListTasksQuery validates and maps the board-read query string per +// docs/specs/office/system-design/taskless-coordinator-authority-02.md +// #request-and-response-contract. Every rule is strict on purpose: an +// empty value means absent, enumerated values match byte-for-byte with no +// case folding or trimming, and repeating a single-valued parameter is a +// refusal rather than "last one wins". +func parseListTasksQuery(query url.Values) (sqlite.ListTasksOptions, error) { + opts := sqlite.ListTasksOptions{ + Status: repeatableListParam(query, "status"), + Priority: repeatableListParam(query, "priority"), + SortDesc: true, + } + if err := parseSingleValuedFilters(query, &opts); err != nil { + return sqlite.ListTasksOptions{}, err + } + if err := parseSortAndOrder(query, &opts); err != nil { + return sqlite.ListTasksOptions{}, err + } + if err := parseLimit(query, &opts); err != nil { + return sqlite.ListTasksOptions{}, err + } + if err := parseCursor(query, &opts); err != nil { + return sqlite.ListTasksOptions{}, err + } + if err := parseIncludeSystem(query, &opts); err != nil { + return sqlite.ListTasksOptions{}, err + } + return opts, nil +} + +func parseSingleValuedFilters(query url.Values, opts *sqlite.ListTasksOptions) error { + assignee, _, err := singleListParam(query, "assignee") + if err != nil { + return err + } + opts.AssigneeID = assignee + + project, _, err := singleListParam(query, "project") + if err != nil { + return err + } + opts.ProjectID = project + return nil +} + +func parseSortAndOrder(query url.Values, opts *sqlite.ListTasksOptions) error { + sortRaw, sortPresent, err := singleListParam(query, "sort") + if err != nil { + return err + } + if sortPresent { + switch sortRaw { + case string(sqlite.TaskSortUpdatedAt), string(sqlite.TaskSortCreatedAt), string(sqlite.TaskSortPriority): + opts.SortField = sqlite.TaskListSortField(sortRaw) + default: + return ErrInvalidListParams + } + } + + orderRaw, orderPresent, err := singleListParam(query, "order") + if err != nil { + return err + } + if orderPresent { + switch orderRaw { + case "asc": + opts.SortDesc = false + case "desc": + opts.SortDesc = true + default: + return ErrInvalidListParams + } + } + return nil +} + +func parseLimit(query url.Values, opts *sqlite.ListTasksOptions) error { + limitRaw, present, err := singleListParam(query, "limit") + if err != nil { + return err + } + if !present { + return nil + } + n, convErr := strconv.Atoi(limitRaw) + if convErr != nil { + return ErrInvalidListParams + } + opts.Limit = n + return nil +} + +func parseCursor(query url.Values, opts *sqlite.ListTasksOptions) error { + cursorValue, cursorPresent, err := singleListParam(query, "cursor") + if err != nil { + return err + } + cursorID, cursorIDPresent, err := singleListParam(query, "cursor_id") + if err != nil { + return err + } + if cursorPresent != cursorIDPresent { + return ErrInvalidListParams + } + opts.CursorValue = cursorValue + opts.CursorID = cursorID + return nil +} + +func parseIncludeSystem(query url.Values, opts *sqlite.ListTasksOptions) error { + raw, present, err := singleListParam(query, "include_system") + if err != nil { + return err + } + if !present { + return nil + } + switch raw { + case "true": + opts.IncludeSystem = true + case "false": + opts.IncludeSystem = false + default: + return ErrInvalidListParams + } + return nil +} + +// singleListParam reads a single-valued query parameter. A repeat of the +// key is ErrInvalidListParams; a present-but-empty value is treated as +// absent (present=false) per the "empty means absent" normalization rule. +func singleListParam(query url.Values, key string) (value string, present bool, err error) { + values := query[key] + switch len(values) { + case 0: + return "", false, nil + case 1: + if values[0] == "" { + return "", false, nil + } + return values[0], true, nil + default: + return "", false, ErrInvalidListParams + } +} + +// repeatableListParam reads a repeatable query parameter, dropping any +// individually-empty values ("empty means absent" applies per value). +func repeatableListParam(query url.Values, key string) []string { + values := query[key] + out := make([]string, 0, len(values)) + for _, v := range values { + if v != "" { + out = append(out, v) + } + } + return out +} diff --git a/apps/backend/internal/office/runtime/tasks_list_query_test.go b/apps/backend/internal/office/runtime/tasks_list_query_test.go new file mode 100644 index 0000000000..510aaa0f4e --- /dev/null +++ b/apps/backend/internal/office/runtime/tasks_list_query_test.go @@ -0,0 +1,187 @@ +package runtime + +import ( + "errors" + "net/url" + "testing" + + "github.com/kandev/kandev/internal/office/repository/sqlite" +) + +func TestParseListTasksQuery_EmptyQueryDefaultsToDescByUpdatedAt(t *testing.T) { + opts, err := parseListTasksQuery(url.Values{}) + if err != nil { + t.Fatalf("parseListTasksQuery: %v", err) + } + if len(opts.Status) != 0 || len(opts.Priority) != 0 { + t.Fatalf("filters = %+v, want none", opts) + } + if !opts.SortDesc { + t.Fatalf("SortDesc = false, want true (default)") + } + if opts.SortField != "" { + t.Fatalf("SortField = %q, want empty (caller defaults it)", opts.SortField) + } +} + +func TestParseListTasksQuery_EmptyValueMeansAbsentForSingleValued(t *testing.T) { + opts, err := parseListTasksQuery(url.Values{"assignee": {""}, "project": {""}}) + if err != nil { + t.Fatalf("parseListTasksQuery: %v", err) + } + if opts.AssigneeID != "" || opts.ProjectID != "" { + t.Fatalf("opts = %+v, want both empty", opts) + } +} + +func TestParseListTasksQuery_EmptyValueDroppedFromRepeatable(t *testing.T) { + opts, err := parseListTasksQuery(url.Values{"status": {"TODO", ""}}) + if err != nil { + t.Fatalf("parseListTasksQuery: %v", err) + } + if len(opts.Status) != 1 || opts.Status[0] != "TODO" { + t.Fatalf("Status = %v, want [TODO]", opts.Status) + } +} + +func TestParseListTasksQuery_RepeatedSingleValuedParamIsInvalid(t *testing.T) { + _, err := parseListTasksQuery(url.Values{"assignee": {"agent-1", "agent-2"}}) + if !errors.Is(err, ErrInvalidListParams) { + t.Fatalf("error = %v, want ErrInvalidListParams", err) + } +} + +func TestParseListTasksQuery_RepeatableParamUnion(t *testing.T) { + opts, err := parseListTasksQuery(url.Values{ + "status": {"TODO", "IN_PROGRESS"}, + "priority": {"high", "medium"}, + }) + if err != nil { + t.Fatalf("parseListTasksQuery: %v", err) + } + if len(opts.Status) != 2 || opts.Status[0] != "TODO" || opts.Status[1] != "IN_PROGRESS" { + t.Fatalf("Status = %v", opts.Status) + } + if len(opts.Priority) != 2 || opts.Priority[0] != "high" || opts.Priority[1] != "medium" { + t.Fatalf("Priority = %v", opts.Priority) + } +} + +func TestParseListTasksQuery_SortFieldExactEnumMatchCaseSensitive(t *testing.T) { + for _, valid := range []string{"updated_at", "created_at", "priority"} { + opts, err := parseListTasksQuery(url.Values{"sort": {valid}}) + if err != nil { + t.Fatalf("sort=%s: %v", valid, err) + } + if string(opts.SortField) != valid { + t.Fatalf("SortField = %q, want %q", opts.SortField, valid) + } + } + if _, err := parseListTasksQuery(url.Values{"sort": {"Updated_At"}}); !errors.Is(err, ErrInvalidListParams) { + t.Fatalf("case-mismatched sort: error = %v, want ErrInvalidListParams", err) + } + if _, err := parseListTasksQuery(url.Values{"sort": {"bogus"}}); !errors.Is(err, ErrInvalidListParams) { + t.Fatalf("unknown sort: error = %v, want ErrInvalidListParams", err) + } +} + +func TestParseListTasksQuery_OrderAscOverridesDefaultDesc(t *testing.T) { + opts, err := parseListTasksQuery(url.Values{"order": {"asc"}}) + if err != nil { + t.Fatalf("parseListTasksQuery: %v", err) + } + if opts.SortDesc { + t.Fatalf("SortDesc = true, want false for order=asc") + } +} + +func TestParseListTasksQuery_OrderInvalidValueRejected(t *testing.T) { + if _, err := parseListTasksQuery(url.Values{"order": {"descending"}}); !errors.Is(err, ErrInvalidListParams) { + t.Fatalf("error = %v, want ErrInvalidListParams", err) + } +} + +func TestParseListTasksQuery_LimitParsesInteger(t *testing.T) { + opts, err := parseListTasksQuery(url.Values{"limit": {"50"}}) + if err != nil { + t.Fatalf("parseListTasksQuery: %v", err) + } + if opts.Limit != 50 { + t.Fatalf("Limit = %d, want 50", opts.Limit) + } +} + +func TestParseListTasksQuery_LimitNonIntegerRejected(t *testing.T) { + if _, err := parseListTasksQuery(url.Values{"limit": {"fifty"}}); !errors.Is(err, ErrInvalidListParams) { + t.Fatalf("error = %v, want ErrInvalidListParams", err) + } +} + +func TestParseListTasksQuery_CursorAndCursorIDMustBothBePresentOrAbsent(t *testing.T) { + if _, err := parseListTasksQuery(url.Values{}); err != nil { + t.Fatalf("neither present: %v", err) + } + if _, err := parseListTasksQuery(url.Values{"cursor": {"v1"}, "cursor_id": {"task-1"}}); err != nil { + t.Fatalf("both present: %v", err) + } + if _, err := parseListTasksQuery(url.Values{"cursor": {"v1"}}); !errors.Is(err, ErrInvalidListParams) { + t.Fatalf("cursor only: error = %v, want ErrInvalidListParams", err) + } + if _, err := parseListTasksQuery(url.Values{"cursor_id": {"task-1"}}); !errors.Is(err, ErrInvalidListParams) { + t.Fatalf("cursor_id only: error = %v, want ErrInvalidListParams", err) + } +} + +func TestParseListTasksQuery_CursorValuesPassThroughVerbatim(t *testing.T) { + opts, err := parseListTasksQuery(url.Values{"cursor": {"2026-01-01"}, "cursor_id": {"task-9"}}) + if err != nil { + t.Fatalf("parseListTasksQuery: %v", err) + } + if opts.CursorValue != "2026-01-01" || opts.CursorID != "task-9" { + t.Fatalf("cursor = %q/%q", opts.CursorValue, opts.CursorID) + } +} + +func TestParseListTasksQuery_IncludeSystemBooleanStrict(t *testing.T) { + opts, err := parseListTasksQuery(url.Values{"include_system": {"true"}}) + if err != nil || !opts.IncludeSystem { + t.Fatalf("include_system=true: opts=%+v err=%v", opts, err) + } + opts, err = parseListTasksQuery(url.Values{"include_system": {"false"}}) + if err != nil || opts.IncludeSystem { + t.Fatalf("include_system=false: opts=%+v err=%v", opts, err) + } + if _, err := parseListTasksQuery(url.Values{"include_system": {"1"}}); !errors.Is(err, ErrInvalidListParams) { + t.Fatalf("include_system=1: error = %v, want ErrInvalidListParams", err) + } +} + +func TestToTaskListItems_MapsAllFields(t *testing.T) { + rows := []*sqlite.TaskRow{{ + ID: "task-1", WorkspaceID: "ws-1", Identifier: "KAN-1", Title: "Title", + Description: "Desc", Status: "TODO", Priority: "high", ParentID: "task-0", + ProjectID: "proj-1", AssigneeAgentProfileID: "agent-1", Labels: `["a"]`, + CreatedAt: "2026-01-01", UpdatedAt: "2026-01-02", IsSystem: true, + }} + items := toTaskListItems(rows) + if len(items) != 1 { + t.Fatalf("items = %d, want 1", len(items)) + } + got := items[0] + want := TaskListItem{ + ID: "task-1", WorkspaceID: "ws-1", Identifier: "KAN-1", Title: "Title", + Description: "Desc", Status: "TODO", Priority: "high", ParentID: "task-0", + ProjectID: "proj-1", AssigneeID: "agent-1", Labels: `["a"]`, + CreatedAt: "2026-01-01", UpdatedAt: "2026-01-02", IsSystem: true, + } + if got != want { + t.Fatalf("item = %+v, want %+v", got, want) + } +} + +func TestToTaskListItems_EmptyInputYieldsEmptySlice(t *testing.T) { + items := toTaskListItems(nil) + if items == nil || len(items) != 0 { + t.Fatalf("items = %#v, want empty non-nil slice", items) + } +} diff --git a/apps/backend/internal/office/runtime/tasks_list_test.go b/apps/backend/internal/office/runtime/tasks_list_test.go new file mode 100644 index 0000000000..dead295abf --- /dev/null +++ b/apps/backend/internal/office/runtime/tasks_list_test.go @@ -0,0 +1,284 @@ +package runtime + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "testing" + + "github.com/gin-gonic/gin" + "github.com/jmoiron/sqlx" + _ "github.com/mattn/go-sqlite3" + + settingsstore "github.com/kandev/kandev/internal/agent/settings/store" + "github.com/kandev/kandev/internal/common/logger" + "github.com/kandev/kandev/internal/office/agents" + "github.com/kandev/kandev/internal/office/models" + "github.com/kandev/kandev/internal/office/repository/sqlite" +) + +// fakeTaskFilteredLister is a TaskFilteredLister fake that records the +// workspace and options it was called with, and returns a canned result or +// error. +type fakeTaskFilteredLister struct { + calls int + workspaceIDs []string + opts []sqlite.ListTasksOptions + result *sqlite.ListTasksFilteredResult + err error +} + +func (f *fakeTaskFilteredLister) ListTasksFiltered( + _ context.Context, workspaceID string, opts sqlite.ListTasksOptions, +) (*sqlite.ListTasksFilteredResult, error) { + f.calls++ + f.workspaceIDs = append(f.workspaceIDs, workspaceID) + f.opts = append(f.opts, opts) + if f.err != nil { + return nil, f.err + } + if f.result != nil { + return f.result, nil + } + return &sqlite.ListTasksFilteredResult{}, nil +} + +// boardReadHarness wires a runtime handler around a taskless run (empty +// task_id claim) and an injected TaskFilteredLister, mirroring +// newRuntimeHandlerHarnessWithProjectManager but for the board-read route, +// which needs a taskless token and a lister dependency neither existing +// harness constructs. +type boardReadHarness struct { + router *gin.Engine + token string + runEvents *recordingRunEvents +} + +// newBoardReadHarness mints a taskless token (empty task_id) claiming +// claimWorkspaceID. The agent row itself always lives in a fixed real +// workspace, independent of claimWorkspaceID, so an empty-claim test case +// can still resolve the agent by ID. +func newBoardReadHarness(t *testing.T, caps Capabilities, claimWorkspaceID string, lister TaskFilteredLister) *boardReadHarness { + t.Helper() + gin.SetMode(gin.TestMode) + db, err := sqlx.Open("sqlite3", ":memory:") + if err != nil { + t.Fatalf("open sqlite: %v", err) + } + t.Cleanup(func() { _ = db.Close() }) + if _, _, err := settingsstore.Provide(db, db, nil); err != nil { + t.Fatalf("settings store init: %v", err) + } + repo, err := sqlite.NewWithDB(db, db, nil) + if err != nil { + t.Fatalf("new repo: %v", err) + } + agentSvc := agents.NewAgentService(repo, logger.Default(), nil) + agentSvc.SetAuth(agents.NewAgentAuth("board-read-test-key")) + agent := &models.AgentInstance{ + ID: "agent-1", + WorkspaceID: "ws-agent-home", + Name: "Coordinator", + Role: models.AgentRoleCEO, + } + if err := repo.CreateAgentInstance(context.Background(), agent); err != nil { + t.Fatalf("create agent: %v", err) + } + capabilityJSON, err := MarshalCapabilities(caps) + if err != nil { + t.Fatalf("marshal capabilities: %v", err) + } + token, err := agentSvc.MintRuntimeJWT("agent-1", "", claimWorkspaceID, "run-1", "sess-1", capabilityJSON) + if err != nil { + t.Fatalf("mint runtime token: %v", err) + } + runEvents := &recordingRunEvents{} + router := gin.New() + RegisterRoutes(router.Group(""), NewHandler( + agentSvc, + NewActions(ActionDependencies{Agents: agentSvc}), + nil, + runEvents, + nil, + nil, + lister, + )) + return &boardReadHarness{router: router, token: token, runEvents: runEvents} +} + +func (h *boardReadHarness) get(t *testing.T, path string) *httptest.ResponseRecorder { + t.Helper() + req := httptest.NewRequest(http.MethodGet, path, nil) + req.Header.Set("Authorization", "Bearer "+h.token) + resp := httptest.NewRecorder() + h.router.ServeHTTP(resp, req) + return resp +} + +func TestListTasks_TasklessRunWithCapabilitySucceeds(t *testing.T) { + lister := &fakeTaskFilteredLister{result: &sqlite.ListTasksFilteredResult{ + Tasks: []*sqlite.TaskRow{ + {ID: "task-a", WorkspaceID: "ws-1", Title: "Alpha", Status: "TODO", Priority: "medium"}, + }, + NextCursor: "cursor-1", + NextID: "task-a", + }} + h := newBoardReadHarness(t, Capabilities{CanListTasks: true}, "ws-1", lister) + + resp := h.get(t, "/runtime/tasks") + if resp.Code != http.StatusOK { + t.Fatalf("status = %d, want %d; body=%s", resp.Code, http.StatusOK, resp.Body.String()) + } + if lister.calls != 1 || lister.workspaceIDs[0] != "ws-1" { + t.Fatalf("lister calls/workspaces = %d/%v, want 1/[ws-1]", lister.calls, lister.workspaceIDs) + } + var decoded struct { + Tasks []TaskListItem `json:"tasks"` + NextCursor string `json:"next_cursor"` + NextID string `json:"next_id"` + } + if err := json.Unmarshal(resp.Body.Bytes(), &decoded); err != nil { + t.Fatalf("decode response: %v", err) + } + if len(decoded.Tasks) != 1 || decoded.Tasks[0].ID != "task-a" { + t.Fatalf("tasks = %+v", decoded.Tasks) + } + if decoded.NextCursor != "cursor-1" || decoded.NextID != "task-a" { + t.Fatalf("cursor = %q/%q", decoded.NextCursor, decoded.NextID) + } +} + +func TestListTasks_WithoutCapabilityDenied(t *testing.T) { + lister := &fakeTaskFilteredLister{} + h := newBoardReadHarness(t, Capabilities{}, "ws-1", lister) + + resp := h.get(t, "/runtime/tasks") + if resp.Code != http.StatusForbidden { + t.Fatalf("status = %d, want %d; body=%s", resp.Code, http.StatusForbidden, resp.Body.String()) + } + if lister.calls != 0 { + t.Fatalf("lister should not be called when capability is denied: %d", lister.calls) + } +} + +func TestListTasks_EmptyWorkspaceClaimRefusedBeforeQuery(t *testing.T) { + lister := &fakeTaskFilteredLister{} + h := newBoardReadHarness(t, Capabilities{CanListTasks: true}, "", lister) + + resp := h.get(t, "/runtime/tasks") + if resp.Code != http.StatusForbidden { + t.Fatalf("status = %d, want %d; body=%s", resp.Code, http.StatusForbidden, resp.Body.String()) + } + if lister.calls != 0 { + t.Fatalf("lister should not be called with an empty workspace claim: %d", lister.calls) + } +} + +func TestListTasks_InvalidParamRefusedBeforeQuery(t *testing.T) { + lister := &fakeTaskFilteredLister{} + h := newBoardReadHarness(t, Capabilities{CanListTasks: true}, "ws-1", lister) + + resp := h.get(t, "/runtime/tasks?sort=bogus") + if resp.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want %d; body=%s", resp.Code, http.StatusBadRequest, resp.Body.String()) + } + if lister.calls != 0 { + t.Fatalf("lister should not be called with an invalid parameter: %d", lister.calls) + } +} + +func TestListTasks_MalformedQueryRefusedBeforeQuery(t *testing.T) { + lister := &fakeTaskFilteredLister{} + h := newBoardReadHarness(t, Capabilities{CanListTasks: true}, "ws-1", lister) + + resp := h.get(t, "/runtime/tasks?limit=1;bad") + if resp.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want %d; body=%s", resp.Code, http.StatusBadRequest, resp.Body.String()) + } + if lister.calls != 0 { + t.Fatalf("lister should not be called with a malformed query: %d", lister.calls) + } +} + +func TestListTasks_RepeatableStatusFilterReachesLister(t *testing.T) { + lister := &fakeTaskFilteredLister{} + h := newBoardReadHarness(t, Capabilities{CanListTasks: true}, "ws-1", lister) + + resp := h.get(t, "/runtime/tasks?status=TODO&status=IN_PROGRESS") + if resp.Code != http.StatusOK { + t.Fatalf("status = %d, want %d; body=%s", resp.Code, http.StatusOK, resp.Body.String()) + } + if lister.calls != 1 { + t.Fatalf("lister calls = %d, want 1", lister.calls) + } + got := lister.opts[0].Status + if len(got) != 2 || got[0] != "TODO" || got[1] != "IN_PROGRESS" { + t.Fatalf("status opts = %v, want [TODO IN_PROGRESS]", got) + } +} + +func TestListTasks_ListerErrorSurfacesAsInternalError(t *testing.T) { + lister := &fakeTaskFilteredLister{err: errors.New("db unavailable")} + h := newBoardReadHarness(t, Capabilities{CanListTasks: true}, "ws-1", lister) + + resp := h.get(t, "/runtime/tasks") + if resp.Code != http.StatusInternalServerError { + t.Fatalf("status = %d, want %d; body=%s", resp.Code, http.StatusInternalServerError, resp.Body.String()) + } +} + +func TestListTasks_NoListerConfiguredFailsClosed(t *testing.T) { + h := newBoardReadHarness(t, Capabilities{CanListTasks: true}, "ws-1", nil) + + resp := h.get(t, "/runtime/tasks") + if resp.Code != http.StatusInternalServerError { + t.Fatalf("status = %d, want %d; body=%s", resp.Code, http.StatusInternalServerError, resp.Body.String()) + } +} + +func TestListTasks_AppendsActionRunEventOnSuccess(t *testing.T) { + lister := &fakeTaskFilteredLister{} + h := newBoardReadHarness(t, Capabilities{CanListTasks: true}, "ws-1", lister) + + resp := h.get(t, "/runtime/tasks") + if resp.Code != http.StatusOK { + t.Fatalf("status = %d, want %d; body=%s", resp.Code, http.StatusOK, resp.Body.String()) + } + assertActionRunEvent(t, h.runEvents, "list_tasks", "workspace", "ws-1") +} + +func TestListTasks_RepeatedIdenticalCallsAreNotDeduplicated(t *testing.T) { + lister := &fakeTaskFilteredLister{} + h := newBoardReadHarness(t, Capabilities{CanListTasks: true}, "ws-1", lister) + + for i := 0; i < 2; i++ { + resp := h.get(t, "/runtime/tasks") + if resp.Code != http.StatusOK { + t.Fatalf("call %d: status = %d, want %d; body=%s", i, resp.Code, http.StatusOK, resp.Body.String()) + } + } + if lister.calls != 2 { + t.Fatalf("lister calls = %d, want 2", lister.calls) + } + if len(h.runEvents.events) != 2 { + t.Fatalf("run events = %d, want 2 (no dedup)", len(h.runEvents.events)) + } + for _, event := range h.runEvents.events { + if event.eventType != "runtime.action" { + t.Fatalf("event = %#v, want eventType runtime.action", event) + } + } +} + +func TestListTasks_DeniedCapabilityAppendsDeniedRunEvent(t *testing.T) { + lister := &fakeTaskFilteredLister{} + h := newBoardReadHarness(t, Capabilities{}, "ws-1", lister) + + resp := h.get(t, "/runtime/tasks") + if resp.Code != http.StatusForbidden { + t.Fatalf("status = %d, want %d; body=%s", resp.Code, http.StatusForbidden, resp.Body.String()) + } + assertDeniedRunEvent(t, h.runEvents, "list_tasks", "workspace", "ws-1") +} diff --git a/apps/backend/internal/office/service/budget_admission.go b/apps/backend/internal/office/service/budget_admission.go index 618e7277b8..998e9e0a78 100644 --- a/apps/backend/internal/office/service/budget_admission.go +++ b/apps/backend/internal/office/service/budget_admission.go @@ -5,6 +5,7 @@ import ( "encoding/json" "errors" "strconv" + "strings" "time" "go.uber.org/zap" @@ -276,11 +277,12 @@ func (si *SchedulerIntegration) resolveRunProject( if err := json.Unmarshal([]byte(payload), &parsed); err != nil { return "", projectResolutionUnparseable } - if parsed.TaskID == "" { + taskID := strings.TrimSpace(parsed.TaskID) + if taskID == "" { return "", projectResolutionNone } - info, err := si.svc.repo.GetTaskBasicInfo(ctx, parsed.TaskID) + info, err := si.svc.repo.GetTaskBasicInfo(ctx, taskID) if err != nil { return "", projectResolutionLookupError } diff --git a/apps/backend/internal/office/service/budget_admission_test.go b/apps/backend/internal/office/service/budget_admission_test.go index dd84b9fc02..f839545494 100644 --- a/apps/backend/internal/office/service/budget_admission_test.go +++ b/apps/backend/internal/office/service/budget_admission_test.go @@ -573,6 +573,7 @@ func TestResolveRunProject(t *testing.T) { {"empty payload", "", "", service.ProjectResolutionNoneForTest}, {"empty object payload", "{}", "", service.ProjectResolutionNoneForTest}, {"no task_id key", `{"other":"field"}`, "", service.ProjectResolutionNoneForTest}, + {"whitespace-only task_id", `{"task_id":" "}`, "", service.ProjectResolutionNoneForTest}, {"task resolves with no project", `{"task_id":"task-no-project"}`, "", service.ProjectResolutionNoneForTest}, {"task resolves with a project", `{"task_id":"task-with-project"}`, "project-1", service.ProjectResolutionFoundForTest}, {"unparseable payload", `{not-json`, "", service.ProjectResolutionUnparseableForTest}, diff --git a/apps/backend/internal/office/service/scheduler_integration.go b/apps/backend/internal/office/service/scheduler_integration.go index ab8d1d2913..b659dbc5b6 100644 --- a/apps/backend/internal/office/service/scheduler_integration.go +++ b/apps/backend/internal/office/service/scheduler_integration.go @@ -5,6 +5,7 @@ import ( "database/sql" "errors" "fmt" + "strings" "time" "go.uber.org/zap" @@ -350,9 +351,11 @@ func (si *SchedulerIntegration) prepareAndLaunch( agent *models.AgentInstance, taskID string, execCfg *ExecutorConfig, ) { runCtx, err := (&officeruntime.ContextBuilder{ - Agents: si.svc, - Runs: si.svc.repo, - Seats: si.svc, + Agents: si.svc, + Runs: si.svc.repo, + Seats: si.svc, + RunnerLister: si.svc.repo, + ScopeEvents: si.svc, }).BuildAndPersist(ctx, run) if err != nil { si.logger.Warn("runtime context build failed; retrying run", @@ -1028,9 +1031,13 @@ func (si *SchedulerIntegration) releaseCheckoutIfNeeded(ctx context.Context, run si.svc.releaseTaskCheckoutForRun(ctx, run) } -// extractTaskID parses the task_id from a run payload. +// extractTaskID parses the task_id from a run payload, trimmed so a +// whitespace-only value is treated as absent — the same "taskless" test +// officeruntime.ContextBuilder applies, so checkoutTask's task-bound/ +// taskless branch and the runtime's scope-derivation branch never disagree +// on which run has a task. func (si *SchedulerIntegration) extractTaskID(payload string) string { - return ParseRunPayload(payload)["task_id"] + return strings.TrimSpace(ParseRunPayload(payload)["task_id"]) } // extractProjectID looks up the project ID for a task in the payload. diff --git a/apps/backend/internal/office/service/scheduler_taskless_launch_test.go b/apps/backend/internal/office/service/scheduler_taskless_launch_test.go index d63c7178d3..0e40a18e98 100644 --- a/apps/backend/internal/office/service/scheduler_taskless_launch_test.go +++ b/apps/backend/internal/office/service/scheduler_taskless_launch_test.go @@ -74,6 +74,62 @@ func TestSchedulerTick_TasklessRunFailsInsteadOfFinishing(t *testing.T) { } } +// TestSchedulerTick_WhitespaceOnlyTaskIDTreatedAsTaskless is the Review +// round 3 regression test (R3REV-02): a run whose payload.task_id is +// non-empty but whitespace-only (e.g. " ") must be classified taskless +// end-to-end, the same as an absent task_id, per the terminology REQ-003 +// and REQ-004 share ("absent, empty, or whitespace-only ... empty after +// trimming"). Before the fix, extractTaskID returned the untrimmed value, +// so checkoutTask's `taskID == ""` short-circuit never fired; the run +// instead attempted an exact-match checkout against a task id that could +// never exist and silently requeued (scheduled a retry) forever, rather +// than reaching failTasklessRun's loud, immediate, correctly-classified +// failure — exactly the "runs forever, does nothing, reports nothing" +// pathology this card's WO-35 predecessor already fixed for the empty case. +func TestSchedulerTick_WhitespaceOnlyTaskIDTreatedAsTaskless(t *testing.T) { + mock := &mockTaskStarter{} + svc := newTestService(t, service.ServiceOptions{TaskStarter: mock}) + ctx := context.Background() + + agent := &models.AgentInstance{ + ID: "coordinator-r3rev02", + WorkspaceID: "ws-1", + Name: "coordinator-r3rev02", + Role: models.AgentRoleCEO, + Status: models.AgentStatusIdle, + ExecutorPreference: `{"type":"worktree"}`, + } + if err := svc.CreateAgentInstance(ctx, agent); err != nil { + t.Fatalf("create agent: %v", err) + } + + if _, err := svc.QueueRun(ctx, agent.ID, service.RunReasonRoutineTrigger, `{"task_id":" "}`, ""); err != nil { + t.Fatalf("queue: %v", err) + } + + service.RunSchedulerTick(svc, ctx) + + if mock.callCount() != 0 { + t.Fatalf("expected 0 StartTask calls for a whitespace-only task_id, got %d", mock.callCount()) + } + + runs, err := svc.ListRuns(ctx, "ws-1") + if err != nil { + t.Fatalf("list runs: %v", err) + } + if len(runs) != 1 { + t.Fatalf("run count = %d, want 1", len(runs)) + } + if runs[0].Status != service.RunStatusFailed { + t.Fatalf("run status = %q, want %q — a whitespace-only task_id must be classified "+ + "taskless and fail loudly on this tick, not silently requeue against a task id "+ + "that can never exist", runs[0].Status, service.RunStatusFailed) + } + if runs[0].ErrorMessage == "" { + t.Error("expected a non-empty error_message explaining the run could not launch") + } +} + // TestSchedulerTick_TasklessRunRecordsTerminalShape is the Testing round 3 // regression test. failTasklessRun calls repo.MarkRunFailed directly // (not through HandleAgentFailure), so it bypassed office_loop_terminal_total diff --git a/apps/backend/internal/runs/repository/sqlite/runs.go b/apps/backend/internal/runs/repository/sqlite/runs.go index e0091e89dc..c5f251f729 100644 --- a/apps/backend/internal/runs/repository/sqlite/runs.go +++ b/apps/backend/internal/runs/repository/sqlite/runs.go @@ -135,6 +135,38 @@ func (r *Repository) SetRunSessionID( return n > 0, nil } +// UpdateRunRuntimeSnapshotCAS is UpdateRunRuntimeSnapshot's compare-and-swap +// sibling: the write only takes effect while the run's current +// capabilities still equal prevCapabilities. Used to decide first-write- +// wins when two processors build runtime context for the same run +// concurrently (docs/specs/office/system-design/ +// taskless-coordinator-authority-01.md#first-write-wins-and-how). The +// comparison is a value compare rather than a SQL JSON extraction so it +// stays dialect-neutral across SQLite and Postgres. The bool reports +// whether this call's write took effect. +func (r *Repository) UpdateRunRuntimeSnapshotCAS( + ctx context.Context, + id string, + prevCapabilities string, + capabilities string, + inputSnapshot string, + sessionID string, +) (bool, error) { + result, err := r.db.ExecContext(ctx, r.db.Rebind(` + UPDATE runs + SET capabilities = ?, input_snapshot = ?, session_id = ? + WHERE id = ? AND COALESCE(capabilities, '') = ? + `), capabilities, inputSnapshot, sessionID, id, prevCapabilities) + if err != nil { + return false, err + } + affected, err := result.RowsAffected() + if err != nil { + return false, err + } + return affected > 0, nil +} + // UpdateRunPromptArtifacts persists the assembled prompt the agent // received and the continuation-summary content prepended at dispatch. // Called from the scheduler-integration after BuildAgentPrompt completes diff --git a/apps/backend/internal/runs/repository/sqlite/runs_snapshot_cas_test.go b/apps/backend/internal/runs/repository/sqlite/runs_snapshot_cas_test.go new file mode 100644 index 0000000000..9aebbdbeb4 --- /dev/null +++ b/apps/backend/internal/runs/repository/sqlite/runs_snapshot_cas_test.go @@ -0,0 +1,81 @@ +package sqlite_test + +import ( + "context" + "testing" + + "github.com/kandev/kandev/internal/office/models" +) + +// TestUpdateRunRuntimeSnapshotCAS_WinsWhenPrevMatches covers the ordinary +// first-writer case: the run's current capabilities equal prevCapabilities, +// so the write takes effect and the bool reports true. +func TestUpdateRunRuntimeSnapshotCAS_WinsWhenPrevMatches(t *testing.T) { + repo := newTestRepo(t) + ctx := context.Background() + run := mustCreateRun(t, repo, &models.Run{ + ID: "run-cas-win", AgentProfileID: "agent-1", Reason: "heartbeat", + Capabilities: `{"task_scope_source":""}`, + }) + + won, err := repo.UpdateRunRuntimeSnapshotCAS( + ctx, run.ID, `{"task_scope_source":""}`, `{"task_scope_source":"runner_set"}`, `{"in":"new"}`, "sess-1", + ) + if err != nil { + t.Fatalf("UpdateRunRuntimeSnapshotCAS: %v", err) + } + if !won { + t.Fatal("expected CAS to win when prevCapabilities matches") + } + + got := mustGetRun(t, repo, run.ID) + checkString(t, "capabilities", got.Capabilities, `{"task_scope_source":"runner_set"}`) + checkString(t, "input_snapshot", got.InputSnapshot, `{"in":"new"}`) + checkString(t, "session_id", got.SessionID, "sess-1") +} + +// TestUpdateRunRuntimeSnapshotCAS_LosesWhenPrevStale covers the race: a +// second processor already wrote a different capabilities value, so this +// call's prevCapabilities is stale and the write must not take effect. +func TestUpdateRunRuntimeSnapshotCAS_LosesWhenPrevStale(t *testing.T) { + repo := newTestRepo(t) + ctx := context.Background() + run := mustCreateRun(t, repo, &models.Run{ + ID: "run-cas-lose", AgentProfileID: "agent-1", Reason: "heartbeat", + Capabilities: `{"task_scope_source":"runner_set","allowed_task_ids":["t1"]}`, + }) + + won, err := repo.UpdateRunRuntimeSnapshotCAS( + ctx, run.ID, `{"task_scope_source":""}`, `{"task_scope_source":"runner_set","allowed_task_ids":["t2"]}`, `{}`, "sess-2", + ) + if err != nil { + t.Fatalf("UpdateRunRuntimeSnapshotCAS: %v", err) + } + if won { + t.Fatal("expected CAS to lose when prevCapabilities is stale") + } + + got := mustGetRun(t, repo, run.ID) + checkString(t, "capabilities unchanged", got.Capabilities, `{"task_scope_source":"runner_set","allowed_task_ids":["t1"]}`) + checkString(t, "session_id unchanged", got.SessionID, "") +} + +// TestUpdateRunRuntimeSnapshotCAS_UnaffectedRunsUntouched proves the swap +// is scoped to the target row only. +func TestUpdateRunRuntimeSnapshotCAS_UnaffectedRunsUntouched(t *testing.T) { + repo := newTestRepo(t) + ctx := context.Background() + run := mustCreateRun(t, repo, &models.Run{ + ID: "run-cas-a", AgentProfileID: "agent-1", Reason: "heartbeat", Capabilities: `{}`, + }) + other := mustCreateRun(t, repo, &models.Run{ + ID: "run-cas-b", AgentProfileID: "agent-2", Reason: "heartbeat", Capabilities: `{"untouched":true}`, + }) + + if _, err := repo.UpdateRunRuntimeSnapshotCAS(ctx, run.ID, `{}`, `{"cap":"new"}`, `{}`, "sess"); err != nil { + t.Fatalf("UpdateRunRuntimeSnapshotCAS: %v", err) + } + + untouched := mustGetRun(t, repo, other.ID) + checkString(t, "other capabilities", untouched.Capabilities, `{"untouched":true}`) +} diff --git a/docs/plans/office-taskless-coordinator-authority/plan.md b/docs/plans/office-taskless-coordinator-authority/plan.md new file mode 100644 index 0000000000..eb45ee7c27 --- /dev/null +++ b/docs/plans/office-taskless-coordinator-authority/plan.md @@ -0,0 +1,165 @@ +--- +created: 2026-09-06 +status: implemented +requirements: + - REQ-OFFICE-COORDINATOR-AUTHORITY-001 + - REQ-OFFICE-COORDINATOR-AUTHORITY-002 + - REQ-OFFICE-COORDINATOR-AUTHORITY-003 + - REQ-OFFICE-COORDINATOR-AUTHORITY-004 + - REQ-OFFICE-COORDINATOR-AUTHORITY-005 +system_design: + - ../../specs/office/system-design/taskless-coordinator-authority-01.md + - ../../specs/office/system-design/taskless-coordinator-authority-02.md +legacy_specs: [] +--- + +# Implementation Plan: Taskless Coordinator Authority + +## Overview + +The pre-installed "Coordinator heartbeat" routine is a taskless (no +`task_template`) scheduled run whose job is to monitor the workspace, surface +blockers, and react to events with no human driving the loop. This change adds +the authority layer for a taskless run with a runtime session. The scheduler +still refuses a taskless launch, so session creation remains separate work. +The old runtime capability vocabulary had no board-read key, and a taskless +run's task-mutation scope was computed as `AllowedTaskIDs = [""]`, which +matched no real task id or wildcard. + +This plan implements +[`taskless-coordinator-authority-01.md`](../../specs/office/system-design/taskless-coordinator-authority-01.md) +(capability vocabulary, task-scope derivation, annotation predicate) and +[`-02.md`](../../specs/office/system-design/taskless-coordinator-authority-02.md) +(board-read wire contract) end to end in a single work order: a new +`list_tasks` capability and `GET /runtime/tasks` endpoint scoped strictly to +the run token's workspace claim, a materialized "runner set" task scope for +taskless runs in place of the dead `[""]` placeholder, and a narrow +workspace-scoped annotation right (`post_comment` on any task in-workspace) +for taskless runs only, with state mutation staying limited to task scope +exactly as today. + +## Scope + +### In scope + +- `CapabilityListTasks` in the closed capability vocabulary, granted + unconditionally by `FromAgent`. +- `GET /runtime/tasks`: capability-gated, paginated, ordered, deterministic + board read whose workspace comes only from the signed run token's claim. +- Taskless task-scope materialization from the agent's runner set (bounded, + deterministically ordered, computed once per run, reused verbatim on + re-mint via a compare-and-swap guard against concurrent first-build races). +- `canAnnotateTask`: taskless runs may `post_comment` on any task in their own + workspace; task-bound runs keep their existing own-task-only reach. +- No existence oracle: annotation and mutation paths on an out-of-scope or + cross-workspace task return the same denial regardless of whether the task + exists. +- `agentctl kandev tasks list` switched to the new runtime endpoint. + +### Out of scope + +- The taskless session seam (how the run's session is created in the first + place) — tracked separately, not part of this diff. +- Workflow-step-move, task-archive, or step-decision capabilities — these stay + explicitly denied. +- Widening a taskless run's *mutation* authority to its whole workspace — only + board-read and annotation are workspace-scoped; state mutation stays + limited to the run's own runner set. + +## Technical approach + +See the system design documents for the full contract. In short: + +- `office/runtime/capabilities.go` adds the `list_tasks` key to the closed + vocabulary and trims/discards empty or wildcard entries passed to + `WithTaskScope`. +- `office/runtime/context_builder.go` adds scope derivation + (`deriveScope`/`deriveRunnerSet`/`reusePersistedTaskScope`), a + CAS-guarded persistence path (`BuildAndPersist` / + `persistWithCAS`, capped retries), and a scope-truncation/unavailable audit + event. +- `office/runtime/actions.go` splits the pre-existing mutation-authorization + check (`authorizeTaskWorkspace`, used by `UpdateTaskStatus` / + `CreateSubtask`) from the new annotation predicate (`canAnnotateTask`, used + only by `PostComment`), which branches on task-bound (own-task-only) vs. + taskless (workspace-scoped) runs. +- `office/runtime/tasks_list.go` implements the `GET /runtime/tasks` handler: + capability check, then workspace-claim check, then parameter parsing, then + the query — in that order, so a malformed request from an unauthorized + caller is rejected on capability first. +- `internal/runs/repository/sqlite/runs.go` adds + `UpdateRunRuntimeSnapshotCAS` for the compare-and-swap persistence path. +- `office/service/budget_admission.go`'s `resolveRunProject` trims `task_id` + before the emptiness check, closing a regression a newer upstream + pre-launch budget gate would otherwise have hit against a whitespace-only + `task_id`. + +## Tests + +| Acceptance criteria | Evidence | +| --- | --- | +| `AC-OFFICE-COORDINATOR-AUTHORITY-001.*` | `internal/office/runtime/capabilities_test.go`, `internal/office/runtime/tasks_list_test.go`, `internal/office/runtime/handler_test.go` — capability gating, audit logging of accepted/denied calls | +| `AC-OFFICE-COORDINATOR-AUTHORITY-002.*` | `internal/office/runtime/tasks_list_query_test.go`, `internal/office/runtime/tasks_list_test.go` — ordering, pagination bounds, determinism | +| `AC-OFFICE-COORDINATOR-AUTHORITY-003.*` | `internal/office/runtime/scope_derivation_test.go`, `internal/office/runtime/context_builder_test.go`, `internal/runs/repository/sqlite/runs_snapshot_cas_test.go` — runner-set materialization, capping/ordering, CAS-guarded persistence and reuse | +| `AC-OFFICE-COORDINATOR-AUTHORITY-004.*` | `internal/office/runtime/actions_annotation_test.go`, `internal/office/runtime/handler_taskless_annotation_test.go`, `internal/office/runtime/actions_test.go` — taskless workspace-scoped annotation, task-bound own-task-only annotation unchanged, no existence oracle | +| `AC-OFFICE-COORDINATOR-AUTHORITY-005.*` | `internal/office/runtime/capabilities_test.go`, `internal/office/runtime/context_test.go` — denied-authority invariants (no step-move/archive/decision keys; wildcard scope never matches; whitespace `task_id` trimmed) | + +Also: `internal/office/service/scheduler_taskless_launch_test.go` (taskless +launch integration), `internal/office/service/budget_admission_test.go` +(whitespace `task_id` trim), `apps/backend/cmd/agentctl/kandev_tasks_test.go` +(CLI switched to the new endpoint). + +## E2E tests + +None. This is a backend runtime-authorization contract with no `apps/web` +change (`git diff --stat -- apps/web` is empty for this diff). + +## Work orders + +- [done] [Task 01: Implement Taskless Coordinator Authority](task-01-implement-taskless-coordinator-authority.md) + +## Dependency order + +```text +Task 01 +``` + +Single task; the capability, scope-derivation, and annotation changes land +together because the scope-derivation change is what makes the annotation +predicate's taskless branch meaningful (an annotation right with no +materialized scope to reason about would be untestable in isolation). + +## Verification results + +- `go build ./...`, `go vet ./...` — clean. +- `go test -count=1 ./internal/office/... ./internal/runs/... ./cmd/agentctl/...` — all packages `ok`. +- `go test -race -count=1 ./internal/office/runtime/... ./internal/office/repository/sqlite/... ./internal/office/service/... ./internal/runs/repository/sqlite/...` — all `ok`. +- `gofmt -l` on every changed Go file — clean. +- `make -C apps/backend lint` (golangci-lint) — 0 issues. +- `python3 scripts/lint-architecture.py --all` — clean. +- `python3 scripts/lint-spec-files.py --all` — all passed. +- Reviewed across 6 rounds (architecture/quality, security, test-rigor, and + an independent cross-vendor pass) with no open production-bug residual. + +## Risks + +- The taskless annotation widening (comment on any task in-workspace) is a + deliberate, narrow authority increase reviewed specifically for + existence-oracle and cross-workspace leakage; state-mutation authority is + unchanged in shape from today's task-bound behavior. +- The CAS-guarded scope persistence caps retries + (`maxScopeSwapAttempts = 3`); a reviewer should confirm the fail-closed + behavior on exhaustion (empty scope, not a stale or partial one) still + holds if that constant changes. + +## Open questions + +None outstanding. + +## Package handoff + +Implementation is complete on branch `feature/office-beta-taskless-6n8`. This +plan and its work order were added to satisfy the repository's PR +documentation coverage gate for the non-doc, non-test source files this diff +touches; the implementation itself predates this plan file and was developed +directly from the requirements and system-design documents linked above. diff --git a/docs/plans/office-taskless-coordinator-authority/task-01-implement-taskless-coordinator-authority.md b/docs/plans/office-taskless-coordinator-authority/task-01-implement-taskless-coordinator-authority.md new file mode 100644 index 0000000000..01f6819e4e --- /dev/null +++ b/docs/plans/office-taskless-coordinator-authority/task-01-implement-taskless-coordinator-authority.md @@ -0,0 +1,166 @@ +--- +id: "01-implement-taskless-coordinator-authority" +title: "Implement taskless coordinator authority" +status: done +wave: 1 +depends_on: [] +plan: "plan.md" +requirements: + - REQ-OFFICE-COORDINATOR-AUTHORITY-001 + - REQ-OFFICE-COORDINATOR-AUTHORITY-002 + - REQ-OFFICE-COORDINATOR-AUTHORITY-003 + - REQ-OFFICE-COORDINATOR-AUTHORITY-004 + - REQ-OFFICE-COORDINATOR-AUTHORITY-005 +acceptance_criteria: + - AC-OFFICE-COORDINATOR-AUTHORITY-001.1 + - AC-OFFICE-COORDINATOR-AUTHORITY-001.2 + - AC-OFFICE-COORDINATOR-AUTHORITY-001.3 + - AC-OFFICE-COORDINATOR-AUTHORITY-001.4 + - AC-OFFICE-COORDINATOR-AUTHORITY-001.5 + - AC-OFFICE-COORDINATOR-AUTHORITY-001.6 + - AC-OFFICE-COORDINATOR-AUTHORITY-001.7 + - AC-OFFICE-COORDINATOR-AUTHORITY-001.8 + - AC-OFFICE-COORDINATOR-AUTHORITY-001.9 + - AC-OFFICE-COORDINATOR-AUTHORITY-001.10 + - AC-OFFICE-COORDINATOR-AUTHORITY-001.11 + - AC-OFFICE-COORDINATOR-AUTHORITY-002.1 + - AC-OFFICE-COORDINATOR-AUTHORITY-002.2 + - AC-OFFICE-COORDINATOR-AUTHORITY-002.3 + - AC-OFFICE-COORDINATOR-AUTHORITY-002.4 + - AC-OFFICE-COORDINATOR-AUTHORITY-002.5 + - AC-OFFICE-COORDINATOR-AUTHORITY-002.6 + - AC-OFFICE-COORDINATOR-AUTHORITY-002.7 + - AC-OFFICE-COORDINATOR-AUTHORITY-002.8 + - AC-OFFICE-COORDINATOR-AUTHORITY-002.9 + - AC-OFFICE-COORDINATOR-AUTHORITY-002.10 + - AC-OFFICE-COORDINATOR-AUTHORITY-002.11 + - AC-OFFICE-COORDINATOR-AUTHORITY-002.12 + - AC-OFFICE-COORDINATOR-AUTHORITY-002.13 + - AC-OFFICE-COORDINATOR-AUTHORITY-003.1 + - AC-OFFICE-COORDINATOR-AUTHORITY-003.2 + - AC-OFFICE-COORDINATOR-AUTHORITY-003.3 + - AC-OFFICE-COORDINATOR-AUTHORITY-003.4 + - AC-OFFICE-COORDINATOR-AUTHORITY-003.5 + - AC-OFFICE-COORDINATOR-AUTHORITY-003.6 + - AC-OFFICE-COORDINATOR-AUTHORITY-003.7 + - AC-OFFICE-COORDINATOR-AUTHORITY-003.8 + - AC-OFFICE-COORDINATOR-AUTHORITY-003.9 + - AC-OFFICE-COORDINATOR-AUTHORITY-003.10 + - AC-OFFICE-COORDINATOR-AUTHORITY-003.11 + - AC-OFFICE-COORDINATOR-AUTHORITY-003.12 + - AC-OFFICE-COORDINATOR-AUTHORITY-003.13 + - AC-OFFICE-COORDINATOR-AUTHORITY-003.14 + - AC-OFFICE-COORDINATOR-AUTHORITY-003.15 + - AC-OFFICE-COORDINATOR-AUTHORITY-004.1 + - AC-OFFICE-COORDINATOR-AUTHORITY-004.2 + - AC-OFFICE-COORDINATOR-AUTHORITY-004.3 + - AC-OFFICE-COORDINATOR-AUTHORITY-004.4 + - AC-OFFICE-COORDINATOR-AUTHORITY-004.5 + - AC-OFFICE-COORDINATOR-AUTHORITY-004.6 + - AC-OFFICE-COORDINATOR-AUTHORITY-004.7 + - AC-OFFICE-COORDINATOR-AUTHORITY-004.8 + - AC-OFFICE-COORDINATOR-AUTHORITY-004.9 + - AC-OFFICE-COORDINATOR-AUTHORITY-004.10 + - AC-OFFICE-COORDINATOR-AUTHORITY-004.11 + - AC-OFFICE-COORDINATOR-AUTHORITY-004.12 + - AC-OFFICE-COORDINATOR-AUTHORITY-004.13 + - AC-OFFICE-COORDINATOR-AUTHORITY-005.1 + - AC-OFFICE-COORDINATOR-AUTHORITY-005.2 + - AC-OFFICE-COORDINATOR-AUTHORITY-005.3 + - AC-OFFICE-COORDINATOR-AUTHORITY-005.4 + - AC-OFFICE-COORDINATOR-AUTHORITY-005.5 + - AC-OFFICE-COORDINATOR-AUTHORITY-005.6 +system_design: + - ../../specs/office/system-design/taskless-coordinator-authority-01.md + - ../../specs/office/system-design/taskless-coordinator-authority-02.md +--- + +# Task 01: Implement Taskless Coordinator Authority + +## Summary + +Add a governed board-read capability and a materialized task-mutation scope +for taskless Office runs, plus a narrow workspace-scoped annotation right, so +the pre-installed "Coordinator heartbeat" routine (and any other taskless +scheduled routine) can enumerate actionable board state and flag blockers +instead of launching into a run that can see and change nothing. + +## In scope + +- `CapabilityListTasks` added to the closed capability vocabulary + (`office/runtime/capabilities.go`), granted unconditionally by `FromAgent`; + `WithTaskScope` trims and discards empty/whitespace/wildcard entries. +- `GET /runtime/tasks` (`office/runtime/tasks_list.go`, + `office/runtime/handler.go`, `office/routes.go`): capability check, then + workspace-claim check, then parameter parsing, then the query; ordered, + paginated, deterministic; workspace resolved only from the signed run + token's claim. +- Taskless task-scope materialization + (`office/runtime/context_builder.go`): `deriveScope` / + `deriveRunnerSet` / `reusePersistedTaskScope`, capped and deterministically + ordered (`scopeRunnerSetCap = 500`), computed once per run and persisted + via `BuildAndPersist` with a CAS-guarded retry + (`persistWithCAS`, `maxScopeSwapAttempts = 3`) against concurrent + first-build races; `runtime.scope_truncated` / `runtime.scope_unavailable` + audit events. +- `office/runtime/context.go`: `CanMutateTask` refuses an empty or wildcard + `taskID` before the self-match check; new `TaskScopeSource` provenance + field. +- `office/runtime/actions.go`: the pre-existing mutation-authorization check + is named `authorizeTaskWorkspace` (used by `UpdateTaskStatus` / + `CreateSubtask`, unchanged in behavior); a new `canAnnotateTask` (used only + by `PostComment`) refuses a wildcard target and branches on task-bound + (own-task-only, matching today) vs. taskless (workspace-scoped via + `Tasks.GetTaskWorkspaceID`, fails closed on a lookup error or missing row). +- `internal/runs/repository/sqlite/runs.go`: + `UpdateRunRuntimeSnapshotCAS(ctx, id, prevCapabilities, capabilities, + inputSnapshot, sessionID)` — conditional `UPDATE ... WHERE id = ? AND + COALESCE(capabilities, '') = ?`. +- `office/service/budget_admission.go`: `resolveRunProject` trims `task_id` + before the emptiness check, matching the taskless definition used + elsewhere ("absent, empty, or whitespace-only, i.e. empty after + trimming"). +- `cmd/agentctl/kandev_tasks.go`: `agentctl kandev tasks list` calls the new + runtime endpoint, one flag per accepted query parameter. + +## Out of scope + +- The taskless session seam (tracked separately). +- Workflow-step-move, task-archive, or step-decision capabilities. +- Widening taskless *mutation* authority beyond the runner set. + +## Results + +- `go build ./...`, `go vet ./...` — clean. +- `go test -count=1 ./internal/office/... ./internal/runs/... ./cmd/agentctl/...` — all `ok`. +- `go test -race -count=1 ./internal/office/runtime/... ./internal/office/repository/sqlite/... ./internal/office/service/... ./internal/runs/repository/sqlite/...` — all `ok`. +- `gofmt -l` — clean on every changed file. +- `make -C apps/backend lint` — 0 issues. +- `python3 scripts/lint-architecture.py --all` — clean. +- `python3 scripts/lint-spec-files.py --all` — all passed. +- Reviewed across 6 rounds (architecture/quality, security, test-rigor, and + an independent cross-vendor pass); no open production-bug residual. + +## Tests + +- `internal/office/runtime/capabilities_test.go`, + `internal/office/runtime/tasks_list_test.go`, + `internal/office/runtime/tasks_list_query_test.go`, + `internal/office/runtime/handler_test.go` — board-read capability gating, + ordering, pagination, workspace-claim scoping (REQ-001, REQ-002). +- `internal/office/runtime/scope_derivation_test.go`, + `internal/office/runtime/context_builder_test.go`, + `internal/office/runtime/context_test.go`, + `internal/runs/repository/sqlite/runs_snapshot_cas_test.go` — runner-set + materialization, capping/ordering, CAS-guarded persistence and reuse, + fail-closed on exhaustion (REQ-003, REQ-005). +- `internal/office/runtime/actions_annotation_test.go`, + `internal/office/runtime/handler_taskless_annotation_test.go`, + `internal/office/runtime/actions_test.go` — taskless workspace-scoped + annotation, task-bound own-task-only annotation unchanged, no existence + oracle (REQ-004). +- `internal/office/service/scheduler_taskless_launch_test.go`, + `internal/office/service/budget_admission_test.go` — taskless launch + integration and the whitespace `task_id` trim. +- `apps/backend/cmd/agentctl/kandev_tasks_test.go` — CLI switched to the new + runtime endpoint. diff --git a/docs/public/automation-and-mcp.md b/docs/public/automation-and-mcp.md index 971aa7e5cd..3a23e3a38f 100644 --- a/docs/public/automation-and-mcp.md +++ b/docs/public/automation-and-mcp.md @@ -763,6 +763,19 @@ $KANDEV_CLI kandev task create \ Project list and create operations are forced to the workspace in the validated Office run token; the agent cannot select another workspace in these commands. Office runs cannot create or administer workspaces. Create additional workspaces through Kandev's user-facing setup and settings surfaces. +An Office run can read tasks in its signed workspace with: + +```bash +$KANDEV_CLI kandev tasks list +``` + +The command supports repeatable `--status` and `--priority` filters, plus +`--assignee`, `--project`, `--sort`, `--order`, `--limit`, `--cursor`, +`--cursor-id`, and `--include-system`. Use `--cursor` and `--cursor-id` +together to continue a page walk. The workspace comes from the short-lived +runtime token, so `KANDEV_WORKSPACE_ID` is not required for this command. +Taskless launch and session creation remain separate Office scheduler work. +
diff --git a/docs/specs/office/requirements/taskless-coordinator-authority.md b/docs/specs/office/requirements/taskless-coordinator-authority.md new file mode 100644 index 0000000000..cc4bf91008 --- /dev/null +++ b/docs/specs/office/requirements/taskless-coordinator-authority.md @@ -0,0 +1,322 @@ +--- +status: active +system: office +created: 2026-09-06 +owners: + - kandev +--- + +# Taskless Coordinator Authority Requirements + +## Overview + +A lightweight (taskless) routine fire is specified to produce a real agent run +(`../system-design/scheduler-01.md`, "Heavy vs lightweight routines"). The pre-installed +"Coordinator heartbeat" routine is that shape: empty `task_template`, cron `*/5 * * * *`, +and the job "monitor the workspace, surface blockers, and react to events while no human +is driving the loop." + +That run cannot do its job today, and the reason is **not** the missing session seam: two +runtime-contract defects stop it either way, both evidenced in the design's +[current-state sections](../system-design/taskless-coordinator-authority-01.md#the-read-that-already-exists): +the capability vocabulary holds no task-enumeration key, though the board read is already +reachable ungoverned via the dashboard route; and a taskless run's task scope is +`[""]`, which matches nothing. + +This capability makes a scheduled taskless run's authority explicit and enforced. It does +not create the session seam, launch the run, or change a task-bound run's mutation or +annotation authority beyond the two exceptions named in +AC-OFFICE-COORDINATOR-AUTHORITY-005.5. +[Prior art](../system-design/taskless-coordinator-authority-01.md#prior-art) and +[concurrency](../system-design/taskless-coordinator-authority-01.md#concurrency-and-revocation) +are in the design. + +## Terminology + +- **Taskless run:** a `runs` row whose `payload.task_id` is absent, empty, or + whitespace-only, i.e. empty after trimming. This one test gates both the scope + derivation of REQ-003 and the annotation branch of REQ-004, and is applied before + either branch. +- **Task-bound run:** any run that is not taskless. +- **Runner set:** the tasks the run's agent is already responsible for in the run's + workspace: runner projection resolves to that agent, `state` in `TODO` or + `IN_PROGRESS`, not archived, not automation-origin, **and `workspace_id` is the run's + workspace**. The first four clauses are `CountActionableTasksForAgent`'s; the + workspace clause is **not** in it and is added here + ([derivation](../system-design/taskless-coordinator-authority-01.md#task-scope-derivation)). +- **Board read:** enumerating workspace tasks, mutating none. +- **Annotation:** appending a task comment. Additive, attributed, changes no task field. +- **State mutation:** changing a task's status, or creating a parented task. +- **Scope snapshot:** the task-scope list materialized into `runs.capabilities` and the + run JWT, beside the already-frozen capability booleans, with a marker naming which + source produced it and whether that source is final. + +## Requirements + +### REQ-OFFICE-COORDINATOR-AUTHORITY-001: Board read is a granted, governed capability + +**Intent:** A scheduled coordinator must be able to enumerate the tasks it coordinates, +and that enumeration must be authorized, workspace-pinned from the token, and recorded +like every other runtime action. + +**User story:** As a workspace owner, I want an unattended agent's board reads gated and +audited like its writes. + +#### Acceptance criteria + +- **AC-OFFICE-COORDINATOR-AUTHORITY-001.1:** The capability vocabulary shall include a + `list_tasks` key, and `Allows("list_tasks")` shall report the granted state rather + than falling through to the closed-vocabulary default. +- **AC-OFFICE-COORDINATOR-AUTHORITY-001.2:** `FromAgent` shall grant `list_tasks` for + every agent role, independent of `permissions`. +- **AC-OFFICE-COORDINATOR-AUTHORITY-001.3:** The runtime action surface shall expose a + board-read endpoint resolving its workspace from the run token's claim, never from a + caller-supplied value. +- **AC-OFFICE-COORDINATOR-AUTHORITY-001.4:** When a run without `list_tasks` calls that + endpoint, the system shall refuse with `ErrCapabilityDenied` (`403`) and append a + `runtime.denied` event with `action=list_tasks`. +- **AC-OFFICE-COORDINATOR-AUTHORITY-001.5:** On success the system shall append a + `runtime.action` event with `action=list_tasks`. +- **AC-OFFICE-COORDINATOR-AUTHORITY-001.6:** When the run token carries an empty + workspace claim, the system shall refuse with `ErrWorkspaceOutOfScope` (`403`) and + return no rows. +- **AC-OFFICE-COORDINATOR-AUTHORITY-001.7:** A board read shall succeed for a taskless + run and shall not be restricted to the run's runner set. +- **AC-OFFICE-COORDINATOR-AUTHORITY-001.8:** `agentctl kandev tasks list` shall call the + runtime board-read endpoint, not the dashboard workspace task route. +- **AC-OFFICE-COORDINATOR-AUTHORITY-001.9:** The dashboard workspace task route shall + remain available to browser callers, unchanged. +- **AC-OFFICE-COORDINATOR-AUTHORITY-001.10:** `agentctl kandev tasks list` shall expose + one flag per query parameter the endpoint accepts, including page size, sort column, + sort direction, both cursor components and the system-workflow opt-in, and a repeatable + flag for every parameter the design's table marks repeatable. +- **AC-OFFICE-COORDINATOR-AUTHORITY-001.11:** Board-read events shall not be + deduplicated: each accepted read shall append exactly one `runtime.action` and each + refusal exactly one `runtime.denied`, and an identical repeat shall append a further + row rather than coalescing with the first. + +### REQ-OFFICE-COORDINATOR-AUTHORITY-002: Board read is ordered, bounded, and deterministic + +**Intent:** An unattended reader pages with no human to notice a duplicated or skipped +row, so ordering must be total, page size bounded by contract, and malformed parameters +must fail loudly rather than silently change the page. + +**User story:** As a coordinator agent, I want a second page that continues exactly where +the first ended, so I neither double-act nor skip a task. + +Parameter names, response fields and parse order are +[declared in the design](../system-design/taskless-coordinator-authority-02.md#request-and-response-contract). + +#### Acceptance criteria + +- **AC-OFFICE-COORDINATOR-AUTHORITY-002.1:** A board read shall order results by a named + sort column and break ties on the `tasks.id` column in the same direction, so the + ordering is total. +- **AC-OFFICE-COORDINATOR-AUTHORITY-002.2:** When no sort column is requested, the system + shall sort by `tasks.updated_at` descending, and shall request that direction + explicitly rather than relying on a repository default. +- **AC-OFFICE-COORDINATOR-AUTHORITY-002.3:** When a sort column outside the allow-list + (`updated_at`, `created_at`, `priority`) is requested, the system shall refuse with + `ErrInvalidListParams` (`400`) and return no rows. +- **AC-OFFICE-COORDINATOR-AUTHORITY-002.4:** When no page size is requested, or one above + 500 or at or below zero is, the system shall return at most 100 rows. +- **AC-OFFICE-COORDINATOR-AUTHORITY-002.5:** When more rows match than the page size, the + system shall return a continuation cursor pairing the tail row's sort value with its + `tasks.id`, as two separately addressable response fields. +- **AC-OFFICE-COORDINATOR-AUTHORITY-002.6:** On the final page the system shall return an + empty continuation cursor. +- **AC-OFFICE-COORDINATOR-AUTHORITY-002.7:** When no task matches, the system shall return + `200 OK` with an empty list, an empty cursor and no error. +- **AC-OFFICE-COORDINATOR-AUTHORITY-002.8:** A board read shall unconditionally exclude + archived, ephemeral and automation-origin tasks, and shall exclude tasks in + kandev-managed system workflows unless the caller opts in through the declared opt-in + parameter. Only the system-workflow exclusion has an opt-in. +- **AC-OFFICE-COORDINATOR-AUTHORITY-002.9:** A board read shall take the same ordered, + bounded path whether or not filter parameters were supplied. +- **AC-OFFICE-COORDINATOR-AUTHORITY-002.10:** A board read shall mutate no task, and + repeating it with the same parameters shall return the same page while the matched rows + are unchanged. +- **AC-OFFICE-COORDINATOR-AUTHORITY-002.11:** When the query fails, the system shall + return an error, no rows and no cursor, never a partial page. +- **AC-OFFICE-COORDINATOR-AUTHORITY-002.12:** The endpoint shall accept a continuation + cursor as its two components and resume strictly after the row they identify, under the + sort column and direction supplied on that same request. The endpoint shall neither + encode nor verify the sort that issued a cursor; reusing one under a different sort is a + caller error it does not detect. +- **AC-OFFICE-COORDINATOR-AUTHORITY-002.13:** When any of these holds, the system shall + refuse the whole read with `ErrInvalidListParams` (`400`), return no rows, and shall not + serve a partially-parsed page even when other parameters were valid: only one cursor + component supplied; a non-integer page size; a sort direction outside `asc` / `desc`; a + non-boolean opt-in; or a repeat of a parameter the design's parameter table marks + single-valued. A parameter that table marks repeatable shall instead match any of its + supplied values, and shall not be an error. An empty value shall be treated as absent, + so an empty `cursor` beside a non-empty `cursor_id` is the one-component refusal above; + enumerated values shall match exactly, with no case folding or trimming. + +### REQ-OFFICE-COORDINATOR-AUTHORITY-003: A taskless run's task scope is materialized, not empty + +**Intent:** `AllowedTaskIDs = [""]` cannot match anything while presenting as a grant. +Replace it with an honest scope: empty when the run has no writable tasks, otherwise the +runner set — not the workspace: `tasks-01.md` already decided workspace membership +alone must not authorize mutating another task. + +**User story:** As a workspace owner, I want an unattended run's write authority readable +from `runs.capabilities`. + +#### Acceptance criteria + +- **AC-OFFICE-COORDINATOR-AUTHORITY-003.1:** `WithTaskScope` shall discard empty and + whitespace-only task identifiers, so no scope list contains an entry that can never + match. +- **AC-OFFICE-COORDINATOR-AUTHORITY-003.2:** When a run is taskless, the task scope shall + be materialized from the runner set at run-claim time. +- **AC-OFFICE-COORDINATOR-AUTHORITY-003.3:** When a run is task-bound, the task scope + shall be exactly its `task_id` with surrounding whitespace removed, with no runner-set + expansion, and the run context's own task identifier shall carry that same trimmed + value. +- **AC-OFFICE-COORDINATOR-AUTHORITY-003.4:** The materialized scope shall be ordered by + `tasks.updated_at` descending with `tasks.id` descending as the tiebreak, and capped at + 500 entries. +- **AC-OFFICE-COORDINATOR-AUTHORITY-003.5:** When the runner set exceeds the cap, the + system shall retain the first 500 under that ordering and, per + AC-OFFICE-COORDINATOR-AUTHORITY-003.14, append a `runtime.scope_truncated` event at + level `warn` recording the cap and the true total. +- **AC-OFFICE-COORDINATOR-AUTHORITY-003.6:** When the runner-set query fails, the system + shall fail closed with an empty task scope, append a `runtime.scope_unavailable` event + at level `warn` recording the error per AC-OFFICE-COORDINATOR-AUTHORITY-003.14, and + still build the run context. +- **AC-OFFICE-COORDINATOR-AUTHORITY-003.7:** When the runner set is empty, the task scope + shall be empty and every task-scoped mutation shall be refused with `ErrTaskOutOfScope`. +- **AC-OFFICE-COORDINATOR-AUTHORITY-003.8:** The materialized scope shall be serialized + into `runs.capabilities` and `runs.input_snapshot` and carried in the run JWT, as the + capability booleans already are. +- **AC-OFFICE-COORDINATOR-AUTHORITY-003.9:** The scope snapshot shall be taken once per + run and, once final, not recomputed for that run's life, so a task assigned to the agent + mid-run is not writable by that run. +- **AC-OFFICE-COORDINATOR-AUTHORITY-003.10:** The system shall not assign + `WildcardTaskScope` to a run on the basis that the run is taskless. +- **AC-OFFICE-COORDINATOR-AUTHORITY-003.11:** When a run token is re-minted for an + existing run carrying a final scope snapshot, the system shall reproduce it, not + re-derive the runner set. +- **AC-OFFICE-COORDINATOR-AUTHORITY-003.12:** The serialized snapshot shall record which + source produced the scope — run payload or runner set, both **final**, or unavailable + runner set, **provisional** — and that marker shall govern every later context build for + the run: (a) a run carrying a final marker shall have its task scope reused verbatim, + with no runner-set query; (b) a run whose marker is absent, provisional, unrecognized, or + in a snapshot that cannot be parsed — including one persisted before this capability + shipped — shall have its scope derived afresh and persisted with its marker, so a + transient runner-set failure is retried rather than frozen; (c) when two processors build context for + one run, the first persisted final marker shall win and the second shall reuse rather + than overwrite it; (d) reuse shall apply to the task scope only, and capability booleans + shall keep being derived from the agent on every build, unchanged from today. +- **AC-OFFICE-COORDINATOR-AUTHORITY-003.13:** A runner-set-materialized scope shall + contain only tasks whose workspace is the run's workspace. The task-bound scope of + AC-OFFICE-COORDINATOR-AUTHORITY-003.3 is not workspace-filtered, unchanged from today. +- **AC-OFFICE-COORDINATOR-AUTHORITY-003.14:** A scope event shall be appended only by the + build whose scope becomes the run's persisted scope, and only when an appender is + configured; a build that loses AC-OFFICE-COORDINATOR-AUTHORITY-003.12(c)'s race, or has + no appender, shall append none and shall still build the run context. +- **AC-OFFICE-COORDINATOR-AUTHORITY-003.15:** When the runner set cannot be derived — no + reader configured, or the run's workspace empty after trimming — the system shall issue + no query and shall take AC-OFFICE-COORDINATOR-AUTHORITY-003.6's outcome, never an empty + final runner set, recording the unmet condition in place of a query error. + +### REQ-OFFICE-COORDINATOR-AUTHORITY-004: A taskless run's annotation is workspace-scoped; state mutation is not + +**Intent:** Surfacing a blocker is the scheduled coordinator's stated job and requires +commenting on a task it does not run. Changing that task's state does not, and a +task-bound worker needs neither. + +**User story:** As a coordinator agent, I want to comment on any task in my workspace to +flag a blocker, without being able to re-status another agent's work. + +The widening is granted to **taskless runs only**, and the branch lives in the +enforcement predicate rather than in who holds `post_comment`. The rejected parity argument is in the design's +[authority boundary](../system-design/taskless-coordinator-authority-01.md#the-authority-boundary). + +#### Acceptance criteria + +- **AC-OFFICE-COORDINATOR-AUTHORITY-004.1:** When a **taskless** run holds `post_comment` + and the target task belongs to the run's workspace, the system shall record the comment, + whether or not the task is in the run's task scope. +- **AC-OFFICE-COORDINATOR-AUTHORITY-004.2:** When the target task belongs to another + workspace, the system shall refuse with `ErrTaskOutOfScope` (`403`) and record no + comment. +- **AC-OFFICE-COORDINATOR-AUTHORITY-004.3:** When no task matches the target id, the + system shall refuse with `ErrTaskOutOfScope` (`403`) and record no comment, identically to + AC-OFFICE-COORDINATOR-AUTHORITY-004.2 so annotation is not an existence oracle. When the lookup itself fails, the system shall return that error (`500`) and + record no comment, so an outage is not read as a refusal. +- **AC-OFFICE-COORDINATOR-AUTHORITY-004.4:** When no target task is supplied and the run + has no bound task, the system shall refuse with `ErrTaskOutOfScope` (`403`) and record + no comment. +- **AC-OFFICE-COORDINATOR-AUTHORITY-004.5:** A recorded comment shall be attributed to the + calling agent and shall append a `runtime.action` event naming the target task. +- **AC-OFFICE-COORDINATOR-AUTHORITY-004.6:** When the comment body is empty or + whitespace-only, the system shall refuse with `ErrCommentBodyRequired` (`400`) and + record no comment. +- **AC-OFFICE-COORDINATOR-AUTHORITY-004.7:** Annotation shall not be idempotent: an + identical repeat shall record a second comment, with no deduplication on body, agent or + run. +- **AC-OFFICE-COORDINATOR-AUTHORITY-004.8:** When a run attempts to change the status of a + task outside its task scope, the system shall refuse with `ErrTaskOutOfScope`, whether or + not the task is in the run's workspace. +- **AC-OFFICE-COORDINATOR-AUTHORITY-004.9:** When a run creates a subtask under a parent + outside its task scope, the system shall refuse with `ErrTaskOutOfScope`. +- **AC-OFFICE-COORDINATOR-AUTHORITY-004.10:** When a run creates a task parented to a + task outside its task scope, the system shall refuse with `ErrTaskOutOfScope`. +- **AC-OFFICE-COORDINATOR-AUTHORITY-004.11:** Root task creation shall keep requiring only + `create_task` and a non-empty workspace, and shall succeed on a taskless run. +- **AC-OFFICE-COORDINATOR-AUTHORITY-004.12:** When a **task-bound** run targets any task + other than its own bound task, the system shall refuse the annotation with + `ErrTaskOutOfScope` and record no comment, whether or not the target is in the run's + workspace, which is today's reach exactly. +- **AC-OFFICE-COORDINATOR-AUTHORITY-004.13:** When a **taskless** run's workspace is empty + after trimming, the system shall refuse the annotation with `ErrWorkspaceOutOfScope` + (`403`) and record no comment, checked before the target task's workspace is resolved. A + task-bound run is unaffected. + +### REQ-OFFICE-COORDINATOR-AUTHORITY-005: Denied authority stays denied + +**Intent:** This capability widens read and defines write; it must not quietly grant the +two things Office already decided an agent may not do, nor add a second way to cast a +step verdict. + +**User story:** As a workspace owner, I want an unattended agent to stay unable to move, +archive, or manufacture a decision on a card. + +`record_step_decision_kandev` is excluded: it resolves task, step and role **from the +calling session** (`internal/mcp/server/agent_decision_tool.go`), so a runtime key would +put a second identity model on one decision ledger. + +#### Acceptance criteria + +- **AC-OFFICE-COORDINATOR-AUTHORITY-005.1:** No workflow-step-move key shall be added, and + `agentctl kandev tasks move` shall keep failing locally without issuing an HTTP request. +- **AC-OFFICE-COORDINATOR-AUTHORITY-005.2:** No archive key shall be added, and `agentctl + kandev tasks archive` shall keep failing locally without issuing an HTTP request. +- **AC-OFFICE-COORDINATOR-AUTHORITY-005.3:** No step-decision key shall be added, and no + runtime endpoint shall write a step decision row. +- **AC-OFFICE-COORDINATOR-AUTHORITY-005.4:** `Allows` shall keep returning false for any + key outside the vocabulary, so it remains closed after `list_tasks`. +- **AC-OFFICE-COORDINATOR-AUTHORITY-005.5:** A task-bound run's task scope, its + state-mutation refusals, and its annotation reach shall be unchanged by this capability, + with exactly two exceptions: the read-only board-read grant of + AC-OFFICE-COORDINATOR-AUTHORITY-001.2; and a `task_id` carrying surrounding whitespace, + which AC-OFFICE-COORDINATOR-AUTHORITY-003.3 now trims. +- **AC-OFFICE-COORDINATOR-AUTHORITY-005.6:** A taskless run holding `post_comment` shall be + able to annotate a task that is in its workspace and outside its task scope, pinning the + positive half of the branch that AC-OFFICE-COORDINATOR-AUTHORITY-004.12 pins negatively. + +## Out of scope + +Each exclusion is a contract; reasons are +[in the design](../system-design/taskless-coordinator-authority-01.md#out-of-scope). +The taskless session seam; recording a step decision from a taskless run; workflow-step +moves and archival for agents; narrowing `spawn_agent_run`; a tiebreak on comment +ordering; preconditions or optimistic concurrency on task-status mutation; backfilling +scope markers onto pre-existing runs; per-task ACLs or role-varying authority; live +re-resolution of task scope during a run; changing `checkIdleSkip`; and frontend surfaces. + +## System design + +[Taskless coordinator authority, part 1](../system-design/taskless-coordinator-authority-01.md). diff --git a/docs/specs/office/system-design/taskless-coordinator-authority-01.md b/docs/specs/office/system-design/taskless-coordinator-authority-01.md new file mode 100644 index 0000000000..61d1f8034f --- /dev/null +++ b/docs/specs/office/system-design/taskless-coordinator-authority-01.md @@ -0,0 +1,533 @@ +--- +status: current +system: office +requirements: + - REQ-OFFICE-COORDINATOR-AUTHORITY-001 + - REQ-OFFICE-COORDINATOR-AUTHORITY-002 + - REQ-OFFICE-COORDINATOR-AUTHORITY-003 + - REQ-OFFICE-COORDINATOR-AUTHORITY-004 + - REQ-OFFICE-COORDINATOR-AUTHORITY-005 +created: 2026-09-06 +owners: + - kandev +--- + +# Taskless Coordinator Authority System Design Part 1 + +## Purpose and boundaries + +This design records the authority boundary for a scheduled, unattended Office run and +the mechanism that enforces it. It owns the runtime capability vocabulary, the +task-scope derivation and the annotation predicate. The board-read endpoint's wire +contract — route, parameters, response, ordering, error mapping and CLI — is +[part 2](taskless-coordinator-authority-02.md). Neither part owns run launching, session +identity, or the workflow engine. This change prepares authority for a taskless run that +has a runtime session. It does not create that session or change the scheduler's current +taskless launch refusal. Taskless session creation remains a separate feature. + +## Requirement mapping + +| Requirement | Design section | +| --- | --- | +| `REQ-OFFICE-COORDINATOR-AUTHORITY-001` | [Vocabulary change](#vocabulary-change), [part 2 Board read](taskless-coordinator-authority-02.md#board-read) | +| `REQ-OFFICE-COORDINATOR-AUTHORITY-002` | [part 2 Request and response contract](taskless-coordinator-authority-02.md#request-and-response-contract) | +| `REQ-OFFICE-COORDINATOR-AUTHORITY-003` | [Task-scope derivation](#task-scope-derivation), [Snapshot semantics](#snapshot-semantics) | +| `REQ-OFFICE-COORDINATOR-AUTHORITY-004` | [Three scope classes](#three-scope-classes) | +| `REQ-OFFICE-COORDINATOR-AUTHORITY-005` | [What stays denied](#what-stays-denied) | + +## Prior art + +**Leg 1, compiled wiki.** Searched: vault `/Users/henry/Documents/henry/wiki` (from +`~/.obsidian-wiki/config.henry`), QMD collection `wiki`. **The leg did not run.** +`/Users/henry/Documents` is unreadable from this execution environment (`ls: Operation +not permitted`, on the vault path and on the parent), and neither `obsidian-wiki` nor +`qmd` is on `PATH`, so the GraphRAG pre-pass, the QMD pass and the grep fallback were +all unavailable. A tool-availability failure, not an empty result: the vault may hold a +position on unattended-agent authority this spec has not consulted. + +**Leg 2, `saas-kb`.** Searched: nothing. `search_fsm_docs` is not exposed in this +session (only `codex` and `kandev` MCP servers are present, and no tool-discovery +mechanism surfaced it). **The leg did not run.** No cross-vendor comparison informed +this contract. + +**Leg 3, substitute, in-repo prior reasoning.** Both external legs being unavailable, +the frozen in-repo contracts were read instead, and they constrain this design. +`agents-03.md` froze that step-move and archive "fail before making an HTTP request ... +because no signed Office runtime capability exists", preserved by +[What stays denied](#what-stays-denied). `tasks-01.md` ("Permissions") froze +`AllowedTaskIDs` as the rule stopping "a worker on task T1 from mutating task T2 just +because both belong to its workspace", which is why `WildcardTaskScope` is refused. +`runtime-01.md` froze capabilities as taken at run-claim time and kept by an in-flight +JWT; the scope snapshot is that shape plus the reuse rule in +[Snapshot semantics](#snapshot-semantics). `office/AGENTS.md` ("Participant slate: one +builder") records the trap the step-decision exclusion avoids: a second answer to a +question that has exactly one. + +**What we are doing differently.** Nothing departs from a documented position. The one +place this could have gone wider, `WildcardTaskScope` for taskless runs, is rejected +because `tasks-01.md` already decided against workspace-wide mutation. + +## The read that already exists + +`agentctl kandev tasks list` (`cmd/agentctl/kandev_tasks.go`) issues +`GET /api/v1/office/workspaces/$KANDEV_WORKSPACE_ID/tasks` — the dashboard route, not +`/runtime/*`. `AgentAuthMiddleware` accepts any valid agent JWT whose workspace claim +equals `:wsId`, and `buildEnvVars` (`internal/office/service/env_builder.go`) sets +`KANDEV_WORKSPACE_ID` on every run, taskless included. So the board read is reachable +today with no capability check, no `runtime.action` event, and a workspace taken from +the URL rather than the token claim. + +## What already works taskless + +`CanMutateTask` (`internal/office/runtime/context.go`) is consulted at exactly four +sites in `internal/office/runtime/actions.go`: `PostComment`, `UpdateTaskStatus`, +`CreateSubtask`, and `CreateTask` when `parent_task_id` is set. Every other runtime +action is workspace- or agent-scoped and already succeeds on a taskless run: root +`create_task`, `create_project`, `create_agent`, `modify_agents`, `spawn_agent_run`, +`request_approval`, `read_memory`, `write_memory`, `list_projects`, `list_skills`, +`delete_skills`. + +## The authority boundary + +One table, decided once. Every row answers "what may a scheduled coordinator do?" + +| Action class | Keys | Scope for a taskless run | Why | +|---|---|---|---| +| Board read | `list_tasks` (new) | The run's workspace, from the token claim | Already reachable ungoverned via the dashboard route; bringing it inside the contract adds the gate and the audit trail without adding reach. | +| Annotation | `post_comment` | The run's workspace, **taskless runs only** | The routine's stated job, and unreachable any other way. A task-bound run keeps today's own-task-only reach. | +| State mutation | `update_task_status`, `create_subtask`, parented `create_task` | The runner set only | `tasks-01.md` already decided workspace membership must not authorize mutating another task. | +| Workspace-scoped | root `create_task`, `create_project`, `create_agent`, `modify_agents`, `spawn_agent_run`, `request_approval`, `read_memory`, `write_memory`, `list_projects`, `list_skills`, `delete_skills` | Unchanged | These never consulted `CanMutateTask` and already succeed on a taskless run. | +| Denied | step move, archive, step decision | None | Frozen by `agents-03.md`; step decision belongs to the session-bound MCP tool. | + +`list_tasks` is granted to every role by default rather than gated on a permission: the +read is already reachable today, so defaulting it off would remove capability installs +already have while adding no safety. + +### The parity argument, and why it is retired + +Workspace-wide annotation for **every** run is rejected, and so is the parity argument for +it: that it grants no power beyond `spawn_agent_run`, which is already workspace-wide and +unattended-reachable. The observation is factually correct — `SpawnAgentRun` checks only +`target.WorkspaceID == runCtx.WorkspaceID`, with no task scoping at all — but it does not +follow that a new grant may match it. `spawn_agent_run`'s breadth is a known +runaway-containment gap, tracked separately for a causation cap and a per-workspace launch +budget; a capability that is already too permissive is an argument for narrowing that one, +never a licence for the next grant to copy it. Reasoning by parity with the loosest +existing capability ratchets the floor upward every time it is used. + +The grant is therefore bounded by need instead. A scheduled coordinator whose job is to +surface blockers cannot do it without commenting on tasks it does not run; a task-bound +worker has no such need. So the widening is taskless-only, and the branch lives in the +enforcement predicate rather than implicitly in who holds `post_comment` — which is what +makes the boundary checkable rather than merely intended. + +The other rejected alternative is `WithTaskScope(WildcardTaskScope)` for taskless runs. +It is the one-line fix, and it grants an unattended agent write authority over every task +in the workspace, the exact case `tasks-01.md`'s `AllowedTaskIDs` rule exists to prevent. + +## Vocabulary change + +`internal/office/runtime/capabilities.go` gains one key, `CapabilityListTasks = +"list_tasks"`, with a matching `CanListTasks` field on `Capabilities`, a `case` in +`Allows`, an entry in `AllowedKeys`'s stable-order list, and an unconditional `true` in +`FromAgent` beside `CanListProjects` and `CanListSkills`. + +`Allows`'s `default: return false` is preserved: the vocabulary stays closed, and this +is a deliberate extension rather than an opening of it. No `shared.Permissions` key is +added — `list_tasks` is capability-only, so `AllPermissionKeys` and +`ValidateNoEscalation` are untouched. + +`AllowedKeys` ordering is load-bearing: it is rendered into the prompt as +`AllowedActions` (`assembleAgentPrompt`). `list_tasks` is inserted next to the other +read keys so the prompt's action list stays grouped by kind. + + +## Task-scope derivation + +`ContextBuilder.Build` currently does: + +```go +taskID := payload["task_id"] +caps := FromAgent(agent).WithTaskScope(taskID) +``` + +Three changes. + +**Tasklessness is decided once, by trimming.** `strings.TrimSpace(payload["task_id"])` +is computed before any branch, and its emptiness is the single definition of "taskless" +used by both this derivation and the annotation predicate. The trimmed value is also what +`RunContext.TaskID` carries (AC-003.3), so the `taskID == c.TaskID` short-circuit in +`CanMutateTask`, the `input_snapshot`, and AC-004.12's "its own bound task" all agree on +one spelling. + +This is a real, if narrow, behavior change for a task-bound run, and AC-005.5 names it as +one of its two exceptions rather than claiming nothing moved: today a padded `" T1 "` +scopes to `[" T1 "]` and the run can mutate *nothing*, because no task id has that +spelling. After trimming it reaches `T1`, the task it was always meant to be bound to. +That is a fix, not a widening — but it is not "byte-for-byte today", so it is written +down. Without that, a whitespace-only +`task_id` is non-empty for the branch test and empty for `WithTaskScope`, which is the +contradiction AC-003.1 and AC-003.3 would otherwise encode. + +**`WithTaskScope` filters.** It drops empty and whitespace-only entries before storing +them, so `WithTaskScope("")` yields an empty `AllowedTaskIDs` rather than `[""]`. This +alone converts the current silent lie into an honest empty scope; `CanMutateTask` already +returns false for both, so no task-bound behavior moves. + +**Taskless runs materialize the runner set.** When the trimmed id is empty, the builder +resolves the runner set through a new reader and the resulting ids become +`AllowedTaskIDs`, ordered `updated_at DESC, id DESC` and capped at 500. + +### The runner-set predicate + +`CountActionableTasksForAgent` supplies four of the five clauses — runner projection +equals the agent, `state IN ('TODO','IN_PROGRESS')`, `archived_at IS NULL`, and not +automation-origin — but it takes only an agent id and has **no workspace clause**. The +new reader adds `workspace_id = ?` bound to `runCtx.WorkspaceID` (AC-003.13). The +capability's scope is a write authority, so it is filtered explicitly rather than left to +rely on agent profiles happening to be workspace-unique. + +An empty `runCtx.WorkspaceID` is not a filter value. Binding it would match only tasks +that themselves carry an empty workspace and then freeze that as a **final** `runner_set` +scope, so the query is not issued at all and the scope takes the provisional +`unavailable` path instead (AC-003.15) — the same answer a failed query gets, for the +same reason: authority that could not be verified is not granted. + +That filter binds **this branch only**. A task-bound run's scope is its own trimmed +`task_id` and is not workspace-checked, exactly as today — the id came from the run's own +payload, not from a board query, and adding a check there would be new behavior that +AC-003.3 disclaims. + +### ContextBuilder dependencies + +`ContextBuilder` today holds `Agents shared.AgentReader` and `Runs RunSnapshotStore`. It +gains **two** narrow local interfaces, both satisfied at the composition root and both +nil-safe: + +- `RunnerTaskLister` — returns the ordered, capped runner-set ids plus the true total, so + truncation is detectable without a second count query. A nil lister is **not** an empty + runner set: it is a scope that could not be derived, so it takes the provisional + `unavailable` path (AC-003.15) and is retried on the next build, rather than freezing a + final `runner_set` empty scope no later build would revisit. +- `ScopeEventAppender` — appends a run event. A nil appender skips the event and never + fails the build. + +Derivation returns an internal `scopeDerivation` value — the ids, the true total, whether +it was truncated, the query error if any, and the resulting marker. It fills +`AllowedTaskIDs` and is not exposed on `RunContext`, so an unexported `build` returns +`(RunContext, scopeDerivation, error)`: exported `Build` drops the derivation, and +`BuildAndPersist` keeps it to choose the event and its payload after the swap. + +**Event timing follows the winning write, not the derivation.** `BuildAndPersist` emits +`runtime.scope_truncated` / `runtime.scope_unavailable` only after its compare-and-swap +succeeds, so the events on a run describe the scope actually in force rather than every +scope that was speculatively computed for it. `BuildAndPersist` owns the +`ScopeEventAppender` call site outright: `Build` derives the scope and never appends, so a +`ContextBuilder` with no `Runs` store persists nothing and therefore emits nothing. This is +the mechanism behind AC-003.14, which scopes AC-003.5's and AC-003.6's event obligation to +the build that wins and to a configured appender: a losing build, a build with no appender, +and a build that persists nothing each append none and still return a context. + +Failure is closed: a query error yields an empty scope and a context that still builds. This is deliberately opposite to `checkIdleSkip`, +which fails open: its open failure means "launch the agent anyway", costing a wasted run, whereas an open failure here would mean "grant authority you could not +verify." + +### Run events + +Both are new `RunEventType` values. That type is an explicitly open set ("Adapters may +emit additional values"), so no enum gate blocks them, and the run-detail Events tab +renders them through its existing generic renderer. + +| Event | Level | Payload keys | +|---|---|---| +| `runtime.scope_truncated` | `warn` | `cap` (500), `total` (true runner-set size), `agent_id`, `run_id` | +| `runtime.scope_unavailable` | `warn` | `error` (query error, or AC-003.15's unmet condition), `agent_id`, `run_id` | + +A clipped coordinator is therefore visible in its own run rather than merely +under-powered, and a fail-closed empty scope is distinguishable from an honestly empty +one. + +### Snapshot semantics + +`BuildAndPersist` is called from `prepareAndLaunch` +(`internal/office/service/scheduler_integration.go`) on **every launch attempt**, and it +always re-derives `Capabilities` from the live agent and payload before overwriting +`runs.capabilities` and `runs.input_snapshot`. There is no read-back path. `runtime-01.md` +records that "a re-issued JWT after restart uses the same capability set", and that holds +today only because the capability booleans are a pure function of the agent: re-deriving +them is idempotent. + +A runner set is not a pure function of the agent. It is a projection of a mutable board, +so re-deriving it on a relaunch or after `RecoverStale` produces a *different* answer, and +AC-003.9 ("taken once per run") and AC-003.11 ("a re-minted token reproduces the persisted +snapshot") would both be false. The precedent does not transfer, so the reuse is made +explicit rather than inherited. + +The serialized capability snapshot gains a `task_scope_source` marker with three values: + +| Marker | Finality | Meaning | +|---|---|---| +| `payload` | final | scope is the run's own trimmed `task_id` | +| `runner_set` | final | scope was materialized from the runner set | +| `unavailable` | **provisional** | the runner-set query failed; scope is empty, fail-closed | + +`Build` reads the run's persisted capabilities first. If `task_scope_source` names a +**final** marker, the persisted `AllowedTaskIDs` is reused verbatim and no runner-set query +is issued. Otherwise — no marker, the provisional `unavailable`, a value outside the three +above, or a `runs.capabilities` string that does not parse — the scope is derived afresh +and written with its marker (AC-003.12(b)). The marker's *finality*, not the scope's +emptiness, distinguishes "derived, and legitimately empty" from "not usably derived yet". + +Three consequences worth stating, because each was a silent gap: + +- **A transient failure is retried, not frozen.** `unavailable` being provisional means the + next `BuildAndPersist` for that run tries the runner set again. Treating it as final + would let one database blip de-scope a coordinator for the whole life of the run, with + no event distinguishing "will retry" from "never again". +- **An unparseable or unrecognized snapshot derives rather than fails.** `Build` reads + `run.Capabilities` for the first time under this design, so this parse path is new. + Deriving is the safe answer: it is the normal path, it cannot widen authority beyond the + runner set, and it avoids bricking a run on a value we cannot interpret. +- **Reuse covers the task scope only.** Capability booleans keep re-deriving from the agent + on every build (AC-003.12(d)). + +#### First write wins, and how + +AC-003.12(c) is a concurrency guarantee, so it needs a mechanism rather than an intention. +`UpdateRunRuntimeSnapshot` is an unconditional +`UPDATE runs SET capabilities=?, input_snapshot=?, session_id=? WHERE id=?` — no predicate +at all — so two processors that both read "no final marker" would both derive and the +**last** would win, which is the opposite of the requirement. + +The runs repository therefore gains a compare-and-swap sibling: + +``` +UpdateRunRuntimeSnapshotCAS(ctx, id, prevCapabilities, capabilities, inputSnapshot, sessionID) (bool, error) + +UPDATE runs SET capabilities = ?, input_snapshot = ?, session_id = ? +WHERE id = ? AND COALESCE(capabilities, '') = ? +``` + +`prevCapabilities` is the exact string `Build` read when it checked the marker. The bool is +`RowsAffected() > 0`. On `false` another processor wrote first: re-read the run, and if its +marker is now final, adopt that scope and emit no scope event. If it is still not final, +retry the derive-and-swap — bounded at three attempts, after which `BuildAndPersist` +returns an error and the launch attempt fails, which the next attempt retries from scratch. + +**The swap protects the complete runtime snapshot.** If a writer loses, it re-reads the run +and adopts the winner's `capabilities`, `input_snapshot`, and `session_id` together. It +does not perform an unconditional follow-up write, so it cannot replace the winner's +scope or session identity. A normal build that reuses a final snapshot still refreshes +the derived capability booleans through the existing write path. + +Comparing the previous **value** rather than extracting the marker in SQL is deliberate: +`json_extract` is SQLite-flavoured, Postgres is a supported driver +(`internal/persistence/provider.go`), and `CancelRunsForTasks` already records that +dialect-specific SQL is kept out of the shared runs writer. A value compare is +dialect-neutral and needs no `dialect.JSONExtract`. + +No lock and no transaction are added: a single conditional `UPDATE` is atomic, and the +losing side reconciles by reading. + +The consequence is stated rather than hidden: a task assigned to the agent while a run is +in flight is not writable by that run. The next run picks it up. For a routine firing +every five minutes, worst-case latency is one cadence. + +## Three scope classes + +`CanMutateTask` stays pure and keeps its current meaning — it is now the +**state-mutation** predicate, consulted by `UpdateTaskStatus`, `CreateSubtask`, and +`CreateTask` with a parent. Unchanged for every run, taskless or not. + +`PostComment` stops calling it and calls a new **annotation** predicate, which branches on +tasklessness using the trimmed-id test defined above: + +- **Task-bound run** — the target must equal the run's own bound task. Anything else is + `ErrTaskOutOfScope` (`403`), which is byte-for-byte today's behavior, since + `CanMutateTask` short-circuits on `taskID == c.TaskID` and a task-bound run's scope is + that single id (AC-004.12). It never reads `runCtx.WorkspaceID`, so the empty-claim guard + below does not reach it and AC-005.5's "unchanged" holds for annotation too. +- **Taskless run** — an empty or whitespace-only `runCtx.WorkspaceID` is + `ErrWorkspaceOutOfScope` (`403`), decided before the target is resolved (AC-004.13); + without that guard an empty claim would compare equal to an unowned task's empty + `workspace_id` and record the comment. The guard belongs to this branch alone because + only this branch compares workspaces at all. Then resolve the target task's workspace and + compare it to `runCtx.WorkspaceID`. Equal, record the comment (AC-004.1, AC-005.6). + Anything else — a different workspace, or no such task — is `ErrTaskOutOfScope` (`403`), the *same* + sentinel and therefore the same response body, so annotation cannot be used to probe + whether a task id exists elsewhere. No target and no bound task, `ErrTaskOutOfScope`. + + The sentinels are aligned deliberately. `respondRuntimeError` writes + `{"error": err.Error()}`, so pairing a cross-workspace `ErrWorkspaceOutOfScope` with an + unresolvable `ErrTaskOutOfScope` would produce the bodies `forbidden: workspace out of + scope` and `forbidden: task out of scope`, letting an unattended agent separate "exists + elsewhere" from "does not exist" by reading them. One sentinel on both paths is what + makes the anti-oracle claim true. Only the annotation path is aligned; + `validateTaskRelations` keeps `ErrWorkspaceOutOfScope` for parented creation, unchanged. + + A *failed lookup* is not a refusal. `GetTaskWorkspaceID` already distinguishes them — + `("", nil)` for no such row, `("", err)` for a query failure — so a failure is returned + as-is and surfaces as `500` (AC-004.3). Collapsing it into the `403` would disguise a + database outage as an authorization decision. +- **Either** — an empty or whitespace-only body is `ErrCommentBodyRequired` (`400`), + checked before the branch so a malformed request is not also an existence oracle. The + full order is capability, body, branch, with the taskless branch adding its workspace + claim before the target. + +This is the only behavioral widening in the design, and it is bounded by the workspace on +every path and by tasklessness at the branch. + +The predicate needs no new dependency. `Actions.deps.Tasks` is a `TaskCreator`, and that +interface already declares `GetTaskWorkspaceID(ctx, taskID) (string, error)` alongside +`GetTaskProjectID`; `validateTaskRelations` already calls it for exactly this comparison, +a target task's workspace against the run's. The annotation predicate calls the same +method on the same dependency. + +No `TaskWorkspaceReader` interface is introduced. A second reader behind one question, +wired at two composition sites that can drift, is the trap `office/AGENTS.md` records under +"Participant slate: one builder". + +The **board-read** class is workspace-only and consults neither predicate. + +## What stays denied + +No `move_task` or `archive_task` key is added. `tasksMove` and `tasksArchive` keep +failing locally before any HTTP request, preserving `agents-03.md`. + +No `record_step_decision` key is added. The MCP tool +(`internal/mcp/server/agent_decision_tool.go`) resolves task, step and role from +`s.taskID` / `s.sessionID` and returns an error when either is empty. Adding a runtime key +would put a second identity model on the same decision ledger, which is the failure mode +`office/AGENTS.md` records for participant slates. A taskless run gains decision recording +when it gains a session, and not before. + +## Concurrency and revocation + +Concurrent annotations do not conflict: comments are additive. `ListComments` orders by +`created_at` with **no** secondary key, so two comments written within one clock tick have +an unspecified relative order. That is recorded rather than fixed — the read path is +shared with the dashboard, and changing it is outside this capability. + +A board read paged over a mutable sort column can see a row twice or miss it if that row +is written between pages. The contract guarantees a total order within one page, not a +stable order across a mutating board. + +Board-read events are not deduplicated (AC-001.11): each accepted read appends one +`runtime.action` and each refusal one `runtime.denied`, so a retry loop is visible as +repeated rows rather than being silently collapsed. + +Two runs of one agent can hold overlapping task scope only after `RecoverStale` re-queues +a claimed run whose process is still live with an unexpired JWT (default 4h); +`ClaimNextEligibleRun`'s per-agent busy lock (`agent_profile_id`, claimed count zero) +prevents it otherwise. The compare-and-swap in +[Snapshot semantics](#snapshot-semantics) makes that overlap harmless: the first final +marker wins, the loser reconciles by reading, and only the winner emits a scope event. Task-status +mutation is untouched and keeps last-write-wins and its existing approver gate, with no +revision token or precondition. Revoking an agent's permissions mid-run does +not affect the in-flight JWT's snapshot, unchanged from `runtime-01.md`. + +## Failure modes + +- **Runner-set read fails.** Empty scope, `runtime.scope_unavailable`, provisional marker + `unavailable`, context built. Every task-scoped mutation then refuses with + `ErrTaskOutOfScope`; board read and workspace-scoped actions are unaffected. The next + `BuildAndPersist` for that run derives again, because the marker is not final. +- **Persisted snapshot unparseable, or its marker unrecognized.** Treated as "not usably + derived": scope derived afresh and rewritten. No run is bricked by a value we cannot + read. +- **Runner set underivable.** No lister wired, or an empty run workspace. No query is + issued; empty scope, provisional `unavailable` marker, retried on the next build. +- **Empty workspace claim on taskless annotation.** `ErrWorkspaceOutOfScope` (`403`), no + comment, decided before the target is resolved. A task-bound run reads no claim and is + unaffected. +- **Annotation workspace lookup fails.** `500`, no comment. Distinct from the `403` a + missing or foreign task gets, so an outage is not read as a refusal. +- **Board-read parameters invalid.** `ErrInvalidListParams` (`400`), no query issued, no + rows, no cursor. +- **Board-read query fails.** `500`, no partial page, no cursor. The run continues; the + agent sees an error from the CLI. +- **No such task during annotation.** `ErrTaskOutOfScope` (`403`); no comment written; + indistinguishable from a cross-workspace target by design, same sentinel. +- **Cap exceeded.** First 500 by `(updated_at DESC, id DESC)`, `runtime.scope_truncated` + recorded with the true total. +- **Overlapping runs for one agent.** The compare-and-swap decides: first final marker + wins, the loser re-reads and adopts it, and emits no scope event. + +## Durability + +- **`runs.capabilities` / `runs.input_snapshot`**: durable, now carrying a materialized + task-scope list plus `task_scope_source` for taskless runs, written together by one + conditional `UPDATE` so they cannot diverge. A JWT re-minted after restart reproduces the + same authority because a *final* scope is read back rather than re-derived; a provisional + `unavailable` is retried instead. +- **`office_run_events`**: durable. `runtime.action`, `runtime.denied`, + `runtime.scope_truncated`, `runtime.scope_unavailable`. +- **Runner set itself**: not durable. It is a projection of `tasks`, materialized once per + run and thereafter read from the snapshot. +- **No migration.** Runs persisted before this capability carry no marker and derive fresh + on their next context build; nothing backfills `runs`. + +## Testing + +- Vocabulary: `Allows` returns the granted state for `list_tasks` and still returns false + for an unknown key; `AllowedKeys` includes it in stable order; `FromAgent` grants it for + every role. +- Scope: `WithTaskScope("")` and `WithTaskScope(" ")` both yield an empty list; a taskless + run yields the runner set; a task-bound run yields exactly its trimmed `task_id` and a + `RunContext.TaskID` trimmed to match; the runner-set workspace filter does not apply to + the task-bound branch; a whitespace-only payload id is treated as taskless; a query + error, a nil lister and an empty run workspace each yield an empty list, an + `unavailable` marker and no build error, the last two issuing no query; over-cap truncates deterministically and + records the true total; the scope excludes tasks in other workspaces. +- Snapshot: a second `BuildAndPersist` for a run with a **final** marker reuses the + persisted scope and issues no runner-set query; a run with no marker derives and persists + one; a run with a provisional `unavailable` marker derives again; an unparseable + snapshot and an unrecognized marker both derive rather than fail; capability booleans + still re-derive. Concurrency: a CAS whose `prevCapabilities` no longer matches reports + `false`, does not overwrite, and the loser adopts the persisted final scope and emits no + `runtime.scope_truncated` / `runtime.scope_unavailable` row; a build with no appender, and + one with no `Runs` store, each emit nothing and still return a context, so a scope-event + test must wire a `Runs` store to observe one. +- Enforcement: status update, subtask and parented create refuse outside the runner set; a + taskless run comments inside its workspace and refuses outside it; a taskless run with an + empty workspace claim refuses even a task whose own `workspace_id` is empty, while a + task-bound run with an empty claim still reaches its own task; a task-bound run + refuses any target but its own task; an empty body is `400`; root create succeeds on a + taskless run. A cross-workspace target and a nonexistent one return the **same** sentinel + and the same body, while a failing workspace lookup returns `500`. A task-bound run whose + payload id is padded with whitespace reaches its own task. +- Board read: capability denial is `403` with `runtime.denied` and precedes parameter + validation; empty workspace claim refuses; the filtered path is taken with no query + parameters; an out-of-allow-list sort is `400`; a default read comes back descending; a + repeated `sort` is `400` while a repeated `status` unions; a cursor without `cursor_id` + is `400`; a two-page walk over rows sharing an `updated_at` returns each row exactly + once; two identical reads append two `runtime.action` rows. Normalization: `order=DESC`, + `include_system=1` and `limit=abc` are each `400`, while `limit=` and `limit=0` both take + the 100-row default, and `?cursor=&cursor_id=x` is `400` rather than a first page. +- CLI: `tasks list` succeeds with `KANDEV_WORKSPACE_ID` unset, and a repeated `--status` + reaches the endpoint as two `status` values rather than one. +- Regression: a task-bound run's capabilities, scope and refusals are byte-identical to + today, except that `list_tasks` is now granted. + +## Out of scope + +- **The taskless session seam.** `task_sessions.task_id` is `NOT NULL` and `launchAgent` + refuses a run with no `task_id` (`failTasklessRun`). This says what such a run may do + once it can run, not how it runs. +- **Recording a step decision from a taskless run.** Reasons under REQ-005. +- **Workflow-step moves and archival for agents.** Denied per `agents-03.md`. +- **Narrowing `spawn_agent_run`.** Its unscoped workspace-wide reach is a real containment + gap, and is why REQ-004 rejects it as a precedent, but it is a separate contract change. +- **A tiebreak on comment ordering.** `ListComments` orders by `created_at` with no + secondary key, so two comments in one clock tick have an unspecified order. That read + path is shared with the dashboard. +- **Preconditions or optimistic concurrency on task-status mutation.** Last-write-wins and + the existing approver gate are kept. +- **Backfilling scope markers onto pre-existing runs.** They derive fresh per AC-003.12(b). +- **Per-task ACLs, or role-varying authority.** `FromAgent` remains the single derivation. +- **Live re-resolution of task scope during a run.** Rejected for the snapshot semantics + `runtime-01.md` already froze. +- **Changing `checkIdleSkip`.** A board-reading coordinator may deserve a different + idle-skip predicate, but that is a scheduler contract change. +- **Frontend surfaces.** No UI. The run detail Events tab renders the four new + `runtime.*` event rows through its existing generic renderer. diff --git a/docs/specs/office/system-design/taskless-coordinator-authority-02.md b/docs/specs/office/system-design/taskless-coordinator-authority-02.md new file mode 100644 index 0000000000..e7f28e4ea9 --- /dev/null +++ b/docs/specs/office/system-design/taskless-coordinator-authority-02.md @@ -0,0 +1,218 @@ +--- +status: current +system: office +requirements: + - REQ-OFFICE-COORDINATOR-AUTHORITY-001 + - REQ-OFFICE-COORDINATOR-AUTHORITY-002 +created: 2026-09-06 +owners: + - kandev +--- + +# Taskless Coordinator Authority System Design Part 2 + +## Purpose and boundaries + +This part owns the board-read wire contract: the runtime route, its query parameters and +response shape, the ordering and paging rules, the error mapping, and the `agentctl` +surface that reaches it. The capability vocabulary that gates it, the task-scope +derivation and the annotation predicate are +[part 1](taskless-coordinator-authority-01.md). + +## Requirement mapping + +| Requirement | Design section | +| --- | --- | +| `REQ-OFFICE-COORDINATOR-AUTHORITY-001` | [Board read](#board-read), [CLI](#cli) | +| `REQ-OFFICE-COORDINATOR-AUTHORITY-002` | [Request and response contract](#request-and-response-contract), [Ordering and the descending default](#ordering-and-the-descending-default) | + +## Board read + +New route, mounted in `runtime.RegisterRoutes` beside the existing group: + +``` +GET /api/v1/office/runtime/tasks +``` + +`/runtime/` is already on `officeWorkspacelessPrefixes` +(`internal/backendapp/office_scope.go`) with the reason "every handler calls +`contextFromRequest`, which ... derives workspace/task/run from its claims." The new +handler honors that: it reads `runCtx.WorkspaceID` and ignores any caller-supplied +workspace. + +**Evaluation order**, which decides which refusal wins when a request is wrong in more +than one way: + +1. `Allows(CapabilityListTasks)` — else `ErrCapabilityDenied` (`403`) + `runtime.denied`. +2. Non-empty workspace claim — else `ErrWorkspaceOutOfScope` (`403`). +3. Parse and validate **every** query parameter — any failure is `ErrInvalidListParams` + (`400`), with no query issued and no partially-parsed page. +4. Delegate to `ListTasksFiltered` — always, with no unfiltered branch. + +Authorization therefore always precedes parameter validation, so a run lacking the +capability learns nothing about which parameters would have been accepted. + +Step 4 is the substance of AC-002.9: the dashboard handler forks on +`hasTaskFilterParams` and serves an unfiltered read from a query ordered +`ORDER BY t.updated_at DESC` with no tiebreak, which is unstable across pages. The +runtime read never takes that fork. + +### Request and response contract + +| Parameter | Cardinality | Maps to | Rule | +|---|---|---|---| +| `status` | repeatable | `ListTasksOptions.Status` | matches any supplied value | +| `priority` | repeatable | `.Priority` | matches any supplied value | +| `assignee` | single-valued | `.AssigneeID` | agent profile id, exact match | +| `project` | single-valued | `.ProjectID` | exact match | +| `sort` | single-valued | `.SortField` | `updated_at` \| `created_at` \| `priority`; absent → `updated_at` | +| `order` | single-valued | `.SortDesc` | `asc` \| `desc`; absent → `desc`, for every sort column | +| `limit` | single-valued | `.Limit` | integer; absent, `<= 0` or `> 500` → 100 | +| `cursor` | single-valued | `.CursorValue` | must be supplied with `cursor_id` | +| `cursor_id` | single-valued | `.CursorID` | must be supplied with `cursor` | +| `include_system` | single-valued | `.IncludeSystem` | boolean; absent → `false` | + +Repeating a single-valued parameter is `ErrInvalidListParams`, never "last one wins" — +positional resolution is exactly the silent behavior change AC-002.13 exists to prevent. + +#### Normalization + +The table above says what each parameter means; these rules say how its raw value is read, +and they are strict on purpose. AC-002.13's whole point is that a malformed request fails +loudly instead of quietly becoming a different query, and every lenient rule here would be +a way to get a page you did not ask for. + +- **Empty means absent.** A parameter present with an empty value is treated as not + supplied. So `?limit=` takes the default, and `?cursor=&cursor_id=x` is *one* cursor + component supplied, which is the `400` above — not a first page. +- **Enumerated values match exactly.** `sort`, `order` and `include_system` are compared + byte-for-byte against their allowed spellings: `updated_at` / `created_at` / `priority`, + `asc` / `desc`, `true` / `false`. No case folding and no trimming, so `DESC`, `True`, + `1` and `" desc"` are each `ErrInvalidListParams`. A caller that has to guess the casing + is a caller that will silently get the wrong order. +- **`limit` parses as a base-10 integer.** A value that does not parse is `400`; one that + parses is then clamped by AC-002.4 (`<= 0` or `> 500` → 100). Parsing and clamping are + different steps: `abc` is an error, `0` is not. +- **No trimming anywhere.** `status`, `priority`, `assignee`, `project`, `cursor` and + `cursor_id` are passed through as given. A filter value with stray whitespace matches + nothing, which is a visibly empty page rather than a silently different one. + +Response body: + +```json +{ "tasks": [ /* task rows */ ], "next_cursor": "", "next_id": "" } +``` + +`next_cursor` and `next_id` are separate fields rather than one opaque composite, so a +caller resumes by echoing both back (AC-002.5, AC-002.12). Both are empty on the final +page. A cursor is only meaningful under the sort column and direction that produced it; +the endpoint does not encode the sort into the cursor, so a caller that changes `sort` or +`order` mid-walk gets a well-ordered but differently-anchored page. That is stated rather +than defended against, because detecting it would mean encoding sort state into the +cursor, which the existing keyset shape does not carry. + +### Ordering and the descending default + +`ListTasksFiltered` gives a total order on `(, tasks.id)` with both legs in +the same direction, an out-of-allow-list sort rejected by `resolveListTasksOptions`, a +limit clamped by `limit <= 0 || limit > 500 → 100`, archived, ephemeral and +automation-origin rows excluded in `buildTaskWhereClause`, and system-workflow rows +excluded unless `IncludeSystem`. + +One thing it does **not** give is a descending default. `resolveListTasksOptions` +computes `dir := "DESC"; if !opts.SortDesc { dir = "ASC" }`, so the zero value yields +**ascending**; only the dashboard caller sets `SortDesc: true`. The `ListTasksOptions` +struct comment claiming a DESC default for `updated_at`/`created_at` describes callers, +not the function. The runtime handler therefore sets `SortDesc` explicitly from the +`order` parameter, defaulting it to `true` (AC-002.2). Relying on the repository default +would ship the contract inverted. + +#### Four exclusions, one opt-in + +`ListTasksFiltered` drops four classes of row, and only one of them is negotiable by the +caller. Three are emitted by `buildTaskWhereClause`; the fourth is appended by +`ListTasksFiltered` itself, after that helper returns: + +| Excluded | Predicate | Emitted by | Opt-in | +|---|---|---|---| +| Archived | `t.archived_at IS NULL` | `buildTaskWhereClause` | none | +| Ephemeral | `t.is_ephemeral = 0` | `buildTaskWhereClause` | none | +| Automation-origin | `COALESCE(t.origin,'') != 'automation_run'` (`notAutomationOriginT`) | `buildTaskWhereClause` | none | +| System-workflow | `COALESCE(w.workflow_template_id,'') NOT IN (...)` | `ListTasksFiltered` | `include_system` | + +The runtime handler calls `ListTasksFiltered`, so it gets all four; a caller reaching +`buildTaskWhereClause` directly would get three. The system-workflow clause is further +guarded by `!opts.IncludeSystem && len(sysArgs) > 0`, and `systemTasksPlaceholders()` +returns nil args when `SystemWorkflowTemplateIDs` is empty, so with no system template ids +configured the clause is omitted whatever `include_system` says. That branch is defensive +and currently unreachable, but it is why the opt-in column reads as a toggle on a clause +that exists only when there is a system-workflow list to exclude against. + +AC-002.8 names all four rather than only the two an implementer would notice from the +route. The ephemeral and automation-origin predicates are inherited from the shared +query, not chosen here, and they are invisible in the request: a coordinator that cannot +see an automation-origin task should be reading a contract that says so, instead of +inferring it from a `WHERE` clause it never sees. The spec already names the +automation-origin clause on the write side — it is one of the four the runner set +inherits from `CountActionableTasksForAgent` — so leaving it unstated on the read side +would have been an asymmetry rather than a uniform silence. + +Widening any of the three unconditional exclusions is a separate contract change, not a +new parameter. `include_system` stays the only opt-in this endpoint offers. + +### Error mapping + +`respondRuntimeError` today maps `errTaskTitleRequired` and `ErrProjectRequired` to +`400`, `shared.ErrForbidden` to `403` + `runtime.denied`, and everything else to `500`. +`resolveListTasksOptions` returns a bare `fmt.Errorf("invalid sort field: %s")`, which +under that mapping would surface an out-of-allow-list sort as `500`. + +Two new sentinels in `internal/office/runtime/errors.go`, both added to +`respondRuntimeError`'s `400` branch beside the existing two: + +- `ErrInvalidListParams` — any board-read parameter that fails validation. The handler + validates parameters itself and returns this sentinel; it does not depend on the + repository's untyped error text. +- `ErrCommentBodyRequired` — an empty or whitespace-only comment body (AC-004.6). + `PostComment` performs no body validation today, so this is new behavior, not a + re-mapping. + +`ErrCapabilityDenied`, `ErrTaskOutOfScope` and `ErrWorkspaceOutOfScope` already wrap +`shared.ErrForbidden` and keep their `403`. + +### CLI + +`cmd/agentctl/kandev_tasks.go`'s `tasksList` is re-pointed from +`/api/v1/office/workspaces/{ws}/tasks` to `/api/v1/office/runtime/tasks`, and stops +reading `KANDEV_WORKSPACE_ID` to build its path — the token is the authority. + +**It must also stop *requiring* that variable.** `getWithParams` takes a +`requiredEnvName` / `requiredEnvVal` pair and aborts with `" must be set"` when the +value is empty, before issuing any request. Re-pointing the path while keeping that guard +would leave the command hard-failing on an environment variable the contract has just +declared non-authoritative. `tasksList` therefore calls a variant with no required-env +check, and succeeds with `KANDEV_WORKSPACE_ID` unset (AC-001.8). + +Its three existing flags (`--status`, `--assignee`, `--project`) keep working, and it +gains one flag per remaining parameter: `--priority`, `--sort`, `--order`, `--limit`, +`--cursor`, `--cursor-id`, `--include-system` (AC-001.10). Without these the paging +contract of REQ-002 would be specified but unreachable, since this CLI is the only +sanctioned agent path to the endpoint. + +**`--status` and `--priority` must be repeatable**, because the parameter table marks +those two repeatable and AC-002.13 gives them union semantics. Today they cannot be: +`tasksList` declares `--status` with `flag.String`, and `getWithParams` takes a +`map[string]string` and calls `url.Values.Set`, so a map cannot hold two values for one +key and `Set` would overwrite rather than append. Both change together — a repeatable +`flag.Var` collecting into a slice, and a request helper carrying `url.Values` (built with +`Add`) instead of a `map[string]string`. Left as-is, the union half of AC-002.13 is +specified behavior with no way for an agent to reach it, which is the gap AC-001.10 +exists to close. + +Board-read coverage for the exclusion set: an ephemeral task and an automation-origin +task are both absent from a board read, and stay absent with `include_system=true`, which +is what pins them as unconditional rather than merely default-off. + +The dashboard route is left in place: it serves the browser, and the scope middleware +plus `AgentAuthMiddleware` already constrain it. This design removes it as the *agent's* +path, not as a route.