package workflow import ( "context" "encoding/json" "fmt" "log" "time" "switchboard-core/events" "switchboard-core/models" "switchboard-core/sandbox" "switchboard-core/store" "github.com/google/uuid" ) // MaxConsecutiveAutomated is the cycle guard limit for automated stages. const MaxConsecutiveAutomated = 10 // Engine orchestrates workflow instance lifecycle. type Engine struct { stores store.Stores bus *events.Bus runner *sandbox.Runner } // NewEngine creates a workflow engine. func NewEngine(stores store.Stores, bus *events.Bus, runner *sandbox.Runner) *Engine { return &Engine{stores: stores, bus: bus, runner: runner} } // Start creates a new workflow instance and kicks off the first stage. func (e *Engine) Start(ctx context.Context, workflowID string, initialData json.RawMessage, userID string) (*models.WorkflowInstance, error) { wf, err := e.stores.Workflows.GetByID(ctx, workflowID) if err != nil { return nil, fmt.Errorf("workflow not found: %w", err) } if !wf.IsActive { return nil, fmt.Errorf("workflow %q is not active", wf.Name) } ver, err := e.stores.Workflows.GetLatestVersion(ctx, workflowID) if err != nil { return nil, fmt.Errorf("no published version: %w", err) } var stages []models.WorkflowStage if err := json.Unmarshal(ver.Snapshot, &stages); err != nil { return nil, fmt.Errorf("corrupt version snapshot: %w", err) } if len(stages) == 0 { return nil, fmt.Errorf("workflow has no stages") } inst := &models.WorkflowInstance{ WorkflowID: workflowID, WorkflowVersion: ver.VersionNumber, CurrentStage: stages[0].Name, StageData: initialData, Status: models.InstanceStatusActive, StartedBy: userID, Metadata: json.RawMessage(`{}`), } if wf.EntryMode == "public_link" { tok := uuid.New().String() inst.EntryToken = &tok } if err := e.stores.Workflows.CreateInstance(ctx, inst); err != nil { return nil, fmt.Errorf("create instance: %w", err) } // Create initial assignment if first stage has a team if stages[0].AssignmentTeamID != nil { a := &models.WorkflowAssignment{ InstanceID: inst.ID, Stage: stages[0].Name, TeamID: *stages[0].AssignmentTeamID, } if err := e.stores.Workflows.CreateAssignment(ctx, a); err != nil { log.Printf("[workflow-engine] create initial assignment: %v", err) } } e.emit(ctx, "workflow.started", inst.ID, map[string]any{ "workflow_id": workflowID, "instance_id": inst.ID, "started_by": userID, }) // If first stage is automated, process it if stages[0].StageMode == models.StageModeAutomated { if err := e.processAutomatedStage(ctx, inst, stages, 0); err != nil { log.Printf("[workflow-engine] automated stage error on start: %v", err) } // Re-read instance after automated processing inst, _ = e.stores.Workflows.GetInstance(ctx, inst.ID) } return inst, nil } // Advance moves an instance to the next stage. func (e *Engine) Advance(ctx context.Context, instanceID string, stageData json.RawMessage, userID string) (*models.WorkflowInstance, error) { return e.advanceInternal(ctx, instanceID, stageData, userID, 0) } func (e *Engine) advanceInternal(ctx context.Context, instanceID string, stageData json.RawMessage, userID string, autoDepth int) (*models.WorkflowInstance, error) { inst, err := e.stores.Workflows.GetInstance(ctx, instanceID) if err != nil { return nil, fmt.Errorf("instance not found: %w", err) } if inst.Status != models.InstanceStatusActive { return nil, fmt.Errorf("instance is %s, not active", inst.Status) } ver, err := e.stores.Workflows.GetVersion(ctx, inst.WorkflowID, inst.WorkflowVersion) if err != nil { return nil, fmt.Errorf("version not found: %w", err) } var stages []models.WorkflowStage if err := json.Unmarshal(ver.Snapshot, &stages); err != nil { return nil, fmt.Errorf("corrupt snapshot: %w", err) } // Find current stage ordinal currentOrdinal := -1 for _, s := range stages { if s.Name == inst.CurrentStage { currentOrdinal = s.Ordinal break } } if currentOrdinal < 0 { return nil, fmt.Errorf("current stage %q not found in snapshot", inst.CurrentStage) } currentStage := stages[currentOrdinal] // Merge stage data merged := mergeJSON(inst.StageData, stageData) // Resolve next stage nextOrdinal, err := ResolveNextStage(stages, currentOrdinal, merged) if err != nil { return nil, fmt.Errorf("resolve next stage: %w", err) } // Terminal — complete the instance if nextOrdinal >= len(stages) { if err := e.stores.Workflows.CompleteInstance(ctx, instanceID); err != nil { return nil, fmt.Errorf("complete: %w", err) } e.emit(ctx, "workflow.completed", instanceID, map[string]any{ "instance_id": instanceID, }) return e.stores.Workflows.GetInstance(ctx, instanceID) } nextStage := stages[nextOrdinal] // Advance in store if err := e.stores.Workflows.AdvanceStage(ctx, instanceID, nextStage.Name, merged); err != nil { return nil, fmt.Errorf("advance store: %w", err) } // Cancel old assignments for the previous stage oldAssignments, _ := e.stores.Workflows.ListAssignmentsByInstance(ctx, instanceID) for _, a := range oldAssignments { if a.Stage == currentStage.Name && (a.Status == models.AssignmentStatusUnassigned || a.Status == models.AssignmentStatusClaimed) { e.stores.Workflows.CancelAssignment(ctx, a.ID) } } // Create new assignment if next stage has a team if nextStage.AssignmentTeamID != nil { a := &models.WorkflowAssignment{ InstanceID: instanceID, Stage: nextStage.Name, TeamID: *nextStage.AssignmentTeamID, } if err := e.stores.Workflows.CreateAssignment(ctx, a); err != nil { log.Printf("[workflow-engine] create assignment: %v", err) } else { e.emit(ctx, "workflow.assigned", a.TeamID, map[string]any{ "instance_id": instanceID, "stage": nextStage.Name, "assignment_id": a.ID, "team_id": a.TeamID, }) } } e.emit(ctx, "workflow.advanced", instanceID, map[string]any{ "instance_id": instanceID, "previous_stage": currentStage.Name, "current_stage": nextStage.Name, }) // If next stage is automated, process it if nextStage.StageMode == models.StageModeAutomated { if err := e.processAutomatedStage(ctx, inst, stages, autoDepth+1); err != nil { log.Printf("[workflow-engine] automated stage error: %v", err) } } return e.stores.Workflows.GetInstance(ctx, instanceID) } // Cancel terminates an active instance and all its open assignments. func (e *Engine) Cancel(ctx context.Context, instanceID string, userID string) error { inst, err := e.stores.Workflows.GetInstance(ctx, instanceID) if err != nil { return fmt.Errorf("instance not found: %w", err) } if inst.Status != models.InstanceStatusActive { return fmt.Errorf("instance is %s, not active", inst.Status) } if err := e.stores.Workflows.CancelInstance(ctx, instanceID); err != nil { return fmt.Errorf("cancel: %w", err) } // Cancel all open assignments assignments, _ := e.stores.Workflows.ListAssignmentsByInstance(ctx, instanceID) for _, a := range assignments { if a.Status == models.AssignmentStatusUnassigned || a.Status == models.AssignmentStatusClaimed { e.stores.Workflows.CancelAssignment(ctx, a.ID) } } e.emit(ctx, "workflow.cancelled", instanceID, map[string]any{ "instance_id": instanceID, "cancelled_by": userID, }) return nil } // ── Public Entry (v0.3.3) ─────────────────── // StartPublic creates an instance for a public_link workflow without authentication. // The caller is identified as "public:". Returns the instance including its entry_token. func (e *Engine) StartPublic(ctx context.Context, workflowID string, initialData json.RawMessage) (*models.WorkflowInstance, error) { wf, err := e.stores.Workflows.GetByID(ctx, workflowID) if err != nil { return nil, fmt.Errorf("workflow not found: %w", err) } if wf.EntryMode != "public_link" { return nil, fmt.Errorf("workflow %q does not accept public entry", wf.Name) } anonymousID := "public:" + uuid.New().String() return e.Start(ctx, workflowID, initialData, anonymousID) } // ResumePublic returns an active instance by its entry token. No authentication required. func (e *Engine) ResumePublic(ctx context.Context, entryToken string) (*models.WorkflowInstance, error) { inst, err := e.stores.Workflows.GetInstanceByToken(ctx, entryToken) if err != nil { return nil, fmt.Errorf("instance not found: %w", err) } if inst.Status != models.InstanceStatusActive { return nil, fmt.Errorf("instance is %s, not active", inst.Status) } return inst, nil } // AdvancePublic advances an instance identified by entry token. Only public-audience stages // can be advanced this way. The original anonymous identity is used as the actor. func (e *Engine) AdvancePublic(ctx context.Context, entryToken string, stageData json.RawMessage) (*models.WorkflowInstance, error) { inst, err := e.stores.Workflows.GetInstanceByToken(ctx, entryToken) if err != nil { return nil, fmt.Errorf("instance not found: %w", err) } if inst.Status != models.InstanceStatusActive { return nil, fmt.Errorf("instance is %s, not active", inst.Status) } // Load version snapshot to check audience ver, err := e.stores.Workflows.GetVersion(ctx, inst.WorkflowID, inst.WorkflowVersion) if err != nil { return nil, fmt.Errorf("version not found: %w", err) } var stages []models.WorkflowStage if err := json.Unmarshal(ver.Snapshot, &stages); err != nil { return nil, fmt.Errorf("corrupt snapshot: %w", err) } // Find current stage and validate audience for _, s := range stages { if s.Name == inst.CurrentStage { if s.Audience != models.AudiencePublic { return nil, fmt.Errorf("stage %q requires authenticated access", s.Name) } break } } return e.advanceInternal(ctx, inst.ID, stageData, inst.StartedBy, 0) } // emit publishes an event on the bus. func (e *Engine) emit(_ context.Context, label, room string, payload map[string]any) { if e.bus == nil { return } e.bus.Publish(events.Event{ Label: label, Room: room, Payload: events.MustJSON(payload), Ts: time.Now().UnixMilli(), }) } // mergeJSON merges b into a (shallow). Returns a if b is empty. func mergeJSON(a, b json.RawMessage) json.RawMessage { if len(b) == 0 || string(b) == "{}" || string(b) == "null" { if len(a) == 0 { return json.RawMessage(`{}`) } return a } if len(a) == 0 || string(a) == "{}" || string(a) == "null" { return b } var ma, mb map[string]json.RawMessage if json.Unmarshal(a, &ma) != nil { return b } if json.Unmarshal(b, &mb) != nil { return a } for k, v := range mb { ma[k] = v } merged, err := json.Marshal(ma) if err != nil { return b } return merged }