Skip to content

Self-hosted workflows for coding-agent delivery. Orchestrate CodeBuddy, Codex and Claude Code with scripts and human approval gates. Includes Local workflows for coding assistants.

refactor(runtime): remove workspace instruction masks and script helper (#953)

crispinhu27c1fa0f7b16c7
diff --git a/cmd/agentflow-gate-mcp/main.go b/cmd/agentflow-gate-mcp/main.go
index 6fb4c300..c75f81f3 100644
--- a/cmd/agentflow-gate-mcp/main.go
+++ b/cmd/agentflow-gate-mcp/main.go
@@ -5,16 +5,9 @@ import (
"os"
"agentflow/internal/gatemcp"
- "agentflow/internal/scriptview"
)
func main() {
- if handled, err := scriptview.Run(os.Args[1:]); handled {
- if err != nil {
- log.Fatal(err)
- }
- return
- }
if err := gatemcp.Run(os.Stdin, os.Stdout, os.Getenv("AGENTFLOW_GATE_RESULT_PATH")); err != nil {
log.Fatal(err)
}
diff --git a/docs/conversation-native-cli.md b/docs/conversation-native-cli.md
index ffc385c7..a53a22e9 100644
--- a/docs/conversation-native-cli.md
+++ b/docs/conversation-native-cli.md
@@ -16,7 +16,7 @@ Docker 工作区内的原生文件、补丁和命令在三种审批模式下均
Runner 需要 0.10.1 或以上版本,该版本支持取消后台导出并释放工作区锁。Docker 镜像优先使用已安装的 CLI;支持官方安装器的 CLI 缺失时自动安装。ZCode 没有独立 npm 包,须在执行机器及工作区镜像内预装官方 CLI 并加入 PATH,缺失时明确报错。原生工具调用围栏与进程生命周期管理依赖 Python3。每个 Docker 会话阶段使用独立的 Linux 子进程收养进程,结束或取消时回收其全部后代,包含另建进程组的原生命令;不影响容器里的其他命令。平台会在启动前检查依赖,固定安装步骤以容器 root 用户在 `/` 中运行,实际 CLI 保留工作区的容器用户;无法准备时中止,不降级绕过调用围栏。建议在受控工作区镜像中预安装 CLI 和依赖。
-原生会话的工具回调在执行机器上中继。宿主进程使用 Docker host gateway;通过 docker.sock 管理工作区的容器进程自动识别自身容器网络,工作区加入相同网络并访问该地址。自定义路由可通过 `AGENTFLOW_CONVERSATION_RELAY_HOST` 和 `AGENTFLOW_CONVERSATION_DOCKER_NETWORK` 显式指定工作区能访问的执行进程地址与 Docker 网络。会话目录会以相同路径挂进工作区,而 docker.sock 背后的 Docker 守护进程按自己所在主机解析挂载源,因此容器内的平台进程须把 `AGENTFLOW_CONVERSATION_DIR` 设在与宿主机同路径挂载的目录中;`compose.yaml` 将其设为 `${LOOPFORGE_DATA_DIR}/conversations`。Runner 不读该变量,原生会话目录固定在其工作区根目录的 `.conversations` 下,容器内运行 Runner 时须同路径挂载该工作区目录。未设置时会话目录位于 `AGENTFLOW_ASSISTANT_SESSION_DIR` 下,该目录在命名卷里时打开工作区会报 `mkdirat ... read-only file system`。附件等按用户保存的助手数据仍在 `AGENTFLOW_ASSISTANT_SESSION_DIR`,不挂进工作区。Docker 工作区需要工作区脚本视图辅助程序:部署时设置 `AGENTFLOW_GATE_MCP_BINARY`(指向已构建的辅助二进制)或 `AGENTFLOW_SOURCE_ROOT`(源码目录,按需构建),两者都缺失时打开工作区会报 `script view helper unavailable`。
+原生会话的工具回调在执行机器上中继。宿主进程使用 Docker host gateway;通过 docker.sock 管理工作区的容器进程自动识别自身容器网络,工作区加入相同网络并访问该地址。自定义路由可通过 `AGENTFLOW_CONVERSATION_RELAY_HOST` 和 `AGENTFLOW_CONVERSATION_DOCKER_NETWORK` 显式指定工作区能访问的执行进程地址与 Docker 网络。会话目录会以相同路径挂进工作区,而 docker.sock 背后的 Docker 守护进程按自己所在主机解析挂载源,因此容器内的平台进程须把 `AGENTFLOW_CONVERSATION_DIR` 设在与宿主机同路径挂载的目录中;`compose.yaml` 将其设为 `${LOOPFORGE_DATA_DIR}/conversations`。Runner 不读该变量,原生会话目录固定在其工作区根目录的 `.conversations` 下,容器内运行 Runner 时须同路径挂载该工作区目录。未设置时会话目录位于 `AGENTFLOW_ASSISTANT_SESSION_DIR` 下,该目录在命名卷里时打开工作区会报 `mkdirat ... read-only file system`。附件等按用户保存的助手数据仍在 `AGENTFLOW_ASSISTANT_SESSION_DIR`,不挂进工作区。Docker 工作区直接在主容器中运行 SOP 脚本和 CLI。历史容器存在指令遮蔽挂载时,工作区下次取得执行权后会重建容器并保留工作区文件。标记为重建时运行的准备脚本随后在新容器补跑。
模式交接时,交接工具要求模型只回复一句「好的。」再结束旧阶段,交接之后的展示由平台隐藏;不要求“不输出任何内容”,否则模型可能只产出推理、没有正文的回合,该回合写入原生日志后,续接时会被模型服务拒绝(如 `the conversation must end with a user message`)。交接工具成功后,旧阶段即使未输出 `type=result` 或异常退出,也继续完成交接。续接原生会话时,如果原生日志缺失,或模型服务在本阶段产生任何输出或工具调用之前就拒绝了续接(400/422、会话结构无效、无结果退出),平台用完整对话上下文新建一次原生会话重试;已有输出或工具调用的中断,以及鉴权、限流、额度、网络、执行机器不可用等原因,仍续接原会话或直接报错,不重复执行副作用。
diff --git a/docs/deployment.md b/docs/deployment.md
index e50aea6f..d2f5829e 100644
--- a/docs/deployment.md
+++ b/docs/deployment.md
@@ -79,7 +79,7 @@ For native services running as an ordinary host user, default/root Docker images
The Compose deployment mounts the host Docker socket into the platform container so built-in AI SOPs run out of the box. `AGENTFLOW_ISOLATED_IMAGE` points to the installed platform image: default sandboxes start separate sibling containers from that same image, with no second CLI download or image build. They do not mount the Docker socket. Custom Dockerfiles still build and cache their own images. The run workspace is mounted at `/workspace` on the Compose network. Because bind mounts are resolved by the host Docker daemon, `LOOPFORGE_DATA_DIR` (written to `.env` by `scripts/configure.sh`, default `./.data`) is mounted into the platform container at the same absolute path; workspaces and CLI state live under it. Native conversation workspaces bind-mount their conversation roots the same way, so `compose.yaml` sets `AGENTFLOW_CONVERSATION_DIR` to `${LOOPFORGE_DATA_DIR}/conversations`. Attachments and other per-user assistant state stay in `AGENTFLOW_ASSISTANT_SESSION_DIR` (`/data/assistant` in the `platform-data` volume), which is never mounted into a workspace. A platform container whose `AGENTFLOW_CONVERSATION_DIR` is unset keeps conversation roots there too, and opening a conversation workspace then fails with `mkdirat ... read-only file system`.
-Access to the Docker socket is equivalent to root on the host. Two safeguards follow from that: the platform runs every task in a sandbox container, including SOPs configured for the `local` driver (`AGENTFLOW_LOCAL_SANDBOX=docker`), and only platform administrators can point a repository at a host source path. Even so, anyone who can run SOPs can execute code in containers on this host, so only give accounts to people you trust and do not expose the service to untrusted networks. To run without the socket, remove the `docker.sock` volume and the `AGENTFLOW_LOCAL_SANDBOX` setting from `compose.yaml`, then connect a separate Docker-capable worker or execution machine for AI SOPs; the script-only welcome SOP then runs inside the platform container.
+Access to the Docker socket is equivalent to root on the host. Two safeguards follow from that: the platform runs every task in a sandbox container, including SOPs configured for the `local` driver (`AGENTFLOW_LOCAL_SANDBOX=docker`), and only platform administrators can point a repository at a host source path. Even so, anyone who can run SOPs can execute code in containers on this host, so only give accounts to people you trust and do not expose the service to untrusted networks. Agent CLIs also apply a bound repository's own configuration as their native rules define, including unattended SOP runs: `AGENTS.md`/`CLAUDE.md` instructions, `.codebuddy/`, `.claude/settings.json` (hooks and environment) and `.mcp.json` can start commands or MCP servers inside the sandbox. Bind only repositories whose contents you trust. To run without the socket, remove the `docker.sock` volume and the `AGENTFLOW_LOCAL_SANDBOX` setting from `compose.yaml`, then connect a separate Docker-capable worker or execution machine for AI SOPs; the script-only welcome SOP then runs inside the platform container.
### Slow networks: clone and image build limits
diff --git a/docs/release-readiness.md b/docs/release-readiness.md
index 7e21eabf..c1e88181 100644
--- a/docs/release-readiness.md
+++ b/docs/release-readiness.md
@@ -11,7 +11,7 @@ The supported access model is explicit: signed-in users can read project data ac
## Final source and deployment review
- Independently checked all **1,718 recorded source blob hashes** against the recorded master. After the hosted-CI compatibility fixes, the candidate has 1,464 unchanged upstream files, 180 reviewed adaptations and 74 recorded exclusions, plus 60 audited public additions in the platform export scope. Private deployment files outside the export scope remain excluded. No private Git history is imported.
-- Latest upstream features include durable group-to-SOP handoff and isolated script views. Their source and tests are included. MySQL concurrent claims/lease recovery and Docker script views (including non-root identity) were explicitly exercised.
+- The runtime includes durable group-to-SOP handoff and executes SOP scripts directly in Docker workspaces. The Docker tests cover non-root execution and reopening previously masked workspaces. MySQL concurrent claims and lease recovery were explicitly exercised.
- The preview had still been running an older executable after the source sync. Rebuilt the service and runner/gate helpers, restarted the preview, and compared its key JavaScript assets byte-for-byte with the current source. The handoff acceptance case now exercises the current endpoint behavior.
- Fixed a remaining viewer permission gap in group creation, role dispatch, SOP control and handoff retry, and blocked run-bound assistant execution for read-only members. Tests cover denial for viewers/non-members and continued access for owners; viewer reads remain available. This generic permission fix should be ported back to internal upstream.
- Updated the source audit record and the checker: `--source` now verifies the actual source blobs as well as the remote commit label. No unrelated source hashes were reset.
diff --git a/docs/testing/acceptance-matrix.md b/docs/testing/acceptance-matrix.md
index 68ae2e27..569be002 100644
--- a/docs/testing/acceptance-matrix.md
+++ b/docs/testing/acceptance-matrix.md
@@ -34,7 +34,7 @@ Which automated cases protect each user-facing capability, and what they need. "
| Requirement spaces: CRUD, timeline, threads, artifacts, and members | `e2e/api/60-spaces.test.mjs` | — |
| Task groups and multi-role collaboration | `internal/httpapi/rooms_test.go`, `internal/repo/group_run_view_test.go`, `internal/runtime/workspace_preparation_test.go`, `webtest/tests/collaboration-groups.test.mjs` | No model |
| Group SOP handoff artifact inheritance | `internal/engine/state_helpers_cases_test.go`, `internal/engine/ops_validation_cases_test.go` | Engine `GroupSOPHandoff` only. `migrations/015_sop_handoff_jobs.sql` creates `sop_handoff_jobs` and `migrations/017_bot_sop_controls.sql` alters it, but no Go service reads or writes that table, so the job table is outside automatic coverage |
-| Script views isolated from agent instructions | `internal/runtime/sandbox_script_test.go`, `internal/scriptview/` | Linux/Docker cases as supported by the host |
+| Scripts and agents share the sandbox with repository instructions visible | `internal/runtime/sandbox_script_test.go` | Run Docker cases with `AGENTFLOW_DOCKER_SCRIPT_SMOKE=1` and local `alpine:3.20` |
| Data persists across container recreation | `e2e/container-persistence.mjs` via `scripts/test-container.sh` | Docker |
| Rooms, scheduled dispatch, platform MCP tools, credential flags never leaking | `e2e/api/50-platform.test.mjs` | — |
| Project integrations: notification bots, insight sources, business domains, and WeCom identity bindings | `e2e/api/62-integrations.test.mjs` | No outbound WeCom or insight call |
diff --git a/docs/validation.md b/docs/validation.md
index c774b1c9..88202bfd 100644
--- a/docs/validation.md
+++ b/docs/validation.md
@@ -115,7 +115,7 @@ Removed the viewport-sized blank space above expanded onboarding and tightened t
- `python3 scripts/check-upstream.py --source <private-checkout>` checked all **1,715** recorded source hashes against the actual Git blobs and confirmed that the recorded commit matches fetched `origin/master`. Public code adaptations and private deployment exclusions remain explicit.
- `TestSOPHandoffMySQLConcurrentClaimsAndLeaseRecovery` passed against an isolated disposable MySQL database. The fixture container was removed after the check.
-- Both opt-in Docker script-view cases passed: dependency removal with instruction masks and preservation of non-root execution identity. Reproduce with `AGENTFLOW_DOCKER_SCRIPT_SMOKE=1`, a local `alpine:3.20` fixture and the current gate binary.
+- The opt-in Docker cases cover a script and agent sharing the workspace container, non-root execution, and rebuilding an existing masked container with its saved files and preparation recipe. Run with `AGENTFLOW_DOCKER_SCRIPT_SMOKE=1` and a local `alpine:3.20` fixture.
- `e2e/api/66-sop-handoff.test.mjs` passed with real CodeBuddy/MySQL: user context persists, repeated requests reuse the active job, the summary is archived, and the selected SOP approval must still be explicitly accepted before continuation.
- The viewer patch is covered by `project_write_access_test.go`, `assistant_workbench_test.go` and the extended `e2e/api/58-permissions.test.mjs`. A viewer can read a run conversation but cannot turn that access into group dispatch, SOP control, handoff retry or workspace execution.
- The updated preview is supervised on port 8091. Its `assistant.js`, `collaboration.js` and `app/issues.js` contents matched the current embedded source. Preview freshness is not inferred solely from the JSON baseline label.
diff --git a/internal/engine/node_execute.go b/internal/engine/node_execute.go
index 23a24f62..7234e6b9 100644
--- a/internal/engine/node_execute.go
+++ b/internal/engine/node_execute.go
@@ -469,11 +469,8 @@ func (e *Engine) executeNode(ctx context.Context, runID string, wf domain.Workfl
ctx = withGitToken(ctx, gitTok)
ctx = gitwork.WithSSHKeys(ctx, gitCredentials.GitSSHKeys)
ctx = withGitIdentity(ctx, sb.credentialSnapshot().GitUserName, sb.credentialSnapshot().GitUserEmail)
- // Repository checkout and Agent-configuration index isolation belong to the
- // run environment, not to each node. The same checkout and .git/index are
- // reused by all nodes, so repeatedly toggling skip-worktree only creates
- // needless index.lock contention. A reconstructed runEnvironment (restart or
- // lease takeover) starts unprepared and revalidates the persisted checkout.
+ // Share the checkout between nodes. A reconstructed run environment
+ // revalidates the persisted checkout after restart or lease takeover.
// A runner that integrates on its own checkout needs nothing from a
// control-plane clone, so none is made.
stagingCheckout := true
@@ -484,20 +481,9 @@ func (e *Engine) executeNode(ctx context.Context, runID string, wf domain.Workfl
if !stagingCheckout {
return nil
}
- repoWorkspaces := repositoryWorkspaceDirs(sb.Workspace(), current.RepositoryContexts())
- for _, dir := range repoWorkspaces {
- if err := runtime.RestoreProjectAgentGitIndex(ctx, dir, sb.Driver()); err != nil {
- return fmt.Errorf("restore repository Agent configuration index: %w", err)
- }
- }
if err := prepareRepositories(ctx, sb.Workspace(), current.RepositoryContexts()); err != nil {
return explainGitAuthFailure(fmt.Errorf("repository checkout: %w", err), strings.TrimSpace(gitTok) != "")
}
- for _, dir := range repoWorkspaces {
- if err := runtime.ProtectProjectAgentGitIndex(ctx, dir, sb.Driver()); err != nil {
- return fmt.Errorf("protect repository Agent configuration index: %w", err)
- }
- }
for _, rc := range current.RepositoryContexts() {
e.observe(runID, node.ID, domain.TelemetryEvent{Category: "sandbox", Name: "repository.checked_out", Phase: "finish", Message: rc.Name + " @ " + rc.WorkBranch, Attributes: map[string]any{"repositoryId": rc.RepositoryID, "repositoryDir": rc.WorkspaceDir, "baseBranch": rc.BaseBranch, "workBranch": rc.WorkBranch}})
}
diff --git a/internal/engine/repository_workspace.go b/internal/engine/repository_workspace.go
index 718064b9..6c2c16f3 100644
--- a/internal/engine/repository_workspace.go
+++ b/internal/engine/repository_workspace.go
@@ -4,6 +4,7 @@ import (
"agentflow/internal/domain"
"agentflow/internal/gitwork"
"agentflow/internal/procwatch"
+ "agentflow/internal/runtime"
"bytes"
"context"
"crypto/rand"
@@ -57,8 +58,8 @@ func repositoryWorkspaceDirs(workspace string, repositories []domain.RepositoryC
// prepareRepositories checks out every run repository into its WorkspaceDir
// (a first-level sub-directory of the run workspace).
func prepareRepositories(ctx context.Context, workspace string, repositories []domain.RepositoryContext) error {
- if len(repositories) == 0 {
- return nil
+ if err := runtime.RestoreLegacyWorkspaceAgentConfig(ctx, workspace, repositories); err != nil {
+ return err
}
for _, rc := range repositories {
if err := prepareRepository(ctx, repositoryWorkspacePath(workspace, rc), rc); err != nil {
diff --git a/internal/engine/run_environment.go b/internal/engine/run_environment.go
index d2faf2a5..73920c67 100644
--- a/internal/engine/run_environment.go
+++ b/internal/engine/run_environment.go
@@ -56,8 +56,7 @@ func (r *runEnvironment) endReportedOutputs(nodeID string) {
delete(r.reported, nodeID)
}
-// prepareRepositoriesOnce keeps repository checkout and Agent-configuration
-// index isolation at the run-environment lifecycle rather than the node
+// prepareRepositoriesOnce keeps repository checkout at the run-environment
// lifecycle. nodeMu serializes callers, and a reconstructed environment starts
// with repositoriesPrepared=false so process restarts and lease takeovers
// still revalidate the persisted workspace once before executing a node.
diff --git a/internal/engine/run_environment_test.go b/internal/engine/run_environment_test.go
index b0e6dbf8..45e10fe2 100644
--- a/internal/engine/run_environment_test.go
+++ b/internal/engine/run_environment_test.go
@@ -141,7 +141,20 @@ func TestReconstructedRunEnvironmentCleansStaleAgentGitIndexLock(t *testing.T) {
runGit("commit", "-m", "baseline")
ctx := context.Background()
- if err := runtime.ProtectProjectAgentGitIndex(ctx, workspace, "docker"); err != nil {
+ runGit("update-index", "--skip-worktree", "AGENTS.md")
+ const legacyExcludes = `# AgentFlow managed sandbox: repository Agent configuration
+AGENTS.md
+AGENTS.override.md
+CLAUDE.md
+CLAUDE.local.md
+CODEBUDDY.md
+.mcp.json
+.agents/
+.codex/
+.claude/
+.codebuddy/
+`
+ if err := os.WriteFile(filepath.Join(workspace, ".git", "info", "exclude"), []byte(legacyExcludes), 0o600); err != nil {
t.Fatal(err)
}
lockPath := filepath.Join(workspace, ".git", "index.lock")
@@ -151,17 +164,11 @@ func TestReconstructedRunEnvironmentCleansStaleAgentGitIndexLock(t *testing.T) {
// A worker restart reconstructs runEnvironment while preserving the run
// workspace. The first node on the new worker must revalidate checkout and
- // isolation, remove a stale lock, then leave AGENTS.md protected again.
+ // make the existing instruction files visible to Git again.
reconstructed := &runEnvironment{}
repository := domain.RepositoryContext{RepositoryID: "repo", BaseBranch: "main", WorkBranch: "main"}
err := reconstructed.prepareRepositoriesOnce(func() error {
- if err := runtime.RestoreProjectAgentGitIndex(ctx, workspace, "docker"); err != nil {
- return err
- }
- if err := prepareRepository(ctx, workspace, repository); err != nil {
- return err
- }
- return runtime.ProtectProjectAgentGitIndex(ctx, workspace, "docker")
+ return prepareRepositories(ctx, workspace, []domain.RepositoryContext{repository})
})
if err != nil {
t.Fatalf("reconstruct run environment: %v", err)
@@ -169,7 +176,7 @@ func TestReconstructedRunEnvironmentCleansStaleAgentGitIndexLock(t *testing.T) {
if _, err := os.Stat(lockPath); !os.IsNotExist(err) {
t.Fatalf("stale index lock survived reconstruction: %v", err)
}
- if flag := runGit("ls-files", "-v", "--", "AGENTS.md"); !strings.HasPrefix(flag, "S ") {
- t.Fatalf("AGENTS.md protection after reconstruction = %q", flag)
+ if flag := runGit("ls-files", "-v", "--", "AGENTS.md"); !strings.HasPrefix(flag, "H ") {
+ t.Fatalf("AGENTS.md index flag after reconstruction = %q", flag)
}
}
diff --git a/internal/runner/daemon.go b/internal/runner/daemon.go
index 1fc88766..c4ea0e8d 100644
--- a/internal/runner/daemon.go
+++ b/internal/runner/daemon.go
@@ -717,7 +717,7 @@ func (d *Daemon) executeTerminal(ctx context.Context, task domain.RunnerTask) ex
return execResult{status: domain.RunnerTaskFailed, errMsg: fmt.Sprintf("workspace %s: %v", workspace, err)}
}
if task.Invocation != nil {
- if err := checkoutInvocationRepositories(ctx, workspace, task.Invocation, runnerTaskSandboxDriver(task)); err != nil {
+ if err := checkoutInvocationRepositories(ctx, workspace, task.Invocation); err != nil {
return execResult{status: domain.RunnerTaskFailed, errMsg: fmt.Sprintf("repository checkout: %v", err)}
}
if err := writeRunnerHumanContext(workspace, task.Invocation.HumanContext); err != nil {
@@ -797,7 +797,7 @@ func (d *Daemon) executeInvocation(ctx context.Context, task domain.RunnerTask)
if err := os.MkdirAll(workspace, 0o755); err != nil {
return execResult{status: domain.RunnerTaskFailed, errMsg: fmt.Sprintf("workspace %s: %v", workspace, err)}, nil
}
- if err := checkoutInvocationRepositories(ctx, workspace, inv, runnerTaskSandboxDriver(task)); err != nil {
+ if err := checkoutInvocationRepositories(ctx, workspace, inv); err != nil {
return execResult{status: domain.RunnerTaskFailed, errMsg: fmt.Sprintf("repository checkout: %v", err)}, nil
}
if err := writeRunnerHumanContext(workspace, inv.HumanContext); err != nil {
@@ -1105,7 +1105,7 @@ func invocationGitToken(inv *domain.RunnerInvocation) string {
// kept for persisted legacy invocations that already checked out at the
// workspace root. Later invocations and gates reuse the existing checkout
// (once per workspace).
-func checkoutInvocationRepositories(ctx context.Context, workspace string, inv *domain.RunnerInvocation, driver string, refreshClean ...bool) error {
+func checkoutInvocationRepositories(ctx context.Context, workspace string, inv *domain.RunnerInvocation, refreshClean ...bool) error {
if inv == nil {
return nil
}
@@ -1133,9 +1133,6 @@ func checkoutInvocationRepositories(ctx context.Context, workspace string, inv *
if err := configureRepositoryGitIdentity(ctx, target, inv.GitUserName, inv.GitUserEmail); err != nil {
return err
}
- if err := runtime.ProtectProjectAgentGitIndex(ctx, target, driver); err != nil {
- return fmt.Errorf("protect repository Agent configuration in %s: %w", repo.Dir, err)
- }
}
return nil
}
diff --git a/internal/runner/daemon_test.go b/internal/runner/daemon_test.go
index d66307b4..c9d83734 100644
--- a/internal/runner/daemon_test.go
+++ b/internal/runner/daemon_test.go
@@ -312,7 +312,7 @@ func TestConfigureRepositoryGitIdentityOverridesStaleLocalConfig(t *testing.T) {
}
}
-func TestCheckoutInvocationRepositoriesProtectsEachSandboxedRepository(t *testing.T) {
+func TestCheckoutInvocationRepositoriesLeavesAgentConfigVisible(t *testing.T) {
root := t.TempDir()
invocation := &domain.RunnerInvocation{}
for _, name := range []string{"frontend", "backend"} {
@@ -344,7 +344,7 @@ func TestCheckoutInvocationRepositoriesProtectsEachSandboxedRepository(t *testin
if err := os.MkdirAll(workspace, 0o755); err != nil {
t.Fatal(err)
}
- if err := checkoutInvocationRepositories(context.Background(), workspace, invocation, "docker"); err != nil {
+ if err := checkoutInvocationRepositories(context.Background(), workspace, invocation); err != nil {
t.Fatal(err)
}
for _, name := range []string{"frontend", "backend"} {
@@ -355,13 +355,13 @@ func TestCheckoutInvocationRepositoriesProtectsEachSandboxedRepository(t *testin
t.Fatalf("git ls-files %s: %v: %s", name, err, output)
}
for _, line := range strings.Split(strings.TrimSpace(string(output)), "\n") {
- if !strings.HasPrefix(line, "S ") {
- t.Fatalf("%s repository path is not skip-worktree protected: %q", name, line)
+ if !strings.HasPrefix(line, "H ") {
+ t.Fatalf("%s repository instruction file was hidden from Git: %q", name, line)
}
}
exclude, err := os.ReadFile(filepath.Join(repository, ".git", "info", "exclude"))
- if err != nil || !strings.Contains(string(exclude), ".agents/") {
- t.Fatalf("%s repository excludes were not installed: %v %q", name, err, exclude)
+ if err != nil || strings.Contains(string(exclude), ".agents/") {
+ t.Fatalf("%s repository instruction excludes: %v %q", name, err, exclude)
}
}
}
diff --git a/internal/runner/invocation_repositories_test.go b/internal/runner/invocation_repositories_test.go
index 1c3228d8..39237167 100644
--- a/internal/runner/invocation_repositories_test.go
+++ b/internal/runner/invocation_repositories_test.go
@@ -30,7 +30,7 @@ func TestInvocationRepositoriesPrefersListAndFallsBackToLegacy(t *testing.T) {
func TestCheckoutInvocationRepositoriesSkipsLegacyWithoutCloneURL(t *testing.T) {
workspace := t.TempDir()
inv := &domain.RunnerInvocation{Repository: &domain.RunnerRepository{RepositoryID: "legacy", CloneURL: " "}}
- if err := checkoutInvocationRepositories(context.Background(), workspace, inv, "local"); err != nil {
+ if err := checkoutInvocationRepositories(context.Background(), workspace, inv); err != nil {
t.Fatalf("legacy repository without clone URL should be skipped: %v", err)
}
}
diff --git a/internal/runner/repository_checkout.go b/internal/runner/repository_checkout.go
index a5da0d64..3ad4ba9c 100644
--- a/internal/runner/repository_checkout.go
+++ b/internal/runner/repository_checkout.go
@@ -10,6 +10,7 @@ import (
"agentflow/internal/domain"
"agentflow/internal/gitwork"
+ "agentflow/internal/runtime"
)
func checkoutRepositoryForPreparation(ctx context.Context, workspace string, repository *domain.RunnerRepository, refresh bool) error {
@@ -29,6 +30,9 @@ func checkoutRepositoryForPreparation(ctx context.Context, workspace string, rep
if !info.IsDir() {
return fmt.Errorf("repository .git is not a real directory")
}
+ if err := runtime.RestoreLegacyProjectAgentConfig(ctx, workspace); err != nil {
+ return err
+ }
if _, ok := gitwork.RevParse(ctx, workspace, "HEAD"); !ok {
// A killed clone leaves .git before there are refs or checked-out files.
// Never remove an index, refs or source files from a damaged checkout.
diff --git a/internal/runner/repository_checkout_test.go b/internal/runner/repository_checkout_test.go
index a4fcf53f..4f3e61d3 100644
--- a/internal/runner/repository_checkout_test.go
+++ b/internal/runner/repository_checkout_test.go
@@ -94,20 +94,20 @@ func TestCheckoutRepositoryPreservesDamagedCheckoutWithLocalWork(t *testing.T) {
func TestPreparationRefreshesCleanCheckoutAndBaseline(t *testing.T) {
remote, workspace := bareRemoteWithBaseline(t), t.TempDir()
inv := &domain.RunnerInvocation{Repositories: []domain.RunnerRepository{{CloneURL: remote, Ref: "master", WorkBranch: "feature/retry"}}}
- if err := checkoutInvocationRepositories(context.Background(), workspace, inv, "local"); err != nil {
+ if err := checkoutInvocationRepositories(context.Background(), workspace, inv); err != nil {
t.Fatal(err)
}
before, _ := os.Stat(workspace)
oldHead := runGitT(t, workspace, "rev-parse", "HEAD")
want := advanceCheckoutRemote(t, remote)
// Ordinary nodes keep the frozen checkout, even when its tree is clean.
- if err := checkoutInvocationRepositories(context.Background(), workspace, inv, "local"); err != nil {
+ if err := checkoutInvocationRepositories(context.Background(), workspace, inv); err != nil {
t.Fatal(err)
}
if got := runGitT(t, workspace, "rev-parse", "HEAD"); got != oldHead {
t.Fatal("ordinary node changed the run baseline")
}
- if err := checkoutInvocationRepositories(context.Background(), workspace, inv, "local", true); err != nil {
+ if err := checkoutInvocationRepositories(context.Background(), workspace, inv, true); err != nil {
t.Fatal(err)
}
if got := runGitT(t, workspace, "rev-parse", "HEAD"); got != want {
@@ -127,7 +127,7 @@ func TestRepositoryCanRefreshRejectsSymlinkEscape(t *testing.T) {
t.Run(kind, func(t *testing.T) {
remote, workspace := bareRemoteWithBaseline(t), t.TempDir()
inv := &domain.RunnerInvocation{Repositories: []domain.RunnerRepository{{CloneURL: remote, Ref: "master"}}}
- if err := checkoutInvocationRepositories(context.Background(), workspace, inv, "local"); err != nil {
+ if err := checkoutInvocationRepositories(context.Background(), workspace, inv); err != nil {
t.Fatal(err)
}
path := filepath.Join(workspace, ".git")
@@ -179,7 +179,7 @@ func TestPreparationRefreshPreservesLocalChangesAndCommits(t *testing.T) {
t.Run(kind, func(t *testing.T) {
remote, workspace := bareRemoteWithBaseline(t), t.TempDir()
inv := &domain.RunnerInvocation{Repositories: []domain.RunnerRepository{{CloneURL: remote, Ref: "master", WorkBranch: "feature/keep"}}}
- if err := checkoutInvocationRepositories(context.Background(), workspace, inv, "local"); err != nil {
+ if err := checkoutInvocationRepositories(context.Background(), workspace, inv); err != nil {
t.Fatal(err)
}
file := "local.txt"
@@ -207,7 +207,7 @@ func TestPreparationRefreshPreservesLocalChangesAndCommits(t *testing.T) {
refs := runGitT(t, workspace, "show-ref")
status := runGitT(t, workspace, "status", "--porcelain=v1", "--ignored=matching")
advanceCheckoutRemote(t, remote)
- if err := checkoutInvocationRepositories(context.Background(), workspace, inv, "local", true); err != nil {
+ if err := checkoutInvocationRepositories(context.Background(), workspace, inv, true); err != nil {
t.Fatal(err)
}
if got := runGitT(t, workspace, "rev-parse", "HEAD"); got != head {
@@ -226,12 +226,12 @@ func TestPreparationRefreshPreservesLocalChangesAndCommits(t *testing.T) {
func TestPreparationRefreshKeepsCheckoutWhenCloneFails(t *testing.T) {
remote, workspace := bareRemoteWithBaseline(t), t.TempDir()
inv := &domain.RunnerInvocation{Repositories: []domain.RunnerRepository{{CloneURL: remote, Ref: "master"}}}
- if err := checkoutInvocationRepositories(context.Background(), workspace, inv, "local"); err != nil {
+ if err := checkoutInvocationRepositories(context.Background(), workspace, inv); err != nil {
t.Fatal(err)
}
head := runGitT(t, workspace, "rev-parse", "HEAD")
inv.Repositories[0].CloneURL = filepath.Join(t.TempDir(), "missing-remote.git")
- if err := checkoutInvocationRepositories(context.Background(), workspace, inv, "local", true); err == nil {
+ if err := checkoutInvocationRepositories(context.Background(), workspace, inv, true); err == nil {
t.Fatal("missing remote unexpectedly cloned")
}
if got := runGitT(t, workspace, "rev-parse", "HEAD"); got != head {
diff --git a/internal/runner/workspace_preparation.go b/internal/runner/workspace_preparation.go
index 71993d86..50880975 100644
--- a/internal/runner/workspace_preparation.go
+++ b/internal/runner/workspace_preparation.go
@@ -79,7 +79,7 @@ func (d *Daemon) prepareRunnerWorkspace(ctx context.Context, root string, reques
if err := os.MkdirAll(root, 0700); err != nil {
return runnerWorkspaceError(err)
}
- if err := checkoutInvocationRepositories(ctx, root, request.PreparationInvocation, runnerTaskSandboxDriver(task), request.RefreshCleanRepositories); err != nil {
+ if err := checkoutInvocationRepositories(ctx, root, request.PreparationInvocation, request.RefreshCleanRepositories); err != nil {
return runnerWorkspaceError(fmt.Errorf("prepare workspace repositories: %w", err))
}
sb, release, err := d.acquireTaskSandbox(ctx, task)
@@ -122,7 +122,7 @@ func (d *Daemon) handleRunnerWorkspaceTerminal(ctx context.Context, root, scope
unlock := onceRelease(gate.Unlock)
d.workspacePreparing.Store(key, true)
defer d.workspacePreparing.Delete(key)
- if err := checkoutInvocationRepositories(ctx, root, request.PreparationInvocation, runnerTaskSandboxDriver(task)); err != nil {
+ if err := checkoutInvocationRepositories(ctx, root, request.PreparationInvocation); err != nil {
unlock()
return runtime.TerminalResult{}, fmt.Errorf("prepare workspace repositories: %w", err)
}
diff --git a/internal/runtime/claude_install_test.go b/internal/runtime/claude_install_test.go
index 13c6cfbb..f5837c32 100644
--- a/internal/runtime/claude_install_test.go
+++ b/internal/runtime/claude_install_test.go
@@ -99,7 +99,7 @@ func TestDockerSandboxRunsOnDemandClaudeCodeFromMountedDirectory(t *testing.T) {
printf '%s\n' "$*" >> "$DOCKER_TEST_LOG"
case "$*" in
"image inspect loopforge-platform:tested") exit 0 ;;
- "inspect "*) exit 1 ;;
+ "inspect "*) echo 'Error: No such container' >&2; exit 1 ;;
"exec "*) echo /workspace ;;
esac
`})
diff --git a/internal/runtime/conversation_sandbox.go b/internal/runtime/conversation_sandbox.go
index 0b8b4cc1..d7f7a933 100644
--- a/internal/runtime/conversation_sandbox.go
+++ b/internal/runtime/conversation_sandbox.go
@@ -33,8 +33,13 @@ func ConfigureConversationSandbox(ctx context.Context, sandbox Sandbox, root str
if s.requirements.ConversationRoot == root {
return nil
}
+ previousRoot := s.requirements.ConversationRoot
s.requirements.ConversationRoot = root
- return s.Recreate(ctx)
+ if err := s.Recreate(ctx); err != nil {
+ s.requirements.ConversationRoot = previousRoot
+ return err
+ }
+ return nil
}
// Keep security configuration mounted at fixed paths. Anchoring every parent
diff --git a/internal/runtime/core_cases_test.go b/internal/runtime/core_cases_test.go
index 94df90ce..2e8b7004 100644
--- a/internal/runtime/core_cases_test.go
+++ b/internal/runtime/core_cases_test.go
@@ -326,30 +326,6 @@ func TestHandleBrowserOperationErrors(t *testing.T) {
func TestProcessSandboxPathsProfilesAndCommands(t *testing.T) {
workspace := t.TempDir()
- if err := os.WriteFile(filepath.Join(workspace, "AGENTS.md"), []byte("rules"), 0o600); err != nil {
- t.Fatal(err)
- }
- if err := os.MkdirAll(filepath.Join(workspace, "nested", ".claude"), 0o700); err != nil {
- t.Fatal(err)
- }
- paths, err := discoverProjectAgentPaths(workspace)
- if err != nil || !cvRContains(paths, "AGENTS.md") || !cvRContains(paths, filepath.Join("nested", ".claude")) {
- t.Fatalf("paths=%v err=%v", paths, err)
- }
- if _, err := validateAgentConfigTarget(workspace, "AGENTS.md"); err != nil {
- t.Fatal(err)
- }
- outside := filepath.Join(t.TempDir(), "AGENTS.md")
- _ = os.WriteFile(outside, []byte("x"), 0o600)
- if err := os.Symlink(outside, filepath.Join(workspace, "CLAUDE.md")); err != nil {
- t.Fatal(err)
- }
- if _, err := validateAgentConfigTarget(workspace, "CLAUDE.md"); err == nil {
- t.Fatal("outside symlink accepted")
- }
- if err := os.Remove(filepath.Join(workspace, "CLAUDE.md")); err != nil {
- t.Fatal(err)
- }
env := appendEnvironment([]string{"A=1", "A=2", "bad"}, map[string]string{"A": "3", "B": "4"})
if strings.Join(env, ",") != "A=3,B=4" {
t.Fatalf("env=%v", env)
@@ -366,24 +342,14 @@ func TestProcessSandboxPathsProfilesAndCommands(t *testing.T) {
if first, err := agentStateDirectoryRequirements(req); err != nil || first == "" {
t.Fatalf("first=%q err=%v", first, err)
}
- profile, err := seatbeltProfileCommand(workspace, req, true)
- if err != nil || !strings.Contains(profile, "deny file-read") {
+ profile, err := seatbeltProfileCommand(workspace, req)
+ if err != nil || !strings.Contains(profile, "(deny file-write*)") {
t.Fatalf("profile=%q err=%v", profile, err)
}
- args, err := bwrapArgsCommand(workspace, req, true)
+ args, err := bwrapArgsCommand(workspace, req)
if err != nil || !cvRContains(args, "--tmpfs") || !cvRContains(args, "--ro-bind") {
t.Fatalf("args=%v err=%v", args, err)
}
- emptyDir, emptyFile, err := isolationMaskSources(workspace)
- if err != nil {
- t.Fatal(err)
- }
- if info, _ := os.Stat(emptyDir); !info.IsDir() {
- t.Fatal("empty dir")
- }
- if info, _ := os.Stat(emptyFile); !info.Mode().IsRegular() {
- t.Fatal("empty file")
- }
sb := &processSandbox{id: "id", workspace: workspace, driver: "bwrap", binary: "/bin/echo", profile: domain.SandboxProfile{Environment: map[string]string{"X": "1"}}}
if _, err := sb.command(context.Background(), CommandSpec{}, nil); err == nil {
t.Fatal("empty command accepted")
diff --git a/internal/runtime/docker_build_progress_test.go b/internal/runtime/docker_build_progress_test.go
index 713b7b87..d2fce64d 100644
--- a/internal/runtime/docker_build_progress_test.go
+++ b/internal/runtime/docker_build_progress_test.go
@@ -18,7 +18,7 @@ import (
func installFakeDockerBuild(t *testing.T, buildScript string) {
t.Helper()
bin := t.TempDir()
- script := "#!/bin/sh\ncase \"$1\" in\n inspect|image) exit 1 ;;\n build)\n" + buildScript + "\n ;;\nesac\nexit 0\n"
+ script := "#!/bin/sh\ncase \"$1\" in\n inspect) echo \"No such container\" >&2; exit 1 ;;\n image) exit 1 ;;\n build)\n" + buildScript + "\n ;;\nesac\nexit 0\n"
if err := os.WriteFile(filepath.Join(bin, "docker"), []byte(script), 0o755); err != nil {
t.Fatal(err)
}
diff --git a/internal/runtime/docker_cases_test.go b/internal/runtime/docker_cases_test.go
index 837f84f4..07125108 100644
--- a/internal/runtime/docker_cases_test.go
+++ b/internal/runtime/docker_cases_test.go
@@ -32,7 +32,6 @@ func TestDockerConversationProcessPreservesInteractiveInput(t *testing.T) {
func TestDockerSandboxLifecycleWithFakeCLI(t *testing.T) {
workspace := t.TempDir()
cvRInstallFakeDocker(t, workspace)
- _ = os.WriteFile(filepath.Join(workspace, "AGENTS.md"), []byte("hidden"), 0o600)
dockerfile := domain.DockerfileDefinition{ID: "cvR", Content: "FROM scratch\n", Files: map[string]string{"asset.txt": "asset"}}
sbAny, err := createDocker(context.Background(), "cvR-run", workspace,
domain.SandboxProfile{Driver: "docker", ReadOnlyRootFS: true, Environment: map[string]string{"A": "1"}},
@@ -70,12 +69,9 @@ func TestDockerDiscoveryImagesAndBuildHelpers(t *testing.T) {
workspace := t.TempDir()
cvRInstallFakeDocker(t, workspace)
ctx := context.Background()
- source, err := dockerWorkspaceBindSource(ctx, "box")
- if err != nil || source != workspace || !dockerContainerReusable(source, nil, workspace) {
- t.Fatalf("source=%q err=%v", source, err)
- }
- if dockerContainerReusable("", nil, workspace) || dockerBindMatchesWorkspace("", workspace) {
- t.Fatal("empty bind matched")
+ info, err := inspectDockerWorkspaceMounts(ctx, "box")
+ if err != nil || info == nil || info.source != workspace || info.legacyMasks {
+ t.Fatalf("mounts=%+v err=%v", info, err)
}
found, err := dockerSandboxesUnder(ctx, filepath.Dir(workspace))
if err != nil || found["agentflow-cvr"] != filepath.Base(workspace) {
@@ -158,26 +154,9 @@ func TestDockerArgumentAndErrorBranches(t *testing.T) {
}
}
-func TestDockerMasksAndManagerPaths(t *testing.T) {
+func TestDockerManagerReclaimsCachedImages(t *testing.T) {
workspace := t.TempDir()
cvRInstallFakeDocker(t, workspace)
- _ = os.WriteFile(filepath.Join(workspace, "CLAUDE.md"), []byte("x"), 0o600)
- sb := &dockerSandbox{name: "box", workspace: workspace}
- hide, err := sb.currentAgentMasks()
- if err != nil || !cvRContains(hide, "/workspace/CLAUDE.md") {
- t.Fatalf("hide=%v err=%v", hide, err)
- }
- masks, err := sb.scriptMasks(context.Background())
- if err != nil || !cvRContains(masks, "/workspace/CLAUDE.md") {
- t.Fatalf("masks=%v err=%v", masks, err)
- }
- if !maskedAgentCommand(CommandSpec{Provider: "codex"}) || maskedAgentCommand(CommandSpec{Provider: "script"}) || !trustedScriptCommand(CommandSpec{Provider: "script"}) {
- t.Fatal("command classification")
- }
- args := dockerScriptCreateArgs("helper", "base", workspace, "image", "owner")
- if !cvRContains(args, "--cap-add=SYS_ADMIN") {
- t.Fatalf("script args=%v", args)
- }
m := NewManager(workspace)
count, err := m.ReclaimCachedDockerImages(context.Background(), nil)
if err != nil || count != 1 {
@@ -185,29 +164,6 @@ func TestDockerMasksAndManagerPaths(t *testing.T) {
}
}
-func TestDockerScriptContainerAndExecution(t *testing.T) {
- workspace := t.TempDir()
- cvRInstallFakeDocker(t, workspace)
- gate := filepath.Join(t.TempDir(), "gate-{os}-{arch}")
- gateLinux := strings.ReplaceAll(strings.ReplaceAll(gate, "{os}", "linux"), "{arch}", "amd64")
- if err := os.WriteFile(gateLinux, []byte("#!/bin/sh\n"), 0o755); err != nil {
- t.Fatal(err)
- }
- t.Setenv("AGENTFLOW_GATE_MCP_BINARY", gate)
- _ = os.WriteFile(filepath.Join(workspace, "AGENTS.md"), []byte("hidden"), 0o600)
- sb := &dockerSandbox{name: "box", workspace: workspace, started: true, profile: domain.SandboxProfile{Environment: map[string]string{"A": "1"}}}
- if err := sb.ensureScriptContainer(context.Background()); err != nil {
- t.Fatal(err)
- }
- out, err := sb.execScript(context.Background(), CommandSpec{Provider: "script", Argv: []string{"sh", "-c", "echo ok"}, environment: map[string]string{"B": "2"}}, nil)
- if err != nil || !strings.Contains(out, "/workspace") {
- t.Fatalf("exec script=%q err=%v", out, err)
- }
- if err := sb.refreshAgentMasks(context.Background()); err != nil {
- t.Fatal(err)
- }
-}
-
func TestDockerExecRecoversFromUnsafeCWD(t *testing.T) {
workspace := t.TempDir()
bin := t.TempDir()
@@ -215,8 +171,10 @@ func TestDockerExecRecoversFromUnsafeCWD(t *testing.T) {
script := `#!/bin/sh
workspace="${CVR_DOCKER_WORKSPACE}"
marker="${CVR_DOCKER_MARKER}"
-if [ "${1-}" = inspect ] && [ "${2-}" = -f ]; then echo "$workspace"; exit 0; fi
-if [ "${1-}" = inspect ]; then exit 0; fi
+if [ "${1-}" = inspect ]; then
+ printf '[{"Destination":"/workspace","Source":"%s"}]\n' "$workspace"
+ exit 0
+fi
if [ "${1-}" = exec ]; then
case "$*" in *"cd /workspace && pwd"*) echo /workspace; exit 0;; esac
if [ ! -e "$marker" ]; then
@@ -254,6 +212,78 @@ func TestDockerExecInvalidatesMissingContainer(t *testing.T) {
}
}
+func TestSandboxEnvironmentIdentityRecoversExternallyStoppedOrRemovedContainer(t *testing.T) {
+ bin, state := t.TempDir(), t.TempDir()
+ // A stateful docker stand-in: "status" holds running/exited, "generation"
+ // counts docker create and "starts" counts docker start.
+ script := `#!/bin/sh
+state="${CVR_DOCKER_STATE}"
+status() { cat "$state/status" 2>/dev/null; }
+count() { n=$(cat "$state/$1" 2>/dev/null || echo 0); echo $((n + 1)) > "$state/$1"; }
+case "$*" in
+ "inspect --format {{.State.Running}}|{{.Id}}|{{.State.StartedAt}} box")
+ case "$(status)" in
+ running) echo "true|id-$(cat "$state/generation")|start-$(cat "$state/starts")"; exit 0 ;;
+ exited) echo "false|id-$(cat "$state/generation")|start-$(cat "$state/starts")"; exit 0 ;;
+ esac
+ echo 'Error: No such object: box' >&2; exit 1 ;;
+ "inspect --type container --format {{json .Mounts}} box")
+ [ -n "$(status)" ] || { echo 'Error: No such container: box' >&2; exit 1; }
+ printf '[{"Destination":"/workspace","Source":"%s"}]\n' "$CVR_DOCKER_WORKSPACE"; exit 0 ;;
+ "start box") [ -n "$(status)" ] || exit 1; echo running > "$state/status"; count starts; exit 0 ;;
+ "create --name box "*) echo exited > "$state/status"; count generation; exit 0 ;;
+ "rm -f box") rm -f "$state/status"; exit 0 ;;
+ "exec box "*) [ "$(status)" = running ] || { echo 'Error response from daemon: container box is not running' >&2; exit 1; }
+ case "$*" in *"cd /workspace && pwd"*) echo /workspace ;; esac; exit 0 ;;
+ "image inspect --format {{.Config.User}} "*) exit 0 ;;
+ "image inspect "*) exit 0 ;;
+esac
+exit 0
+`
+ if err := os.WriteFile(filepath.Join(bin, "docker"), []byte(script), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ workspace := t.TempDir()
+ t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
+ t.Setenv("CVR_DOCKER_STATE", state)
+ t.Setenv("CVR_DOCKER_WORKSPACE", workspace)
+ for name, value := range map[string]string{"status": "running", "generation": "1", "starts": "1"} {
+ if err := os.WriteFile(filepath.Join(state, name), []byte(value+"\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ ctx := context.Background()
+ sb := &dockerSandbox{id: "box", name: "box", workspace: workspace, started: true,
+ dockerfile: domain.DockerfileDefinition{Content: "FROM alpine:3.20\n"}}
+ identity, err := SandboxEnvironmentIdentity(ctx, sb)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, external := range []string{"stopped", "removed"} {
+ if external == "stopped" {
+ err = os.WriteFile(filepath.Join(state, "status"), []byte("exited\n"), 0o644)
+ } else {
+ err = os.Remove(filepath.Join(state, "status"))
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ // The first call after an external stop/removal recovers; it must not
+ // keep failing on the cached started flag.
+ next, err := SandboxEnvironmentIdentity(ctx, sb)
+ if err != nil || next == identity || !sb.started {
+ t.Fatalf("container %s: identity %q (was %q) started=%v err=%v", external, next, identity, sb.started, err)
+ }
+ if again, err := SandboxEnvironmentIdentity(ctx, sb); err != nil || again != next {
+ t.Fatalf("container %s: identity unstable %q != %q %v", external, again, next, err)
+ }
+ identity = next
+ }
+ if data, err := os.ReadFile(filepath.Join(state, "generation")); err != nil || strings.TrimSpace(string(data)) != "2" {
+ t.Fatalf("removed container was not recreated exactly once: %q %v", data, err)
+ }
+}
+
func cvRInstallFakeDocker(t *testing.T, workspace string) {
t.Helper()
bin := t.TempDir()
@@ -261,25 +291,14 @@ func cvRInstallFakeDocker(t *testing.T, workspace string) {
set -eu
workspace="${CVR_DOCKER_WORKSPACE}"
if [ "${1-}" = inspect ] && [ "${2-}" = -f ]; then
- case "${3-}" in
- "{{range"*) printf '%s\n' "$workspace" ;;
- *) printf '/agentflow-cvr\t%s\n' "$workspace" ;;
- esac
+ printf '/agentflow-cvr\t%s\n' "$workspace"
exit 0
fi
-if [ "${1-}" = inspect ] && [ "${2-}" = --format ]; then
- case "${3-}" in
- "{{json .}}") echo '{"Id":"base-id","Image":"base-image","State":{"Running":true,"StartedAt":"now"}}'; exit 0 ;;
- "{{json .Mounts}}") echo '[]'; exit 0 ;;
- "{{.State.Running}}|{{.Id}}"*) echo 'true|container-id|now'; exit 0 ;;
- *) echo 'Error: No such container' >&2; exit 1 ;;
- esac
-fi
-case " $* " in
- *" --workspace-script-view-version "*) echo agentflow-script-view-v3; exit 0 ;;
-esac
case "$*" in
- "image inspect --format {{.Architecture}} "*) echo amd64; exit 0 ;;
+ "inspect --type container --format {{json .Mounts}} box")
+ printf '[{"Destination":"/workspace","Source":"%s"}]\n' "$workspace"; exit 0 ;;
+ "inspect --type container "*) echo 'Error: No such container' >&2; exit 1 ;;
+ "inspect --format {{.State.Running}}|{{.Id}}|{{.State.StartedAt}} "*) echo 'true|container-id|now'; exit 0 ;;
"image inspect --format {{.Config.User}} "*) exit 0 ;;
"image inspect "*) exit 1 ;;
"images --format {{.Repository}} --filter reference=agentflow-img-*"*) printf 'agentflow-img-a:latest\nagentflow-img-b\nagentflow-img-a\n'; exit 0 ;;
diff --git a/internal/runtime/git_index_lock_test.go b/internal/runtime/git_index_lock_test.go
index ad2e0b17..3434091a 100644
--- a/internal/runtime/git_index_lock_test.go
+++ b/internal/runtime/git_index_lock_test.go
@@ -30,9 +30,7 @@ func agentIndexRepo(t *testing.T) (workspace, lockPath string) {
}
testRuntimeGit(t, workspace, "add", "AGENTS.md")
testRuntimeGit(t, workspace, "commit", "-m", "baseline")
- if err := ProtectProjectAgentGitIndex(context.Background(), workspace, "docker"); err != nil {
- t.Fatal(err)
- }
+ markLegacyProjectAgentConfig(t, workspace)
return workspace, filepath.Join(workspace, ".git", "index.lock")
}
@@ -78,7 +76,7 @@ func TestRestoreProjectAgentGitIndexKeepsAlternatePathLock(t *testing.T) {
t.Fatal(err)
}
defer holder.Close()
- err = RestoreProjectAgentGitIndex(context.Background(), workspace, "docker")
+ err = RestoreLegacyProjectAgentConfig(context.Background(), workspace)
if err == nil || !strings.Contains(err.Error(), "held by a live process") {
t.Fatalf("restore error = %v, want live-process protection", err)
}
diff --git a/internal/runtime/git_isolation.go b/internal/runtime/git_isolation.go
index 6bae9221..b87faf1d 100644
--- a/internal/runtime/git_isolation.go
+++ b/internal/runtime/git_isolation.go
@@ -14,9 +14,11 @@ import (
"sync"
"syscall"
"time"
+
+ "agentflow/internal/domain"
)
-const projectAgentGitExcludeBlock = `# AgentFlow managed sandbox: repository Agent configuration
+const legacyProjectAgentGitExcludeBlock = `# AgentFlow managed sandbox: repository Agent configuration
AGENTS.md
AGENTS.override.md
CLAUDE.md
@@ -33,52 +35,78 @@ const agentFlowGitExcludeBlock = `# AgentFlow managed runtime (hooks, bindings,
.agentflow/
`
-// UsesProjectAgentConfigIsolation reports whether a sandbox hides repository
-// Agent CLI configuration from commands running inside it. Local execution
-// deliberately keeps its historical, unisolated Git behavior.
-func UsesProjectAgentConfigIsolation(driver string) bool {
- switch strings.TrimSpace(driver) {
- case "seatbelt", "bwrap", "docker":
- return true
- default:
- return false
+// RestoreLegacyWorkspaceAgentConfig clears the Git settings installed by the
+// old instruction masks in private checkouts, including legacy root checkouts.
+func RestoreLegacyWorkspaceAgentConfig(ctx context.Context, workspace string, repositories []domain.RepositoryContext) error {
+ if err := RestoreLegacyProjectAgentConfig(ctx, workspace); err != nil {
+ return err
}
+ for _, repo := range repositories {
+ dir := strings.TrimSpace(repo.WorkspaceDir)
+ if dir == "" || dir == "." {
+ continue
+ }
+ if !filepath.IsLocal(dir) || filepath.Base(dir) != dir {
+ continue
+ }
+ target := filepath.Join(workspace, dir)
+ if info, err := os.Lstat(target); err == nil && info.IsDir() {
+ if err := RestoreLegacyProjectAgentConfig(ctx, target); err != nil {
+ return err
+ }
+ } else if err != nil && !os.IsNotExist(err) {
+ return err
+ }
+ }
+ return nil
}
-// RestoreProjectAgentGitIndex clears the temporary skip-worktree bits before
-// AgentFlow refreshes or checks out the run branch. The workspace is a private
-// clone, so these index bits can only have been set by AgentFlow.
-func RestoreProjectAgentGitIndex(ctx context.Context, workspace, driver string) error {
- return updateProjectAgentGitIndex(ctx, workspace, driver, "--no-skip-worktree")
-}
+// RestoreLegacyProjectAgentConfig only updates clones tagged by the old masks.
+// Keep their marker until the index is restored so an interrupted upgrade can
+// retry without touching unmarked repositories or unrelated Git excludes.
+func RestoreLegacyProjectAgentConfig(ctx context.Context, workspace string) error {
+ git, err := os.Lstat(filepath.Join(workspace, ".git"))
+ if os.IsNotExist(err) || err == nil && !git.IsDir() {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ gitExcludeMu.Lock()
+ defer gitExcludeMu.Unlock()
-// ProtectProjectAgentGitIndex prevents sandbox masks and read denials from
-// looking like repository changes to Git. Tracked paths use skip-worktree;
-// untracked paths use the private clone's .git/info/exclude. Neither mechanism
-// changes the source repository or its committed .gitignore.
-func ProtectProjectAgentGitIndex(ctx context.Context, workspace, driver string) error {
- if !UsesProjectAgentConfigIsolation(driver) {
+ target := filepath.Join(workspace, ".git", "info", "exclude")
+ root, rel, err := openWorkspacePath(workspace, target)
+ if err != nil {
+ return err
+ }
+ defer root.Close()
+ info, err := root.Lstat(rel)
+ if os.IsNotExist(err) || err == nil && !info.Mode().IsRegular() {
return nil
}
- if err := ensureProjectAgentGitExcludes(workspace); err != nil {
+ if err != nil {
+ return err
+ }
+ content, err := root.ReadFile(rel)
+ if err != nil {
return err
}
- return updateProjectAgentGitIndex(ctx, workspace, driver, "--skip-worktree")
+ block := []byte(legacyProjectAgentGitExcludeBlock)
+ if !bytes.Contains(content, block) {
+ return nil
+ }
+ if err := clearLegacyProjectAgentGitIndex(ctx, workspace); err != nil {
+ return err
+ }
+ return writeManagedFile(workspace, target, bytes.ReplaceAll(content, block, nil), info.Mode().Perm())
}
-func ensureProjectAgentGitExcludes(workspace string) error {
- return appendGitExcludeBlock(workspace, projectAgentGitExcludeBlock, "project Agent Git excludes")
-}
+var gitExcludeMu sync.Mutex
// EnsureAgentFlowGitExcludes marks .agentflow/ ignored in the private clone so
// agent git stash -u does not remove runtime hook files mid-session.
func EnsureAgentFlowGitExcludes(workspace string) error {
- return appendGitExcludeBlock(workspace, agentFlowGitExcludeBlock, "AgentFlow runtime excludes")
-}
-
-var gitExcludeMu sync.Mutex
-
-func appendGitExcludeBlock(workspace, block, label string) error {
// Parallel branches prepare the same checkout; check-then-append must not
// interleave or the block is appended twice.
gitExcludeMu.Lock()
@@ -98,14 +126,12 @@ func appendGitExcludeBlock(workspace, block, label string) error {
if err != nil && !os.IsNotExist(err) {
return err
}
- if bytes.Contains(existing, []byte(block)) {
+ if bytes.Contains(existing, []byte(agentFlowGitExcludeBlock)) {
return nil
}
if err := root.MkdirAll(filepath.Dir(excludePath), 0o700); err != nil {
return err
}
- // Keep append semantics: separate preparation paths may add different
- // managed blocks concurrently. The held root confines the open operation.
file, err := root.OpenFile(excludePath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600)
if err != nil {
return err
@@ -116,23 +142,15 @@ func appendGitExcludeBlock(workspace, block, label string) error {
return err
}
}
- if _, err := file.WriteString(block); err != nil {
- return fmt.Errorf("write %s: %w", label, err)
+ if _, err := file.WriteString(agentFlowGitExcludeBlock); err != nil {
+ return fmt.Errorf("write AgentFlow runtime excludes: %w", err)
}
return nil
}
-func updateProjectAgentGitIndex(ctx context.Context, workspace, driver, mode string) error {
- if !UsesProjectAgentConfigIsolation(driver) {
- return nil
- }
- if _, err := os.Stat(filepath.Join(workspace, ".git")); err != nil {
- if os.IsNotExist(err) {
- return nil
- }
- return err
- }
- paths, err := trackedProjectAgentConfigPathsForMode(ctx, workspace, mode)
+func clearLegacyProjectAgentGitIndex(ctx context.Context, workspace string) error {
+ const mode = "--no-skip-worktree"
+ paths, err := trackedSkippedProjectAgentConfigPaths(ctx, workspace)
if err != nil || len(paths) == 0 {
return err
}
@@ -363,7 +381,7 @@ func procMayOwnFile(procDir string, uid uint32) bool {
return true
}
-func trackedProjectAgentConfigPathsForMode(ctx context.Context, workspace, mode string) ([]string, error) {
+func trackedSkippedProjectAgentConfigPaths(ctx context.Context, workspace string) ([]string, error) {
cmd := exec.CommandContext(ctx, "git", "-C", workspace, "ls-files", "-v", "-z")
output, err := cmd.Output()
if err != nil {
@@ -379,25 +397,33 @@ func trackedProjectAgentConfigPathsForMode(ctx context.Context, workspace, mode
continue
}
path := string(entry[2:])
- isProtected := entry[0] == 'S'
- needsUpdate := mode == "--skip-worktree" && !isProtected || mode == "--no-skip-worktree" && isProtected
- if needsUpdate && isProjectAgentConfigPath(path) {
+ if (entry[0] == 'S' || entry[0] == 's') && isLegacyProjectAgentConfigPath(path) {
paths = append(paths, path)
}
}
return paths, nil
}
-func isProjectAgentConfigPath(path string) bool {
+var legacyProjectAgentDirNames = map[string]bool{
+ ".agents": true, ".codex": true, ".claude": true, ".codebuddy": true,
+}
+
+var legacyProjectAgentFileNames = map[string]bool{
+ "AGENTS.md": true, "AGENTS.override.md": true,
+ "CLAUDE.md": true, "CLAUDE.local.md": true,
+ "CODEBUDDY.md": true, ".mcp.json": true,
+}
+
+func isLegacyProjectAgentConfigPath(path string) bool {
clean := filepath.ToSlash(filepath.Clean(path))
if clean == "." || clean == ".." || strings.HasPrefix(clean, "../") || strings.HasPrefix(clean, "/") {
return false
}
parts := strings.Split(clean, "/")
for _, part := range parts[:len(parts)-1] {
- if projectAgentDirNames[part] {
+ if legacyProjectAgentDirNames[part] {
return true
}
}
- return projectAgentDirNames[parts[len(parts)-1]] || projectAgentFileNames[parts[len(parts)-1]]
+ return legacyProjectAgentDirNames[parts[len(parts)-1]] || legacyProjectAgentFileNames[parts[len(parts)-1]]
}
diff --git a/internal/runtime/git_ssh_terminal_test.go b/internal/runtime/git_ssh_terminal_test.go
index 82d7ace2..66a3f588 100644
--- a/internal/runtime/git_ssh_terminal_test.go
+++ b/internal/runtime/git_ssh_terminal_test.go
@@ -101,7 +101,7 @@ func TestTerminalGitSSHAgentStaysOutOfWorkspace(t *testing.T) {
// every other bwrap process of the workspace sees an empty tmpfs there.
func TestBwrapPrivateBindsReachOnlyTheirProcess(t *testing.T) {
workspace := t.TempDir()
- base, err := bwrapArgsCommand(workspace, SandboxRequirements{}, false)
+ base, err := bwrapArgsCommand(workspace, SandboxRequirements{})
if err != nil {
t.Fatal(err)
}
diff --git a/internal/runtime/isolated_image_test.go b/internal/runtime/isolated_image_test.go
index 33fa8115..5de2a691 100644
--- a/internal/runtime/isolated_image_test.go
+++ b/internal/runtime/isolated_image_test.go
@@ -19,7 +19,7 @@ func TestIsolatedRuntimeImageReusesInstalledImage(t *testing.T) {
printf '%s\n' "$*" >> "$DOCKER_TEST_LOG"
case "$*" in
"image inspect loopforge-platform:tested") exit 0 ;;
- "inspect "*) exit 1 ;;
+ "inspect "*) echo 'Error: No such container' >&2; exit 1 ;;
"exec "*) echo /workspace ;;
"build "*) exit 99 ;;
esac
diff --git a/internal/runtime/runtime_test.go b/internal/runtime/runtime_test.go
index b3b828be..6cf262ef 100644
--- a/internal/runtime/runtime_test.go
+++ b/internal/runtime/runtime_test.go
@@ -216,19 +216,6 @@ func TestDockerBindMatchesWorkspace(t *testing.T) {
}
}
-func TestDockerContainerReusableWhenBindMatches(t *testing.T) {
- dir := t.TempDir()
- if !dockerContainerReusable(dir, nil, dir) {
- t.Fatal("matching bind should be reused after worker restart")
- }
- if dockerContainerReusable(dir, fmt.Errorf("inspect failed"), dir) {
- t.Fatal("inspect failure must not reuse")
- }
- if dockerContainerReusable(filepath.Join(dir, "other"), nil, dir) {
- t.Fatal("mismatched bind must not reuse")
- }
-}
-
func TestIsSandboxInterrupt(t *testing.T) {
if IsSandboxInterrupt(nil) {
t.Fatal("nil")
@@ -660,7 +647,7 @@ func TestManagerRejectsUnknownSandboxDriver(t *testing.T) {
}
}
-func TestSeatbeltProfileDeniesHostWritesAndProjectAgentConfig(t *testing.T) {
+func TestSeatbeltProfileDeniesHostWrites(t *testing.T) {
workspace := t.TempDir()
home := t.TempDir()
t.Setenv("HOME", home)
@@ -668,14 +655,14 @@ func TestSeatbeltProfileDeniesHostWritesAndProjectAgentConfig(t *testing.T) {
if err := os.MkdirAll(stateDir, 0o700); err != nil {
t.Fatal(err)
}
- profile, err := seatbeltProfileRequirements(workspace, ProviderRequirements("claude-code"))
+ profile, err := seatbeltProfileCommand(workspace, ProviderRequirements("claude-code"))
if err != nil {
t.Fatal(err)
}
if strings.Contains(profile, stateDir) {
t.Fatal("host Claude state must not be writable by a user-credential run")
}
- needles := []string{"(deny file-write*)", "(allow file-write*", "/private/tmp", "/dev/null", filepath.Join(workspace, "AGENTS.md"), filepath.Join(workspace, ".claude")}
+ needles := []string{"(deny file-write*)", "(allow file-write*", "/private/tmp", "/dev/null", workspace}
if runtime.GOOS == "darwin" {
needles = append(needles, "/private/var/folders")
}
@@ -695,7 +682,7 @@ func TestBwrapProvidesWritableRuntimeInfrastructure(t *testing.T) {
t.Fatal(err)
}
bunfs := stubBunFSMountPoint(t, filepath.Join(t.TempDir(), "$bunfs"))
- args, err := bwrapArgsRequirements(workspace, ProviderRequirements("codebuddy"))
+ args, err := bwrapArgsCommand(workspace, ProviderRequirements("codebuddy"))
if err != nil {
t.Fatal(err)
}
@@ -851,212 +838,65 @@ func TestLightweightSandboxSmoke(t *testing.T) {
}
}
-func TestBwrapAndDockerMaskRepositoryAgentConfig(t *testing.T) {
+func TestRestoreLegacyWorkspaceAgentConfig(t *testing.T) {
workspace := t.TempDir()
- if err := os.MkdirAll(filepath.Join(workspace, ".agents", "skills", "repo"), 0o755); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(filepath.Join(workspace, "AGENTS.md"), []byte("repo prompt"), 0o600); err != nil {
- t.Fatal(err)
- }
- if err := os.MkdirAll(filepath.Join(workspace, "services", "api", ".claude"), 0o755); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(filepath.Join(workspace, "services", "api", "CLAUDE.md"), []byte("nested prompt"), 0o600); err != nil {
- t.Fatal(err)
- }
- docker, err := dockerAgentConfigMasks(workspace)
- if err != nil {
+ repository := filepath.Join(workspace, "repo")
+ if err := os.Mkdir(repository, 0o700); err != nil {
t.Fatal(err)
}
- for name, isDir := range map[string]bool{"empty-dir": true, "empty-file": false} {
- target := filepath.Join(workspace, ".agentflow", "isolation", name)
- info, err := os.Lstat(target)
- if err != nil || (isDir && !info.IsDir()) || (!isDir && !info.Mode().IsRegular()) {
- t.Fatalf("Docker mount target %s: %v, %v", target, info, err)
- }
- }
- bwrap, err := bwrapAgentConfigMasks(workspace)
- if err != nil {
- t.Fatal(err)
- }
- bwrapText, dockerText := strings.Join(bwrap, " "), strings.Join(docker, " ")
- for _, target := range []string{filepath.Join(workspace, "AGENTS.md"), filepath.Join(workspace, ".agents"), filepath.Join(workspace, "services", "api", ".claude"), filepath.Join(workspace, "services", "api", "CLAUDE.md")} {
- if !strings.Contains(bwrapText, target) {
- t.Fatalf("bwrap mask missing %s: %v", target, bwrap)
- }
- }
- for _, target := range []string{"dst=/workspace/AGENTS.md", "dst=/workspace/.agents", "dst=/workspace/services/api/.claude", "dst=/workspace/services/api/CLAUDE.md"} {
- if !strings.Contains(dockerText, target) {
- t.Fatalf("docker mask missing %s: %v", target, docker)
- }
- }
- if strings.Contains(dockerText, "src="+workspace) {
- t.Fatalf("docker isolation sources nested inside workspace bind: %v", docker)
- }
-}
+ testRuntimeGit(t, repository, "init", "-b", "main")
+ testRuntimeGit(t, repository, "config", "user.email", "[email protected]")
+ testRuntimeGit(t, repository, "config", "user.name", "AgentFlow Test")
-func TestManagedSandboxGitIndexPreservesMaskedAgentConfig(t *testing.T) {
- if _, err := exec.LookPath("git"); err != nil {
- t.Skip("git is unavailable")
- }
- workspace := t.TempDir()
- testRuntimeGit(t, workspace, "init", "-b", "main")
- testRuntimeGit(t, workspace, "config", "user.email", "[email protected]")
- testRuntimeGit(t, workspace, "config", "user.name", "AgentFlow Test")
-
- originals := map[string]string{
- "AGENTS.md": "root instructions\n",
- ".codex/config.toml": "model = \"host\"\n",
- ".agents/skills/repo/SKILL.md": "repository skill\n",
- "services/api/CLAUDE.md": "nested instructions\n",
- "services/api/.claude/settings.json": "{\"enabled\":true}\n",
- }
- for path, content := range originals {
- full := filepath.Join(workspace, filepath.FromSlash(path))
- if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil {
+ paths := []string{"AGENTS.md", "subdir/CLAUDE.md", ".codex/config.toml", "app.txt"}
+ for _, name := range paths {
+ path := filepath.Join(repository, name)
+ if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
t.Fatal(err)
}
- if err := os.WriteFile(full, []byte(content), 0o600); err != nil {
+ if err := os.WriteFile(path, []byte("original\n"), 0o600); err != nil {
t.Fatal(err)
}
}
- businessPath := filepath.Join(workspace, "src", "app.txt")
- if err := os.MkdirAll(filepath.Dir(businessPath), 0o755); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(businessPath, []byte("before\n"), 0o600); err != nil {
- t.Fatal(err)
- }
- testRuntimeGit(t, workspace, "add", "-A")
- testRuntimeGit(t, workspace, "commit", "-m", "baseline")
- untrackedAgentConfig := filepath.Join(workspace, "services", "worker", "CODEBUDDY.md")
- if err := os.MkdirAll(filepath.Dir(untrackedAgentConfig), 0o755); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(untrackedAgentConfig, []byte("untracked local instructions\n"), 0o600); err != nil {
+ testRuntimeGit(t, repository, "add", "-A")
+ testRuntimeGit(t, repository, "commit", "-m", "baseline")
+ testRuntimeGit(t, repository, append([]string{"update-index", "--skip-worktree"}, paths...)...)
+ exclude := filepath.Join(repository, ".git", "info", "exclude")
+ kept := "*.generated\n" + agentFlowGitExcludeBlock + "/tmp/\n"
+ data := "*.generated\n" + legacyProjectAgentGitExcludeBlock + agentFlowGitExcludeBlock + "/tmp/\n"
+ if err := os.WriteFile(exclude, []byte(data), 0o600); err != nil {
t.Fatal(err)
}
- ctx := context.Background()
- if err := ProtectProjectAgentGitIndex(ctx, workspace, "bwrap"); err != nil {
+ repos := []domain.RepositoryContext{{WorkspaceDir: "repo"}}
+ if err := RestoreLegacyWorkspaceAgentConfig(context.Background(), workspace, repos); err != nil {
t.Fatal(err)
}
- for path := range originals {
- flag := testRuntimeGit(t, workspace, "ls-files", "-v", "--", path)
- if !strings.HasPrefix(flag, "S ") {
- t.Fatalf("protected path %s does not have skip-worktree set: %q", path, flag)
+ for _, name := range paths[:len(paths)-1] {
+ if flag := testRuntimeGit(t, repository, "ls-files", "-v", "--", name); !strings.HasPrefix(flag, "H ") {
+ t.Fatalf("%s still hidden: %s", name, flag)
}
}
- if err := RestoreProjectAgentGitIndex(ctx, workspace, "bwrap"); err != nil {
- t.Fatal(err)
- }
- if flag := testRuntimeGit(t, workspace, "ls-files", "-v", "--", "AGENTS.md"); strings.HasPrefix(flag, "S ") {
- t.Fatalf("restore left skip-worktree set: %q", flag)
- }
- if err := ProtectProjectAgentGitIndex(ctx, workspace, "docker"); err != nil {
- t.Fatal(err)
- }
-
- // Emulate the filesystem view produced by the Docker/bwrap masks: files
- // become empty and protected directories contain no repository files.
- if err := os.WriteFile(filepath.Join(workspace, "AGENTS.md"), nil, 0o600); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(filepath.Join(workspace, "services", "api", "CLAUDE.md"), nil, 0o600); err != nil {
- t.Fatal(err)
- }
- for _, dir := range []string{".codex", ".agents", "services/api/.claude"} {
- if err := os.RemoveAll(filepath.Join(workspace, filepath.FromSlash(dir))); err != nil {
- t.Fatal(err)
- }
- }
- if err := os.WriteFile(untrackedAgentConfig, nil, 0o600); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(businessPath, []byte("after\n"), 0o600); err != nil {
- t.Fatal(err)
- }
-
- testRuntimeGit(t, workspace, "add", "-A")
- if got := testRuntimeGit(t, workspace, "diff", "--cached", "--name-only"); got != "src/app.txt" {
- t.Fatalf("masked project configuration leaked into staged diff: %q", got)
+ if flag := testRuntimeGit(t, repository, "ls-files", "-v", "--", "app.txt"); !strings.HasPrefix(flag, "S ") {
+ t.Fatalf("user skip-worktree flag changed: %s", flag)
}
- testRuntimeGit(t, workspace, "commit", "-m", "business change")
- for path, original := range originals {
- if got := testRuntimeGit(t, workspace, "show", "HEAD:"+path); got+"\n" != original {
- t.Fatalf("committed content for %s = %q, want %q", path, got, strings.TrimSuffix(original, "\n"))
- }
+ if got, err := os.ReadFile(exclude); err != nil || string(got) != kept {
+ t.Fatalf("exclude = %q, err=%v", got, err)
}
-}
-
-func TestLocalSandboxDoesNotChangeProjectAgentGitIndex(t *testing.T) {
- workspace := t.TempDir()
- testRuntimeGit(t, workspace, "init", "-b", "main")
- testRuntimeGit(t, workspace, "config", "user.email", "[email protected]")
- testRuntimeGit(t, workspace, "config", "user.name", "AgentFlow Test")
- if err := os.WriteFile(filepath.Join(workspace, "AGENTS.md"), []byte("local instructions\n"), 0o600); err != nil {
+ // A subsequent call must leave newly set user bits alone once the marker is gone.
+ testRuntimeGit(t, repository, "update-index", "--skip-worktree", "AGENTS.md")
+ if err := RestoreLegacyWorkspaceAgentConfig(context.Background(), workspace, repos); err != nil {
t.Fatal(err)
}
- testRuntimeGit(t, workspace, "add", "AGENTS.md")
- testRuntimeGit(t, workspace, "commit", "-m", "baseline")
- if err := ProtectProjectAgentGitIndex(context.Background(), workspace, "local"); err != nil {
- t.Fatal(err)
- }
- if flag := testRuntimeGit(t, workspace, "ls-files", "-v", "--", "AGENTS.md"); strings.HasPrefix(flag, "S ") {
- t.Fatalf("local sandbox unexpectedly set skip-worktree: %q", flag)
+ if flag := testRuntimeGit(t, repository, "ls-files", "-v", "--", "AGENTS.md"); !strings.HasPrefix(flag, "S ") {
+ t.Fatalf("unmarked checkout changed on reuse: %s", flag)
}
}
-func TestProjectAgentGitIndexUpdatesAreIdempotent(t *testing.T) {
- workspace := t.TempDir()
- testRuntimeGit(t, workspace, "init", "-b", "main")
- testRuntimeGit(t, workspace, "config", "user.email", "[email protected]")
- testRuntimeGit(t, workspace, "config", "user.name", "AgentFlow Test")
- if err := os.WriteFile(filepath.Join(workspace, "AGENTS.md"), []byte("instructions\n"), 0o600); err != nil {
- t.Fatal(err)
- }
- testRuntimeGit(t, workspace, "add", "AGENTS.md")
- testRuntimeGit(t, workspace, "commit", "-m", "baseline")
-
- ctx := context.Background()
- if err := ProtectProjectAgentGitIndex(ctx, workspace, "docker"); err != nil {
- t.Fatal(err)
- }
- lockPath := filepath.Join(workspace, ".git", "index.lock")
- lock, err := os.OpenFile(lockPath, os.O_CREATE|os.O_RDWR, 0o600)
- if err != nil {
- t.Fatal(err)
- }
- // A second protect has no paths to update and therefore must not contend
- // with an unrelated live index lock.
- if err := ProtectProjectAgentGitIndex(ctx, workspace, "docker"); err != nil {
- lock.Close()
- t.Fatalf("idempotent protect touched the index: %v", err)
- }
- if err := lock.Close(); err != nil {
- t.Fatal(err)
- }
- if err := os.Remove(lockPath); err != nil {
- t.Fatal(err)
- }
-
- if err := RestoreProjectAgentGitIndex(ctx, workspace, "docker"); err != nil {
- t.Fatal(err)
- }
- lock, err = os.OpenFile(lockPath, os.O_CREATE|os.O_RDWR, 0o600)
- if err != nil {
- t.Fatal(err)
- }
- // Restore is idempotent for the same reason.
- if err := RestoreProjectAgentGitIndex(ctx, workspace, "docker"); err != nil {
- lock.Close()
- t.Fatalf("idempotent restore touched the index: %v", err)
- }
- if err := lock.Close(); err != nil {
- t.Fatal(err)
- }
- if err := os.Remove(lockPath); err != nil {
+func markLegacyProjectAgentConfig(t *testing.T, workspace string) {
+ t.Helper()
+ testRuntimeGit(t, workspace, "update-index", "--skip-worktree", "AGENTS.md")
+ if err := os.WriteFile(filepath.Join(workspace, ".git", "info", "exclude"), []byte(legacyProjectAgentGitExcludeBlock), 0o600); err != nil {
t.Fatal(err)
}
}
@@ -1071,14 +911,12 @@ func TestRestoreProjectAgentGitIndexRemovesStaleIndexLock(t *testing.T) {
}
testRuntimeGit(t, workspace, "add", "AGENTS.md")
testRuntimeGit(t, workspace, "commit", "-m", "baseline")
- if err := ProtectProjectAgentGitIndex(context.Background(), workspace, "docker"); err != nil {
- t.Fatal(err)
- }
+ markLegacyProjectAgentConfig(t, workspace)
lockPath := filepath.Join(workspace, ".git", "index.lock")
if err := os.WriteFile(lockPath, nil, 0o600); err != nil {
t.Fatal(err)
}
- if err := RestoreProjectAgentGitIndex(context.Background(), workspace, "docker"); err != nil {
+ if err := RestoreLegacyProjectAgentConfig(context.Background(), workspace); err != nil {
t.Fatalf("restore with stale index lock: %v", err)
}
if _, err := os.Stat(lockPath); !os.IsNotExist(err) {
@@ -1099,9 +937,7 @@ func TestRestoreProjectAgentGitIndexKeepsLiveIndexLock(t *testing.T) {
}
testRuntimeGit(t, workspace, "add", "AGENTS.md")
testRuntimeGit(t, workspace, "commit", "-m", "baseline")
- if err := ProtectProjectAgentGitIndex(context.Background(), workspace, "docker"); err != nil {
- t.Fatal(err)
- }
+ markLegacyProjectAgentConfig(t, workspace)
lockPath := filepath.Join(workspace, ".git", "index.lock")
lock, err := os.OpenFile(lockPath, os.O_CREATE|os.O_RDWR, 0o600)
if err != nil {
@@ -1112,7 +948,7 @@ func TestRestoreProjectAgentGitIndexKeepsLiveIndexLock(t *testing.T) {
wait, poll := gitIndexLockWait, gitIndexLockPoll
gitIndexLockWait, gitIndexLockPoll = 300*time.Millisecond, 20*time.Millisecond
defer func() { gitIndexLockWait, gitIndexLockPoll = wait, poll }()
- err = RestoreProjectAgentGitIndex(context.Background(), workspace, "docker")
+ err = RestoreLegacyProjectAgentConfig(context.Background(), workspace)
if err == nil || !strings.Contains(err.Error(), "held by a live process") {
t.Fatalf("restore error = %v, want live-process protection", err)
}
@@ -2290,19 +2126,6 @@ func TestDockerWorkspaceExecDropsInnerLoginShell(t *testing.T) {
}
}
-func TestSandboxMasksRejectSymlinkedAgentDirectory(t *testing.T) {
- dir := t.TempDir()
- if err := os.Symlink(t.TempDir(), filepath.Join(dir, ".claude")); err != nil {
- t.Fatal(err)
- }
- if _, err := bwrapAgentConfigMasks(dir); err == nil {
- t.Fatal("bwrap masks accepted a symlinked Agent CLI directory")
- }
- if _, err := dockerAgentConfigMasks(dir); err == nil {
- t.Fatal("Docker masks accepted a symlinked Agent CLI directory")
- }
-}
-
func TestAdapterRequiresTerminalResult(t *testing.T) {
adapter := newProtocolAdapter(domain.ExecutorDefinition{Kind: "codebuddy", Protocol: "stream-json"}, nil)
if adapter.Finished() || adapter.Failed() {
@@ -2466,6 +2289,7 @@ func TestProjectAgentGitIndexWaitsForBriefLiveLock(t *testing.T) {
}
testRuntimeGit(t, workspace, "add", "AGENTS.md")
testRuntimeGit(t, workspace, "commit", "-m", "baseline")
+ markLegacyProjectAgentConfig(t, workspace)
wait, poll := gitIndexLockWait, gitIndexLockPoll
gitIndexLockWait, gitIndexLockPoll = 5*time.Second, 20*time.Millisecond
defer func() { gitIndexLockWait, gitIndexLockPoll = wait, poll }()
@@ -2479,7 +2303,7 @@ func TestProjectAgentGitIndexWaitsForBriefLiveLock(t *testing.T) {
lock.Close()
os.Remove(lockPath)
}()
- if err := ProtectProjectAgentGitIndex(context.Background(), workspace, "docker"); err != nil {
+ if err := RestoreLegacyProjectAgentConfig(context.Background(), workspace); err != nil {
t.Fatalf("brief live lock failed preparation: %v", err)
}
}
@@ -2496,6 +2320,7 @@ func TestProjectAgentGitIndexLockWaitStopsOnCancel(t *testing.T) {
}
testRuntimeGit(t, workspace, "add", "AGENTS.md")
testRuntimeGit(t, workspace, "commit", "-m", "baseline")
+ markLegacyProjectAgentConfig(t, workspace)
wait, poll := gitIndexLockWait, gitIndexLockPoll
gitIndexLockWait, gitIndexLockPoll = time.Minute, 20*time.Millisecond
defer func() { gitIndexLockWait, gitIndexLockPoll = wait, poll }()
@@ -2509,7 +2334,7 @@ func TestProjectAgentGitIndexLockWaitStopsOnCancel(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
defer cancel()
started := time.Now()
- err = ProtectProjectAgentGitIndex(ctx, workspace, "docker")
+ err = RestoreLegacyProjectAgentConfig(ctx, workspace)
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("cancelled wait error = %v, want context deadline", err)
}
diff --git a/internal/runtime/sandbox_docker.go b/internal/runtime/sandbox_docker.go
index feaa67b5..0540f445 100644
--- a/internal/runtime/sandbox_docker.go
+++ b/internal/runtime/sandbox_docker.go
@@ -6,6 +6,7 @@ import (
"context"
"crypto/sha256"
"encoding/hex"
+ "encoding/json"
"errors"
"fmt"
"log"
@@ -68,16 +69,34 @@ func removeDockerSandbox(ctx context.Context, container, image string) {
ctx, cancel := context.WithTimeout(ctx, dockerTeardownTimeout)
defer cancel()
if strings.TrimSpace(container) != "" {
- _ = exec.CommandContext(ctx, "docker", "rm", "-f", dockerScriptContainerName(container)).Run()
- removeDockerBrowser(ctx, container)
- _ = exec.CommandContext(ctx, "docker", "rm", "-f", container).Run()
+ _ = removeDockerWorkspaceContainers(ctx, container)
}
if ephemeralDockerImage(image) {
_ = exec.CommandContext(ctx, "docker", "rmi", "-f", image).Run()
}
}
-const dockerTeardownTimeout = 60 * time.Second
+const (
+ dockerTeardownTimeout = 60 * time.Second
+ legacyDockerScriptSuffix = "-scripts"
+)
+
+func removeDockerWorkspaceContainers(ctx context.Context, container string) error {
+ // Older runs can still own a script companion. Reclaim it with the workspace.
+ if err := removeDockerContainer(ctx, container+legacyDockerScriptSuffix); err != nil {
+ return err
+ }
+ removeDockerBrowser(ctx, container)
+ return removeDockerContainer(ctx, container)
+}
+
+func removeDockerContainer(ctx context.Context, name string) error {
+ out, err := exec.CommandContext(ctx, "docker", "rm", "-f", name).CombinedOutput()
+ if err != nil && !dockerObjectGone(string(out), err) {
+ return fmt.Errorf("remove Docker container %s: %w: %s", name, err, strings.TrimSpace(string(out)))
+ }
+ return nil
+}
// dockerAvailable keeps run teardown from spawning processes on control planes
// that only ever use the local driver. Cleanup runs per finished run and on a
@@ -145,14 +164,6 @@ func (s *dockerSandbox) Exec(ctx context.Context, command CommandSpec, sink Even
}
func (s *dockerSandbox) execOnce(ctx context.Context, command CommandSpec, sink EventSink) (out string, err error) {
- if trustedScriptCommand(command) {
- return s.execScript(ctx, command, sink)
- }
- if maskedAgentCommand(command) {
- if err := s.refreshAgentMasks(ctx); err != nil {
- return "", err
- }
- }
args := []string{"exec"}
if command.Stdin != nil {
args = append(args, "-i")
@@ -267,14 +278,7 @@ func dropShellLoginFlag(argv []string) []string {
}
func (s *dockerSandbox) Recreate(ctx context.Context) error {
- s.mu.Lock()
- s.started = false
- name := s.name
- s.mu.Unlock()
- _ = exec.CommandContext(ctx, "docker", "rm", "-f", dockerScriptContainerName(name)).Run()
- removeDockerBrowser(ctx, name)
- _ = exec.CommandContext(ctx, "docker", "rm", "-f", name).Run()
- return s.ensureStarted(ctx)
+ return s.start(ctx, true)
}
// invalidate drops the cached started flag without docker rm. The next
@@ -368,10 +372,6 @@ func dockerInterruptExcerpt(out string) string {
const dockerInterruptTailLines = 5
-func dockerContainerReusable(source string, sourceErr error, workspace string) bool {
- return sourceErr == nil && dockerBindMatchesWorkspace(source, workspace)
-}
-
func isDockerCwdUnsafe(out string, err error) bool {
if err == nil {
return false
@@ -380,12 +380,36 @@ func isDockerCwdUnsafe(out string, err error) bool {
return strings.Contains(msg, "outside of container mount") || strings.Contains(msg, "container breakout") || strings.Contains(msg, "oci runtime exec failed") || strings.Contains(msg, "exit status 126")
}
-func dockerWorkspaceBindSource(ctx context.Context, name string) (string, error) {
- out, err := exec.CommandContext(ctx, "docker", "inspect", "-f", `{{range .Mounts}}{{if eq .Destination "/workspace"}}{{.Source}}{{end}}{{end}}`, name).CombinedOutput()
+type dockerWorkspaceMounts struct {
+ source string
+ legacyMasks bool
+}
+
+func inspectDockerWorkspaceMounts(ctx context.Context, name string) (*dockerWorkspaceMounts, error) {
+ out, err := exec.CommandContext(ctx, "docker", "inspect", "--type", "container", "--format", `{{json .Mounts}}`, name).CombinedOutput()
+ if dockerObjectGone(string(out), err) {
+ return nil, nil
+ }
if err != nil {
- return "", fmt.Errorf("docker inspect mounts: %w: %s", err, out)
+ return nil, fmt.Errorf("docker inspect mounts: %w: %s", err, strings.TrimSpace(string(out)))
+ }
+ var mounts []struct {
+ Destination, Source string
+ }
+ if err := json.Unmarshal(out, &mounts); err != nil {
+ return nil, fmt.Errorf("decode Docker mounts for %s: %w", name, err)
}
- return strings.TrimSpace(string(out)), nil
+ workspace := &dockerWorkspaceMounts{}
+ for _, mount := range mounts {
+ switch mount.Destination {
+ case "/workspace":
+ workspace.source = mount.Source
+ case "/workspace/.agentflow/isolation/empty-dir", "/workspace/.agentflow/isolation/empty-file":
+ // Older containers keep these binds even when restarted.
+ workspace.legacyMasks = true
+ }
+ }
+ return workspace, nil
}
func dockerBindMatchesWorkspace(source, workspace string) bool {
@@ -646,27 +670,32 @@ func staleCachedDockerImages(listed []string, keep, inUse map[string]struct{}) [
}
func (s *dockerSandbox) ensureStarted(ctx context.Context) error {
+ return s.start(ctx, false)
+}
+
+func (s *dockerSandbox) start(ctx context.Context, recreate bool) error {
s.mu.Lock()
defer s.mu.Unlock()
- if s.started {
+ if s.started && !recreate {
return nil
}
+ s.started = false
name, workspace, p := s.name, s.workspace, s.profile
- if err := exec.CommandContext(ctx, "docker", "inspect", name).Run(); err == nil {
- source, sourceErr := dockerWorkspaceBindSource(ctx, name)
- if dockerContainerReusable(source, sourceErr, workspace) {
- if startErr := exec.CommandContext(ctx, "docker", "start", name).Run(); startErr != nil {
- _ = exec.CommandContext(ctx, "docker", "rm", "-f", name).Run()
- } else if readyErr := waitDockerWorkspaceReady(ctx, name); readyErr != nil {
- _ = exec.CommandContext(ctx, "docker", "rm", "-f", name).Run()
- } else {
- s.started = true
- return nil
+ mounts, err := inspectDockerWorkspaceMounts(ctx, name)
+ if err != nil {
+ return err
+ }
+ if mounts != nil {
+ if !dockerBindMatchesWorkspace(mounts.source, workspace) {
+ return fmt.Errorf("docker sandbox %s is bound to %s, not %s", name, mounts.source, workspace)
+ }
+ if !recreate && !mounts.legacyMasks {
+ if err := exec.CommandContext(ctx, "docker", "start", name).Run(); err == nil {
+ if err := waitDockerWorkspaceReady(ctx, name); err == nil {
+ s.started = true
+ return nil
+ }
}
- } else if sourceErr != nil {
- _ = exec.CommandContext(ctx, "docker", "rm", "-f", name).Run()
- } else {
- return fmt.Errorf("docker sandbox %s is bound to %s, not %s", name, source, workspace)
}
}
built, err := ensureDockerImage(ctx, workspace, s.dockerfile)
@@ -674,7 +703,6 @@ func (s *dockerSandbox) ensureStarted(ctx context.Context) error {
return err
}
image := built
- s.builtImage = built
args := []string{"create", "--name", name, "--init", "--cap-drop=ALL", "--security-opt", "no-new-privileges", "-v", workspace + ":/workspace"}
// Native installs own private (0700) workspaces as the service user.
// A root image without DAC capabilities cannot access another UID's bind.
@@ -707,15 +735,6 @@ func (s *dockerSandbox) ensureStarted(ctx context.Context) error {
}
args = append(args, guards...)
}
- var aliases []string
- if root := s.requirements.ConversationRoot; root != "" {
- aliases = append(aliases, filepath.Join(root, "ws"))
- }
- maskArgs, err := dockerAgentConfigMasks(workspace, aliases...)
- if err != nil {
- return err
- }
- args = append(args, maskArgs...)
stateArgs, err := dockerAgentStateMountRequirements(s.requirements)
if err != nil {
return err
@@ -735,6 +754,14 @@ func (s *dockerSandbox) ensureStarted(ctx context.Context) error {
} else {
args = append(args, image, "sh", "-lc", "trap : TERM INT; sleep infinity & wait")
}
+ // Resolve the replacement image and mounts before retiring a workspace with
+ // legacy masks. Its new container ID invalidates old preparation receipts.
+ if mounts != nil || recreate {
+ if err := removeDockerWorkspaceContainers(ctx, name); err != nil {
+ return err
+ }
+ }
+ s.builtImage = built
if out, err := exec.CommandContext(ctx, "docker", args...).CombinedOutput(); err != nil {
dropEphemeralDockerImage(s.builtImage)
s.builtImage = ""
diff --git a/internal/runtime/sandbox_mask_targets_guard_test.go b/internal/runtime/sandbox_mask_targets_guard_test.go
deleted file mode 100644
index 4a4a7975..00000000
--- a/internal/runtime/sandbox_mask_targets_guard_test.go
+++ /dev/null
@@ -1,62 +0,0 @@
-package runtime
-
-import (
- "os"
- "path/filepath"
- "strings"
- "testing"
-)
-
-// A symlinked empty-file target must be rejected even when it points to a
-// regular file inside the workspace: Docker would bind the mask over the link
-// target instead of the placeholder, so the link target must stay untouched.
-func TestEnsureDockerMaskTargetsRejectsSymlinkedFile(t *testing.T) {
- workspace := t.TempDir()
- isolation, err := EnsureControlDirectory(workspace, "isolation")
- if err != nil {
- t.Fatal(err)
- }
- real := filepath.Join(isolation, "real-file")
- if err := os.WriteFile(real, nil, 0o600); err != nil {
- t.Fatal(err)
- }
- if err := os.Symlink(real, filepath.Join(isolation, "empty-file")); err != nil {
- t.Fatal(err)
- }
- err = ensureDockerMaskTargets(workspace)
- if err == nil || !strings.Contains(err.Error(), "workspace path is a symlink") {
- t.Fatalf("ensureDockerMaskTargets() error = %v, want symlink error", err)
- }
- if info, err := os.Lstat(filepath.Join(isolation, "empty-file")); err != nil || info.Mode()&os.ModeSymlink == 0 {
- t.Fatalf("symlinked target was replaced: %v, %v", info, err)
- }
-}
-
-// The empty-dir target must be a directory; a regular file in its place is an
-// error rather than silently skipped.
-func TestEnsureDockerMaskTargetsRejectsFileAsEmptyDir(t *testing.T) {
- workspace := t.TempDir()
- isolation, err := EnsureControlDirectory(workspace, "isolation")
- if err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(filepath.Join(isolation, "empty-dir"), nil, 0o600); err != nil {
- t.Fatal(err)
- }
- if err := ensureDockerMaskTargets(workspace); err == nil {
- t.Fatal("ensureDockerMaskTargets accepted a regular file as the empty-dir target")
- }
-}
-
-// dockerAgentConfigMasks must stop on a broken mount target instead of
-// returning masks Docker cannot mount.
-func TestDockerAgentConfigMasksPropagatesTargetError(t *testing.T) {
- workspace := t.TempDir()
- if _, err := EnsureControlDirectory(workspace, "isolation", "empty-file"); err != nil {
- t.Fatal(err)
- }
- masks, err := dockerAgentConfigMasks(workspace)
- if err == nil || !strings.Contains(err.Error(), "sandbox mask target is not a regular file") || masks != nil {
- t.Fatalf("dockerAgentConfigMasks() = %v, %v; want nil masks and non-regular file error", masks, err)
- }
-}
diff --git a/internal/runtime/sandbox_mask_targets_test.go b/internal/runtime/sandbox_mask_targets_test.go
deleted file mode 100644
index 3ab668ff..00000000
--- a/internal/runtime/sandbox_mask_targets_test.go
+++ /dev/null
@@ -1,56 +0,0 @@
-package runtime
-
-import (
- "os"
- "path/filepath"
- "strings"
- "testing"
-)
-
-func TestEnsureDockerMaskTargetsCreatesTargets(t *testing.T) {
- workspace := t.TempDir()
- for i := 0; i < 2; i++ {
- if err := ensureDockerMaskTargets(workspace); err != nil {
- t.Fatalf("call %d: %v", i+1, err)
- }
- }
- dir, err := os.Lstat(filepath.Join(workspace, ".agentflow", "isolation", "empty-dir"))
- if err != nil || !dir.IsDir() {
- t.Fatalf("empty-dir target: %v, %v", dir, err)
- }
- file, err := os.Lstat(filepath.Join(workspace, ".agentflow", "isolation", "empty-file"))
- if err != nil || !file.Mode().IsRegular() {
- t.Fatalf("empty-file target: %v, %v", file, err)
- }
- if file.Mode().Perm() != 0o600 {
- t.Fatalf("empty-file mode = %v, want 0600", file.Mode().Perm())
- }
-}
-
-func TestEnsureDockerMaskTargetsKeepsExistingFile(t *testing.T) {
- workspace := t.TempDir()
- if err := ensureDockerMaskTargets(workspace); err != nil {
- t.Fatal(err)
- }
- target := filepath.Join(workspace, ".agentflow", "isolation", "empty-file")
- if err := os.WriteFile(target, []byte("kept"), 0o600); err != nil {
- t.Fatal(err)
- }
- if err := ensureDockerMaskTargets(workspace); err != nil {
- t.Fatal(err)
- }
- if data, err := os.ReadFile(target); err != nil || string(data) != "kept" {
- t.Fatalf("existing empty-file was rewritten: %q, %v", data, err)
- }
-}
-
-func TestEnsureDockerMaskTargetsRejectsNonRegularFile(t *testing.T) {
- workspace := t.TempDir()
- if _, err := EnsureControlDirectory(workspace, "isolation", "empty-file"); err != nil {
- t.Fatal(err)
- }
- err := ensureDockerMaskTargets(workspace)
- if err == nil || !strings.Contains(err.Error(), "sandbox mask target is not a regular file") {
- t.Fatalf("ensureDockerMaskTargets() error = %v, want non-regular file error", err)
- }
-}
diff --git a/internal/runtime/sandbox_native_test.go b/internal/runtime/sandbox_native_test.go
index 054d1d29..718243a2 100644
--- a/internal/runtime/sandbox_native_test.go
+++ b/internal/runtime/sandbox_native_test.go
@@ -23,7 +23,7 @@ func TestBwrapBunFSMountPoint(t *testing.T) {
// Missing but creatable: created once, then mounted.
created := stubBunFSMountPoint(t, filepath.Join(t.TempDir(), "$bunfs"))
- args, err := bwrapArgsRequirements(workspace, claude)
+ args, err := bwrapArgsCommand(workspace, claude)
if err != nil {
t.Fatal(err)
}
@@ -37,7 +37,7 @@ func TestBwrapBunFSMountPoint(t *testing.T) {
// Cannot be created (parent missing / read-only root): skip the mount
// instead of failing the whole sandbox.
missing := stubBunFSMountPoint(t, filepath.Join(t.TempDir(), "absent", "$bunfs"))
- args, err = bwrapArgsRequirements(workspace, claude)
+ args, err = bwrapArgsCommand(workspace, claude)
if err != nil {
t.Fatal(err)
}
@@ -47,7 +47,7 @@ func TestBwrapBunFSMountPoint(t *testing.T) {
// CLIs without BunFS never touch it.
untouched := stubBunFSMountPoint(t, filepath.Join(t.TempDir(), "$bunfs"))
- if _, err := bwrapArgsRequirements(workspace, ProviderRequirements("codex")); err != nil {
+ if _, err := bwrapArgsCommand(workspace, ProviderRequirements("codex")); err != nil {
t.Fatal(err)
}
if _, err := os.Stat(untouched); !os.IsNotExist(err) {
diff --git a/internal/runtime/sandbox_owner_linux_test.go b/internal/runtime/sandbox_owner_linux_test.go
index 2e7fe9f1..62f96d78 100644
--- a/internal/runtime/sandbox_owner_linux_test.go
+++ b/internal/runtime/sandbox_owner_linux_test.go
@@ -30,7 +30,6 @@ func TestDockerSandboxNativeOwner(t *testing.T) {
t.Fatal(err)
}
defer sandbox.Close(context.Background())
- defer os.RemoveAll(dockerIsolationMaskRoot(workspace))
want := fmt.Sprintf("%d:%d", os.Geteuid(), os.Getegid())
for _, provider := range []string{"", "script"} {
command := fmt.Sprintf(`test "$(id -u):$(id -g)" = %s && printf owner-ok > result.txt && grep -q '^CapEff:[[:space:]]*0000000000000000$' /proc/self/status && grep -q '^NoNewPrivs:[[:space:]]*1$' /proc/self/status`, want)
diff --git a/internal/runtime/sandbox_process.go b/internal/runtime/sandbox_process.go
index eebb9131..25b4af94 100644
--- a/internal/runtime/sandbox_process.go
+++ b/internal/runtime/sandbox_process.go
@@ -14,106 +14,6 @@ import (
"agentflow/internal/domain"
)
-// projectAgentPaths are deliberately absent from the executor's filesystem
-// view. AgentFlow definitions are the only source of instructions, skills and
-// CLI configuration for unattended runs.
-var rootProjectAgentPaths = []string{
- "AGENTS.md",
- "AGENTS.override.md",
- "CLAUDE.md",
- "CLAUDE.local.md",
- "CODEBUDDY.md",
- ".agents",
- ".codex",
- ".claude",
- ".codebuddy",
- ".mcp.json",
-}
-
-var projectAgentDirNames = map[string]bool{
- ".agents": true, ".codex": true, ".claude": true, ".codebuddy": true,
-}
-
-var projectAgentFileNames = map[string]bool{
- "AGENTS.md": true, "AGENTS.override.md": true,
- "CLAUDE.md": true, "CLAUDE.local.md": true,
- "CODEBUDDY.md": true, ".mcp.json": true,
-}
-
-func discoverProjectAgentPaths(workspace string) ([]string, error) {
- seen := map[string]bool{}
- for _, rel := range rootProjectAgentPaths {
- seen[filepath.Clean(rel)] = true
- }
- err := filepath.WalkDir(workspace, func(path string, entry os.DirEntry, walkErr error) error {
- if walkErr != nil {
- return walkErr
- }
- rel, err := filepath.Rel(workspace, path)
- if err != nil || rel == "." {
- return err
- }
- name := entry.Name()
- if projectAgentDirNames[name] {
- seen[rel] = true
- if entry.IsDir() {
- return filepath.SkipDir
- }
- return nil
- }
- if entry.IsDir() {
- if name == ".git" || name == ".agentflow" || name == "node_modules" {
- return filepath.SkipDir
- }
- return nil
- }
- if projectAgentFileNames[name] {
- seen[rel] = true
- }
- return nil
- })
- if err != nil {
- return nil, err
- }
- out := make([]string, 0, len(seen))
- for rel := range seen {
- out = append(out, rel)
- }
- sort.Strings(out)
- return out, nil
-}
-
-func validateAgentConfigTarget(workspace, rel string) (os.FileInfo, error) {
- target := filepath.Join(workspace, rel)
- info, err := os.Lstat(target)
- if err != nil {
- return nil, err
- }
- if info.Mode()&os.ModeSymlink == 0 {
- return info, nil
- }
- if projectAgentDirNames[filepath.Base(rel)] {
- return nil, fmt.Errorf("refusing symlinked Agent CLI directory: %s", target)
- }
- resolved, err := filepath.EvalSymlinks(target)
- if err != nil {
- return nil, err
- }
- root, err := filepath.Abs(workspace)
- if err != nil {
- return nil, err
- }
- resolved, err = filepath.Abs(resolved)
- if err != nil {
- return nil, err
- }
- inside, err := filepath.Rel(root, resolved)
- if err != nil || inside == ".." || strings.HasPrefix(inside, ".."+string(os.PathSeparator)) || !projectAgentFileNames[filepath.Base(resolved)] {
- return nil, fmt.Errorf("refusing Agent CLI configuration symlink outside the known project configuration set: %s", target)
- }
- return os.Stat(target)
-}
-
func appendEnvironment(base []string, overlays ...map[string]string) []string {
values := map[string]string{}
order := make([]string, 0, len(base))
@@ -236,14 +136,14 @@ func (s *processSandbox) command(ctx context.Context, command CommandSpec, base
var cmd *exec.Cmd
switch s.driver {
case "seatbelt":
- profile, err := seatbeltProfileCommand(s.workspace, s.requirements, !trustedScriptCommand(command))
+ profile, err := seatbeltProfileCommand(s.workspace, s.requirements)
if err != nil {
return nil, err
}
args := append([]string{"-p", profile}, command.Argv...)
cmd = exec.CommandContext(ctx, s.binary, args...)
case "bwrap":
- args, err := bwrapArgsCommand(s.workspace, s.requirements, !trustedScriptCommand(command))
+ args, err := bwrapArgsCommand(s.workspace, s.requirements)
if err != nil {
return nil, err
}
@@ -340,11 +240,7 @@ func agentStateDirectories(requirements SandboxRequirements) ([]resolvedCLIState
return result, nil
}
-func seatbeltProfileRequirements(workspace string, requirements SandboxRequirements) (string, error) {
- return seatbeltProfileCommand(workspace, requirements, true)
-}
-
-func seatbeltProfileCommand(workspace string, requirements SandboxRequirements, maskAgentConfig bool) (string, error) {
+func seatbeltProfileCommand(workspace string, requirements SandboxRequirements) (string, error) {
root, err := filepath.Abs(workspace)
if err != nil {
return "", err
@@ -367,28 +263,6 @@ func seatbeltProfileCommand(workspace string, requirements SandboxRequirements,
fmt.Fprintf(&b, "(allow file-write* (subpath %s))\n", strconv.Quote(state.path))
}
b.WriteString("(allow file-write* (literal \"/dev/null\"))\n")
- if !maskAgentConfig {
- return b.String(), nil
- }
- maskedPaths, err := discoverProjectAgentPaths(root)
- if err != nil {
- return "", err
- }
- for _, rel := range maskedPaths {
- path := filepath.Join(root, rel)
- if _, err := os.Lstat(path); err == nil {
- if _, err := validateAgentConfigTarget(root, rel); err != nil {
- return "", err
- }
- } else if !os.IsNotExist(err) {
- return "", err
- }
- if projectAgentDirNames[filepath.Base(rel)] {
- fmt.Fprintf(&b, "(deny file-read* (subpath %s))\n", strconv.Quote(path))
- } else {
- fmt.Fprintf(&b, "(deny file-read* (literal %s))\n", strconv.Quote(path))
- }
- }
return b.String(), nil
}
@@ -412,10 +286,6 @@ func ensureBunFSMountPoint() bool {
return true
}
-func bwrapArgsRequirements(workspace string, requirements SandboxRequirements) ([]string, error) {
- return bwrapArgsCommand(workspace, requirements, true)
-}
-
// bwrapPrivateBinds adds per-process binds before the "--" that ends the
// bwrap options. They come after --tmpfs /tmp, so a directory under the host
// /tmp is visible to this process only.
@@ -430,7 +300,7 @@ func bwrapPrivateBinds(args, binds []string) []string {
return append(out, "--")
}
-func bwrapArgsCommand(workspace string, requirements SandboxRequirements, maskAgentConfig bool) ([]string, error) {
+func bwrapArgsCommand(workspace string, requirements SandboxRequirements) ([]string, error) {
root, err := filepath.Abs(workspace)
if err != nil {
return nil, err
@@ -459,150 +329,10 @@ func bwrapArgsCommand(workspace string, requirements SandboxRequirements, maskAg
return nil, statErr
}
}
- if maskAgentConfig {
- maskArgs, err := bwrapAgentConfigMasks(root)
- if err != nil {
- return nil, err
- }
- args = append(args, maskArgs...)
- }
args = append(args, "--")
return args, nil
}
-func isolationMaskSources(workspace string) (emptyDir, emptyFile string, err error) {
- return isolationMaskSourcesAt(filepath.Join(workspace, ".agentflow", "isolation"))
-}
-
-func isolationMaskSourcesAt(root string) (emptyDir, emptyFile string, err error) {
- if err = os.MkdirAll(filepath.Dir(root), 0o700); err != nil {
- return "", "", err
- }
- if err = ensureDirectoryNoSymlink(root, 0o700); err != nil {
- return "", "", err
- }
- emptyDir = filepath.Join(root, "empty-dir")
- emptyFile = filepath.Join(root, "empty-file")
- if err = ensureDirectoryNoSymlink(emptyDir, 0o700); err != nil {
- return "", "", err
- }
- if info, statErr := os.Lstat(emptyFile); statErr == nil && (info.Mode()&os.ModeSymlink != 0 || !info.Mode().IsRegular()) {
- return "", "", fmt.Errorf("sandbox mask path is not a regular file: %s", emptyFile)
- } else if statErr != nil && !os.IsNotExist(statErr) {
- return "", "", statErr
- }
- file, openErr := os.OpenFile(emptyFile, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600)
- if openErr != nil {
- return "", "", openErr
- }
- if err = file.Close(); err != nil {
- return "", "", err
- }
- return emptyDir, emptyFile, nil
-}
-
-func bwrapAgentConfigMasks(workspace string) ([]string, error) {
- emptyDir, emptyFile, err := isolationMaskSources(workspace)
- if err != nil {
- return nil, err
- }
- args := []string{"--ro-bind", emptyDir, emptyDir, "--ro-bind", emptyFile, emptyFile}
- maskedPaths, err := discoverProjectAgentPaths(workspace)
- if err != nil {
- return nil, err
- }
- for _, rel := range maskedPaths {
- target := filepath.Join(workspace, rel)
- info, statErr := validateAgentConfigTarget(workspace, rel)
- if os.IsNotExist(statErr) {
- continue
- }
- if statErr != nil {
- return nil, statErr
- }
- source := emptyFile
- if info.IsDir() {
- source = emptyDir
- }
- args = append(args, "--ro-bind", source, target)
- }
- return args, nil
-}
-
-func dockerIsolationMaskRoot(workspace string) string {
- workspace = filepath.Clean(workspace)
- return filepath.Join(filepath.Dir(workspace), ".isolation-masks", filepath.Base(workspace))
-}
-
-// ensureDockerMaskTargets creates the in-workspace mount targets for the
-// isolation mask sources: Docker Desktop cannot create missing nested mount
-// targets on a VirtioFS share.
-func ensureDockerMaskTargets(workspace string) error {
- if _, err := EnsureControlDirectory(workspace, "isolation", "empty-dir"); err != nil {
- return err
- }
- target := filepath.Join(workspace, ".agentflow", "isolation", "empty-file")
- root, rel, err := openWorkspacePath(workspace, target)
- if err != nil {
- return err
- }
- defer root.Close()
- file, err := root.OpenFile(rel, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600)
- if err == nil {
- return file.Close()
- }
- if !os.IsExist(err) {
- return err
- }
- info, err := root.Lstat(rel)
- if err != nil {
- return err
- }
- if !info.Mode().IsRegular() {
- return fmt.Errorf("sandbox mask target is not a regular file: %s", target)
- }
- return nil
-}
-
-func dockerAgentConfigMasks(workspace string, aliases ...string) ([]string, error) {
- if err := ensureDockerMaskTargets(workspace); err != nil {
- return nil, err
- }
- emptyDir, emptyFile, err := isolationMaskSourcesAt(dockerIsolationMaskRoot(workspace))
- if err != nil {
- return nil, err
- }
- emptyDirTarget := filepath.ToSlash(filepath.Join("/workspace", ".agentflow", "isolation", "empty-dir"))
- emptyFileTarget := filepath.ToSlash(filepath.Join("/workspace", ".agentflow", "isolation", "empty-file"))
- args := []string{
- "--mount", "type=bind,src=" + emptyDir + ",dst=" + emptyDirTarget + ",readonly",
- "--mount", "type=bind,src=" + emptyFile + ",dst=" + emptyFileTarget + ",readonly",
- }
- maskedPaths, err := discoverProjectAgentPaths(workspace)
- if err != nil {
- return nil, err
- }
- for _, rel := range maskedPaths {
- info, statErr := validateAgentConfigTarget(workspace, rel)
- if os.IsNotExist(statErr) {
- continue
- }
- if statErr != nil {
- return nil, statErr
- }
- source := emptyFile
- if info.IsDir() {
- source = emptyDir
- }
- containerTarget := filepath.ToSlash(filepath.Join("/workspace", rel))
- args = append(args, "--mount", "type=bind,src="+source+",dst="+containerTarget+",readonly")
- for _, alias := range aliases {
- args = append(args, "--mount", "type=bind,src="+source+",dst="+filepath.ToSlash(filepath.Join(alias, rel))+",readonly")
- }
- }
- return args, nil
-}
-
// dockerAgentStateMount exposes only the state directory belonging to the CLI
// selected for this invocation. Authentication and session state stay in the
// operator's normal CLI home; they are never copied into the workspace, stored
diff --git a/internal/runtime/sandbox_script_docker.go b/internal/runtime/sandbox_script_docker.go
deleted file mode 100644
index 196c3fc5..00000000
--- a/internal/runtime/sandbox_script_docker.go
+++ /dev/null
@@ -1,250 +0,0 @@
-package runtime
-
-import (
- "context"
- "crypto/sha256"
- "encoding/hex"
- "encoding/json"
- "fmt"
- "os"
- "os/exec"
- "path/filepath"
- "strings"
-
- "agentflow/internal/scriptview"
-)
-
-const scriptViewLabel = "agentflow.script-view-owner"
-const scriptViewBinary = "/.agentflow-script-view"
-
-func dockerScriptContainerName(name string) string { return name + "-scripts" }
-
-// Scripts use a private copy of the existing mount namespace, rather than a
-// fresh image: apt installs, PHP extensions and running services remain shared.
-// This companion stays alive for the run so services started by scripts survive
-// an individual exec. Its bootstrap capabilities are dropped before every script.
-func (s *dockerSandbox) ensureScriptContainer(ctx context.Context) error {
- s.mu.Lock()
- defer s.mu.Unlock()
- var base struct {
- ID string `json:"Id"`
- Image string
- State struct {
- Running bool
- StartedAt string
- }
- }
- raw, err := exec.CommandContext(ctx, "docker", "inspect", "--format", "{{json .}}", s.name).CombinedOutput()
- if err != nil {
- if dockerObjectGone(string(raw), err) {
- s.started = false
- return fmt.Errorf("Error response from daemon: no such container: %s", s.name)
- }
- return fmt.Errorf("inspect script environment: %w", err)
- }
- if err = json.Unmarshal(raw, &base); err != nil {
- return err
- }
- if !base.State.Running {
- s.started = false
- return fmt.Errorf("Error response from daemon: workspace container %s is not running", s.name)
- }
- if base.ID == "" || base.Image == "" {
- return fmt.Errorf("script execution environment metadata is incomplete")
- }
- arch, err := exec.CommandContext(ctx, "docker", "image", "inspect", "--format", "{{.Architecture}}", base.Image).Output()
- if err != nil {
- return fmt.Errorf("inspect script environment architecture: %w", err)
- }
- binary, err := resolveGateMCPBinary("linux", strings.TrimSpace(string(arch)))
- if err != nil {
- return fmt.Errorf("script view helper unavailable: %w", err)
- }
- contents, err := os.ReadFile(binary)
- if err != nil {
- return err
- }
- sum := sha256.Sum256(contents)
- owner := base.ID + "|" + base.State.StartedAt + "|" + scriptview.Version + "|" + hex.EncodeToString(sum[:])
- name := dockerScriptContainerName(s.name)
- existing, probeErr := exec.CommandContext(ctx, "docker", "inspect", "--format", `{{.State.Running}}|{{index .Config.Labels "`+scriptViewLabel+`"}}`, name).CombinedOutput()
- if probeErr == nil && strings.TrimSpace(string(existing)) == "true|"+owner {
- return nil
- }
- if probeErr != nil && !dockerObjectGone(string(existing), probeErr) {
- return fmt.Errorf("inspect script view: %w", probeErr)
- }
- // A stopped helper lost any services in its cgroup. Recreate it so its ID and
- // start time invalidate old preparation receipts instead of claiming readiness.
- if probeErr == nil {
- if out, err := exec.CommandContext(ctx, "docker", "rm", "-f", name).CombinedOutput(); err != nil {
- return fmt.Errorf("remove stale script view: %w: %s", err, strings.TrimSpace(string(out)))
- }
- }
- args := dockerScriptCreateArgs(name, s.name, s.workspace, base.Image, owner)
- if out, err := exec.CommandContext(ctx, "docker", args...).CombinedOutput(); err != nil {
- return fmt.Errorf("create script view: %w: %s", err, strings.TrimSpace(string(out)))
- }
- ready := false
- defer func() {
- if !ready {
- _ = exec.Command("docker", "rm", "-f", name).Run()
- }
- }()
- if out, err := exec.CommandContext(ctx, "docker", "cp", binary, name+":"+scriptViewBinary).CombinedOutput(); err != nil {
- return fmt.Errorf("install script view helper: %w: %s", err, strings.TrimSpace(string(out)))
- }
- if out, err := exec.CommandContext(ctx, "docker", "start", name).CombinedOutput(); err != nil {
- return fmt.Errorf("start script view: %w: %s", err, strings.TrimSpace(string(out)))
- }
- probe, err := exec.CommandContext(ctx, "docker", "exec", name, scriptViewBinary, scriptview.ProbeArgument).CombinedOutput()
- if err != nil || strings.TrimSpace(string(probe)) != scriptview.Version {
- return fmt.Errorf("script view helper version is incompatible; deploy the matching platform helper")
- }
- ready = true
- return nil
-}
-
-func dockerScriptCreateArgs(name, base, workspace, image, owner string) []string {
- args := []string{"create", "--name", name, "--user", "0:0", "--pid=container:" + base, "--network=container:" + base,
- "--cap-drop=ALL", "--security-opt", "no-new-privileges", "--security-opt", "seccomp=unconfined", "--security-opt", "apparmor=unconfined",
- "--label", scriptViewLabel + "=" + owner,
- // This bind also lets the existing workspace sweeper find orphan helpers.
- "-v", workspace + ":/workspace"}
- for _, capability := range []string{"SYS_ADMIN", "SYS_CHROOT", "SYS_PTRACE", "SETPCAP", "SETUID", "SETGID", "DAC_OVERRIDE"} {
- args = append(args, "--cap-add="+capability)
- }
- return append(args, "--entrypoint", "sh", image, "-c", "trap : TERM INT; sleep infinity & wait")
-}
-
-func (s *dockerSandbox) execScript(ctx context.Context, command CommandSpec, sink EventSink) (string, error) {
- if err := s.ensureScriptContainer(ctx); err != nil {
- return "", err
- }
- masks, err := s.scriptMasks(ctx)
- if err != nil {
- return "", err
- }
- view := scriptview.Config{Masks: masks, Aliases: s.conversationAliases(), Argv: dockerWorkspaceExecArgv(command.Argv)}
- config, err := json.Marshal(view)
- if err != nil {
- return "", err
- }
- args := []string{"exec"}
- for _, environment := range appendEnvironment(nil, s.profile.Environment, command.environment) {
- args = append(args, "-e", environment)
- }
- args = append(args, dockerScriptContainerName(s.name), scriptViewBinary, "--workspace-script-view", string(config))
- return runCommand(exec.CommandContext(ctx, "docker", args...), sink)
-}
-
-func (s *dockerSandbox) scriptMasks(ctx context.Context) ([]string, error) {
- // Keep actual mounts, including legacy masks attached to replaced directories,
- // and combine them below with refreshed masks discovered in current files.
- raw, err := exec.CommandContext(ctx, "docker", "inspect", "--format", "{{json .Mounts}}", s.name).Output()
- if err != nil {
- return nil, fmt.Errorf("inspect script view masks: %w", err)
- }
- var mounts []struct {
- Source, Destination string
- RW bool
- }
- if err = json.Unmarshal(raw, &mounts); err != nil {
- return nil, err
- }
- dir, file, err := isolationMaskSourcesAt(dockerIsolationMaskRoot(s.workspace))
- if err != nil {
- return nil, err
- }
- var masks []string
- for _, m := range mounts {
- if m.RW || (m.Source != dir && m.Source != file) {
- continue
- }
- if scriptview.ValidMask(m.Destination, s.conversationAliases()...) {
- masks = append(masks, m.Destination)
- }
- }
- current, err := s.currentAgentMasks()
- if err != nil {
- return nil, err
- }
- seen := map[string]bool{}
- for _, target := range masks {
- seen[target] = true
- }
- for _, target := range current {
- if !seen[target] {
- masks = append(masks, target)
- seen[target] = true
- }
- }
- return masks, nil
-}
-
-// Preserve ordinary process isolation but omit instruction-file masks for
-// platform-defined scripts. Agent invocations keep their original masks.
-func trustedScriptCommand(command CommandSpec) bool { return command.Provider == "script" }
-
-// Agents receive refreshed masks: a dependency update can replace
-// the directory that a canonical container's old bind mount was attached to.
-// Rediscover masks for every invocation so replacement instruction files cannot
-// become visible after a script legitimately removes/reinstalls a package.
-func maskedAgentCommand(command CommandSpec) bool {
- switch command.Provider {
- case "codebuddy", "codex", "claude-code":
- return true
- }
- return false
-}
-
-func (s *dockerSandbox) currentAgentMasks() ([]string, error) {
- paths, err := discoverProjectAgentPaths(s.workspace)
- if err != nil {
- return nil, err
- }
- var hide []string
- for _, rel := range paths {
- _, err := validateAgentConfigTarget(s.workspace, rel)
- if os.IsNotExist(err) {
- continue
- }
- if err != nil {
- return nil, err
- }
- hide = append(hide, filepath.ToSlash(filepath.Join("/workspace", rel)))
- if root := s.requirements.ConversationRoot; root != "" {
- hide = append(hide, filepath.ToSlash(filepath.Join(root, "ws", rel)))
- }
- }
- return hide, nil
-}
-
-// Add fresh readonly masks before launching an Agent in the canonical container.
-// Only this trusted setup runs in the helper; the Agent retains the canonical
-// Docker seccomp/AppArmor policy as well as its capability restrictions.
-func (s *dockerSandbox) refreshAgentMasks(ctx context.Context) error {
- if err := s.ensureScriptContainer(ctx); err != nil {
- return err
- }
- hide, err := s.currentAgentMasks()
- if err != nil {
- return err
- }
- config, err := json.Marshal(scriptview.Config{Refresh: true, Hide: hide, Aliases: s.conversationAliases()})
- if err != nil {
- return err
- }
- out, err := exec.CommandContext(ctx, "docker", "exec", dockerScriptContainerName(s.name), scriptViewBinary, scriptview.Argument, string(config)).CombinedOutput()
- if err != nil {
- return fmt.Errorf("refresh agent instruction isolation: %w: %s", err, strings.TrimSpace(string(out)))
- }
- return nil
-}
-
-func (s *dockerSandbox) conversationAliases() []string {
- if s.requirements.ConversationRoot == "" {
- return nil
- }
- return []string{filepath.ToSlash(filepath.Join(s.requirements.ConversationRoot, "ws"))}
-}
diff --git a/internal/runtime/sandbox_script_test.go b/internal/runtime/sandbox_script_test.go
index b00e70ad..2936f68f 100644
--- a/internal/runtime/sandbox_script_test.go
+++ b/internal/runtime/sandbox_script_test.go
@@ -13,9 +13,9 @@ import (
"agentflow/internal/domain"
)
-func TestScriptViewsPreserveProcessSandboxBoundaries(t *testing.T) {
+func TestProcessSandboxUsesSamePolicyForScriptsAndAgents(t *testing.T) {
root := t.TempDir()
- if err := os.WriteFile(filepath.Join(root, "CLAUDE.md"), []byte("repo instructions"), 0600); err != nil {
+ if err := os.WriteFile(filepath.Join(root, "CLAUDE.md"), []byte("repo instructions"), 0o600); err != nil {
t.Fatal(err)
}
for _, driver := range []string{"bwrap", "seatbelt"} {
@@ -26,203 +26,231 @@ func TestScriptViewsPreserveProcessSandboxBoundaries(t *testing.T) {
t.Fatal(err)
}
text := strings.Join(cmd.Args, " ")
- masked := strings.Contains(text, filepath.Join(root, "CLAUDE.md"))
- if masked != (provider != "script") {
- t.Fatalf("%s/%s mask=%v: %s", driver, provider, masked, text)
+ if strings.Contains(text, filepath.Join(root, "CLAUDE.md")) {
+ t.Fatalf("%s/%s masks repository instructions: %s", driver, provider, text)
}
if driver == "bwrap" && !strings.Contains(text, "--ro-bind / /") {
- t.Fatal("script lost host filesystem boundary")
+ t.Fatal("command lost host filesystem boundary")
}
if driver == "seatbelt" && !strings.Contains(text, "(deny file-write*)") {
- t.Fatal("script lost host write boundary")
+ t.Fatal("command lost host write boundary")
}
}
}
- args := strings.Join(dockerScriptCreateArgs("helper", "canonical", "/work", "image", "generation"), " ")
- for _, part := range []string{"--cap-drop=ALL", "no-new-privileges", "--pid=container:canonical", "--network=container:canonical"} {
- if !strings.Contains(args, part) {
- t.Fatal(args)
- }
- }
- if strings.Contains(args, "--privileged") {
- t.Fatal("helper must not be a privileged container")
- }
}
-func TestDockerScriptViewDependencyRemoval(t *testing.T) {
+func dockerScriptTestSandbox(t *testing.T) (context.Context, *dockerSandbox) {
+ t.Helper()
if os.Getenv("AGENTFLOW_DOCKER_SCRIPT_SMOKE") != "1" {
t.Skip("set AGENTFLOW_DOCKER_SCRIPT_SMOKE=1 for local Docker regression")
}
- ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
- defer cancel()
- image := "alpine:3.20"
- if out, err := exec.CommandContext(ctx, "docker", "image", "inspect", image).CombinedOutput(); err != nil {
- t.Fatalf("local fixture image: %s %v", out, err)
- }
+ ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
+ t.Cleanup(cancel)
root := os.Getenv("AGENTFLOW_DOCKER_TEST_ROOT")
if root == "" {
root = "."
}
- workspace, err := os.MkdirTemp(root, ".script-view-test-")
+ workspace, err := os.MkdirTemp(root, ".docker-script-test-")
if err != nil {
t.Fatal(err)
}
+ t.Cleanup(func() { _ = os.RemoveAll(workspace) })
workspace, err = filepath.Abs(workspace)
if err != nil {
t.Fatal(err)
}
- defer os.RemoveAll(workspace)
- path := filepath.Join(workspace, "vendor", "test-package")
- if err = os.MkdirAll(path, 0755); err != nil {
- t.Fatal(err)
+ t.Setenv("AGENTFLOW_ISOLATED_IMAGE", "alpine:3.20")
+ t.Setenv("AGENTFLOW_DOCKER_NETWORK", "none")
+ name := fmt.Sprintf("agentflow-script-qa-%d", time.Now().UnixNano())
+ sb := &dockerSandbox{id: name, name: name, workspace: workspace,
+ profile: domain.SandboxProfile{Driver: "docker"},
+ dockerfile: domain.DockerfileDefinition{Content: IsolatedDockerfile},
}
- if err = os.WriteFile(filepath.Join(path, "CLAUDE.md"), []byte("dependency instructions"), 0644); err != nil {
+ t.Cleanup(func() { _ = sb.Close(context.Background()) })
+ return ctx, sb
+}
+
+func dockerScriptTestConversationRoot(t *testing.T, sb *dockerSandbox) string {
+ t.Helper()
+ root, err := os.MkdirTemp(filepath.Dir(sb.workspace), ".docker-conversation-test-")
+ if err != nil {
t.Fatal(err)
}
- name := fmt.Sprintf("agentflow-script-view-qa-%d", time.Now().UnixNano())
- masks, err := dockerAgentConfigMasks(workspace)
- if err != nil {
+ t.Cleanup(func() { _ = os.RemoveAll(root) })
+ t.Setenv("AGENTFLOW_CONVERSATION_RELAY_HOST", "host.docker.internal")
+ t.Setenv("AGENTFLOW_CONVERSATION_DOCKER_NETWORK", "none")
+ return root
+}
+
+func TestDockerWorkspaceScriptsAndAgentsShareEnvironment(t *testing.T) {
+ ctx, sb := dockerScriptTestSandbox(t)
+ path := filepath.Join(sb.workspace, "repo", "dependency")
+ if err := os.MkdirAll(path, 0o755); err != nil {
t.Fatal(err)
}
- args := []string{"run", "--pull=never", "-d", "--name", name, "--cap-drop=ALL", "--security-opt", "no-new-privileges", "-v", workspace + ":/workspace"}
- args = append(args, masks...)
- args = append(args, image, "sh", "-c", "sleep 300")
- if out, err := exec.CommandContext(ctx, "docker", args...).CombinedOutput(); err != nil {
- t.Fatalf("fixture: %s %v", out, err)
+ if err := os.WriteFile(filepath.Join(path, "AGENTS.md"), []byte("repository instructions"), 0o644); err != nil {
+ t.Fatal(err)
}
- sb := &dockerSandbox{id: name, name: name, workspace: workspace, started: true, profile: domain.SandboxProfile{Driver: "docker"}}
- defer sb.Close(context.Background())
- defer os.RemoveAll(dockerIsolationMaskRoot(workspace))
- // A live runtime install and a service, absent from the image, must survive.
- if out, err := sb.Exec(ctx, CommandSpec{Argv: []string{"sh", "-c", "printf installed > /usr/local/runtime-installed; printf '%s' secret > /tmp/runtime-marker"}}, nil); err != nil {
- t.Fatalf("runtime marker: %s %v", out, err)
+ // A conversation without preparation scripts can start using just the main container.
+ t.Setenv("AGENTFLOW_GATE_MCP_BINARY", filepath.Join(sb.workspace, "absent-gate-helper"))
+ conversationRoot := dockerScriptTestConversationRoot(t, sb)
+ if err := ConfigureConversationSandbox(ctx, sb, conversationRoot); err != nil {
+ t.Fatal(err)
}
- fail, err := sb.Exec(ctx, CommandSpec{Provider: "claude-code", Argv: []string{"sh", "-c", "test ! -s vendor/test-package/CLAUDE.md && rm -rf vendor/test-package"}}, nil)
- if err == nil {
- t.Fatalf("fixture did not reproduce protected mount: %s", fail)
+ wf := domain.WorkflowDefinition{}
+ if state, err := EnsureWorkspacePreparation(ctx, sb, wf, nil, nil); err != nil || state.Status != "ready" {
+ t.Fatalf("prepare conversation workspace: %+v %v", state, err)
}
- hostname, err := sb.Exec(ctx, CommandSpec{Argv: []string{"hostname"}}, nil)
+ identity, err := ReadSandboxEnvironmentIdentity(ctx, sb)
if err != nil {
t.Fatal(err)
}
- script := `test "$(cat /usr/local/runtime-installed)" = installed
- test "$(cat /tmp/runtime-marker)" = secret
- test "$(cat vendor/test-package/CLAUDE.md)" = 'dependency instructions'
- rm -rf vendor/test-package
- mkdir -p vendor/test-package
- printf replacement > vendor/test-package/CLAUDE.md
- printf script-installed > /usr/local/script-installed
- for field in CapEff CapPrm CapInh CapBnd CapAmb; do grep -q "^$field:[[:space:]]*0000000000000000$" /proc/self/status; done
- grep -q '^NoNewPrivs:[[:space:]]*1$' /proc/self/status
- sleep 120 >/dev/null 2>&1 &
- echo $! > /workspace/script-service-pid
- `
- script = "test \"$(hostname)\" = " + shellSingleQuote(strings.TrimSpace(hostname)) + "\n" + script
+ read := CommandSpec{Provider: "cursor", WorkingDir: filepath.Join(conversationRoot, "ws"),
+ Argv: []string{"cat", "repo/dependency/AGENTS.md"},
+ }
+ if out, err := sb.Exec(ctx, read, nil); err != nil || strings.TrimSpace(out) != "repository instructions" {
+ t.Fatalf("workspace CLI reads repository instruction: %q %v", out, err)
+ }
+ guard := filepath.Join(conversationRoot, "home", ".cursor", "hooks.json")
+ if out, err := sb.Exec(ctx, CommandSpec{Provider: "cursor", Argv: []string{"sh", "-ec",
+ `test "$(cat "$1")" = '{}' && ! (printf changed > "$1") 2>/dev/null`, "guard", guard}}, nil); err != nil {
+ t.Fatalf("conversation approval configuration is writable: %q %v", out, err)
+ }
+
+ script := `test "$(cat repo/dependency/AGENTS.md)" = 'repository instructions'
+rm -r repo/dependency
+mkdir repo/dependency
+printf replacement > repo/dependency/AGENTS.md
+printf prepared > /usr/local/script-marker
+sleep 120 </dev/null >/dev/null 2>&1 &
+echo $! > script-service-pid`
if out, err := sb.Exec(ctx, CommandSpec{Provider: "script", Argv: []string{"sh", "-ec", script}}, nil); err != nil {
- t.Fatalf("unmasked script: %s %v", out, err)
+ t.Fatalf("workspace script: %q %v", out, err)
+ }
+ check := `test "$(cat repo/dependency/AGENTS.md)" = replacement
+test "$(cat /usr/local/script-marker)" = prepared
+kill -0 "$(cat script-service-pid)"
+grep -q '^CapEff:[[:space:]]*0000000000000000$' /proc/self/status
+grep -q '^NoNewPrivs:[[:space:]]*1$' /proc/self/status
+grep -q '^Seccomp:[[:space:]]*2$' /proc/self/status`
+ if out, err := sb.Exec(ctx, CommandSpec{Provider: "codex", Argv: []string{"sh", "-ec", check}}, nil); err != nil {
+ t.Fatalf("script state unavailable to agent: %q %v", out, err)
}
- if data, err := os.ReadFile(filepath.Join(path, "CLAUDE.md")); err != nil || string(data) != "replacement" {
- t.Fatal(string(data), err)
+ if after, err := ReadSandboxEnvironmentIdentity(ctx, sb); err != nil || after != identity {
+ t.Fatalf("script changed the environment identity: %q %v", after, err)
}
- // The script namespace is discarded; refresh masks before the next Agent so
- // replaced dependency directories cannot expose new instructions.
- if out, err := sb.Exec(ctx, CommandSpec{Provider: "claude-code", Argv: []string{"sh", "-ec", `test ! -s vendor/test-package/CLAUDE.md || { echo mask-lost; cat vendor/test-package/CLAUDE.md; exit 1; }; test "$(cat /usr/local/script-installed)" = script-installed || { echo install-lost; exit 1; }; kill -0 "$(cat script-service-pid)" || { echo service-lost; cat script-service-pid; exit 1; }; grep -q '^Seccomp:[[:space:]]*2$' /proc/self/status`}}, nil); err != nil {
- t.Fatalf("agent isolation/runtime: %s %v", out, err)
+ if out, err := exec.CommandContext(ctx, "docker", "inspect", sb.name+legacyDockerScriptSuffix).CombinedOutput(); !dockerObjectGone(string(out), err) {
+ t.Fatalf("script companion exists: %s %v", out, err)
}
- before, err := SandboxEnvironmentIdentity(ctx, sb)
+}
+
+func TestDockerWorkspaceRecreatesLegacyMaskedContainer(t *testing.T) {
+ ctx, sb := dockerScriptTestSandbox(t)
+ workspace := sb.workspace
+ mask, err := EnsureControlDirectory(workspace, "isolation")
if err != nil {
t.Fatal(err)
}
- if out, err := sb.Exec(ctx, CommandSpec{Provider: "script", Argv: []string{"sh", "-ec", `test "$(cat vendor/test-package/CLAUDE.md)" = replacement; kill -0 "$(cat script-service-pid)"`}}, nil); err != nil {
- t.Fatalf("second script: %s %v", out, err)
- }
- after, err := SandboxEnvironmentIdentity(ctx, sb)
- if err != nil || before != after {
- t.Fatal("warm environment identity changed", before, after, err)
- }
- if out, err := exec.CommandContext(ctx, "docker", "rm", "-f", dockerScriptContainerName(name)).CombinedOutput(); err != nil {
- t.Fatalf("recreate helper: %s %v", out, err)
+ emptyFile := filepath.Join(mask, "empty-file")
+ if err := os.WriteFile(emptyFile, nil, 0o644); err != nil {
+ t.Fatal(err)
}
- next, err := SandboxEnvironmentIdentity(ctx, sb)
- if err != nil || next == after {
- t.Fatal("helper loss did not invalidate preparation", next, err)
+ instructions := filepath.Join(workspace, "AGENTS.md")
+ if err := os.WriteFile(instructions, []byte("keep existing instructions"), 0o644); err != nil {
+ t.Fatal(err)
}
- // A stopped canonical container must invalidate the cached handle so retry
- // can restart it, rather than failing permanently on the old started flag.
- if out, err := exec.CommandContext(ctx, "docker", "stop", "-t", "1", name).CombinedOutput(); err != nil {
- t.Fatalf("stop canonical: %s %v", out, err)
+ if err := os.WriteFile(filepath.Join(workspace, "prepared-count"), []byte("once\n"), 0o644); err != nil {
+ t.Fatal(err)
}
- if _, err := sb.Exec(ctx, CommandSpec{Provider: "script", Argv: []string{"sh", "-c", "true"}}, nil); !IsSandboxInterrupt(err) {
- t.Fatalf("stopped container was not retryable: %v", err)
+ bind := []string{"run", "--pull=never", "--network", "none", "-d", "-v", workspace + ":/workspace"}
+ legacy := append(append([]string{}, bind...), "--name", sb.name,
+ "-v", emptyFile+":/workspace/.agentflow/isolation/empty-file:ro", "-v", emptyFile+":/workspace/AGENTS.md:ro",
+ "alpine:3.20", "sleep", "120")
+ companion := append(append([]string{}, bind...), "--name", sb.name+legacyDockerScriptSuffix, "alpine:3.20", "sleep", "120")
+ for _, args := range [][]string{legacy, companion} {
+ if out, err := exec.CommandContext(ctx, "docker", args...).CombinedOutput(); err != nil {
+ t.Fatalf("legacy fixture: %s %v", out, err)
+ }
}
- if out, err := sb.Exec(ctx, CommandSpec{Provider: "script", Argv: []string{"sh", "-c", "true"}}, nil); err != nil {
- t.Fatalf("restart canonical: %s %v", out, err)
+ oldIdentity, err := ReadSandboxEnvironmentIdentity(ctx, sb)
+ if err != nil {
+ t.Fatal(err)
}
- // Old gate helpers accept unknown argv as MCP mode and may exit zero without
- // executing anything. The version handshake must reject that silent no-op.
- stale := filepath.Join(workspace, "old-helper")
- if err := os.WriteFile(stale, []byte("#!/bin/sh\nexit 0\n"), 0755); err != nil {
+ wf := domain.WorkflowDefinition{Nodes: []domain.WorkflowNode{{
+ ID: "prepare", Name: "Prepare", Type: "script", RunOnWorkspaceRebuild: true,
+ Script: "printf 'again\\n' >> prepared-count; printf ready > /tmp/prepared",
+ }}}
+ if _, err := RecordWorkspacePreparation(ctx, sb, wf, nil, "prepare", ""); err != nil {
t.Fatal(err)
}
- t.Setenv("AGENTFLOW_GATE_MCP_BINARY", stale)
- if _, err := sb.Exec(ctx, CommandSpec{Provider: "script", Argv: []string{"sh", "-c", "touch never-executed"}}, nil); err == nil || !strings.Contains(err.Error(), "version is incompatible") {
- t.Fatalf("stale helper accepted: %v", err)
+ t.Setenv("AGENTFLOW_ISOLATED_IMAGE", sb.name+"-missing-image:local")
+ if _, err := EnsureWorkspacePreparation(ctx, sb, wf, nil, nil); err == nil {
+ t.Fatal("legacy upgrade unexpectedly succeeded without a replacement image")
}
- if _, err := os.Stat(filepath.Join(workspace, "never-executed")); !os.IsNotExist(err) {
- t.Fatalf("rejected script still ran: %v", err)
+ if err := ConfigureConversationSandbox(ctx, sb, dockerScriptTestConversationRoot(t, sb)); err == nil || sb.requirements.ConversationRoot != "" {
+ t.Fatalf("failed conversation configuration was applied: %v", err)
}
- if err := sb.Close(ctx); err != nil {
- t.Fatal(err)
+ if identity, err := ReadSandboxEnvironmentIdentity(ctx, sb); err != nil || identity != oldIdentity {
+ t.Fatalf("failed upgrade discarded the old workspace: %s %v", identity, err)
}
- if out, err := exec.CommandContext(ctx, "docker", "inspect", dockerScriptContainerName(name)).CombinedOutput(); err == nil || !dockerObjectGone(string(out), err) {
- t.Fatalf("helper leaked: %s %v", out, err)
+ t.Setenv("AGENTFLOW_ISOLATED_IMAGE", "alpine:3.20")
+ for range 2 {
+ state, err := EnsureWorkspacePreparation(ctx, sb, wf, nil, nil)
+ if err != nil || state.Status != "ready" || state.Environment == oldIdentity {
+ t.Fatalf("legacy workspace was not rebuilt: %+v %v", state, err)
+ }
}
-
-}
-
-func TestDockerScriptViewPreservesNonRootUser(t *testing.T) {
- if os.Getenv("AGENTFLOW_DOCKER_SCRIPT_SMOKE") != "1" {
- t.Skip("set AGENTFLOW_DOCKER_SCRIPT_SMOKE=1 for local Docker regression")
+ if data, err := os.ReadFile(filepath.Join(workspace, "prepared-count")); err != nil || string(data) != "once\nagain\n" {
+ t.Fatalf("workspace preparation replayed incorrectly: %q %v", data, err)
}
- ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
- defer cancel()
- root := os.Getenv("AGENTFLOW_DOCKER_TEST_ROOT")
- if root == "" {
- root = "."
+ if out, err := sb.Exec(ctx, CommandSpec{Argv: []string{"sh", "-ec",
+ `test "$(cat AGENTS.md)" = 'keep existing instructions'; test "$(cat /tmp/prepared)" = ready`}}, nil); err != nil {
+ t.Fatalf("recreated workspace lost files or prep: %s %v", out, err)
}
- workspace, err := os.MkdirTemp(root, ".script-user-test-")
- if err != nil {
- t.Fatal(err)
+ if out, err := exec.CommandContext(ctx, "docker", "inspect", sb.name+legacyDockerScriptSuffix).CombinedOutput(); !dockerObjectGone(string(out), err) {
+ t.Fatalf("legacy companion not reclaimed: %s %v", out, err)
}
- workspace, err = filepath.Abs(workspace)
+}
+
+func TestDockerWorkspaceRecoversExternallyStoppedOrRemovedContainer(t *testing.T) {
+ ctx, sb := dockerScriptTestSandbox(t)
+ identity, err := SandboxEnvironmentIdentity(ctx, sb)
if err != nil {
t.Fatal(err)
}
- defer os.RemoveAll(workspace)
- if err = os.Chmod(workspace, 0777); err != nil {
- t.Fatal(err)
- }
- if err = os.WriteFile(filepath.Join(workspace, "CLAUDE.md"), []byte("original"), 0644); err != nil {
- t.Fatal(err)
+ for _, remove := range [][]string{{"stop", "-t", "0", sb.name}, {"rm", "-f", sb.name}} {
+ if out, err := exec.CommandContext(ctx, "docker", remove...).CombinedOutput(); err != nil {
+ t.Fatalf("docker %s: %s %v", remove[0], out, err)
+ }
+ next, err := SandboxEnvironmentIdentity(ctx, sb)
+ if err != nil || next == identity {
+ t.Fatalf("after docker %s: identity %q (was %q) %v", remove[0], next, identity, err)
+ }
+ if out, err := sb.Exec(ctx, CommandSpec{Argv: []string{"true"}}, nil); err != nil {
+ t.Fatalf("after docker %s: exec %q %v", remove[0], out, err)
+ }
+ identity = next
}
- maskArgs, err := dockerAgentConfigMasks(workspace)
- if err != nil {
+}
+
+func TestDockerWorkspaceScriptPreservesNonRootUser(t *testing.T) {
+ ctx, sb := dockerScriptTestSandbox(t)
+ if err := os.Chmod(sb.workspace, 0o777); err != nil {
t.Fatal(err)
}
- defer os.RemoveAll(dockerIsolationMaskRoot(workspace))
- name := fmt.Sprintf("agentflow-script-user-qa-%d", time.Now().UnixNano())
- args := []string{"run", "--pull=never", "-d", "--name", name, "--user", "65534:65534", "--cap-drop=ALL", "--security-opt", "no-new-privileges", "-v", workspace + ":/workspace"}
- args = append(args, maskArgs...)
- args = append(args, "alpine:3.20", "sh", "-c", "sleep 120")
+ args := []string{"run", "--pull=never", "--network", "none", "-d", "--name", sb.name,
+ "--user", "65534:65534", "--cap-drop=ALL", "--security-opt", "no-new-privileges",
+ "-v", sb.workspace + ":/workspace", "alpine:3.20", "sleep", "120"}
if out, err := exec.CommandContext(ctx, "docker", args...).CombinedOutput(); err != nil {
- t.Fatalf("nonroot fixture: %s %v", out, err)
+ t.Fatalf("non-root fixture: %s %v", out, err)
}
- sb := &dockerSandbox{id: name, name: name, workspace: workspace, started: true}
- defer sb.Close(context.Background())
- if out, err := sb.Exec(ctx, CommandSpec{Provider: "script", Argv: []string{"sh", "-ec", `test "$(id -u)" = 65534; test "$(id -g)" = 65534; test "$(cat CLAUDE.md)" = original; printf done > user-output; grep -q '^CapBnd:[[:space:]]*0000000000000000$' /proc/self/status`}}, nil); err != nil {
- t.Fatalf("nonroot script: %s %v", out, err)
+ script := `test "$(id -u):$(id -g)" = 65534:65534
+printf done > user-output
+grep -q '^CapBnd:[[:space:]]*0000000000000000$' /proc/self/status`
+ if out, err := sb.Exec(ctx, CommandSpec{Provider: "script", Argv: []string{"sh", "-ec", script}}, nil); err != nil {
+ t.Fatalf("non-root script: %s %v", out, err)
}
- if data, err := os.ReadFile(filepath.Join(workspace, "user-output")); err != nil || string(data) != "done" {
- t.Fatal(string(data), err)
+ if data, err := os.ReadFile(filepath.Join(sb.workspace, "user-output")); err != nil || string(data) != "done" {
+ t.Fatalf("non-root script output: %q %v", data, err)
}
}
diff --git a/internal/runtime/workspace_preparation.go b/internal/runtime/workspace_preparation.go
index eedbddae..1f2b2501 100644
--- a/internal/runtime/workspace_preparation.go
+++ b/internal/runtime/workspace_preparation.go
@@ -291,6 +291,9 @@ func EnsureWorkspacePreparation(ctx context.Context, sb Sandbox, wf domain.Workf
if err != nil {
return WorkspacePreparationStatus{Status: "failed", Error: err.Error(), Steps: []WorkspacePreparationStep{}}, err
}
+ if err := RestoreLegacyWorkspaceAgentConfig(ctx, sb.Workspace(), repositories); err != nil {
+ return WorkspacePreparationStatus{Status: "failed", Error: err.Error(), Steps: []WorkspacePreparationStep{}}, err
+ }
old := ReadWorkspacePreparationStatus(sb.Workspace(), sb.ID())
prior := map[string]WorkspacePreparationStep{}
if old.Environment == epoch {
diff --git a/internal/runtime/workspace_terminal_sandbox.go b/internal/runtime/workspace_terminal_sandbox.go
index 54970a26..c6645b50 100644
--- a/internal/runtime/workspace_terminal_sandbox.go
+++ b/internal/runtime/workspace_terminal_sandbox.go
@@ -159,7 +159,16 @@ func SandboxEnvironmentIdentity(ctx context.Context, sandbox Sandbox) (string, e
if err := s.ensureStarted(ctx); err != nil {
return "", err
}
- if err := s.ensureScriptContainer(ctx); err != nil {
+ identity, err := ReadSandboxEnvironmentIdentity(ctx, s)
+ if err == nil || ctx.Err() != nil {
+ return identity, err
+ }
+ // The started flag is a process-local cache. A container stopped or
+ // removed outside this process (daemon restart, prune, manual cleanup)
+ // must be revalidated here, or every later preparation keeps failing.
+ // Restarting or recreating changes the identity, so preparation replays.
+ s.invalidate()
+ if err := s.ensureStarted(ctx); err != nil {
return "", err
}
}
@@ -181,13 +190,6 @@ func ReadSandboxEnvironmentIdentity(ctx context.Context, sandbox Sandbox) (strin
if !strings.HasPrefix(strings.TrimSpace(string(output)), "true|") {
return "", fmt.Errorf("workspace execution environment is not running")
}
- companion, companionErr := exec.CommandContext(ctx, "docker", "inspect", "--format", "{{.State.Running}}|{{.Id}}|{{.State.StartedAt}}", dockerScriptContainerName(s.name)).CombinedOutput()
- if companionErr != nil && !dockerObjectGone(string(companion), companionErr) {
- return "", fmt.Errorf("inspect script environment: %w", companionErr)
- }
- if companionErr == nil {
- output = append(output, companion...)
- }
overlay, err := json.Marshal(s.profile.Environment)
if err != nil {
return "", err
diff --git a/internal/runtime/workspace_terminal_sandbox_test.go b/internal/runtime/workspace_terminal_sandbox_test.go
index 24027a82..3d3b5398 100644
--- a/internal/runtime/workspace_terminal_sandbox_test.go
+++ b/internal/runtime/workspace_terminal_sandbox_test.go
@@ -187,14 +187,12 @@ func TestWorkspaceTerminalDockerRealPTY(t *testing.T) {
t.Fatal(workspaceErr)
}
defer os.RemoveAll(workspace)
- defer os.RemoveAll(dockerIsolationMaskRoot(workspace))
name := fmt.Sprintf("agentflow-terminal-qa-%d", time.Now().UnixNano())
create := exec.CommandContext(ctx, "docker", "run", "--pull=never", "--rm", "-d", "--name", name, "-v", workspace+":/workspace", "alpine:3.20", "sh", "-c", "sleep 60")
if output, err := create.CombinedOutput(); err != nil {
t.Fatalf("create isolated container: %s %v", output, err)
}
defer exec.Command("docker", "rm", "-f", name).Run()
- defer exec.Command("docker", "rm", "-f", dockerScriptContainerName(name)).Run()
sb := &dockerSandbox{id: name, name: name, workspace: workspace, started: true}
if output, err := sb.Exec(ctx, CommandSpec{Argv: []string{"sh", "-c", "printf sandbox-only > /tmp/terminal-env-marker"}}, nil); err != nil {
t.Fatalf("SOP command: %s %v", output, err)
diff --git a/internal/scriptview/scriptview.go b/internal/scriptview/scriptview.go
deleted file mode 100644
index 952211e2..00000000
--- a/internal/scriptview/scriptview.go
+++ /dev/null
@@ -1,172 +0,0 @@
-// Package scriptview provides the trusted bootstrap for SOP scripts sharing a
-// live Docker sandbox. It is deliberately a separate mode of the existing
-// static gate helper so installed runners do not need another runtime artifact.
-//
-// Only the platform invokes this mode, inside its dedicated helper container.
-// Script execution clones the Agent container's mount namespace before removing
-// platform instruction masks, and drops all bootstrap privileges before exec.
-// A separate refresh mode may only add read-only masks to the canonical mount
-// namespace; Agents themselves remain in the original hardened container.
-package scriptview
-
-import (
- "encoding/json"
- "fmt"
- "io"
- "os"
- "path"
- "slices"
- "strings"
-)
-
-const (
- Argument = "--workspace-script-view"
- ProbeArgument = "--workspace-script-view-version"
- Version = "agentflow-script-view-v3"
-)
-
-type Config struct {
- Aliases []string `json:"aliases,omitempty"`
- Masks []string `json:"masks"`
- Hide []string `json:"hide,omitempty"`
- Argv []string `json:"argv"`
- Refresh bool `json:"refresh,omitempty"`
-}
-
-// Run handles only private script-view modes. On Linux script execution replaces
-// the process; refresh and version probes return. Callers must terminate the
-// helper after a handled result, without falling back to unisolated execution.
-func Run(args []string) (bool, error) {
- if len(args) > 0 && args[0] == ProbeArgument {
- if len(args) != 1 {
- return true, fmt.Errorf("workspace script view version probe accepts no arguments")
- }
- _, err := fmt.Fprintln(os.Stdout, Version)
- return true, err
- }
- if len(args) == 0 || args[0] != Argument {
- return false, nil
- }
- if len(args) != 2 {
- return true, fmt.Errorf("workspace script view requires one configuration argument")
- }
- config, err := parseConfig(args[1])
- if err != nil {
- return true, err
- }
- return true, execute(config)
-}
-
-func parseConfig(raw string) (Config, error) {
- var config Config
- decoder := json.NewDecoder(strings.NewReader(raw))
- decoder.DisallowUnknownFields()
- if err := decoder.Decode(&config); err != nil {
- return config, fmt.Errorf("decode workspace script view configuration: %w", err)
- }
- if err := decoder.Decode(new(any)); err != io.EOF {
- return config, fmt.Errorf("workspace script view configuration must contain one JSON object")
- }
- if err := validateConfigMode(config); err != nil {
- return config, err
- }
- for _, alias := range config.Aliases {
- if !strings.HasPrefix(alias, "/") || path.Clean(alias) != alias || !strings.HasSuffix(alias, "/ws") || strings.ContainsAny(alias, "\x00\n\r") {
- return config, fmt.Errorf("invalid workspace alias %q", alias)
- }
- }
- if err := validateAliasedMaskLists(config.Aliases, config.Masks, config.Hide); err != nil {
- return config, err
- }
- // Children must be detached before their parent when a legacy container has
- // both a directory mask and a file mask below it.
- slices.SortFunc(config.Masks, maskOrder(true))
- slices.SortFunc(config.Hide, maskOrder(false))
- return config, nil
-}
-
-// validateConfigMode enforces that refresh requests never execute commands or
-// detach masks, and that script executions never modify canonical masks.
-func validateConfigMode(config Config) error {
- if config.Refresh {
- if len(config.Argv) != 0 || len(config.Masks) != 0 {
- return fmt.Errorf("instruction mask refresh cannot execute commands or detach masks")
- }
- } else {
- if len(config.Hide) != 0 {
- return fmt.Errorf("workspace script commands cannot modify canonical instruction masks")
- }
- if len(config.Argv) == 0 || config.Argv[0] == "" {
- return fmt.Errorf("workspace script view command is empty")
- }
- }
- for _, argument := range config.Argv {
- if strings.IndexByte(argument, 0) >= 0 {
- return fmt.Errorf("workspace script view command contains a null byte")
- }
- }
- return nil
-}
-
-// validateMaskLists rejects invalid or duplicate entries within each list.
-func validateMaskLists(lists ...[]string) error {
- return validateAliasedMaskLists(nil, lists...)
-}
-
-// validateAliasedMaskLists is validateMaskLists for a view whose workspace is
-// also mounted at the given conversation aliases.
-func validateAliasedMaskLists(aliases []string, lists ...[]string) error {
- for _, list := range lists {
- seen := make(map[string]bool, len(list))
- for _, target := range list {
- if !ValidMask(target, aliases...) || seen[target] {
- return fmt.Errorf("invalid or duplicate workspace instruction mask %q", target)
- }
- seen[target] = true
- }
- }
- return nil
-}
-
-// maskOrder sorts mask paths by length (longest or shortest first), breaking
-// ties lexically so the order is deterministic.
-func maskOrder(longestFirst bool) func(a, b string) int {
- return func(a, b string) int {
- if len(a) != len(b) {
- if longestFirst {
- return len(b) - len(a)
- }
- return len(a) - len(b)
- }
- return strings.Compare(a, b)
- }
-}
-
-// ValidMask accepts only repository instruction paths that the platform masks.
-// Runtime state, the workspace root and arbitrary mounts are never eligible.
-func ValidMask(target string, aliases ...string) bool {
- base := maskBase(target, aliases)
- if base == "" || path.Clean(target) != target || strings.ContainsAny(target, "\x00\n\r") {
- return false
- }
- parts := strings.Split(strings.TrimPrefix(target, base+"/"), "/")
- for _, part := range parts[:len(parts)-1] {
- if part == ".agentflow" || part == ".git" {
- return false
- }
- }
- switch parts[len(parts)-1] {
- case "AGENTS.md", "AGENTS.override.md", "CLAUDE.md", "CLAUDE.local.md", "CODEBUDDY.md", ".mcp.json", ".agents", ".codex", ".claude", ".codebuddy":
- return true
- }
- return false
-}
-
-func maskBase(target string, aliases []string) string {
- for _, base := range append([]string{"/workspace"}, aliases...) {
- if strings.HasPrefix(target, base+"/") {
- return base
- }
- }
- return ""
-}
diff --git a/internal/scriptview/scriptview_cases_test.go b/internal/scriptview/scriptview_cases_test.go
deleted file mode 100644
index 096f552f..00000000
--- a/internal/scriptview/scriptview_cases_test.go
+++ /dev/null
@@ -1,162 +0,0 @@
-//go:build linux
-
-package scriptview
-
-import (
- "os"
- "path/filepath"
- "strings"
- "testing"
- "time"
-)
-
-func TestLinuxMaskHelpers(t *testing.T) {
- if err := removeMasks(nil); err != nil {
- t.Fatal(err)
- }
- if err := applyMasks(nil); err != nil {
- t.Fatal(err)
- }
- for _, name := range []string{".agents", ".codex", ".claude", ".codebuddy"} {
- if !instructionDirectory(name) {
- t.Fatal(name)
- }
- }
- if instructionDirectory(".github") {
- t.Fatal("unexpected instruction directory")
- }
- if got := decodeMountPath(`a\040b\011c\012d\134e`); got != "a b\tc\nd\\e" {
- t.Fatalf("decoded = %q", got)
- }
-}
-
-func TestExecuteRefreshFailsClosedOrCompletes(t *testing.T) {
- done := make(chan error, 1)
- go func() {
- done <- execute(Config{Refresh: true})
- }()
- select {
- case <-done:
- // Both outcomes are valid: restricted test containers reject namespace
- // entry, while privileged builders can refresh an empty mask list.
- case <-time.After(10 * time.Second):
- t.Fatal("script view namespace setup hung")
- }
-}
-
-// The helper runs as root inside sandboxes; these cases touch /workspace and
-// capabilities the same way, so an unprivileged test process cannot run them.
-func requireRoot(t *testing.T) {
- t.Helper()
- if os.Geteuid() != 0 {
- t.Skip("needs root")
- }
-}
-
-func TestApplyMaskValidationAndFilesystemBranches(t *testing.T) {
- requireRoot(t)
- const workspace = "/workspace"
- createdWorkspace := false
- if _, err := os.Stat(workspace); os.IsNotExist(err) {
- if err := os.Mkdir(workspace, 0o755); err != nil {
- t.Fatal(err)
- }
- createdWorkspace = true
- }
- rootDir := filepath.Join(workspace, "cvs-scriptview")
- _ = os.RemoveAll(rootDir)
- if err := os.MkdirAll(filepath.Join(workspace, ".agentflow", "isolation", "empty-dir"), 0o755); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(filepath.Join(workspace, ".agentflow", "isolation", "empty-file"), nil, 0o444); err != nil {
- t.Fatal(err)
- }
- if err := os.MkdirAll(rootDir, 0o755); err != nil {
- t.Fatal(err)
- }
- t.Cleanup(func() {
- _ = os.RemoveAll(rootDir)
- if createdWorkspace {
- _ = os.RemoveAll(workspace)
- }
- })
- root, err := os.OpenRoot(workspace)
- if err != nil {
- t.Fatal(err)
- }
- defer root.Close()
-
- if err := applyMask(root, filepath.Join(rootDir, "AGENTS.md")); err != nil {
- t.Fatalf("missing mask should be ignored: %v", err)
- }
- outside := filepath.Join(t.TempDir(), "AGENTS.md")
- if err := os.WriteFile(outside, nil, 0o600); err != nil {
- t.Fatal(err)
- }
- if err := os.Symlink(outside, filepath.Join(rootDir, "AGENTS.md")); err != nil {
- t.Fatal(err)
- }
- if err := applyMask(root, filepath.Join(rootDir, "AGENTS.md")); err == nil || !strings.Contains(err.Error(), "outside") {
- t.Fatalf("outside symlink error = %v", err)
- }
- if err := os.Remove(filepath.Join(rootDir, "AGENTS.md")); err != nil {
- t.Fatal(err)
- }
-
- realAgents := filepath.Join(workspace, "cvs-real", ".agents")
- if err := os.MkdirAll(realAgents, 0o755); err != nil {
- t.Fatal(err)
- }
- t.Cleanup(func() { _ = os.RemoveAll(filepath.Dir(realAgents)) })
- if err := os.Symlink(realAgents, filepath.Join(rootDir, ".agents")); err != nil {
- t.Fatal(err)
- }
- if err := applyMask(root, filepath.Join(rootDir, ".agents")); err == nil || !strings.Contains(err.Error(), "symlinked") {
- t.Fatalf("instruction symlink error = %v", err)
- }
-
- regular := filepath.Join(rootDir, "CLAUDE.md")
- if err := os.WriteFile(regular, []byte("x"), 0o600); err != nil {
- t.Fatal(err)
- }
- if err := applyMask(root, regular); err == nil || !strings.Contains(err.Error(), "not read-only") {
- t.Fatalf("writable source error = %v", err)
- }
-}
-
-func TestRemoveMasksRejectsWritableSources(t *testing.T) {
- requireRoot(t)
- rootDir := "/workspace/cvs-scriptview-remove"
- if err := os.MkdirAll(rootDir, 0o755); err != nil {
- t.Fatal(err)
- }
- t.Cleanup(func() { _ = os.RemoveAll(rootDir) })
- // Construct the writable source this case rejects independently of other
- // tests, which may remove their instruction fixtures during cleanup.
- source := "/workspace/.agentflow/isolation/empty-file"
- if err := os.MkdirAll(filepath.Dir(source), 0o755); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(source, nil, 0o600); err != nil {
- t.Fatal(err)
- }
- err := removeMasks([]string{filepath.Join(rootDir, "AGENTS.md")})
- if err == nil || !strings.Contains(err.Error(), "not read-only") {
- t.Fatalf("removeMasks error = %v", err)
- }
-}
-
-// This runs in the disposable go test process and intentionally leaves that
-// process capability-free. Keeping the current UID/GID avoids changing file
-// ownership while exercising the same final privilege drop as the helper.
-func TestZDropPrivilegesForDisposableTestProcess(t *testing.T) {
- requireRoot(t)
- groups, err := os.Getgroups()
- if err != nil {
- t.Fatal(err)
- }
- err = dropPrivileges(processIdentity{uid: os.Geteuid(), gid: os.Getegid(), groups: groups})
- if err != nil {
- t.Fatalf("drop privileges: %v", err)
- }
-}
diff --git a/internal/scriptview/scriptview_linux.go b/internal/scriptview/scriptview_linux.go
deleted file mode 100644
index 7786e170..00000000
--- a/internal/scriptview/scriptview_linux.go
+++ /dev/null
@@ -1,427 +0,0 @@
-//go:build linux
-
-package scriptview
-
-import (
- "bufio"
- "errors"
- "fmt"
- "os"
- "os/exec"
- "path/filepath"
- "runtime"
- "strconv"
- "strings"
-
- "golang.org/x/sys/unix"
-)
-
-type processIdentity struct {
- uid, gid int
- groups []int
-}
-
-func execute(config Config) error {
- identity, err := readProcessIdentity("/proc/1/status")
- if err != nil {
- return fmt.Errorf("read workspace container identity: %w", err)
- }
- root, err := unix.Open("/proc/1/root", unix.O_PATH|unix.O_DIRECTORY|unix.O_CLOEXEC, 0)
- if err != nil {
- return fmt.Errorf("open workspace container root: %w", err)
- }
- defer unix.Close(root)
- namespace, err := unix.Open("/proc/1/ns/mnt", unix.O_RDONLY|unix.O_CLOEXEC, 0)
- if err != nil {
- return fmt.Errorf("open workspace mount namespace: %w", err)
- }
- defer unix.Close(namespace)
- ipc, err := unix.Open("/proc/1/ns/ipc", unix.O_RDONLY|unix.O_CLOEXEC, 0)
- if err != nil {
- return fmt.Errorf("open workspace IPC namespace: %w", err)
- }
- defer unix.Close(ipc)
- uts, err := unix.Open("/proc/1/ns/uts", unix.O_RDONLY|unix.O_CLOEXEC, 0)
- if err != nil {
- return fmt.Errorf("open workspace hostname namespace: %w", err)
- }
- defer unix.Close(uts)
-
- // Namespace and credential changes apply only to this OS thread. Never
- // return it to the Go thread pool: on success exec replaces the process, and
- // on failure the command entry point terminates this dedicated helper.
- runtime.LockOSThread()
- // Go runtime threads initially share CLONE_FS. Linux refuses setns into
- // a mount namespace until this thread has its own root/cwd state.
- if err := unix.Unshare(unix.CLONE_FS); err != nil {
- return fmt.Errorf("isolate workspace script filesystem state: %w", err)
- }
- if err := unix.Setns(ipc, unix.CLONE_NEWIPC); err != nil {
- return fmt.Errorf("enter workspace IPC namespace: %w", err)
- }
- if err := unix.Setns(uts, unix.CLONE_NEWUTS); err != nil {
- return fmt.Errorf("enter workspace hostname namespace: %w", err)
- }
- if err := unix.Setns(namespace, unix.CLONE_NEWNS); err != nil {
- return fmt.Errorf("enter workspace mount namespace: %w", err)
- }
- if err := unix.Fchdir(root); err != nil {
- return fmt.Errorf("enter workspace container root: %w", err)
- }
- if err := unix.Chroot("."); err != nil {
- return fmt.Errorf("adopt workspace container root: %w", err)
- }
- if err := unix.Chdir("/"); err != nil {
- return fmt.Errorf("enter workspace container root: %w", err)
- }
- if err := validateAliases(config.Aliases); err != nil {
- return err
- }
- if config.Refresh {
- // This narrowly scoped operation may only ADD verified read-only masks
- // to the canonical namespace. It never detaches a mount or runs user
- // commands. Agents still execute in their original hardened container.
- return applyMasks(config.Hide, config.Aliases...)
- }
- // Adopt the target root before copying its mount namespace: unshare then
- // remaps root/cwd onto the copied mounts. Fchdir to the old root descriptor
- // after unshare would instead point back outside the copied namespace.
- if err := unix.Unshare(unix.CLONE_NEWNS); err != nil {
- return fmt.Errorf("clone workspace mount namespace: %w", err)
- }
- if err := unix.Mount("", "/", "", unix.MS_REC|unix.MS_PRIVATE, ""); err != nil {
- return fmt.Errorf("make workspace script mounts private: %w", err)
- }
- if err := unix.Chdir("/workspace"); err != nil {
- return fmt.Errorf("enter workspace script directory: %w", err)
- }
- if err := removeMasks(config.Masks, config.Aliases...); err != nil {
- return err
- }
- if err := dropPrivileges(identity); err != nil {
- return fmt.Errorf("drop workspace script bootstrap privileges: %w", err)
- }
- binary, err := exec.LookPath(config.Argv[0])
- if err != nil {
- return fmt.Errorf("locate workspace script command: %w", err)
- }
- if err := unix.Exec(binary, config.Argv, os.Environ()); err != nil {
- return fmt.Errorf("execute workspace script command: %w", err)
- }
- return nil
-}
-
-func removeMasks(targets []string, aliases ...string) error {
- if len(targets) == 0 {
- return nil
- }
- root, err := os.OpenRoot("/workspace")
- if err != nil {
- return fmt.Errorf("open script instruction mask root: %w", err)
- }
- defer root.Close()
- sources := make([]unix.Stat_t, 0, 2)
- for _, name := range []string{".agentflow/isolation/empty-file", ".agentflow/isolation/empty-dir"} {
- source, err := root.Open(name)
- if err != nil {
- return fmt.Errorf("open platform instruction mask source: %w", err)
- }
- var stat unix.Stat_t
- var fs unix.Statfs_t
- statErr := unix.Fstat(int(source.Fd()), &stat)
- fsErr := unix.Fstatfs(int(source.Fd()), &fs)
- _ = source.Close()
- if statErr != nil {
- return fmt.Errorf("inspect platform instruction mask source: %w", statErr)
- }
- if fsErr != nil {
- return fmt.Errorf("inspect platform instruction mask source: %w", fsErr)
- }
- if fs.Flags&unix.ST_RDONLY == 0 {
- return fmt.Errorf("platform instruction mask source is not read-only")
- }
- sources = append(sources, stat)
- }
- // /proc/self refers to the Go process leader, which still belongs to the
- // helper's original namespace. Only the locked calling thread entered the
- // private workspace view.
- file, err := os.Open("/proc/thread-self/mountinfo")
- if err != nil {
- return fmt.Errorf("read workspace script mounts: %w", err)
- }
- defer file.Close()
- mounts := make(map[string]bool)
- scanner := bufio.NewScanner(file)
- scanner.Buffer(make([]byte, 4096), 1024*1024)
- for scanner.Scan() {
- fields := strings.Fields(scanner.Text())
- if len(fields) >= 6 {
- mounts[decodeMountPath(fields[4])] = true
- }
- }
- if err := scanner.Err(); err != nil {
- return fmt.Errorf("read workspace script mounts: %w", err)
- }
- for _, target := range targets {
- if !mounts[target] {
- // A package manager can replace the parent directory in a prior
- // script. Docker still lists the detached old dentry as a mask,
- // although it no longer exists at this path in the namespace.
- continue
- }
- file, err := openMaskTarget(root, target, aliases)
- if err != nil {
- if os.IsNotExist(err) {
- continue
- }
- return fmt.Errorf("inspect script instruction mask %s: %w", target, err)
- }
- var stat unix.Stat_t
- var fs unix.Statfs_t
- statErr := unix.Fstat(int(file.Fd()), &stat)
- fsErr := unix.Fstatfs(int(file.Fd()), &fs)
- _ = file.Close()
- if statErr != nil || fsErr != nil {
- return fmt.Errorf("inspect script instruction mask %s: %w", target, errors.Join(statErr, fsErr))
- }
- owned := false
- for _, source := range sources {
- if stat.Dev == source.Dev && stat.Ino == source.Ino && stat.Mode&unix.S_IFMT == source.Mode&unix.S_IFMT && fs.Flags&unix.ST_RDONLY != 0 {
- owned = true
- break
- }
- }
- if !owned {
- // A stale dentry or unrelated user-provided mount is not ours to
- // detach, even when Docker once reported a mask at the same path.
- continue
- }
- // Even in this private namespace, never follow a replacement final
- // symlink and accidentally detach a different mount.
- if err := unix.Unmount(target, unix.MNT_DETACH|unix.UMOUNT_NOFOLLOW); err != nil {
- return fmt.Errorf("detach workspace instruction mask %s: %w", target, err)
- }
- }
- return nil
-}
-
-func applyMasks(targets []string, aliases ...string) error {
- if len(targets) == 0 {
- return nil
- }
- root, err := os.OpenRoot("/workspace")
- if err != nil {
- return fmt.Errorf("open Agent instruction mask root: %w", err)
- }
- defer root.Close()
- for _, target := range targets {
- if err := applyMask(root, target, aliases...); err != nil {
- return err
- }
- }
- return nil
-}
-
-func applyMask(root *os.Root, target string, aliases ...string) error {
- resolved, err := filepath.EvalSymlinks(target)
- if err != nil {
- if os.IsNotExist(err) {
- return nil
- }
- return fmt.Errorf("resolve Agent instruction mask %s: %w", target, err)
- }
- if !ValidMask(resolved, aliases...) {
- return fmt.Errorf("Agent instruction mask resolves outside the project configuration set: %s", target)
- }
- if info, err := os.Lstat(target); err != nil {
- return fmt.Errorf("inspect Agent instruction mask %s: %w", target, err)
- } else if info.Mode()&os.ModeSymlink != 0 && instructionDirectory(filepath.Base(target)) {
- return fmt.Errorf("refusing symlinked Agent instruction directory: %s", target)
- }
- destination, err := openMaskTarget(root, resolved, aliases)
- if err != nil {
- return fmt.Errorf("open Agent instruction mask %s: %w", target, err)
- }
- defer destination.Close()
- info, err := destination.Stat()
- if err != nil {
- return err
- }
- sourceName := ".agentflow/isolation/empty-file"
- if info.IsDir() {
- sourceName = ".agentflow/isolation/empty-dir"
- } else if !info.Mode().IsRegular() {
- return fmt.Errorf("Agent instruction mask is not a regular file or directory: %s", target)
- }
- source, err := root.Open(sourceName)
- if err != nil {
- return fmt.Errorf("open platform instruction mask source: %w", err)
- }
- defer source.Close()
- var sourceFS unix.Statfs_t
- if err := unix.Fstatfs(int(source.Fd()), &sourceFS); err != nil {
- return fmt.Errorf("inspect platform instruction mask source: %w", err)
- }
- if sourceFS.Flags&unix.ST_RDONLY == 0 {
- return fmt.Errorf("platform instruction mask source is not read-only")
- }
- var sourceStat, targetStat unix.Stat_t
- var targetFS unix.Statfs_t
- if err := unix.Fstat(int(source.Fd()), &sourceStat); err != nil {
- return fmt.Errorf("inspect platform instruction mask source: %w", err)
- }
- if err := unix.Fstat(int(destination.Fd()), &targetStat); err != nil {
- return fmt.Errorf("inspect Agent instruction mask %s: %w", target, err)
- }
- if err := unix.Fstatfs(int(destination.Fd()), &targetFS); err != nil {
- return fmt.Errorf("inspect Agent instruction mask %s: %w", target, err)
- }
- if sourceStat.Dev == targetStat.Dev && sourceStat.Ino == targetStat.Ino && targetFS.Flags&unix.ST_RDONLY != 0 {
- // Refresh is idempotent: repeated Agent invocations must not build an
- // ever-growing stack of identical mounts in the canonical namespace.
- return nil
- }
- // Bind from the existing read-only platform source. Bind mounts inherit its
- // read-only flag; descriptor paths prevent target symlink substitution from
- // redirecting the operation outside the securely opened workspace root.
- sourcePath := fmt.Sprintf("/proc/thread-self/fd/%d", source.Fd())
- targetPath := fmt.Sprintf("/proc/thread-self/fd/%d", destination.Fd())
- if err := unix.Mount(sourcePath, targetPath, "", unix.MS_BIND, ""); err != nil {
- return fmt.Errorf("apply Agent instruction mask %s: %w", target, err)
- }
- masked, err := openMaskTarget(root, resolved, aliases)
- if err != nil {
- return fmt.Errorf("verify Agent instruction mask %s: %w", target, err)
- }
- defer masked.Close()
- var maskedFS unix.Statfs_t
- if err := unix.Fstatfs(int(masked.Fd()), &maskedFS); err != nil {
- return fmt.Errorf("verify Agent instruction mask %s: %w", target, err)
- }
- if maskedFS.Flags&unix.ST_RDONLY == 0 {
- return fmt.Errorf("Agent instruction mask did not remain read-only: %s", target)
- }
- return nil
-}
-
-// Aliases are platform supplied, but verify they name the same mounted
-// workspace before the privileged helper touches any instruction path.
-func validateAliases(aliases []string) error {
- canonical, err := os.Stat("/workspace")
- if err != nil {
- return err
- }
- for _, alias := range aliases {
- info, err := os.Stat(alias)
- if err != nil || !os.SameFile(canonical, info) {
- return fmt.Errorf("workspace alias does not name the workspace: %s", alias)
- }
- }
- return nil
-}
-
-func openMaskTarget(root *os.Root, target string, aliases []string) (*os.File, error) {
- base := maskBase(target, aliases)
- if base == "" {
- return nil, fmt.Errorf("instruction mask outside workspace: %s", target)
- }
- if base == "/workspace" {
- return root.Open(strings.TrimPrefix(target, base+"/"))
- }
- aliasRoot, err := os.OpenRoot(base)
- if err != nil {
- return nil, err
- }
- defer aliasRoot.Close()
- return aliasRoot.Open(strings.TrimPrefix(target, base+"/"))
-}
-
-func instructionDirectory(name string) bool {
- return name == ".agents" || name == ".codex" || name == ".claude" || name == ".codebuddy"
-}
-
-func decodeMountPath(value string) string {
- return strings.NewReplacer(`\040`, " ", `\011`, "\t", `\012`, "\n", `\134`, `\`).Replace(value)
-}
-
-func readProcessIdentity(path string) (processIdentity, error) {
- file, err := os.Open(path)
- if err != nil {
- return processIdentity{}, err
- }
- defer file.Close()
- var identity processIdentity
- var foundUID, foundGID, foundGroups bool
- scanner := bufio.NewScanner(file)
- for scanner.Scan() {
- fields := strings.Fields(scanner.Text())
- if len(fields) == 0 {
- continue
- }
- switch fields[0] {
- case "Uid:", "Gid:":
- if len(fields) < 3 {
- return identity, fmt.Errorf("invalid container identity field %s", fields[0])
- }
- value, err := strconv.Atoi(fields[2])
- if err != nil || value < 0 {
- return identity, fmt.Errorf("invalid container identity field %s", fields[0])
- }
- if fields[0] == "Uid:" {
- identity.uid, foundUID = value, true
- } else {
- identity.gid, foundGID = value, true
- }
- case "Groups:":
- foundGroups = true
- for _, raw := range fields[1:] {
- group, err := strconv.Atoi(raw)
- if err != nil || group < 0 {
- return identity, fmt.Errorf("invalid container supplementary group")
- }
- identity.groups = append(identity.groups, group)
- }
- }
- }
- if err := scanner.Err(); err != nil {
- return identity, err
- }
- if !foundUID || !foundGID || !foundGroups {
- return identity, fmt.Errorf("container process identity is incomplete")
- }
- return identity, nil
-}
-
-func dropPrivileges(identity processIdentity) error {
- if err := unix.Prctl(unix.PR_CAP_AMBIENT, unix.PR_CAP_AMBIENT_CLEAR_ALL, 0, 0, 0); err != nil && !errors.Is(err, unix.EINVAL) {
- return err
- }
- // Invalid capability numbers return EINVAL. Discover the kernel's final
- // supported capability without depending on procfs settings in the image.
- for capability := 0; capability < 256; capability++ {
- if err := unix.Prctl(unix.PR_CAPBSET_DROP, uintptr(capability), 0, 0, 0); err != nil {
- if errors.Is(err, unix.EINVAL) {
- break
- }
- return fmt.Errorf("drop capability %d: %w", capability, err)
- }
- }
- if err := unix.Setgroups(identity.groups); err != nil {
- return fmt.Errorf("restore supplementary groups: %w", err)
- }
- if err := unix.Setresgid(identity.gid, identity.gid, identity.gid); err != nil {
- return fmt.Errorf("restore container GID: %w", err)
- }
- if err := unix.Setresuid(identity.uid, identity.uid, identity.uid); err != nil {
- return fmt.Errorf("restore container UID: %w", err)
- }
- header := unix.CapUserHeader{Version: unix.LINUX_CAPABILITY_VERSION_3}
- data := [2]unix.CapUserData{}
- if err := unix.Capset(&header, &data[0]); err != nil {
- return fmt.Errorf("clear process capabilities: %w", err)
- }
- if err := unix.Prctl(unix.PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0); err != nil {
- return fmt.Errorf("disable privilege escalation: %w", err)
- }
- return nil
-}
diff --git a/internal/scriptview/scriptview_linux_test.go b/internal/scriptview/scriptview_linux_test.go
deleted file mode 100644
index 90f23658..00000000
--- a/internal/scriptview/scriptview_linux_test.go
+++ /dev/null
@@ -1,50 +0,0 @@
-//go:build linux
-
-package scriptview
-
-import (
- "os"
- "path/filepath"
- "reflect"
- "testing"
-)
-
-func TestContainerIdentityUsesEffectiveIDsAndPreservesGroups(t *testing.T) {
- name := filepath.Join(t.TempDir(), "status")
- if err := os.WriteFile(name, []byte("Name:\ttini\nUid:\t10 1000 1000 1000\nGid:\t20 2000 2000 2000\nGroups:\t20 2000 3000\n"), 0o600); err != nil {
- t.Fatal(err)
- }
- identity, err := readProcessIdentity(name)
- if err != nil {
- t.Fatal(err)
- }
- if identity.uid != 1000 || identity.gid != 2000 || !reflect.DeepEqual(identity.groups, []int{20, 2000, 3000}) {
- t.Fatalf("container identity changed: %+v", identity)
- }
-}
-
-func TestContainerIdentityRejectsMissingOrInvalidIDs(t *testing.T) {
- for _, status := range []string{
- "Uid:\t0 0 0 0\nGid:\t0 0 0 0\n",
- "Uid:\t0 invalid 0 0\nGid:\t0 0 0 0\nGroups:\t0\n",
- "Uid:\t0 0 0 0\nGid:\t0 -1 0 0\nGroups:\t0\n",
- "Uid:\t0 0 0 0\nGid:\t0 0 0 0\nGroups:\tinvalid\n",
- } {
- name := filepath.Join(t.TempDir(), "status")
- if err := os.WriteFile(name, []byte(status), 0o600); err != nil {
- t.Fatal(err)
- }
- if _, err := readProcessIdentity(name); err == nil {
- t.Errorf("unsafe container identity accepted: %q", status)
- }
- }
-}
-
-func TestMountPathDecodesProcEscapes(t *testing.T) {
- if got := decodeMountPath(`/workspace/project\040name/CLAUDE.md`); got != "/workspace/project name/CLAUDE.md" {
- t.Fatalf("escaped mask mount path=%q", got)
- }
- if got := decodeMountPath(`/workspace/slash\134040/CLAUDE.md`); got != `/workspace/slash\040/CLAUDE.md` {
- t.Fatalf("mount path was decoded more than once: %q", got)
- }
-}
diff --git a/internal/scriptview/scriptview_other.go b/internal/scriptview/scriptview_other.go
deleted file mode 100644
index 4a5d684f..00000000
--- a/internal/scriptview/scriptview_other.go
+++ /dev/null
@@ -1,9 +0,0 @@
-//go:build !linux
-
-package scriptview
-
-import "fmt"
-
-func execute(Config) error {
- return fmt.Errorf("workspace script views require Linux inside the Docker helper")
-}
diff --git a/internal/scriptview/scriptview_parse_config_test.go b/internal/scriptview/scriptview_parse_config_test.go
deleted file mode 100644
index c53f99c8..00000000
--- a/internal/scriptview/scriptview_parse_config_test.go
+++ /dev/null
@@ -1,69 +0,0 @@
-package scriptview
-
-import (
- "slices"
- "strings"
- "testing"
-)
-
-func TestMaskOrderSortsByLengthThenLexically(t *testing.T) {
- input := []string{"/workspace/b/CLAUDE.md", "/workspace/.claude", "/workspace/a/CLAUDE.md", "/workspace/AGENTS.md"}
-
- longest := slices.Clone(input)
- slices.SortFunc(longest, maskOrder(true))
- wantLongest := []string{"/workspace/a/CLAUDE.md", "/workspace/b/CLAUDE.md", "/workspace/AGENTS.md", "/workspace/.claude"}
- if !slices.Equal(longest, wantLongest) {
- t.Fatalf("longest first = %v, want %v", longest, wantLongest)
- }
-
- shortest := slices.Clone(input)
- slices.SortFunc(shortest, maskOrder(false))
- wantShortest := []string{"/workspace/.claude", "/workspace/AGENTS.md", "/workspace/a/CLAUDE.md", "/workspace/b/CLAUDE.md"}
- if !slices.Equal(shortest, wantShortest) {
- t.Fatalf("shortest first = %v, want %v", shortest, wantShortest)
- }
-}
-
-func TestValidateMaskListsChecksEachListIndependently(t *testing.T) {
- if err := validateMaskLists([]string{"/workspace/CLAUDE.md"}, []string{"/workspace/CLAUDE.md"}); err != nil {
- t.Fatalf("same mask in different lists should be accepted: %v", err)
- }
- if err := validateMaskLists(nil, nil); err != nil {
- t.Fatalf("empty lists should be accepted: %v", err)
- }
- for _, list := range [][]string{
- {"/workspace/CLAUDE.md", "/workspace/CLAUDE.md"},
- {"/workspace/README.md"},
- {"/workspace/.git/CLAUDE.md"},
- } {
- err := validateMaskLists(list)
- if err == nil || !strings.Contains(err.Error(), "invalid or duplicate workspace instruction mask") {
- t.Fatalf("validateMaskLists(%v) = %v, want invalid/duplicate error", list, err)
- }
- }
-}
-
-func TestValidateConfigModeMessages(t *testing.T) {
- cases := []struct {
- config Config
- want string
- }{
- {Config{Refresh: true, Argv: []string{"sh"}}, "instruction mask refresh cannot execute commands or detach masks"},
- {Config{Refresh: true, Masks: []string{"/workspace/CLAUDE.md"}}, "instruction mask refresh cannot execute commands or detach masks"},
- {Config{Argv: []string{"sh"}, Hide: []string{"/workspace/CLAUDE.md"}}, "workspace script commands cannot modify canonical instruction masks"},
- {Config{}, "workspace script view command is empty"},
- {Config{Argv: []string{""}}, "workspace script view command is empty"},
- {Config{Argv: []string{"sh", "a\x00b"}}, "workspace script view command contains a null byte"},
- }
- for _, tc := range cases {
- err := validateConfigMode(tc.config)
- if err == nil || err.Error() != tc.want {
- t.Fatalf("validateConfigMode(%+v) = %v, want %q", tc.config, err, tc.want)
- }
- }
- for _, ok := range []Config{{Refresh: true, Hide: []string{"/workspace/CLAUDE.md"}}, {Argv: []string{"sh", "-c", "true"}}} {
- if err := validateConfigMode(ok); err != nil {
- t.Fatalf("validateConfigMode(%+v) = %v, want nil", ok, err)
- }
- }
-}
diff --git a/internal/scriptview/scriptview_test.go b/internal/scriptview/scriptview_test.go
deleted file mode 100644
index 1967cc35..00000000
--- a/internal/scriptview/scriptview_test.go
+++ /dev/null
@@ -1,114 +0,0 @@
-package scriptview
-
-import (
- "reflect"
- "testing"
-)
-
-func TestValidMaskRejectsBroaderMountRemoval(t *testing.T) {
- for _, target := range []string{
- "/workspace/CLAUDE.md", "/workspace/vendor/phpstan/phpstan/CLAUDE.md",
- "/workspace/repository/AGENTS.override.md", "/workspace/repository/.claude", "/workspace/.mcp.json",
- } {
- if !ValidMask(target) {
- t.Errorf("platform mask rejected: %q", target)
- }
- }
- for _, target := range []string{
- "/", "/workspace", "/workspace/", "/workspace/vendor", "/etc/CLAUDE.md",
- "/workspace/../etc/CLAUDE.md", "/workspace/repository/../CLAUDE.md", "/workspace//CLAUDE.md",
- "/workspace/.agentflow/config/CLAUDE.md", "/workspace/repo/.git/CLAUDE.md",
- "workspace/CLAUDE.md", "/workspace/CLAUDE.custom.md", "/workspace/CLAUDE.md\n",
- "/workspace/CODEBUDDY.md\x00", "/workspace/.claude/settings.json",
- } {
- if ValidMask(target) {
- t.Errorf("non-platform mount accepted: %q", target)
- }
- }
-}
-
-func TestConfigRejectsInvalidExecutionAndMaskRequests(t *testing.T) {
- for _, raw := range []string{
- `{`, `null`, `{}`, `{"argv":[]}`, `{"argv":[""]}`,
- `{"argv":["sh","hello\u0000there"]}`,
- `{"argv":["sh"],"privileged":true}`,
- `{"argv":["sh"]} {"argv":["other"]}`,
- `{"argv":["sh"]} false`,
- `{"argv":["sh"],"masks":["/workspace"]}`,
- `{"argv":["sh"],"masks":["/workspace/CLAUDE.md","/workspace/CLAUDE.md"]}`,
- `{"argv":["sh"],"hide":["/workspace"]}`,
- `{"argv":["sh"],"hide":["/workspace/CLAUDE.md","/workspace/CLAUDE.md"]}`,
- } {
- if _, err := parseConfig(raw); err == nil {
- t.Errorf("invalid configuration accepted: %s", raw)
- }
- }
-}
-
-func TestConfigRefreshesMasksParentFirst(t *testing.T) {
- config, err := parseConfig(`{"refresh":true,"hide":["/workspace/.claude/CLAUDE.md","/workspace/.claude"]}`)
- if err != nil {
- t.Fatal(err)
- }
- if got := config.Hide[0]; got != "/workspace/.claude" {
- t.Fatalf("parent mask must precede its children: %#v", config.Hide)
- }
- if !config.Refresh || len(config.Argv) != 0 || len(config.Masks) != 0 {
- t.Fatalf("mask refresh must not execute or detach: %#v", config)
- }
-}
-
-func TestRefreshCanOnlyAddCanonicalReadOnlyMasks(t *testing.T) {
- for _, raw := range []string{
- `{"refresh":true,"argv":["sh"],"hide":["/workspace/CLAUDE.md"]}`,
- `{"refresh":true,"masks":["/workspace/CLAUDE.md"]}`,
- `{"argv":["sh"],"hide":["/workspace/CLAUDE.md"]}`,
- `{"refresh":true,"hide":["/etc/CLAUDE.md"]}`,
- } {
- if _, err := parseConfig(raw); err == nil {
- t.Errorf("unsafe refresh/script combination accepted: %s", raw)
- }
- }
-}
-
-func TestConfigPreservesArgvAndDetachesChildMasksFirst(t *testing.T) {
- config, err := parseConfig(`{"argv":["sh","-c","printf '%s' \"$VALUE\""],"masks":["/workspace/.claude","/workspace/.claude/CLAUDE.md","/workspace/CLAUDE.md"]}`)
- if err != nil {
- t.Fatal(err)
- }
- if !reflect.DeepEqual(config.Argv, []string{"sh", "-c", `printf '%s' "$VALUE"`}) {
- t.Fatalf("command arguments changed: %#v", config.Argv)
- }
- if got := config.Masks[0]; got != "/workspace/.claude/CLAUDE.md" {
- t.Fatalf("child mount must precede parent: %#v", config.Masks)
- }
-}
-
-func TestRunDispatchFailsClosedOnInvalidMode(t *testing.T) {
- for _, args := range [][]string{nil, {"--other-mode"}} {
- if handled, err := Run(args); handled || err != nil {
- t.Fatalf("ordinary gate invocation was intercepted: handled=%v err=%v", handled, err)
- }
- }
- for _, args := range [][]string{{Argument}, {Argument, `{}`, "unexpected"}, {Argument, `{"argv":["sh"],"masks":["/"]}`}, {ProbeArgument, "unexpected"}} {
- if handled, err := Run(args); !handled || err == nil {
- t.Fatalf("invalid private invocation did not fail closed: handled=%v err=%v", handled, err)
- }
- }
-}
-
-func TestConfigOnlyAcceptsExplicitWorkspaceAliases(t *testing.T) {
- config, err := parseConfig(`{"refresh":true,"aliases":["/native/conversation/ws"],"hide":["/native/conversation/ws/repo/AGENTS.md"]}`)
- if err != nil || len(config.Hide) != 1 {
- t.Fatal(config, err)
- }
- for _, raw := range []string{
- `{"refresh":true,"hide":["/native/conversation/ws/repo/AGENTS.md"]}`,
- `{"refresh":true,"aliases":["/etc"],"hide":["/etc/AGENTS.md"]}`,
- `{"refresh":true,"aliases":["/native/ws"],"hide":["/native/ws/.git/AGENTS.md"]}`,
- } {
- if _, err := parseConfig(raw); err == nil {
- t.Fatal("unsafe alias accepted", raw)
- }
- }
-}