Enforce runtime report contracts and recoverable session exports
This commit is contained in:
@@ -0,0 +1,160 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"github.com/yuin/goldmark"
|
||||
"github.com/yuin/goldmark/extension"
|
||||
)
|
||||
|
||||
const reportLimit = 2 << 20
|
||||
|
||||
// renderReport is deterministic and deliberately structural: no factual or
|
||||
// completion validation is implied. Raw HTML is disabled by Goldmark's default
|
||||
// renderer; the document has no scripts, stylesheets or remote dependencies.
|
||||
func renderReport(format string, output map[string]any) (string, []byte, error) {
|
||||
if err := protocol.ValidateOutputFormat(format); err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
var markdown string
|
||||
for _, key := range []string{"markdown", "report", "result", "summary", "message"} {
|
||||
if text, ok := output[key].(string); ok && strings.TrimSpace(text) != "" {
|
||||
markdown = text
|
||||
break
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(markdown) == "" {
|
||||
return "", nil, fmt.Errorf("requested report requires nonempty textual output (markdown, report, result, summary or message)")
|
||||
}
|
||||
if len(markdown) > reportLimit {
|
||||
return "", nil, fmt.Errorf("report source exceeds size limit")
|
||||
}
|
||||
if format == "markdown" {
|
||||
return "report.md", []byte(markdown), nil
|
||||
}
|
||||
var body bytes.Buffer
|
||||
if err := goldmark.New(goldmark.WithExtensions(extension.GFM)).Convert([]byte(markdown), &body); err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
// No external resources are fetched even if markdown includes image links.
|
||||
doc := "<!doctype html>\n<html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width\"><meta http-equiv=\"Content-Security-Policy\" content=\"default-src 'none'; style-src 'unsafe-inline'; img-src data:; base-uri 'none'; form-action 'none'\"><title>Run report</title><style>body{max-width:70rem;margin:3rem auto;padding:0 1.5rem;font:18px/1.6 system-ui}pre{white-space:pre-wrap}img{max-width:100%}table{border-collapse:collapse}td,th{border:1px solid;padding:.4rem}</style></head><body><main>" + body.String() + "</main></body></html>\n"
|
||||
if len(doc) > reportLimit {
|
||||
return "", nil, fmt.Errorf("rendered report exceeds size limit")
|
||||
}
|
||||
return "report.html", []byte(doc), nil
|
||||
}
|
||||
|
||||
// finalizeDeliverable runs before the successful terminal store transition.
|
||||
// Fixed names and os.Root keep writes confined even if a stage left symlinks.
|
||||
// Existing files (including model-created reports) are never overwritten.
|
||||
func (r *runner) finalizeDeliverable(ctx context.Context, id int64, sequence int, output map[string]any) error {
|
||||
detail, err := r.store.GetRun(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if detail.OutputFormat == "" {
|
||||
return nil
|
||||
}
|
||||
if detail.Status != protocol.RunStatusQueued && detail.Status != protocol.RunStatusRunning {
|
||||
return nil // never create evidence for an already-settled/canceled run
|
||||
}
|
||||
if sequence <= 0 {
|
||||
return fmt.Errorf("requested report has no completed visit")
|
||||
}
|
||||
name, body, err := renderReport(detail.OutputFormat, output)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var visit *protocol.RunStep
|
||||
for i := range detail.Steps {
|
||||
if detail.Steps[i].Sequence == sequence {
|
||||
visit = &detail.Steps[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
if visit == nil || visit.Status != "completed" {
|
||||
return fmt.Errorf("requested report has no completed terminal visit")
|
||||
}
|
||||
var inventoried int64
|
||||
for _, file := range visit.Artifacts {
|
||||
inventoried += file.SizeBytes
|
||||
}
|
||||
if len(visit.Artifacts) >= maxArtifactFiles || inventoried+int64(len(body)) > maxArtifactTotalBytes {
|
||||
return fmt.Errorf("requested report exceeds artifact inventory bounds")
|
||||
}
|
||||
root, err := os.OpenRoot(r.artifactsRoot)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer root.Close()
|
||||
run := strconv.FormatInt(id, 10)
|
||||
public := filepath.Join(run, "public")
|
||||
// Refuse symlinked directories, rather than using another visit's files.
|
||||
for _, dir := range []string{run, public} {
|
||||
info, err := root.Lstat(dir)
|
||||
if os.IsNotExist(err) {
|
||||
err = root.Mkdir(dir, 0755)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
|
||||
return fmt.Errorf("report directory is not a normal directory")
|
||||
}
|
||||
}
|
||||
target := filepath.Join(public, name)
|
||||
file, err := root.OpenFile(target, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create requested report: %w", err)
|
||||
}
|
||||
written, writeErr := file.Write(body)
|
||||
if writeErr == nil && written != len(body) {
|
||||
writeErr = io.ErrShortWrite
|
||||
}
|
||||
if writeErr == nil {
|
||||
writeErr = file.Sync()
|
||||
}
|
||||
closeErr := file.Close()
|
||||
if writeErr != nil {
|
||||
return writeErr
|
||||
}
|
||||
if closeErr != nil {
|
||||
return closeErr
|
||||
}
|
||||
info, err := root.Lstat(target)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !info.Mode().IsRegular() || info.Size() <= 0 || info.Size() > reportLimit {
|
||||
return fmt.Errorf("requested report is missing, empty, not a normal file or oversized")
|
||||
}
|
||||
check, err := root.Open(target)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
actual, err := io.ReadAll(io.LimitReader(check, reportLimit+1))
|
||||
check.Close()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !bytes.Equal(actual, body) {
|
||||
return fmt.Errorf("requested report changed during verification")
|
||||
}
|
||||
contentType := "text/markdown; charset=utf-8"
|
||||
if detail.OutputFormat == "html" {
|
||||
contentType = "text/html; charset=utf-8"
|
||||
}
|
||||
return r.store.RecordDeliverable(ctx, id, sequence, protocol.StageArtifact{Name: "public/" + name, SizeBytes: info.Size(), ContentType: contentType, URL: artifactURL(id, sequence, "public/"+name)})
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"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"
|
||||
"git.a-wan.net/alan/pipelines/internal/summarise"
|
||||
)
|
||||
|
||||
func TestRenderReportContract(t *testing.T) {
|
||||
for _, format := range []string{"html", "markdown"} {
|
||||
name, body, err := renderReport(format, map[string]any{"markdown": "# Report\n\n**Done**\n<script>alert(1)</script>"})
|
||||
if err != nil || name == "" || len(body) == 0 {
|
||||
t.Fatalf("%s: %s %v", format, body, err)
|
||||
}
|
||||
if format == "html" && (!strings.Contains(string(body), "<h1>Report</h1>") || strings.Contains(string(body), "<script>") || !strings.Contains(string(body), "Content-Security-Policy")) {
|
||||
t.Fatalf("unsafe or malformed report: %s", body)
|
||||
}
|
||||
_, again, _ := renderReport(format, map[string]any{"markdown": "# Report\n\n**Done**\n<script>alert(1)</script>"})
|
||||
if string(again) != string(body) {
|
||||
t.Fatal("not deterministic")
|
||||
}
|
||||
}
|
||||
for _, output := range []map[string]any{nil, {}, {"markdown": " \n"}, {"files": []string{"report.html"}}, {"markdown": strings.Repeat("x", reportLimit+1)}} {
|
||||
if _, _, err := renderReport("html", output); err == nil {
|
||||
t.Fatalf("accepted absent/oversized output: %.80v", output)
|
||||
}
|
||||
}
|
||||
if _, _, err := renderReport("../../escape", map[string]any{"summary": "hello"}); err == nil {
|
||||
t.Fatal("accepted invalid format")
|
||||
}
|
||||
}
|
||||
|
||||
func reportRunner(t *testing.T, format string) (*runner, int64) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
s, err := pipeline.Open(filepath.Join(t.TempDir(), "report.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { s.Close() })
|
||||
if _, err := s.Submit(ctx, "report", pipeline.Template([]string{"one"}, true)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, _ := s.List(ctx)
|
||||
d, _ := s.Get(ctx, items[0].ID, 1)
|
||||
id, _, err := s.CreateRunTitled(ctx, d, "report-key", "workspace", false, nil, map[string]any{"prompt": "task"}, pipeline.RunOverrides{OutputFormat: format}, summarise.Title{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.BeginStep(ctx, id, 1, "one", nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.FinishStep(ctx, id, protocol.RunStep{Sequence: 1, Stage: "one", Status: "completed", Outcome: "success", Output: map[string]any{"markdown": "# Result"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return &runner{ctx: ctx, store: s, artifactsRoot: t.TempDir(), notifyModes: map[int64]string{id: "off"}}, id
|
||||
}
|
||||
|
||||
func TestDeliverableBeforeSuccess(t *testing.T) {
|
||||
for _, format := range []string{"html", "markdown", ""} {
|
||||
t.Run(format, func(t *testing.T) {
|
||||
r, id := reportRunner(t, format)
|
||||
r.finishRunState(id, "report", "workspace", "succeeded", "success", "", 1, 1, "one", stage.Values{"markdown": "# Result"})
|
||||
d, err := r.store.GetRun(context.Background(), id)
|
||||
if err != nil || d.Status != "succeeded" || d.OutputFormat != format {
|
||||
t.Fatalf("%+v %v", d, err)
|
||||
}
|
||||
if format != "" {
|
||||
if len(d.Steps[0].Artifacts) != 1 {
|
||||
t.Fatalf("missing report inventory: %+v", d.Steps)
|
||||
}
|
||||
file := d.Steps[0].Artifacts[0]
|
||||
if file.SizeBytes <= 0 || !strings.HasPrefix(file.Name, "public/report.") {
|
||||
t.Fatalf("%+v", file)
|
||||
}
|
||||
body, err := os.ReadFile(filepath.Join(r.artifactsRoot, "1", file.Name))
|
||||
if err != nil || len(body) == 0 {
|
||||
t.Fatalf("missing requested report: %v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeliverableMissingFailsRun(t *testing.T) {
|
||||
r, id := reportRunner(t, "html")
|
||||
r.finishRunState(id, "report", "workspace", "succeeded", "success", "", 1, 1, "one", nil)
|
||||
d, _ := r.store.GetRun(context.Background(), id)
|
||||
if d.Status != "failed" || !strings.Contains(d.Diagnostic, "deliverable contract") {
|
||||
t.Fatalf("missing report succeeded: %+v", d)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeliverableRejectsExistingFilesAndSymlinks(t *testing.T) {
|
||||
for _, kind := range []string{"file", "directory", "symlink", "public-symlink", "run-symlink"} {
|
||||
t.Run(kind, func(t *testing.T) {
|
||||
r, id := reportRunner(t, "html")
|
||||
public := filepath.Join(r.artifactsRoot, "1", "public")
|
||||
if err := os.MkdirAll(public, 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
target := filepath.Join(public, "report.html")
|
||||
outside := filepath.Join(t.TempDir(), "keep")
|
||||
if err := os.WriteFile(outside, []byte("keep"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var err error
|
||||
switch kind {
|
||||
case "file":
|
||||
err = os.WriteFile(target, []byte("keep"), 0600)
|
||||
case "directory":
|
||||
err = os.Mkdir(target, 0755)
|
||||
case "symlink":
|
||||
err = os.Symlink(outside, target)
|
||||
case "public-symlink":
|
||||
os.Remove(public)
|
||||
err = os.Symlink(filepath.Dir(outside), public)
|
||||
case "run-symlink":
|
||||
os.Remove(public)
|
||||
os.Remove(filepath.Dir(public))
|
||||
err = os.Symlink(filepath.Dir(outside), filepath.Dir(public))
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := r.finalizeDeliverable(context.Background(), id, 1, map[string]any{"markdown": "new"}); err == nil {
|
||||
t.Fatal("unsafe/existing target accepted")
|
||||
}
|
||||
body, _ := os.ReadFile(outside)
|
||||
if string(body) != "keep" {
|
||||
t.Fatal("outside evidence overwritten")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestOutputFormatRetryInheritanceThroughRuntime(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
s, err := pipeline.Open(filepath.Join(t.TempDir(), "retry-format.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer s.Close()
|
||||
if _, err := s.Submit(ctx, "report", pipeline.Template([]string{"one"}, true)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, _ := s.List(ctx)
|
||||
r, err := newRunner(ctx, s)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { cancel(); r.wg.Wait() }()
|
||||
r.artifactsRoot = t.TempDir()
|
||||
r.execute = func(context.Context, stage.Definition, stage.Values) (stage.Result, error) {
|
||||
return stage.Result{}, fmt.Errorf("fixture failure")
|
||||
}
|
||||
original, err := r.start(protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: "original-format", Workspace: t.TempDir(), Input: map[string]any{"prompt": "task"}, OutputFormat: "html", NotifyMode: "off"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.wg.Wait()
|
||||
r.execute = func(context.Context, stage.Definition, stage.Values) (stage.Result, error) {
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "# Recovered report"}}, nil
|
||||
}
|
||||
retry, err := r.retry(protocol.Message{RunID: original.ID, RequestKey: "retry-format", RetryMode: "restart"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.wg.Wait()
|
||||
retry, err = s.GetRun(ctx, retry.ID)
|
||||
if err != nil || retry.Status != "succeeded" || retry.OutputFormat != "html" {
|
||||
t.Fatalf("contract not inherited: %+v %v", retry, err)
|
||||
}
|
||||
if _, ok := artifactNamed(retry.Steps[0].Artifacts, "public/report.html"); !ok {
|
||||
t.Fatal("retry report missing")
|
||||
}
|
||||
replay, err := r.retry(protocol.Message{RunID: original.ID, RequestKey: "retry-format", RetryMode: "restart"})
|
||||
if err != nil || replay.ID != retry.ID {
|
||||
t.Fatalf("retry idempotency lost: %+v %v", replay, err)
|
||||
}
|
||||
}
|
||||
@@ -38,6 +38,9 @@ type runner struct {
|
||||
mu sync.Mutex
|
||||
active map[int64]activeRun
|
||||
execute func(context.Context, stage.Definition, stage.Values) (stage.Result, error)
|
||||
|
||||
exportRepairMu sync.Mutex
|
||||
|
||||
// title generates the operator-facing run title from the run prompt. When nil
|
||||
// the store derives a fallback from the prompt with no model call, so tests
|
||||
// and unconfigured servers stay deterministic.
|
||||
@@ -121,6 +124,9 @@ func newRunner(ctx context.Context, s *pipeline.Store) (*runner, error) {
|
||||
}
|
||||
|
||||
func (r *runner) start(request protocol.Message, retryOf ...int64) (*protocol.RunDetail, error) {
|
||||
if err := protocol.ValidateOutputFormat(request.OutputFormat); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if request.Version <= 0 || request.RequestKey == "" || len(request.RequestKey) > 128 {
|
||||
return nil, fmt.Errorf("an explicit version and request key are required")
|
||||
}
|
||||
@@ -283,7 +289,7 @@ func (r *runner) start(request protocol.Message, retryOf ...int64) (*protocol.Ru
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
id, created, err := r.store.CreateRunTitled(r.ctx, d, request.RequestKey, workspace, request.AllowTools, request.WritePaths, request.Input, pipeline.RunOverrides{Model: request.Model, StageModels: request.StageModels, NotifyMode: request.NotifyMode}, runTitle, retryOf...)
|
||||
id, created, err := r.store.CreateRunTitled(r.ctx, d, request.RequestKey, workspace, request.AllowTools, request.WritePaths, request.Input, pipeline.RunOverrides{Model: request.Model, StageModels: request.StageModels, NotifyMode: request.NotifyMode, OutputFormat: request.OutputFormat}, runTitle, retryOf...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -707,7 +713,7 @@ func (r *runner) retry(request protocol.Message) (*protocol.RunDetail, error) {
|
||||
if notifyMode == "" {
|
||||
notifyMode, _ = r.store.RunNotifyMode(r.ctx, original.ID)
|
||||
}
|
||||
return r.start(protocol.Message{PipelineID: original.PipelineID, Version: version, RequestKey: request.RequestKey, RetryMode: mode, RetrySource: original.ID, RetryStage: request.RetryStage, RetryVisit: request.RetryVisit, RetryInput: request.RetryInput, Workspace: original.Workspace, Input: original.Input, AllowTools: original.AllowTools, WritePaths: original.WritePaths, Model: original.Model, StageModels: original.StageModels, NotifyMode: notifyMode}, original.ID)
|
||||
return r.start(protocol.Message{PipelineID: original.PipelineID, Version: version, RequestKey: request.RequestKey, RetryMode: mode, RetrySource: original.ID, RetryStage: request.RetryStage, RetryVisit: request.RetryVisit, RetryInput: request.RetryInput, Workspace: original.Workspace, Input: original.Input, AllowTools: original.AllowTools, WritePaths: original.WritePaths, Model: original.Model, StageModels: original.StageModels, NotifyMode: notifyMode, OutputFormat: original.OutputFormat}, original.ID)
|
||||
}
|
||||
|
||||
func (r *runner) cancel(id int64) error {
|
||||
@@ -1307,6 +1313,11 @@ func (r *runner) finishRunState(id int64, name, workspace, status, outcome, diag
|
||||
r.mu.Lock()
|
||||
c, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
if status == "succeeded" {
|
||||
if err := r.finalizeDeliverable(c, id, sequence, input); err != nil {
|
||||
status, outcome, diagnostic = "failed", "error", "deliverable contract: "+err.Error()
|
||||
}
|
||||
}
|
||||
if err := r.store.FinishRun(c, id, status, outcome, diagnostic, input); err != nil {
|
||||
log.Printf("finish run %d: %v", id, err)
|
||||
}
|
||||
@@ -1965,7 +1976,8 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
// 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}
|
||||
evidence := &protocol.SessionExport{SessionID: owner.ID, Backend: owner.Backend, Directory: owner.Directory, RecordedAt: time.Now().UTC().Format(time.RFC3339)}
|
||||
defer classifySessionExport(evidence)
|
||||
if owner.Backend != "v1" && owner.Backend != "v2" {
|
||||
evidence.Source = "unavailable"
|
||||
evidence.Diagnostic = "session export unavailable: harness has no native export path"
|
||||
@@ -1990,17 +2002,20 @@ func (r *runner) exportStageSession(ctx context.Context, owner pipeline.SessionO
|
||||
Provider: modelConfig.Provider,
|
||||
Model: modelConfig.Model,
|
||||
})
|
||||
evidence.Attempts = result.Attempts
|
||||
if err != nil {
|
||||
evidence.Source = "native_export"
|
||||
evidence.Diagnostic = stage.RedactEvidence(err.Error())
|
||||
return evidence
|
||||
}
|
||||
evidence.Source = result.Source
|
||||
evidence.Status = result.Status
|
||||
evidence.HTML = result.HTML
|
||||
evidence.HTMLBytes = result.HTMLBytes
|
||||
evidence.Messages = result.Messages
|
||||
evidence.Truncated = result.Truncated
|
||||
evidence.Diagnostic = result.Diagnostic
|
||||
verifySessionExportFile(evidence, artifactsDir)
|
||||
return evidence
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/stage"
|
||||
"os"
|
||||
)
|
||||
|
||||
func verifySessionExportFile(evidence *protocol.SessionExport, directory string) {
|
||||
if evidence.HTML == "" || evidence.HTMLBytes <= 0 {
|
||||
return
|
||||
}
|
||||
valid := false
|
||||
if evidence.HTML == stage.SessionHTMLFile {
|
||||
if root, err := os.OpenRoot(directory); err == nil {
|
||||
defer root.Close()
|
||||
info, err := root.Lstat(evidence.HTML)
|
||||
valid = err == nil && info.Mode().IsRegular() && info.Size() > 0 && info.Size() <= stage.SessionExportFileLimit && info.Size() == evidence.HTMLBytes
|
||||
}
|
||||
}
|
||||
if !valid {
|
||||
evidence.HTML = ""
|
||||
evidence.HTMLBytes = 0
|
||||
evidence.Diagnostic = "session readback returned, but exported file failed normal/nonempty/bounded verification"
|
||||
}
|
||||
}
|
||||
|
||||
// classifySessionExport describes evidence completeness, not stage success.
|
||||
// Empty exports prove only that a session ID was recorded, not that its turns
|
||||
// were captured. Keep that distinction even for historical records at read time.
|
||||
func classifySessionExport(evidence *protocol.SessionExport) {
|
||||
if evidence.Status == "empty" {
|
||||
return
|
||||
}
|
||||
switch {
|
||||
case evidence.Source == "unavailable":
|
||||
evidence.Status = "unavailable"
|
||||
case evidence.Messages == 0 && evidence.HTML == "" && evidence.Diagnostic != "":
|
||||
evidence.Status = "failed"
|
||||
case evidence.Messages == 0:
|
||||
evidence.Status = "empty"
|
||||
if evidence.Diagnostic == "" {
|
||||
evidence.Diagnostic = "session recorded but export contains no messages; full session evidence was not captured"
|
||||
}
|
||||
case evidence.Truncated || evidence.Diagnostic != "" || evidence.HTML == "" || evidence.HTMLBytes <= 0:
|
||||
evidence.Status = "partial"
|
||||
default:
|
||||
evidence.Status = "complete"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/stage"
|
||||
)
|
||||
|
||||
// repairSessionExport is runtime-owned and read-only to OpenCode. It never
|
||||
// resumes a session, runs a stage, changes a definition, or overwrites evidence.
|
||||
func (r *runner) repairSessionExport(ctx context.Context, id int64, sequence int) (*protocol.RunDetail, error) {
|
||||
r.exportRepairMu.Lock()
|
||||
defer r.exportRepairMu.Unlock()
|
||||
if id <= 0 || sequence <= 0 {
|
||||
return nil, fmt.Errorf("positive run ID and export_sequence are required")
|
||||
}
|
||||
r.mu.Lock()
|
||||
_, executing := r.active[id]
|
||||
r.mu.Unlock()
|
||||
if executing {
|
||||
return nil, fmt.Errorf("run execution cleanup is still active; repair deferred")
|
||||
}
|
||||
d, err := r.store.GetRun(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if d.Status == "running" || d.Status == "queued" || d.Status == "waiting" {
|
||||
return nil, fmt.Errorf("session export repair requires a settled run")
|
||||
}
|
||||
var step *protocol.RunStep
|
||||
for i := range d.Steps {
|
||||
if d.Steps[i].Sequence == sequence {
|
||||
step = &d.Steps[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
if step == nil || step.AgentActive {
|
||||
return nil, fmt.Errorf("no settled recorded session for this visit")
|
||||
}
|
||||
if len(step.SessionExportRepairs) >= 20 {
|
||||
return nil, fmt.Errorf("repair attempt limit reached for this visit")
|
||||
}
|
||||
owner, err := r.store.RepairSessionOwner(ctx, id, sequence)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("exact original session ownership metadata unavailable: %w", err)
|
||||
}
|
||||
active, err := r.store.ActiveSessionOwners(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, current := range active {
|
||||
if current.ID == owner.ID {
|
||||
return nil, fmt.Errorf("original session is still active; export repair deferred")
|
||||
}
|
||||
}
|
||||
evidence := &protocol.SessionExport{SessionID: owner.ID, Backend: owner.Backend, Directory: owner.Directory, RecordedAt: time.Now().UTC().Format(time.RFC3339), Source: "native_export"}
|
||||
// Capture and retain failures too. The diagnostic is evidence, not a new
|
||||
// run outcome, and cannot change the original stage/run success status.
|
||||
recordFailure := func(message string) (*protocol.RunDetail, error) {
|
||||
recordCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
|
||||
defer cancel()
|
||||
evidence.Status = "failed"
|
||||
evidence.Diagnostic = stage.RedactEvidence(message)
|
||||
if err := r.store.RecordSessionExportRepair(recordCtx, id, sequence, evidence); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return r.store.GetRun(recordCtx, id)
|
||||
}
|
||||
if owner.Backend != "v1" && owner.Backend != "v2" {
|
||||
return recordFailure("native export unavailable for original harness")
|
||||
}
|
||||
if len(step.Artifacts) >= maxArtifactFiles {
|
||||
return recordFailure("artifact inventory full; repair not attempted")
|
||||
}
|
||||
root, err := os.OpenRoot(r.artifactsRoot)
|
||||
if err != nil {
|
||||
return recordFailure(err.Error())
|
||||
}
|
||||
defer root.Close()
|
||||
run := strconv.FormatInt(id, 10)
|
||||
public := filepath.Join(run, "public")
|
||||
for _, dir := range []string{run, public} {
|
||||
info, err := root.Lstat(dir)
|
||||
if os.IsNotExist(err) {
|
||||
if err := root.Mkdir(dir, 0700); err != nil {
|
||||
return recordFailure(err.Error())
|
||||
}
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return recordFailure(err.Error())
|
||||
}
|
||||
if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
|
||||
return recordFailure("repair directory is not a normal directory")
|
||||
}
|
||||
}
|
||||
var nonce [16]byte
|
||||
if _, err := rand.Read(nonce[:]); err != nil {
|
||||
return recordFailure(err.Error())
|
||||
}
|
||||
name := fmt.Sprintf("session-repair-%d-%s.html", sequence, hex.EncodeToString(nonce[:]))
|
||||
// Stage.ExportSession is a runtime rendering helper, not a model stage.
|
||||
// No prompts/configs/definitions are involved. Export uses original owner.
|
||||
exportCtx, cancel := context.WithTimeout(ctx, stage.SessionExportTimeout)
|
||||
defer cancel()
|
||||
export := r.exportSession
|
||||
if export == nil {
|
||||
export = stage.ExportSession
|
||||
}
|
||||
result, err := export(exportCtx, stage.SessionExportRequest{SessionID: owner.ID, Backend: owner.Backend, Directory: owner.Directory, ArtifactsDir: filepath.Join(r.artifactsRoot, public), FileName: name, RunID: id, Sequence: sequence, Stage: step.Stage, Provider: step.Provider, Model: step.Model})
|
||||
persistCtx, persistCancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
|
||||
defer persistCancel()
|
||||
evidence.Attempts = result.Attempts
|
||||
if err != nil {
|
||||
return recordFailure(err.Error())
|
||||
}
|
||||
evidence.Status = result.Status
|
||||
evidence.Messages = result.Messages
|
||||
evidence.Truncated = result.Truncated
|
||||
evidence.Diagnostic = result.Diagnostic
|
||||
if result.HTML != "" {
|
||||
if result.HTML != name {
|
||||
return recordFailure("repair exporter returned an unexpected filename")
|
||||
}
|
||||
info, err := root.Lstat(filepath.Join(public, name))
|
||||
if err != nil {
|
||||
return recordFailure(err.Error())
|
||||
}
|
||||
if !info.Mode().IsRegular() || info.Size() <= 0 || info.Size() > stage.SessionExportFileLimit || result.Messages <= 0 {
|
||||
return recordFailure("repair export missing, empty, non-normal or oversized")
|
||||
}
|
||||
var used int64
|
||||
for _, file := range step.Artifacts {
|
||||
used += file.SizeBytes
|
||||
}
|
||||
if used+info.Size() > maxArtifactTotalBytes {
|
||||
return recordFailure("repaired export exceeds artifact inventory byte bounds")
|
||||
}
|
||||
evidence.HTML = "public/" + name
|
||||
evidence.HTMLBytes = info.Size()
|
||||
if err := r.store.RecordDeliverable(persistCtx, id, sequence, protocol.StageArtifact{Name: evidence.HTML, SizeBytes: info.Size(), ContentType: "text/html; charset=utf-8", URL: artifactURL(id, sequence, evidence.HTML)}); err != nil {
|
||||
return recordFailure(err.Error())
|
||||
}
|
||||
}
|
||||
classifySessionExport(evidence)
|
||||
if err := r.store.RecordSessionExportRepair(persistCtx, id, sequence, evidence); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return r.store.GetRun(persistCtx, id)
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/cli"
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/stage"
|
||||
)
|
||||
|
||||
func TestRuntimeSessionExportRepairPreservesOriginalAndUsesRecordedOwner(t *testing.T) {
|
||||
h, s, id := sessionExportRunner(t, "v2", func(stage.SessionExportRequest) (stage.SessionExportResult, error) {
|
||||
return stage.SessionExportResult{}, errors.New("export read failed")
|
||||
})
|
||||
// The synthetic executor does not own a real agent to settle. Model real
|
||||
// runtime cleanup explicitly before exercising the settled-only repair gate.
|
||||
if err := s.ConfirmRecoveredSession(context.Background(), pipeline.SessionOwner{RunID: id, ID: "ses_run"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
original, err := s.GetRun(context.Background(), id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before, _ := json.Marshal(original.Steps[0].SessionExport)
|
||||
if original.Steps[0].SessionExport.Status != "failed" {
|
||||
t.Fatalf("failure not durable: %+v", original.Steps[0].SessionExport)
|
||||
}
|
||||
owner, err := s.RepairSessionOwner(context.Background(), id, 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if owner.ID != "ses_run" || owner.Backend != "v2" || owner.Directory != original.Workspace {
|
||||
t.Fatalf("owner changed: %+v", owner)
|
||||
}
|
||||
public := filepath.Join(h.runner.artifactsRoot, "1", "public")
|
||||
if err := os.MkdirAll(public, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
old := filepath.Join(public, "session.html")
|
||||
if err := os.WriteFile(old, []byte("historical evidence"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// First repair also fails: it must remain durable without losing original.
|
||||
failed, err := h.runner.repairSessionExport(context.Background(), id, 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(failed.Steps[0].SessionExportRepairs) != 1 || failed.Steps[0].SessionExportRepairs[0].Status != "failed" {
|
||||
t.Fatalf("repair failure disappeared: %+v", failed.Steps)
|
||||
}
|
||||
// Restore readback availability; this is a fake native export CLI, not a
|
||||
// model stage, no generation/resumption/definition mutation is performed.
|
||||
sessionExportCLI(t)
|
||||
h.runner.exportSession = nil
|
||||
repaired, err := h.runner.repairSessionExport(context.Background(), id, 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if repaired.Status != original.Status || len(repaired.Steps[0].SessionExportRepairs) != 2 {
|
||||
t.Fatalf("repair changed run outcome: %+v", repaired)
|
||||
}
|
||||
latest := repaired.Steps[0].SessionExportRepairs[1]
|
||||
if latest.Status != "complete" || latest.Messages != 2 || latest.SessionID != owner.ID || latest.Backend != owner.Backend || !strings.HasPrefix(latest.HTML, "public/session-repair-1-") {
|
||||
t.Fatalf("repair not recorded: %+v", latest)
|
||||
}
|
||||
after, _ := json.Marshal(repaired.Steps[0].SessionExport)
|
||||
if string(before) != string(after) {
|
||||
t.Fatal("original evidence overwritten")
|
||||
}
|
||||
body, _ := os.ReadFile(old)
|
||||
if string(body) != "historical evidence" {
|
||||
t.Fatal("historical export overwritten")
|
||||
}
|
||||
body, err = os.ReadFile(filepath.Join(h.runner.artifactsRoot, "1", latest.HTML))
|
||||
if err != nil || len(body) == 0 {
|
||||
t.Fatalf("repair file missing: %v", err)
|
||||
}
|
||||
if _, ok := artifactNamed(repaired.Steps[0].Artifacts, latest.HTML); !ok {
|
||||
t.Fatal("repaired export not discoverable")
|
||||
}
|
||||
// A second successful attempt is a new version, never an overwrite.
|
||||
again, err := h.runner.repairSessionExport(context.Background(), id, 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if again.Steps[0].SessionExportRepairs[2].HTML == latest.HTML {
|
||||
t.Fatal("repair reused filename")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuntimeRepairRejectsUnrecordedAndActiveVisits(t *testing.T) {
|
||||
h, _, id := sessionExportRunner(t, "v2", func(stage.SessionExportRequest) (stage.SessionExportResult, error) {
|
||||
return stage.SessionExportResult{}, errors.New("unavailable")
|
||||
})
|
||||
for _, sequence := range []int{0, 1, 2} {
|
||||
if _, err := h.runner.repairSessionExport(context.Background(), id, sequence); err == nil {
|
||||
t.Fatalf("invalid visit %d accepted", sequence)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCLIRepairSessionExportUsesRuntimeProtocol(t *testing.T) {
|
||||
t.Setenv("PIPELINES_HARNESS_CONFIG", filepath.Join(t.TempDir(), "harnesses.json"))
|
||||
h, s, id := sessionExportRunner(t, "v2", func(stage.SessionExportRequest) (stage.SessionExportResult, error) {
|
||||
return stage.SessionExportResult{}, errors.New("fixture readback unavailable")
|
||||
})
|
||||
if err := s.ConfirmRecoveredSession(context.Background(), pipeline.SessionOwner{RunID: id, ID: "ses_run"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sessionExportCLI(t)
|
||||
h.runner.exportSession = nil
|
||||
server := httptest.NewServer(h)
|
||||
defer server.Close()
|
||||
var out bytes.Buffer
|
||||
app := cli.App{Out: &out, Err: &out, In: strings.NewReader("")}
|
||||
err := app.Run(context.Background(), []string{"--url", "ws" + strings.TrimPrefix(server.URL, "http") + "/connect", "repair-session-export", "1", "1", "--json"})
|
||||
if err != nil {
|
||||
t.Fatalf("repair command failed: %v %s", err, out.String())
|
||||
}
|
||||
var evidence struct {
|
||||
Status string `json:"status"`
|
||||
SessionID string `json:"session_id"`
|
||||
HTML string `json:"html"`
|
||||
}
|
||||
if err := json.Unmarshal(out.Bytes(), &evidence); err != nil || evidence.Status != "complete" || evidence.SessionID != "ses_run" || !strings.HasPrefix(evidence.HTML, "public/session-repair-1-") {
|
||||
t.Fatalf("wrong repair reply: %+v %v %s", evidence, err, out.String())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSessionExportCompleteness(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
evidence protocol.SessionExport
|
||||
want string
|
||||
}{
|
||||
{protocol.SessionExport{Source: "native_export", HTML: "session.html", HTMLBytes: 100}, "empty"},
|
||||
{protocol.SessionExport{Source: "native_export", Diagnostic: "export failed"}, "failed"},
|
||||
{protocol.SessionExport{Source: "native_export", Messages: 2, HTML: "session.html", HTMLBytes: 100, Truncated: true}, "partial"},
|
||||
{protocol.SessionExport{Source: "native_export", Messages: 2, HTML: "session.html", HTMLBytes: 100}, "complete"},
|
||||
{protocol.SessionExport{Source: "unavailable"}, "unavailable"},
|
||||
} {
|
||||
classifySessionExport(&tc.evidence)
|
||||
if tc.evidence.Status != tc.want {
|
||||
t.Fatalf("%+v want %s", tc.evidence, tc.want)
|
||||
}
|
||||
if tc.want == "empty" && tc.evidence.Diagnostic == "" {
|
||||
t.Fatal("empty export has no warning")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuntimeSessionExportFileVerificationDoesNotClaimMissingEvidence(t *testing.T) {
|
||||
for _, kind := range []string{"missing", "empty", "symlink", "normal"} {
|
||||
t.Run(kind, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "session.html")
|
||||
switch kind {
|
||||
case "empty":
|
||||
if err := os.WriteFile(path, nil, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case "normal":
|
||||
if err := os.WriteFile(path, []byte("html"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case "symlink":
|
||||
if err := os.Symlink(filepath.Join(t.TempDir(), "outside"), path); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
evidence := &protocol.SessionExport{Source: "native_export", Messages: 2, HTML: "session.html", HTMLBytes: 4}
|
||||
verifySessionExportFile(evidence, dir)
|
||||
classifySessionExport(evidence)
|
||||
if (evidence.Status == "complete") != (kind == "normal") {
|
||||
t.Fatalf("%s: %+v", kind, evidence)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -276,9 +276,12 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
|
||||
response.Error = err.Error()
|
||||
}
|
||||
}
|
||||
} else if runs != nil && (request.Type == protocol.RunPipeline || request.Type == protocol.RetryRun || request.Type == protocol.ListRuns || request.Type == protocol.GetRun || request.Type == protocol.CancelRun || request.Type == protocol.DecideRun || request.Type == protocol.SetRunTitle || request.Type == protocol.GetRunEvidence) {
|
||||
} else if runs != nil && (request.Type == protocol.RunPipeline || request.Type == protocol.RetryRun || request.Type == protocol.ListRuns || request.Type == protocol.GetRun || request.Type == protocol.CancelRun || request.Type == protocol.DecideRun || request.Type == protocol.SetRunTitle || request.Type == protocol.GetRunEvidence || request.Type == protocol.RepairSessionExport) {
|
||||
var err error
|
||||
switch request.Type {
|
||||
case protocol.RepairSessionExport:
|
||||
response.Type = protocol.Run
|
||||
response.RunDetail, err = runs.repairSessionExport(ctx, request.RunID, request.ExportSequence)
|
||||
case protocol.GetRunEvidence:
|
||||
response.Type = protocol.RunEvidence
|
||||
response.Evidence, err = runs.evidence(ctx, request.RunID)
|
||||
|
||||
Reference in New Issue
Block a user