Record and serve per-stage artifacts

Every agent stage now writes into a per-run/step artifacts directory under
the data dir (<data>/artifacts/<run>/<step>), passed to Pi as
PIPELINES_ARTIFACTS_DIR, exposed on the OpenCode client env seam, and stated
in the agent prompt boilerplate so agents save images, screenshots, reports
and logs there.

After each step the server scans that directory with a bounded, symlink- and
traversal-safe inventory (os.OpenRoot + Lstat + O_NOFOLLOW) recording name,
size_bytes, content type (extension then 512-byte sniff fallback) and URL,
enforcing max files, per-file bytes and total bytes while counting skipped
and truncated entries. A missing, unreadable or oversized directory yields
only a best-effort diagnostic and never changes the step outcome.

The list is carried on protocol.RunStep as Artifacts []StageArtifact plus
skipped/truncated counters (omitempty, backwards compatible), persisted in a
new step_artifacts table keyed (run_id, sequence) alongside the
notifications/file-changes tables and loaded by GetRun.

GET /artifacts/{run}/{step}/{name} on the existing handler serves the bytes
with http.ServeContent, so Content-Type, Content-Length, HEAD and Range
(206/416) come from the stdlib; unknown runs/steps, absolute paths,
traversal, symlink escapes and non-regular files are refused.

The TUI lists each selected step's artifacts (name + human size) in the
retained-evidence section and adds an artifacts summary in the style of the
file-changes summary. Adds docs/stage-artifacts.md linked from README and an
artifacts subsection to the packaged operations skill reference.

