Agent Executor (AX) is Google's open agentic orchestration runtime
Go
api,runner: bind at most one workspace per task (#496)
Jaana Dogan6a1d6ea8e7e6
diff --git a/README.md b/README.mdindex 11ef4ff..bc8a01d 100644--- a/README.md+++ b/README.md@@ -28,9 +28,9 @@ kind: Taskmetadata:name: testspec:- workspaces:- - name: golang- goal: "Ensure that Go tool chain is available and is built from source"+ workspace:+ name: golang+ goal: "Ensure that Go tool chain is available and is built from source"debug: true # lets you `ax ssh` into the sandbox```diff --git a/cmd/ax-task-runner/main.go b/cmd/ax-task-runner/main.goindex 262b0da..e9e0d9c 100644--- a/cmd/ax-task-runner/main.go+++ b/cmd/ax-task-runner/main.go@@ -16,22 +16,18 @@// loads the Task and Workspace specs and hands them to the runner package,// which does everything else.//-// AX delivers the Task as YAML in AX_TASK_YAML and the bound-// Workspaces as a multi-document YAML stream in AX_WORKSPACES_YAML. For local-// runs the specs can be read from files instead with --task-file and one or-// more --workspace-file flags.+// AX delivers the Task as YAML in AX_TASK_YAML and the bound Workspace, if+// any, as YAML in AX_WORKSPACE_YAML. For local runs the specs can be read from+// files instead with --task-file and --workspace-file.package mainimport ("context"- "errors""flag""fmt"- "io""log/slog""os""os/signal"- "strings""syscall""github.com/google/ax/pkg/apis/v1alpha1"@@ -39,22 +35,16 @@ import ("gopkg.in/yaml.v3")-// stringList collects a repeatable flag.-type stringList []string--func (l *stringList) String() string { return strings.Join(*l, ",") }-func (l *stringList) Set(v string) error { *l = append(*l, v); return nil }-func main() {var (cfg runner.ConfigtaskFile string- wsFiles stringList+ wsFile string)flag.IntVar(&cfg.Port, "port", runner.DefaultPort, "Port for the probe and guest server")flag.IntVar(&cfg.MetadataPort, "metadata-port", runner.DefaultMetadataPort, "Loopback-only port for the metadata endpoints")flag.StringVar(&taskFile, "task-file", "", "Read the Task YAML from this file instead of AX_TASK_YAML")- flag.Var(&wsFiles, "workspace-file", "Read Workspace YAML from this file instead of the environment; repeatable, and each file may hold several documents")+ flag.StringVar(&wsFile, "workspace-file", "", "Read the Workspace YAML from this file instead of AX_WORKSPACE_YAML")flag.Parse()logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo}))@@ -67,11 +57,12 @@ func main() {cfg.Task = &task}- workspaces, err := loadWorkspaces(wsFiles)- if err != nil {+ var ws v1alpha1.Workspace+ if err := loadSpec(wsFile, "AX_WORKSPACE_YAML", &ws); err != nil {fatal(err)+ } else if ws.GetMetadata() != nil {+ cfg.Workspace = &ws}- cfg.Workspaces = workspacesctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)defer stop()@@ -103,44 +94,6 @@ func loadSpec(file, envVar string, out any) error {return nil}-// loadWorkspaces reads Workspace documents from the given files, or when none-// are given from AX_WORKSPACES_YAML. Empty documents are skipped. It is not an-// error for no source to be present.-func loadWorkspaces(files []string) ([]*v1alpha1.Workspace, error) {- var sources [][]byte- switch {- case len(files) > 0:- for _, f := range files {- data, err := os.ReadFile(f)- if err != nil {- return nil, fmt.Errorf("reading %s: %w", f, err)- }- sources = append(sources, data)- }- case os.Getenv("AX_WORKSPACES_YAML") != "":- sources = append(sources, []byte(os.Getenv("AX_WORKSPACES_YAML")))- }-- var workspaces []*v1alpha1.Workspace- for _, src := range sources {- dec := yaml.NewDecoder(strings.NewReader(string(src)))- for {- var ws v1alpha1.Workspace- err := dec.Decode(&ws)- if errors.Is(err, io.EOF) {- break- }- if err != nil {- return nil, fmt.Errorf("parsing workspace yaml: %w", err)- }- if ws.GetMetadata() != nil {- workspaces = append(workspaces, &ws)- }- }- }- return workspaces, nil-}-func fatal(err error) {slog.Error("task runner failed", "error", err)os.Exit(1)diff --git a/cmd/ax/main.go b/cmd/ax/main.goindex 5c4e1cc..447a928 100644--- a/cmd/ax/main.go+++ b/cmd/ax/main.go@@ -697,16 +697,12 @@ func runDescribe(serverURL, atespace string, args []string) error {fmt.Printf("Actor: %s\n", actor)fmt.Printf("Worker IP: %s\n", workerIP)if task.Spec != nil {- if refs := task.Spec.WorkspaceRefs(); len(refs) > 0 {- paths := task.Spec.WorkspacePaths()- fmt.Println("Workspaces:")- for i, ref := range refs {- fmt.Printf(" - %s path=%s", ref.Name, paths[i])- if ref.Goal != "" {- fmt.Printf(" goal=%q", ref.Goal)- }- fmt.Println()+ if ref := task.Spec.GetWorkspace(); ref != nil {+ fmt.Printf("Workspace: %s path=%s", ref.Name, task.Spec.WorkspacePath())+ if ref.Goal != "" {+ fmt.Printf(" goal=%q", ref.Goal)}+ fmt.Println()}if task.Spec.Image != "" {fmt.Printf("Image: %s\n", task.Spec.Image)diff --git a/cmd/ax/main_test.go b/cmd/ax/main_test.goindex df96280..4c4078a 100644--- a/cmd/ax/main_test.go+++ b/cmd/ax/main_test.go@@ -314,7 +314,7 @@ type fakeMainReconciler struct {deleted chan struct{}}-func (f *fakeMainReconciler) Reconcile(ctx context.Context, task *v1alpha1.Task, workspaces ...*v1alpha1.Workspace) (*v1alpha1.Task, error) {+func (f *fakeMainReconciler) Reconcile(ctx context.Context, task *v1alpha1.Task, ws *v1alpha1.Workspace) (*v1alpha1.Task, error) {return task, nil}diff --git a/docs/concepts.md b/docs/concepts.mdindex 72bad3b..881c6ba 100644--- a/docs/concepts.md+++ b/docs/concepts.md@@ -4,7 +4,7 @@ Every AX resource lives in an **atespace**. The default atespace is `default`.## Task-The smallest unit of isolated execution. A `Task` declares the container image and command, compute limits, environment variables, and references to one or more `Workspace`s under `spec.workspaces`. Each workspace is mounted at its own path, and the first serves as the command's working directory.+The smallest unit of isolated execution. A `Task` declares the container image and command, compute limits, environment variables, and optionally a reference to a `Workspace` under `spec.workspace`. The workspace is mounted at `/workspace` unless the binding sets a path, and that path is the command's working directory.The unit is deliberately small. An agent is not one process that runs to completion; over its lifetime it plans, delegates, retries, and fans work out. AX does not try to model that shape. It gives you one primitive that is cheap to create, isolate, suspend, and throw away, and lets the agent compose as many of them as its work demands. A single task may be the whole job, or it may be the root of a large tree of tasks spawned as the agent breaks the problem down. Either way each node gets the same sandbox, the same lifecycle, and the same tooling.@@ -14,7 +14,7 @@ The unit is deliberately small. An agent is not one process that runs to complet| Condition | True when ||---|---|-| `WorkspaceReady` | Every workspace has finished setting up. Stays True afterwards. |+| `WorkspaceReady` | The workspace has finished setting up. Stays True afterwards. || `Ready` | The task is running and `WorkspaceReady` is True. This is the one to wait on. |Two transitions are worth knowing. Suspending a task sets `Ready` to False with reason `TaskSuspended`; resuming sets it back. Deleting a task tears down the sandbox on Agent Substrate and removes the record. `ax delete` blocks until that has completed.diff --git a/docs/manifests.md b/docs/manifests.mdindex 290b9fd..603c2ef 100644--- a/docs/manifests.md+++ b/docs/manifests.md@@ -26,28 +26,19 @@ spec:cpu: "2"memory: "4Gi"- workspaces:- - name: default-workspace- path: "/workspace"- goal: "Install dependencies and run the test suite" # Antigravity prepares the workspace to this goal on first run+ workspace:+ name: default-workspace+ path: "/workspace" # optional; this is the default+ goal: "Install dependencies and run the test suite" # Antigravity prepares the workspace to this goal on first rundebug: true # serve guest services inside the sandbox so `ax ssh` works; off by default```-### Binding several workspaces+### Binding a workspace-`spec.workspaces` takes as many entries as you like, so a task can compose reusable `Workspace` resources, for example the code to work on plus a shared set of tools:+A task binds at most one `Workspace` through `spec.workspace`. The binding needs a `name`; without a `path` the workspace is mounted at `/workspace`. That path is the working directory of `spec.command`, and the task reports `WorkspaceReady` once the workspace is prepared. A task with no `workspace` gets an empty working directory at `/workspace`.-```yaml-spec:- workspaces:- - name: my-service # mounted at /workspace/my-service, the command's working directory- goal: "Install dependencies and run the test suite"- - name: team-tools- path: "/workspace/tools" # explicit mount path-```--Each entry is set up independently at its own path, in order. Every entry needs a `name`; without a `path` it lands at `/workspace/<name>`, and paths must be unique. The first entry is the working directory of `spec.command`, and the task reports `WorkspaceReady` only once all of them are prepared. See [`examples/multi-workspace.yaml`](../examples/multi-workspace.yaml) for a complete set.+To work on content from several sources, put it all in one `Workspace`, for example by listing several repositories under `spec.git` or adding files through `spec.files`.### Sizing the sandboxdiff --git a/docs/runner.md b/docs/runner.mdindex e7328f0..02b3ec8 100644--- a/docs/runner.md+++ b/docs/runner.md@@ -15,7 +15,7 @@ The control plane does not run `spec.command` as the container entrypoint. It al| Container image | `spec.image`, or the default `ax-task-runner` image when unset || Container command | `/usr/local/bin/ax-task-runner`, always || `AX_TASK_YAML` | The `Task` launch configuration as YAML, excluding status |-| `AX_WORKSPACES_YAML` | Every bound `Workspace` resource as a multi-document YAML stream, in the task's binding order |+| `AX_WORKSPACE_YAML` | The bound `Workspace` resource as YAML; unset when the task binds none || `spec.env` entries | Each one set directly in the container environment || `GEMINI_API_KEY` | Set when the atespace has a Gemini credential configured || Volume | A durable directory mounted at `/workspace` |@@ -39,11 +39,11 @@ The `/workspace` volume is what survives suspend and resume. Agent Substrate sna| Path | Behavior ||---|---|| `/metadata/v1alpha1/ax/task` | Return the `Task` as `application/yaml`. Optional, but your command and `ax` tooling may expect it. |-| `/metadata/v1alpha1/ax/workspaces` | Return every bound `Workspace` as a multi-document YAML stream. Optional, as above. |+| `/metadata/v1alpha1/ax/workspace` | Return the bound `Workspace` as `application/yaml`, or `404` when there is none. Optional, as above. |-**Prepare each workspace once.** A task binds workspaces through `spec.workspaces`. For each binding, at its path, clone the Git repos from `spec.git`, create the skills path, write any MCP configuration, and run any environment bootstrap the binding asks for through its `goal`. A binding without a path lands at `/workspace/<name>`. Record that setup happened somewhere on the durable volume or in a known location, per workspace, then skip the work on later boots. Resume restarts the container, and re-cloning into a restored workspace would destroy the agent's state. The default runner writes a marker file under `/ax` for each workspace path.+**Prepare the workspace once.** A task binds at most one workspace through `spec.workspace`. At the binding's path, `/workspace` unless it sets one, clone the Git repos from `spec.git`, create the skills path, write any MCP configuration, and run any environment bootstrap the binding asks for through its `goal`. A task with no binding gets an empty `/workspace`. Record that setup happened somewhere on the durable volume or in a known location, then skip the work on later boots. Resume restarts the container, and re-cloning into a restored workspace would destroy the agent's state. The default runner writes a marker file under `/ax`.-**Run the command and supervise it.** Start `spec.command` as a child process with the first workspace as its working directory. Give it `AX_METADATA_URL` pointing at your loopback metadata server plus every `spec.env` entry. Put it in its own process group so you can signal everything it spawns.+**Run the command and supervise it.** Start `spec.command` as a child process with the workspace path as its working directory. Give it `AX_METADATA_URL` pointing at your loopback metadata server plus every `spec.env` entry. Put it in its own process group so you can signal everything it spawns.**Stay up after the command exits.** The runner is PID 1, and the container lives as long as it does. If the runner exits when the command does, the metadata server goes with it and `ax ssh` stops working. Log the exit status and keep serving until you are told to stop. The control plane does not currently read the command's exit status back from the container.@@ -91,7 +91,6 @@ import ("log/slog""os""os/signal"- "strings""syscall""github.com/google/ax/pkg/apis/v1alpha1"@@ -103,23 +102,19 @@ func main() {var task v1alpha1.Task_ = yaml.Unmarshal([]byte(os.Getenv("AX_TASK_YAML")), &task)- // AX_WORKSPACES_YAML is a multi-document stream, one Workspace per document.- var workspaces []*v1alpha1.Workspace- dec := yaml.NewDecoder(strings.NewReader(os.Getenv("AX_WORKSPACES_YAML")))- for {- var ws v1alpha1.Workspace- if err := dec.Decode(&ws); err != nil {- break- }- workspaces = append(workspaces, &ws)+ // AX_WORKSPACE_YAML is unset when the task binds no workspace.+ var ws *v1alpha1.Workspace+ if raw := os.Getenv("AX_WORKSPACE_YAML"); raw != "" {+ ws = &v1alpha1.Workspace{}+ _ = yaml.Unmarshal([]byte(raw), ws)}ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)defer stop()err := runner.Run(ctx, runner.Config{- Task: &task,- Workspaces: workspaces,+ Task: &task,+ Workspace: ws,OnCommandExit: func(exit runner.CommandExit) {slog.Info("agent finished", "exitCode", exit.ExitCode)// Upload artifacts, notify a webhook, and so on.@@ -136,7 +131,7 @@ Cross-compile it for `linux/amd64` with `CGO_ENABLED=0` and copy it into your im### 3. Write a runner from scratch-If the default lifecycle does not fit, for example because your agent framework already supervises processes or you want a different workspace layout, write your own in any language. Read `AX_TASK_YAML` and `AX_WORKSPACES_YAML`, satisfy the contract in the previous section, and install the result at `/usr/local/bin/ax-task-runner`. The `ax.io/v1alpha1` schema is defined in `pkg/apis/v1alpha1/ax.proto`, and [Manifests](manifests.md) walks through every field.+If the default lifecycle does not fit, for example because your agent framework already supervises processes or you want a different workspace layout, write your own in any language. Read `AX_TASK_YAML` and `AX_WORKSPACE_YAML`, satisfy the contract in the previous section, and install the result at `/usr/local/bin/ax-task-runner`. The `ax.io/v1alpha1` schema is defined in `pkg/apis/v1alpha1/ax.proto`, and [Manifests](manifests.md) walks through every field.### Ship it@@ -160,7 +155,7 @@ AX provisions a dedicated Agent Substrate actor template for each distinct imageThe default runner accepts its specs from files as well as the environment, which makes it easy to run outside a cluster. Your own runner should offer something similar:```bash-ax-task-runner --task-file task.yaml --workspace-file code.yaml --workspace-file tools.yaml --port 8080 --metadata-port 8099+ax-task-runner --task-file task.yaml --workspace-file code.yaml --port 8080 --metadata-port 8099# In another shell:curl -i http://127.0.0.1:8080/readyz@@ -172,11 +167,11 @@ Once the image is built, the fastest end-to-end check is a task with `debug: tru## Checklist- Executable present at `/usr/local/bin/ax-task-runner`-- Reads `AX_TASK_YAML` and `AX_WORKSPACES_YAML`-- Serves `/healthz` and `/readyz` on port 80, with `/readyz` returning `503` until every workspace is ready+- Reads `AX_TASK_YAML` and `AX_WORKSPACE_YAML`+- Serves `/healthz` and `/readyz` on port 80, with `/readyz` returning `503` until the workspace is ready- Serves the metadata endpoints on loopback only, at `AX_METADATA_URL`-- Prepares each workspace exactly once across restarts and resumes, at its own path-- Starts `spec.command` in the first workspace with `AX_METADATA_URL` and `spec.env`+- Prepares the workspace exactly once across restarts and resumes, at its path+- Starts `spec.command` in the workspace with `AX_METADATA_URL` and `spec.env`- Keeps running after the command exits- Forwards `SIGTERM` to the command's process group and exits after a grace period- Serves guest gRPC services on port 80 only when `spec.debug` is truediff --git a/docs/sandbox.md b/docs/sandbox.mdindex 3da1d3e..401d580 100644--- a/docs/sandbox.md+++ b/docs/sandbox.md@@ -25,7 +25,7 @@ Your agent can introspect its own configuration without any SDK. The metadata en| Endpoint | Method | Returns | Description ||---|---|---|---|| `/metadata/v1alpha1/ax/task` | `GET` | `application/yaml` | Task launch configuration, excluding status. |-| `/metadata/v1alpha1/ax/workspaces` | `GET` | `application/yaml` | Every bound `Workspace`, as a multi-document stream in binding order. |+| `/metadata/v1alpha1/ax/workspace` | `GET` | `application/yaml` | The bound `Workspace`. `404` when the task binds none. |```bash# From inside a task:diff --git a/examples/task.yaml b/examples/task.yamlindex c9d5467..ad825b7 100644--- a/examples/task.yaml+++ b/examples/task.yaml@@ -28,9 +28,8 @@ spec:cpu: "2"memory: "4Gi"- workspaces:- - name: default-workspace- path: "/workspace"+ workspace:+ name: default-workspacedebug: true # serve guest services so `ax ssh` works; off by default---diff --git a/internal/controller/reconciler.go b/internal/controller/reconciler.goindex 2ae24f6..136fe8e 100644--- a/internal/controller/reconciler.go+++ b/internal/controller/reconciler.go@@ -92,7 +92,7 @@ func NewTaskReconciler(client *substrate.Client, defaultTemplate, defaultTemplat}// Reconcile handles the reconciliation loop for a single Task.-func (r *TaskReconciler) Reconcile(ctx context.Context, task *v1alpha1.Task, workspaces ...*v1alpha1.Workspace) (*v1alpha1.Task, error) {+func (r *TaskReconciler) Reconcile(ctx context.Context, task *v1alpha1.Task, ws *v1alpha1.Workspace) (*v1alpha1.Task, error) {if task.Metadata == nil {task.Metadata = &v1alpha1.ObjectMeta{}}@@ -167,9 +167,11 @@ func (r *TaskReconciler) Reconcile(ctx context.Context, task *v1alpha1.Task, worextraEnv["AX_TASK_YAML"] = string(taskYAML)}- // Inject the bound Workspace specs as a multi-document YAML stream.- if wsYAML, err := marshalWorkspaces(workspaces); err == nil && wsYAML != "" {- extraEnv["AX_WORKSPACES_YAML"] = wsYAML+ // Inject the bound Workspace spec, if any.+ if ws != nil {+ if wsYAML, err := yaml.Marshal(ws); err == nil {+ extraEnv["AX_WORKSPACE_YAML"] = string(wsYAML)+ }}// Resource limits are enforced by the per-task template, so they are checked@@ -474,22 +476,3 @@ func (r *TaskReconciler) deleteTaskTemplates(ctx context.Context, atespace, task}return errors.Join(errs...)}--// marshalWorkspaces renders the workspaces as a multi-document YAML stream in-// order, skipping nil entries. It returns "" when there is nothing to render.-func marshalWorkspaces(workspaces []*v1alpha1.Workspace) (string, error) {- var sb strings.Builder- enc := yaml.NewEncoder(&sb)- for _, ws := range workspaces {- if ws == nil {- continue- }- if err := enc.Encode(ws); err != nil {- return "", err- }- }- if err := enc.Close(); err != nil {- return "", err- }- return sb.String(), nil-}diff --git a/internal/controller/reconciler_test.go b/internal/controller/reconciler_test.goindex d548c77..78d47c0 100644--- a/internal/controller/reconciler_test.go+++ b/internal/controller/reconciler_test.go@@ -258,7 +258,7 @@ func TestTaskReconciler(t *testing.T) {Status: &v1alpha1.TaskStatus{Actor: "not-the-task", Phase: "Running"},}- reconciled, err := reconciler.Reconcile(ctx, task)+ reconciled, err := reconciler.Reconcile(ctx, task, nil)if err != nil {t.Fatalf("Reconcile failed: %v", err)}@@ -551,7 +551,7 @@ func TestTaskReconciler_ResourceLimits(t *testing.T) {},}- if _, err := reconciler.Reconcile(ctx, task); err != nil {+ if _, err := reconciler.Reconcile(ctx, task, nil); err != nil {t.Fatalf("Reconcile failed: %v", err)}if len(mockSrv.createdTemplates) != 1 {@@ -568,7 +568,7 @@ func TestTaskReconciler_ResourceLimits(t *testing.T) {// Raising a limit is a launch configuration change and must provision a new// template, under a new name, carrying the new value.task.Spec.Resources.Limits.Memory = "8Gi"- if _, err := reconciler.Reconcile(ctx, task); err != nil {+ if _, err := reconciler.Reconcile(ctx, task, nil); err != nil {t.Fatalf("Reconcile with changed limits failed: %v", err)}if len(mockSrv.createdTemplates) != 2 {@@ -590,7 +590,7 @@ func TestTaskReconciler_ResourceLimits(t *testing.T) {Metadata: &v1alpha1.ObjectMeta{Name: "plain-task", Atespace: "default"},Spec: &v1alpha1.TaskSpec{Image: "ghrc.io/my-org/my-image"},}- if _, err := reconciler.Reconcile(ctx, plain); err != nil {+ if _, err := reconciler.Reconcile(ctx, plain, nil); err != nil {t.Fatalf("Reconcile of task without limits failed: %v", err)}if got := mockSrv.createdTemplates[len(mockSrv.createdTemplates)-1].GetResources(); got != nil {@@ -646,7 +646,7 @@ func TestTaskReconciler_ResourceLimitsFailurePaths(t *testing.T) {{Limits: &v1alpha1.ResourceList{Memory: "-4Gi"}},{Requests: &v1alpha1.ResourceList{Cpu: "500m"}, Limits: &v1alpha1.ResourceList{Cpu: "2"}},} {- reconciled, err := reconciler.Reconcile(ctx, newTask("bad-limits", reqs))+ reconciled, err := reconciler.Reconcile(ctx, newTask("bad-limits", reqs), nil)if err == nil {t.Errorf("Reconcile(%v) succeeded, want error", reqs)}@@ -669,7 +669,7 @@ func TestTaskReconciler_ResourceLimitsFailurePaths(t *testing.T) {reconciled, err := reconciler.Reconcile(ctx, newTask("rejected-limits", &v1alpha1.ResourcesSpec{Limits: &v1alpha1.ResourceList{Cpu: "2", Memory: "4Gi"},- }))+ }), nil)if err == nil {t.Fatal("Reconcile succeeded although the template with limits was rejected")}@@ -688,7 +688,7 @@ func TestTaskReconciler_ResourceLimitsFailurePaths(t *testing.T) {}reconciler := setup(t, mockSrv)- reconciled, err := reconciler.Reconcile(ctx, newTask("no-limits", nil))+ reconciled, err := reconciler.Reconcile(ctx, newTask("no-limits", nil), nil)if err != nil {t.Fatalf("Reconcile without limits failed: %v", err)}@@ -925,7 +925,7 @@ func TestTaskReconciler_TransientSubstrateUnavailable(t *testing.T) {Metadata: &v1alpha1.ObjectMeta{Name: "transient-atespace"},Spec: &v1alpha1.TaskSpec{Image: "ghrc.io/my-org/my-image"},}- reconciled, err := reconciler.Reconcile(ctx, task)+ reconciled, err := reconciler.Reconcile(ctx, task, nil)if err == nil {t.Fatal("expected error from Reconcile when EnsureAtespace fails, got nil")}@@ -941,7 +941,7 @@ func TestTaskReconciler_TransientSubstrateUnavailable(t *testing.T) {Metadata: &v1alpha1.ObjectMeta{Name: "transient-actor"},Spec: &v1alpha1.TaskSpec{Image: "ghrc.io/my-org/my-image"},}- reconciled2, err := reconciler.Reconcile(ctx, task2)+ reconciled2, err := reconciler.Reconcile(ctx, task2, nil)if err == nil {t.Fatal("expected error from Reconcile when EnsureActor fails, got nil")}@@ -959,7 +959,7 @@ func TestTaskReconciler_TransientSubstrateUnavailable(t *testing.T) {Spec: &v1alpha1.TaskSpec{Image: "ghrc.io/my-org/my-image"},Status: &v1alpha1.TaskStatus{Phase: "Running"},}- reconciled3, err := reconciler.Reconcile(ctx, task3)+ reconciled3, err := reconciler.Reconcile(ctx, task3, nil)if err == nil {t.Fatal("expected error from Reconcile when ResumeActor fails, got nil")}@@ -971,7 +971,7 @@ func TestTaskReconciler_TransientSubstrateUnavailable(t *testing.T) {// Recovery on retry:mockSrv.resumeActorErr = nilreconciled3.Status.Phase = "Running"- recovered, err := reconciler.Reconcile(ctx, reconciled3)+ recovered, err := reconciler.Reconcile(ctx, reconciled3, nil)if err != nil {t.Fatalf("expected Reconcile to succeed after Substrate recovers, got %v", err)}@@ -985,7 +985,7 @@ func TestTaskReconciler_TransientSubstrateUnavailable(t *testing.T) {Metadata: &v1alpha1.ObjectMeta{Name: "permanent-actor-err"},Spec: &v1alpha1.TaskSpec{Image: "ghrc.io/my-org/my-image"},}- reconciled4, err := reconciler.Reconcile(ctx, task4)+ reconciled4, err := reconciler.Reconcile(ctx, task4, nil)if err == nil {t.Fatal("expected error on InvalidArgument, got nil")}diff --git a/internal/metadata/server.go b/internal/metadata/server.goindex 803c00a..238d188 100644--- a/internal/metadata/server.go+++ b/internal/metadata/server.go@@ -44,7 +44,7 @@ type Server struct {grpcCleanup func()mu sync.RWMutextask *v1alpha1.Task- workspaces []*v1alpha1.Workspace+ workspace *v1alpha1.WorkspaceworkspaceReady bool}@@ -58,18 +58,17 @@ type ServerOptions struct {}// NewServer creates a new metadata and guest server serving the task and its-// bound workspaces, in the task's declaration order. Nil workspaces are dropped.-// port is the probe and guest port; the metadata endpoints use-// ServerOptions.MetadataPort on loopback. A zero port picks a free one; read-// the result from ProbeAddr or MetadataURL after Start.-func NewServer(port int, task *v1alpha1.Task, workspaces []*v1alpha1.Workspace, opts ...ServerOptions) *Server {+// bound workspace, which may be nil. port is the probe and guest port; the+// metadata endpoints use ServerOptions.MetadataPort on loopback. A zero port+// picks a free one; read the result from ProbeAddr or MetadataURL after Start.+func NewServer(port int, task *v1alpha1.Task, ws *v1alpha1.Workspace, opts ...ServerOptions) *Server {var opt ServerOptionsif len(opts) > 0 {opt = opts[0]}s := &Server{- task: task,- workspaces: compactWorkspaces(workspaces),+ task: task,+ workspace: ws,}// Guest services expose process execution and file access inside the container,@@ -118,10 +117,10 @@ func NewServer(port int, task *v1alpha1.Task, workspaces []*v1alpha1.Workspace,// Metadata endpoints, for the task command only:// /metadata/v1alpha1/ax/task the Task- // /metadata/v1alpha1/ax/workspaces every bound Workspace, as a YAML stream+ // /metadata/v1alpha1/ax/workspace the bound Workspace, as YAMLmetadataMux := http.NewServeMux()metadataMux.HandleFunc("/metadata/v1alpha1/ax/task", s.handleTask)- metadataMux.HandleFunc("/metadata/v1alpha1/ax/workspaces", s.handleWorkspaces)+ metadataMux.HandleFunc("/metadata/v1alpha1/ax/workspace", s.handleWorkspace)s.metadataServer = &http.Server{Addr: net.JoinHostPort("127.0.0.1", fmt.Sprint(opt.MetadataPort)),@@ -192,23 +191,12 @@ func (s *Server) Stop(ctx context.Context) error {return errors.Join(probeErr, metadataErr)}-// UpdateState allows dynamic updates to the current Task and Workspaces.-func (s *Server) UpdateState(task *v1alpha1.Task, workspaces []*v1alpha1.Workspace) {+// UpdateState allows dynamic updates to the current Task and Workspace.+func (s *Server) UpdateState(task *v1alpha1.Task, ws *v1alpha1.Workspace) {s.mu.Lock()defer s.mu.Unlock()s.task = task- s.workspaces = compactWorkspaces(workspaces)-}--// compactWorkspaces returns a copy of workspaces without nil entries.-func compactWorkspaces(workspaces []*v1alpha1.Workspace) []*v1alpha1.Workspace {- out := make([]*v1alpha1.Workspace, 0, len(workspaces))- for _, ws := range workspaces {- if ws != nil {- out = append(out, ws)- }- }- return out+ s.workspace = ws}// SetWorkspaceReady updates whether the maiden run workspace setup has completed.@@ -260,27 +248,20 @@ func (s *Server) handleTask(w http.ResponseWriter, r *http.Request) {}}-// handleWorkspaces serves every bound workspace as a multi-document YAML stream-// in the task's declaration order.-func (s *Server) handleWorkspaces(w http.ResponseWriter, r *http.Request) {+// handleWorkspace serves the bound workspace as YAML, or 404 when the task+// binds none.+func (s *Server) handleWorkspace(w http.ResponseWriter, r *http.Request) {s.mu.RLock()- workspaces := s.workspaces+ ws := s.workspaces.mu.RUnlock()- if len(workspaces) == 0 {+ if ws == nil {http.Error(w, "workspace metadata not available", http.StatusNotFound)return}w.Header().Set("Content-Type", "application/yaml")- enc := yaml.NewEncoder(w)- for _, ws := range workspaces {- if err := enc.Encode(ws); err != nil {- http.Error(w, err.Error(), http.StatusInternalServerError)- return- }- }- if err := enc.Close(); err != nil {+ if err := yaml.NewEncoder(w).Encode(ws); err != nil {http.Error(w, err.Error(), http.StatusInternalServerError)}}diff --git a/internal/metadata/server_test.go b/internal/metadata/server_test.goindex 209925b..a2cd6a0 100644--- a/internal/metadata/server_test.go+++ b/internal/metadata/server_test.go@@ -59,14 +59,7 @@ func TestMetadataServer(t *testing.T) {Spec: &v1alpha1.WorkspaceSpec{},}- ws2 := &v1alpha1.Workspace{- ApiVersion: v1alpha1.APIVersion,- Kind: v1alpha1.KindWorkspace,- Metadata: &v1alpha1.ObjectMeta{Name: "ws-tools", Atespace: "default"},- Spec: &v1alpha1.WorkspaceSpec{},- }-- srv := metadata.NewServer(0, task, []*v1alpha1.Workspace{ws, ws2})+ srv := metadata.NewServer(0, task, ws)if err := srv.Start(); err != nil {t.Fatalf("failed to start server: %v", err)}@@ -121,26 +114,19 @@ func TestMetadataServer(t *testing.T) {t.Errorf("expected task name 'task123', got %s", fetchedTask.Metadata.Name)}- // Test /metadata/v1alpha1/ax/workspaces returns every bound workspace in order- resp, err = http.Get(srv.MetadataURL() + "/metadata/v1alpha1/ax/workspaces")+ // Test /metadata/v1alpha1/ax/workspace returns the bound workspace+ resp, err = http.Get(srv.MetadataURL() + "/metadata/v1alpha1/ax/workspace")if err != nil {- t.Fatalf("get workspaces metadata failed: %v", err)+ t.Fatalf("get workspace metadata failed: %v", err)}defer resp.Body.Close()- var names []string- dec := yaml.NewDecoder(resp.Body)- for {- var doc v1alpha1.Workspace- if err := dec.Decode(&doc); err != nil {- if err == io.EOF {- break- }- t.Fatalf("decoding workspaces stream: %v", err)- }- names = append(names, doc.Metadata.Name)+ body, _ = io.ReadAll(resp.Body)+ var fetchedWS v1alpha1.Workspace+ if err := yaml.Unmarshal(body, &fetchedWS); err != nil {+ t.Fatalf("unmarshaling workspace yaml: %v", err)}- if len(names) != 2 || names[0] != "ws-default" || names[1] != "ws-tools" {- t.Errorf("expected workspaces [ws-default ws-tools], got %v", names)+ if fetchedWS.Metadata.Name != "ws-default" {+ t.Errorf("expected workspace 'ws-default', got %s", fetchedWS.Metadata.Name)}// Test multiplexed gRPC ProcessService on the same port@@ -227,7 +213,7 @@ func TestMetadataServer_MetadataOnlyOnLoopback(t *testing.T) {}// The metadata endpoints are not served on the probe port.- for _, path := range []string{"/metadata/v1alpha1/ax/task", "/metadata/v1alpha1/ax/workspaces"} {+ for _, path := range []string{"/metadata/v1alpha1/ax/task", "/metadata/v1alpha1/ax/workspace"} {resp, err := http.Get("http://" + srv.ProbeAddr() + path)if err != nil {t.Fatalf("request to probe port failed: %v", err)diff --git a/internal/server/server.go b/internal/server/server.goindex ee2b505..ac59496 100644--- a/internal/server/server.go+++ b/internal/server/server.go@@ -34,7 +34,7 @@ import (// Reconciler coordinates sandbox/actor lifecycles on Agent Substrate directly.type Reconciler interface {- Reconcile(ctx context.Context, task *v1alpha1.Task, workspaces ...*v1alpha1.Workspace) (*v1alpha1.Task, error)+ Reconcile(ctx context.Context, task *v1alpha1.Task, ws *v1alpha1.Workspace) (*v1alpha1.Task, error)ReconcileDelete(ctx context.Context, atespace, taskName string) error}@@ -186,8 +186,7 @@ func (s *Server) CreateTask(ctx context.Context, req *v1alpha1.CreateTaskRequest// Directly reconcile with Substrateif s.reconciler != nil {- workspaces := s.fetchWorkspaces(ctx, atespace, task)- reconciled, err := s.reconciler.Reconcile(ctx, task, workspaces...)+ reconciled, err := s.reconciler.Reconcile(ctx, task, s.fetchWorkspace(ctx, atespace, task))if err != nil {slog.Error("direct reconcile error on create task", "task", taskName, "error", err)if reconciled != nil && reconciled.Status != nil {@@ -299,8 +298,7 @@ func (s *Server) SuspendTask(ctx context.Context, req *v1alpha1.SuspendTaskRequetask.Status.Phase = "Suspended"if s.reconciler != nil {- workspaces := s.fetchWorkspaces(ctx, atespace, task)- reconciled, err := s.reconciler.Reconcile(ctx, task, workspaces...)+ reconciled, err := s.reconciler.Reconcile(ctx, task, s.fetchWorkspace(ctx, atespace, task))if err != nil {if substrate.IsTransientError(err) {return nil, status.Errorf(codes.Unavailable, "suspending task on substrate: %v", err)@@ -350,8 +348,7 @@ func (s *Server) ResumeTask(ctx context.Context, req *v1alpha1.ResumeTaskRequesttask.Status.Phase = "Running"if s.reconciler != nil {- workspaces := s.fetchWorkspaces(ctx, atespace, task)- reconciled, err := s.reconciler.Reconcile(ctx, task, workspaces...)+ reconciled, err := s.reconciler.Reconcile(ctx, task, s.fetchWorkspace(ctx, atespace, task))if err != nil {if reconciled != nil && reconciled.Status != nil {task.Status = reconciled.Status@@ -380,20 +377,18 @@ func (s *Server) ResumeTask(ctx context.Context, req *v1alpha1.ResumeTaskRequestreturn task, nil}-func (s *Server) fetchWorkspaces(ctx context.Context, atespace string, task *v1alpha1.Task) []*v1alpha1.Workspace {- var workspaces []*v1alpha1.Workspace- if task.Spec == nil {- return workspaces+// fetchWorkspace loads the Workspace the task binds, or nil when the task+// binds none or the Workspace does not exist.+func (s *Server) fetchWorkspace(ctx context.Context, atespace string, task *v1alpha1.Task) *v1alpha1.Workspace {+ name := task.GetSpec().GetWorkspace().GetName()+ if name == "" {+ return nil}- for _, ref := range task.Spec.WorkspaceRefs() {- if ref.Name == "" {- continue- }- if wsp, err := s.store.GetWorkspace(ctx, atespace, ref.Name); err == nil {- workspaces = append(workspaces, wsp)- }+ ws, err := s.store.GetWorkspace(ctx, atespace, name)+ if err != nil {+ return nil}- return workspaces+ return ws}func (s *Server) WatchTask(req *v1alpha1.WatchTaskRequest, stream grpc.ServerStreamingServer[v1alpha1.WatchTaskResponse]) error {diff --git a/internal/server/server_test.go b/internal/server/server_test.goindex 95ce797..dc4be1c 100644--- a/internal/server/server_test.go+++ b/internal/server/server_test.go@@ -283,28 +283,28 @@ func TestCreate_RejectsInvalidNames(t *testing.T) {}}-func TestCreateTask_ValidatesWorkspaceBindings(t *testing.T) {+func TestCreateTask_ValidatesWorkspaceBinding(t *testing.T) {srv := server.NewServer(memory.NewStore())ctx := context.Background()_, err := srv.CreateTask(ctx, &v1alpha1.CreateTaskRequest{Task: &v1alpha1.Task{Metadata: &v1alpha1.ObjectMeta{Name: "bad"},Spec: &v1alpha1.TaskSpec{- Workspaces: []*v1alpha1.WorkspaceRef{{Name: "a", Path: "/same"}, {Name: "b", Path: "/same"}},+ Workspace: &v1alpha1.WorkspaceRef{Path: "/w"},},}})if status.Code(err) != codes.InvalidArgument {- t.Fatalf("expected InvalidArgument for colliding workspace paths, got %v", err)+ t.Fatalf("expected InvalidArgument for a nameless workspace binding, got %v", err)}_, err = srv.CreateTask(ctx, &v1alpha1.CreateTaskRequest{Task: &v1alpha1.Task{Metadata: &v1alpha1.ObjectMeta{Name: "good"},Spec: &v1alpha1.TaskSpec{- Workspaces: []*v1alpha1.WorkspaceRef{{Name: "a"}, {Name: "b"}},+ Workspace: &v1alpha1.WorkspaceRef{Name: "a"},},}})if err != nil {- t.Fatalf("expected a valid multi-workspace task to be accepted, got %v", err)+ t.Fatalf("expected a valid workspace binding to be accepted, got %v", err)}}@@ -319,7 +319,7 @@ type fakeReconciler struct {onDelete func(ctx context.Context, atespace, taskName string) error}-func (f *fakeReconciler) Reconcile(ctx context.Context, task *v1alpha1.Task, workspaces ...*v1alpha1.Workspace) (*v1alpha1.Task, error) {+func (f *fakeReconciler) Reconcile(ctx context.Context, task *v1alpha1.Task, ws *v1alpha1.Workspace) (*v1alpha1.Task, error) {f.reconcileCount++f.observedTask = proto.Clone(task).(*v1alpha1.Task)if f.reconcileErr != nil {diff --git a/internal/workspace/setup.go b/internal/workspace/setup.goindex 78acf93..5898270 100644--- a/internal/workspace/setup.go+++ b/internal/workspace/setup.go@@ -331,8 +331,8 @@ func bootstrapTimeout() time.Duration {}// MarkerName returns the maiden-run marker file name for a workspace mounted at-// path. The name is derived from the path so several workspaces in one-// container track their setup independently.+// path. The name is derived from the path so a workspace mounted somewhere+// other than the default tracks its setup independently.func MarkerName(path string) string {if path == "" {path = defaultWorkspacePathdiff --git a/pkg/apis/v1alpha1/ax.pb.go b/pkg/apis/v1alpha1/ax.pb.goindex 27e9490..7e1ee96 100644--- a/pkg/apis/v1alpha1/ax.pb.go+++ b/pkg/apis/v1alpha1/ax.pb.go@@ -15,7 +15,7 @@// Code generated by protoc-gen-go. DO NOT EDIT.// versions:// protoc-gen-go v1.36.11-// protoc v5.28.2+// protoc v7.34.1// source: pkg/apis/v1alpha1/ax.protopackage v1alpha1@@ -180,9 +180,11 @@ type TaskSpec struct {Command []string `protobuf:"bytes,2,rep,name=command,proto3" json:"command,omitempty"`Env []*EnvVar `protobuf:"bytes,3,rep,name=env,proto3" json:"env,omitempty"`Resources *ResourcesSpec `protobuf:"bytes,4,opt,name=resources,proto3" json:"resources,omitempty"`- // workspaces binds one or more Workspaces, each mounted at its own path- // under /workspace. The first entry is the task command's working directory.- Workspaces []*WorkspaceRef `protobuf:"bytes,5,rep,name=workspaces,proto3" json:"workspaces,omitempty"`+ // workspace binds the Workspace the task works in. It is mounted at+ // /workspace unless the binding sets a path, and that path is the task+ // command's working directory. A task without a workspace gets an empty+ // working directory at /workspace.+ Workspace *WorkspaceRef `protobuf:"bytes,5,opt,name=workspace,proto3" json:"workspace,omitempty"`// debug enables the in-container guest services (process execution and file// access) that back `ax ssh`. Off by default.Debug bool `protobuf:"varint,6,opt,name=debug,proto3" json:"debug,omitempty"`@@ -248,9 +250,9 @@ func (x *TaskSpec) GetResources() *ResourcesSpec {return nil}-func (x *TaskSpec) GetWorkspaces() []*WorkspaceRef {+func (x *TaskSpec) GetWorkspace() *WorkspaceRef {if x != nil {- return x.Workspaces+ return x.Workspace}return nil}@@ -2446,15 +2448,13 @@ const file_pkg_apis_v1alpha1_ax_proto_rawDesc = "" +"\x04kind\x18\x02 \x01(\tR\x04kind\x123\n" +"\bmetadata\x18\x03 \x01(\v2\x17.ax.v1alpha1.ObjectMetaR\bmetadata\x12)\n" +"\x04spec\x18\x04 \x01(\v2\x15.ax.v1alpha1.TaskSpecR\x04spec\x12/\n" +- "\x06status\x18\x05 \x01(\v2\x17.ax.v1alpha1.TaskStatusR\x06status\"\xec\x01\n" ++ "\x06status\x18\x05 \x01(\v2\x17.ax.v1alpha1.TaskStatusR\x06status\"\xea\x01\n" +"\bTaskSpec\x12\x14\n" +"\x05image\x18\x01 \x01(\tR\x05image\x12\x18\n" +"\acommand\x18\x02 \x03(\tR\acommand\x12%\n" +"\x03env\x18\x03 \x03(\v2\x13.ax.v1alpha1.EnvVarR\x03env\x128\n" +- "\tresources\x18\x04 \x01(\v2\x1a.ax.v1alpha1.ResourcesSpecR\tresources\x129\n" +- "\n" +- "workspaces\x18\x05 \x03(\v2\x19.ax.v1alpha1.WorkspaceRefR\n" +- "workspaces\x12\x14\n" ++ "\tresources\x18\x04 \x01(\v2\x1a.ax.v1alpha1.ResourcesSpecR\tresources\x127\n" ++ "\tworkspace\x18\x05 \x01(\v2\x19.ax.v1alpha1.WorkspaceRefR\tworkspace\x12\x14\n" +"\x05debug\x18\x06 \x01(\bR\x05debug\"2\n" +"\x06EnvVar\x12\x12\n" +"\x04name\x18\x01 \x01(\tR\x04name\x12\x14\n" +@@ -2689,7 +2689,7 @@ var file_pkg_apis_v1alpha1_ax_proto_depIdxs = []int32{7, // 3: ax.v1alpha1.Task.status:type_name -> ax.v1alpha1.TaskStatus3, // 4: ax.v1alpha1.TaskSpec.env:type_name -> ax.v1alpha1.EnvVar4, // 5: ax.v1alpha1.TaskSpec.resources:type_name -> ax.v1alpha1.ResourcesSpec- 6, // 6: ax.v1alpha1.TaskSpec.workspaces:type_name -> ax.v1alpha1.WorkspaceRef+ 6, // 6: ax.v1alpha1.TaskSpec.workspace:type_name -> ax.v1alpha1.WorkspaceRef5, // 7: ax.v1alpha1.ResourcesSpec.requests:type_name -> ax.v1alpha1.ResourceList5, // 8: ax.v1alpha1.ResourcesSpec.limits:type_name -> ax.v1alpha1.ResourceList8, // 9: ax.v1alpha1.TaskStatus.conditions:type_name -> ax.v1alpha1.Conditiondiff --git a/pkg/apis/v1alpha1/ax.proto b/pkg/apis/v1alpha1/ax.protoindex 580d97c..aefa599 100644--- a/pkg/apis/v1alpha1/ax.proto+++ b/pkg/apis/v1alpha1/ax.proto@@ -72,9 +72,11 @@ message TaskSpec {repeated string command = 2;repeated EnvVar env = 3;ResourcesSpec resources = 4;- // workspaces binds one or more Workspaces, each mounted at its own path- // under /workspace. The first entry is the task command's working directory.- repeated WorkspaceRef workspaces = 5;+ // workspace binds the Workspace the task works in. It is mounted at+ // /workspace unless the binding sets a path, and that path is the task+ // command's working directory. A task without a workspace gets an empty+ // working directory at /workspace.+ WorkspaceRef workspace = 5;// debug enables the in-container guest services (process execution and file// access) that back `ax ssh`. Off by default.bool debug = 6;diff --git a/pkg/apis/v1alpha1/types.go b/pkg/apis/v1alpha1/types.goindex 3a74b77..5b98965 100644--- a/pkg/apis/v1alpha1/types.go+++ b/pkg/apis/v1alpha1/types.go@@ -203,45 +203,22 @@ func (w *Workspace) UnmarshalYAML(n *yaml.Node) error { return unmarshalYAML(n,func (m *Model) MarshalYAML() (any, error) { return marshalYAML(m) }func (m *Model) UnmarshalYAML(n *yaml.Node) error { return unmarshalYAML(n, m, normalizeModel) }-// Workspace bindings.+// Workspace binding.//-// A task binds one or more workspaces through spec.workspaces. Every entry is-// treated the same way regardless of how many there are.+// A task binds at most one workspace through spec.workspace.-// DefaultWorkspacePath is the durable volume every workspace lives under. A-// binding without a path is mounted at DefaultWorkspacePath/<name>, and a task-// with no bindings gets an empty working directory at DefaultWorkspacePath.+// DefaultWorkspacePath is where the task's workspace is mounted unless the+// binding sets a path. It is the task command's working directory, and a task+// with no workspace gets an empty directory there.const DefaultWorkspacePath = "/workspace"-// WorkspaceRefs returns the workspaces the task binds, in declaration order,-// with nil entries dropped.-func (s *TaskSpec) WorkspaceRefs() []*WorkspaceRef {- if s == nil {- return nil+// WorkspacePath returns the task command's working directory: the bound+// workspace's path when set, otherwise DefaultWorkspacePath.+func (s *TaskSpec) WorkspacePath() string {+ if p := s.GetWorkspace().GetPath(); p != "" {+ return p}- out := make([]*WorkspaceRef, 0, len(s.GetWorkspaces()))- for _, r := range s.GetWorkspaces() {- if r != nil {- out = append(out, r)- }- }- return out-}--// WorkspacePaths returns the mount path of each workspace in WorkspaceRefs, in-// the same order. An explicit path wins; otherwise the workspace lands at-// DefaultWorkspacePath/<name>.-func (s *TaskSpec) WorkspacePaths() []string {- refs := s.WorkspaceRefs()- paths := make([]string, len(refs))- for i, r := range refs {- if r.GetPath() != "" {- paths[i] = r.GetPath()- } else {- paths[i] = DefaultWorkspacePath + "/" + r.GetName()- }- }- return paths+ return DefaultWorkspacePath}// Resource names.@@ -312,33 +289,13 @@ func ValidateTask(t *Task) error {return err}spec := t.GetSpec()- if spec == nil {- return nil- }- refs := spec.WorkspaceRefs()- paths := spec.WorkspacePaths()- names := make(map[string]bool, len(refs))- seen := make(map[string]string, len(refs))- for i, r := range refs {- field := fmt.Sprintf("spec.workspaces[%d]", i)- if r.GetName() == "" {- return fmt.Errorf("%s: name is required", field)- }- if names[r.GetName()] {- return fmt.Errorf("%s: workspace %q is bound more than once", field, r.GetName())- }- names[r.GetName()] = true- if r.GetPath() != "" && !strings.HasPrefix(r.GetPath(), "/") {- return fmt.Errorf("%s: path %q must be absolute", field, r.GetPath())- }- p := strings.TrimRight(paths[i], "/")- if p == "" {- p = "/"+ if ref := spec.GetWorkspace(); ref != nil {+ if ref.GetName() == "" {+ return errors.New("spec.workspace: name is required")}- if other, dup := seen[p]; dup {- return fmt.Errorf("%s: path %q is already used by workspace %q", field, paths[i], other)+ if p := ref.GetPath(); p != "" && !strings.HasPrefix(p, "/") {+ return fmt.Errorf("spec.workspace: path %q must be absolute", p)}- seen[p] = r.GetName()}return ValidateResources(spec.GetResources())}diff --git a/pkg/apis/v1alpha1/types_test.go b/pkg/apis/v1alpha1/types_test.goindex 286df86..e6fefbe 100644--- a/pkg/apis/v1alpha1/types_test.go+++ b/pkg/apis/v1alpha1/types_test.go@@ -44,8 +44,8 @@ func fullTask() *v1alpha1.Task {Resources: &v1alpha1.ResourcesSpec{Requests: &v1alpha1.ResourceList{Cpu: "500m", Memory: "1Gi"},},- Workspaces: []*v1alpha1.WorkspaceRef{{Name: "ws", Path: "/workspace", Goal: "build"}},- Debug: true,+ Workspace: &v1alpha1.WorkspaceRef{Name: "ws", Path: "/workspace", Goal: "build"},+ Debug: true,},Status: &v1alpha1.TaskStatus{Phase: "Running",@@ -225,25 +225,6 @@ spec:}}-// The original schema bound a single workspace under spec.workspace. That field-// is gone, so manifests still using it are rejected like any unknown field.-func TestTask_SingularWorkspace_Rejected(t *testing.T) {- taskYAML := `-apiVersion: ax.io/v1alpha1-kind: Task-metadata:- name: test-task-spec:- workspace:- name: default-workspace-`- var task v1alpha1.Task- err := yaml.Unmarshal([]byte(taskYAML), &task)- if err == nil || !strings.Contains(err.Error(), "workspace") {- t.Fatalf("expected spec.workspace to be rejected as unknown, got %v", err)- }-}-func TestModel_SecretKey_UnmarshalYAML(t *testing.T) {cases := map[string]string{"structured": `@@ -336,34 +317,23 @@ func mustStruct(t *testing.T, m map[string]any) *structpb.Struct {return s}-func TestTaskSpec_WorkspaceRefs(t *testing.T) {- single := &v1alpha1.TaskSpec{Workspaces: []*v1alpha1.WorkspaceRef{{Name: "one"}}}- if refs := single.WorkspaceRefs(); len(refs) != 1 || refs[0].Name != "one" {- t.Errorf("single: refs = %v", refs)- }- if paths := single.WorkspacePaths(); len(paths) != 1 || paths[0] != v1alpha1.DefaultWorkspacePath+"/one" {- t.Errorf("single: paths = %v, want [%s/one]", paths, v1alpha1.DefaultWorkspacePath)- }-- multi := &v1alpha1.TaskSpec{Workspaces: []*v1alpha1.WorkspaceRef{- {Name: "code"},- nil,- {Name: "tools", Path: "/opt/tools"},- }}- refs := multi.WorkspaceRefs()- if len(refs) != 2 || refs[0].Name != "code" || refs[1].Name != "tools" {- t.Errorf("multi: refs = %v", refs)- }- if paths := multi.WorkspacePaths(); len(paths) != 2 || paths[0] != "/workspace/code" || paths[1] != "/opt/tools" {- t.Errorf("multi: paths = %v", paths)- }-- var nilSpec *v1alpha1.TaskSpec- if refs := nilSpec.WorkspaceRefs(); len(refs) != 0 {- t.Errorf("nil spec: refs = %v", refs)+func TestTaskSpec_WorkspacePath(t *testing.T) {+ tests := []struct {+ name string+ spec *v1alpha1.TaskSpec+ want string+ }{+ {name: "nil spec", want: v1alpha1.DefaultWorkspacePath},+ {name: "no workspace", spec: &v1alpha1.TaskSpec{}, want: v1alpha1.DefaultWorkspacePath},+ {name: "default path", spec: &v1alpha1.TaskSpec{Workspace: &v1alpha1.WorkspaceRef{Name: "one"}}, want: v1alpha1.DefaultWorkspacePath},+ {name: "explicit path", spec: &v1alpha1.TaskSpec{Workspace: &v1alpha1.WorkspaceRef{Name: "one", Path: "/opt/code"}}, want: "/opt/code"},}- if paths := (&v1alpha1.TaskSpec{}).WorkspacePaths(); len(paths) != 0 {- t.Errorf("empty spec: paths = %v", paths)+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ if got := tt.spec.WorkspacePath(); got != tt.want {+ t.Errorf("WorkspacePath() = %q, want %q", got, tt.want)+ }+ })}}@@ -453,39 +423,18 @@ func TestValidateTask(t *testing.T) {wantErr string}{{name: "nil spec"},- {name: "no workspaces", spec: &v1alpha1.TaskSpec{}},- {name: "list of one", spec: &v1alpha1.TaskSpec{Workspaces: []*v1alpha1.WorkspaceRef{{Name: "a"}}}},+ {name: "no workspace", spec: &v1alpha1.TaskSpec{}},+ {name: "default path", spec: &v1alpha1.TaskSpec{Workspace: &v1alpha1.WorkspaceRef{Name: "a"}}},+ {name: "explicit path", spec: &v1alpha1.TaskSpec{Workspace: &v1alpha1.WorkspaceRef{Name: "a", Path: "/x"}}},{- name: "nameless entry with path",- spec: &v1alpha1.TaskSpec{Workspaces: []*v1alpha1.WorkspaceRef{{Path: "/w"}}},- wantErr: "spec.workspaces[0]: name is required",- },- {name: "list default paths", spec: &v1alpha1.TaskSpec{Workspaces: []*v1alpha1.WorkspaceRef{{Name: "a"}, {Name: "b"}}}},- {name: "list explicit paths", spec: &v1alpha1.TaskSpec{Workspaces: []*v1alpha1.WorkspaceRef{{Name: "a", Path: "/x"}, {Name: "b", Path: "/y"}}}},- {- name: "nameless entry in list",- spec: &v1alpha1.TaskSpec{Workspaces: []*v1alpha1.WorkspaceRef{{Name: "a"}, {Path: "/b"}}},- wantErr: "spec.workspaces[1]: name is required",- },- {- name: "duplicate name",- spec: &v1alpha1.TaskSpec{Workspaces: []*v1alpha1.WorkspaceRef{{Name: "a", Path: "/x"}, {Name: "a", Path: "/y"}}},- wantErr: `workspace "a" is bound more than once`,- },- {- name: "duplicate path",- spec: &v1alpha1.TaskSpec{Workspaces: []*v1alpha1.WorkspaceRef{{Name: "a", Path: "/same"}, {Name: "b", Path: "/same/"}}},- wantErr: `path "/same/" is already used by workspace "a"`,- },- {- name: "default path collides with explicit",- spec: &v1alpha1.TaskSpec{Workspaces: []*v1alpha1.WorkspaceRef{{Name: "a"}, {Name: "b", Path: "/workspace/a"}}},- wantErr: "already used",+ name: "nameless binding",+ spec: &v1alpha1.TaskSpec{Workspace: &v1alpha1.WorkspaceRef{Path: "/w"}},+ wantErr: "spec.workspace: name is required",},{name: "relative path",- spec: &v1alpha1.TaskSpec{Workspaces: []*v1alpha1.WorkspaceRef{{Name: "a", Path: "rel"}}},- wantErr: "spec.workspaces[0]: path \"rel\" must be absolute",+ spec: &v1alpha1.TaskSpec{Workspace: &v1alpha1.WorkspaceRef{Name: "a", Path: "rel"}},+ wantErr: "spec.workspace: path \"rel\" must be absolute",},}for _, tt := range tests {@@ -504,33 +453,32 @@ func TestValidateTask(t *testing.T) {}}-func TestTask_Workspaces_YAML(t *testing.T) {+func TestTask_Workspace_YAML(t *testing.T) {taskYAML := `apiVersion: ax.io/v1alpha1kind: Taskmetadata:- name: multi+ name: singlespec:- workspaces:- - name: code- goal: "build it"- - name: tools- path: /opt/tools+ workspace:+ name: code+ path: /opt/code+ goal: "build it"`var task v1alpha1.Taskif err := yaml.Unmarshal([]byte(taskYAML), &task); err != nil {t.Fatalf("unmarshaling task: %v", err)}- refs := task.Spec.WorkspaceRefs()- if len(refs) != 2 || refs[0].Name != "code" || refs[0].Goal != "build it" || refs[1].Path != "/opt/tools" {- t.Fatalf("unexpected refs: %v", refs)+ ref := task.Spec.GetWorkspace()+ if ref == nil || ref.Name != "code" || ref.Path != "/opt/code" || ref.Goal != "build it" {+ t.Fatalf("unexpected workspace binding: %v", ref)}out, err := yaml.Marshal(&task)if err != nil {t.Fatal(err)}- if !strings.Contains(string(out), "workspaces:") || strings.Contains(string(out), "\n workspace:") {- t.Errorf("expected workspaces list and no singular workspace in output:\n%s", out)+ if !strings.Contains(string(out), "workspace:") || strings.Contains(string(out), "workspaces:") {+ t.Errorf("expected a singular workspace mapping in output:\n%s", out)}var back v1alpha1.Taskif err := yaml.Unmarshal(out, &back); err != nil {@@ -539,6 +487,22 @@ spec:if !proto.Equal(&task, &back) {t.Errorf("round trip changed the task:\n%s", out)}++ // The earlier spec.workspaces list is no longer part of the schema, so+ // manifests still using it are rejected like any unknown field.+ listYAML := `+apiVersion: ax.io/v1alpha1+kind: Task+metadata:+ name: multi+spec:+ workspaces:+ - name: code+`+ var rejected v1alpha1.Task+ if err := yaml.Unmarshal([]byte(listYAML), &rejected); err == nil {+ t.Error("expected spec.workspaces list to be rejected")+ }}func TestWorkspace_Files_YAML(t *testing.T) {diff --git a/runner/runner.go b/runner/runner.goindex cd1fb78..0124582 100644--- a/runner/runner.go+++ b/runner/runner.go@@ -43,8 +43,8 @@ const (// DefaultMetadataPort is the loopback port for the metadata endpoints when// Config.MetadataPort is zero.DefaultMetadataPort = 8099- // DefaultWorkspacePath is the command's working directory when the task- // binds no workspaces.+ // DefaultWorkspacePath is the command's working directory unless the task's+ // workspace binding sets a path.DefaultWorkspacePath = v1alpha1.DefaultWorkspacePath// stopGracePeriod is how long a running task command gets to exit after@@ -61,44 +61,15 @@ type Config struct {// command reads through AX_METADATA_URL. Zero means DefaultMetadataPort.MetadataPort int// Task is the task to run. It supplies the command, its environment, and- // the workspace bindings. Nil runs with no command and default settings.+ // the workspace binding. Nil runs with no command and default settings.Task *v1alpha1.Task- // Workspaces are the Workspace resources the task binds. Each is matched to- // an entry of the task's spec.workspaces by name.- Workspaces []*v1alpha1.Workspace+ // Workspace is the Workspace resource the task's spec.workspace refers to.+ // Nil sets up an empty working directory instead.+ Workspace *v1alpha1.Workspace// OnCommandExit, when set, is called once the task command has exited.OnCommandExit func(CommandExit)}-// mount pairs one workspace binding from the task spec with the Workspace-// resource that satisfies it and the path it is set up at.-type mount struct {- ref *v1alpha1.WorkspaceRef- ws *v1alpha1.Workspace- path string-}--// resolveMounts lines up the task's workspace bindings with the Workspace-// resources in cfg. Bindings are matched by name; a binding whose Workspace was-// not supplied is set up as an empty directory.-func resolveMounts(cfg Config) []mount {- byName := make(map[string]*v1alpha1.Workspace, len(cfg.Workspaces))- for _, ws := range cfg.Workspaces {- if ws != nil {- byName[ws.GetMetadata().GetName()] = ws- }- }-- spec := cfg.Task.GetSpec()- refs := spec.WorkspaceRefs()- paths := spec.WorkspacePaths()- mounts := make([]mount, len(refs))- for i, ref := range refs {- mounts[i] = mount{ref: ref, ws: byName[ref.GetName()], path: paths[i]}- }- return mounts-}-// CommandExit describes how the task command finished.type CommandExit struct {// Pid of the command's process.@@ -111,10 +82,10 @@ type CommandExit struct {// Run executes the task-runner lifecycle and blocks until ctx is cancelled.//-// Every workspace the task binds is set up in declaration order, each at its-// own path. The task's spec.command, if any, is then started as a child process-// in its own process group with the first workspace as its working directory-// and AX_METADATA_URL plus spec.env in its environment. The metadata and guest+// The task's workspace is set up at its path, /workspace unless the binding+// says otherwise. The task's spec.command, if any, is then started as a child+// process in its own process group with that path as its working directory and+// AX_METADATA_URL plus spec.env in its environment. The metadata and guest// server keeps serving whether or not the command is still running. When ctx is// cancelled a running command is sent SIGTERM, given a grace period, and then// killed.@@ -131,23 +102,11 @@ func Run(ctx context.Context, cfg Config) error {if metadataPort <= 0 {metadataPort = DefaultMetadataPort}- mounts := resolveMounts(cfg)- if len(mounts) == 0 {- // Nothing bound: still provide an empty working directory at the default path.- mounts = []mount{{ref: &v1alpha1.WorkspaceRef{}, path: DefaultWorkspacePath}}- }- wsPath := mounts[0].path- workspaces := make([]*v1alpha1.Workspace, 0, len(mounts))- paths := make([]string, len(mounts))- for i, m := range mounts {- paths[i] = m.path- if m.ws != nil {- workspaces = append(workspaces, m.ws)- }- }- slog.Info("initializing AX task runner", "port", port, "wsPath", wsPath, "workspaces", paths)+ ref := cfg.Task.GetSpec().GetWorkspace()+ wsPath := cfg.Task.GetSpec().WorkspacePath()+ slog.Info("initializing AX task runner", "port", port, "workspace", ref.GetName(), "wsPath", wsPath)- metaServer := metadata.NewServer(port, cfg.Task, workspaces, metadata.ServerOptions{+ metaServer := metadata.NewServer(port, cfg.Task, cfg.Workspace, metadata.ServerOptions{WorkspacePath: wsPath,MetadataPort: metadataPort,})@@ -164,16 +123,11 @@ func Run(ctx context.Context, cfg Config) error {_ = metaServer.Stop(context.Background())}()- ready := true- for _, m := range mounts {- if _, err := workspace.SetupWorkspace(ctx, m.ws, m.path, m.ref.GetGoal()); err != nil {- slog.Error("workspace maiden run setup failed", "workspace", m.ref.GetName(), "path", m.path, "error", err)- ready = false- }- }- if ready {+ if _, err := workspace.SetupWorkspace(ctx, cfg.Workspace, wsPath, ref.GetGoal()); err != nil {+ slog.Error("workspace maiden run setup failed", "workspace", ref.GetName(), "path", wsPath, "error", err)+ } else {metaServer.SetWorkspaceReady(true)- slog.Info("workspace maiden run setup marked ready", "count", len(mounts))+ slog.Info("workspace maiden run setup marked ready", "path", wsPath)}cmdArgs := cfg.Task.GetSpec().GetCommand()diff --git a/runner/runner_test.go b/runner/runner_test.goindex 2810adc..4e2a63b 100644--- a/runner/runner_test.go+++ b/runner/runner_test.go@@ -174,7 +174,7 @@ func newHarness(t *testing.T) *harness {}h.task = &v1alpha1.Task{Metadata: &v1alpha1.ObjectMeta{Name: "lib-task", Atespace: "default"},- Spec: &v1alpha1.TaskSpec{Workspaces: []*v1alpha1.WorkspaceRef{{Name: "ws", Path: h.wsPath}}},+ Spec: &v1alpha1.TaskSpec{Workspace: &v1alpha1.WorkspaceRef{Name: "ws", Path: h.wsPath}},}h.cfg = runner.Config{Port: freePort(t),@@ -244,21 +244,14 @@ func freePort(t *testing.T) int {return lis.Addr().(*net.TCPAddr).Port}-func TestRun_SetsUpEveryWorkspace(t *testing.T) {+func TestRun_SetsUpBoundWorkspace(t *testing.T) {h := newHarness(t)root := t.TempDir()codePath := filepath.Join(root, "code")- toolsPath := filepath.Join(root, "tools")outFile := filepath.Join(root, "out.txt")- h.task.Spec.Workspaces = []*v1alpha1.WorkspaceRef{- {Name: "code", Path: codePath},- {Name: "tools", Path: toolsPath},- }- h.cfg.Workspaces = []*v1alpha1.Workspace{- {Metadata: &v1alpha1.ObjectMeta{Name: "tools"}, Spec: &v1alpha1.WorkspaceSpec{}},- {Metadata: &v1alpha1.ObjectMeta{Name: "code"}, Spec: &v1alpha1.WorkspaceSpec{}},- }+ h.task.Spec.Workspace = &v1alpha1.WorkspaceRef{Name: "code", Path: codePath}+ h.cfg.Workspace = &v1alpha1.Workspace{Metadata: &v1alpha1.ObjectMeta{Name: "code"}, Spec: &v1alpha1.WorkspaceSpec{}}h.task.Spec.Command = []string{"sh", "-c", "pwd > " + outFile}exit := h.runUntilCommandExits(t)@@ -266,25 +259,23 @@ func TestRun_SetsUpEveryWorkspace(t *testing.T) {t.Fatalf("unexpected exit: %+v", exit)}- // Both workspace directories exist and each has its own maiden-run marker.- for _, p := range []string{codePath, toolsPath} {- if st, err := os.Stat(p); err != nil || !st.IsDir() {- t.Errorf("workspace dir %s missing: %v", p, err)- }- marker := filepath.Join(workspace.AXDir, workspace.MarkerName(p))- if _, err := os.Stat(marker); err != nil {- t.Errorf("marker %s missing: %v", marker, err)- }+ // The workspace directory exists and has its maiden-run marker.+ if st, err := os.Stat(codePath); err != nil || !st.IsDir() {+ t.Errorf("workspace dir %s missing: %v", codePath, err)+ }+ marker := filepath.Join(workspace.AXDir, workspace.MarkerName(codePath))+ if _, err := os.Stat(marker); err != nil {+ t.Errorf("marker %s missing: %v", marker, err)}- // The command ran in the first workspace.+ // The command ran in the workspace.out, _ := os.ReadFile(outFile)wantDir, _ := filepath.EvalSymlinks(codePath)if gotDir, _ := filepath.EvalSymlinks(strings.TrimSpace(string(out))); gotDir != wantDir {- t.Errorf("command cwd = %q, want first workspace %q", strings.TrimSpace(string(out)), codePath)+ t.Errorf("command cwd = %q, want workspace %q", strings.TrimSpace(string(out)), codePath)}- // Readiness reflects all workspaces, and the metadata server lists them in binding order.+ // Readiness reflects the workspace, and the metadata server serves it.resp, err := http.Get(fmt.Sprintf("http://127.0.0.1:%d/readyz", h.cfg.Port))if err != nil {t.Fatal(err)@@ -293,13 +284,13 @@ func TestRun_SetsUpEveryWorkspace(t *testing.T) {if resp.StatusCode != http.StatusOK {t.Errorf("readyz = %d, want 200", resp.StatusCode)}- resp, err = http.Get(fmt.Sprintf("http://127.0.0.1:%d/metadata/v1alpha1/ax/workspaces", h.cfg.MetadataPort))+ resp, err = http.Get(fmt.Sprintf("http://127.0.0.1:%d/metadata/v1alpha1/ax/workspace", h.cfg.MetadataPort))if err != nil {t.Fatal(err)}defer resp.Body.Close()body, _ := io.ReadAll(resp.Body)- if !strings.Contains(string(body), "name: code") || !strings.Contains(string(body), "name: tools") || strings.Index(string(body), "name: code") > strings.Index(string(body), "name: tools") {- t.Errorf("workspaces endpoint should list code then tools:\n%s", body)+ if !strings.Contains(string(body), "name: code") {+ t.Errorf("workspace endpoint should serve the bound workspace:\n%s", body)}}