Commit Graph

264 Commits

Author SHA1 Message Date
João Salavisa bd24f7f07b test(task-service): cover documents, attachments, messages and resources (#2588)
Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-12 22:17:54 +01:00
nova28 93e5c51116 fix(backend): record step transitions so session workflow history stops returning empty (#2520)
Co-authored-by: nova28 <17953305+nova28@users.noreply.github.com>
Co-authored-by: Carlos Florencio <carlosmflorencio@gmail.com>
2026-08-12 17:06:40 +01:00
João Salavisa fbb04aed92 fix(backend): scope task state, move and delete to the calling user (#2503)
Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-10 21:23:03 +01:00
Carlos Florêncio 0b60af298e feat: add task autopilot mode and MCP profiles (#2445) 2026-08-09 20:29:48 +01:00
João Salavisa d6e2c358da refactor(task): share task-plan WS error mapping across both surfaces (#2465)
Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-09 18:38:14 +01:00
nova28 d7f640f8ab fix(worktree): destroy every repo's worktree during multi-repo task cleanup (#2460)
Co-authored-by: nova28 <17953305+nova28@users.noreply.github.com>
Co-authored-by: Carlos Florencio <carlosmflorencio@gmail.com>
2026-08-09 18:21:44 +01:00
nova28 e035a0c355 feat(tasks): add external_id create idempotency (#2440)
Co-authored-by: nova28 <17953305+nova28@users.noreply.github.com>
Co-authored-by: Carlos Florencio <carlosmflorencio@gmail.com>
2026-08-09 18:07:23 +01:00
Carlos Florêncio 2832170eb4 fix(task): preserve task-owned worktrees across session deletion (#2456) 2026-08-09 12:05:48 +01:00
nova28 b309d2beb6 fix(web): render workflow description in settings (#2418) 2026-08-09 11:49:04 +01:00
Carlos Florêncio de4e4161ed feat: surface port forwarding controls and browser navigation (#2383) 2026-08-08 13:49:58 +01:00
João Salavisa 9514ab28e4 fix(tasks): clear the error icon once the agent recovers (#2391)
Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-07 19:48:31 +01:00
Clément Fiere 084ecc8b54 feat: show queued prompt count badge in the task sidebar (#2354) 2026-08-07 15:34:39 +01:00
Clément Fiere 4d80edacf2 feat: re-parent tasks by drag and drop in the sidebar (#2355) 2026-08-07 15:33:41 +01:00
Luan Martins 10996c1b57 feat: add optional workflow-level agent prompt (#2338) 2026-08-07 15:22:44 +01:00
nova28 6b40d5b2ec feat(automation): make the automation the object, with its own runs destination (#2190)
Co-authored-by: Carlos Florencio <carlosmflorencio@gmail.com>
2026-08-06 11:18:59 +01:00
Carlos Florêncio 80e4d77bb1 feat(secrets): add scoped repository secret environments (#2237) 2026-08-05 23:05:54 +01:00
nova28 d15d5da8fa fix(backend): seed every workspace with its stored base branch (#2270) 2026-08-05 22:37:07 +01:00
Carlos Florêncio 7cd0989fe8 fix: initialize new repositories with a main branch (#2297) 2026-08-05 22:34:26 +01:00
Carlos Florêncio 84fe8132a1 feat: support remote contribution tasks (#2265) 2026-08-05 19:25:58 +01:00
Carlos Florêncio a7b416a1a8 fix(web): retire unreachable archived sidebar filter (#2246) 2026-08-05 19:06:49 +01:00
Alassane ae31fa85a9 feat(gitlab): add task MR lifecycle notifications (#2125)
Co-authored-by: Carlos Florencio <carlosmflorencio@gmail.com>
2026-08-05 18:22:31 +01:00
Carlos Florêncio 3c9bf8295f feat: support 100 MiB prompt attachments (#2261) 2026-08-04 22:11:13 +01:00
José Almeida d6b95500eb fix: make pending message queues manageable (#2239) 2026-08-04 08:49:46 +01:00
Carlos Florêncio 2ee2fa8c66 fix: make agent turn cancellation responsive (#2228) 2026-08-04 08:09:07 +01:00
Carlos Florêncio 3f46da6645 fix(backend): harden office-disabled cron, title limits, and dead-runtime cleanup (#2206) 2026-08-03 15:11:58 +01:00
Carlos Florêncio 431e5d40fe fix: enforce classified Git admission paths (#2150) (#2181) 2026-08-03 11:04:34 +01:00
Carlos Florêncio 2a2c9d3118 docs: clarify generated task title guidance (#2171) 2026-08-02 21:15:49 +01:00
Carlos Florêncio f51a83e4d3 fix: publish clarification task state updates (#2174) 2026-08-02 20:42:57 +01:00
Carlos Florêncio 484d5b148b feat: track inferred context compactions (#2162) 2026-08-02 17:25:55 +01:00
Carlos Florêncio 554c33f24d feat: bound task status and session traffic (#2148) 2026-08-02 16:06:14 +01:00
Carlos Florêncio 3b00a22589 feat: add optional agent-generated task titles (#2104) 2026-08-02 15:53:46 +01:00
Carlos Florêncio 190eeddbc4 fix: default new workspaces to host GitHub access (#2156) 2026-08-02 14:13:04 +01:00
Carlos Florêncio 1d70a0df6d feat: enforce task title length limit (#2134) 2026-08-01 19:42:23 +01:00
Clément Fiere 59d1cc7277 feat: add Slack-style unread divider to session transcript (#1922) 2026-07-31 14:42:14 +01:00
João Salavisa 9be979827d fix: sync quick chats and their names across devices (#2085)
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-31 09:01:22 +01:00
nova28 9b6d976f3b fix(backend): preserve local repository creation on macOS (#2052) 2026-07-30 16:23:39 +01:00
Carlos Florêncio 21674ec03c fix: bound task cleanup retries and ignore missing resources (#2027) (#2046) 2026-07-29 23:14:36 +01:00
João Salavisa 60040a71f1 fix(backend): return real results from Service.GetBlocking (#2015)
GetBlocking unconditionally returned an empty slice behind a TODO, so any
caller asking "which tasks does this task block?" silently got a wrong
answer. The reverse-lookup query the TODO asked for already exists on the
blocker repository as ListTasksBlockedBy (used by the office scheduler and
the handoff context builder) and is already part of the BlockerRepository
interface, so GetBlocking now delegates to it.

Like GetBlockers, it reports the raw blocker edges without filtering
archived tasks — every other ListTasksBlockedBy consumer does the same.

ListTasksBlockedBy also gains a deterministic ORDER BY (mirroring
ListTaskBlockers) and normalizes an empty result to a non-nil slice.

Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-28 23:03:43 +01:00
Carlos Florêncio a65087e062 fix: pull unstarted feeder tasks into available WIP steps (#2003) 2026-07-28 21:26:05 +01:00
Carlos Florêncio f501346d15 feat: add visible WIP overflow queues (#2001) 2026-07-28 15:46:16 +01:00
Alassane 4411f1c057 fix: match GitLab MR against repository remote_url identity (#1996) 2026-07-28 09:24:57 +01:00
Carlos Florêncio d705b3c2f3 fix(mcp): restore live add-branch worktrees (#1990)
* fix(mcp): restore live add-branch worktrees

* fix(mcp): reject deferred live branch additions

* docs(mcp): clarify live branch response contract
2026-07-27 22:08:18 +01:00
João Salavisa b118a4fe98 fix(mcp): honor explicit task_id in plan/walkthrough/review tools (#1984)
* fix(mcp): honor explicit task_id in plan/walkthrough/review tools

resolveTaskID silently discarded the caller-supplied task_id whenever the
MCP server was session-bound (every agent session) and substituted the
caller's own task. A parent reading a child's plan got the parent's empty
plan back ("No plan exists"), and a cross-task create/update would have
written to the wrong task — all with no error, despite the tool schemas
advertising task_id as a usable parameter.

Honor an explicitly provided task_id and fall back to the session-bound
task only when the argument is absent, matching how message_task_kandev /
stop_task_kandev already address other tasks. Cross-task access stays safe:
internal/mcp/scope attaches the stream owner's identity (from the agent's
own execution, never the payload), and the plan/walkthrough/review services
gate the target task_id through the same workspace-ownership check every
other cross-task surface uses — an out-of-reach task is rejected, not
served. The review service gains the SetTaskAuthorizer wiring the plan and
walkthrough services already had, so publish_review_findings is covered too.

Tool descriptions now document the default-to-current / cross-task-within-
reach behavior. Tests cover the resolution precedence (explicit wins /
fallback to bound / neither errors), a session-bound-to-A reads/creates a
plan for B regression, and the review authorizer allow/deny paths.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(mcp): drop mcp.Required() from task_id on session-defaulting tools

The plan, walkthrough, and publish-review tools default task_id to the
session-bound task when it is omitted, so advertising it as required
contradicted that documented behavior (flagged by Codex and CodeRabbit on
the PR). Mark task_id optional on all eight; handler behavior is unchanged.
The genuinely cross-task tools (update/move/delete/archive_task,
message_task, get_task_conversation) keep task_id required.

Adds a schema test asserting task_id is present-but-optional on every
session-defaulting tool.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* test(mcp): cover review scoping + walkthrough/review tool-desc reach

Addresses two non-blocking review findings:

- Extend TestPlanAndWalkthroughScoping to exercise ReviewService through the
  assembled AuthorizeTaskAccess → SetTaskAuthorizer → PublishFindings path, so
  all three task-scoped services are covered uniformly (foreign owner denied
  with ErrTaskNotFound; real owner passes and the finding is stored).
- Document the default-to-current / cross-task-within-reach semantics in the
  top-level descriptions of the walkthrough and publish-review tools (was only
  in the task_id parameter description), since LLMs read the tool description
  first. Broaden the description test to assert all eight session-defaulting
  tools carry it.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* test(mcp): assert review finding persists through the auth gate

Follow-up to review: query repo.ListTaskReviewFindings after the owner
publish in TestPlanAndWalkthroughScoping and assert exactly one finding was
stored, so the test verifies the write landed in the repository rather than
only the service's returned slice.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-27 18:34:55 +01:00
Carlos Florêncio 06d72a1215 fix: enforce workflow-step WIP limits on task creation (#1980) 2026-07-27 16:14:13 +01:00
Carlos Florêncio 49e00447a5 fix: restore legacy GitHub launch compatibility (#1962) 2026-07-26 19:07:46 +01:00
João Salavisa bb72d70586 refactor(backend): remove dead code and deprecated shims (#1965)
Delete unreachable/unused backend symbols confirmed by staticcheck U1000
and golang.org/x/tools/deadcode, plus deprecated back-compat aliases kept
alive only by their own tests.

Removed (unused):
- parseGitHubRepoURL, syncTaskStateForBulkWorkflowMove (task/service)
- resolvePrimaryRepoInfo (orchestrator/executor)
- resolveWorkflowAgentProfile, workflowDefaultAgentProfile wrappers (mcp/handlers)
- cleanupExitedContainer (runtime/lifecycle) + orphaned fmt import
- VscodeManager.setEnv (agentctl/server/process)
- repoRootDir const (cmd/preview)

Removed (deprecated shims):
- Canceller.CancelSessionAndNotify alias -> callers use DetachSessionAndNotify
- ScriptPlaceholder type alias (live scriptPlaceholders var kept)
- Placeholder{QueueRun,ClearDecisions,QueueRunForEachParticipant}Callback
  no-op structs and their self-referential test

No behavior change; build, vet, and affected-package tests pass.

Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-26 17:54:12 +01:00
João Salavisa 57adf1449c feat(review): native code-review agent with inline findings in the Changes panel (#1957)
* feat(review): persist and publish native code-review findings

Adds the backend core for reviewing a task's working diff before a PR
exists: task-scoped review runs and anchored, advisory findings that the
Changes/Review panel can render as inline comments.

- task_review_runs / task_review_findings schema, models, and repository,
  with supersede-on-re-review and a restart sweep that cancels in-flight
  runs rather than leaving them looking alive.
- ReviewService as the single write path, publishing bus events that the
  WS gateway forwards to the client.
- internal/review: reviewer-identity resolution (agent profile > code-review
  utility agent > user default, failing closed on passthrough-only profiles),
  change-set collection, prompt batching, response parsing, anchor
  extraction, and run orchestration.
- publish_review_findings_kandev MCP tool plus the task.review.* WS actions.
- Go djb2 that matches apps/web/lib/utils/hash.ts, asserted from shared
  fixtures on both sides so stale detection agrees across the wire.

Spec: docs/specs/native-code-review/spec.md
Plan: docs/plans/native-code-review/plan.md

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(review): add run_code_review workflow step and wire the review runner

Makes a review pass triggerable both ways and actually runnable end to end.

- run_code_review on_enter action across models, engine compile, and an
  orchestrator callback that logs rather than propagates failures, so a task
  never gets stuck in a step because no reviewer was configured.
- The step's optional agent_profile_id is what lets a step review with a
  different model than it implemented with; export/import swap it for a
  portable agent name/model/mode so it survives a cross-workspace round trip
  instead of carrying a dangling id.
- Concrete adapters for reviewer identity, changed-file collection, prompt
  rendering from the code-review utility agent's editable prompt, and
  inference (session-bound agentctl, falling back to the host instance so a
  review works on a task whose agent is not running).
- Boot sweep cancels review runs interrupted by a restart; the E2E reset
  clears review state before deleting the tasks that own it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(web): add review findings state, helpers, and live updates

Frontend plumbing for native code review, ahead of the UI that renders it.

- Review types, WS message map, and an API client that preserves the backend's
  machine-readable failure code so the surface can show an actionable message.
- A review store slice that merges findings by id (a re-publish refreshes an
  issue rather than listing it twice) and keeps a bounded run history.
- Findings helpers: composite file keys matching reviewFileKey, staleness via
  the same per-file diff hash that drives review marks, and best-effort
  re-anchoring from the stored anchor text so a moved finding follows the code
  it was written about instead of pointing at whatever now occupies its line.
- Hooks for backfill, resolve/dismiss/reopen with optimistic rollback, and
  sending a finding to the agent as follow-up context without changing its
  status — handing a finding to an agent is not the human accepting it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(web): render review findings inline in the Changes diff

Findings now appear where the code is, in the same annotation surface as
anchored review comments, with the run control that produces them.

- ReviewFindingCard: severity chip, category, Markdown body, and the three
  advisory actions. A suggestion is labelled "not applied automatically"
  because it is display-only in this iteration. Resolved and dismissed
  findings collapse to one muted line with an Undo, so a reviewed diff does
  not stay cluttered while the human can still change their mind.
- A review-finding annotation type threaded through the diff viewer, anchored
  from the same per-file diff hash the backend stamped. A finding whose diff
  moved is re-anchored from its stored text when that text survives, and
  otherwise reported as unanchored rather than placed against unrelated code.
- Review changes control with idle / running / cancel / failed states, and an
  inline Settings link for the one failure the user can actually fix.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(web): make the review control reachable from the Review toolbar

Mounts the Review changes control next to the walkthrough action and lets an
inline finding wire its own actions.

The finding card container now reads the active task and session from the store
instead of taking four callbacks threaded through FileDiffViewer and DiffViewer;
an inline finding annotation only exists when the active task has findings, so
the store is always present and every other diff consumer is spared the
plumbing. Staleness likewise hashes the diff the viewer already holds, which is
already normalized, so it matches the hash the backend stamped without passing
it down.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(web): surface stale review findings above their file's diff

A finding whose diff moved and whose anchor text is gone had nowhere to render,
so it was silently dropped. It now appears in a collapsed per-file banner above
the diff: the finding may still be valid, and placing it at its stored line
would point at whatever code now occupies that line instead.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* docs(review): mark the landed native code-review plan tasks done

Tasks 01-09 (backend persistence through inline diff rendering) are
implemented, tested, and committed. Tasks 10-13 — findings overview and step
editor, mobile parity, E2E, and public docs — remain pending.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* test(review): cover the on-demand review path end to end

Adds the mock-agent review responder and a Playwright spec, so both the happy
path and the no-reviewer path are verified against a real backend.

The mock agent answers any prompt carrying the review sentinel with fenced JSON,
deriving its anchors from the prompt's own diff rather than hardcoding them, so
findings land on files and lines the fixture really changed. It includes one
deliberately malformed entry to exercise the rejected-entry path.

Writing it caught an off-by-one shared by three diff walkers: splitting on "\n"
leaves an empty element after a trailing newline, which carries no diff marker
and was being counted as a context line, pushing new-side numbering one past the
end of a hunk. Interior blank lines still count, since a whitespace-stripped
blank context line legitimately appears as "".

Also adds a listInferenceAgents helper: default_utility_agent_id needs the
registered agent-type id, and an agent row UUID is rejected as not
inference-capable.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(review): close review-run races and stale client findings

Addresses the three blockers and three suggestions from the PR #1957 automated
reviews. Two independent reviewers found each blocker separately.

- Launch claimed the task slot only after inserting the run row, so two
  concurrent launches both created a run and the loser returned a pending row
  with no goroutine behind it — a review that never finished until the next
  restart. The slot is now claimed before any DB write, and freed on every
  early return.
- Cancelling only marked the row. The goroutine ran on the shared background
  context, finished inference, and its completion overwrote the cancelled
  status and published findings the user had declined. Runs now carry a cancel
  handle, the WS action routes through the runner so the live context is
  cancelled, CompleteRun/FailRun refuse to resurrect a terminal run, and a
  cancelled pass neither publishes nor re-reports itself as failed.
- The backend deletes a superseded finding and inserts a replacement with a new
  id, but the publish event carried only the new one, so every open browser
  showed both at the same anchor until a reload. The event now names the
  superseded ids and the slice drops them.
- Run() waited on the shared WaitGroup, blocking on every other task's review;
  it now waits on its own pass only.
- createReviewSlice is typed over the `set` it actually uses, so call sites no
  longer pass superfluous arguments (CodeQL js/superfluous-trailing-arguments).
- A GetAgentProfile fault no longer collapses into "profile not found", which
  would have told the user to configure an agent they already have.

The cancel bug exposed a hole in the original tests: they asserted cancel could
not override a terminal run, but never the reverse. Both directions are covered
now, along with the concurrent-launch race, per-run waiting, and the supersede
path on both sides of the wire. Test fakes now mirror the service's terminal
guard rather than hiding it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-26 15:05:56 +01:00
Carlos Florêncio 6ffb23c187 fix: harden background work lifecycle tracking (#1955) 2026-07-26 14:18:35 +01:00
João Salavisa c3d235b83b fix(auth): close per-user session isolation gaps (service, WS, orchestrator) (#1939)
* fix(auth): scope session-keyed reads and mutations to the workspace owner

Session-keyed service entry points did not apply per-user scoping, so
knowing another user's session or task ID was enough to reach it:

- GetTaskSession, ListTaskSessions, GetPrimarySession returned rows for
  any ID. These feed GET /task-sessions/:id and GET /tasks/:id/sessions,
  whose DTO carries session Metadata, the host worktree path, the branch,
  and container/executor IDs.
- DismissLastAgentError mutated any session.
- ApproveSession approved a workflow review step on any session, which
  advances the task's workflow — the highest-impact of the set.

Authorize via authorizeTaskID off the row already read, rather than
AuthorizeSessionAccess, which would re-read the session on what is a hot
path. Internal identity-less callers (pollers, event bus, office
schedulers, office agent JWTs) and the synthetic identity used while auth
is disabled stay unscoped, and unowned pre-auth rows stay visible.

Batch helpers that take ID lists are deliberately left alone: their
callers derive IDs from an already-authorized task list, so per-ID checks
would add N queries to list views for no gain. Recorded in AGENTS.md.

Also route httpApproveSession through handleNotFound so a denial answers
404 like every other session route instead of a 500 that would confirm
the session exists.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(auth): scope the session-keyed paths that bypass the task service

An adversarial sweep of the previous commit found session-keyed surfaces
reachable with a caller-supplied ID and no ownership check. They bypass
the task service, so scoping its methods did not cover them:

- POST /task-sessions/:id/{set-mode,set-model,set-config-option,
  authenticate} and .../processes/:processId/stop resolve their execution
  with a bare in-memory lookup, which skips the GetOrEnsure* chokepoint
  where the lifecycle per-user check runs. A non-owner could switch
  another user's model or mode, re-authenticate their agent, or kill
  their process. Guarded by a shared denySessionAccess helper.
- The orchestrator reads sessions through its own repo handle, so
  GetTaskSessionStatus and CheckSessionPR inherited nothing from the task
  service. CheckSessionPR also installs a PR watch as a side effect.
  Added a SetSessionAccessChecker hook mirroring the lifecycle manager's,
  wired to taskSvc.AuthorizeSessionAccess. The check runs before
  CheckSessionPR's unconfigured-GitHub early return so it applies
  regardless of setup, and denials reuse the "session not found" shape so
  they cannot be told apart from a missing session.
- GetMessage had no scoping while ListMessages beside it did, so a
  caller holding another user's (session_id, message_id) pair could read
  their shell output.

This does NOT close the whole surface. A second sweep found the
orchestrator's session-mutating WS actions (session.stop/delete/rename/
set_primary/set_plan_mode/reset_context/recover/launch/ensure,
agent.cancel, permission.respond) and agent.stdin / agent.resize also
unscoped — agent.stdin writes arbitrary input into another user's agent
process. Those touch live session lifecycle and need their own change;
recorded in AGENTS.md so the gap is not mistaken for covered.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(auth): scope every session-keyed WS action, plus a gateway backstop

Completes the sweep. Dispatched WS actions were left to authorize
themselves at the service layer, and a dozen never did — a caller with a
guessed session ID could stop, delete, rename, relaunch or reset another
user's live agent session, cancel their in-flight turn, answer their
permission prompts, or write arbitrary bytes into their agent process.

Two layers, deliberately both:

1. Gateway backstop. Client.authorizeAction checks any dispatched payload
   carrying task_id or session_id against the client's identity before
   dispatch. Per-method opt-in across ~74 actions in four packages had
   been missed repeatedly; this makes a newly added action scoped by
   default. Verified safe to apply generically: session_id means a task
   session everywhere, and user-shell/terminal actions key off task_id /
   task_environment_id, so nothing is misread.

2. Explicit guards, for defense in depth and for non-WS callers:
   - orchestrator: StopSession, DeleteSession, SetPrimarySession,
     RenameSession, ResetAgentContext, CancelAgent, RespondToPermission,
     SetSessionPlanModeByID, RecoverSession, LaunchSession, EnsureSession,
     CancelTransientRetry. Added SetTaskAccessChecker for the task-keyed
     ones. LaunchSession guards every intent at the single funnel;
     SessionID is empty on create, so the task check carries that case.
   - agent.stdin / agent.resize now call lifecycleMgr.CheckSessionAccess,
     the helper already documented for bare-lookup handlers.

Guards go first in each method, before any repo/executor use.
TestSessionKeyedEntryPointsGuardBeforeDependencies runs all twelve with
nil dependencies and fails on a panic if one is placed too late.

Denials are indistinguishable from a missing resource: WS returns
not-found, CancelTransientRetry reports "nothing cancelled", and
GetTaskSessionStatus reuses its "session not found" shape.

Unwired checkers stay permissive throughout, so identity-less internal
callers (schedulers, event bus, workflow engine) and pre-auth single-user
instances are unaffected — pinned per entry point.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(auth): scope environment-keyed user-shell actions

Third sweep finding, in surface the previous commit's own comment claimed
was covered. The user-shell actions key off task_environment_id and treat
task_id as optional, so a task_id-only backstop missed them:
user_shell.stop with an empty task_id and a foreign task_environment_id
fell through to the legacy runner path and tore down another user's
terminal PTY. That path never reaches
GetOrEnsureExecutionForEnvironment, where the environment check normally
runs, so neither layer caught it.

- Gateway backstop now also reads task_environment_id, gated by a new
  AuthPolicy.ActionEnvironment hook wired to
  taskSvc.AuthorizeEnvironmentAccess. This covers all three
  environment-keyed actions generically, not just the reported one.
- wsUserShellStop guards explicitly via a new
  lifecycleMgr.CheckEnvironmentAccess, mirroring CheckSessionAccess, so
  the fallback is safe independent of the gateway.

Corrected the comment that wrongly asserted task_environment_id was
already covered, and recorded in AGENTS.md both the exact field names the
backstop reads and why a permissive type on one of them would silently
opt out.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(auth): authorize both IDs on task+session entry points

Review finding (P1). Entry points taking both a task and a session ID
only checked the session, so a caller could satisfy that check with one
of their own sessions while pointing taskID at another user's task:

- CheckSessionPR then used the unchecked taskID for GetTaskPR,
  resolveTaskRepo, resolvePrimaryTaskRepositoryID and EnsurePRWatch —
  cross-workspace PR disclosure plus a PR-watch write.
- CancelTransientRetry handed it to handleRecoverableFailure, which
  writes against that task.

Both now use a new authorizeTaskSessionPair, which authorizes each ID and
additionally requires the pair to be consistent, so the two arguments
cannot describe different tasks. GetTaskSessionStatus already validated
the pair after loading the session and is unchanged.

The consistency half is skipped when the session cannot be loaded: both
IDs are authorized by then, so a mismatch is a caller bug rather than a
cross-user leak, and failing there would change behavior for
identity-less internal callers.

Recorded the rule in AGENTS.md — a two-ID entry point must never use
authorizeSession alone.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(auth): scope AttachWorkspaceSources

Found while rebasing onto main. POST /tasks/:id/workspace-sources and the
add_workspace_sources_kandev MCP tool landed on main during this PR's
review with no ownership check, so a caller could attach repositories and
folders to another user's task and have them materialized into that
task's workspace.

Same class as the rest of this PR, so fixed here rather than left for a
follow-up. The WS dispatch backstop added earlier already covered the
browser path (the payload carries task_id); this closes the HTTP route
and the MCP tool, which do not go through it.

ErrTaskNotFound already maps to 404 in workspaceSourceHTTPStatus, so the
denial surfaces correctly without touching the handler.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(auth): map denied shell-output reads to 404

Review finding. GetMessage became per-user scoped earlier in this PR, so
a denial now arrives as ErrTaskNotFound. httpGetShellOutput only mapped
sql.ErrNoRows to 404, sending everything else to the 500 branch — so a
foreign message answered 500 while a missing one answered 404, which is
an existence signal and inconsistent with the 404-everywhere rule the
other session routes follow.

Kept the sql.ErrNoRows branch explicit rather than replacing it outright:
isNotFound classifies typed sentinels and the "not found" substring, and
"sql: no rows in result set" matches neither, so routing that case
through handleNotFound alone regressed the missing-message response to
500 (caught by TestHTTPShellOutputSnapshot).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* test(auth): make the shell-output scoping test actually exercise the guard

Both reviewers caught that TestHTTPGetShellOutputDeniesForeignMessageWith404
was vacuous. httpGetShellOutput has a second 404 gate after the service
call — `if !ok || message.TaskSessionID != c.Param("id")` — and
ExtractShellExecOutput returns ok=false for nil metadata. The fixture had
none, so the route answered 404 through that gate whether or not scoping
denied the read.

Confirmed by mutation rather than inspection: with the authorization
removed from GetMessage the test still passed. With valid shell-output
metadata in the fixture it returns 200 and the victim's stdout, so the
test fails as intended; restoring the guard makes it pass again.

Also mutation-tested the sibling denial tests, since this is a defect
class rather than a one-off:
- TestHTTPGetTaskSessionDeniesForeignSessionWith404 — sound, returns 200
  with the session DTO when the guard is removed.
- TestProcessRoutesDenyForeignSession — catches removal, though via the
  documented nil-lifecycleMgr panic rather than a status assertion.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* test(auth): add an in-test witness to the shell-output scoping test

Review suggestion. The fixture fix made the test exercise the guard, but
nothing in the test proved the 404 came from authorization rather than the
route's post-service `!ok` gate — which is exactly how it went vacuous in
the first place. The evidence lived in a commit message describing a
manual mutation run, not in the test.

Now asserts both directions, matching the approve-route test: the
non-owner gets 404, and the owner does NOT. If the assertion ever stops
proving authorization, the owner case fails and says so.

Re-verified by mutation: removing the guard from GetMessage fails the test
with 200 and the victim's stdout; restoring it passes.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-26 14:09:52 +01:00
Carlos Florêncio 45ba6691c9 fix: isolate task state when switching workspaces (#1951) 2026-07-26 10:40:40 +01:00