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:
2026-10-17 19:40:43 +01:00
parent b568c86d13
commit 58c6b9b7c6
16 changed files with 1710 additions and 24 deletions
+452
View File
@@ -0,0 +1,452 @@
package stage
import (
"bytes"
"context"
"fmt"
"html"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"git.a-wan.net/alan/pipelines/internal/opencode"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// Session file export bounds. A stage's session is written under its own
// artifacts directory in markdown and html so the existing artifact listing and
// serving paths find it with no special casing. The source read is capped at
// SessionExportSourceLimit and each rendered file at SessionExportFileLimit, so
// the pair adds at most ~4 MiB per step, inside the artifact scan limits.
const (
SessionMarkdownFile = "session.md"
SessionHTMLFile = "session.html"
// SessionExportSourceLimit is the native session read cap; it is the one
// opencode.MaxSessionExport value, not a second copy.
SessionExportSourceLimit = opencode.MaxSessionExport
SessionExportFileLimit = 2 << 20
SessionExportTimeout = 10 * time.Second
)
// SessionExportRequest names the stage session to export and the evidence the
// rendered files carry. Directory is the session's workspace (the directory the
// export CLI runs in); ArtifactsDir is the step's artifacts directory.
type SessionExportRequest struct {
SessionID string
Backend string
Directory string
ArtifactsDir string
RunID int64
Sequence int
Stage string
Provider string
Model string
}
// SessionExportResult is the outcome of one session export. Markdown/HTML are
// the written file names, their byte sizes, the decoded message count, the
// source, whether either file or the source was truncated and a sanitized
// diagnostic (for example a skipped overwrite).
type SessionExportResult struct {
Markdown string
HTML string
MarkdownBytes int64
HTMLBytes int64
Messages int
Source string
Truncated bool
Diagnostic string
}
const (
// sessionExportSource is the recorded source of a native-export readback.
sessionExportSource = "native_export"
// markdownTruncationBanner and htmlTruncationBanner are the visible labels a
// truncated export carries near its start and end so it is never mistaken for
// the whole session.
markdownTruncationBanner = "\n> **TRUNCATED**: this exported session is not the whole session; it was cut at the export size cap.\n"
htmlTruncationBanner = "<p style=\"padding:0.5rem;border:1px solid #b00;color:#900\"><strong>TRUNCATED</strong>: this exported session is not the whole session; it was cut at the export size cap.</p>\n"
)
// ExportSession reads the stage's session read-only through the native export
// path, renders it to bounded markdown and html and writes both files
// atomically into the step's artifacts directory, refusing to overwrite an
// existing file. It returns a sanitized error and writes nothing when the read
// fails; it never mutates, resumes, interrupts or deletes the session.
func ExportSession(ctx context.Context, request SessionExportRequest) (SessionExportResult, error) {
if !opencode.ValidSessionID(request.SessionID) {
return SessionExportResult{}, fmt.Errorf("session export: invalid session ID")
}
if request.ArtifactsDir == "" {
return SessionExportResult{}, fmt.Errorf("session export: no artifacts directory")
}
session, err := opencode.ExportSession(ctx, opencode.Executable(), request.Directory, request.Backend, request.SessionID)
if err != nil {
return SessionExportResult{}, fmt.Errorf("session export: %s", RedactEvidence(err.Error()))
}
markdown, markdownTruncated := renderSessionMarkdown(session, request)
htmlDoc, htmlTruncated := renderSessionHTML(session, request)
result := SessionExportResult{
Markdown: SessionMarkdownFile,
HTML: SessionHTMLFile,
Messages: len(session.Messages),
Source: sessionExportSource,
Truncated: session.Truncated || markdownTruncated || htmlTruncated,
Diagnostic: "",
}
written, diagnostic, err := writeSessionPair(request.ArtifactsDir, []sessionFile{
{name: SessionMarkdownFile, data: []byte(markdown)},
{name: SessionHTMLFile, data: []byte(htmlDoc)},
})
if err != nil {
return SessionExportResult{}, fmt.Errorf("session export: %s", RedactEvidence(err.Error()))
}
if written[0] {
result.MarkdownBytes = int64(len(markdown))
}
if written[1] {
result.HTMLBytes = int64(len(htmlDoc))
}
result.Diagnostic = diagnostic
return result, nil
}
// sessionFile is one rendered file to write into the artifacts directory.
type sessionFile struct {
name string
data []byte
}
// writeSessionPair stages every rendered file to a temporary file, then renames
// each into place, so a failure before the renames leaves no partial session.md
// or session.html behind. An existing target is never overwritten: its file is
// skipped and the reason is returned as a diagnostic.
func writeSessionPair(dir string, files []sessionFile) ([]bool, string, error) {
written := make([]bool, len(files))
temps := make([]string, len(files))
cleanup := func() {
for _, tmp := range temps {
if tmp != "" {
_ = os.Remove(tmp)
}
}
}
var skipped []string
for i, file := range files {
target := filepath.Join(dir, file.name)
if _, err := os.Lstat(target); err == nil {
skipped = append(skipped, file.name)
continue
} else if !os.IsNotExist(err) {
cleanup()
return written, "", err
}
tmp, err := os.CreateTemp(dir, "."+file.name+".tmp-*")
if err != nil {
cleanup()
return written, "", err
}
temps[i] = tmp.Name()
if _, err := tmp.Write(file.data); err != nil {
tmp.Close()
cleanup()
return written, "", err
}
if err := tmp.Close(); err != nil {
cleanup()
return written, "", err
}
}
for i, file := range files {
if temps[i] == "" {
continue
}
if err := os.Rename(temps[i], filepath.Join(dir, file.name)); err != nil {
cleanup()
return written, "", err
}
written[i] = true
}
diagnostic := ""
if len(skipped) > 0 {
diagnostic = "existing " + strings.Join(skipped, ", ") + " was not overwritten"
}
return written, diagnostic, nil
}
// sessionMeta is one metadata row the rendered files carry.
type sessionMeta struct {
label string
value string
}
// sessionMetadata is the run/step/session identity both renderers show, so a
// file is self-describing without the run record.
func sessionMetadata(session opencode.ExportedSession, request SessionExportRequest) []sessionMeta {
meta := []sessionMeta{
{"run", strconv.FormatInt(request.RunID, 10)},
{"step", strconv.Itoa(request.Sequence)},
{"stage", request.Stage},
{"session", session.ID},
{"backend", session.Backend},
{"messages", strconv.Itoa(len(session.Messages))},
{"source", sessionExportSource},
{"truncated", strconv.FormatBool(session.Truncated)},
{"exported_at", time.Now().UTC().Format(time.RFC3339)},
}
if request.Provider != "" {
meta = append(meta, sessionMeta{"provider", request.Provider})
}
if request.Model != "" {
meta = append(meta, sessionMeta{"model", request.Model})
}
return meta
}
// renderSessionMarkdown renders the session as bounded markdown. The second
// result reports whether the rendered file itself was cut at the cap.
func renderSessionMarkdown(session opencode.ExportedSession, request SessionExportRequest) (string, bool) {
var header bytes.Buffer
header.WriteString("# Stage session export\n\n")
for _, meta := range sessionMetadata(session, request) {
fmt.Fprintf(&header, "- %s: %s\n", meta.label, meta.value)
}
header.WriteString("\n")
var body bytes.Buffer
if len(session.Messages) == 0 {
body.WriteString("_No messages were recorded for this session._\n\n")
}
for i, message := range session.Messages {
renderMarkdownMessage(&body, i+1, message)
}
return assembleSessionFile(header.String(), body.String(), session.Truncated, markdownTruncationBanner, markdownTruncationBanner)
}
// renderMarkdownMessage renders one turn with its role and parts.
func renderMarkdownMessage(out *bytes.Buffer, index int, message opencode.ExportedMessage) {
role := message.Role
if role == "" {
role = "unknown"
}
fmt.Fprintf(out, "## %d. %s\n\n", index, role)
var details bytes.Buffer
if message.ID != "" {
fmt.Fprintf(&details, "- id: %s\n", message.ID)
}
if message.Model != "" {
fmt.Fprintf(&details, "- model: %s\n", message.Model)
}
if message.Agent != "" {
fmt.Fprintf(&details, "- agent: %s\n", message.Agent)
}
if message.CreatedAt != 0 {
fmt.Fprintf(&details, "- created_at: %d\n", message.CreatedAt)
}
if details.Len() > 0 {
out.WriteString(details.String())
out.WriteString("\n")
}
for _, part := range message.Parts {
renderMarkdownPart(out, part)
}
}
// renderMarkdownPart renders one content element. Unknown types are rendered as
// their raw JSON rather than dropped.
func renderMarkdownPart(out *bytes.Buffer, part opencode.ExportedPart) {
switch part.Type {
case protocol.ChatPartText:
out.WriteString(part.Text)
out.WriteString("\n\n")
case protocol.ChatPartReasoning:
fmt.Fprintf(out, "_reasoning_\n\n%s\n\n", part.Text)
case protocol.ChatPartTool:
renderMarkdownTool(out, part)
default:
label := part.Type
if label == "" {
label = "unknown"
}
fmt.Fprintf(out, "### %s\n\n", label)
raw := part.Raw
if len(raw) == 0 {
raw = []byte("{}")
}
fence := dynamicFence(string(raw))
fmt.Fprintf(out, "%sjson\n%s\n%s\n\n", fence, strings.TrimSpace(string(raw)), fence)
}
}
// renderMarkdownTool renders a tool call with its name, status, input, result
// and error.
func renderMarkdownTool(out *bytes.Buffer, part opencode.ExportedPart) {
name := part.Name
if name == "" {
name = part.ID
}
status := ""
if part.State != nil {
status = part.State.Status
}
fmt.Fprintf(out, "### tool: %s (%s)\n\n", name, status)
if part.State == nil {
return
}
if len(part.State.Input) > 0 {
input := string(part.State.Input)
fence := dynamicFence(input)
fmt.Fprintf(out, "input:\n\n%sjson\n%s\n%s\n\n", fence, strings.TrimSpace(input), fence)
}
for _, content := range part.State.Content {
if content.Text != "" {
out.WriteString(content.Text)
out.WriteString("\n\n")
} else if content.URI != "" {
fmt.Fprintf(out, "- %s (%s)\n", content.URI, content.Mime)
}
}
if part.State.Error != nil {
fmt.Fprintf(out, "error: %s\n\n", part.State.Error.Message)
}
}
// renderSessionHTML renders the session as bounded html, escaping every session
// text value. The second result reports whether the rendered file was cut.
func renderSessionHTML(session opencode.ExportedSession, request SessionExportRequest) (string, bool) {
var header bytes.Buffer
header.WriteString("<!doctype html>\n<html lang=\"en\"><head><meta charset=\"utf-8\">")
header.WriteString("<title>Stage session export</title>")
header.WriteString("<style>body{font-family:system-ui,sans-serif;margin:1rem}pre{overflow:auto;background:#f6f6f6;padding:0.5rem}dl{display:grid;grid-template-columns:max-content 1fr;gap:0 1rem}</style>")
header.WriteString("</head><body>\n<h1>Stage session export</h1>\n<dl>\n")
for _, meta := range sessionMetadata(session, request) {
fmt.Fprintf(&header, "<dt>%s</dt><dd>%s</dd>\n", html.EscapeString(meta.label), html.EscapeString(meta.value))
}
header.WriteString("</dl>\n")
var body bytes.Buffer
if len(session.Messages) == 0 {
body.WriteString("<p><em>No messages were recorded for this session.</em></p>\n")
}
for i, message := range session.Messages {
renderHTMLMessage(&body, i+1, message)
}
body.WriteString("</body></html>\n")
trailing := htmlTruncationBanner + "</body></html>\n"
return assembleSessionFile(header.String(), body.String(), session.Truncated, htmlTruncationBanner, trailing)
}
// renderHTMLMessage renders one turn with its role and parts.
func renderHTMLMessage(out *bytes.Buffer, index int, message opencode.ExportedMessage) {
role := message.Role
if role == "" {
role = "unknown"
}
fmt.Fprintf(out, "<h2>%d. %s</h2>\n", index, html.EscapeString(role))
fmt.Fprintf(out, "<p class=\"meta\">id: %s | model: %s | agent: %s | created_at: %d</p>\n",
html.EscapeString(message.ID), html.EscapeString(message.Model), html.EscapeString(message.Agent), message.CreatedAt)
for _, part := range message.Parts {
renderHTMLPart(out, part)
}
}
// renderHTMLPart renders one content element, escaping all session text.
func renderHTMLPart(out *bytes.Buffer, part opencode.ExportedPart) {
switch part.Type {
case protocol.ChatPartText:
fmt.Fprintf(out, "<pre class=\"text\">%s</pre>\n", html.EscapeString(part.Text))
case protocol.ChatPartReasoning:
fmt.Fprintf(out, "<details><summary>reasoning</summary><pre>%s</pre></details>\n", html.EscapeString(part.Text))
case protocol.ChatPartTool:
renderHTMLTool(out, part)
default:
label := part.Type
if label == "" {
label = "unknown"
}
raw := part.Raw
if len(raw) == 0 {
raw = []byte("{}")
}
fmt.Fprintf(out, "<h3>%s</h3>\n<pre>%s</pre>\n", html.EscapeString(label), html.EscapeString(strings.TrimSpace(string(raw))))
}
}
// renderHTMLTool renders a tool call with its name, status, input, result and
// error, escaping every value.
func renderHTMLTool(out *bytes.Buffer, part opencode.ExportedPart) {
name := part.Name
if name == "" {
name = part.ID
}
status := ""
if part.State != nil {
status = part.State.Status
}
fmt.Fprintf(out, "<h3>tool: %s (%s)</h3>\n", html.EscapeString(name), html.EscapeString(status))
if part.State == nil {
return
}
if len(part.State.Input) > 0 {
fmt.Fprintf(out, "<pre class=\"input\">%s</pre>\n", html.EscapeString(strings.TrimSpace(string(part.State.Input))))
}
for _, content := range part.State.Content {
if content.Text != "" {
fmt.Fprintf(out, "<pre class=\"output\">%s</pre>\n", html.EscapeString(content.Text))
} else if content.URI != "" {
fmt.Fprintf(out, "<p>%s (%s)</p>\n", html.EscapeString(content.URI), html.EscapeString(content.Mime))
}
}
if part.State.Error != nil {
fmt.Fprintf(out, "<p class=\"error\">error: %s</p>\n", html.EscapeString(part.State.Error.Message))
}
}
// assembleSessionFile joins the metadata header and the rendered body, adding
// the visible truncation banners near the start and the end when the source was
// already truncated or when the rendered output itself had to be cut, and never
// returning more than SessionExportFileLimit bytes. The second result reports
// whether the rendered output was cut.
func assembleSessionFile(header, body string, sourceTruncated bool, leading, trailing string) (string, bool) {
limit := SessionExportFileLimit
rendered := false
truncated := sourceTruncated
if len(header)+len(body)+len(leading)+len(trailing) > limit {
rendered = true
truncated = true
room := limit - len(header) - len(leading) - len(trailing)
if room < 0 {
room = 0
}
if len(body) > room {
body, _ = truncateRunes(body, room)
}
}
var out strings.Builder
out.Grow(min(limit, len(header)+len(body)+2*len(leading)))
out.WriteString(header)
if truncated {
out.WriteString(leading)
}
out.WriteString(body)
if truncated {
out.WriteString(trailing)
}
result := out.String()
if len(result) > limit {
result, _ = truncateRunes(result, limit)
}
return result, rendered
}
// dynamicFence returns a run of at least three backticks longer than any run in
// text, so markdown content that itself contains a fence cannot break out.
func dynamicFence(text string) string {
fence := "```"
for strings.Contains(text, fence) {
fence += "`"
}
return fence
}
+206
View File
@@ -0,0 +1,206 @@
package stage
import (
"context"
"os"
"path/filepath"
"strings"
"testing"
"git.a-wan.net/alan/pipelines/internal/opencode"
)
// sessionCLI writes a fake `opencode` CLI that answers the session export
// invocation (v1 `export <id>` or v2 `session export <id>`) with body and points
// PIPELINES_OPENCODE at it, so ExportSession runs without a service.
func sessionCLI(t *testing.T, id, body string) {
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\" = " + id + " ] || exit 9\n" +
"cat <<'EOF'\n" + body + "\nEOF\n"
if err := os.WriteFile(path, []byte(script), 0700); err != nil {
t.Fatal(err)
}
t.Setenv("PIPELINES_OPENCODE", path)
}
func sessionBody() string {
return `{"info":{"id":"ses_ok"},"messages":[` +
`{"info":{"id":"m1","role":"user"},"text":"please run"},` +
`{"info":{"id":"m2","role":"assistant","modelID":"gpt"},"parts":[` +
`{"type":"text","text":"hello <b>&\" world"},` +
`{"type":"reasoning","text":"thinking hard"},` +
`{"type":"tool","name":"read","state":{"status":"completed","input":{"path":"a.go"},"content":[{"type":"text","text":"tool output"}]}},` +
`{"type":"file","uri":"file:///tmp/x"}]}]}`
}
func sessionRequest(dir string) SessionExportRequest {
return SessionExportRequest{
SessionID: "ses_ok", Backend: "v2", Directory: dir, ArtifactsDir: dir,
RunID: 7, Sequence: 2, Stage: "implementer", Provider: "prov", Model: "gpt",
}
}
func TestExportSessionWritesBothFilesWithRealContent(t *testing.T) {
dir := t.TempDir()
sessionCLI(t, "ses_ok", sessionBody())
result, err := ExportSession(context.Background(), sessionRequest(dir))
if err != nil {
t.Fatal(err)
}
if result.Markdown != "session.md" || result.HTML != "session.html" {
t.Fatalf("file names wrong: %+v", result)
}
if result.Messages != 2 || result.Source != "native_export" || result.Truncated {
t.Fatalf("evidence wrong: %+v", result)
}
markdown, err := os.ReadFile(filepath.Join(dir, SessionMarkdownFile))
if err != nil {
t.Fatal(err)
}
htmlDoc, err := os.ReadFile(filepath.Join(dir, SessionHTMLFile))
if err != nil {
t.Fatal(err)
}
if result.MarkdownBytes != int64(len(markdown)) || result.HTMLBytes != int64(len(htmlDoc)) {
t.Fatalf("sizes wrong: %+v", result)
}
for _, want := range []string{"hello <b>&\" world", "thinking hard", "tool: read (completed)", "tool output", `{"path":"a.go"}`, "please run"} {
if !strings.Contains(string(markdown), want) {
t.Fatalf("markdown missing %q", want)
}
}
if !strings.Contains(string(markdown), "file:///tmp/x") {
t.Fatal("markdown dropped the unknown 'file' part")
}
// HTML must escape session text and still carry the tool detail.
if strings.Contains(string(htmlDoc), "<b>") {
t.Fatal("html rendered unescaped session text")
}
for _, want := range []string{"&lt;b&gt;", "&amp;", "tool: read (completed)", "tool output"} {
if !strings.Contains(string(htmlDoc), want) {
t.Fatalf("html missing %q", want)
}
}
// No temporary file may survive a successful write.
temps, _ := filepath.Glob(filepath.Join(dir, ".*tmp*"))
if len(temps) != 0 {
t.Fatalf("temporary files left behind: %v", temps)
}
}
func TestExportSessionRenderedTruncationBannerInBothFiles(t *testing.T) {
// A source under the read cap but whose rendering exceeds the file cap.
huge := strings.Repeat("line of text\n", SessionExportFileLimit/7)
session := opencode.ExportedSession{
ID: "ses_ok",
Backend: "v2",
Messages: []opencode.ExportedMessage{{
Role: "assistant",
Parts: []opencode.ExportedPart{{Type: "text", Text: huge}},
}},
}
markdown, mdTruncated := renderSessionMarkdown(session, sessionRequest(t.TempDir()))
htmlDoc, htmlTruncated := renderSessionHTML(session, sessionRequest(t.TempDir()))
if !mdTruncated || !htmlTruncated {
t.Fatalf("rendered truncation not reported: md=%v html=%v", mdTruncated, htmlTruncated)
}
for name, content := range map[string]string{"markdown": markdown, "html": htmlDoc} {
if len(content) > SessionExportFileLimit {
t.Fatalf("%s exceeds cap: %d", name, len(content))
}
if strings.Count(content, "TRUNCATED") < 2 {
t.Fatalf("%s lacks a leading and trailing truncation banner", name)
}
}
}
func TestExportSessionSourceTruncationIsLabelledNotWhole(t *testing.T) {
session := opencode.ExportedSession{
ID: "ses_ok",
Backend: "v2",
Truncated: true,
Messages: []opencode.ExportedMessage{{Role: "assistant", Parts: []opencode.ExportedPart{{Type: "text", Text: "partial"}}}},
}
markdown, _ := renderSessionMarkdown(session, sessionRequest(t.TempDir()))
if strings.Count(markdown, "TRUNCATED") < 2 {
t.Fatalf("source truncation must be labelled at both ends:\n%s", markdown)
}
if !strings.Contains(markdown, "truncated: true") {
t.Fatal("metadata must record truncation")
}
}
func TestExportSessionEmptySessionIsHonest(t *testing.T) {
session := opencode.ExportedSession{ID: "ses_ok", Backend: "v2"}
markdown, _ := renderSessionMarkdown(session, sessionRequest(t.TempDir()))
if !strings.Contains(markdown, "messages: 0") || !strings.Contains(markdown, "No messages were recorded") {
t.Fatalf("empty session must be honest, not fabricated:\n%s", markdown)
}
}
func TestExportSessionRefusesOverwrite(t *testing.T) {
dir := t.TempDir()
sessionCLI(t, "ses_ok", sessionBody())
existing := filepath.Join(dir, SessionMarkdownFile)
if err := os.WriteFile(existing, []byte("keep me"), 0600); err != nil {
t.Fatal(err)
}
result, err := ExportSession(context.Background(), sessionRequest(dir))
if err != nil {
t.Fatal(err)
}
kept, err := os.ReadFile(existing)
if err != nil || string(kept) != "keep me" {
t.Fatalf("existing session.md was overwritten: %q %v", kept, err)
}
if result.MarkdownBytes != 0 || !strings.Contains(result.Diagnostic, "not overwritten") {
t.Fatalf("skip reason not recorded: %+v", result)
}
if _, err := os.Stat(filepath.Join(dir, SessionHTMLFile)); err != nil {
t.Fatalf("html should still be written: %v", err)
}
}
func TestExportSessionFailureWritesNoFiles(t *testing.T) {
dir := t.TempDir()
t.Setenv("PIPELINES_OPENCODE", filepath.Join(t.TempDir(), "absent-opencode"))
_, err := ExportSession(context.Background(), sessionRequest(dir))
if err == nil {
t.Fatal("export failure must return an error")
}
entries, err := os.ReadDir(dir)
if err != nil {
t.Fatal(err)
}
if len(entries) != 0 {
t.Fatalf("failure wrote files: %v", entries)
}
}
func TestExportSessionRejectsInvalidIDAndMissingDirectory(t *testing.T) {
sessionCLI(t, "ses_ok", sessionBody())
bad := sessionRequest(t.TempDir())
bad.SessionID = "not-a-session"
if _, err := ExportSession(context.Background(), bad); err == nil {
t.Fatal("invalid session id accepted")
}
missing := sessionRequest(t.TempDir())
missing.ArtifactsDir = ""
if _, err := ExportSession(context.Background(), missing); err == nil {
t.Fatal("missing artifacts directory accepted")
}
}
// TestAssembleSessionFileNeverExceedsLimit confirms the final guard bounds even
// a pathological header.
func TestAssembleSessionFileNeverExceedsLimit(t *testing.T) {
header := strings.Repeat("h", SessionExportFileLimit+10)
body := strings.Repeat("b", 100)
got, _ := assembleSessionFile(header, body, false, markdownTruncationBanner, markdownTruncationBanner)
if len(got) > SessionExportFileLimit {
t.Fatalf("assembled file exceeds cap: %d", len(got))
}
}