Merge branches 'worktree-agent-a752b94716f8d18ba' and 'worktree-agent-a253f0d23f8cafea3' into worktree-agent-a96b82d1c1cee18ca

This commit is contained in:
2026-12-03 00:27:14 +00:00
22 changed files with 1195 additions and 72 deletions
+4 -2
View File
@@ -90,9 +90,11 @@ only when asked). Stage use: `references/format.md`.
## In a Pipelines chat
A chat's agent has a `pipelines` MCP server: `show_file`, `show_image`,
`show_html` (follows the light/dark theme when it styles for dark), `show_diff` (show the
`show_html` (follows the light/dark theme when it styles for dark; its result warns about blocked scripts or remote resources), `show_diff` (show the
operator changes, e.g. before a pull request; `head`, `paths`), `show_run` (a
live run card), `schedule_followup` (come back to this chat later) and `notify`
live run card), `schedule_followup` (come back to this chat at a time, or when a
run finishes or needs the operator: `run_id` with `on`; returns an id for
`cancel_followup`) and `notify`
(every Pipelines app the operator is signed in to plus their phone; cleared
everywhere once they read it or open the chat). Pipelines already notifies when
a reply ends or the agent asks something, so `notify` is only for news mid-turn
+10 -6
View File
@@ -21,10 +21,11 @@ regenerate, or a file you rewrote.
| --- | --- | --- |
| `show_file` | `path`, `title?`, `replace?` | Any file the operator should see: images inline, other files as a preview card. Use instead of naming a path. A file up to 5 MiB is copied when shown, so the card keeps that version; a larger one stays linked and its card says "changed since shown" or "no longer exists". |
| `show_image` | `url_or_path`, `title?`, `alt?`, `replace?` | A home `image/*` file, or an `https://` URL that Pipelines downloads and keeps (public hosts only, PNG/JPEG/GIF/WebP/AVIF/BMP, at most 10 MiB, no credentials, no redirect to plain http). A failed download is an error and nothing is shown. |
| `show_html` | `html`, `title?`, `height_hint?` (120-600), `replace?` | Self-contained HTML/SVG: diagrams, charts, tables. Sandboxed: no JavaScript, no network; inline CSS/SVG, `<details>`, `:hover`. Follows the operator's light/dark theme only when it declares dark support: `@media (prefers-color-scheme: dark)`, `color-scheme` or `light-dark()`; anything else is always shown light, on white. Refused above 512 KiB. |
| `show_html` | `html`, `title?`, `height_hint?` (120-600), `replace?` | Self-contained HTML/SVG: diagrams, charts, tables. Sandboxed: no JavaScript, no network; inline CSS/SVG, `<details>`, `:hover`. Follows the operator's light/dark theme only when it declares dark support: `@media (prefers-color-scheme: dark)`, `color-scheme` or `light-dark()`; anything else is always shown light, on white. The result warns when the document has scripts or loads remote resources (both blocked) or lacks dark support; fix and `replace`. Refused above 512 KiB. |
| `show_diff` | `path?`, `base?`, `head?`, `paths?`, `committed_only?`, `title?`, `replace?` | A Git diff card when the operator asks to see the changes, or before submitting a pull request. No `base`: uncommitted work (staged, unstaged, untracked) against HEAD. `base` (e.g. `main`): everything since the merge base, which is what a PR contains, plus uncommitted work unless `committed_only`. `head` (e.g. `pipelines/run-123`): that revision instead of the work tree, against `base` or HEAD. `paths`: repository-relative files, directories or globs (`*.go`), at most 50. Pipelines runs Git; do not paste the diff. |
| `show_run` | `run_id`, `title?`, `replace?` | A live card for a run: pipeline, title, status, current stage, duration; it updates as the run progresses and opens the run when tapped. |
| `schedule_followup` | `message`, `at?` or `after_minutes?` | Queue a prompt to yourself in this chat, 1 minute to 7 days ahead (`at` is RFC 3339). It is a scheduled message from "Agent follow-up" the operator can remove; it does not hold the operator's own messages back, and is delivered when the chat is free at that time. At most 3 pending per chat. Do not wait for it in the current turn. |
| `schedule_followup` | `message`, and `at?` or `after_minutes?`, or `run_id?` with `on?` | Queue a prompt to yourself in this chat: 1 minute to 7 days ahead (`at` is RFC 3339), or when run `run_id` reaches `on`: `finished` (default; it ended) or `attention` (it waits on a human decision, or ended), delivered after 7 days at the latest with the run's state appended. A run that already meets `on` is refused (act on it now). It is a scheduled message from "Agent follow-up" the operator can remove; it does not hold the operator's own messages back, and is delivered when the chat is free. At most 3 pending per chat. The result names the follow-up id and lists the pending ones. Do not wait for it in the current turn. |
| `cancel_followup` | `id` | Remove one of this chat's undelivered follow-ups by the id `schedule_followup` returned; the result lists those still pending. |
| `notify` | `title`, `message`, `priority?` | A notification on every Pipelines app the operator is signed in to (web tabs, desktop, Android) and their phone (ntfy); a tap opens this chat. Opening the chat, or tapping or dismissing it on any device, clears it on all of them. Pipelines already notifies when the reply ends and for questions and approvals, so use it only for news mid-turn or after background work the turn does not wait for; a turn that notified sends no separate "replied" notification. 5 per minute per chat; the result says where it went, and undelivered sends report why. |
`show_diff` lists at most 300 files; a file patch over 256 KiB or a total over
@@ -43,10 +44,13 @@ authoritative record before acting.
## Questions and approvals
Claude Code questions appear as a form. The operator may pick an option, answer
in their own words, or dismiss it; a dismissal arrives as a denial saying they
will reply in the chat, so wait for that message. Question text, descriptions
and option descriptions render Markdown.
A question the agent asks appears as a form on every harness: Claude Code's
AskUserQuestion, OpenCode's question tool, and Codex's request for user input
(and MCP elicitations). The operator may pick an option, answer in their own
words, or dismiss it. On Claude Code a dismissal arrives as a denial saying
they will reply in the chat; on OpenCode, and for Codex elicitations, it cancels the question.
Either way, wait for their message. Question text, descriptions and option
descriptions render Markdown.
## Chat protocol (via `pipelines rpc -`)
+1 -1
View File
@@ -75,7 +75,7 @@ func TestHandshakeListAndCall(t *testing.T) {
t.Fatalf("tool without description or schema: %v", entry)
}
}
if strings.Join(names, ",") != "show_file,show_image,show_html,show_diff,notify,show_run,schedule_followup" {
if strings.Join(names, ",") != "show_file,show_image,show_html,show_diff,notify,show_run,schedule_followup,cancel_followup" {
t.Fatalf("tools = %v", names)
}
if list["id"] != "l" {
+29 -8
View File
@@ -10,6 +10,8 @@ const (
ToolNotify = "notify"
// ToolScheduleFollowup queues a prompt into the calling chat for later.
ToolScheduleFollowup = "schedule_followup"
// ToolCancelFollowup removes a follow-up this chat scheduled.
ToolCancelFollowup = "cancel_followup"
)
// MaxHTMLBytes bounds one show_html document. A larger one is refused, never
@@ -29,12 +31,16 @@ const (
MaxFollowupMinutes = 7 * 24 * 60
MaxPendingFollowups = 3
MaxFollowupTextBytes = 8 << 10
// A run-triggered follow-up (run_id with on) is delivered when the run
// reaches the condition, or after MaxFollowupMinutes at the latest.
FollowupOnFinished = "finished"
FollowupOnAttention = "attention"
)
// IsTool reports whether name is one of the Pipelines tools.
func IsTool(name string) bool {
switch name {
case ToolShowFile, ToolShowImage, ToolShowHTML, ToolShowDiff, ToolShowRun, ToolNotify, ToolScheduleFollowup:
case ToolShowFile, ToolShowImage, ToolShowHTML, ToolShowDiff, ToolShowRun, ToolNotify, ToolScheduleFollowup, ToolCancelFollowup:
return true
}
return false
@@ -48,7 +54,7 @@ const Instructions = "These tools act on Pipelines, the app the operator reads t
"Pipelines already notifies them when your reply ends and when you ask a question or need an approval, so do not notify for those " +
"(a notify replaces this turn's end-of-reply notification). It reaches every Pipelines app they are signed in to and their phone, " +
"and clears everywhere once they open the chat. " +
"Use show_run to follow a pipeline run live in the chat, and schedule_followup to come back to this chat later (for example to check on a run). " +
"Use show_run to follow a pipeline run live in the chat, and schedule_followup to come back to this chat later (at a time, or when a run finishes or needs the operator; cancel_followup removes one). " +
"Every show_* result names the shown item's id: pass it as replace to update that card instead of adding another. " +
"Your thinking is not shown to the operator: before asking them a question (for example with AskUserQuestion), " +
"write what you found and why you are asking as a normal message, because the question form shows only the question and its options."
@@ -182,14 +188,29 @@ func definitions() []toolDefinition {
{
Name: ToolScheduleFollowup,
Title: "Schedule a follow-up in this chat",
Description: "Queue a message to yourself in this chat, delivered as a new prompt at a later time (for example to check on a long run). " +
"The operator sees it in the chat as a scheduled message from the agent and can remove it. " +
"Give at (an RFC 3339 time) or after_minutes, between 1 minute and 7 days from now. At most 3 follow-ups can be pending per chat. " +
"It is delivered when the chat is free at that time, so do not wait for it in the current turn.",
Description: "Queue a message to yourself in this chat, delivered as a new prompt later: at a time (at, an RFC 3339 time, or after_minutes, " +
"between 1 minute and 7 days from now), or when a pipeline run reaches a state (run_id with on: finished when it ends, " +
"attention when it waits on the operator's decision or ends, whichever is first; delivered after 7 days at the latest). " +
"The operator sees it in the chat as a scheduled message from the agent and can remove it. At most 3 follow-ups can be pending per chat. " +
"It is delivered when the chat is free, so do not wait for it in the current turn. " +
"The result names the follow-up's id (for cancel_followup) and lists the chat's pending follow-ups.",
InputSchema: objectSchema([]string{"message"}, map[string]any{
"message": stringProperty("What the follow-up prompt should say: enough for you to know what to do then."),
"at": stringProperty("When to deliver it, as an RFC 3339 time such as 2026-05-01T09:30:00Z. Give this or after_minutes."),
"after_minutes": map[string]any{"type": "integer", "description": "Minutes from now to deliver it (1-10080). Give this or at."},
"at": stringProperty("When to deliver it, as an RFC 3339 time such as 2026-05-01T09:30:00Z. Give this, after_minutes, or run_id."),
"after_minutes": map[string]any{"type": "integer", "description": "Minutes from now to deliver it (1-10080). Give this, at, or run_id."},
"run_id": map[string]any{"type": "integer", "description": "Deliver it when this pipeline run reaches on, instead of at a time."},
"on": map[string]any{"type": "string", "enum": []string{FollowupOnFinished, FollowupOnAttention},
"description": "With run_id: finished (the run ended: succeeded, failed, canceled or interrupted) or attention (it waits on a human decision, or ended). Default finished."},
}),
Annotations: map[string]any{"readOnlyHint": false, "destructiveHint": false, "openWorldHint": false},
},
{
Name: ToolCancelFollowup,
Title: "Cancel a follow-up in this chat",
Description: "Remove a follow-up this chat scheduled with schedule_followup and that has not been delivered yet. " +
"The result lists the follow-ups still pending.",
InputSchema: objectSchema([]string{"id"}, map[string]any{
"id": stringProperty("The follow-up's id, from the schedule_followup result."),
}),
Annotations: map[string]any{"readOnlyHint": false, "destructiveHint": false, "openWorldHint": false},
},
+4
View File
@@ -27,6 +27,10 @@ func TestValidateArgumentsRefusesUnknownAndMistypedFields(t *testing.T) {
{ToolNotify, `{"title":"t","message":"m","priority":"urgent"}`, "priority must be one of low, default, high"},
{ToolScheduleFollowup, `{"message":"m","after_minutes":5}`, ""},
{ToolScheduleFollowup, `{"message":"m","in_minutes":5,"delay":1}`, `unknown arguments "delay", "in_minutes"`},
{ToolScheduleFollowup, `{"message":"m","run_id":7,"on":"attention"}`, ""},
{ToolScheduleFollowup, `{"message":"m","run_id":7,"on":"done"}`, "on must be one of finished, attention"},
{ToolCancelFollowup, `{"id":"followup-1"}`, ""},
{ToolCancelFollowup, `{}`, "id is required"},
}
for _, c := range cases {
err := ValidateArguments(c.tool, json.RawMessage(c.args))
+3
View File
@@ -95,6 +95,9 @@ type chatHub struct {
// shownRefresh brings listed items up to date (file states, followed
// runs) before a subscribe reply carries them; nil leaves them as stored.
shownRefresh func(ctx context.Context, sessionID string, items []protocol.ChatShownItem) []protocol.ChatShownItem
// queueResumed runs once the durable queues are restored after a restart
// (the chat tools re-arm run-triggered follow-ups); nil does nothing.
queueResumed func(ctx context.Context)
// autoSwitch records the usage-limit refusals the server already
// continued on another Claude account (chat_auto_switch.go).
autoSwitch chatAutoSwitchState
+347 -23
View File
@@ -5,7 +5,10 @@ import (
"crypto/rand"
"encoding/hex"
"fmt"
"log"
"strconv"
"strings"
"sync"
"time"
"git.a-wan.net/alan/pipelines/internal/chattools"
@@ -16,12 +19,33 @@ import (
// with a send_at, under the sender label chatFollowupClient. The operator sees
// it as a scheduled message from the agent and can remove it like any queued
// prompt; until it is due it does not hold the operator's prompts back
// (chatQueueHead).
// (chatQueueHead). cancel_followup removes one the agent no longer needs.
//
// A run-triggered follow-up (run_id with on) is queued the same way with the
// longest allowed send_at as its deadline, and its operation id names the run
// and condition (chatRunFollowupPrefix). The run event hub tells the service
// when a run changes; once the run meets the condition the prompt is requeued
// as due now, with the run's state appended. The queue row is the durable
// record: after a restart resumeRunFollowups re-arms the watches from it.
// chatFollowupClient is the sender label of an agent's follow-up prompt.
const chatFollowupClient = "Agent follow-up"
func (s *chatToolService) runScheduleFollowup(ctx context.Context, sessionID, message, at string, afterMinutes *int64) chattools.Result {
// chatRunFollowupPrefix starts a run-triggered follow-up's operation id:
// followup-run-<run id>-<on>-<random>.
const chatRunFollowupPrefix = chatFollowupPrefix + "run-"
// runFollowupWatches maps a run to the follow-ups (operation id to session)
// waiting on it. mu also serialises every count-then-queue, cancel and trigger
// of the follow-ups, so concurrent calls cannot exceed the pending bound or
// deliver one twice.
type runFollowupWatches struct {
mu sync.Mutex
items map[int64]map[string]string
timers map[int64]*time.Timer
}
func (s *chatToolService) runScheduleFollowup(ctx context.Context, sessionID, message, at string, afterMinutes, runID *int64, on string) chattools.Result {
fail := func(format string, args ...any) chattools.Result {
return chattools.Result{Text: "Nothing was scheduled: " + fmt.Sprintf(format, args...), IsError: true}
}
@@ -35,7 +59,34 @@ func (s *chatToolService) runScheduleFollowup(ctx context.Context, sessionID, me
at = strings.TrimSpace(at)
now := s.now()
var sendAt time.Time
var run *protocol.RunSummary
switch {
case runID != nil && (at != "" || afterMinutes != nil):
return fail("give run_id or a time (at or after_minutes), not both.")
case runID == nil && on != "":
return fail("on needs run_id.")
case runID != nil:
if on == "" {
on = chattools.FollowupOnFinished
}
if *runID <= 0 {
return fail("run_id must be a positive run number.")
}
if s.runs == nil {
return fail("this server does not record runs.")
}
summary, found, err := s.runs.RunSummaryByID(ctx, *runID)
if err != nil {
return fail("%v", err)
}
if !found {
return fail("there is no run %d.", *runID)
}
if runFollowupDue(summary, on) {
return fail("run %d is already %s; act on it now (pipelines inspect %d).", *runID, runStateText(summary), *runID)
}
run = &summary
sendAt = now.Add(time.Duration(chattools.MaxFollowupMinutes) * time.Minute)
case at != "" && afterMinutes != nil:
return fail("give either at or after_minutes, not both.")
case afterMinutes != nil:
@@ -57,34 +108,315 @@ func (s *chatToolService) runScheduleFollowup(ctx context.Context, sessionID, me
}
sendAt = parsed
default:
return fail("give at (an RFC 3339 time) or after_minutes.")
return fail("give at (an RFC 3339 time), after_minutes, or run_id.")
}
if s.hub == nil || s.broker == nil {
return fail("follow-ups are not available on this server.")
}
pending := 0
for _, prompt := range s.hub.queueFrame(sessionID).Prompts {
if strings.HasPrefix(prompt.OperationID, chatFollowupPrefix) {
pending++
}
}
if pending >= chattools.MaxPendingFollowups {
return fail("this chat already has %d follow-ups pending (the limit is %d); the operator can remove one, or wait for one to be delivered.", pending, chattools.MaxPendingFollowups)
w := &s.followups
w.mu.Lock()
pending := s.pendingFollowups(sessionID)
if len(pending) >= chattools.MaxPendingFollowups {
w.mu.Unlock()
return fail("this chat already has %d follow-ups pending (the limit is %d); cancel one with cancel_followup, or wait for one to be delivered.%s", len(pending), chattools.MaxPendingFollowups, followupListText(pending, now))
}
var token [8]byte
_, _ = rand.Read(token[:])
operationID := chatFollowupPrefix + hex.EncodeToString(token[:])
text := fmt.Sprintf("[Follow-up you scheduled at %s with schedule_followup] %s", now.UTC().Format(time.RFC3339), message)
if run != nil {
operationID = fmt.Sprintf("%s%d-%s-%s", chatRunFollowupPrefix, run.ID, on, hex.EncodeToString(token[:]))
text = fmt.Sprintf("[Follow-up you scheduled at %s with schedule_followup, for when run %d %s; delivered at %s at the latest] %s",
now.UTC().Format(time.RFC3339), run.ID, runFollowupCondition(on), sendAt.UTC().Format(time.RFC3339), message)
}
if err := s.hub.queueFollowup(ctx, s.broker, sessionID, operationID, text, sendAt); err != nil {
w.mu.Unlock()
return fail("%v", err)
}
return chattools.Result{Text: fmt.Sprintf("Scheduled: Pipelines will send this chat your follow-up at %s (in %s), when the chat is free; the operator sees it queued and can remove it. Do not wait for it now.",
sendAt.UTC().Format(time.RFC3339), sendAt.Sub(now).Round(time.Minute))}
if run != nil {
s.watchRunFollowupLocked(run.ID, sessionID, operationID)
}
pending = s.pendingFollowups(sessionID)
w.mu.Unlock()
if run != nil {
// The run may have changed between the check above and the watch:
// look again once, as an event would.
s.scheduleRunFollowupCheck(run.ID)
return chattools.Result{Text: fmt.Sprintf("Scheduled follow-up %s: Pipelines will send this chat your follow-up when run %d %s (it is %s now), or at %s at the latest, when the chat is free; the operator sees it queued and can remove it. Do not wait for it now.%s",
operationID, run.ID, runFollowupCondition(on), runStateText(*run), sendAt.UTC().Format(time.RFC3339), followupListText(pending, now))}
}
return chattools.Result{Text: fmt.Sprintf("Scheduled follow-up %s: Pipelines will send this chat your follow-up at %s (in %s), when the chat is free; the operator sees it queued and can remove it. Do not wait for it now.%s",
operationID, sendAt.UTC().Format(time.RFC3339), sendAt.Sub(now).Round(time.Minute), followupListText(pending, now))}
}
// runCancelFollowup removes one of this chat's pending follow-ups.
func (s *chatToolService) runCancelFollowup(ctx context.Context, sessionID, id string) chattools.Result {
id = strings.TrimSpace(id)
if s.hub == nil {
return chattools.Result{Text: "Nothing was canceled: follow-ups are not available on this server.", IsError: true}
}
w := &s.followups
w.mu.Lock()
defer w.mu.Unlock()
if !strings.HasPrefix(id, chatFollowupPrefix) {
return chattools.Result{Text: fmt.Sprintf("Nothing was canceled: %q is not a follow-up id (they start with %s).%s", id, chatFollowupPrefix, followupListText(s.pendingFollowups(sessionID), s.now())), IsError: true}
}
found, err := s.hub.unqueue(ctx, sessionID, id)
if err != nil {
return chattools.Result{Text: "Nothing was canceled: " + err.Error(), IsError: true}
}
if runID, _, ok := parseRunFollowupID(id); ok {
s.unwatchRunFollowupLocked(runID, id)
}
pending := s.pendingFollowups(sessionID)
if !found {
return chattools.Result{Text: fmt.Sprintf("Nothing was canceled: this chat has no pending follow-up %s (it may have been delivered or removed already).%s", id, followupListText(pending, s.now())), IsError: true}
}
return chattools.Result{Text: fmt.Sprintf("Canceled follow-up %s.%s", id, followupListText(pending, s.now()))}
}
// pendingFollowups are the chat's follow-ups still waiting in its queue.
func (s *chatToolService) pendingFollowups(sessionID string) []protocol.ChatQueuedPrompt {
var pending []protocol.ChatQueuedPrompt
for _, prompt := range s.hub.queueFrame(sessionID).Prompts {
if strings.HasPrefix(prompt.OperationID, chatFollowupPrefix) {
pending = append(pending, prompt)
}
}
return pending
}
// followupListText lists pending follow-ups for a tool result, or says there
// are none.
func followupListText(pending []protocol.ChatQueuedPrompt, now time.Time) string {
if len(pending) == 0 {
return " No follow-ups are pending in this chat."
}
parts := make([]string, 0, len(pending))
for _, prompt := range pending {
when := "when the chat is free"
if runID, on, ok := parseRunFollowupID(prompt.OperationID); ok && prompt.SendAt > now.UnixMilli() {
when = fmt.Sprintf("when run %d %s", runID, runFollowupCondition(on))
} else if prompt.SendAt > now.UnixMilli() {
when = "at " + time.UnixMilli(prompt.SendAt).UTC().Format(time.RFC3339)
}
parts = append(parts, prompt.OperationID+" ("+when+")")
}
return fmt.Sprintf(" Pending follow-ups (%d of %d): %s.", len(pending), chattools.MaxPendingFollowups, strings.Join(parts, "; "))
}
// parseRunFollowupID reads the run and condition from a run-triggered
// follow-up's operation id.
func parseRunFollowupID(operationID string) (int64, string, bool) {
rest, ok := strings.CutPrefix(operationID, chatRunFollowupPrefix)
if !ok {
return 0, "", false
}
fields := strings.SplitN(rest, "-", 3)
if len(fields) != 3 {
return 0, "", false
}
runID, err := strconv.ParseInt(fields[0], 10, 64)
if err != nil || runID <= 0 || (fields[1] != chattools.FollowupOnFinished && fields[1] != chattools.FollowupOnAttention) {
return 0, "", false
}
return runID, fields[1], true
}
func runFollowupCondition(on string) string {
if on == chattools.FollowupOnAttention {
return "needs the operator or finishes"
}
return "finishes"
}
// runFollowupDue reports whether a run meets a follow-up's condition: it ended,
// or (for attention) it waits on a human decision.
func runFollowupDue(summary protocol.RunSummary, on string) bool {
if shownRunTerminal(summary.Status) {
return true
}
return on == chattools.FollowupOnAttention && summary.Status == protocol.RunStatusWaiting && summary.ExportPendingSequence == 0
}
// runStateText describes a run's state in one phrase.
func runStateText(summary protocol.RunSummary) string {
text := summary.Status
if outcome := strings.TrimSpace(summary.Outcome); outcome != "" {
text += " (" + outcome + ")"
}
if stage := strings.TrimSpace(summary.CurrentStage); stage != "" {
if summary.Status == protocol.RunStatusWaiting {
text += " waiting at stage " + stage
} else {
text += " at stage " + stage
}
}
return text
}
func (s *chatToolService) watchRunFollowupLocked(runID int64, sessionID, operationID string) {
w := &s.followups
if w.items == nil {
w.items = map[int64]map[string]string{}
}
if w.items[runID] == nil {
w.items[runID] = map[string]string{}
}
w.items[runID][operationID] = sessionID
}
func (s *chatToolService) unwatchRunFollowupLocked(runID int64, operationID string) {
w := &s.followups
delete(w.items[runID], operationID)
if len(w.items[runID]) == 0 {
delete(w.items, runID)
}
}
// observeRunFollowups is the run event hub's observer for run-triggered
// follow-ups: a watched run's change is checked once its burst settles.
func (s *chatToolService) observeRunFollowups(frame protocol.RunEventFrame) {
s.followups.mu.Lock()
watched := len(s.followups.items[frame.RunID]) > 0
s.followups.mu.Unlock()
if watched {
s.scheduleRunFollowupCheck(frame.RunID)
}
}
// scheduleRunFollowupCheck checks runID's follow-ups after the coalescing
// delay, at most once at a time.
func (s *chatToolService) scheduleRunFollowupCheck(runID int64) {
w := &s.followups
w.mu.Lock()
defer w.mu.Unlock()
if w.timers == nil {
w.timers = map[int64]*time.Timer{}
}
if w.timers[runID] != nil {
return
}
w.timers[runID] = time.AfterFunc(shownRunRefreshDelay, func() {
w.mu.Lock()
delete(w.timers, runID)
w.mu.Unlock()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
s.checkRunFollowups(ctx, runID)
})
}
// checkRunFollowups delivers runID's follow-ups whose condition the run now
// meets: each is requeued as due now with the run's state appended. One that
// is no longer queued (delivered at its deadline, or removed) is forgotten.
func (s *chatToolService) checkRunFollowups(ctx context.Context, runID int64) {
if s.runs == nil || s.hub == nil {
return
}
summary, found, err := s.runs.RunSummaryByID(ctx, runID)
if err != nil {
log.Printf("chat follow-ups run=%d: %v", runID, err)
return
}
w := &s.followups
w.mu.Lock()
defer w.mu.Unlock()
for operationID, sessionID := range w.items[runID] {
_, on, ok := parseRunFollowupID(operationID)
if !ok {
s.unwatchRunFollowupLocked(runID, operationID)
continue
}
state := ""
switch {
case !found:
state = fmt.Sprintf("run %d no longer exists", runID)
case runFollowupDue(summary, on):
state = fmt.Sprintf("run %d is now %s", runID, runStateText(summary))
default:
continue
}
s.unwatchRunFollowupLocked(runID, operationID)
var text string
for _, prompt := range s.hub.queueFrame(sessionID).Prompts {
if prompt.OperationID == operationID {
text = prompt.Text
}
}
if text == "" {
continue
}
removed, err := s.hub.unqueue(ctx, sessionID, operationID)
if err != nil || !removed {
if err != nil {
log.Printf("chat follow-ups session=%s run=%d: %v", sessionID, runID, err)
}
continue
}
text += "\n\n[Pipelines: " + state + "; read it with pipelines inspect " + strconv.FormatInt(runID, 10) + ".]"
// The chat already shows this follow-up from when it was scheduled, so
// the requeue is not announced as a second user message.
if _, err := s.hub.admitFollowup(ctx, s.broker, sessionID, operationID, text, time.Time{}); err != nil {
log.Printf("chat follow-ups session=%s run=%d: requeue: %v", sessionID, runID, err)
}
}
}
// resumeRunFollowups re-arms the run-triggered follow-ups the restored queues
// hold, and delivers those whose run already meets the condition (it may have
// finished while the server was down).
func (s *chatToolService) resumeRunFollowups(ctx context.Context) {
if s.hub == nil {
return
}
s.hub.mu.Lock()
type waiting struct {
runID int64
sessionID, opID string
}
var found []waiting
for sessionID, room := range s.hub.rooms {
for _, p := range room.queue {
if runID, _, ok := parseRunFollowupID(p.operationID); ok && p.sendAt.After(s.hub.clock()) {
found = append(found, waiting{runID, sessionID, p.operationID})
}
}
}
s.hub.mu.Unlock()
runs := map[int64]bool{}
s.followups.mu.Lock()
for _, f := range found {
s.watchRunFollowupLocked(f.runID, f.sessionID, f.opID)
runs[f.runID] = true
}
s.followups.mu.Unlock()
for runID := range runs {
s.checkRunFollowups(ctx, runID)
}
}
// queueFollowup queues an agent's follow-up prompt for sendAt: durably, under
// the follow-up sender label, shown to every attached client as scheduled.
func (h *chatHub) queueFollowup(ctx context.Context, broker chatBroker, sessionID, operationID, text string, sendAt time.Time) error {
messageID, err := h.admitFollowup(ctx, broker, sessionID, operationID, text, sendAt)
if err != nil {
return err
}
h.broadcastUser(protocol.ChatEventFrame{
SessionID: sessionID,
MessageID: messageID,
Kind: protocol.ChatEventUser,
Part: &protocol.ChatPart{Type: protocol.ChatPartText, ID: "usr", Text: text},
Client: chatFollowupClient,
OperationID: operationID,
}, "")
return nil
}
// admitFollowup queues a follow-up prompt without announcing it and returns
// its message id.
func (h *chatHub) admitFollowup(ctx context.Context, broker chatBroker, sessionID, operationID, text string, sendAt time.Time) (string, error) {
p := &chatQueuedPrompt{
text: text,
operationID: operationID,
@@ -97,15 +429,7 @@ func (h *chatHub) queueFollowup(ctx context.Context, broker chatBroker, sessionI
admission, err := h.admitPrompt(ctx, sessionID, broker, p)
if admission == chatAdmitRefused {
h.forgetOp(sessionID, operationID)
return err
return "", err
}
h.broadcastUser(protocol.ChatEventFrame{
SessionID: sessionID,
MessageID: p.messageID,
Kind: protocol.ChatEventUser,
Part: &protocol.ChatPart{Type: protocol.ChatPartText, ID: "usr", Text: text},
Client: chatFollowupClient,
OperationID: operationID,
}, "")
return nil
return p.messageID, nil
}
@@ -0,0 +1,243 @@
package server
import (
"context"
"strings"
"sync"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/chattools"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// lockedRuns is a run store a test can change while the service reads it.
type lockedRuns struct {
mu sync.Mutex
runs map[int64]protocol.RunSummary
}
func (l *lockedRuns) RunSummaryByID(_ context.Context, id int64) (protocol.RunSummary, bool, error) {
l.mu.Lock()
defer l.mu.Unlock()
run, ok := l.runs[id]
return run, ok, nil
}
func (l *lockedRuns) set(run protocol.RunSummary) {
l.mu.Lock()
defer l.mu.Unlock()
l.runs[run.ID] = run
}
func followupID(t *testing.T, r chattools.Result) string {
t.Helper()
_, rest, ok := strings.Cut(r.Text, "Scheduled follow-up ")
if r.IsError || !ok {
t.Fatalf("the result names the follow-up id: %v", r)
}
return strings.TrimSuffix(strings.Fields(rest)[0], ":")
}
func newFollowupFixture(t *testing.T) (*chatToolFixture, *lockedRuns) {
t.Helper()
f := newChatToolFixture(t)
runs := &lockedRuns{runs: map[int64]protocol.RunSummary{}}
f.service.runs = runs
f.service.broker = newChannelChat()
return f, runs
}
// awaitReleased waits until sessionID's follow-up was delivered to the broker
// with want in its text, or requeued as due now with it.
func awaitReleased(t *testing.T, f *chatToolFixture, sessionID, want string) {
t.Helper()
broker := f.service.broker.(*channelChat)
deadline := time.Now().Add(5 * time.Second)
for {
for _, text := range broker.promptTexts() {
if strings.Contains(text, want) {
return
}
}
for _, p := range f.service.pendingFollowups(sessionID) {
if p.SendAt == 0 && strings.Contains(p.Text, want) {
return
}
}
if time.Now().After(deadline) {
t.Fatalf("the follow-up was not released with %q: prompts %v, queue %+v", want, broker.promptTexts(), f.service.pendingFollowups(sessionID))
}
time.Sleep(10 * time.Millisecond)
}
}
// The schedule result names the id and lists what is pending; cancel_followup
// removes exactly that follow-up.
func TestScheduleFollowupReturnsTheIDAndCancelRemovesIt(t *testing.T) {
f, _ := newFollowupFixture(t)
token := f.token(t, chatToolSessionScope+"ses_c")
first := f.call(token, "schedule_followup", `{"message":"one","after_minutes":30}`)
id := followupID(t, first)
if !strings.HasPrefix(id, chatFollowupPrefix) || !strings.Contains(first.Text, "Pending follow-ups (1 of 3): "+id+" (at ") {
t.Fatalf("schedule result = %v", first)
}
second := followupID(t, f.call(token, "schedule_followup", `{"message":"two","after_minutes":60}`))
r := f.call(token, "cancel_followup", `{"id":"`+id+`"}`)
if r.IsError || !strings.Contains(r.Text, "Canceled follow-up "+id) || !strings.Contains(r.Text, "(1 of 3): "+second) {
t.Fatalf("cancel = %v", r)
}
if r := f.call(token, "cancel_followup", `{"id":"`+id+`"}`); !r.IsError || !strings.Contains(r.Text, "no pending follow-up") {
t.Fatalf("a second cancel is refused: %v", r)
}
if r := f.call(token, "cancel_followup", `{"id":"op-1"}`); !r.IsError || !strings.Contains(r.Text, "not a follow-up id") {
t.Fatalf("an operator prompt cannot be canceled: %v", r)
}
other := f.token(t, chatToolSessionScope+"ses_other")
if r := f.call(other, "cancel_followup", `{"id":"`+second+`"}`); !r.IsError {
t.Fatalf("another chat cannot cancel this chat's follow-up: %v", r)
}
if pending := f.service.pendingFollowups("ses_c"); len(pending) != 1 || pending[0].OperationID != second {
t.Fatalf("pending = %+v", pending)
}
}
// Concurrent schedules never exceed the pending bound.
func TestScheduleFollowupBoundHoldsUnderConcurrency(t *testing.T) {
f, _ := newFollowupFixture(t)
token := f.token(t, chatToolSessionScope+"ses_k")
var wg sync.WaitGroup
var mu sync.Mutex
accepted := 0
for i := 0; i < 12; i++ {
wg.Add(1)
go func() {
defer wg.Done()
if r := f.call(token, "schedule_followup", `{"message":"m","after_minutes":30}`); !r.IsError {
mu.Lock()
accepted++
mu.Unlock()
}
}()
}
wg.Wait()
if pending := len(f.service.pendingFollowups("ses_k")); accepted != chattools.MaxPendingFollowups || pending != chattools.MaxPendingFollowups {
t.Fatalf("accepted %d, pending %d", accepted, pending)
}
}
func TestRunFollowupBounds(t *testing.T) {
f, runs := newFollowupFixture(t)
runs.set(protocol.RunSummary{ID: 5, Status: "succeeded", Outcome: "done"})
runs.set(protocol.RunSummary{ID: 6, Status: protocol.RunStatusWaiting, CurrentStage: "decide"})
token := f.token(t, chatToolSessionScope+"ses_bounds")
for _, tc := range []struct{ args, want string }{
{`{"message":"m","run_id":99}`, "there is no run 99"},
{`{"message":"m","run_id":0}`, "positive run number"},
{`{"message":"m","run_id":5}`, "run 5 is already succeeded (done)"},
{`{"message":"m","run_id":6,"on":"attention"}`, "run 6 is already waiting waiting at stage decide"},
{`{"message":"m","run_id":6,"after_minutes":5}`, "not both"},
{`{"message":"m","on":"finished","after_minutes":5}`, "on needs run_id"},
} {
if r := f.call(token, "schedule_followup", tc.args); !r.IsError || !strings.Contains(r.Text, tc.want) {
t.Errorf("%s: got %v, want %q", tc.args, r, tc.want)
}
}
// A run waiting on a person has not finished: on finished still waits.
if r := f.call(token, "schedule_followup", `{"message":"m","run_id":6}`); r.IsError || !strings.Contains(r.Text, "when run 6 finishes") {
t.Fatalf("finished follow-up on a waiting run = %v", r)
}
}
// A run-triggered follow-up stays pending while the run works and is
// released, with the run's state, once the run needs the operator.
func TestRunFollowupIsDeliveredWhenTheRunNeedsAttention(t *testing.T) {
previous := shownRunRefreshDelay
shownRunRefreshDelay = 10 * time.Millisecond
t.Cleanup(func() { shownRunRefreshDelay = previous })
f, runs := newFollowupFixture(t)
runs.set(protocol.RunSummary{ID: 7, Status: "running", CurrentStage: "implement"})
token := f.token(t, chatToolSessionScope+"ses_t")
r := f.call(token, "schedule_followup", `{"message":"check run 7","run_id":7,"on":"attention"}`)
id := followupID(t, r)
if !strings.HasPrefix(id, chatRunFollowupPrefix+"7-attention-") || !strings.Contains(r.Text, "when run 7 needs the operator or finishes") {
t.Fatalf("schedule = %v", r)
}
pending := f.service.pendingFollowups("ses_t")
if len(pending) != 1 || pending[0].SendAt <= time.Now().Add(6*24*time.Hour).UnixMilli() {
t.Fatalf("the follow-up waits with a 7-day deadline: %+v", pending)
}
f.service.observeRun(protocol.RunEventFrame{RunID: 7})
time.Sleep(50 * time.Millisecond)
if p := f.service.pendingFollowups("ses_t"); len(p) != 1 || p[0].SendAt == 0 {
t.Fatalf("a still-running run keeps the follow-up waiting: %+v", p)
}
runs.set(protocol.RunSummary{ID: 7, Status: protocol.RunStatusWaiting, CurrentStage: "decide"})
f.service.observeRun(protocol.RunEventFrame{RunID: 7})
awaitReleased(t, f, "ses_t", "run 7 is now waiting waiting at stage decide")
f.service.followups.mu.Lock()
watched := len(f.service.followups.items[7])
f.service.followups.mu.Unlock()
if watched != 0 {
t.Fatal("a released follow-up is no longer watched")
}
}
// After a restart the restored queue re-arms the watch, and a run that
// finished meanwhile releases its follow-up at once.
func TestRunFollowupsResumeAfterRestart(t *testing.T) {
f, runs := newFollowupFixture(t)
runs.set(protocol.RunSummary{ID: 8, Status: "running"})
token := f.token(t, chatToolSessionScope+"ses_r")
followupID(t, f.call(token, "schedule_followup", `{"message":"after restart","run_id":8}`))
// Forget the in-memory watch, as a restarted server would have.
f.service.followups.mu.Lock()
f.service.followups.items = nil
f.service.followups.mu.Unlock()
runs.set(protocol.RunSummary{ID: 8, Status: "failed", Outcome: "error", CurrentStage: "review"})
f.service.resumeRunFollowups(context.Background())
awaitReleased(t, f, "ses_r", "run 8 is now failed (error) at stage review")
}
func TestShowHTMLWarnsAboutBlockedResourcesAndLightOnlyPages(t *testing.T) {
for _, tc := range []struct {
html string
want []string
none bool
}{
{html: `<style>@media (prefers-color-scheme: dark){body{color:#eee}}</style><p>ok <a href="https://example.com">link</a></p>`, none: true},
{html: `<script src="https://cdn.example.com/chart.js"></script><style>:root{color-scheme:light dark}</style>`, want: []string{"JavaScript", "1 remote resource(s) (such as https://cdn.example.com/chart.js)"}},
{html: `<link rel="stylesheet" href="//fonts.example.com/a.css"><div style="background:url('https://x.example/b.png')"></div>`, want: []string{"2 remote resource(s)", "always shown light"}},
{html: `<button onclick="go()">x</button><svg style="color:light-dark(#000,#fff)"></svg>`, want: []string{"JavaScript"}},
} {
warnings := strings.Join(shownHTMLWarnings(tc.html), " ")
if tc.none && warnings != "" {
t.Errorf("%s: unexpected warnings %q", tc.html, warnings)
}
for _, want := range tc.want {
if !strings.Contains(warnings, want) {
t.Errorf("%s: warnings %q lack %q", tc.html, warnings, want)
}
}
}
f := newChatToolFixture(t)
token := f.token(t, chatToolSessionScope+"ses_h")
if r := f.call(token, "show_html", `{"html":"<script>x()</script><p>hi</p>"}`); r.IsError || !strings.Contains(r.Text, "Warning: it contains JavaScript") || !strings.Contains(r.Text, "always shown light") {
t.Fatalf("show_html result = %v", r)
}
}
func TestAmbiguousCallAdviceFitsTheTool(t *testing.T) {
for tool, want := range map[string]string{
chattools.ToolShowHTML: "different title",
chattools.ToolShowRun: "different title",
chattools.ToolNotify: "message wording",
chattools.ToolScheduleFollowup: "message wording",
chattools.ToolCancelFollowup: "in a moment",
} {
if got := ambiguousCallAdvice(tool); !strings.Contains(got, want) {
t.Errorf("%s: %q lacks %q", tool, got, want)
}
}
}
+56
View File
@@ -0,0 +1,56 @@
package server
import (
"fmt"
"regexp"
"strings"
)
// show_html renders in a sandbox with no scripts and no network, and follows
// the dark theme only when the document declares dark support (the same test
// as the app's artifactHtmlSupportsDark). shownHTMLWarnings tells the model
// when its document relies on what the sandbox blocks, or will stay light, so
// it can fix the view rather than believe it was shown as written.
var (
shownHTMLScript = regexp.MustCompile(`(?i)<script\b`)
shownHTMLHandler = regexp.MustCompile(`(?i)<[a-z][^>]*\son[a-z]+\s*=`)
shownHTMLDarkAware = regexp.MustCompile(`(?i)prefers-color-scheme|color-scheme|light-dark\(`)
// A remote reference: an attribute or CSS url()/@import naming an
// http(s) or protocol-relative address.
shownHTMLRemote = regexp.MustCompile(`(?i)(?:\b(?:src|href|srcset|poster|data)\s*=\s*["']?|url\(\s*["']?|@import\s+["'])((?:https?:)?//[^"')\s>]+)`)
)
// shownHTMLWarnings lists what in html will not work as written, or nil.
func shownHTMLWarnings(html string) []string {
var warnings []string
if shownHTMLScript.MatchString(html) || shownHTMLHandler.MatchString(html) {
warnings = append(warnings, "it contains JavaScript (<script> or on* handlers), which does not run here; use CSS, <details> and inline SVG instead.")
}
var remote []string
seen := map[string]bool{}
lower := strings.ToLower(html)
for _, match := range shownHTMLRemote.FindAllStringSubmatchIndex(html, -1) {
address := html[match[2]:match[3]]
// A link to another page is fine: only resources the page loads are
// blocked. An <a href> is the common case.
if tag := strings.LastIndex(lower[:match[0]], "<"); tag >= 0 && (strings.HasPrefix(lower[tag:], "<a ") || strings.HasPrefix(lower[tag:], "<a\n")) {
continue
}
if !seen[address] {
seen[address] = true
remote = append(remote, address)
}
}
if len(remote) > 0 {
example := remote[0]
if len(example) > 120 {
example = example[:120] + "…"
}
warnings = append(warnings, fmt.Sprintf("it loads %d remote resource(s) (such as %s), which the sandbox blocks: inline styles, fonts and images (data: URLs or inline SVG).", len(remote), example))
}
if !shownHTMLDarkAware.MatchString(html) {
warnings = append(warnings, "it does not declare dark support, so it is always shown light, on white, even in a dark theme; add @media (prefers-color-scheme: dark) styles, a color-scheme declaration or light-dark() colors.")
}
return warnings
}
+16 -2
View File
@@ -83,7 +83,11 @@ func (s *chatToolService) run(ctx context.Context, sessionID, tool, id string, a
return fail("Nothing was shown: html is not valid UTF-8.")
}
item := protocol.ChatShownItem{Kind: protocol.ChatShownHTML, Title: boundedLine(in.Title, 200), HTML: in.HTML, HTMLBytes: len(in.HTML), HeightHint: clampHeightHint(in.HeightHint)}
return &item, chattools.Result{Text: fmt.Sprintf("Shown in the operator's Pipelines chat (%s, sandboxed: scripts and network are disabled; it follows the operator's light or dark theme only if it styles itself for dark mode).", humanBytes(int64(len(in.HTML))))}
text := fmt.Sprintf("Shown in the operator's Pipelines chat (%s, sandboxed: scripts and network are disabled; it follows the operator's light or dark theme only if it styles itself for dark mode).", humanBytes(int64(len(in.HTML))))
if warnings := shownHTMLWarnings(in.HTML); len(warnings) > 0 {
text += " Warning: " + strings.Join(warnings, " ")
}
return &item, chattools.Result{Text: text}
case chattools.ToolShowDiff:
var in struct {
Path string `json:"path"`
@@ -111,11 +115,21 @@ func (s *chatToolService) run(ctx context.Context, sessionID, tool, id string, a
Message string `json:"message"`
At string `json:"at"`
AfterMinutes *int64 `json:"after_minutes"`
RunID *int64 `json:"run_id"`
On string `json:"on"`
}
if err := decode(&in); err != nil {
return fail("Nothing was scheduled: %v", err)
}
return nil, s.runScheduleFollowup(ctx, sessionID, in.Message, in.At, in.AfterMinutes)
return nil, s.runScheduleFollowup(ctx, sessionID, in.Message, in.At, in.AfterMinutes, in.RunID, in.On)
case chattools.ToolCancelFollowup:
var in struct {
ID string `json:"id"`
}
if err := decode(&in); err != nil {
return fail("Nothing was canceled: %v", err)
}
return nil, s.runCancelFollowup(ctx, sessionID, in.ID)
case chattools.ToolNotify:
var in struct {
Title string `json:"title"`
+1
View File
@@ -95,6 +95,7 @@ func (s *chatToolService) watchRun(runID int64, sessionID, itemID string) {
// observeRun is the run event hub's observer: a followed run's change is
// reread once its burst of events settles.
func (s *chatToolService) observeRun(frame protocol.RunEventFrame) {
s.observeRunFollowups(frame)
w := &s.watch
w.mu.Lock()
defer w.mu.Unlock()
+19 -1
View File
@@ -56,6 +56,9 @@ type chatToolService struct {
// fetch is how web images are downloaded (tests replace its guard).
fetch shownImageFetcher
watch runWatches
// followups serialises follow-up scheduling and follows the runs that
// run-triggered follow-ups wait on.
followups runFollowupWatches
}
func newChatToolService(tokens chatToolTokenStore, shown chatShownStore, hub *chatHub, registry operatorRegistry) *chatToolService {
@@ -192,7 +195,7 @@ func (s *chatToolService) session(ctx context.Context, token, tool string, argum
if _, ok := strings.CutPrefix(scope, chatToolInstanceScope); ok && s.hub != nil {
id, ambiguous := s.hub.awaitToolCallSession(ctx, tool, arguments, chatToolCorrelationWait)
if ambiguous {
return "", "Pipelines could not tell which chat made this call (another chat made an identical one); retry with a different title."
return "", "Pipelines could not tell which chat made this call (another chat made an identical one); " + ambiguousCallAdvice(tool)
}
if id == "" {
return "", "Pipelines could not match this call to a chat it is showing; the tools work only in chats opened through Pipelines."
@@ -202,6 +205,21 @@ func (s *chatToolService) session(ctx context.Context, token, tool string, argum
return "", "This chat is not ready for Pipelines tools yet."
}
// ambiguousCallAdvice says how to make a call distinguishable from another
// chat's identical one: change an argument the tool has and that does not alter
// what it does.
func ambiguousCallAdvice(tool string) string {
switch tool {
case chattools.ToolShowFile, chattools.ToolShowImage, chattools.ToolShowHTML, chattools.ToolShowDiff, chattools.ToolShowRun:
return "retry with a different title."
case chattools.ToolNotify:
return "retry with slightly different message wording."
case chattools.ToolScheduleFollowup:
return "retry with slightly different message wording."
}
return "retry the call in a moment."
}
// chatSessionDirectory is the chat's recorded working directory, or "".
func (s *chatToolService) chatSessionDirectory(ctx context.Context, sessionID string) string {
if s.registry == nil {
+111
View File
@@ -0,0 +1,111 @@
package server
import (
"context"
"os"
"path/filepath"
"strings"
"testing"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
)
const threeStageModelSource = "# stage a\n\n```prompt\nDo A.\n```\n\n```tools\nread\n```\n\n```edges\nsuccess -> b\nerror -> #failure\n```\n\n```configs\ntype=model\nprovider=opencode-go\nmodel=deepseek-v4.1-flash\nretries=0\n```\n\n# stage b\n\n```prompt\nDo B.\n```\n\n```tools\nread\n```\n\n```edges\nsuccess -> c\nerror -> #failure\n```\n\n```configs\ntype=model\nprovider=opencode-go\nmodel=deepseek-v4.1-flash\nretries=0\n```\n\n# stage c\n\n```prompt\nDo C.\n```\n\n```tools\nread\n```\n\n```edges\nsuccess -> #success\nerror -> #failure\n```\n\n```configs\ntype=model\nprovider=opencode-go\nmodel=deepseek-v4.1-flash\nretries=0\n```\n"
// TestRetryResumesAnInterruptedRunAfterItsLastCompletedStep proves a run the
// server stopped (interrupted) can be retried: it resumes after its last
// completed step without rerunning that prefix, whether the stop came during a
// visit (the interrupted visit runs again) or between visits (the next stage
// starts with the completed visit's handoff).
func TestRetryResumesAnInterruptedRunAfterItsLastCompletedStep(t *testing.T) {
for _, midVisit := range []bool{true, false} {
name := "between-visits"
if midVisit {
name = "mid-visit"
}
t.Run(name, func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
store, err := pipeline.Open(filepath.Join(t.TempDir(), "interrupted.db"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
if _, err := store.Submit(ctx, "resume", threeStageModelSource); err != nil {
t.Fatal(err)
}
items, _ := store.List(ctx)
d, err := store.Get(ctx, items[0].ID, 1)
if err != nil {
t.Fatal(err)
}
workspace := t.TempDir()
id, _, err := store.CreateRun(ctx, d, "interrupted-"+name, workspace, true, nil, map[string]any{"prompt": "task"})
if err != nil {
t.Fatal(err)
}
if err := store.BeginStep(ctx, id, 1, "a", map[string]any{"prompt": "task"}); err != nil {
t.Fatal(err)
}
if err := store.FinishStep(ctx, id, protocol.RunStep{Sequence: 1, Stage: "a", Status: "completed", Outcome: "success", Target: "b", Output: map[string]any{"handoff": "from-a"}}); err != nil {
t.Fatal(err)
}
if midVisit {
if err := store.BeginStep(ctx, id, 2, "b", map[string]any{"handoff": "from-a"}); err != nil {
t.Fatal(err)
}
}
if err := store.RecoverRuns(ctx); err != nil {
t.Fatal(err)
}
source, err := store.GetRun(ctx, id)
if err != nil || source.Status != "interrupted" {
t.Fatalf("source run was not interrupted: %+v %v", source, err)
}
r, err := newRunner(ctx, store)
if err != nil {
t.Fatal(err)
}
calls := map[string]int{}
r.execute = func(_ context.Context, def stage.Definition, input stage.Values) (stage.Result, error) {
calls[def.Key]++
switch def.Key {
case "b":
if input["handoff"] != "from-a" {
t.Errorf("resumed stage lost the completed handoff: %#v", input)
}
data, err := os.ReadFile(def.Turn.Input)
if err != nil {
t.Fatalf("read input.md: %v", err)
}
if !strings.Contains(string(data), "# Previous attempt") || !strings.Contains(string(data), "This is attempt 2.") {
t.Errorf("resumed stage was not told about the previous attempt:\n%s", data)
}
return stage.Result{Outcome: "success", Output: stage.Values{"handoff": "from-b"}}, nil
case "c":
return stage.Result{Outcome: "success", Output: stage.Values{"summary": "done"}}, nil
}
t.Errorf("unexpected stage %q", def.Key)
return stage.Result{}, nil
}
retried, err := r.retry(protocol.Message{RunID: id, RequestKey: "resume-" + name})
if err != nil {
t.Fatal(err)
}
r.wg.Wait()
retried, err = store.GetRun(ctx, retried.ID)
if err != nil || retried.Status != "succeeded" || retried.RetrySource != id {
t.Fatalf("interrupted run did not resume to success: %+v %v", retried, err)
}
if calls["a"] != 0 || calls["b"] != 1 || calls["c"] != 1 {
t.Fatalf("resume reran the completed prefix or skipped work: %v", calls)
}
if len(retried.Steps) == 0 || retried.Steps[0].Stage != "b" || retried.Steps[0].Sequence != 2 {
t.Fatalf("resume started at the wrong step: %+v", retried.Steps)
}
})
}
}
+14
View File
@@ -356,6 +356,20 @@ func TestRetryResumeReusesPrefixHandoffAndReplaysRequestAfterReopen(t *testing.T
if !strings.Contains(string(data), want) {
t.Errorf("retry input.md missing override %q:\n%s", want, data)
}
// Only the override keys are shown, labelled as the operator's
// correction; the merged input (handoff from A) is not reprinted.
text := string(data)
section := text[strings.Index(text, "# Operator correction"):]
if !strings.Contains(text, "# Operator correction") || strings.Contains(section, "from-a") || strings.Contains(text, "# Retry input") {
t.Errorf("retry input.md did not render only the operator correction:\n%s", data)
}
// The retried stage learns why the source attempt failed.
wantAttempt := fmt.Sprintf("This is attempt %d.", bCalls)
for _, want := range []string{"# Previous attempt", wantAttempt, "failed in stage b", "deliberate failure", "Partial edits"} {
if !strings.Contains(text, want) {
t.Errorf("retry input.md missing %q:\n%s", want, data)
}
}
}
if bCalls <= 2 {
return stage.Result{}, fmt.Errorf("deliberate failure")
+97 -11
View File
@@ -662,8 +662,9 @@ func (r *runner) retrySourceCheckpointSelected(sourceID int64, pinned *protocol.
if err != nil {
return retryCheckpoint{}, err
}
if source.Status != "failed" || source.FinishedAt == "" {
return retryCheckpoint{}, fmt.Errorf("retry source %d is not a terminal failed run", sourceID)
interrupted := source.Status == "interrupted"
if (source.Status != "failed" && !interrupted) || source.FinishedAt == "" {
return retryCheckpoint{}, fmt.Errorf("retry source %d is not a terminal failed or interrupted run", sourceID)
}
if source.PipelineID != pinned.ID {
return retryCheckpoint{}, fmt.Errorf("retry source %d belongs to a different pipeline", sourceID)
@@ -672,6 +673,28 @@ func (r *runner) retrySourceCheckpointSelected(sourceID int64, pinned *protocol.
return retryCheckpoint{}, fmt.Errorf("retry source %d has no failed stage checkpoint", sourceID)
}
failed := source.Steps[len(source.Steps)-1]
if interrupted && selectedStage == "" {
// A server stop interrupts a run mid-visit (the visit is recorded as
// interrupted, with the input it began with) or between visits (the
// last recorded visit completed and routed to its next stage). Either
// way the run resumes after its last completed step: the interrupted
// visit runs again, or the next stage starts with the handoff the
// completed visit produced.
switch failed.Status {
case "interrupted":
failed.Target = protocol.FailureEnd
case "completed":
if failed.Target == "" || failed.Target == protocol.SuccessEnd || failed.Target == protocol.FailureEnd {
return retryCheckpoint{}, fmt.Errorf("retry source %d has no unfinished stage to resume; use --mode=restart", sourceID)
}
failed = protocol.RunStep{Sequence: failed.Sequence + 1, Stage: failed.Target, Status: "interrupted", Target: protocol.FailureEnd, Input: failed.Output}
if failed.Input == nil {
failed.Input = map[string]any{}
}
default:
return retryCheckpoint{}, fmt.Errorf("retry source %d has no safe interrupted-stage checkpoint; use --mode=restart", sourceID)
}
}
if selectedStage != "" {
failed = protocol.RunStep{}
visits := 0
@@ -705,7 +728,7 @@ func (r *runner) retrySourceCheckpointSelected(sourceID int64, pinned *protocol.
return retryCheckpoint{}, fmt.Errorf("retry stage %q has no visit %d", selectedStage, selectedVisit)
}
}
if (failed.Status != "completed" && failed.Status != "failed") || (selectedStage == "" && failed.Target != protocol.FailureEnd) {
if (failed.Status != "completed" && failed.Status != "failed" && !(interrupted && failed.Status == "interrupted")) || (selectedStage == "" && failed.Target != protocol.FailureEnd) {
return retryCheckpoint{}, fmt.Errorf("retry source %d has no safe failed-stage checkpoint", sourceID)
}
var handoff map[string]any
@@ -813,8 +836,10 @@ func (r *runner) retry(request protocol.Message) (*protocol.RunDetail, error) {
if original.Executing {
return nil, fmt.Errorf("run %d is still executing; wait for it to stop completely before retrying", original.ID)
}
if original.Status != "failed" || original.FinishedAt == "" {
return nil, fmt.Errorf("only failed runs can be retried (run %d is %s)", original.ID, original.Status)
// An interrupted run (the server stopped mid-run) resumes after its last
// completed step, like a failed run resumes its failed stage.
if (original.Status != "failed" && original.Status != "interrupted") || original.FinishedAt == "" {
return nil, fmt.Errorf("only failed or interrupted runs can be retried (run %d is %s)", original.ID, original.Status)
}
if request.RequestKey == "" {
return nil, fmt.Errorf("retry requires an idempotency request key")
@@ -998,6 +1023,7 @@ func (r *runner) run(ctx context.Context, id int64, d *protocol.PipelineDetail,
return
}
state := rebuildRetryState(source, checkpoint.failed, storedHandoff)
state.previousAttempt = r.previousAttemptSection(ctx, source, d.Graph, state.key)
if override, ok := storedHandoff["override"].(map[string]any); ok {
state.retryOverride = stage.Values(override)
}
@@ -1019,9 +1045,65 @@ func (r *runner) run(ctx context.Context, id int64, d *protocol.PipelineDetail,
input := stage.Values(request.Input)
state := newRunState(d.Graph.Stages[0].Key, input)
state.memory["input"] = memoryValue{output: original}
if request.RetrySource > 0 {
// A restart from entry still tells its first model visit why the
// source run failed.
if source, err := r.store.GetRun(ctx, request.RetrySource); err == nil {
state.previousAttempt = r.previousAttemptSection(ctx, source, d.Graph, state.key)
}
}
r.runLoop(ctx, id, d.Graph, d.Name, workspace, request, state)
}
// maxRetryChain bounds the walk that numbers a retry attempt.
const maxRetryChain = 50
// previousAttemptSection renders the bounded "# Previous attempt" section for
// a retried run whose first visit is the model stage firstStage: the attempt
// number (counted along the retry chain), the stage the source run stopped in
// and its diagnostic. A first visit that is not a model stage gets nothing, so
// the note never lands on an unrelated later stage.
func (r *runner) previousAttemptSection(ctx context.Context, source *protocol.RunDetail, graph protocol.Graph, firstStage string) string {
if source == nil {
return ""
}
model := false
for _, declared := range graph.Stages {
if declared.Key == firstStage {
model = stage.EffectiveType(declared.Type) == stage.ModelType
}
}
if !model {
return ""
}
parentOf := func(d *protocol.RunDetail) int64 {
if d.RetryOf > 0 {
return d.RetryOf
}
return d.RetrySource
}
attempt := 2
for previous := parentOf(source); previous > 0 && attempt < maxRetryChain; attempt++ {
ancestor, err := r.store.GetRun(ctx, previous)
if err != nil || ancestor == nil {
break
}
previous = parentOf(ancestor)
}
failedStage, diagnostic := source.CurrentStage, ""
if n := len(source.Steps); n > 0 {
last := source.Steps[n-1]
failedStage, diagnostic = last.Stage, strings.TrimSpace(last.Diagnostic)
}
if diagnostic == "" {
diagnostic = strings.TrimSpace(source.Diagnostic)
}
if diagnostic == "" {
diagnostic = strings.TrimSpace(source.FailureReason)
}
return turn.RenderPreviousAttempt(turn.PreviousAttempt{Attempt: attempt, Stage: failedStage, Diagnostic: diagnostic, Run: source.ID})
}
// terminalFinish classifies a stage's resolved target. A terminal key yields the
// run's final status, outcome and diagnostic; an empty target means the stage
// named an undeclared outcome; any other value is a stage key and is not
@@ -1098,7 +1180,10 @@ type runState struct {
// retryOverride is applied once, after the selected stage's memory bindings
// have been resolved. It is intentionally not part of run input or memory.
retryOverride stage.Values
priorBudgets map[string]stage.BudgetSnapshot
// previousAttempt is the rendered "# Previous attempt" section a retried
// run's first model visit receives; prepareTurn consumes it.
previousAttempt string
priorBudgets map[string]stage.BudgetSnapshot
// adopt names the visit to re-adopt from a previous server process instead
// of starting it; it is consumed by the loop's first iteration.
adopt *adoptedVisit
@@ -1779,11 +1864,12 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
finish("failed", "error", copyErr.Error())
return
}
// Keep the merged values for this visit's input.md: the model reads
// files, not the persisted step row, so the override must be visible
// there. A selected-stage override belongs only to this invocation,
// not to a later visit reached through the stage graph.
retryInput = input
// The step row persists the merged input; input.md shows only the
// operator's override keys: the model reads files, not the step row,
// so the correction must be visible there, without re-printing the
// whole input. A selected-stage override belongs only to this
// invocation, not to a later visit reached through the stage graph.
retryInput = state.retryOverride
state.retryOverride = nil
}
if adopted == nil {
+29 -17
View File
@@ -52,15 +52,25 @@ func stageTurnPaths(paths turn.Paths) stage.TurnPaths {
// completed turn in full) before the visit starts. A failure here is a run failure: the file
// protocol is the stage contract, not best-effort evidence.
//
// retryInput is the complete merged input for a selected-stage retry and nil for
// an ordinary visit. A retry override is persisted on the step, but the model
// reads input.md rather than the step row, so the same values must be written
// into the file or the operator's correction is invisible to the model.
// retryInput is the operator's override for a selected-stage retry (only the
// keys it sets) and nil for an ordinary visit. The merged input is persisted on
// the step, but the model reads input.md rather than the step row, so the
// correction must be written into the file or it is invisible to the model.
// A retried run's first visit also gets a bounded "# Previous attempt" section
// saying why the source run failed; it is consumed here so later visits do not
// repeat it.
func (r *runner) prepareTurn(paths turn.Paths, state *runState, retryInput stage.Values) error {
if err := paths.Ensure(); err != nil {
return err
}
input := turnInputWithRetry(state.turnInput(), retryInput)
if state.previousAttempt != "" {
if !strings.HasSuffix(input, "\n") {
input += "\n"
}
input += "\n" + state.previousAttempt
state.previousAttempt = ""
}
history := turn.RenderHistory(state.turns)
memory := turn.RenderEssential(turn.Essential{
Task: state.prompt,
@@ -82,24 +92,26 @@ func (r *runner) prepareTurn(paths turn.Paths, state *runState, retryInput stage
return nil
}
// turnInputWithRetry appends the merged retry input to the ordinary turn input.
// It is rendered as a fenced JSON object because the values are operator data,
// not prose; encoding/json sorts map keys so the file is deterministic.
func turnInputWithRetry(base string, retryInput stage.Values) string {
if len(retryInput) == 0 {
// turnInputWithRetry appends the operator's retry override to the ordinary turn
// input as an "Operator correction": only the keys the operator set, not the
// whole merged input the stage already has. It is rendered as a fenced JSON
// object because the values are operator data, not prose; encoding/json sorts
// map keys so the file is deterministic.
func turnInputWithRetry(base string, override stage.Values) string {
if len(override) == 0 {
return base
}
encoded, err := json.MarshalIndent(retryInput, "", " ")
if err != nil {
// A retry input that cannot be rendered is still shown as a visible
// section; the stage can choose its error outcome rather than silently
// receiving a correction it cannot see.
return base + "\n\n# Retry input\n\nThe retry input could not be rendered.\n"
}
if !strings.HasSuffix(base, "\n") {
base += "\n"
}
return base + "\n# Retry input\n\nThis retry was given this complete input:\n\n```json\n" + string(encoded) + "\n```\n"
encoded, err := json.MarshalIndent(override, "", " ")
if err != nil {
// A correction that cannot be rendered is still shown as a visible
// section; the stage can choose its error outcome rather than silently
// receiving a correction it cannot see.
return base + "\n# Operator correction\n\nThe operator's retry correction could not be rendered.\n"
}
return base + "\n# Operator correction\n\nThe operator retried this stage with these corrected input values; they override the earlier ones:\n\n```json\n" + string(encoded) + "\n```\n"
}
// turnInput is the run prompt on the first visit; later visits carry the run
+4
View File
@@ -191,6 +191,7 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
tools.runs = stores[0]
tools.broker = options.Chat
events.observe(tools.observeRun)
hub.queueResumed = tools.resumeRunFollowups
registerChatTools(mux, tools, build.Version)
}
mux.HandleFunc("GET /discovery", serveServerDiscovery)
@@ -635,6 +636,9 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
hub.reattachSessions(ctx, options.Chat)
// Restore live turn ownership before queue rooms can start runners.
hub.resumeQueued(ctx, options.Chat)
if hub.queueResumed != nil {
hub.queueResumed(ctx)
}
close(ready)
hub.observeRunningTurns(ctx, options.Chat)
close(done)
+8 -1
View File
@@ -7,6 +7,7 @@ import (
"time"
"git.a-wan.net/alan/pipelines/internal/opencode"
"git.a-wan.net/alan/pipelines/internal/turn"
)
func (m ModelStage) Run(ctx context.Context, def Definition, input Values) (Result, error) {
@@ -71,7 +72,13 @@ func (m ModelStage) Run(ctx context.Context, def Definition, input Values) (Resu
attemptCtx, cancel := context.WithTimeoutCause(ctx, spec.Config.Timeout, &stageTimeoutCause{timeout: spec.Config.Timeout})
// A completed turn without a valid outcome gets one in-session follow-up
// asking only for the outcome, rather than a full retry of its work.
text, generateErr := client.Generate(withOutputRepair(attemptCtx, outcomesFor(def.Edges)), spec.Config, prompt)
attemptPrompt := prompt
if attempt > 0 && err != nil {
// An in-stage retry says why the last attempt failed rather than
// resending an identical prompt that invites the same failure.
attemptPrompt = prompt + "\n\n" + turn.RenderPreviousAttempt(turn.PreviousAttempt{Attempt: attempt + 1, Stage: def.Key, Diagnostic: err.Error()})
}
text, generateErr := client.Generate(withOutputRepair(attemptCtx, outcomesFor(def.Edges)), spec.Config, attemptPrompt)
if generateErr == nil && attemptCtx.Err() != nil {
generateErr = attemptCtx.Err()
}
+48
View File
@@ -0,0 +1,48 @@
package stage
import (
"context"
"strings"
"testing"
)
type retryableTestError struct{ text string }
func (e retryableTestError) Error() string { return e.text }
func (e retryableTestError) Retryable() bool { return true }
// TestInStageRetryTellsTheModelWhyTheLastAttemptFailed proves an in-stage
// retry does not resend an identical prompt: the second attempt carries a
// bounded "# Previous attempt" section with the attempt number, the stage and
// the last failure, while the first attempt is unchanged.
func TestInStageRetryTellsTheModelWhyTheLastAttemptFailed(t *testing.T) {
def := turnDefinition(t)
def.Configs["retries"] = "1"
prompts := []string{}
client := generatorFunc(func(_ context.Context, _ ModelConfig, prompt string) (string, error) {
prompts = append(prompts, prompt)
if len(prompts) == 1 {
return "", retryableTestError{"provider overloaded: " + strings.Repeat("x", 5000)}
}
return "# outcome\nsuccess\n\n# handoff\n\ndone\n", nil
})
result, err := (ModelStage{Client: client}).Run(context.Background(), def, Values{"prompt": "task"})
if err != nil || result.Outcome != "success" || len(prompts) != 2 {
t.Fatalf("retry did not succeed: %+v %v prompts=%d", result, err, len(prompts))
}
if strings.Contains(prompts[0], "# Previous attempt") {
t.Fatalf("first attempt carried a previous-attempt section:\n%s", prompts[0])
}
second := prompts[1]
if !strings.HasPrefix(second, prompts[0]) {
t.Fatal("retry prompt does not extend the original prompt")
}
for _, want := range []string{"# Previous attempt", "attempt 2 of stage " + def.Key, "provider overloaded", "Partial edits", "[truncated]"} {
if !strings.Contains(second, want) {
t.Fatalf("retry prompt missing %q:\n%s", want, second[len(prompts[0]):])
}
}
if extra := len(second) - len(prompts[0]); extra > 2600 {
t.Fatalf("previous-attempt section is unbounded: %d bytes", extra)
}
}
+57
View File
@@ -0,0 +1,57 @@
package turn
import (
"fmt"
"strings"
)
// PreviousAttemptCap bounds the diagnostic carried into a "# Previous attempt"
// section. A failure's head usually names the cause, so the head is kept.
const PreviousAttemptCap = 2000
// PreviousAttempt describes the attempt that failed before this one: a run
// retry (the source run's failing stage) or a stage's own in-stage retry.
type PreviousAttempt struct {
// Attempt is the 1-based number of the attempt that is about to run.
Attempt int
// Stage is the stage the previous attempt failed in.
Stage string
// Diagnostic is why it failed; it is bounded when rendered.
Diagnostic string
// Run is the failed source run for a run retry; 0 for an in-stage retry.
Run int64
}
// RenderPreviousAttempt renders a bounded "# Previous attempt" section that
// tells a retried stage why the last attempt failed, so it does not repeat the
// same mistake, and that partial edits from it may remain in the worktree.
func RenderPreviousAttempt(p PreviousAttempt) string {
var b strings.Builder
b.WriteString("# Previous attempt\n\n")
attempt := p.Attempt
if attempt < 2 {
attempt = 2
}
stageName := oneLine(p.Stage)
if stageName == "" {
stageName = "unknown"
}
if p.Run > 0 {
fmt.Fprintf(&b, "This is attempt %d. The previous attempt (run %d) failed in stage %s.", attempt, p.Run, capLine(stageName, essentialLineCap))
} else {
fmt.Fprintf(&b, "This is attempt %d of stage %s. The previous attempt failed.", attempt, capLine(stageName, essentialLineCap))
}
b.WriteString(" Partial edits from it may still be in the worktree; check them before redoing work.\n")
detail := strings.TrimSpace(p.Diagnostic)
if detail == "" {
b.WriteString("\nNo diagnostic was recorded.\n")
return b.String()
}
if len(detail) > PreviousAttemptCap {
detail = strings.ToValidUTF8(cutAtRune(detail, PreviousAttemptCap), "") + "\n[truncated]"
}
b.WriteString("\nDiagnostic:\n\n~~~\n")
b.WriteString(strings.ReplaceAll(detail, "~~~", "~ ~ ~"))
b.WriteString("\n~~~\n")
return b.String()
}
+66
View File
@@ -0,0 +1,66 @@
package turn
import (
"strings"
"testing"
)
func TestRenderPreviousAttemptIsBoundedAndNamesTheFailure(t *testing.T) {
text := RenderPreviousAttempt(PreviousAttempt{Attempt: 3, Stage: "land", Run: 42, Diagnostic: "checks failed: go test ./...\n~~~\n" + strings.Repeat("y", 9000)})
for _, want := range []string{"# Previous attempt", "attempt 3", "run 42", "stage land", "checks failed", "Partial edits", "[truncated]"} {
if !strings.Contains(text, want) {
t.Fatalf("missing %q:\n%s", want, text)
}
}
if len(text) > PreviousAttemptCap+500 {
t.Fatalf("section is %d bytes", len(text))
}
// A diagnostic cannot close the fence early.
if strings.Count(text, "~~~") != 2 {
t.Fatalf("diagnostic broke the fence:\n%s", text)
}
empty := RenderPreviousAttempt(PreviousAttempt{Stage: "plan"})
if !strings.Contains(empty, "No diagnostic was recorded.") || !strings.Contains(empty, "attempt 2 of stage plan") {
t.Fatalf("empty diagnostic rendering:\n%s", empty)
}
}
// TestEssentialMemoryRevisitShowsOwnPreviousHandoff proves a stage that runs
// again (a reviewer after the implementer fixed its findings) sees its own last
// handoff, bounded, besides the immediately previous stage's handoff.
func TestEssentialMemoryRevisitShowsOwnPreviousHandoff(t *testing.T) {
entries := feedbackLoopEntries()
entries = append(entries, MemoryEntry{Stage: "code", Visit: 2, Outcome: "success", Output: "# handoff\n\nFixed the lock leak and added the eviction test.\n"})
memory := RenderEssential(Essential{Task: "Add a cache.", StageKey: "review", Entries: entries, InputPath: "in.md", HistoryPath: "hist.md"})
if len(memory) > EssentialCap {
t.Fatalf("essential memory is %d bytes, over the cap", len(memory))
}
for _, want := range []string{
"## Previous stage: code · visit 2",
"Fixed the lock leak",
"## This stage's previous visit: review · visit 1 · outcome changes_requested",
"cache.go:42 leaks the lock on the error path.",
} {
if !strings.Contains(memory, want) {
t.Fatalf("memory missing %q:\n%s", want, memory)
}
}
if strings.Contains(memory, "Long preamble.") {
t.Fatalf("own handoff carried non-handoff text:\n%s", memory)
}
// Long own handoffs are bounded with a pointer to history.md.
entries[2].Output = "# handoff\n\n" + paragraph("finding", 5000)
memory = RenderEssential(Essential{Task: "Add a cache.", StageKey: "review", Entries: entries, InputPath: "in.md", HistoryPath: "hist.md"})
if len(memory) > EssentialCap || !strings.Contains(memory, "full text in history.md") {
t.Fatalf("own handoff not bounded (%d bytes):\n%s", len(memory), memory)
}
// No own section on a first visit or when the previous turn is this stage.
for _, key := range []string{"land", "code"} {
memory = RenderEssential(Essential{Task: "Add a cache.", StageKey: key, Entries: entries})
if strings.Contains(memory, "This stage's previous visit") {
t.Fatalf("%s got an own-handoff section:\n%s", key, memory)
}
}
}
+28
View File
@@ -19,6 +19,9 @@ const (
// essentialHandoffMin is the least room a previous stage's handoff gets
// when the task also needs more than half of the remaining budget.
essentialHandoffMin = 1024
// essentialOwnHandoffCap bounds a revisiting stage's own last handoff
// (for example a reviewer's earlier must-fix findings it must confirm).
essentialOwnHandoffCap = 768
)
// Essential is everything RenderEssential needs for one visit's memory.md.
@@ -63,6 +66,7 @@ func RenderEssential(e Essential) string {
fixed.WriteString("\n")
var tail strings.Builder
tail.WriteString(renderOwnHandoff(e.Entries, e.StageKey))
if ledger := renderLedger(e.Entries, e.StageKey); ledger != "" {
tail.WriteString("\n## Stage ledger\n\n")
tail.WriteString(ledger)
@@ -180,6 +184,30 @@ func HandoffSection(markdown string) (string, bool) {
return section, section != ""
}
// renderOwnHandoff returns a bounded section with the stage's own handoff from
// its latest earlier visit, so a revisiting stage (a reviewer confirming its
// previous must-fix findings) sees what it said last time. It is empty on a
// first visit and when that visit is the immediately previous turn, which the
// "Previous stage" section already shows.
func renderOwnHandoff(entries []MemoryEntry, current string) string {
if current == "" {
return ""
}
for i := len(entries) - 1; i >= 0; i-- {
if entries[i].Stage != current {
continue
}
if i == len(entries)-1 {
return ""
}
own := entries[i]
body, source := previousHandoff(own.Output)
title := capLine(fmt.Sprintf("%s · visit %d%s", oneLine(own.Stage), own.Visit, outcomeSuffix(own.Outcome)), 2*essentialLineCap)
return "\n## This stage's previous visit: " + title + "\n\n" + source + truncateWithNote(body, essentialOwnHandoffCap, "history.md") + "\n"
}
return ""
}
func previousHandoff(output string) (string, string) {
if section, ok := HandoffSection(output); ok {
return strings.TrimSpace(demoteHeadings(section)), ""