919a39e49a
* feat(auth): add auth core — identities, sessions, PATs, invites, mode state machine Phase 1 of opt-in authentication + multi-user segregation: - internal/auth: argon2id password hashing (PHC), opaque session/PAT tokens (SHA-256 at rest), login rate limiter, auth-mode state machine (disabled/setup/enabled), setup-wizard promotion of the pre-auth default-user row into the admin account, invites, admin user management with last-admin guard. - internal/auth/store: auth_identities (OIDC-ready), auth_sessions, auth_api_tokens, auth_invites tables (SQLite+Postgres dialects). - internal/auth/authn: request-identity plumbing (gin + plain contexts), RequireAdmin middleware. - users table: display_name/role/status columns via new MigrateLogger wiring; AccountRepository surface (consumer-scoped, keeps existing Repository fakes untouched). - config: AuthConfig.Required/SessionTTLHours/CookieName (KANDEV_AUTH_REQUIRED), FeaturesConfig.Auth; profiles.yaml + runtime flag registry entry for KANDEV_FEATURES_AUTH. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(auth): enforce opt-in auth over HTTP — middleware, auth API, boot payload Phase 2 of opt-in authentication + multi-user segregation: - internal/auth/httpmw: global gin middleware after CORS. Disabled mode injects the synthetic single-user admin identity (behavior unchanged); enabled mode resolves session cookie then PAT bearer, with an explicit allowlist (health, SPA bootstrap reads, credential endpoints, self-authenticating webhooks), deferral for WS/proxy upgrades and office agent JWTs, and SPA shell availability for the login page. - internal/auth/httpapi: full auth surface — setup wizard, login/logout, me, password change, sessions, PATs, invites (mint/preview/accept), auth settings (enable/disable), admin user management. - Boot payload: initialState.auth block always present; unauthenticated visitors on auth-enabled instances get features+auth only (no data). - External MCP: PAT required once auth is enabled (open while disabled). - Admin guards on destructive system routes and runtime-flag overrides. - Startup warning when bound non-loopback with auth disabled (ServerConfig.NonLoopbackBinds fail-closed nudge). - Wiring: auth store in Repositories, auth service in Services, ClaimUnownedWorkspaces backfill on the task repository. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(auth): per-user workspace scoping across HTTP services Phase 3 of opt-in authentication + multi-user segregation: - Task service: workspaces, workflows, repositories, and tasks are scoped to the request identity (owner-only visibility; pre-auth unowned rows stay shared). Denials use *NotFound sentinels - no existence leak. Internal callers and the disabled-mode synthetic identity remain unscoped, preserving behavior exactly when auth is off. - CreateWorkspace stamps the authenticated caller as owner. - Session chokepoint: lifecycle Manager.GetOrEnsureExecution runs a settable session-access check covering shell/files/ports/vscode/LSP. - Secrets: per-user user_id column, scoped CRUD/list, ClaimUnowned wired into the setup-wizard backfills. - Boot payload inherits scoping automatically. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(auth): scope WebSocket gateway to authenticated users Phase 4 of opt-in authentication + multi-user segregation: - Connection auth: /ws, /terminal, /lsp, /vscode, /port-proxy routes are guarded when auth is enabled - session cookie (same-origin upgrade), resolved identity from the HTTP middleware, or ?token=<PAT> for headerless programmatic clients; JSON 401 before any upgrade. - Client identity: every WS client carries its authn.Identity; dispatched RPC actions (workspace.list, task CRUD, ...) run under a context carrying it, so WS RPC gets the same per-user scoping as HTTP. - Subscription checks: task/session subscribe+focus verify workspace visibility via the task service; user topic subscriptions are pinned to the client's own user. - Broadcast routing: new Hub.BroadcastToWorkspace routes workspace-scoped events (task/workflow/repo/office/session-state) to the owner's clients only, with safe fallbacks (unowned/unresolvable -> broadcast) so events never vanish; instance-wide events (executors, environments, agent profiles, system jobs) stay global by design. - Replaced the long-standing discarded-token TODO in HandleConnection. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * docs(auth): add feature spec and backend architecture notes for opt-in auth - docs/specs/auth/spec.md: product behavior (opt-in, setup wizard, per-user workspaces, sessions/PATs, invites, public surface, v1 limits) - apps/backend/AGENTS.md: internal/auth package layout + scoping rules for new service entry points and WS broadcast call sites Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * docs(auth): public documentation for opt-in authentication - New docs/public/authentication.md: enabling, users & invites, PATs, public endpoints, limitations, disabling - run-as-a-service.md: network-security note now points at the real authentication boundary instead of reverse-proxy-only guidance - meta.json: nav entry under Configure Kandev Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * docs(auth): ADR for opt-in authentication architecture Records the load-bearing choices: mode state machine + synthetic identity in disabled mode, opaque DB-backed credentials over JWTs, default-user promotion at setup, service-layer scoping with no-admin-bypass, and the explicit public allowlist. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(web): auth UI — login, setup wizard, invites, users & account settings Adds the frontend half of opt-in authentication: a pre-auth gate in main.tsx that renders the setup wizard or login/invite pages instead of the app shell whenever the boot payload's auth block says so, a new `auth` store slice + feature flag mirroring the backend's StatePayload, credentialed fetch (`credentials: "include"`) with a 401 handler that clears the session and redirects to /login, and a full auth-api.ts client for the /api/v1/auth and /api/v1/users routes. Settings additions: a System > Users page (list/create/disable/promote users, invite-link dialog) and System > Authentication page (enable/ disable with confirm + env-locked banner), gated on the `auth` feature flag and admin role. A new Account sidebar group (Profile & Password, API Tokens) is shown to signed-in users once auth is enabled. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * test(auth): E2E lifecycle suite + fix workspace event WS leak it caught New dedicated Playwright auth project (backend restarts with KANDEV_AUTH_REQUIRED=true, isolated from the tokenless default suite): setup-mode boot gating, admin setup wizard, login/logout + bad credentials, PATs, admin-surface authorization, anonymous WS rejection, UI login flow, and the acceptance test - two-user segregation across HTTP, boot payload, and WebSocket. The segregation spec immediately caught a real leak: workspace.* event payloads carry their ID as 'id' (the payload IS the workspace DTO), not 'workspace_id', so BroadcastToWorkspace fell back to broadcast-to-all for workspace create/update/delete. Fixed with action-aware extraction plus a unit regression test. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(auth): close cross-user access gaps found in security audit Two independent security audits of the auth branch found several authorization gaps where session/workspace-scoped surfaces were not wired to the new per-user chokepoint. All fixed: - IDOR on reverse-proxy/terminal routes (vscode, port-proxy, terminal): these resolve executions via GetExecutionBySessionID / GetOrEnsureExecutionForEnvironment / EnsurePassthroughExecution, which skipped the session-access check that only GetOrEnsureExecution ran. Added the check inside the env/passthrough resolvers (before the cache short-circuit) and an explicit CheckSessionAccess gate in the two bare-lookup proxy handlers. An authenticated non-owner can no longer reach another user's IDE, forwarded ports, or shell. - Cross-user agent-conversation read: ListMessages / ListMessagesPaginated / SearchMessages now authorize the session. - Cross-user repository-script read/inject: script CRUD now authorizes the parent repository's workspace. - Office HTTP surface: a group middleware enforces workspace ownership on :wsId routes for real users (agent-JWT callers keep their claim scoping). - Login rate-limit bypass: SetTrustedProxies(nil) so a spoofed X-Forwarded-For can't rotate the limiter key on a directly-reachable backend. - Invite double-provisioning race: MarkInviteUsed is now the atomic serialization point (consumed before user creation). - Setup wizard: serialized with a mutex so concurrent first-visitors can't corrupt the promoted admin profile. - Log sanitizer: explicit kandev_pat_ redaction rule. Regression tests added for message/script scoping and the execution-access-before-cache invariant. Auth E2E (incl. two-user segregation) still green. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(auth): scope repository active-session-count endpoint GET /api/v1/repositories/:id/active-session-count went through CountActiveSessionsByRepository, which was not identity-scoped - a cross-user info leak of another owner's active session counts. Added the same authorizeRepositoryID gate the script routes use. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(auth): add json tags to auth store models — omit digests, fix token UI The auth store structs (APIToken, Invite, LoginIdentity, Session) had db: tags but no json: tags, so the handlers that serialize them directly sent Go-cased keys (CreatedAt, Name) AND leaked the SHA-256/password digests to clients. Two consequences: - The API-tokens UI showed 'Invalid Date' and an empty name (frontend reads created_at/name). - token_sha256 / password_hash were serialized in list responses. Added json tags with snake_case keys the frontend reads and json:"-" on every credential digest. Regression test asserts digests never serialize and the snake_case timestamp/name keys are present. Also adds the auth-screenshots capture spec (artifacts gitignored). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(web): move auth enable into feature toggles; show current user in sidebar Remove the standalone Authentication settings page and its dedicated settings/get-auth-settings API surface now that enabling auth lives in the Feature Toggles system, and drop env_required now that /auth/me no longer returns it. Add a current-user chip with a logout action to the sidebar footer, shown only in enabled auth mode. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * refactor(auth): make features.auth the single on/off control Per review feedback: authentication configuration now lives entirely in the existing Feature Toggles system rather than a separate Authentication settings section. - The auth mode is derived from the features.auth runtime flag (KANDEV_FEATURES_AUTH): off -> disabled, on+no-admin -> setup, on+admin -> enabled. Removed the parallel auth.mode system setting, the SetEnabled service method, GET/PATCH /api/v1/auth/settings, the AuthConfig.Required field, KANDEV_AUTH_REQUIRED, and the auth service's Settings-store dependency and EnvRequired/env_required. - The features.auth registry entry is re-described as the actual enable switch (high-risk, restart-required) and defaults off in every profile (dev was previously true — that only revealed UI before; now it would enforce, so it must be an explicit opt-in). - Setup no longer persists a mode; completing the wizard creates the admin and the mode auto-derives to enabled. - Startup 'exposed without auth' warning + all docs (public guide, run-as-a-service, spec, ADR, AGENTS.md) point at the feature toggle. - E2E: auth specs use KANDEV_FEATURES_AUTH; screenshot spec captures the Feature Toggles page instead of the removed Authentication page; the member-restriction assertion targets an admin invite route. - Tests updated across service/httpmw/httpapi/profiles for the derived mode; full suite green (only pre-existing sandbox-FS failures remain). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(auth): complete cross-user isolation — integrations, automation, plan/walkthrough, session reads A follow-up isolation audit found that per-user scoping had been wired into the task service, secrets, office, and the WS gateway — but several workspace/task/session-scoped surfaces still resolved a caller-supplied ID with no ownership gate. Closed all of them; cross-user access now returns 404 across the board. - Integrations (jira/linear/sentry/slack/azure-devops/gitlab/github/ workflow-sync): a global middleware authorizes the workspace_id (query, or gitlab's /workspaces/:id/ path) on those route groups. Previously a member who knew another user's workspace ID could read/overwrite their integration connection config and watches. - Automation: workspace-authorizer seam gates get/list/create/update/delete/ enable/disable, triggers, run history, and — critically — the webhook secret. Was fully cross-tenant over WS before. - Task plans (PlanService) and walkthroughs (WalkthroughService): task- authorizer seam on every read/write. These bypassed the task service. - Session reads that hit the repo directly — session turns, task context, git snapshots, file reviews — now call AuthorizeSession/TaskAccess. Internal callers (pollers, schedulers, MCP) carry no identity and stay unscoped; disabled mode is unaffected. Regression tests added (plan/walkthrough scoping, automation authorizer matrix, integration path extraction) and the two-user E2E now asserts integration routes are shielded. Docs (spec, ADR, public guide) updated to state what is isolated and that filesystem/agent-credential isolation remains an OS-level limitation. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(web): current-user chip uses border hover, not accent fill The sidebar current-user chip used hover:bg-accent (a purpleish fill). Switch to the border-hover idiom used elsewhere (border border-transparent -> hover:border-border) with the neutral hover:bg-muted/50 the adjacent workspace picker uses, so the hover reads as a subtle outline instead of a colored background. Screenshot spec now captures the chip hover state. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(web): right-align current-user chip in the sidebar footer Push the user chip to the far right of the expanded footer (ml-auto) so it sits opposite the left-aligned icon buttons; collapsed mode keeps the centered vertical stack unchanged. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(auth): reject synthetic identity on management routes and scope office run broadcasts Address code-review findings on the opt-in authentication PR: - P1: while auth is disabled the middleware injects a synthetic admin (RoleAdmin), and RequireAdmin alone let it through — so anyone hitting a not-yet-enabled instance could mint a PAT or plant an admin that survives enablement and hijacks first-run setup. Add authn.RequireRealIdentity and guard the credential/session/user-management routes with it (public bootstrap routes stay reachable). Responds 404 while disabled. - P1: office run events carry task_id but no workspace_id, so they fell back to a global broadcast and leaked across users. Resolve the workspace from the task and route via the new Hub.BroadcastToWorkspaceOrDrop, which fails closed (drops rather than global-broadcasts) when the workspace is unknown and auth is enforced. - nit: type createAuthSlice as a single-arg creator and call it with just set. Also register the authentication docs page and its settings routes in docs/public/coverage.json so the public-docs validator passes. 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>
574 lines
17 KiB
Go
574 lines
17 KiB
Go
package service
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"os"
|
|
"strconv"
|
|
"time"
|
|
|
|
"go.uber.org/zap"
|
|
|
|
"github.com/kandev/kandev/internal/common/logger"
|
|
"github.com/kandev/kandev/internal/events"
|
|
"github.com/kandev/kandev/internal/events/bus"
|
|
"github.com/kandev/kandev/internal/task/models"
|
|
"github.com/kandev/kandev/internal/task/repository"
|
|
)
|
|
|
|
var (
|
|
ErrTaskPlanNotFound = errors.New("task plan not found")
|
|
ErrTaskIDRequired = errors.New("task_id is required")
|
|
ErrContentRequired = errors.New("content is required")
|
|
ErrSessionIDRequired = errors.New("session_id is required")
|
|
ErrRevisionNotFound = errors.New("task plan revision not found")
|
|
ErrRevisionIDRequired = errors.New("target_revision_id is required")
|
|
ErrRevisionTaskMismatch = errors.New("revision does not belong to given task")
|
|
ErrSessionTaskMismatch = errors.New("session does not belong to given task")
|
|
)
|
|
|
|
const (
|
|
createdByAgent = "agent"
|
|
createdByUser = "user"
|
|
defaultCoalesceWindow = 5 * time.Minute
|
|
coalesceWindowEnvVar = "KANDEV_PLAN_COALESCE_WINDOW_MS"
|
|
defaultAgentAuthorFallback = "Agent"
|
|
defaultUserAuthorFallback = "User"
|
|
)
|
|
|
|
// planRepo is the repository surface this service depends on. It combines the
|
|
// plan-revision storage with a tiny slice of session lookups used to resolve
|
|
// the active session's agent profile name when the MCP path doesn't provide
|
|
// an explicit author_name.
|
|
type planRepo interface {
|
|
repository.PlanRepository
|
|
GetActiveTaskSessionByTaskID(ctx context.Context, taskID string) (*models.TaskSession, error)
|
|
GetTaskSessionByTaskID(ctx context.Context, taskID string) (*models.TaskSession, error)
|
|
GetTaskSession(ctx context.Context, id string) (*models.TaskSession, error)
|
|
}
|
|
|
|
// PlanService provides task plan business logic.
|
|
type PlanService struct {
|
|
repo planRepo
|
|
eventBus bus.EventBus
|
|
logger *logger.Logger
|
|
coalesceWindow time.Duration
|
|
// authorizeTask gates plan access by the task's workspace ownership
|
|
// (opt-in auth). Nil = unscoped (internal callers / auth disabled).
|
|
authorizeTask func(ctx context.Context, taskID string) error
|
|
}
|
|
|
|
// NewPlanService creates a new task plan service. The concrete repository
|
|
// passed by callers must implement both PlanRepository and the session-lookup
|
|
// methods on planRepo (the SQLite repository does both).
|
|
func NewPlanService(repo planRepo, eventBus bus.EventBus, log *logger.Logger) *PlanService {
|
|
return &PlanService{
|
|
repo: repo,
|
|
eventBus: eventBus,
|
|
logger: log.WithFields(zap.String("component", "plan-service")),
|
|
coalesceWindow: readCoalesceWindow(),
|
|
}
|
|
}
|
|
|
|
// SetTaskAuthorizer wires the per-user task-access check (opt-in auth). The
|
|
// authorizer must return nil for contexts without a request identity.
|
|
func (s *PlanService) SetTaskAuthorizer(fn func(ctx context.Context, taskID string) error) {
|
|
s.authorizeTask = fn
|
|
}
|
|
|
|
func (s *PlanService) authorize(ctx context.Context, taskID string) error {
|
|
if s.authorizeTask == nil {
|
|
return nil
|
|
}
|
|
return s.authorizeTask(ctx, taskID)
|
|
}
|
|
|
|
func readCoalesceWindow() time.Duration {
|
|
raw := os.Getenv(coalesceWindowEnvVar)
|
|
if raw == "" {
|
|
return defaultCoalesceWindow
|
|
}
|
|
ms, err := strconv.Atoi(raw)
|
|
if err != nil || ms < 0 {
|
|
return defaultCoalesceWindow
|
|
}
|
|
return time.Duration(ms) * time.Millisecond
|
|
}
|
|
|
|
// CreatePlanRequest contains parameters for creating/updating a task plan.
|
|
// AuthorKind and AuthorName are optional; when absent they are derived from CreatedBy.
|
|
type CreatePlanRequest struct {
|
|
TaskID string
|
|
Title string
|
|
Content string
|
|
CreatedBy string // "agent" | "user"
|
|
AuthorKind string // optional explicit override
|
|
AuthorName string // optional; display snapshot
|
|
}
|
|
|
|
// CreatePlan upserts a plan and appends or coalesces a revision.
|
|
func (s *PlanService) CreatePlan(ctx context.Context, req CreatePlanRequest) (*models.TaskPlan, error) {
|
|
if err := s.authorize(ctx, req.TaskID); err != nil {
|
|
return nil, err
|
|
}
|
|
return s.upsertPlan(ctx, req)
|
|
}
|
|
|
|
// UpdatePlanRequest mirrors CreatePlanRequest; kept as a distinct type for API clarity.
|
|
type UpdatePlanRequest struct {
|
|
TaskID string
|
|
Title string
|
|
Content string
|
|
CreatedBy string
|
|
AuthorKind string
|
|
AuthorName string
|
|
}
|
|
|
|
// UpdatePlan updates an existing plan (errors if missing).
|
|
func (s *PlanService) UpdatePlan(ctx context.Context, req UpdatePlanRequest) (*models.TaskPlan, error) {
|
|
if req.TaskID == "" {
|
|
return nil, ErrTaskIDRequired
|
|
}
|
|
if err := s.authorize(ctx, req.TaskID); err != nil {
|
|
return nil, err
|
|
}
|
|
existing, err := s.repo.GetTaskPlan(ctx, req.TaskID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if existing == nil {
|
|
return nil, ErrTaskPlanNotFound
|
|
}
|
|
title := req.Title
|
|
if title == "" {
|
|
title = existing.Title
|
|
}
|
|
createdBy := req.CreatedBy
|
|
if createdBy == "" {
|
|
createdBy = existing.CreatedBy
|
|
}
|
|
return s.upsertPlan(ctx, CreatePlanRequest{
|
|
TaskID: req.TaskID,
|
|
Title: title,
|
|
Content: req.Content,
|
|
CreatedBy: createdBy,
|
|
AuthorKind: req.AuthorKind,
|
|
AuthorName: req.AuthorName,
|
|
})
|
|
}
|
|
|
|
// upsertPlan is the shared write path. It upserts the task_plans HEAD row and either
|
|
// coalesces into the latest revision (same author within window) or appends a new revision
|
|
// — both steps run in one write transaction via WritePlanRevision so HEAD and history
|
|
// cannot diverge under concurrent writers or partial failures.
|
|
func (s *PlanService) upsertPlan(ctx context.Context, req CreatePlanRequest) (*models.TaskPlan, error) {
|
|
if req.TaskID == "" {
|
|
return nil, ErrTaskIDRequired
|
|
}
|
|
|
|
title := req.Title
|
|
if title == "" {
|
|
title = "Plan"
|
|
}
|
|
// Resolve a missing AuthorName for agent writes from the active session's
|
|
// profile snapshot before falling back to the literal "Agent". The MCP path
|
|
// (handleCreateTaskPlan / handleUpdateTaskPlan) doesn't carry the agent's
|
|
// display name in the request, so without this lookup every agent revision
|
|
// would render as "Agent" in the history UI.
|
|
if req.AuthorName == "" {
|
|
kindHint := req.AuthorKind
|
|
if kindHint == "" {
|
|
kindHint = req.CreatedBy
|
|
}
|
|
if kindHint == createdByAgent {
|
|
req.AuthorName = s.resolveAgentDisplayName(ctx, req.TaskID)
|
|
}
|
|
}
|
|
authorKind, authorName, createdBy := resolveAuthor(req)
|
|
|
|
existing, err := s.repo.GetTaskPlan(ctx, req.TaskID)
|
|
if err != nil {
|
|
s.logger.Error("get existing plan", zap.String("task_id", req.TaskID), zap.Error(err))
|
|
return nil, err
|
|
}
|
|
eventType := events.TaskPlanCreated
|
|
if existing != nil {
|
|
eventType = events.TaskPlanUpdated
|
|
}
|
|
|
|
plan := &models.TaskPlan{
|
|
TaskID: req.TaskID,
|
|
Title: title,
|
|
Content: req.Content,
|
|
CreatedBy: createdBy,
|
|
}
|
|
if existing != nil {
|
|
plan.ID = existing.ID
|
|
plan.CreatedAt = existing.CreatedAt
|
|
}
|
|
|
|
latest, err := s.repo.GetLatestTaskPlanRevision(ctx, req.TaskID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
now := time.Now().UTC()
|
|
coalesce := s.canCoalesce(latest, authorKind, authorName, now)
|
|
|
|
rev := &models.TaskPlanRevision{
|
|
TaskID: req.TaskID,
|
|
Title: title,
|
|
Content: req.Content,
|
|
AuthorKind: authorKind,
|
|
AuthorName: authorName,
|
|
}
|
|
var coalesceID *string
|
|
if coalesce {
|
|
coalesceID = &latest.ID
|
|
// Preserve the original revision's author + number on merge.
|
|
rev.RevisionNumber = latest.RevisionNumber
|
|
rev.AuthorKind = latest.AuthorKind
|
|
rev.AuthorName = latest.AuthorName
|
|
rev.CreatedAt = latest.CreatedAt
|
|
}
|
|
|
|
if err := s.repo.WritePlanRevision(ctx, plan, rev, coalesceID); err != nil {
|
|
s.logger.Error("write plan revision", zap.String("task_id", req.TaskID), zap.Error(err))
|
|
return nil, err
|
|
}
|
|
|
|
saved, err := s.repo.GetTaskPlan(ctx, req.TaskID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if saved == nil {
|
|
return nil, ErrTaskPlanNotFound
|
|
}
|
|
s.publishPlanEvent(ctx, eventType, saved)
|
|
s.publishRevisionEvent(ctx, rev, coalesce)
|
|
return saved, nil
|
|
}
|
|
|
|
// resolveAgentDisplayName returns the agent profile's display name for the
|
|
// task's most recent session, or "" if no usable session/snapshot exists.
|
|
// Tries the active session first (running/starting/waiting) and falls back to
|
|
// the most recent session by started_at so plans written between turns still
|
|
// get the right author name.
|
|
func (s *PlanService) resolveAgentDisplayName(ctx context.Context, taskID string) string {
|
|
session, err := s.repo.GetActiveTaskSessionByTaskID(ctx, taskID)
|
|
if err != nil || session == nil {
|
|
session, err = s.repo.GetTaskSessionByTaskID(ctx, taskID)
|
|
if err != nil || session == nil {
|
|
return ""
|
|
}
|
|
}
|
|
return agentDisplayNameFromSnapshot(session.AgentProfileSnapshot)
|
|
}
|
|
|
|
// agentDisplayNameFromSnapshot picks the best available display name from a
|
|
// session's agent_profile_snapshot. The orchestrator's canonical key is
|
|
// "name" (the profile's display name, e.g. "Claude Sonnet 4.5"); we try it
|
|
// first so a snapshot that carries both "name" and a stale older "label"
|
|
// doesn't render the stale value. Falls back through "label" (older paths)
|
|
// and "agent_display_name" (some DTO mappings) before giving up.
|
|
func agentDisplayNameFromSnapshot(snapshot map[string]interface{}) string {
|
|
if snapshot == nil {
|
|
return ""
|
|
}
|
|
for _, key := range []string{"name", "label", "agent_display_name"} {
|
|
if v, ok := snapshot[key]; ok {
|
|
if s, ok := v.(string); ok && s != "" {
|
|
return s
|
|
}
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func (s *PlanService) canCoalesce(latest *models.TaskPlanRevision, authorKind, authorName string, now time.Time) bool {
|
|
if latest == nil {
|
|
return false
|
|
}
|
|
if latest.RevertOfRevisionID != nil {
|
|
return false // revert markers are permanent
|
|
}
|
|
if latest.AuthorKind != authorKind || latest.AuthorName != authorName {
|
|
return false
|
|
}
|
|
if s.coalesceWindow <= 0 {
|
|
return false
|
|
}
|
|
return now.Sub(latest.UpdatedAt) < s.coalesceWindow
|
|
}
|
|
|
|
// resolveAuthor derives the authoritative (kind, name, legacyCreatedBy) tuple
|
|
// from a write request. Callers may pass explicit AuthorKind/AuthorName; when
|
|
// absent we fall back to CreatedBy and a literal display name.
|
|
func resolveAuthor(req CreatePlanRequest) (kind, name, createdBy string) {
|
|
createdBy = req.CreatedBy
|
|
kind = req.AuthorKind
|
|
if kind == "" {
|
|
kind = createdBy
|
|
}
|
|
if kind != createdByAgent && kind != createdByUser {
|
|
kind = createdByAgent
|
|
}
|
|
if createdBy == "" {
|
|
createdBy = kind
|
|
}
|
|
name = req.AuthorName
|
|
if name == "" {
|
|
if kind == createdByAgent {
|
|
name = defaultAgentAuthorFallback
|
|
} else {
|
|
name = defaultUserAuthorFallback
|
|
}
|
|
}
|
|
return kind, name, createdBy
|
|
}
|
|
|
|
// GetPlan retrieves a task plan by task ID. Returns nil, nil if missing.
|
|
func (s *PlanService) GetPlan(ctx context.Context, taskID string) (*models.TaskPlan, error) {
|
|
if taskID == "" {
|
|
return nil, ErrTaskIDRequired
|
|
}
|
|
if err := s.authorize(ctx, taskID); err != nil {
|
|
return nil, err
|
|
}
|
|
return s.repo.GetTaskPlan(ctx, taskID)
|
|
}
|
|
|
|
type MarkImplementationStartedRequest struct {
|
|
TaskID string
|
|
SessionID string
|
|
Actor string
|
|
}
|
|
|
|
func (s *PlanService) MarkImplementationStarted(ctx context.Context, req MarkImplementationStartedRequest) (*models.TaskPlan, error) {
|
|
if req.TaskID == "" {
|
|
return nil, ErrTaskIDRequired
|
|
}
|
|
if req.SessionID == "" {
|
|
return nil, ErrSessionIDRequired
|
|
}
|
|
if err := s.authorize(ctx, req.TaskID); err != nil {
|
|
return nil, err
|
|
}
|
|
session, err := s.repo.GetTaskSession(ctx, req.SessionID)
|
|
if err != nil {
|
|
if errors.Is(err, models.ErrTaskSessionNotFound) {
|
|
return nil, ErrSessionTaskMismatch
|
|
}
|
|
return nil, err
|
|
}
|
|
if session == nil || session.TaskID != req.TaskID {
|
|
return nil, ErrSessionTaskMismatch
|
|
}
|
|
actor := req.Actor
|
|
if actor == "" {
|
|
actor = createdByUser
|
|
}
|
|
plan, err := s.repo.MarkTaskPlanImplementationStarted(ctx, req.TaskID, req.SessionID, actor)
|
|
if err != nil {
|
|
if errors.Is(err, repository.ErrTaskPlanNotFound) {
|
|
return nil, ErrTaskPlanNotFound
|
|
}
|
|
return nil, err
|
|
}
|
|
if plan == nil {
|
|
return nil, ErrTaskPlanNotFound
|
|
}
|
|
s.publishPlanEvent(ctx, events.TaskPlanUpdated, plan)
|
|
return plan, nil
|
|
}
|
|
|
|
// DeletePlan removes a plan and all its revisions (cascade via FK when task goes; here we delete only HEAD).
|
|
// Historical revisions remain for audit; callers wanting a full wipe should delete the task.
|
|
func (s *PlanService) DeletePlan(ctx context.Context, taskID string) error {
|
|
if taskID == "" {
|
|
return ErrTaskIDRequired
|
|
}
|
|
if err := s.authorize(ctx, taskID); err != nil {
|
|
return err
|
|
}
|
|
existing, err := s.repo.GetTaskPlan(ctx, taskID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if existing == nil {
|
|
return ErrTaskPlanNotFound
|
|
}
|
|
if err := s.repo.DeleteTaskPlan(ctx, taskID); err != nil {
|
|
return err
|
|
}
|
|
s.publishPlanEvent(ctx, events.TaskPlanDeleted, existing)
|
|
return nil
|
|
}
|
|
|
|
// ListRevisions returns plan revisions newest-first without content (metadata only).
|
|
func (s *PlanService) ListRevisions(ctx context.Context, taskID string) ([]*models.TaskPlanRevision, error) {
|
|
if taskID == "" {
|
|
return nil, ErrTaskIDRequired
|
|
}
|
|
if err := s.authorize(ctx, taskID); err != nil {
|
|
return nil, err
|
|
}
|
|
return s.repo.ListTaskPlanRevisions(ctx, taskID, 0)
|
|
}
|
|
|
|
// GetRevision returns a single revision with content (for diff/preview).
|
|
func (s *PlanService) GetRevision(ctx context.Context, id string) (*models.TaskPlanRevision, error) {
|
|
rev, err := s.repo.GetTaskPlanRevision(ctx, id)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if rev == nil {
|
|
return nil, ErrRevisionNotFound
|
|
}
|
|
if err := s.authorize(ctx, rev.TaskID); err != nil {
|
|
return nil, err
|
|
}
|
|
return rev, nil
|
|
}
|
|
|
|
// RevertPlanRequest parameters for a revert-to-revision operation.
|
|
type RevertPlanRequest struct {
|
|
TaskID string
|
|
TargetRevisionID string
|
|
AuthorName string // user display name; "User" fallback when empty
|
|
}
|
|
|
|
// RevertPlan creates a new revision whose content mirrors the target and updates HEAD,
|
|
// atomically via WritePlanRevision. Revert revisions are never coalesced (the "restored
|
|
// from vK" marker is preserved).
|
|
func (s *PlanService) RevertPlan(ctx context.Context, req RevertPlanRequest) (*models.TaskPlanRevision, error) {
|
|
if req.TaskID == "" {
|
|
return nil, ErrTaskIDRequired
|
|
}
|
|
if req.TargetRevisionID == "" {
|
|
return nil, ErrRevisionIDRequired
|
|
}
|
|
if err := s.authorize(ctx, req.TaskID); err != nil {
|
|
return nil, err
|
|
}
|
|
target, err := s.repo.GetTaskPlanRevision(ctx, req.TargetRevisionID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if target == nil {
|
|
return nil, ErrRevisionNotFound
|
|
}
|
|
if target.TaskID != req.TaskID {
|
|
return nil, ErrRevisionTaskMismatch
|
|
}
|
|
|
|
authorName := req.AuthorName
|
|
if authorName == "" {
|
|
authorName = defaultUserAuthorFallback
|
|
}
|
|
|
|
head, err := s.repo.GetTaskPlan(ctx, req.TaskID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
plan := &models.TaskPlan{
|
|
TaskID: req.TaskID,
|
|
Title: target.Title,
|
|
Content: target.Content,
|
|
CreatedBy: createdByUser,
|
|
}
|
|
if head != nil {
|
|
plan.ID = head.ID
|
|
plan.CreatedAt = head.CreatedAt
|
|
}
|
|
|
|
targetID := target.ID
|
|
rev := &models.TaskPlanRevision{
|
|
TaskID: req.TaskID,
|
|
Title: target.Title,
|
|
Content: target.Content,
|
|
AuthorKind: createdByUser,
|
|
AuthorName: authorName,
|
|
RevertOfRevisionID: &targetID,
|
|
}
|
|
if err := s.repo.WritePlanRevision(ctx, plan, rev, nil); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
saved, err := s.repo.GetTaskPlan(ctx, req.TaskID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if saved == nil {
|
|
return nil, ErrTaskPlanNotFound
|
|
}
|
|
s.publishPlanEvent(ctx, events.TaskPlanUpdated, saved)
|
|
s.publishRevisionEvent(ctx, rev, false)
|
|
s.publishReverted(ctx, rev)
|
|
return rev, nil
|
|
}
|
|
|
|
func (s *PlanService) publishPlanEvent(ctx context.Context, eventType string, plan *models.TaskPlan) {
|
|
if s.eventBus == nil {
|
|
return
|
|
}
|
|
payload := map[string]interface{}{
|
|
"id": plan.ID,
|
|
"task_id": plan.TaskID,
|
|
"title": plan.Title,
|
|
"content": plan.Content,
|
|
"created_by": plan.CreatedBy,
|
|
"created_at": plan.CreatedAt,
|
|
"updated_at": plan.UpdatedAt,
|
|
}
|
|
if plan.ImplementationStartedAt != nil {
|
|
payload["implementation_started_at"] = *plan.ImplementationStartedAt
|
|
}
|
|
if plan.ImplementationStartedSessionID != nil {
|
|
payload["implementation_started_session_id"] = *plan.ImplementationStartedSessionID
|
|
}
|
|
if plan.ImplementationStartedBy != nil {
|
|
payload["implementation_started_by"] = *plan.ImplementationStartedBy
|
|
}
|
|
if err := s.eventBus.Publish(ctx, eventType, bus.NewEvent(eventType, "plan-service", payload)); err != nil {
|
|
s.logger.Error("publish plan event", zap.String("event_type", eventType), zap.Error(err))
|
|
}
|
|
}
|
|
|
|
func (s *PlanService) publishRevisionEvent(ctx context.Context, rev *models.TaskPlanRevision, coalesced bool) {
|
|
if s.eventBus == nil {
|
|
return
|
|
}
|
|
payload := revisionPayload(rev)
|
|
payload["coalesced"] = coalesced
|
|
if err := s.eventBus.Publish(ctx, events.TaskPlanRevisionCreated, bus.NewEvent(events.TaskPlanRevisionCreated, "plan-service", payload)); err != nil {
|
|
s.logger.Error("publish revision event", zap.Error(err))
|
|
}
|
|
}
|
|
|
|
func (s *PlanService) publishReverted(ctx context.Context, rev *models.TaskPlanRevision) {
|
|
if s.eventBus == nil {
|
|
return
|
|
}
|
|
payload := revisionPayload(rev)
|
|
if err := s.eventBus.Publish(ctx, events.TaskPlanReverted, bus.NewEvent(events.TaskPlanReverted, "plan-service", payload)); err != nil {
|
|
s.logger.Error("publish reverted event", zap.Error(err))
|
|
}
|
|
}
|
|
|
|
func revisionPayload(rev *models.TaskPlanRevision) map[string]interface{} {
|
|
p := map[string]interface{}{
|
|
"id": rev.ID,
|
|
"task_id": rev.TaskID,
|
|
"revision_number": rev.RevisionNumber,
|
|
"title": rev.Title,
|
|
"author_kind": rev.AuthorKind,
|
|
"author_name": rev.AuthorName,
|
|
"created_at": rev.CreatedAt,
|
|
"updated_at": rev.UpdatedAt,
|
|
}
|
|
if rev.RevertOfRevisionID != nil {
|
|
p["revert_of_revision_id"] = *rev.RevertOfRevisionID
|
|
}
|
|
return p
|
|
}
|