server: export a finished stage's real session as session.md and session.html
Every OpenCode-harness model stage now writes its real session into its own step artifacts directory as session.md and session.html, so the existing bounded artifact listing, the /artifacts/<run>/<step>/<name> serving path and the artifact scan find and serve them with no special casing, while the stage keeps its bounded preview in the run record unchanged. - internal/opencode/export.go adds the one shared native export invocation and the exact session-ID/messages validation used by both Connection.Messages and the new ExportSession, so the readback path does not diverge. The backend's published subcommand is used (v1 `export <id>`, v2 `session export <id>`), the source read is capped at 8 MiB, and a larger session is read as a prefix and reported truncated instead of failing. boundedOutput.ReadFrom keeps the cap effective so overflow and the truncation path are real. - internal/stage/session_export.go renders markdown and html with a metadata header, every role and every part (unknown part types as raw JSON, every session text escaped in html), atomic temp+rename writes that never overwrite an existing file, a visible truncation banner at both ends when the source or the 2 MiB rendered cap cuts it, and an honest 0-message header for an empty session rather than fabricated text. - protocol.SessionExport and RunStep.SessionExport are stored in a new step_session_exports table (CREATE TABLE IF NOT EXISTS, so an old database gains an empty table with no migration) loaded through the existing main SELECT alongside the other per-step evidence and deleted by run retention. - internal/server/runner.go exports after the post-stage filediff capture and before scanArtifacts, with context.WithTimeout(context.WithoutCancel(ctx), 10s); it never waits for session idleness and a failure or a Pi stage (no native export path) records a sanitized diagnostic and continues, never changing the stage status, outcome, target, timing or result validation. Reflected where it belongs: the packaged skill references (internal/author/skill/references/operations.md and delivery.md) carry the new Session export rules and the run-artifacts bullet, and docs/stage-artifacts.md documents the names, the <run>/<step> paths, the served URL, the caps, the truncation labels, failure isolation and the Pi limitation. The packaged templates (examples/*.md) only tell a stage to save its own artifacts and say nothing about the server-written session export, so none needed updating; no new reference file was added, so install.go's managed inventory is unchanged. Shared documentation: README.md's per-step artifacts sentence is now stale - it should name the exported session alongside images, screenshots, reports and logs. It is deliberately not committed here; the shared documents are folded by the single documentation writer. Checks: gofmt -l on the touched packages produced no output; go vet ./... passed; go test -race -count=1 ./... passed.
This commit is contained in:
@@ -46,9 +46,13 @@ type runner struct {
|
||||
verdict func(context.Context, map[string]any) string
|
||||
// events pushes run state deltas to subscribed clients. When nil (tests that
|
||||
// build a runner directly) emits are dropped, so nothing else changes.
|
||||
events *runEventHub
|
||||
wg sync.WaitGroup
|
||||
schedulerWG sync.WaitGroup
|
||||
events *runEventHub
|
||||
// exportSession writes a finished stage's session into its own artifacts
|
||||
// directory. It defaults to stage.ExportSession; a failure is best-effort and
|
||||
// never changes the stage's status, outcome, target or result validation.
|
||||
exportSession func(context.Context, stage.SessionExportRequest) (stage.SessionExportResult, error)
|
||||
wg sync.WaitGroup
|
||||
schedulerWG sync.WaitGroup
|
||||
// attentionMu guards attentionSent, the per-run set of run-attention events
|
||||
// already delivered — by a stage's own notify policy or by the run-level
|
||||
// default — so neither republishes the same genuine event.
|
||||
@@ -78,7 +82,7 @@ func newRunner(ctx context.Context, s *pipeline.Store) (*runner, error) {
|
||||
return nil, err
|
||||
}
|
||||
root := filepath.Join(s.Directory(), "artifacts")
|
||||
return &runner{ctx: ctx, store: s, artifactsRoot: root, active: map[int64]activeRun{}, attentionSent: map[int64]map[string]bool{}}, nil
|
||||
return &runner{ctx: ctx, store: s, artifactsRoot: root, active: map[int64]activeRun{}, attentionSent: map[int64]map[string]bool{}, exportSession: stage.ExportSession}, nil
|
||||
}
|
||||
|
||||
func (r *runner) start(request protocol.Message, retryOf ...int64) (*protocol.RunDetail, error) {
|
||||
@@ -956,8 +960,19 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
changes.Status = "partial"
|
||||
changes.Diagnostic = "Agent cleanup was not confirmed; files may still be changing."
|
||||
}
|
||||
// Export the stage's session into its own artifacts directory before the
|
||||
// bounded scan, so the existing listing and serving paths find the files
|
||||
// with no special casing. This is bounded, best-effort evidence: it never
|
||||
// waits for session idleness and a failure never changes the stage's
|
||||
// status, outcome, target or result validation.
|
||||
var sessionExport *protocol.SessionExport
|
||||
if artifactsDir != "" {
|
||||
if owner, ownerErr := r.store.RunSessionOwner(ctx, id, sequence); ownerErr == nil && owner.ID != "" {
|
||||
sessionExport = r.exportStageSession(ctx, owner, artifactsDir, id, sequence, key, modelConfig)
|
||||
}
|
||||
}
|
||||
artifacts, artifactsSkipped, artifactsTruncated := r.scanArtifacts(id, sequence, artifactsDir)
|
||||
step := protocol.RunStep{Sequence: sequence, Stage: key, Status: "completed", Outcome: result.Outcome, Output: result.Output, Transcript: operations.Transcript(client.Transcript), SessionID: stageSession, FileChanges: changes, Artifacts: artifacts, ArtifactsSkipped: artifactsSkipped, ArtifactsTruncated: artifactsTruncated}
|
||||
step := protocol.RunStep{Sequence: sequence, Stage: key, Status: "completed", Outcome: result.Outcome, Output: result.Output, Transcript: operations.Transcript(client.Transcript), SessionID: stageSession, FileChanges: changes, SessionExport: sessionExport, Artifacts: artifacts, ArtifactsSkipped: artifactsSkipped, ArtifactsTruncated: artifactsTruncated}
|
||||
// Stamp the effective provider/model this visit actually ran with for every
|
||||
// model stage, including failures, so the app/TUI evidence reflects any
|
||||
// override. Non-model stages keep empty values.
|
||||
@@ -1058,6 +1073,53 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
finish("failed", "error", "total stage budget exceeded")
|
||||
}
|
||||
|
||||
// exportStageSession writes the finished stage's session into its own artifacts
|
||||
// directory and returns the evidence for the step. A non-OpenCode harness (pi)
|
||||
// has no native export path, so it records that limitation and writes no files.
|
||||
// Any export error is recorded as a sanitized diagnostic and never returned to
|
||||
// the stage: the export is read-only, bounded and best-effort.
|
||||
func (r *runner) exportStageSession(ctx context.Context, owner pipeline.SessionOwner, artifactsDir string, runID int64, sequence int, key string, modelConfig stage.ModelConfig) *protocol.SessionExport {
|
||||
evidence := &protocol.SessionExport{SessionID: owner.ID, Backend: owner.Backend}
|
||||
if owner.Backend != "v1" && owner.Backend != "v2" {
|
||||
evidence.Source = "unavailable"
|
||||
evidence.Diagnostic = "session export unavailable: harness has no native export path"
|
||||
return evidence
|
||||
}
|
||||
export := r.exportSession
|
||||
if export == nil {
|
||||
export = stage.ExportSession
|
||||
}
|
||||
// A canceled stage still gets one bounded, non-blocking attempt; the export
|
||||
// never consumes the stage timeout and never waits for the session.
|
||||
exportCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), stage.SessionExportTimeout)
|
||||
defer cancel()
|
||||
result, err := export(exportCtx, stage.SessionExportRequest{
|
||||
SessionID: owner.ID,
|
||||
Backend: owner.Backend,
|
||||
Directory: owner.Directory,
|
||||
ArtifactsDir: artifactsDir,
|
||||
RunID: runID,
|
||||
Sequence: sequence,
|
||||
Stage: key,
|
||||
Provider: modelConfig.Provider,
|
||||
Model: modelConfig.Model,
|
||||
})
|
||||
if err != nil {
|
||||
evidence.Source = "native_export"
|
||||
evidence.Diagnostic = stage.RedactEvidence(err.Error())
|
||||
return evidence
|
||||
}
|
||||
evidence.Source = result.Source
|
||||
evidence.Markdown = result.Markdown
|
||||
evidence.HTML = result.HTML
|
||||
evidence.MarkdownBytes = result.MarkdownBytes
|
||||
evidence.HTMLBytes = result.HTMLBytes
|
||||
evidence.Messages = result.Messages
|
||||
evidence.Truncated = result.Truncated
|
||||
evidence.Diagnostic = result.Diagnostic
|
||||
return evidence
|
||||
}
|
||||
|
||||
// setTitle renames a run: it replaces the stored operator-facing title without
|
||||
// touching the run's input, steps or execution, then returns the updated detail.
|
||||
func (r *runner) setTitle(id int64, title string) (*protocol.RunDetail, error) {
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/stage"
|
||||
)
|
||||
|
||||
// sessionExportLiveSource is a one-stage pipeline that declares the read tool so
|
||||
// the stage runs as an agent (the V2 path that persists session messages) while
|
||||
// the prompt tells it not to use any tool.
|
||||
func sessionExportLiveSource(provider, model string) string {
|
||||
return "# stage one\n\n```output\n{ summary }\n```\n\n" +
|
||||
"```prompt\nReturn success with summary exactly: session export live check. Do not use any tool.\n```\n\n" +
|
||||
"```tools\nread\n```\n\n" +
|
||||
"```configs\nprovider=" + provider + "\nmodel=" + model + "\nretries=0\ntimeout=2m\n```\n\n" +
|
||||
"```edges\nsuccess -> #success\nerror -> #failure\n```\n\n"
|
||||
}
|
||||
|
||||
// TestSessionExportLive is an opt-in live check: it runs one real OpenCode stage
|
||||
// on a temporary store and artifacts root using the configured host harness,
|
||||
// then proves the real session.md/session.html are written, listed and served
|
||||
// 200. It is gated so the default suite never spends inference.
|
||||
func TestSessionExportLive(t *testing.T) {
|
||||
if os.Getenv("PIPELINES_SESSION_EXPORT_LIVE") != "1" {
|
||||
t.Skip("set PIPELINES_SESSION_EXPORT_LIVE=1 and PIPELINES_SESSION_EXPORT_MODEL to run chargeable session-export inference")
|
||||
}
|
||||
model := os.Getenv("PIPELINES_SESSION_EXPORT_MODEL")
|
||||
provider, id, ok := strings.Cut(model, "/")
|
||||
if !ok || !stage.ValidModel(provider, id) {
|
||||
t.Fatal("explicit valid PIPELINES_SESSION_EXPORT_MODEL required")
|
||||
}
|
||||
// Isolate notifications from the operator's real ntfy service.
|
||||
endpoint := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
fmt.Fprint(w, `{"id":"session-export-live-receipt","event":"message"}`)
|
||||
}))
|
||||
defer endpoint.Close()
|
||||
t.Setenv("PIPELINES_NTFY_URL", endpoint.URL+"/live")
|
||||
t.Setenv("PIPELINES_NTFY_TOKEN", "")
|
||||
t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "")
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 6*time.Minute)
|
||||
defer cancel()
|
||||
root := t.TempDir()
|
||||
store, err := pipeline.Open(filepath.Join(root, "runs.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
if _, err := store.Submit(ctx, "session-export-live", sessionExportLiveSource(provider, id)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, err := store.List(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
handler := Handler(ctx, store).(*runHandler)
|
||||
handler.runner.artifactsRoot = filepath.Join(root, "artifacts")
|
||||
defer func() { cancel(); WaitRuns(handler) }()
|
||||
workspace := filepath.Join(root, "ws")
|
||||
if err := os.Mkdir(workspace, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
run, err := handler.runner.start(protocol.Message{
|
||||
PipelineID: items[0].ID, Version: 1, RequestKey: "session-export-live",
|
||||
Workspace: workspace, Input: map[string]any{"prompt": "Return the fixed session export live check."},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
handler.runner.wg.Wait()
|
||||
detail, err := store.GetRun(context.Background(), run.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if detail.Status != "succeeded" || len(detail.Steps) != 1 {
|
||||
t.Fatalf("live run did not succeed: %+v", detail)
|
||||
}
|
||||
step := detail.Steps[0]
|
||||
if step.SessionExport == nil || step.SessionExport.Source != "native_export" || step.SessionExport.MarkdownBytes == 0 || step.SessionExport.HTMLBytes == 0 {
|
||||
t.Fatalf("live session export evidence missing: %+v", step.SessionExport)
|
||||
}
|
||||
if step.SessionExport.Messages == 0 || step.SessionExport.Truncated {
|
||||
t.Fatalf("live session export was empty or truncated: %+v", step.SessionExport)
|
||||
}
|
||||
srv := httptest.NewServer(handler)
|
||||
defer srv.Close()
|
||||
for _, name := range []string{"session.md", "session.html"} {
|
||||
artifact, ok := artifactNamed(step.Artifacts, name)
|
||||
if !ok {
|
||||
t.Fatalf("%s not in live artifact listing: %+v", name, step.Artifacts)
|
||||
}
|
||||
resp, err := http.Get(srv.URL + artifact.URL)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("%s served HTTP %d", name, resp.StatusCode)
|
||||
}
|
||||
path := filepath.Join(handler.runner.artifactsRoot, fmt.Sprint(run.ID), "1", name)
|
||||
if evidenceDir := os.Getenv("PIPELINES_SESSION_EXPORT_LIVE_DIR"); evidenceDir != "" {
|
||||
if err := os.MkdirAll(evidenceDir, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(evidenceDir, name), body, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
first := string(body)
|
||||
if idx := strings.IndexByte(first, '\n'); idx >= 0 {
|
||||
first = first[:idx]
|
||||
}
|
||||
t.Logf("live export %s: path=%s size=%d messages=%d url=%s http=%d first_line=%q", name, path, len(body), step.SessionExport.Messages, artifact.URL, resp.StatusCode, first)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSessionExportRecorded is the fallback evidence path: with no chargeable
|
||||
// inference, it exports one real recorded session read-only through the same
|
||||
// code path, clearly labelled as not produced by a fresh runner stage.
|
||||
func TestSessionExportRecorded(t *testing.T) {
|
||||
session := os.Getenv("PIPELINES_SESSION_EXPORT_RECORDED_ID")
|
||||
if session == "" {
|
||||
t.Skip("set PIPELINES_SESSION_EXPORT_RECORDED_ID and _DIR to export a recorded session read-only (no inference)")
|
||||
}
|
||||
dir := os.Getenv("PIPELINES_SESSION_EXPORT_RECORDED_DIR")
|
||||
if dir == "" {
|
||||
t.Fatal("PIPELINES_SESSION_EXPORT_RECORDED_DIR required")
|
||||
}
|
||||
if err := os.MkdirAll(dir, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result, err := stage.ExportSession(context.Background(), stage.SessionExportRequest{
|
||||
SessionID: session, Backend: "v2", Directory: dir, ArtifactsDir: dir,
|
||||
RunID: 0, Sequence: 0, Stage: "recorded",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("recorded session export failed: %v", err)
|
||||
}
|
||||
for _, name := range []string{stage.SessionMarkdownFile, stage.SessionHTMLFile} {
|
||||
info, err := os.Stat(filepath.Join(dir, name))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data, _ := os.ReadFile(filepath.Join(dir, name))
|
||||
first := string(data)
|
||||
if idx := strings.IndexByte(first, '\n'); idx >= 0 {
|
||||
first = first[:idx]
|
||||
}
|
||||
t.Logf("recorded export (NOT a fresh runner stage) %s: path=%s size=%d first_line=%q", name, filepath.Join(dir, name), info.Size(), first)
|
||||
}
|
||||
if result.MarkdownBytes == 0 || result.HTMLBytes == 0 {
|
||||
t.Fatalf("recorded export wrote no files: %+v", result)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"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"
|
||||
)
|
||||
|
||||
// sessionExportBody is a minimal native export envelope with a user and an
|
||||
// assistant turn, used by the fake CLI below.
|
||||
const sessionExportBody = `{"info":{"id":"ses_run"},"messages":[` +
|
||||
`{"info":{"id":"m1","role":"user"},"text":"do the task"},` +
|
||||
`{"info":{"id":"m2","role":"assistant"},"parts":[` +
|
||||
`{"type":"text","text":"done"},` +
|
||||
`{"type":"tool","name":"shell","state":{"status":"completed","input":{"cmd":"ls"},"content":[{"type":"text","text":"output here"}]}}]}]}`
|
||||
|
||||
// sessionExportCLI points PIPELINES_OPENCODE at a fake `opencode export` that
|
||||
// returns sessionExportBody, so the runner's real export path runs.
|
||||
func sessionExportCLI(t *testing.T) {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "opencode")
|
||||
script := "#!/bin/sh\n" +
|
||||
"[ \"$1\" = export ] && shift || { [ \"$1\" = session ] && [ \"$2\" = export ] && shift 2 || exit 8; }\n" +
|
||||
"[ \"$1\" = ses_run ] || exit 9\n" +
|
||||
"cat <<'EOF'\n" + sessionExportBody + "\nEOF\n"
|
||||
if err := os.WriteFile(path, []byte(script), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("PIPELINES_OPENCODE", path)
|
||||
}
|
||||
|
||||
// sessionExportRunner runs one stage that records a session for the run, so the
|
||||
// runner's post-stage export has an owner to read. The export seam is supplied by
|
||||
// the caller; ready gates the stage until the test has captured the run id.
|
||||
func sessionExportRunner(t *testing.T, backend string, seam func(stage.SessionExportRequest) (stage.SessionExportResult, error)) (*runHandler, *pipeline.Store, int64) {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancel)
|
||||
store, err := pipeline.Open(filepath.Join(t.TempDir(), "session.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { store.Close() })
|
||||
if _, err := store.Submit(ctx, "session-export", pipeline.Template([]string{"one"}, true)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, err := store.List(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
handler := Handler(ctx, store).(*runHandler)
|
||||
t.Cleanup(func() { cancel(); WaitRuns(handler) })
|
||||
handler.runner.artifactsRoot = t.TempDir()
|
||||
if seam != nil {
|
||||
handler.runner.exportSession = func(_ context.Context, request stage.SessionExportRequest) (stage.SessionExportResult, error) {
|
||||
return seam(request)
|
||||
}
|
||||
}
|
||||
ready := make(chan struct{})
|
||||
var runID int64
|
||||
handler.runner.execute = func(ctx context.Context, _ stage.Definition, _ stage.Values) (stage.Result, error) {
|
||||
<-ready
|
||||
if err := handler.runner.store.RunSession(ctx, runID, 1, "ses_run", true, backend, ""); err != nil {
|
||||
return stage.Result{}, err
|
||||
}
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{"summary": "done"}}, nil
|
||||
}
|
||||
run, err := handler.runner.start(protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: "session", Workspace: t.TempDir(), Input: map[string]any{"prompt": "task"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runID = run.ID
|
||||
close(ready)
|
||||
handler.runner.wg.Wait()
|
||||
return handler, store, run.ID
|
||||
}
|
||||
|
||||
// TestRunnerExportsSessionFilesIntoArtifactsAndServesThem proves the real export
|
||||
// path writes both files into the step's artifacts directory, lists them with
|
||||
// artifact URLs and serves them 200, without changing the step's status, outcome
|
||||
// or target.
|
||||
func TestRunnerExportsSessionFilesIntoArtifactsAndServesThem(t *testing.T) {
|
||||
sessionExportCLI(t)
|
||||
handler, store, runID := sessionExportRunner(t, "v2", nil)
|
||||
detail, err := store.GetRun(context.Background(), runID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if detail.Status != "succeeded" || len(detail.Steps) != 1 {
|
||||
t.Fatalf("unexpected run: %+v", detail)
|
||||
}
|
||||
step := detail.Steps[0]
|
||||
if step.Status != "completed" || step.Outcome != "success" {
|
||||
t.Fatalf("export changed the stage result: %+v", step)
|
||||
}
|
||||
if len(step.Transcript) > 32<<10 || strings.Contains(step.Transcript, "do the task") || strings.Contains(step.Transcript, "session.md") {
|
||||
t.Fatalf("transcript was changed by the export: %q", step.Transcript)
|
||||
}
|
||||
if step.SessionExport == nil || step.SessionExport.SessionID != "ses_run" || step.SessionExport.Source != "native_export" {
|
||||
t.Fatalf("export evidence missing: %+v", step.SessionExport)
|
||||
}
|
||||
if step.SessionExport.Messages != 2 || step.SessionExport.MarkdownBytes == 0 || step.SessionExport.HTMLBytes == 0 {
|
||||
t.Fatalf("export evidence wrong: %+v", step.SessionExport)
|
||||
}
|
||||
for _, name := range []string{"session.md", "session.html"} {
|
||||
artifact, ok := artifactNamed(step.Artifacts, name)
|
||||
if !ok {
|
||||
t.Fatalf("%s not in the artifact listing: %+v", name, step.Artifacts)
|
||||
}
|
||||
wantURL := fmt.Sprintf("/artifacts/%d/1/%s", runID, name)
|
||||
if artifact.URL != wantURL || artifact.SizeBytes == 0 {
|
||||
t.Fatalf("%s listing wrong: %+v", name, artifact)
|
||||
}
|
||||
}
|
||||
|
||||
srv := httptest.NewServer(handler)
|
||||
defer srv.Close()
|
||||
for _, name := range []string{"session.md", "session.html"} {
|
||||
resp, err := http.Get(srv.URL + fmt.Sprintf("/artifacts/%d/1/%s", runID, name))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK || len(body) == 0 {
|
||||
t.Fatalf("%s served %d (%d bytes)", name, resp.StatusCode, len(body))
|
||||
}
|
||||
contentType := resp.Header.Get("Content-Type")
|
||||
if name == "session.md" && !strings.HasPrefix(contentType, "text/markdown") && !strings.HasPrefix(contentType, "text/plain") {
|
||||
t.Fatalf("session.md content type = %q", contentType)
|
||||
}
|
||||
if name == "session.html" && !strings.HasPrefix(contentType, "text/html") {
|
||||
t.Fatalf("session.html content type = %q", contentType)
|
||||
}
|
||||
if name == "session.md" && !strings.Contains(string(body), "do the task") {
|
||||
t.Fatalf("served markdown missing session text")
|
||||
}
|
||||
if name == "session.html" && !strings.Contains(string(body), "output here") {
|
||||
t.Fatalf("served html missing tool output")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunnerSessionExportFailureTruncationAndUnavailableHarness proves the three
|
||||
// non-success export outcomes are recorded as evidence and never fail the run.
|
||||
func TestRunnerSessionExportFailureTruncationAndUnavailableHarness(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
backend string
|
||||
seam func(stage.SessionExportRequest) (stage.SessionExportResult, error)
|
||||
wantSrc string
|
||||
wantDiag string
|
||||
wantTrunc bool
|
||||
}{
|
||||
{
|
||||
name: "failure",
|
||||
backend: "v2",
|
||||
seam: func(stage.SessionExportRequest) (stage.SessionExportResult, error) {
|
||||
return stage.SessionExportResult{}, errors.New("native session export failed")
|
||||
},
|
||||
wantSrc: "native_export",
|
||||
wantDiag: "native session export failed",
|
||||
},
|
||||
{
|
||||
name: "truncated",
|
||||
backend: "v2",
|
||||
seam: func(stage.SessionExportRequest) (stage.SessionExportResult, error) {
|
||||
return stage.SessionExportResult{Source: "native_export", Truncated: true, Messages: 3}, nil
|
||||
},
|
||||
wantSrc: "native_export",
|
||||
wantTrunc: true,
|
||||
},
|
||||
{
|
||||
name: "unavailable",
|
||||
backend: "pi",
|
||||
seam: nil,
|
||||
wantSrc: "unavailable",
|
||||
wantDiag: "harness has no native export path",
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
handler, store, runID := sessionExportRunner(t, tc.backend, tc.seam)
|
||||
detail, err := store.GetRun(context.Background(), runID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if detail.Status != "succeeded" {
|
||||
t.Fatalf("export outcome failed the run: %+v", detail.Status)
|
||||
}
|
||||
step := detail.Steps[0]
|
||||
if step.Status != "completed" || step.Outcome != "success" {
|
||||
t.Fatalf("export changed the stage result: %+v", step)
|
||||
}
|
||||
if step.SessionExport == nil || step.SessionExport.Source != tc.wantSrc {
|
||||
t.Fatalf("export evidence wrong: %+v", step.SessionExport)
|
||||
}
|
||||
if tc.wantDiag != "" && !strings.Contains(step.SessionExport.Diagnostic, tc.wantDiag) {
|
||||
t.Fatalf("diagnostic %q missing %q", step.SessionExport.Diagnostic, tc.wantDiag)
|
||||
}
|
||||
if step.SessionExport.Truncated != tc.wantTrunc {
|
||||
t.Fatalf("truncated = %v, want %v", step.SessionExport.Truncated, tc.wantTrunc)
|
||||
}
|
||||
if tc.wantSrc == "unavailable" {
|
||||
if artifacts, _, _ := handler.runner.scanArtifacts(runID, 1, filepath.Join(handler.runner.artifactsRoot, fmt.Sprint(runID), "1")); len(artifacts) != 0 {
|
||||
t.Fatalf("unavailable harness wrote files: %+v", artifacts)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user