From 18e2bc9caf2537170e892924097c55e554c3f4fa Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Mon, 31 Aug 2026 21:28:46 +1000 Subject: [PATCH] refactor(lint): extract more helpers to clear nestif/gocyclo findings - toolset.go: extract requireApproval out of toolExecute (nestif) - gateway.go: extract handleDeny/handleVersion/handleUpdateCheck/ handleRestartAdapter out of dispatchLocal (gocyclo 26 -> under 20) - cronstore/store.go: extract applyPatch/applyScheduleChange out of Update (nestif, gocognit) Behavior-preserving. --- internal/agentexec/toolset.go | 77 +++++++++++--------- internal/gateway/gateway.go | 83 ++++++++++++++-------- internal/infrastructure/cronstore/store.go | 77 +++++++++++--------- 3 files changed, 139 insertions(+), 98 deletions(-) diff --git a/internal/agentexec/toolset.go b/internal/agentexec/toolset.go index bf0db4319..1f0ebe8e2 100644 --- a/internal/agentexec/toolset.go +++ b/internal/agentexec/toolset.go @@ -244,41 +244,8 @@ func toolExecute(entry tools.ToolEntry, opts ToolSetOptions) func(context.Contex } } if entry.Classification.IsApprovalRequired() { - if opts.Approval == nil { - return "", fmt.Errorf("tool %s requires approval but no approver is configured", entry.Name) - } - approveCtx, cancel := context.WithTimeout(ctx, tools.ToolApprovalTimeout) - defer cancel() - desc := entry.Description - if entry.BuildApprovalDescription != nil { - desc = entry.BuildApprovalDescription(args) - } - decision, err := opts.Approval.RequestApproval(approveCtx, entry.Name, desc) - if err != nil { - // Distinguish a tool-level timeout (our own deadline) - // from a turn-level cancellation (/stop). A turn - // cancellation must propagate as a context error; a - // tool timeout must surface as a plain error so the - // model can report it instead of the turn aborting. - if (errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled)) && ctx.Err() == nil { - return "", fmt.Errorf("tool %s: approval timed out after %v", entry.Name, tools.ToolApprovalTimeout) - } - return "", fmt.Errorf("tool %s: approval: %w", entry.Name, err) - } - switch decision { - case tools.ApprovalApproved, tools.ApprovalPermanentlyApproved: - // Fall through to execution. PermanentlyApproved is - // handled by the adapter caching the decision; the - // dispatch layer treats both the same. - case tools.ApprovalDenied: - return "", fmt.Errorf("tool %s: %w", entry.Name, tools.ErrApprovalDenied) - default: - // Fail closed: an unrecognised decision value from - // a faulty or future Approver must not execute the - // tool. ApprovalDecision is an exported int type, - // so a value returned with nil error is a defect - // in the approver, not a grant. - return "", fmt.Errorf("tool %s: approval returned unexpected decision %v", entry.Name, decision) + if err := requireApproval(ctx, entry, opts, args); err != nil { + return "", err } } out, err := entry.Handler(ctx, args) @@ -294,3 +261,43 @@ func toolExecute(entry tools.ToolEntry, opts ToolSetOptions) func(context.Contex return payload, nil } } + +// requireApproval blocks until entry's approval is granted, returning an +// error if it is denied, times out, or the approver misbehaves. +func requireApproval(ctx context.Context, entry tools.ToolEntry, opts ToolSetOptions, args map[string]any) error { + if opts.Approval == nil { + return fmt.Errorf("tool %s requires approval but no approver is configured", entry.Name) + } + approveCtx, cancel := context.WithTimeout(ctx, tools.ToolApprovalTimeout) + defer cancel() + desc := entry.Description + if entry.BuildApprovalDescription != nil { + desc = entry.BuildApprovalDescription(args) + } + decision, err := opts.Approval.RequestApproval(approveCtx, entry.Name, desc) + if err != nil { + // Distinguish a tool-level timeout (our own deadline) from a + // turn-level cancellation (/stop). A turn cancellation must + // propagate as a context error; a tool timeout must surface as + // a plain error so the model can report it instead of the turn + // aborting. + if (errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled)) && ctx.Err() == nil { + return fmt.Errorf("tool %s: approval timed out after %v", entry.Name, tools.ToolApprovalTimeout) + } + return fmt.Errorf("tool %s: approval: %w", entry.Name, err) + } + switch decision { + case tools.ApprovalApproved, tools.ApprovalPermanentlyApproved: + // PermanentlyApproved is handled by the adapter caching the + // decision; the dispatch layer treats both the same. + return nil + case tools.ApprovalDenied: + return fmt.Errorf("tool %s: %w", entry.Name, tools.ErrApprovalDenied) + default: + // Fail closed: an unrecognised decision value from a faulty or + // future Approver must not execute the tool. ApprovalDecision is + // an exported int type, so a value returned with nil error is a + // defect in the approver, not a grant. + return fmt.Errorf("tool %s: approval returned unexpected decision %v", entry.Name, decision) + } +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index f2c76fec5..0f2567c4e 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -345,18 +345,8 @@ func (r *Router) dispatchLocal(ctx context.Context, msg Message, text, cmd strin reply, err := r.handleApproveCommand(ctx, rest) return reply, true, err case "/deny": - if r.Dangerous == nil { - return "Dangerous approvals are not configured.", true, nil - } - fields := strings.Fields(rest) - if len(fields) != 1 { - return "Usage: /deny ", true, nil - } - result, err := r.Dangerous.Decide(ctx, fields[0], "deny") - if err != nil { - return fmt.Sprintf("Cannot deny action: %v", err), true, nil - } - return result, true, nil + reply, err := r.handleDeny(ctx, rest) + return reply, true, err case "/cancel": reply, err := r.handleCancel(ctx, rest) return reply, true, err @@ -384,31 +374,62 @@ func (r *Router) dispatchLocal(ctx context.Context, msg Message, text, cmd strin case "/help": return r.helpText(), true, nil case "/version": - if r.Version == "" { - return "Version information is not configured.", true, nil - } - return r.Version, true, nil + return r.handleVersion(), true, nil case "/update": - if r.Updates == nil { - return "Updates are not configured.", true, nil - } - snapshot, err := r.Updates.Check(ctx, 0) - if err != nil { - return fmt.Sprintf("Could not check for updates: %v", err), true, nil - } - return releaseupdate.FormatSnapshot(snapshot), true, nil + return r.handleUpdateCheck(ctx), true, nil case "/restart": - if r.Restart == nil { - return "Chat adapter restart is not configured.", true, nil - } - if err := r.Restart(ctx); err != nil { - return fmt.Sprintf("Could not restart the chat adapter: %v", err), true, nil - } - return "Chat adapter reload requested.", true, nil + return r.handleRestartAdapter(ctx), true, nil } return r.dispatchSessionCommand(ctx, msg, cmd, rest) } +// handleDeny denies a pending dangerous action by ID. +func (r *Router) handleDeny(ctx context.Context, rest string) (string, error) { + if r.Dangerous == nil { + return "Dangerous approvals are not configured.", nil + } + fields := strings.Fields(rest) + if len(fields) != 1 { + return "Usage: /deny ", nil + } + result, err := r.Dangerous.Decide(ctx, fields[0], "deny") + if err != nil { + return fmt.Sprintf("Cannot deny action: %v", err), nil + } + return result, nil +} + +// handleVersion reports the configured build version. +func (r *Router) handleVersion() string { + if r.Version == "" { + return "Version information is not configured." + } + return r.Version +} + +// handleUpdateCheck reports the latest available update snapshot. +func (r *Router) handleUpdateCheck(ctx context.Context) string { + if r.Updates == nil { + return "Updates are not configured." + } + snapshot, err := r.Updates.Check(ctx, 0) + if err != nil { + return fmt.Sprintf("Could not check for updates: %v", err) + } + return releaseupdate.FormatSnapshot(snapshot) +} + +// handleRestartAdapter reloads the chat adapter. +func (r *Router) handleRestartAdapter(ctx context.Context) string { + if r.Restart == nil { + return "Chat adapter restart is not configured." + } + if err := r.Restart(ctx); err != nil { + return fmt.Sprintf("Could not restart the chat adapter: %v", err) + } + return "Chat adapter reload requested." +} + // dispatchSessionCommand handles the session-lifecycle command group // (/new, /topic, /retry, /undo, /title, /branch, /compress and their // aliases). Split out from dispatchLocal to keep cyclomatic complexity diff --git a/internal/infrastructure/cronstore/store.go b/internal/infrastructure/cronstore/store.go index 4802f677c..313337356 100644 --- a/internal/infrastructure/cronstore/store.go +++ b/internal/infrastructure/cronstore/store.go @@ -334,38 +334,8 @@ func (s *Store) Update(ctx context.Context, id string, patch Patch) error { if s.buf[i].ID != id { continue } - if patch.Pool != nil { - s.buf[i].Pool = *patch.Pool - } - if patch.Detail != nil { - s.buf[i].Detail = *patch.Detail - } - if patch.Schedule != nil { - s.buf[i].Schedule = patch.Schedule.resolve() - // Schedule change: NextRun is stale. Recompute from - // the last run if there is one, else as a first run - // from now. Keeping it strictly future-of-now would - // re-fire a job the operator just shortened. - now := time.Now().UTC() - if s.buf[i].LastRun != nil { - next, err := s.buf[i].Schedule.nextRun(*s.buf[i].LastRun) - if err != nil { - return err - } - s.buf[i].NextRun = next.UTC() - } else { - next, err := s.buf[i].Schedule.firstRun(now) - if err != nil { - return err - } - s.buf[i].NextRun = next.UTC() - } - } - if patch.Target != nil { - s.buf[i].Target = *patch.Target - } - if patch.Payload != nil { - s.buf[i].Payload = *patch.Payload + if err := applyPatch(&s.buf[i], patch); err != nil { + return err } s.buf[i].Updated = time.Now().UTC() return s.writeLocked() @@ -374,6 +344,49 @@ func (s *Store) Update(ctx context.Context, id string, patch Patch) error { }) } +// applyPatch overwrites record's non-nil Patch fields in place, recomputing +// NextRun when Schedule changes. +func applyPatch(record *JobSpec, patch Patch) error { + if patch.Pool != nil { + record.Pool = *patch.Pool + } + if patch.Detail != nil { + record.Detail = *patch.Detail + } + if patch.Schedule != nil { + if err := applyScheduleChange(record, patch.Schedule); err != nil { + return err + } + } + if patch.Target != nil { + record.Target = *patch.Target + } + if patch.Payload != nil { + record.Payload = *patch.Payload + } + return nil +} + +// applyScheduleChange sets record's Schedule and recomputes NextRun, which +// is stale once Schedule changes. Recomputed from the last run if there is +// one, else as a first run from now — keeping it strictly future-of-now +// would re-fire a job the operator just shortened. +func applyScheduleChange(record *JobSpec, schedule *Schedule) error { + record.Schedule = schedule.resolve() + var next time.Time + var err error + if record.LastRun != nil { + next, err = record.Schedule.nextRun(*record.LastRun) + } else { + next, err = record.Schedule.firstRun(time.Now().UTC()) + } + if err != nil { + return err + } + record.NextRun = next.UTC() + return nil +} + // Delete removes the job by id. Idempotent: deleting a missing id // returns nil rather than ErrJobNotFound, so a CLI retry after a // partial failure cannot stall the operator.