Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .github/workflows/go.yml
Original file line number Diff line number Diff line change
Expand Up @@ -37,5 +37,10 @@ jobs:
- name: Build
run: go build -v ./...

- name: Load service shutdown smoke image
run: docker pull busybox@sha256:73aaf090f3d85aa34ee199857f03fa3a95c8ede2ffd4cc2cdb5b94e566b11662

- name: Test
env:
MINDTRIAL_TEST_BUSYBOX_IMAGE: busybox@sha256:73aaf090f3d85aa34ee199857f03fa3a95c8ede2ffd4cc2cdb5b94e566b11662
run: go test -tags=test -race -v ./...
24 changes: 23 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1292,6 +1292,7 @@ Tools must be defined in `config.yaml` under the `tools` section. Each tool defi
- **parameter-files**: Mapping of parameter names to container file paths where argument values should be written. Argument values are converted to strings, non-string values are marshaled to JSON. The tool's command should read these files as needed.
- **auxiliary-dir**: Directory path inside the container where task files with `local` access will be automatically mounted. If specified, files with `local` access attached to the task will be mounted to this directory using each file's unique reference `name` exactly as provided. Files in this directory are reset between tool calls.
- **shared-dir**: Directory path inside the container that persists across all tool calls within a single task. If specified, files created in this directory will be available for any subsequent tool calls but will be removed when the task completes.
- **bind-mounts**: [Operator-owned host directories](#persistent-host-directories) attached to this tool only (optional).
- **command**: Command to run inside the container. The standard output of the command execution is captured and passed back to the LLM as is.
- **env**: Environment variables to set in the container.
- **dependencies**: [Task services](#task-services) the tool can access, each with a `service` name and optional `env` [templates](#templates).
Expand Down Expand Up @@ -1422,6 +1423,7 @@ Services are defined in `config.yaml` under the `services` section:

- **name**: A unique name for the service, used in `dependencies` and `service-inputs`.
- **image**: Docker image used to run the service.
- **bind-mounts**: [Operator-owned host directories](#persistent-host-directories) attached to this service only (optional).
- **command**: Command overriding the image's default command (optional).
- **env**: Environment variables set for every instance of the service (optional).
- **endpoint**: Where tools and validators connect to the service.
Expand Down Expand Up @@ -1477,6 +1479,7 @@ Validators are defined in `config.yaml` under the `validators` section:

- **name**: A unique name for the validator, used by `custom-validator` in task validation rules.
- **image**: Docker image used to run the validator.
- **bind-mounts**: [Operator-owned host directories](#persistent-host-directories) attached to this validator only (optional).
- **command**: Command overriding the image's default command (optional). Each argument is a [template](#templates) and is passed directly to Docker, without a shell.
- **env**: Environment variables set in the validator container (optional). Each value is a [template](#templates).
- **template-files**: Files created for each validation and mounted read-only into the validator container (optional).
Expand Down Expand Up @@ -1549,6 +1552,24 @@ The object must match this schema:

Results checked by a custom validator record `custom` as their validation method. Failed answers are shown exactly as the model returned them, without a comparison against `expected-result`. Validator runs are not counted as model tool calls.

#### Persistent host directories

Set `bind-mounts` on a **service**, **tool**, or **custom validator** in the operator’s `config.yaml`. Use this to collect files after a container is removed, or to give one container read-only access to existing inputs. For scratch space shared by tool calls and deleted at task completion, keep using `shared-dir`.

```yaml
# In one service, tool, or custom validator definition:
bind-mounts:
- source: ./exports # Create this directory beside config.yaml before running.
target: /exports # Absolute path in the container.
writable: true # Omit for read-only access.
```

The source must already be a directory accessible to both MindTrial and the Docker daemon at the resolved path. Relative sources resolve beside `config.yaml`, regardless of where you launch MindTrial. They are literal operator paths, never task or model templates. MindTrial does not create, chmod, relabel, empty, or delete the host directory. The configured image must have the needed filesystem permissions; files keep the writer’s UID and permissions. On SELinux hosts, provide a dedicated directory with an appropriate container-accessible label. Do not expose private exports to a model-controlled tool. Targets must not overlap other configured mounts in the same container.

Every container with the same writable source can see or overwrite the same data, including on retries. For independent service exports, mount a pre-existing **parent** and have the service create one child per instance. For example, declare `input-env: {output: APP_OUTPUT_DIR}` on the service; in `tool-selector.service-inputs` set its `output` to `"/exports/{{ .Service.InstanceID }}"`. The generated service container name is unique across retries and appears in the DEBUG log alongside the task trace. Only explicitly configured containers see the mount; a network dependency does not inherit it.

At normal teardown MindTrial asks a ready service to stop before reading its final logs and removing it. It gives the service up to 10 seconds to flush; a crash or forced stop can still leave partial files.

#### Templates

Service inputs, dependency environment variables, and custom validator settings use Go template syntax. MindTrial checks template syntax before any task runs, and using a field that does not exist is an error.
Expand All @@ -1557,12 +1578,13 @@ Each kind of template has its own fields:

| Template | Available fields |
| --- | --- |
| `service-inputs` string values | `.Evaluation.Seed`, `.Task.Name`, `.Provider.Name`, `.Run.Name` |
| `service-inputs` string values | `.Service.InstanceID`, `.Evaluation.Seed`, `.Task.Name`, `.Provider.Name`, `.Run.Name` |
| `dependencies[].env` values | `.Name`, `.Host`, `.Port`, `.Endpoint` |
| Validator `command`, `env`, and `template-files` | `.OriginalTask.*`, `.Candidate.Response`, `.Rules.*`, `.Evaluation.Seed`, `.Task.Name`, `.Provider.Name`, `.Run.Name` |

Fields:

- **{{ .Service.InstanceID }}**: Generated service container name, unique to this service instance, including across retries. Available in service-input templates only.
- **{{ .Evaluation.Seed }}**: Evaluation seed shared by all providers, runs, tasks, and attempts of one evaluation.
- **{{ .Task.Name }}**, **{{ .Provider.Name }}**, **{{ .Run.Name }}**: Names of the task, the provider, and the run configuration.
- **{{ .Name }}**: Name of the service.
Expand Down
113 changes: 113 additions & 0 deletions config/bind_mounts.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
// Copyright (C) 2026 Petr Malik
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at <https://mozilla.org/MPL/2.0/>.

package config

import (
"fmt"
"os"
"path"
"path/filepath"
"strings"
)

// BindMountConfig attaches an existing host directory. MindTrial never owns its contents.
type BindMountConfig struct {
// Source is the host directory, resolved relative to the configuration file when needed.
Source string `yaml:"source" validate:"required"`
// Target is the absolute, non-root path inside the container.
Target string `yaml:"target" validate:"required"`
// Writable permits writes to the host directory; mounts are read-only by default.
Writable bool `yaml:"writable,omitempty"`
}

// ValidateSource checks that the resolved host source exists and is a directory.
// Callers should recheck at mount time because the filesystem may change after preflight.
func (c BindMountConfig) ValidateSource() error {
if !filepath.IsAbs(c.Source) {
return fmt.Errorf("%w: bind source %q is not an absolute host path", ErrInvalidConfigProperty, c.Source)
}
info, err := os.Stat(c.Source)
if err != nil {
return fmt.Errorf("%w: bind source %q: %w", ErrInvalidConfigProperty, c.Source, err)
}
if !info.IsDir() {
return fmt.Errorf("%w: bind source %q is not a directory", ErrInvalidConfigProperty, c.Source)
}
return nil
}

// resolveBindMounts interprets relative sources against config.yaml, as with output-dir.
// Never expand task templates in host paths. Defer filesystem checks until preflight: an
// unrelated configured tool or service need not be available for this evaluation.
func (c *AppConfig) resolveBindMounts(configDir string) error {
for _, tool := range c.Tools {
if len(tool.BindMounts) == 0 {
continue
}
reserved := make([]string, 0, 2+len(tool.ParameterFiles))
reserved = append(reserved, tool.SharedDir, tool.AuxiliaryDir)
for _, parameterPath := range tool.ParameterFiles {
reserved = append(reserved, parameterPath)
}
if err := resolveMounts(configDir, tool.BindMounts, reserved); err != nil {
return fmt.Errorf("tool %q: %w", tool.Name, err)
}
}
for _, service := range c.Services {
if err := resolveMounts(configDir, service.BindMounts, nil); err != nil {
return fmt.Errorf("service %q: %w", service.Name, err)
}
}
for _, validator := range c.Validators {
if len(validator.BindMounts) == 0 {
continue
}
var reserved []string
for _, file := range validator.TemplateFiles {
reserved = append(reserved, file.Path)
}
if err := resolveMounts(configDir, validator.BindMounts, reserved); err != nil {
return fmt.Errorf("validator %q: %w", validator.Name, err)
}
}
return nil
}

func resolveMounts(configDir string, mounts []BindMountConfig, reserved []string) error {
for i := range mounts {
mount := &mounts[i]
if strings.TrimSpace(mount.Source) == "" || !path.IsAbs(mount.Target) || path.Clean(mount.Target) == "/" {
return fmt.Errorf("%w: bind-mounts[%d] needs a host source and an absolute non-root container target", ErrInvalidConfigProperty, i)
}
mount.Target = path.Clean(mount.Target)
for _, reservedPath := range reserved {
if reservedPath == "" {
continue
}
reservedPath = path.Clean(reservedPath)
if pathContains(reservedPath, mount.Target) || pathContains(mount.Target, reservedPath) {
return fmt.Errorf("%w: bind target %q overlaps container path %q", ErrInvalidConfigProperty, mount.Target, reservedPath)
}
}
source := mount.Source
if !filepath.IsAbs(source) {
source = filepath.Join(configDir, source)
}
absoluteSource, err := filepath.Abs(source)
if err != nil {
return fmt.Errorf("%w: bind source %q: %w", ErrInvalidConfigProperty, mount.Source, err)
}
mount.Source = absoluteSource
reserved = append(reserved, mount.Target)
}
return nil
}

// pathContains compares cleaned POSIX paths at component boundaries.
func pathContains(parent string, child string) bool {
return parent == child || strings.HasPrefix(child, strings.TrimSuffix(parent, "/")+"/")
}
74 changes: 74 additions & 0 deletions config/bind_mounts_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
// Copyright (C) 2026 Petr Malik
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at <https://mozilla.org/MPL/2.0/>.

package config

import (
"os"
"path/filepath"
"testing"

"github.com/petmal/mindtrial/pkg/testutils"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestBindMountConfigValidateSource(t *testing.T) {
directory := t.TempDir()
file := testutils.CreateMockFile(t, "bind-source-*.txt", []byte("keep"))
t.Cleanup(func() { assert.NoError(t, os.Remove(file)) })
tests := []struct {
name string
source string
wantErr error
}{
{
name: "directory",
source: directory,
},
{
name: "missing directory",
source: filepath.Join(directory, "missing"),
wantErr: os.ErrNotExist,
},
{
name: "file",
source: file,
wantErr: ErrInvalidConfigProperty,
},
{
name: "relative source",
source: "relative",
wantErr: ErrInvalidConfigProperty,
},
{
name: "empty source",
wantErr: ErrInvalidConfigProperty,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := (BindMountConfig{Source: tt.source}).ValidateSource()
if tt.wantErr != nil {
require.ErrorIs(t, err, ErrInvalidConfigProperty)
assert.ErrorIs(t, err, tt.wantErr)
return
}
require.NoError(t, err)
})
}
assert.NoDirExists(t, filepath.Join(directory, "missing"))
assert.FileExists(t, file)
}

func TestBindMountConfigValidateSourceRechecksDirectory(t *testing.T) {
source := filepath.Join(t.TempDir(), "source")
require.NoError(t, os.Mkdir(source, 0o700))
mount := BindMountConfig{Source: source}
require.NoError(t, mount.ValidateSource())
require.NoError(t, os.Remove(source))
require.ErrorIs(t, mount.ValidateSource(), os.ErrNotExist)
}
6 changes: 6 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,8 @@ type ToolConfig struct {
// If set, files created in this directory will be available for any subsequent tool calls but
// will be removed when the task completes.
SharedDir string `yaml:"shared-dir,omitempty"`
// BindMounts attaches existing operator-owned directories only to this container.
BindMounts []BindMountConfig `yaml:"bind-mounts,omitempty" validate:"omitempty,dive"`
// Command specifies the command to execute as a list of its components.
Command []string `yaml:"command,omitempty"`
// Env specifies additional environment variables to set.
Expand Down Expand Up @@ -356,6 +358,8 @@ type ServiceConfig struct {
Name string `yaml:"name" validate:"required"`
// Image is the Docker image used to run the service.
Image string `yaml:"image" validate:"required"`
// BindMounts attaches existing operator-owned directories only to this container.
BindMounts []BindMountConfig `yaml:"bind-mounts,omitempty" validate:"omitempty,dive"`
// Command overrides the image command used to start the service.
Command []string `yaml:"command,omitempty"`
// Env specifies static environment variables applied to every instance of the service.
Expand Down Expand Up @@ -392,6 +396,8 @@ type ValidatorConfig struct {
Name string `yaml:"name" validate:"required"`
// Image is the Docker image used to run the validator.
Image string `yaml:"image" validate:"required"`
// BindMounts attaches existing operator-owned directories only to this container.
BindMounts []BindMountConfig `yaml:"bind-mounts,omitempty" validate:"omitempty,dive"`
// Command overrides the image command used to run validation. Each argument may use
// custom-validator template variables and is passed directly to Docker without shell expansion.
// Prefer TemplateFiles for values that may be large or contain arbitrary bytes, such as candidate responses.
Expand Down
Loading
Loading