Files
kandev/apps/backend/internal/workflow/models/export.go
T
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

426 lines
15 KiB
Go

package models
import (
"fmt"
"maps"
taskmodels "github.com/kandev/kandev/internal/task/models"
)
const (
ExportVersion = 1
ExportType = "kandev_workflow"
)
// WorkflowExport is the portable format for sharing workflows.
type WorkflowExport struct {
Version int `json:"version" yaml:"version"`
Type string `json:"type" yaml:"type"`
Workflows []WorkflowPortable `json:"workflows" yaml:"workflows"`
}
// AgentProfilePortable stores enough agent profile info for cross-workspace matching.
type AgentProfilePortable struct {
AgentName string `json:"agent_name" yaml:"agent_name"`
Model string `json:"model,omitempty" yaml:"model,omitempty"`
Mode string `json:"mode,omitempty" yaml:"mode,omitempty"`
}
// AgentProfileResolver resolves an agent profile ID to its portable representation.
type AgentProfileResolver func(profileID string) *AgentProfilePortable
// AgentProfileMatcher finds a matching agent profile ID by agent name, model, and mode.
type AgentProfileMatcher func(agentName, model, mode string) string
// WorkflowPortable is a workflow without instance-specific fields (IDs, timestamps).
type WorkflowPortable struct {
Name string `json:"name" yaml:"name"`
Description string `json:"description,omitempty" yaml:"description,omitempty"`
AgentProfile *AgentProfilePortable `json:"agent_profile,omitempty" yaml:"agent_profile,omitempty"`
Steps []StepPortable `json:"steps" yaml:"steps"`
}
// StepPortable is a workflow step without instance-specific fields.
type StepPortable struct {
Name string `json:"name" yaml:"name"`
Position int `json:"position" yaml:"position"`
Color string `json:"color" yaml:"color"`
Prompt string `json:"prompt,omitempty" yaml:"prompt,omitempty"`
Events StepEvents `json:"events" yaml:"events"`
IsStartStep bool `json:"is_start_step" yaml:"is_start_step"`
ShowInCommandPanel bool `json:"show_in_command_panel" yaml:"show_in_command_panel"`
AllowManualMove bool `json:"allow_manual_move" yaml:"allow_manual_move"`
AutoArchiveAfterHours int `json:"auto_archive_after_hours,omitempty" yaml:"auto_archive_after_hours,omitempty"`
AgentProfile *AgentProfilePortable `json:"agent_profile,omitempty" yaml:"agent_profile,omitempty"`
AutoAdvanceRequiresSignal bool `json:"auto_advance_requires_signal" yaml:"auto_advance_requires_signal"`
WIPLimit int `json:"wip_limit,omitempty" yaml:"wip_limit,omitempty"`
PullFromStepPosition *int `json:"pull_from_step_position,omitempty" yaml:"pull_from_step_position,omitempty"`
}
// BuildWorkflowExport builds a portable WorkflowExport from domain models.
// stepsByWorkflow maps workflow ID → its steps (ordered by position).
// resolveProfile converts agent profile IDs to portable form (may be nil).
func BuildWorkflowExport(workflows []*taskmodels.Workflow, stepsByWorkflow map[string][]*WorkflowStep, resolveProfile AgentProfileResolver) *WorkflowExport {
portable := make([]WorkflowPortable, 0, len(workflows))
for _, wf := range workflows {
steps := stepsByWorkflow[wf.ID]
portable = append(portable, buildWorkflowPortable(wf, steps, resolveProfile))
}
return &WorkflowExport{
Version: ExportVersion,
Type: ExportType,
Workflows: portable,
}
}
func buildWorkflowPortable(wf *taskmodels.Workflow, steps []*WorkflowStep, resolveProfile AgentProfileResolver) WorkflowPortable {
portableSteps := make([]StepPortable, 0, len(steps))
// Build step ID → position map for converting move_to_step references.
idToPos := make(map[string]int, len(steps))
for _, s := range steps {
idToPos[s.ID] = s.Position
}
for _, s := range steps {
sp := StepPortable{
Name: s.Name,
Position: s.Position,
Color: s.Color,
Prompt: s.Prompt,
Events: ConvertReviewProfileToPortable(convertStepIDToPosition(s.Events, idToPos), resolveProfile),
IsStartStep: s.IsStartStep,
ShowInCommandPanel: s.ShowInCommandPanel,
AllowManualMove: s.AllowManualMove,
AutoArchiveAfterHours: s.AutoArchiveAfterHours,
AutoAdvanceRequiresSignal: s.AutoAdvanceRequiresSignal,
WIPLimit: s.WIPLimit,
}
if pos, ok := idToPos[s.PullFromStepID]; ok {
sp.PullFromStepPosition = &pos
}
if resolveProfile != nil && s.AgentProfileID != "" {
sp.AgentProfile = resolveProfile(s.AgentProfileID)
}
portableSteps = append(portableSteps, sp)
}
wp := WorkflowPortable{
Name: wf.Name,
Description: wf.Description,
Steps: portableSteps,
}
if resolveProfile != nil && wf.AgentProfileID != "" {
wp.AgentProfile = resolveProfile(wf.AgentProfileID)
}
return wp
}
// Validate checks that the export data is well-formed.
func (e *WorkflowExport) Validate() error {
if e.Version != ExportVersion {
return fmt.Errorf("unsupported export version: %d (expected %d)", e.Version, ExportVersion)
}
if e.Type != ExportType {
return fmt.Errorf("unsupported export type: %q (expected %q)", e.Type, ExportType)
}
if len(e.Workflows) == 0 {
return fmt.Errorf("export contains no workflows")
}
for i, wf := range e.Workflows {
if wf.Name == "" {
return fmt.Errorf("workflow %d: name is required", i)
}
positions := make(map[int]bool, len(wf.Steps))
for j, step := range wf.Steps {
if step.Name == "" {
return fmt.Errorf("workflow %d step %d: name is required", i, j)
}
if positions[step.Position] {
return fmt.Errorf("workflow %d: duplicate step position %d", i, step.Position)
}
positions[step.Position] = true
if err := validateOnEnterActions(step); err != nil {
return fmt.Errorf("workflow %d step %d: %w", i, j, err)
}
if step.WIPLimit < 0 {
return fmt.Errorf("workflow %d step %d: wip_limit must be non-negative", i, j)
}
}
// Validate that move_to_step references point to valid positions.
if err := validateStepPositionRefs(wf.Steps, positions); err != nil {
return fmt.Errorf("workflow %d: %w", i, err)
}
if err := validatePullSourceRefs(wf.Steps, positions); err != nil {
return fmt.Errorf("workflow %d: %w", i, err)
}
}
return nil
}
func validatePullSourceRefs(steps []StepPortable, validPositions map[int]bool) error {
pullSources := make(map[int]int, len(steps))
for _, step := range steps {
if step.PullFromStepPosition == nil {
continue
}
pos := *step.PullFromStepPosition
if pos == step.Position {
return fmt.Errorf("step %q: pull_from_step_position cannot reference itself", step.Name)
}
if !validPositions[pos] {
return fmt.Errorf("step %q: pull_from_step_position %d does not match any step", step.Name, pos)
}
pullSources[step.Position] = pos
}
if hasPullSourceCycle(pullSources) {
return fmt.Errorf("pull_from_step_position cannot create a pull cycle")
}
return nil
}
func hasPullSourceCycle(pullSources map[int]int) bool {
const (
visiting = 1
visited = 2
)
states := make(map[int]int, len(pullSources))
for start := range pullSources {
if states[start] == visited {
continue
}
current := start
path := make([]int, 0)
for states[current] != visited {
if states[current] == visiting {
return true
}
states[current] = visiting
path = append(path, current)
next, ok := pullSources[current]
if !ok {
break
}
current = next
}
for _, position := range path {
states[position] = visited
}
}
return false
}
// PullFromStepID maps the portable pull-source position to a workflow-step ID.
func (s StepPortable) PullFromStepID(posToID map[int]string) string {
if s.PullFromStepPosition == nil {
return ""
}
return posToID[*s.PullFromStepPosition]
}
// validateOnEnterActions rejects malformed on_enter actions in a portable step.
// Currently this guards set_session_mode, which requires a non-empty string
// "mode" config — without it the action is silently dropped at compile time, so
// an import would "succeed" with an inert action. See issue #1183. This mirrors
// the embedded-YAML loader's allow-list check.
func validateOnEnterActions(step StepPortable) error {
for _, a := range step.Events.OnEnter {
if a.Type != OnEnterSetSessionMode {
continue
}
if mode, _ := a.Config["mode"].(string); mode == "" {
return fmt.Errorf("step %q on_enter: set_session_mode requires a non-empty string \"mode\" config", step.Name)
}
}
return nil
}
func validateStepPositionRefs(steps []StepPortable, validPositions map[int]bool) error {
for _, step := range steps {
for _, a := range step.Events.OnTurnStart {
if a.Type == OnTurnStartMoveToStep {
if err := checkPositionRef(a.Config, validPositions); err != nil {
return fmt.Errorf("step %q on_turn_start: %w", step.Name, err)
}
}
}
for _, a := range step.Events.OnTurnComplete {
if a.Type == OnTurnCompleteMoveToStep {
if err := checkPositionRef(a.Config, validPositions); err != nil {
return fmt.Errorf("step %q on_turn_complete: %w", step.Name, err)
}
}
}
}
return nil
}
func checkPositionRef(config map[string]any, validPositions map[int]bool) error {
if config == nil {
return fmt.Errorf("move_to_step action missing config")
}
pos, exists := config["step_position"]
if !exists {
return fmt.Errorf("move_to_step action missing step_position")
}
posInt, ok := toInt(pos)
if !ok {
return fmt.Errorf("step_position has unexpected type %T", pos)
}
if !validPositions[posInt] {
return fmt.Errorf("step_position %d does not match any step", posInt)
}
return nil
}
// convertStepIDToPosition rewrites move_to_step events: step_id → step_position.
func convertStepIDToPosition(events StepEvents, idToPos map[string]int) StepEvents {
return remapStepEvents(events, "step_id", "step_position", func(v any) (any, bool) {
s, ok := v.(string)
if !ok {
return nil, false
}
pos, found := idToPos[s]
return pos, found
})
}
// ReviewAgentProfilePortableKey is the on_enter config key that carries a
// run_code_review action's reviewing profile in portable form. The instance
// `agent_profile_id` is meaningless in another workspace, so export swaps it for
// the {agent_name, model, mode} triple and import matches it back.
const ReviewAgentProfilePortableKey = "agent_profile"
// ConvertReviewProfileToPortable rewrites run_code_review on_enter actions,
// replacing `agent_profile_id` with a portable `agent_profile` descriptor.
// An unresolvable profile has its key dropped, so the imported action falls back
// to the code-review utility agent instead of carrying a dangling ID.
func ConvertReviewProfileToPortable(events StepEvents, resolveProfile AgentProfileResolver) StepEvents {
return remapReviewProfile(events, ReviewAgentProfileConfigKey, ReviewAgentProfilePortableKey, func(v any) (any, bool) {
profileID, ok := v.(string)
if !ok || profileID == "" || resolveProfile == nil {
return nil, false
}
portable := resolveProfile(profileID)
if portable == nil {
return nil, false
}
return map[string]any{
"agent_name": portable.AgentName,
"model": portable.Model,
"mode": portable.Mode,
}, true
})
}
// ConvertReviewProfileToID rewrites run_code_review on_enter actions, replacing
// a portable `agent_profile` descriptor with a local `agent_profile_id`.
func ConvertReviewProfileToID(events StepEvents, matchProfile AgentProfileMatcher) StepEvents {
return remapReviewProfile(events, ReviewAgentProfilePortableKey, ReviewAgentProfileConfigKey, func(v any) (any, bool) {
descriptor, ok := v.(map[string]any)
if !ok || matchProfile == nil {
return nil, false
}
agentName, _ := descriptor["agent_name"].(string)
model, _ := descriptor["model"].(string)
mode, _ := descriptor["mode"].(string)
profileID := matchProfile(agentName, model, mode)
if profileID == "" {
return nil, false
}
return profileID, true
})
}
// remapReviewProfile rewrites the profile key on every run_code_review on_enter
// action, leaving other actions and triggers untouched. When the lookup fails,
// the source key is removed rather than preserved, so no instance-specific or
// unmatched reference survives the round trip.
func remapReviewProfile(events StepEvents, fromKey, toKey string, lookup func(any) (any, bool)) StepEvents {
result := events
result.OnEnter = make([]OnEnterAction, 0, len(events.OnEnter))
for _, a := range events.OnEnter {
if a.Type == OnEnterRunCodeReview && a.Config != nil {
if cfg, ok := remapConfigKey(a.Config, fromKey, toKey, lookup); ok {
a = OnEnterAction{Type: a.Type, Config: cfg}
} else if _, exists := a.Config[fromKey]; exists {
cfg := make(map[string]any, len(a.Config))
maps.Copy(cfg, a.Config)
delete(cfg, fromKey)
a = OnEnterAction{Type: a.Type, Config: cfg}
}
}
result.OnEnter = append(result.OnEnter, a)
}
return result
}
// ConvertPositionToStepID rewrites move_to_step events: step_position → step_id.
// posToID maps position → new step ID.
func ConvertPositionToStepID(events StepEvents, posToID map[int]string) StepEvents {
return remapStepEvents(events, "step_position", "step_id", func(v any) (any, bool) {
pos, ok := toInt(v)
if !ok {
return nil, false
}
id, found := posToID[pos]
return id, found
})
}
// remapStepEvents rewrites move_to_step config in OnTurnStart and OnTurnComplete actions,
// replacing fromKey with toKey using the provided lookup function.
func remapStepEvents(events StepEvents, fromKey, toKey string, lookup func(any) (any, bool)) StepEvents {
result := StepEvents{
OnEnter: append([]OnEnterAction{}, events.OnEnter...),
OnExit: append([]OnExitAction{}, events.OnExit...),
}
for _, a := range events.OnTurnStart {
if a.Type == OnTurnStartMoveToStep {
if cfg, ok := remapConfigKey(a.Config, fromKey, toKey, lookup); ok {
a = OnTurnStartAction{Type: a.Type, Config: cfg}
}
}
result.OnTurnStart = append(result.OnTurnStart, a)
}
for _, a := range events.OnTurnComplete {
if a.Type == OnTurnCompleteMoveToStep {
if cfg, ok := remapConfigKey(a.Config, fromKey, toKey, lookup); ok {
a = OnTurnCompleteAction{Type: a.Type, Config: cfg}
}
}
result.OnTurnComplete = append(result.OnTurnComplete, a)
}
return result
}
// remapConfigKey copies config, replaces fromKey with toKey using lookup.
func remapConfigKey(config map[string]any, fromKey, toKey string, lookup func(any) (any, bool)) (map[string]any, bool) {
if config == nil {
return nil, false
}
val, exists := config[fromKey]
if !exists {
return nil, false
}
newVal, found := lookup(val)
if !found {
return nil, false
}
cfg := make(map[string]any, len(config))
maps.Copy(cfg, config)
delete(cfg, fromKey)
cfg[toKey] = newVal
return cfg, true
}
func toInt(v any) (int, bool) {
switch val := v.(type) {
case float64:
return int(val), true
case int:
return val, true
default:
return 0, false
}
}