chore(office): delete duplicated scheduler/channels/configloader files (#1084)

IdleTimeoutManager, the BuildPrompt family, ChannelRelay, and
configloader.Watcher were forked into internal/office/service/ and
internal/orchestrator/watcher/ during the scheduler/→service/ refactor
but never removed from their original homes. All four types (and their
two same-package self-tests) had zero importers across the repo.

Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
João Salavisa
2026-05-26 17:03:11 +01:00
committed by GitHub
parent 6ee7369efc
commit d7d74a8bc5
6 changed files with 0 additions and 1185 deletions
@@ -1,259 +0,0 @@
package channels
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"net/url"
"time"
"go.uber.org/zap"
"github.com/kandev/kandev/internal/office/models"
)
// ChannelRelay handles outbound message delivery to external platforms.
type ChannelRelay struct {
svc *ChannelService
client *http.Client
}
// NewChannelRelay creates a new channel relay.
func NewChannelRelay(svc *ChannelService) *ChannelRelay {
return &ChannelRelay{
svc: svc,
client: &http.Client{Timeout: 10 * time.Second},
}
}
// NewChannelRelayWithClient creates a channel relay with a custom HTTP client (for testing).
func NewChannelRelayWithClient(svc *ChannelService, client *http.Client) *ChannelRelay {
return &ChannelRelay{svc: svc, client: client}
}
// RelayComment checks whether a comment should be relayed to an external
// platform and, if so, sends it via the appropriate platform API.
func (r *ChannelRelay) RelayComment(ctx context.Context, comment *models.TaskComment) error {
if comment.ReplyChannelID == "" {
return nil // not a channel comment
}
if comment.AuthorType != "agent" {
return nil // only relay agent comments
}
channel, err := r.svc.GetChannelByID(ctx, comment.ReplyChannelID)
if err != nil {
return fmt.Errorf("load channel %s: %w", comment.ReplyChannelID, err)
}
config, err := parseChannelConfig(channel.Config)
if err != nil {
return fmt.Errorf("parse channel config: %w", err)
}
// Channel relay fires from the comment-bridging path triggered by
// an agent turn. When a RunResolver is wired, attribute the
// activity to whichever run is currently claimed for this task so
// it surfaces under Tasks Touched on the run detail page.
runID := ""
if r.svc.runs != nil {
runID = r.svc.runs.ResolveRunForTask(ctx, comment.TaskID)
}
sendErr := r.sendWithRetry(ctx, string(channel.Platform), config, comment.Body)
if sendErr != nil {
r.svc.activity.LogActivityWithRun(ctx, channel.WorkspaceID, "system", "", "channel.delivery_failed",
"channel", channel.ID,
fmt.Sprintf(`{"error":%q,"platform":%q}`, sendErr.Error(), channel.Platform),
runID, "")
return sendErr
}
r.svc.activity.LogActivityWithRun(ctx, channel.WorkspaceID, "system", "", "channel.message_relayed",
"channel", channel.ID,
fmt.Sprintf(`{"platform":%q}`, channel.Platform),
runID, "")
return nil
}
// channelConfig holds platform-specific config fields.
type channelConfig struct {
BotToken string `json:"bot_token"`
ChatID string `json:"chat_id"`
ChannelID string `json:"channel_id"`
WebhookURL string `json:"webhook_url"`
}
func parseChannelConfig(raw string) (*channelConfig, error) {
var cfg channelConfig
if err := json.Unmarshal([]byte(raw), &cfg); err != nil {
return nil, err
}
return &cfg, nil
}
const maxRetries = 3
// sendWithRetry dispatches a message with exponential backoff.
func (r *ChannelRelay) sendWithRetry(
ctx context.Context, platform string, cfg *channelConfig, message string,
) error {
var lastErr error
for attempt := 0; attempt < maxRetries; attempt++ {
if attempt > 0 {
delay := time.Duration(1<<uint(attempt-1)) * time.Second
// Use NewTimer rather than time.After so a context cancellation
// during the backoff stops the underlying timer immediately
// instead of leaving it pinned in the runtime until it fires.
timer := time.NewTimer(delay)
select {
case <-timer.C:
case <-ctx.Done():
// Stop() returns false if the timer already fired between
// the select winning and Stop running; drain timer.C in
// that case so the buffered value does not strand on the
// channel.
if !timer.Stop() {
<-timer.C
}
return ctx.Err()
}
}
lastErr = r.dispatch(ctx, platform, cfg, message)
if lastErr == nil {
return nil
}
r.svc.logger.Warn("channel relay attempt failed",
zap.String("platform", platform),
zap.Int("attempt", attempt+1),
zap.Error(lastErr))
}
return fmt.Errorf("relay failed after %d attempts: %w", maxRetries, lastErr)
}
// dispatch routes to the platform-specific sender.
func (r *ChannelRelay) dispatch(
ctx context.Context, platform string, cfg *channelConfig, message string,
) error {
switch platform {
case "telegram":
return r.sendTelegram(ctx, cfg.BotToken, cfg.ChatID, message)
case "slack":
return r.sendSlack(ctx, cfg.BotToken, cfg.ChannelID, message)
case "discord":
return r.sendDiscord(ctx, cfg.BotToken, cfg.ChannelID, message)
case "webhook":
return r.sendGenericWebhook(ctx, cfg.WebhookURL, message)
default:
return fmt.Errorf("unsupported platform: %s", platform)
}
}
// sendTelegram sends a message via the Telegram Bot API.
func (r *ChannelRelay) sendTelegram(ctx context.Context, botToken, chatID, message string) error {
url := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", botToken)
body := map[string]string{
"chat_id": chatID,
"text": message,
"parse_mode": "Markdown",
}
return r.postJSON(ctx, url, nil, body)
}
// sendSlack sends a message via the Slack Web API.
func (r *ChannelRelay) sendSlack(ctx context.Context, botToken, channelID, message string) error {
headers := map[string]string{
"Authorization": "Bearer " + botToken,
}
body := map[string]string{
"channel": channelID,
"text": message,
}
return r.postJSON(ctx, "https://slack.com/api/chat.postMessage", headers, body)
}
// sendDiscord sends a message via the Discord API.
func (r *ChannelRelay) sendDiscord(ctx context.Context, botToken, channelID, message string) error {
url := fmt.Sprintf("https://discord.com/api/v10/channels/%s/messages", channelID)
headers := map[string]string{
"Authorization": "Bot " + botToken,
}
body := map[string]string{
"content": message,
}
return r.postJSON(ctx, url, headers, body)
}
// sendGenericWebhook sends a message to a generic webhook endpoint.
// The URL is validated before dispatching to prevent SSRF.
func (r *ChannelRelay) sendGenericWebhook(ctx context.Context, webhookURL, message string) error {
if err := validateWebhookURL(webhookURL); err != nil {
return fmt.Errorf("invalid webhook URL: %w", err)
}
body := map[string]string{"text": message}
return r.postJSON(ctx, webhookURL, nil, body)
}
// validateWebhookURL rejects URLs that could be used for SSRF attacks:
// only http/https schemes are allowed, bare IP addresses are blocked,
// and RFC-1918 / loopback ranges are blocked.
func validateWebhookURL(raw string) error {
u, err := url.Parse(raw)
if err != nil {
return fmt.Errorf("parse URL: %w", err)
}
if u.Scheme != "http" && u.Scheme != "https" {
return fmt.Errorf("scheme %q not allowed (only http/https)", u.Scheme)
}
host := u.Hostname()
if host == "" {
return fmt.Errorf("missing host")
}
// Block bare IP addresses (IPv4 and IPv6).
if ip := net.ParseIP(host); ip != nil {
if ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() {
return fmt.Errorf("webhook URL resolves to a private/loopback address")
}
// Block all bare IPs to prevent SSRF via direct IP notation.
return fmt.Errorf("webhook URL must use a hostname, not a bare IP address")
}
// Block localhost by name.
if host == "localhost" {
return fmt.Errorf("webhook URL must not target localhost")
}
return nil
}
// postJSON is a helper that POSTs a JSON body and checks for a 2xx response.
func (r *ChannelRelay) postJSON(
ctx context.Context, url string, headers map[string]string, body interface{},
) error {
payload, err := json.Marshal(body)
if err != nil {
return fmt.Errorf("marshal body: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(payload))
if err != nil {
return fmt.Errorf("create request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
for k, v := range headers {
req.Header.Set(k, v)
}
resp, err := r.client.Do(req)
if err != nil {
return fmt.Errorf("send request: %w", err)
}
defer func() { _ = resp.Body.Close() }()
_, _ = io.Copy(io.Discard, resp.Body)
if resp.StatusCode >= 300 {
return fmt.Errorf("platform returned HTTP %d", resp.StatusCode)
}
return nil
}
@@ -1,141 +0,0 @@
package configloader
import (
"context"
"log"
"path/filepath"
"sync"
"time"
"github.com/fsnotify/fsnotify"
)
// DefaultDebounceDuration is the default debounce interval for filesystem events.
const DefaultDebounceDuration = 100 * time.Millisecond
// Watcher watches workspace directories for changes and triggers reloads.
type Watcher struct {
loader *ConfigLoader
watcher *fsnotify.Watcher
debounce time.Duration
onReload func(workspace string)
}
// NewWatcher creates a file system watcher backed by the given config loader.
func NewWatcher(loader *ConfigLoader) (*Watcher, error) {
fsw, err := fsnotify.NewWatcher()
if err != nil {
return nil, err
}
return &Watcher{
loader: loader,
watcher: fsw,
debounce: DefaultDebounceDuration,
}, nil
}
// SetDebounceDuration overrides the debounce interval (useful for tests).
func (w *Watcher) SetDebounceDuration(d time.Duration) {
w.debounce = d
}
// SetOnReload registers a callback invoked after a workspace is reloaded.
// The callback receives the workspace name that was reloaded.
func (w *Watcher) SetOnReload(fn func(workspace string)) {
w.onReload = fn
}
// Start begins watching all workspace directories. It blocks until ctx is cancelled.
func (w *Watcher) Start(ctx context.Context) error {
if err := w.addWatchPaths(); err != nil {
return err
}
w.eventLoop(ctx)
return nil
}
// addWatchPaths registers the workspaces directory and each workspace's subdirectories.
func (w *Watcher) addWatchPaths() error {
wsDir := filepath.Join(w.loader.BasePath(), "workspaces")
if err := w.watcher.Add(wsDir); err != nil {
return err
}
workspaces := w.loader.GetWorkspaces()
for _, ws := range workspaces {
w.addWorkspaceSubdirs(ws.DirPath)
}
return nil
}
// addWorkspaceSubdirs watches the workspace root and its immediate subdirectories.
func (w *Watcher) addWorkspaceSubdirs(wsPath string) {
_ = w.watcher.Add(wsPath)
for _, sub := range []string{"agents", "skills", "projects", "routines"} {
_ = w.watcher.Add(filepath.Join(wsPath, sub))
}
}
// flushPending drains the pending workspace set, reloads each, and fires the
// onReload callback. It is called from the debounce timer.
func (w *Watcher) flushPending(mu *sync.Mutex, pending map[string]struct{}) {
mu.Lock()
names := make([]string, 0, len(pending))
for n := range pending {
names = append(names, n)
}
for n := range pending {
delete(pending, n)
}
mu.Unlock()
for _, n := range names {
if err := w.loader.Reload(n); err != nil {
log.Printf("configloader: reload %s: %v", n, err)
continue
}
if w.onReload != nil {
w.onReload(n)
}
}
}
// eventLoop processes fsnotify events with debouncing.
func (w *Watcher) eventLoop(ctx context.Context) {
var mu sync.Mutex
pending := make(map[string]struct{})
var timer *time.Timer
for {
select {
case <-ctx.Done():
return
case event, ok := <-w.watcher.Events:
if !ok {
return
}
wsName := w.loader.WorkspaceNameFromPath(event.Name)
if wsName == "" {
continue
}
mu.Lock()
pending[wsName] = struct{}{}
if timer != nil {
timer.Stop()
}
timer = time.AfterFunc(w.debounce, func() {
w.flushPending(&mu, pending)
})
mu.Unlock()
case err, ok := <-w.watcher.Errors:
if !ok {
return
}
log.Printf("configloader: watcher error: %v", err)
}
}
}
// Stop closes the underlying fsnotify watcher.
func (w *Watcher) Stop() error {
return w.watcher.Close()
}
@@ -1,129 +0,0 @@
package configloader
import (
"context"
"os"
"path/filepath"
"testing"
"time"
)
func TestWatcherDetectsFileChange(t *testing.T) {
base := setupTestWorkspace(t)
loader := NewConfigLoader(base)
if err := loader.Load(); err != nil {
t.Fatalf("Load() error: %v", err)
}
watcher, err := NewWatcher(loader)
if err != nil {
t.Fatalf("NewWatcher() error: %v", err)
}
watcher.SetDebounceDuration(10 * time.Millisecond)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() {
_ = watcher.Start(ctx)
}()
// Wait for watcher to register paths.
time.Sleep(50 * time.Millisecond)
// Write a new agent file.
agentsDir := filepath.Join(base, "workspaces", "default", "agents")
writeFile(t, filepath.Join(agentsDir, "new-agent.yml"), `
name: new-agent
role: worker
budget_monthly_cents: 1000
`)
// Wait for debounce + reload.
time.Sleep(200 * time.Millisecond)
agents := loader.GetAgents("default")
found := false
for _, a := range agents {
if a.Name == "new-agent" {
found = true
}
}
if !found {
t.Error("watcher did not detect new agent file")
}
// Cleanup.
cancel()
if err := watcher.Stop(); err != nil {
t.Fatalf("Stop() error: %v", err)
}
}
func TestWatcherDetectsFileDeletion(t *testing.T) {
base := setupTestWorkspace(t)
loader := NewConfigLoader(base)
if err := loader.Load(); err != nil {
t.Fatalf("Load() error: %v", err)
}
// Verify ceo exists.
agents := loader.GetAgents("default")
hasCEO := false
for _, a := range agents {
if a.Name == "ceo" {
hasCEO = true
}
}
if !hasCEO {
t.Fatal("expected ceo agent to exist before deletion")
}
watcher, err := NewWatcher(loader)
if err != nil {
t.Fatalf("NewWatcher() error: %v", err)
}
watcher.SetDebounceDuration(10 * time.Millisecond)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() {
_ = watcher.Start(ctx)
}()
time.Sleep(50 * time.Millisecond)
// Delete the ceo agent file.
ceoPath := filepath.Join(base, "workspaces", "default", "agents", "ceo.yml")
if err := os.Remove(ceoPath); err != nil {
t.Fatalf("remove ceo.yml: %v", err)
}
time.Sleep(200 * time.Millisecond)
agents = loader.GetAgents("default")
for _, a := range agents {
if a.Name == "ceo" {
t.Error("watcher did not detect ceo file deletion")
}
}
cancel()
_ = watcher.Stop()
}
func TestWatcherStopIsIdempotent(t *testing.T) {
base := setupTestWorkspace(t)
loader := NewConfigLoader(base)
_ = loader.Load()
watcher, err := NewWatcher(loader)
if err != nil {
t.Fatalf("NewWatcher() error: %v", err)
}
// Stop without ever starting should not panic.
if err := watcher.Stop(); err != nil {
t.Fatalf("Stop() error: %v", err)
}
}
@@ -1,138 +0,0 @@
package scheduler
import (
"context"
"sync"
"time"
"go.uber.org/zap"
"github.com/kandev/kandev/internal/common/logger"
)
// DefaultIdleTimeout is the default duration after which a terminal-state
// task's agentctl execution is cleaned up if no viewer is connected.
const DefaultIdleTimeout = 5 * time.Minute
// terminalTaskStates lists task states that are considered terminal.
var terminalTaskStates = map[string]bool{
"COMPLETED": true,
"CANCELLED": true,
"FAILED": true,
}
// IdleTimeoutManager manages idle timers for sessions whose tasks have
// reached a terminal state.
type IdleTimeoutManager struct {
ss *SchedulerService
timeout time.Duration
timers map[string]*time.Timer // sessionID -> timer
mu sync.Mutex
logger *logger.Logger
}
// NewIdleTimeoutManager creates a new IdleTimeoutManager.
func NewIdleTimeoutManager(ss *SchedulerService, timeout time.Duration) *IdleTimeoutManager {
if timeout <= 0 {
timeout = DefaultIdleTimeout
}
return &IdleTimeoutManager{
ss: ss,
timeout: timeout,
timers: make(map[string]*time.Timer),
logger: ss.logger.WithFields(zap.String("component", "idle-timeout")),
}
}
// OnRunFinished is called after a run is marked as finished.
// It checks if the task is in a terminal state and starts an idle timer.
func (m *IdleTimeoutManager) OnRunFinished(sessionID, taskID string) {
if sessionID == "" || taskID == "" {
return
}
if !m.isTaskTerminal(taskID) {
return
}
m.startTimer(sessionID)
}
// OnViewerConnected cancels any pending idle timer for the session.
func (m *IdleTimeoutManager) OnViewerConnected(sessionID string) {
m.cancelTimer(sessionID)
}
// OnViewerDisconnected starts an idle timer if the task is terminal.
func (m *IdleTimeoutManager) OnViewerDisconnected(sessionID string, taskTerminal bool) {
if !taskTerminal {
return
}
m.startTimer(sessionID)
}
// isTaskTerminal checks if the task's current state is terminal.
func (m *IdleTimeoutManager) isTaskTerminal(taskID string) bool {
fields, err := m.ss.repo.GetTaskExecutionFields(context.Background(), taskID)
if err != nil {
m.logger.Debug("failed to check task state for idle timeout",
zap.String("task_id", taskID), zap.Error(err))
return false
}
return terminalTaskStates[fields.State]
}
// startTimer starts (or restarts) the idle timer for a session.
func (m *IdleTimeoutManager) startTimer(sessionID string) {
m.mu.Lock()
defer m.mu.Unlock()
// Cancel existing timer if present.
if existing, ok := m.timers[sessionID]; ok {
existing.Stop()
}
m.logger.Info("idle timeout started for terminal session",
zap.String("session_id", sessionID),
zap.Duration("timeout", m.timeout))
m.timers[sessionID] = time.AfterFunc(m.timeout, func() {
m.cleanup(sessionID)
})
}
// cancelTimer cancels a pending idle timer for a session.
func (m *IdleTimeoutManager) cancelTimer(sessionID string) {
m.mu.Lock()
defer m.mu.Unlock()
if timer, ok := m.timers[sessionID]; ok {
timer.Stop()
delete(m.timers, sessionID)
m.logger.Info("idle timeout cancelled (viewer connected)",
zap.String("session_id", sessionID))
}
}
// cleanup performs the actual cleanup when the idle timer fires.
func (m *IdleTimeoutManager) cleanup(sessionID string) {
m.mu.Lock()
delete(m.timers, sessionID)
m.mu.Unlock()
m.logger.Info("idle timeout expired, cleaning up execution",
zap.String("session_id", sessionID))
// Log activity. We don't have a workspace ID here, so use empty string.
m.ss.svc.LogActivityWithRun(context.Background(), "",
"system", "idle-timeout",
"execution_idle_cleanup", "session", sessionID,
mustJSON(map[string]string{
"reason": "terminal task idle timeout",
}), "", sessionID)
}
// PendingCount returns the number of active idle timers (for testing).
func (m *IdleTimeoutManager) PendingCount() int {
m.mu.Lock()
defer m.mu.Unlock()
return len(m.timers)
}
@@ -1,402 +0,0 @@
package scheduler
import (
"encoding/json"
"fmt"
"strings"
)
// PromptContext holds the data needed to build a run prompt.
type PromptContext struct {
Reason string
// Task fields
TaskID string
TaskIdentifier string
TaskTitle string
TaskDescription string
TaskPriority string
ProjectName string
// Comment fields
CommentBody string
CommentAuthor string
CommentAuthorType string
// Blocker fields
ResolvedBlockerTitles []string
// Children completed fields
ChildSummaries []ChildSummaryPrompt
ChildSummariesTruncated bool
// Approval fields
ApprovalType string
ApprovalStatus string
ApprovalNote string
ApprovalAgentName string
// Heartbeat fields (CEO)
AgentsIdle int
AgentsWorking int
AgentsPaused int
TasksInProgress int
TasksCompleted int
TasksPending int
BudgetUsedPct int
RecentErrors []string
// Stage fields (execution policy)
StageID string // execution policy stage ID
StageType string // "work", "review", "approval", "ship"
BuilderComments []string // latest comments from the builder/assignee
ReviewFeedback string // aggregated feedback from rejected review
// Office task-handoffs phase 8 — cross-task context appended to every
// run prompt. Document bodies are intentionally NOT included; the
// agent must call get_task_document_kandev to fetch them.
HandoffContext *HandoffPromptContext
}
// HandoffPromptContext bundles the cross-task context surfaced by the
// office task-handoffs feature into each run's system prompt. The fields
// mirror v1.TaskContext but trimmed to what the agent actually needs to
// know.
type HandoffPromptContext struct {
ParentRef string // identifier + title (e.g. "KAN-12 Plan implementation"); empty for roots
SiblingRefs []string // identifier + title per sibling
BlockerRefs []string // identifier + title per active blocker
BlockedByRefs []string // tasks this one is currently blocking
AvailableDocs []HandoffDocPrompt // documents on self/parent/siblings; bodies NOT included
WorkspaceMode string // inherit_parent | new_workspace | shared_group | ""
WorkspaceMembers []string // identifier + title of every active group member (besides self)
MaterializedPath string // reference path so the agent can `cd` if needed
MaterializedKind string // plain_folder | single_repo | multi_repo | remote_environment
WorkspaceStatus string // active | requires_configuration
}
// HandoffDocPrompt is the metadata-only document projection appended to
// the prompt's "Documents available" section. Fetching the body requires
// an explicit get_task_document_kandev call.
type HandoffDocPrompt struct {
TaskRef string // identifier + title of the document's owning task
Key string
Title string
}
// ChildSummaryPrompt holds display data for a completed child task.
type ChildSummaryPrompt struct {
Identifier string
Title string
State string
LastComment string
}
// BuildPrompt generates a structured prompt for a run reason. The
// handoff context (cross-task references + available document keys) is
// appended to every prompt so the agent always sees the surrounding
// task tree, regardless of which reason woke it.
func BuildPrompt(pc *PromptContext) string {
body := buildPromptBody(pc)
if section := buildHandoffSection(pc.HandoffContext); section != "" {
if !strings.HasSuffix(body, "\n") {
body += "\n"
}
body += "\n" + section
}
return body
}
func buildPromptBody(pc *PromptContext) string {
switch pc.Reason {
case RunReasonTaskAssigned:
return buildTaskAssignedPrompt(pc)
case RunReasonTaskComment:
return buildTaskCommentPrompt(pc)
case RunReasonTaskBlockersResolved:
return buildBlockersResolvedPrompt(pc)
case RunReasonTaskChildrenCompleted:
return buildChildrenCompletedPrompt(pc)
case RunReasonApprovalResolved:
return buildApprovalResolvedPrompt(pc)
case RunReasonHeartbeat:
return buildHeartbeatPrompt(pc)
case RunReasonBudgetAlert:
return buildBudgetAlertPrompt(pc)
case RunReasonAgentError:
return buildAgentErrorPrompt(pc)
default:
return fmt.Sprintf("You have been woken for reason: %s.", pc.Reason)
}
}
// buildHandoffSection renders the "Related tasks" / "Documents
// available" / "Workspace" block. Returns the empty string when the
// HandoffPromptContext is nil or carries no information so the prompt
// stays untouched for tasks without any handoff context.
//
// Document bodies are intentionally omitted; agents must call
// get_task_document_kandev to fetch a specific document.
func buildHandoffSection(hc *HandoffPromptContext) string {
if hc == nil || handoffSectionEmpty(hc) {
return ""
}
var b strings.Builder
appendRelationsSubsection(&b, hc)
appendDocumentsSubsection(&b, hc)
appendWorkspaceSubsection(&b, hc)
return strings.TrimRight(b.String(), "\n")
}
func appendRelationsSubsection(b *strings.Builder, hc *HandoffPromptContext) {
if hc.ParentRef == "" && len(hc.SiblingRefs) == 0 && len(hc.BlockerRefs) == 0 && len(hc.BlockedByRefs) == 0 {
return
}
b.WriteString("Related tasks:\n")
if hc.ParentRef != "" {
fmt.Fprintf(b, "- Parent: %s\n", hc.ParentRef)
}
for _, ref := range hc.SiblingRefs {
fmt.Fprintf(b, "- Sibling: %s\n", ref)
}
for _, ref := range hc.BlockerRefs {
fmt.Fprintf(b, "- Blocked by: %s\n", ref)
}
for _, ref := range hc.BlockedByRefs {
fmt.Fprintf(b, "- Blocks: %s\n", ref)
}
}
func appendDocumentsSubsection(b *strings.Builder, hc *HandoffPromptContext) {
if len(hc.AvailableDocs) == 0 {
return
}
if b.Len() > 0 {
b.WriteString("\n")
}
b.WriteString("Documents available (fetch with get_task_document_kandev):\n")
for _, d := range hc.AvailableDocs {
title := d.Title
if title == "" {
title = d.Key
}
fmt.Fprintf(b, "- %s %s — %q\n", d.TaskRef, d.Key, title)
}
}
func appendWorkspaceSubsection(b *strings.Builder, hc *HandoffPromptContext) {
if hc.WorkspaceMode == "" && hc.MaterializedPath == "" && len(hc.WorkspaceMembers) == 0 {
return
}
if b.Len() > 0 {
b.WriteString("\n")
}
b.WriteString("Workspace:\n")
if hc.WorkspaceMode != "" {
fmt.Fprintf(b, "- mode: %s\n", hc.WorkspaceMode)
}
if len(hc.WorkspaceMembers) > 0 {
fmt.Fprintf(b, "- shared with: %s\n", strings.Join(hc.WorkspaceMembers, ", "))
}
if hc.MaterializedPath != "" {
fmt.Fprintf(b, "- path: %s\n", hc.MaterializedPath)
}
if hc.MaterializedKind != "" {
fmt.Fprintf(b, "- kind: %s\n", hc.MaterializedKind)
}
if hc.WorkspaceStatus != "" && hc.WorkspaceStatus != "active" {
fmt.Fprintf(b, "- status: %s\n", hc.WorkspaceStatus)
}
}
func handoffSectionEmpty(hc *HandoffPromptContext) bool {
return hc.ParentRef == "" &&
len(hc.SiblingRefs) == 0 &&
len(hc.BlockerRefs) == 0 &&
len(hc.BlockedByRefs) == 0 &&
len(hc.AvailableDocs) == 0 &&
hc.WorkspaceMode == "" &&
hc.MaterializedPath == "" &&
len(hc.WorkspaceMembers) == 0
}
func buildTaskAssignedPrompt(pc *PromptContext) string {
switch pc.StageType {
case "review":
return buildReviewStagePrompt(pc)
case "ship":
return buildShipStagePrompt(pc)
case "work":
if pc.ReviewFeedback != "" {
return buildReworkPrompt(pc)
}
}
return buildDefaultWorkPrompt(pc)
}
func buildDefaultWorkPrompt(pc *PromptContext) string {
var b strings.Builder
fmt.Fprintf(&b, "You have been assigned task %s: %s.\n", taskRef(pc), pc.TaskTitle)
if pc.ProjectName != "" {
fmt.Fprintf(&b, "Project: %s\n", pc.ProjectName)
}
if pc.TaskDescription != "" {
fmt.Fprintf(&b, "Description: %s\n", pc.TaskDescription)
}
if pc.TaskPriority != "" {
fmt.Fprintf(&b, "Priority: %s\n", pc.TaskPriority)
}
b.WriteString("Read the description and start working.")
return b.String()
}
func buildReviewStagePrompt(pc *PromptContext) string {
var b strings.Builder
fmt.Fprintf(&b, "You are reviewing task %s: %s.\n", taskRef(pc), pc.TaskTitle)
if pc.TaskDescription != "" {
fmt.Fprintf(&b, "\nTask description:\n%s\n", pc.TaskDescription)
}
if len(pc.BuilderComments) > 0 {
fmt.Fprintf(&b, "\nBuilder's comments:\n%s\n", strings.Join(pc.BuilderComments, "\n"))
}
b.WriteString("\nReview the implementation carefully. Check for correctness, edge cases, and code quality.\n")
b.WriteString("Submit your verdict: approve if the work is satisfactory, or reject with specific feedback on what needs to change.")
return b.String()
}
func buildShipStagePrompt(pc *PromptContext) string {
return fmt.Sprintf(
"Task %s: %s has been approved by all reviewers.\n\nCommit the changes and create a pull request. Run verification (format, lint, test) before committing.",
taskRef(pc), pc.TaskTitle,
)
}
func buildReworkPrompt(pc *PromptContext) string {
var b strings.Builder
fmt.Fprintf(&b, "Task %s: %s was returned by reviewers with feedback.\n", taskRef(pc), pc.TaskTitle)
fmt.Fprintf(&b, "\nReviewer feedback:\n%s\n", pc.ReviewFeedback)
b.WriteString("\nAddress the feedback and resubmit your changes.")
return b.String()
}
func buildTaskCommentPrompt(pc *PromptContext) string {
var b strings.Builder
fmt.Fprintf(&b, "New comment on your task %s: %s\n", taskRef(pc), pc.TaskTitle)
if pc.CommentAuthor != "" {
authorDesc := pc.CommentAuthor
if pc.CommentAuthorType != "" {
authorDesc += " (" + pc.CommentAuthorType + ")"
}
fmt.Fprintf(&b, "From: %s\n", authorDesc)
}
fmt.Fprintf(&b, "Comment: %s\n", pc.CommentBody)
b.WriteString("Address this comment.")
return b.String()
}
func buildBlockersResolvedPrompt(pc *PromptContext) string {
var b strings.Builder
fmt.Fprintf(&b, "All blockers for your task %s: %s have been resolved.\n", taskRef(pc), pc.TaskTitle)
if len(pc.ResolvedBlockerTitles) > 0 {
fmt.Fprintf(&b, "Resolved blockers: %s\n", strings.Join(pc.ResolvedBlockerTitles, ", "))
}
b.WriteString("You can now proceed with your work.")
return b.String()
}
func buildChildrenCompletedPrompt(pc *PromptContext) string {
var b strings.Builder
fmt.Fprintf(&b, "All child tasks for your task %s: %s have completed.\n", taskRef(pc), pc.TaskTitle)
if len(pc.ChildSummaries) > 0 {
b.WriteString("\nCompleted children:\n")
for _, c := range pc.ChildSummaries {
writeChildSummaryLine(&b, &c)
}
if pc.ChildSummariesTruncated {
b.WriteString("(showing first 20 children — fetch the full list via API)\n")
}
}
b.WriteString("\nReview their output and determine next steps.")
return b.String()
}
func writeChildSummaryLine(b *strings.Builder, c *ChildSummaryPrompt) {
ref := c.Identifier
if ref == "" {
ref = "?"
}
fmt.Fprintf(b, "- %s (%s) [%s]", ref, c.Title, c.State)
if c.LastComment != "" {
summary := truncateComment(c.LastComment)
fmt.Fprintf(b, " — %q", summary)
}
b.WriteString("\n")
}
func truncateComment(s string) string {
if len(s) > 500 {
return s[:485] + " [truncated]"
}
return s
}
func buildApprovalResolvedPrompt(pc *PromptContext) string {
var b strings.Builder
fmt.Fprintf(&b, "Your approval request %s has been %s.\n", pc.ApprovalType, pc.ApprovalStatus)
if pc.ApprovalNote != "" {
fmt.Fprintf(&b, "Decision note: %s\n", pc.ApprovalNote)
}
if pc.ApprovalStatus == "rejected" && pc.ApprovalType == "task_review" {
b.WriteString("Address the feedback and resubmit.")
}
if pc.ApprovalStatus == "approved" && pc.ApprovalType == "hire_agent" && pc.ApprovalAgentName != "" {
fmt.Fprintf(&b, "The new agent %s is now active.\n", pc.ApprovalAgentName)
}
return b.String()
}
func buildHeartbeatPrompt(pc *PromptContext) string {
var b strings.Builder
b.WriteString("Workspace status update:\n")
fmt.Fprintf(&b, "Agents: %d idle, %d working, %d paused\n",
pc.AgentsIdle, pc.AgentsWorking, pc.AgentsPaused)
fmt.Fprintf(&b, "Tasks: %d in progress, %d completed since last heartbeat, %d pending assignment\n",
pc.TasksInProgress, pc.TasksCompleted, pc.TasksPending)
fmt.Fprintf(&b, "Budget: %d%% used this month\n", pc.BudgetUsedPct)
if len(pc.RecentErrors) > 0 {
fmt.Fprintf(&b, "Errors: %s\n", strings.Join(pc.RecentErrors, "; "))
}
b.WriteString("Review the status and take action if needed.")
return b.String()
}
func buildBudgetAlertPrompt(pc *PromptContext) string {
return fmt.Sprintf("Budget alert: %d%% of monthly budget has been used. Review spending.", pc.BudgetUsedPct)
}
func buildAgentErrorPrompt(pc *PromptContext) string {
errMsg := "unknown"
if len(pc.RecentErrors) > 0 {
errMsg = pc.RecentErrors[0]
}
return fmt.Sprintf("An agent session has failed. Error: %s\nInvestigate and take corrective action.", errMsg)
}
func taskRef(pc *PromptContext) string {
if pc.TaskIdentifier != "" {
return "[" + pc.TaskIdentifier + "]"
}
return "[" + pc.TaskID + "]"
}
// ParseRunPayload extracts common fields from a run payload JSON.
func ParseRunPayload(payloadJSON string) map[string]string {
result := make(map[string]string)
if payloadJSON == "" || payloadJSON == "{}" {
return result
}
_ = json.Unmarshal([]byte(payloadJSON), &result)
return result
}
@@ -1,116 +0,0 @@
package scheduler
import (
"strings"
"testing"
)
func TestBuildPrompt_NoHandoffContextLeavesPromptUntouched(t *testing.T) {
pc := &PromptContext{
Reason: RunReasonTaskAssigned,
TaskTitle: "Implement endpoint",
}
out := BuildPrompt(pc)
if strings.Contains(out, "Related tasks") {
t.Errorf("expected no related-tasks section when HandoffContext is nil; got:\n%s", out)
}
if strings.Contains(out, "Documents available") {
t.Errorf("expected no documents section; got:\n%s", out)
}
}
func TestBuildPrompt_AppendsRelatedTasksSection(t *testing.T) {
pc := &PromptContext{
Reason: RunReasonTaskAssigned,
TaskTitle: "Implement endpoint",
HandoffContext: &HandoffPromptContext{
ParentRef: "KAN-12 Plan implementation",
SiblingRefs: []string{"KAN-14 Write spec"},
BlockerRefs: []string{"KAN-13 Plan implementation"},
BlockedByRefs: []string{"KAN-15 Review"},
},
}
out := BuildPrompt(pc)
if !strings.Contains(out, "Related tasks:") {
t.Errorf("missing related tasks header:\n%s", out)
}
if !strings.Contains(out, "Parent: KAN-12 Plan implementation") {
t.Errorf("missing parent ref:\n%s", out)
}
if !strings.Contains(out, "Sibling: KAN-14 Write spec") {
t.Errorf("missing sibling ref:\n%s", out)
}
if !strings.Contains(out, "Blocked by: KAN-13 Plan implementation") {
t.Errorf("missing blocker ref:\n%s", out)
}
if !strings.Contains(out, "Blocks: KAN-15 Review") {
t.Errorf("missing blocked-by ref:\n%s", out)
}
}
// REGRESSION: the spec is explicit that document BODIES never appear in
// the prompt — the agent must fetch them via get_task_document_kandev.
// This test enforces the contract by including a docs entry whose
// "title" is set to a marker string and asserting only key+title (no
// content) appear.
func TestBuildPrompt_DocumentBodiesNeverInlined(t *testing.T) {
pc := &PromptContext{
Reason: RunReasonTaskAssigned,
TaskTitle: "Implement endpoint",
HandoffContext: &HandoffPromptContext{
ParentRef: "KAN-12 Plan",
AvailableDocs: []HandoffDocPrompt{
{TaskRef: "KAN-12 Plan", Key: "spec", Title: "Architecture spec"},
{TaskRef: "KAN-12 Plan", Key: "plan", Title: "Implementation plan"},
},
},
}
out := BuildPrompt(pc)
if !strings.Contains(out, "Documents available (fetch with get_task_document_kandev)") {
t.Errorf("missing documents header:\n%s", out)
}
if !strings.Contains(out, "spec") || !strings.Contains(out, "Architecture spec") {
t.Errorf("missing spec doc:\n%s", out)
}
// The fetch instruction must reference the tool name explicitly so
// agents can't be tempted to inline document bodies in their own
// prompts.
if !strings.Contains(out, "get_task_document_kandev") {
t.Errorf("documents section must name the fetch tool:\n%s", out)
}
}
func TestBuildPrompt_RendersWorkspaceSection(t *testing.T) {
pc := &PromptContext{
Reason: RunReasonTaskAssigned,
TaskTitle: "Implement endpoint",
HandoffContext: &HandoffPromptContext{
WorkspaceMode: "inherit_parent",
WorkspaceMembers: []string{"KAN-13 Plan", "KAN-14 Spec"},
MaterializedPath: "/workspaces/.../task-KAN-12",
MaterializedKind: "single_repo",
},
}
out := BuildPrompt(pc)
if !strings.Contains(out, "Workspace:") {
t.Errorf("missing workspace header:\n%s", out)
}
if !strings.Contains(out, "mode: inherit_parent") {
t.Errorf("missing mode line:\n%s", out)
}
if !strings.Contains(out, "shared with: KAN-13 Plan, KAN-14 Spec") {
t.Errorf("missing members line:\n%s", out)
}
if !strings.Contains(out, "/workspaces/.../task-KAN-12") {
t.Errorf("missing path:\n%s", out)
}
}
func TestBuildHandoffSection_EmptyContextProducesEmptyString(t *testing.T) {
if got := buildHandoffSection(nil); got != "" {
t.Errorf("nil context should produce empty string, got %q", got)
}
if got := buildHandoffSection(&HandoffPromptContext{}); got != "" {
t.Errorf("zero context should produce empty string, got %q", got)
}
}