Files
kandev/apps/backend/internal/workflow/models/models.go
T
João Salavisa 97c1f689e4 feat(workflow): explicit step-completion signal for auto-advance (#1276)
* feat(workflow): explicit step-completion signal for auto-advance

Adds `step_complete_kandev` MCP tool + `WorkflowStep.auto_advance_requires_signal`
column so workflow steps can gate their `on_turn_complete` transitions on an
agent-emitted completion signal instead of inferring "done" from any turn-end.
See docs/decisions/0015-explicit-completion-signal-for-auto-advance.md for the
motivation, alternatives considered, and trade-offs.

* fix(workflow): address PR review feedback for explicit completion signal

- Dedup `LoadPendingStepSignal` into `internal/task/models` so the MCP
  handler (write site) and the orchestrator (read site) share one decoder.
- Gate the out-of-band subscriber on `WorkflowStep.AutoAdvanceRequiresSignal`
  so `step_complete_kandev` is not an unintended manual-advance path for
  signalless steps.
- Fail closed on step-load errors in `processOnTurnCompleteViaEngine`: a
  loader hiccup must block the transition rather than silently bypass the
  gate.
- Reject `step_complete_kandev` for terminal sessions
  (Completed / Failed / Cancelled) so the agent gets a clear error instead
  of `accepted: true` followed by a no-op.
- Surface bus-publish failures back to the agent instead of swallowing
  them — the idempotency guard makes the retry safe and prevents the
  session from getting stuck.
- New `TestOnStepCompletionSignaled` covers the subscriber paths
  (RUNNING / WAITING+match / stale step / not signal-gated).
- ADR doc fixes: payload field list now matches the wire shape, writer
  ownership is documented, the unsubstantiated 250ms-debounce claim is
  removed, and the late-signal re-close race is recorded as a deferred
  open question.
- Drop the new toggle's HelpTip in favour of an inline description — the
  shadcn tooltip portal was intercepting clicks on the agent-profile
  dropdown options in the workflow settings E2E.

* fix(workflow): round-2 review fixes for explicit completion signal

- Split `handleStepComplete` into `resolveStepCompleteTarget` +
  `publishStepCompletionEvent` helpers so the entrypoint clears funlen
  (88 → under 80 lines) and the two halves are independently testable.
- Classify session/task load errors instead of returning `NotFound` for
  every failure: use the exported `taskrepo.ErrTaskNotFound` sentinel for
  task lookups, substring-match for the session repo (no sentinel today),
  and surface anything else as `InternalError` with the raw error logged
  but not leaked to the agent — so a transient DB hiccup triggers a retry
  rather than session abandonment.
- Pin `step_complete_kandev` explicitly in the mode-specific tool-count
  tests: `Contains` in `ModeTask`, `NotContains` in `ModeConfig` and
  `ModeOffice`, so accidental dereg or cross-mode registration is caught
  by the diff instead of by a still-equal count.

* fix(workflow): round-3 review fixes + defer pipeline-editor toggle

- Defer the "Wait for agent completion signal" sub-toggle to a follow-up
  PR. Adding it to the step config card shifts the layout enough that the
  agent profile select's Radix popper opens into a sibling tooltip's hover
  path, breaking workflow-agent-profile.spec.ts on shard 7. The backend
  column ships in this PR — workflows can opt in via the YAML import or
  the MCP `update_workflow_step_kandev` tool — and the UI affordance gets
  its own iteration where the test interference can be investigated
  without blocking the rest of the change.
- Re-publish the bus event on the `already_signaled` short-circuit when
  the session is WAITING_FOR_INPUT. Without this, an agent's retry after
  the first call's publish failed would short-circuit on the persisted
  bag, never fire the subscriber, and leave the session stuck.
- handleStepComplete docstring: drop the non-existent feature-flag claim
  and the "audit entry" wording — gating is purely
  `WorkflowStep.AutoAdvanceRequiresSignal` and the bag is cleared on the
  next turn start with no separate audit trail.
- `step_complete_kandev` tool description: same fix — clarify that the
  call succeeds for non-gated steps but the signal is discarded on the
  next turn start (no audit history to query later).

* test(workflow): cover handleStepComplete + reword defer-comment

- Add `TestHandleStepComplete_*` (6 subtests, all passing) covering the
  uncovered handler paths flagged by Claude/cubic on round 3:
  missing-fields validation, session-does-not-belong-to-task ownership
  guard, terminal-session rejection (Completed/Failed/Cancelled),
  first-call happy path (bag persisted + bus payload shape pinned), dedup
  while RUNNING (no re-publish), and dedup while WAITING_FOR_INPUT (the
  retry-after-publish-failure path — must re-publish so the subscriber
  fires).
- Reword the deferred-toggle comment to drop the YAML-export claim:
  the workflow export model doesn't yet serialize
  `auto_advance_requires_signal`, so MCP `update_workflow_step_kandev`
  is the only configuration path that round-trips today. Note the
  follow-up needs to extend the export schema alongside the UI toggle.

* test(workflow): pin signaled_at + drop redundant GetTaskSession on bag-clear

- Assert `signaled_at` is present and parses as RFC3339Nano in
  `TestHandleStepComplete_FirstCallAccepted`. The field is part of the
  handler's documented response contract; pinning it catches accidental
  drop/rename regressions.
- Add `clearPendingStepSignalByID(ctx, sessionID)` as a thin DB-only
  variant of `clearPendingStepSignal` and use it from
  `executeStepTransition`, where the session struct isn't read after the
  clear. Avoids an extra `GetTaskSession` round-trip per transition.
  `clearPendingStepSignal(session)` still exists for the
  in-memory-mutation case (subscriber's stale-step path).

* fix(workflow): subscriber stale-clear guard + ADR/comment drift fixes

- onStepCompletionSignaled's stale-step path now reads the bag and only
  clears it when its current StepID matches the (stale) event's stepID.
  Previously the unconditional clear could destroy a valid signal that
  the new step's agent had just written when sessions are reused across
  steps without auto_start_agent. (Greptile P1.)
- Drop the "feature flag" phrase from WorkflowStep.AutoAdvanceRequiresSignal
  docstring — leftover from an earlier draft. The gating is purely the
  boolean field; the global flag was removed two rounds ago.
- Merge the two adjacent `if triggerOnEnter` blocks in
  executeStepTransition so the full triggerOnEnter=true path reads top-
  to-bottom in one place. (CodeRabbit + cubic.)
- ADR 0015 Mechanism section: re-label the SessionStepHistory.Metadata
  audit annotation, the `step_complete_signaled` system message, and the
  expvar telemetry counters as deferred. They're planned shapes, not
  current behaviour — calling them "Audit" / "Chat visibility" /
  "Telemetry" in present tense was misleading for future readers.

* fix(workflow): drop subscriber complexity + reload session on stale-clear

- Extract `parseStepCompletionEvent` and `stepIsSignalGated` helpers from
  `onStepCompletionSignaled`. Cyclomatic complexity goes 17 → under 15
  (cyclop on new code, CI lint regression after the round-6
  stale-clear guard).
- The stale-step branch now re-loads the session from the DB before
  deciding whether to clear the bag. The previous round-6 fix checked
  the local `session.Metadata` snapshot, which can be older than a
  concurrent write from the new step's agent — that check could see a
  stale signal that had since been overwritten with a valid one and
  erase the new bag entry. The narrower load-on-clear is cheap and
  closes the cubic P1 hole. (The broader race in
  `processOnTurnCompleteViaEngine` reading session.Metadata is the
  monotonic-marker open question in ADR 0015; out of scope here.)

* test(workflow): pin stale-event guard's preserve-current-bag side + dedup StringFromAny

- Add `TestOnStepCompletionSignaled` subtest "stale event → valid bag
  for CURRENT step is preserved" — fires a stale step-A event while
  the bag holds a valid step-B signal, asserts the bag still contains
  StepID=step_b after the subscriber runs. Pins the negative side of
  the round-6 `existing.StepID == stepID` guard, so a regression that
  drops or inverts the guard (and would silently leave signal-gated
  steps stuck) fails the test instead of slipping through.
- Promote `pendingSignalString` to exported `models.StringFromAny`
  and reuse it from the orchestrator subscriber's
  `parseStepCompletionEvent`. Eliminates the byte-for-byte duplicate
  helper across the two packages; the bag-shape decoder and the bus-
  event decoder now share one source of truth for "missing string".

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
2026-06-05 18:32:27 +01:00

295 lines
13 KiB
Go

package models
import (
"maps"
"time"
)
// OnEnterActionType represents the type of action to execute when entering a step.
type OnEnterActionType string
const (
OnEnterEnablePlanMode OnEnterActionType = "enable_plan_mode"
OnEnterAutoStartAgent OnEnterActionType = "auto_start_agent"
OnEnterResetAgentContext OnEnterActionType = "reset_agent_context"
// OnEnterSetSessionMode declares the agent's session permission mode (e.g.
// "default", "acceptEdits") for a step on entry. The target mode is carried
// in the action Config under the "mode" key. See issue #1183.
OnEnterSetSessionMode OnEnterActionType = "set_session_mode"
// Phase 2 (ADR-0004) — generic actions are also permitted on on_enter
// so review/approval steps can clear decisions and fan out runs to
// participants when the task arrives at the step.
OnEnterClearDecisions OnEnterActionType = "clear_decisions"
OnEnterQueueRunForEachParticipant OnEnterActionType = "queue_run_for_each_participant"
OnEnterQueueRun OnEnterActionType = "queue_run"
)
// OnTurnStartActionType represents the type of action to execute when a user sends a message.
type OnTurnStartActionType string
const (
OnTurnStartMoveToNext OnTurnStartActionType = "move_to_next"
OnTurnStartMoveToPrevious OnTurnStartActionType = "move_to_previous"
OnTurnStartMoveToStep OnTurnStartActionType = "move_to_step"
)
// OnTurnStartAction represents an action to execute when a user sends a message.
type OnTurnStartAction struct {
Type OnTurnStartActionType `json:"type" yaml:"type"`
Config map[string]interface{} `json:"config,omitempty" yaml:"config,omitempty"`
}
// OnTurnCompleteActionType represents the type of action to execute when an agent turn completes.
type OnTurnCompleteActionType string
const (
OnTurnCompleteMoveToNext OnTurnCompleteActionType = "move_to_next"
OnTurnCompleteMoveToPrevious OnTurnCompleteActionType = "move_to_previous"
OnTurnCompleteMoveToStep OnTurnCompleteActionType = "move_to_step"
OnTurnCompleteDisablePlanMode OnTurnCompleteActionType = "disable_plan_mode"
)
// OnEnterAction represents an action to execute when entering a step.
type OnEnterAction struct {
Type OnEnterActionType `json:"type" yaml:"type"`
Config map[string]interface{} `json:"config,omitempty" yaml:"config,omitempty"`
}
// OnTurnCompleteAction represents an action to execute when an agent turn completes.
type OnTurnCompleteAction struct {
Type OnTurnCompleteActionType `json:"type" yaml:"type"`
Config map[string]interface{} `json:"config,omitempty" yaml:"config,omitempty"`
}
// OnExitActionType represents the type of action to execute when leaving a step.
type OnExitActionType string
const (
OnExitDisablePlanMode OnExitActionType = "disable_plan_mode"
)
// OnExitAction represents an action to execute when leaving a step.
type OnExitAction struct {
Type OnExitActionType `json:"type" yaml:"type"`
Config map[string]interface{} `json:"config,omitempty" yaml:"config,omitempty"`
}
// GenericActionType represents the type of a Phase 2 (ADR-0004) action that
// can appear under any of the new event-driven triggers (on_comment,
// on_blocker_resolved, on_children_completed, on_approval_resolved,
// on_heartbeat, on_budget_alert, on_agent_error). Actions are compiled into
// the engine's typed Action structs by engine.CompileStep.
type GenericActionType string
const (
// GenericActionQueueRun queues a run on a target task/agent.
GenericActionQueueRun GenericActionType = "queue_run"
// GenericActionClearDecisions clears recorded decisions for the
// (task, step) pair. Typically used by a Review step's on_enter to
// start fresh after a rejection round.
GenericActionClearDecisions GenericActionType = "clear_decisions"
// GenericActionQueueRunForEachParticipant fans out queue_run over
// every participant of the step matching a configured role.
GenericActionQueueRunForEachParticipant GenericActionType = "queue_run_for_each_participant"
)
// GenericAction is the persisted shape of a Phase 2 action used in the
// new event-driven triggers. Config carries the action-specific parameters
// (target, task_id, reason, payload, role, …) interpreted by
// engine.CompileStep.
type GenericAction struct {
Type GenericActionType `json:"type" yaml:"type"`
Config map[string]interface{} `json:"config,omitempty" yaml:"config,omitempty"`
}
// StepEvents contains event-driven actions for a workflow step.
//
// The four kanban-era triggers (OnEnter, OnTurnStart, OnTurnComplete, OnExit)
// keep their typed action slices for backwards compatibility. The Phase 2
// (ADR-0004) triggers all use GenericAction so new action kinds can be added
// without further model changes — engine.CompileStep is the single point of
// translation into typed engine.Action structs.
type StepEvents struct {
OnEnter []OnEnterAction `json:"on_enter,omitempty" yaml:"on_enter,omitempty"`
OnTurnStart []OnTurnStartAction `json:"on_turn_start,omitempty" yaml:"on_turn_start,omitempty"`
OnTurnComplete []OnTurnCompleteAction `json:"on_turn_complete,omitempty" yaml:"on_turn_complete,omitempty"`
OnExit []OnExitAction `json:"on_exit,omitempty" yaml:"on_exit,omitempty"`
// Phase 2 (ADR-0004) — new event-driven triggers. Empty slices keep
// today's kanban behaviour; the engine simply finds no actions for the
// trigger and exits.
OnComment []GenericAction `json:"on_comment,omitempty" yaml:"on_comment,omitempty"`
OnBlockerResolved []GenericAction `json:"on_blocker_resolved,omitempty" yaml:"on_blocker_resolved,omitempty"`
OnChildrenCompleted []GenericAction `json:"on_children_completed,omitempty" yaml:"on_children_completed,omitempty"`
OnApprovalResolved []GenericAction `json:"on_approval_resolved,omitempty" yaml:"on_approval_resolved,omitempty"`
OnHeartbeat []GenericAction `json:"on_heartbeat,omitempty" yaml:"on_heartbeat,omitempty"`
OnBudgetAlert []GenericAction `json:"on_budget_alert,omitempty" yaml:"on_budget_alert,omitempty"`
OnAgentError []GenericAction `json:"on_agent_error,omitempty" yaml:"on_agent_error,omitempty"`
}
// ReviewStatus represents the review state of a session
type ReviewStatus string
const (
ReviewStatusPending ReviewStatus = "pending"
ReviewStatusChangesRequested ReviewStatus = "changes_requested"
ReviewStatusApproved ReviewStatus = "approved"
)
// WorkflowTemplate represents a pre-defined workflow type that workflows can adopt
type WorkflowTemplate struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
IsSystem bool `json:"is_system"`
// Hidden marks templates that produce hidden workflow instances
// (excluded from management UI and pickers). Used by system-only flows.
// Not persisted to DB; sourced from the embedded YAML at load time.
Hidden bool `json:"hidden,omitempty"`
Steps []StepDefinition `json:"steps"` // JSON stored
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// StepDefinition represents a step in a workflow template (stored as JSON in WorkflowTemplate)
type StepDefinition struct {
ID string `json:"id"`
Name string `json:"name"`
Position int `json:"position"`
Color string `json:"color"`
Prompt string `json:"prompt,omitempty"`
Events StepEvents `json:"events"`
AllowManualMove bool `json:"allow_manual_move"`
IsStartStep bool `json:"is_start_step"`
ShowInCommandPanel bool `json:"show_in_command_panel"`
AutoArchiveAfterHours int `json:"auto_archive_after_hours,omitempty"`
AgentProfileID string `json:"agent_profile_id,omitempty"`
// StageType mirrors WorkflowStep.StageType for templates so the office
// default + coordination workflows can declare their UX role
// ("work", "review", "approval", "custom") in YAML.
StageType StageType `json:"stage_type,omitempty"`
// AutoAdvanceRequiresSignal gates on_turn_complete transitions on an
// explicit `step_complete_kandev` MCP signal from the agent (ADR 0015).
AutoAdvanceRequiresSignal bool `json:"auto_advance_requires_signal,omitempty" yaml:"auto_advance_requires_signal,omitempty"`
}
// WorkflowStep represents a step in a workflow
type WorkflowStep struct {
ID string `json:"id"`
WorkflowID string `json:"workflow_id"`
Name string `json:"name"`
Position int `json:"position"`
Color string `json:"color"`
Prompt string `json:"prompt,omitempty"`
Events StepEvents `json:"events"`
AllowManualMove bool `json:"allow_manual_move"`
IsStartStep bool `json:"is_start_step"`
ShowInCommandPanel bool `json:"show_in_command_panel"`
AutoArchiveAfterHours int `json:"auto_archive_after_hours,omitempty"`
AgentProfileID string `json:"agent_profile_id,omitempty"`
// StageType is a Phase 2 (ADR-0004) semantic hint for the frontend
// ("work", "review", "approval", "custom"). The engine does not branch
// on it. Stored as TEXT in workflow_steps.stage_type, defaulting to
// "custom" so existing rows remain unchanged.
StageType StageType `json:"stage_type,omitempty"`
// AutoAdvanceRequiresSignal gates on_turn_complete transitions on an
// explicit `step_complete_kandev` MCP signal from the agent (ADR 0015).
// When true, bare turn-end does NOT trigger the step's transition
// actions; instead the orchestrator waits for the agent (or a manual
// UI fallback) to write the pending-signal bag on TaskSession.Metadata.
AutoAdvanceRequiresSignal bool `json:"auto_advance_requires_signal,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// HasOnEnterAction checks if the step has a specific on_enter action type.
func (s *WorkflowStep) HasOnEnterAction(actionType OnEnterActionType) bool {
for _, action := range s.Events.OnEnter {
if action.Type == actionType {
return true
}
}
return false
}
// HasOnTurnStartAction checks if the step has any on_turn_start actions.
func (s *WorkflowStep) HasOnTurnStartAction() bool {
return len(s.Events.OnTurnStart) > 0
}
// HasOnTurnCompleteAction checks if the step has a specific on_turn_complete action type.
func (s *WorkflowStep) HasOnTurnCompleteAction(actionType OnTurnCompleteActionType) bool {
for _, action := range s.Events.OnTurnComplete {
if action.Type == actionType {
return true
}
}
return false
}
// StepTransitionTrigger represents how a session moved between steps
type StepTransitionTrigger string
const (
StepTransitionTriggerManual StepTransitionTrigger = "manual"
StepTransitionTriggerAutoComplete StepTransitionTrigger = "auto_complete"
StepTransitionTriggerApproval StepTransitionTrigger = "approval"
)
// SessionStepHistory represents an audit trail entry for session step transitions
type SessionStepHistory struct {
ID int64 `json:"id"`
SessionID string `json:"session_id"`
FromStepID *string `json:"from_step_id,omitempty"`
ToStepID string `json:"to_step_id"`
Trigger StepTransitionTrigger `json:"trigger"`
ActorID *string `json:"actor_id,omitempty"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
CreatedAt time.Time `json:"created_at"`
}
// RemapStepEvents returns a copy of events with all step_id references
// in move_to_step actions replaced using the provided ID mapping.
func RemapStepEvents(events StepEvents, idMap map[string]string) StepEvents {
result := StepEvents{}
result.OnEnter = append(result.OnEnter, events.OnEnter...)
for _, a := range events.OnTurnStart {
if a.Type == OnTurnStartMoveToStep && a.Config != nil {
if stepID, ok := a.Config["step_id"].(string); ok {
if newID, found := idMap[stepID]; found {
cfg := make(map[string]any, len(a.Config))
maps.Copy(cfg, a.Config)
cfg["step_id"] = newID
a.Config = cfg
}
}
}
result.OnTurnStart = append(result.OnTurnStart, a)
}
for _, a := range events.OnTurnComplete {
if a.Type == OnTurnCompleteMoveToStep && a.Config != nil {
if stepID, ok := a.Config["step_id"].(string); ok {
if newID, found := idMap[stepID]; found {
cfg := make(map[string]any, len(a.Config))
maps.Copy(cfg, a.Config)
cfg["step_id"] = newID
a.Config = cfg
}
}
}
result.OnTurnComplete = append(result.OnTurnComplete, a)
}
result.OnExit = append(result.OnExit, events.OnExit...)
// Phase 2 (ADR-0004) — copy generic-action lists through. None of these
// actions carry step_id references today, so a shallow copy suffices.
result.OnComment = append(result.OnComment, events.OnComment...)
result.OnBlockerResolved = append(result.OnBlockerResolved, events.OnBlockerResolved...)
result.OnChildrenCompleted = append(result.OnChildrenCompleted, events.OnChildrenCompleted...)
result.OnApprovalResolved = append(result.OnApprovalResolved, events.OnApprovalResolved...)
result.OnHeartbeat = append(result.OnHeartbeat, events.OnHeartbeat...)
result.OnBudgetAlert = append(result.OnBudgetAlert, events.OnBudgetAlert...)
result.OnAgentError = append(result.OnAgentError, events.OnAgentError...)
return result
}