ARTEX - AI autonomous penetration testing system (English translation; upstream: Autumn-27/ARTEX, AGPL-3.0)
Go aiai-agentsautonomous-agentsbug-bountydockergolanglinuxllmmcpnextjspenetration-testingpentestpostgresqlreareactred-teamsecuritysecurity-automationsqlitetypescript
security(agent): command-output spills go to a root-owned per-task dir
BaaRai7520c6e5887d
diff --git a/SECURITY.md b/SECURITY.mdindex e1afb8d..a2c83c4 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -51,7 +51,7 @@ Operators running self-hosted LLM gateways or Ollama on a LAN or Docker bridge c## Agent Process Isolation-The server runs as root, but the processes an agent starts (Bash, the interactive shell, custom tools and stdio MCP servers) run as the unprivileged uid and gid set by `-exec-uid` and `-exec-gid` (default 10001). Only the run directories and their own home (`<data>/exec-home`) are writable by them. No agent working directory is an ancestor of another: the main agent and the planner work in `tasks/<id>/main`, a worker in `tasks/<id>/i<N>`, a chat in `sessions/<id>`. Their parents (`tasks/`, `sessions/` and `tasks/<id>`) are root:root 0755, so the executor cannot create, rename or remove an entry there, and only the leaves are shared with the executor group (setgid, 0775); with the drop active the server creates each level without following a symlink. Files that a task wrote directly in `tasks/<id>/` before this layout are not moved and keep the owner and mode they had, so one that was group-writable stays writable by the executor. `keys/` (`jwt.key`, `secret.key`), the config file and the MITM CA key are root-only, and the server's environment block no longer carries `ARTEX_PG_DSN`, `ARTEX_SECRET_KEY`, the LLM API keys or the LLM proxy and base URLs (Linux). The agent's file tools (Read, Write, Edit, MultiEdit, LS, Glob, Grep) run inside the server but reach only the run's working directory: paths are opened through `os.Root`, so absolute paths elsewhere, `..` and symlinks leading out are refused, and a working directory reached through any symlink is refused. The executor cannot replace a run directory or one of its parents, so the race that remains is the swap between an `EvalSymlinks` check and the open of a file inside a run directory, which the executor can do only inside a leaf (every executor process has the same identity, so this is any leaf, never a leaf itself or its parents). `ingest_bbot` reads its file through the same confinement. Custom-tool scripts are protected only when the executor privilege drop is active: they are then written to `<data>/exec-scripts`, a root-owned directory the executor can read and cannot change; with the drop disabled they still go to `.tools/` under the run directory. Residual, not closed here: the other root reads and writes by path remain open, and a symlink the executor places can redirect them, so root may read or write outside the workspace. They are the command-output spill (`cmd-output/`, written by Norma), `ingest_scan_output` (a root read by path), the `ask_operator` image staging (a root read and write under the task `uploads/` directory), chat uploads under the `tasks/<id>/main/uploads/` or `sessions/<id>/uploads/` directories, and task archive packaging (`lstat` then open by path). The Docker image has no setuid programs and `docker-compose.yml` sets `no-new-privileges`. These are a containment layer, not a sandbox: an executor can still read world-readable files under the data directory, reach the loopback API and the database if the network allows it, and use any credential it was given through the platform. Persistence tools (custom tools, MCP servers, skills) need operator approval by default.+The server runs as root, but the processes an agent starts (Bash, the interactive shell, custom tools and stdio MCP servers) run as the unprivileged uid and gid set by `-exec-uid` and `-exec-gid` (default 10001). Only the run directories and their own home (`<data>/exec-home`) are writable by them. No agent working directory is an ancestor of another: the main agent and the planner work in `tasks/<id>/main`, a worker in `tasks/<id>/i<N>`, a chat in `sessions/<id>`. Their parents (`tasks/`, `sessions/` and `tasks/<id>`) are root:root 0755, so the executor cannot create, rename or remove an entry there, and only the leaves are shared with the executor group (setgid, 0775); with the drop active the server creates each level without following a symlink. Files that a task wrote directly in `tasks/<id>/` before this layout are not moved and keep the owner and mode they had, so one that was group-writable stays writable by the executor. `keys/` (`jwt.key`, `secret.key`), the config file and the MITM CA key are root-only, and the server's environment block no longer carries `ARTEX_PG_DSN`, `ARTEX_SECRET_KEY`, the LLM API keys or the LLM proxy and base URLs (Linux). The agent's file tools (Read, Write, Edit, MultiEdit, LS, Glob, Grep) run inside the server but reach only the run's working directory: paths are opened through `os.Root`, so absolute paths elsewhere, `..` and symlinks leading out are refused, and a working directory reached through any symlink is refused. The executor cannot replace a run directory or one of its parents, so the race that remains is the swap between an `EvalSymlinks` check and the open of a file inside a run directory, which the executor can do only inside a leaf (every executor process has the same identity, so this is any leaf, never a leaf itself or its parents). `ingest_bbot` reads its file through the same confinement. Custom-tool scripts are protected only when the executor privilege drop is active: they are then written to `<data>/exec-scripts`, a root-owned directory the executor can read and cannot change; with the drop disabled they still go to `.tools/` under the run directory. Command-output spills (the full output of a tool call over the size cap, written by Norma inside the server) follow the same rule: with the drop active they go to a root-owned directory per task or chat session outside the run directory, `<data>/spill/tasks/<id>` or `<data>/spill/sessions/<id>` (root with the executor group, 0750, below root:root 0755 parents), which is deleted and archived with the task, or deleted with the conversation. The executor cannot create, rename or remove an entry there. Norma writes a spill file 0600 and the server makes it root with the executor group, 0640, when the tool call returns: the agent reads it with Bash, not with the file tools, which do not reach outside the run directory. With the drop disabled spills still go to `cmd-output/` under the run directory. Residual, not closed here: the other root reads and writes by path remain open, and a symlink the executor places can redirect them, so root may read or write outside the workspace. They are `ingest_scan_output` (a root read by path), the `ask_operator` image staging (a root read and write under the task `uploads/` directory), chat uploads under the `tasks/<id>/main/uploads/` or `sessions/<id>/uploads/` directories, and task archive packaging (`lstat` then open by path). The Docker image has no setuid programs and `docker-compose.yml` sets `no-new-privileges`. These are a containment layer, not a sandbox: an executor can still read world-readable files under the data directory, reach the loopback API and the database if the network allows it, and use any credential it was given through the platform. Persistence tools (custom tools, MCP servers, skills) need operator approval by default.## What to Expectdiff --git a/agent/chat.go b/agent/chat.goindex f6cf0ab..c4acbc8 100644--- a/agent/chat.go+++ b/agent/chat.go@@ -191,9 +191,10 @@ func (c *ChatAgent) Chat(ctx context.Context, agentKey, sessionID, message strinMaxDuration: maxDuration,Compaction: compactionConfig(c.window),Todos: actool.NewTodoStore(),- // large tool output spills to cmd-output/ under the session dir.+ // large tool output spills to cmd-output/ under the session dir, or to the+ // session's spill directory (spill.go).// the truncation cap uses the SDK default (30000 chars of tool.Capture).- ToolOutputDir: filepath.Join(sessionWorkDir, "cmd-output"),+ ToolOutputDir: SessionToolOutputDir(c.workDir, sessionID, sessionWorkDir),// hitting the budget (steps) → the SDK runs wrap-up: output a one-line summary. The prompt and// wrap-up rounds are editable in the backend per agent key// (each custom agent gets its own copy; empty/0 uses the generic default: 10 rounds).@@ -207,6 +208,7 @@ func (c *ChatAgent) Chat(ctx context.Context, agentKey, sessionID, message strinif c.guard != nil {opts.Hooks = c.guard.Hooks()}+ opts.Hooks = SpillHooks(opts.Hooks, opts.ToolOutputDir)// The session id is the provider-side identity (session header, usage metering)// with or without persistence; Norma only puts it on ctx when it writes a transcript.opts.SessionID = sessionIDdiff --git a/agent/mainagent.go b/agent/mainagent.goindex 7fc9a7e..50350b6 100644--- a/agent/mainagent.go+++ b/agent/mainagent.go@@ -156,7 +156,7 @@ func (m *MainAgent) Chat(ctx context.Context, taskID int64, mainSeg int, as *db.WebSearchProxy: m.webSearch.Proxy,BashEnv: proxyEnv(m.proxyAddr, m.proxyCACert), // Bash subcommands go through the proxy + trust the CA by defaultWorkingDir: mainDir, // the main run directory <workDir>/tasks/<taskID>/main- ToolOutputDir: cmdOutDir(mainDir),+ ToolOutputDir: TaskToolOutputDir(m.workDir, taskID, mainDir),MaxTurns: m.maxTurns, // 0 = unlimited (configurable in agent management)Compaction: compactionConfig(m.compactionWindow()), // long chats stay within the windowTodos: actool.NewTodoStore(), // session-level temporary todos (TodoWrite), planning only, dropped on exit@@ -171,6 +171,7 @@ func (m *MainAgent) Chat(ctx context.Context, taskID int64, mainSeg int, as *db.if hooks != nil { // typed-nil guard: only set when concrete (avoids harness panic)opts.Hooks = hooks}+ opts.Hooks = SpillHooks(opts.Hooks, opts.ToolOutputDir)// Segment 0 keeps the legacy "exp%d-main" name so existing transcripts still// load; each new session (seg>=1) gets its own file for a clean context. The id// is the provider-side identity (session header, usage metering) with or withoutdiff --git a/agent/planner.go b/agent/planner.goindex 68afd15..3ee934f 100644--- a/agent/planner.go+++ b/agent/planner.go@@ -554,7 +554,7 @@ func (p *Planner) Plan(ctx context.Context, taskID int64, as *db.AssetStore, tsWebSearchProxy: p.webSearch.Proxy,BashEnv: proxyEnv(p.proxyAddr, p.proxyCACert), // Bash subcommands go through the proxy + trust its CA by defaultWorkingDir: taskDir, // the main run directory <workDir>/tasks/<taskID>/main- ToolOutputDir: cmdOutDir(taskDir),+ ToolOutputDir: TaskToolOutputDir(p.workDir, taskID, taskDir),MaxTurns: p.maxTurns, // 0 = unlimited (configurable in agent management)MaxDuration: maxDur, // 0=unlimited; with a deadline = time remaining until itCompaction: compactionConfig(p.compactionWindow()),@@ -575,6 +575,7 @@ func (p *Planner) Plan(ctx context.Context, taskID int64, as *db.AssetStore, tsif hooks != nil { // typed-nil guard: only set when concrete (avoids harness panic)opts.Hooks = hooks}+ opts.Hooks = SpillHooks(opts.Hooks, opts.ToolOutputDir)// The session id is the provider-side identity (session header, usage metering)// with or without persistence; Norma only puts it on ctx when it writes a transcript.opts.SessionID = fmt.Sprintf("exp%d-planner", ts.ID())diff --git a/agent/spill.go b/agent/spill.gonew file mode 100644index 0000000..7d43d65--- /dev/null+++ b/agent/spill.go@@ -0,0 +1,116 @@+package agent++import (+ "bytes"+ "context"+ "log"+ "path/filepath"+ "strconv"++ "github.com/Autumn-27/norma/harness"+ "github.com/Autumn-27/norma/llm"+)++// Command-output spills. Norma's tool.Capture writes an oversized tool output to a+// file in ToolOutputDir, from the server process. In <run dir>/cmd-output the+// executor, which can write in the run directory, could turn cmd-output into a+// symlink that root then writes through. When agent processes run as the executor+// the server therefore owns the spill directory: one per task or chat session,+// outside every run directory, that the executor can read and cannot change.++// spillDirMaker creates a spill directory below the data directory, and+// spillFileSharer lets the executor read the spill files in one (Norma writes them+// 0600). The server sets both when agent processes run as the executor+// (server/execpriv_unix.go); nil keeps the spill in <run dir>/cmd-output.+var (+ spillDirMaker func(base, dir string) error+ spillFileSharer func(dir string) error+)++// SetSpillDirMaker sets how spill directories are created and how the spill files in+// one are shared with the executor. Call it before any agent runs.+func SetSpillDirMaker(mkdir func(base, dir string) error, share func(dir string) error) {+ spillDirMaker, spillFileSharer = mkdir, share+}++// TaskSpillDir is the server-owned spill directory of a task's agents:+// <base>/spill/tasks/<taskID>. It is removed and archived with the task directory.+func TaskSpillDir(base, taskID string) string {+ return filepath.Join(base, "spill", "tasks", taskID)+}++// SessionSpillDir is the server-owned spill directory of a chat session:+// <base>/spill/sessions/<sessionID>.+func SessionSpillDir(base, sessionID string) string {+ return filepath.Join(base, "spill", "sessions", sessionID)+}++// toolOutputDir returns the ToolOutputDir of a run. Without a maker it is+// <run dir>/cmd-output, which Norma creates on the first spill. With one it is+// spillDir, created here; when that fails the run gets no spill directory and+// oversized output is truncated instead.+func toolOutputDir(base, runDir, spillDir string) string {+ if spillDirMaker == nil {+ return filepath.Join(runDir, "cmd-output")+ }+ if err := spillDirMaker(base, spillDir); err != nil {+ log.Printf("[agent] spill directory %s: %v", spillDir, err)+ return ""+ }+ return spillDir+}++// TaskToolOutputDir is the ToolOutputDir of a task agent that works in runDir.+func TaskToolOutputDir(base string, taskID int64, runDir string) string {+ return toolOutputDir(base, runDir, TaskSpillDir(base, strconv.FormatInt(taskID, 10)))+}++// SessionToolOutputDir is the ToolOutputDir of a chat that works in runDir.+func SessionToolOutputDir(base, sessionID, runDir string) string {+ return toolOutputDir(base, runDir, SessionSpillDir(base, sessionID))+}++// spillMarker is in every result whose full output Capture wrote to a spill file.+var spillMarker = []byte("persisted-output")++// spillHooks shares the spill files of dir with the executor once the tool call that+// wrote one returns, before the model gets the path. inner may be nil.+type spillHooks struct {+ inner harness.HookRunner+ share func(dir string) error+ dir string+}++// SpillHooks returns the hooks of a run whose ToolOutputDir is dir. With a sharer+// set they wrap hooks (which may be nil); otherwise hooks is returned as it is.+func SpillHooks(hooks harness.HookRunner, dir string) harness.HookRunner {+ if spillFileSharer == nil || dir == "" {+ return hooks+ }+ return spillHooks{inner: hooks, share: spillFileSharer, dir: dir}+}++func (h spillHooks) PreToolUse(ctx context.Context, name string, input []byte) (bool, string, []byte) {+ if h.inner != nil {+ return h.inner.PreToolUse(ctx, name, input)+ }+ return false, "", nil+}++func (h spillHooks) PostToolUse(ctx context.Context, name string, input, result []byte, isErr bool) {+ if bytes.Contains(result, spillMarker) {+ if err := h.share(h.dir); err != nil {+ log.Printf("[agent] share the spill files in %s: %v", h.dir, err)+ }+ }+ if h.inner != nil {+ h.inner.PostToolUse(ctx, name, input, result, isErr)+ }+}++func (h spillHooks) Stop(ctx context.Context, messages []llm.Message) (bool, []string, string) {+ if h.inner != nil {+ return h.inner.Stop(ctx, messages)+ }+ return false, nil, ""+}diff --git a/agent/spill_test.go b/agent/spill_test.gonew file mode 100644index 0000000..c259a7e--- /dev/null+++ b/agent/spill_test.go@@ -0,0 +1,145 @@+package agent++import (+ "context"+ "encoding/json"+ "errors"+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/Autumn-27/norma/harness"+ "github.com/Autumn-27/norma/llm"+ actool "github.com/Autumn-27/norma/tool"+)++// countHooks counts the calls a spillHooks forwards.+type countHooks struct{ pre, post, stop int }++func (h *countHooks) PreToolUse(context.Context, string, []byte) (bool, string, []byte) {+ h.pre+++ return true, "blocked", nil+}+func (h *countHooks) PostToolUse(context.Context, string, []byte, []byte, bool) { h.post++ }+func (h *countHooks) Stop(context.Context, []llm.Message) (bool, []string, string) {+ h.stop+++ return true, nil, "stop"+}++// Without the privilege drop the spill stays in <run dir>/cmd-output and the hooks+// are not wrapped. With it, a task's agents share <base>/spill/tasks/<taskID> and a+// chat gets <base>/spill/sessions/<sessionID>: outside every run directory, created+// through the server's maker.+func TestToolOutputDir(t *testing.T) {+ base := t.TempDir()+ mainDir := filepath.Join(base, "tasks", "7", "main")+ worker := filepath.Join(base, "tasks", "7", "i12")+ session := filepath.Join(base, "sessions", "conv-3")++ if got, want := TaskToolOutputDir(base, 7, worker), filepath.Join(worker, "cmd-output"); got != want {+ t.Errorf("task ToolOutputDir without the drop = %s, want %s", got, want)+ }+ if got, want := SessionToolOutputDir(base, "conv-3", session), filepath.Join(session, "cmd-output"); got != want {+ t.Errorf("session ToolOutputDir without the drop = %s, want %s", got, want)+ }+ if entries, err := os.ReadDir(base); err != nil || len(entries) != 0 {+ t.Errorf("the data directory holds %v (%v), want nothing created", entries, err)+ }+ inner := &countHooks{}+ if got := SpillHooks(inner, filepath.Join(worker, "cmd-output")); got != harness.HookRunner(inner) {+ t.Errorf("hooks without the drop = %T, want them unchanged", got)+ }+ if got := SpillHooks(nil, filepath.Join(worker, "cmd-output")); got != nil {+ t.Errorf("nil hooks without the drop = %T, want nil", got)+ }++ var made, shared []string+ fail := false+ SetSpillDirMaker(func(b, dir string) error {+ if b != base {+ t.Errorf("maker base = %s, want %s", b, base)+ }+ if fail {+ return errors.New("refused")+ }+ made = append(made, dir)+ return nil+ }, func(dir string) error {+ shared = append(shared, dir)+ return nil+ })+ t.Cleanup(func() { SetSpillDirMaker(nil, nil) })++ task7 := filepath.Join(base, "spill", "tasks", "7")+ task8 := filepath.Join(base, "spill", "tasks", "8")+ conv3 := filepath.Join(base, "spill", "sessions", "conv-3")+ conv4 := filepath.Join(base, "spill", "sessions", "conv-4")+ got := []string{+ TaskToolOutputDir(base, 7, mainDir),+ TaskToolOutputDir(base, 7, worker),+ TaskToolOutputDir(base, 8, filepath.Join(base, "tasks", "8", "main")),+ SessionToolOutputDir(base, "conv-3", session),+ SessionToolOutputDir(base, "conv-4", filepath.Join(base, "sessions", "conv-4")),+ }+ want := []string{task7, task7, task8, conv3, conv4}+ if strings.Join(got, "|") != strings.Join(want, "|") {+ t.Errorf("ToolOutputDir with the drop = %v, want %v", got, want)+ }+ if strings.Join(made, "|") != strings.Join(want, "|") {+ t.Errorf("maker calls = %v, want %v", made, want)+ }+ if TaskSpillDir(base, "7") != task7 || SessionSpillDir(base, "conv-3") != conv3 {+ t.Errorf("spill directories: task %s, session %s", TaskSpillDir(base, "7"), SessionSpillDir(base, "conv-3"))+ }+ sep := string(filepath.Separator)+ for _, dir := range got {+ for _, runRoot := range []string{filepath.Join(base, "tasks"), filepath.Join(base, "sessions")} {+ if strings.HasPrefix(dir, runRoot+sep) {+ t.Errorf("spill directory %s is under %s", dir, runRoot)+ }+ }+ }+ // A spill directory that cannot be created is not replaced by the run directory.+ fail = true+ if got := TaskToolOutputDir(base, 9, filepath.Join(base, "tasks", "9", "main")); got != "" {+ t.Errorf("ToolOutputDir after a maker failure = %q, want none", got)+ }+ if got := SpillHooks(inner, ""); got != harness.HookRunner(inner) {+ t.Errorf("hooks of a run without a spill directory = %T, want them unchanged", got)+ }++ // The hooks share the spill files after a tool call whose result Capture spilled,+ // and forward every call. The marker is the one Norma writes.+ out := t.TempDir()+ spilled := actool.Capture(&actool.ToolContext{OutputDir: out}, strings.Repeat("x", actool.MaxOutput(nil)+1))+ entries, err := os.ReadDir(out)+ if err != nil || len(entries) != 1 || !strings.Contains(spilled, filepath.Join(out, entries[0].Name())) {+ t.Fatalf("Capture did not spill to %s: %v %v\n%s", out, entries, err, spilled)+ }+ raw, _ := json.Marshal(spilled)+ small, _ := json.Marshal(actool.Capture(&actool.ToolContext{OutputDir: out}, "small output"))+ ctx := context.Background()+ for _, hooks := range []harness.HookRunner{SpillHooks(inner, task7), SpillHooks(nil, task7)} {+ shared = nil+ hooks.PostToolUse(ctx, "Bash", nil, small, false)+ if len(shared) != 0 {+ t.Errorf("the sharer ran for a result without a spill: %v", shared)+ }+ hooks.PostToolUse(ctx, "Bash", nil, raw, false)+ if len(shared) != 1 || shared[0] != task7 {+ t.Errorf("sharer calls after a spill = %v, want [%s]", shared, task7)+ }+ hooks.PreToolUse(ctx, "Bash", nil)+ hooks.Stop(ctx, nil)+ }+ if block, msg, _ := SpillHooks(inner, task7).PreToolUse(ctx, "Bash", nil); !block || msg != "blocked" {+ t.Errorf("PreToolUse = %v %q, want the inner answer", block, msg)+ }+ if prevent, _, msg := SpillHooks(inner, task7).Stop(ctx, nil); !prevent || msg != "stop" {+ t.Errorf("Stop = %v %q, want the inner answer", prevent, msg)+ }+ if inner.pre != 2 || inner.post != 2 || inner.stop != 2 {+ t.Errorf("forwarded calls: pre %d post %d stop %d, want 2 each", inner.pre, inner.post, inner.stop)+ }+}diff --git a/agent/worker.go b/agent/worker.goindex 0ebd093..d75b9cb 100644--- a/agent/worker.go+++ b/agent/worker.go@@ -387,9 +387,6 @@ func IsRunDirName(name string) bool {return true}-// cmdOutDir is the SDK large-tool-output spill dir under an agent's run dir.-func cmdOutDir(dir string) string { return filepath.Join(dir, "cmd-output") }-func workerSystem(proxyAddr, caCert, dataDir, runDir string) string {body := renderSystem("worker", workerDefaultTmpl, WorkerVars{ProxyAddr: proxyAddr, DataDir: dataDir, Now: nowStr()})// caCert is present only when the recording MITM is on, which is exactly when@@ -604,10 +601,10 @@ func (w *Worker) execute(ctx context.Context, name string, taskID int64, as *db.// deadline → task-timeout prompt; turns = the turn budget ran out inside the// clamped window → fall back to the per-run prompt. Non-clamped stays pure per-run.Settlement: settle,- // large tool output spills to cmd-output/ with a head + pointer (SDK tool.Capture);- // full output preserved on disk. The truncation cap uses the SDK default (30000- // chars).- ToolOutputDir: cmdOutDir(runDir),+ // large tool output spills to a file with a head + pointer (SDK tool.Capture);+ // full output preserved on disk, in cmd-output/ or in the task's spill+ // directory (spill.go). The truncation cap uses the SDK default (30000 chars).+ ToolOutputDir: TaskToolOutputDir(w.workDir, taskID, runDir),Compaction: compactionConfig(w.compactionWindow()), // long tool-heavy runs stay within the windowTodos: actool.NewTodoStore(), // session-level scratch todos (TodoWrite), pure planning, discarded on exitNonStreaming: w.nonStreaming(), // when this profile selects non-streaming, use Provider.Complete@@ -619,6 +616,7 @@ func (w *Worker) execute(ctx context.Context, name string, taskID int64, as *db.if hooks != nil { // typed-nil guard: only set when concrete (avoids harness panic)opts.Hooks = hooks}+ opts.Hooks = SpillHooks(opts.Hooks, opts.ToolOutputDir)// The session id is the provider-side identity (session header, usage metering)// with or without persistence; Norma only puts it on ctx when it writes a transcript.opts.SessionID = WorkerSessionID(ts.ID(), intent.ID)diff --git a/server/conversations.go b/server/conversations.goindex cb810ae..8657ce8 100644--- a/server/conversations.go+++ b/server/conversations.go@@ -7,6 +7,7 @@ import ("log""math""net/http"+ "os""path/filepath""strconv""strings"@@ -223,9 +224,19 @@ func (s *Server) pgDeleteConversation(w http.ResponseWriter, r *http.Request) {writeErr(w, 500, err.Error())return}+ s.removeConversationSpill(c.ID)writeJSON(w, 200, map[string]any{"deleted": c.ID})}+// removeConversationSpill removes the command-output spill directory of a deleted+// conversation's chat session (<data>/spill/sessions/conv-<id>).+func (s *Server) removeConversationSpill(id int64) {+ dir := agent.SessionSpillDir(s.m.dir, s.convBusyKey(id))+ if err := os.RemoveAll(dir); err != nil {+ log.Printf("[conv %d] remove the spill directory %s: %v", id, dir, err)+ }+}+const maxConversationDeleteBatch = 100type conversationDeleteItem struct {@@ -287,6 +298,7 @@ func (s *Server) pgDeleteConversationsBatch(w http.ResponseWriter, r *http.RequedeletedSet := make(map[int64]struct{}, len(deleted))for _, id := range deleted {deletedSet[id] = struct{}{}+ s.removeConversationSpill(id)}items := make([]conversationDeleteItem, 0, len(ids))for _, id := range ids {diff --git a/server/execpriv_other.go b/server/execpriv_other.goindex b8f68f9..16aadf6 100644--- a/server/execpriv_other.go+++ b/server/execpriv_other.go@@ -23,6 +23,8 @@ func prepareExecScript(p ExecPrivilege, path string) error { return nil }func shareRestoredTaskDir(p ExecPrivilege, taskDir string) error { return nil }+func shareRestoredSpillDir(p ExecPrivilege, dir string) error { return nil }+// PrepareExecPrivilege fails when a drop is enabled; a disabled one does nothing.func PrepareExecPrivilege(p *ExecPrivilege, dataDir, keyDir, configPath string) error {if p.Enabled {diff --git a/server/execpriv_root_linux_test.go b/server/execpriv_root_linux_test.goindex 6ec1f38..8a0d8a5 100644--- a/server/execpriv_root_linux_test.go+++ b/server/execpriv_root_linux_test.go@@ -54,7 +54,8 @@ func newExecRootFixture(t *testing.T) *execRootFixture {if err != nil {t.Fatal(err)}- t.Cleanup(func() { agent.SetRunDirMaker(nil) }) // PrepareExecPrivilege sets it process-wide+ // PrepareExecPrivilege sets them process-wide.+ t.Cleanup(func() { agent.SetRunDirMaker(nil); agent.SetSpillDirMaker(nil, nil) })if err := PrepareExecPrivilege(&priv, dataDir, "", ""); err != nil {t.Fatal(err)}diff --git a/server/execpriv_unix.go b/server/execpriv_unix.goindex 10a2b8d..96af442 100644--- a/server/execpriv_unix.go+++ b/server/execpriv_unix.go@@ -143,8 +143,10 @@ func prepareExecScript(p ExecPrivilege, path string) error {// Their parents (tasks/, sessions/ and tasks/<id>) are root:root 0755, so the// executor cannot create, rename or remove a run directory, and no run directory is// an ancestor of another. Inside a run directory new subdirectories inherit the-// group. The key files and the config file (which can hold the database DSN) are-// restricted to root. Nothing else under the data directory changes; directories a+// group. Command-output spills leave the run directories for <data>/spill, which the+// executor group reads and cannot change (makeSpillDir). The key files and the+// config file (which can hold the database DSN) are restricted to root. Nothing+// else under the data directory changes; directories a// root-only path needs are left as they are. It sets p.ScriptDir to the script// directory it creates.func PrepareExecPrivilege(p *ExecPrivilege, dataDir, keyDir, configPath string) error {@@ -156,6 +158,10 @@ func PrepareExecPrivilege(p *ExecPrivilege, dataDir, keyDir, configPath string)return fmt.Errorf("share the run directories with the executor group: %w", err)}agent.SetRunDirMaker(func(base, leaf string) error { return makeRunDir(base, leaf, gid) })+ agent.SetSpillDirMaker(+ func(base, dir string) error { return makeSpillDir(base, dir, gid) },+ func(dir string) error { return shareSpillFiles(dir, gid) },+ )if err := prepareExecHome(*p, dataDir); err != nil {return fmt.Errorf("prepare the executor home: %w", err)}@@ -215,6 +221,66 @@ func setDirOwner(dir string, gid int, mode os.FileMode) error {// executor group. A parent is set before the next level is touched: once it is// root-only, the executor cannot swap what is below it.func makeRunDir(base, leaf string, gid int) error {+ return makeLeafDir(base, leaf, gid, runDirMode)+}++// spillDirMode is the mode of a command-output spill directory: the executor group+// reads what the server writes there and cannot create, rename or remove an entry.+const spillDirMode = 0o750++// makeSpillDir creates the spill directory dir below base (<base>/spill/tasks/<id>+// or <base>/spill/sessions/<id>): root-owned with the executor as its group, below+// root:root 0755 parents.+func makeSpillDir(base, dir string, gid int) error {+ return makeLeafDir(base, dir, gid, spillDirMode)+}++// shareSpillFiles lets the executor group read the spill files in dir. Norma writes+// them 0600 and the agent reads them back with Bash, which runs as the executor:+// each becomes root:gid 0640. The executor cannot write in dir, so every entry is a+// file the server wrote; it is still opened without following a symlink.+func shareSpillFiles(dir string, gid int) error {+ entries, err := os.ReadDir(dir)+ if err != nil {+ return err+ }+ for _, e := range entries {+ if !e.Type().IsRegular() {+ continue+ }+ f, err := os.OpenFile(filepath.Join(dir, e.Name()), os.O_RDONLY|syscall.O_NOFOLLOW, 0)+ if err != nil {+ return err+ }+ err = f.Chown(0, gid)+ if err == nil {+ err = f.Chmod(0o640)+ }+ f.Close()+ if err != nil {+ return err+ }+ }+ return nil+}++// shareRestoredSpillDir puts the ownership back on a spill directory that was+// restored from an archive: the package keeps neither owners nor directory modes.+func shareRestoredSpillDir(p ExecPrivilege, dir string) error {+ if !p.Enabled {+ return nil+ }+ gid := int(p.GID)+ if err := setDirOwner(dir, gid, spillDirMode); err != nil {+ return err+ }+ return shareSpillFiles(dir, gid)+}++// makeLeafDir creates the directory leaf below base with mode and the group gid.+// Every directory between base and the leaf is root:root 0755. A parent is set+// before the next level is touched.+func makeLeafDir(base, leaf string, gid int, leafMode os.FileMode) error {rel, err := filepath.Rel(base, leaf)if err != nil || rel == "." || !filepath.IsLocal(rel) {return fmt.Errorf("%s is not below %s", leaf, base)@@ -225,7 +291,7 @@ func makeRunDir(base, leaf string, gid int) error {dir = filepath.Join(dir, part)group, mode := 0, os.FileMode(0o755)if i == len(parts)-1 {- group, mode = gid, runDirMode+ group, mode = gid, leafMode}if err := os.Mkdir(dir, mode.Perm()); err != nil && !errors.Is(err, fs.ErrExist) {return errdiff --git a/server/manager.go b/server/manager.goindex 650625e..9e2a558 100644--- a/server/manager.go+++ b/server/manager.go@@ -1756,17 +1756,19 @@ type taskFileDeleteStage struct {done bool}-// stageTaskFiles atomically renames the task workspace and owned transcripts to-// a same-filesystem staging directory. The trailing dash in the transcript-// prefix is significant: exploration 12 must not match exploration 123.+// stageTaskFiles atomically renames the task workspace, its command-output spill+// directory and owned transcripts to a same-filesystem staging directory. The+// trailing dash in the transcript prefix is significant: exploration 12 must not+// match exploration 123.func stageTaskFiles(dataDir, taskID string, explorationID int64) (*taskFileDeleteStage, error) {stage := &taskFileDeleteStage{}var targets []string- taskDir := filepath.Join(dataDir, "tasks", taskID)- if _, err := os.Lstat(taskDir); err == nil {- targets = append(targets, taskDir)- } else if !os.IsNotExist(err) {- return nil, err+ for _, dir := range []string{filepath.Join(dataDir, "tasks", taskID), agent.TaskSpillDir(dataDir, taskID)} {+ if _, err := os.Lstat(dir); err == nil {+ targets = append(targets, dir)+ } else if !os.IsNotExist(err) {+ return nil, err+ }}transcriptDir := filepath.Join(dataDir, "transcripts")diff --git a/server/manager_delete_files_test.go b/server/manager_delete_files_test.goindex 95a3814..93b4d1a 100644--- a/server/manager_delete_files_test.go+++ b/server/manager_delete_files_test.go@@ -8,6 +8,7 @@ import ("strings""testing"+ "github.com/Autumn-27/artex/agent"pgdb "github.com/Autumn-27/artex/db""github.com/Autumn-27/artex/traffic")@@ -119,6 +120,56 @@ func TestDeleteTaskFilesMissingTargetsIsIdempotent(t *testing.T) {}}+// Deleting a task removes its command-output spill directory, also when the task+// has no workspace left, and not the spills of another task or of a chat session. A+// rollback puts the directory back.+func TestDeleteTaskFilesRemovesSpillDir(t *testing.T) {+ dataDir := t.TempDir()+ spill := agent.TaskSpillDir(dataDir, "77")+ if spill != filepath.Join(dataDir, "spill", "tasks", "77") {+ t.Fatalf("task spill directory = %s", spill)+ }+ file := filepath.Join("spill", "tasks", "77", "output-1-1.txt")+ kept := []string{+ filepath.Join("spill", "tasks", "78", "output-1-2.txt"),+ filepath.Join("spill", "tasks", "7", "output-1-3.txt"),+ filepath.Join("spill", "sessions", "conv-77", "output-1-4.txt"),+ }+ for _, path := range append([]string{file, filepath.Join("tasks", "77", "main", "notes.txt")}, kept...) {+ createDeleteFixture(t, dataDir, path, false)+ }++ stage, err := stageTaskFiles(dataDir, "77", 12)+ if err != nil {+ t.Fatal(err)+ }+ assertPathMissing(t, spill)+ if err := stage.rollback(); err != nil {+ t.Fatal(err)+ }+ assertPathExists(t, filepath.Join(dataDir, file))++ if deleted, err := deleteTaskFiles(dataDir, "77", 12); err != nil || !deleted {+ t.Fatalf("delete task files: deleted=%v err=%v", deleted, err)+ }+ assertPathMissing(t, spill)+ assertPathMissing(t, filepath.Join(dataDir, "tasks", "77"))+ for _, path := range kept {+ assertPathExists(t, filepath.Join(dataDir, path))+ }++ // A task whose workspace is gone still loses its spills.+ if deleted, err := deleteTaskFiles(dataDir, "78", 13); err != nil || !deleted {+ t.Fatalf("delete spill-only task files: deleted=%v err=%v", deleted, err)+ }+ assertPathMissing(t, agent.TaskSpillDir(dataDir, "78"))+ assertPathExists(t, filepath.Join(dataDir, kept[1]))+ assertPathExists(t, filepath.Join(dataDir, kept[2]))+ if entries, err := os.ReadDir(filepath.Join(dataDir, ".delete-staging")); err != nil || len(entries) != 0 {+ t.Fatalf("delete staging holds %v (%v), want it empty", entries, err)+ }+}+func TestStageTaskFilesRollbackRestoresWorkspaceAndTranscripts(t *testing.T) {dataDir := t.TempDir()paths := []string{diff --git a/server/rundir_root_linux_test.go b/server/rundir_root_linux_test.goindex aba7925..52faaa1 100644--- a/server/rundir_root_linux_test.go+++ b/server/rundir_root_linux_test.go@@ -273,6 +273,12 @@ func TestTaskArchiveRestoreRunDirOwnershipAsRoot(t *testing.T) {t.Fatal(err)}}+ // A spill file of the task, as Norma writes it.+ spillDir := agent.TaskToolOutputDir(f.data, 1, f.work)+ spillFile := filepath.Join(spillDir, "output-1-1.txt")+ if err := os.WriteFile(spillFile, []byte("spilled output"), 0o600); err != nil {+ t.Fatal(err)+ }stage, err := stageTaskArchiveFiles(f.data, 1, taskID, 73)if err != nil {@@ -281,6 +287,9 @@ func TestTaskArchiveRestoreRunDirOwnershipAsRoot(t *testing.T) {if _, err := os.Lstat(task); !os.IsNotExist(err) {t.Fatalf("task directory still hot after staging: %v", err)}+ if _, err := os.Lstat(spillDir); !os.IsNotExist(err) {+ t.Fatalf("spill directory still hot after staging: %v", err)+ }archivePath := taskArchivePath(f.data, 1, taskID)snapshot := &pgdb.TaskArchiveSnapshot{FormatVersion: pgdb.TaskArchiveFormatVersion, TaskID: 1, ExplorationID: 73}_, _, checksum, err := writeTaskArchivePackage(archivePath, stage.payload, snapshot)@@ -320,8 +329,16 @@ func TestTaskArchiveRestoreRunDirOwnershipAsRoot(t *testing.T) {t.Errorf("%s: %v gid %d, want group read/write with gid %d", path, fi.Mode(), st.Gid, DefaultExecGID)}}- // The executor works in the restored run directory again.- c := exec.Command("sh", "-c", "echo more >> uploads/evidence.txt && echo new > after-restore.txt && id -u")+ // The spill directory is back for the executor to read, and not to write.+ checkDir(t, filepath.Join(f.data, "spill", "tasks"), 0, parentDirMode)+ checkDir(t, spillDir, DefaultExecGID, 0o750)+ if fi, err := os.Lstat(spillFile); err != nil {+ t.Fatal(err)+ } else if st := fi.Sys().(*syscall.Stat_t); fi.Mode() != 0o640 || st.Uid != 0 || st.Gid != DefaultExecGID {+ t.Errorf("%s: %v uid %d gid %d, want 0640 root:%d", spillFile, fi.Mode(), st.Uid, st.Gid, DefaultExecGID)+ }+ // The executor works in the restored run directory again, and reads the spill.+ c := exec.Command("sh", "-c", "echo more >> uploads/evidence.txt && echo new > after-restore.txt && test \"$(cat '"+spillFile+"')\" = 'spilled output' && ! touch '"+spillDir+"/planted' 2>/dev/null && id -u")c.Dir = f.workapplyExecCredential(c, f.priv)out, err := c.CombinedOutput()diff --git a/server/spill_root_linux_test.go b/server/spill_root_linux_test.gonew file mode 100644index 0000000..ca954d7--- /dev/null+++ b/server/spill_root_linux_test.go@@ -0,0 +1,191 @@+//go:build linux++package server++import (+ "context"+ "encoding/json"+ "fmt"+ "os"+ "os/exec"+ "path/filepath"+ "strings"+ "syscall"+ "testing"+ "time"++ "github.com/Autumn-27/artex/agent"+ actool "github.com/Autumn-27/norma/tool"+)++// Root test of the command-output spill. The agent turned <run dir>/cmd-output into+// a symlink to a root-only directory. A Bash call whose output is over the cap runs+// as Norma's loop runs it, with the ToolOutputDir and the hooks the agents pass:+// nothing is written through the link, the spill file lands in the task's spill+// directory, and the executor reads it there and cannot change the directory.+func TestSpillDirAsRoot(t *testing.T) {+ f := newExecRootFixture(t)+ if err := InstallBashShim(f.priv); err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { os.RemoveAll(filepath.SplitList(os.Getenv("PATH"))[0]) })+ py, err := exec.LookPath("python3")+ if err != nil {+ t.Fatalf("python3 is needed for the executor probe: %v", err)+ }+ trap := filepath.Join(f.data, "trap")+ if err := os.Mkdir(trap, 0o700); err != nil {+ t.Fatal(err)+ }+ planted := filepath.Join(f.work, "cmd-output")+ if err := os.Symlink(trap, planted); err != nil {+ t.Fatal(err)+ }++ // What the main agent of task 1 gives Norma, and a chat session beside it.+ dir := agent.TaskToolOutputDir(f.data, 1, f.work)+ hooks := agent.SpillHooks(nil, dir)+ session := agent.SessionToolOutputDir(f.data, "conv-3", agent.EnsureSessionDir(f.data, "conv-3"))+ spillRoot := filepath.Join(f.data, "spill")+ if dir != filepath.Join(spillRoot, "tasks", "1") || session != filepath.Join(spillRoot, "sessions", "conv-3") {+ t.Fatalf("spill directories: task %s, session %s", dir, session)+ }+ if hooks == nil {+ t.Fatal("the run has no hooks to share its spill files")+ }+ checkLayout := func() {+ t.Helper()+ for _, parent := range []string{spillRoot, filepath.Join(spillRoot, "tasks"), filepath.Join(spillRoot, "sessions")} {+ checkDir(t, parent, 0, parentDirMode)+ }+ checkDir(t, dir, DefaultExecGID, 0o750)+ checkDir(t, session, DefaultExecGID, 0o750)+ }+ checkLayout()++ // One tool call: the tool, then the post-tool hook with the flattened result.+ const size = 40000+ ctx := context.Background()+ tc := &actool.ToolContext{WorkingDir: f.work, OutputDir: dir}+ in, _ := json.Marshal(map[string]string{"command": fmt.Sprintf("id -u; head -c %d /dev/zero | tr '\\0' x", size)})+ res, err := actool.NewBash().Call(ctx, in, tc)+ if err != nil {+ t.Fatal(err)+ }+ out := res.Flatten()+ if !strings.HasPrefix(out, fmt.Sprintf("%d\n", DefaultExecUID)) {+ t.Fatalf("the command did not run as the executor:\n%.200s", out)+ }+ entries, err := os.ReadDir(dir)+ if err != nil || len(entries) != 1 {+ t.Fatalf("the spill directory holds %v (%v), want one spill file", entries, err)+ }+ file := filepath.Join(dir, entries[0].Name())+ if !strings.Contains(out, "<persisted-output>") || !strings.Contains(out, file) {+ t.Fatalf("the result does not point to the spill file %s:\n%s", file, out[max(0, len(out)-300):])+ }+ stat := func() (os.FileMode, *syscall.Stat_t) {+ t.Helper()+ fi, err := os.Lstat(file)+ if err != nil {+ t.Fatal(err)+ }+ return fi.Mode(), fi.Sys().(*syscall.Stat_t)+ }+ // Norma writes the file for root alone: the executor cannot read it yet.+ if mode, _ := stat(); mode != 0o600 {+ t.Fatalf("spill file as Norma wrote it: %v, want a regular file 0600", mode)+ }+ raw, _ := json.Marshal(out)+ hooks.PostToolUse(ctx, "Bash", in, raw, res.IsError)+ if mode, st := stat(); mode != 0o640 || st.Uid != 0 || st.Gid != DefaultExecGID {+ t.Fatalf("spill file after the hook: %v uid %d gid %d, want 0640 root:%d", mode, st.Uid, st.Gid, DefaultExecGID)+ }+ want := fmt.Sprintf("%d\n%s", DefaultExecUID, strings.Repeat("x", size))+ if got, err := os.ReadFile(file); err != nil || string(got) != want {+ t.Fatalf("spill file: %d bytes (%v), want the full output of %d bytes", len(got), err, len(want))+ }++ // Nothing went through the planted link, and it is still a link.+ if entries, err := os.ReadDir(trap); err != nil || len(entries) != 0 {+ t.Fatalf("the symlinked cmd-output target holds %v (%v), want it empty", entries, err)+ }+ checkDir(t, trap, 0, 0o700)+ if fi, err := os.Lstat(planted); err != nil || fi.Mode()&os.ModeSymlink == 0 {+ t.Fatalf("cmd-output in the run directory changed: %v %v", fi, err)+ }++ // The agent reads the spill back with Bash, as the executor.+ in, _ = json.Marshal(map[string]string{"command": fmt.Sprintf("id -u; wc -c < '%s'; tail -c 5 '%s'", file, file)})+ res, err = actool.NewBash().Call(ctx, in, tc)+ if err != nil {+ t.Fatal(err)+ }+ wantRead := fmt.Sprintf("%d\n%d\nxxxxx", DefaultExecUID, len(want))+ if got := res.Flatten(); strings.TrimSpace(got) != wantRead {+ t.Fatalf("Bash read of the spill file as the executor = %q, want %q", got, wantRead)+ }++ // The executor cannot change the spill directory or the file.+ code := `import errno, os+d = os.environ["SPILL_DIR"]+f = os.environ["SPILL_FILE"]+print("uid=%d gid=%d" % (os.getuid(), os.getgid()))+st = os.stat(f)+print("file=%o uid=%d gid=%d" % (st.st_mode & 0o7777, st.st_uid, st.st_gid))+def attempt(name, fn):+ try:+ fn()+ print(name + "=done")+ except OSError as e:+ print(name + "=" + errno.errorcode.get(e.errno, str(e.errno)))+attempt("read", lambda: open(f).read())+attempt("list", lambda: os.listdir(d))+attempt("create", lambda: open(os.path.join(d, "planted.txt"), "w").close())+attempt("rename", lambda: os.rename(f, f + ".moved"))+attempt("unlink", lambda: os.unlink(f))+attempt("mkdir", lambda: os.mkdir(os.path.join(d, "planted-dir")))+attempt("symlink", lambda: os.symlink("/etc/passwd", os.path.join(d, "planted-link")))+attempt("link", lambda: os.link(f, os.path.join(d, "planted-hardlink")))+attempt("write", lambda: open(f, "a").close())+attempt("rename_dir", lambda: os.rename(d, d + ".moved"))+attempt("rmdir_dir", lambda: os.rmdir(d))+attempt("create_in_parent", lambda: open(os.path.join(os.path.dirname(d), "2"), "w").close())+attempt("chmod_dir", lambda: os.chmod(d, 0o777))+attempt("chmod_file", lambda: os.chmod(f, 0o666))+`+ probe, err := execPython(ctx, py, "probe", code, nil, f.work, []string{"SPILL_DIR=" + dir, "SPILL_FILE=" + file}, 30*time.Second, f.priv)+ if err != nil {+ t.Fatal(err)+ }+ t.Logf("executor probe output:\n%s", probe)+ for _, want := range []string{+ fmt.Sprintf("uid=%d gid=%d\n", DefaultExecUID, DefaultExecGID),+ fmt.Sprintf("file=640 uid=0 gid=%d\n", DefaultExecGID),+ "read=done\n", "list=done\n",+ "chmod_dir=EPERM\n", "chmod_file=EPERM\n",+ } {+ if !strings.Contains(probe, want) {+ t.Errorf("want %q in the probe output:\n%s", want, probe)+ }+ }+ for _, name := range []string{+ "create", "rename", "unlink", "mkdir", "symlink", "link", "write", "rename_dir", "rmdir_dir", "create_in_parent",+ } {+ if !strings.Contains(probe, name+"=EACCES\n") && !strings.Contains(probe, name+"=EPERM\n") {+ t.Errorf("%s was not refused with EACCES or EPERM:\n%s", name, probe)+ }+ }+ if strings.Contains(probe, "[exit:") {+ t.Errorf("the probe failed:\n%s", probe)+ }+ // The directory still holds the one spill file, with the layout it had.+ if entries, err := os.ReadDir(dir); err != nil || len(entries) != 1 || entries[0].Name() != filepath.Base(file) {+ t.Errorf("the spill directory holds %v (%v), want only %s", entries, err, filepath.Base(file))+ }+ checkLayout()+ // A later run of the same agents finds the directories and leaves them so.+ agent.TaskToolOutputDir(f.data, 1, f.work)+ agent.SessionToolOutputDir(f.data, "conv-3", filepath.Join(f.data, "sessions", "conv-3"))+ checkLayout()+}diff --git a/server/spill_test.go b/server/spill_test.gonew file mode 100644index 0000000..ac80cdb--- /dev/null+++ b/server/spill_test.go@@ -0,0 +1,34 @@+package server++import (+ "path/filepath"+ "testing"++ "github.com/Autumn-27/artex/agent"+)++// Deleting a conversation removes the spill directory of its chat session only: the+// spills of another conversation and the session's run directory stay.+func TestRemoveConversationSpill(t *testing.T) {+ dataDir := t.TempDir()+ s := &Server{m: &Manager{dir: dataDir}}+ spill := agent.SessionSpillDir(dataDir, s.convBusyKey(5))+ if spill != filepath.Join(dataDir, "spill", "sessions", "conv-5") {+ t.Fatalf("session spill directory = %s", spill)+ }+ kept := []string{+ filepath.Join("spill", "sessions", "conv-50", "output-1-2.txt"),+ filepath.Join("spill", "tasks", "5", "output-1-3.txt"),+ filepath.Join("sessions", "conv-5", "notes.txt"),+ }+ for _, path := range append([]string{filepath.Join("spill", "sessions", "conv-5", "output-1-1.txt")}, kept...) {+ createDeleteFixture(t, dataDir, path, false)+ }+ s.removeConversationSpill(5)+ assertPathMissing(t, spill)+ for _, path := range kept {+ assertPathExists(t, filepath.Join(dataDir, path))+ }+ // A conversation that never spilled has nothing to remove.+ s.removeConversationSpill(6)+}diff --git a/server/task_archive_package.go b/server/task_archive_package.goindex 8311494..6efef3f 100644--- a/server/task_archive_package.go+++ b/server/task_archive_package.go@@ -15,6 +15,7 @@ import ("strconv""strings"+ "github.com/Autumn-27/artex/agent"pgdb "github.com/Autumn-27/artex/db""github.com/klauspost/compress/zstd")@@ -123,6 +124,13 @@ func stageTaskArchiveFiles(dataDir string, archiveID int64, taskID string, explo} else if !os.IsNotExist(err) {return nil, err}+ // The command-output spills of the task are packed and deleted with it.+ spillDir := agent.TaskSpillDir(dataDir, taskID)+ if _, err := os.Lstat(spillDir); err == nil {+ targets = append(targets, archiveFileMove{Source: spillDir, Relative: filepath.Join("files", "spill", "tasks", taskID)})+ } else if !os.IsNotExist(err) {+ return nil, err+ }transcriptDir := filepath.Join(dataDir, "transcripts")entries, err := os.ReadDir(transcriptDir)if err != nil && !os.IsNotExist(err) {@@ -227,9 +235,10 @@ func (s *taskArchiveFileStage) commit() error {return os.RemoveAll(s.root)}-// installTaskArchiveFiles moves the extracted workspace and transcripts back under-// the data directory. The workspace is the whole task directory, run directories-// (main/, i<N>/) included; priv puts their ownership back.+// installTaskArchiveFiles moves the extracted workspace, spill directory and+// transcripts back under the data directory. The workspace is the whole task+// directory, run directories (main/, i<N>/) included; priv puts their ownership+// back, and that of the spill directory.func installTaskArchiveFiles(dataDir, extractedDir, taskID string, archiveID int64, priv ExecPrivilege) (*taskArchiveRestoreFiles, error) {stage := &taskArchiveRestoreFiles{extracted: extractedDir}numericTaskID, err := strconv.ParseInt(taskID, 10, 64)@@ -246,6 +255,15 @@ func installTaskArchiveFiles(dataDir, extractedDir, taskID string, archiveID int} else if !os.IsNotExist(err) {return nil, err}+ spill := filepath.Join(extractedDir, "files", "spill", "tasks", taskID)+ spillDir := agent.TaskSpillDir(dataDir, taskID)+ hasSpill := false+ if _, err := os.Lstat(spill); err == nil {+ sources = append(sources, restoredArchivePath{Source: spill, Destination: spillDir})+ hasSpill = true+ } else if !os.IsNotExist(err) {+ return nil, err+ }transcripts := filepath.Join(extractedDir, "files", "transcripts")entries, err := os.ReadDir(transcripts)if err != nil && !os.IsNotExist(err) {@@ -284,6 +302,12 @@ func installTaskArchiveFiles(dataDir, extractedDir, taskID string, archiveID intreturn nil, fmt.Errorf("restore the run directory ownership of %s: %w", taskDir, err)}}+ if hasSpill {+ if err := shareRestoredSpillDir(priv, spillDir); err != nil {+ _ = stage.rollback()+ return nil, fmt.Errorf("restore the spill directory ownership of %s: %w", spillDir, err)+ }+ }return stage, nil}diff --git a/server/task_archive_package_test.go b/server/task_archive_package_test.goindex 8a8e10d..58d01d0 100644--- a/server/task_archive_package_test.go+++ b/server/task_archive_package_test.go@@ -8,6 +8,7 @@ import ("path/filepath""testing"+ "github.com/Autumn-27/artex/agent"pgdb "github.com/Autumn-27/artex/db""github.com/klauspost/compress/zstd")@@ -19,11 +20,16 @@ func TestTaskArchivePackageFilesRoundTrip(t *testing.T) {// The task directory packs whole: the main agent's run directory and a worker's.taskFile := filepath.Join(dataDir, "tasks", taskID, "main", "uploads", "evidence.txt")workerFile := filepath.Join(dataDir, "tasks", taskID, "i7", "notes.txt")+ // The task's command-output spills are packed with it, and those of another task stay.+ spillFile := filepath.Join(agent.TaskSpillDir(dataDir, taskID), "output-1-1.txt")+ unrelatedSpill := filepath.Join(agent.TaskSpillDir(dataDir, "43"), "output-1-2.txt")transcriptFile := filepath.Join(dataDir, "transcripts", "exp73-worker-1.jsonl")unrelatedTranscript := filepath.Join(dataDir, "transcripts", "exp74-worker-1.jsonl")for path, body := range map[string]string{taskFile: "task evidence",workerFile: "worker notes",+ spillFile: "spilled output",+ unrelatedSpill: "leave me hot",transcriptFile: "transcript",unrelatedTranscript: "leave me hot",} {@@ -39,11 +45,14 @@ func TestTaskArchivePackageFilesRoundTrip(t *testing.T) {if err != nil {t.Fatal(err)}- for _, path := range []string{taskFile, workerFile} {+ for _, path := range []string{taskFile, workerFile, spillFile, filepath.Dir(spillFile)} {if _, err := os.Stat(path); !os.IsNotExist(err) {t.Fatalf("task file %s still hot after staging: %v", path, err)}}+ if _, err := os.Stat(unrelatedSpill); err != nil {+ t.Fatalf("the spill of another task was staged: %v", err)+ }if _, err := os.Stat(transcriptFile); !os.IsNotExist(err) {t.Fatalf("task transcript still hot after staging: %v", err)}@@ -94,7 +103,7 @@ func TestTaskArchivePackageFilesRoundTrip(t *testing.T) {if err := installed.commit(); err != nil {t.Fatal(err)}- for path, want := range map[string]string{taskFile: "task evidence", workerFile: "worker notes", transcriptFile: "transcript"} {+ for path, want := range map[string]string{taskFile: "task evidence", workerFile: "worker notes", spillFile: "spilled output", transcriptFile: "transcript"} {got, err := os.ReadFile(path)if err != nil || string(got) != want {t.Fatalf("restored %s = %q, %v; want %q", path, got, err, want)