Tests cover the scan records and caps, missing/oversized directories,
HTTP HEAD/Range/traversal/symlink/unknown refusals and protocol round-trips.
This commit is contained in:
2026-10-15 17:51:18 +01:00
parent 370eaaed1f
commit 0f5a188c6a
19 changed files with 905 additions and 49 deletions
+11
View File
@@ -124,6 +124,7 @@ func (c *AgentClient) Generate(ctx context.Context, config ModelConfig, prompt s
}
}
prompt += "\nRun directory: " + c.Directory + ". Edit scope: " + editPaths + ". There is no implicit language or extension restriction; explicit stage permissions and run scopes are authoritative. Select verification commands from the actual repository and permitted commands. Older generic language-specific boilerplate is not a runtime permission policy. Do not invent a missing file-list or manual-approval requirement. Do not infer that later stages lack editing because this stage is read-only. Respect this stage's role and available tools. Work in the run directory; do not modify unrelated locations or Pipelines history/configuration. Do not delegate. Commit/push only when the task explicitly requests it. Final response must be only the stage result JSON."
prompt += artifactsPrompt(c.ArtifactsDir)
if c.Policy.Shell != nil {
prompt += "\nPermitted shell commands: " + strings.Join(c.Policy.Shell, "; ")
}
@@ -158,6 +159,16 @@ func (c *AgentClient) Generate(ctx context.Context, config ModelConfig, prompt s
return text, err
}
// artifactsPrompt is the general, technology-neutral boilerplate that tells an
// agent stage where to save the files it produces. It is empty when the runtime
// did not provide a directory, so existing prompts are unchanged without one.
func artifactsPrompt(directory string) string {
if directory == "" {
return ""
}
return "\nArtifacts directory: " + directory + ". Save any artifacts you produce - images, screenshots, reports, logs - into that directory; they are attached to this stage."
}
// settleV2Usage issues one bounded final session-aggregate read and records the
// reported usage on the existing per-session ledger. It is best-effort: any read
// or validation failure leaves the snapshot unknown rather than failing the run.
+35
View File
@@ -0,0 +1,35 @@
package stage
import (
"strings"
"testing"
)
func TestPiEnvironmentCarriesArtifactsDirectory(t *testing.T) {
env := piEnvironment("/tmp/ref", "/data/artifacts/7/3")
want := ArtifactsEnv + "=/data/artifacts/7/3"
for _, entry := range env {
if entry == want {
return
}
}
t.Fatalf("Pi environment missing %q", want)
}
func TestPiEnvironmentOmitsEmptyArtifactsDirectory(t *testing.T) {
for _, entry := range piEnvironment("/tmp/ref", "") {
if strings.HasPrefix(entry, ArtifactsEnv+"=") {
t.Fatalf("unexpected artifacts entry %q", entry)
}
}
}
func TestArtifactsPromptStatesDirectory(t *testing.T) {
prompt := artifactsPrompt("/data/artifacts/1/2")
if !strings.Contains(prompt, "Artifacts directory: /data/artifacts/1/2") {
t.Fatalf("prompt missing artifacts directory: %q", prompt)
}
if artifactsPrompt("") != "" {
t.Fatal("empty directory must add no boilerplate")
}
}
+17 -4
View File
@@ -23,10 +23,16 @@ const maxModelResponse = 1 << 20
// A fresh location-scoped session avoids unrelated user conversation history and
// is retained for debugging. Generation is text-only: no agent tools are run.
type OpenCodeClient struct {
Directory string // empty uses the pipeline server's working directory
Backend string
Reference string
FormatAudit string
Directory string // empty uses the pipeline server's working directory
Backend string
Reference string
FormatAudit string
// ArtifactsDir is exported to the spawned OpenCode CLI as
// PIPELINES_ARTIFACTS_DIR where the runtime controls the process. V2 agent
// tools execute inside the shared `opencode serve` process, so its
// environment cannot be set per stage; the stage prompt is the guaranteed
// carrier of the artifacts directory there.
ArtifactsDir string
Operations *OperationLog
OnGenerationSession func(id, backend, reference string, active bool) error
connection *opencode.Connection
@@ -34,6 +40,10 @@ type OpenCodeClient struct {
sessionPollInterval time.Duration // test seam; defaults to defaultSessionPollInterval
}
// ArtifactsEnv names the environment variable carrying a stage's artifacts
// directory to a locally spawned harness.
const ArtifactsEnv = "PIPELINES_ARTIFACTS_DIR"
// defaultSessionPollInterval bounds the delay between V2 active-session checks.
// The V2 /api/experimental/session/{id}/wait request blocks server-side until the
// CLI's own request timeout (observed ~6 minutes, HTTP 499) expires, which a long
@@ -118,6 +128,9 @@ func (c OpenCodeClient) call(ctx context.Context, method, path string, body any)
}
cmd := opencode.CommandContext(ctx, opencode.Executable(), args...)
cmd.Dir = directory
if c.ArtifactsDir != "" {
cmd.Env = append(os.Environ(), ArtifactsEnv+"="+c.ArtifactsDir)
}
stdout := &boundedBuffer{limit: maxModelResponse}
stderr := &boundedBuffer{limit: 8 << 10}
cmd.Stdout = stdout
+34 -18
View File
@@ -25,23 +25,26 @@ type PiClient struct {
Executable, Directory, SessionID, Reference, Transcript string
Tools []string
WritePaths []string
Policy ToolPolicy
OnSession func(string, bool) error
OnOwnership func(string, string, bool) error
WorkStarted bool
cmd *exec.Cmd
in io.WriteCloser
lines chan []byte
readErr chan error
next int
ready, settled bool
stopping bool
runErr error
budget *Budget
tokens int64
cost float64
usageSeen map[string]bool
completed int
// ArtifactsDir is exported to the spawned Pi process as
// PIPELINES_ARTIFACTS_DIR so its tools can write stage artifacts.
ArtifactsDir string
Policy ToolPolicy
OnSession func(string, bool) error
OnOwnership func(string, string, bool) error
WorkStarted bool
cmd *exec.Cmd
in io.WriteCloser
lines chan []byte
readErr chan error
next int
ready, settled bool
stopping bool
runErr error
budget *Budget
tokens int64
cost float64
usageSeen map[string]bool
completed int
}
func (c *PiClient) BudgetCapable() bool { return true }
@@ -147,7 +150,7 @@ func (c *PiClient) Generate(ctx context.Context, config ModelConfig, prompt stri
c.cmd = exec.Command(c.Executable, args...)
c.cmd.Dir = c.Directory
c.cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
c.cmd.Env = append(os.Environ(), "PI_OFFLINE=1", "PIPELINES_PI_POLICY="+filepath.Join(c.Reference, "policy.json"), "PIPELINES_PI_LEASE="+filepath.Join(c.Reference, "lease"), "PIPELINES_PI_STOPPED="+filepath.Join(c.Reference, "quiescent"))
c.cmd.Env = piEnvironment(c.Reference, c.ArtifactsDir)
stderr, err := os.OpenFile(filepath.Join(c.Reference, "stderr.log"), os.O_CREATE|os.O_WRONLY, 0600)
if err != nil {
return "", err
@@ -308,6 +311,19 @@ func (c *PiClient) Generate(ctx context.Context, config ModelConfig, prompt stri
return piResult(last)
}
// piEnvironment builds the spawned Pi process environment, including the
// per-stage artifacts directory when the runtime provided one.
func piEnvironment(reference, artifactsDir string) []string {
env := append(os.Environ(), "PI_OFFLINE=1",
"PIPELINES_PI_POLICY="+filepath.Join(reference, "policy.json"),
"PIPELINES_PI_LEASE="+filepath.Join(reference, "lease"),
"PIPELINES_PI_STOPPED="+filepath.Join(reference, "quiescent"))
if artifactsDir != "" {
env = append(env, ArtifactsEnv+"="+artifactsDir)
}
return env
}
func (c *PiClient) rpc(ctx context.Context, kind string, fields map[string]any) ([]byte, error) {
c.next++
id := fmt.Sprint(c.next)
+6 -3
View File
@@ -14,9 +14,12 @@ type Definition struct {
ReportFileArtifacts bool
Key string
Type string
Blocks map[string]string
Configs map[string]string
Edges map[string]string
// ArtifactsDir is the per-run/step directory the runtime created for this
// visit; empty when the runner did not provide one (for example in tests).
ArtifactsDir string
Blocks map[string]string
Configs map[string]string
Edges map[string]string
}
// Result selects one declared outcome. The future graph runner owns resolving