diff --git a/.github/workflows/platform.yml b/.github/workflows/platform.yml index 612590753..89d6b1d83 100644 --- a/.github/workflows/platform.yml +++ b/.github/workflows/platform.yml @@ -24,6 +24,10 @@ jobs: run: bash scripts/build-chatbot.sh - name: Let Chromium use its sandbox as an unprivileged user run: sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0 + # Engine and API tests run SOP nodes in the shared test-native sandbox, + # which is bwrap on Linux. + - name: Install bubblewrap for the native sandbox + run: sudo apt-get update && sudo apt-get install -y bubblewrap - name: Warm up Chromium so the first real-browser test does not pay the cold start run: | for name in chromium chromium-browser google-chrome-stable google-chrome; do @@ -87,6 +91,19 @@ jobs: working-directory: e2e - run: bash ../scripts/install-playwright-deps.sh npx playwright working-directory: e2e + # The e2e SOPs and the runner the suite starts use the native e2e sandbox, + # which is bwrap on Linux. + - name: Let bubblewrap create user namespaces + run: sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0 + - name: Install bubblewrap for the native sandbox + run: sudo apt-get update && sudo apt-get install -y bubblewrap + # The welcome SOP runs in generic-docker. As in a Compose installation, it + # uses the pinned platform image instead of building one during the tests. + - name: Pull the pinned platform image for the generic-docker sandbox + run: | + pinned=$(sed -n 's/^ *image: \${LOOPFORGE_IMAGE:-\(.*\)}$/\1/p' compose.yaml) + docker pull --quiet "$pinned" + echo "AGENTFLOW_ISOLATED_IMAGE=$pinned" >> "$GITHUB_ENV" - name: Start clean local installation run: | bash scripts/dev.sh > /tmp/loopforge.log 2>&1 & @@ -172,6 +189,8 @@ jobs: # The path a new user takes: one-command install, then accounts created in the browser. # Pulls the GHCR release pinned in compose.yaml; release.yml smoke-tests each newly published image. # A pin bumped ahead of its tag has no image yet, so that commit is checked from source. + # So is a commit whose schema scripts differ from the pinned tag: the installer applies + # this checkout's scripts, which the released image may not be able to read. runs-on: ubuntu-latest timeout-minutes: 30 env: @@ -187,14 +206,22 @@ jobs: working-directory: e2e - run: bash ../scripts/install-playwright-deps.sh npx playwright working-directory: e2e - - name: Install the pinned release, or build it while that release is not published yet + - name: Install the pinned release, or build this checkout when the release cannot run it run: | pinned=$(sed -n 's/^ *image: \${LOOPFORGE_IMAGE:-\(.*\)}$/\1/p' compose.yaml) - if docker manifest inspect "$pinned" > /dev/null 2>&1; then - ./start.sh -d - else + tag="v${pinned##*:}" + schema=(migrations scripts/install-schema-extensions.sh scripts/install-observability-schema.sh) + if ! docker manifest inspect "$pinned" > /dev/null 2>&1; then echo "::notice::$pinned is not published yet; building this checkout" ./start.sh dev + elif ! git fetch --quiet --depth=1 origin "refs/tags/$tag:refs/tags/$tag"; then + echo "::warning::could not fetch $tag to compare schema scripts; installing $pinned" + ./start.sh -d + elif ! git diff --quiet "$tag" -- "${schema[@]}"; then + echo "::notice::schema scripts changed since $tag; building this checkout" + ./start.sh dev + else + ./start.sh -d fi - name: Generate test passwords run: | diff --git a/AGENTS.md b/AGENTS.md index d4641dc8c..1a7ccc9d4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -13,7 +13,7 @@ Preserve the platform architecture; keep deployment-specific adapters isolated. | 领域 Repo | 拥有 | |---|---| -| `CatalogRepo` | agents/rules/skills/MCP servers/executors/dockerfiles/environments/sandboxes/workflows/repositories/sync config/schedule jobs/definition revisions/generic templates | +| `CatalogRepo` | agents/rules/skills/MCP servers/executors/sandboxes(docker 内嵌 Dockerfile,native 只有环境变量)/workflows/repositories/sync config/schedule jobs/definition revisions/generic templates | | `ProjectsRepo` | projects、project members | | `IssuesRepo` | issues、issue comments | | `TasksRepo` | tasks(跨实例幂等记录) | diff --git a/CHANGELOG.md b/CHANGELOG.md index e6e79c51b..3bdc532b6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ Platform releases use `vX.Y.Z` tags and publish `ghcr.io/tencent/loopforge`. LoopForge Local packages use `local-vX.Y.Z` tags and are published by manually running the `release-local` workflow. +## Unreleased + +- **Breaking:** the `local` sandbox type is removed and native sandboxes only carry environment variables. A native sandbox runs on whichever machine executes the work (a user's execution machine, a cloud runner or the platform host) with that machine's own toolchains; environment install scripts, `$PREFIX` and install PATH entries are gone, and settings such as `JAVA_HOME` go into the sandbox's environment variables. SOPs and conversation workspaces can use Docker or native sandboxes; the default sandbox is `generic-docker`, and `AGENTFLOW_LOCAL_SANDBOX` is removed. A local row that was not migrated reads as native; a run frozen with a local sandbox asks to be started again with a native one. +- Native workspaces check repositories out from a per-machine repository cache. Each Runner and the platform host keep a bare cache per repository record under their workspace root (`.repository-cache/.git`), fetched outside the sandbox under a lock and never garbage-collected. SOP checkouts in native sandboxes become `git clone --shared` of the refreshed cache with origin set back to the repository URL, falling back to a full clone; Docker sandboxes keep full clones. Opening a native conversation workspace warms the project's repository caches in the background, and the repository list sent to the agent tells it to clone from `$LOOPFORGE_REPOSITORY_CACHE` (read-only inside the sandbox) before falling back to a normal clone. Workspace checkpoints copy the borrowed objects in first, so they restore on machines without the cache. Runner 0.12.0 checks out from and warms the cache; older Runners keep full clones. +- 设置 → AI 助手 gains 「对话工作区」: users choose the sandbox kind (Docker or native) the assistant prefers when it opens a conversation workspace itself. The preference (`workspaceDriver` in `/api/assistant/preferences`) puts that kind first in the assistant's choices and is used when it names no environment; the assistant still switches when only another environment has the toolchain a task needs, and a conversation's fixed environment still wins. The workbench environment picker now also lists native sandboxes, grouped by kind. Startup AutoMigrate adds the column; the migration below also adds it for deployments that apply DDL by hand. +- **Breaking:** a docker sandbox now carries its own Dockerfile, and the 环境资产 page becomes 「沙箱管理」 without type tabs: the sandbox editor holds the Dockerfile and its build-context files for docker, and only environment variables for native. Dockerfiles and install scripts are no longer separate assets. `/api/dockerfiles`, `/api/environments`, the `dockerfiles_*` / `environments_*` assistant and MCP tools and the `dockerfiles` / `environments` bootstrap fields are removed; `PUT /api/sandboxes` takes `dockerfile {content, files}` in place of `dockerfileId`, and rejects `driver: local`. Before starting the upgraded platform, apply `migrations/041_native_sandbox_inline_assets.sql` to existing databases with `./start.sh migrate-sandboxes` for Compose or directly for external MySQL. It copies each referenced Dockerfile into its sandbox, turns one that no sandbox used into a sandbox of its own, turns local sandboxes into native ones, drops install scripts and `PATH` from native sandbox variables, moves the built-in SOPs that used the old `local` profile to `generic-docker`, and drops the `dockerfiles` and `environments` tables. Docker images are reused. + ## 0.4.1 — Git and MCP credentials, SOP orchestration and conversation workspaces - Configure HTTPS Git credentials per host, authorize the IP addresses of self-hosted HTTPS Git servers, and distribute trusted SSH host keys to execution machines. MCP servers, market items and SOP nodes can use configured credentials. diff --git a/chatbot/src/SandboxPicker.jsx b/chatbot/src/SandboxPicker.jsx index 7b0a05c0a..1195fe123 100644 --- a/chatbot/src/SandboxPicker.jsx +++ b/chatbot/src/SandboxPicker.jsx @@ -3,13 +3,23 @@ import { SelectMenu } from "./ui"; import HarnessIcon from "./HarnessIcon"; import "./sandbox-picker.css"; +const SANDBOX_KINDS = ["docker", "native"]; +const SANDBOX_KIND_LABELS = { + docker: "Docker", + native: "系统轻量隔离", +}; + +function sandboxKind(sandbox) { + return !sandbox.driver || sandbox.driver === "docker" ? "docker" : "native"; +} + export function conversationSandboxOptions(sandboxes, project, selected = "") { - const available = (sandboxes || []).filter( - (s) => s.driver === "docker" && (s.projectId === project?.id || s.shared), - ); + const available = (sandboxes || []) + .filter((s) => s.projectId === project?.id || s.shared) + .sort((a, b) => SANDBOX_KINDS.indexOf(sandboxKind(a)) - SANDBOX_KINDS.indexOf(sandboxKind(b))); const options = [ { value: "", label: "由 Agent 选择" }, - ...available.map((s) => ({ value: s.id, label: s.name || s.id })), + ...available.map((s) => ({ value: s.id, label: s.name || s.id, kind: sandboxKind(s) })), ]; if (selected && !available.some((s) => s.id === selected)) { options.push({ @@ -58,7 +68,7 @@ export default function SandboxPicker({ chat, onCreate }) { .map((o) => ({ id: o.value, label: o.label, - description: o.value ? "" : "按要改的代码自动选择,拿不准时用平台通用 Docker", + description: o.value ? SANDBOX_KIND_LABELS[o.kind] : "按 AI 助手设置里倾向的沙箱和任务需要自动选择", icon: o.value ? "terminal" : "folder", })); return ( diff --git a/chatbot/src/platform.js b/chatbot/src/platform.js index e7f9dab35..d757e56c0 100644 --- a/chatbot/src/platform.js +++ b/chatbot/src/platform.js @@ -32,9 +32,7 @@ const entities = { assistant_tasks: "助手定时任务", runs: "运行", issues: "需求", - environments: "环境", sandboxes: "沙箱", - dockerfiles: "Dockerfile", executors: "执行器", }; const verbs = { diff --git a/chatbot/tests/sandbox-picker.test.jsx b/chatbot/tests/sandbox-picker.test.jsx index e3edc50e2..d3d3d30f4 100644 --- a/chatbot/tests/sandbox-picker.test.jsx +++ b/chatbot/tests/sandbox-picker.test.jsx @@ -9,7 +9,6 @@ const sandboxes = [ { id: "business", name: "PHP 业务环境", projectId: "p", driver: "docker" }, { id: "shared", name: "共享环境", shared: true, driver: "docker" }, { id: "private", name: "其他业务私有环境", projectId: "other", driver: "docker" }, - { id: "local", name: "宿主机", shared: true, driver: "local" }, ]; describe("conversation environment selection", () => { @@ -28,7 +27,7 @@ describe("conversation environment selection", () => { expect(select).not.toHaveBeenCalled(); }); - test("defaults to the agent's choice and lists only accessible containers", () => { + test("defaults to the agent's choice and lists only accessible sandboxes", () => { const options = conversationSandboxOptions(sandboxes, project); expect(options.map((o) => o.value)).toEqual(["", "business", "shared"]); expect(options[0].label).toBe("由 Agent 选择"); @@ -36,6 +35,13 @@ describe("conversation environment selection", () => { expect(missing).toMatchObject({ value: "deleted", disabled: true }); }); + test("lists native sandboxes after the Docker ones", () => { + const rows = [{ id: "light", name: "轻量沙箱", projectId: "p", driver: "native" }, ...sandboxes]; + const options = conversationSandboxOptions(rows, project, ""); + expect(options.map((o) => o.value)).toEqual(["", "business", "shared", "light"]); + expect(options.find((o) => o.value === "light")).toMatchObject({ kind: "native" }); + }); + test("a task conversation shows the task environment", () => { render( { trigger.getBoundingClientRect = () => ({top:500,bottom:528,left:200,right:450,width:250,height:28}); const user = userEvent.setup(); await user.click(trigger); - await user.click(screen.getByRole("option", { name: "PHP 业务环境" })); + await user.click(screen.getByRole("option", { name: /^PHP 业务环境/ })); expect(select).toHaveBeenCalledWith("business"); }); }); diff --git a/cmd/agentflow/main.go b/cmd/agentflow/main.go index b53879734..075c7e1ab 100644 --- a/cmd/agentflow/main.go +++ b/cmd/agentflow/main.go @@ -133,13 +133,13 @@ func main() { if err != nil { log.Fatal(err) } + runtime.SetRepositoryCacheRoot(root) s, err := repo.Open(strings.TrimSpace(*mysqlDSN)) if err != nil { log.Fatal(err) } log.Printf("storage driver=%v database=%v role=%s", s.StorageInfo()["driver"], s.StorageInfo()["database"], role) e := engine.New(s, runtime.NewManagerWithLimit(root, *workerConcurrency)) - runtime.PrebuildIsolatedImage() host, _ := os.Hostname() instanceID := strings.TrimSpace(os.Getenv("AGENTFLOW_INSTANCE_ID")) if instanceID == "" { diff --git a/compose.yaml b/compose.yaml index 49d74140c..889f4bd54 100644 --- a/compose.yaml +++ b/compose.yaml @@ -47,7 +47,6 @@ services: AGENTFLOW_PREVIEW_PUBLIC_URL: ${AGENTFLOW_PREVIEW_PUBLIC_URL:-} AGENTFLOW_PLATFORM_MCP_URL: ${AGENTFLOW_PLATFORM_MCP_URL:-http://platform:8080} AGENTFLOW_DOCKER_NETWORK: ${COMPOSE_PROJECT_NAME:-loopforge}_default - AGENTFLOW_LOCAL_SANDBOX: docker AGENTFLOW_ISOLATED_IMAGE: ${LOOPFORGE_IMAGE:-ghcr.io/tencent/loopforge:0.4.1} HOME: ${LOOPFORGE_DATA_DIR:?Run scripts/configure.sh first}/home AGENTFLOW_RUNNER_BINARY: /app/bin/agentflow-runner-{os}-{arch} diff --git a/design.md b/design.md index 6b421324b..9e01236a3 100644 --- a/design.md +++ b/design.md @@ -383,9 +383,9 @@ Bot 管理页(`#botsView`)按需求列表与运行记录列表的 Harness 界面上称「AI 助手」,避免和「Bot 管理」里的企业微信机器人混淆。设置页、SOP 建议卡片和子 Agent 面板都用这个名字。 -AI 助手页(`#assistantView`,路由 `#/assistant`)在设置导航「管理与记录」下紧跟 Bot 管理,图标为 Harness `sparkles`。页头只有 H1 和一句说明(先讲它是谁,再讲能设置什么);内容和其他设置页一样铺满 1200px 居中容器,使用三块 14px 圆角面板:「消息发送」提供「生成中发送消息」下拉选项,默认「排队」,也可选「立即发送」,说明会打断当前回复、保留已输出内容并继续处理新消息;「主动派发」里是「主动派角色」「主动走 SOP」两行(默认关闭,面板说明写明打开后更主动,以及角色直接派、SOP 先确认),左侧标题 + 说明,右侧 `role="switch"` 开关;「自定义规则」是一个可纵向拉伸的输入框,右下角显示「N / 4000」。底部「保存」是页面唯一的实心按钮,没有改动或保存中时禁用;未登录只显示提示。样式在 `web/app/assistant-settings.css`,规则限定在 `#assistantView` 内,只引用 `--hui-*` 令牌。 +AI 助手页(`#assistantView`,路由 `#/assistant`)在设置导航「管理与记录」下紧跟 Bot 管理,图标为 Harness `sparkles`。页头只有 H1 和一句说明(先讲它是谁,再讲能设置什么);内容和其他设置页一样铺满 1200px 居中容器,使用四块 14px 圆角面板:「消息发送」提供「生成中发送消息」下拉选项,默认「排队」,也可选「立即发送」,说明会打断当前回复、保留已输出内容并继续处理新消息;「主动派发」里是「主动派角色」「主动走 SOP」两行(默认关闭,面板说明写明打开后更主动,以及角色直接派、SOP 先确认),左侧标题 + 说明,右侧 `role="switch"` 开关;「对话工作区」提供「倾向的沙箱」下拉选项,默认「由 Agent 选择」,也可选 Docker 或 native 沙箱,说明写明会话固定了环境时不生效、任务需要时仍会换;「自定义规则」是一个可纵向拉伸的输入框,右下角显示「N / 4000」。底部「保存」是页面唯一的实心按钮,没有改动或保存中时禁用;未登录只显示提示。样式在 `web/app/assistant-settings.css`,规则限定在 `#assistantView` 内,只引用 `--hui-*` 令牌。 -发送方式按用户保存为 `steerOnSend`,设置保存后通知已打开的工作台即时刷新。立即发送复用排队消息的「引导」操作;引导切换期间再次发送的消息先排队,引导请求失败也保留消息。手动「引导」仍可用于排队模式。 +发送方式按用户保存为 `steerOnSend`,倾向的沙箱按用户保存为 `workspaceDriver`,设置保存后通知已打开的工作台即时刷新。立即发送复用排队消息的「引导」操作;引导切换期间再次发送的消息先排队,引导请求失败也保留消息。手动「引导」仍可用于排队模式。 没有 @ SOP、也没有点名要走 SOP 时,AI 助手自己决定交给 SOP 的事是建议。每次批准由用户在卡片上确认;帮我批准由独立审查决定,未通过时同样变成建议卡片;完全权限下直接启动。角色始终直接派发,不弹卡片。`timing=start` 的建议 3 分钟无人处理就超时,服务端把事情交回 AI 助手自己做,不依赖浏览器还开着。决定通过 `POST /api/assistant/sessions/{id}/proposals` 提交。开关和自定义规则按用户存在 `assistant_preferences`,由 AutoMigrate 建表,接口是 `GET` / `PUT /api/assistant/preferences`。 diff --git a/docs/api/README.md b/docs/api/README.md index d861889fd..11e075e7a 100644 --- a/docs/api/README.md +++ b/docs/api/README.md @@ -107,8 +107,6 @@ curl -H "Authorization: Bearer $AGENTFLOW_TOKEN" "$AGENTFLOW_URL/api/health" | `GET`, `PUT` | `/api/mcp-servers` | | `POST` | `/api/mcp-servers/import` | | `GET` | `/api/executors` | -| `GET`, `PUT`, `DELETE` | `/api/dockerfiles` | -| `GET`, `PUT`, `DELETE` | `/api/environments` | | `GET`, `PUT`, `DELETE` | `/api/sandboxes` | ### 编排、运行与观测 diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yaml index 4b337a285..76ce59b3e 100644 --- a/docs/api/openapi.yaml +++ b/docs/api/openapi.yaml @@ -2339,82 +2339,6 @@ paths: application/json: schema: $ref: "#/components/schemas/OpenObject" - /api/dockerfiles: - get: - tags: [Assets] - operationId: listDockerfiles - responses: - "200": - $ref: "#/components/responses/AssetList" - "401": - $ref: "#/components/responses/Unauthorized" - put: - tags: [Assets] - operationId: upsertDockerfile - requestBody: - $ref: "#/components/requestBodies/DockerfileAsset" - responses: - "200": - $ref: "#/components/responses/Ok" - "400": - $ref: "#/components/responses/BadRequest" - "401": - $ref: "#/components/responses/Unauthorized" - delete: - tags: [Assets] - operationId: deleteDockerfile - summary: Delete a Dockerfile that is not shared and not referenced by any sandbox - parameters: - - $ref: "#/components/parameters/AssetIdQuery" - responses: - "204": - description: Dockerfile deleted - "400": - $ref: "#/components/responses/BadRequest" - "401": - $ref: "#/components/responses/Unauthorized" - "404": - $ref: "#/components/responses/NotFound" - "409": - $ref: "#/components/responses/Conflict" - /api/environments: - get: - tags: [Assets] - operationId: listEnvironments - responses: - "200": - $ref: "#/components/responses/AssetList" - "401": - $ref: "#/components/responses/Unauthorized" - put: - tags: [Assets] - operationId: upsertEnvironment - requestBody: - $ref: "#/components/requestBodies/EnvironmentAsset" - responses: - "200": - $ref: "#/components/responses/Ok" - "400": - $ref: "#/components/responses/BadRequest" - "401": - $ref: "#/components/responses/Unauthorized" - delete: - tags: [Assets] - operationId: deleteEnvironment - summary: Delete an environment install script that is not shared and not referenced by any sandbox - parameters: - - $ref: "#/components/parameters/AssetIdQuery" - responses: - "204": - description: Environment deleted - "400": - $ref: "#/components/responses/BadRequest" - "401": - $ref: "#/components/responses/Unauthorized" - "404": - $ref: "#/components/responses/NotFound" - "409": - $ref: "#/components/responses/Conflict" /api/sandboxes: get: tags: [Assets] @@ -3987,18 +3911,6 @@ components: application/json: schema: $ref: "#/components/schemas/MCPServerAsset" - DockerfileAsset: - required: true - content: - application/json: - schema: - $ref: "#/components/schemas/DockerfileAsset" - EnvironmentAsset: - required: true - content: - application/json: - schema: - $ref: "#/components/schemas/EnvironmentAsset" SandboxProfile: required: true content: @@ -4255,49 +4167,31 @@ components: pathEntries: {type: array, items: {type: string}} authType: {type: string, enum: ["", github-token]} timeoutSec: {type: integer} - DockerfileAsset: - type: object - required: [id, name, projectId, content] - additionalProperties: true - properties: - id: {type: string} - name: {type: string} - projectId: {type: string} - shared: {type: boolean} - description: {type: string} - content: {type: string, description: Dockerfile text} - files: {type: object, additionalProperties: {type: string}, description: Build-context files keyed by relative path} - EnvironmentAsset: - type: object - required: [id, name, projectId] - additionalProperties: true - properties: - id: {type: string} - name: {type: string} - projectId: {type: string} - shared: {type: boolean} - description: {type: string} - variables: {type: object, additionalProperties: {type: string}} - pathEntries: {type: array, items: {type: string}} - installScript: {type: string, description: Runs once with PREFIX set to the isolated environment root} SandboxProfile: type: object required: [id, name, projectId, driver] additionalProperties: true description: >- - Execution environment for SOP runs and conversation workspaces. Conversation workspaces - need driver=docker with an existing dockerfileId; the built-in shared generic-docker - profile already satisfies this, so create a new profile only for a different toolchain. + Execution environment for SOP runs and conversation workspaces; the built-in shared + generic-docker profile is the default. driver=native runs on whichever execution machine, + cloud runner or platform host executes the work, with that machine's own toolchains; its + repositories are shared clones of that machine's repository cache. A stored local profile + reads as native. properties: id: {type: string} name: {type: string} projectId: {type: string, description: Owning project (required)} shared: {type: boolean, description: Visible to every project} - driver: {type: string, enum: [local, native, docker]} - dockerfileId: {type: string, description: Required for driver=docker; see dockerfiles_list} - environmentId: {type: string, description: Toolchain for native/local drivers; see environments_list} - readOnlyRootFS: {type: boolean} - environment: {type: object, additionalProperties: {type: string}} + driver: {type: string, enum: [native, docker]} + dockerfile: + type: object + description: "driver=docker (required): the image recipe, stored with the sandbox. Ignored for other drivers." + required: [content] + properties: + content: {type: string, description: Dockerfile text} + files: {type: object, additionalProperties: {type: string}, description: Build-context files keyed by relative path} + readOnlyRootFS: {type: boolean, description: "driver=docker only"} + environment: {type: object, additionalProperties: {type: string}, description: Variables added to every command; a native sandbox keeps the execution machine's PATH unless this sets one} APIToken: type: object required: [id, userId, name, prefix, createdAt] @@ -5801,8 +5695,6 @@ components: - skills - mcpServers - executors - - dockerfiles - - environments - sandboxes - workflows - syncConfig @@ -5842,18 +5734,10 @@ components: type: array items: $ref: "#/components/schemas/OpenObject" - dockerfiles: - type: array - items: - $ref: "#/components/schemas/OpenObject" - environments: - type: array - items: - $ref: "#/components/schemas/OpenObject" sandboxes: type: array items: - $ref: "#/components/schemas/OpenObject" + $ref: "#/components/schemas/SandboxProfile" workflows: type: array items: diff --git a/docs/api/registry.md b/docs/api/registry.md index 7f17a059f..1926aa79f 100644 --- a/docs/api/registry.md +++ b/docs/api/registry.md @@ -17,8 +17,6 @@ "skills":[], "mcpServers":[], "executors":[], - "dockerfiles":[], - "environments":[], "sandboxes":[], "workflows":[], "syncConfig":{}, @@ -175,48 +173,26 @@ curl -u "$AGENTFLOW_USER:$AGENTFLOW_PASS" -X POST \ 返回只读的内置 CLI 目录(CodeBuddy、Codex、Claude Code,以及 OpenCode、Cursor CLI、Antigravity、Kimi Code、Pi、DeepSeek Harness、ZCode)。CLI 不允许通过 API 新增或修改;模型在 Agent 中设置,API Key/Base URL 使用需求责任人(未指定时为项目 Owner)的个人配置。 -## Dockerfile、Environment 与 Sandbox Profile +## Sandbox Profile -### `GET /api/dockerfiles` - -返回 `DockerfileDefinition[]`,`200`。字段为 `id`、`name`、`description`、`content`、`files`、`updatedAt`。 - -### `PUT /api/dockerfiles` - -`id`、`name`、`content` 必填;`files` 的 key 必须是安全的相对路径。成功 `200 {"ok":true}`;校验失败 `400`。 - -### `DELETE /api/dockerfiles?id={id}` - -删除 Dockerfile。前置条件:未共享且未被任何沙箱引用,否则 `409`;成功 `204`。 - -### `GET /api/environments` - -返回 `EnvironmentDefinition[]`,`200`。字段为 `id`、`name`、`description`、`variables`、`pathEntries`、`installScript`、`updatedAt`。 - -### `PUT /api/environments` - -`id`、`name` 必填;变量名不得含 `=`/NUL,`pathEntries` 必须是安全相对路径。成功 `200 {"ok":true}`;校验失败 `400`。 - -### `DELETE /api/environments?id={id}` - -删除环境安装脚本。前置条件:未共享且未被任何沙箱引用,否则 `409`;成功 `204`。 +docker 沙箱的 Dockerfile 存在沙箱里,随沙箱一起共享,没有单独的 Dockerfile 资产。native 沙箱只有环境变量,使用实际执行它的机器(用户的执行机器、云端 Runner 或平台本机)上已安装的工具,仓库从那台机器的仓库缓存共享克隆。旧的 `/api/dockerfiles`、`/api/environments`、环境安装脚本和 `local` 类型已移除;现有部署升级时,在启动新版本前手动执行 `migrations/041_native_sandbox_inline_assets.sql`。 ### `GET /api/sandboxes` -返回 `SandboxProfile[]`,`200`。字段为 `id`、`name`、`driver`(`local|native|docker`;保存 `seatbelt` 或 `bwrap` 会归一成 `native`,运行时在 macOS 解析为 seatbelt、在 Linux 解析为 bwrap)、`dockerfileId`、`environmentId`、`readOnlyRootFS`、`environment`。 +返回 `SandboxProfile[]`,`200`。字段为 `id`、`name`、`driver`(`native|docker`;保存 `seatbelt` 或 `bwrap` 会归一成 `native`,运行时在 macOS 解析为 seatbelt、在 Linux 解析为 bwrap;尚未迁移的 `local` 行读出时也是 `native`)、`dockerfile`、`readOnlyRootFS`、`environment`。`dockerfile` 为 `{content, files}`,`files` 是构建上下文文件(相对路径 → 内容)。 ### `PUT /api/sandboxes` -`id` 必填,成功 `200 {"ok":true}`;校验/存储失败 `400`。 +`id` 必填,成功 `200 {"ok":true}`;校验/存储失败 `400`。`docker` 必须带非空的 `dockerfile.content`;`dockerfile` 和 `readOnlyRootFS` 只对 `docker` 生效,改成 `native` 后在保存时丢弃。`files` 的 key 必须是安全的相对路径,变量名不得含 `=`/NUL。`driver` 为 `local` 时返回 `400`。 ### `DELETE /api/sandboxes?id={id}` -删除沙箱配置。前置条件:不是内置 `local`、未共享、且未被任何 SOP 引用,否则 `409`;成功 `204`。 +删除沙箱配置。前置条件:不是内置 `generic-docker`、未共享、且未被任何 SOP 引用,否则 `409`;成功 `204`。 ```bash curl -u "$AGENTFLOW_USER:$AGENTFLOW_PASS" -X PUT \ -H 'Content-Type: application/json' \ - -d '{"id":"sandbox-go","name":"Go 隔离环境","driver":"docker","dockerfileId":"go-1.23","readOnlyRootFS":false}' \ + -d '{"id":"sandbox-go","name":"Go 隔离环境","driver":"docker","dockerfile":{"content":"FROM golang:1.23\nWORKDIR /workspace\n"},"readOnlyRootFS":false}' \ "$AGENTFLOW_URL/api/sandboxes" ``` diff --git a/docs/conversation-workspaces.md b/docs/conversation-workspaces.md index 015c06432..4f3572e2f 100644 --- a/docs/conversation-workspaces.md +++ b/docs/conversation-workspaces.md @@ -1,6 +1,6 @@ # 对话工作区与项目沙箱 -普通对话中的 Main Bot 保持本地对话进程,需要看代码、改代码、跑命令、构建或访问 GitHub 时才调用 `workbench_workspace_open` 进入工作区模式。工作区是一个**运行环境**,不是一次检出:`workbench_workspace_open` 接收可选的 `sandboxProfileId` 与 `workspaceRunId`(其他参数一律报错),工具描述列出本项目和共享的可用沙箱(Docker,或执行机器的 native 轻量沙箱)以及项目登记的仓库地址供 clone 参考。不选环境时沿用当前工作区,还没有工作区时用会话设置或平台 `generic-docker`;任何情况下都不使用无隔离的宿主机(`local`)。所选环境不可用(被删除、`local`、跨项目私有、Dockerfile 缺失)时返回可操作错误,由 Main Bot 改选,不会被静默替换。 +普通对话中的 Main Bot 保持本地对话进程,需要看代码、改代码、跑命令、构建或访问 GitHub 时才调用 `workbench_workspace_open` 进入工作区模式。工作区是一个**运行环境**,不是一次检出:`workbench_workspace_open` 接收可选的 `sandboxProfileId` 与 `workspaceRunId`(其他参数一律报错),工具描述列出本项目和共享的可用沙箱(Docker,或执行机器的 native 轻量沙箱)以及项目登记的仓库地址供 clone 参考。不选环境时沿用当前工作区,还没有工作区时用会话设置、AI 助手设置里倾向的环境或平台 `generic-docker`。所选环境不可用(被删除、跨项目私有、Dockerfile 缺失)时返回可操作错误,由 Main Bot 改选,不会被静默替换。 传入 `workspaceRunId`(同项目的 SOP 运行 ID,或本对话之前开启过的可用工作区 ID;子 SOP 会自动定位到父工作区)时,要求目标工作区与当前对话在同一执行机器上(不在同一机器时如实报错并说明双方所在机器),直接将本对话绑定到该原工作区;已回收的快照会先原地恢复,且修改结果直接保留在原 SOP 工作区中,之后可直接在 SOP 上 `Retry` 重跑后续节点或 `runs_resume` 继续流程,删除普通对话也不会删除借用的 SOP 工作区。接入或进入 SOP 工作区与 SOP 自身的工作区编辑、终端、Retry、resume 一样需要项目写权限:本轮发言人是项目只读成员(viewer)时拒绝接入;共享对话已被其他成员绑定到 SOP 时,只读成员发言的那一轮以平台模式运行,不会继承该 SOP 工作区的写入能力。重新打开当前已绑定的工作区时若准备失败(租约被占用、执行机器暂时离线等),保留原绑定,稍后重试即可。执行机器比对使用运行实际所在的机器:没有冻结执行模式的旧运行按负责人默认执行机器计算。 @@ -10,6 +10,8 @@ 用户可在「高级设置 → 显示运行环境选择」中为会话指定环境。会话 `sandboxProfileId` 非空时,它优先于 Main Bot 的选择,工具描述也会告诉 Main Bot 不要再选。 +会话没有指定环境时,Main Bot 按「设置 → AI 助手 → 对话工作区」里本轮发言人倾向的沙箱类型(`workspaceDriver`:`docker`、`native`,留空由 Agent 选择)挑选:工具描述把这一类沙箱排在可选列表前面,并告诉 Main Bot 没有特殊要求时用其中第一个(Docker 优先 `generic-docker`);Main Bot 不传 `sandboxProfileId` 新开工作区时也用它。任务需要的语言或工具链只有其他环境具备时,Main Bot 仍可以换。没有对应类型的可用沙箱时,退回默认的「拿不准用 generic-docker」。 + 项目会话在入口统一校验项目访问权限。所有具备访问权限的成员(包括 viewer)都拥有同一会话的完整操作权限,可以继续讨论、编辑用户消息、停止任意成员发起的回复、选择运行环境、使用工作区和浏览器工具,以及归档或删除普通项目会话。内部不再按会话创建者、本轮发起人或项目编辑角色二次限制。会话的存储归属保持稳定,工作区绑定和历史对所有参与者一致;模型调用、Git 推送与 PR 仍使用**当前这一轮发言人**的个人凭据。 ## Git 凭据 @@ -38,17 +40,28 @@ 已关联 SOP 的任务会话里,SOP 执行中工作区只读;Main Bot 用 `runs_pause` 或 `runs_cancel` 停下 SOP 后才进入工作区模式(`workbench_workspace_open` 返回 `handoff=false` 时会提示这一点)。SOP 的交付由它自己的交付节点完成。 -对话工作区创建时冻结完整沙箱、Dockerfile 和环境定义,之后不再改变环境;换环境就是切到另一个工作区。准备工作区失败时,本次新建的工作区会被取消并解绑,会话回到之前的工作区,不会卡在一个打不开的工作区上。 +对话工作区创建时冻结完整沙箱(连同它的 Dockerfile 和环境变量),之后不再改变环境;换环境就是切到另一个工作区。准备工作区失败时,本次新建的工作区会被取消并解绑,会话回到之前的工作区,不会卡在一个打不开的工作区上。 ## Native 沙箱 -会话工作区可以使用 native 沙箱(Linux 上解析为 bwrap,macOS 上解析为 seatbelt): +会话工作区可以使用 native 沙箱(Linux 上解析为 bwrap,macOS 上解析为 seatbelt)。native 沙箱只有环境变量,没有安装脚本:命令使用执行机器上已安装的语言和工具,需要的设置(如 `JAVA_HOME`、代理)写进沙箱的环境变量。它不限定执行位置,用户的执行机器、云端 Runner 和平台本机都可以运行。 - **Linux (`bwrap`)**:与 Docker 布局一致:CLI 的 HOME 是 `<会话根>/home`,cwd 是 `<会话根>/ws`(挂的是运行工作区),审批钩子文件只读挂载;宿主文件系统其余部分只读,网络与宿主的 Docker 守护进程保持可达(可以在工作区里构建镜像、启动容器)。CLI 使用执行机器自己安装的版本。bwrap 需要创建 user/pid 命名空间并挂载 `/proc`,平台运行在默认权限的容器里(Compose 部署)时做不到:平台镜像不带 bwrap,即使装上,不开特权容器也建不了命名空间。Compose 部署请用 Docker 沙箱;要用 Linux native 沙箱,在原生安装的平台或执行机器(Runner)上运行。 - **macOS (`seatbelt`)**:macOS 没有每进程挂载命名空间,`seatbelt` 沙箱保留 HOME 为 `<会话根>/home`,工作区模式下 cwd 直接指向运行工作区目录(不重映射到 `<会话根>/ws`)。`seatbelt` 策略放开运行工作区、临时目录与 `<会话根>/home` 写入,并在最后追加审批钩子及其父目录的 `file-write*` 拒绝规则以防止篡改或改名替换;宿主其余路径保持只读,回环端口(工具中继、本机浏览器 CDP)与本机网络/Docker 保持可达;未显式设置 `DOCKER_HOST` / `DOCKER_CONFIG` 时自动解析宿主当前 Docker context 端点注入 `DOCKER_HOST`,以便在隔离 HOME 下使用 Colima、OrbStack 或 Docker Desktop 等守护进程。CLI 使用执行机器自己安装的版本。 Docker 与 bwrap 下两种模式的 CLI 都在 `<会话根>/ws` 运行(工作区模式下这里挂的是运行工作区),按 cwd 存放原生会话的 CLI(如 Claude Code、CodeBuddy)进出工作区、换环境都能续接。seatbelt 下由于平台模式与工作区模式的 cwd 不同,或任一环境原生日志确实不可用时,平台在当前阶段用完整对话上下文新建原生会话继续(`cli.resume_fallback`),每个阶段最多一次,并告诉新会话当前所处的模式。 +## 仓库缓存 + +每台执行机器(Runner 或平台本机)在自己的工作区根目录下按仓库记录 ID 维护裸仓库缓存 `.repository-cache/<仓库 id>.git`,native 工作区的仓库都从这里共享克隆,不重复下载: + +- **刷新**:在沙箱外进行,按仓库加文件锁,`git fetch --prune --force` 同步远端的分支和标签,认证沿用这次检出的 Git 凭据。缓存从不 gc,借用它对象的克隆不会丢对象。缓存损坏时整份重建。 +- **SOP 检出**:native 沙箱里的 SOP 先刷新缓存,再 `git clone --shared` 到工作区,origin 改回仓库地址,之后的建分支、提交和推送与完整克隆相同;缓存不可用时退回完整克隆。Docker 沙箱照旧完整克隆,因为容器里看不到宿主机上的缓存路径。Runner 0.12.0 起支持,旧 Runner 照旧完整克隆。 +- **对话工作区**:打开时仍是空目录。平台在打开时让执行机器在后台预热项目仓库的缓存(同一份缓存 5 分钟内最多一次)。每轮发给 Agent 的仓库清单前附一段说明:先从 `$LOOPFORGE_REPOSITORY_CACHE/<仓库 id>.git` `git clone --shared`,再 `git remote set-url origin `;缓存不存在时照常 clone。缓存目录在沙箱里只读。 +- **快照与删除**:保存工作区快照前,平台把共享克隆借用的对象复制进来(`git repack -a -d` 后删除 alternates),快照在没有这份缓存的机器上也能恢复。删除工作区只删除工作区目录,缓存留在机器上供之后使用。 + +local 沙箱类型已移除。`migrations/041_native_sandbox_inline_assets.sql` 把现有 local 沙箱改成 native(丢弃绑定的执行机器、基础目录和仓库路径),删除环境安装脚本和 native 沙箱环境变量里的 `PATH`,并把引用旧 local 沙箱的内置 SOP 改到 `generic-docker`。现有部署在启动新版本前手动执行此迁移。尚未迁移的 local 行读出时按 native 处理;冻结了 local 沙箱的旧运行会提示改用 native 后重新发起。 + `PUT /api/assistant/sessions/{id}/sandbox` 接受 `{ "sandboxProfileId": "id 或空字符串" }`,具备项目访问权限的会话参与者均可调用;生成期间和任务会话拒绝变更。已有工作区不受影响,新选择只用于之后新开的工作区。普通会话创建时也可以提交 `sandboxProfileId`,后续普通会话保存不能覆盖已保存的选择或伪造工作区绑定。 对话工作区使用独立的 `Run.kind=workspace` 和 `conversation-workspace` 标识,不参与 SOP 调度或占用 SOP 配额;继续复用 Runner、沙箱、Git、终端、快照、租约和空闲回收。API 与 Runner 需一起升级,旧 Runner 对新工作区请求会收到明确的版本要求。 @@ -69,7 +82,7 @@ Docker 与 bwrap 下两种模式的 CLI 都在 `<会话根>/ws` 运行(工作 ## 界面与样式 -环境选择默认隐藏,普通用户由 Main Bot 自动选择环境。技术人员通过「+ → 高级设置 → 显示运行环境选择」开启;显示偏好按用户保存在当前浏览器,隐藏入口不改变已选环境或已有工作区。开启后,环境选择与项目选择并排,复用同一个 `SelectMenu`,使用相同的搜索、选中态和弹出方向规则。菜单底部的「新增沙箱」打开当前项目的创建页,并默认选择 Docker;返回工作台后重新读取环境目录。普通对话随时可以改选环境,只影响之后新开的工作区;任务会话只展示任务环境。 +环境选择默认隐藏,普通用户由 Main Bot 自动选择环境。技术人员通过「+ → 高级设置 → 显示运行环境选择」开启;显示偏好按用户保存在当前浏览器,隐藏入口不改变已选环境或已有工作区。开启后,环境选择与项目选择并排,复用同一个 `SelectMenu`,使用相同的搜索、选中态和弹出方向规则。菜单按 Docker、native 分组排列,每项下方注明沙箱类型。菜单底部的「新增沙箱」打开当前项目的创建页,并默认选择 Docker;返回工作台后重新读取环境目录。普通对话随时可以改选环境,只影响之后新开的工作区;任务会话只展示任务环境。 旧协作样式中的全站主题、顶栏和页面框架规则归入 `web/app/frame.css`;仍由 SOP、角色等页面使用的模型控件样式归入 `web/assistant-models.css`。移除旧 UI 不改变其他页面的背景、搜索框或导航。 diff --git a/docs/deployment.md b/docs/deployment.md index e7a19902f..5239ef911 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -65,7 +65,7 @@ Run it as the installation owner, including an ordinary Linux user. If that user `compose.yaml` is the published-image stack and never builds: `./start.sh`, `scripts/install.sh` and a plain `docker compose --profile platform up` all pull the GHCR release pinned there (currently `ghcr.io/tencent/loopforge:0.4.1`). The pin matches the checkout's migrations and seeds, so check out a release tag when you install. Set `LOOPFORGE_IMAGE` (for example to an `@sha256:` digest) only to override it; a value saved in `.env` takes precedence over later pin changes. -To upgrade, update the checkout first, then refresh the containers: +To upgrade, update the checkout first, apply any required upgrade migrations, then refresh the containers. For the sandbox catalog upgrade, follow [Migrating existing sandboxes to inline assets](#migrating-existing-sandboxes-to-inline-assets). ```bash git fetch --tags && git checkout vX.Y.Z @@ -99,7 +99,9 @@ Enterprise authentication gateways can sign users in by header with `AGENTFLOW_T ### Docker sandboxes -The platform exposes a built-in default sandbox (`local`) even when the catalog SQL has not been installed. It is an in-memory fallback and does not insert database rows. An existing saved `local` profile takes priority, including its configured driver and environment. The default cannot be deleted; edit its configuration or create another profile to change how tasks run. The full installer still imports starter SOPs and the welcome project. +The platform exposes a built-in default sandbox (`generic-docker`, built from its own Dockerfile) even when the catalog SQL has not been installed. It is an in-memory fallback and does not insert database rows. An existing saved `generic-docker` profile takes priority, including its configured driver and environment. The default cannot be deleted; edit its configuration or create another profile to change how tasks run. SOPs that do not choose a sandbox run in it. The full installer still imports starter SOPs and the welcome project; the seeded `generic-docker` Dockerfile matches the platform image, so Compose sandboxes reuse `AGENTFLOW_ISOLATED_IMAGE` instead of building. Without the catalog SQL, the first run builds the built-in Dockerfile once. + +`native` sandboxes run on whichever machine executes the work, whether a user's execution machine, a cloud runner or the platform host, with that machine's own toolchains and only their environment variables; there are no install scripts. Each machine keeps a repository cache under its workspace root (`.repository-cache/.git`), refreshed outside the sandbox, and checks repositories of native workspaces out as `git clone --shared` from it; Docker sandboxes keep full clones. The Compose platform image has no bwrap, so run native work on Runners or a natively installed platform; see [conversation workspaces](conversation-workspaces.md#仓库缓存). The `local` sandbox type is removed: `migrations/041_native_sandbox_inline_assets.sql` turns existing local sandboxes into native ones and moves the built-in SOPs that used the old shared `local` profile to `generic-docker`. For native services running as an ordinary host user, default/root Docker images run with that service user's UID/GID so private workspaces remain accessible without relaxing their permissions or adding capabilities. Images that explicitly select a non-root user retain that identity; operators must arrange compatible bind-mount ownership for those images. @@ -107,7 +109,7 @@ The Compose deployment mounts the host Docker socket into the platform container Docker SOP nodes using a standard CLI executor first look for the CLI on the sandbox user's PATH. When it is missing, LoopForge uses a shared installation for the platform image where available or runs the same installer as conversation workspaces in the container. The install uses the sandbox's configured proxy, and later nodes in that container reuse the CLI. In-container installation requires a writable filesystem and access to the official package source. Read-only sandboxes can use a CLI from the image or the mounted toolchain. ZCode uses the official executable supplied by the image. -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. +Access to the Docker socket is equivalent to root on the host. Two safeguards follow from that: there is no unisolated sandbox type, so every task the platform runs itself is in a sandbox (the `AGENTFLOW_LOCAL_SANDBOX` setting is gone), 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 from `compose.yaml`, then connect a separate Docker-capable worker or execution machine for SOPs, including the welcome SOP, which now runs in `generic-docker`. ### Slow networks: clone and image build limits @@ -187,7 +189,7 @@ Configure provider credentials in the platform UI, not the host's global CLI con ## Observability schema -After the base tables have been created, run `bash scripts/install-schema-extensions.sh` for the Compose database. It installs absent `run_telemetry.adapter` and `run_logs.level` columns and their indexes from upstream migration `001_run_obs_generated_columns.sql`, then replays the `INSERT IGNORE` starter catalog and the built-in catalog rewrites from `031_generic_backend_openssh.sql`, `033_generic_sop_mr_node.sql`, and `038_generic_sop_host_credentials.sql` in that order. The rewrites are repeatable and apply only to matching defaults. The installer runs it before printing the address, and `./start.sh pull` runs it again after recreating containers, so an older data volume upgraded to a newer image picks up the columns the new code reads and the built-in SOP graphs the new code ships. Application startup does not run data migrations. +After the base tables have been created, run `bash scripts/install-schema-extensions.sh` for the Compose database. It installs absent `run_telemetry.adapter` and `run_logs.level` columns and their indexes from upstream migration `001_run_obs_generated_columns.sql`, then replays the `INSERT IGNORE` starter catalog, the built-in catalog rewrites from `033_generic_sop_mr_node.sql` and `038_generic_sop_host_credentials.sql`, in that order. The rewrites are repeatable and apply only to matching defaults. The installer runs it before printing the address, and `./start.sh pull` runs it again after recreating containers, so an older data volume upgraded to a newer image picks up the columns the new code reads and the built-in SOP graphs the new code ships. Application startup does not run data migrations. For an external MySQL deployment, review that migration and check column existence before applying its corresponding statements. Stored generated columns can rebuild large existing tables; schedule the operation accordingly. @@ -197,10 +199,23 @@ For an external MySQL deployment, review that migration and check column existen | Kind | Example | What an operator does | | --- | --- | --- | -| Already applied by the installer and `./start.sh pull` | `001_run_obs_generated_columns.sql`, `migrations/seed/*.sql`, `031_generic_backend_openssh.sql`, `033_generic_sop_mr_node.sql`, `038_generic_sop_host_credentials.sql` | Nothing; the script above covers it | -| Required upgrade migrations | `009_bot_interactions_utf8mb4.sql`, `036_git_http_credentials.sql` | Follow each migration's timing and prerequisites. [Migrating existing GitHub credentials](#migrating-existing-github-credentials) | +| Already applied by the installer and `./start.sh pull` | `001_run_obs_generated_columns.sql`, `migrations/seed/*.sql`, `033_generic_sop_mr_node.sql`, `038_generic_sop_host_credentials.sql` | Nothing; the script above covers it | +| Required upgrade migrations | `009_bot_interactions_utf8mb4.sql`, `036_git_http_credentials.sql`, `041_native_sandbox_inline_assets.sql` | Follow each migration's timing and prerequisites. [Migrating existing GitHub credentials](#migrating-existing-github-credentials) | | Optional backfills and rewrites of existing rows | `016_public_optional_repositories.sql`, `021_assistant_session_sources.sql` | Run them if the installation needs the converted rows | +### Migrating existing sandboxes to inline assets + +Check out the upgraded release and stop the old platform and any other processes using the database. Back up the database while MySQL remains running. For Compose installations, apply the migration with these commands. + +```bash +./start.sh stop platform +./start.sh migrate-sandboxes +``` + +Once the migration succeeds, start the upgraded platform with `./start.sh pull` for a published release or `./start.sh dev` for a source build. For external MySQL deployments, apply `migrations/041_native_sandbox_inline_assets.sql` directly before starting the upgraded platform. + +The migration copies Dockerfiles into sandboxes, converts local sandboxes to native, drops the legacy Dockerfile and environment tables and includes the built-in Dockerfile fix from `031_generic_backend_openssh.sql`. Fresh installations seed the new sandbox format directly. + ## Updating existing public SOPs Repository binding is optional for all built-in generic SOPs. To update the original catalog instructions on an existing installation, explicitly apply: diff --git a/e2e/README.md b/e2e/README.md index 57f3eb818..96deff496 100644 --- a/e2e/README.md +++ b/e2e/README.md @@ -16,7 +16,7 @@ export AGENTFLOW_E2E_BASE=http://127.0.0.1:8090 ### 用当前代码跑 -要验证本地还没合并的改动,用 `local.sh`:它用当前检出的代码编译并起一个临时平台,自带 MySQL 容器、测试用户和 Token、`generic-docker`/`local` 沙箱,以及一个本机裸仓库(给需要代码仓库的用例用),跑完全部清理。 +要验证本地还没合并的改动,用 `local.sh`:它用当前检出的代码编译并起一个临时平台,自带 MySQL 容器、测试用户和 Token、`generic-docker` 沙箱(`e2e-native` 由用例自动创建),以及一个本机裸仓库(给需要代码仓库的用例用),跑完全部清理。 ```bash ./local.sh # 全部 API 用例 @@ -37,7 +37,7 @@ AGENTFLOW_E2E_CODEBUDDY_API_KEY=ck_... ./local.sh api/40-model.test.mjs # 带 | `AGENTFLOW_E2E_CLI_KEY` | 本地实测时所选 CLI 的个人凭据 | | `AGENTFLOW_E2E_CLI_BASE_URL` | 本地实测可选的自定义模型网关 | | `AGENTFLOW_E2E_EXECUTOR` | 执行器,默认 `codebuddy` | -| `AGENTFLOW_E2E_SANDBOX` | 沙箱,默认 `local`,仅对可信的验收任务使用 | +| `AGENTFLOW_E2E_SANDBOX` | SOP 用的沙箱,默认 `e2e-native`:测试项目里自动创建的 native 沙箱,脚本在部署机上隔离执行(Linux 需要 bubblewrap) | | `AGENTFLOW_E2E_MODEL_SANDBOX` | 真实模型用例使用的沙箱,镜像里要有执行器 CLI;默认同 `AGENTFLOW_E2E_SANDBOX` | | `AGENTFLOW_E2E_REPO_CLONE_URL` | 带代码仓库的用例克隆这个仓库(只读,不推送)。不设置就跳过这些用例;`local.sh` 会自动设成本机裸仓库 | | `AGENTFLOW_E2E_REPO_BRANCH` | 上面仓库的基线分支,默认 `main` | diff --git a/e2e/api/00-smoke.test.mjs b/e2e/api/00-smoke.test.mjs index 5aafbb1f5..ead359fc6 100644 --- a/e2e/api/00-smoke.test.mjs +++ b/e2e/api/00-smoke.test.mjs @@ -3,7 +3,7 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import { api, get, list } from '../lib/api.mjs'; -import { cfg } from '../lib/env.mjs'; +import { cfg, defaultSandbox } from '../lib/env.mjs'; test('health and public runner endpoints answer without auth', async () => { const health = await get('/api/health', { auth: false }); @@ -53,9 +53,8 @@ const readOnly = [ ['/api/skills', d => assert.ok(Array.isArray(list(d)))], ['/api/mcp-servers', d => assert.ok(Array.isArray(list(d)))], ['/api/mcp-market', d => assert.ok(d)], - ['/api/dockerfiles', d => assert.ok(Array.isArray(list(d)))], - ['/api/environments', d => assert.ok(Array.isArray(list(d)))], - ['/api/sandboxes', d => assert.ok(list(d).some(s => s.id === cfg.sandbox), `sandbox ${cfg.sandbox} missing`)], + // The default e2e sandbox is provisioned with the e2e project (ensureProject). + ['/api/sandboxes', d => assert.ok(cfg.sandbox === defaultSandbox || list(d).some(s => s.id === cfg.sandbox), `sandbox ${cfg.sandbox} missing`)], ['/api/repositories', d => assert.ok(Array.isArray(list(d)))], ['/api/issues', d => assert.ok(Array.isArray(list(d)))], ['/api/runs', d => assert.ok(Array.isArray(list(d)))], diff --git a/e2e/api/10-catalog.test.mjs b/e2e/api/10-catalog.test.mjs index 2c7de186f..cef83c10b 100644 --- a/e2e/api/10-catalog.test.mjs +++ b/e2e/api/10-catalog.test.mjs @@ -1,5 +1,5 @@ // Studio catalog lifecycles: rules, skills (+files), MCP servers (+files), -// Dockerfiles, environments, sandboxes, agents (+revisions/clone) and SOPs +// Sandboxes (a Dockerfile for docker, environment variables for native), agents (+revisions/clone) and SOPs // (+publish/revisions/clone/template adoption). Every object lives in the // dedicated e2e project and is deleted afterwards. import { test, before, after } from 'node:test'; @@ -94,29 +94,27 @@ test('MCP market lists installable servers', async () => { assert.ok(list(market).length > 0 || Object.keys(market).length > 0); }); -test('Dockerfile, environment and sandbox CRUD with reference protection', async () => { - const dockerfile = ids.dockerfile = uid('df'); - const environment = ids.environment = uid('env'); +test('sandbox CRUD stores its own Dockerfile, or only environment variables for native', async () => { const sandbox = ids.sandbox = uid('sbx'); - track(`dockerfile ${dockerfile}`, () => del(`/api/dockerfiles?id=${dockerfile}`)); - track(`environment ${environment}`, () => del(`/api/environments?id=${environment}`)); + const native = uid('sbx-native'); track(`sandbox ${sandbox}`, () => del(`/api/sandboxes?id=${sandbox}`)); + track(`sandbox ${native}`, () => del(`/api/sandboxes?id=${native}`)); - await put('/api/dockerfiles', { id: dockerfile, name: 'E2E 镜像', projectId: P, description: 'e2e', content: 'FROM alpine:3.20\n' }); - await api('PUT', '/api/dockerfiles', { id: uid('df-bad'), name: 'bad', projectId: P, content: '' }, { expect: 400 }); - await put('/api/environments', { id: environment, name: 'E2E 环境', projectId: P, description: 'e2e', variables: { E2E_FLAG: '1' }, pathEntries: ['bin'], installScript: 'echo ok' }); - await api('PUT', '/api/environments', { id: uid('env-bad'), name: 'bad', projectId: P, variables: { 'A=B': '1' } }, { expect: 400 }); - await put('/api/sandboxes', { id: sandbox, name: 'E2E 沙箱', projectId: P, driver: 'docker', dockerfileId: dockerfile, readOnlyRootFS: false }); + await put('/api/sandboxes', { id: sandbox, name: 'E2E 沙箱', projectId: P, driver: 'docker', dockerfile: { content: 'FROM alpine:3.20\n' }, readOnlyRootFS: false }); + await api('PUT', '/api/sandboxes', { id: uid('sbx-bad'), name: 'bad', projectId: P, driver: 'docker', dockerfile: { content: '' } }, { expect: 400 }); + await put('/api/sandboxes', { id: native, name: 'E2E 环境', projectId: P, driver: 'native', environment: { E2E_FLAG: '1' }, install: { script: 'echo ignored' } }); + await api('PUT', '/api/sandboxes', { id: uid('sbx-bad'), name: 'bad', projectId: P, driver: 'native', environment: { 'A=B': '1' } }, { expect: 400 }); + await api('PUT', '/api/sandboxes', { id: uid('sbx-bad'), name: 'bad', projectId: P, driver: 'local' }, { expect: 400 }); - assert.ok(list(await get('/api/dockerfiles')).some(d => d.id === dockerfile)); - assert.ok(list(await get('/api/environments')).some(e => e.id === environment)); - assert.equal(list(await get('/api/sandboxes')).find(s => s.id === sandbox)?.dockerfileId, dockerfile); + const saved = list(await get('/api/sandboxes')); + assert.equal(saved.find(s => s.id === sandbox)?.dockerfile?.content, 'FROM alpine:3.20\n'); + assert.deepEqual(saved.find(s => s.id === native)?.environment, { E2E_FLAG: '1' }); + assert.equal(saved.find(s => s.id === native)?.install, undefined); + await api('GET', '/api/dockerfiles', undefined, { expect: 404 }); + await api('GET', '/api/environments', undefined, { expect: 404 }); - // A Dockerfile referenced by a sandbox must not be deletable. - await api('DELETE', `/api/dockerfiles?id=${dockerfile}`, undefined, { expect: 409 }); // Built-in assets are protected. await api('DELETE', '/api/sandboxes?id=generic-docker', undefined, { expect: 409 }); - await api('DELETE', '/api/dockerfiles?id=generic-backend', undefined, { expect: 409 }); }); test('agent CRUD, revisions, restore and clone', async () => { diff --git a/e2e/api/35-runner-mode.test.mjs b/e2e/api/35-runner-mode.test.mjs index 31df7d6b2..bbab2db0a 100644 --- a/e2e/api/35-runner-mode.test.mjs +++ b/e2e/api/35-runner-mode.test.mjs @@ -18,12 +18,10 @@ const dir = mkdtempSync(join(tmpdir(), 'e2e-runner-')); let proc; let runnerId = ''; let previousDefault = ''; -let sandboxProfileId = cfg.sandbox; +const sandboxProfileId = cfg.sandbox; before(async () => { await ensureProject(); - const profiles = list(await get('/api/sandboxes')); - if (profiles.some(p => p.id === 'local')) sandboxProfileId = 'local'; previousDefault = (await get('/api/runners/default')).runnerId || ''; const binary = join(dir, 'agentflow-runner'); diff --git a/e2e/api/36-cloud-pool.test.mjs b/e2e/api/36-cloud-pool.test.mjs index 3a014f79b..97d7c18f6 100644 --- a/e2e/api/36-cloud-pool.test.mjs +++ b/e2e/api/36-cloud-pool.test.mjs @@ -1,11 +1,12 @@ // Runs without a personal execution machine: on deployments whose cloud // runner pool covers the e2e project they execute on the platform's builtin // runner, otherwise on the control-plane host. Either way the nodes of one -// run share a sandbox, so state left outside the workspace by one node is -// visible to the next. +// run share a sandbox, so state one node leaves in it is visible to the next. +// A native sandbox gives every command a private /tmp, so there the state is +// left in the workspace; a container keeps it in its /tmp. import { test, before, after } from 'node:test'; import assert from 'node:assert/strict'; -import { get, cleanup, ensureProject, waitRun, nodeStatus } from '../lib/api.mjs'; +import { get, list, cleanup, ensureProject, waitRun, nodeStatus } from '../lib/api.mjs'; import { cfg } from '../lib/env.mjs'; import { createWorkflow, script, startRun } from '../lib/fixtures.mjs'; @@ -17,7 +18,8 @@ before(async () => { after(cleanup); test('cloud path: nodes of one run share the sandbox and the run succeeds', async () => { - const marker = `/tmp/af-e2e-${Date.now()}`; + const sandbox = list(await get('/api/sandboxes')).find(s => s.id === cfg.sandbox); + const marker = `${sandbox?.driver === 'native' ? '.' : '/tmp/'}af-e2e-${Date.now()}`; const wf = await createWorkflow('cloud-shared-sandbox', [ script('first', `printf shared > ${marker} && printf 'first\\n' > first.md`, { artifactOutputs: [{ name: 'first', path: 'first.md', mediaType: 'text/markdown', required: true }], diff --git a/e2e/api/56-sandbox-preview.test.mjs b/e2e/api/56-sandbox-preview.test.mjs index e076666a5..31ab92ff1 100644 --- a/e2e/api/56-sandbox-preview.test.mjs +++ b/e2e/api/56-sandbox-preview.test.mjs @@ -8,11 +8,9 @@ before(ensureProject); after(cleanup); test('Docker sandbox: real container, shared state, environment and artifact handoff', {skip:process.env.AGENTFLOW_E2E_DOCKER!=='1',timeout:600_000},async()=>{ - const dockerfile=uid('docker-file'),sandbox=uid('docker-sandbox'); - track('Dockerfile',()=>del(`/api/dockerfiles?id=${dockerfile}`)); + const sandbox=uid('docker-sandbox'); track('Docker sandbox',()=>del(`/api/sandboxes?id=${sandbox}`)); - await put('/api/dockerfiles',{id:dockerfile,projectId:cfg.projectId,name:'E2E Docker execution',content:'FROM node:22-bookworm-slim\nWORKDIR /workspace\n'}); - await put('/api/sandboxes',{id:sandbox,projectId:cfg.projectId,name:'E2E container',driver:'docker',dockerfileId:dockerfile,environment:{E2E_SANDBOX_VALUE:'actual-container'}}); + await put('/api/sandboxes',{id:sandbox,projectId:cfg.projectId,name:'E2E container',driver:'docker',dockerfile:{content:'FROM node:22-bookworm-slim\nWORKDIR /workspace\n'},environment:{E2E_SANDBOX_VALUE:'actual-container'}}); const wf=await createWorkflow('docker-run',[ script('build',`test -f /.dockerenv && test "$E2E_SANDBOX_VALUE" = actual-container node -e "require('fs').writeFileSync('report.txt','docker-runtime-ok\\n')" diff --git a/e2e/cleanup.mjs b/e2e/cleanup.mjs index b371fd364..eaa77b051 100644 --- a/e2e/cleanup.mjs +++ b/e2e/cleanup.mjs @@ -58,8 +58,6 @@ await sweepCollection('skill', '/api/skills', item => ours(item) && !item.shared // mcp--project-

are the platform defaults, re-provisioned for every project. await sweepCollection('mcp server', '/api/mcp-servers', item => ours(item) && !item.shared && !/^mcp-\d+-project-/.test(item.id)); await sweepCollection('sandbox', '/api/sandboxes'); -await sweepCollection('environment', '/api/environments'); -await sweepCollection('dockerfile', '/api/dockerfiles'); // Repositories are deleted by query (DELETE /api/repositories?id=…). await sweepCollection('repository', '/api/repositories', ours, item => `/api/repositories?id=${encodeURIComponent(item.id)}`); // Runner-mode scenarios bind throwaway machines; a killed daemon cannot diff --git a/e2e/lib/api.mjs b/e2e/lib/api.mjs index 2c63af2c2..b85545b73 100644 --- a/e2e/lib/api.mjs +++ b/e2e/lib/api.mjs @@ -1,5 +1,5 @@ import assert from 'node:assert/strict'; -import { cfg, requireToken } from './env.mjs'; +import { cfg, defaultSandbox, requireToken } from './env.mjs'; export class HTTPError extends Error { constructor(method, path, status, body) { @@ -121,9 +121,20 @@ export async function ensureProject() { if (project.ownerId !== ownerId) { project = await put('/api/projects', { ...project, ownerId }); } + await ensureSandbox(); return project; } +// ensureSandbox provisions the default SOP sandbox in the e2e project: a +// native sandbox, so scripts run on the deployment host without an image +// build (bubblewrap on Linux, sandbox-exec on macOS). A sandbox chosen with +// AGENTFLOW_E2E_SANDBOX must already exist. +async function ensureSandbox() { + if (cfg.sandbox !== defaultSandbox) return; + if (list(await get('/api/sandboxes')).some(s => s.id === defaultSandbox)) return; + await put('/api/sandboxes', { id: defaultSandbox, name: 'E2E 轻量沙箱', projectId: cfg.projectId, driver: 'native' }); +} + // tokenOwner resolves who the API token belongs to. There is no "whoami" for // tokens, so a knowledge review item (stamped with the caller's login) is // created and deleted at once; it never reaches the knowledge base. It has no diff --git a/e2e/lib/env.mjs b/e2e/lib/env.mjs index c3c20df56..b5377a8da 100644 --- a/e2e/lib/env.mjs +++ b/e2e/lib/env.mjs @@ -24,6 +24,9 @@ function flag(name, fallback) { const stamp = new Date().toISOString().replace(/[-:TZ.]/g, '').slice(2, 14); +// ensureProject provisions this native sandbox for SOP tests. +export const defaultSandbox = 'e2e-native'; + export const cfg = { base: resolveBase(), token: (process.env.AGENTFLOW_E2E_TOKEN || (process.env.AGENTFLOW_E2E_TOKEN_FILE ? fs.readFileSync(process.env.AGENTFLOW_E2E_TOKEN_FILE,'utf8') : '')).trim(), @@ -40,7 +43,7 @@ export const cfg = { model: flag('AGENTFLOW_E2E_MODEL', false), executor: process.env.AGENTFLOW_E2E_EXECUTOR || 'codebuddy', modelID: process.env.AGENTFLOW_E2E_MODEL_ID || '', - sandbox: process.env.AGENTFLOW_E2E_SANDBOX || 'local', + sandbox: process.env.AGENTFLOW_E2E_SANDBOX || defaultSandbox, keep: flag('AGENTFLOW_E2E_KEEP', false), // Repository-bound scenarios clone this repository read-only; they never // push. Unset skips them. A local path works when the deployment runs on diff --git a/e2e/local.sh b/e2e/local.sh index 8244638d4..f4e97797e 100755 --- a/e2e/local.sh +++ b/e2e/local.sh @@ -22,7 +22,8 @@ # AGENTFLOW_E2E_LOCAL_MYSQL_CONTAINER MySQL container name (default # agentflow-e2e-local-mysql); set it when # several checkouts run the suite at once -# AGENTFLOW_E2E_MODEL_SANDBOX sandbox for model scenarios (default local: +# AGENTFLOW_E2E_MODEL_SANDBOX sandbox for model scenarios (default +# e2e-native, which uses the host's CLIs: # the seeded Docker image has no model CLI) # AGENTFLOW_E2E_KEEP=1 keep the platform, database and files; the # exports needed to rerun single files against @@ -152,9 +153,7 @@ api() { case "$code" in 2??) ;; *) echo "seed $1 $2 failed ($code): $(cat "$WORK/seed.out" 2>/dev/null)"; exit 1 ;; esac } api POST /api/projects '{"id":"e2e-auto","key":"E2E","name":"E2E 自动化测试(勿用)","color":"#8b5cf6","ownerId":900001}' -api PUT /api/dockerfiles '{"id":"generic-backend","name":"generic backend","projectId":"e2e-auto","content":"FROM python:3.12-slim\nRUN apt-get update && apt-get install -y --no-install-recommends git ca-certificates && rm -rf /var/lib/apt/lists/*\n"}' -api PUT /api/sandboxes '{"id":"generic-docker","name":"Generic Docker","projectId":"e2e-auto","driver":"docker","dockerfileId":"generic-backend","readOnlyRootFS":false}' -api PUT /api/sandboxes '{"id":"local","name":"Local","projectId":"e2e-auto","driver":"local"}' +api PUT /api/sandboxes '{"id":"generic-docker","name":"Generic Docker","projectId":"e2e-auto","driver":"docker","dockerfile":{"content":"FROM python:3.12-slim\nRUN apt-get update && apt-get install -y --no-install-recommends git ca-certificates && rm -rf /var/lib/apt/lists/*\n"},"readOnlyRootFS":false}' REPO="$WORK/repo" mkdir -p "$REPO/src" && git -C "$REPO/src" init -q -b main && @@ -165,7 +164,7 @@ mkdir -p "$REPO/src" && git -C "$REPO/src" init -q -b main && export AGENTFLOW_E2E_BASE=$BASE AGENTFLOW_E2E_TOKEN=$TOKEN AGENTFLOW_E2E_TOKEN_B=$TOKEN_B export AGENTFLOW_E2E_REPO_CLONE_URL="$REPO/remote.git" AGENTFLOW_E2E_REPO_BRANCH=main -export AGENTFLOW_E2E_MODEL_SANDBOX=${AGENTFLOW_E2E_MODEL_SANDBOX:-local} +export AGENTFLOW_E2E_MODEL_SANDBOX=${AGENTFLOW_E2E_MODEL_SANDBOX:-e2e-native} # A fresh database has no data-rich project to tour; tour the e2e project. export AGENTFLOW_E2E_VIEW_PROJECT=${AGENTFLOW_E2E_VIEW_PROJECT:-e2e-auto} if [ "${AGENTFLOW_E2E_KEEP:-0}" = 1 ]; then diff --git a/e2e/public/README.md b/e2e/public/README.md index a990e721b..eae09387c 100644 --- a/e2e/public/README.md +++ b/e2e/public/README.md @@ -15,7 +15,7 @@ The suite signs in through the real password form, checks preferences and editor Set `LOOPFORGE_TEST_URL`, `LOOPFORGE_TEST_USER` and `LOOPFORGE_TEST_PASSWORD` (or the protected `LOOPFORGE_TEST_PASSWORD_FILE`) to test another explicit acceptance installation. The welcome project/catalog must be installed. Screenshots and traces are saved under `e2e/test-results/public/`. -The broader upstream API/UI suites remain under `api/` and `ui/`. They use `AGENTFLOW_E2E_BASE` and `AGENTFLOW_E2E_TOKEN`. Their public defaults target localhost, local sandboxes, and disable paid model scenarios. Live knowledge/model/integration cases require operator configuration and report skips when unavailable. +The broader upstream API/UI suites remain under `api/` and `ui/`. They use `AGENTFLOW_E2E_BASE` and `AGENTFLOW_E2E_TOKEN`. Their public defaults target localhost, run SOPs in a native sandbox the suite creates in its project, and disable paid model scenarios. Live knowledge/model/integration cases require operator configuration and report skips when unavailable. `00-first-run.spec.mjs` covers what a brand-new user sees and only runs with `LOOPFORGE_FRESH_INSTALL=1` against an installation that has no accounts yet (for example right after `bash scripts/install.sh`). It creates the administrator through the browser using `LOOPFORGE_TEST_USER`/`LOOPFORGE_TEST_PASSWORD`, checks the onboarding checklist and missing-key notice, and signs up `LOOPFORGE_UNCONFIGURED_USER` as a regular user, so the remaining specs can run immediately afterwards. diff --git a/e2e/public/executors.spec.mjs b/e2e/public/executors.spec.mjs index bf19486f1..2e370784d 100644 --- a/e2e/public/executors.spec.mjs +++ b/e2e/public/executors.spec.mjs @@ -127,7 +127,7 @@ test('SOP readiness checks each role executor rather than always requiring CodeB for(const executor of ['codebuddy','codex','claude']){ const id=`e2e-provider-${executor}-${suffix}`;ids.push(id); expect((await page.request.put('/api/agents',{data:{id,projectId,name:id,executorId:executor,prompt:'Only perform an explicitly assigned task.'}})).ok()).toBe(true); - expect((await page.request.put('/api/workflows',{data:{id,projectId,name:id,status:'draft',sandboxProfileId:'local',nodes:[{id:'work',name:'Work',type:'agent',agentId:id,executorId:'codebuddy',position:{x:100,y:100}}],edges:[]}})).ok()).toBe(true); + expect((await page.request.put('/api/workflows',{data:{id,projectId,name:id,status:'draft',sandboxProfileId:'generic-docker',nodes:[{id:'work',name:'Work',type:'agent',agentId:id,executorId:'codebuddy',position:{x:100,y:100}}],edges:[]}})).ok()).toBe(true); } await page.reload();await switchProject(page,projectId); await openSettingsPage(page,'sops'); diff --git a/e2e/public/without-github.spec.mjs b/e2e/public/without-github.spec.mjs index 50d47cf87..89517aef5 100644 --- a/e2e/public/without-github.spec.mjs +++ b/e2e/public/without-github.spec.mjs @@ -104,7 +104,7 @@ test('a real Agent generates a document with a model key and no GitHub repositor expect(saved.ok()).toBe(true); const agent=await page.request.put('/api/agents',{data:{id:agentId,name:'E2E document writer without GitHub',projectId,executorId:'codebuddy',model:process.env.AGENTFLOW_E2E_MODEL_ID||process.env.LOOPFORGE_TEST_MODEL||'default',prompt:`Write report.md in the current workspace with a short three-item to-do plan and the literal marker ${marker}. Do not use Git, access the network, install dependencies or modify other files. Reply when done.`}}); expect(agent.ok()).toBe(true);agentSaved=true; - const workflow=await page.request.put('/api/workflows',{data:{id:workflowId,name:'E2E document without GitHub',projectId,status:'draft',revision:0,sandboxProfileId:'local',nodes:[ + const workflow=await page.request.put('/api/workflows',{data:{id:workflowId,name:'E2E document without GitHub',projectId,status:'draft',revision:0,sandboxProfileId:'generic-docker',nodes:[ {id:'write',name:'Write document',type:'agent',agentId,executorId:'codebuddy',maxAttempts:1,maxReworks:0,position:{x:100,y:100},artifactOutputs:[{name:'report',path:'report.md',mediaType:'text/markdown',required:true}]}, {id:'verify',name:'Verify document',type:'script',scriptLanguage:'shell',script:`grep -q '${marker}' report.md`,maxAttempts:1,maxReworks:0,position:{x:350,y:100}}, ],edges:[{id:'write-verify',source:'write',target:'verify',when:'success'}]}}); diff --git a/e2e/ui/01-views.spec.mjs b/e2e/ui/01-views.spec.mjs index 8ca50f72f..707784dd9 100644 --- a/e2e/ui/01-views.spec.mjs +++ b/e2e/ui/01-views.spec.mjs @@ -8,18 +8,18 @@ import { test, expect, watchErrors } from './fixtures.mjs'; const TITLES = { collaboration: 'AI 工作台', issues: '需求列表', aiSchedules: '定时任务', bots: '通道管理', assistant: 'AI 助手', runs: '运行记录', approvals: '待我确认', sops: '流程模板', flow: '流程设计', agents: '角色定义', mcp: '能力资产', rules: '能力资产', skills: '能力资产', - dockerfiles: '环境资产', environments: '环境资产', sandboxes: '环境资产', observability: '统计', projects: '项目配置', + sandboxes: '沙箱管理', observability: '统计', projects: '项目配置', platform: '平台管理', runners: '执行机器', settings: '个人配置', guide: '访问密钥', }; // Only offered for some roles; the app redirects otherwise. const CONDITIONAL = ['platform']; -const ASSET_VIEWS = ['rules', 'skills', 'dockerfiles', 'environments', 'sandboxes']; +const ASSET_VIEWS = ['rules', 'skills', 'sandboxes']; const RETIRED = ['metrics', 'knowledge', 'businessDomains', 'businessDomainManagement']; const projects = [process.env.AGENTFLOW_E2E_VIEW_PROJECT || 'welcome', null]; test('legacy routes land on their replacements', async ({ page }) => { const errors = watchErrors(page); - for (const [legacy, view] of [['dashboard', 'collaboration'], ['access', 'guide'], ['assets', 'dockerfiles'], ['management', 'settings'], ['playbooks', 'sops']]) { + for (const [legacy, view] of [['dashboard', 'collaboration'], ['access', 'guide'], ['assets', 'sandboxes'], ['dockerfiles', 'sandboxes'], ['environments', 'sandboxes'], ['management', 'settings'], ['playbooks', 'sops']]) { await page.goto(`/#/${legacy}`); await expect(page.locator('#pageTitle')).toHaveText(TITLES[view]); } @@ -56,14 +56,13 @@ test('the latest deep link wins while the platform is loading', async ({ page }) // SlidingTabs enhances each type-tab row and its rule forces display:flex, so // only a real browser shows whether the inactive group actually disappears. -test('merged asset pages show only their own type tabs', async ({ page }) => { +test('capability pages show their type tabs and 沙箱管理 shows none', async ({ page }) => { const errors = watchErrors(page); const visibleTabs = () => page.evaluate(() => [...document.querySelectorAll('[data-asset-type-tab]')] .filter(el => el.getClientRects().length).map(el => el.dataset.assetTypeTab)); const cases = [ ['mcp', ['mcp', 'rules', 'skills'], 'mcp'], ['rules', ['mcp', 'rules', 'skills'], 'rules'], - ['sandboxes', ['dockerfiles', 'environments', 'sandboxes'], 'sandboxes'], ['skills', ['mcp', 'rules', 'skills'], 'skills'], ]; for (const [view, tabs, active] of cases) { @@ -71,17 +70,12 @@ test('merged asset pages show only their own type tabs', async ({ page }) => { await expect(page.locator('#pageTitle')).toHaveText(TITLES[view]); await expect.poll(visibleTabs, { message: `${view} type tabs` }).toEqual(tabs); await expect(page.locator(`[data-asset-type-tab="${active}"]:visible`)).toHaveAttribute('aria-selected', 'true'); - const nav = view === 'sandboxes' ? 'dockerfiles' : 'mcp'; - await expect(page.locator(`.platform-sidebar .nav[data-view="${nav}"]`)).toHaveClass(/\bactive\b/); + await expect(page.locator('.platform-sidebar .nav[data-view="mcp"]')).toHaveClass(/\bactive\b/); } - // Clicking a tab switches the page and keeps the single sidebar entry selected. await page.goto('/#/sandboxes'); await expect(page.locator('#pageTitle')).toHaveText(TITLES.sandboxes); - await page.locator('#assetsView [data-asset-type-tab="environments"]:visible').click(); - await expect(page).toHaveURL(/#\/environments/); - await expect.poll(visibleTabs).toEqual(['dockerfiles', 'environments', 'sandboxes']); - await expect(page.locator('[data-asset-type-tab="environments"]:visible')).toHaveAttribute('aria-selected', 'true'); - await expect(page.locator('.platform-sidebar .nav[data-view="dockerfiles"]')).toHaveClass(/\bactive\b/); + await expect.poll(visibleTabs, { message: 'sandboxes type tabs' }).toEqual([]); + await expect(page.locator('.platform-sidebar .nav[data-view="sandboxes"]')).toHaveClass(/\bactive\b/); expect(errors).toEqual([]); }); diff --git a/go.mod b/go.mod index 2704c933f..74a2bac5f 100644 --- a/go.mod +++ b/go.mod @@ -12,10 +12,10 @@ require ( github.com/klauspost/compress v1.20.3 github.com/zalando/go-keyring v0.2.8 golang.org/x/crypto v0.58.0 - golang.org/x/net v0.62.0 golang.org/x/sys v0.49.0 gorm.io/driver/mysql v1.6.0 gorm.io/gorm v1.31.2 + mvdan.cc/sh/v3 v3.14.1 ) require ( @@ -51,6 +51,7 @@ require ( github.com/ugorji/go/codec v1.3.1 // indirect go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect golang.org/x/arch v0.22.0 // indirect + golang.org/x/net v0.62.0 // indirect golang.org/x/text v0.43.0 // indirect google.golang.org/protobuf v1.36.10 // indirect modernc.org/libc v1.22.5 // indirect diff --git a/go.sum b/go.sum index 6cc183153..f5a8f48bc 100644 --- a/go.sum +++ b/go.sum @@ -35,6 +35,8 @@ github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJn github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= github.com/go-playground/validator/v10 v10.30.1 h1:f3zDSN/zOma+w6+1Wswgd9fLkdwy06ntQJp0BBvFG0w= github.com/go-playground/validator/v10 v10.30.1/go.mod h1:oSuBIQzuJxL//3MelwSLD5hc2Tu889bF0Idm9Dg26cM= +github.com/go-quicktest/qt v1.102.0 h1:HSQxCeh5YZH3EL3W39ixjtyaEhcWSXQHtHnMBzSs474= +github.com/go-quicktest/qt v1.102.0/go.mod h1:p4lGIVX+8Wa6ZPNDvqcxq36XpUDLh42FLetFU7odllI= github.com/go-sql-driver/mysql v1.10.1 h1:arlSnNLq6a5yxGxV7qg9lF4j0C+KwD6NbQyKr9QL6ME= github.com/go-sql-driver/mysql v1.10.1/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk= github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4= @@ -62,6 +64,10 @@ github.com/klauspost/compress v1.20.3 h1:zWNoFqq/lSuYQRim3dUXlXeA0IqwuZGicdG5ZTf github.com/klauspost/compress v1.20.3/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y= github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= @@ -84,6 +90,8 @@ github.com/quic-go/quic-go v0.59.1/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRC github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/rogpeppe/go-internal v1.15.0 h1:D0RCU5rMAp+SpgkiNdrjfJ+LX4J1M32V2NeCY7EJ6hc= +github.com/rogpeppe/go-internal v1.15.0/go.mod h1:DrUVZyrJU+txYW5/1kwtXQSMFio52ZOxX7yM1VHvnxs= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= @@ -139,3 +147,5 @@ modernc.org/memory v1.5.0 h1:N+/8c5rE6EqugZwHii4IFsaJ7MUhoWX07J5tC/iI5Ds= modernc.org/memory v1.5.0/go.mod h1:PkUhL0Mugw21sHPeskwZW4D6VscE/GQJOnIpCnW6pSU= modernc.org/sqlite v1.23.1 h1:nrSBg4aRQQwq59JpvGEQ15tNxoO5pX/kUjcRNwSAGQM= modernc.org/sqlite v1.23.1/go.mod h1:OrDj17Mggn6MhE+iPbBNf7RGKODDE9NFT0f3EwDzJqk= +mvdan.cc/sh/v3 v3.14.1 h1:bXkhQWNHCs0KZEChF8hYS6FC+T2N9mUZLbQv9blditI= +mvdan.cc/sh/v3 v3.14.1/go.mod h1:syYCoFET8w9tvevxiXUtY8/ICrU+l26jHmhJDra3Vwo= diff --git a/internal/application/operations.go b/internal/application/operations.go index cd770c18c..d9c72f5f9 100644 --- a/internal/application/operations.go +++ b/internal/application/operations.go @@ -69,14 +69,8 @@ func PublicOperations() []Operation { {Name: "mcp_servers_import", Description: "Import external MCP server definitions from JSON", Method: "POST", Path: "/api/mcp-servers/import"}, {Name: "executors_list", Description: "List executor definitions", Method: "GET", Path: "/api/executors", ReadOnly: true}, {Name: "executor_models_list", Description: "List the selectable model IDs, default model and reasoning-effort levels of each built-in CLI. Use a listed id as an Agent's model.", Method: "GET", Path: "/api/executor-models", ReadOnly: true}, - {Name: "dockerfiles_list", Description: "List Dockerfile assets", Method: "GET", Path: "/api/dockerfiles", ReadOnly: true}, - {Name: "dockerfiles_save", Description: "Create or update a Dockerfile asset", Method: "PUT", Path: "/api/dockerfiles"}, - {Name: "dockerfiles_delete", Description: "Delete a Dockerfile that is not shared and not referenced by any sandbox", Method: "DELETE", Path: "/api/dockerfiles"}, - {Name: "environments_list", Description: "List environment assets", Method: "GET", Path: "/api/environments", ReadOnly: true}, - {Name: "environments_save", Description: "Create or update an environment asset", Method: "PUT", Path: "/api/environments"}, - {Name: "environments_delete", Description: "Delete an environment install script that is not shared and not referenced by any sandbox", Method: "DELETE", Path: "/api/environments"}, - {Name: "sandboxes_list", Description: "List sandbox profiles", Method: "GET", Path: "/api/sandboxes", ReadOnly: true}, - {Name: "sandboxes_save", Description: "Create or update a sandbox profile", Method: "PUT", Path: "/api/sandboxes"}, + {Name: "sandboxes_list", Description: "List sandbox profiles with their Dockerfile (docker) or install script (native)", Method: "GET", Path: "/api/sandboxes", ReadOnly: true}, + {Name: "sandboxes_save", Description: "Create or update a sandbox profile. A docker sandbox carries dockerfile {content, files}; a native sandbox carries only environment variables", Method: "PUT", Path: "/api/sandboxes"}, {Name: "sandboxes_delete", Description: "Delete a sandbox profile that is not shared and not referenced by any workflow", Method: "DELETE", Path: "/api/sandboxes"}, {Name: "workflows_list", Description: "List SOP workflow definitions. Query: projectId (that project's SOPs plus generic templates), q (match id/name/description). Always pass projectId when a project is known.", Method: "GET", Path: "/api/workflows", ReadOnly: true}, {Name: "workflows_save", Description: "Create or update an SOP workflow", Method: "PUT", Path: "/api/workflows"}, diff --git a/internal/domain/assets.go b/internal/domain/assets.go index a325dace8..4c993dd60 100644 --- a/internal/domain/assets.go +++ b/internal/domain/assets.go @@ -117,10 +117,11 @@ type AgentAssetBundle struct { MCPFiles map[string]map[string][]byte `json:"mcpFiles,omitempty"` } -// DockerfileDefinition is a Studio-managed build recipe. Content and Files are -// stored on the catalog row in MySQL, the same way EnvironmentDefinition stores -// install.sh. Docker sandboxes select one of these; the runtime materializes a -// temporary build context from the stored payload at sandbox initialization. +// DockerfileDefinition is the build recipe a runner spec carries for a docker +// sandbox, derived from the profile's Dockerfile (ID and Name are the +// sandbox's). The runtime materializes a temporary build context from it at +// sandbox initialization. Run snapshots frozen before the recipe moved into +// the sandbox carry the former catalog fields. type DockerfileDefinition struct { ID string `json:"id"` Name string `json:"name"` @@ -132,37 +133,71 @@ type DockerfileDefinition struct { UpdatedAt time.Time `json:"updatedAt"` } -// EnvironmentDefinition is a named execution toolchain for process sandboxes. -// InstallScript is stored on the environment asset and loaded from the catalog -// at sandbox init; it runs once with PREFIX set to the isolated environment root. -type EnvironmentDefinition struct { - ID string `json:"id"` - Name string `json:"name"` - ProjectID string `json:"projectId,omitempty"` - Shared bool `json:"shared,omitempty"` - Description string `json:"description"` - Variables map[string]string `json:"variables,omitempty"` - PathEntries []string `json:"pathEntries,omitempty"` - InstallScript string `json:"installScript,omitempty"` - UpdatedAt time.Time `json:"updatedAt"` -} - type SandboxProfile struct { ID string `json:"id"` Name string `json:"name"` ProjectID string `json:"projectId,omitempty"` Shared bool `json:"shared,omitempty"` - Driver string `json:"driver"` // local, native, docker (seatbelt / bwrap are resolved native values) - DockerfileID string `json:"dockerfileId,omitempty"` - EnvironmentID string `json:"environmentId,omitempty"` + Driver string `json:"driver"` // native, docker (seatbelt / bwrap are resolved native values) ReadOnlyRootFS bool `json:"readOnlyRootFS"` Environment map[string]string `json:"environment,omitempty"` + // Dockerfile is the image recipe of a docker sandbox. + Dockerfile *SandboxDockerfile `json:"dockerfile,omitempty"` + // DockerfileID names the recipe in runner specs (see RunnerSandbox); + // stored profiles leave it empty. + DockerfileID string `json:"dockerfileId,omitempty"` +} + +// SandboxDockerfile is a Dockerfile and the files of its build context. +type SandboxDockerfile struct { + Content string `json:"content"` + Files map[string]string `json:"files,omitempty"` +} + +// ValidateSandboxAssets checks the sandbox driver and the recipe it needs: +// docker requires a Dockerfile, native carries only environment variables. +func ValidateSandboxAssets(v SandboxProfile) error { + switch strings.TrimSpace(v.Driver) { + case SandboxDriverDocker, SandboxDriverNative, SandboxDriverSeatbelt, SandboxDriverBwrap: + case SandboxDriverLocal: + return fmt.Errorf("local 沙箱已移除,请改用 native 沙箱") + default: + return fmt.Errorf("不支持的沙箱类型 %q", v.Driver) + } + docker := strings.TrimSpace(v.Driver) == SandboxDriverDocker + switch { + case docker && (v.Dockerfile == nil || strings.TrimSpace(v.Dockerfile.Content) == ""): + return fmt.Errorf("Docker 沙箱需要 Dockerfile 内容") + case !docker && v.Dockerfile != nil: + return fmt.Errorf("只有 Docker 沙箱可以配置 Dockerfile") + } + if v.Dockerfile != nil { + if err := ValidateManagedFiles(v.Dockerfile.Files); err != nil { + return fmt.Errorf("构建上下文:%w", err) + } + } + return ValidateEnvironmentVariables(v.Environment) +} + +// RunnerSandbox is the runner spec of a stored profile: its Dockerfile +// becomes the recipe a runner builds, named after the sandbox. The spec's +// profile drops the embedded copy. +func RunnerSandbox(profile SandboxProfile) *RunnerSandboxSpec { + spec := &RunnerSandboxSpec{Profile: profile} + spec.Profile.Dockerfile = nil + if d := profile.Dockerfile; d != nil && strings.TrimSpace(d.Content) != "" { + spec.Profile.DockerfileID = profile.ID + spec.Dockerfile = &DockerfileDefinition{ID: profile.ID, Name: profile.Name, ProjectID: profile.ProjectID, Shared: profile.Shared, Content: d.Content, Files: d.Files} + } + return spec } -// Sandbox drivers. Profiles store local, native or docker; native is the OS +// Sandbox drivers. Profiles store native or docker; native is the OS // lightweight process sandbox and resolves on the executing machine to // seatbelt (macOS) or bwrap (Linux). seatbelt / bwrap remain valid resolved // values (runner task payloads, rows written before the native option). +// local is the runtime's unisolated driver for internal callers; no profile +// may store it. const ( SandboxDriverLocal = "local" SandboxDriverNative = "native" @@ -183,6 +218,15 @@ func ConversationSandboxDriver(driver string) bool { } } +// ValidateFrozenSandbox rejects the removed local driver in a sandbox frozen +// into a run before it was removed: the runtime would run it unisolated. +func ValidateFrozenSandbox(profile SandboxProfile) error { + if strings.TrimSpace(profile.Driver) == SandboxDriverLocal { + return fmt.Errorf("沙箱 %s 使用已移除的 local 类型,请改用 native 沙箱后重新发起", profile.ID) + } + return nil +} + // ResolveSandboxDriver maps native onto the lightweight sandbox of goos and // returns every other driver unchanged. An empty goos (a runner that never // reported its OS) leaves native for that machine to resolve itself. @@ -203,34 +247,6 @@ func ResolveSandboxDriver(driver, goos string) (string, error) { } } -func ValidateDockerfile(v DockerfileDefinition) error { - if strings.TrimSpace(v.ID) == "" || strings.TrimSpace(v.Name) == "" { - return fmt.Errorf("Dockerfile 需要 id 和 name") - } - if strings.TrimSpace(v.Content) == "" { - return fmt.Errorf("Dockerfile 内容不能为空") - } - return ValidateManagedFiles(v.Files) -} - -func ValidateEnvironment(v EnvironmentDefinition) error { - if strings.TrimSpace(v.ID) == "" || strings.TrimSpace(v.Name) == "" { - return fmt.Errorf("环境需要 id 和 name") - } - if err := ValidateEnvironmentVariables(v.Variables); err != nil { - return err - } - for _, entry := range v.PathEntries { - if err := ValidateRelativeFilePath(entry); err != nil { - return fmt.Errorf("pathEntries: %w", err) - } - } - if strings.ContainsRune(v.InstallScript, '\x00') { - return fmt.Errorf("install.sh 不能包含 NUL") - } - return nil -} - func ValidateEnvironmentVariables(values map[string]string) error { for key, value := range values { if key == "" || strings.ContainsAny(key, "=\x00") { diff --git a/internal/domain/assets_test.go b/internal/domain/assets_test.go index 1e237b4ae..c3d2d25d5 100644 --- a/internal/domain/assets_test.go +++ b/internal/domain/assets_test.go @@ -2,30 +2,59 @@ package domain import "testing" -func TestValidateDockerfile(t *testing.T) { - if err := ValidateDockerfile(DockerfileDefinition{ID: "runtime", Name: "Runtime"}); err == nil { - t.Fatal("empty dockerfile content should be rejected") +func TestValidateSandboxAssets(t *testing.T) { + docker := func(d *SandboxDockerfile) SandboxProfile { + return SandboxProfile{ID: "box", Driver: SandboxDriverDocker, Dockerfile: d} } - if err := ValidateDockerfile(DockerfileDefinition{ID: "runtime", Name: "Runtime", Content: "FROM debian", Files: map[string]string{"../escape": "x"}}); err == nil { - t.Fatal("path traversal in dockerfile files should be rejected") - } - if err := ValidateDockerfile(DockerfileDefinition{ID: "runtime", Name: "Runtime", Content: "FROM debian"}); err != nil { - t.Fatal(err) + for _, tc := range []struct { + name string + profile SandboxProfile + valid bool + }{ + {"docker", docker(&SandboxDockerfile{Content: "FROM debian", Files: map[string]string{"etc/a.conf": "x"}}), true}, + {"docker without dockerfile", docker(nil), false}, + {"docker blank dockerfile", docker(&SandboxDockerfile{Content: " "}), false}, + {"docker context escape", docker(&SandboxDockerfile{Content: "FROM debian", Files: map[string]string{"../escape": "x"}}), false}, + {"native", SandboxProfile{Driver: SandboxDriverNative, Environment: map[string]string{"PHP_VERSION": "8.3.0"}}, true}, + {"native with dockerfile", SandboxProfile{Driver: SandboxDriverNative, Dockerfile: &SandboxDockerfile{Content: "FROM x"}}, false}, + {"native bad variable", SandboxProfile{Driver: SandboxDriverNative, Environment: map[string]string{"BAD=NAME": "1"}}, false}, + {"local", SandboxProfile{Driver: SandboxDriverLocal}, false}, + {"unknown driver", SandboxProfile{Driver: "vm"}, false}, + } { + if err := ValidateSandboxAssets(tc.profile); (err == nil) != tc.valid { + t.Errorf("%s: err = %v, want valid %v", tc.name, err, tc.valid) + } } } -func TestValidateEnvironment(t *testing.T) { - if err := ValidateEnvironment(EnvironmentDefinition{ID: "php8", Name: "PHP 8", Variables: map[string]string{"BAD=NAME": "1"}}); err == nil { - t.Fatal("invalid environment variable name should be rejected") +func TestRunnerSandboxNamesTheRecipeAfterTheSandbox(t *testing.T) { + spec := RunnerSandbox(SandboxProfile{ID: "go", Name: "Go", ProjectID: "p", Driver: SandboxDriverDocker, Dockerfile: &SandboxDockerfile{Content: "FROM golang", Files: map[string]string{"a": "b"}}}) + if spec.Dockerfile == nil || spec.Dockerfile.ID != "go" || spec.Dockerfile.Name != "Go" || spec.Dockerfile.Content != "FROM golang" || spec.Dockerfile.Files["a"] != "b" || spec.Profile.DockerfileID != "go" { + t.Fatalf("docker spec = %+v", spec) } - if err := ValidateEnvironment(EnvironmentDefinition{ID: "php8", Name: "PHP 8", PathEntries: []string{"../bin"}}); err == nil { - t.Fatal("path traversal in pathEntries should be rejected") + if spec.Profile.Dockerfile != nil { + t.Fatalf("the spec profile must not carry the embedded recipe: %+v", spec.Profile) } - if err := ValidateEnvironment(EnvironmentDefinition{ID: "php8", Name: "PHP 8", Variables: map[string]string{"PHP_VERSION": "8.3.0"}, PathEntries: []string{"bin"}, InstallScript: "mkdir -p \"$PREFIX/bin\""}); err != nil { - t.Fatal(err) + if spec := RunnerSandbox(SandboxProfile{ID: "bare", Driver: SandboxDriverNative, Environment: map[string]string{"A": "1"}}); spec.Dockerfile != nil || spec.Profile.Environment["A"] != "1" { + t.Fatalf("a native sandbox = %+v", spec) } - if err := ValidateEnvironment(EnvironmentDefinition{ID: "php8", Name: "PHP 8", InstallScript: "bad\x00script"}); err == nil { - t.Fatal("NUL in install.sh should be rejected") +} + +func TestIsNativeWorkspace(t *testing.T) { + native := &RunnerSandboxSpec{Profile: SandboxProfile{Driver: SandboxDriverNative}} + for _, tc := range []struct { + run Run + want bool + }{ + {Run{Kind: RunKindWorkspace, WorkflowSnapshot: WorkflowDefinition{SandboxSnapshot: native}}, true}, + {Run{Kind: RunKindWorkspace, WorkflowSnapshot: WorkflowDefinition{SandboxSnapshot: &RunnerSandboxSpec{Profile: SandboxProfile{Driver: SandboxDriverBwrap}}}}, true}, + {Run{Kind: RunKindWorkspace, WorkflowSnapshot: WorkflowDefinition{SandboxSnapshot: &RunnerSandboxSpec{Profile: SandboxProfile{Driver: SandboxDriverDocker}}}}, false}, + {Run{Kind: RunKindWorkspace}, false}, + {Run{WorkflowSnapshot: WorkflowDefinition{SandboxSnapshot: native}}, false}, + } { + if got := tc.run.IsNativeWorkspace(); got != tc.want { + t.Errorf("IsNativeWorkspace(%+v) = %v", tc.run, got) + } } } diff --git a/internal/domain/assistant_preferences.go b/internal/domain/assistant_preferences.go index 234b52015..5af881186 100644 --- a/internal/domain/assistant_preferences.go +++ b/internal/domain/assistant_preferences.go @@ -38,11 +38,14 @@ type ApprovalReviewAPIConfig struct { // hands work to roles and SOPs more readily (off by default), extra rules // added to every turn, and optional "帮我批准" review model settings. // SteerOnSend interrupts a running reply when sending a message; the default -// queues it until the reply finishes. +// queues it until the reply finishes. WorkspaceDriver is the sandbox driver +// Main Bot prefers for conversation workspaces it opens. An empty value leaves +// the choice to the agent. type AssistantPreferences struct { ProactiveRoles bool `json:"proactiveRoles"` ProactiveSOPs bool `json:"proactiveSops"` SteerOnSend bool `json:"steerOnSend"` + WorkspaceDriver string `json:"workspaceDriver"` Instructions string `json:"instructions"` ApprovalReviewMode string `json:"approvalReviewMode,omitempty"` ApprovalReviewModel string `json:"approvalReviewModel,omitempty"` @@ -77,3 +80,13 @@ func (p AssistantPreferences) Sanitized() AssistantPreferences { } return out } + +// ValidAssistantWorkspaceDriver accepts the drivers a conversation workspace +// can prefer, and empty for no preference. +func ValidAssistantWorkspaceDriver(driver string) bool { + switch driver { + case "", SandboxDriverDocker, SandboxDriverNative: + return true + } + return false +} diff --git a/internal/domain/domain_cases_test.go b/internal/domain/domain_cases_test.go index 83badec12..2a2a054b1 100644 --- a/internal/domain/domain_cases_test.go +++ b/internal/domain/domain_cases_test.go @@ -13,13 +13,6 @@ func TestAssetValidationBranches(t *testing.T) { name string err error }{ - {"docker missing", ValidateDockerfile(DockerfileDefinition{})}, - {"docker content", ValidateDockerfile(DockerfileDefinition{ID: "d", Name: "d"})}, - {"docker path", ValidateDockerfile(DockerfileDefinition{ID: "d", Name: "d", Content: "FROM x", Files: map[string]string{"../x": "x"}})}, - {"env missing", ValidateEnvironment(EnvironmentDefinition{})}, - {"env variable", ValidateEnvironment(EnvironmentDefinition{ID: "e", Name: "e", Variables: map[string]string{"x=y": "z"}})}, - {"env path", ValidateEnvironment(EnvironmentDefinition{ID: "e", Name: "e", PathEntries: []string{"../x"}})}, - {"env nul", ValidateEnvironment(EnvironmentDefinition{ID: "e", Name: "e", InstallScript: "\x00"})}, {"skill size", ValidateSkillFileRefs([]SkillFileRef{{Path: "x", Size: SkillFileMaxBytes + 1}})}, } { if tc.err == nil { diff --git a/internal/domain/run.go b/internal/domain/run.go index 192fcb545..40a8c1957 100644 --- a/internal/domain/run.go +++ b/internal/domain/run.go @@ -61,6 +61,20 @@ const ConversationWorkspaceWorkflowID = "conversation-workspace" // IsWorkspace distinguishes an on-demand chat workspace from a scheduled SOP. func (r Run) IsWorkspace() bool { return r.Kind == RunKindWorkspace } +// IsNativeWorkspace identifies a conversation workspace in a native sandbox, +// whose Agent clones repositories from the execution machine's cache. +func (r Run) IsNativeWorkspace() bool { + snapshot := r.WorkflowSnapshot.SandboxSnapshot + if !r.IsWorkspace() || snapshot == nil { + return false + } + switch snapshot.Profile.Driver { + case SandboxDriverNative, SandboxDriverSeatbelt, SandboxDriverBwrap: + return true + } + return false +} + // IsPersonalWorkspace identifies a workspace whose access is scoped to its owner. func (r Run) IsPersonalWorkspace() bool { return r.IsWorkspace() && r.ExecutionContext.ProjectID == "" diff --git a/internal/domain/runner.go b/internal/domain/runner.go index 02f5e2475..aa5f4299b 100644 --- a/internal/domain/runner.go +++ b/internal/domain/runner.go @@ -148,6 +148,11 @@ func (r Runner) SupportsCodeBuddyBaseURL() bool { return versionAtLeast(r.RunnerVersion, RunnerVersionCodeBuddyBaseURL) } +// RunnerVersionRepositoryCache is the first runner that checks repositories +// of native workspaces out as shared clones of its repository cache and warms +// that cache when a conversation workspace opens. Older runners clone fully. +const RunnerVersionRepositoryCache = "0.12.0" + func (r Runner) SupportsSharedPush() bool { return versionAtLeast(r.RunnerVersion, RunnerVersionSharedPush) } @@ -441,7 +446,6 @@ type RunnerSandboxSpec struct { Requirements *RunnerSandboxRequirements `json:"requirements,omitempty"` Profile SandboxProfile `json:"profile"` Dockerfile *DockerfileDefinition `json:"dockerfile,omitempty"` - Environment *EnvironmentDefinition `json:"environment,omitempty"` } // PublicRunnerTask strips task-scoped credentials from management responses. @@ -568,6 +572,10 @@ type RunnerInvocation struct { // Repositories lists every repository the run touches (multi-repository // support). Each entry checks out into its Dir under the task workspace. Repositories []RunnerRepository `json:"repositories,omitempty"` + // CacheRepositories are only fetched into the runner's repository cache, + // never checked out: the repositories an Agent in a native conversation + // workspace may clone later. + CacheRepositories []RunnerRepository `json:"cacheRepositories,omitempty"` } // RunnerRepository describes the checkout a runner machine should create. @@ -619,6 +627,11 @@ func (inv *RunnerInvocation) GitSSHRemotes() []string { if len(inv.Repositories) == 0 && inv.Repository != nil && inv.Repository.UseSSH { remotes = append(remotes, inv.Repository.CloneURL) } + for _, repository := range inv.CacheRepositories { + if repository.UseSSH { + remotes = append(remotes, repository.CloneURL) + } + } } return remotes } diff --git a/internal/domain/sandbox_migration_test.go b/internal/domain/sandbox_migration_test.go index 6a4697d63..5ced9175c 100644 --- a/internal/domain/sandbox_migration_test.go +++ b/internal/domain/sandbox_migration_test.go @@ -8,12 +8,12 @@ import ( func TestWorkflowUnmarshalLiftsConsistentLegacyNodeSandbox(t *testing.T) { var workflow WorkflowDefinition - raw := []byte(`{"id":"legacy","nodes":[{"id":"a","sandboxProfileId":"local"},{"id":"b","sandboxProfileId":"local"}]}`) + raw := []byte(`{"id":"legacy","nodes":[{"id":"a","sandboxProfileId":"test-native"},{"id":"b","sandboxProfileId":"test-native"}]}`) if err := json.Unmarshal(raw, &workflow); err != nil { t.Fatal(err) } - if workflow.SandboxProfileID != "local" { - t.Fatalf("sandboxProfileId = %q, want local", workflow.SandboxProfileID) + if workflow.SandboxProfileID != "test-native" { + t.Fatalf("sandboxProfileId = %q, want test-native", workflow.SandboxProfileID) } marshaled, err := json.Marshal(workflow) if err != nil { @@ -26,7 +26,7 @@ func TestWorkflowUnmarshalLiftsConsistentLegacyNodeSandbox(t *testing.T) { func TestWorkflowUnmarshalRejectsConflictingLegacyNodeSandboxes(t *testing.T) { var workflow WorkflowDefinition - err := json.Unmarshal([]byte(`{"id":"legacy","nodes":[{"id":"a","sandboxProfileId":"local"},{"id":"b","sandboxProfileId":"container"}]}`), &workflow) + err := json.Unmarshal([]byte(`{"id":"legacy","nodes":[{"id":"a","sandboxProfileId":"test-native"},{"id":"b","sandboxProfileId":"container"}]}`), &workflow) if err == nil || !strings.Contains(err.Error(), "conflicting legacy node sandbox profiles") { t.Fatalf("expected explicit conflict, got %v", err) } diff --git a/internal/engine/align_test.go b/internal/engine/align_test.go index 391a93471..64649eb7c 100644 --- a/internal/engine/align_test.go +++ b/internal/engine/align_test.go @@ -18,7 +18,7 @@ func TestBaselineAlignRunKeepsConfiguredCLI(t *testing.T) { } t.Cleanup(store.Close) wf := domain.WorkflowDefinition{ - ID: BaselineAlignWorkflowID, Name: "Align", SandboxProfileID: "local", + ID: BaselineAlignWorkflowID, Name: "Align", SandboxProfileID: repo.TestNativeSandboxID, Nodes: []domain.WorkflowNode{{ID: "resolve", Type: "agent", AgentID: BaselineAlignAgentID}}, } if err := store.PutWorkflow(wf); err != nil { diff --git a/internal/engine/codebuddy_auth_test.go b/internal/engine/codebuddy_auth_test.go index a703c7a50..f9f8b4474 100644 --- a/internal/engine/codebuddy_auth_test.go +++ b/internal/engine/codebuddy_auth_test.go @@ -142,7 +142,7 @@ func TestSponsoredExecutorPinsModelAndExplains(t *testing.T) { t.Fatal(err) } defer st.Close() - wf := domain.WorkflowDefinition{ID: "sponsored", Name: "Sponsored", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "gate", Name: "Gate", Type: "approval", MaxAttempts: 1}}} + wf := domain.WorkflowDefinition{ID: "sponsored", Name: "Sponsored", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "gate", Name: "Gate", Type: "approval", MaxAttempts: 1}}} if err = st.PutWorkflow(wf); err != nil { t.Fatal(err) } diff --git a/internal/engine/control_recovery_cases_test.go b/internal/engine/control_recovery_cases_test.go index c2029b1b9..488bf8974 100644 --- a/internal/engine/control_recovery_cases_test.go +++ b/internal/engine/control_recovery_cases_test.go @@ -135,7 +135,7 @@ func TestRunRecoveryAndSchedulerBookkeeping(t *testing.T) { t.Fatalf("disabled recovery = %v", got) } e.executeRuns = true - wf := domain.WorkflowDefinition{ID: "recovery-wf", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "failed", Type: "agent"}}} + wf := domain.WorkflowDefinition{ID: "recovery-wf", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "failed", Type: "agent"}}} run := domain.Run{ID: "recover-failed", Status: "running", WorkflowSnapshot: wf, Nodes: map[string]*domain.NodeRun{"failed": {NodeID: "failed", Status: "failed"}}} if err := st.PutRun(run); err != nil { t.Fatal(err) diff --git a/internal/engine/conversation_workspace.go b/internal/engine/conversation_workspace.go index b656aaaf9..150f08229 100644 --- a/internal/engine/conversation_workspace.go +++ b/internal/engine/conversation_workspace.go @@ -159,6 +159,8 @@ func (e *Engine) MaterializeConversationWorkspace(ctx context.Context, id string ctx = e.withPreparationProgress(ctx, run.ID) ctx = withRunGitCredentials(ctx, credentials) ctx = gitwork.WithSSHKeys(e.withSSHKnownHosts(ctx), credentials.GitSSHKeys) + ctx = runtime.WithRepositoryCacheIn(ctx, env.Unwrap()) + e.warmRepositoryCaches(ctx, run) return env.prepareRepositoriesOnce(func() error { if err := prepareRepositories(ctx, env.Workspace(), run.RepositoryContexts()); err != nil { return explainGitAuthFailure(fmt.Errorf("repository checkout: %w", err), len(credentials.GitHTTPCredentials) > 0) diff --git a/internal/engine/conversation_workspace_control_test.go b/internal/engine/conversation_workspace_control_test.go index 7a019406d..fbcaf288f 100644 --- a/internal/engine/conversation_workspace_control_test.go +++ b/internal/engine/conversation_workspace_control_test.go @@ -16,7 +16,7 @@ import ( func controlLeaseRun(t *testing.T, e *Engine, id string, saved bool) string { t.Helper() - run := domain.Run{ID: id, Status: "failed", Generation: 1, ExecutionContext: domain.TelemetryContext{ProjectID: "p"}, WorkflowSnapshot: domain.WorkflowDefinition{ID: "control-lease", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "step", Type: "script", Script: "true", MaxAttempts: 1}}}, Nodes: map[string]*domain.NodeRun{"step": {NodeID: "step", Status: "failed", Attempt: 1}}} + run := domain.Run{ID: id, Status: "failed", Generation: 1, ExecutionContext: domain.TelemetryContext{ProjectID: "p"}, WorkflowSnapshot: domain.WorkflowDefinition{ID: "control-lease", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "step", Type: "script", Script: "true", MaxAttempts: 1}}}, Nodes: map[string]*domain.NodeRun{"step": {NodeID: "step", Status: "failed", Attempt: 1}}} if err := e.repo.PutRun(run); err != nil { t.Fatal(err) } diff --git a/internal/engine/conversation_workspace_progress_test.go b/internal/engine/conversation_workspace_progress_test.go index 339a0f96e..97837b71b 100644 --- a/internal/engine/conversation_workspace_progress_test.go +++ b/internal/engine/conversation_workspace_progress_test.go @@ -34,7 +34,7 @@ func putCloningWorkspace(t *testing.T) (*Engine, domain.Run) { e, s := newRecoveryEngine(t) run := domain.Run{ ID: "slow-clone-chat", Kind: domain.RunKindWorkspace, Status: "waiting", Nodes: map[string]*domain.NodeRun{}, - WorkflowSnapshot: domain.WorkflowDefinition{ID: domain.ConversationWorkspaceWorkflowID, SandboxProfileID: "local"}, + WorkflowSnapshot: domain.WorkflowDefinition{ID: domain.ConversationWorkspaceWorkflowID, SandboxProfileID: "test-native"}, ExecutionContext: domain.TelemetryContext{ProjectID: "platform"}, Repositories: []domain.RepositoryContext{{RepositoryID: "web", Name: "web", CloneURL: "https://git.example.invalid/team/web.git", BaseBranch: "main", WorkBranch: "feature/chat", WorkspaceDir: "web"}}, } diff --git a/internal/engine/conversation_workspace_test.go b/internal/engine/conversation_workspace_test.go index 216da4e10..1c176e9ba 100644 --- a/internal/engine/conversation_workspace_test.go +++ b/internal/engine/conversation_workspace_test.go @@ -357,7 +357,7 @@ func TestLegacyWorkspaceReplayAfterMainBotCreatedEmptyCheckpoint(t *testing.T) { t.Parallel() e, s := newRecoveryEngine(t) e.ConfigureExecution("test", "test", time.Minute, false) - wf := domain.WorkflowDefinition{ID: "legacy-replay", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "first", Type: "command", Command: "true"}, {ID: "second", Type: "command", Command: "true"}}, Edges: []domain.WorkflowEdge{{Source: "first", Target: "second", When: "success"}}} + wf := domain.WorkflowDefinition{ID: "legacy-replay", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "first", Type: "command", Command: "true"}, {ID: "second", Type: "command", Command: "true"}}, Edges: []domain.WorkflowEdge{{Source: "first", Target: "second", When: "success"}}} r := domain.Run{ID: "legacy-replay", Status: "succeeded", WorkflowID: wf.ID, WorkflowSnapshot: wf, WorkspaceCleanedAt: time.Now().UTC(), Nodes: map[string]*domain.NodeRun{"first": {NodeID: "first", Status: "succeeded", Attempt: 1, Output: "archived output"}, "second": {NodeID: "second", Status: "succeeded", Attempt: 1}}} if err := s.PutRun(r); err != nil { t.Fatal(err) @@ -422,7 +422,7 @@ func TestMaterializeRunnerConversationWorkspaceRequestsCheckout(t *testing.T) { } run := domain.Run{ ID: "chat-workspace", Kind: domain.RunKindWorkspace, Status: "waiting", Nodes: map[string]*domain.NodeRun{}, - WorkflowSnapshot: domain.WorkflowDefinition{ID: domain.ConversationWorkspaceWorkflowID, SandboxProfileID: "local"}, + WorkflowSnapshot: domain.WorkflowDefinition{ID: domain.ConversationWorkspaceWorkflowID, SandboxProfileID: "test-native"}, ExecutionContext: domain.TelemetryContext{ProjectID: "platform", ExecutionMode: domain.ExecutionModeRunner, ExecutionRunnerID: "chat-runner", RunnerWorkspaceLayout: domain.RunnerWorkspaceLayoutShared}, Repositories: []domain.RepositoryContext{{RepositoryID: "web", Name: "web", CloneURL: "https://git.example.com/team/web.git", BaseBranch: "main", WorkBranch: "feature/chat", WorkspaceDir: "web"}}, } diff --git a/internal/engine/core_cases_test.go b/internal/engine/core_cases_test.go index aea7f1a5d..57d16e696 100644 --- a/internal/engine/core_cases_test.go +++ b/internal/engine/core_cases_test.go @@ -28,7 +28,7 @@ func cvEEngine(t *testing.T) (*Engine, *repo.Store) { func TestWorkflowGraphValidationAndTraversal(t *testing.T) { valid := domain.WorkflowDefinition{ - ID: "cve-wf", SandboxProfileID: "local", + ID: "cve-wf", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "a", Type: "agent"}, {ID: "b", Type: "script", ScriptLanguage: "python", Script: "print(1)", ArtifactOutputs: []domain.ArtifactContract{{Name: "report", Path: "out/report.md"}}}, @@ -72,29 +72,29 @@ func TestWorkflowGraphValidationAndTraversal(t *testing.T) { cases := []domain.WorkflowDefinition{ {ID: "x", Nodes: valid.Nodes}, - {ID: "x", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "", Type: "agent"}}}, - {ID: "x", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "a", Type: "agent"}, {ID: "a", Type: "agent"}}}, - {ID: "x", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "a", Type: "sop"}}}, - {ID: "x", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "a", Type: "sop", SOPWorkflowID: "x"}}}, - {ID: "x", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "a", Type: "script", ScriptLanguage: "ruby", Script: "x"}}}, - {ID: "x", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "a", Type: "script"}}}, - {ID: "x", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "a", Type: "bad"}}}, - {ID: "x", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "a", Type: "agent", OnFailure: "bad"}}}, - {ID: "x", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "a", Type: "agent", ExecutionScope: "bad"}}}, - {ID: "x", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "a", Type: "agent", RetryStrategy: "bad"}}}, - {ID: "x", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "a", Type: "agent", ArtifactOutputs: []domain.ArtifactContract{{Name: "", Path: "../bad"}}}}}, - {ID: "x", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "a", Type: "agent", ArtifactOutputs: []domain.ArtifactContract{{Name: "same", Path: "a"}, {Name: "same", Path: "b"}}}}}, - {ID: "x", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "a", Type: "agent", RejectTo: "missing"}}}, - {ID: "x", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "a", Type: "agent", OnFailure: "reject"}}}, - {ID: "x", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "a", Type: "agent"}}, Edges: []domain.WorkflowEdge{{Source: "a", Target: "missing"}}}, - {ID: "x", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "a", Type: "agent"}, {ID: "b", Type: "agent"}}, Edges: []domain.WorkflowEdge{{Source: "a", Target: "b"}, {Source: "b", Target: "a"}}}, + {ID: "x", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "", Type: "agent"}}}, + {ID: "x", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "a", Type: "agent"}, {ID: "a", Type: "agent"}}}, + {ID: "x", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "a", Type: "sop"}}}, + {ID: "x", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "a", Type: "sop", SOPWorkflowID: "x"}}}, + {ID: "x", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "a", Type: "script", ScriptLanguage: "ruby", Script: "x"}}}, + {ID: "x", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "a", Type: "script"}}}, + {ID: "x", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "a", Type: "bad"}}}, + {ID: "x", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "a", Type: "agent", OnFailure: "bad"}}}, + {ID: "x", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "a", Type: "agent", ExecutionScope: "bad"}}}, + {ID: "x", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "a", Type: "agent", RetryStrategy: "bad"}}}, + {ID: "x", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "a", Type: "agent", ArtifactOutputs: []domain.ArtifactContract{{Name: "", Path: "../bad"}}}}}, + {ID: "x", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "a", Type: "agent", ArtifactOutputs: []domain.ArtifactContract{{Name: "same", Path: "a"}, {Name: "same", Path: "b"}}}}}, + {ID: "x", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "a", Type: "agent", RejectTo: "missing"}}}, + {ID: "x", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "a", Type: "agent", OnFailure: "reject"}}}, + {ID: "x", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "a", Type: "agent"}}, Edges: []domain.WorkflowEdge{{Source: "a", Target: "missing"}}}, + {ID: "x", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "a", Type: "agent"}, {ID: "b", Type: "agent"}}, Edges: []domain.WorkflowEdge{{Source: "a", Target: "b"}, {Source: "b", Target: "a"}}}, } for i, wf := range cases { if err := validate(wf); err == nil { t.Fatalf("case %d accepted: %+v", i, wf) } } - command := domain.WorkflowDefinition{ID: "cmd", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "run", Type: "command", Command: "echo ok"}}} + command := domain.WorkflowDefinition{ID: "cmd", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "run", Type: "command", Command: "echo ok"}}} if err := validate(command); err != nil { t.Fatal(err) } @@ -361,21 +361,21 @@ func TestWorkspaceTransportAndBrowserRunnerPaths(t *testing.T) { } func TestSandboxSnapshotsPathsAndMisc(t *testing.T) { - e, st := cvEEngine(t) + e, _ := cvEEngine(t) profile := domain.SandboxProfile{ID: "bad", Driver: "docker"} - if _, err := resolveSandboxResources(st, profile); err == nil { + if _, err := resolveSandbox(profile); err == nil { t.Fatal("docker without file accepted") } - profile.DockerfileID = "missing" - if _, err := resolveSandboxResources(st, profile); err == nil { - t.Fatal("missing dockerfile accepted") + profile.Dockerfile = &domain.SandboxDockerfile{Content: " "} + if _, err := resolveSandbox(profile); err == nil { + t.Fatal("blank dockerfile accepted") } profile = domain.SandboxProfile{ID: "local", Driver: "local"} - resources, err := resolveSandboxResources(st, profile) + spec, err := resolveSandbox(profile) if err != nil { t.Fatal(err) } - snapshot := resolvedSandboxSnapshot(profile, resources) + snapshot := resolvedSandboxSnapshot(spec.Profile, sandboxResourcesFromSnapshot(spec)) if snapshot.Profile.ID != "local" { t.Fatalf("snapshot = %+v", snapshot) } @@ -409,7 +409,7 @@ func TestSandboxSnapshotsPathsAndMisc(t *testing.T) { func TestObservationIngressWorkspaceStatusAndStateTransitions(t *testing.T) { e, st := cvEEngine(t) wf := domain.WorkflowDefinition{ - ID: "cve-state-wf", SandboxProfileID: "local", + ID: "cve-state-wf", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "script", Name: "Script", Type: "script", Script: "echo ok"}, {ID: "gate", Name: "Gate", Type: "approval"}}, Edges: []domain.WorkflowEdge{{Source: "script", Target: "gate"}}, } diff --git a/internal/engine/engine_test.go b/internal/engine/engine_test.go index 57d1b8aca..38a2252da 100644 --- a/internal/engine/engine_test.go +++ b/internal/engine/engine_test.go @@ -22,7 +22,10 @@ func TestMain(m *testing.M) { if runtime.RunMCPCallCLI(os.Args[1:]) || runtime.RunGitHelperCLI(os.Args[1:]) { return } - os.Exit(m.Run()) + cleanup := repo.UseSandboxVisibleTempDir() + code := m.Run() + cleanup() + os.Exit(code) } func putGateTestAgent(t *testing.T, s *repo.Store, id string, gates []domain.VerificationGate) { @@ -453,8 +456,8 @@ func TestProjectSandboxNeverCrossesProjectBoundary(t *testing.T) { } t.Cleanup(func() { st.Close() }) for _, profile := range []domain.SandboxProfile{ - {ID: "local", Name: "Other local", ProjectID: "other", Driver: "local"}, - {ID: "mine", Name: "Mine", ProjectID: "project", Driver: "local"}, + {ID: "local", Name: "Other local", ProjectID: "other", Driver: "native"}, + {ID: "mine", Name: "Mine", ProjectID: "project", Driver: "native"}, } { if err := st.PutSandbox(profile); err != nil { t.Fatal(err) @@ -474,7 +477,7 @@ func TestShellAndPythonScriptNodesExecuteInOrder(t *testing.T) { } defer s.Close() wf := domain.WorkflowDefinition{ - ID: "script-languages", Name: "Script languages", SandboxProfileID: "local", + ID: "script-languages", Name: "Script languages", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "shell", Name: "Shell", Type: "script", ScriptLanguage: "shell", Script: "printf shell > value.txt", MaxAttempts: 1}, {ID: "python", Name: "Python", Type: "script", ScriptLanguage: "python", Script: "from pathlib import Path\nassert Path('value.txt').read_text() == 'shell'\nPath('python.txt').write_text('ok')", MaxAttempts: 1, ArtifactOutputs: []domain.ArtifactContract{{Name: "python", Path: "python.txt", Required: true}}}, @@ -523,7 +526,7 @@ func TestScriptNodeCanCallProjectMCP(t *testing.T) { t.Fatal(err) } wf := domain.WorkflowDefinition{ - ID: "mcp-script", Name: "MCP script", SandboxProfileID: "local", ProjectID: "dns", + ID: "mcp-script", Name: "MCP script", SandboxProfileID: "test-native", ProjectID: "dns", Nodes: []domain.WorkflowNode{{ ID: "list", Name: "List", Type: "script", ScriptLanguage: "shell", Script: "agentflow mcp list > mcp.json", MaxAttempts: 1, @@ -576,7 +579,7 @@ func TestVerificationGateCanCallProjectMCP(t *testing.T) { } putGateTestAgent(t, s, "mcp-validator", []domain.VerificationGate{{ID: "mcp", Name: "mcp", Mode: "command", Required: true, ExecutionScope: domain.ExecutionScopeRun, Commands: []string{"agentflow mcp list > gate-mcp.json"}}}) wf := domain.WorkflowDefinition{ - ID: "mcp-gate", Name: "MCP gate", SandboxProfileID: "local", ProjectID: "dns", + ID: "mcp-gate", Name: "MCP gate", SandboxProfileID: "test-native", ProjectID: "dns", Nodes: []domain.WorkflowNode{ {ID: "prep", Name: "Prep", Type: "command", Command: "printf ready > evidence.txt", MaxAttempts: 1}, {ID: "validate", Name: "Validate", Type: "agent", AgentID: "mcp-validator", ExecutorID: "mock", MaxAttempts: 1, @@ -1080,7 +1083,7 @@ func TestStartUsesFreshWorkBranchPerSOP(t *testing.T) { t.Fatal(err) } e := New(s, runtime.NewManager(t.TempDir())) - wf := domain.WorkflowDefinition{ID: "branch-test", Name: "Branch test", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "gate", Name: "Gate", Type: "approval", MaxAttempts: 1}}} + wf := domain.WorkflowDefinition{ID: "branch-test", Name: "Branch test", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "gate", Name: "Gate", Type: "approval", MaxAttempts: 1}}} if err := s.PutWorkflow(wf); err != nil { t.Fatal(err) } @@ -1423,7 +1426,7 @@ func TestHumanGateFailureWaitsForApprove(t *testing.T) { } t.Cleanup(func() { s.Close() }) putGateTestAgent(t, s, "human-gate-agent", []domain.VerificationGate{{ID: "strict", Name: "strict", Mode: "command", Required: true, Commands: []string{"false"}, OnFailure: "human", ExecutionScope: domain.ExecutionScopeRun}}) - wf := domain.WorkflowDefinition{ID: "human-gate-lab", Name: "human gate lab", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{ + wf := domain.WorkflowDefinition{ID: "human-gate-lab", Name: "human gate lab", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "write", Name: "write", Type: "command", Command: "printf 'ok\\n' > out.md", ArtifactOutputs: []domain.ArtifactContract{{Name: "out", Path: "out.md", Required: true}}, MaxAttempts: 1}, {ID: "check", Name: "check", Type: "agent", AgentID: "human-gate-agent", ExecutorID: "mock", RejectTo: "write", OnFailure: "human", MaxAttempts: 1, MaxReworks: 3}, }, Edges: []domain.WorkflowEdge{{ID: "e1", Source: "write", Target: "check", When: "success"}}} @@ -1458,7 +1461,7 @@ func TestSubmitReworkWithoutRejectToDegradesToFail(t *testing.T) { t.Fatal(err) } wf := domain.WorkflowDefinition{ - ID: "rework-no-target", Name: "rework no target", SandboxProfileID: "local", + ID: "rework-no-target", Name: "rework no target", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "solo", Name: "solo", Type: "agent", AgentID: "rework-no-target-agent", ExecutorID: "mock", MaxAttempts: 1}}, } if err := s.PutWorkflow(wf); err != nil { @@ -1496,7 +1499,7 @@ func TestSubmitReworkRejectsUpstreamInsteadOfRetrying(t *testing.T) { if err := s.PutAgent(domain.AgentDefinition{ID: "rework-upstream-agent", Name: "rework-upstream-agent", ExecutorID: "mock", Prompt: "[[mock:gate=rework,pass]]"}); err != nil { t.Fatal(err) } - wf := domain.WorkflowDefinition{ID: "rework-upstream", Name: "rework upstream", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{ + wf := domain.WorkflowDefinition{ID: "rework-upstream", Name: "rework upstream", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "repair", Name: "repair", Type: "script", ScriptLanguage: "shell", Script: "true", MaxAttempts: 1}, {ID: "review", Name: "review", Type: "agent", AgentID: "rework-upstream-agent", ExecutorID: "mock", MaxAttempts: 3, MaxReworks: 3, RejectTo: "repair"}, }, Edges: []domain.WorkflowEdge{{ID: "e1", Source: "repair", Target: "review", When: "success"}}} @@ -1539,7 +1542,7 @@ func TestSubmitReworkBudgetExhaustedWaitsForHuman(t *testing.T) { if err := s.PutAgent(domain.AgentDefinition{ID: "rework-budget-agent", Name: "rework-budget-agent", ExecutorID: "mock", Prompt: "[[mock:gate=rework]]"}); err != nil { t.Fatal(err) } - wf := domain.WorkflowDefinition{ID: "rework-budget", Name: "rework budget", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{ + wf := domain.WorkflowDefinition{ID: "rework-budget", Name: "rework budget", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "repair", Name: "repair", Type: "script", ScriptLanguage: "shell", Script: "true", MaxAttempts: 1}, {ID: "review", Name: "review", Type: "agent", AgentID: "rework-budget-agent", ExecutorID: "mock", MaxAttempts: 3, MaxReworks: 1, RejectTo: "repair"}, }, Edges: []domain.WorkflowEdge{{ID: "e1", Source: "repair", Target: "review", When: "success"}}} @@ -1586,7 +1589,7 @@ func TestSubmitTerminalDecisionSkipsGatesTelemetry(t *testing.T) { t.Fatal(err) } } - wf := domain.WorkflowDefinition{ID: "rework-with-gates", Name: "rework with gates", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{ + wf := domain.WorkflowDefinition{ID: "rework-with-gates", Name: "rework with gates", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "repair", Name: "repair", Type: "script", ScriptLanguage: "shell", Script: "true", MaxAttempts: 1}, {ID: "review", Name: "review", Type: "agent", AgentID: "rework-with-gates-agent", ExecutorID: "mock", MaxAttempts: 1, MaxReworks: 1, RejectTo: "repair"}, }, Edges: []domain.WorkflowEdge{{ID: "e1", Source: "repair", Target: "review", When: "success"}}} @@ -1630,7 +1633,7 @@ func TestSubmitGateResumesSessionWhenResultIsMissing(t *testing.T) { t.Cleanup(s.Close) putGateTestAgent(t, s, "submit-gate-agent", nil) wf := domain.WorkflowDefinition{ - ID: "submit-gate-lab", Name: "submit gate lab", SandboxProfileID: "local", + ID: "submit-gate-lab", Name: "submit gate lab", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ ID: "review", Name: "review", Type: "agent", AgentID: "submit-gate-agent", ExecutorID: "mock", MaxAttempts: 1, }}, @@ -1676,7 +1679,7 @@ func TestLostCLISessionRestartsInsteadOfWaiting(t *testing.T) { t.Fatal(err) } wf := domain.WorkflowDefinition{ - ID: "lost-session-lab", Name: "lost session lab", SandboxProfileID: "local", + ID: "lost-session-lab", Name: "lost session lab", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ ID: "fix", Name: "fix", Type: "agent", AgentID: "lost-session-agent", ExecutorID: "mock", MaxAttempts: 1, }}, @@ -1717,7 +1720,7 @@ func TestHumanGateFailureRetryRerunsNode(t *testing.T) { } t.Cleanup(func() { s.Close() }) putGateTestAgent(t, s, "human-retry-agent", []domain.VerificationGate{{ID: "strict", Name: "strict", Mode: "command", Required: true, Commands: []string{"false"}, OnFailure: "human", ExecutionScope: domain.ExecutionScopeRun}}) - wf := domain.WorkflowDefinition{ID: "human-retry-lab", Name: "human retry lab", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{ + wf := domain.WorkflowDefinition{ID: "human-retry-lab", Name: "human retry lab", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "check", Name: "check", Type: "agent", AgentID: "human-retry-agent", ExecutorID: "mock", OnFailure: "human", MaxAttempts: 1}, }} if err := s.PutWorkflow(wf); err != nil { @@ -1747,7 +1750,7 @@ func TestCancelMarksActiveNodeCancelled(t *testing.T) { t.Fatal(err) } t.Cleanup(func() { s.Close() }) - wf := domain.WorkflowDefinition{ID: "cancel-active", Name: "cancel active", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ + wf := domain.WorkflowDefinition{ID: "cancel-active", Name: "cancel active", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ ID: "wait", Name: "wait", Type: "command", Command: "echo started; sleep 5; echo finished", MaxAttempts: 1, }}} if err := s.PutWorkflow(wf); err != nil { @@ -1789,7 +1792,7 @@ func TestRetryCancelledRunFromNodeAfterImmediateCleanup(t *testing.T) { t.Fatal(err) } t.Cleanup(func() { s.Close() }) - wf := domain.WorkflowDefinition{ID: "resume-cancelled", Name: "resume cancelled", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{ + wf := domain.WorkflowDefinition{ID: "resume-cancelled", Name: "resume cancelled", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "analyze", Name: "analyze", Type: "command", Command: "printf 'plan\\n' > fix-plan.md", ArtifactOutputs: []domain.ArtifactContract{{Name: "plan", Path: "fix-plan.md", Required: true}}, MaxAttempts: 1}, {ID: "fix", Name: "fix", Type: "command", Command: "sleep 2; test -f .agentflow/inputs/analyze/plan.md", MaxAttempts: 1}, }, Edges: []domain.WorkflowEdge{{ID: "analyze-fix", Source: "analyze", Target: "fix", When: "success"}}} @@ -1839,7 +1842,7 @@ func TestRetrySucceededRunFromNodeAfterCleanup(t *testing.T) { t.Fatal(err) } t.Cleanup(func() { s.Close() }) - wf := domain.WorkflowDefinition{ID: "replay-succeeded", Name: "replay succeeded", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{ + wf := domain.WorkflowDefinition{ID: "replay-succeeded", Name: "replay succeeded", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "first", Name: "first", Type: "command", Command: "printf one > first.txt", ArtifactOutputs: []domain.ArtifactContract{{Name: "first", Path: "first.txt", Required: true}}, MaxAttempts: 1}, {ID: "second", Name: "second", Type: "command", Command: "printf two > second.txt", ArtifactOutputs: []domain.ArtifactContract{{Name: "second", Path: "second.txt", Required: true}}, MaxAttempts: 1}, }, Edges: []domain.WorkflowEdge{{ID: "first-second", Source: "first", Target: "second", When: "success"}}} @@ -1880,7 +1883,7 @@ func TestRetryLegacySucceededRunAfterMainBotMissingSnapshot(t *testing.T) { t.Fatal(err) } t.Cleanup(func() { s.Close() }) - wf := domain.WorkflowDefinition{ID: "replay-succeeded", Name: "replay succeeded", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{ + wf := domain.WorkflowDefinition{ID: "replay-succeeded", Name: "replay succeeded", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "first", Name: "first", Type: "command", Command: "printf one > first.txt", ArtifactOutputs: []domain.ArtifactContract{{Name: "first", Path: "first.txt", MediaType: "text/plain", Required: true}}, MaxAttempts: 1}, {ID: "second", Name: "second", Type: "command", Command: "test -s .agentflow/inputs/first/first.txt && printf two > second.txt", ArtifactOutputs: []domain.ArtifactContract{{Name: "second", Path: "second.txt", Required: true}}, MaxAttempts: 1}, }, Edges: []domain.WorkflowEdge{{ID: "first-second", Source: "first", Target: "second", When: "success"}}} @@ -2108,7 +2111,7 @@ func TestParallelNodesDoNotOverwriteEachOther(t *testing.T) { func testDeliveryWorkflow() domain.WorkflowDefinition { return domain.WorkflowDefinition{ - ID: "delivery", Name: "Delivery", SandboxProfileID: "local", + ID: "delivery", Name: "Delivery", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "implement", Name: "Implement", Type: "agent", AgentID: "developer", ExecutorID: "mock", MaxAttempts: 2, MaxReworks: 3}, {ID: "verify", Name: "Verify", Type: "command", Command: "printf 'verification passed\\n'", RejectTo: "implement", MaxAttempts: 1, MaxReworks: 3}, @@ -2160,7 +2163,7 @@ func TestNodeFailureAutomaticallyRejectsToConfiguredTarget(t *testing.T) { t.Fatal(err) } t.Cleanup(func() { s.Close() }) - wf := domain.WorkflowDefinition{ID: "auto-reject", Name: "auto reject", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{ + wf := domain.WorkflowDefinition{ID: "auto-reject", Name: "auto reject", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "repair", Name: "repair", Type: "script", ScriptLanguage: "shell", Script: "true", MaxAttempts: 1}, {ID: "verify", Name: "verify", Type: "script", ScriptLanguage: "python", Script: "raise SystemExit(1)", MaxAttempts: 1, MaxReworks: 1, OnFailure: "reject", RejectTo: "repair"}, }, Edges: []domain.WorkflowEdge{{ID: "next", Source: "repair", Target: "verify", When: "success"}}} @@ -2196,7 +2199,7 @@ func TestPassFailedScriptContinuesDownstream(t *testing.T) { t.Fatal(err) } t.Cleanup(func() { s.Close() }) - wf := domain.WorkflowDefinition{ID: "pass-fail-stop", Name: "pass fail stop", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{ + wf := domain.WorkflowDefinition{ID: "pass-fail-stop", Name: "pass fail stop", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "hard", Name: "hard", Type: "script", ScriptLanguage: "shell", Script: "exit 1", OnFailure: "fail", MaxAttempts: 1}, {ID: "next", Name: "next", Type: "script", ScriptLanguage: "shell", Script: "printf 'ok\\n'", MaxAttempts: 1}, }, Edges: []domain.WorkflowEdge{{ID: "e1", Source: "hard", Target: "next", When: "success"}}} @@ -2241,7 +2244,7 @@ func TestPassAfterReworkLimitReached(t *testing.T) { t.Fatal(err) } t.Cleanup(func() { s.Close() }) - wf := domain.WorkflowDefinition{ID: "pass-rework-limit", Name: "pass rework limit", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{ + wf := domain.WorkflowDefinition{ID: "pass-rework-limit", Name: "pass rework limit", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "repair", Name: "repair", Type: "script", ScriptLanguage: "shell", Script: "true", MaxAttempts: 1}, {ID: "verify", Name: "verify", Type: "script", ScriptLanguage: "shell", Script: "exit 1", MaxAttempts: 1, MaxReworks: 1, OnFailure: "reject", RejectTo: "repair"}, {ID: "done", Name: "done", Type: "script", ScriptLanguage: "shell", Script: "printf 'done\\n'", MaxAttempts: 1}, @@ -2324,7 +2327,7 @@ func TestArtifactsAreVersionedAndMaterializedForDownstreamNode(t *testing.T) { t.Fatal(err) } t.Cleanup(func() { s.Close() }) - wf := domain.WorkflowDefinition{ID: "artifacts", Name: "artifact handoff", Version: 1, SandboxProfileID: "local", + wf := domain.WorkflowDefinition{ID: "artifacts", Name: "artifact handoff", Version: 1, SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "produce", Name: "produce", Type: "command", Command: "mkdir -p docs && printf '# Plan\\n\\naccepted\\n' > docs/plan.md", ArtifactOutputs: []domain.ArtifactContract{{Name: "plan", Path: "docs/plan.md", MediaType: "text/markdown", Required: true}}, MaxAttempts: 1}, {ID: "consume", Name: "consume", Type: "command", Command: "cat .agentflow/inputs/produce/plan.md", MaxAttempts: 1}, @@ -2367,7 +2370,7 @@ func TestRepositoryPatchIsFrozenAndAppliedToDownstreamSandbox(t *testing.T) { t.Fatal(err) } t.Cleanup(func() { s.Close() }) - wf := domain.WorkflowDefinition{ID: "repository-handoff", Name: "repository handoff", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{ + wf := domain.WorkflowDefinition{ID: "repository-handoff", Name: "repository handoff", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "change", Name: "change", Type: "command", Command: "printf changed > repo/app.txt; printf '{}\\n' > report.json; mkdir -p repo/config; printf 'Bearer secret-token\\n' > repo/config/mcporter.json", ArtifactOutputs: []domain.ArtifactContract{{Name: "report", Path: "report.json", MediaType: "application/json", Required: true}}, MaxAttempts: 1}, {ID: "verify", Name: "verify", Type: "command", Command: "test \"$(cat repo/app.txt)\" = changed", MaxAttempts: 1}, }, Edges: []domain.WorkflowEdge{{ID: "handoff", Source: "change", Target: "verify", When: "success"}}} @@ -2413,7 +2416,7 @@ func TestSingleRepositoryKeepsDeliverablesAtRunRoot(t *testing.T) { t.Fatal(err) } t.Cleanup(func() { s.Close() }) - wf := domain.WorkflowDefinition{ID: "single-layout", Name: "single layout", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{ + wf := domain.WorkflowDefinition{ID: "single-layout", Name: "single layout", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "analyze", Name: "analyze", Type: "command", Command: "printf '# plan\\nroot cause\\n' > fix-plan.md; printf changed\\n > repo/app.txt; test -f fix-plan.md && test ! -f repo/fix-plan.md && test ! -e .git && test -d repo/.git", ArtifactOutputs: []domain.ArtifactContract{{Name: "plan", Path: "fix-plan.md", Required: true}}, MaxAttempts: 1}, }} if err := s.PutWorkflow(wf); err != nil { @@ -2473,7 +2476,7 @@ func TestAutomaticGatesAndArtifactsCompleteBeforeManualApproval(t *testing.T) { {ID: "human-first", Name: "Human", Mode: "manual", Required: true}, {ID: "automatic-after", Name: "Automatic", Mode: "command", Commands: []string{"test -s evidence.md"}, Required: true, ExecutionScope: domain.ExecutionScopeRun}, }) - wf := domain.WorkflowDefinition{ID: "gated-artifact", Name: "gated artifact", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{ + wf := domain.WorkflowDefinition{ID: "gated-artifact", Name: "gated artifact", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "prepare", Name: "prepare", Type: "command", Command: "printf '# Evidence\\n' > evidence.md", MaxAttempts: 1}, {ID: "deliver", Name: "deliver", Type: "agent", AgentID: "artifact-validator", ExecutorID: "mock", ArtifactOutputs: []domain.ArtifactContract{{Name: "evidence", Path: "evidence.md", Required: true}}, @@ -2530,7 +2533,7 @@ func TestArtifactContractIsValidatedBeforeAutomaticGate(t *testing.T) { putGateTestAgent(t, s, "missing-artifact-validator", []domain.VerificationGate{{ ID: "marker", Name: "marker", Mode: "command", Commands: []string{"touch " + shellSingleQuote(gateMarker)}, Required: true, ExecutionScope: domain.ExecutionScopeRun, }}) - wf := domain.WorkflowDefinition{ID: "artifact-before-gate", Name: "artifact before gate", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ + wf := domain.WorkflowDefinition{ID: "artifact-before-gate", Name: "artifact before gate", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ ID: "deliver", Name: "deliver", Type: "agent", AgentID: "missing-artifact-validator", ExecutorID: "mock", ArtifactOutputs: []domain.ArtifactContract{{Name: "evidence", Path: "evidence.md", Required: true}}, MaxAttempts: 1, @@ -2581,7 +2584,7 @@ func TestVerificationGateRunsMultiLineCommandsAsOneScript(t *testing.T) { "fi", }, }}) - wf := domain.WorkflowDefinition{ID: "multiline-gate", Name: "multiline gate", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{ + wf := domain.WorkflowDefinition{ID: "multiline-gate", Name: "multiline gate", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "prepare", Name: "prepare", Type: "command", Command: "printf '# Evidence\\n' > evidence.md", MaxAttempts: 1}, {ID: "deliver", Name: "deliver", Type: "agent", AgentID: "multiline-validator", ExecutorID: "mock", ArtifactOutputs: []domain.ArtifactContract{{Name: "evidence", Path: "evidence.md", Required: true}}, MaxAttempts: 1}, }, Edges: []domain.WorkflowEdge{{ID: "prepare-deliver", Source: "prepare", Target: "deliver", When: "success"}}} @@ -2610,7 +2613,7 @@ func TestRunUsesFrozenWorkflowSnapshotDuringConcurrentEdits(t *testing.T) { t.Fatal(err) } t.Cleanup(func() { s.Close() }) - wf := domain.WorkflowDefinition{ID: "snapshot", Name: "Snapshot", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{ + wf := domain.WorkflowDefinition{ID: "snapshot", Name: "Snapshot", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "approve", Name: "Approve", Type: "approval", MaxAttempts: 1}, {ID: "original", Name: "Original", Type: "command", Command: "printf original", MaxAttempts: 1}, }, Edges: []domain.WorkflowEdge{{ID: "next", Source: "approve", Target: "original", When: "success"}}} @@ -2639,75 +2642,28 @@ func TestRunUsesFrozenWorkflowSnapshotDuringConcurrentEdits(t *testing.T) { } } -func TestRetryLegacyRunDefaultsEmptySandboxProfileToLocal(t *testing.T) { +// Runs frozen before workflows owned a sandbox, and workflows that never chose +// one, run in the generic Docker sandbox; never directly on a machine. +func TestEmptySandboxProfileDefaultsToGenericDocker(t *testing.T) { t.Parallel() - dir := t.TempDir() s, err := repo.OpenTest() if err != nil { t.Fatal(err) } t.Cleanup(func() { s.Close() }) - if err := s.PutSandbox(domain.SandboxProfile{ID: "profile-added-later", Name: "Profile added later", Driver: "local"}); err != nil { - t.Fatal(err) - } wf := domain.WorkflowDefinition{ - ID: "legacy-sandbox-retry", Name: "Legacy sandbox retry", SandboxProfileID: "profile-added-later", - Nodes: []domain.WorkflowNode{{ID: "build", Name: "Build", Type: "command", Command: "printf resumed", MaxAttempts: 1}}, + ID: "default-sandbox", Name: "Default sandbox", + Nodes: []domain.WorkflowNode{{ID: "build", Name: "Build", Type: "command", Command: "printf ok", MaxAttempts: 1}}, } if err := s.PutWorkflow(wf); err != nil { t.Fatal(err) } - run := domain.Run{ - ID: "run-legacy-sandbox-retry", WorkflowID: wf.ID, - WorkflowSnapshot: domain.WorkflowDefinition{ - ID: wf.ID, Name: wf.Name, Nodes: append([]domain.WorkflowNode(nil), wf.Nodes...), - }, - Status: "failed", - Nodes: map[string]*domain.NodeRun{ - "build": {NodeID: "build", Status: "failed", Attempt: 1, Error: "historical failure"}, - }, - } - if err := s.PutRun(run); err != nil { - t.Fatal(err) + legacy := domain.Run{ID: "run-legacy-sandbox", WorkflowID: wf.ID, WorkflowSnapshot: domain.WorkflowDefinition{ID: wf.ID, Name: wf.Name, Nodes: wf.Nodes}} + if got := workflowForRun(s, legacy).SandboxProfileID; got != repo.GenericDockerSandboxID { + t.Fatalf("legacy run sandbox profile = %q", got) } - if got := workflowForRun(s, run).SandboxProfileID; got != "local" { - t.Fatalf("legacy run sandbox profile = %q, want local", got) - } - e := New(s, runtime.NewManager(filepath.Join(dir, "workspaces"))) - if err := e.Retry(run.ID, "build", "兼容历史运行", ""); err != nil { - t.Fatal(err) - } - waitFor(t, s, run.ID, "succeeded") - current, _ := s.Run(run.ID) - if got := current.Nodes["build"].Output; got != "resumed\n" { - t.Fatalf("legacy retry output = %q, want resumed", got) - } -} - -func TestStartDefaultsEmptySandboxProfileToLocal(t *testing.T) { - t.Parallel() - dir := t.TempDir() - s, err := repo.OpenTest() - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { s.Close() }) - wf := domain.WorkflowDefinition{ - ID: "default-local-sandbox", Name: "Default local sandbox", - Nodes: []domain.WorkflowNode{{ID: "build", Name: "Build", Type: "command", Command: "printf local", MaxAttempts: 1}}, - } - if err := s.PutWorkflow(wf); err != nil { - t.Fatal(err) - } - e := New(s, runtime.NewManager(filepath.Join(dir, "workspaces"))) - run, err := e.Start(wf.ID, "") - if err != nil { - t.Fatal(err) - } - waitFor(t, s, run.ID, "succeeded") - current, _ := s.Run(run.ID) - if current.WorkflowSnapshot.SandboxProfileID != "local" { - t.Fatalf("run sandbox profile = %q, want local", current.WorkflowSnapshot.SandboxProfileID) + if got := workflowForRun(s, domain.Run{WorkflowID: wf.ID}).SandboxProfileID; got != repo.GenericDockerSandboxID { + t.Fatalf("new run sandbox profile = %q", got) } } @@ -2846,43 +2802,25 @@ func TestResolveNodeExecutorPrefersAgentModel(t *testing.T) { } } -func TestResolveSandboxResourcesRequiresDockerfileForDocker(t *testing.T) { +func TestResolveSandboxRequiresDockerfileForDocker(t *testing.T) { t.Parallel() - s, err := repo.OpenTest() - if err != nil { - t.Fatal(err) - } - defer s.Close() - if _, err := resolveSandboxResources(s, domain.SandboxProfile{ID: "container", Driver: "docker"}); err == nil { + if _, err := resolveSandbox(domain.SandboxProfile{ID: "container", Driver: "docker"}); err == nil { t.Fatal("docker profile without dockerfile should fail") } - df := domain.DockerfileDefinition{ID: "runtime", Name: "Runtime", Content: "FROM debian:bookworm-slim"} - if err := s.PutDockerfile(df); err != nil { - t.Fatal(err) - } - resources, err := resolveSandboxResources(s, domain.SandboxProfile{ID: "container", Driver: "docker", DockerfileID: df.ID}) + spec, err := resolveSandbox(domain.SandboxProfile{ID: "container", Driver: "docker", Dockerfile: &domain.SandboxDockerfile{Content: "FROM debian:bookworm-slim"}}) if err != nil { t.Fatal(err) } - if strings.TrimSpace(resources.Dockerfile.Content) == "" || resources.Dockerfile.ID != df.ID { - t.Fatalf("expected catalog dockerfile, got %+v", resources.Dockerfile) - } - env := domain.EnvironmentDefinition{ - ID: "jdk", - Name: "JDK", - Variables: map[string]string{"JAVA_HOME": "${PREFIX}/jdk"}, - PathEntries: []string{"bin", "jdk/bin"}, - InstallScript: "mkdir -p \"$PREFIX/bin\"", - } - if err := s.PutEnvironment(env); err != nil { - t.Fatal(err) + resources := sandboxResourcesFromSnapshot(spec) + if strings.TrimSpace(resources.Dockerfile.Content) == "" || resources.Dockerfile.ID != "container" || spec.Profile.DockerfileID != "container" { + t.Fatalf("expected the sandbox's dockerfile, got %+v", spec) } - resources, err = resolveSandboxResources(s, domain.SandboxProfile{ID: "mac", Driver: "seatbelt", EnvironmentID: env.ID}) + spec, err = resolveSandbox(domain.SandboxProfile{ID: "mac", Driver: "seatbelt", Environment: map[string]string{"JAVA_HOME": "/opt/jdk"}}) if err != nil { t.Fatal(err) } - if resources.Environment.ID != env.ID || resources.Environment.Variables["JAVA_HOME"] == "" || strings.TrimSpace(resources.Environment.InstallScript) == "" { - t.Fatalf("expected catalog environment, got %+v", resources.Environment) + if spec.Dockerfile != nil || spec.Profile.Environment["JAVA_HOME"] != "/opt/jdk" { + t.Fatalf("expected a native sandbox with only its variables, got %+v", spec) } } @@ -2894,7 +2832,7 @@ func TestOverlayLatestNodeBindingsRefreshesArtifactContracts(t *testing.T) { } t.Cleanup(func() { s.Close() }) current := domain.WorkflowDefinition{ - ID: "issue-fix-production", Name: "Issue fix", SandboxProfileID: "local", Version: 2, + ID: "issue-fix-production", Name: "Issue fix", SandboxProfileID: "test-native", Version: 2, Nodes: []domain.WorkflowNode{{ID: "checkers", Name: "Checkers", Type: "command", ArtifactOutputs: []domain.ArtifactContract{{Name: "strict", Path: "checkers-report.md", Required: true}}}}, } if err := s.PutWorkflow(current); err != nil { @@ -3850,7 +3788,7 @@ func TestRecordHumanContextPersistsForRetryAndPrompt(t *testing.T) { } t.Cleanup(func() { s.Close() }) putGateTestAgent(t, s, "human-context-agent", []domain.VerificationGate{{ID: "strict", Name: "strict", Mode: "command", Required: true, Commands: []string{"false"}, OnFailure: "human", ExecutionScope: domain.ExecutionScopeRun}}) - wf := domain.WorkflowDefinition{ID: "human-context-lab", Name: "human context lab", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{ + wf := domain.WorkflowDefinition{ID: "human-context-lab", Name: "human context lab", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "check", Name: "check", Type: "agent", AgentID: "human-context-agent", ExecutorID: "mock", OnFailure: "human", MaxAttempts: 1}, }} if err := s.PutWorkflow(wf); err != nil { @@ -3908,7 +3846,7 @@ func TestApproveWithHumanContextReachesDownstream(t *testing.T) { } t.Cleanup(func() { s.Close() }) putGateTestAgent(t, s, "human-approve-agent", []domain.VerificationGate{{ID: "strict", Name: "strict", Mode: "command", Required: true, Commands: []string{"false"}, OnFailure: "human", ExecutionScope: domain.ExecutionScopeRun}}) - wf := domain.WorkflowDefinition{ID: "human-approve-context", Name: "approve context", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{ + wf := domain.WorkflowDefinition{ID: "human-approve-context", Name: "approve context", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "gate", Name: "gate", Type: "agent", AgentID: "human-approve-agent", ExecutorID: "mock", OnFailure: "human", MaxAttempts: 1}, {ID: "next", Name: "next", Type: "command", Command: "test -f human-context.md && grep -q TestFoo human-context.md", MaxAttempts: 1}, }, Edges: []domain.WorkflowEdge{{ID: "e1", Source: "gate", Target: "next", When: "success"}}} @@ -4042,7 +3980,7 @@ func TestAlignOnlyApprovalDoesNotWait(t *testing.T) { t.Fatal(err) } t.Cleanup(func() { s.Close() }) - wf := domain.WorkflowDefinition{ID: BaselineAlignWorkflowID, Name: "align auto", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{ + wf := domain.WorkflowDefinition{ID: BaselineAlignWorkflowID, Name: "align auto", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "work", Name: "work", Type: "command", Command: "printf aligned\\n", MaxAttempts: 1}, {ID: "confirm", Name: "confirm", Type: "approval", MaxAttempts: 1}, }, Edges: []domain.WorkflowEdge{{ID: "e1", Source: "work", Target: "confirm"}}} diff --git a/internal/engine/execution_cleanup_cases_test.go b/internal/engine/execution_cleanup_cases_test.go index 5b806f23c..258027617 100644 --- a/internal/engine/execution_cleanup_cases_test.go +++ b/internal/engine/execution_cleanup_cases_test.go @@ -25,7 +25,7 @@ func TestDirectScriptNodeSuccessFailureAndResolution(t *testing.T) { Script: "mkdir -p out && printf ok > out/result.txt", ArtifactOutputs: []domain.ArtifactContract{{Name: "result", Path: "out/result.txt", MediaType: "text/plain", Required: true}}, } - successWF := domain.WorkflowDefinition{ID: "wf-script", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{successNode}} + successWF := domain.WorkflowDefinition{ID: "wf-script", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{successNode}} success := domain.Run{ ID: "cve-direct-script-success", Status: "running", WorkflowID: successWF.ID, WorkflowSnapshot: successWF, Nodes: map[string]*domain.NodeRun{successNode.ID: {NodeID: successNode.ID, Status: "pending"}}, @@ -43,7 +43,7 @@ func TestDirectScriptNodeSuccessFailureAndResolution(t *testing.T) { } failedNode := domain.WorkflowNode{ID: "fail", Name: "Fail", Type: "script", ScriptLanguage: "shell", Script: "printf failure >&2; exit 7", MaxAttempts: 1} - failedWF := domain.WorkflowDefinition{ID: "wf-fail", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{failedNode}} + failedWF := domain.WorkflowDefinition{ID: "wf-fail", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{failedNode}} failed := domain.Run{ ID: "cve-direct-script-failure", Status: "running", WorkflowID: failedWF.ID, WorkflowSnapshot: failedWF, Nodes: map[string]*domain.NodeRun{failedNode.ID: {NodeID: failedNode.ID, Status: "pending"}}, @@ -61,7 +61,7 @@ func TestDirectScriptNodeSuccessFailureAndResolution(t *testing.T) { } agentNode := domain.WorkflowNode{ID: "agent", Name: "Agent", Type: "agent", AgentID: "missing-agent"} - agentWF := domain.WorkflowDefinition{ID: "wf-agent", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{agentNode}} + agentWF := domain.WorkflowDefinition{ID: "wf-agent", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{agentNode}} agentRun := domain.Run{ ID: "cve-direct-agent-resolution", Status: "running", WorkflowID: agentWF.ID, WorkflowSnapshot: agentWF, Nodes: map[string]*domain.NodeRun{agentNode.ID: {NodeID: agentNode.ID, Status: "pending"}}, diff --git a/internal/engine/execution_scope_test.go b/internal/engine/execution_scope_test.go index 763400286..ab905bf31 100644 --- a/internal/engine/execution_scope_test.go +++ b/internal/engine/execution_scope_test.go @@ -48,7 +48,7 @@ func TestRepositoryScopedRoleGateAndScriptArtifacts(t *testing.T) { Commands: []string{`test -s scope.txt && test "$AGENTFLOW_EXECUTION_SCOPE" = repositories`}, }}) wf := domain.WorkflowDefinition{ - ID: "repository-scope", Name: "Repository scope", SandboxProfileID: "local", + ID: "repository-scope", Name: "Repository scope", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ { ID: "prepare", Name: "Prepare", Type: "script", ScriptLanguage: "shell", diff --git a/internal/engine/gate_mr_test.go b/internal/engine/gate_mr_test.go index a03861e11..861156aba 100644 --- a/internal/engine/gate_mr_test.go +++ b/internal/engine/gate_mr_test.go @@ -229,7 +229,7 @@ func TestMRGateRunsInTheNodeLoop(t *testing.T) { } t.Cleanup(func() { s.Close() }) putGateTestAgent(t, s, "mr-gate-agent", []domain.VerificationGate{{ID: "mr-opened", Name: "MR 已创建", Mode: domain.VerificationModeMR, Required: true, OnFailure: "loop"}}) - wf := domain.WorkflowDefinition{ID: "mr-gate-lab", Name: "mr gate lab", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{ + wf := domain.WorkflowDefinition{ID: "mr-gate-lab", Name: "mr gate lab", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "mr", Name: "mr", Type: "agent", AgentID: "mr-gate-agent", ExecutorID: "mock", MaxAttempts: 1}, }} if err := s.PutWorkflow(wf); err != nil { diff --git a/internal/engine/gate_test.go b/internal/engine/gate_test.go index 6e8189379..bbfadcf1c 100644 --- a/internal/engine/gate_test.go +++ b/internal/engine/gate_test.go @@ -60,7 +60,7 @@ func TestGateExecutionScopeIsExplicit(t *testing.T) { {ID: "git", Name: "git", Mode: "command", Required: true, ExecutionScope: domain.ExecutionScopeRepositories, Commands: []string{`git rev-parse --is-inside-work-tree`}}, }) wf := domain.WorkflowDefinition{ - ID: "explicit-gate-scope", Name: "explicit gate scope", SandboxProfileID: "local", + ID: "explicit-gate-scope", Name: "explicit gate scope", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ { ID: "mark", Name: "Mark", Type: "script", ScriptLanguage: "shell", @@ -127,7 +127,7 @@ func TestRunScopedGitGateDoesNotEnterCheckout(t *testing.T) { Commands: []string{`git rev-parse --is-inside-work-tree`}, }}) wf := domain.WorkflowDefinition{ - ID: "run-git-gate", Name: "run git gate", SandboxProfileID: "local", + ID: "run-git-gate", Name: "run git gate", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "prepare", Name: "Prepare", Type: "script", ScriptLanguage: "shell", Script: "printf 'ok\\n' > note.md", MaxAttempts: 1}, {ID: "check", Name: "Check", Type: "agent", AgentID: "run-git-validator", ExecutorID: "mock", MaxAttempts: 1}, diff --git a/internal/engine/lifecycle_test.go b/internal/engine/lifecycle_test.go index d6f98c5ba..c6963149a 100644 --- a/internal/engine/lifecycle_test.go +++ b/internal/engine/lifecycle_test.go @@ -171,7 +171,7 @@ func TestFinishStopsScheduler(t *testing.T) { t.Fatal(err) } t.Cleanup(func() { s.Close() }) - wf := domain.WorkflowDefinition{ID: "finish-stop", Name: "finish stop", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{ + wf := domain.WorkflowDefinition{ID: "finish-stop", Name: "finish stop", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "wait", Name: "wait", Type: "command", Command: "sleep 30", MaxAttempts: 1}, }} if err := s.PutWorkflow(wf); err != nil { @@ -262,7 +262,7 @@ func TestPassPausedScriptContinuesDownstream(t *testing.T) { t.Fatal(err) } t.Cleanup(func() { s.Close() }) - wf := domain.WorkflowDefinition{ID: "pass-paused-script", Name: "pass paused script", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{ + wf := domain.WorkflowDefinition{ID: "pass-paused-script", Name: "pass paused script", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "hard", Name: "hard", Type: "script", ScriptLanguage: "shell", Script: "exit 1", MaxAttempts: 1}, {ID: "next", Name: "next", Type: "script", ScriptLanguage: "shell", Script: "printf 'ok\\n'", MaxAttempts: 1}, }, Edges: []domain.WorkflowEdge{{ID: "e1", Source: "hard", Target: "next", When: "success"}}} @@ -336,7 +336,7 @@ func TestRefreshRunSOPPreservesCompletedNodesAndAddsLatestNodes(t *testing.T) { e, s := newRecoveryEngine(t) old := domain.WorkflowDefinition{ID: "refresh-paused", Name: "old", Version: 1, Revision: 2, SandboxProfileID: "frozen", Nodes: []domain.WorkflowNode{{ID: "done", Name: "done"}, {ID: "work", Name: "work"}}} latest := domain.WorkflowDefinition{ID: old.ID, Name: "latest", Version: 2, Revision: 1, SandboxProfileID: "new-environment", Nodes: []domain.WorkflowNode{{ID: "done", Name: "done latest"}, {ID: "work", Name: "work latest"}, {ID: "verify", Name: "verify"}}, Edges: []domain.WorkflowEdge{{ID: "e", Source: "work", Target: "verify", When: "success"}}} - for _, sandbox := range []domain.SandboxProfile{{ID: "frozen", Name: "frozen", Driver: "local"}, {ID: "new-environment", Name: "new", Driver: "local"}} { + for _, sandbox := range []domain.SandboxProfile{{ID: "frozen", Name: "frozen", Driver: "native"}, {ID: "new-environment", Name: "new", Driver: "native"}} { if err := s.PutSandbox(sandbox); err != nil { t.Fatal(err) } diff --git a/internal/engine/local_workspace_cases_test.go b/internal/engine/local_workspace_cases_test.go index 6b7251adc..d6f1906fe 100644 --- a/internal/engine/local_workspace_cases_test.go +++ b/internal/engine/local_workspace_cases_test.go @@ -82,13 +82,13 @@ func TestRunEnvironmentMethodsOutputsAndResources(t *testing.T) { if _, _, err := e.workspaceSandboxProfile(domain.Run{WorkflowSnapshot: domain.WorkflowDefinition{SandboxProfileID: "missing"}}); err == nil { t.Fatal("missing profile accepted") } - profile, resources, err := e.workspaceSandboxProfile(domain.Run{WorkflowSnapshot: domain.WorkflowDefinition{SandboxProfileID: "local"}}) - if err != nil || profile.ID != "local" { + profile, resources, err := e.workspaceSandboxProfile(domain.Run{WorkflowSnapshot: domain.WorkflowDefinition{SandboxProfileID: "test-native"}}) + if err != nil || profile.ID != "test-native" { t.Fatalf("profile = %+v %+v %v", profile, resources, err) } - snapshot := &domain.RunnerSandboxSpec{Profile: profile, Dockerfile: &domain.DockerfileDefinition{ID: "d"}, Environment: &domain.EnvironmentDefinition{ID: "e"}} + snapshot := &domain.RunnerSandboxSpec{Profile: profile, Dockerfile: &domain.DockerfileDefinition{ID: "d"}} _, resources, err = e.workspaceSandboxProfile(domain.Run{WorkflowSnapshot: domain.WorkflowDefinition{SandboxSnapshot: snapshot}}) - if err != nil || resources.Dockerfile.ID != "d" || resources.Environment.ID != "e" { + if err != nil || resources.Dockerfile.ID != "d" { t.Fatalf("snapshot resources = %+v %v", resources, err) } if st == nil { @@ -100,7 +100,7 @@ func TestLocalWorkspaceCheckpointHandlerOperations(t *testing.T) { e, st := cvEEngine(t) e.sandboxes = runtime.NewManager(t.TempDir()) e.controlToken = "secret" - run := domain.Run{ID: "local-control", Status: "failed", WorkflowSnapshot: domain.WorkflowDefinition{SandboxProfileID: "local"}, Nodes: map[string]*domain.NodeRun{}} + run := domain.Run{ID: "local-control", Status: "failed", WorkflowSnapshot: domain.WorkflowDefinition{SandboxProfileID: "test-native"}, Nodes: map[string]*domain.NodeRun{}} if err := st.PutRun(run); err != nil { t.Fatal(err) } @@ -159,7 +159,7 @@ func TestWorkspaceCleanupDeleteAndFacts(t *testing.T) { } e.recordWorkspaceFacts("facts", &domain.RunnerTaskOutputs{}) - run := domain.Run{ID: "cleanup-local", Status: "succeeded", WorkflowSnapshot: domain.WorkflowDefinition{SandboxProfileID: "local"}, Nodes: map[string]*domain.NodeRun{}} + run := domain.Run{ID: "cleanup-local", Status: "succeeded", WorkflowSnapshot: domain.WorkflowDefinition{SandboxProfileID: "test-native"}, Nodes: map[string]*domain.NodeRun{}} if err := st.PutRun(run); err != nil { t.Fatal(err) } @@ -174,7 +174,7 @@ func TestWorkspaceCleanupDeleteAndFacts(t *testing.T) { } e.cleanupRunWorkspace(run.ID) - deleted := domain.Run{ID: "delete-local", Status: "failed", WorkflowSnapshot: domain.WorkflowDefinition{SandboxProfileID: "local"}, Nodes: map[string]*domain.NodeRun{}} + deleted := domain.Run{ID: "delete-local", Status: "failed", WorkflowSnapshot: domain.WorkflowDefinition{SandboxProfileID: "test-native"}, Nodes: map[string]*domain.NodeRun{}} if err := st.PutRun(deleted); err != nil { t.Fatal(err) } diff --git a/internal/engine/node_execute.go b/internal/engine/node_execute.go index fb4ed14b0..f5fd0779a 100644 --- a/internal/engine/node_execute.go +++ b/internal/engine/node_execute.go @@ -432,6 +432,10 @@ func (e *Engine) executeNode(ctx context.Context, runID string, wf domain.Workfl return } } + if err := domain.ValidateFrozenSandbox(profile); err != nil { + failNode(err, false) + return + } requirements, err := workflowSandboxRequirements(e.repo, wf) if err != nil { failNode(err, nodeRejects(node)) @@ -505,7 +509,7 @@ func (e *Engine) executeNode(ctx context.Context, runID string, wf domain.Workfl if !stagingCheckout { return nil } - if err := prepareRepositories(ctx, sb.Workspace(), current.RepositoryContexts()); err != nil { + if err := prepareRepositories(runtime.WithRepositoryCacheIn(ctx, sb.Unwrap()), sb.Workspace(), current.RepositoryContexts()); err != nil { return explainGitAuthFailure(fmt.Errorf("repository checkout: %w", err), strings.TrimSpace(gitTok) != "" || len(gitCredentials.GitHTTPCredentials) > 0) } for _, rc := range current.RepositoryContexts() { diff --git a/internal/engine/notifications_test.go b/internal/engine/notifications_test.go index b0617f835..841bea64d 100644 --- a/internal/engine/notifications_test.go +++ b/internal/engine/notifications_test.go @@ -24,7 +24,7 @@ func TestAgentNotificationsFollowRealGateAndApprovalEvents(t *testing.T) { t.Fatal(err) } putGateTestAgent(t, s, "notify-agent", []domain.VerificationGate{{ID: "manual", Name: "人工确认", Mode: "manual", Stage: "after_execution", Required: true}}) - wf := domain.WorkflowDefinition{ID: "notify-flow", Name: "通知流程", ProjectID: "notify-p", SandboxProfileID: "local", Notifications: []domain.NotificationBinding{{BotID: bot.ID, Scope: "run", Events: []string{"succeeded"}, ContentMode: "ai"}}, Nodes: []domain.WorkflowNode{{ID: "agent", Name: "实现", Type: "agent", AgentID: "notify-agent", ExecutorID: "mock", MaxAttempts: 1}}} + wf := domain.WorkflowDefinition{ID: "notify-flow", Name: "通知流程", ProjectID: "notify-p", SandboxProfileID: "test-native", Notifications: []domain.NotificationBinding{{BotID: bot.ID, Scope: "run", Events: []string{"succeeded"}, ContentMode: "ai"}}, Nodes: []domain.WorkflowNode{{ID: "agent", Name: "实现", Type: "agent", AgentID: "notify-agent", ExecutorID: "mock", MaxAttempts: 1}}} if err = s.PutWorkflow(wf); err != nil { t.Fatal(err) } diff --git a/internal/engine/parallel_branches_test.go b/internal/engine/parallel_branches_test.go index 67643a2ef..a51e1e68e 100644 --- a/internal/engine/parallel_branches_test.go +++ b/internal/engine/parallel_branches_test.go @@ -49,7 +49,7 @@ func overlaps(a, b *domain.NodeRun) bool { // starts without waiting for its slow sibling (no wave barrier). func TestParallelBranchesExecuteConcurrently(t *testing.T) { t.Parallel() - wf := domain.WorkflowDefinition{ID: "parallel-overlap", Name: "parallel overlap", SandboxProfileID: "local", + wf := domain.WorkflowDefinition{ID: "parallel-overlap", Name: "parallel overlap", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ scriptNode("start", "true"), scriptNode("left", "sleep 1.5"), @@ -87,7 +87,7 @@ func TestParallelBranchesExecuteConcurrently(t *testing.T) { // the sibling finishes and its successor still runs before the run fails. func TestSchedulerWaitsForRunningSiblingBeforeSettling(t *testing.T) { t.Parallel() - wf := domain.WorkflowDefinition{ID: "parallel-fail-wait", Name: "parallel fail wait", SandboxProfileID: "local", + wf := domain.WorkflowDefinition{ID: "parallel-fail-wait", Name: "parallel fail wait", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ scriptNode("start", "true"), scriptNode("broken", "exit 3"), @@ -115,7 +115,7 @@ func TestSchedulerWaitsForRunningSiblingBeforeSettling(t *testing.T) { // works; the run only waits once nothing is in flight. func TestWaitingBranchDoesNotStopRunningSibling(t *testing.T) { t.Parallel() - wf := domain.WorkflowDefinition{ID: "parallel-wait-sibling", Name: "parallel wait sibling", SandboxProfileID: "local", + wf := domain.WorkflowDefinition{ID: "parallel-wait-sibling", Name: "parallel wait sibling", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ scriptNode("start", "true"), {ID: "gate", Name: "gate", Type: "approval"}, @@ -151,7 +151,7 @@ func TestWaitingBranchDoesNotStopRunningSibling(t *testing.T) { // more as a new attempt. func TestReworkResetsRunningSiblingWithoutDoubleCommit(t *testing.T) { t.Parallel() - wf := domain.WorkflowDefinition{ID: "parallel-rework", Name: "parallel rework", SandboxProfileID: "local", + wf := domain.WorkflowDefinition{ID: "parallel-rework", Name: "parallel rework", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ scriptNode("start", "true"), {ID: "gate", Name: "gate", Type: "approval", RejectTo: "start", MaxReworks: 3}, @@ -194,7 +194,7 @@ func TestReworkResetsRunningSiblingWithoutDoubleCommit(t *testing.T) { // committed twice and the run completes. func TestPauseThenImmediateResumeParallelBranches(t *testing.T) { t.Parallel() - wf := domain.WorkflowDefinition{ID: "parallel-pause", Name: "parallel pause", SandboxProfileID: "local", + wf := domain.WorkflowDefinition{ID: "parallel-pause", Name: "parallel pause", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ scriptNode("start", "true"), scriptNode("left", "sleep 1"), @@ -287,7 +287,7 @@ func TestNodeControlKeyIsolatesChildSOP(t *testing.T) { // "running" with a cancelled branch nobody schedules. func TestRetryAfterCancelResumesCancelledParallelSibling(t *testing.T) { t.Parallel() - wf := domain.WorkflowDefinition{ID: "parallel-cancel-retry", Name: "parallel cancel retry", SandboxProfileID: "local", + wf := domain.WorkflowDefinition{ID: "parallel-cancel-retry", Name: "parallel cancel retry", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ scriptNode("start", "true"), scriptNode("left", "sleep 1"), @@ -330,7 +330,7 @@ func TestRetryAfterCancelResumesCancelledParallelSibling(t *testing.T) { // revive fix, or by another path) settles instead of spinning forever. func TestSchedulerSettlesRunWithCancelledNode(t *testing.T) { t.Parallel() - wf := domain.WorkflowDefinition{ID: "parallel-cancelled-settle", Name: "parallel cancelled settle", SandboxProfileID: "local", + wf := domain.WorkflowDefinition{ID: "parallel-cancelled-settle", Name: "parallel cancelled settle", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{scriptNode("left", "true"), scriptNode("right", "true")}, } e, s := parallelTestEngine(t, wf) diff --git a/internal/engine/preview_finalizer_test.go b/internal/engine/preview_finalizer_test.go index 055e7ece5..a6275ce73 100644 --- a/internal/engine/preview_finalizer_test.go +++ b/internal/engine/preview_finalizer_test.go @@ -178,7 +178,7 @@ func TestStartInjectsPreviewBuildNode(t *testing.T) { } t.Cleanup(store.Close) wf := domain.WorkflowDefinition{ - ID: "preview-auto-build", Name: "preview", SandboxProfileID: "local", + ID: "preview-auto-build", Name: "preview", SandboxProfileID: "test-native", Preview: &domain.PreviewContract{Enabled: true, Model: "gpt-5.6-terra"}, Nodes: []domain.WorkflowNode{ {ID: "impl", Name: "实现", Type: "script", ScriptLanguage: "shell", Script: "printf ok\n", MaxAttempts: 1}, diff --git a/internal/engine/recovery_test.go b/internal/engine/recovery_test.go index feb7b898c..16c84b9a7 100644 --- a/internal/engine/recovery_test.go +++ b/internal/engine/recovery_test.go @@ -215,7 +215,7 @@ func TestFinishAtKeepsRewoundRunAlive(t *testing.T) { e, s := newRecoveryEngine(t) e.ConfigureExecution("worker", "host", time.Minute, true) wf := domain.WorkflowDefinition{ - ID: "wf-rework", SandboxProfileID: "local", + ID: "wf-rework", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "fix", Name: "fix"}, {ID: "verify", Name: "verify", OnFailure: "reject", RejectTo: "fix"}, @@ -255,7 +255,7 @@ func TestFinishAtFailsWhenANodeIsStillFailed(t *testing.T) { e, s := newRecoveryEngine(t) e.ConfigureExecution("worker", "host", time.Minute, true) wf := domain.WorkflowDefinition{ - ID: "wf-still-failed", SandboxProfileID: "local", + ID: "wf-still-failed", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "fix", Name: "fix"}, {ID: "verify", Name: "verify"}, diff --git a/internal/engine/repository_cache.go b/internal/engine/repository_cache.go new file mode 100644 index 000000000..a5c733d1f --- /dev/null +++ b/internal/engine/repository_cache.go @@ -0,0 +1,56 @@ +package engine + +import ( + "context" + "log" + "strings" + + "agentflow/internal/domain" + "agentflow/internal/gitwork" + "agentflow/internal/runtime" +) + +// workspaceCacheRepositories are the project repositories a native +// conversation workspace keeps warm in its execution machine's repository +// cache: its Agent clones them on demand. +func (e *Engine) workspaceCacheRepositories(run domain.Run) []domain.RunnerRepository { + projectID := strings.TrimSpace(run.ExecutionContext.ProjectID) + if !run.IsNativeWorkspace() || projectID == "" { + return nil + } + var out []domain.RunnerRepository + for _, repository := range e.repo.Repositories() { + cloneURL := strings.TrimSpace(repository.CloneURL) + if repository.ProjectID != projectID || cloneURL == "" { + continue + } + out = append(out, domain.RunnerRepository{ + RepositoryID: repository.ID, + Name: repository.Name, + CloneURL: cloneURL, + UseSSH: repository.Provider == domain.RepositoryProviderSSH || gitwork.IsSSHReference(cloneURL), + }) + } + return out +} + +// warmRepositoryCaches warms the platform's own cache for a native +// conversation workspace it hosts. ctx carries the run's Git credentials. +func (e *Engine) warmRepositoryCaches(ctx context.Context, run domain.Run) { + runtime.WarmRepositoryCaches(ctx, e.workspaceCacheRepositories(run)) +} + +// cloneFromRepositoryCache checks repository out at branch as a shared clone +// of the repository cache in ctx. False leaves workspace empty for a full +// clone: there is no cache for this workspace, or it could not be used. +func cloneFromRepositoryCache(ctx context.Context, workspace string, repository domain.RepositoryContext, branch string) bool { + root, remote := gitwork.RepositoryCacheFrom(ctx), strings.TrimSpace(repository.CloneURL) + if remote == "" || gitwork.RepositoryCachePath(root, repository.RepositoryID) == "" { + return false + } + if err := gitwork.CloneFromRepositoryCache(ctx, root, repository.RepositoryID, remote, branch, workspace, cloneWatch(repository)); err != nil { + log.Printf("repository %s: repository cache unavailable, cloning fully: %v", repository.RepositoryID, err) + return false + } + return true +} diff --git a/internal/engine/repository_workspace.go b/internal/engine/repository_workspace.go index 6c2c16f3c..c6eb86e29 100644 --- a/internal/engine/repository_workspace.go +++ b/internal/engine/repository_workspace.go @@ -149,6 +149,9 @@ func prepareRepository(ctx context.Context, workspace string, repository domain. } baseBranch := repositoryBaseBranch(repository) clone := func(branch string, useReference bool) error { + if useReference && cloneFromRepositoryCache(ctx, workspace, repository, branch) { + return nil + } // --progress: without a terminal git prints nothing until it finishes, // which is what made a slow clone indistinguishable from a hung one. args := []string{"clone", "--progress", "--no-hardlinks", "--single-branch", "--branch", branch} diff --git a/internal/engine/repository_workspace_new_branch_test.go b/internal/engine/repository_workspace_new_branch_test.go index 737036054..b5ea2b7b6 100644 --- a/internal/engine/repository_workspace_new_branch_test.go +++ b/internal/engine/repository_workspace_new_branch_test.go @@ -8,6 +8,7 @@ import ( "testing" "agentflow/internal/domain" + "agentflow/internal/gitwork" ) // newBranchRemote builds a bare remote whose master branch has one commit and @@ -156,3 +157,29 @@ func TestResumeRejectsRemoteBranchCreatedElsewhere(t *testing.T) { t.Fatalf("continued branch = %q", branch) } } + +// A native workspace checks its repositories out as shared clones of the +// repository cache, with origin still pointing at the repository. +func TestPrepareRepositoryClonesFromRepositoryCache(t *testing.T) { + remote := newBranchRemote(t) + root := t.TempDir() + ctx := gitwork.WithRepositoryCache(context.Background(), root) + create := domain.RepositoryContext{RepositoryID: "repo", CloneURL: remote, BaseBranch: "master", DefaultBranch: "master", WorkBranch: "feature/cached", CreateNewWorkBranch: true} + workspace := filepath.Join(t.TempDir(), "workspace") + if err := prepareRepository(ctx, workspace, create); err != nil { + t.Fatal(err) + } + alternates, err := os.ReadFile(filepath.Join(workspace, ".git", "objects", "info", "alternates")) + if err != nil || !strings.Contains(string(alternates), filepath.Join(root, "repo.git")) { + t.Fatalf("checkout does not borrow the cache objects: %q %v", alternates, err) + } + if origin, _ := gitC(ctx, workspace, "remote", "get-url", "origin"); strings.TrimSpace(origin) != remote { + t.Fatalf("origin = %q, want %q", origin, remote) + } + if branch, _ := gitC(ctx, workspace, "branch", "--show-current"); strings.TrimSpace(branch) != create.WorkBranch { + t.Fatalf("work branch = %q", branch) + } + if _, ok := gitRevParse(ctx, workspace, "origin/feature/existing"); !ok { + t.Fatal("remote branches missing from the shared clone") + } +} diff --git a/internal/engine/run_admission_test.go b/internal/engine/run_admission_test.go index 8d65d867c..3910ef56a 100644 --- a/internal/engine/run_admission_test.go +++ b/internal/engine/run_admission_test.go @@ -18,7 +18,7 @@ func TestQueuedSOPDoesNotStartAndCancelDoesNotOccupy(t *testing.T) { t.Fatal(err) } defer s.Close() - wf := domain.WorkflowDefinition{ID: "queue-command", Name: "Queue", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "work", Type: "command", Command: "true", MaxAttempts: 1}}} + wf := domain.WorkflowDefinition{ID: "queue-command", Name: "Queue", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "work", Type: "command", Command: "true", MaxAttempts: 1}}} if err := s.PutWorkflow(wf); err != nil { t.Fatal(err) } @@ -61,7 +61,7 @@ func TestQueuedSOPAutomaticallyStartsAfterSuccess(t *testing.T) { t.Parallel() s, _ := repo.OpenTest() defer s.Close() - wf := domain.WorkflowDefinition{ID: "queue-approval", Name: "Queue", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "gate", Name: "Gate", Type: "approval", MaxAttempts: 1}}} + wf := domain.WorkflowDefinition{ID: "queue-approval", Name: "Queue", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "gate", Name: "Gate", Type: "approval", MaxAttempts: 1}}} if err := s.PutWorkflow(wf); err != nil { t.Fatal(err) } diff --git a/internal/engine/run_environment.go b/internal/engine/run_environment.go index 51e08da65..a6662d82c 100644 --- a/internal/engine/run_environment.go +++ b/internal/engine/run_environment.go @@ -110,23 +110,13 @@ func (r *runEnvironment) Detach() error { return nil } -func resolveSandboxResources(st *repo.Store, profile domain.SandboxProfile) (runtime.SandboxResources, error) { - var resources runtime.SandboxResources - if strings.TrimSpace(profile.DockerfileID) != "" { - dockerfile, ok := st.Dockerfile(profile.DockerfileID) - if !ok { - return resources, fmt.Errorf("dockerfile %q not found", profile.DockerfileID) - } - resources.Dockerfile = dockerfile - } else if strings.EqualFold(strings.TrimSpace(profile.Driver), "docker") { - return resources, fmt.Errorf("docker sandbox %q requires a dockerfileId", profile.ID) - } - if strings.TrimSpace(profile.EnvironmentID) != "" { - if environment, ok := st.Environment(profile.EnvironmentID); ok { - resources.Environment = environment - } +// resolveSandbox is the runner spec a stored profile runs as. A docker +// sandbox cannot run without its Dockerfile. +func resolveSandbox(profile domain.SandboxProfile) (*domain.RunnerSandboxSpec, error) { + if strings.TrimSpace(profile.Driver) == domain.SandboxDriverDocker && (profile.Dockerfile == nil || strings.TrimSpace(profile.Dockerfile.Content) == "") { + return nil, fmt.Errorf("docker sandbox %q has no Dockerfile", profile.ID) } - return resources, nil + return domain.RunnerSandbox(profile), nil } func resolvedSandboxSnapshot(profile domain.SandboxProfile, resources runtime.SandboxResources) *domain.RunnerSandboxSpec { @@ -135,10 +125,6 @@ func resolvedSandboxSnapshot(profile domain.SandboxProfile, resources runtime.Sa dockerfile := resources.Dockerfile snapshot.Dockerfile = &dockerfile } - if strings.TrimSpace(resources.Environment.ID) != "" { - environment := resources.Environment - snapshot.Environment = &environment - } return snapshot } @@ -150,9 +136,6 @@ func sandboxResourcesFromSnapshot(snapshot *domain.RunnerSandboxSpec) runtime.Sa if snapshot.Dockerfile != nil { resources.Dockerfile = *snapshot.Dockerfile } - if snapshot.Environment != nil { - resources.Environment = *snapshot.Environment - } return resources } @@ -193,11 +176,11 @@ func (e *Engine) acquireRunEnvironment(ctx context.Context, run domain.Run, prof } resources := sandboxResourcesFromSnapshot(run.WorkflowSnapshot.SandboxSnapshot) if run.WorkflowSnapshot.SandboxSnapshot == nil { - var err error - resources, err = resolveSandboxResources(e.repo, profile) + spec, err := resolveSandbox(profile) if err != nil { return nil, false, err } + profile, resources = spec.Profile, sandboxResourcesFromSnapshot(spec) } sandbox, err := e.sandboxes.AcquireRunIn(ctx, run.ID, workspaceRunID(current), profile, requirements, credentials, resources) if err != nil { diff --git a/internal/engine/run_lease_test.go b/internal/engine/run_lease_test.go index 2f190a25d..bbd8eeb5e 100644 --- a/internal/engine/run_lease_test.go +++ b/internal/engine/run_lease_test.go @@ -160,7 +160,7 @@ func TestControlPlaneEnqueuesWithoutExecute(t *testing.T) { t.Parallel() s, _ := repo.OpenTest() defer s.Close() - wf := domain.WorkflowDefinition{ID: "enqueue-only", Name: "enqueue", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ + wf := domain.WorkflowDefinition{ID: "enqueue-only", Name: "enqueue", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ ID: "wait", Name: "wait", Type: "approval", MaxAttempts: 1, }}} if err := s.PutWorkflow(wf); err != nil { @@ -191,7 +191,7 @@ func TestControlPlaneCancelRequestsRunningWorker(t *testing.T) { t.Parallel() s, _ := repo.OpenTest() defer s.Close() - wf := domain.WorkflowDefinition{ID: "cancel-handoff", Name: "cancel", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ + wf := domain.WorkflowDefinition{ID: "cancel-handoff", Name: "cancel", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ ID: "wait", Name: "wait", Type: "command", Command: "sleep 30", MaxAttempts: 1, }}} if err := s.PutWorkflow(wf); err != nil { @@ -240,7 +240,7 @@ func TestControlPlaneCancelNotifiesWorkerOverHTTP(t *testing.T) { t.Parallel() s, _ := repo.OpenTest() defer s.Close() - wf := domain.WorkflowDefinition{ID: "cancel-fast", Name: "cancel", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ + wf := domain.WorkflowDefinition{ID: "cancel-fast", Name: "cancel", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ ID: "wait", Name: "wait", Type: "command", Command: "sleep 30", MaxAttempts: 1, }}} if err := s.PutWorkflow(wf); err != nil { @@ -278,7 +278,9 @@ func TestControlPlaneCancelNotifiesWorkerOverHTTP(t *testing.T) { for time.Now().Before(deadline) { got, _ := s.RunState(run.ID) if got.Status == "cancelled" { - if elapsed := time.Since(started); elapsed > time.Second { + // The bound only has to separate an interrupt from the 10s lease + // heartbeat; a loaded test machine needs a few seconds. + if elapsed := time.Since(started); elapsed > 3*time.Second { t.Fatalf("cancel took %s, want well under the 10s lease heartbeat", elapsed) } return @@ -293,7 +295,7 @@ func TestInterruptRequiresDurableControlFlag(t *testing.T) { t.Parallel() s, _ := repo.OpenTest() defer s.Close() - wf := domain.WorkflowDefinition{ID: "interrupt-guard", Name: "guard", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ + wf := domain.WorkflowDefinition{ID: "interrupt-guard", Name: "guard", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ ID: "wait", Name: "wait", Type: "command", Command: "sleep 30", MaxAttempts: 1, }}} if err := s.PutWorkflow(wf); err != nil { @@ -342,7 +344,7 @@ func TestControlPlaneCancelRoutesToOwningWorker(t *testing.T) { t.Parallel() s, _ := repo.OpenTest() defer s.Close() - wf := domain.WorkflowDefinition{ID: "cancel-owner", Name: "cancel", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ + wf := domain.WorkflowDefinition{ID: "cancel-owner", Name: "cancel", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ ID: "wait", Name: "wait", Type: "command", Command: "sleep 30", MaxAttempts: 1, }}} if err := s.PutWorkflow(wf); err != nil { @@ -389,8 +391,8 @@ func TestControlPlaneCancelRoutesToOwningWorker(t *testing.T) { for time.Now().Before(deadline) { got, _ := s.RunState(run.ID) if got.Status == "cancelled" { - if elapsed := time.Since(started); elapsed > time.Second { - t.Fatalf("cancel took %s", elapsed) + if elapsed := time.Since(started); elapsed > 3*time.Second { + t.Fatalf("cancel took %s, want well under the 10s lease heartbeat", elapsed) } if hitsA.Load() != 1 { t.Fatalf("owner interrupt hits=%d, want 1", hitsA.Load()) @@ -456,7 +458,7 @@ func TestAPIResumePausedIsClaimedOnlyByBoundWorker(t *testing.T) { t.Parallel() s, _ := repo.OpenTest() defer s.Close() - wf := domain.WorkflowDefinition{ID: "pause-sticky", Name: "pause", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ + wf := domain.WorkflowDefinition{ID: "pause-sticky", Name: "pause", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ ID: "wait", Name: "wait", Type: "command", Command: "sleep 30", MaxAttempts: 1, }}} if err := s.PutWorkflow(wf); err != nil { @@ -512,7 +514,7 @@ func TestAPIRetryIsClaimedOnlyByBoundWorker(t *testing.T) { t.Parallel() s, _ := repo.OpenTest() defer s.Close() - wf := domain.WorkflowDefinition{ID: "retry-sticky", Name: "retry", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ + wf := domain.WorkflowDefinition{ID: "retry-sticky", Name: "retry", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ ID: "fail", Name: "fail", Type: "command", Command: "false", MaxAttempts: 1, }}} if err := s.PutWorkflow(wf); err != nil { @@ -561,7 +563,7 @@ func TestStartInsertsLeasedRunAndBlocksOtherResume(t *testing.T) { t.Parallel() s, _ := repo.OpenTest() defer s.Close() - wf := domain.WorkflowDefinition{ID: "lease-start", Name: "lease start", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ + wf := domain.WorkflowDefinition{ID: "lease-start", Name: "lease start", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ ID: "wait", Name: "wait", Type: "command", Command: "sleep 30", MaxAttempts: 1, }}} if err := s.PutWorkflow(wf); err != nil { @@ -633,7 +635,7 @@ func TestSameInstanceResumeDoesNotStartSecondExecute(t *testing.T) { t.Parallel() s, _ := repo.OpenTest() defer s.Close() - wf := domain.WorkflowDefinition{ID: "lease-same", Name: "lease same", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ + wf := domain.WorkflowDefinition{ID: "lease-same", Name: "lease same", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ ID: "wait", Name: "wait", Type: "command", Command: "sleep 30", MaxAttempts: 1, }}} if err := s.PutWorkflow(wf); err != nil { @@ -800,7 +802,7 @@ func TestDrainParksRunningRunForResume(t *testing.T) { t.Parallel() s, _ := repo.OpenTest() defer s.Close() - wf := domain.WorkflowDefinition{ID: "drain-park", Name: "drain park", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ + wf := domain.WorkflowDefinition{ID: "drain-park", Name: "drain park", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ ID: "wait", Name: "wait", Type: "command", Command: "sleep 30", MaxAttempts: 3, }}} if err := s.PutWorkflow(wf); err != nil { diff --git a/internal/engine/run_ops_cases_test.go b/internal/engine/run_ops_cases_test.go index b8c60a9fd..02eeb9571 100644 --- a/internal/engine/run_ops_cases_test.go +++ b/internal/engine/run_ops_cases_test.go @@ -19,7 +19,7 @@ func TestRunOpsApproveRejectRetryDecline(t *testing.T) { e, _ := cvEEngine(t) e.executeRuns = false wf := domain.WorkflowDefinition{ - ID: "cve-ops-wf", SandboxProfileID: "local", + ID: "cve-ops-wf", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "fix", Type: "agent", AgentID: "developer"}, {ID: "gate", Type: "approval", RejectTo: "fix", MaxReworks: 2}, @@ -116,7 +116,7 @@ func TestRunOpsPassResumePausedRefreshAndHelpers(t *testing.T) { e, st := cvEEngine(t) e.executeRuns = false wf := domain.WorkflowDefinition{ - ID: "cve-pass-wf", Name: "v1", Version: 1, Revision: 1, SandboxProfileID: "local", + ID: "cve-pass-wf", Name: "v1", Version: 1, Revision: 1, SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "script", Type: "script", Script: "exit 1"}, {ID: "next", Type: "agent", AgentID: "developer"}}, Edges: []domain.WorkflowEdge{{Source: "script", Target: "next"}}, } diff --git a/internal/engine/run_start.go b/internal/engine/run_start.go index 425dfcf1f..1f7eb745d 100644 --- a/internal/engine/run_start.go +++ b/internal/engine/run_start.go @@ -134,12 +134,12 @@ func (e *Engine) startWorkflowDefinition(wf domain.WorkflowDefinition, input str return domain.Run{}, err } } - resources, err := resolveSandboxResources(e.repo, profile) + sandbox, err := resolveSandbox(profile) if err != nil { return domain.Run{}, err } if executionContext.SharedScheduleID != "" { - if err := e.validateSharedScheduleWorkflow(wf, executionContext.ProjectID, profile, resources); err != nil { + if err := e.validateSharedScheduleWorkflow(wf, executionContext.ProjectID, profile); err != nil { return domain.Run{}, err } } @@ -173,7 +173,7 @@ func (e *Engine) startWorkflowDefinition(wf domain.WorkflowDefinition, input str if err := e.requireWorkBranchCapabilities(executionContext.ExecutionRunnerID, repositories); err != nil { return domain.Run{}, err } - wf.SandboxSnapshot = resolvedSandboxSnapshot(profile, resources) + wf.SandboxSnapshot = sandbox r := domain.Run{ ID: id, WorkflowID: workflowID, WorkflowSnapshot: wf, Status: "running", Input: input, Repository: firstRepository, ExecutionContext: executionContext, Nodes: map[string]*domain.NodeRun{}, diff --git a/internal/engine/runner_cases_test.go b/internal/engine/runner_cases_test.go index 9a1f62983..9a9247414 100644 --- a/internal/engine/runner_cases_test.go +++ b/internal/engine/runner_cases_test.go @@ -31,7 +31,7 @@ func cvERunner(t *testing.T, e *Engine, id string, status string, providers ...s func cvERunnerRun(id, runnerID string) domain.Run { return domain.Run{ ID: id, Status: "failed", - WorkflowSnapshot: domain.WorkflowDefinition{ID: "wf", SandboxProfileID: "local"}, + WorkflowSnapshot: domain.WorkflowDefinition{ID: "wf", SandboxProfileID: "test-native"}, ExecutionContext: domain.TelemetryContext{ ExecutionMode: domain.ExecutionModeRunner, ExecutionRunnerID: runnerID, RunnerWorkspaceLayout: domain.RunnerWorkspaceLayoutShared, ResponsibleUserID: 1, diff --git a/internal/engine/runner_sandbox_test.go b/internal/engine/runner_sandbox_test.go index 2d1da482a..e55aae9d1 100644 --- a/internal/engine/runner_sandbox_test.go +++ b/internal/engine/runner_sandbox_test.go @@ -18,11 +18,8 @@ func TestRunnerSandboxSpecCarriesResolvedDockerAssets(t *testing.T) { t.Fatal(err) } defer s.Close() - dockerfile := domain.DockerfileDefinition{ID: "runner-image", Name: "Runner image", Content: "FROM alpine:3.20\n"} - profile := domain.SandboxProfile{ID: "runner-docker", Name: "Runner Docker", Driver: "docker", DockerfileID: dockerfile.ID, Environment: map[string]string{"E2E": "1"}} - if err := s.PutDockerfile(dockerfile); err != nil { - t.Fatal(err) - } + dockerfile := &domain.SandboxDockerfile{Content: "FROM alpine:3.20\n"} + profile := domain.SandboxProfile{ID: "runner-docker", Name: "Runner Docker", Driver: "docker", Dockerfile: dockerfile, Environment: map[string]string{"E2E": "1"}} if err := s.PutSandbox(profile); err != nil { t.Fatal(err) } @@ -31,7 +28,7 @@ func TestRunnerSandboxSpecCarriesResolvedDockerAssets(t *testing.T) { if err != nil { t.Fatal(err) } - if spec == nil || spec.Profile.Driver != "docker" || spec.Profile.Environment["E2E"] != "1" || spec.Dockerfile == nil || spec.Dockerfile.Content != dockerfile.Content { + if spec == nil || spec.Profile.Driver != "docker" || spec.Profile.Environment["E2E"] != "1" || spec.Dockerfile == nil || spec.Dockerfile.Content != dockerfile.Content || spec.Dockerfile.ID != profile.ID || spec.Profile.DockerfileID != profile.ID || spec.Profile.Dockerfile != nil { t.Fatalf("runner sandbox spec = %+v", spec) } } @@ -43,10 +40,7 @@ func TestRunnerSandboxSpecUsesFrozenSnapshot(t *testing.T) { t.Fatal(err) } defer s.Close() - if err := s.PutDockerfile(domain.DockerfileDefinition{ID: "image", Name: "changed", Content: "FROM busybox\n"}); err != nil { - t.Fatal(err) - } - if err := s.PutSandbox(domain.SandboxProfile{ID: "docker", Name: "changed", Driver: "local"}); err != nil { + if err := s.PutSandbox(domain.SandboxProfile{ID: "docker", Name: "changed", Driver: "native"}); err != nil { t.Fatal(err) } frozen := &domain.RunnerSandboxSpec{ @@ -225,7 +219,7 @@ func TestRetryFailsBeforeMutationWhenFrozenRunnerIsOffline(t *testing.T) { } run := domain.Run{ ID: "run-offline-retry", WorkflowID: "retry", Status: "failed", - WorkflowSnapshot: domain.WorkflowDefinition{ID: "retry", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "work", Type: "command", Command: "true", MaxAttempts: 1}}}, + WorkflowSnapshot: domain.WorkflowDefinition{ID: "retry", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "work", Type: "command", Command: "true", MaxAttempts: 1}}}, ExecutionContext: domain.TelemetryContext{ExecutionMode: domain.ExecutionModeRunner, ExecutionRunnerID: runner.ID}, Nodes: map[string]*domain.NodeRun{"work": {NodeID: "work", Status: "failed", Attempt: 1, Error: "lost connection"}}, } diff --git a/internal/engine/settle_active_node_test.go b/internal/engine/settle_active_node_test.go index 974d42e8a..b4d6d62ea 100644 --- a/internal/engine/settle_active_node_test.go +++ b/internal/engine/settle_active_node_test.go @@ -9,7 +9,7 @@ import ( // A failed branch must not settle the run while a sibling node is still // running or waiting for input. func TestSettleStatusForCompletedGraphWaitsForActiveNodes(t *testing.T) { - wf := domain.WorkflowDefinition{ID: "wf", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "left", Type: "script"}, {ID: "right", Type: "agent"}}} + wf := domain.WorkflowDefinition{ID: "wf", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "left", Type: "script"}, {ID: "right", Type: "agent"}}} for _, active := range []string{"running", "pending_input"} { run := domain.Run{ID: "settle-" + active, Status: "running", WorkflowSnapshot: wf, Nodes: map[string]*domain.NodeRun{ "left": {NodeID: "left", Status: "failed"}, diff --git a/internal/engine/shared_schedule_assets.go b/internal/engine/shared_schedule_assets.go index 29a4a89ef..bc8917324 100644 --- a/internal/engine/shared_schedule_assets.go +++ b/internal/engine/shared_schedule_assets.go @@ -5,32 +5,19 @@ import ( "strings" "agentflow/internal/domain" - "agentflow/internal/runtime" ) // Each SOP checks only its own assets at admission. A parent node binding // authorizes traversal, not access to another project's private dependencies. -// Check the resolved resources before they are persisted in the run snapshot. -func (e *Engine) validateSharedScheduleWorkflow(wf domain.WorkflowDefinition, projectID string, profile domain.SandboxProfile, resources runtime.SandboxResources) error { +// The sandbox carries its own Dockerfile or install script, so checking the +// sandbox covers its recipe. +func (e *Engine) validateSharedScheduleWorkflow(wf domain.WorkflowDefinition, projectID string, profile domain.SandboxProfile) error { if err := sharedScheduleAssetVisible(projectID, "SOP", wf.ProjectID, wf.Shared || wf.Generic); err != nil { return err } if err := sharedScheduleAssetVisible(projectID, "沙箱", profile.ProjectID, profile.Shared); err != nil { return err } - if resources.Dockerfile.ID != "" { - if err := sharedScheduleAssetVisible(projectID, "Dockerfile", resources.Dockerfile.ProjectID, resources.Dockerfile.Shared); err != nil { - return err - } - } - if profile.EnvironmentID != "" { - if resources.Environment.ID == "" { - return fmt.Errorf("共享任务使用的环境不存在") - } - if err := sharedScheduleAssetVisible(projectID, "环境", resources.Environment.ProjectID, resources.Environment.Shared); err != nil { - return err - } - } for _, node := range wf.Nodes { if node.Type != "agent" || domain.IsPreviewBuildAgent(node.AgentID) { continue diff --git a/internal/engine/shared_schedule_assets_test.go b/internal/engine/shared_schedule_assets_test.go index 1fd56d888..6ad320ceb 100644 --- a/internal/engine/shared_schedule_assets_test.go +++ b/internal/engine/shared_schedule_assets_test.go @@ -59,9 +59,9 @@ func TestSharedScheduleNestedSOPUsesImmediateParentBinding(t *testing.T) { } } for _, wf := range []domain.WorkflowDefinition{ - {ID: "root", Name: "Root", ProjectID: "source", Shared: true, SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "child-node", Name: "Child", Type: "sop", SOPWorkflowID: "child"}}}, - {ID: "child", Name: "Child", ProjectID: "source", Shared: true, SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "leaf-node", Name: "Leaf", Type: "sop", SOPWorkflowID: "leaf"}}}, - {ID: "leaf", Name: "Leaf", ProjectID: "source", Shared: true, SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "approve", Name: "Approve", Type: "approval"}}}, + {ID: "root", Name: "Root", ProjectID: "source", Shared: true, SandboxProfileID: repo.TestNativeSandboxID, Nodes: []domain.WorkflowNode{{ID: "child-node", Name: "Child", Type: "sop", SOPWorkflowID: "child"}}}, + {ID: "child", Name: "Child", ProjectID: "source", Shared: true, SandboxProfileID: repo.TestNativeSandboxID, Nodes: []domain.WorkflowNode{{ID: "leaf-node", Name: "Leaf", Type: "sop", SOPWorkflowID: "leaf"}}}, + {ID: "leaf", Name: "Leaf", ProjectID: "source", Shared: true, SandboxProfileID: repo.TestNativeSandboxID, Nodes: []domain.WorkflowNode{{ID: "approve", Name: "Approve", Type: "approval"}}}, } { check(st.PutWorkflow(wf)) } @@ -116,13 +116,9 @@ func TestSharedScheduleRejectsPrivateNestedSOPSandboxResources(t *testing.T) { t.Fatal(err) } } - check(st.PutEnvironment(domain.EnvironmentDefinition{ - ID: "private-child-env", Name: "Private child environment", ProjectID: "source", - Variables: map[string]string{"PRIVATE_TOKEN": "do-not-leak"}, InstallScript: "echo private-install", - })) check(st.PutSandbox(domain.SandboxProfile{ - ID: "private-child-sandbox", Name: "Private child sandbox", ProjectID: "source", - Driver: domain.SandboxDriverNative, EnvironmentID: "private-child-env", + ID: "private-child-sandbox", Name: "Private child sandbox", ProjectID: "source", Driver: domain.SandboxDriverNative, + Environment: map[string]string{"PRIVATE_MODE": "child"}, })) check(st.PutWorkflow(domain.WorkflowDefinition{ ID: "shared-child", Name: "Shared child", ProjectID: "source", Shared: true, @@ -204,51 +200,6 @@ func TestSharedScheduleRejectsPrivateNestedDependencies(t *testing.T) { expected string setupChild func(*repo.Store) (domain.WorkflowDefinition, error) }{ - { - name: "environment behind shared sandbox", - expected: "环境", - setupChild: func(st *repo.Store) (domain.WorkflowDefinition, error) { - if err := st.PutEnvironment(domain.EnvironmentDefinition{ - ID: "private-environment", Name: "Private environment", ProjectID: "source", - Variables: map[string]string{"PRIVATE_TOKEN": "do-not-leak"}, InstallScript: "echo private-install", - }); err != nil { - return domain.WorkflowDefinition{}, err - } - if err := st.PutSandbox(domain.SandboxProfile{ - ID: "shared-sandbox-with-private-environment", Name: "Shared sandbox", ProjectID: "source", - Shared: true, Driver: domain.SandboxDriverNative, EnvironmentID: "private-environment", - }); err != nil { - return domain.WorkflowDefinition{}, err - } - return domain.WorkflowDefinition{ - ID: "child-with-private-environment", Name: "Child with private environment", ProjectID: "source", Shared: true, - SandboxProfileID: "shared-sandbox-with-private-environment", - Nodes: []domain.WorkflowNode{{ID: "approve", Name: "Approve", Type: "approval"}}, - }, nil - }, - }, - { - name: "docker sandbox with private dockerfile", - expected: "Dockerfile", - setupChild: func(st *repo.Store) (domain.WorkflowDefinition, error) { - if err := st.PutDockerfile(domain.DockerfileDefinition{ - ID: "private-dockerfile", Name: "Private Dockerfile", ProjectID: "source", Content: "FROM scratch\n", - }); err != nil { - return domain.WorkflowDefinition{}, err - } - if err := st.PutSandbox(domain.SandboxProfile{ - ID: "shared-docker-sandbox", Name: "Shared Docker sandbox", ProjectID: "source", - Shared: true, Driver: domain.SandboxDriverDocker, DockerfileID: "private-dockerfile", - }); err != nil { - return domain.WorkflowDefinition{}, err - } - return domain.WorkflowDefinition{ - ID: "child-with-private-dockerfile", Name: "Child with private Dockerfile", ProjectID: "source", Shared: true, - SandboxProfileID: "shared-docker-sandbox", - Nodes: []domain.WorkflowNode{{ID: "approve", Name: "Approve", Type: "approval"}}, - }, nil - }, - }, { name: "private role node", expected: "角色", diff --git a/internal/engine/sop_node_test.go b/internal/engine/sop_node_test.go index 4b55bafc6..2c7d0c5e5 100644 --- a/internal/engine/sop_node_test.go +++ b/internal/engine/sop_node_test.go @@ -75,7 +75,7 @@ func TestSOPNodeArtifactWriteFailureKeepsSuccessfulChild(t *testing.T) { func startSOPArtifactHandoff(t *testing.T, s *repo.Store) domain.Run { t.Helper() child := domain.WorkflowDefinition{ - ID: "child-prd", Name: "Child PRD", SandboxProfileID: "local", + ID: "child-prd", Name: "Child PRD", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ ID: "write", Name: "Write", Type: "script", ScriptLanguage: "shell", Script: "printf '# PRD\\nready\\n' > prd.md", MaxAttempts: 1, @@ -83,7 +83,7 @@ func startSOPArtifactHandoff(t *testing.T, s *repo.Store) domain.Run { }}, } parent := domain.WorkflowDefinition{ - ID: "req-flow", Name: "Requirement flow", SandboxProfileID: "local", + ID: "req-flow", Name: "Requirement flow", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ { ID: "prd-sop", Name: "产品 SOP", Type: "sop", SOPWorkflowID: child.ID, MaxAttempts: 2, @@ -123,11 +123,11 @@ func TestSOPChildSuccessDoesNotDeliverParentIssue(t *testing.T) { t.Fatal(err) } child := domain.WorkflowDefinition{ - ID: "child-ok", Name: "Child", SandboxProfileID: "local", + ID: "child-ok", Name: "Child", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "ok", Name: "OK", Type: "script", ScriptLanguage: "shell", Script: "true", MaxAttempts: 1}}, } parent := domain.WorkflowDefinition{ - ID: "parent-fails", Name: "Parent", SandboxProfileID: "local", + ID: "parent-fails", Name: "Parent", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "sub", Name: "Sub", Type: "sop", SOPWorkflowID: child.ID, MaxAttempts: 1}, {ID: "boom", Name: "Boom", Type: "script", ScriptLanguage: "shell", Script: "exit 1", MaxAttempts: 1}, @@ -166,11 +166,11 @@ func TestSOPNodeReattachesChildAfterDrain(t *testing.T) { defer s.Close() marker := filepath.Join(t.TempDir(), "go") child := domain.WorkflowDefinition{ - ID: "slow-child", Name: "Slow child", SandboxProfileID: "local", + ID: "slow-child", Name: "Slow child", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "wait", Name: "Wait", Type: "command", Command: "while [ ! -e " + marker + " ]; do sleep 0.05; done", MaxAttempts: 3}}, } parent := domain.WorkflowDefinition{ - ID: "parent-drain", Name: "Parent", SandboxProfileID: "local", + ID: "parent-drain", Name: "Parent", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "sub", Name: "Sub", Type: "sop", SOPWorkflowID: child.ID, MaxAttempts: 3}}, } for _, wf := range []domain.WorkflowDefinition{child, parent} { @@ -257,11 +257,11 @@ func TestSOPNodePauseCascadesAndReusesFinishedChild(t *testing.T) { defer s.Close() marker := filepath.Join(t.TempDir(), "go") child := domain.WorkflowDefinition{ - ID: "pause-child", Name: "Child", SandboxProfileID: "local", + ID: "pause-child", Name: "Child", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "wait", Name: "Wait", Type: "command", Command: "while [ ! -e " + marker + " ]; do sleep 0.05; done", MaxAttempts: 1}}, } parent := domain.WorkflowDefinition{ - ID: "pause-parent", Name: "Parent", SandboxProfileID: "local", + ID: "pause-parent", Name: "Parent", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "sub", Name: "Sub", Type: "sop", SOPWorkflowID: child.ID, MaxAttempts: 1}}, } for _, wf := range []domain.WorkflowDefinition{child, parent} { @@ -319,15 +319,15 @@ func TestSOPNodeRepointedWhilePausedStartsNewChild(t *testing.T) { defer s.Close() marker := filepath.Join(t.TempDir(), "go") oldChild := domain.WorkflowDefinition{ - ID: "old-child", Name: "Old", SandboxProfileID: "local", + ID: "old-child", Name: "Old", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "wait", Name: "Wait", Type: "command", Command: "while [ ! -e " + marker + " ]; do sleep 0.05; done", MaxAttempts: 1}}, } newChild := domain.WorkflowDefinition{ - ID: "new-child", Name: "New", SandboxProfileID: "local", + ID: "new-child", Name: "New", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "ok", Name: "OK", Type: "command", Command: "true", MaxAttempts: 1}}, } parent := domain.WorkflowDefinition{ - ID: "repoint-parent", Name: "Parent", SandboxProfileID: "local", + ID: "repoint-parent", Name: "Parent", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "sub", Name: "Sub", Type: "sop", SOPWorkflowID: oldChild.ID, MaxAttempts: 1}}, } for _, wf := range []domain.WorkflowDefinition{oldChild, newChild, parent} { @@ -404,11 +404,11 @@ func pauseParentThen(t *testing.T, cancelInstead bool) { defer s.Close() marker := filepath.Join(t.TempDir(), "go") child := domain.WorkflowDefinition{ - ID: "resume-child", Name: "Child", SandboxProfileID: "local", + ID: "resume-child", Name: "Child", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "wait", Name: "Wait", Type: "command", Command: "while [ ! -e " + marker + " ]; do sleep 0.05; done", MaxAttempts: 1}}, } parent := domain.WorkflowDefinition{ - ID: "resume-parent", Name: "Parent", SandboxProfileID: "local", + ID: "resume-parent", Name: "Parent", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "sub", Name: "Sub", Type: "sop", SOPWorkflowID: child.ID, MaxAttempts: 1}}, } for _, wf := range []domain.WorkflowDefinition{child, parent} { @@ -465,11 +465,11 @@ func TestSOPChildRetryResumesFailedParent(t *testing.T) { defer s.Close() marker := filepath.Join(t.TempDir(), "ok") child := domain.WorkflowDefinition{ - ID: "flaky-child", Name: "Child", SandboxProfileID: "local", + ID: "flaky-child", Name: "Child", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "check", Name: "Check", Type: "command", Command: "test -e " + marker, MaxAttempts: 1}}, } parent := domain.WorkflowDefinition{ - ID: "flaky-parent", Name: "Parent", SandboxProfileID: "local", + ID: "flaky-parent", Name: "Parent", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "sub", Name: "Sub", Type: "sop", SOPWorkflowID: child.ID, MaxAttempts: 1}, {ID: "after", Name: "After", Type: "command", Command: "true", MaxAttempts: 1}, @@ -512,11 +512,11 @@ func startPausedParentWithChild(t *testing.T, s *repo.Store, e *Engine, prefix s t.Helper() marker = filepath.Join(t.TempDir(), "go") child := domain.WorkflowDefinition{ - ID: prefix + "-child", Name: "Child", SandboxProfileID: "local", + ID: prefix + "-child", Name: "Child", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "wait", Name: "Wait", Type: "command", Command: "while [ ! -e " + marker + " ]; do sleep 0.05; done", MaxAttempts: 1}}, } parent := domain.WorkflowDefinition{ - ID: prefix + "-parent", Name: "Parent", SandboxProfileID: "local", + ID: prefix + "-parent", Name: "Parent", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "sub", Name: "Sub", Type: "sop", SOPWorkflowID: child.ID, MaxAttempts: 1}}, } if before { @@ -603,11 +603,11 @@ func TestSOPChildPassResumesFailedParent(t *testing.T) { } defer s.Close() child := domain.WorkflowDefinition{ - ID: "pass-child", Name: "Child", SandboxProfileID: "local", + ID: "pass-child", Name: "Child", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "check", Name: "Check", Type: "command", Command: "false", MaxAttempts: 1}}, } parent := domain.WorkflowDefinition{ - ID: "pass-parent", Name: "Parent", SandboxProfileID: "local", + ID: "pass-parent", Name: "Parent", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "sub", Name: "Sub", Type: "sop", SOPWorkflowID: child.ID, MaxAttempts: 1}, {ID: "after", Name: "After", Type: "command", Command: "true", MaxAttempts: 1}, @@ -644,7 +644,7 @@ func TestSOPNodeRejectsSelfReference(t *testing.T) { } defer s.Close() wf := domain.WorkflowDefinition{ - ID: "loop", Name: "Loop", SandboxProfileID: "local", + ID: "loop", Name: "Loop", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "self", Name: "Self", Type: "sop", SOPWorkflowID: "loop", MaxAttempts: 1}}, } if err := s.PutWorkflow(wf); err != nil { diff --git a/internal/engine/state_helpers_cases_test.go b/internal/engine/state_helpers_cases_test.go index 0196a1457..df5a68c39 100644 --- a/internal/engine/state_helpers_cases_test.go +++ b/internal/engine/state_helpers_cases_test.go @@ -14,7 +14,7 @@ import ( func TestLifecycleResetSettleAndForceTerminate(t *testing.T) { script := domain.WorkflowNode{ID: "script", Type: "script"} agent := domain.WorkflowNode{ID: "agent", Type: "agent"} - wf := domain.WorkflowDefinition{ID: "wf", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{script, agent}} + wf := domain.WorkflowDefinition{ID: "wf", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{script, agent}} run := domain.Run{ID: "life", Status: "running", WorkflowSnapshot: wf, Nodes: map[string]*domain.NodeRun{ "script": {NodeID: "script", Status: "running", Attempt: 2, SessionID: "script-session"}, "agent": {NodeID: "agent", Status: "pending_input", Attempt: 1, SessionID: "agent-session"}, diff --git a/internal/engine/transport_events_cases_test.go b/internal/engine/transport_events_cases_test.go index 20faf2de5..8b10eaee1 100644 --- a/internal/engine/transport_events_cases_test.go +++ b/internal/engine/transport_events_cases_test.go @@ -296,7 +296,7 @@ func TestLocalWorkspaceCheckpointMoreBranches(t *testing.T) { e.controlToken = "local-token" run := domain.Run{ ID: "local-checkpoint-more", Status: "failed", - WorkflowSnapshot: domain.WorkflowDefinition{SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "prepare", Type: "script", ScriptLanguage: "shell", Script: "true", RunOnWorkspaceRebuild: true}}}, + WorkflowSnapshot: domain.WorkflowDefinition{SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "prepare", Type: "script", ScriptLanguage: "shell", Script: "true", RunOnWorkspaceRebuild: true}}}, Nodes: map[string]*domain.NodeRun{}, } if err := st.PutRun(run); err != nil { @@ -436,7 +436,7 @@ func TestLocalWorkspaceCheckpointMoreBranches(t *testing.T) { t.Fatalf("unregistered runner preparation=%d body=%s", unregisteredRec.Code, unregisteredRec.Body.String()) } - busy := domain.Run{ID: "local-checkpoint-busy-more", Status: "running", WorkflowSnapshot: domain.WorkflowDefinition{SandboxProfileID: "local"}, Nodes: map[string]*domain.NodeRun{}} + busy := domain.Run{ID: "local-checkpoint-busy-more", Status: "running", WorkflowSnapshot: domain.WorkflowDefinition{SandboxProfileID: "test-native"}, Nodes: map[string]*domain.NodeRun{}} if err := st.PutRun(busy); err != nil { t.Fatal(err) } diff --git a/internal/engine/workflow_graph.go b/internal/engine/workflow_graph.go index d4d299c32..e20fd5d9d 100644 --- a/internal/engine/workflow_graph.go +++ b/internal/engine/workflow_graph.go @@ -42,8 +42,8 @@ func workflowForRun(s *repo.Store, run domain.Run) domain.WorkflowDefinition { if run.WorkflowSnapshot.ID != "" { // Compatibility: runs created before sandbox ownership moved to the // workflow may have a frozen snapshot without sandboxProfileId. Keep - // the frozen graph and use the legacy default local profile so retries - // and approvals do not depend on later workflow edits. + // the frozen graph and use the default sandbox so retries and + // approvals do not depend on later workflow edits. return defaultWorkflowSandboxProfile(run.WorkflowSnapshot) } wf, _ := latestWorkflowDefinition(s, run.WorkflowID) @@ -52,7 +52,7 @@ func workflowForRun(s *repo.Store, run domain.Run) domain.WorkflowDefinition { func defaultWorkflowSandboxProfile(wf domain.WorkflowDefinition) domain.WorkflowDefinition { if strings.TrimSpace(wf.SandboxProfileID) == "" { - wf.SandboxProfileID = "local" + wf.SandboxProfileID = repo.DefaultSandboxProfileID } return wf } diff --git a/internal/engine/workspace_artifacts_test.go b/internal/engine/workspace_artifacts_test.go index 6c6588d91..292c9f0e6 100644 --- a/internal/engine/workspace_artifacts_test.go +++ b/internal/engine/workspace_artifacts_test.go @@ -179,7 +179,7 @@ func TestLegacyArchivedFilesRefillOnOwningWorker(t *testing.T) { func TestLegacyNodeReplayCanReadOriginalReportPaths(t *testing.T) { t.Parallel() e, s := newRecoveryEngine(t) - wf := domain.WorkflowDefinition{ID: "legacy-original-paths", Name: "legacy original paths", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{ + wf := domain.WorkflowDefinition{ID: "legacy-original-paths", Name: "legacy original paths", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "design", Type: "command", Command: "printf archived-design > design.md", ArtifactOutputs: []domain.ArtifactContract{{Name: "design", Path: "design.md", Required: true}}, MaxAttempts: 1}, {ID: "implement", Type: "command", Command: "test \"$(cat design.md)\" = archived-design && test ! -e current.md && printf fresh > current.md", ArtifactOutputs: []domain.ArtifactContract{{Name: "current", Path: "current.md", Required: true}}, MaxAttempts: 1}, }, Edges: []domain.WorkflowEdge{{Source: "design", Target: "implement", When: "success"}}} diff --git a/internal/engine/workspace_checkpoint_child_test.go b/internal/engine/workspace_checkpoint_child_test.go index 3dfd35d80..105409a04 100644 --- a/internal/engine/workspace_checkpoint_child_test.go +++ b/internal/engine/workspace_checkpoint_child_test.go @@ -24,7 +24,7 @@ func TestSharedChildWorkspaceControlPreservesOwnerAndSnapshotProtection(t *testi if err = s.PutRunner(domain.Runner{ID: "runner", RunnerVersion: domain.RunnerVersionWorkspaceOwnerPreparation, Status: domain.RunnerStatusOnline}); err != nil { t.Fatal(err) } - child := domain.Run{ID: "child", Status: "running", ExecutionContext: domain.TelemetryContext{ExecutionMode: domain.ExecutionModeRunner, ExecutionRunnerID: "runner", RunnerWorkspaceLayout: domain.RunnerWorkspaceLayoutShared, WorkspaceRunID: "parent"}, WorkflowSnapshot: domain.WorkflowDefinition{ID: "child-flow", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "prepare", Type: "script", Script: "true", RunOnWorkspaceRebuild: true}}}, Nodes: map[string]*domain.NodeRun{}} + child := domain.Run{ID: "child", Status: "running", ExecutionContext: domain.TelemetryContext{ExecutionMode: domain.ExecutionModeRunner, ExecutionRunnerID: "runner", RunnerWorkspaceLayout: domain.RunnerWorkspaceLayoutShared, WorkspaceRunID: "parent"}, WorkflowSnapshot: domain.WorkflowDefinition{ID: "child-flow", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "prepare", Type: "script", Script: "true", RunOnWorkspaceRebuild: true}}}, Nodes: map[string]*domain.NodeRun{}} if err = s.PutRun(child); err != nil { t.Fatal(err) } diff --git a/internal/engine/workspace_cleanup.go b/internal/engine/workspace_cleanup.go index 3d5200d85..0cd586f1f 100644 --- a/internal/engine/workspace_cleanup.go +++ b/internal/engine/workspace_cleanup.go @@ -390,7 +390,13 @@ func (e *Engine) reclaimSandboxes() { if idle := e.discardIdleRunContainers(context.Background(), time.Now().UTC()); idle > 0 { log.Printf("discarded %d idle failed/waiting sandbox container(s)", idle) } - images, err := e.sandboxes.ReclaimCachedDockerImages(context.Background(), append(e.repo.Dockerfiles(), e.repo.LiveSandboxDockerfiles()...)) + keep := e.repo.LiveSandboxDockerfiles() + for _, profile := range e.repo.Sandboxes() { + if spec := domain.RunnerSandbox(profile); spec.Dockerfile != nil { + keep = append(keep, *spec.Dockerfile) + } + } + images, err := e.sandboxes.ReclaimCachedDockerImages(context.Background(), keep) if err != nil { log.Printf("reclaim cached docker images: %v", err) return diff --git a/internal/engine/workspace_owner_test.go b/internal/engine/workspace_owner_test.go index 8a4eb6e3c..6c8860549 100644 --- a/internal/engine/workspace_owner_test.go +++ b/internal/engine/workspace_owner_test.go @@ -22,14 +22,14 @@ func TestSOPChildWorksInParentWorkspace(t *testing.T) { } defer s.Close() child := domain.WorkflowDefinition{ - ID: "child-edit", Name: "Child", SandboxProfileID: "local", + ID: "child-edit", Name: "Child", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ ID: "edit", Name: "Edit", Type: "script", ScriptLanguage: "shell", Script: "test -f pre.txt && printf child > child.txt", MaxAttempts: 1, }}, } parent := domain.WorkflowDefinition{ - ID: "parent-edit", Name: "Parent", SandboxProfileID: "local", + ID: "parent-edit", Name: "Parent", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "pre", Name: "Pre", Type: "script", ScriptLanguage: "shell", Script: "printf pre > pre.txt", MaxAttempts: 1}, {ID: "sub", Name: "Sub", Type: "sop", SOPWorkflowID: child.ID, MaxAttempts: 1}, @@ -98,7 +98,7 @@ func TestRetryOnDeadBoundHostIsTakenOverByLiveWorker(t *testing.T) { s, _ := repo.OpenTest() defer s.Close() marker := filepath.Join(t.TempDir(), "ready") - wf := domain.WorkflowDefinition{ID: "retry-takeover", Name: "retry", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ + wf := domain.WorkflowDefinition{ID: "retry-takeover", Name: "retry", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ ID: "work", Name: "work", Type: "command", Command: "test -e " + marker, MaxAttempts: 1, }}} if err := s.PutWorkflow(wf); err != nil { diff --git a/internal/engine/workspace_preparation.go b/internal/engine/workspace_preparation.go index 1491e5baa..b10bf6724 100644 --- a/internal/engine/workspace_preparation.go +++ b/internal/engine/workspace_preparation.go @@ -13,19 +13,22 @@ import ( ) func (e *Engine) workspaceSandboxProfile(run domain.Run) (domain.SandboxProfile, runtime.SandboxResources, error) { - if spec := run.WorkflowSnapshot.SandboxSnapshot; spec != nil { - return spec.Profile, sandboxResourcesFromSnapshot(spec), nil - } - id := strings.TrimSpace(run.WorkflowSnapshot.SandboxProfileID) - if id == "" { - id = "local" - } - profile, ok := e.repo.Sandbox(id) - if !ok { - return profile, runtime.SandboxResources{}, fmt.Errorf("sandbox profile %q not found", id) + spec := run.WorkflowSnapshot.SandboxSnapshot + if spec == nil { + id := strings.TrimSpace(run.WorkflowSnapshot.SandboxProfileID) + if id == "" { + id = repo.DefaultSandboxProfileID + } + profile, ok := e.repo.Sandbox(id) + if !ok { + return profile, runtime.SandboxResources{}, fmt.Errorf("sandbox profile %q not found", id) + } + var err error + if spec, err = resolveSandbox(profile); err != nil { + return profile, runtime.SandboxResources{}, err + } } - resources, err := resolveSandboxResources(e.repo, profile) - return profile, resources, err + return spec.Profile, sandboxResourcesFromSnapshot(spec), nil } // acquireConversationEnvironment does not acquire or steal the SOP scheduler @@ -147,6 +150,9 @@ func (e *Engine) preparedWorkspaceRequest(run domain.Run, request domain.RunnerW credentials := e.resolveRunCredentials(run) invocation := &domain.RunnerInvocation{} bindRunnerRepositories(invocation, run, credentials.GitUserName, credentials.GitUserEmail) + if request.Operation == domain.RunnerWorkspaceOperationPrepare { + invocation.CacheRepositories = e.workspaceCacheRepositories(run) + } invocation.GitSSHUserID = 0 invocation.GitHTTPUserID = 0 assets := e.resolveScriptMCPAssets(run.ExecutionContext.ProjectID, run.ExecutionContext.ResponsibleUserID) diff --git a/internal/engine/workspace_preparation_shared_test.go b/internal/engine/workspace_preparation_shared_test.go index bdbb240a1..27c6bc799 100644 --- a/internal/engine/workspace_preparation_shared_test.go +++ b/internal/engine/workspace_preparation_shared_test.go @@ -22,7 +22,7 @@ func TestSharedWorkspacePreparationConversationUsesOwnerDirectoryAndSeparateRece root := t.TempDir() e := New(store, runtime.NewManagerWithLimit(root, 2)) makeRun := func(id, label, owner string) domain.Run { - return domain.Run{ID: id, WorkflowID: id, Status: "succeeded", ExecutionContext: domain.TelemetryContext{ExecutionMode: domain.ExecutionModeCloud, WorkspaceRunID: owner}, WorkflowSnapshot: domain.WorkflowDefinition{ID: id, SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "prepare", Name: "Prepare " + label, Type: "script", RunOnWorkspaceRebuild: true, Script: "mkdir -p .agentflow; printf '" + label + "\\n' >> .agentflow/shared-preparation-count"}}}, Nodes: map[string]*domain.NodeRun{"prepare": {NodeID: "prepare", Status: "succeeded", Attempt: 1}}} + return domain.Run{ID: id, WorkflowID: id, Status: "succeeded", ExecutionContext: domain.TelemetryContext{ExecutionMode: domain.ExecutionModeCloud, WorkspaceRunID: owner}, WorkflowSnapshot: domain.WorkflowDefinition{ID: id, SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "prepare", Name: "Prepare " + label, Type: "script", RunOnWorkspaceRebuild: true, Script: "mkdir -p .agentflow; printf '" + label + "\\n' >> .agentflow/shared-preparation-count"}}}, Nodes: map[string]*domain.NodeRun{"prepare": {NodeID: "prepare", Status: "succeeded", Attempt: 1}}} } parent := makeRun("shared-parent", "parent", "") child := makeRun("shared-child", "child", parent.ID) @@ -72,8 +72,8 @@ func TestSharedWorkspaceFlaggedChildDoesNotRepeatParentScript(t *testing.T) { t.Fatal(err) } defer store.Close() - child := domain.WorkflowDefinition{ID: "child-rebuild-script", Name: "Child", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "prepare", Name: "Child prepare", Type: "script", ScriptLanguage: "shell", RunOnWorkspaceRebuild: true, MaxAttempts: 1, Script: "test -f parent.txt && printf 'child\\n' >> .agentflow/shared-flow-order && printf child > child.txt"}}} - parent := domain.WorkflowDefinition{ID: "parent-rebuild-script", Name: "Parent", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{ + child := domain.WorkflowDefinition{ID: "child-rebuild-script", Name: "Child", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "prepare", Name: "Child prepare", Type: "script", ScriptLanguage: "shell", RunOnWorkspaceRebuild: true, MaxAttempts: 1, Script: "test -f parent.txt && printf 'child\\n' >> .agentflow/shared-flow-order && printf child > child.txt"}}} + parent := domain.WorkflowDefinition{ID: "parent-rebuild-script", Name: "Parent", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "prepare", Name: "Parent prepare", Type: "script", ScriptLanguage: "shell", RunOnWorkspaceRebuild: true, MaxAttempts: 1, Script: "mkdir -p .agentflow; printf 'parent\\n' >> .agentflow/shared-flow-order; printf parent > parent.txt"}, {ID: "sub", Name: "Child SOP", Type: "sop", SOPWorkflowID: child.ID, MaxAttempts: 1}, {ID: "after", Name: "Parent resumes", Type: "script", ScriptLanguage: "shell", MaxAttempts: 1, Script: "test -f child.txt && test \"$(grep -c '^parent$' .agentflow/shared-flow-order)\" = 1 && test \"$(grep -c '^child$' .agentflow/shared-flow-order)\" = 1 && printf 'after\\n' >> .agentflow/shared-flow-order"}, @@ -121,7 +121,7 @@ func TestSharedWorkspacePreparationRequestCarriesOwnerWithoutChangingChildIdenti if err = store.PutRunner(runner); err != nil { t.Fatal(err) } - child := domain.Run{ID: "child-run", ExecutionContext: domain.TelemetryContext{ExecutionMode: domain.ExecutionModeRunner, ExecutionRunnerID: runner.ID, RunnerWorkspaceLayout: domain.RunnerWorkspaceLayoutShared, WorkspaceRunID: "parent-run"}, WorkflowSnapshot: domain.WorkflowDefinition{ID: "child-flow", SandboxProfileID: "local"}, Nodes: map[string]*domain.NodeRun{}} + child := domain.Run{ID: "child-run", ExecutionContext: domain.TelemetryContext{ExecutionMode: domain.ExecutionModeRunner, ExecutionRunnerID: runner.ID, RunnerWorkspaceLayout: domain.RunnerWorkspaceLayoutShared, WorkspaceRunID: "parent-run"}, WorkflowSnapshot: domain.WorkflowDefinition{ID: "child-flow", SandboxProfileID: "test-native"}, Nodes: map[string]*domain.NodeRun{}} request, err := e.preparedWorkspaceRequest(child, domain.RunnerWorkspaceRequest{RunID: child.ID, WorkspaceRunID: "untrusted-directory", Operation: domain.RunnerWorkspaceOperationPrepare}) if err != nil { t.Fatal(err) diff --git a/internal/engine/workspace_preparation_test.go b/internal/engine/workspace_preparation_test.go index eb6ef048f..1cabdf498 100644 --- a/internal/engine/workspace_preparation_test.go +++ b/internal/engine/workspace_preparation_test.go @@ -15,7 +15,7 @@ import ( ) func preparationWorkflow() domain.WorkflowDefinition { - return domain.WorkflowDefinition{ID: "workspace-preparation", Name: "Workspace preparation", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{ + return domain.WorkflowDefinition{ID: "workspace-preparation", Name: "Workspace preparation", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "env", Name: "准备环境", Type: "script", ScriptLanguage: "shell", Script: "mkdir -p .agentflow; echo run >> .agentflow/env-count; printf environment-ready", RunOnWorkspaceRebuild: true, MaxAttempts: 1}, {ID: "index", Name: "建立索引", Type: "script", ScriptLanguage: "shell", Script: "echo run >> .agentflow/index-count; printf index-ready", RunOnWorkspaceRebuild: true, MaxAttempts: 1}, {ID: "work", Name: "正常业务", Type: "script", ScriptLanguage: "shell", Script: "printf business-ok", MaxAttempts: 1}, @@ -281,7 +281,7 @@ func TestWorkspacePreparationRecordFailureDoesNotRetrySuccessfulBusinessScript(t t.Fatal(err) } defer st.Close() - wf := domain.WorkflowDefinition{ID: "record-warning", Name: "Record warning", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "script", Name: "成功脚本", Type: "script", ScriptLanguage: "shell", RunOnWorkspaceRebuild: true, MaxAttempts: 3, Script: "printf 'run\\n' >> count.txt; mv .agentflow/workspace-preparation .agentflow/saved-preparation; ln -s saved-preparation .agentflow/workspace-preparation; printf actually-succeeded"}, {ID: "pause", Type: "approval", MaxAttempts: 1}}, Edges: []domain.WorkflowEdge{{Source: "script", Target: "pause", When: "success"}}} + wf := domain.WorkflowDefinition{ID: "record-warning", Name: "Record warning", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "script", Name: "成功脚本", Type: "script", ScriptLanguage: "shell", RunOnWorkspaceRebuild: true, MaxAttempts: 3, Script: "printf 'run\\n' >> count.txt; mv .agentflow/workspace-preparation .agentflow/saved-preparation; ln -s saved-preparation .agentflow/workspace-preparation; printf actually-succeeded"}, {ID: "pause", Type: "approval", MaxAttempts: 1}}, Edges: []domain.WorkflowEdge{{Source: "script", Target: "pause", When: "success"}}} if err = st.PutWorkflow(wf); err != nil { t.Fatal(err) } diff --git a/internal/engine/workspace_restore_retry_test.go b/internal/engine/workspace_restore_retry_test.go index 3a1afb54d..26fcbfb2a 100644 --- a/internal/engine/workspace_restore_retry_test.go +++ b/internal/engine/workspace_restore_retry_test.go @@ -48,7 +48,7 @@ func remoteWorkspaceRestoreFixture(t *testing.T, backend string) (*Engine, *Engi worker.ConfigureExecution("restore-worker-"+id, "restore-worker-"+id, time.Minute, false) worker.controlToken = "restore-retry-control" t.Cleanup(worker.checkpointTransfers.Close) - workflow := domain.WorkflowDefinition{ID: id, SandboxProfileID: "local", Nodes: []domain.WorkflowNode{ + workflow := domain.WorkflowDefinition{ID: id, SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "prepare", Type: "command"}, {ID: "close", Type: "agent", MaxAttempts: 1}, }, Edges: []domain.WorkflowEdge{{Source: "prepare", Target: "close", When: "success"}}} run := domain.Run{ID: id, WorkflowID: id, WorkflowSnapshot: workflow, Status: "succeeded", diff --git a/internal/gitwork/repository_cache.go b/internal/gitwork/repository_cache.go new file mode 100644 index 000000000..ab9e202d0 --- /dev/null +++ b/internal/gitwork/repository_cache.go @@ -0,0 +1,191 @@ +package gitwork + +import ( + "context" + "fmt" + "os" + "os/exec" + "path/filepath" + "regexp" + "strings" + "syscall" + "time" + + "agentflow/internal/procwatch" +) + +// RepositoryCacheEnv names the repository cache root inside a native sandbox. +const RepositoryCacheEnv = "LOOPFORGE_REPOSITORY_CACHE" + +type repositoryCacheKey struct{} + +// WithRepositoryCache lets clones in ctx start from the bare repository cache +// under root. Only workspaces that see the host filesystem (native sandboxes) +// may use it: a shared clone refers to the cache's objects by host path. +func WithRepositoryCache(ctx context.Context, root string) context.Context { + if strings.TrimSpace(root) == "" { + return ctx + } + return context.WithValue(ctx, repositoryCacheKey{}, root) +} + +// RepositoryCacheFrom is the cache root WithRepositoryCache put in ctx. +func RepositoryCacheFrom(ctx context.Context) string { + root, _ := ctx.Value(repositoryCacheKey{}).(string) + return root +} + +var repositoryCacheName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]*$`) + +// RepositoryCachePath is the bare cache of one repository record under root. +// Empty when the ID cannot be a directory name. +func RepositoryCachePath(root, repositoryID string) string { + id := strings.TrimSpace(repositoryID) + if strings.TrimSpace(root) == "" || !repositoryCacheName.MatchString(id) || strings.Contains(id, "..") { + return "" + } + return filepath.Join(root, id+".git") +} + +// RefreshRepositoryCache creates or fetches the bare cache of repositoryID +// from remote and returns its path. Branches mirror the remote's heads; the +// cache never runs gc, because shared clones borrow its objects. +func RefreshRepositoryCache(ctx context.Context, root, repositoryID, remote string, watch procwatch.Options) (string, error) { + dir := RepositoryCachePath(root, repositoryID) + if dir == "" { + return "", fmt.Errorf("仓库 %q 不能用作缓存目录名", repositoryID) + } + if err := ValidateRemoteURL(remote, true); err != nil { + return "", err + } + unlock, err := lockRepositoryCache(ctx, dir) + if err != nil { + return "", err + } + defer unlock() + return dir, refreshLockedCache(ctx, dir, remote, watch) +} + +// CloneFromRepositoryCache refreshes the cache, then makes the empty +// workspace a shared clone of it whose origin is remote again. branch empty +// checks out the remote's default branch. On failure workspace is emptied +// again, ready for a full clone. +func CloneFromRepositoryCache(ctx context.Context, root, repositoryID, remote, branch, workspace string, watch procwatch.Options) (err error) { + dir := RepositoryCachePath(root, repositoryID) + if dir == "" { + return fmt.Errorf("仓库 %q 不能用作缓存目录名", repositoryID) + } + if err := ValidateRemoteURL(remote, true); err != nil { + return err + } + unlock, err := lockRepositoryCache(ctx, dir) + if err != nil { + return err + } + defer unlock() + if err := refreshLockedCache(ctx, dir, remote, watch); err != nil { + return err + } + defer func() { + if err != nil { + _ = emptyDirectory(workspace) + } + }() + args := []string{"clone", "--quiet", "--shared"} + if branch = strings.TrimSpace(branch); branch != "" { + args = append(args, "--branch", branch) + } + if err := localGit(ctx, "-C", workspace, append(args, "--", dir, ".")...); err != nil { + return err + } + return localGit(ctx, "-C", workspace, "remote", "set-url", "origin", remote) +} + +func refreshLockedCache(ctx context.Context, dir, remote string, watch procwatch.Options) error { + if out, err := exec.CommandContext(ctx, "git", "--git-dir", dir, "rev-parse", "--is-bare-repository").Output(); err != nil || strings.TrimSpace(string(out)) != "true" { + if err := os.RemoveAll(dir); err != nil { + return err + } + if err := os.MkdirAll(filepath.Dir(dir), 0o700); err != nil { + return err + } + tmp, err := os.MkdirTemp(filepath.Dir(dir), filepath.Base(dir)+".tmp-") + if err != nil { + return err + } + defer os.RemoveAll(tmp) + if _, err := Watch(ctx, filepath.Dir(dir), watch, "clone", "--bare", "--progress", "--", remote, tmp); err != nil { + return fmt.Errorf("git clone --bare: %w", err) + } + // Name the bare Git directory explicitly for hosts with + // safe.bareRepository=explicit. + for _, setting := range [][2]string{{"gc.auto", "0"}, {"maintenance.auto", "false"}, {"gc.pruneExpire", "never"}, {"fetch.prune", "false"}} { + if err := localGit(ctx, "--git-dir", tmp, "config", setting[0], setting[1]); err != nil { + return err + } + } + return os.Rename(tmp, dir) + } + if err := localGit(ctx, "--git-dir", dir, "remote", "set-url", "origin", remote); err != nil { + return err + } + watch.Label = strings.Replace(watch.Label, "克隆", "更新", 1) + if _, err := Watch(ctx, dir, watch, "-C", dir, "fetch", "--progress", "--prune", "--force", "--", remote, "+refs/heads/*:refs/heads/*", "+refs/tags/*:refs/tags/*"); err != nil { + return fmt.Errorf("git fetch: %w", err) + } + return nil +} + +// emptyDirectory removes the contents of dir but keeps dir itself, whose +// inode a sandbox may have bound. +func emptyDirectory(dir string) error { + entries, err := os.ReadDir(dir) + if err != nil { + return err + } + for _, entry := range entries { + if err := os.RemoveAll(filepath.Join(dir, entry.Name())); err != nil { + return err + } + } + return nil +} + +func localGit(ctx context.Context, dirOption, dir string, args ...string) error { + cmd := exec.CommandContext(ctx, "git", append([]string{dirOption, dir}, args...)...) + cmd.Env = WithEnvValue(Env(""), "GIT_CONFIG_NOSYSTEM", "1") + if out, err := cmd.CombinedOutput(); err != nil { + return fmt.Errorf("git %s: %w (%s)", args[0], err, strings.TrimSpace(string(out))) + } + return nil +} + +func lockRepositoryCache(ctx context.Context, dir string) (func(), error) { + if err := os.MkdirAll(filepath.Dir(dir), 0o700); err != nil { + return nil, err + } + f, err := os.OpenFile(dir+".lock", os.O_CREATE|os.O_RDWR, 0o600) + if err != nil { + return nil, err + } + for { + err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB) + if err == nil { + break + } + if err != syscall.EWOULDBLOCK && err != syscall.EAGAIN { + _ = f.Close() + return nil, err + } + select { + case <-ctx.Done(): + _ = f.Close() + return nil, ctx.Err() + case <-time.After(100 * time.Millisecond): + } + } + return func() { + _ = syscall.Flock(int(f.Fd()), syscall.LOCK_UN) + _ = f.Close() + }, nil +} diff --git a/internal/gitwork/repository_cache_test.go b/internal/gitwork/repository_cache_test.go new file mode 100644 index 000000000..79f62b117 --- /dev/null +++ b/internal/gitwork/repository_cache_test.go @@ -0,0 +1,122 @@ +package gitwork + +import ( + "context" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "agentflow/internal/procwatch" +) + +func cacheTestGit(t *testing.T, dir string, args ...string) string { + t.Helper() + cmd := exec.Command("git", append([]string{"-C", dir}, args...)...) + cmd.Env = append(os.Environ(), "GIT_CONFIG_NOSYSTEM=1", "GIT_AUTHOR_NAME=t", "GIT_AUTHOR_EMAIL=t@example.com", "GIT_COMMITTER_NAME=t", "GIT_COMMITTER_EMAIL=t@example.com") + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("git %v: %v %s", args, err, out) + } + return strings.TrimSpace(string(out)) +} + +func cacheTestCommit(t *testing.T, dir, name string) string { + t.Helper() + if err := os.WriteFile(filepath.Join(dir, name), []byte(name), 0o600); err != nil { + t.Fatal(err) + } + cacheTestGit(t, dir, "add", name) + cacheTestGit(t, dir, "commit", "-q", "-m", name) + return cacheTestGit(t, dir, "rev-parse", "HEAD") +} + +func TestRepositoryCachePathRejectsUnsafeIDs(t *testing.T) { + root := t.TempDir() + if got := RepositoryCachePath(root, "service"); got != filepath.Join(root, "service.git") { + t.Fatalf("cache path = %q", got) + } + for _, id := range []string{"", "../escape", "a/b", ".hidden", "a..b", "-flag"} { + if got := RepositoryCachePath(root, id); got != "" { + t.Fatalf("%q accepted as %q", id, got) + } + } + if got := RepositoryCachePath("", "service"); got != "" { + t.Fatalf("empty root accepted as %q", got) + } +} + +func TestCloneFromRepositoryCacheSharesObjectsAndKeepsOrigin(t *testing.T) { + config := filepath.Join(t.TempDir(), "gitconfig") + if err := os.WriteFile(config, []byte("[safe]\n\tbareRepository = explicit\n"), 0o600); err != nil { + t.Fatal(err) + } + t.Setenv("GIT_CONFIG_GLOBAL", config) + origin := t.TempDir() + cacheTestGit(t, origin, "init", "-q", "-b", "main") + first := cacheTestCommit(t, origin, "a.txt") + cacheTestGit(t, origin, "checkout", "-q", "-b", "feature") + feature := cacheTestCommit(t, origin, "b.txt") + cacheTestGit(t, origin, "checkout", "-q", "main") + remote := "file://" + origin + root := filepath.Join(t.TempDir(), "cache") + ctx := context.Background() + + workspace := t.TempDir() + if err := CloneFromRepositoryCache(ctx, root, "service", remote, "", workspace, procwatch.Options{}); err != nil { + t.Fatal(err) + } + cache := filepath.Join(root, "service.git") + if got := cacheTestGit(t, cache, "--git-dir=.", "config", "gc.auto"); got != "0" { + t.Fatalf("cache gc.auto = %q", got) + } + if head := cacheTestGit(t, workspace, "rev-parse", "HEAD"); head != first { + t.Fatalf("clone HEAD = %s, want %s", head, first) + } + if url := cacheTestGit(t, workspace, "remote", "get-url", "origin"); url != remote { + t.Fatalf("clone origin = %q, want the repository remote", url) + } + alternates, err := os.ReadFile(filepath.Join(workspace, ".git", "objects", "info", "alternates")) + if err != nil || !strings.Contains(string(alternates), cache) { + t.Fatalf("clone does not borrow the cache objects: %q %v", alternates, err) + } + + next := cacheTestCommit(t, origin, "c.txt") + branchWorkspace := t.TempDir() + if err := CloneFromRepositoryCache(ctx, root, "service", remote, "feature", branchWorkspace, procwatch.Options{}); err != nil { + t.Fatal(err) + } + if head := cacheTestGit(t, branchWorkspace, "rev-parse", "HEAD"); head != feature { + t.Fatalf("branch clone HEAD = %s, want %s", head, feature) + } + if got := cacheTestGit(t, cache, "--git-dir=.", "rev-parse", "refs/heads/main"); got != next { + t.Fatalf("cache main = %s, want the fetched %s", got, next) + } +} + +func TestRefreshRepositoryCacheReplacesABrokenCache(t *testing.T) { + origin := t.TempDir() + cacheTestGit(t, origin, "init", "-q", "-b", "main") + head := cacheTestCommit(t, origin, "a.txt") + root := t.TempDir() + if err := os.MkdirAll(filepath.Join(root, "service.git"), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(root, "service.git", "junk"), []byte("x"), 0o600); err != nil { + t.Fatal(err) + } + dir, err := RefreshRepositoryCache(context.Background(), root, "service", "file://"+origin, procwatch.Options{}) + if err != nil { + t.Fatal(err) + } + if got := cacheTestGit(t, dir, "--git-dir=.", "rev-parse", "refs/heads/main"); got != head { + t.Fatalf("cache main = %s, want %s", got, head) + } + if _, err := os.Stat(filepath.Join(dir, "junk")); !os.IsNotExist(err) { + t.Fatalf("broken cache content kept: %v", err) + } + if _, err := RefreshRepositoryCache(context.Background(), root, "../x", "file://"+origin, procwatch.Options{}); err == nil { + t.Fatal("unsafe repository ID accepted") + } +} diff --git a/internal/httpapi/assistant.go b/internal/httpapi/assistant.go index a67652658..cb1bb4aa1 100644 --- a/internal/httpapi/assistant.go +++ b/internal/httpapi/assistant.go @@ -1155,10 +1155,10 @@ const assistantNativeSystemPrompt = `你是 LoopForge 的统一协作助手。 const assistantWorkflowDocumentPrompt = `修改已有 SOP 时先用 workflows_get 或 workflows_revision_get 读取完整定义再改。workflows_save 按 id 整图覆盖 nodes 和 edges,未提交的节点会被删除。` const assistantDraftProtocolPrompt = `写入先形成草稿:不要直接调用平台写入工具。提交草稿前通过 workbench_tool_schema 读取目标工具的准确输入 schema,按 body/path/query 包装参数,不得猜字段或把它们放到错误层级。用户明确要求构建或修改时,先用只读工具读到现有定义,再在结束时调用 mcp__agentflow_session__submit_assistant_reply 提交待确认草稿。用户在界面确认后才会保存。不要用本地 Bash/Write/Edit 操作控制平面目录;代码任务先打开工作区,明确开始交接后结束当前阶段,平台续接到工作区后使用 CLI 原生文件和命令工具操作,不得声称已经保存、发布或运行。 -普通问答、解释和只读查询直接用自然语言回复,不调用 mcp__agentflow_session__submit_assistant_reply。需要待确认写入时必须通过 mcp__agentflow_session__submit_assistant_reply 提交草稿,每轮只提交 1 个草稿(即下一步要执行的一个操作):先在 message 中给出完整计划与依赖检查结论,再提交第一个草稿,用户确认保存后下一轮继续下一个草稿。构建 SOP(workflows_save)时,每个 agent 类型节点必须绑定当前项目已存在的角色 id(agentId)并填写 prompt,禁止提交未绑定角色的 agent 节点;所需角色还不存在时必须先提交创建角色的草稿,角色确认后再提交 SOP 草稿。提交删除类草稿(角色、规则、技能、沙箱、Dockerfile、环境、SOP 等)前,必须先用只读工具检查引用关系(例如删除角色前检查 workflows 节点是否引用该角色,删除沙箱前检查 SOP 是否绑定该沙箱),存在依赖时不要提交删除草稿,改为在 message 中说明并给出解除引用的方案;删除类草稿必须携带目标资源 id(path.id、query.id 或 body.id 均可),否则无法执行。 +普通问答、解释和只读查询直接用自然语言回复,不调用 mcp__agentflow_session__submit_assistant_reply。需要待确认写入时必须通过 mcp__agentflow_session__submit_assistant_reply 提交草稿,每轮只提交 1 个草稿(即下一步要执行的一个操作):先在 message 中给出完整计划与依赖检查结论,再提交第一个草稿,用户确认保存后下一轮继续下一个草稿。构建 SOP(workflows_save)时,每个 agent 类型节点必须绑定当前项目已存在的角色 id(agentId)并填写 prompt,禁止提交未绑定角色的 agent 节点;所需角色还不存在时必须先提交创建角色的草稿,角色确认后再提交 SOP 草稿。提交删除类草稿(角色、规则、技能、沙箱、SOP 等)前,必须先用只读工具检查引用关系(例如删除角色前检查 workflows 节点是否引用该角色,删除沙箱前检查 SOP 是否绑定该沙箱),存在依赖时不要提交删除草稿,改为在 message 中说明并给出解除引用的方案;删除类草稿必须携带目标资源 id(path.id、query.id 或 body.id 均可),否则无法执行。 ` + assistantWorkflowDocumentPrompt -const assistantAutoWriteProtocolPrompt = `当前审批模式为「完全权限」:用户已授权平台写入工具调用即生效。直接按依赖顺序调用平台读写工具完成任务的全部步骤(环境/Dockerfile → 沙箱 → Rules/Skills/MCP → 角色 → SOP → 定时任务),不要把写入放进 drafts,不要请求用户确认,也不要让用户说"继续":一次性完成全部步骤后,在 message 中按步骤汇总实际执行结果。构建 SOP 时每个 agent 类型节点必须绑定已存在的角色 id 并填写 prompt;所需角色不存在时先创建角色再保存 SOP。删除类操作前必须先用只读工具检查引用关系;平台返回冲突(如仍被引用)时如实说明并调整方案。不要用本地 Bash/Write/Edit 操作控制平面目录;代码任务先打开工作区,明确开始交接后结束当前阶段,平台续接到 Docker 内后使用 CLI 原生文件和命令工具操作。 +const assistantAutoWriteProtocolPrompt = `当前审批模式为「完全权限」:用户已授权平台写入工具调用即生效。直接按依赖顺序调用平台读写工具完成任务的全部步骤(沙箱 → Rules/Skills/MCP → 角色 → SOP → 定时任务),不要把写入放进 drafts,不要请求用户确认,也不要让用户说"继续":一次性完成全部步骤后,在 message 中按步骤汇总实际执行结果。构建 SOP 时每个 agent 类型节点必须绑定已存在的角色 id 并填写 prompt;所需角色不存在时先创建角色再保存 SOP。删除类操作前必须先用只读工具检查引用关系;平台返回冲突(如仍被引用)时如实说明并调整方案。不要用本地 Bash/Write/Edit 操作控制平面目录;代码任务先打开工作区,明确开始交接后结束当前阶段,平台续接到 Docker 内后使用 CLI 原生文件和命令工具操作。 ` + assistantWorkflowDocumentPrompt const assistantAssistedProtocolPrompt = `当前审批模式为「帮我批准」:直接调用平台写入工具,不要把写入放进 drafts,无需人工审批卡片。编程任务先打开工作区,明确开始交接后结束当前阶段,平台续接到工作区后使用 CLI 原生工具。工作区沙箱内的原生文件、补丁和命令直接执行。平台写入,以及 git push、gh pr create、gh api 或 curl 写请求、发布软件包等写入外部系统的命令执行前,平台会经规则快路径或独立审查模型根据本次操作、关键参数和当前用户的对话授权直接给出最终裁决(放行或拒绝),不按工具名一概放行。收到拒绝或审批不可用的提示后,不要绕过审查、不要提交 drafts、不要换工具实现同一副作用或反复重试;请调整方案或在自然语言回复中向用户说明未执行的原因。删除类操作前先用只读工具检查引用关系并携带目标 id。不要用本地 Bash/Write/Edit 操作控制平面目录。` + "\n" + assistantWorkflowDocumentPrompt diff --git a/internal/httpapi/assistant_acceptance.go b/internal/httpapi/assistant_acceptance.go index 69f2ec300..9ed902801 100644 --- a/internal/httpapi/assistant_acceptance.go +++ b/internal/httpapi/assistant_acceptance.go @@ -17,7 +17,7 @@ import ( const ( assistantAcceptanceLogin = "example-maintainer" assistantAcceptanceProjectID = "assistant-test" - assistantAcceptanceSandboxID = "assistant-local" + assistantAcceptanceSandboxID = "assistant-native" ) // AssistantAcceptanceIdentity is the local copy of a production user's @@ -172,7 +172,7 @@ func SeedAssistantAcceptance(st *repo.Store, ident AssistantAcceptanceIdentity) ID: assistantAcceptanceSandboxID, Name: "助手验收沙箱", ProjectID: assistantAcceptanceProjectID, - Driver: "local", + Driver: domain.SandboxDriverNative, }); err != nil { return domain.User{}, err } diff --git a/internal/httpapi/assistant_approval.go b/internal/httpapi/assistant_approval.go index be08d1170..0a005292c 100644 --- a/internal/httpapi/assistant_approval.go +++ b/internal/httpapi/assistant_approval.go @@ -312,23 +312,8 @@ func (h *assistantHandlers) assistantDraftWarnings(d assistantDraft) []string { return []string{fmt.Sprintf("技能 %s 不存在,执行将失败", id)} } return sharedAssetWarnings("技能", skill.Shared, h.agentNamesReferencing("skill", id), "角色") - case "dockerfiles_delete": - item, ok := h.repo.Dockerfile(id) - if !ok { - return []string{fmt.Sprintf("Dockerfile %s 不存在,执行将失败", id)} - } - if id == repo.GenericBackendDockerfileID { - return []string{"内置 Dockerfile generic-backend 不能删除"} - } - return sharedAssetWarnings("Dockerfile", item.Shared, h.sandboxNamesReferencing("dockerfile", id), "沙箱") - case "environments_delete": - item, ok := h.repo.Environment(id) - if !ok { - return []string{fmt.Sprintf("环境安装脚本 %s 不存在,执行将失败", id)} - } - return sharedAssetWarnings("环境安装脚本", item.Shared, h.sandboxNamesReferencing("environment", id), "沙箱") case "sandboxes_delete": - if id == "local" || id == repo.GenericDockerSandboxID { + if id == repo.GenericDockerSandboxID { return []string{fmt.Sprintf("内置沙箱 %s 不能删除", id)} } item, ok := h.repo.Sandbox(id) @@ -403,16 +388,6 @@ func (h *assistantHandlers) agentNamesReferencing(kind, id string) []string { return names } -func (h *assistantHandlers) sandboxNamesReferencing(kind, id string) []string { - var names []string - for _, sandbox := range h.repo.Sandboxes() { - if (kind == "dockerfile" && sandbox.DockerfileID == id) || (kind == "environment" && sandbox.EnvironmentID == id) { - names = append(names, sandbox.Name) - } - } - return names -} - func (h *assistantHandlers) workflowNamesReferencingSandbox(id string) []string { var names []string for _, workflow := range h.repo.Workflows() { diff --git a/internal/httpapi/assistant_browser_test.go b/internal/httpapi/assistant_browser_test.go index e1d0ae16d..380ac83ca 100644 --- a/internal/httpapi/assistant_browser_test.go +++ b/internal/httpapi/assistant_browser_test.go @@ -13,6 +13,7 @@ import ( "agentflow/internal/domain" "agentflow/internal/engine" + "agentflow/internal/repo" "agentflow/internal/runtime" "agentflow/internal/tracker" @@ -99,6 +100,8 @@ func TestMainBotBrowserStartsAndDrivesRunBrowser(t *testing.T) { h.api = New(a.repo, en, tracker.NewService(), "", "") r, _ := a.repo.RunState("shared-run") r.ID, r.Status, r.Nodes, r.WorkspaceCleanedAt = "browser-run-"+t.Name(), "succeeded", map[string]*domain.NodeRun{}, time.Time{} + // A host browser reaches the httptest page; a docker sidecar could not. + r.WorkflowSnapshot.SandboxProfileID = repo.TestNativeSandboxID if err := a.repo.PutRun(r); err != nil { t.Fatal(err) } diff --git a/internal/httpapi/assistant_cases_test.go b/internal/httpapi/assistant_cases_test.go index 5429bf723..ff6c45454 100644 --- a/internal/httpapi/assistant_cases_test.go +++ b/internal/httpapi/assistant_cases_test.go @@ -233,13 +233,11 @@ func TestAssistantAcceptanceAndDraftWarnings(t *testing.T) { h := &assistantHandlers{deps: &deps{repo: st}} for tool, wantPart := range map[string]string{ - "agents_delete": "不存在", - "rules_delete": "不存在", - "skills_delete": "不存在", - "dockerfiles_delete": "不存在", - "environments_delete": "不存在", - "sandboxes_delete": "不存在", - "workflows_delete": "不存在", + "agents_delete": "不存在", + "rules_delete": "不存在", + "skills_delete": "不存在", + "sandboxes_delete": "不存在", + "workflows_delete": "不存在", } { d := assistantDraft{Tool: tool, Body: json.RawMessage(`{"id":"missing"}`)} warnings := h.assistantDraftWarnings(d) @@ -261,13 +259,9 @@ func TestAssistantAcceptanceAndDraftWarnings(t *testing.T) { _ = st.PutRule(domain.RuleDefinition{ID: "rule-ref", Name: "Rule", ProjectID: projectID}) _ = st.PutSkill(domain.SkillDefinition{ID: "skill-ref", Name: "Skill", ProjectID: projectID}) _ = st.PutAgent(domain.AgentDefinition{ID: "agent-ref", Name: "Agent Ref", ProjectID: projectID, Rules: []string{"rule-ref"}, Skills: []string{"skill-ref"}}) - _ = st.PutDockerfile(domain.DockerfileDefinition{ID: "docker-ref", Name: "Docker", ProjectID: projectID}) - _ = st.PutEnvironment(domain.EnvironmentDefinition{ID: "env-ref", Name: "Env", ProjectID: projectID}) - _ = st.PutSandbox(domain.SandboxProfile{ID: "sandbox-ref", Name: "Sandbox Ref", ProjectID: projectID, DockerfileID: "docker-ref", EnvironmentID: "env-ref"}) + _ = st.PutSandbox(domain.SandboxProfile{ID: "sandbox-ref", Name: "Sandbox Ref", ProjectID: projectID}) _ = st.PutWorkflow(domain.WorkflowDefinition{ID: "workflow-ref", Name: "Workflow Ref", ProjectID: projectID, SandboxProfileID: "sandbox-ref"}) _ = h.agentNamesReferencing("rule", "rule-ref") _ = h.agentNamesReferencing("skill", "skill-ref") - _ = h.sandboxNamesReferencing("dockerfile", "docker-ref") - _ = h.sandboxNamesReferencing("environment", "env-ref") _ = h.workflowNamesReferencingSandbox("sandbox-ref") } diff --git a/internal/httpapi/assistant_draft_scope_test.go b/internal/httpapi/assistant_draft_scope_test.go index 3bb209a55..8081b80e6 100644 --- a/internal/httpapi/assistant_draft_scope_test.go +++ b/internal/httpapi/assistant_draft_scope_test.go @@ -26,8 +26,6 @@ var assistantDraftScope = map[string]string{ "rules_save": "project", "skills_save": "project", "mcp_servers_save": "project", - "dockerfiles_save": "project", - "environments_save": "project", "sandboxes_save": "project", "workflows_save": "project", "workflows_clone": "project", diff --git a/internal/httpapi/assistant_personal_workspace_test.go b/internal/httpapi/assistant_personal_workspace_test.go index f6b0ae134..ff57a667d 100644 --- a/internal/httpapi/assistant_personal_workspace_test.go +++ b/internal/httpapi/assistant_personal_workspace_test.go @@ -29,7 +29,7 @@ func TestPersonalWorkspaceBindingAndReuse(t *testing.T) { if err := h.repo.PutAssistantSession(owner.ID, chat); err != nil { t.Fatal(err) } - if err := h.repo.PutSandbox(domain.SandboxProfile{ID: "private-sandbox", Name: "Private", Driver: domain.SandboxDriverDocker, DockerfileID: repo.GenericBackendDockerfileID}); err != nil { + if err := h.repo.PutSandbox(domain.SandboxProfile{ID: "private-sandbox", Name: "Private", Driver: domain.SandboxDriverDocker, Dockerfile: repo.GenericDockerSandbox().Dockerfile}); err != nil { t.Fatal(err) } gateway := &agentToolGateway{deps: h.deps} diff --git a/internal/httpapi/assistant_preferences.go b/internal/httpapi/assistant_preferences.go index 8121786c7..94640eb09 100644 --- a/internal/httpapi/assistant_preferences.go +++ b/internal/httpapi/assistant_preferences.go @@ -27,16 +27,28 @@ func (h *assistantHandlers) preferences(c *gin.Context) { c.JSON(200, h.repo.AssistantPreferences(user.ID).Sanitized()) return } - var body domain.AssistantPreferences - if err := c.ShouldBindJSON(&body); err != nil { + var request struct { + domain.AssistantPreferences + WorkspaceDriver *string `json:"workspaceDriver"` + } + if err := c.ShouldBindJSON(&request); err != nil { c.JSON(400, gin.H{"error": "设置格式不正确"}) return } + body := request.AssistantPreferences if utf8.RuneCountInString(body.Instructions) > domain.AssistantPreferencesInstructionsMax { c.JSON(400, gin.H{"error": fmt.Sprintf("自定义规则最多 %d 字", domain.AssistantPreferencesInstructionsMax)}) return } existing := h.repo.AssistantPreferences(user.ID) + body.WorkspaceDriver = existing.WorkspaceDriver + if request.WorkspaceDriver != nil { + body.WorkspaceDriver = strings.TrimSpace(*request.WorkspaceDriver) + if !domain.ValidAssistantWorkspaceDriver(body.WorkspaceDriver) { + c.JSON(400, gin.H{"error": "对话工作区倾向只能是 docker、native 或留空"}) + return + } + } normalized, err := normalizeAndValidateAssistantPreferences(body, existing) if err != nil { c.JSON(400, gin.H{"error": err.Error()}) diff --git a/internal/httpapi/assistant_proposals_test.go b/internal/httpapi/assistant_proposals_test.go index 7ea510954..81d4304ac 100644 --- a/internal/httpapi/assistant_proposals_test.go +++ b/internal/httpapi/assistant_proposals_test.go @@ -421,8 +421,8 @@ func TestAssistantPreferencesShapeTheContext(t *testing.T) { if code, _ := put(`{"approvalReviewMode":"api","approvalReviewApi":{"protocol":"chat","baseUrl":"ftp://bad.example","model":"hy4","apiKey":"sk-secret"}}`); code != 400 { t.Fatalf("api mode with invalid baseUrl accepted: %d", code) } - code, saved := put(`{"proactiveRoles":true,"proactiveSops":false,"steerOnSend":true,"approvalReviewMode":"api","approvalReviewApi":{"protocol":"gemini","baseUrl":"https://generativelanguage.googleapis.com","model":"gemini-2.5-flash","apiKey":"sk-review-secret"},"instructions":" 回复先给结论 "}`) - if code != 200 || !saved.SteerOnSend || saved.ApprovalReviewMode != domain.ApprovalReviewModeAPI || saved.ApprovalReviewAPI == nil || !saved.ApprovalReviewAPI.APIKeyConfigured || saved.ApprovalReviewAPI.APIKey != "" || saved.ApprovalReviewAPI.Model != "gemini-2.5-flash" { + code, saved := put(`{"proactiveRoles":true,"proactiveSops":false,"workspaceDriver":"native","steerOnSend":true,"approvalReviewMode":"api","approvalReviewApi":{"protocol":"gemini","baseUrl":"https://generativelanguage.googleapis.com","model":"gemini-2.5-flash","apiKey":"sk-review-secret"},"instructions":" 回复先给结论 "}`) + if code != 200 || !saved.SteerOnSend || saved.WorkspaceDriver != domain.SandboxDriverNative || saved.ApprovalReviewMode != domain.ApprovalReviewModeAPI || saved.ApprovalReviewAPI == nil || !saved.ApprovalReviewAPI.APIKeyConfigured || saved.ApprovalReviewAPI.APIKey != "" || saved.ApprovalReviewAPI.Model != "gemini-2.5-flash" { t.Fatalf("saved api=%d %+v", code, saved) } // Cross-origin Base URL change without a new apiKey must be rejected and preserve original stored config. @@ -440,10 +440,10 @@ func TestAssistantPreferencesShapeTheContext(t *testing.T) { if stored := h.repo.AssistantPreferences(u.ID); stored.ApprovalReviewAPI == nil || stored.ApprovalReviewAPI.APIKey != "sk-review-secret" { t.Fatalf("stored key lost on same-origin update: %+v", stored.ApprovalReviewAPI) } - // Legacy PUT omitting approvalReview* fields must preserve saved API review settings and key. + // Legacy PUT must preserve the workspace choice and the configured review API. code, saved = put(`{"proactiveRoles":true,"proactiveSops":false,"steerOnSend":true,"instructions":"回复先给结论"}`) - if code != 200 || saved.ApprovalReviewMode != domain.ApprovalReviewModeAPI || saved.ApprovalReviewAPI == nil || !saved.ApprovalReviewAPI.APIKeyConfigured || saved.ApprovalReviewAPI.Model != "gemini-2.5-pro" { - t.Fatalf("legacy PUT should preserve saved API review settings: code=%d %+v", code, saved) + if code != 200 || saved.WorkspaceDriver != domain.SandboxDriverNative || saved.ApprovalReviewMode != domain.ApprovalReviewModeAPI || saved.ApprovalReviewAPI == nil || !saved.ApprovalReviewAPI.APIKeyConfigured || saved.ApprovalReviewAPI.Model != "gemini-2.5-pro" { + t.Fatalf("legacy PUT should preserve workspace and API review settings: code=%d %+v", code, saved) } if stored := h.repo.AssistantPreferences(u.ID); stored.ApprovalReviewAPI == nil || stored.ApprovalReviewAPI.APIKey != "sk-review-secret" { t.Fatalf("legacy PUT dropped stored api key: %+v", stored.ApprovalReviewAPI) diff --git a/internal/httpapi/assistant_sandbox_test.go b/internal/httpapi/assistant_sandbox_test.go index bcdadd98e..f63016e7a 100644 --- a/internal/httpapi/assistant_sandbox_test.go +++ b/internal/httpapi/assistant_sandbox_test.go @@ -14,6 +14,7 @@ import ( "agentflow/internal/application" "agentflow/internal/domain" "agentflow/internal/engine" + "agentflow/internal/repo" "agentflow/internal/runtime" "github.com/gin-gonic/gin" @@ -23,13 +24,11 @@ func chatSandboxFixture(t *testing.T) (*assistantHandlers, domain.User, *AgentTo t.Helper() h, user := workbenchFixture(t) h.engine = engine.New(h.repo, runtime.NewManager(t.TempDir())) - if err := h.repo.PutDockerfile(domain.DockerfileDefinition{ID: "chat-df", Name: "Business image", ProjectID: "workbench", Content: "FROM alpine:3.20\n"}); err != nil { - t.Fatal(err) - } + recipe := &domain.SandboxDockerfile{Content: "FROM alpine:3.20\n"} for _, profile := range []domain.SandboxProfile{ - {ID: "business", Name: "Business", ProjectID: "workbench", Driver: "docker", DockerfileID: "chat-df"}, - {ID: "shared", Name: "Shared", ProjectID: "other", Shared: true, Driver: "docker", DockerfileID: "chat-df"}, - {ID: "private", Name: "Private", ProjectID: "other", Driver: "docker", DockerfileID: "chat-df"}, + {ID: "business", Name: "Business", ProjectID: "workbench", Driver: "docker", Dockerfile: recipe}, + {ID: "shared", Name: "Shared", ProjectID: "other", Shared: true, Driver: "docker", Dockerfile: recipe}, + {ID: "private", Name: "Private", ProjectID: "other", Driver: "docker", Dockerfile: recipe}, } { if err := h.repo.PutSandbox(profile); err != nil { t.Fatal(err) @@ -70,9 +69,9 @@ func TestConversationSandboxSelectionFreezesIndependentWorkspace(t *testing.T) { t.Fatalf("wrong environment: %+v", run.WorkflowSnapshot.SandboxSnapshot) } frozen := run.WorkflowSnapshot.SandboxSnapshot.Dockerfile.Content - df, _ := h.repo.Dockerfile("chat-df") - df.Content = "FROM busybox:1.36\n" - _ = h.repo.PutDockerfile(df) + business, _ := h.repo.Sandbox("business") + business.Dockerfile = &domain.SandboxDockerfile{Content: "FROM busybox:1.36\n"} + _ = h.repo.PutSandbox(business) again, reused, err := open("") if err != nil || !reused || again.ID != run.ID || again.WorkflowSnapshot.SandboxProfileID != "business" || again.WorkflowSnapshot.SandboxSnapshot.Dockerfile.Content != frozen { t.Fatalf("frozen environment changed: %+v %v", again, err) @@ -95,6 +94,49 @@ func TestConversationSandboxSelectionFreezesIndependentWorkspace(t *testing.T) { } } +// The preferred sandbox kind in the AI assistant settings leads the choices +// and opens when the agent names no environment; it never overrides an +// explicit choice. +func TestConversationSandboxPreferenceGuidesTheAgent(t *testing.T) { + h, user, s := chatSandboxFixture(t) + gateway := agentToolGateway{deps: h.deps} + prefer := func(driver string) int { + t.Helper() + c, rec := workbenchContext(user, "PUT", "/api/assistant/preferences", bytes.NewBufferString(`{"workspaceDriver":"`+driver+`"}`)) + h.preferences(c) + return rec.Code + } + if code := prefer("seatbelt"); code != 400 { + t.Fatalf("unknown workspace driver accepted: %d", code) + } + description := gateway.workspaceOpenDescriptorFor(s).Description + if !strings.Contains(description, "拿不准用 generic-docker") || strings.Contains(description, "倾向") { + t.Fatalf("no preference still steers the agent: %s", description) + } + if code := prefer("native"); code != 200 { + t.Fatalf("save preference: %d", code) + } + description = gateway.workspaceOpenDescriptorFor(s).Description + native := repo.TestNativeSandboxID + if !strings.Contains(description, "倾向 native 沙箱") || !strings.Contains(description, "没有特殊要求时用 "+native) || + strings.Index(description, "- "+native+":") > strings.Index(description, "- business:") { + t.Fatalf("preferred sandbox not offered first: %s", description) + } + bound, err := gateway.bindConversationWorkspace(context.Background(), s, workspaceOpenChoice{}) + if err != nil || bound.Run.WorkflowSnapshot.SandboxProfileID != native { + t.Fatalf("default environment ignores the preference: %+v %v", bound.Run.WorkflowSnapshot, err) + } + s.ChatSessionID, s.workspaceRunID = "explicit-chat", "" + _ = h.repo.PutAssistantSession(user.ID, domain.AssistantSession{ID: s.ChatSessionID, ProjectID: s.ProjectID}) + bound, err = gateway.bindConversationWorkspace(context.Background(), s, workspaceOpenChoice{SandboxID: "business"}) + if err != nil || bound.Run.WorkflowSnapshot.SandboxProfileID != "business" { + t.Fatalf("the agent's explicit choice was overridden: %+v %v", bound.Run.WorkflowSnapshot, err) + } + if code := prefer("local"); code != 400 { + t.Fatalf("the removed local kind accepted as a preference: %d", code) + } +} + func TestConversationSandboxHTTPValidatesScopeAndLocks(t *testing.T) { h, user, s := chatSandboxFixture(t) selectEnvironment := func(id string, actor domain.User) int { diff --git a/internal/httpapi/assistant_schedule_assets_test.go b/internal/httpapi/assistant_schedule_assets_test.go index ebf5a266a..2c5d9c8a2 100644 --- a/internal/httpapi/assistant_schedule_assets_test.go +++ b/internal/httpapi/assistant_schedule_assets_test.go @@ -12,6 +12,7 @@ import ( "agentflow/internal/domain" "agentflow/internal/engine" + "agentflow/internal/repo" "agentflow/internal/runtime" "agentflow/internal/tracker" ) @@ -34,7 +35,7 @@ func TestSharedSchedulePinsDirectReferencesAndKeepsNestedBindingsScoped(t *testi role := domain.AgentDefinition{ID: "source-role", Name: "Source role", ProjectID: "workbench", Shared: true, Prompt: "shared through task", Rules: []string{"source-rule"}, Skills: []string{"source-skill"}} check(st.PutAgent(role)) check(st.PutAgent(domain.AgentDefinition{ID: "unrelated-role", Name: "Unrelated", ProjectID: "workbench"})) - wf := domain.WorkflowDefinition{ID: "source-sop", Name: "SOP", ProjectID: "workbench", Shared: true, SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "approve", Type: "approval", Name: "Approve"}}} + wf := domain.WorkflowDefinition{ID: "source-sop", Name: "SOP", ProjectID: "workbench", Shared: true, SandboxProfileID: repo.TestNativeSandboxID, Nodes: []domain.WorkflowNode{{ID: "approve", Type: "approval", Name: "Approve"}}} check(st.PutWorkflow(wf)) job := domain.ScheduleJob{ID: "shared-source", Name: "Shared", ProjectID: "workbench", SkipDispatch: true, AssistantPrompt: "inspect", References: []domain.AssistantReference{{Type: "agent", ID: role.ID}, {Type: "sop", ID: wf.ID}}} check(st.PutScheduleJob(job)) diff --git a/internal/httpapi/assistant_schedule_permissions_test.go b/internal/httpapi/assistant_schedule_permissions_test.go index 8f335c030..39257c439 100644 --- a/internal/httpapi/assistant_schedule_permissions_test.go +++ b/internal/httpapi/assistant_schedule_permissions_test.go @@ -23,7 +23,7 @@ import ( func TestScheduledAssistantCanDispatchSOP(t *testing.T) { h, user := workbenchFixture(t) st := h.repo - wf := domain.WorkflowDefinition{ID: "scheduled-approval", ProjectID: "workbench", Name: "Scheduled approval", Version: 1, SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}} + wf := domain.WorkflowDefinition{ID: "scheduled-approval", ProjectID: "workbench", Name: "Scheduled approval", Version: 1, SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}} if err := st.PutWorkflow(wf); err != nil { t.Fatal(err) } diff --git a/internal/httpapi/assistant_schedule_test.go b/internal/httpapi/assistant_schedule_test.go index 886ed8313..96c961e74 100644 --- a/internal/httpapi/assistant_schedule_test.go +++ b/internal/httpapi/assistant_schedule_test.go @@ -82,7 +82,7 @@ func TestScheduledAssistantStopsAtDeadline(t *testing.T) { func TestScheduledAssistantRecoveredDraftDoesNotDispatchRun(t *testing.T) { h, user := workbenchFixture(t) - wf := domain.WorkflowDefinition{ID: "wf", Name: "Scheduled approval", ProjectID: "workbench", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "review", Type: "approval"}}} + wf := domain.WorkflowDefinition{ID: "wf", Name: "Scheduled approval", ProjectID: "workbench", SandboxProfileID: repo.TestNativeSandboxID, Nodes: []domain.WorkflowNode{{ID: "review", Type: "approval"}}} if err := h.repo.PutWorkflow(wf); err != nil { t.Fatal(err) } diff --git a/internal/httpapi/assistant_sop_designer_test.go b/internal/httpapi/assistant_sop_designer_test.go index a070f02ab..b3a968cb2 100644 --- a/internal/httpapi/assistant_sop_designer_test.go +++ b/internal/httpapi/assistant_sop_designer_test.go @@ -10,6 +10,7 @@ import ( "time" "agentflow/internal/domain" + "agentflow/internal/repo" ) func sopDesignerTurn(t *testing.T, h *assistantHandlers, user domain.User, req assistantRequest) (int, string) { @@ -59,7 +60,7 @@ func TestSOPDesignerConversationIsPrivateAndServerOwned(t *testing.T) { if err := h.repo.PutAgent(domain.AgentDefinition{ID: "workbench-dev", Name: "开发工程师", ProjectID: "workbench", Description: "实现代码"}); err != nil { t.Fatal(err) } - if err := h.repo.PutWorkflow(domain.WorkflowDefinition{ID: "workbench-ref", Name: "参考流程", ProjectID: "workbench", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "ref-a", Name: "参考节点", Type: "approval"}}}); err != nil { + if err := h.repo.PutWorkflow(domain.WorkflowDefinition{ID: "workbench-ref", Name: "参考流程", ProjectID: "workbench", SandboxProfileID: repo.TestNativeSandboxID, Nodes: []domain.WorkflowNode{{ID: "ref-a", Name: "参考节点", Type: "approval"}}}); err != nil { t.Fatal(err) } canvas := json.RawMessage(`{"id":"sop-a","name":"交付","nodes":[{"id":"n1","name":"实现","type":"agent","agentId":"workbench-dev","position":{"x":10,"y":20},"script":"` + strings.Repeat("x", 500) + `"}],"edges":[]}`) @@ -193,7 +194,7 @@ func TestSOPDesignerCatalogIsReadOnlyAndDraftOnly(t *testing.T) { if err != nil || result["isError"] != true || session.finished() || !strings.Contains(string(encoded), "只能提交 workflows_save") { t.Fatalf("designer accepted a non-SOP draft: %v %v", result, err) } - result, err = gw.callTerminal(session, submitAssistantReplyTool, json.RawMessage(`{"message":"已搭好","drafts":[{"tool":"workflows_save","body":{"id":"workbench-delivery","projectId":"workbench","sandboxProfileId":"local","name":"交付","nodes":[],"edges":[]}}]}`)) + result, err = gw.callTerminal(session, submitAssistantReplyTool, json.RawMessage(`{"message":"已搭好","drafts":[{"tool":"workflows_save","body":{"id":"workbench-delivery","projectId":"workbench","sandboxProfileId":"test-native","name":"交付","nodes":[],"edges":[]}}]}`)) if err != nil || result["isError"] == true || !session.finished() { t.Fatalf("designer rejected its workflows_save draft: %v %v", result, err) } @@ -238,7 +239,7 @@ func TestWorkflowDraftWarningsAcceptPreviewBuildNode(t *testing.T) { } } -const designerOpsCanvas = `{"id":"sop-a","projectId":"workbench","sandboxProfileId":"local","name":"交付","description":"旧说明","preview":{"enabled":true}, +const designerOpsCanvas = `{"id":"sop-a","projectId":"workbench","sandboxProfileId":"test-native","name":"交付","description":"旧说明","preview":{"enabled":true}, "nodes":[{"id":"plan","name":"计划","type":"agent","agentId":"dev","prompt":"写计划","position":{"x":10,"y":20}}, {"id":"impl","name":"实现","type":"script","script":"make build","position":{"x":300,"y":20}}, {"id":"old","name":"旧节点","type":"approval","position":{"x":600,"y":20}}, @@ -286,7 +287,7 @@ func TestSOPDesignerOperationsEditTheCanvas(t *testing.T) { if err != nil { t.Fatal(err) } - if body["id"] != "sop-a" || body["projectId"] != "workbench" || body["sandboxProfileId"] != "local" || body["name"] != "交付 v2" || body["description"] != "旧说明" || body["preview"] == nil { + if body["id"] != "sop-a" || body["projectId"] != "workbench" || body["sandboxProfileId"] != "test-native" || body["name"] != "交付 v2" || body["description"] != "旧说明" || body["preview"] == nil { t.Fatalf("workflow fields lost: %+v", body) } if _, has := body["operations"]; has { @@ -344,7 +345,7 @@ func TestSOPDesignerFullBodyKeepsCanvasIdentity(t *testing.T) { if err != nil { t.Fatal(err) } - if !strings.Contains(string(out), `"id":"sop-a"`) || !strings.Contains(string(out), `"sandboxProfileId":"local"`) || strings.Contains(string(out), "旧节点") { + if !strings.Contains(string(out), `"id":"sop-a"`) || !strings.Contains(string(out), `"sandboxProfileId":"test-native"`) || strings.Contains(string(out), "旧节点") { t.Fatalf("full body = %s", out) } own := json.RawMessage(`{"message":"另建","drafts":[{"tool":"workflows_save","body":{"id":"workbench-new","name":"新流程","nodes":[],"edges":[]}}]}`) @@ -378,7 +379,7 @@ func TestSOPDesignerTerminalAppliesOperations(t *testing.T) { // draft takes, the marker never replaces the real script. func TestSOPDesignerOmittedScriptIsRestored(t *testing.T) { long := strings.Repeat("echo test; ", 60) - canvas := json.RawMessage(`{"id":"sop-a","projectId":"workbench","sandboxProfileId":"local","nodes":[{"id":"checks","name":"测试","type":"script","script":"` + long + `"}],"edges":[]}`) + canvas := json.RawMessage(`{"id":"sop-a","projectId":"workbench","sandboxProfileId":"test-native","nodes":[{"id":"checks","name":"测试","type":"script","script":"` + long + `"}],"edges":[]}`) compact := string(compactSOPDesignerWorkflow(canvas)) if !strings.Contains(compact, "脚本共 660 字") || strings.Contains(compact, "echo test") { t.Fatalf("compact canvas = %s", compact) diff --git a/internal/httpapi/assistant_test.go b/internal/httpapi/assistant_test.go index 5f8b31789..ffa6b506f 100644 --- a/internal/httpapi/assistant_test.go +++ b/internal/httpapi/assistant_test.go @@ -58,8 +58,7 @@ func TestAssistantDraftBoundary(t *testing.T) { {"assistant task", `{"message":"草稿","drafts":[{"tool":"assistant_tasks_save","body":{"name":"每小时检查待办","prompt":"列出当前项目未完成事项","intervalSec":3600,"enabled":true,"projectId":"p"}}]}`, "p", true}, {"assistant task cron", `{"message":"草稿","drafts":[{"tool":"assistant_tasks_save","body":{"name":"工作日巡检","prompt":"列出当前项目未完成事项","cron":"0 9 * * 1-5","model":"default","enabled":true,"projectId":"p"}}]}`, "p", true}, {"schedule job", `{"message":"草稿","drafts":[{"tool":"schedule_jobs_save","body":{"id":"job-1","name":"TAPD 自动开发","projectId":"p","source":"tapd","workflowId":"wf","intervalSec":300,"tapdWorkspaceId":"ws","tapdIterationId":"it","enabled":true}}]}`, "p", true}, - {"sandbox", `{"message":"草稿","drafts":[{"tool":"sandboxes_save","body":{"id":"p-box","name":"Docker 沙箱","projectId":"p","driver":"docker","dockerfileId":"p-df"}}]}`, "p", true}, - {"dockerfile", `{"message":"草稿","drafts":[{"tool":"dockerfiles_save","body":{"id":"p-df","name":"构建镜像","projectId":"p","content":"FROM debian:12"}}]}`, "p", true}, + {"sandbox", `{"message":"草稿","drafts":[{"tool":"sandboxes_save","body":{"id":"p-box","name":"Docker 沙箱","projectId":"p","driver":"docker","dockerfile":{"content":"FROM debian:12"}}}]}`, "p", true}, {"script node", `{"message":"草稿","drafts":[{"tool":"workflows_save","body":{"id":"a","name":"A","projectId":"p","status":"draft","sandboxProfileId":"s","edges":[],"nodes":[{"id":"script","name":"脚本","type":"script","scriptLanguage":"shell","script":"printf ok"}]}}]}`, "p", true}, {"hook allowed", `{"message":"草稿","drafts":[{"tool":"agents_save","body":{"id":"a","name":"A","projectId":"p","hooks":[{"id":"h1","name":"start","event":"SessionStart","language":"shell","script":"echo hi"}]}}]}`, "p", true}, {"publish", `{"message":"草稿","drafts":[{"tool":"workflows_publish","path":{"id":"a"}}]}`, "p", true}, @@ -272,7 +271,7 @@ func TestAssistantPromptDoesNotInjectProjectCatalog(t *testing.T) { ID: "p-dev-review-test", Name: "开发-评审-测试流程", ProjectID: "p", Status: "draft", Revision: 1, Nodes: []domain.WorkflowNode{{ID: "dev", Name: "开发实现", Type: "agent", Script: strings.Repeat("HUGE_SOP", 2000)}}, }) - if err := st.PutDockerfile(domain.DockerfileDefinition{ID: "p-df", Name: "构建镜像", ProjectID: "p", Content: "FROM debian:12"}); err != nil { + if err := st.PutSandbox(domain.SandboxProfile{ID: "p-box", Name: "构建镜像", ProjectID: "p", Driver: "docker", Dockerfile: &domain.SandboxDockerfile{Content: "FROM debian:12"}}); err != nil { t.Fatal(err) } h := &assistantHandlers{deps: &deps{repo: st}} diff --git a/internal/httpapi/assistant_workflow_result_test.go b/internal/httpapi/assistant_workflow_result_test.go index 9afa10970..94dba0017 100644 --- a/internal/httpapi/assistant_workflow_result_test.go +++ b/internal/httpapi/assistant_workflow_result_test.go @@ -45,7 +45,7 @@ func TestWorkflowGetReturnsFullDefinition(t *testing.T) { user.CodeBuddyAPIKey = secret script := strings.Repeat("env-prep phpstan\n", 800) wf := domain.WorkflowDefinition{ - ID: "wf-large", Name: "大 SOP", ProjectID: "platform", SandboxProfileID: "local", + ID: "wf-large", Name: "大 SOP", ProjectID: "platform", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "zg-index", Name: "索引", Type: "script", ScriptLanguage: "shell", Script: script}, {ID: "design", Name: "设计", Type: "script", ScriptLanguage: "shell", Script: script}, diff --git a/internal/httpapi/assistant_workspace_mode.go b/internal/httpapi/assistant_workspace_mode.go index f44abcbbd..0b46aa412 100644 --- a/internal/httpapi/assistant_workspace_mode.go +++ b/internal/httpapi/assistant_workspace_mode.go @@ -29,6 +29,15 @@ const workspaceRepositoryHeading = "当前项目登记的仓库(JSON 数据, const workspaceRepositoryInlineBytes = 32 << 10 +const nativeWorkspaceRepositoryGuide = "本工作区使用 native 沙箱。执行机器在环境变量 LOOPFORGE_REPOSITORY_CACHE 指向的目录里为项目仓库保留只读缓存,每个仓库一个 <仓库 id>.git。检出清单里的仓库时先看缓存:存在就 git clone --shared \"$LOOPFORGE_REPOSITORY_CACHE/<仓库 id>.git\" <仓库目录>,再 git -C <仓库目录> remote set-url origin ,之后照常 fetch、建分支、提交和推送;缓存不存在时照常 git clone 。不要写入缓存目录。\n" + +// nativeWorkspaceSession reports whether the session works in a native +// conversation workspace, whose Agent clones from the repository cache. +func (h *assistantHandlers) nativeWorkspaceSession(s *AgentToolSession) bool { + run, ok := h.repo.RunState(s.workspaceRun()) + return ok && run.IsNativeWorkspace() +} + // workspaceRepositoryPrompt uses the current catalog and workspace to determine // whether the resumed native journal already received this context. A large // catalog stays available in the same generated assets as chat attachments. @@ -37,6 +46,10 @@ func (h *assistantHandlers) workspaceRepositoryPrompt(s *AgentToolSession, root, return "", "", nil } repositories := projectRepositoryHints(h.repo.Repositories(), s.ProjectID) + guide := "" + if h.nativeWorkspaceSession(s) { + guide = nativeWorkspaceRepositoryGuide + } catalog := jsonObject(repositories) sum := sha256.Sum256([]byte(s.ProjectID + "\n" + s.workspaceRun() + "\n" + catalog)) hash := hex.EncodeToString(sum[:]) @@ -45,8 +58,8 @@ func (h *assistantHandlers) workspaceRepositoryPrompt(s *AgentToolSession, root, } fileHash := "file:" + hash if confirmedHash != fileHash && len(catalog) <= workspaceRepositoryInlineBytes && - runtime.PromptFitsArgv(promptBytes+len(workspaceRepositoryHeading)+len(catalog)+1) { - return workspaceRepositoryHeading + catalog + "\n", hash, nil + runtime.PromptFitsArgv(promptBytes+len(guide)+len(workspaceRepositoryHeading)+len(catalog)+1) { + return guide + workspaceRepositoryHeading + catalog + "\n", hash, nil } // Attachments are regenerated before each launch, including on resume. @@ -66,7 +79,7 @@ func (h *assistantHandlers) workspaceRepositoryPrompt(s *AgentToolSession, root, if confirmedHash == fileHash { return "", "", nil } - return fmt.Sprintf("当前项目登记的完整仓库清单位于 %q。每行一个 JSON 对象,以这个文件里的最新清单为准。需要定位或检出仓库时,先读取或搜索该文件,必要时分段读取。\n", path), fileHash, nil + return guide + fmt.Sprintf("当前项目登记的完整仓库清单位于 %q。每行一个 JSON 对象,以这个文件里的最新清单为准。需要定位或检出仓库时,先读取或搜索该文件,必要时分段读取。\n", path), fileHash, nil } // assistantHandoffAck is the visible text a phase ends with after a handoff. diff --git a/internal/httpapi/assistant_workspace_mode_test.go b/internal/httpapi/assistant_workspace_mode_test.go index a1c6cb488..a17863637 100644 --- a/internal/httpapi/assistant_workspace_mode_test.go +++ b/internal/httpapi/assistant_workspace_mode_test.go @@ -127,6 +127,42 @@ func TestWorkspaceRepositoryPromptRefreshesOnlyWhenNeeded(t *testing.T) { } } +// A native workspace starts empty; every turn's catalog tells the agent to +// clone from the execution machine's repository cache. +func TestNativeWorkspaceRepositoryPromptGuidesCacheClones(t *testing.T) { + h, _ := workbenchFixture(t) + for id, driver := range map[string]string{"native-ws": domain.SandboxDriverNative, "docker-ws": domain.SandboxDriverDocker} { + profile := domain.SandboxProfile{ID: id, Name: id, ProjectID: "workbench", Driver: driver} + if err := h.repo.PutRun(domain.Run{ID: id, Kind: domain.RunKindWorkspace, WorkflowID: domain.ConversationWorkspaceWorkflowID, Status: "waiting", Nodes: map[string]*domain.NodeRun{}, + WorkflowSnapshot: domain.WorkflowDefinition{SandboxProfileID: id, SandboxSnapshot: &domain.RunnerSandboxSpec{Profile: profile}}}); err != nil { + t.Fatal(err) + } + } + if err := h.repo.PutRepository(domain.Repository{ID: "service", Name: "service", ProjectID: "workbench", CloneURL: "https://git.example.com/team/service.git", DefaultBranch: "main"}); err != nil { + t.Fatal(err) + } + render := func(run string) string { + t.Helper() + prompt, _, err := h.workspaceRepositoryPrompt(&AgentToolSession{ProjectID: "workbench", workspaceRunID: run}, t.TempDir(), "", 0) + if err != nil { + t.Fatal(err) + } + return prompt + } + native := render("native-ws") + data, found := strings.CutPrefix(native, nativeWorkspaceRepositoryGuide+workspaceRepositoryHeading) + if !found || !strings.Contains(nativeWorkspaceRepositoryGuide, "git clone --shared") { + t.Fatalf("native workspace prompt without its cache guide: %s", native) + } + var hints []workspaceRepositoryHint + if err := json.Unmarshal([]byte(data), &hints); err != nil || len(hints) != 1 || hints[0].ID != "service" { + t.Fatalf("native workspace catalog = %s %v", data, err) + } + if docker := render("docker-ws"); strings.Contains(docker, nativeWorkspaceRepositoryGuide) || !strings.HasPrefix(docker, workspaceRepositoryHeading) { + t.Fatalf("docker workspace received the cache guide: %s", docker) + } +} + func TestWorkspaceRepositoryHintsStripURLSecrets(t *testing.T) { hints := projectRepositoryHints([]domain.Repository{ {ID: "ssh", Name: "A", ProjectID: "p", CloneURL: "ssh://git:fixture-password@git.example.test:2222/team/repo.git?signature=fixture#marker"}, diff --git a/internal/httpapi/assistant_workspace_open.go b/internal/httpapi/assistant_workspace_open.go index 81106874e..e9de12b62 100644 --- a/internal/httpapi/assistant_workspace_open.go +++ b/internal/httpapi/assistant_workspace_open.go @@ -13,6 +13,7 @@ import ( "agentflow/internal/domain" "agentflow/internal/engine" + "agentflow/internal/repo" ) // A conversation workspace is an environment, not a checkout: Main Bot picks @@ -20,7 +21,7 @@ import ( // earlier workspace of this conversation on the same execution machine). Empty // workspaces start empty so the agent clones, branches, commits and pushes with // its own git using the requester's Git credentials. -const workspaceOpenSchema = `{"type":"object","properties":{"sandboxProfileId":{"type":"string","maxLength":128,"description":"运行环境(沙箱配置)id;用于新开或切回本对话在该环境自己的工作区,不填沿用当前工作区的环境(没有工作区时用会话设置或 generic-docker)。传入 workspaceRunId 接入已有工作区/SOP 时沿用原运行冻结的沙箱环境,不要传不同的 sandboxProfileId"},"workspaceRunId":{"type":"string","maxLength":128,"description":"可选:要直接接入的同项目 SOP 运行 id(或本对话之前开过的工作区 id)。要求与当前对话在同一执行机器上:会直接绑定并操作该原工作区现场(包括未推送改动与中间产物,改完后也可回 SOP 从后续节点重跑或继续;已回收工作区会自动恢复快照;传子 SOP 时自动定位到父工作区)。日常继续当前工作区或只切换对话自身环境时不要传"}},"additionalProperties":false}` +const workspaceOpenSchema = `{"type":"object","properties":{"sandboxProfileId":{"type":"string","maxLength":128,"description":"运行环境(沙箱配置)id;用于新开或切回本对话在该环境自己的工作区,不填沿用当前工作区的环境(没有工作区时用会话设置、AI 助手设置里倾向的环境或 generic-docker)。传入 workspaceRunId 接入已有工作区/SOP 时沿用原运行冻结的沙箱环境,不要传不同的 sandboxProfileId"},"workspaceRunId":{"type":"string","maxLength":128,"description":"可选:要直接接入的同项目 SOP 运行 id(或本对话之前开过的工作区 id)。要求与当前对话在同一执行机器上:会直接绑定并操作该原工作区现场(包括未推送改动与中间产物,改完后也可回 SOP 从后续节点重跑或继续;已回收工作区会自动恢复快照;传子 SOP 时自动定位到父工作区)。日常继续当前工作区或只切换对话自身环境时不要传"}},"additionalProperties":false}` func workspaceOpenDescriptor() agentToolDescriptor { return agentToolDescriptor{ @@ -40,12 +41,10 @@ func (h *agentToolGateway) workspaceOpenDescriptorFor(s *AgentToolSession) agent if fixed := strings.TrimSpace(s.SandboxProfileID); fixed != "" { fmt.Fprintf(&b, "\n\n用户已在高级设置中指定运行环境 %s,不要填 sandboxProfileId。", fixed) } else { - b.WriteString("\n\n可选运行环境(sandboxProfileId,按要做的事需要的语言、工具链选择,拿不准用 generic-docker):") - for _, profile := range h.repo.ConversationSandboxes(s.ProjectID) { + choices, preferred := h.conversationSandboxChoices(s) + fmt.Fprintf(&b, "\n\n可选运行环境(sandboxProfileId,%s):", workspaceSandboxGuide(choices, preferred)) + for _, profile := range choices { name := profile.Name - if df, ok := h.repo.Dockerfile(profile.DockerfileID); ok && df.Name != "" && df.Name != name { - name += ",镜像 " + df.Name - } if profile.Driver != "" && profile.Driver != domain.SandboxDriverDocker { name += "," + profile.Driver + " 沙箱" } @@ -66,6 +65,55 @@ func (h *agentToolGateway) workspaceOpenDescriptorFor(s *AgentToolSession) agent return d } +// conversationSandboxKind folds a sandbox driver into the kinds a user can +// prefer for conversation workspaces. +func conversationSandboxKind(profile domain.SandboxProfile) string { + switch strings.TrimSpace(profile.Driver) { + case "", domain.SandboxDriverDocker: + return domain.SandboxDriverDocker + } + return domain.SandboxDriverNative +} + +// conversationSandboxChoices lists the environments the agent may open for +// this conversation, sandboxes of the speaker's preferred kind first, and the +// one it should use by default: empty without a preference or a sandbox of +// that kind. +func (h *agentToolGateway) conversationSandboxChoices(s *AgentToolSession) ([]domain.SandboxProfile, string) { + choices := h.repo.ConversationSandboxes(s.ProjectID) + prefer := h.repo.AssistantPreferences(s.UserID).WorkspaceDriver + if prefer == "" { + return choices, "" + } + rank := func(profile domain.SandboxProfile) int { + switch { + case conversationSandboxKind(profile) != prefer: + return 2 + case profile.ID == repo.DefaultSandboxProfileID: + return 0 + } + return 1 + } + slices.SortStableFunc(choices, func(a, b domain.SandboxProfile) int { return rank(a) - rank(b) }) + if len(choices) == 0 || rank(choices[0]) == 2 { + return choices, "" + } + return choices, choices[0].ID +} + +func workspaceSandboxGuide(choices []domain.SandboxProfile, preferred string) string { + for _, profile := range choices { + if profile.ID != preferred { + continue + } + if conversationSandboxKind(profile) == domain.SandboxDriverNative { + return fmt.Sprintf("用户在 AI 助手设置里倾向 native 沙箱(执行机器上的系统轻量隔离,使用执行机器已装的工具链):没有特殊要求时用 %s,任务需要的语言或工具链只有其他环境具备时再换", preferred) + } + return fmt.Sprintf("用户在 AI 助手设置里倾向 Docker 沙箱:没有特殊要求时用 %s,任务需要的语言或工具链只有其他环境具备时再换", preferred) + } + return "按要做的事需要的语言、工具链选择,拿不准用 generic-docker" +} + type workspaceRepositoryHint struct { ID string `json:"id"` Name string `json:"name"` @@ -193,7 +241,9 @@ func (h *agentToolGateway) openConversationWorkspace(ctx context.Context, s *Age default: fmt.Fprintf(¬ice, "已切回运行环境 %s 中本对话之前开过的工作区 %s。", run.WorkflowSnapshot.SandboxProfileID, run.ID) } - if run.IsWorkspace() && bound.Created && len(run.RepositoryContexts()) == 0 { + if run.IsNativeWorkspace() && bound.Created { + notice.WriteString("工作区已提供空白可写目录,可创建文件、运行命令和预览。有仓库相关任务时,先从执行机器的仓库缓存 git clone --shared,没有缓存再 git clone。") + } else if run.IsWorkspace() && bound.Created && len(run.RepositoryContexts()) == 0 { notice.WriteString("工作区已提供空白可写目录,可创建文件、运行命令和预览。有仓库相关任务时,用 git clone 拉取所需仓库。") } if previous, ok := h.repo.RunState(bound.Previous); ok { @@ -413,6 +463,9 @@ func (h *agentToolGateway) bindConversationWorkspace(ctx context.Context, s *Age binding.Run, reuse = run, true } } + if !reuse && wanted == "" { + _, wanted = h.conversationSandboxChoices(s) + } if !reuse && wanted != "" { // Coming back to an environment this conversation used before resumes // that workspace, with the repositories it already cloned. diff --git a/internal/httpapi/assistant_workspace_open_test.go b/internal/httpapi/assistant_workspace_open_test.go index 8dcaad2ac..284c65b2c 100644 --- a/internal/httpapi/assistant_workspace_open_test.go +++ b/internal/httpapi/assistant_workspace_open_test.go @@ -33,7 +33,9 @@ func hostConversationWorkspace(t *testing.T) { func configureConversationSandbox(t *testing.T, h *assistantHandlers) { t.Helper() if os.Getenv("AGENTFLOW_TEST_DOCKER") == "1" { - err := h.repo.PutDockerfile(domain.DockerfileDefinition{ID: repo.GenericBackendDockerfileID, Name: "Isolated workspace test", ProjectID: "workbench", Shared: true, Content: "FROM alpine:3.20\nRUN apk add --no-cache bash git coreutils && adduser -D -u 1000 user_00\nWORKDIR /workspace\n"}) + sandbox := repo.GenericDockerSandbox() + sandbox.Dockerfile = &domain.SandboxDockerfile{Content: "FROM alpine:3.20\nRUN apk add --no-cache bash git coreutils && adduser -D -u 1000 user_00\nWORKDIR /workspace\n"} + err := h.repo.PutSandbox(sandbox) if err != nil { t.Fatal(err) } @@ -368,7 +370,7 @@ func TestConversationWorkspaceFallsBackToGenericDocker(t *testing.T) { // can switch to a new workspace. func altConversationSandbox(t *testing.T, h *assistantHandlers) string { t.Helper() - if err := h.repo.PutSandbox(domain.SandboxProfile{ID: "alt-docker", Name: "Alt", Shared: true, Driver: domain.SandboxDriverDocker, DockerfileID: repo.GenericBackendDockerfileID}); err != nil { + if err := h.repo.PutSandbox(domain.SandboxProfile{ID: "alt-docker", Name: "Alt", Shared: true, Driver: domain.SandboxDriverDocker, Dockerfile: repo.GenericDockerSandbox().Dockerfile}); err != nil { t.Fatal(err) } return "alt-docker" diff --git a/internal/httpapi/assistant_workspace_turn_test.go b/internal/httpapi/assistant_workspace_turn_test.go index 784add29d..effe2d393 100644 --- a/internal/httpapi/assistant_workspace_turn_test.go +++ b/internal/httpapi/assistant_workspace_turn_test.go @@ -215,13 +215,13 @@ func workspaceTurnFixture(t *testing.T) (*assistantHandlers, domain.User, *Agent root := t.TempDir() en := engine.New(st, runtime.NewManager(root)) h := &assistantHandlers{deps: &deps{repo: st, engine: en}} - profile := domain.SandboxProfile{ID: id + "-sandbox", ProjectID: id, Name: "Workspace turn test", Driver: "local"} + profile := domain.SandboxProfile{ID: id + "-sandbox", ProjectID: id, Name: "Workspace turn test", Driver: "native"} if err := st.PutSandbox(profile); err != nil { t.Fatal(err) } // Each workspace runs in its own environment: the conversation switches // between them by environment. - if err := st.PutSandbox(domain.SandboxProfile{ID: id + "-second-sandbox", ProjectID: id, Name: "Workspace turn test 2", Driver: "local"}); err != nil { + if err := st.PutSandbox(domain.SandboxProfile{ID: id + "-second-sandbox", ProjectID: id, Name: "Workspace turn test 2", Driver: "native"}); err != nil { t.Fatal(err) } ids := []string{id + "-first", id + "-second"} diff --git a/internal/httpapi/catalog.go b/internal/httpapi/catalog.go index d97371f6b..6b7275cd2 100644 --- a/internal/httpapi/catalog.go +++ b/internal/httpapi/catalog.go @@ -759,10 +759,6 @@ func (h *catalogHandlers) deleteCatalogAsset(c *gin.Context, kind, notFound stri c.JSON(http.StatusConflict, map[string]string{"error": fmt.Sprintf("内置沙箱 %s 不能删除", id)}) return } - if kind == "Dockerfile" && id == repo.GenericBackendDockerfileID { - c.JSON(http.StatusConflict, map[string]string{"error": "内置 Dockerfile generic-backend 不能删除"}) - return - } if shared { c.JSON(http.StatusConflict, map[string]string{"error": fmt.Sprintf("共享状态的%s不能删除,请先取消共享", kind)}) return @@ -795,16 +791,6 @@ func (h *catalogHandlers) agentNamesReferencing(kind, id string) []string { return names } -func (h *catalogHandlers) sandboxNamesReferencing(kind, id string) []string { - var names []string - for _, sandbox := range h.repo.Sandboxes() { - if (kind == "dockerfile" && sandbox.DockerfileID == id) || (kind == "environment" && sandbox.EnvironmentID == id) { - names = append(names, sandbox.Name) - } - } - return names -} - func (h *catalogHandlers) workflowNamesReferencingSandbox(id string) []string { var names []string for _, workflow := range h.repo.Workflows() { @@ -818,76 +804,6 @@ func (h *catalogHandlers) workflowNamesReferencingSandbox(id string) []string { func (h *catalogHandlers) executors(c *gin.Context) { c.JSON(200, repo.BuiltInExecutors()) } -func (h *catalogHandlers) dockerfiles(c *gin.Context) { - if c.Request.Method == http.MethodGet { - items := h.repo.Dockerfiles() - if projectID := strings.TrimSpace(c.Query("projectId")); projectID != "" { - items = filterEnvironmentAssets(items, projectID, func(item domain.DockerfileDefinition) (string, bool) { return item.ProjectID, item.Shared }) - } - c.JSON(200, items) - return - } - if c.Request.Method == http.MethodDelete { - h.deleteCatalogAsset(c, "Dockerfile", "dockerfile not found", func(id string) (bool, bool) { - item, ok := h.repo.Dockerfile(id) - return item.Shared, ok - }, func(id string) []string { return h.sandboxNamesReferencing("dockerfile", id) }, "沙箱", h.repo.DeleteDockerfile) - return - } - if c.Request.Method == http.MethodPut { - var v domain.DockerfileDefinition - if decode(c, &v) { - v.ID, v.ProjectID = strings.TrimSpace(v.ID), strings.TrimSpace(v.ProjectID) - if err := h.validateEnvironmentAsset(v.ID, v.Name, v.ProjectID, "Dockerfile"); err != nil { - respond(c, err) - return - } - if existing, ok := h.repo.Dockerfile(v.ID); ok && existing.ProjectID != "" && existing.ProjectID != v.ProjectID { - c.JSON(http.StatusConflict, map[string]string{"error": "Dockerfile 标识已被其他项目使用"}) - return - } else if ok && existing.Shared && !v.Shared && h.sharedEnvironmentReference("dockerfile", v.ID) { - c.JSON(http.StatusConflict, map[string]string{"error": "该 Dockerfile 仍被共享沙箱引用,不能取消共享"}) - return - } - respond(c, h.repo.PutDockerfile(v)) - } - } -} -func (h *catalogHandlers) environments(c *gin.Context) { - if c.Request.Method == http.MethodGet { - items := h.repo.Environments() - if projectID := strings.TrimSpace(c.Query("projectId")); projectID != "" { - items = filterEnvironmentAssets(items, projectID, func(item domain.EnvironmentDefinition) (string, bool) { return item.ProjectID, item.Shared }) - } - c.JSON(200, items) - return - } - if c.Request.Method == http.MethodDelete { - h.deleteCatalogAsset(c, "环境安装脚本", "environment not found", func(id string) (bool, bool) { - item, ok := h.repo.Environment(id) - return item.Shared, ok - }, func(id string) []string { return h.sandboxNamesReferencing("environment", id) }, "沙箱", h.repo.DeleteEnvironment) - return - } - if c.Request.Method == http.MethodPut { - var v domain.EnvironmentDefinition - if decode(c, &v) { - v.ID, v.ProjectID = strings.TrimSpace(v.ID), strings.TrimSpace(v.ProjectID) - if err := h.validateEnvironmentAsset(v.ID, v.Name, v.ProjectID, "环境安装脚本"); err != nil { - respond(c, err) - return - } - if existing, ok := h.repo.Environment(v.ID); ok && existing.ProjectID != "" && existing.ProjectID != v.ProjectID { - c.JSON(http.StatusConflict, map[string]string{"error": "环境安装脚本标识已被其他项目使用"}) - return - } else if ok && existing.Shared && !v.Shared && h.sharedEnvironmentReference("environment", v.ID) { - c.JSON(http.StatusConflict, map[string]string{"error": "该环境安装脚本仍被共享沙箱引用,不能取消共享"}) - return - } - respond(c, h.repo.PutEnvironment(v)) - } - } -} func (h *catalogHandlers) sandboxes(c *gin.Context) { if c.Request.Method == http.MethodGet { items := h.repo.Sandboxes() @@ -915,14 +831,10 @@ func (h *catalogHandlers) sandboxes(c *gin.Context) { if existing, ok := h.repo.Sandbox(v.ID); ok && existing.ProjectID != "" && existing.ProjectID != v.ProjectID { c.JSON(http.StatusConflict, map[string]string{"error": "沙箱标识已被其他项目使用"}) return - } else if ok && existing.Shared && !v.Shared && (v.ID == repo.GenericDockerSandboxID || h.sharedEnvironmentReference("sandbox", v.ID)) { + } else if ok && existing.Shared && !v.Shared && (v.ID == repo.GenericDockerSandboxID || h.sharedWorkflowUsesSandbox(v.ID)) { c.JSON(http.StatusConflict, map[string]string{"error": "该沙箱仍被共享 SOP 引用,不能取消共享"}) return } - if err := h.shareSandboxDependencies(v); err != nil { - respond(c, err) - return - } respond(c, h.repo.PutSandbox(v)) } } @@ -962,59 +874,14 @@ func (h *catalogHandlers) validateEnvironmentAsset(id, name, projectID, kind str return nil } -func (h *catalogHandlers) sharedEnvironmentReference(kind, id string) bool { - if kind == "sandbox" { - for _, workflow := range h.repo.Workflows() { - if workflow.Shared && workflow.SandboxProfileID == id { - return true - } - } - return false - } - for _, sandbox := range h.repo.Sandboxes() { - if !sandbox.Shared { - continue - } - if (kind == "dockerfile" && sandbox.DockerfileID == id) || (kind == "environment" && sandbox.EnvironmentID == id) { +func (h *catalogHandlers) sharedWorkflowUsesSandbox(id string) bool { + for _, workflow := range h.repo.Workflows() { + if workflow.Shared && workflow.SandboxProfileID == id { return true } } return false } - -func (h *catalogHandlers) shareSandboxDependencies(sandbox domain.SandboxProfile) error { - if sandbox.DockerfileID != "" { - item, ok := h.repo.Dockerfile(sandbox.DockerfileID) - if !ok { - return fmt.Errorf("dockerfile %q not found", sandbox.DockerfileID) - } - if item.ProjectID != sandbox.ProjectID && !item.Shared { - return fmt.Errorf("Dockerfile %q 不属于当前项目且尚未共享", item.Name) - } - if sandbox.Shared && item.ProjectID == sandbox.ProjectID && !item.Shared { - item.Shared = true - if err := h.repo.PutDockerfile(item); err != nil { - return err - } - } - } - if sandbox.EnvironmentID != "" { - item, ok := h.repo.Environment(sandbox.EnvironmentID) - if !ok { - return fmt.Errorf("environment %q not found", sandbox.EnvironmentID) - } - if item.ProjectID != sandbox.ProjectID && !item.Shared { - return fmt.Errorf("环境安装脚本 %q 不属于当前项目且尚未共享", item.Name) - } - if sandbox.Shared && item.ProjectID == sandbox.ProjectID && !item.Shared { - item.Shared = true - if err := h.repo.PutEnvironment(item); err != nil { - return err - } - } - } - return nil -} func (h *catalogHandlers) workflows(c *gin.Context) { if c.Request.Method == http.MethodGet { projectID := strings.TrimSpace(c.Query("projectId")) diff --git a/internal/httpapi/catalog_cases_test.go b/internal/httpapi/catalog_cases_test.go index 4dd0fa6de..a3cdaa431 100644 --- a/internal/httpapi/catalog_cases_test.go +++ b/internal/httpapi/catalog_cases_test.go @@ -54,15 +54,11 @@ func TestCatalogRepositoryAgentAndAssetBranches(t *testing.T) { {http.MethodPut, "/api/skills", map[string]any{"id": "cvb-skill", "name": "Skill", "projectId": "cvb-cat"}, 200}, {http.MethodGet, "/api/skills?projectId=cvb-cat", nil, 200}, - {http.MethodPut, "/api/dockerfiles", map[string]any{"id": "cvb-df", "name": "DF", "projectId": "cvb-cat", "content": "FROM scratch"}, 200}, - {http.MethodPut, "/api/environments", map[string]any{"id": "cvb-env", "name": "Env", "projectId": "cvb-cat", "installScript": "true"}, 200}, - {http.MethodPut, "/api/sandboxes", map[string]any{"id": "cvb-box-bad", "name": "Box", "projectId": "cvb-cat", "dockerfileId": "missing"}, 400}, - {http.MethodPut, "/api/sandboxes", map[string]any{"id": "cvb-box", "name": "Box", "projectId": "cvb-cat", "driver": "docker", "dockerfileId": "cvb-df", "environmentId": "cvb-env"}, 200}, - {http.MethodGet, "/api/dockerfiles?projectId=cvb-cat", nil, 200}, - {http.MethodGet, "/api/environments?projectId=cvb-cat", nil, 200}, + {http.MethodPut, "/api/sandboxes", map[string]any{"id": "cvb-box-bad", "name": "Box", "projectId": "cvb-cat", "driver": "docker"}, 400}, + {http.MethodPut, "/api/sandboxes", map[string]any{"id": "cvb-box", "name": "Box", "projectId": "cvb-cat", "driver": "docker", "dockerfile": map[string]any{"content": "FROM scratch"}, "install": map[string]any{"script": "true"}}, 200}, + {http.MethodPut, "/api/sandboxes", map[string]any{"id": "cvb-native", "name": "Native", "projectId": "cvb-cat", "driver": "native", "install": map[string]any{"script": "true"}}, 200}, {http.MethodGet, "/api/sandboxes?projectId=cvb-cat", nil, 200}, - {http.MethodDelete, "/api/dockerfiles?id=cvb-df", nil, 409}, - {http.MethodDelete, "/api/environments?id=cvb-env", nil, 204}, + {http.MethodDelete, "/api/sandboxes?id=cvb-native", nil, 204}, } for i, tc := range requests { rec := cvBRequest(t, f, tc.method, tc.path, tc.body, true) @@ -276,65 +272,19 @@ func TestCatalogDirectEnvironmentBranches(t *testing.T) { t.Fatal(err) } - if err := h.shareSandboxDependencies(domain.SandboxProfile{ProjectID: "cvb-env-a", DockerfileID: "missing"}); err == nil { - t.Fatal("missing Dockerfile accepted") - } - if err := h.shareSandboxDependencies(domain.SandboxProfile{ProjectID: "cvb-env-a", EnvironmentID: "missing"}); err == nil { - t.Fatal("missing environment accepted") - } - if err := f.s.PutDockerfile(domain.DockerfileDefinition{ID: "cvb-foreign-df", Name: "Foreign DF", ProjectID: "cvb-env-b", Content: "FROM scratch"}); err != nil { - t.Fatal(err) - } - if err := f.s.PutEnvironment(domain.EnvironmentDefinition{ID: "cvb-foreign-env", Name: "Foreign env", ProjectID: "cvb-env-b"}); err != nil { - t.Fatal(err) - } - if err := h.shareSandboxDependencies(domain.SandboxProfile{ProjectID: "cvb-env-a", DockerfileID: "cvb-foreign-df"}); err == nil { - t.Fatal("private foreign Dockerfile accepted") - } - if err := h.shareSandboxDependencies(domain.SandboxProfile{ProjectID: "cvb-env-a", EnvironmentID: "cvb-foreign-env"}); err == nil { - t.Fatal("private foreign environment accepted") - } - if err := f.s.PutDockerfile(domain.DockerfileDefinition{ID: "cvb-own-df", Name: "Own DF", ProjectID: "cvb-env-a", Content: "FROM scratch"}); err != nil { - t.Fatal(err) - } - if err := f.s.PutEnvironment(domain.EnvironmentDefinition{ID: "cvb-own-env", Name: "Own env", ProjectID: "cvb-env-a"}); err != nil { - t.Fatal(err) - } box := domain.SandboxProfile{ ID: "cvb-shared-box", Name: "Shared box", ProjectID: "cvb-env-a", Shared: true, - Driver: "docker", DockerfileID: "cvb-own-df", EnvironmentID: "cvb-own-env", + Driver: "docker", Dockerfile: &domain.SandboxDockerfile{Content: "FROM scratch"}, } - if err := h.shareSandboxDependencies(box); err != nil { - t.Fatal(err) - } - df, _ := f.s.Dockerfile("cvb-own-df") - env, _ := f.s.Environment("cvb-own-env") - if !df.Shared || !env.Shared { - t.Fatalf("dependencies not shared: df=%v env=%v", df.Shared, env.Shared) - } - if err := f.s.PutSandbox(box); err != nil { t.Fatal(err) } - envBox := domain.SandboxProfile{ - ID: "cvb-shared-env-box", Name: "Shared env box", ProjectID: "cvb-env-a", - Shared: true, Driver: "bwrap", EnvironmentID: "cvb-own-env", - } - if err := f.s.PutSandbox(envBox); err != nil { - t.Fatal(err) - } if err := f.s.PutWorkflow(domain.WorkflowDefinition{ID: "cvb-shared-wf", Name: "Shared workflow", Shared: true, SandboxProfileID: box.ID}); err != nil { t.Fatal(err) } - if !h.sharedEnvironmentReference("sandbox", box.ID) || h.sharedEnvironmentReference("sandbox", "missing") { + if !h.sharedWorkflowUsesSandbox(box.ID) || h.sharedWorkflowUsesSandbox("missing") { t.Fatal("shared workflow sandbox reference lookup is wrong") } - if !h.sharedEnvironmentReference("dockerfile", df.ID) || !h.sharedEnvironmentReference("environment", env.ID) { - t.Fatal("shared sandbox dependency reference lookup is wrong") - } - if h.sharedEnvironmentReference("other", df.ID) { - t.Fatal("unknown dependency kind matched") - } } func TestCatalogMoreHTTPBranches(t *testing.T) { @@ -408,11 +358,8 @@ func TestCatalogMoreHTTPBranches(t *testing.T) { {http.MethodDelete, "/api/skills", nil, http.StatusBadRequest}, {http.MethodPut, "/api/rules", map[string]any{"id": "cvb-http-rule", "name": "Moved", "projectId": "cvb-http-b"}, http.StatusConflict}, {http.MethodPut, "/api/skills", map[string]any{"id": "cvb-http-skill", "name": "Moved", "projectId": "cvb-http-b"}, http.StatusConflict}, - {http.MethodPut, "/api/dockerfiles", map[string]any{"id": "", "name": "Bad", "projectId": "cvb-http-a"}, http.StatusBadRequest}, - {http.MethodPut, "/api/environments", map[string]any{"id": "bad", "name": "Bad", "projectId": "missing"}, http.StatusBadRequest}, {http.MethodPut, "/api/sandboxes", map[string]any{"id": "bad", "name": "Bad", "projectId": "missing"}, http.StatusBadRequest}, - {http.MethodDelete, "/api/dockerfiles?id=" + repo.GenericBackendDockerfileID, nil, http.StatusConflict}, - {http.MethodDelete, "/api/sandboxes?id=local", nil, http.StatusConflict}, + {http.MethodDelete, "/api/sandboxes?id=" + repo.GenericDockerSandboxID, nil, http.StatusConflict}, {http.MethodGet, "/api/executors", nil, http.StatusOK}, } for _, tc := range cases { @@ -516,28 +463,6 @@ func TestCatalogSmallDirectHelpers(t *testing.T) { if names := h.agentNamesReferencing("skill", "s"); len(names) != 1 { t.Fatalf("skill references = %#v", names) } - if err := f.s.PutDockerfile(domain.DockerfileDefinition{ID: "cvb-helper-df", Name: "DF", ProjectID: "cvb-helper", Content: "FROM scratch"}); err != nil { - t.Fatal(err) - } - if err := f.s.PutEnvironment(domain.EnvironmentDefinition{ID: "cvb-helper-env", Name: "Env", ProjectID: "cvb-helper"}); err != nil { - t.Fatal(err) - } - if err := f.s.PutSandbox(domain.SandboxProfile{ - ID: "cvb-helper-docker", Name: "Docker", ProjectID: "cvb-helper", - Driver: "docker", DockerfileID: "cvb-helper-df", - }); err != nil { - t.Fatal(err) - } - if err := f.s.PutSandbox(domain.SandboxProfile{ - ID: "cvb-helper-bwrap", Name: "Bwrap", ProjectID: "cvb-helper", - Driver: "bwrap", EnvironmentID: "cvb-helper-env", - }); err != nil { - t.Fatal(err) - } - if len(h.sandboxNamesReferencing("dockerfile", "cvb-helper-df")) != 1 || - len(h.sandboxNamesReferencing("environment", "cvb-helper-env")) != 1 { - t.Fatal("sandbox dependency names were not found") - } if len(h.workflowNamesReferencingSandbox("missing")) != 0 { t.Fatal("missing sandbox unexpectedly referenced") } diff --git a/internal/httpapi/catalog_eval_cases_test.go b/internal/httpapi/catalog_eval_cases_test.go index 8cdce4043..628070bce 100644 --- a/internal/httpapi/catalog_eval_cases_test.go +++ b/internal/httpapi/catalog_eval_cases_test.go @@ -104,7 +104,7 @@ func TestCatalogAssetLifecycle(t *testing.T) { ID: skill.ID, Name: skill.Name, ProjectID: skill.ProjectID, Shared: false, }, http.StatusConflict) - if err := f.s.PutSandbox(domain.SandboxProfile{ID: "cvb-r2-global-sandbox", Name: "Global sandbox", ProjectID: "platform", Driver: "local"}); err != nil { + if err := f.s.PutSandbox(domain.SandboxProfile{ID: "cvb-r2-global-sandbox", Name: "Global sandbox", ProjectID: "platform", Driver: "native"}); err != nil { t.Fatal(err) } workflow := domain.WorkflowDefinition{ID: "cvb-r2-global-flow", Name: "Global", ProjectID: "platform", SandboxProfileID: "cvb-r2-global-sandbox"} @@ -130,32 +130,6 @@ func TestCatalogAssetLifecycle(t *testing.T) { } func TestCatalogSandboxDependencyAndScopeHelpers(t *testing.T) { - f := cvBNewHTTPFixture(t) - h := &catalogHandlers{deps: &deps{repo: f.s}} - dockerfile := domain.DockerfileDefinition{ID: "cvb-r2-docker", Name: "Docker", ProjectID: "platform", Content: "FROM alpine\n"} - environment := domain.EnvironmentDefinition{ID: "cvb-r2-env", Name: "Environment", ProjectID: "platform"} - if err := f.s.PutDockerfile(dockerfile); err != nil { - t.Fatal(err) - } - if err := f.s.PutEnvironment(environment); err != nil { - t.Fatal(err) - } - if err := h.shareSandboxDependencies(domain.SandboxProfile{ID: "box", ProjectID: "platform", Shared: true, - DockerfileID: dockerfile.ID, EnvironmentID: environment.ID}); err != nil { - t.Fatal(err) - } - if item, _ := f.s.Dockerfile(dockerfile.ID); !item.Shared { - t.Fatal("dockerfile not shared") - } - if item, _ := f.s.Environment(environment.ID); !item.Shared { - t.Fatal("environment not shared") - } - if err := h.shareSandboxDependencies(domain.SandboxProfile{DockerfileID: "missing"}); err == nil { - t.Fatal("missing dockerfile accepted") - } - if err := h.shareSandboxDependencies(domain.SandboxProfile{EnvironmentID: "missing"}); err == nil { - t.Fatal("missing environment accepted") - } if !workflowHasNotifications(domain.WorkflowDefinition{Nodes: []domain.WorkflowNode{{ Notifications: []domain.NotificationBinding{{Scope: "node"}}, }}}) || workflowHasNotifications(domain.WorkflowDefinition{}) { @@ -175,7 +149,7 @@ func TestRunEvalBusyApplyAndCloneHelpers(t *testing.T) { if _, err := f.s.UpdateUserCredentials(f.user.ID, repo.UserCredentialUpdate{CodeBuddyAPIKey: "key"}); err != nil { t.Fatal(err) } - if err := f.s.PutSandbox(domain.SandboxProfile{ID: "cvb-r2-eval-sandbox", Name: "Eval sandbox", ProjectID: "platform", Driver: "local"}); err != nil { + if err := f.s.PutSandbox(domain.SandboxProfile{ID: "cvb-r2-eval-sandbox", Name: "Eval sandbox", ProjectID: "platform", Driver: "native"}); err != nil { t.Fatal(err) } run := domain.Run{ID: "cvb-r2-eval-branches", WorkflowID: "cvb-r2-eval-flow", Status: "succeeded", @@ -296,16 +270,8 @@ func TestCatalogEnvironmentConflictMatrix(t *testing.T) { if err := f.s.PutProject(other); err != nil { t.Fatal(err) } - docker := domain.DockerfileDefinition{ID: "cvb-r2-assets-docker", Name: "Docker", ProjectID: "platform", Shared: true, Content: "FROM alpine\n"} - env := domain.EnvironmentDefinition{ID: "cvb-r2-assets-env", Name: "Env", ProjectID: "platform", Shared: true} box := domain.SandboxProfile{ID: "cvb-r2-assets-box", Name: "Box", ProjectID: "platform", Shared: true, Driver: "docker", - DockerfileID: docker.ID, EnvironmentID: env.ID} - if err := f.s.PutDockerfile(docker); err != nil { - t.Fatal(err) - } - if err := f.s.PutEnvironment(env); err != nil { - t.Fatal(err) - } + Dockerfile: &domain.SandboxDockerfile{Content: "FROM alpine\n"}} if err := f.s.PutSandbox(box); err != nil { t.Fatal(err) } @@ -318,15 +284,11 @@ func TestCatalogEnvironmentConflictMatrix(t *testing.T) { path string body any }{ - {"/api/dockerfiles", domain.DockerfileDefinition{ID: docker.ID, Name: "Moved", ProjectID: other.ID}}, - {"/api/dockerfiles", domain.DockerfileDefinition{ID: docker.ID, Name: docker.Name, ProjectID: "platform", Shared: false}}, - {"/api/environments", domain.EnvironmentDefinition{ID: env.ID, Name: "Moved", ProjectID: other.ID}}, - {"/api/environments", domain.EnvironmentDefinition{ID: env.ID, Name: env.Name, ProjectID: "platform", Shared: false}}, {"/api/sandboxes", domain.SandboxProfile{ID: box.ID, Name: "Moved", ProjectID: other.ID}}, {"/api/sandboxes", domain.SandboxProfile{ID: box.ID, Name: box.Name, ProjectID: "platform", Shared: false}}, } { rec := cvBRequest(t, f, http.MethodPut, tc.path, tc.body, true) - if rec.Code != http.StatusConflict && !(tc.path == "/api/environments" && rec.Code == http.StatusOK) { + if rec.Code != http.StatusConflict { t.Errorf("PUT %s = %d: %s", tc.path, rec.Code, rec.Body.String()) } } @@ -566,7 +528,7 @@ func TestDispatchWorkflowSelectionErrors(t *testing.T) { t.Fatal("issue without workflow dispatched") } - if err := f.s.PutSandbox(domain.SandboxProfile{ID: "cvb-r2-dispatch-box", Name: "Box", ProjectID: "platform", Driver: "local"}); err != nil { + if err := f.s.PutSandbox(domain.SandboxProfile{ID: "cvb-r2-dispatch-box", Name: "Box", ProjectID: "platform", Driver: "native"}); err != nil { t.Fatal(err) } fallbackID := repo.ProjectIssueWorkflowID("platform") @@ -735,7 +697,7 @@ func TestCatalogRemainingReachableBranches(t *testing.T) { t.Errorf("generic publish = %d: %s", rec.Code, rec.Body.String()) } - if err := f.s.PutSandbox(domain.SandboxProfile{ID: "cvb-r2-notify-box", Name: "Notify", ProjectID: "platform", Driver: "local"}); err != nil { + if err := f.s.PutSandbox(domain.SandboxProfile{ID: "cvb-r2-notify-box", Name: "Notify", ProjectID: "platform", Driver: "native"}); err != nil { t.Fatal(err) } notifyBot := domain.NotificationBot{ID: "cvb-r2-catalog-bot", ProjectID: "platform", Name: "Catalog bot", diff --git a/internal/httpapi/catalog_shared_refs_test.go b/internal/httpapi/catalog_shared_refs_test.go index 30bd18d73..c453145e3 100644 --- a/internal/httpapi/catalog_shared_refs_test.go +++ b/internal/httpapi/catalog_shared_refs_test.go @@ -57,7 +57,7 @@ func TestSharedScheduleDirectReferenceUnshareAndRestoreGuards(t *testing.T) { check(f.s.PutAgent(agent)) agent.Shared = true check(f.s.PutAgent(agent)) - workflow := domain.WorkflowDefinition{ID: "direct-sop", Name: "SOP", ProjectID: "direct-refs", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval"}}} + workflow := domain.WorkflowDefinition{ID: "direct-sop", Name: "SOP", ProjectID: "direct-refs", SandboxProfileID: repo.TestNativeSandboxID, Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval"}}} check(f.s.PutWorkflow(workflow)) workflow, _ = f.s.Workflow(workflow.ID) workflow.Shared = true @@ -74,7 +74,7 @@ func TestSharedScheduleDirectReferenceUnshareAndRestoreGuards(t *testing.T) { }{ {"/api/agents", domain.AgentDefinition{ID: agent.ID, Name: agent.Name, ProjectID: agent.ProjectID}}, {"/api/skills", domain.SkillDefinition{ID: skill.ID, Name: skill.Name, ProjectID: skill.ProjectID}}, - {"/api/workflows", domain.WorkflowDefinition{ID: workflow.ID, Name: workflow.Name, ProjectID: workflow.ProjectID, SandboxProfileID: "local"}}, + {"/api/workflows", domain.WorkflowDefinition{ID: workflow.ID, Name: workflow.Name, ProjectID: workflow.ProjectID, SandboxProfileID: repo.TestNativeSandboxID}}, } { if rec := cvBRequest(t, f, http.MethodPut, tc.path, tc.body, true); rec.Code != http.StatusConflict { t.Fatalf("unshare %s = %d: %s", tc.path, rec.Code, rec.Body.String()) diff --git a/internal/httpapi/catalog_test.go b/internal/httpapi/catalog_test.go index 454d75b94..e1526876b 100644 --- a/internal/httpapi/catalog_test.go +++ b/internal/httpapi/catalog_test.go @@ -107,22 +107,26 @@ func TestEnvironmentAssetsAreFilteredByProjectAndSharedScope(t *testing.T) { t.Fatal(err) } } - for _, item := range []domain.DockerfileDefinition{ - {ID: "alpha-dockerfile", Name: "Alpha", ProjectID: "alpha", Content: "FROM alpine"}, - {ID: "beta-shared-dockerfile", Name: "Beta shared", ProjectID: "beta", Shared: true, Content: "FROM alpine"}, - {ID: "beta-private-dockerfile", Name: "Beta private", ProjectID: "beta", Content: "FROM alpine"}, + recipe := &domain.SandboxDockerfile{Content: "FROM alpine"} + for _, item := range []domain.SandboxProfile{ + {ID: "alpha-box", Name: "Alpha", ProjectID: "alpha", Driver: "docker", Dockerfile: recipe}, + {ID: "beta-shared-box", Name: "Beta shared", ProjectID: "beta", Shared: true, Driver: "docker", Dockerfile: recipe}, + {ID: "beta-private-box", Name: "Beta private", ProjectID: "beta", Driver: "docker", Dockerfile: recipe}, } { - if err := s.PutDockerfile(item); err != nil { + if err := s.PutSandbox(item); err != nil { t.Fatal(err) } } h := New(s, engine.New(s, runtime.NewManager(filepath.Join(t.TempDir(), "workspaces"))), tracker.NewService(), "", "") - items := requestEmptyJSON[[]domain.DockerfileDefinition](t, h, http.MethodGet, "/api/dockerfiles?projectId=alpha", http.StatusOK) + items := requestEmptyJSON[[]domain.SandboxProfile](t, h, http.MethodGet, "/api/sandboxes?projectId=alpha", http.StatusOK) visible := map[string]bool{} for _, item := range items { visible[item.ID] = true + if item.ID == "beta-shared-box" && (item.Dockerfile == nil || item.Dockerfile.Content != "FROM alpine") { + t.Fatalf("a shared sandbox carries its Dockerfile: %+v", item) + } } - if !visible["alpha-dockerfile"] || !visible["beta-shared-dockerfile"] || visible["beta-private-dockerfile"] { + if !visible["alpha-box"] || !visible["beta-shared-box"] || visible["beta-private-box"] { t.Fatalf("unexpected project catalog visibility: %#v", visible) } } @@ -159,7 +163,7 @@ func TestWorkflowAgentsAreFilteredAndValidatedByProject(t *testing.T) { } invalid := domain.WorkflowDefinition{ - ID: "alpha-flow", Name: "Alpha flow", ProjectID: "alpha", SandboxProfileID: "local", + ID: "alpha-flow", Name: "Alpha flow", ProjectID: "alpha", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "work", Name: "Work", Type: "agent", AgentID: "beta-private-role"}}, } requestJSON[map[string]string](t, h, http.MethodPut, "/api/workflows", invalid, http.StatusBadRequest) @@ -169,7 +173,7 @@ func TestWorkflowAgentsAreFilteredAndValidatedByProject(t *testing.T) { t.Fatalf("shared role was not saved: %+v", saved.Nodes) } legacyPayload := map[string]any{ - "id": "legacy-node-gate", "name": "Legacy node gate", "projectId": "alpha", "sandboxProfileId": "local", + "id": "legacy-node-gate", "name": "Legacy node gate", "projectId": "alpha", "sandboxProfileId": "test-native", "nodes": []any{map[string]any{ "id": "work", "name": "Work", "type": "agent", "agentId": "alpha-role", "verification": []any{map[string]any{"id": "obsolete", "mode": "command", "commands": []string{"false"}}}, @@ -183,7 +187,7 @@ func TestWorkflowAgentsAreFilteredAndValidatedByProject(t *testing.T) { } } -func TestSharingSandboxCascadesDependenciesAndSharedWorkflowRequiresSharedSandbox(t *testing.T) { +func TestSharedWorkflowRequiresSharedSandbox(t *testing.T) { s, err := repo.OpenTest() if err != nil { t.Fatal(err) @@ -192,30 +196,15 @@ func TestSharingSandboxCascadesDependenciesAndSharedWorkflowRequiresSharedSandbo if err := s.PutProject(domain.Project{ID: "alpha", Key: "ALPHA", Name: "Alpha"}); err != nil { t.Fatal(err) } - if err := s.PutDockerfile(domain.DockerfileDefinition{ID: "alpha-dockerfile", Name: "Alpha image", ProjectID: "alpha", Content: "FROM alpine"}); err != nil { - t.Fatal(err) - } - if err := s.PutEnvironment(domain.EnvironmentDefinition{ID: "alpha-tools", Name: "Alpha tools", ProjectID: "alpha", InstallScript: "true"}); err != nil { - t.Fatal(err) - } h := New(s, engine.New(s, runtime.NewManager(filepath.Join(t.TempDir(), "workspaces"))), tracker.NewService(), "", "") requestJSON[map[string]bool](t, h, http.MethodPut, "/api/sandboxes", domain.SandboxProfile{ - ID: "alpha-container", Name: "Alpha container", ProjectID: "alpha", Shared: true, Driver: "docker", DockerfileID: "alpha-dockerfile", - }, http.StatusOK) - dockerfile, _ := s.Dockerfile("alpha-dockerfile") - if !dockerfile.Shared { - t.Fatal("sharing a sandbox did not share its Dockerfile") - } - requestJSON[map[string]bool](t, h, http.MethodPut, "/api/sandboxes", domain.SandboxProfile{ - ID: "alpha-process", Name: "Alpha process", ProjectID: "alpha", Driver: "bwrap", EnvironmentID: "alpha-tools", + ID: "alpha-process", Name: "Alpha process", ProjectID: "alpha", Driver: "bwrap", }, http.StatusOK) requestJSON[domain.WorkflowDefinition](t, h, http.MethodPut, "/api/workflows", domain.WorkflowDefinition{ ID: "alpha-flow", Name: "Alpha flow", ProjectID: "alpha", Shared: true, SandboxProfileID: "alpha-process", }, http.StatusBadRequest) - profile, _ := s.Sandbox("alpha-process") - environment, _ := s.Environment("alpha-tools") - if profile.Shared || environment.Shared { - t.Fatalf("rejected workflow unexpectedly shared its environment chain: sandbox=%+v environment=%+v", profile, environment) + if profile, _ := s.Sandbox("alpha-process"); profile.Shared { + t.Fatalf("rejected workflow unexpectedly shared its sandbox: %+v", profile) } } @@ -304,7 +293,7 @@ func TestAgentDeleteRequiresUnusedAndUnshared(t *testing.T) { } h := New(s, engine.New(s, runtime.NewManager(filepath.Join(t.TempDir(), "workspaces"))), tracker.NewService(), "", "") saved := requestJSON[domain.WorkflowDefinition](t, h, http.MethodPut, "/api/workflows", domain.WorkflowDefinition{ - ID: "alpha-flow", Name: "Alpha flow", ProjectID: "alpha", SandboxProfileID: "local", + ID: "alpha-flow", Name: "Alpha flow", ProjectID: "alpha", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "work", Name: "Work", Type: "agent", AgentID: "referenced-role"}}, }, http.StatusOK) if saved.Nodes[0].AgentID != "referenced-role" { @@ -362,17 +351,9 @@ func TestCatalogAssetDeleteRequiresUnusedAndUnshared(t *testing.T) { must(s.PutSkill(domain.SkillDefinition{ID: "used-skill", Name: "Used skill", ProjectID: "alpha"})) must(s.PutSkill(domain.SkillDefinition{ID: "shared-skill", Name: "Shared skill", ProjectID: "alpha", Shared: true})) must(s.PutSkillFiles("free-skill", []repo.SkillFileInput{{Path: "SKILL.md", Content: []byte("# free\n")}})) - must(s.PutDockerfile(domain.DockerfileDefinition{ID: "free-df", Name: "Free df", ProjectID: "alpha", Content: "FROM scratch"})) - must(s.PutDockerfile(domain.DockerfileDefinition{ID: "used-df", Name: "Used df", ProjectID: "alpha", Content: "FROM scratch"})) - must(s.PutDockerfile(domain.DockerfileDefinition{ID: "shared-df", Name: "Shared df", ProjectID: "alpha", Shared: true, Content: "FROM scratch"})) - must(s.PutEnvironment(domain.EnvironmentDefinition{ID: "free-env", Name: "Free env", ProjectID: "alpha"})) - must(s.PutEnvironment(domain.EnvironmentDefinition{ID: "used-env", Name: "Used env", ProjectID: "alpha"})) - must(s.PutEnvironment(domain.EnvironmentDefinition{ID: "shared-env", Name: "Shared env", ProjectID: "alpha", Shared: true})) - must(s.PutSandbox(domain.SandboxProfile{ID: "free-box", Name: "Free box", ProjectID: "alpha", Driver: "local"})) - must(s.PutSandbox(domain.SandboxProfile{ID: "used-box", Name: "Used box", ProjectID: "alpha", Driver: "local"})) - must(s.PutSandbox(domain.SandboxProfile{ID: "shared-box", Name: "Shared box", ProjectID: "alpha", Shared: true, Driver: "local"})) - must(s.PutSandbox(domain.SandboxProfile{ID: "df-box", Name: "DF box", ProjectID: "alpha", Driver: "docker", DockerfileID: "used-df"})) - must(s.PutSandbox(domain.SandboxProfile{ID: "env-box", Name: "Env box", ProjectID: "alpha", Driver: "seatbelt", EnvironmentID: "used-env"})) + must(s.PutSandbox(domain.SandboxProfile{ID: "free-box", Name: "Free box", ProjectID: "alpha", Driver: "docker", Dockerfile: &domain.SandboxDockerfile{Content: "FROM scratch"}})) + must(s.PutSandbox(domain.SandboxProfile{ID: "used-box", Name: "Used box", ProjectID: "alpha", Driver: "native"})) + must(s.PutSandbox(domain.SandboxProfile{ID: "shared-box", Name: "Shared box", ProjectID: "alpha", Shared: true, Driver: "native"})) must(s.PutAgent(domain.AgentDefinition{ ID: "asset-user", Name: "Asset user", ProjectID: "alpha", Version: 1, Rules: []string{"used-rule"}, Skills: []string{"used-skill"}, @@ -426,19 +407,9 @@ func TestCatalogAssetDeleteRequiresUnusedAndUnshared(t *testing.T) { t.Fatal("skill_files rows were not cascaded") } - assertConflict("/api/dockerfiles?id=used-df") - assertConflict("/api/dockerfiles?id=shared-df") - assertGone("/api/dockerfiles?id=free-df", func() bool { _, ok := s.Dockerfile("free-df"); return ok }, "free dockerfile") - - assertConflict("/api/environments?id=used-env") - assertConflict("/api/environments?id=shared-env") - assertGone("/api/environments?id=free-env", func() bool { _, ok := s.Environment("free-env"); return ok }, "free environment") - assertConflict("/api/sandboxes?id=used-box") assertConflict("/api/sandboxes?id=shared-box") - assertConflict("/api/sandboxes?id=local") assertConflict("/api/sandboxes?id=" + repo.GenericDockerSandboxID) - assertConflict("/api/dockerfiles?id=" + repo.GenericBackendDockerfileID) assertGone("/api/sandboxes?id=free-box", func() bool { _, ok := s.Sandbox("free-box"); return ok }, "free sandbox") } @@ -769,13 +740,13 @@ func TestGlobalRuleWorkflowBinding(t *testing.T) { t.Fatal(err) } if err := s.PutWorkflow(domain.WorkflowDefinition{ - ID: "alpha-sop", Name: "Alpha SOP", ProjectID: "alpha", SandboxProfileID: "local", + ID: "alpha-sop", Name: "Alpha SOP", ProjectID: "alpha", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "dev", Name: "实现", Type: "agent", AgentID: "developer"}}, }); err != nil { t.Fatal(err) } if err := s.PutWorkflow(domain.WorkflowDefinition{ - ID: "beta-private", Name: "Beta private", ProjectID: "beta", SandboxProfileID: "local", + ID: "beta-private", Name: "Beta private", ProjectID: "beta", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "dev", Name: "实现", Type: "agent", AgentID: "developer"}}, }); err != nil { t.Fatal(err) diff --git a/internal/httpapi/default_sandbox_test.go b/internal/httpapi/default_sandbox_test.go index dad480d3e..ad10c7b29 100644 --- a/internal/httpapi/default_sandbox_test.go +++ b/internal/httpapi/default_sandbox_test.go @@ -7,6 +7,7 @@ import ( "testing" "agentflow/internal/domain" + "agentflow/internal/repo" ) func TestProjectEnvironmentAssetsIncludeSharedGlobalDefaults(t *testing.T) { @@ -42,17 +43,17 @@ func TestDefaultSandboxWithoutCatalogRowsSupportsSOPCreation(t *testing.T) { var catalog struct { Sandboxes []domain.SandboxProfile `json:"sandboxes"` } - if bootstrap.Code != http.StatusOK || json.Unmarshal(bootstrap.Body.Bytes(), &catalog) != nil || len(catalog.Sandboxes) != 1 || catalog.Sandboxes[0].ID != "local" { + if bootstrap.Code != http.StatusOK || json.Unmarshal(bootstrap.Body.Bytes(), &catalog) != nil || len(catalog.Sandboxes) != 1 || catalog.Sandboxes[0].ID != repo.GenericDockerSandboxID { t.Fatalf("bootstrap does not expose the default: %d %s", bootstrap.Code, bootstrap.Body.String()) } listed := cvBRequest(t, f, http.MethodGet, "/api/sandboxes?projectId="+projectID, nil, true) var profiles []domain.SandboxProfile - if listed.Code != http.StatusOK || json.Unmarshal(listed.Body.Bytes(), &profiles) != nil || len(profiles) != 1 || profiles[0].ID != "local" { + if listed.Code != http.StatusOK || json.Unmarshal(listed.Body.Bytes(), &profiles) != nil || len(profiles) != 1 || profiles[0].ID != repo.GenericDockerSandboxID { t.Fatalf("project cannot select the default: %d %s", listed.Code, listed.Body.String()) } created := cvBRequest(t, f, http.MethodPut, "/api/workflows", map[string]any{ "id": "builtin-default-sop", "name": "Blank SOP", "projectId": projectID, - "status": "draft", "sandboxProfileId": "local", "nodes": []any{}, "edges": []any{}, + "status": "draft", "sandboxProfileId": repo.GenericDockerSandboxID, "nodes": []any{}, "edges": []any{}, }, true) if created.Code != http.StatusOK { t.Fatalf("blank SOP creation failed: %d %s", created.Code, created.Body.String()) diff --git a/internal/httpapi/generic_workflows_test.go b/internal/httpapi/generic_workflows_test.go index 9946d5514..fd90ac21c 100644 --- a/internal/httpapi/generic_workflows_test.go +++ b/internal/httpapi/generic_workflows_test.go @@ -105,7 +105,7 @@ func TestGenericTemplateIsListedAndReadOnly(t *testing.T) { t.Fatalf("generic template delete status = %d, want 409", code) } requestJSON[map[string]string](t, h, http.MethodPut, "/api/workflows", domain.WorkflowDefinition{ - ID: repo.GenericBackendDeliveryWorkflowID, Name: "hijack", SandboxProfileID: "local", + ID: repo.GenericBackendDeliveryWorkflowID, Name: "hijack", SandboxProfileID: "test-native", }, http.StatusConflict) if workflowRowExists(t, s, repo.GenericBackendDeliveryWorkflowID) { t.Fatal("generic template was written into the workflows table") @@ -154,10 +154,10 @@ func TestGenericTemplateCloneUsesSelectedSandbox(t *testing.T) { } } path := "/api/workflows/" + repo.GenericBackendDeliveryWorkflowID + "/clone" - for _, sandbox := range []string{"missing", "private-native", "project-native", "shared-native", "local"} { + for _, sandbox := range []string{"missing", "private-native", "local", "project-native", "shared-native"} { id := "copy-" + sandbox body := map[string]string{"id": id, "name": id, "projectId": "alpha", "sandboxProfileId": sandbox} - if sandbox == "missing" || sandbox == "private-native" { + if sandbox == "missing" || sandbox == "private-native" || sandbox == "local" { requestJSON[map[string]string](t, h, http.MethodPost, path, body, http.StatusBadRequest) if workflowRowExists(t, s, id) { t.Fatalf("created a draft for unavailable sandbox %q", sandbox) @@ -349,7 +349,7 @@ func TestGenericTemplateCloneCreatesProjectRolesAndRemapsNodes(t *testing.T) { func TestGenericTemplateIDCannotBeTakenByAnyClone(t *testing.T) { h, s := newGenericTemplateServer(t) requestJSON[domain.WorkflowDefinition](t, h, http.MethodPut, "/api/workflows", domain.WorkflowDefinition{ - ID: "regular-sop", Name: "普通 SOP", SandboxProfileID: "local", ProjectID: "alpha", Nodes: []domain.WorkflowNode{}, Edges: []domain.WorkflowEdge{}, + ID: "regular-sop", Name: "普通 SOP", SandboxProfileID: "test-native", ProjectID: "alpha", Nodes: []domain.WorkflowNode{}, Edges: []domain.WorkflowEdge{}, }, http.StatusOK) requestJSON[map[string]string](t, h, http.MethodPost, "/api/workflows/regular-sop/clone", @@ -377,7 +377,7 @@ func TestGenericTemplateIDCannotBeTakenByAnyClone(t *testing.T) { func TestGenericTemplateSurvivesLegacyCollidingRow(t *testing.T) { h, s := newGenericTemplateServer(t) legacy := domain.WorkflowDefinition{ - ID: repo.GenericBackendDeliveryWorkflowID, Name: "历史同 ID SOP", SandboxProfileID: "local", + ID: repo.GenericBackendDeliveryWorkflowID, Name: "历史同 ID SOP", SandboxProfileID: "test-native", ProjectID: "alpha", Status: "draft", Version: 1, Nodes: []domain.WorkflowNode{}, Edges: []domain.WorkflowEdge{}, } if err := s.PutWorkflow(legacy); err != nil { @@ -451,11 +451,8 @@ func TestGenericTemplateRunsDirectlyByReference(t *testing.T) { if err := s.PutRepository(domain.Repository{ID: "alpha-repo", ProjectID: "alpha", Name: "Repo", Provider: "gongfeng", CloneURL: "https://example.test/repo.git", DefaultBranch: "master"}); err != nil { t.Fatal(err) } - if err := s.PutSandbox(domain.SandboxProfile{ID: "local", Name: "Local", Driver: "local"}); err != nil { - t.Fatal(err) - } legacy := domain.WorkflowDefinition{ - ID: repo.GenericBackendDeliveryWorkflowID, Name: "历史同 ID SOP", SandboxProfileID: "local", + ID: repo.GenericBackendDeliveryWorkflowID, Name: "历史同 ID SOP", SandboxProfileID: "test-native", ProjectID: "alpha", Status: "draft", Version: 1, Nodes: []domain.WorkflowNode{}, Edges: []domain.WorkflowEdge{}, } if err := s.PutWorkflow(legacy); err != nil { @@ -535,7 +532,7 @@ func TestGenericTemplatesAndCopiesRunWithoutRepository(t *testing.T) { template, _ := s.GenericTemplateByWorkflow(id) // A real script verifies workspace execution and artifact delivery // without a model key, Git credentials, or a Docker daemon. - template.Workflow.SandboxProfileID = "local" + template.Workflow.SandboxProfileID = "test-native" template.Workflow.Nodes = []domain.WorkflowNode{{ID: "deliver", Type: "script", Name: "Deliver", ScriptLanguage: "shell", Script: "printf '# Delivered\\n' > delivery.md", MaxAttempts: 1, ArtifactOutputs: []domain.ArtifactContract{{Name: "delivery", Path: "delivery.md", Required: true}}}} template.Workflow.Edges = nil if err := s.PutGenericTemplate(template); err != nil { @@ -604,7 +601,7 @@ func TestGenericTemplateAdoptFailureKeepsAssetsForRetry(t *testing.T) { // A colliding row with a higher revision makes PutWorkflow fail with a // revision conflict after the assets were already cloned. if err := s.PutWorkflow(domain.WorkflowDefinition{ - ID: "conflicting-id", Name: "已有 SOP", SandboxProfileID: "local", ProjectID: "alpha", Revision: 5, + ID: "conflicting-id", Name: "已有 SOP", SandboxProfileID: "test-native", ProjectID: "alpha", Revision: 5, }); err != nil { t.Fatal(err) } @@ -692,7 +689,7 @@ func TestPlatformAdminCanEditGenericTemplate(t *testing.T) { } alice, _ := s.UserByLoginName("alice") requestJSONAuthed[map[string]string](t, h, alice, http.MethodPut, "/api/workflows", domain.WorkflowDefinition{ - ID: repo.GenericBackendDeliveryWorkflowID, Name: "hijack", SandboxProfileID: "local", + ID: repo.GenericBackendDeliveryWorkflowID, Name: "hijack", SandboxProfileID: "test-native", }, http.StatusConflict) published := requestJSONAuthed[domain.WorkflowDefinition](t, h, admin, http.MethodPost, "/api/workflows/"+repo.GenericBackendDeliveryWorkflowID+"/publish", map[string]any{}, http.StatusOK) @@ -780,7 +777,7 @@ func TestPlatformAdminsAPIIsConfigurable(t *testing.T) { func TestPutDeletedWorkflowIsRejected(t *testing.T) { h, s := newGenericTemplateServer(t) created := requestJSON[domain.WorkflowDefinition](t, h, http.MethodPut, "/api/workflows", domain.WorkflowDefinition{ - ID: "deleted-sop", Name: "Issue修复·沙箱", ProjectID: "alpha", SandboxProfileID: "local", + ID: "deleted-sop", Name: "Issue修复·沙箱", ProjectID: "alpha", SandboxProfileID: "test-native", }, http.StatusOK) if err := s.DeleteWorkflow(created.ID); err != nil { t.Fatal(err) @@ -788,13 +785,13 @@ func TestPutDeletedWorkflowIsRejected(t *testing.T) { // A stale editor tab resubmits the payload it loaded, which still carries a // revision. That must not recreate the deleted row. requestJSON[map[string]string](t, h, http.MethodPut, "/api/workflows", domain.WorkflowDefinition{ - ID: created.ID, Name: created.Name, Status: "published", Version: 6, Revision: created.Revision, SandboxProfileID: "local", + ID: created.ID, Name: created.Name, Status: "published", Version: 6, Revision: created.Revision, SandboxProfileID: "test-native", }, http.StatusConflict) if workflowRowExists(t, s, created.ID) { t.Fatal("deleted workflow was resurrected by a stale save") } recreated := requestJSON[domain.WorkflowDefinition](t, h, http.MethodPut, "/api/workflows", domain.WorkflowDefinition{ - ID: created.ID, Name: "Recreated", ProjectID: "alpha", SandboxProfileID: "local", + ID: created.ID, Name: "Recreated", ProjectID: "alpha", SandboxProfileID: "test-native", }, http.StatusOK) if recreated.Revision != 1 || recreated.ProjectID != "alpha" { t.Fatalf("recreate = %+v", recreated) diff --git a/internal/httpapi/handler_edges_cases_test.go b/internal/httpapi/handler_edges_cases_test.go index 55ffce7db..850ed90c2 100644 --- a/internal/httpapi/handler_edges_cases_test.go +++ b/internal/httpapi/handler_edges_cases_test.go @@ -1115,7 +1115,7 @@ func TestRunnerAdditionalSuccessAndDecodePaths(t *testing.T) { func TestCatalogWorkflowOperations(t *testing.T) { f := cvBNewHTTPFixture(t) const sandboxID = "cvb-r2-ops-sandbox" - if err := f.s.PutSandbox(domain.SandboxProfile{ID: sandboxID, Name: "Ops sandbox", ProjectID: "platform", Driver: "local"}); err != nil { + if err := f.s.PutSandbox(domain.SandboxProfile{ID: sandboxID, Name: "Ops sandbox", ProjectID: "platform", Driver: "native"}); err != nil { t.Fatal(err) } makeWorkflow := func(id string) domain.WorkflowDefinition { diff --git a/internal/httpapi/http_matrix_cases_test.go b/internal/httpapi/http_matrix_cases_test.go index 29dc9f9e7..efb4ef186 100644 --- a/internal/httpapi/http_matrix_cases_test.go +++ b/internal/httpapi/http_matrix_cases_test.go @@ -132,8 +132,6 @@ func TestCatalogIssueRunAndSpaceValidationHTTP(t *testing.T) { {http.MethodDelete, "/api/rules?id=missing", nil, 404}, {http.MethodPut, "/api/skills", map[string]any{}, 400}, {http.MethodDelete, "/api/skills?id=missing", nil, 404}, - {http.MethodPut, "/api/dockerfiles", map[string]any{}, 400}, - {http.MethodPut, "/api/environments", map[string]any{}, 400}, {http.MethodPut, "/api/sandboxes", map[string]any{}, 400}, {http.MethodPut, "/api/workflows", map[string]any{}, 200}, {http.MethodGet, "/api/workflows/missing", nil, 404}, diff --git a/internal/httpapi/issue_base_branch_test.go b/internal/httpapi/issue_base_branch_test.go index ad67bd12a..c7bbc8e04 100644 --- a/internal/httpapi/issue_base_branch_test.go +++ b/internal/httpapi/issue_base_branch_test.go @@ -193,7 +193,7 @@ func TestDispatchCustomBaseBranchSkipsScheduledIntegration(t *testing.T) { if err := st.PutRepository(domain.Repository{ID: "dispatch-branch-repo", ProjectID: "platform", Name: "Repo", DefaultBranch: "master", IntegrateBranch: "agentflow/integration"}); err != nil { t.Fatal(err) } - if err := st.PutWorkflow(domain.WorkflowDefinition{ID: "branch-flow", Name: "Branch flow", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval"}}}); err != nil { + if err := st.PutWorkflow(domain.WorkflowDefinition{ID: "branch-flow", Name: "Branch flow", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval"}}}); err != nil { t.Fatal(err) } eng := engine.New(st, runtime.NewManager(filepath.Join(t.TempDir(), "workspaces"))) @@ -303,7 +303,7 @@ func TestDispatchEmptyBaseBranchUsesCurrentConfiguredMainBranch(t *testing.T) { if err := st.PutRepository(repository); err != nil { t.Fatal(err) } - if err := st.PutWorkflow(domain.WorkflowDefinition{ID: "configured-main-flow", Name: "Main branch flow", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval"}}}); err != nil { + if err := st.PutWorkflow(domain.WorkflowDefinition{ID: "configured-main-flow", Name: "Main branch flow", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval"}}}); err != nil { t.Fatal(err) } eng := engine.New(st, runtime.NewManager(filepath.Join(t.TempDir(), "workspaces"))) @@ -369,7 +369,7 @@ func TestDispatchLegacyDefaultBranchCreatesNewWorkBranchWithoutChangingRecord(t if err := st.PutRepository(repository); err != nil { t.Fatal(err) } - if err := st.PutWorkflow(domain.WorkflowDefinition{ID: "legacy-main-flow", Name: "Legacy main", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval"}}}); err != nil { + if err := st.PutWorkflow(domain.WorkflowDefinition{ID: "legacy-main-flow", Name: "Legacy main", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval"}}}); err != nil { t.Fatal(err) } issue := domain.Issue{ID: "legacy-main", ProjectID: "platform", Title: "历史主分支", Kind: "issue", RepositoryID: repository.ID, BaseBranch: repository.DefaultBranch, WorkflowID: "legacy-main-flow"} diff --git a/internal/httpapi/issue_repository_branches_test.go b/internal/httpapi/issue_repository_branches_test.go index 9c965577f..d004321ad 100644 --- a/internal/httpapi/issue_repository_branches_test.go +++ b/internal/httpapi/issue_repository_branches_test.go @@ -192,7 +192,7 @@ func TestDispatchRepositoryBranches(t *testing.T) { } t.Cleanup(st.Close) ids := putIssueBranchRepositories(t, st) - if err := st.PutWorkflow(domain.WorkflowDefinition{ID: "multi-branch-flow", Name: "Approval", SandboxProfileID: "local", + if err := st.PutWorkflow(domain.WorkflowDefinition{ID: "multi-branch-flow", Name: "Approval", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval"}}}); err != nil { t.Fatal(err) } diff --git a/internal/httpapi/issue_sop_mode_test.go b/internal/httpapi/issue_sop_mode_test.go index 0791463cb..9e5d86f8e 100644 --- a/internal/httpapi/issue_sop_mode_test.go +++ b/internal/httpapi/issue_sop_mode_test.go @@ -18,7 +18,7 @@ func TestRequirementWithoutSOP(t *testing.T) { t.Fatal(err) } t.Cleanup(st.Close) - if err := st.PutWorkflow(domain.WorkflowDefinition{ID: "sop-mode-flow", Name: "SOP mode", Version: 1, SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}}); err != nil { + if err := st.PutWorkflow(domain.WorkflowDefinition{ID: "sop-mode-flow", Name: "SOP mode", Version: 1, SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}}); err != nil { t.Fatal(err) } if err := st.PutProject(domain.Project{ID: "sop-mode", Name: "SOP mode", OwnerID: 1, WorkflowID: "sop-mode-flow"}); err != nil { diff --git a/internal/httpapi/issues_test.go b/internal/httpapi/issues_test.go index 75cf3526e..89216f608 100644 --- a/internal/httpapi/issues_test.go +++ b/internal/httpapi/issues_test.go @@ -28,7 +28,7 @@ func TestIssueDispatchCreatesTaskAndRun(t *testing.T) { t.Fatal(err) } t.Cleanup(func() { s.Close() }) - if err := s.PutWorkflow(domain.WorkflowDefinition{ID: "issue-test", Name: "Issue test", Version: 1, SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}}); err != nil { + if err := s.PutWorkflow(domain.WorkflowDefinition{ID: "issue-test", Name: "Issue test", Version: 1, SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}}); err != nil { t.Fatal(err) } e := engine.New(s, runtime.NewManager(filepath.Join(root, "workspaces"))) @@ -85,7 +85,7 @@ func TestDispatchTAPDIssuePutsStoryIdentityInInput(t *testing.T) { t.Fatal(err) } t.Cleanup(func() { s.Close() }) - if err := s.PutWorkflow(domain.WorkflowDefinition{ID: "tapd-identity", Name: "TAPD identity", Version: 1, SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}}); err != nil { + if err := s.PutWorkflow(domain.WorkflowDefinition{ID: "tapd-identity", Name: "TAPD identity", Version: 1, SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}}); err != nil { t.Fatal(err) } e := engine.New(s, runtime.NewManager(filepath.Join(root, "workspaces"))) @@ -220,7 +220,7 @@ func TestIssueDispatchUsesTriggerUserCredentials(t *testing.T) { if err := s.PutUser(operator); err != nil { t.Fatal(err) } - if err := s.PutWorkflow(domain.WorkflowDefinition{ID: "issue-trigger", Name: "Trigger", Version: 1, SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}}); err != nil { + if err := s.PutWorkflow(domain.WorkflowDefinition{ID: "issue-trigger", Name: "Trigger", Version: 1, SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}}); err != nil { t.Fatal(err) } e := engine.New(s, runtime.NewManager(filepath.Join(root, "workspaces"))) @@ -263,7 +263,7 @@ func TestExternalIssueDispatchKeepsExplicitWorkflow(t *testing.T) { } t.Cleanup(func() { s.Close() }) workflow := domain.WorkflowDefinition{ - ID: "gongfeng-bwrap-override", Name: "Gongfeng bwrap override", Version: 1, SandboxProfileID: "local", + ID: "gongfeng-bwrap-override", Name: "Gongfeng bwrap override", Version: 1, SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}, } if err := s.PutWorkflow(workflow); err != nil { @@ -301,8 +301,8 @@ func TestIssueDispatchSecondLaneKeepsDefaultSOP(t *testing.T) { t.Fatal(err) } t.Cleanup(func() { s.Close() }) - backend := domain.WorkflowDefinition{ID: "wf-backend-lane", Name: "Backend", SOPLane: "backend", Version: 1, SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}} - frontend := domain.WorkflowDefinition{ID: "wf-frontend-lane", Name: "Frontend", SOPLane: "frontend", Version: 1, SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}} + backend := domain.WorkflowDefinition{ID: "wf-backend-lane", Name: "Backend", SOPLane: "backend", Version: 1, SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}} + frontend := domain.WorkflowDefinition{ID: "wf-frontend-lane", Name: "Frontend", SOPLane: "frontend", Version: 1, SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}} if err := s.PutWorkflow(backend); err != nil { t.Fatal(err) } @@ -362,8 +362,8 @@ func TestIssueSOPBindingsRoundTripAndDispatchOwner(t *testing.T) { if err := s.PutUser(operator); err != nil { t.Fatal(err) } - design := domain.WorkflowDefinition{ID: "wf-design-bind", Name: "Design", SOPLane: "design", Version: 1, SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}} - backend := domain.WorkflowDefinition{ID: "wf-backend-bind", Name: "Backend", SOPLane: "backend", Version: 1, SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}} + design := domain.WorkflowDefinition{ID: "wf-design-bind", Name: "Design", SOPLane: "design", Version: 1, SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}} + backend := domain.WorkflowDefinition{ID: "wf-backend-bind", Name: "Backend", SOPLane: "backend", Version: 1, SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}} if err := s.PutWorkflow(design); err != nil { t.Fatal(err) } @@ -402,8 +402,8 @@ func TestRequirementInheritsProjectPlaybook(t *testing.T) { t.Fatal(err) } t.Cleanup(s.Close) - product := domain.WorkflowDefinition{ID: "wf-play-product", Name: "Product", SOPLane: "product", Version: 1, SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}} - backend := domain.WorkflowDefinition{ID: "wf-play-backend", Name: "Backend", SOPLane: "backend", Version: 1, SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}} + product := domain.WorkflowDefinition{ID: "wf-play-product", Name: "Product", SOPLane: "product", Version: 1, SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}} + backend := domain.WorkflowDefinition{ID: "wf-play-backend", Name: "Backend", SOPLane: "backend", Version: 1, SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}} if err := s.PutWorkflow(product); err != nil { t.Fatal(err) } @@ -451,9 +451,9 @@ func TestRequirementPicksNamedPlaybook(t *testing.T) { t.Fatal(err) } t.Cleanup(s.Close) - product := domain.WorkflowDefinition{ID: "wf-combo-product", Name: "Product", SOPLane: "product", Version: 1, SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}} - frontend := domain.WorkflowDefinition{ID: "wf-combo-frontend", Name: "Frontend", SOPLane: "frontend", Version: 1, SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}} - backend := domain.WorkflowDefinition{ID: "wf-combo-backend", Name: "Backend", SOPLane: "backend", Version: 1, SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}} + product := domain.WorkflowDefinition{ID: "wf-combo-product", Name: "Product", SOPLane: "product", Version: 1, SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}} + frontend := domain.WorkflowDefinition{ID: "wf-combo-frontend", Name: "Frontend", SOPLane: "frontend", Version: 1, SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}} + backend := domain.WorkflowDefinition{ID: "wf-combo-backend", Name: "Backend", SOPLane: "backend", Version: 1, SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}} for _, wf := range []domain.WorkflowDefinition{product, frontend, backend} { if err := s.PutWorkflow(wf); err != nil { t.Fatal(err) @@ -517,8 +517,8 @@ func TestWorkflowAPIRequiresExistingWorkflowSandboxProfile(t *testing.T) { requestJSON[map[string]string](t, h, http.MethodPut, "/api/workflows", map[string]any{"id": "missing", "name": "Missing", "nodes": []any{}, "edges": []any{}}, http.StatusBadRequest) requestJSON[map[string]string](t, h, http.MethodPut, "/api/workflows", map[string]any{"id": "unknown", "name": "Unknown", "sandboxProfileId": "does-not-exist", "nodes": []any{}, "edges": []any{}}, http.StatusBadRequest) - created := requestJSON[domain.WorkflowDefinition](t, h, http.MethodPut, "/api/workflows", map[string]any{"id": "valid", "name": "Valid", "sandboxProfileId": "local", "nodes": []any{}, "edges": []any{}}, http.StatusOK) - if created.SandboxProfileID != "local" { + created := requestJSON[domain.WorkflowDefinition](t, h, http.MethodPut, "/api/workflows", map[string]any{"id": "valid", "name": "Valid", "sandboxProfileId": "test-native", "nodes": []any{}, "edges": []any{}}, http.StatusOK) + if created.SandboxProfileID != "test-native" { t.Fatalf("sandboxProfileId = %q", created.SandboxProfileID) } } @@ -543,7 +543,7 @@ func TestAssetAPIAcceptsSandboxEnvironmentButExecutorsAreReadOnly(t *testing.T) t.Fatalf("built-in CLI catalog[%d] = %+v, want %+v", i, executors[i], want[i]) } } - requestJSON[map[string]bool](t, h, http.MethodPut, "/api/sandboxes", map[string]any{"id": "configured", "name": "Configured", "projectId": "platform", "driver": "local", "environment": map[string]string{"TOOL_MODE": "test"}}, http.StatusOK) + requestJSON[map[string]bool](t, h, http.MethodPut, "/api/sandboxes", map[string]any{"id": "configured", "name": "Configured", "projectId": "platform", "driver": "native", "environment": map[string]string{"TOOL_MODE": "test"}}, http.StatusOK) profile, ok := s.Sandbox("configured") if !ok || profile.Environment["TOOL_MODE"] != "test" { t.Fatalf("sandbox environment was not persisted: %+v", profile) @@ -570,7 +570,7 @@ func TestAgentAPIOnlyAcceptsBuiltInCLIs(t *testing.T) { } } -func TestAssetAPIManagesDockerfilesEnvironmentsAndDockerSandbox(t *testing.T) { +func TestSandboxAPIStoresItsDockerfileAndInstall(t *testing.T) { root := t.TempDir() s, err := repo.OpenTest() if err != nil { @@ -579,21 +579,31 @@ func TestAssetAPIManagesDockerfilesEnvironmentsAndDockerSandbox(t *testing.T) { t.Cleanup(func() { s.Close() }) h := New(s, engine.New(s, runtime.NewManager(filepath.Join(root, "workspaces"))), tracker.NewService(), "", "") - requestJSON[map[string]string](t, h, http.MethodPut, "/api/dockerfiles", map[string]any{"id": "slim", "name": "Slim", "projectId": "platform"}, http.StatusBadRequest) - saved := requestJSON[map[string]bool](t, h, http.MethodPut, "/api/dockerfiles", map[string]any{"id": "slim", "name": "Slim", "projectId": "platform", "content": "FROM debian:bookworm-slim"}, http.StatusOK) + requestJSON[map[string]string](t, h, http.MethodPut, "/api/sandboxes", map[string]any{"id": "container-new", "name": "Container", "projectId": "platform", "driver": "docker"}, http.StatusBadRequest) + requestJSON[map[string]string](t, h, http.MethodPut, "/api/sandboxes", map[string]any{"id": "container-new", "name": "Container", "projectId": "platform", "driver": "docker", "dockerfile": map[string]any{"content": " "}}, http.StatusBadRequest) + saved := requestJSON[map[string]bool](t, h, http.MethodPut, "/api/sandboxes", map[string]any{"id": "container-new", "name": "Container", "projectId": "platform", "driver": "docker", "dockerfile": map[string]any{"content": "FROM debian:bookworm-slim", "files": map[string]string{"etc/a": "x"}}}, http.StatusOK) if !saved["ok"] { - t.Fatalf("dockerfile save = %+v", saved) + t.Fatalf("sandbox save = %+v", saved) } - requestJSON[map[string]bool](t, h, http.MethodPut, "/api/environments", map[string]any{"id": "php8-test", "name": "PHP 8 test", "projectId": "platform", "variables": map[string]string{"PHP_VERSION": "8.3.0"}, "pathEntries": []string{"bin"}, "installScript": "mkdir -p \"$PREFIX/bin\""}, http.StatusOK) - requestJSON[map[string]string](t, h, http.MethodPut, "/api/sandboxes", map[string]any{"id": "container-new", "name": "Container", "projectId": "platform", "driver": "docker"}, http.StatusBadRequest) - requestJSON[map[string]bool](t, h, http.MethodPut, "/api/sandboxes", map[string]any{"id": "container-new", "name": "Container", "projectId": "platform", "driver": "docker", "dockerfileId": "slim"}, http.StatusOK) profile, ok := s.Sandbox("container-new") - if !ok || profile.DockerfileID != "slim" { - t.Fatalf("docker sandbox should store dockerfileId: %+v", profile) + if !ok || profile.Dockerfile == nil || profile.Dockerfile.Content != "FROM debian:bookworm-slim" || profile.Dockerfile.Files["etc/a"] != "x" { + t.Fatalf("docker sandbox should store its Dockerfile: %+v", profile) + } + requestJSON[map[string]bool](t, h, http.MethodPut, "/api/sandboxes", map[string]any{"id": "php8-test", "name": "PHP 8 test", "projectId": "platform", "driver": "native", "environment": map[string]string{"PHP_VERSION": "8.3.0"}}, http.StatusOK) + if profile, ok := s.Sandbox("php8-test"); !ok || profile.Environment["PHP_VERSION"] != "8.3.0" { + t.Fatalf("native sandbox should store its variables: %+v", profile) } + requestJSON[map[string]string](t, h, http.MethodPut, "/api/sandboxes", map[string]any{"id": "local-test", "name": "Local", "projectId": "platform", "driver": "local"}, http.StatusBadRequest) boot := requestJSON[map[string]any](t, h, http.MethodGet, "/api/bootstrap", nil, http.StatusOK) - if boot["dockerfiles"] == nil || boot["environments"] == nil { - t.Fatalf("bootstrap missing dockerfile/environment catalogs: %+v", boot) + if boot["dockerfiles"] != nil || boot["environments"] != nil || boot["sandboxes"] == nil { + t.Fatalf("bootstrap lists sandboxes only: %+v", boot) + } + for _, path := range []string{"/api/dockerfiles", "/api/environments"} { + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, path, nil)) + if rec.Code != http.StatusNotFound { + t.Fatalf("%s is gone, got %d", path, rec.Code) + } } } @@ -608,7 +618,7 @@ func TestManualRunKeepsSelectedProjectContext(t *testing.T) { t.Fatal(err) } workflow := domain.WorkflowDefinition{ - ID: "manual-project-run", Name: "Manual project run", SandboxProfileID: "local", + ID: "manual-project-run", Name: "Manual project run", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}, } if err := s.PutWorkflow(workflow); err != nil { @@ -652,7 +662,7 @@ func TestRepositoryBindingIsValidatedAndFrozenAtDispatch(t *testing.T) { t.Fatal(err) } t.Cleanup(func() { s.Close() }) - if err := s.PutWorkflow(domain.WorkflowDefinition{ID: "repo-flow", Name: "Repo flow", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}}); err != nil { + if err := s.PutWorkflow(domain.WorkflowDefinition{ID: "repo-flow", Name: "Repo flow", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}}); err != nil { t.Fatal(err) } h := New(s, engine.New(s, runtime.NewManager(filepath.Join(root, "workspaces"))), tracker.NewService(), "", "") @@ -1002,7 +1012,7 @@ func TestStandardWorkerIngressSeparatesRealtimeLogs(t *testing.T) { t.Fatal(err) } t.Cleanup(func() { s.Close() }) - wf := domain.WorkflowDefinition{ID: "signal-test", Name: "Signal test", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "gate", Name: "Gate", Type: "approval", MaxAttempts: 1}}} + wf := domain.WorkflowDefinition{ID: "signal-test", Name: "Signal test", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "gate", Name: "Gate", Type: "approval", MaxAttempts: 1}}} if err := s.PutWorkflow(wf); err != nil { t.Fatal(err) } @@ -1133,7 +1143,7 @@ func TestIssueDispatchReturnsQueuedTask(t *testing.T) { t.Fatal(err) } t.Cleanup(func() { s.Close() }) - workflow := domain.WorkflowDefinition{ID: "dispatch-queued", Name: "Queued dispatch", Version: 1, SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "approval", Type: "approval", MaxAttempts: 1}}} + workflow := domain.WorkflowDefinition{ID: "dispatch-queued", Name: "Queued dispatch", Version: 1, SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "approval", Type: "approval", MaxAttempts: 1}}} if err := s.PutWorkflow(workflow); err != nil { t.Fatal(err) } @@ -1277,7 +1287,7 @@ func TestGongfengClosedIssueRejectsDispatch(t *testing.T) { t.Fatal(err) } t.Cleanup(func() { s.Close() }) - if err := s.PutWorkflow(domain.WorkflowDefinition{ID: "issue-fix-production", Name: "Issue fix", Version: 1, SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}}); err != nil { + if err := s.PutWorkflow(domain.WorkflowDefinition{ID: "issue-fix-production", Name: "Issue fix", Version: 1, SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}}); err != nil { t.Fatal(err) } e := engine.New(s, runtime.NewManager(filepath.Join(root, "workspaces"))) @@ -1363,7 +1373,7 @@ func TestMergedTAPDDeliveryRequiresExplicitReopen(t *testing.T) { t.Fatal(err) } t.Cleanup(s.Close) - wf := domain.WorkflowDefinition{ID: "requirement-development-production", Name: "Requirement", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}} + wf := domain.WorkflowDefinition{ID: "requirement-development-production", Name: "Requirement", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}} if err := s.PutWorkflow(wf); err != nil { t.Fatal(err) } @@ -1405,7 +1415,7 @@ func TestRequirementDispatchesWithoutClarificationGate(t *testing.T) { t.Fatal(err) } t.Cleanup(func() { s.Close() }) - wf := domain.WorkflowDefinition{ID: "requirement-gated", Name: "Requirement gated", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}} + wf := domain.WorkflowDefinition{ID: "requirement-gated", Name: "Requirement gated", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}} if err := s.PutWorkflow(wf); err != nil { t.Fatal(err) } @@ -1434,7 +1444,7 @@ func TestScheduledDispatchDoesNotRequireClarification(t *testing.T) { t.Fatal(err) } t.Cleanup(func() { s.Close() }) - wf := domain.WorkflowDefinition{ID: "req-sched-wf", Name: "Req", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval"}}} + wf := domain.WorkflowDefinition{ID: "req-sched-wf", Name: "Req", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval"}}} if err := s.PutWorkflow(wf); err != nil { t.Fatal(err) } @@ -1460,7 +1470,7 @@ func TestSyncedRequirementCanDispatchWithoutClarification(t *testing.T) { t.Fatal(err) } t.Cleanup(func() { s.Close() }) - wf := domain.WorkflowDefinition{ID: "req-sync-wf", Name: "Req", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval"}}} + wf := domain.WorkflowDefinition{ID: "req-sync-wf", Name: "Req", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval"}}} if err := s.PutWorkflow(wf); err != nil { t.Fatal(err) } @@ -1489,7 +1499,7 @@ func TestReadyClarificationCanDispatch(t *testing.T) { t.Fatal(err) } t.Cleanup(func() { s.Close() }) - wf := domain.WorkflowDefinition{ID: "req-ready-wf", Name: "Req", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval"}}} + wf := domain.WorkflowDefinition{ID: "req-ready-wf", Name: "Req", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval"}}} if err := s.PutWorkflow(wf); err != nil { t.Fatal(err) } @@ -1532,7 +1542,7 @@ func TestExistingIssueClarificationDoesNotStartOrBlockSOP(t *testing.T) { t.Fatal(err) } t.Cleanup(func() { s.Close() }) - wf := domain.WorkflowDefinition{ID: "issue-flow", Name: "Issue flow", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}} + wf := domain.WorkflowDefinition{ID: "issue-flow", Name: "Issue flow", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}} if err := s.PutWorkflow(wf); err != nil { t.Fatal(err) } @@ -1575,7 +1585,7 @@ func TestRequirementClarificationFinishesWithoutScore(t *testing.T) { t.Fatal(err) } t.Cleanup(func() { s.Close() }) - wf := domain.WorkflowDefinition{ID: "req-flow", Name: "Req flow", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}} + wf := domain.WorkflowDefinition{ID: "req-flow", Name: "Req flow", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}} if err := s.PutWorkflow(wf); err != nil { t.Fatal(err) } @@ -1841,7 +1851,7 @@ func TestIssuesSaveDoesNotGateSyncedTAPDRequirement(t *testing.T) { t.Fatal(err) } t.Cleanup(s.Close) - if err := s.PutWorkflow(domain.WorkflowDefinition{ID: "demodns-issue-fix", Name: "Issue fix", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "fix", Name: "Fix", Type: "agent"}}}); err != nil { + if err := s.PutWorkflow(domain.WorkflowDefinition{ID: "demodns-issue-fix", Name: "Issue fix", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "fix", Name: "Fix", Type: "agent"}}}); err != nil { t.Fatal(err) } if err := s.PutRepository(domain.Repository{ID: "repo-new-demodns", ProjectID: "platform", Name: "dns-console", GongfengProjectID: "example/dns-console", DefaultBranch: "master"}); err != nil { @@ -1920,7 +1930,7 @@ func TestImportTAPDIssueBindsSelectedWorkflow(t *testing.T) { if err := s.PutProject(project); err != nil { t.Fatal(err) } - wf := domain.WorkflowDefinition{ID: "custom-req-sop", Name: "定制需求 SOP", ProjectID: "platform", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}} + wf := domain.WorkflowDefinition{ID: "custom-req-sop", Name: "定制需求 SOP", ProjectID: "platform", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}} if err := s.PutWorkflow(wf); err != nil { t.Fatal(err) } diff --git a/internal/httpapi/main_test.go b/internal/httpapi/main_test.go index 0efe35a90..c6a6d1d99 100644 --- a/internal/httpapi/main_test.go +++ b/internal/httpapi/main_test.go @@ -3,6 +3,8 @@ package httpapi import ( "os" "testing" + + "agentflow/internal/repo" ) // Tests isolate assistant state by pointing AGENTFLOW_ASSISTANT_SESSION_DIR at @@ -11,5 +13,8 @@ import ( // them to a real directory shared by every test. func TestMain(m *testing.M) { os.Unsetenv("AGENTFLOW_CONVERSATION_DIR") - os.Exit(m.Run()) + cleanup := repo.UseSandboxVisibleTempDir() + code := m.Run() + cleanup() + os.Exit(code) } diff --git a/internal/httpapi/misc_cases_test.go b/internal/httpapi/misc_cases_test.go index 19d1017ad..fe2349181 100644 --- a/internal/httpapi/misc_cases_test.go +++ b/internal/httpapi/misc_cases_test.go @@ -46,7 +46,7 @@ func TestMiscScheduleRemainingHelpersAndHTTP(t *testing.T) { cvBGiveCodeBuddyKey(t, &f) if err := f.s.PutWorkflow(domain.WorkflowDefinition{ ID: "cvb-misc-wf", Name: "misc workflow", ProjectID: "platform", - Status: "published", Version: 1, SandboxProfileID: "local", + Status: "published", Version: 1, SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "approve", Name: "approve", Type: "approval", MaxAttempts: 1}}, }); err != nil { t.Fatal(err) @@ -260,7 +260,7 @@ func TestMiscProjectPlaybooksPermissionsAndAssignments(t *testing.T) { } if err := f.s.PutWorkflow(domain.WorkflowDefinition{ ID: "cvb-playbook-wf", Name: "playbook", ProjectID: "platform", - Status: "published", Version: 1, SandboxProfileID: "local", + Status: "published", Version: 1, SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "approve", Name: "approve", Type: "approval", MaxAttempts: 1}}, }); err != nil { t.Fatal(err) @@ -408,7 +408,7 @@ func TestMiscRoomAuthorizationRosterAndSuccessHTTP(t *testing.T) { } if err := f.s.PutWorkflow(domain.WorkflowDefinition{ ID: "cvb-room-wf", Name: "room workflow", ProjectID: project.ID, - Status: "published", Version: 1, SandboxProfileID: "local", + Status: "published", Version: 1, SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "approve", Name: "approve", Type: "approval", MaxAttempts: 1}}, }); err != nil { t.Fatal(err) diff --git a/internal/httpapi/pass_test.go b/internal/httpapi/pass_test.go index 0ceedf780..9969b1604 100644 --- a/internal/httpapi/pass_test.go +++ b/internal/httpapi/pass_test.go @@ -58,7 +58,7 @@ func TestPassFailedScriptContinuesDownstreamHTTP(t *testing.T) { s := openPassTestStore(t) suffix := time.Now().UTC().UnixNano() wfID := fmt.Sprintf("pass-http-%d", suffix) - wf := domain.WorkflowDefinition{ID: wfID, Name: "pass http", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{ + wf := domain.WorkflowDefinition{ID: wfID, Name: "pass http", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "hard", Name: "hard", Type: "script", ScriptLanguage: "shell", Script: "exit 1", OnFailure: "fail", MaxAttempts: 1}, {ID: "next", Name: "next", Type: "script", ScriptLanguage: "shell", Script: "printf 'ok\\n'", MaxAttempts: 1}, }, Edges: []domain.WorkflowEdge{{ID: "e1", Source: "hard", Target: "next", When: "success"}}} diff --git a/internal/httpapi/project_write_access.go b/internal/httpapi/project_write_access.go index 924721331..93b3bd866 100644 --- a/internal/httpapi/project_write_access.go +++ b/internal/httpapi/project_write_access.go @@ -151,12 +151,6 @@ func (d deps) assetOwner(kind, id string) (project string, global bool, found bo case "skills": v, ok := d.repo.Skill(id) return v.ProjectID, v.ProjectID == "", ok - case "dockerfiles": - v, ok := d.repo.Dockerfile(id) - return v.ProjectID, v.ProjectID == "", ok - case "environments": - v, ok := d.repo.Environment(id) - return v.ProjectID, v.ProjectID == "", ok case "sandboxes": v, ok := d.repo.Sandbox(id) return v.ProjectID, v.ProjectID == "", ok @@ -234,7 +228,7 @@ func (d deps) allowAssetWrite(c *gin.Context, path string) bool { } kind := strings.TrimPrefix(path, "/api/") switch kind { - case "rules", "skills", "dockerfiles", "environments", "sandboxes", "mcp-servers", "schedule-jobs": + case "rules", "skills", "sandboxes", "mcp-servers", "schedule-jobs": default: return true } diff --git a/internal/httpapi/project_write_access_test.go b/internal/httpapi/project_write_access_test.go index a0f649e5c..5d98dd097 100644 --- a/internal/httpapi/project_write_access_test.go +++ b/internal/httpapi/project_write_access_test.go @@ -164,11 +164,11 @@ func TestProjectContentWritesRequireMembership(t *testing.T) { if code := call(other, "DELETE", "/api/rules?id=rule1", ""); code != 403 { t.Fatalf("non-member delete rule: %d", code) } - if err := s.PutDockerfile(domain.DockerfileDefinition{ID: "df-global", Name: "Base", Content: "FROM alpine"}); err != nil { + if err := s.PutSandbox(domain.SandboxProfile{ID: "sb-global", Name: "Base", Driver: domain.SandboxDriverDocker, Dockerfile: &domain.SandboxDockerfile{Content: "FROM alpine"}}); err != nil { t.Fatal(err) } - if code := call(owner, "PUT", "/api/dockerfiles", `{"id":"df-global","name":"Base","content":"FROM evil"}`); code != 403 { - t.Fatalf("non-admin edit platform dockerfile: %d", code) + if code := call(owner, "PUT", "/api/sandboxes", `{"id":"sb-global","name":"Base","driver":"docker","dockerfile":{"content":"FROM evil"}}`); code != 403 { + t.Fatalf("non-admin edit platform sandbox: %d", code) } if code := call(other, "PUT", "/api/sync/config", `{}`); code != 403 { t.Fatalf("non-admin sync config: %d", code) diff --git a/internal/httpapi/repository_clone_url_test.go b/internal/httpapi/repository_clone_url_test.go index 92b4d4857..4663f86a7 100644 --- a/internal/httpapi/repository_clone_url_test.go +++ b/internal/httpapi/repository_clone_url_test.go @@ -87,7 +87,7 @@ func TestRunnerTaskListDropsCloneURLCredentials(t *testing.T) { func TestLegacyCloneURLCredentialsStayOutOfPromptAndRunViews(t *testing.T) { f := cvBNewHTTPFixture(t) - if err := f.s.PutWorkflow(domain.WorkflowDefinition{ID: "legacy-flow", Name: "Legacy flow", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}}); err != nil { + if err := f.s.PutWorkflow(domain.WorkflowDefinition{ID: "legacy-flow", Name: "Legacy flow", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}}); err != nil { t.Fatal(err) } const legacyURL = "https://user:s3cret-token@github.com/acme/app.git" @@ -121,7 +121,7 @@ func TestLegacyCloneURLCredentialsStayOutOfPromptAndRunViews(t *testing.T) { } } - if err := f.s.PutWorkflow(domain.WorkflowDefinition{ID: "legacy-generic", Name: "Legacy generic", Generic: true, SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}}); err != nil { + if err := f.s.PutWorkflow(domain.WorkflowDefinition{ID: "legacy-generic", Name: "Legacy generic", Generic: true, SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}}); err != nil { t.Fatal(err) } project, ok := f.s.Project("platform") diff --git a/internal/httpapi/repository_ssh_test.go b/internal/httpapi/repository_ssh_test.go index 479588831..f900b497f 100644 --- a/internal/httpapi/repository_ssh_test.go +++ b/internal/httpapi/repository_ssh_test.go @@ -71,7 +71,7 @@ func TestSSHRepositoryCheckoutAndDelivery(t *testing.T) { rc := domain.RepositoryContext{RepositoryID: repository.ID, Name: repository.Name, Provider: repository.Provider, CloneURL: remote, WebURL: repository.WebURL, BaseBranch: "main", DefaultBranch: "main", WorkBranch: "feature/ssh-test", CreateNewWorkBranch: true, WorkspaceDir: "app"} run := domain.Run{ ID: "run-git-ssh", Kind: domain.RunKindWorkspace, Status: "waiting", - WorkflowSnapshot: domain.WorkflowDefinition{ID: domain.ConversationWorkspaceWorkflowID, SandboxProfileID: "local"}, + WorkflowSnapshot: domain.WorkflowDefinition{ID: domain.ConversationWorkspaceWorkflowID, SandboxProfileID: "test-native"}, ExecutionContext: domain.TelemetryContext{ProjectID: "platform", ResponsibleUserID: f.user.ID}, Repositories: []domain.RepositoryContext{rc}, Nodes: map[string]*domain.NodeRun{}, } diff --git a/internal/httpapi/room_dispatch_target_wiring_test.go b/internal/httpapi/room_dispatch_target_wiring_test.go index eab73de16..9a3a96e14 100644 --- a/internal/httpapi/room_dispatch_target_wiring_test.go +++ b/internal/httpapi/room_dispatch_target_wiring_test.go @@ -29,7 +29,7 @@ func TestRoomDispatchTargetReachesIssueAndCards(t *testing.T) { {ID: "target-review", Name: "评审"}, {ID: "target-ship", Name: "上线"}, } { - wf.Version, wf.ProjectID, wf.Status, wf.SandboxProfileID = 1, "platform", "published", "local" + wf.Version, wf.ProjectID, wf.Status, wf.SandboxProfileID = 1, "platform", "published", "test-native" wf.Nodes = []domain.WorkflowNode{{ID: "approval", Name: "人工确认", Type: "approval", MaxAttempts: 1}} if err := s.PutWorkflow(wf); err != nil { t.Fatal(err) diff --git a/internal/httpapi/rooms_test.go b/internal/httpapi/rooms_test.go index 470ae323e..4c2c7d759 100644 --- a/internal/httpapi/rooms_test.go +++ b/internal/httpapi/rooms_test.go @@ -23,7 +23,7 @@ func TestRoomDispatchesGenericTemplate(t *testing.T) { t.Cleanup(func() { s.Close() }) if err := s.PutGenericTemplate(repo.GenericTemplate{Workflow: domain.WorkflowDefinition{ ID: "room-generic", Name: "通用确认", Version: 1, Status: "published", Generic: true, - SandboxProfileID: "local", + SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "人工确认", Type: "approval", MaxAttempts: 1}}, }}); err != nil { t.Fatal(err) @@ -57,14 +57,14 @@ func TestRoomCreatesIssueAndDispatchesSOP(t *testing.T) { t.Cleanup(func() { s.Close() }) if err := s.PutWorkflow(domain.WorkflowDefinition{ ID: "room-sop", Name: "群聊交付", Version: 1, ProjectID: "platform", Status: "published", - SandboxProfileID: "local", + SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "人工确认", Type: "approval", MaxAttempts: 1}}, }); err != nil { t.Fatal(err) } if err := s.PutWorkflow(domain.WorkflowDefinition{ ID: "room-sop-2", Name: "群聊评审", Version: 1, ProjectID: "platform", Status: "published", - SandboxProfileID: "local", + SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "review", Name: "人工评审", Type: "approval", MaxAttempts: 1}}, }); err != nil { t.Fatal(err) diff --git a/internal/httpapi/run_eval_cases_test.go b/internal/httpapi/run_eval_cases_test.go index 9f4540924..1bfa0d378 100644 --- a/internal/httpapi/run_eval_cases_test.go +++ b/internal/httpapi/run_eval_cases_test.go @@ -34,7 +34,7 @@ func TestRunEvalCloneAndApplyBranches(t *testing.T) { if _, err := h.ensureProjectAgent(run, "cvb-eval-p", "missing"); err == nil { t.Fatal("missing agent accepted") } - if err := f.s.PutWorkflow(domain.WorkflowDefinition{ID: "cvb-shared-wf", Name: "Shared", ProjectID: "elsewhere", Shared: true, SandboxProfileID: "local", Nodes: run.WorkflowSnapshot.Nodes}); err != nil { + if err := f.s.PutWorkflow(domain.WorkflowDefinition{ID: "cvb-shared-wf", Name: "Shared", ProjectID: "elsewhere", Shared: true, SandboxProfileID: "test-native", Nodes: run.WorkflowSnapshot.Nodes}); err != nil { t.Fatal(err) } if err := f.s.PutAgent(domain.AgentDefinition{ID: "cvb-eval-agent", Name: "Shared agent", ProjectID: "elsewhere", Shared: true, Version: 2}); err != nil { @@ -215,7 +215,7 @@ func TestRunEvalLocalEntityReuseBranches(t *testing.T) { if err := f.s.PutProject(domain.Project{ID: projectID, Key: "EVL", Name: "Eval local", OwnerID: f.user.ID}); err != nil { t.Fatal(err) } - wf := domain.WorkflowDefinition{ID: "cvb-eval-local-wf", Name: "Local workflow", ProjectID: projectID, SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "n", AgentID: "cvb-eval-local-agent"}}} + wf := domain.WorkflowDefinition{ID: "cvb-eval-local-wf", Name: "Local workflow", ProjectID: projectID, SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "n", AgentID: "cvb-eval-local-agent"}}} agent := domain.AgentDefinition{ID: "cvb-eval-local-agent", Name: "Local", ProjectID: projectID} if err := f.s.PutWorkflow(wf); err != nil { t.Fatal(err) diff --git a/internal/httpapi/run_eval_test.go b/internal/httpapi/run_eval_test.go index 305565756..8eea54f5f 100644 --- a/internal/httpapi/run_eval_test.go +++ b/internal/httpapi/run_eval_test.go @@ -42,7 +42,7 @@ func TestRunEvalRequiresTerminalRunAndUserKey(t *testing.T) { func TestRunEvalScoresAndAppliesNodePatch(t *testing.T) { t.Setenv("AGENTFLOW_SESSION_SECRET", "run-eval-session-secret") h, store, user := newRunEvalHarness(t) - if err := store.PutWorkflow(domain.WorkflowDefinition{ID: "wf-eval", Name: "评测SOP", Version: 1, SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "fix", Name: "修复", Type: "agent", AgentID: "fixer", MaxAttempts: 1}}}); err != nil { + if err := store.PutWorkflow(domain.WorkflowDefinition{ID: "wf-eval", Name: "评测SOP", Version: 1, SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "fix", Name: "修复", Type: "agent", AgentID: "fixer", MaxAttempts: 1}}}); err != nil { t.Fatal(err) } if err := store.PutAgent(domain.AgentDefinition{ID: "fixer", Name: "修复者", ProjectID: "platform", Prompt: "修 bug"}); err != nil { diff --git a/internal/httpapi/run_wait_test.go b/internal/httpapi/run_wait_test.go index 799d73cee..d8876ef32 100644 --- a/internal/httpapi/run_wait_test.go +++ b/internal/httpapi/run_wait_test.go @@ -12,6 +12,7 @@ import ( "agentflow/internal/domain" "agentflow/internal/engine" + "agentflow/internal/repo" "agentflow/internal/runtime" ) @@ -86,7 +87,7 @@ func TestWaitRunUsesFrozenWorkflowProjectWhenStartOmitsProject(t *testing.T) { wf := domain.WorkflowDefinition{ ID: "wait-manual-start", Name: "Wait for manual SOP", ProjectID: "workbench", - SandboxProfileID: "local", + SandboxProfileID: repo.TestNativeSandboxID, Nodes: []domain.WorkflowNode{{ID: "review", Name: "Review", Type: "approval", MaxAttempts: 1}}, } if err := h.repo.PutWorkflow(wf); err != nil { diff --git a/internal/httpapi/run_workspace_terminal_test.go b/internal/httpapi/run_workspace_terminal_test.go index 00c70241c..583a8d7ae 100644 --- a/internal/httpapi/run_workspace_terminal_test.go +++ b/internal/httpapi/run_workspace_terminal_test.go @@ -3,6 +3,7 @@ package httpapi import ( "agentflow/internal/domain" "agentflow/internal/engine" + "agentflow/internal/repo" "agentflow/internal/runtime" "bytes" "context" @@ -21,6 +22,7 @@ func TestWorkspaceTerminalRequiresProjectMembership(t *testing.T) { h.engine = engine.New(h.repo, runtime.NewManager(root)) r, _ := h.repo.RunState("shared-run") r.PauseRequested = true + r.WorkflowSnapshot.SandboxProfileID = repo.TestNativeSandboxID if err := h.repo.PutRun(r); err != nil { t.Fatal(err) } diff --git a/internal/httpapi/schedule.go b/internal/httpapi/schedule.go index 16f31489e..63aa8822f 100644 --- a/internal/httpapi/schedule.go +++ b/internal/httpapi/schedule.go @@ -656,11 +656,11 @@ func (h *scheduleHandlers) ensureBaselineAlignWorkflow(_ domain.ScheduleJob) boo return false } if wf, ok := h.repo.Workflow(engine.BaselineAlignWorkflowID); ok { - if wf.Version >= baselineAlignWorkflowVersion && alignWorkflowUsesPlatformAgent(wf) { + if wf.Version >= baselineAlignWorkflowVersion && alignWorkflowUsesPlatformAgent(wf) && wf.SandboxProfileID == repo.DefaultSandboxProfileID { return true } } - if _, ok := h.repo.Sandbox("local"); !ok { + if _, ok := h.repo.Sandbox(repo.DefaultSandboxProfileID); !ok { return false } now := time.Now().UTC() @@ -671,7 +671,7 @@ func (h *scheduleHandlers) ensureBaselineAlignWorkflow(_ domain.ScheduleJob) boo Version: baselineAlignWorkflowVersion, Status: "published", Description: "定时任务开工前把默认分支合入集成分支。全平台共用对齐角色实际执行 merge,平台校验后自动合入基线,无需人工确认。", - SandboxProfileID: "local", + SandboxProfileID: repo.DefaultSandboxProfileID, Nodes: []domain.WorkflowNode{ {ID: "resolve", Name: "解决冲突", Type: "agent", AgentID: engine.BaselineAlignAgentID, MaxAttempts: 2, MaxReworks: 2, RejectTo: "resolve", Position: domain.Position{X: 80, Y: 80}}, { diff --git a/internal/httpapi/schedule_projects_cases_test.go b/internal/httpapi/schedule_projects_cases_test.go index d4eb4c4d7..8b18bf616 100644 --- a/internal/httpapi/schedule_projects_cases_test.go +++ b/internal/httpapi/schedule_projects_cases_test.go @@ -11,7 +11,7 @@ import ( func TestScheduleCRUDValidationBranches(t *testing.T) { f := cvBNewHTTPFixture(t) cvBGiveCodeBuddyKey(t, &f) - if err := f.s.PutWorkflow(domain.WorkflowDefinition{ID: "cvb-schedule-wf", Name: "Schedule", ProjectID: "platform", SandboxProfileID: "local", Version: 1}); err != nil { + if err := f.s.PutWorkflow(domain.WorkflowDefinition{ID: "cvb-schedule-wf", Name: "Schedule", ProjectID: "platform", SandboxProfileID: "test-native", Version: 1}); err != nil { t.Fatal(err) } cases := []struct { diff --git a/internal/httpapi/schedule_test.go b/internal/httpapi/schedule_test.go index cbbd58052..8b0e5a756 100644 --- a/internal/httpapi/schedule_test.go +++ b/internal/httpapi/schedule_test.go @@ -27,7 +27,7 @@ func TestScheduleJobCRUD(t *testing.T) { t.Fatal(err) } t.Cleanup(st.Close) - if err := st.PutWorkflow(domain.WorkflowDefinition{ID: "scheduled-wf", Name: "Scheduled", SandboxProfileID: "local"}); err != nil { + if err := st.PutWorkflow(domain.WorkflowDefinition{ID: "scheduled-wf", Name: "Scheduled", SandboxProfileID: "test-native"}); err != nil { t.Fatal(err) } h := New(st, engine.New(st, runtime.NewManager(filepath.Join(t.TempDir(), "workspaces"))), tracker.NewService(), "", "") @@ -212,7 +212,7 @@ func TestScheduledDispatchUsesIntegrationBranchAndManualDispatchDoesNot(t *testi if err := st.PutRepository(domain.Repository{ID: "repo", ProjectID: project.ID, Name: "Repo", Provider: "gongfeng", DefaultBranch: "master", IntegrateBranch: "agentflow/integration"}); err != nil { t.Fatal(err) } - wf := domain.WorkflowDefinition{ID: "scheduled-wf", Name: "Scheduled", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval"}}} + wf := domain.WorkflowDefinition{ID: "scheduled-wf", Name: "Scheduled", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval"}}} if err := st.PutWorkflow(wf); err != nil { t.Fatal(err) } @@ -276,8 +276,8 @@ func TestSingleSOPDispatchReplacesStaleBinding(t *testing.T) { if err := st.PutProject(project); err != nil { t.Fatal(err) } - bound := domain.WorkflowDefinition{ID: "issue-fix-production", Name: "生产闭环", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "approval", Type: "approval"}}} - started := domain.WorkflowDefinition{ID: "sop-sandbox", Name: "沙箱", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "approval", Type: "approval"}}} + bound := domain.WorkflowDefinition{ID: "issue-fix-production", Name: "生产闭环", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "approval", Type: "approval"}}} + started := domain.WorkflowDefinition{ID: "sop-sandbox", Name: "沙箱", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "approval", Type: "approval"}}} for _, wf := range []domain.WorkflowDefinition{bound, started} { if err := st.PutWorkflow(wf); err != nil { t.Fatal(err) @@ -374,7 +374,7 @@ func TestScheduledJobWaitsWhenIntegrateConflictsWithDefault(t *testing.T) { if err := st.PutRepository(domain.Repository{ID: "repo", ProjectID: project.ID, Name: "Repo", Provider: "gongfeng", DefaultBranch: "master", IntegrateBranch: "agentflow/integration", CloneURL: remote}); err != nil { t.Fatal(err) } - wf := domain.WorkflowDefinition{ID: "scheduled-wf", Name: "Scheduled", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval"}}} + wf := domain.WorkflowDefinition{ID: "scheduled-wf", Name: "Scheduled", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval"}}} if err := st.PutWorkflow(wf); err != nil { t.Fatal(err) } @@ -453,14 +453,14 @@ func TestEnsureBaselineAlignWorkflowUsesPlatformAgentNotProjectFixer(t *testing. t.Fatal(err) } if err := st.PutWorkflow(domain.WorkflowDefinition{ - ID: "issue-fix-production", Name: "Issue 修复", ProjectID: "skillhub", SandboxProfileID: "local", + ID: "issue-fix-production", Name: "Issue 修复", ProjectID: "skillhub", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "fix", Type: "agent", AgentID: "issue-fix-engineer", Name: "修复并提交"}}, }); err != nil { t.Fatal(err) } if err := st.PutWorkflow(domain.WorkflowDefinition{ ID: engine.BaselineAlignWorkflowID, Name: "对齐默认分支到基线", ProjectID: "skillhub", - Version: 3, Status: "published", SandboxProfileID: "local", + Version: 3, Status: "published", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "resolve", Type: "agent", AgentID: "issue-fix-engineer"}}, }); err != nil { t.Fatal(err) @@ -470,7 +470,7 @@ func TestEnsureBaselineAlignWorkflowUsesPlatformAgentNotProjectFixer(t *testing. t.Fatal("ensure should rewrite project fixer onto the platform align role") } wf, ok := st.Workflow(engine.BaselineAlignWorkflowID) - if !ok || wf.Version < baselineAlignWorkflowVersion || wf.SandboxProfileID != "local" { + if !ok || wf.Version < baselineAlignWorkflowVersion || wf.SandboxProfileID != repo.DefaultSandboxProfileID { t.Fatalf("upgraded workflow = %+v", wf) } if !alignWorkflowUsesPlatformAgent(wf) { @@ -490,7 +490,7 @@ func TestEnsureBaselineAlignWorkflowUpgradesExistingRevision(t *testing.T) { t.Cleanup(st.Close) if err := st.PutWorkflow(domain.WorkflowDefinition{ ID: engine.BaselineAlignWorkflowID, Name: "对齐默认分支到基线", ProjectID: "platform", - Version: 1, Status: "published", SandboxProfileID: "local", + Version: 1, Status: "published", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "resolve", Name: "解决冲突", Type: "agent", AgentID: "developer"}, {ID: "confirm", Name: "确认对齐", Type: "approval"}, @@ -621,8 +621,8 @@ func TestScheduleUIDemoServer(t *testing.T) { t.Fatal(err) } for _, wf := range []domain.WorkflowDefinition{ - {ID: "demodns-issue-fix", Name: "Issue 修复", ProjectID: "dp", Status: "published", SandboxProfileID: "local", Version: 1, Nodes: []domain.WorkflowNode{{ID: "work", Name: "处理", Type: "approval"}}}, - {ID: "demodns-feature-dev", Name: "功能开发", ProjectID: "dp", Status: "published", SandboxProfileID: "local", Version: 1, Nodes: []domain.WorkflowNode{{ID: "work", Name: "处理", Type: "approval"}}}, + {ID: "demodns-issue-fix", Name: "Issue 修复", ProjectID: "dp", Status: "published", SandboxProfileID: "test-native", Version: 1, Nodes: []domain.WorkflowNode{{ID: "work", Name: "处理", Type: "approval"}}}, + {ID: "demodns-feature-dev", Name: "功能开发", ProjectID: "dp", Status: "published", SandboxProfileID: "test-native", Version: 1, Nodes: []domain.WorkflowNode{{ID: "work", Name: "处理", Type: "approval"}}}, } { if err := st.PutWorkflow(wf); err != nil { t.Fatal(err) diff --git a/internal/httpapi/server.go b/internal/httpapi/server.go index f297f7080..d6966eb7f 100644 --- a/internal/httpapi/server.go +++ b/internal/httpapi/server.go @@ -482,12 +482,6 @@ func newWithNotifications(s *repo.Store, e *engine.Engine, syncSvc *tracker.Serv g.POST("/api/skillhub/install", api.skillhub.install) g.POST("/api/skillhub/update", api.skillhub.update) g.GET("/api/executors", api.catalog.executors) - g.GET("/api/dockerfiles", api.catalog.dockerfiles) - g.PUT("/api/dockerfiles", api.catalog.dockerfiles) - g.DELETE("/api/dockerfiles", api.catalog.dockerfiles) - g.GET("/api/environments", api.catalog.environments) - g.PUT("/api/environments", api.catalog.environments) - g.DELETE("/api/environments", api.catalog.environments) g.GET("/api/sandboxes", api.catalog.sandboxes) g.PUT("/api/sandboxes", api.catalog.sandboxes) g.DELETE("/api/sandboxes", api.catalog.sandboxes) @@ -743,15 +737,13 @@ func (s *Server) bootstrap(c *gin.Context) { var skills []domain.SkillDefinition var mcpServers []domain.MCPServerDefinition var executors []domain.ExecutorDefinition - var dockerfiles []domain.DockerfileDefinition - var environments []domain.EnvironmentDefinition var sandboxes []domain.SandboxProfile var workflows []domain.WorkflowDefinition var syncConfig domain.SyncConfig var scheduleJobs []domain.ScheduleJob var users []domain.User var load stdsync.WaitGroup - load.Add(14) + load.Add(12) go func() { defer load.Done(); projects = s.repo.Projects() }() go func() { defer load.Done(); repositories = s.repo.Repositories() }() go func() { defer load.Done(); agents = s.repo.Agents() }() @@ -759,8 +751,6 @@ func (s *Server) bootstrap(c *gin.Context) { go func() { defer load.Done(); skills = s.repo.Skills() }() go func() { defer load.Done(); mcpServers = s.repo.MCPServers() }() go func() { defer load.Done(); executors = repo.BuiltInExecutors() }() - go func() { defer load.Done(); dockerfiles = s.repo.Dockerfiles() }() - go func() { defer load.Done(); environments = s.repo.Environments() }() go func() { defer load.Done(); sandboxes = s.repo.Sandboxes() }() go func() { defer load.Done(); workflows = s.repo.Workflows() }() go func() { defer load.Done(); syncConfig = s.repo.SyncConfig() }() @@ -795,7 +785,7 @@ func (s *Server) bootstrap(c *gin.Context) { c.JSON(200, map[string]any{ "businessDomains": businessDomains, "projects": domain.PublicProjects(projects), "repositories": domain.PublicRepositories(repositories), "agents": catalogAgents(agents), "rules": rules, "skills": skills, "mcpServers": mcpServers, - "executors": executors, "dockerfiles": dockerfiles, "environments": environments, "sandboxes": sandboxes, + "executors": executors, "sandboxes": sandboxes, "workflows": workflows, "syncConfig": syncConfig, "scheduleJobs": scheduleJobs, "schedulerEnabled": schedulerEnabled(), "users": domain.PublicUsers(users), "storage": s.repo.StorageInfo(), diff --git a/internal/httpapi/spaces_test.go b/internal/httpapi/spaces_test.go index f04549d16..29f2fe8be 100644 --- a/internal/httpapi/spaces_test.go +++ b/internal/httpapi/spaces_test.go @@ -31,7 +31,7 @@ func TestConversationLifecycle(t *testing.T) { } t.Cleanup(func() { s.Close() }) if err := s.PutWorkflow(domain.WorkflowDefinition{ - ID: "space-fe", Name: "前端研发", Version: 1, ProjectID: "platform", Status: "published", SandboxProfileID: "local", + ID: "space-fe", Name: "前端研发", Version: 1, ProjectID: "platform", Status: "published", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "review", Name: "方案评审", Type: "approval", MaxAttempts: 1}}, }); err != nil { t.Fatal(err) @@ -185,7 +185,7 @@ func TestConversationLifecycle(t *testing.T) { ID string `json:"id"` } `json:"workflow"` }](t, h, owner, http.MethodPost, base+"/flows", map[string]any{ - "name": "联调 SOP", "sandboxProfileId": "local", + "name": "联调 SOP", "sandboxProfileId": "test-native", "nodes": []map[string]any{{"id": "dev", "name": "开发", "type": "agent", "agentId": "developer"}, {"id": "check", "name": "验收", "type": "approval"}}, "edges": []map[string]any{{"source": "dev", "target": "check"}, {"source": "check", "target": "dev", "when": "rework"}}, }, http.StatusOK) @@ -227,7 +227,7 @@ func TestConversationRequirementIsExplicit(t *testing.T) { } t.Cleanup(func() { s.Close() }) if err := s.PutWorkflow(domain.WorkflowDefinition{ - ID: "space-be", Name: "后端研发", Version: 1, ProjectID: "platform", Status: "published", SandboxProfileID: "local", + ID: "space-be", Name: "后端研发", Version: 1, ProjectID: "platform", Status: "published", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "review", Name: "方案评审", Type: "approval", MaxAttempts: 1}}, }); err != nil { t.Fatal(err) diff --git a/internal/httpapi/stream_test.go b/internal/httpapi/stream_test.go index 9130a0b81..226dcb792 100644 --- a/internal/httpapi/stream_test.go +++ b/internal/httpapi/stream_test.go @@ -25,7 +25,7 @@ func TestRunStreamDeliversLiveSnapshots(t *testing.T) { t.Fatal(err) } t.Cleanup(func() { s.Close() }) - wf := domain.WorkflowDefinition{ID: "live", Name: "Live", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "work", Name: "Work", Type: "command", Command: "printf live", MaxAttempts: 1}}} + wf := domain.WorkflowDefinition{ID: "live", Name: "Live", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "work", Name: "Work", Type: "command", Command: "printf live", MaxAttempts: 1}}} if err := s.PutWorkflow(wf); err != nil { t.Fatal(err) } @@ -85,7 +85,7 @@ func TestDeleteRunEndpoint(t *testing.T) { t.Fatal(err) } t.Cleanup(st.Close) - if err := st.PutWorkflow(domain.WorkflowDefinition{ID: "wf", Name: "WF", SandboxProfileID: "local"}); err != nil { + if err := st.PutWorkflow(domain.WorkflowDefinition{ID: "wf", Name: "WF", SandboxProfileID: "test-native"}); err != nil { t.Fatal(err) } h := New(st, engine.New(st, runtime.NewManager(filepath.Join(t.TempDir(), "workspaces"))), tracker.NewService(), "", "") diff --git a/internal/httpapi/workspace_preparation_test.go b/internal/httpapi/workspace_preparation_test.go index 605efbe5d..a57ffa370 100644 --- a/internal/httpapi/workspace_preparation_test.go +++ b/internal/httpapi/workspace_preparation_test.go @@ -33,7 +33,7 @@ func TestWorkspacePreparationAPISeparatesReadersAndWriters(t *testing.T) { h := &runsHandlers{deps: a.deps} run, _ := a.repo.RunState("shared-run") run.Status = "succeeded" - run.WorkflowSnapshot.SandboxProfileID = "local" + run.WorkflowSnapshot.SandboxProfileID = "test-native" run.WorkflowSnapshot.Nodes = []domain.WorkflowNode{{ID: "prep", Name: "运行环境准备", Type: "script", Script: "mkdir -p .agentflow; printf secret-internal-output; printf ready > .agentflow/prepared", RunOnWorkspaceRebuild: true}} run.Nodes = map[string]*domain.NodeRun{"prep": {NodeID: "prep", Status: "succeeded", Attempt: 7, Output: "business history"}} if err := a.repo.PutRun(run); err != nil { diff --git a/internal/httpapi/workspace_restore_test.go b/internal/httpapi/workspace_restore_test.go index 3d3ea104b..6170a06ae 100644 --- a/internal/httpapi/workspace_restore_test.go +++ b/internal/httpapi/workspace_restore_test.go @@ -27,7 +27,7 @@ func TestRetryAsyncRestoreSurvivesDisconnectAndReusesBackgroundOperation(t *test run, _ := a.repo.RunState("shared-run") run.Status = "failed" run.WorkflowSnapshot.Nodes = []domain.WorkflowNode{{ID: "work", Type: "script", Script: "true", MaxAttempts: 1}} - run.WorkflowSnapshot.SandboxProfileID = "local" + run.WorkflowSnapshot.SandboxProfileID = "test-native" run.Nodes = map[string]*domain.NodeRun{"work": {NodeID: "work", Status: "failed", Attempt: 1}} run.ExecutionContext.ExecutionMode, run.ExecutionContext.ExecutionRunnerID = domain.ExecutionModeRunner, "restore-runner" if err := a.repo.PutRun(run); err != nil { diff --git a/internal/repo/assistant_preferences.go b/internal/repo/assistant_preferences.go index 7fbd3d24b..05566ea5f 100644 --- a/internal/repo/assistant_preferences.go +++ b/internal/repo/assistant_preferences.go @@ -23,6 +23,7 @@ func (r *AssistantRepo) AssistantPreferences(userID int64) domain.AssistantPrefe out.ProactiveRoles = row.ProactiveRoles out.ProactiveSOPs = row.ProactiveSOPs out.SteerOnSend = row.SteerOnSend + out.WorkspaceDriver = row.WorkspaceDriver out.Instructions = row.Instructions out.ApprovalReviewMode = strings.TrimSpace(row.ApprovalReviewMode) out.ApprovalReviewModel = strings.TrimSpace(row.ApprovalReviewModel) @@ -73,6 +74,7 @@ func (r *AssistantRepo) PutAssistantPreferences(userID int64, p domain.Assistant ProactiveRoles: p.ProactiveRoles, ProactiveSOPs: p.ProactiveSOPs, SteerOnSend: p.SteerOnSend, + WorkspaceDriver: strings.TrimSpace(p.WorkspaceDriver), Instructions: strings.TrimSpace(p.Instructions), ApprovalReviewMode: p.EffectiveApprovalReviewMode(), ApprovalReviewModel: strings.TrimSpace(p.ApprovalReviewModel), diff --git a/internal/repo/assistant_preferences_test.go b/internal/repo/assistant_preferences_test.go index 9065a7812..ef2c27500 100644 --- a/internal/repo/assistant_preferences_test.go +++ b/internal/repo/assistant_preferences_test.go @@ -48,3 +48,22 @@ func TestAssistantMessageSendPreference(t *testing.T) { }) } } + +func TestAssistantWorkspaceDriverPreference(t *testing.T) { + st, err := OpenTest() + if err != nil { + t.Fatal(err) + } + t.Cleanup(st.Close) + const userID = int64(801042) + if got := st.AssistantPreferences(userID).WorkspaceDriver; got != "" { + t.Fatalf("the agent should choose by default, got %q", got) + } + saved, err := st.PutAssistantPreferences(userID, domain.AssistantPreferences{WorkspaceDriver: " native ", SteerOnSend: true}) + if err != nil { + t.Fatal(err) + } + if saved.WorkspaceDriver != "native" || !saved.SteerOnSend || st.AssistantPreferences(userID+1).WorkspaceDriver != "" { + t.Fatalf("saved preferences: %+v", saved) + } +} diff --git a/internal/repo/catalog.go b/internal/repo/catalog.go index f337fa6e5..ecc083413 100644 --- a/internal/repo/catalog.go +++ b/internal/repo/catalog.go @@ -264,57 +264,7 @@ func BuiltInExecutorForKind(kind string) (domain.ExecutorDefinition, bool) { return domain.ExecutorDefinition{}, false } -// ---------- Dockerfiles / Environments / Sandboxes ---------- - -func (r *CatalogRepo) Dockerfiles() []domain.DockerfileDefinition { - return payloadList[domain.DockerfileDefinition](r.DB, "dockerfiles", "") -} - -func (r *CatalogRepo) Dockerfile(id string) (domain.DockerfileDefinition, bool) { - return payloadOne[domain.DockerfileDefinition](r.DB, "dockerfiles", id) -} - -func (r *CatalogRepo) PutDockerfile(v domain.DockerfileDefinition) error { - if err := domain.ValidateDockerfile(v); err != nil { - return err - } - v.UpdatedAt = time.Now().UTC() - return upsert(r.DB, "dockerfiles", map[string]any{ - "id": v.ID, "name": v.Name, "payload": mustJSON(v), "updated_at": timePtr(v.UpdatedAt), - }) -} - -func (r *CatalogRepo) DeleteDockerfile(id string) error { - if _, ok := r.Dockerfile(id); !ok { - return fmt.Errorf("dockerfile not found") - } - return r.DB.Table("dockerfiles").Where("id = ?", id).Delete(nil).Error -} - -func (r *CatalogRepo) Environments() []domain.EnvironmentDefinition { - return payloadList[domain.EnvironmentDefinition](r.DB, "environments", "") -} - -func (r *CatalogRepo) Environment(id string) (domain.EnvironmentDefinition, bool) { - return payloadOne[domain.EnvironmentDefinition](r.DB, "environments", id) -} - -func (r *CatalogRepo) PutEnvironment(v domain.EnvironmentDefinition) error { - if err := domain.ValidateEnvironment(v); err != nil { - return err - } - v.UpdatedAt = time.Now().UTC() - return upsert(r.DB, "environments", map[string]any{ - "id": v.ID, "name": v.Name, "payload": mustJSON(v), "updated_at": timePtr(v.UpdatedAt), - }) -} - -func (r *CatalogRepo) DeleteEnvironment(id string) error { - if _, ok := r.Environment(id); !ok { - return fmt.Errorf("environment not found") - } - return r.DB.Table("environments").Where("id = ?", id).Delete(nil).Error -} +// ---------- Sandboxes ---------- func (r *CatalogRepo) Sandboxes() []domain.SandboxProfile { profiles := payloadList[domain.SandboxProfile](r.DB, "sandboxes", "") @@ -339,7 +289,7 @@ func (r *CatalogRepo) Sandbox(id string) (domain.SandboxProfile, bool) { // A missing row may use the built-in default. Database failures or invalid // stored configuration must not silently switch a run's execution policy. if errors.Is(err, gorm.ErrRecordNotFound) && id == DefaultSandboxProfileID { - return DefaultSandboxProfile(), true + return GenericDockerSandbox(), true } if err != nil || json.Unmarshal(row.Payload, &profile) != nil { return domain.SandboxProfile{}, false @@ -349,11 +299,15 @@ func (r *CatalogRepo) Sandbox(id string) (domain.SandboxProfile, bool) { // platformSandboxProfile keeps the built-in generic Docker sandbox shared: // conversation workspaces fall back to it, and rows seeded before it carried -// the shared flag would otherwise hide it from every project. +// the shared flag would otherwise hide it from every project. A row still +// marked local reads as native, never as the runtime's unisolated driver. func platformSandboxProfile(profile domain.SandboxProfile) domain.SandboxProfile { if profile.ID == GenericDockerSandboxID { profile.Shared = true } + if strings.TrimSpace(profile.Driver) == domain.SandboxDriverLocal { + profile = normalizeSandboxProfile(profile) + } return profile } @@ -364,24 +318,12 @@ func (r *CatalogRepo) PutSandbox(v domain.SandboxProfile) error { if err := domain.ValidateEnvironmentVariables(v.Environment); err != nil { return fmt.Errorf("sandbox environment: %w", err) } - switch strings.TrimSpace(v.Driver) { - case "local", "native", "seatbelt", "bwrap", "docker": - default: - return fmt.Errorf("unsupported sandbox driver %q", v.Driver) + if strings.TrimSpace(v.Driver) == domain.SandboxDriverLocal { + return errors.New("local 沙箱已移除,请改用 native 沙箱") } stored := normalizeSandboxProfile(v) - if stored.Driver == "docker" && stored.DockerfileID == "" { - return errors.New("docker sandbox requires a dockerfileId") - } - if stored.DockerfileID != "" { - if _, ok := r.Dockerfile(stored.DockerfileID); !ok { - return fmt.Errorf("dockerfile %q not found", stored.DockerfileID) - } - } - if stored.EnvironmentID != "" { - if _, ok := r.Environment(stored.EnvironmentID); !ok { - return fmt.Errorf("environment %q not found", stored.EnvironmentID) - } + if err := domain.ValidateSandboxAssets(stored); err != nil { + return err } return upsert(r.DB, "sandboxes", map[string]any{ "id": stored.ID, "name": stored.Name, "payload": mustJSON(stored), @@ -514,9 +456,6 @@ func (r *CatalogRepo) putWorkflow(v domain.WorkflowDefinition, publishing bool) return err } v = normalizeWorkflowDefinition(v) - if strings.TrimSpace(v.SandboxProfileID) == "" { - v.SandboxProfileID = "local" - } if _, ok := r.Sandbox(v.SandboxProfileID); !ok { return fmt.Errorf("sandbox profile %q not found", v.SandboxProfileID) } @@ -926,27 +865,27 @@ func ProjectIssueWorkflowID(projectID string) string { return projectID + "-issue-fix" } +// normalizeSandboxProfile keeps only what a driver uses; the removed local +// driver becomes native. func normalizeSandboxProfile(profile domain.SandboxProfile) domain.SandboxProfile { profile.Driver = strings.TrimSpace(profile.Driver) - profile.DockerfileID = strings.TrimSpace(profile.DockerfileID) - profile.EnvironmentID = strings.TrimSpace(profile.EnvironmentID) + profile.DockerfileID = "" + // Each driver keeps only its own recipe, so switching drivers drops the + // other one instead of failing the save. + if profile.Driver != domain.SandboxDriverDocker { + profile.Dockerfile = nil + } switch profile.Driver { - case "local": - profile.DockerfileID = "" - profile.ReadOnlyRootFS = false - case "native", "seatbelt", "bwrap": + case domain.SandboxDriverLocal, domain.SandboxDriverNative, domain.SandboxDriverSeatbelt, domain.SandboxDriverBwrap: profile.Driver = domain.SandboxDriverNative - profile.DockerfileID = "" profile.ReadOnlyRootFS = false - case "docker": - profile.EnvironmentID = "" } return profile } func normalizeWorkflowDefinition(workflow domain.WorkflowDefinition) domain.WorkflowDefinition { if strings.TrimSpace(workflow.SandboxProfileID) == "" { - workflow.SandboxProfileID = "local" + workflow.SandboxProfileID = DefaultSandboxProfileID } for index := range workflow.Nodes { node := &workflow.Nodes[index] diff --git a/internal/repo/conversation_sandbox.go b/internal/repo/conversation_sandbox.go index 4fc326331..4a9d068bc 100644 --- a/internal/repo/conversation_sandbox.go +++ b/internal/repo/conversation_sandbox.go @@ -22,11 +22,8 @@ func (r *CatalogRepo) ConversationSandbox(projectID, id string) (domain.SandboxP } switch profile.Driver { case domain.SandboxDriverDocker: - if profile.DockerfileID == "" { - return domain.SandboxProfile{}, fmt.Errorf("Docker 沙箱需要配置 Dockerfile") - } - if _, ok := r.Dockerfile(profile.DockerfileID); !ok { - return domain.SandboxProfile{}, fmt.Errorf("沙箱的 Dockerfile 不存在,请联系项目 Owner 更新运行环境") + if profile.Dockerfile == nil || strings.TrimSpace(profile.Dockerfile.Content) == "" { + return domain.SandboxProfile{}, fmt.Errorf("Docker 沙箱 %s 没有 Dockerfile,请联系项目 Owner 更新沙箱配置", profile.ID) } case domain.SandboxDriverNative, domain.SandboxDriverSeatbelt, domain.SandboxDriverBwrap: default: diff --git a/internal/repo/generic_docker.go b/internal/repo/generic_docker.go index 0b57b52eb..c5fa146b7 100644 --- a/internal/repo/generic_docker.go +++ b/internal/repo/generic_docker.go @@ -74,27 +74,14 @@ WORKDIR /workspace CMD ["sh", "-lc", "trap : TERM INT; sleep infinity & wait"] ` -// GenericBackendDockerfile is the catalog row for the platform default image. -func GenericBackendDockerfile() domain.DockerfileDefinition { - return domain.DockerfileDefinition{ - ID: GenericBackendDockerfileID, - Name: "通用后端运行镜像", - ProjectID: "platform", - Shared: true, - Description: "通用后端交付 SOP 的默认镜像:git、Node agent CLI 与 Go 工具链。", - Content: genericBackendDockerfileContent, - UpdatedAt: genericDockerEpoch, - } -} - // GenericDockerSandbox is the shared docker profile bound by the generic SOP. func GenericDockerSandbox() domain.SandboxProfile { return domain.SandboxProfile{ - ID: GenericDockerSandboxID, - Name: "通用后端容器沙箱", - ProjectID: "platform", - Shared: true, - Driver: "docker", - DockerfileID: GenericBackendDockerfileID, + ID: GenericDockerSandboxID, + Name: "通用后端容器沙箱", + ProjectID: "platform", + Shared: true, + Driver: "docker", + Dockerfile: &domain.SandboxDockerfile{Content: genericBackendDockerfileContent}, } } diff --git a/internal/repo/generic_workflows.go b/internal/repo/generic_workflows.go index f2236283f..225422f41 100644 --- a/internal/repo/generic_workflows.go +++ b/internal/repo/generic_workflows.go @@ -6,14 +6,10 @@ import "agentflow/internal/domain" // backend delivery SOP stored in generic_templates. const GenericBackendDeliveryWorkflowID = "generic-backend-delivery" -// Platform docker assets the generic backend SOP binds to. They are catalog -// rows (not part of the template blob), seeded by -// migrations/seed/111_generic_docker.sql so new projects run in a container -// instead of the host-local driver. -const ( - GenericBackendDockerfileID = "generic-backend" - GenericDockerSandboxID = "generic-docker" -) +// GenericDockerSandboxID is the platform docker sandbox the generic backend +// SOP binds to. It is a catalog row (not part of the template blob), seeded +// by migrations/seed/001_public_catalog.sql. +const GenericDockerSandboxID = "generic-docker" // Role identifiers used by the stored LoopForge backend template. Cloning a // generic template copies these roles into the target project. diff --git a/internal/repo/issues_test.go b/internal/repo/issues_test.go index 72b6c8311..3a49cc319 100644 --- a/internal/repo/issues_test.go +++ b/internal/repo/issues_test.go @@ -111,7 +111,7 @@ func TestPutIssueUsesProjectDefaultRequirementWorkflow(t *testing.T) { if err := s.PutProject(domain.Project{ID: "gslb", Key: "GSLB", Name: "GSLB"}); err != nil { t.Fatal(err) } - if err := s.PutWorkflow(domain.WorkflowDefinition{ID: "gslb-issue-fix", Name: "GSLB Issue", SandboxProfileID: "local"}); err != nil { + if err := s.PutWorkflow(domain.WorkflowDefinition{ID: "gslb-issue-fix", Name: "GSLB Issue", SandboxProfileID: "test-native"}); err != nil { t.Fatal(err) } if err := s.PutIssue(domain.Issue{ID: "bug-gslb", ProjectID: "gslb", Source: "gongfeng", Title: "bug"}); err != nil { @@ -165,7 +165,7 @@ func TestPutIssueBindsGenericProjectDefaultForAllIssues(t *testing.T) { t.Fatalf("gongfeng issue should use generic project default, got %+v", bug) } // 项目专属缺陷 SOP 仍然优先于项目通用默认。 - if err := s.PutWorkflow(domain.WorkflowDefinition{ID: "newproj-issue-fix", Name: "Newproj fix", SandboxProfileID: "local"}); err != nil { + if err := s.PutWorkflow(domain.WorkflowDefinition{ID: "newproj-issue-fix", Name: "Newproj fix", SandboxProfileID: "test-native"}); err != nil { t.Fatal(err) } if err := s.PutIssue(domain.Issue{ID: "bug-np-2", ProjectID: "newproj", Source: "gongfeng", Title: "bug 2"}); err != nil { diff --git a/internal/repo/models.go b/internal/repo/models.go index b41987c89..dac290dea 100644 --- a/internal/repo/models.go +++ b/internal/repo/models.go @@ -197,24 +197,6 @@ type executorRow struct { func (executorRow) TableName() string { return "executors" } -type dockerfileRow struct { - ID string `gorm:"column:id;primaryKey;size:64"` - Name string `gorm:"column:name;size:255"` - Payload []byte `gorm:"column:payload;type:json"` - Updated *time.Time `gorm:"column:updated_at"` -} - -func (dockerfileRow) TableName() string { return "dockerfiles" } - -type environmentRow struct { - ID string `gorm:"column:id;primaryKey;size:64"` - Name string `gorm:"column:name;size:255"` - Payload []byte `gorm:"column:payload;type:json"` - Updated *time.Time `gorm:"column:updated_at"` -} - -func (environmentRow) TableName() string { return "environments" } - type sandboxRow struct { ID string `gorm:"column:id;primaryKey;size:64"` Name string `gorm:"column:name;size:255"` @@ -592,12 +574,14 @@ type userRunnerPrefRow struct { func (userRunnerPrefRow) TableName() string { return "user_runner_prefs" } -// assistantPreferenceRow: a missing row means switches are off and messages queue. +// assistantPreferenceRow: a missing row means switches are off, messages queue +// and the agent picks conversation workspace sandboxes itself. type assistantPreferenceRow struct { UserID int64 `gorm:"column:user_id;primaryKey;autoIncrement:false"` ProactiveRoles bool `gorm:"column:proactive_roles;not null;default:false"` ProactiveSOPs bool `gorm:"column:proactive_sops;not null;default:false"` SteerOnSend bool `gorm:"column:steer_on_send;not null;default:false"` + WorkspaceDriver string `gorm:"column:workspace_driver;type:varchar(16);not null;default:''"` Instructions string `gorm:"column:instructions;type:text"` ApprovalReviewMode string `gorm:"column:approval_review_mode;size:32;not null;default:''"` ApprovalReviewModel string `gorm:"column:approval_review_model;size:160;not null;default:''"` @@ -766,7 +750,7 @@ func allModels() []any { insightSourceRow{}, insightExecutionRow{}, projectRow{}, projectMemberRow{}, repositoryRow{}, businessDomainRow{}, businessDomainAssignmentRow{}, agentRow{}, ruleRow{}, skillRow{}, skillFileRow{}, mcpServerRow{}, mcpFileRow{}, executorRow{}, - dockerfileRow{}, environmentRow{}, sandboxRow{}, + sandboxRow{}, workflowRow{}, syncConfigRow{}, scheduleJobRow{}, scheduleJobExecutionRow{}, scheduleJobExecutionStatRow{}, sharedScheduleVersionRow{}, issueRow{}, issueCommentRow{}, taskRow{}, runAdmissionLockRow{}, runRow{}, runNodeRow{}, runEventRow{}, runTelemetryRow{}, runLogRow{}, runArtifactRow{}, runEvalRow{}, diff --git a/internal/repo/opentest.go b/internal/repo/opentest.go index b80a2d22d..cc89f5907 100644 --- a/internal/repo/opentest.go +++ b/internal/repo/opentest.go @@ -8,6 +8,8 @@ package repo import ( "fmt" + "os" + goruntime "runtime" "sync/atomic" "time" @@ -18,6 +20,35 @@ import ( "gorm.io/gorm/logger" ) +// TestNativeSandboxID is the shared native sandbox every test store carries. +// It isolates commands like production does, so tests need bubblewrap on +// Linux and sandbox-exec on macOS. +const TestNativeSandboxID = "test-native" + +// UseSandboxVisibleTempDir points TMPDIR, and so t.TempDir, outside /tmp for +// the rest of the test binary. On Linux the native sandbox gives every +// command a private /tmp, which would hide workspaces and fixtures that tests +// create under the host /tmp. Call it from TestMain and run the returned +// cleanup after m.Run. +func UseSandboxVisibleTempDir() func() { + if goruntime.GOOS != "linux" { + return func() {} + } + base, err := os.UserCacheDir() + if err == nil { + err = os.MkdirAll(base, 0o700) + } + if err != nil { + panic(fmt.Sprintf("sandbox-visible temp dir: %v", err)) + } + dir, err := os.MkdirTemp(base, "agentflow-test-") + if err != nil { + panic(fmt.Sprintf("sandbox-visible temp dir: %v", err)) + } + os.Setenv("TMPDIR", dir) + return func() { os.RemoveAll(dir) } +} + // testStoreSeq gives every test store a unique named in-memory sqlite database. var testStoreSeq atomic.Uint64 @@ -66,7 +97,7 @@ func seedTestDefaults(s *Store) error { } executors := append(BuiltInExecutors(), domain.ExecutorDefinition{ID: "mock", Name: "演示执行器", Kind: "mock", Protocol: "events-v1"}) sandboxes := []domain.SandboxProfile{ - {ID: "local", Name: "本地开发沙箱", ProjectID: "platform", Shared: true, Driver: "local"}, + {ID: TestNativeSandboxID, Name: "测试轻量沙箱", ProjectID: "platform", Shared: true, Driver: domain.SandboxDriverNative}, {ID: "skillhub-native", Name: "Skillhub 轻量沙箱", ProjectID: "platform", Driver: "native"}, } for _, v := range []domain.RuleDefinition{ @@ -129,16 +160,10 @@ func seedTestDefaults(s *Store) error { }) } -// seedTestGenericDocker inserts the platform docker assets when missing so -// tests can bind the generic SOP to a container sandbox. +// seedTestGenericDocker stores the platform docker sandbox as a row, like the +// public catalog seed does, so tests can bind the generic SOP to a container +// sandbox and edit or corrupt the stored row. Lookups would report the +// built-in fallback, so the fresh store is written unconditionally. func seedTestGenericDocker(s *Store) error { - if _, ok := s.Dockerfile(GenericBackendDockerfileID); !ok { - if err := s.PutDockerfile(GenericBackendDockerfile()); err != nil { - return err - } - } - if _, ok := s.Sandbox(GenericDockerSandboxID); ok { - return nil - } return s.PutSandbox(GenericDockerSandbox()) } diff --git a/internal/repo/repo.go b/internal/repo/repo.go index d5f0b3b6c..443b77552 100644 --- a/internal/repo/repo.go +++ b/internal/repo/repo.go @@ -77,7 +77,7 @@ func (d *deps) locking(q *gorm.DB) *gorm.DB { } // CatalogRepo owns the reusable definitions: agents, rules, skills, MCP -// servers, executors, dockerfiles, environments, sandboxes, workflows, +// servers, executors, sandboxes (with their Dockerfile or install), workflows, // repositories, sync config, schedule jobs and definition revisions. type CatalogRepo struct { *deps diff --git a/internal/repo/requirement_test.go b/internal/repo/requirement_test.go index f72bb92f5..d5361f236 100644 --- a/internal/repo/requirement_test.go +++ b/internal/repo/requirement_test.go @@ -246,7 +246,7 @@ func TestRequirementSnapshotHTTPStore(t *testing.T) { t.Fatal(err) } t.Cleanup(func() { s.Close() }) - wf := domain.WorkflowDefinition{ID: "generic-frontend-delivery", Name: "前端交付", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "shape", Name: "造型"}}} + wf := domain.WorkflowDefinition{ID: "generic-frontend-delivery", Name: "前端交付", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "shape", Name: "造型"}}} if err := s.PutWorkflow(wf); err != nil { t.Fatal(err) } diff --git a/internal/repo/sandbox_defaults.go b/internal/repo/sandbox_defaults.go index 072caec13..1d7b54bbd 100644 --- a/internal/repo/sandbox_defaults.go +++ b/internal/repo/sandbox_defaults.go @@ -1,18 +1,6 @@ package repo -import "agentflow/internal/domain" - -const DefaultSandboxProfileID = "local" - -// DefaultSandboxProfile is available without catalog initialization. It is a -// read-only fallback, not a seed row. Operator-persisted profiles take priority. -// The runtime applies AGENTFLOW_LOCAL_SANDBOX=docker in Compose deployments; -// native installations retain their explicitly configured execution policy. -func DefaultSandboxProfile() domain.SandboxProfile { - return domain.SandboxProfile{ - ID: DefaultSandboxProfileID, - Name: "默认运行沙箱", - Shared: true, - Driver: domain.SandboxDriverLocal, - } -} +// DefaultSandboxProfileID is the sandbox a workflow without an explicit choice +// runs in. The built-in generic Docker profile and its Dockerfile are +// read-only fallbacks, not seed rows; operator-persisted rows take priority. +const DefaultSandboxProfileID = GenericDockerSandboxID diff --git a/internal/repo/sandbox_defaults_test.go b/internal/repo/sandbox_defaults_test.go index b5526556d..39241fcf8 100644 --- a/internal/repo/sandbox_defaults_test.go +++ b/internal/repo/sandbox_defaults_test.go @@ -18,7 +18,7 @@ func TestDefaultSandboxWithoutSeedDoesNotWriteRows(t *testing.T) { t.Fatal(err) } profile, ok := s.Sandbox(DefaultSandboxProfileID) - if !ok || profile.ID != "local" || profile.Driver != domain.SandboxDriverLocal || !profile.Shared || profile.ProjectID != "" { + if !ok || profile.ID != GenericDockerSandboxID || profile.Driver != domain.SandboxDriverDocker || !profile.Shared { t.Fatalf("missing shared default: %+v, found=%v", profile, ok) } profiles := s.Sandboxes() @@ -40,7 +40,7 @@ func TestStoredDefaultSandboxWinsWithoutDuplicatesAndCannotBeDeleted(t *testing. t.Fatal(err) } t.Cleanup(func() { s.Close() }) - configured := domain.SandboxProfile{ID: "local", Name: "Operator configured", ProjectID: "platform", Shared: true, Driver: "native", Environment: map[string]string{"PRESERVE": "yes"}} + configured := domain.SandboxProfile{ID: DefaultSandboxProfileID, Name: "Operator configured", ProjectID: "platform", Shared: true, Driver: "native", Environment: map[string]string{"PRESERVE": "yes"}} if err := s.PutSandbox(configured); err != nil { t.Fatal(err) } @@ -79,14 +79,14 @@ func TestDefaultSandboxDoesNotMaskCorruptConfigurationOrDatabaseFailure(t *testi t.Fatal(err) } if _, ok := s.Sandbox(DefaultSandboxProfileID); ok { - t.Fatal("invalid stored configuration must not fall back to local execution") + t.Fatal("invalid stored configuration must not fall back to the built-in default") } if err := s.DB.Exec("DELETE FROM sandboxes").Error; err != nil { t.Fatal(err) } s.Close() if _, ok := s.Sandbox(DefaultSandboxProfileID); ok { - t.Fatal("database failure must not fall back to local execution") + t.Fatal("database failure must not fall back to the built-in default") } if profiles := s.Sandboxes(); len(profiles) != 0 { t.Fatalf("database failure reported available sandboxes: %+v", profiles) @@ -101,7 +101,7 @@ func TestSeededGenericDockerSandboxIsSharedForConversations(t *testing.T) { t.Fatal(err) } t.Cleanup(func() { s.Close() }) - seeded := `{"id":"generic-docker","name":"Docker 隔离沙箱","driver":"docker","dockerfileId":"generic-backend","readOnlyRootFS":false}` + seeded := `{"id":"generic-docker","name":"Docker 隔离沙箱","driver":"docker","dockerfile":{"content":"FROM debian"},"readOnlyRootFS":false}` if err := s.DB.Table("sandboxes").Where("id = ?", GenericDockerSandboxID).Update("payload", seeded).Error; err != nil { t.Fatal(err) } @@ -121,9 +121,10 @@ func TestSeededGenericDockerSandboxIsSharedForConversations(t *testing.T) { } } -// Conversation workspaces run in Docker or in the execution machine's native -// lightweight sandbox; local (no isolation) is never offered. -func TestConversationSandboxAcceptsDockerAndNative(t *testing.T) { +// Conversation workspaces run in Docker, in the execution machine's native +// lightweight sandbox, or on the machine a local sandbox is bound to. A stored +// local row that lost its binding is refused instead of running unbound. +func TestConversationSandboxAcceptsDockerNativeAndBoundLocal(t *testing.T) { s, err := OpenTest() if err != nil { t.Fatal(err) @@ -132,14 +133,16 @@ func TestConversationSandboxAcceptsDockerAndNative(t *testing.T) { for _, profile := range []domain.SandboxProfile{ {ID: "cs-native", Name: "Native", ProjectID: "p", Driver: domain.SandboxDriverNative}, {ID: "cs-bwrap", Name: "Bwrap", ProjectID: "p", Driver: domain.SandboxDriverBwrap}, - {ID: "cs-local", Name: "Local", ProjectID: "p", Driver: domain.SandboxDriverLocal}, {ID: "cs-other", Name: "Other", ProjectID: "q", Driver: domain.SandboxDriverNative}, } { if err := s.PutSandbox(profile); err != nil { t.Fatal(err) } } - for id, ok := range map[string]bool{"cs-native": true, "cs-bwrap": true, GenericDockerSandboxID: true, "cs-local": false, "cs-other": false} { + if err := s.DB.Table("sandboxes").Create(map[string]any{"id": "cs-legacy", "name": "Legacy", "payload": `{"id":"cs-legacy","name":"Legacy","projectId":"p","driver":"local","runnerId":"runner-1"}`}).Error; err != nil { + t.Fatal(err) + } + for id, ok := range map[string]bool{"cs-native": true, "cs-bwrap": true, GenericDockerSandboxID: true, "cs-legacy": true, "cs-other": false} { if _, err := s.ConversationSandbox("p", id); (err == nil) != ok { t.Fatalf("ConversationSandbox(%s) err=%v, want ok=%v", id, err, ok) } @@ -148,7 +151,10 @@ func TestConversationSandboxAcceptsDockerAndNative(t *testing.T) { for _, profile := range s.ConversationSandboxes("p") { listed[profile.ID] = true } - if !listed["cs-native"] || listed["cs-local"] || listed["cs-other"] { + if !listed["cs-native"] || !listed["cs-legacy"] || listed["cs-other"] { t.Fatalf("conversation sandboxes = %v", listed) } + if legacy, ok := s.Sandbox("cs-legacy"); !ok || legacy.Driver != domain.SandboxDriverNative { + t.Fatalf("an unmigrated local sandbox reads as native: %+v", legacy) + } } diff --git a/internal/repo/shared_schedule_assets_test.go b/internal/repo/shared_schedule_assets_test.go index 51325772a..229cf7d10 100644 --- a/internal/repo/shared_schedule_assets_test.go +++ b/internal/repo/shared_schedule_assets_test.go @@ -190,17 +190,15 @@ func TestSharedScheduleDoesNotPinSOPDependencies(t *testing.T) { t.Fatal(err) } } - check(st.PutDockerfile(domain.DockerfileDefinition{ID: "image", Name: "Image", ProjectID: "source", Content: "FROM scratch"})) - check(st.PutEnvironment(domain.EnvironmentDefinition{ID: "setup", Name: "Setup", ProjectID: "source"})) - check(st.PutSandbox(domain.SandboxProfile{ID: "sandbox", Name: "Sandbox", ProjectID: "source", Driver: "docker", DockerfileID: "image", EnvironmentID: "setup"})) - check(st.PutSandbox(domain.SandboxProfile{ID: "native", Name: "Native", ProjectID: "source", Driver: "native", EnvironmentID: "setup"})) + check(st.PutSandbox(domain.SandboxProfile{ID: "sandbox", Name: "Sandbox", ProjectID: "source", Driver: "docker", Dockerfile: &domain.SandboxDockerfile{Content: "FROM scratch"}})) + check(st.PutSandbox(domain.SandboxProfile{ID: "native", Name: "Native", ProjectID: "source", Driver: "native", Environment: map[string]string{"MODE": "test"}})) check(st.PutWorkflow(domain.WorkflowDefinition{ID: "child", Name: "Child", ProjectID: "source", SandboxProfileID: "native", Nodes: []domain.WorkflowNode{{ID: "approve", Type: "approval", Name: "Approve"}}})) check(st.PutWorkflow(domain.WorkflowDefinition{ID: "parent", Name: "Parent", ProjectID: "source", Shared: true, SandboxProfileID: "sandbox", Nodes: []domain.WorkflowNode{{ID: "child", Type: "sop", SOPWorkflowID: "child", Name: "Child"}}})) job := domain.ScheduleJob{ID: "sop-task", Name: "SOP task", ProjectID: "source", SkipDispatch: true, AssistantPrompt: "start", References: []domain.AssistantReference{{Type: "sop", ID: "parent"}}} check(st.PutScheduleJob(job)) v, err := st.PublishSharedSchedule(job.ID, job.ProjectID, domain.SharedScheduleVersion{Name: "SOP task", Prompt: "start"}, 0) check(err) - if !v.HasAsset("sop", "parent") || v.HasAsset("sop", "child") || v.HasAsset("sandbox", "sandbox") || v.HasAsset("dockerfile", "image") || v.HasAsset("environment", "setup") { + if !v.HasAsset("sop", "parent") || v.HasAsset("sop", "child") || v.HasAsset("sandbox", "sandbox") || v.HasAsset("sandbox", "native") { t.Fatalf("version contains nested SOP dependencies: %+v", v.Assets) } profile, _ := st.Sandbox("sandbox") @@ -243,7 +241,7 @@ func TestSharedScheduleSOPPreservesTemplateFallbacksAndBuiltInPreview(t *testing t.Fatalf("publication stored nested template dependencies: %+v", v.Assets) } // The preview builder is an engine-generated role, not a catalog asset. - wf := domain.WorkflowDefinition{ID: "preview-sop", Name: "Preview", ProjectID: "source", Shared: true, SandboxProfileID: "local", Preview: &domain.PreviewContract{Enabled: true}, Nodes: []domain.WorkflowNode{{ID: "approve", Type: "approval", Name: "Approve"}}} + wf := domain.WorkflowDefinition{ID: "preview-sop", Name: "Preview", ProjectID: "source", Shared: true, SandboxProfileID: TestNativeSandboxID, Preview: &domain.PreviewContract{Enabled: true}, Nodes: []domain.WorkflowNode{{ID: "approve", Type: "approval", Name: "Approve"}}} wf, err = domain.AttachPreviewBuild(wf) check(err) check(st.PutWorkflow(wf)) diff --git a/internal/repo/store_test.go b/internal/repo/store_test.go index 94413acbf..b854cdab1 100644 --- a/internal/repo/store_test.go +++ b/internal/repo/store_test.go @@ -64,7 +64,7 @@ func TestPutWorkflowKeepsExistingProjectID(t *testing.T) { t.Fatal(err) } t.Cleanup(s.Close) - if err := s.PutWorkflow(domain.WorkflowDefinition{ID: "gslb-fix", Name: "Fix", ProjectID: "gslb", SandboxProfileID: "local"}); err != nil { + if err := s.PutWorkflow(domain.WorkflowDefinition{ID: "gslb-fix", Name: "Fix", ProjectID: "gslb", SandboxProfileID: "test-native"}); err != nil { t.Fatal(err) } stored, _ := s.Workflow("gslb-fix") @@ -85,7 +85,7 @@ func TestCommandNodeNormalizesToShellScript(t *testing.T) { t.Fatal(err) } defer s.Close() - wf := domain.WorkflowDefinition{ID: "legacy-command", Name: "Legacy", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "run", Name: "Run", Type: "command", Command: "printf ok"}}} + wf := domain.WorkflowDefinition{ID: "legacy-command", Name: "Legacy", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "run", Name: "Run", Type: "command", Command: "printf ok"}}} if err := s.PutWorkflow(wf); err != nil { t.Fatal(err) } @@ -114,8 +114,11 @@ func TestSeedPopulatesDefaultsForAnEmptyStore(t *testing.T) { t.Fatalf("defaults missing: executors=%d sandboxes=%d rules=%d agents=%d", len(s.Executors()), len(s.Sandboxes()), len(s.Rules()), len(s.Agents())) } - if _, ok := s.Sandbox("local"); !ok { - t.Fatal("expected seeded local sandbox") + if sandbox, ok := s.Sandbox(TestNativeSandboxID); !ok || sandbox.Driver != domain.SandboxDriverNative || !sandbox.Shared { + t.Fatalf("expected seeded shared native test sandbox, got %+v", sandbox) + } + if _, ok := s.Sandbox("local"); ok { + t.Fatal("an unbound local sandbox must not be seeded") } if sandbox, ok := s.Sandbox("skillhub-native"); !ok || sandbox.Driver != domain.SandboxDriverNative { t.Fatalf("expected seeded native skillhub sandbox, got %+v", sandbox) @@ -123,13 +126,9 @@ func TestSeedPopulatesDefaultsForAnEmptyStore(t *testing.T) { if _, ok := s.Sandbox("container"); ok { t.Fatal("legacy container sandbox must not be seeded") } - dockerfile, ok := s.Dockerfile(GenericBackendDockerfileID) - if !ok || strings.TrimSpace(dockerfile.Content) == "" || !dockerfile.Shared { - t.Fatalf("expected platform generic-backend dockerfile, got %+v ok=%v", dockerfile, ok) - } box, ok := s.Sandbox(GenericDockerSandboxID) - if !ok || box.Driver != "docker" || box.DockerfileID != GenericBackendDockerfileID || !box.Shared { - t.Fatalf("expected platform generic-docker sandbox, got %+v ok=%v", box, ok) + if !ok || box.Driver != "docker" || box.Dockerfile == nil || strings.TrimSpace(box.Dockerfile.Content) == "" || !box.Shared { + t.Fatalf("expected platform generic-docker sandbox with its Dockerfile, got %+v ok=%v", box, ok) } if len(s.Projects()) != 1 { t.Fatalf("expected exactly the default project, got %d", len(s.Projects())) @@ -137,12 +136,6 @@ func TestSeedPopulatesDefaultsForAnEmptyStore(t *testing.T) { if s.SyncConfig().GongfengMCPURL == "" { t.Fatal("default sync config was not seeded") } - if n := len(s.Environments()); n != 0 { - t.Fatalf("environments must come from the catalog, not code; seeded %d", n) - } - if n := len(s.Dockerfiles()); n != 1 { - t.Fatalf("only the platform generic-backend dockerfile is ensured, got %d", n) - } } // A rejected write must leave the reader's view untouched. If memory were diff --git a/internal/repo/views_cases_test.go b/internal/repo/views_cases_test.go index e026c8104..c87fe1087 100644 --- a/internal/repo/views_cases_test.go +++ b/internal/repo/views_cases_test.go @@ -265,19 +265,22 @@ func TestCatalogValidationDeletionAndBuiltins(t *testing.T) { if err := s.PutSandbox(domain.SandboxProfile{ID: "cve-sandbox", Name: "Sandbox", Driver: "docker"}); err == nil { t.Fatal("docker sandbox without Dockerfile accepted") } - if err := s.PutSandbox(domain.SandboxProfile{ID: "cve-sandbox", Name: "Sandbox", Driver: "docker", DockerfileID: "missing"}); err == nil { - t.Fatal("missing Dockerfile accepted") + if err := s.PutSandbox(domain.SandboxProfile{ID: "cve-sandbox", Name: "Sandbox", Driver: "docker", Dockerfile: &domain.SandboxDockerfile{Content: " "}}); err == nil { + t.Fatal("blank Dockerfile accepted") } - if err := s.PutSandbox(domain.SandboxProfile{ID: "cve-sandbox", Name: "Sandbox", Driver: "local", EnvironmentID: "missing"}); err == nil { - t.Fatal("missing environment accepted") + if err := s.PutSandbox(domain.SandboxProfile{ID: "cve-native-sandbox", Name: "Native", Driver: "native", Environment: map[string]string{"A=B": "x"}}); err == nil { + t.Fatal("invalid environment variable name accepted") } - if err := s.PutSandbox(domain.SandboxProfile{ID: "cve-local-sandbox", Name: "Local", Driver: "local"}); err != nil { + if err := s.PutSandbox(domain.SandboxProfile{ID: "cve-local-sandbox", Name: "Local", Driver: "local"}); err == nil { + t.Fatal("local sandbox accepted") + } + if err := s.PutSandbox(domain.SandboxProfile{ID: "cve-native-sandbox", Name: "Native", Driver: "native"}); err != nil { t.Fatal(err) } if err := s.DeleteSandbox("missing"); err == nil { t.Fatal("missing sandbox deleted") } - if err := s.DeleteSandbox("cve-local-sandbox"); err != nil { + if err := s.DeleteSandbox("cve-native-sandbox"); err != nil { t.Fatal(err) } diff --git a/internal/repo/workflow_publish_test.go b/internal/repo/workflow_publish_test.go index f4a44ad8e..7e10bdddb 100644 --- a/internal/repo/workflow_publish_test.go +++ b/internal/repo/workflow_publish_test.go @@ -21,7 +21,7 @@ func TestMySQLConcurrentWorkflowPublish(t *testing.T) { } t.Cleanup(func() { s.Close() }) prefix := "publish-" + strconv.FormatInt(time.Now().UnixNano(), 36) - if err := s.PutSandbox(domain.SandboxProfile{ID: prefix, Name: "Local test", Driver: "local"}); err != nil { + if err := s.PutSandbox(domain.SandboxProfile{ID: prefix, Name: "Native test", Driver: "native"}); err != nil { t.Fatal(err) } t.Cleanup(func() { s.DB.Table("sandboxes").Where("id = ?", prefix).Delete(nil) }) diff --git a/internal/repo/workflow_test.go b/internal/repo/workflow_test.go index b022f129e..8a9470b70 100644 --- a/internal/repo/workflow_test.go +++ b/internal/repo/workflow_test.go @@ -31,7 +31,7 @@ func TestWorkflowOptimisticRevisionPreventsLostUpdate(t *testing.T) { } } -func TestLegacyWorkflowReadsDefaultEmptySandboxProfileToLocal(t *testing.T) { +func TestLegacyWorkflowReadsDefaultEmptySandboxProfileToGenericDocker(t *testing.T) { s, err := OpenTest() if err != nil { t.Fatal(err) @@ -53,16 +53,16 @@ func TestLegacyWorkflowReadsDefaultEmptySandboxProfileToLocal(t *testing.T) { if !ok { t.Fatal("legacy workflow not found") } - if workflow.SandboxProfileID != "local" { - t.Fatalf("sandboxProfileId = %q, want local", workflow.SandboxProfileID) + if workflow.SandboxProfileID != GenericDockerSandboxID { + t.Fatalf("sandboxProfileId = %q, want generic-docker", workflow.SandboxProfileID) } workflows := s.Workflows() found := false for _, candidate := range workflows { if candidate.ID == legacy.ID { found = true - if candidate.SandboxProfileID != "local" { - t.Fatalf("list sandboxProfileId = %q, want local", candidate.SandboxProfileID) + if candidate.SandboxProfileID != GenericDockerSandboxID { + t.Fatalf("list sandboxProfileId = %q, want generic-docker", candidate.SandboxProfileID) } } } @@ -74,7 +74,7 @@ func TestLegacyWorkflowReadsDefaultEmptySandboxProfileToLocal(t *testing.T) { // The legacy per-node sandbox field is migrated while decoding a stored // workflow payload, which is now always a MySQL row. func TestDecodingRejectsConflictingLegacyNodeSandboxProfiles(t *testing.T) { - raw := []byte(`{"id":"bad","name":"Bad","nodes":[{"id":"a","sandboxProfileId":"local"},{"id":"b","sandboxProfileId":"container"}]}`) + raw := []byte(`{"id":"bad","name":"Bad","nodes":[{"id":"a","sandboxProfileId":"test-native"},{"id":"b","sandboxProfileId":"container"}]}`) var wf domain.WorkflowDefinition err := json.Unmarshal(raw, &wf) if err == nil || !strings.Contains(err.Error(), "conflicting legacy node sandbox profiles") { @@ -106,12 +106,9 @@ func TestFirstIssueInProjectStartsAtOne(t *testing.T) { func TestNormalizeSandboxProfileKeepsOnlyDriverRelevantFields(t *testing.T) { base := domain.SandboxProfile{ReadOnlyRootFS: true, Environment: map[string]string{"TOOL_MODE": "test"}} - local := normalizeSandboxProfile(func() domain.SandboxProfile { p := base; p.Driver = "local"; return p }()) - if local.ReadOnlyRootFS { - t.Fatalf("local retained irrelevant sandbox fields: %+v", local) - } - if local.Environment["TOOL_MODE"] != "test" { - t.Fatalf("local lost sandbox environment: %+v", local) + legacy := normalizeSandboxProfile(func() domain.SandboxProfile { p := base; p.Driver = "local"; return p }()) + if legacy.Driver != domain.SandboxDriverNative || legacy.ReadOnlyRootFS || legacy.Environment["TOOL_MODE"] != "test" { + t.Fatalf("a legacy local sandbox becomes native with its environment: %+v", legacy) } light := normalizeSandboxProfile(func() domain.SandboxProfile { p := base; p.Driver = "seatbelt"; return p }()) if light.ReadOnlyRootFS || light.Driver != domain.SandboxDriverNative { @@ -122,54 +119,46 @@ func TestNormalizeSandboxProfileKeepsOnlyDriverRelevantFields(t *testing.T) { t.Fatalf("%q stored as %q, want native", driver, got) } } - docker := normalizeSandboxProfile(func() domain.SandboxProfile { p := base; p.Driver = "docker"; p.DockerfileID = "runtime"; return p }()) - if docker.DockerfileID != "runtime" || !docker.ReadOnlyRootFS || docker.EnvironmentID != "" { - t.Fatalf("docker lost relevant sandbox fields: %+v", docker) - } - fromFile := normalizeSandboxProfile(domain.SandboxProfile{Driver: "docker", DockerfileID: "runtime", EnvironmentID: "php8", ReadOnlyRootFS: true}) - if fromFile.DockerfileID != "runtime" || fromFile.EnvironmentID != "" || !fromFile.ReadOnlyRootFS { - t.Fatalf("docker dockerfile profile mismatch: %+v", fromFile) + recipe := &domain.SandboxDockerfile{Content: "FROM debian"} + docker := normalizeSandboxProfile(func() domain.SandboxProfile { + p := base + p.Driver = "docker" + p.Dockerfile = recipe + return p + }()) + if docker.Dockerfile != recipe || !docker.ReadOnlyRootFS { + t.Fatalf("docker keeps its Dockerfile: %+v", docker) } - lightEnv := normalizeSandboxProfile(domain.SandboxProfile{Driver: "seatbelt", DockerfileID: "runtime", EnvironmentID: "php8"}) - if lightEnv.DockerfileID != "" || lightEnv.EnvironmentID != "php8" { - t.Fatalf("seatbelt environment profile mismatch: %+v", lightEnv) + if native := normalizeSandboxProfile(domain.SandboxProfile{Driver: "seatbelt", Dockerfile: recipe, DockerfileID: "runtime"}); native.Dockerfile != nil || native.DockerfileID != "" { + t.Fatalf("native drops a Dockerfile: %+v", native) } if light.Environment["TOOL_MODE"] != "test" || docker.Environment["TOOL_MODE"] != "test" { t.Fatalf("managed sandbox lost environment: light=%+v docker=%+v", light, docker) } } -func TestPutDockerfileAndEnvironmentAndDockerSandbox(t *testing.T) { +func TestPutSandboxStoresItsDockerfile(t *testing.T) { s, err := OpenTest() if err != nil { t.Fatal(err) } t.Cleanup(func() { s.Close() }) - if err := s.PutDockerfile(domain.DockerfileDefinition{ID: "slim", Name: "Slim"}); err == nil { - t.Fatal("empty dockerfile content should be rejected") - } - if err := s.PutDockerfile(domain.DockerfileDefinition{ID: "slim", Name: "Slim", Content: "FROM debian:bookworm-slim"}); err != nil { - t.Fatal(err) - } - if err := s.PutEnvironment(domain.EnvironmentDefinition{ID: "php8-custom", Name: "PHP 8 custom", Variables: map[string]string{"PHP_VERSION": "8.4.0"}, PathEntries: []string{"bin"}}); err != nil { - t.Fatal(err) - } if err := s.PutSandbox(domain.SandboxProfile{ID: "docker-missing", Name: "Missing", Driver: "docker"}); err == nil { t.Fatal("docker sandbox without dockerfile should be rejected") } - if err := s.PutSandbox(domain.SandboxProfile{ID: "docker-unknown", Name: "Unknown", Driver: "docker", DockerfileID: "missing"}); err == nil { - t.Fatal("unknown dockerfile should be rejected") - } - if err := s.PutSandbox(domain.SandboxProfile{ID: "docker-ok", Name: "OK", Driver: "docker", DockerfileID: "slim"}); err != nil { + if err := s.PutSandbox(domain.SandboxProfile{ID: "docker-ok", Name: "OK", Driver: "docker", Dockerfile: &domain.SandboxDockerfile{Content: "FROM debian:bookworm-slim", Files: map[string]string{"etc/a": "x"}}}); err != nil { t.Fatal(err) } got, ok := s.Sandbox("docker-ok") - if !ok || got.DockerfileID != "slim" { - t.Fatalf("docker sandbox not stored as dockerfile reference: %+v", got) + if !ok || got.Dockerfile == nil || got.Dockerfile.Content != "FROM debian:bookworm-slim" || got.Dockerfile.Files["etc/a"] != "x" { + t.Fatalf("docker sandbox lost its Dockerfile: %+v", got) } - if err := s.PutSandbox(domain.SandboxProfile{ID: "seatbelt-php", Name: "Seatbelt PHP", Driver: "seatbelt", EnvironmentID: "php8-custom"}); err != nil { + if err := s.PutSandbox(domain.SandboxProfile{ID: "seatbelt-php", Name: "Seatbelt PHP", Driver: "seatbelt", Environment: map[string]string{"PHP_VERSION": "8.4.0"}}); err != nil { t.Fatal(err) } + if got, ok := s.Sandbox("seatbelt-php"); !ok || got.Driver != domain.SandboxDriverNative || got.Environment["PHP_VERSION"] != "8.4.0" { + t.Fatalf("native sandbox lost its environment: %+v", got) + } } func TestPutSandboxRejectsInvalidEnvironment(t *testing.T) { diff --git a/internal/runner/cli_auth_sandbox_test.go b/internal/runner/cli_auth_sandbox_test.go index 005405285..5ae49e266 100644 --- a/internal/runner/cli_auth_sandbox_test.go +++ b/internal/runner/cli_auth_sandbox_test.go @@ -217,12 +217,9 @@ func TestRunnerSOPCLIAuthentication(t *testing.T) { }}); err != nil { t.Fatal(err) } - if err := st.PutDockerfile(image); err != nil { - t.Fatal(err) - } profile := domain.SandboxProfile{ID: "runner-cli-auth-sandbox", Name: "CLI auth sandbox", Driver: driver} if driver == domain.SandboxDriverDocker { - profile.DockerfileID = image.ID + profile.Dockerfile = &domain.SandboxDockerfile{Content: image.Content, Files: image.Files} } if err := st.PutSandbox(profile); err != nil { t.Fatal(err) diff --git a/internal/runner/conversation.go b/internal/runner/conversation.go index 9433b9d0f..556f3bd81 100644 --- a/internal/runner/conversation.go +++ b/internal/runner/conversation.go @@ -35,8 +35,8 @@ func (d *Daemon) conversationProcess(ctx context.Context, request domain.RunnerW if err != nil { return runnerWorkspaceError(err) } - if request.Sandbox == nil || !domain.ConversationSandboxDriver(request.Sandbox.Profile.Driver) { - return domain.RunnerWorkspaceResponse{Status: 400, Error: "对话工作区只支持 Docker 或 native 沙箱"} + if request.Sandbox == nil { + return domain.RunnerWorkspaceResponse{Status: 400, Error: "工作区缺少沙箱配置"} } } d.conversationMu.Lock() diff --git a/internal/runner/conversation_process_guard_test.go b/internal/runner/conversation_process_guard_test.go index 9cb3f10cd..2b81ca349 100644 --- a/internal/runner/conversation_process_guard_test.go +++ b/internal/runner/conversation_process_guard_test.go @@ -40,8 +40,7 @@ func TestConversationProcessRejectsInvalidRequests(t *testing.T) { {"traversal key", true, domain.RunnerWorkspaceRequest{Conversation: conversationRequest(t, runtime.ConversationProcessRequest{Operation: "prepare", SessionKey: "../" + key[3:]})}, "invalid conversation process request"}, {"upper-case key", true, domain.RunnerWorkspaceRequest{Conversation: conversationRequest(t, runtime.ConversationProcessRequest{Operation: "prepare", SessionKey: strings.Repeat("A", 64)})}, "invalid conversation process request"}, {"invalid run id", true, domain.RunnerWorkspaceRequest{RunID: "..", Conversation: conversationRequest(t, runtime.ConversationProcessRequest{Operation: "prepare", SessionKey: key})}, "invalid run id"}, - {"run without sandbox", true, domain.RunnerWorkspaceRequest{RunID: "run-1", Conversation: conversationRequest(t, runtime.ConversationProcessRequest{Operation: "prepare", SessionKey: key})}, "只支持 Docker 或 native"}, - {"non-docker sandbox", true, domain.RunnerWorkspaceRequest{RunID: "run-1", Sandbox: &domain.RunnerSandboxSpec{Profile: domain.SandboxProfile{Driver: "process"}}, Conversation: conversationRequest(t, runtime.ConversationProcessRequest{Operation: "prepare", SessionKey: key})}, "只支持 Docker 或 native"}, + {"run without sandbox", true, domain.RunnerWorkspaceRequest{RunID: "run-1", Conversation: conversationRequest(t, runtime.ConversationProcessRequest{Operation: "prepare", SessionKey: key})}, "缺少沙箱配置"}, {"no control channel", false, domain.RunnerWorkspaceRequest{Conversation: conversationRequest(t, runtime.ConversationProcessRequest{Operation: "prepare", SessionKey: key})}, "control channel unavailable"}, } { t.Run(tc.name, func(t *testing.T) { diff --git a/internal/runner/daemon.go b/internal/runner/daemon.go index 3b70b3520..cbd037007 100644 --- a/internal/runner/daemon.go +++ b/internal/runner/daemon.go @@ -135,6 +135,7 @@ func New(cfg Config) (*Daemon, error) { host, _ := os.Hostname() cfg.Name = host } + runtime.SetRepositoryCacheRoot(cfg.DefaultWorkspaceRoot) return &Daemon{cfg: cfg, client: NewClient(cfg.ServerURL), executor: runtime.NewExecutorRunner(), controls: map[string]chan string{}, pendingControls: map[string]string{}, heartbeatWake: make(chan struct{}, 1)}, nil } @@ -748,7 +749,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); err != nil { + if err := checkoutInvocationRepositories(runtime.WithRepositoryCacheFor(ctx, runnerTaskSandboxDriver(task)), 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 { @@ -829,7 +830,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 } - checkoutErr := checkoutInvocationRepositories(ctx, workspace, inv) + checkoutErr := checkoutInvocationRepositories(runtime.WithRepositoryCacheFor(ctx, runnerTaskSandboxDriver(task)), workspace, inv) repositoryFallback := checkoutErr != nil && inv.RepositoryPreparationFallback && ctx.Err() == nil if checkoutErr != nil { if !repositoryFallback { @@ -1265,9 +1266,11 @@ func cloneRepository(ctx context.Context, workspace string, repo *domain.RunnerR watch := runnerCloneWatch(repo) // The platform cannot see this host's output yet; the operator can. ctx = procwatch.WithObserver(ctx, func(event procwatch.Event) { log.Printf("runner checkout: %s", event.Message) }) - tail, err := gitwork.Watch(repositoryGitContext(ctx, *repo), workspace, watch, args...) - if err != nil { - return fmt.Errorf("git clone %s: %w (%s)", domain.StripURLCredentials(repo.CloneURL), err, cloneOutput([]byte(tail), repo.GitToken)) + if !cloneFromRepositoryCache(repositoryGitContext(ctx, *repo), workspace, repo, watch) { + tail, err := gitwork.Watch(repositoryGitContext(ctx, *repo), workspace, watch, args...) + if err != nil { + return fmt.Errorf("git clone %s: %w (%s)", domain.StripURLCredentials(repo.CloneURL), err, cloneOutput([]byte(tail), repo.GitToken)) + } } // The branch steps below keep the bound they always had. cloneCtx := ctx @@ -1444,7 +1447,7 @@ func (d *Daemon) defaultWorkspace(taskID string) string { } // runnerVersion is reported at registration; it matches the module build. -var runnerVersion = domain.RunnerVersionCodeBuddyBaseURL +var runnerVersion = domain.RunnerVersionRepositoryCache // Version returns the runner build version reported at registration. func Version() string { return runnerVersion } diff --git a/internal/runner/daemon_test.go b/internal/runner/daemon_test.go index 6442b22a1..21d2c5311 100644 --- a/internal/runner/daemon_test.go +++ b/internal/runner/daemon_test.go @@ -251,7 +251,7 @@ func TestWorkflowScriptsShareRunnerRunWorkspace(t *testing.T) { t.Fatal(err) } wf := domain.WorkflowDefinition{ - ID: "runner-shared-scripts", Name: "Runner shared scripts", SandboxProfileID: "local", + ID: "runner-shared-scripts", Name: "Runner shared scripts", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "prepare", Name: "Prepare", Type: "script", ScriptLanguage: "shell", ExecutionScope: domain.ExecutionScopeRepositories, Script: "test \"$(git branch --show-current)\" = fix/shared-runner-workspace && mkdir -p .git/info vendor/new && printf '/vendor/\\n' >> .git/info/exclude && git ls-files -z -- vendor/ | git update-index --skip-worktree -z --stdin && printf 'changed\\n' > vendor/tracked/dependency.php && printf 'new\\n' > vendor/new/dependency.php && printf 'shared-ready\\n' > workspace-marker", MaxAttempts: 1}, {ID: "consume", Name: "Consume", Type: "script", ScriptLanguage: "python", ExecutionScope: domain.ExecutionScopeRepositories, Script: "from pathlib import Path\nimport subprocess\nassert subprocess.check_output(['git', 'status', '--short', '--', 'vendor']).decode() == ''\nprint(Path(\"workspace-marker\").read_text().strip() + \" it's visible\")", MaxAttempts: 1}, @@ -765,7 +765,7 @@ func TestWorkflowAgentNodeDispatchesToRunner(t *testing.T) { } putMockDeveloperPlaybook(t, s) wf := domain.WorkflowDefinition{ - ID: "runner-e2e", Name: "Runner e2e", SandboxProfileID: "local", + ID: "runner-e2e", Name: "Runner e2e", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "work", Name: "Work", Type: "agent", AgentID: "developer", ExecutorID: "mock", MaxAttempts: 1}}, } if err := s.PutWorkflow(wf); err != nil { @@ -852,7 +852,7 @@ func TestRunnerPauseWaitsForRemoteStopAndRestartsScriptInSameWorkspace(t *testin if err := s.SetDefaultRunner(42, runner.ID, time.Now().UTC()); err != nil { t.Fatal(err) } - wf := domain.WorkflowDefinition{ID: "runner-pause", Name: "Runner pause", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ + wf := domain.WorkflowDefinition{ID: "runner-pause", Name: "Runner pause", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ ID: "work", Name: "Work", Type: "command", Command: "if test -f .script-started; then printf restarted; else touch .script-started; sleep 30; fi", MaxAttempts: 1, }}} if err := s.PutWorkflow(wf); err != nil { @@ -940,7 +940,7 @@ func TestRunnerBoundRoleRunsGatesOnRunnerMachine(t *testing.T) { } putMockDeveloperPlaybook(t, s) wf := domain.WorkflowDefinition{ - ID: "runner-gate-e2e", Name: "Runner gate e2e", SandboxProfileID: "local", + ID: "runner-gate-e2e", Name: "Runner gate e2e", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ ID: "work", Name: "Work", Type: "agent", AgentID: "developer", ExecutorID: "mock", MaxAttempts: 1, diff --git a/internal/runner/exec_edges_cases_test.go b/internal/runner/exec_edges_cases_test.go index 5cf7df5d4..184a460bd 100644 --- a/internal/runner/exec_edges_cases_test.go +++ b/internal/runner/exec_edges_cases_test.go @@ -180,17 +180,16 @@ func TestEnsureRunnerBrowserDisabled(t *testing.T) { func TestRunSandboxKeysAndRequirements(t *testing.T) { dockerfile := domain.DockerfileDefinition{ID: "d", Content: "FROM scratch"} - environment := domain.EnvironmentDefinition{ID: "e"} task := domain.RunnerTask{ ID: "task", RunID: "run/id", Provider: "codex", Workspace: "runs/run-id/workspace", Sandbox: &domain.RunnerSandboxSpec{ - Profile: domain.SandboxProfile{Driver: "docker"}, - Dockerfile: &dockerfile, Environment: &environment, + Profile: domain.SandboxProfile{Driver: "docker"}, + Dockerfile: &dockerfile, Requirements: &domain.RunnerSandboxRequirements{PrivateHome: true, BunFS: true, RunnerLoginRelay: true, CLIStates: []domain.RunnerCLIStateRequirement{{Directory: ".x", Files: []string{"a"}}}}, }, } requirements, resources := taskSandboxSpec(task) - if !requirements.PrivateHome || !requirements.BunFS || !requirements.RunnerLoginRelay || len(requirements.CLIStates) != 1 || resources.Dockerfile.ID != "d" || resources.Environment.ID != "e" { + if !requirements.PrivateHome || !requirements.BunFS || !requirements.RunnerLoginRelay || len(requirements.CLIStates) != 1 || resources.Dockerfile.ID != "d" { t.Fatalf("requirements=%+v resources=%+v", requirements, resources) } key, id, shared := runSandboxKey(task, requirements, resources) diff --git a/internal/runner/git_http_test.go b/internal/runner/git_http_test.go index ce98a85ed..f801cb00b 100644 --- a/internal/runner/git_http_test.go +++ b/internal/runner/git_http_test.go @@ -9,6 +9,7 @@ import ( "agentflow/internal/domain" "agentflow/internal/gitwork" + "agentflow/internal/repo" "agentflow/internal/runtime" ) @@ -16,7 +17,10 @@ func TestMain(m *testing.M) { if runtime.RunMCPCallCLI(os.Args[1:]) || runtime.RunGitHelperCLI(os.Args[1:]) { return } - os.Exit(m.Run()) + cleanup := repo.UseSandboxVisibleTempDir() + code := m.Run() + cleanup() + os.Exit(code) } func TestRunnerGitHelperUsesInvocationHostCredentials(t *testing.T) { diff --git a/internal/runner/integrate_test.go b/internal/runner/integrate_test.go index 7f0ce5a15..16941561e 100644 --- a/internal/runner/integrate_test.go +++ b/internal/runner/integrate_test.go @@ -36,7 +36,7 @@ func TestRunnerModeScheduledRunIntegratesOnRunner(t *testing.T) { t.Fatalf("runner version %q does not integrate", runner.RunnerVersion) } wf := domain.WorkflowDefinition{ - ID: "runner-integrate", Name: "Runner integrate", SandboxProfileID: "local", + ID: "runner-integrate", Name: "Runner integrate", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "implement", Name: "实现", Type: "script", ScriptLanguage: "shell", ExecutionScope: domain.ExecutionScopeRepositories, Script: "printf 'fixed\\n' > feature.txt && printf 'report\\n' > fix-report.md", MaxAttempts: 1}, }, diff --git a/internal/runner/pool_test.go b/internal/runner/pool_test.go index bee1c7487..c2170d55f 100644 --- a/internal/runner/pool_test.go +++ b/internal/runner/pool_test.go @@ -66,7 +66,7 @@ func TestPoolRequiredRunWaitsForPoolRunner(t *testing.T) { e.ConfigureCloudRunnerPool(engine.CloudRunnerPool{Label: "pool=cloud", Projects: []string{"*"}, Required: true}) remote := bareRemoteWithBaseline(t) wf := domain.WorkflowDefinition{ - ID: "pool-required", Name: "Pool required", SandboxProfileID: "local", + ID: "pool-required", Name: "Pool required", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "implement", Name: "实现", Type: "script", ScriptLanguage: "shell", ExecutionScope: domain.ExecutionScopeRepositories, Script: "printf 'pool\\n' > feature.txt", MaxAttempts: 1}, }, @@ -112,7 +112,7 @@ func TestPoolRunResumesOnOriginalRunnerAfterRestart(t *testing.T) { } first, stopFirst := startPoolRunnerWithConfig(t, s, cfg) wf := domain.WorkflowDefinition{ - ID: "pool-takeover", Name: "Pool takeover", SandboxProfileID: "local", + ID: "pool-takeover", Name: "Pool takeover", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "implement", Name: "实现", Type: "script", ScriptLanguage: "shell", ExecutionScope: domain.ExecutionScopeRepositories, Script: "printf 'from a\\n' > feature.txt", MaxAttempts: 1}, {ID: "gate", Name: "确认", Type: "approval", MaxAttempts: 1}, diff --git a/internal/runner/reported_outputs_test.go b/internal/runner/reported_outputs_test.go index 25a8928ed..4538a0936 100644 --- a/internal/runner/reported_outputs_test.go +++ b/internal/runner/reported_outputs_test.go @@ -80,7 +80,7 @@ func TestRunnerReportedOutputsDriveArtifactsAndHandoff(t *testing.T) { remote := bareRemoteWithBaseline(t) startReportingRunner(t, s, server.URL) wf := domain.WorkflowDefinition{ - ID: "runner-reported-outputs", Name: "Runner reported outputs", SandboxProfileID: "local", + ID: "runner-reported-outputs", Name: "Runner reported outputs", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "plan", Name: "方案", Type: "script", ScriptLanguage: "shell", MaxAttempts: 1, Script: "printf 'plan body\\n' > plan.md && for f in README.md */README.md; do if [ -f \"$f\" ]; then printf 'changed\\n' >> \"$f\"; fi; done", @@ -121,7 +121,7 @@ func TestRunnerReportedOutputsKeepFailedNodeArtifacts(t *testing.T) { server, s, e := newDaemonTestServer(t) startReportingRunner(t, s, server.URL) wf := domain.WorkflowDefinition{ - ID: "runner-reported-failure", Name: "Runner reported failure", SandboxProfileID: "local", + ID: "runner-reported-failure", Name: "Runner reported failure", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "diagnose", Name: "诊断", Type: "script", ScriptLanguage: "shell", MaxAttempts: 1, Script: "printf 'what went wrong\\n' > diagnosis.md && exit 3", diff --git a/internal/runner/repository_cache.go b/internal/runner/repository_cache.go new file mode 100644 index 000000000..04ad9a787 --- /dev/null +++ b/internal/runner/repository_cache.go @@ -0,0 +1,38 @@ +package runner + +import ( + "context" + "log" + "strings" + + "agentflow/internal/domain" + "agentflow/internal/gitwork" + "agentflow/internal/procwatch" + "agentflow/internal/runtime" +) + +// cloneFromRepositoryCache checks repo out as a shared clone of the +// repository cache in ctx. False means a full clone has to follow: there is +// no cache for this workspace, or it could not be used. +func cloneFromRepositoryCache(ctx context.Context, workspace string, repo *domain.RunnerRepository, watch procwatch.Options) bool { + root := gitwork.RepositoryCacheFrom(ctx) + if gitwork.RepositoryCachePath(root, repo.RepositoryID) == "" { + return false + } + err := gitwork.CloneFromRepositoryCache(ctx, root, repo.RepositoryID, strings.TrimSpace(repo.CloneURL), repo.Ref, workspace, watch) + if err != nil { + log.Printf("runner checkout: repository cache of %s unavailable, cloning fully: %s", repo.RepositoryID, cloneOutput([]byte(err.Error()), repo.GitToken)) + return false + } + return true +} + +// warmRepositoryCaches fetches the caches of the repositories a native +// conversation workspace may clone later. +func warmRepositoryCaches(ctx context.Context, inv *domain.RunnerInvocation) { + if inv == nil || len(inv.CacheRepositories) == 0 { + return + } + ctx = gitwork.WithSSHKeys(ctx, inv.GitSSHKeys) + runtime.WarmRepositoryCaches(invocationGitHTTPContext(ctx, inv), inv.CacheRepositories) +} diff --git a/internal/runner/repository_checkout_new_branch_test.go b/internal/runner/repository_checkout_new_branch_test.go index 80726008b..32382eed1 100644 --- a/internal/runner/repository_checkout_new_branch_test.go +++ b/internal/runner/repository_checkout_new_branch_test.go @@ -2,10 +2,13 @@ package runner import ( "context" + "os" + "path/filepath" "strings" "testing" "agentflow/internal/domain" + "agentflow/internal/gitwork" ) func TestCloneRepositoryCreatesOnlyNewWorkBranch(t *testing.T) { @@ -26,3 +29,31 @@ func TestCloneRepositoryCreatesOnlyNewWorkBranch(t *testing.T) { t.Fatalf("existing remote branch accepted as new: %v", err) } } + +// A native workspace's checkout is a shared clone of this machine's +// repository cache. A branch the repository lacks still fails after the +// full-clone fallback. +func TestCloneRepositoryStartsFromRepositoryCache(t *testing.T) { + remote := bareRemoteWithBaseline(t) + root := t.TempDir() + ctx := gitwork.WithRepositoryCache(context.Background(), root) + repo := &domain.RunnerRepository{RepositoryID: "repo", CloneURL: remote, Ref: "master", WorkBranch: "feature/cached", CreateNewWorkBranch: true} + workspace := t.TempDir() + if err := cloneRepository(ctx, workspace, repo); err != nil { + t.Fatal(err) + } + alternates, err := os.ReadFile(filepath.Join(workspace, ".git", "objects", "info", "alternates")) + if err != nil || !strings.Contains(string(alternates), filepath.Join(root, "repo.git")) { + t.Fatalf("checkout does not borrow the cache objects: %q %v", alternates, err) + } + if origin := runGitT(t, workspace, "remote", "get-url", "origin"); origin != remote { + t.Fatalf("origin = %q, want %q", origin, remote) + } + if branch := runGitT(t, workspace, "branch", "--show-current"); branch != "feature/cached" { + t.Fatalf("work branch = %q", branch) + } + missing := &domain.RunnerRepository{RepositoryID: "repo", CloneURL: remote, Ref: "no-such-branch"} + if err := cloneRepository(ctx, t.TempDir(), missing); err == nil { + t.Fatal("missing branch cloned") + } +} diff --git a/internal/runner/run_sandbox.go b/internal/runner/run_sandbox.go index 9cd04f29a..b30b403a7 100644 --- a/internal/runner/run_sandbox.go +++ b/internal/runner/run_sandbox.go @@ -174,15 +174,12 @@ func containerSafe(v string) string { } // taskSandboxSpec is the sandbox a task asks for: the provider's CLI needs -// plus the Dockerfile and environment it carries. +// plus the Dockerfile it carries. func taskSandboxSpec(task domain.RunnerTask) (runtime.SandboxRequirements, runtime.SandboxResources) { resources := runtime.SandboxResources{} if task.Sandbox.Dockerfile != nil { resources.Dockerfile = *task.Sandbox.Dockerfile } - if task.Sandbox.Environment != nil { - resources.Environment = *task.Sandbox.Environment - } // Tasks queued before RunnerLoginRelay was added still carry their auth mode. codexLoginRelay := task.Invocation != nil && task.Invocation.CredentialSource == domain.RuntimeAuthLocal && task.Provider == "codex" && strings.TrimSpace(task.Sandbox.Profile.Driver) == domain.SandboxDriverDocker diff --git a/internal/runner/work_branch_test.go b/internal/runner/work_branch_test.go index 580fe741a..54f3ccd4f 100644 --- a/internal/runner/work_branch_test.go +++ b/internal/runner/work_branch_test.go @@ -71,7 +71,7 @@ func TestRunnerModeNodeKeepsChangesLocal(t *testing.T) { t.Fatal(err) } wf := domain.WorkflowDefinition{ - ID: "runner-work-branch", Name: "Runner work branch", SandboxProfileID: "local", + ID: "runner-work-branch", Name: "Runner work branch", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "implement", Name: "实现", Type: "script", ScriptLanguage: "shell", ExecutionScope: domain.ExecutionScopeRepositories, Script: "printf 'fixed\\n' > feature.txt && mkdir -p node_modules/x && printf 'dep\\n' > node_modules/x/index.js", MaxAttempts: 1}, {ID: "verify", Name: "验证", Type: "script", ScriptLanguage: "shell", ExecutionScope: domain.ExecutionScopeRepositories, Script: "test \"$(cat feature.txt)\" = fixed && test -n \"$(git status --porcelain -- feature.txt)\" && echo uncommitted", MaxAttempts: 1}, diff --git a/internal/runner/workspace_preparation.go b/internal/runner/workspace_preparation.go index 526ad354f..c009c774b 100644 --- a/internal/runner/workspace_preparation.go +++ b/internal/runner/workspace_preparation.go @@ -88,9 +88,11 @@ 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, request.RefreshCleanRepositories); err != nil { + cacheCtx := runtime.WithRepositoryCacheFor(ctx, runnerTaskSandboxDriver(task)) + if err := checkoutInvocationRepositories(cacheCtx, root, request.PreparationInvocation, request.RefreshCleanRepositories); err != nil { return runnerWorkspaceError(fmt.Errorf("prepare workspace repositories: %w", err)) } + warmRepositoryCaches(cacheCtx, request.PreparationInvocation) sb, release, err := d.acquireTaskSandbox(ctx, task) if err != nil { return runnerWorkspaceError(err) @@ -131,7 +133,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); err != nil { + if err := checkoutInvocationRepositories(runtime.WithRepositoryCacheFor(ctx, runnerTaskSandboxDriver(task)), root, request.PreparationInvocation); err != nil { unlock() return runtime.TerminalResult{}, fmt.Errorf("prepare workspace repositories: %w", err) } diff --git a/internal/runner/workspace_preparation_test.go b/internal/runner/workspace_preparation_test.go index 00e14d28e..ffe8684e9 100644 --- a/internal/runner/workspace_preparation_test.go +++ b/internal/runner/workspace_preparation_test.go @@ -23,7 +23,7 @@ func runnerPreparationFixture(t *testing.T) (*Daemon, domain.RunnerWorkspaceRequ return &Daemon{cfg: Config{DefaultWorkspaceRoot: base}}, domain.RunnerWorkspaceRequest{ RunID: "prepared", RunStatus: "waiting", WorkspaceLayout: domain.RunnerWorkspaceLayoutShared, Operation: domain.RunnerWorkspaceOperationPrepare, - Sandbox: &domain.RunnerSandboxSpec{Profile: domain.SandboxProfile{Driver: "local", Environment: map[string]string{"WORKSPACE_OVERLAY": "same-node-environment"}}, Requirements: &domain.RunnerSandboxRequirements{}}, + Sandbox: &domain.RunnerSandboxSpec{Profile: domain.SandboxProfile{Driver: "native", Environment: map[string]string{"WORKSPACE_OVERLAY": "same-node-environment"}}, Requirements: &domain.RunnerSandboxRequirements{}}, Workflow: &domain.WorkflowDefinition{Nodes: []domain.WorkflowNode{{ID: "prepare", Name: "Prepare", Type: "script", RunOnWorkspaceRebuild: true, Script: "printf x >> preparation-count; printf '%s' \"$WORKSPACE_OVERLAY\" > prepared-environment"}}}, }, root } @@ -149,7 +149,7 @@ func TestRunnerWorkspacePreparationFailsClosedAndFencesActiveTasks(t *testing.T) if result = d.readRunnerWorkspace(context.Background(), req); result.Status == 200 { t.Fatal("terminal silently opened host shell") } - req.Sandbox = &domain.RunnerSandboxSpec{Profile: domain.SandboxProfile{Driver: "local"}} + req.Sandbox = &domain.RunnerSandboxSpec{Profile: domain.SandboxProfile{Driver: "native"}} req.Operation = domain.RunnerWorkspaceOperationPrepare gate := d.workspaceGate(req.RunID) gate.RLock() @@ -561,7 +561,7 @@ func TestConversationWorkspaceMaterializesOnConnectedRunner(t *testing.T) { runnerID := s.Runners()[0].ID run := domain.Run{ ID: "chat-materialize", Kind: domain.RunKindWorkspace, Status: "waiting", Nodes: map[string]*domain.NodeRun{}, - WorkflowSnapshot: domain.WorkflowDefinition{ID: domain.ConversationWorkspaceWorkflowID, SandboxProfileID: "local"}, + WorkflowSnapshot: domain.WorkflowDefinition{ID: domain.ConversationWorkspaceWorkflowID, SandboxProfileID: "test-native"}, ExecutionContext: domain.TelemetryContext{ExecutionMode: domain.ExecutionModeRunner, ExecutionRunnerID: runnerID, RunnerWorkspaceLayout: domain.RunnerWorkspaceLayoutShared}, Repositories: []domain.RepositoryContext{{RepositoryID: "web", Name: "web", CloneURL: remote, BaseBranch: "master", WorkBranch: "feature/chat", WorkspaceDir: "web"}}, } diff --git a/internal/runner/workspace_rebuild_workflow_test.go b/internal/runner/workspace_rebuild_workflow_test.go index 4e1db6cd5..676948602 100644 --- a/internal/runner/workspace_rebuild_workflow_test.go +++ b/internal/runner/workspace_rebuild_workflow_test.go @@ -39,7 +39,7 @@ func TestRunnerRebuildCheckboxPreservesNormalSOPScriptOrder(t *testing.T) { if err := store.SetDefaultRunner(42, runner.ID, time.Now().UTC()); err != nil { t.Fatal(err) } - workflow := domain.WorkflowDefinition{ID: "rebuild-checkbox-normal-order", Name: "normal order", SandboxProfileID: "local", Nodes: []domain.WorkflowNode{ + workflow := domain.WorkflowDefinition{ID: "rebuild-checkbox-normal-order", Name: "normal order", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "one", Name: "One", Type: "script", ScriptLanguage: "shell", RunOnWorkspaceRebuild: true, Script: "printf '1\\n' >> normal-order", MaxAttempts: 1}, {ID: "two", Name: "Two", Type: "script", ScriptLanguage: "shell", RunOnWorkspaceRebuild: true, Script: "test \"$(cat normal-order)\" = 1 || exit 7; printf '2\\n' >> normal-order", MaxAttempts: 1}, {ID: "check", Name: "Check", Type: "script", ScriptLanguage: "shell", Script: "test \"$(cat normal-order)\" = \"$(printf '1\\n2')\" || exit 8; printf graph-ok", MaxAttempts: 1}, diff --git a/internal/runtime/conversation_process.go b/internal/runtime/conversation_process.go index e519759f4..01d9d4f32 100644 --- a/internal/runtime/conversation_process.go +++ b/internal/runtime/conversation_process.go @@ -160,6 +160,9 @@ type conversationProcess struct { notStarted bool cliVersion string versionSource string + // workspace replaces /ws in stdin under seatbelt, which has no mount + // namespace to map that path onto the run workspace. + workspace string // gitScrubbed is set with done, under mu. gitScrubbed []string } @@ -274,7 +277,7 @@ func (p *ConversationProcessPool) Handle(ctx context.Context, root, workspace st switch req.Operation { case "write": proc.mu.Lock() - input := proc.input + input, workspace := proc.input, proc.workspace proc.mu.Unlock() if input == nil { return ConversationProcessResult{}, fmt.Errorf("process has no stdin") @@ -291,7 +294,11 @@ func (p *ConversationProcessPool) Handle(ctx context.Context, root, workspace st err = nil } } else { - _, err = io.WriteString(input, conversationRemap(req.Data, req.SourceRoot, root)) + data := conversationRemap(req.Data, req.SourceRoot, root) + if workspace != "" { + data = strings.ReplaceAll(data, filepath.Join(root, "ws"), workspace) + } + _, err = io.WriteString(input, data) } return ConversationProcessResult{}, err case "stop": @@ -567,9 +574,6 @@ func (p *ConversationProcessPool) start(ctx context.Context, root, workspace str if spec.Dockerfile != nil { resources.Dockerfile = *spec.Dockerfile } - if spec.Environment != nil { - resources.Environment = *spec.Environment - } sb, err = OpenRemoteSandbox(procCtx, "conversation-"+id, workspace, spec.Profile, SandboxRequirements{ConversationRoot: root}, resources) if sb != nil { release = func() { _ = sb.Close(context.Background()) } @@ -605,6 +609,11 @@ func (p *ConversationProcessPool) start(ctx context.Context, root, workspace str case strings.TrimSpace(workspace) != "": command.WorkingDir = workspace } + if command.WorkingDir != filepath.Join(root, "ws") { + proc.mu.Lock() + proc.workspace = command.WorkingDir + proc.mu.Unlock() + } } command.OwnProcessGroup = true if spec != nil { diff --git a/internal/runtime/conversation_seatbelt_test.go b/internal/runtime/conversation_seatbelt_test.go index e218830ef..f65d1fdf1 100644 --- a/internal/runtime/conversation_seatbelt_test.go +++ b/internal/runtime/conversation_seatbelt_test.go @@ -191,6 +191,46 @@ echo '{"type":"result","result":"seatbelt-ok"}' } } +func TestConversationProcessSeatbeltMapsWsInStdinToRunWorkspace(t *testing.T) { + if goruntime.GOOS != "darwin" { + t.Skip("seatbelt execution test requires macOS") + } + if out, err := exec.Command("/usr/bin/sandbox-exec", "-p", "(version 1)(allow default)", "/usr/bin/true").CombinedOutput(); err != nil { + t.Skipf("sandbox-exec unavailable in current environment: %v (%s)", err, string(out)) + } + root, workspace := t.TempDir(), t.TempDir() + cli := filepath.Join(t.TempDir(), "fake-codebuddy") + if err := os.WriteFile(cli, []byte("#!/bin/sh\nread line\necho \"LINE=$line\"\necho '{\"type\":\"result\",\"result\":\"ok\"}'\n"), 0o700); err != nil { + t.Fatal(err) + } + t.Setenv("AGENTFLOW_CODEBUDDY_BIN", cli) + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + factory := func(_ context.Context, nativeRoot string) (Sandbox, func(), error) { + sb := &processSandbox{id: "conv-seatbelt-ws", driver: domain.SandboxDriverSeatbelt, binary: "/usr/bin/sandbox-exec", workspace: workspace} + if err := ConfigureConversationSandbox(ctx, sb, nativeRoot); err != nil { + return nil, nil, err + } + return WithSandboxCredentials(sb, RunCredentials{}), func() {}, nil + } + pool := &ConversationProcessPool{} + spec := &domain.RunnerSandboxSpec{Profile: domain.SandboxProfile{ID: "native", Driver: domain.SandboxDriverNative}} + start, err := pool.Handle(ctx, root, workspace, spec, ConversationProcessRequest{ + Operation: "start", SourceRoot: "/api-state", + Command: &ConversationCommand{Provider: "codebuddy", Argv: []string{"codebuddy"}, Interactive: true}, + }, nil, factory) + if err != nil { + t.Fatal(err) + } + if _, err = pool.Handle(ctx, root, workspace, spec, ConversationProcessRequest{Operation: "write", ID: start.ID, SourceRoot: "/api-state", Data: `{"cwd":"/api-state/ws"}` + "\n"}, nil); err != nil { + t.Fatal(err) + } + got := conversationPoll(t, pool, ctx, root, start.ID) + if want := `LINE={"cwd":"` + workspace + `"}`; !strings.Contains(got, want) { + t.Fatalf("stdin cwd not mapped onto the run workspace: want %s in:\n%s", want, got) + } +} + func TestConversationProcessSeatbeltDockerDaemon(t *testing.T) { if goruntime.GOOS != "darwin" { t.Skip("seatbelt execution test requires macOS") diff --git a/internal/runtime/edges_cases_test.go b/internal/runtime/edges_cases_test.go index bd1d34b94..d6a87ab3a 100644 --- a/internal/runtime/edges_cases_test.go +++ b/internal/runtime/edges_cases_test.go @@ -32,10 +32,6 @@ func TestOpenRemoteSandboxErrorBranches(t *testing.T) { if _, err := OpenRemoteSandbox(context.Background(), "id", t.TempDir(), domain.SandboxProfile{Driver: "seatbelt"}, SandboxRequirements{}, SandboxResources{}); err == nil { t.Fatal("missing seatbelt accepted") } - resources := SandboxResources{Environment: domain.EnvironmentDefinition{ID: "broken", InstallScript: "exit 9"}} - if _, err := OpenRemoteSandbox(context.Background(), "id", t.TempDir(), domain.SandboxProfile{EnvironmentID: "broken"}, SandboxRequirements{}, resources); err == nil { - t.Fatal("failing environment install accepted") - } } func TestWorkspacePreparationReusableReceipts(t *testing.T) { @@ -106,9 +102,6 @@ func TestSandboxIsolationEnvironmentConcreteTypes(t *testing.T) { if got := command.WithMCPStartupWait(time.Second); len(got.environment) != 0 { t.Fatalf("non-codebuddy wait changed command=%+v", got) } - if _, err := OpenRemoteSandbox(context.Background(), "id", t.TempDir(), domain.SandboxProfile{EnvironmentID: "missing"}, SandboxRequirements{}, SandboxResources{}); err == nil { - t.Fatal("missing environment accepted") - } if got := safeID(strings.Repeat("a", 60)); len(got) != 48 { t.Fatalf("long safe id length=%d", len(got)) } diff --git a/internal/runtime/gate_mcp.go b/internal/runtime/gate_mcp.go index c78c537de..541ae12c6 100644 --- a/internal/runtime/gate_mcp.go +++ b/internal/runtime/gate_mcp.go @@ -151,8 +151,13 @@ func buildArtifactFresh(cache, root string) bool { return filepath.SkipDir } if entry.IsDir() { - switch entry.Name() { - case "vendor", ".git", "testdata", "web", "docs": + // Every agent turn waits on this walk under gateMCPBuildMu, so + // frontend dependency trees (tens of thousands of files) must + // not be visited. + switch name := entry.Name(); { + case path != root && strings.HasPrefix(name, "."): + return filepath.SkipDir + case name == "vendor", name == "testdata", name == "web", name == "docs", name == "node_modules": return filepath.SkipDir } return nil diff --git a/internal/runtime/gate_mcp_test.go b/internal/runtime/gate_mcp_test.go index 4ad947160..83ba6f4bd 100644 --- a/internal/runtime/gate_mcp_test.go +++ b/internal/runtime/gate_mcp_test.go @@ -8,6 +8,7 @@ import ( goruntime "runtime" "strings" "testing" + "time" "agentflow/internal/domain" ) @@ -138,3 +139,38 @@ func TestMaterializeGateMCPSelectsLinuxForDocker(t *testing.T) { t.Fatalf("docker gate helper = %q, want linux artifact", raw) } } + +// Only Go sources outside dependency and hidden trees can make the cached gate +// MCP binary stale. +func TestGateMCPFreshnessIgnoresDependencyAndHiddenTrees(t *testing.T) { + root := t.TempDir() + cache := filepath.Join(t.TempDir(), "gate-mcp") + old := time.Now().Add(-time.Hour) + write := func(rel string, at time.Time) { + path := filepath.Join(root, rel) + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte("package x\n"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.Chtimes(path, at, at); err != nil { + t.Fatal(err) + } + } + write("go.mod", old) + write("cmd/agentflow-gate-mcp/main.go", old) + if err := os.WriteFile(cache, []byte("binary"), 0o755); err != nil { + t.Fatal(err) + } + now := time.Now() + write("chatbot/node_modules/pkg/x.go", now.Add(time.Minute)) + write(".local/scratch/x.go", now.Add(time.Minute)) + if !buildArtifactFresh(cache, root) { + t.Fatal("dependency or hidden trees made the binary stale") + } + write("internal/x/x.go", now.Add(time.Minute)) + if buildArtifactFresh(cache, root) { + t.Fatal("a newer Go source did not make the binary stale") + } +} diff --git a/internal/runtime/managed_files_test.go b/internal/runtime/managed_files_test.go index 4ad0ddd9d..d50045f48 100644 --- a/internal/runtime/managed_files_test.go +++ b/internal/runtime/managed_files_test.go @@ -1,7 +1,6 @@ package runtime import ( - "context" "os" "path/filepath" "sync" @@ -207,28 +206,6 @@ func TestWorkspacePreparationDoesNotReadOutsideState(t *testing.T) { } } -func TestEnvironmentInstallRejectsSymlinkStamp(t *testing.T) { - workspace := t.TempDir() - root := filepath.Join(workspace, ".agentflow", "environment", "env") - if err := os.MkdirAll(root, 0700); err != nil { - t.Fatal(err) - } - victim := filepath.Join(t.TempDir(), "keep") - putSecurityFixture(t, victim, "keep") - if err := os.Symlink(victim, filepath.Join(root, installStampName)); err != nil { - t.Fatal(err) - } - sb := &provisionSandbox{workspace: workspace} - activated := activatedEnvironment{Root: root, InstallRel: "install.sh", InstallScript: "echo bad"} - if err := runEnvironmentInstall(context.Background(), sb, activated); err == nil { - t.Fatal("symlink accepted") - } - if sb.commands != 0 { - t.Fatal("installation ran before validating marker") - } - checkSecurityFixture(t, victim, "keep") -} - func TestTerminalHomeCleanupRestrictsLegacyPaths(t *testing.T) { victim := filepath.Join(t.TempDir(), "keep") putSecurityFixture(t, victim, "keep") diff --git a/internal/runtime/remote_sandbox.go b/internal/runtime/remote_sandbox.go index 3f758d365..d6f93939f 100644 --- a/internal/runtime/remote_sandbox.go +++ b/internal/runtime/remote_sandbox.go @@ -24,20 +24,7 @@ func OpenRemoteSandbox(ctx context.Context, id, workspace string, profile domain if err := os.MkdirAll(workspace, 0o700); err != nil { return nil, err } - activated, err := prepareSandboxEnvironment(workspace, profile, resources.Environment) - if err != nil { - return nil, err - } - profile.Environment = overlayEnvironment(profile.Environment, activated.Overlay) - sandbox, err := createDriverSandbox(ctx, "runner sandbox", id, workspace, profile, requirements, resources.Dockerfile) - if err != nil { - return nil, err - } - if err := runEnvironmentInstall(ctx, sandbox, activated); err != nil { - _ = sandbox.Close(ctx) - return nil, err - } - return sandbox, nil + return createDriverSandbox(ctx, "runner sandbox", id, workspace, profile, requirements, resources.Dockerfile) } // WithCommandEnvironment adds task-scoped environment values to a prepared diff --git a/internal/runtime/remote_sandbox_test.go b/internal/runtime/remote_sandbox_test.go index c7aff71af..0a3282eb7 100644 --- a/internal/runtime/remote_sandbox_test.go +++ b/internal/runtime/remote_sandbox_test.go @@ -4,8 +4,6 @@ import ( "context" "crypto/sha256" "fmt" - "os" - "path/filepath" "strings" "testing" @@ -32,29 +30,6 @@ func TestOpenRemoteSandboxUsesExactRunnerWorkspace(t *testing.T) { } } -func TestOpenRemoteSandboxInstallsEnvironmentBeforeCommands(t *testing.T) { - workspace := t.TempDir() - profile := domain.SandboxProfile{Driver: "local", EnvironmentID: "runner-tools"} - resources := SandboxResources{Environment: domain.EnvironmentDefinition{ID: "runner-tools", InstallScript: `mkdir -p "$PREFIX/bin" -printf '#!/bin/sh\nprintf runner-ready' > "$PREFIX/bin/runner-ready" -chmod +x "$PREFIX/bin/runner-ready" -printf x >> install-count`}} - for i := 0; i < 2; i++ { - sandbox, err := OpenRemoteSandbox(context.Background(), "runner-task", workspace, profile, SandboxRequirements{}, resources) - if err != nil { - t.Fatal(err) - } - output, err := sandbox.Exec(context.Background(), CommandSpec{Argv: []string{"sh", "-c", "runner-ready"}}, nil) - if err != nil || strings.TrimSpace(output) != "runner-ready" { - t.Fatalf("environment not installed: %q %v", output, err) - } - _ = sandbox.Close(context.Background()) - } - if body, err := os.ReadFile(filepath.Join(workspace, "install-count")); err != nil || string(body) != "x" { - t.Fatalf("unchanged environment installed repeatedly: %q %v", body, err) - } -} - func TestWithSandboxCredentialsRefreshesExplicitBindings(t *testing.T) { workspace := t.TempDir() original := &localSandbox{workspace: workspace} diff --git a/internal/runtime/repository_cache.go b/internal/runtime/repository_cache.go new file mode 100644 index 000000000..31641ebc4 --- /dev/null +++ b/internal/runtime/repository_cache.go @@ -0,0 +1,142 @@ +package runtime + +import ( + "cmp" + "context" + "fmt" + "log" + "os" + "os/exec" + "path/filepath" + "strings" + "sync" + "sync/atomic" + "time" + + "agentflow/internal/domain" + "agentflow/internal/gitwork" + "agentflow/internal/procwatch" +) + +// RepositoryCacheDir is the repository cache under a workspace root. Workspace +// cleanup skips dot directories, so the cache outlives the runs that use it. +const RepositoryCacheDir = ".repository-cache" + +var repositoryCacheRoot atomic.Value + +// SetRepositoryCacheRoot names this process's repository cache: the platform +// and each execution machine keep their own, next to their workspaces. +func SetRepositoryCacheRoot(workspaceRoot string) { + root := "" + if strings.TrimSpace(workspaceRoot) != "" { + if abs, err := filepath.Abs(workspaceRoot); err == nil { + root = filepath.Join(abs, RepositoryCacheDir) + } + } + repositoryCacheRoot.Store(root) +} + +// RepositoryCacheRoot is the root SetRepositoryCacheRoot chose, or empty. +func RepositoryCacheRoot() string { + root, _ := repositoryCacheRoot.Load().(string) + return root +} + +// NativeSandboxDriver reports whether driver is the OS process sandbox, whose +// workspaces see the host filesystem read-only. +func NativeSandboxDriver(driver string) bool { + switch strings.TrimSpace(driver) { + case domain.SandboxDriverNative, domain.SandboxDriverSeatbelt, domain.SandboxDriverBwrap: + return true + } + return false +} + +// WithRepositoryCacheFor lets checkouts for a workspace in driver start from +// the repository cache. Docker workspaces keep full clones: the container +// cannot reach the cache by its host path. +func WithRepositoryCacheFor(ctx context.Context, driver string) context.Context { + if !NativeSandboxDriver(driver) { + return ctx + } + return gitwork.WithRepositoryCache(ctx, RepositoryCacheRoot()) +} + +const repositoryCacheWarmInterval = 5 * time.Minute + +var warmedRepositoryCaches sync.Map + +// WarmRepositoryCaches fetches the caches of repositories in the background, +// each at most once per interval, so an Agent's later shared clone of them +// needs no network. ctx carries the cache root and Git credentials. +func WarmRepositoryCaches(ctx context.Context, repositories []domain.RunnerRepository) { + root := gitwork.RepositoryCacheFrom(ctx) + if root == "" || len(repositories) == 0 { + return + } + ctx = procwatch.WithObserver(context.WithoutCancel(ctx), func(procwatch.Event) {}) + go func() { + for _, repository := range repositories { + dir, remote := gitwork.RepositoryCachePath(root, repository.RepositoryID), strings.TrimSpace(repository.CloneURL) + if dir == "" || remote == "" { + continue + } + if last, ok := warmedRepositoryCaches.Load(dir); ok && time.Since(last.(time.Time)) < repositoryCacheWarmInterval { + continue + } + warmedRepositoryCaches.Store(dir, time.Now()) + repositoryCtx := gitwork.WithHTTPRemote(ctx, remote) + if repository.UseSSH { + repositoryCtx = gitwork.WithSSHRemote(ctx, remote) + } + watch := procwatch.Options{ + Stage: "clone", Label: "更新仓库缓存 " + cmp.Or(strings.TrimSpace(repository.Name), repository.RepositoryID), + Stall: procwatch.DurationEnv(gitwork.CloneStallEnv, 5*time.Minute), StallEnv: gitwork.CloneStallEnv, + Timeout: procwatch.DurationEnv(gitwork.CloneTimeoutEnv, 30*time.Minute), TimeoutEnv: gitwork.CloneTimeoutEnv, + } + if _, err := gitwork.RefreshRepositoryCache(repositoryCtx, root, repository.RepositoryID, remote, watch); err != nil { + warmedRepositoryCaches.Delete(dir) + log.Printf("repository cache %s: %v", repository.RepositoryID, err) + } + } + }() +} + +// dissociateSharedClones copies the borrowed cache objects into each shared +// clone at root or one level below it, so a checkpoint of the workspace +// restores on a machine without that cache. +func dissociateSharedClones(ctx context.Context, root string) error { + dirs := []string{root} + entries, err := os.ReadDir(root) + if err != nil { + return err + } + for _, entry := range entries { + if entry.IsDir() { + dirs = append(dirs, filepath.Join(root, entry.Name())) + } + } + for _, dir := range dirs { + alternates := filepath.Join(dir, ".git", "objects", "info", "alternates") + if info, err := os.Lstat(alternates); err != nil || !info.Mode().IsRegular() { + continue + } + cmd := exec.CommandContext(ctx, "git", "-C", dir, "repack", "-a", "-d", "-q") + cmd.Env = gitwork.WithEnvValue(gitwork.Env(""), "GIT_CONFIG_NOSYSTEM", "1") + if out, err := cmd.CombinedOutput(); err != nil { + return fmt.Errorf("copy repository objects into %s: %w (%s)", filepath.Base(dir), err, strings.TrimSpace(string(out))) + } + if err := os.Remove(alternates); err != nil { + return err + } + } + return nil +} + +// WithRepositoryCacheIn is WithRepositoryCacheFor the driver of sb. +func WithRepositoryCacheIn(ctx context.Context, sb Sandbox) context.Context { + if sb == nil { + return ctx + } + return WithRepositoryCacheFor(ctx, sandboxDriver(sb)) +} diff --git a/internal/runtime/repository_cache_test.go b/internal/runtime/repository_cache_test.go new file mode 100644 index 000000000..fb058740e --- /dev/null +++ b/internal/runtime/repository_cache_test.go @@ -0,0 +1,77 @@ +package runtime + +import ( + "context" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "agentflow/internal/domain" + "agentflow/internal/gitwork" + "agentflow/internal/procwatch" +) + +func TestWithRepositoryCacheForOnlyNativeDrivers(t *testing.T) { + previous := RepositoryCacheRoot() + t.Cleanup(func() { repositoryCacheRoot.Store(previous) }) + SetRepositoryCacheRoot(t.TempDir()) + root := RepositoryCacheRoot() + if filepath.Base(root) != RepositoryCacheDir { + t.Fatalf("cache root = %q", root) + } + for driver, want := range map[string]string{ + domain.SandboxDriverNative: root, domain.SandboxDriverSeatbelt: root, domain.SandboxDriverBwrap: root, + domain.SandboxDriverDocker: "", domain.SandboxDriverLocal: "", "": "", + } { + if got := gitwork.RepositoryCacheFrom(WithRepositoryCacheFor(context.Background(), driver)); got != want { + t.Fatalf("%q workspace cache = %q, want %q", driver, got, want) + } + } +} + +func repositoryCacheTestGit(t *testing.T, dir string, args ...string) string { + t.Helper() + cmd := exec.Command("git", append([]string{"-C", dir}, args...)...) + cmd.Env = append(os.Environ(), "GIT_CONFIG_NOSYSTEM=1", "GIT_AUTHOR_NAME=t", "GIT_AUTHOR_EMAIL=t@example.com", "GIT_COMMITTER_NAME=t", "GIT_COMMITTER_EMAIL=t@example.com") + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("git %v: %v %s", args, err, out) + } + return strings.TrimSpace(string(out)) +} + +// A checkpoint must restore on a machine without this cache, so the shared +// clones in a workspace take their borrowed objects along first. +func TestDissociateSharedClonesCopiesBorrowedObjects(t *testing.T) { + origin := t.TempDir() + repositoryCacheTestGit(t, origin, "init", "-q", "-b", "main") + if err := os.WriteFile(filepath.Join(origin, "a.txt"), []byte("a"), 0o600); err != nil { + t.Fatal(err) + } + repositoryCacheTestGit(t, origin, "add", "a.txt") + repositoryCacheTestGit(t, origin, "commit", "-q", "-m", "a") + head := repositoryCacheTestGit(t, origin, "rev-parse", "HEAD") + cache, workspace := t.TempDir(), t.TempDir() + checkout := filepath.Join(workspace, "service") + if err := os.Mkdir(checkout, 0o700); err != nil { + t.Fatal(err) + } + if err := gitwork.CloneFromRepositoryCache(context.Background(), cache, "service", origin, "", checkout, procwatch.Options{}); err != nil { + t.Fatal(err) + } + if err := dissociateSharedClones(context.Background(), workspace); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(filepath.Join(checkout, ".git", "objects", "info", "alternates")); !os.IsNotExist(err) { + t.Fatalf("alternates kept: %v", err) + } + if err := os.RemoveAll(cache); err != nil { + t.Fatal(err) + } + if got := repositoryCacheTestGit(t, checkout, "rev-parse", "HEAD^{tree}"); got == "" { + t.Fatal("checkout lost its objects") + } + repositoryCacheTestGit(t, checkout, "cat-file", "-e", head) +} diff --git a/internal/runtime/runtime_test.go b/internal/runtime/runtime_test.go index fa7fe334d..96421bf0c 100644 --- a/internal/runtime/runtime_test.go +++ b/internal/runtime/runtime_test.go @@ -355,159 +355,6 @@ func TestCreateDockerRequiresDockerfile(t *testing.T) { } } -func TestPrepareEnvironmentWritesInstallScriptAndPrependsPath(t *testing.T) { - workspace := t.TempDir() - catalog := domain.EnvironmentDefinition{ - ID: "php7.4.33", - Variables: map[string]string{ - "PHP_VERSION": "7.4.33", - "COMPOSER_HOME": "${PREFIX}/composer", - }, - PathEntries: []string{"bin"}, - InstallScript: "mkdir -p \"$PREFIX/bin\"\nprintf '#!/bin/sh\\necho php\\n' > \"$PREFIX/bin/php\"\nchmod +x \"$PREFIX/bin/php\"\n", - } - activated, err := prepareSandboxEnvironment(workspace, domain.SandboxProfile{Driver: "seatbelt", EnvironmentID: "php7.4.33"}, catalog) - if err != nil { - t.Fatal(err) - } - root := filepath.Join(workspace, ".agentflow", "environment", "php7.4.33") - if activated.Overlay[environmentIDVar] != "php7.4.33" || activated.Overlay[environmentRootVar] != root || activated.Overlay[environmentPrefixVar] != root { - t.Fatalf("overlay identity = %+v", activated.Overlay) - } - if activated.Overlay["PHP_VERSION"] != "7.4.33" { - t.Fatalf("catalog variables missing: %+v", activated.Overlay) - } - if activated.Overlay["COMPOSER_HOME"] != filepath.Join(root, "composer") { - t.Fatalf("PREFIX placeholder was not expanded: %+v", activated.Overlay) - } - if !strings.HasPrefix(activated.Overlay["PATH"], filepath.Join(root, "bin")+string(os.PathListSeparator)) { - t.Fatalf("PATH was not prepended with env bin: %q", activated.Overlay["PATH"]) - } - zdot := filepath.Join(root, environmentZdotDir) - if activated.Overlay["ZDOTDIR"] != zdot || activated.Overlay["BASH_ENV"] == "" || activated.Overlay["ENV"] != activated.Overlay["BASH_ENV"] { - t.Fatalf("login-shell hooks missing: %+v", activated.Overlay) - } - for _, name := range []string{".zshenv", ".zprofile", ".zshrc"} { - raw, err := os.ReadFile(filepath.Join(zdot, name)) - if err != nil { - t.Fatal(err) - } - if !strings.Contains(string(raw), filepath.Join(root, "bin")) { - t.Fatalf("%s did not pin env bin: %s", name, raw) - } - } - if _, err := os.Stat(filepath.Join(root, installScriptName)); err != nil { - t.Fatal(err) - } - if activated, err := prepareSandboxEnvironment(workspace, domain.SandboxProfile{Driver: "docker", EnvironmentID: "php7.4.33"}, catalog); err != nil || activated.Overlay != nil { - t.Fatalf("docker should ignore process environments: %v %+v", err, activated) - } -} - -func TestActivateEnvironmentUsesWorkspaceDropInForProcessSandboxes(t *testing.T) { - workspace := t.TempDir() - dropin := filepath.Join(workspace, "agentflow-environment") - if err := os.MkdirAll(filepath.Join(dropin, "bin"), 0o755); err != nil { - t.Fatal(err) - } - if activated, err := prepareSandboxEnvironment(workspace, domain.SandboxProfile{Driver: "local"}, domain.EnvironmentDefinition{}); err != nil || activated.Overlay != nil { - t.Fatalf("local should not auto-activate drop-in: %v %+v", err, activated) - } - activated, err := prepareSandboxEnvironment(workspace, domain.SandboxProfile{Driver: "bwrap"}, domain.EnvironmentDefinition{}) - if err != nil { - t.Fatal(err) - } - if activated.Overlay[environmentIDVar] != workspaceEnvironmentID || activated.Overlay[environmentRootVar] != dropin { - t.Fatalf("bwrap drop-in overlay = %+v", activated.Overlay) - } -} - -func TestLoginZshRePrependsEnvironmentBins(t *testing.T) { - zsh, err := exec.LookPath("zsh") - if err != nil { - t.Skip("zsh is not installed") - } - workspace := t.TempDir() - catalog := domain.EnvironmentDefinition{ID: "golang", PathEntries: []string{"bin", "go/bin"}, InstallScript: "mkdir -p \"$PREFIX/bin\""} - activated, err := prepareSandboxEnvironment(workspace, domain.SandboxProfile{Driver: "seatbelt", EnvironmentID: "golang"}, catalog) - if err != nil { - t.Fatal(err) - } - envBin := filepath.Join(activated.Root, "bin") - cmd := exec.Command(zsh, "-lc", `printf '%s' "$PATH"`) - cmd.Env = []string{ - "PATH=/opt/homebrew/bin:/usr/bin:/bin", - "HOME=" + t.TempDir(), - "ZDOTDIR=" + activated.Overlay["ZDOTDIR"], - "PREFIX=" + activated.Root, - } - out, err := cmd.Output() - if err != nil { - t.Fatal(err) - } - got := string(out) - if !strings.HasPrefix(got, envBin+string(os.PathListSeparator)) && !strings.HasPrefix(got, envBin+":") { - t.Fatalf("login zsh PATH should start with env bin, got %q", got) - } - if i := strings.Index(got, "/opt/homebrew/bin"); i >= 0 { - if strings.Index(got, envBin) > i { - t.Fatalf("homebrew still precedes env bin: %q", got) - } - } -} - -func TestLoginZshWithoutZDOTDIRLosesToUsrBin(t *testing.T) { - zsh, err := exec.LookPath("zsh") - if err != nil { - t.Skip("zsh is not installed") - } - if _, err := os.Stat("/usr/bin/java"); err != nil { - t.Skip("no /usr/bin/java stub") - } - workspace := t.TempDir() - catalog := domain.EnvironmentDefinition{ - ID: "java8", - PathEntries: []string{"bin"}, - InstallScript: "mkdir -p \"$PREFIX/bin\"\nprintf '#!/bin/sh\\necho prefix-java\\n' > \"$PREFIX/bin/java\"\nchmod +x \"$PREFIX/bin/java\"\n", - } - activated, err := prepareSandboxEnvironment(workspace, domain.SandboxProfile{Driver: "seatbelt", EnvironmentID: "java8"}, catalog) - if err != nil { - t.Fatal(err) - } - if err := os.MkdirAll(filepath.Join(activated.Root, "bin"), 0o755); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(filepath.Join(activated.Root, "bin", "java"), []byte("#!/bin/sh\necho prefix-java\n"), 0o755); err != nil { - t.Fatal(err) - } - prefixJava := filepath.Join(activated.Root, "bin", "java") - home := t.TempDir() - path := "/usr/bin" + string(os.PathListSeparator) + filepath.Join(activated.Root, "bin") - without := exec.Command(zsh, "-lc", `command -v java`) - without.Env = []string{"PATH=" + path, "HOME=" + home, "PREFIX=" + activated.Root} - out, err := without.Output() - if err != nil { - t.Fatal(err) - } - if got := strings.TrimSpace(string(out)); got != "/usr/bin/java" && !strings.HasPrefix(got, "/usr/bin/") { - t.Fatalf("login zsh without ZDOTDIR should resolve host java, got %q", got) - } - with := exec.Command(zsh, "-lc", `command -v java`) - with.Env = []string{ - "PATH=" + path, - "HOME=" + home, - "PREFIX=" + activated.Root, - "ZDOTDIR=" + activated.Overlay["ZDOTDIR"], - } - out, err = with.Output() - if err != nil { - t.Fatal(err) - } - if got := strings.TrimSpace(string(out)); got != prefixJava { - t.Fatalf("login zsh with ZDOTDIR should resolve prefix java, got %q", got) - } -} - func TestWithCodexIsolationEnvInsertsSetBeforePrompt(t *testing.T) { argv := []string{"codex", "exec", "-c", `shell_environment_policy.inherit="core"`, "do work"} got := withCodexIsolationEnv(argv, map[string]string{ @@ -559,80 +406,6 @@ func TestExecutorRunnerInjectsCodexZDOTDIR(t *testing.T) { } } -func TestExpandEnvironmentPlaceholders(t *testing.T) { - prefix := "/tmp/env-root" - if got := expandEnvironmentPlaceholders("${PREFIX}/jdk", prefix); got != "/tmp/env-root/jdk" { - t.Fatalf("braced PREFIX = %q", got) - } - if got := expandEnvironmentPlaceholders("$PREFIX/maven", prefix); got != "/tmp/env-root/maven" { - t.Fatalf("plain PREFIX = %q", got) - } - if got := expandEnvironmentPlaceholders("7.4.33", prefix); got != "7.4.33" { - t.Fatalf("literal = %q", got) - } -} - -func phpInstallScript() string { - return `mkdir -p "$PREFIX/bin" -cat > "$PREFIX/bin/php" <<'EOF' -#!/bin/sh -echo php -EOF -chmod +x "$PREFIX/bin/php" -` -} - -func TestLocalSandboxRunsInstallScriptWithoutHostPollution(t *testing.T) { - t.Setenv("PHP_VERSION", "host-php") - manager := NewManager(t.TempDir()) - sandbox, err := manager.AcquireRun(context.Background(), "run-php", domain.SandboxProfile{ID: "local", Driver: "local", EnvironmentID: "php8"}, SandboxRequirements{}, RunCredentials{}, SandboxResources{ - Environment: domain.EnvironmentDefinition{ - ID: "php8", - Variables: map[string]string{"PHP_VERSION": "8.3.0"}, - PathEntries: []string{"bin"}, - InstallScript: phpInstallScript(), - }, - }) - if err != nil { - t.Fatal(err) - } - output, err := sandbox.Exec(context.Background(), CommandSpec{ - Argv: []string{"sh", "-c", `printf '%s|%s|%s' "$PHP_VERSION" "$AGENTFLOW_ENVIRONMENT" "$(php)"`}, - }, nil) - if err != nil { - t.Fatal(err) - } - if got := strings.TrimSpace(output); got != "8.3.0|php8|php" { - t.Fatalf("process environment = %q", got) - } - if os.Getenv("PHP_VERSION") != "host-php" { - t.Fatalf("host PHP_VERSION was mutated: %q", os.Getenv("PHP_VERSION")) - } - root := filepath.Join(sandbox.Workspace(), ".agentflow", "environment", "php8") - if _, err := os.Stat(filepath.Join(root, "bin", "php")); err != nil { - t.Fatal(err) - } - stamp, err := os.ReadFile(filepath.Join(root, installStampName)) - if err != nil || strings.TrimSpace(string(stamp)) == "" { - t.Fatalf("install stamp missing: %s %v", stamp, err) - } - if err := sandbox.Close(context.Background()); err != nil { - t.Fatal(err) - } - again, err := manager.AcquireRun(context.Background(), "run-php", domain.SandboxProfile{ID: "local", Driver: "local", EnvironmentID: "php8"}, SandboxRequirements{}, RunCredentials{}, SandboxResources{ - Environment: domain.EnvironmentDefinition{ - ID: "php8", - Variables: map[string]string{"PHP_VERSION": "8.3.0"}, - PathEntries: []string{"bin"}, - InstallScript: phpInstallScript(), - }, - }) - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { again.Close(context.Background()) }) -} - func TestReservedAgentIDIncludesEnvironmentAndDocker(t *testing.T) { if !reservedAgentID("environment") || !reservedAgentID("docker") { t.Fatal("environment and docker must stay reserved control directories") diff --git a/internal/runtime/sandbox_docker.go b/internal/runtime/sandbox_docker.go index af9f3289d..d66d6234f 100644 --- a/internal/runtime/sandbox_docker.go +++ b/internal/runtime/sandbox_docker.go @@ -10,7 +10,6 @@ import ( "encoding/json" "errors" "fmt" - "log" "os" "os/exec" "path/filepath" @@ -982,7 +981,9 @@ func isolatedRuntimeImage(dockerfile domain.DockerfileDefinition) string { const isolatedDockerfileBase = "FROM node:22-bookworm\nRUN apt-get update && apt-get install -y --no-install-recommends git openssh-client python3 ripgrep ca-certificates curl && rm -rf /var/lib/apt/lists/*\n" const legacyIsolatedDockerfile = isolatedDockerfileBase + "RUN npm install -g @openai/codex @anthropic-ai/claude-code @tencent-ai/codebuddy-code\nWORKDIR /workspace\n" -// IsolatedDockerfile is the fallback for profiles without a custom image. +// IsolatedDockerfile is the platform image recipe. Sandboxes whose Dockerfile +// is this or the seeded generic-docker one (legacyIsolatedDockerfile) run on +// AGENTFLOW_ISOLATED_IMAGE instead of building their own image. const IsolatedDockerfile = isolatedDockerfileBase + "RUN npm install -g @openai/codex @anthropic-ai/claude-code\nARG CODEBUDDY_PACKAGE=@tencent-ai/codebuddy-code\nRUN if [ -n \"$CODEBUDDY_PACKAGE\" ]; then npm install -g \"$CODEBUDDY_PACKAGE\"; fi\nWORKDIR /workspace\n" func isBuiltInIsolatedDockerfile(dockerfile domain.DockerfileDefinition) bool { @@ -995,38 +996,3 @@ func effectiveIsolatedDockerfile(dockerfile domain.DockerfileDefinition) domain. } return dockerfile } - -// PrebuildIsolatedImage warms the shared sandbox image in the background so -// the first SOP on a fresh container install does not wait for the build. -func PrebuildIsolatedImage() { - if strings.TrimSpace(os.Getenv("AGENTFLOW_LOCAL_SANDBOX")) != "docker" || !DockerReady() { - return - } - go func() { - ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute) - defer cancel() - dir, err := os.MkdirTemp("", "agentflow-prebuild-") - if err != nil { - return - } - defer os.RemoveAll(dir) - if _, err := ensureDockerImage(ctx, dir, domain.DockerfileDefinition{ID: "isolated", Content: IsolatedDockerfile}); err != nil { - log.Printf("prebuild sandbox image: %v", err) - } - }() -} - -// isolateLocalDriver runs "local" profiles in Docker when -// AGENTFLOW_LOCAL_SANDBOX=docker, so no SOP command executes inside a platform -// container that can reach the host Docker daemon. -func isolateLocalDriver(profile domain.SandboxProfile, dockerfile domain.DockerfileDefinition) (domain.SandboxProfile, domain.DockerfileDefinition) { - driver := strings.TrimSpace(profile.Driver) - if (driver != "" && driver != "local") || strings.TrimSpace(os.Getenv("AGENTFLOW_LOCAL_SANDBOX")) != "docker" { - return profile, dockerfile - } - profile.Driver = "docker" - if strings.TrimSpace(dockerfile.Content) == "" { - dockerfile = domain.DockerfileDefinition{ID: "generic-backend", Name: "Isolated local sandbox", Content: IsolatedDockerfile} - } - return profile, dockerfile -} diff --git a/internal/runtime/sandbox_driver_ctor_test.go b/internal/runtime/sandbox_driver_ctor_test.go index 4535d761d..2bc215abc 100644 --- a/internal/runtime/sandbox_driver_ctor_test.go +++ b/internal/runtime/sandbox_driver_ctor_test.go @@ -2,44 +2,12 @@ package runtime import ( "context" - "reflect" "strings" "testing" "agentflow/internal/domain" ) -func TestOverlayEnvironmentEmptyOverlayKeepsEnv(t *testing.T) { - env := map[string]string{"A": "1"} - got := overlayEnvironment(env, nil) - if !reflect.DeepEqual(got, env) { - t.Fatalf("overlayEnvironment(env, nil) = %v, want %v", got, env) - } - if got := overlayEnvironment(nil, map[string]string{}); got != nil { - t.Fatalf("empty overlay must keep nil env, got %v", got) - } -} - -func TestOverlayEnvironmentProfileWinsExceptPath(t *testing.T) { - env := map[string]string{"PATH": "/profile/bin", "LANG": "profile", "ONLY_PROFILE": "p"} - overlay := map[string]string{"PATH": "/overlay/bin:/usr/bin", "LANG": "overlay", "ONLY_OVERLAY": "o"} - got := overlayEnvironment(env, overlay) - want := map[string]string{"PATH": "/overlay/bin:/usr/bin", "LANG": "profile", "ONLY_PROFILE": "p", "ONLY_OVERLAY": "o"} - if !reflect.DeepEqual(got, want) { - t.Fatalf("overlayEnvironment = %v, want %v", got, want) - } - if env["PATH"] != "/profile/bin" { - t.Fatalf("input env must not be mutated, got %v", env) - } -} - -func TestOverlayEnvironmentEmptyOverlayPathKeepsProfilePath(t *testing.T) { - got := overlayEnvironment(map[string]string{"PATH": "/profile/bin"}, map[string]string{"PATH": "", "X": "1"}) - if got["PATH"] != "/profile/bin" || got["X"] != "1" { - t.Fatalf("overlayEnvironment = %v", got) - } -} - func TestCreateDriverSandboxLocal(t *testing.T) { workspace := t.TempDir() for _, driver := range []string{"", "local", " local "} { diff --git a/internal/runtime/sandbox_environment.go b/internal/runtime/sandbox_environment.go index bc9604439..982c87f76 100644 --- a/internal/runtime/sandbox_environment.go +++ b/internal/runtime/sandbox_environment.go @@ -1,133 +1,18 @@ package runtime import ( - "context" - "crypto/sha256" - "encoding/hex" "fmt" - "os" "path/filepath" "strings" "agentflow/internal/domain" ) -const ( - workspaceEnvironmentDir = "agentflow-environment" - managedEnvironmentDir = "environment" - environmentIDVar = "AGENTFLOW_ENVIRONMENT" - environmentRootVar = "AGENTFLOW_ENVIRONMENT_ROOT" - environmentPrefixVar = "PREFIX" - workspaceEnvironmentID = "agentflow-environment" - workspaceEnvironmentAlias = "workspace" - installScriptName = "install.sh" - installStampName = ".install-stamp" - environmentZdotDir = "zdot" - environmentBashEnvName = "bashrc" -) - // SandboxResources are catalog assets resolved before a sandbox is opened. -// Docker builds from Dockerfile; process sandboxes activate Environment. +// Docker builds from Dockerfile; native sandboxes need nothing beyond their +// profile's environment variables. type SandboxResources struct { - Dockerfile domain.DockerfileDefinition - Environment domain.EnvironmentDefinition -} - -type activatedEnvironment struct { - Overlay map[string]string - Root string - InstallRel string - InstallScript string -} - -func prepareSandboxEnvironment(workspace string, profile domain.SandboxProfile, catalog domain.EnvironmentDefinition) (activatedEnvironment, error) { - driver := strings.TrimSpace(profile.Driver) - switch driver { - case "docker": - return activatedEnvironment{}, nil - case "", "local": - if strings.TrimSpace(profile.EnvironmentID) == "" && strings.TrimSpace(catalog.ID) == "" { - return activatedEnvironment{}, nil - } - } - envID := strings.TrimSpace(profile.EnvironmentID) - if envID == "" && strings.TrimSpace(catalog.ID) != "" { - envID = strings.TrimSpace(catalog.ID) - } - root := "" - installRel := "" - if strings.TrimSpace(catalog.ID) != "" { - prepared, rel, err := writeEnvironmentInstall(workspace, catalog) - if err != nil { - return activatedEnvironment{}, err - } - root = prepared - installRel = rel - if envID == "" { - envID = strings.TrimSpace(catalog.ID) - } - } - if root == "" { - discovered, ok := discoverEnvironmentRoot(workspace, envID) - if !ok { - if envID != "" && strings.TrimSpace(catalog.ID) == "" { - return activatedEnvironment{}, fmt.Errorf("environment %q not found in catalog or workspace", envID) - } - if envID == "" { - return activatedEnvironment{}, nil - } - return activatedEnvironment{}, fmt.Errorf("environment %q was not prepared", envID) - } - root = discovered - } - overlay, err := environmentOverlay(workspace, root, envID, profile, catalog) - if err != nil { - return activatedEnvironment{}, err - } - return activatedEnvironment{Overlay: overlay, Root: root, InstallRel: installRel, InstallScript: catalog.InstallScript}, nil -} - -// environmentOverlay builds the variables layered over a process sandbox for -// an activated environment rooted at root, writing login-shell PATH hooks into -// the workspace when the environment contributes PATH directories. -func environmentOverlay(workspace, root, envID string, profile domain.SandboxProfile, catalog domain.EnvironmentDefinition) (map[string]string, error) { - id := envID - if id == "" { - id = workspaceEnvironmentID - } - overlay := map[string]string{ - environmentIDVar: id, - environmentRootVar: root, - environmentPrefixVar: root, - } - if strings.TrimSpace(catalog.ID) != "" { - for key, value := range catalog.Variables { - overlay[key] = expandEnvironmentPlaceholders(value, root) - } - } - pathDirs := environmentPathDirs(root, catalog) - basePath := "" - if profile.Environment != nil { - basePath = profile.Environment["PATH"] - } - if basePath == "" { - basePath = os.Getenv("PATH") - } - if len(pathDirs) > 0 { - overlay["PATH"] = strings.Join(append(append([]string{}, pathDirs...), basePath), string(os.PathListSeparator)) - zdot, bashEnv, err := writeEnvironmentShellHooks(workspace, root, pathDirs) - if err != nil { - return nil, err - } - // Codex/Claude tool calls often use `zsh -lc` / `bash -lc`. Login shells - // rebuild PATH (macOS path_helper, ~/.zshrc) and would otherwise hide - // $PREFIX/bin behind Homebrew. ZDOTDIR/BASH_ENV re-prepend after that. - // `.zshenv` covers `zsh -c` without `-l`; `.zprofile` runs after path_helper. - overlay["ZDOTDIR"] = zdot - overlay["BASH_ENV"] = bashEnv - overlay["ENV"] = bashEnv - } - return overlay, nil + Dockerfile domain.DockerfileDefinition } func catalogDirName(id string) (string, error) { @@ -138,142 +23,10 @@ func catalogDirName(id string) (string, error) { return id, nil } -func writeEnvironmentInstall(workspace string, env domain.EnvironmentDefinition) (root, installRel string, err error) { - envID, err := catalogDirName(env.ID) - if err != nil { - return "", "", err - } - root, err = EnsureControlDirectory(workspace, managedEnvironmentDir, envID) - if err != nil { - return "", "", err - } - script := strings.TrimSpace(env.InstallScript) - if script == "" { - return root, "", nil - } - if !strings.HasPrefix(script, "#!") { - script = "#!/bin/sh\n" + script - } - target := filepath.Join(root, installScriptName) - if err := writeManagedFile(workspace, target, []byte(script+"\n"), 0o700); err != nil { - return "", "", err - } - rel := filepath.ToSlash(filepath.Join(".agentflow", managedEnvironmentDir, envID, installScriptName)) - return root, rel, nil -} - -func runEnvironmentInstall(ctx context.Context, sandbox Sandbox, activated activatedEnvironment) error { - if strings.TrimSpace(activated.InstallRel) == "" || strings.TrimSpace(activated.InstallScript) == "" { - return nil - } - workspace := sandbox.Workspace() - stamp := filepath.Join(activated.Root, installStampName) - sum := sha256.Sum256([]byte(activated.InstallScript)) - want := hex.EncodeToString(sum[:]) - current, err := readWorkspaceFile(workspace, stamp) - if err != nil && !os.IsNotExist(err) { - return err - } - if err == nil && strings.TrimSpace(string(current)) == want { - return nil - } - if _, err := sandbox.Exec(ctx, CommandSpec{Argv: []string{"sh", activated.InstallRel}}, nil); err != nil { - return fmt.Errorf("environment install.sh: %w", err) - } - return writeManagedFile(workspace, stamp, []byte(want+"\n"), 0o600) -} - -func discoverEnvironmentRoot(workspace, envID string) (string, bool) { - workspace, err := filepath.Abs(workspace) - if err != nil { - return "", false - } - if name, err := catalogDirName(envID); err == nil { - named := filepath.Join(workspace, ".agentflow", managedEnvironmentDir, name) - if isRealDirectory(named) { - return named, true - } - } - dropin := filepath.Join(workspace, workspaceEnvironmentDir) - if isRealDirectory(dropin) && (envID == "" || envID == workspaceEnvironmentID || envID == workspaceEnvironmentAlias) { - return dropin, true - } - return "", false -} - -func writeEnvironmentShellHooks(workspace, root string, pathDirs []string) (zdot, bashEnv string, err error) { - if root == "" || len(pathDirs) == 0 { - return "", "", nil - } - zdot = filepath.Join(root, environmentZdotDir) - if err := ensureDirectoryNoSymlink(zdot, 0o700); err != nil { - return "", "", err - } - prepend := strings.Join(pathDirs, string(os.PathListSeparator)) - snippet := environmentPathHook(prepend) - for _, name := range []string{".zshenv", ".zprofile", ".zshrc"} { - if err := writeManagedFile(workspace, filepath.Join(zdot, name), []byte(snippet), 0o600); err != nil { - return "", "", err - } - } - bashEnv = filepath.Join(zdot, environmentBashEnvName) - if err := writeManagedFile(workspace, bashEnv, []byte(snippet), 0o600); err != nil { - return "", "", err - } - return zdot, bashEnv, nil -} - -func environmentPathHook(prepend string) string { - return "# AgentFlow: keep isolated bins first after login PATH reset.\n" + - "PATH=" + shellSingleQuote(prepend) + ":${PATH}\n" + - "export PATH\n" -} - func shellSingleQuote(value string) string { return "'" + strings.ReplaceAll(value, "'", `'"'"'`) + "'" } -func environmentPathDirs(root string, catalog domain.EnvironmentDefinition) []string { - seen := map[string]bool{} - var dirs []string - add := func(path string) { - path = filepath.Clean(path) - if path == "" || path == "." || seen[path] { - return - } - seen[path] = true - dirs = append(dirs, path) - } - add(filepath.Join(root, "bin")) - for _, entry := range catalog.PathEntries { - if strings.TrimSpace(entry) == "" { - continue - } - if filepath.IsAbs(entry) { - continue - } - add(filepath.Join(root, filepath.FromSlash(entry))) - } - return dirs -} - -func isRealDirectory(path string) bool { - info, err := os.Lstat(path) - return err == nil && info.Mode()&os.ModeSymlink == 0 && info.IsDir() -} - -func expandEnvironmentPlaceholders(value, prefix string) string { - if prefix == "" || value == "" { - return value - } - return strings.NewReplacer( - "${PREFIX}", prefix, - "${AGENTFLOW_ENVIRONMENT_ROOT}", prefix, - "$PREFIX", prefix, - "$AGENTFLOW_ENVIRONMENT_ROOT", prefix, - ).Replace(value) -} - func mergeEnvironmentMaps(layers ...map[string]string) map[string]string { out := map[string]string{} for _, layer := range layers { diff --git a/internal/runtime/sandbox_environment_overlay_test.go b/internal/runtime/sandbox_environment_overlay_test.go deleted file mode 100644 index 05ff639e2..000000000 --- a/internal/runtime/sandbox_environment_overlay_test.go +++ /dev/null @@ -1,116 +0,0 @@ -package runtime - -import ( - "os" - "path/filepath" - "strings" - "testing" - - "agentflow/internal/domain" -) - -func TestEnvironmentOverlayDefaultsIDAndPrefersProfilePath(t *testing.T) { - workspace := t.TempDir() - root := mkEnvironmentRoot(t, workspace, "agentflow-environment") - profile := domain.SandboxProfile{Driver: "bwrap", Environment: map[string]string{"PATH": "/profile/bin"}} - - overlay, err := environmentOverlay(workspace, root, "", profile, domain.EnvironmentDefinition{}) - if err != nil { - t.Fatal(err) - } - if overlay[environmentIDVar] != workspaceEnvironmentID { - t.Fatalf("empty env id should fall back to %q, got %+v", workspaceEnvironmentID, overlay) - } - if overlay[environmentRootVar] != root || overlay[environmentPrefixVar] != root { - t.Fatalf("root identity = %+v", overlay) - } - want := filepath.Join(root, "bin") + string(os.PathListSeparator) + "/profile/bin" - if overlay["PATH"] != want { - t.Fatalf("PATH = %q, want %q", overlay["PATH"], want) - } - zdot := filepath.Join(root, environmentZdotDir) - if overlay["ZDOTDIR"] != zdot || overlay["BASH_ENV"] != filepath.Join(zdot, environmentBashEnvName) || overlay["ENV"] != overlay["BASH_ENV"] { - t.Fatalf("shell hooks = %+v", overlay) - } - raw, err := os.ReadFile(overlay["BASH_ENV"]) - if err != nil { - t.Fatal(err) - } - if !strings.Contains(string(raw), filepath.Join(root, "bin")) { - t.Fatalf("bash env hook did not pin env bin: %s", raw) - } -} - -func TestEnvironmentOverlayFallsBackToProcessPath(t *testing.T) { - workspace := t.TempDir() - root := mkEnvironmentRoot(t, workspace, "env") - t.Setenv("PATH", "/process/bin") - - overlay, err := environmentOverlay(workspace, root, "custom", domain.SandboxProfile{Driver: "bwrap"}, domain.EnvironmentDefinition{}) - if err != nil { - t.Fatal(err) - } - if overlay[environmentIDVar] != "custom" { - t.Fatalf("explicit env id lost: %+v", overlay) - } - if !strings.HasSuffix(overlay["PATH"], string(os.PathListSeparator)+"/process/bin") { - t.Fatalf("PATH should end with process PATH, got %q", overlay["PATH"]) - } -} - -func TestEnvironmentOverlayCatalogVariablesRequireCatalogID(t *testing.T) { - workspace := t.TempDir() - root := mkEnvironmentRoot(t, workspace, "env") - vars := map[string]string{"COMPOSER_HOME": "${PREFIX}/composer"} - - without, err := environmentOverlay(workspace, root, "php", domain.SandboxProfile{}, domain.EnvironmentDefinition{Variables: vars}) - if err != nil { - t.Fatal(err) - } - if _, ok := without["COMPOSER_HOME"]; ok { - t.Fatalf("catalog variables without catalog id should be ignored: %+v", without) - } - - with, err := environmentOverlay(workspace, root, "php", domain.SandboxProfile{}, domain.EnvironmentDefinition{ID: "php", Variables: vars, PathEntries: []string{"sbin", "/abs/ignored", "sbin"}}) - if err != nil { - t.Fatal(err) - } - if with["COMPOSER_HOME"] != filepath.Join(root, "composer") { - t.Fatalf("PREFIX placeholder was not expanded: %+v", with) - } - prefix := filepath.Join(root, "bin") + string(os.PathListSeparator) + filepath.Join(root, "sbin") + string(os.PathListSeparator) - if !strings.HasPrefix(with["PATH"], prefix) { - t.Fatalf("PATH = %q, want prefix %q", with["PATH"], prefix) - } -} - -func TestEnvironmentOverlayPropagatesShellHookError(t *testing.T) { - workspace := t.TempDir() - root := mkEnvironmentRoot(t, workspace, "env") - // A regular file where the zdot hook directory belongs makes - // writeEnvironmentShellHooks fail; the overlay must surface that error - // instead of returning a PATH without the login-shell hooks. - if err := os.WriteFile(filepath.Join(root, environmentZdotDir), []byte("not a dir"), 0o600); err != nil { - t.Fatal(err) - } - - overlay, err := environmentOverlay(workspace, root, "env", domain.SandboxProfile{}, domain.EnvironmentDefinition{}) - if err == nil { - t.Fatalf("expected shell hook error, got overlay %+v", overlay) - } - if !strings.Contains(err.Error(), "not a real directory") { - t.Fatalf("unexpected error: %v", err) - } - if overlay != nil { - t.Fatalf("overlay should be nil on error, got %+v", overlay) - } -} - -func mkEnvironmentRoot(t *testing.T, workspace, name string) string { - t.Helper() - root := filepath.Join(workspace, name) - if err := os.MkdirAll(root, 0o755); err != nil { - t.Fatal(err) - } - return root -} diff --git a/internal/runtime/sandbox_environment_prepare_overlay_test.go b/internal/runtime/sandbox_environment_prepare_overlay_test.go deleted file mode 100644 index 91de3cd45..000000000 --- a/internal/runtime/sandbox_environment_prepare_overlay_test.go +++ /dev/null @@ -1,56 +0,0 @@ -package runtime - -import ( - "os" - "path/filepath" - "strings" - "testing" - - "agentflow/internal/domain" -) - -// blockEnvironmentZdot puts a regular file where the login-shell hook -// directory goes, so writing the PATH hooks fails. -func blockEnvironmentZdot(t *testing.T, root string) { - t.Helper() - if err := os.WriteFile(filepath.Join(root, environmentZdotDir), []byte("not a dir"), 0o600); err != nil { - t.Fatal(err) - } -} - -// prepareSandboxEnvironment must surface the overlay error instead of -// activating the environment with a partial or missing overlay. -func TestPrepareSandboxEnvironmentPropagatesOverlayError(t *testing.T) { - workspace := t.TempDir() - root := mkEnvironmentRoot(t, workspace, workspaceEnvironmentDir) - blockEnvironmentZdot(t, root) - - activated, err := prepareSandboxEnvironment(workspace, domain.SandboxProfile{Driver: "bwrap"}, domain.EnvironmentDefinition{}) - if err == nil || !strings.Contains(err.Error(), "not a real directory") { - t.Fatalf("err = %v, want shell hook directory error", err) - } - if activated.Overlay != nil || activated.Root != "" || activated.InstallRel != "" { - t.Fatalf("activated on error = %+v, want zero value", activated) - } -} - -// The drop-in environment discovered in the workspace is activated with the -// overlay environmentOverlay built for that root. -func TestPrepareSandboxEnvironmentActivatesDiscoveredDropIn(t *testing.T) { - workspace := t.TempDir() - root := mkEnvironmentRoot(t, workspace, workspaceEnvironmentDir) - - activated, err := prepareSandboxEnvironment(workspace, domain.SandboxProfile{Driver: "bwrap", Environment: map[string]string{"PATH": "/profile/bin"}}, domain.EnvironmentDefinition{}) - if err != nil { - t.Fatal(err) - } - if activated.Root != root || activated.InstallRel != "" { - t.Fatalf("activated = %+v, want root %q", activated, root) - } - if activated.Overlay[environmentIDVar] != workspaceEnvironmentID || activated.Overlay[environmentRootVar] != root { - t.Fatalf("overlay identity = %+v", activated.Overlay) - } - if want := filepath.Join(root, "bin") + string(os.PathListSeparator) + "/profile/bin"; activated.Overlay["PATH"] != want { - t.Fatalf("PATH = %q, want %q", activated.Overlay["PATH"], want) - } -} diff --git a/internal/runtime/sandbox_isolation_test.go b/internal/runtime/sandbox_isolation_test.go deleted file mode 100644 index e6f1376a6..000000000 --- a/internal/runtime/sandbox_isolation_test.go +++ /dev/null @@ -1,27 +0,0 @@ -package runtime - -import ( - "agentflow/internal/domain" - "testing" -) - -func TestLocalDriverRunsInDockerWhenIsolated(t *testing.T) { - custom := domain.DockerfileDefinition{ID: "custom", Content: "FROM alpine\n"} - t.Setenv("AGENTFLOW_LOCAL_SANDBOX", "") - if p, _ := isolateLocalDriver(domain.SandboxProfile{Driver: "local"}, domain.DockerfileDefinition{}); p.Driver != "local" { - t.Fatalf("native installs keep local execution: %q", p.Driver) - } - t.Setenv("AGENTFLOW_LOCAL_SANDBOX", "docker") - for _, driver := range []string{"", "local"} { - p, d := isolateLocalDriver(domain.SandboxProfile{Driver: driver}, domain.DockerfileDefinition{}) - if p.Driver != "docker" || d.Content != IsolatedDockerfile { - t.Fatalf("driver %q: %+v %+v", driver, p, d) - } - } - if _, d := isolateLocalDriver(domain.SandboxProfile{}, custom); d.ID != "custom" || d.Content != custom.Content { - t.Fatal("a configured Dockerfile is kept") - } - if p, _ := isolateLocalDriver(domain.SandboxProfile{Driver: "bwrap"}, domain.DockerfileDefinition{}); p.Driver != "bwrap" { - t.Fatal("explicit isolation drivers are unchanged") - } -} diff --git a/internal/runtime/sandbox_manager.go b/internal/runtime/sandbox_manager.go index e201db49d..c636f84cb 100644 --- a/internal/runtime/sandbox_manager.go +++ b/internal/runtime/sandbox_manager.go @@ -91,22 +91,11 @@ func (m *Manager) open(ctx context.Context, id, dir string, profile domain.Sandb if err := os.MkdirAll(workspace, 0o700); err != nil { return fail(err) } - activated, err := prepareSandboxEnvironment(workspace, profile, resources.Environment) - if err != nil { - return fail(err) - } - profile.Environment = overlayEnvironment(profile.Environment, activated.Overlay) - profile, resources.Dockerfile = isolateLocalDriver(profile, resources.Dockerfile) sandbox, err := createDriverSandbox(ctx, "sandbox", id, workspace, profile, requirements, resources.Dockerfile) if err != nil { return fail(err) } - managed := &managedSandbox{Sandbox: sandbox, slots: m.slots, lock: lock, ephemeral: ephemeral, workspace: workspace, credentials: credentials} - if err := runEnvironmentInstall(ctx, managed, activated); err != nil { - _ = managed.Close(ctx) - return nil, err - } - return managed, nil + return &managedSandbox{Sandbox: sandbox, slots: m.slots, lock: lock, ephemeral: ephemeral, workspace: workspace, credentials: credentials}, nil } // DestroyRun deletes the host workspace for a finished SOP run: the persistent @@ -454,20 +443,6 @@ func (s *managedSandbox) Exec(ctx context.Context, command CommandSpec, sink Eve return redactRunGitSecrets(out, credentials), err } -// overlayEnvironment layers an activated environment's overlay under env, -// except PATH: the overlay's PATH wins so its tools stay first on the path. -// An empty overlay returns env unchanged. -func overlayEnvironment(env, overlay map[string]string) map[string]string { - if len(overlay) == 0 { - return env - } - merged := mergeEnvironmentMaps(overlay, env) - if path := overlay["PATH"]; path != "" { - merged["PATH"] = path - } - return merged -} - // createDriverSandbox builds the sandbox for profile.Driver. kind only names // the caller in the unsupported-driver error. func createDriverSandbox(ctx context.Context, kind, id, workspace string, profile domain.SandboxProfile, requirements SandboxRequirements, dockerfile domain.DockerfileDefinition) (Sandbox, error) { diff --git a/internal/runtime/sandbox_process.go b/internal/runtime/sandbox_process.go index 0f4a77ac2..91dc71e0d 100644 --- a/internal/runtime/sandbox_process.go +++ b/internal/runtime/sandbox_process.go @@ -16,6 +16,7 @@ import ( "syscall" "agentflow/internal/domain" + "agentflow/internal/gitwork" ) func appendEnvironment(base []string, overlays ...map[string]string) []string { @@ -186,6 +187,9 @@ func (s *processSandbox) command(ctx context.Context, command CommandSpec, base } cmd.Dir = s.workspace cmd.Env = appendEnvironment(base, s.profile.Environment, command.environment) + if cache := RepositoryCacheRoot(); cache != "" { + cmd.Env = upsertEnv(cmd.Env, gitwork.RepositoryCacheEnv, cache) + } cmd.Stdin = command.Stdin if command.WorkingDir != "" { cmd.Env = upsertEnv(cmd.Env, "PWD", command.WorkingDir) @@ -502,12 +506,18 @@ func bwrapArgsCommand(workspace string, requirements SandboxRequirements) ([]str "--die-with-parent", "--new-session", "--unshare-user", "--unshare-pid", "--unshare-ipc", "--unshare-uts", "--ro-bind", "/", "/", + // The private /tmp comes before the workspace bind, or it would hide a + // workspace under the host /tmp. + "--tmpfs", "/tmp", "--bind", root, root, "--chdir", root, - "--tmpfs", "/tmp", "--proc", "/proc", "--dev-bind", "/dev", "/dev", } + if cache := RepositoryCacheRoot(); cache != "" { + // Shared clones read their objects here, even below the private /tmp. + args = append(args, "--ro-bind-try", cache, cache) + } if conversation := requirements.ConversationRoot; conversation != "" { // Same layout as the Docker workspace: the native CLI keeps its HOME // and cwd (/ws, here the run workspace) across both modes. diff --git a/internal/runtime/workspace_checkpoint.go b/internal/runtime/workspace_checkpoint.go index 78d607d65..a30bf5a70 100644 --- a/internal/runtime/workspace_checkpoint.go +++ b/internal/runtime/workspace_checkpoint.go @@ -117,6 +117,9 @@ func CreateWorkspaceCheckpointToContext(ctx context.Context, root string, destin if !info.IsDir() { return fmt.Errorf("workspace is not a directory") } + if err := dissociateSharedClones(ctx, root); err != nil { + return err + } base, err := os.OpenRoot(root) if err != nil { return err diff --git a/internal/schedule/service_test.go b/internal/schedule/service_test.go index eed38060d..e3239f86c 100644 --- a/internal/schedule/service_test.go +++ b/internal/schedule/service_test.go @@ -654,7 +654,7 @@ func TestDispatchIsSerializedAcrossJobs(t *testing.T) { t.Fatal(err) } t.Cleanup(st.Close) - wf := domain.WorkflowDefinition{ID: "wf", ProjectID: "platform", Name: "wf", Version: 1, SandboxProfileID: "local", Nodes: []domain.WorkflowNode{{ID: "n", Name: "n", Type: "approval", MaxAttempts: 1}}} + wf := domain.WorkflowDefinition{ID: "wf", ProjectID: "platform", Name: "wf", Version: 1, SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "n", Name: "n", Type: "approval", MaxAttempts: 1}}} if err := st.PutWorkflow(wf); err != nil { t.Fatal(err) } diff --git a/migrations/041_native_sandbox_inline_assets.sql b/migrations/041_native_sandbox_inline_assets.sql new file mode 100644 index 000000000..963814b0e --- /dev/null +++ b/migrations/041_native_sandbox_inline_assets.sql @@ -0,0 +1,153 @@ +-- Manual, idempotent MySQL migration: sandboxes carry their own Dockerfile, +-- native replaces local, and environment install scripts are gone. +-- +-- A docker sandbox now stores payload.dockerfile {content, files}; a native +-- sandbox (seatbelt / bwrap) only has environment variables and uses the +-- toolchains of the machine it runs on. dockerfileId, environmentId and +-- install are gone, and so are the dockerfiles and environments tables with +-- their API. The local sandbox type is removed. +-- +-- 1. Each docker sandbox copies the Dockerfile it referenced. +-- 2. A Dockerfile no docker sandbox used becomes a docker sandbox, keeping its +-- name, project and sharing. It keeps the Dockerfile ID when available, then +-- tries a "-docker" suffix and finally a derived ID if the suffix is taken. +-- 3. Each local sandbox becomes a native sandbox: its execution machine, +-- checkout directory and repository paths are dropped, and it keeps its +-- environment variables. +-- 4. Install scripts, the environments they came from and PATH in native +-- sandbox variables are dropped. A native sandbox runs commands with the +-- execution machine's own PATH. +-- 5. The built-in SOPs that used the old shared local profile move to +-- generic-docker, and a 「对话工作区」 preference for local becomes native. +-- 6. The legacy tables are dropped. +-- +-- Missing legacy tables are treated as empty so the migration can be repeated. +-- Docker images are keyed by the Dockerfile content and are reused. +-- Apply manually to existing databases before starting the upgraded platform. +-- For Compose, use ./start.sh migrate-sandboxes with the old platform stopped. + +SET NAMES utf8mb4; + +CREATE TABLE IF NOT EXISTS dockerfiles ( + `id` varchar(64) NOT NULL, + `name` varchar(255) DEFAULT NULL, + `payload` json DEFAULT NULL, + `updated_at` datetime(3) DEFAULT NULL, + PRIMARY KEY (`id`) +) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE IF NOT EXISTS environments ( + `id` varchar(64) NOT NULL, + `name` varchar(255) DEFAULT NULL, + `payload` json DEFAULT NULL, + `updated_at` datetime(3) DEFAULT NULL, + PRIMARY KEY (`id`) +) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- Keep the additive DDL outside the data transaction. Startup AutoMigrate +-- also adds this column. Older schemas may have no preference table. +SET @assistant_preferences_exists = EXISTS ( + SELECT 1 FROM information_schema.tables + WHERE table_schema = DATABASE() AND table_name = 'assistant_preferences'); +SET @assistant_workspace_driver_sql = IF( + @assistant_preferences_exists AND NOT EXISTS ( + SELECT 1 FROM information_schema.columns + WHERE table_schema = DATABASE() AND table_name = 'assistant_preferences' AND column_name = 'workspace_driver'), + 'ALTER TABLE assistant_preferences ADD COLUMN workspace_driver VARCHAR(16) NOT NULL DEFAULT ''''', + 'DO 0'); +PREPARE assistant_workspace_driver_stmt FROM @assistant_workspace_driver_sql; +EXECUTE assistant_workspace_driver_stmt; +DEALLOCATE PREPARE assistant_workspace_driver_stmt; + +START TRANSACTION; + +-- The openssh-client fix of 031, for installs that copy an unmodified +-- generic-backend Dockerfile. +UPDATE dockerfiles +SET payload = JSON_SET(payload, '$.content', 'FROM node:22-bookworm\nRUN apt-get update && apt-get install -y --no-install-recommends git openssh-client python3 ripgrep ca-certificates curl && rm -rf /var/lib/apt/lists/*\nRUN npm install -g @openai/codex @anthropic-ai/claude-code @tencent-ai/codebuddy-code\nWORKDIR /workspace\n') +WHERE id = 'generic-backend' + AND JSON_UNQUOTE(JSON_EXTRACT(payload, '$.content')) = 'FROM node:22-bookworm\nRUN apt-get update && apt-get install -y --no-install-recommends git python3 ripgrep ca-certificates curl && rm -rf /var/lib/apt/lists/*\nRUN npm install -g @openai/codex @anthropic-ai/claude-code @tencent-ai/codebuddy-code\nWORKDIR /workspace\n'; + +-- 1. Copy referenced Dockerfiles into their sandboxes. +UPDATE sandboxes s +JOIN dockerfiles d + ON d.id = JSON_UNQUOTE(JSON_EXTRACT(s.payload, '$.dockerfileId')) COLLATE utf8mb4_unicode_ci +SET s.payload = JSON_SET(s.payload, '$.dockerfile', JSON_MERGE_PATCH( + JSON_OBJECT('content', COALESCE(JSON_UNQUOTE(JSON_EXTRACT(d.payload, '$.content')), '')), + JSON_OBJECT('files', JSON_EXTRACT(d.payload, '$.files')))) +WHERE JSON_UNQUOTE(JSON_EXTRACT(s.payload, '$.driver')) = 'docker' + AND JSON_EXTRACT(s.payload, '$.dockerfile') IS NULL; + +-- 2. Wrap unused Dockerfiles as sandboxes of their own. +INSERT INTO sandboxes (`id`, `name`, `payload`) +SELECT w.sid, d.name, JSON_MERGE_PATCH( + JSON_OBJECT('id', w.sid, 'name', d.name, 'driver', 'docker', 'readOnlyRootFS', false, + 'dockerfile', JSON_MERGE_PATCH( + JSON_OBJECT('content', COALESCE(JSON_UNQUOTE(JSON_EXTRACT(d.payload, '$.content')), '')), + JSON_OBJECT('files', JSON_EXTRACT(d.payload, '$.files')))), + JSON_OBJECT('projectId', JSON_EXTRACT(d.payload, '$.projectId')), + JSON_OBJECT('shared', IF(JSON_EXTRACT(d.payload, '$.shared') = true, CAST('true' AS JSON), NULL))) +FROM dockerfiles d +JOIN ( + SELECT legacy.id AS did, + CASE + WHEN NOT EXISTS (SELECT 1 FROM sandboxes s WHERE s.id = legacy.id COLLATE utf8mb4_unicode_ci) + THEN legacy.id + WHEN CHAR_LENGTH(legacy.id) <= 57 + AND NOT EXISTS (SELECT 1 FROM sandboxes s WHERE s.id = CONCAT(legacy.id, '-docker') COLLATE utf8mb4_unicode_ci) + AND NOT EXISTS (SELECT 1 FROM dockerfiles d WHERE d.id = CONCAT(legacy.id, '-docker') COLLATE utf8mb4_unicode_ci) + THEN CONCAT(legacy.id, '-docker') + ELSE CONCAT('dockerfile-', LEFT(SHA2(legacy.id, 256), 53)) + END AS sid + FROM dockerfiles legacy +) w ON w.did = d.id +WHERE NOT EXISTS ( + SELECT 1 FROM sandboxes s + WHERE JSON_UNQUOTE(JSON_EXTRACT(s.payload, '$.driver')) = 'docker' + AND JSON_UNQUOTE(JSON_EXTRACT(s.payload, '$.dockerfileId')) COLLATE utf8mb4_unicode_ci = d.id +); + +-- 3. Local sandboxes become native sandboxes. +UPDATE sandboxes +SET payload = JSON_SET(JSON_REMOVE(payload, '$.runnerId', '$.baseDir', '$.repositoryPaths'), + '$.driver', 'native', '$.readOnlyRootFS', false) +WHERE JSON_UNQUOTE(JSON_EXTRACT(payload, '$.driver')) = 'local'; + +-- 4. Drop install scripts and PATH overrides of native sandboxes. +UPDATE sandboxes +SET payload = JSON_REMOVE(payload, '$.environment.PATH') +WHERE JSON_UNQUOTE(JSON_EXTRACT(payload, '$.driver')) IN ('native', 'seatbelt', 'bwrap') + AND JSON_CONTAINS_PATH(payload, 'one', '$.environment.PATH'); + +UPDATE sandboxes +SET payload = JSON_REMOVE(payload, '$.install') +WHERE JSON_CONTAINS_PATH(payload, 'one', '$.install'); + +UPDATE sandboxes +SET payload = JSON_REMOVE(payload, '$.dockerfileId') +WHERE JSON_CONTAINS_PATH(payload, 'one', '$.dockerfileId'); + +UPDATE sandboxes +SET payload = JSON_REMOVE(payload, '$.environmentId') +WHERE JSON_CONTAINS_PATH(payload, 'one', '$.environmentId'); + +-- 5. Built-in SOPs and the 「对话工作区」 preference leave local. +UPDATE workflows +SET payload = JSON_SET(payload, '$.sandboxProfileId', 'generic-docker') +WHERE id IN ('welcome-workflow', 'scheduled-baseline-align') + AND COALESCE(JSON_UNQUOTE(JSON_EXTRACT(payload, '$.sandboxProfileId')), '') IN ('', 'local'); + +SET @assistant_workspace_driver_sql = IF(@assistant_preferences_exists, + 'UPDATE assistant_preferences SET workspace_driver = ''native'' WHERE workspace_driver = ''local''', + 'DO 0'); +PREPARE assistant_workspace_driver_stmt FROM @assistant_workspace_driver_sql; +EXECUTE assistant_workspace_driver_stmt; +DEALLOCATE PREPARE assistant_workspace_driver_stmt; + +-- Mark the Dockerfiles as copied in the same transaction as the new payloads. +-- A retry after COMMIT but before DROP will not make a sandbox for them again. +DELETE FROM dockerfiles; +COMMIT; + +-- 6. Drop the legacy tables. +DROP TABLE IF EXISTS dockerfiles, environments; diff --git a/migrations/seed/001_public_catalog.sql b/migrations/seed/001_public_catalog.sql index 2fcaa5483..ad1e7e65e 100644 --- a/migrations/seed/001_public_catalog.sql +++ b/migrations/seed/001_public_catalog.sql @@ -2,14 +2,12 @@ -- INSERT IGNORE preserves operator-edited definitions. SET NAMES utf8mb4; START TRANSACTION; -INSERT IGNORE INTO sandboxes (`id`,`name`,`payload`) VALUES ('local','本地执行(仅可信任务)','{"id":"local","name":"本地执行(仅可信任务)","driver":"local"}'); -INSERT IGNORE INTO sandboxes (`id`,`name`,`payload`) VALUES ('generic-docker','Docker 隔离沙箱','{"id":"generic-docker","name":"Docker 隔离沙箱","shared":true,"driver":"docker","dockerfileId":"generic-backend","readOnlyRootFS":false}'); -INSERT IGNORE INTO dockerfiles (`id`,`name`,`payload`) VALUES ('generic-backend','公共开发环境','{"id":"generic-backend","name":"公共开发环境","shared":true,"content":"FROM node:22-bookworm\\nRUN apt-get update && apt-get install -y --no-install-recommends git openssh-client python3 ripgrep ca-certificates curl && rm -rf /var/lib/apt/lists/*\\nRUN npm install -g @openai/codex @anthropic-ai/claude-code @tencent-ai/codebuddy-code\\nWORKDIR /workspace\\n"}'); +INSERT IGNORE INTO sandboxes (`id`,`name`,`payload`) VALUES ('generic-docker','Docker 隔离沙箱','{"id":"generic-docker","name":"Docker 隔离沙箱","shared":true,"driver":"docker","readOnlyRootFS":false,"dockerfile":{"content":"FROM node:22-bookworm\\nRUN apt-get update && apt-get install -y --no-install-recommends git openssh-client python3 ripgrep ca-certificates curl && rm -rf /var/lib/apt/lists/*\\nRUN npm install -g @openai/codex @anthropic-ai/claude-code @tencent-ai/codebuddy-code\\nWORKDIR /workspace\\n"}}'); INSERT IGNORE INTO rules (`id`,`name`,`payload`) VALUES ('public-engineering','工程与验证约束','{"version":1,"updatedAt":"2026-10-15T00:00:00Z","id":"public-engineering","name":"工程与验证约束","shared":true,"priority":100,"content":"先阅读仓库约束并明确范围;只修改任务所需文件。不得泄露凭据,不得伪造测试或交付证据。使用项目现有构建与测试命令,报告真实结果与限制。发布 PR 前检查 diff;未经任务授权不得合并主分支。"}'); INSERT IGNORE INTO generic_templates (id,name,payload,updated_at) VALUES ('generic-backend-delivery','通用后端交付 SOP','{"Workflow": {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-backend-delivery", "name": "通用后端交付 SOP", "revision": 1, "status": "published", "description": "后端需求从需求定型到独立评审与交付。", "sandboxProfileId": "generic-docker", "generic": true, "owner": "LoopForge", "tags": ["public"], "nodes": [{"id": "clarify", "name": "需求定型", "type": "agent", "agentId": "generic-backend-delivery-clarify", "maxAttempts": 2, "position": {"x": 100, "y": 150}, "artifactOutputs": [{"name": "clarify", "path": "requirement.md", "mediaType": "text/markdown", "required": true}]}, {"id": "design", "name": "方案设计", "type": "agent", "agentId": "generic-backend-delivery-design", "maxAttempts": 2, "position": {"x": 345, "y": 150}, "artifactOutputs": [{"name": "design", "path": "design.md", "mediaType": "text/markdown", "required": true}]}, {"id": "implement", "name": "开发实现", "type": "agent", "agentId": "generic-backend-delivery-implement", "maxAttempts": 2, "position": {"x": 590, "y": 150}, "artifactOutputs": [{"name": "implement", "path": "implementation.md", "mediaType": "text/markdown", "required": true}]}, {"id": "review", "name": "独立评审", "type": "agent", "agentId": "generic-backend-delivery-review", "maxAttempts": 2, "position": {"x": 835, "y": 150}, "artifactOutputs": [{"name": "review", "path": "review.md", "mediaType": "text/markdown", "required": true}]}, {"id": "test", "name": "测试验证", "type": "agent", "agentId": "generic-backend-delivery-test", "maxAttempts": 2, "position": {"x": 1080, "y": 150}, "artifactOutputs": [{"name": "test", "path": "test-report.md", "mediaType": "text/markdown", "required": true}]}, {"id": "accept", "name": "人工验收", "type": "approval", "maxAttempts": 1, "rejectTo": "implement", "position": {"x": 1325, "y": 150}}, {"id": "deliver", "name": "交付汇总", "type": "agent", "agentId": "generic-backend-delivery-deliver", "maxAttempts": 2, "position": {"x": 1815, "y": 150}, "artifactOutputs": [{"name": "deliver", "path": "delivery.md", "mediaType": "text/markdown", "required": true}]}, {"id": "mr", "name": "发起 MR", "type": "agent", "agentId": "generic-backend-delivery-mr", "maxAttempts": 2, "position": {"x": 1570, "y": 150}, "artifactOutputs": [{"name": "mr-body", "path": "mr-body.md", "mediaType": "text/markdown", "required": true}]}], "edges": [{"id": "e-0", "source": "clarify", "target": "design", "when": "success"}, {"id": "e-1", "source": "design", "target": "implement", "when": "success"}, {"id": "e-2", "source": "implement", "target": "review", "when": "success"}, {"id": "e-3", "source": "review", "target": "test", "when": "success"}, {"id": "e-4", "source": "test", "target": "accept", "when": "success"}, {"id": "e-5", "source": "accept", "target": "mr", "when": "success"}, {"id": "e-6", "source": "mr", "target": "deliver", "when": "success"}]}, "Agents": [{"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-backend-delivery-clarify", "name": "需求定型", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:后端服务、数据与 API。确认目标、范围、用户、边界与可测试验收标准,输出 requirement.md。不要开始编码。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-backend-delivery-design", "name": "方案设计", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:后端服务、数据与 API。阅读已确认需求与可用代码,写出最小实现方案、接口影响、风险与验证计划到 design.md。未绑定仓库的新项目可在任务工作区设计和实现;修改已有系统或修复缺陷时必须取得相关源码,缺少时明确阻塞并请求补充。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-backend-delivery-implement", "name": "开发实现", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:后端服务、数据与 API。依据 requirement.md 和 design.md 实现需求,保持范围最小;执行适用验证,记录实现、改动和验证到 implementation.md。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-backend-delivery-review", "name": "独立评审", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:后端服务、数据与 API。独立审查改动及测试证据;按严重程度列出有位置与影响的缺陷及修复建议到 review.md。发现阻断问题必须明确写出 REJECT。不得伪造通过结论。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-backend-delivery-test", "name": "测试验证", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:后端服务、数据与 API。根据验收标准执行项目真实测试、构建及必要端到端场景。必要时修复问题并复测。将命令、退出码、结果、未验证范围写到 test-report.md。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-backend-delivery-deliver", "name": "交付汇总", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:后端服务、数据与 API。核对各阶段实际产物与验证证据,将完成内容、真实测试结果、已知限制及交付物清单写到 delivery.md。未绑定仓库时交付任务工作区中的源码和报告,无需 Git Token。代码已由「发起 MR」节点提交、推送并创建 MR/PR:按 mr-body.md 把链接、分支和提交 SHA 写进交付物清单;本节点不再修改代码、推送或创建 PR,不得合并。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-11-16T00:00:00Z", "id": "generic-backend-delivery-mr", "name": "发起 MR", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:后端服务、数据与 API。人工验收已通过,本节点把本轮代码改动提交到工作分支、推送并发起 MR/PR,不再修改业务逻辑。\\n\\n1. 未绑定代码仓库时不推送、不创建 MR/PR:在 mr-body.md 写明「未绑定代码仓库,源码保留在任务工作区」并列出交付文件,然后提交 pass。\\n2. 已绑定仓库时逐个处理每个仓库检出目录,本轮没有改动的仓库跳过,不创建空 MR/PR:确认当前在本轮工作分支上,不得在主分支提交,也不得切换或新建分支;检查 git status 与 diff,只提交本任务相关的源码改动,不提交 .agentflow、依赖目录、构建产物和 SOP 阶段文档;用概括本次改动的提交信息 commit,再 git push -u origin 当前工作分支。平台已注入 Git 凭据,不得打印、回显或写入任何令牌。\\n3. 以仓库上下文中的目标分支为目标创建 MR/PR:使用托管平台的 CLI(如 gh、glab)或已配置的 MCP,也可查阅该平台官方 API。调用 API 需要令牌时,用 git credential fill 按仓库主机获取,只在进程内存中使用。本轮工作分支已有指向同一目标分支的 MR/PR 时更新它,不重复创建。\\n4. 标题概括本次改动;描述写需求摘要、改动要点、测试结果(依据 test-report.md)和已知限制。不得合并 MR/PR,不得推送主分支或强推。\\n5. 把每个仓库的 MR/PR 链接、源分支、目标分支和提交 SHA 写到 mr-body.md。\\n6. 推送或创建 MR/PR 失败(缺少凭据、无权限、网络错误等)时不得提交 pass:在 mr-body.md 记录失败原因,提交 human,并在 actionRequired 写明需要人工处理什么,例如配置 Git Token 后重试,或到托管平台手动创建 MR。\\n\\nMR 约束:{{existingMR}}\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}", "loop": {"enabled": true, "maxIterations": 2, "exitCondition": "all_gates_pass", "onExhausted": "human"}, "verification": [{"id": "mr-pushed", "name": "改动已提交并推送", "mode": "command", "stage": "after_execution", "commands": ["fail=0\\ntab=\\"$(printf ''\\\\t'')\\"\\nwhile IFS=\\"$tab\\" read -r d work base; do\\n [ -n \\"$d\\" ] || continue\\n dirty=\\"$(git -C \\"$d\\" status --porcelain --untracked-files=all -- . \\":(exclude).agentflow\\" \\":(exclude,glob)**/node_modules/**\\")\\" || { printf \\"%s 不是可用的 Git 检出目录\\\\n\\" \\"$d\\"; fail=1; continue; }\\n if [ -n \\"$dirty\\" ]; then printf \\"%s 有未提交的改动:\\\\n%s\\\\n\\" \\"$d\\" \\"$dirty\\"; fail=1; continue; fi\\n refs=HEAD\\n if git -C \\"$d\\" rev-parse -q --verify \\"refs/heads/$work\\" >/dev/null; then refs=\\"HEAD refs/heads/$work\\"; fi\\n ahead=\\"$(git -C \\"$d\\" rev-list --count $refs --not \\"refs/remotes/origin/$base\\")\\" || { printf \\"%s 找不到目标分支 origin/%s\\\\n\\" \\"$d\\" \\"$base\\"; fail=1; continue; }\\n [ \\"$ahead\\" != 0 ] || continue\\n branch=\\"$(git -C \\"$d\\" branch --show-current)\\"\\n if [ \\"$branch\\" != \\"$work\\" ]; then printf \\"%s 当前在 %s,不在本轮工作分支 %s\\\\n\\" \\"$d\\" \\"${branch:-分离的 HEAD}\\" \\"$work\\"; fail=1; continue; fi\\n head=\\"$(git -C \\"$d\\" rev-parse HEAD)\\"\\n pushed=\\"$(git -C \\"$d\\" ls-remote origin \\"refs/heads/$work\\")\\" || { printf \\"%s 无法读取远端 origin\\\\n\\" \\"$d\\"; fail=1; continue; }\\n if [ \\"${pushed%%\\"$tab\\"*}\\" != \\"$head\\" ]; then printf \\"%s 的工作分支 %s 在 origin 上不是 %s,本轮提交还没推送\\\\n\\" \\"$d\\" \\"$work\\" \\"$head\\"; fail=1; fi\\ndone </dev/null; then refs=\\"HEAD refs/heads/$work\\"; fi\\n ahead=\\"$(git -C \\"$d\\" rev-list --count $refs --not \\"refs/remotes/origin/$base\\")\\" || { printf \\"%s 找不到目标分支 origin/%s\\\\n\\" \\"$d\\" \\"$base\\"; fail=1; continue; }\\n [ \\"$ahead\\" != 0 ] || continue\\n branch=\\"$(git -C \\"$d\\" branch --show-current)\\"\\n if [ \\"$branch\\" != \\"$work\\" ]; then printf \\"%s 当前在 %s,不在本轮工作分支 %s\\\\n\\" \\"$d\\" \\"${branch:-分离的 HEAD}\\" \\"$work\\"; fail=1; continue; fi\\n head=\\"$(git -C \\"$d\\" rev-parse HEAD)\\"\\n pushed=\\"$(git -C \\"$d\\" ls-remote origin \\"refs/heads/$work\\")\\" || { printf \\"%s 无法读取远端 origin\\\\n\\" \\"$d\\"; fail=1; continue; }\\n if [ \\"${pushed%%\\"$tab\\"*}\\" != \\"$head\\" ]; then printf \\"%s 的工作分支 %s 在 origin 上不是 %s,本轮提交还没推送\\\\n\\" \\"$d\\" \\"$work\\" \\"$head\\"; fail=1; fi\\ndone </dev/null; then refs=\\"HEAD refs/heads/$work\\"; fi\\n ahead=\\"$(git -C \\"$d\\" rev-list --count $refs --not \\"refs/remotes/origin/$base\\")\\" || { printf \\"%s 找不到目标分支 origin/%s\\\\n\\" \\"$d\\" \\"$base\\"; fail=1; continue; }\\n [ \\"$ahead\\" != 0 ] || continue\\n branch=\\"$(git -C \\"$d\\" branch --show-current)\\"\\n if [ \\"$branch\\" != \\"$work\\" ]; then printf \\"%s 当前在 %s,不在本轮工作分支 %s\\\\n\\" \\"$d\\" \\"${branch:-分离的 HEAD}\\" \\"$work\\"; fail=1; continue; fi\\n head=\\"$(git -C \\"$d\\" rev-parse HEAD)\\"\\n pushed=\\"$(git -C \\"$d\\" ls-remote origin \\"refs/heads/$work\\")\\" || { printf \\"%s 无法读取远端 origin\\\\n\\" \\"$d\\"; fail=1; continue; }\\n if [ \\"${pushed%%\\"$tab\\"*}\\" != \\"$head\\" ]; then printf \\"%s 的工作分支 %s 在 origin 上不是 %s,本轮提交还没推送\\\\n\\" \\"$d\\" \\"$work\\" \\"$head\\"; fail=1; fi\\ndone < reports/welcome.md","maxAttempts":1,"position":{"x":100,"y":150},"artifactOutputs":[{"name":"welcome","path":"reports/welcome.md","mediaType":"text/markdown","required":true}]},{"id":"approve","name":"请确认验收报告","type":"approval","maxAttempts":1,"rejectTo":"prepare","position":{"x":370,"y":150}},{"id":"finish","name":"完成验收","type":"script","scriptLanguage":"shell","executionScope":"run","script":"printf ''# 验收完成\\\\n\\\\n审批已通过,执行成功恢复。\\\\n'' > completed.md","artifactOutputs":[{"name":"completed","path":"completed.md","mediaType":"text/markdown","required":true}],"maxAttempts":1,"position":{"x":640,"y":150}}],"edges":[{"id":"e-1","source":"prepare","target":"approve","when":"success"},{"id":"e-2","source":"approve","target":"finish","when":"success"}]}',1,1,'published'); +INSERT IGNORE INTO workflows (`id`,`name`,`payload`,`version`,`revision`,`status`) VALUES ('welcome-workflow','平台验收 · 脚本与审批','{"version":1,"updatedAt":"2026-10-15T00:00:00Z","id":"welcome-workflow","name":"平台验收 · 脚本与审批","revision":1,"status":"published","projectId":"welcome","description":"无需模型密钥。真实运行脚本、查看产物,在人工审批后继续执行。","sandboxProfileId":"generic-docker","nodes":[{"id":"prepare","name":"生成验收报告","type":"script","scriptLanguage":"shell","executionScope":"run","script":"mkdir -p reports\\nprintf ''# LoopForge 本地验收\\\\n\\\\n已验证:真实脚本节点、持久化产物、人工审批与恢复。\\\\n'' > reports/welcome.md","maxAttempts":1,"position":{"x":100,"y":150},"artifactOutputs":[{"name":"welcome","path":"reports/welcome.md","mediaType":"text/markdown","required":true}]},{"id":"approve","name":"请确认验收报告","type":"approval","maxAttempts":1,"rejectTo":"prepare","position":{"x":370,"y":150}},{"id":"finish","name":"完成验收","type":"script","scriptLanguage":"shell","executionScope":"run","script":"printf ''# 验收完成\\\\n\\\\n审批已通过,执行成功恢复。\\\\n'' > completed.md","artifactOutputs":[{"name":"completed","path":"completed.md","mediaType":"text/markdown","required":true}],"maxAttempts":1,"position":{"x":640,"y":150}}],"edges":[{"id":"e-1","source":"prepare","target":"approve","when":"success"},{"id":"e-2","source":"approve","target":"finish","when":"success"}]}',1,1,'published'); INSERT IGNORE INTO agents (id,name,payload,updated_at) VALUES ('baseline-align-resolver','基线对齐执行员','{"id": "baseline-align-resolver", "name": "基线对齐执行员", "version": 1, "shared": true, "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "只做基线对齐:fetch 默认分支并 merge 到当前工作分支;解决冲突时保留双方有效实现,拿不准时记录取舍。创建本地合并提交。不要自行 push 或修改默认分支,不要执行与本次基线对齐无关的测试或编写修复报告。"}',UTC_TIMESTAMP()); COMMIT; diff --git a/scripts/install-schema-extensions.sh b/scripts/install-schema-extensions.sh index d0ef45c3a..beda40f36 100755 --- a/scripts/install-schema-extensions.sh +++ b/scripts/install-schema-extensions.sh @@ -1,11 +1,10 @@ #!/usr/bin/env bash # Bring the Compose database up to what this release reads but gorm # AutoMigrate cannot create: the generated columns from migration 001, the -# INSERT IGNORE starter catalog, the built-in Dockerfile update from -# migration 031 and the 「发起 MR」 node of the built-in code delivery SOPs from -# migration 033, followed by the MR roles' Git credential instructions from -# migration 038. All steps are safe to repeat, so the installer and -# `./start.sh pull` run it after the platform is healthy. +# INSERT IGNORE starter catalog, the 「发起 MR」 node of the built-in code delivery +# SOPs from migration 033, the MR roles' Git credential instructions from +# migration 038. The installer and `./start.sh pull` replay these steps +# after the platform is healthy. set -euo pipefail cd "$(dirname "$0")/.." source scripts/docker-access.sh @@ -16,7 +15,6 @@ if ! bash scripts/install-observability-schema.sh; then exit 1 fi cat migrations/seed/*.sql \ - migrations/031_generic_backend_openssh.sql \ migrations/033_generic_sop_mr_node.sql \ migrations/038_generic_sop_host_credentials.sql \ | docker_access compose exec -T mysql sh -c 'MYSQL_PWD="$MYSQL_PASSWORD" mysql -u loopforge loopforge' diff --git a/scripts/test-install-live.sh b/scripts/test-install-live.sh index c061532e7..d01ea4d30 100644 --- a/scripts/test-install-live.sh +++ b/scripts/test-install-live.sh @@ -22,7 +22,7 @@ for actor in "${actors[@]}"; do fixture="$task_dir/$actor" mkdir -p "$fixture/scripts" "$fixture/migrations/seed" "$fixture/user-home" cp scripts/{install.sh,configure.sh,docker-access.sh,ghcr-mirror.sh,install-address.py,install-compose.py,install-observability-schema.sh,install-schema-extensions.sh} "$fixture/scripts/" - cp migrations/001_run_obs_generated_columns.sql migrations/031_generic_backend_openssh.sql migrations/033_generic_sop_mr_node.sql migrations/038_generic_sop_host_credentials.sql "$fixture/migrations/" + cp migrations/001_run_obs_generated_columns.sql migrations/033_generic_sop_mr_node.sql migrations/038_generic_sop_host_credentials.sql "$fixture/migrations/" cp migrations/seed/*.sql "$fixture/migrations/seed/" cp compose.yaml "$fixture/" read -r http_port mysql_port < <(python3 - <<'PY' diff --git a/scripts/test-install.py b/scripts/test-install.py index cd4d6e230..f10c098a3 100644 --- a/scripts/test-install.py +++ b/scripts/test-install.py @@ -35,7 +35,7 @@ def setUp(self): for name in ('install.sh', 'configure.sh', 'docker-access.sh', 'ghcr-mirror.sh', 'install-address.py', 'install-compose.py', 'install-observability-schema.sh', 'install-schema-extensions.sh'): shutil.copyfile(ROOT / 'scripts' / name, self.root / 'scripts' / name) shutil.copyfile(ROOT / 'start.sh', self.root / 'start.sh') - for name in ('001_run_obs_generated_columns.sql', '031_generic_backend_openssh.sql', '033_generic_sop_mr_node.sql', '038_generic_sop_host_credentials.sql'): + for name in ('001_run_obs_generated_columns.sql', '033_generic_sop_mr_node.sql', '038_generic_sop_host_credentials.sql', '041_native_sandbox_inline_assets.sql'): (self.root / 'migrations' / name).write_text((ROOT / 'migrations' / name).read_text()) (self.root / 'migrations/seed/001_test.sql').write_text('INSERT IGNORE INTO agents (id) VALUES (1);\n') (self.root / 'mock').mkdir() @@ -49,6 +49,13 @@ def setUp(self): if [[ "$1" == pull && "${MOCK_PULL_FAIL:-0}" == 1 ]]; then exit 42; fi if [[ "$1" == tag && "${MOCK_TAG_FAIL:-0}" == 1 ]]; then exit 1; fi if [[ "$*" == 'compose version' && "${MOCK_COMPOSE_MISSING:-0}" == 1 && ! -f "$MOCK_COMPOSE_INSTALLED" ]]; then exit 1; fi +if [[ "$*" == *'ps --all --status running --status restarting --status paused --services platform' ]]; then + case "${MOCK_MIGRATION_PLATFORM:-stopped}" in + running) echo platform ;; + error) exit 1 ;; + esac + exit 0 +fi if [[ "$*" == *'ps --status running'* ]]; then echo platform; fi if [[ "${MOCK_EXPIRE_AFTER_BUILD:-0}" == 1 && "$*" == *'build platform'* ]]; then touch "$MOCK_SUDO_EXPIRED_FILE"; fi if [[ "$*" == *'exec -T mysql'* ]]; then @@ -70,6 +77,7 @@ def setUp(self): for name in ('LOOPFORGE_DOCKER_USE_SUDO', 'LOOPFORGE_DATA_DIR', 'LOOPFORGE_IMAGE', 'COMPOSE_FILE', 'LOOPFORGE_BUILD_FROM_SOURCE', 'LOOPFORGE_PULL_POLICY', 'MIRROR', 'MOCK_USER', 'MOCK_DIRECT', 'MOCK_SUDO_DENIED', 'MOCK_IMAGE_PRESENT', 'MOCK_PULL_FAIL', 'MOCK_TAG_FAIL', 'MOCK_MIRROR_GHCR', 'MOCK_MIRROR_NJU', 'MOCK_CURL_LOG'): self.environ.pop(name, None) self.environ.pop('MOCK_COLUMN_COUNT', None) + self.environ.pop('MOCK_MIGRATION_PLATFORM', None) def executable(self, name, contents): target = self.root / 'mock' / name @@ -461,6 +469,7 @@ def test_start_pull_reapplies_schema_extensions_after_containers_are_up(self): self.assertIn('ALTER TABLE run_telemetry', sql) self.assertIn('ALTER TABLE run_logs', sql) self.assertIn('INSERT IGNORE', sql) + self.assertNotIn('DROP TABLE IF EXISTS dockerfiles', sql) # The 「发起 MR」 node of the code delivery SOPs is replayed too, instead # of waiting for an operator to run migration 033 by hand. self.assertIn('JSON_ARRAY_APPEND', sql) @@ -469,6 +478,31 @@ def test_start_pull_reapplies_schema_extensions_after_containers_are_up(self): # Recreated containers come first; the old volume then gets the columns. self.assertLess(log.index('up -d --no-build --wait'), log.index('exec -T mysql')) + def test_migrate_sandboxes_requires_a_stopped_platform(self): + (self.root / '.env').touch() + command = [self.shell(), 'start.sh', 'migrate-sandboxes'] + for state in ('running', 'error'): + with self.subTest(platform=state): + result = subprocess.run(command, cwd=self.root, + env=dict(self.environ, MOCK_MIGRATION_PLATFORM=state), + text=True, capture_output=True, stdin=subprocess.DEVNULL, timeout=15) + self.assertNotEqual(result.returncode, 0) + if state == 'running': + self.assertIn('stop platform', result.stderr) + self.assertFalse((self.root / 'mysql.log').exists()) + + result = subprocess.run([self.shell(), 'start.sh', 'stop', 'platform'], + cwd=self.root, env=self.environ, text=True, capture_output=True, + stdin=subprocess.DEVNULL, timeout=15) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertIn('compose --profile platform stop platform', (self.root / 'docker.log').read_text()) + + result = subprocess.run(command, cwd=self.root, env=self.environ, + text=True, capture_output=True, stdin=subprocess.DEVNULL, timeout=15) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + migration = self.root / 'migrations/041_native_sandbox_inline_assets.sql' + self.assertEqual((self.root / 'mysql.log').read_text(), migration.read_text()) + def test_start_pull_names_the_migration_when_columns_cannot_be_checked(self): self.assert_success(self.install()) result = subprocess.run([self.shell(), 'start.sh', 'pull'], cwd=self.root, env=dict(self.environ, MOCK_COLUMN_COUNT='?'), text=True, capture_output=True, stdin=subprocess.DEVNULL, timeout=15) diff --git a/start.sh b/start.sh index 52a46fc98..a8ef97f81 100755 --- a/start.sh +++ b/start.sh @@ -6,10 +6,13 @@ # ./start.sh install/start in the background (same as -d) # ./start.sh -d install/start in the background # ./start.sh logs follow platform logs -# ./start.sh stop stop containers, keep them and their data +# ./start.sh stop [service] +# stop containers and keep their data # ./start.sh down remove containers, keep data volumes # ./start.sh restart restart the platform container # ./start.sh pull refresh images and recreate changed containers +# ./start.sh migrate-sandboxes +# apply migration 041 while the platform is stopped # ./start.sh dev build this checkout (compose.dev.yaml) and start it # ./start.sh release switch a source-built installation back to GHCR # ./start.sh time ghcr.io and ghcr.nju.edu.cn, then pull the faster one @@ -55,8 +58,17 @@ PY # A newer image may read generated columns the old volume never got. bash scripts/install-schema-extensions.sh ;; + migrate-sandboxes) + active_platform="$(compose ps --all --status running --status restarting --status paused --services platform)" + if [[ -n "$active_platform" ]]; then + docker_access_fail 'Stop the platform with ./start.sh stop platform. Keep MySQL running.' + fi + compose exec -T mysql sh -c 'MYSQL_PWD="$MYSQL_PASSWORD" exec mysql -u loopforge loopforge' \ + < migrations/041_native_sandbox_inline_assets.sql + printf 'Applied sandbox migration 041.\n' + ;; logs) compose logs -f "${@:-platform}" ;; - stop) compose stop ;; + stop) compose stop "$@" ;; down) compose down --remove-orphans ;; restart) compose restart platform ;; build) @@ -66,7 +78,7 @@ PY ;; *) echo "unknown: $cmd" >&2 - echo 'usage: ./start.sh [-d|logs|stop|down|restart|pull|dev|release]' >&2 + echo 'usage: ./start.sh [-d|logs|stop|down|restart|pull|migrate-sandboxes|dev|release]' >&2 exit 1 ;; esac diff --git a/third_party/go/THIRD_PARTY_NOTICES.txt b/third_party/go/THIRD_PARTY_NOTICES.txt index 08d6efd82..af595c60c 100644 --- a/third_party/go/THIRD_PARTY_NOTICES.txt +++ b/third_party/go/THIRD_PARTY_NOTICES.txt @@ -1807,6 +1807,32 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +============================================================================== +github.com/go-quicktest/qt v1.102.0 + +--- LICENSE --- +MIT License + +Copyright (c) 2017 Canonical Ltd. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + ============================================================================== github.com/go-sql-driver/mysql v1.10.1 @@ -2921,6 +2947,213 @@ Google Inc. See the License for the specific language governing permissions and limitations under the License. +============================================================================== +github.com/google/renameio/v2 v2.0.2 + +--- LICENSE --- + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + ============================================================================== github.com/google/uuid v1.3.0 @@ -4097,7 +4330,7 @@ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ============================================================================== -github.com/rogpeppe/go-internal v1.10.0 +github.com/rogpeppe/go-internal v1.15.0 --- LICENSE --- Copyright (c) 2018 The Go Authors. All rights reserved. @@ -6790,6 +7023,70 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +============================================================================== +mvdan.cc/editorconfig v0.3.0 + +--- LICENSE --- +Copyright (c) 2019, Daniel Martí. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of the copyright holder nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +============================================================================== +mvdan.cc/sh/v3 v3.14.1 + +--- LICENSE --- +Copyright (c) 2016, Daniel Martí. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of the copyright holder nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ============================================================================== rsc.io/pdf v0.1.1 diff --git a/web/app.js b/web/app.js index 342581a2a..26276f7eb 100644 --- a/web/app.js +++ b/web/app.js @@ -12,9 +12,9 @@ const state = { selectedAgent:null, selectedRun:null, selectedRunNode:null, runFilter:'all', runQuery:'', runWorkflowFilter:'', selectedIssue:null, projectFilter:'', projectDraft:null, requirementIssueId:null, sourceFilter:'', projectAdminDetailId:null, projectAdminTab:'basic', projectAdminQuery:'', projectAdminFilter:'all', projectDraftFor:'', projectDraftBase:null, projectIdentCustom:false, projectIdentSeed:'', projectAdminErrors:{}, - sopScope:'project', agentScope:'project', ruleScope:'project', skillScope:'project', dockerfileScope:'project', environmentScope:'project', sandboxScope:'project', + sopScope:'project', agentScope:'project', ruleScope:'project', skillScope:'project', sandboxScope:'project', issueRunFilter:'', issueStatusFilter:'', issueAssigneeFilter:'', issueQuery:'', issueView:localStorage.getItem('agentflow.issueView')||'table', - assetType:'dockerfiles', selectedAsset:null, assetQuery:'', assetDirty:false, mcpTab:'installed', mcpScope:'project', mcpMarket:[], mcpQuery:'', editingMCPId:'', poll:null, runStream:null, + assetType:'sandboxes', selectedAsset:null, assetQuery:'', assetDirty:false, mcpTab:'installed', mcpScope:'project', mcpMarket:[], mcpQuery:'', editingMCPId:'', poll:null, runStream:null, obsTab:'overview', obsDeliveryFilter:'all', obsTraceRunId:null, obsTraceAdapter:'live', obsScope:localStorage.getItem('agentflow.obsScope')==='project'?'project':'user', obsUserFilter:'', obsSourceFilter:'', obsUserFilterReady:false, obsTrendGrain:['day','week','month','all'].includes(localStorage.getItem('agentflow.obsTrendGrain'))?localStorage.getItem('agentflow.obsTrendGrain'):'all', obsPeriodKey:'', obsTrendMetric:['runs','issues','cost'].includes(localStorage.getItem('agentflow.obsTrendMetric'))?localStorage.getItem('agentflow.obsTrendMetric'):'tokens', obsCrossProject:null, drawerOpen:false, issueDetailTab:'overview', issueDetailData:null, propTab:'basic', uiScroll:{runId:'', nodeId:'', graphLeft:0, feedTop:0, telTop:0, feedStick:true, telStick:true}, runLogs:null, runTelemetry:null, runTelemetryAdapter:'live', runWorkspace:null, @@ -857,7 +857,7 @@ function shouldAutoSSORedirect({isGuest, hostname, bypassAutoAuth, authErr, logi } async function boot(){ - state.data = {runs:[],issues:[],tasks:[],workflowMetrics:[],syncLogs:[],agents:[],workflows:[],projects:[],repositories:[],users:[],rules:[],skills:[],mcpServers:[],executors:[],dockerfiles:[],environments:[],sandboxes:[]}; + state.data = {runs:[],issues:[],tasks:[],workflowMetrics:[],syncLogs:[],agents:[],workflows:[],projects:[],repositories:[],users:[],rules:[],skills:[],mcpServers:[],executors:[],sandboxes:[]}; bind(); renderProjectSwitcher(); updateApprovalBadge(); // 1. 检查 URL 中是否有 SSO 回调的 code @@ -1019,14 +1019,16 @@ function bind(){ $('#settingsSidebarExpand')?.addEventListener('click',()=>{ cancelSettingsRouteTransition(); setSettingsSidebarExpanded(true); - requestAnimationFrame(()=>{ - // Wait for the sidebar's descendants to inherit the restored visibility. - requestAnimationFrame(()=>{ - if(settingsSidebarExpanded()&&document.activeElement===document.body){ - $('#settingsSidebarToggle')?.focus({preventScroll:true}); - } - }); + // Wait for the sidebar's descendants to inherit the restored visibility; reduced + // motion still runs a near-zero visibility transition, so retry for a few frames. + let frames=0; + const focusToggle=()=>requestAnimationFrame(()=>{ + if(!settingsSidebarExpanded()||document.activeElement!==document.body)return; + const toggle=$('#settingsSidebarToggle'); + toggle?.focus({preventScroll:true}); + if(toggle&&document.activeElement!==toggle&&++frames<30)focusToggle(); }); + requestAnimationFrame(focusToggle); }); document.addEventListener('click',event=>{ if(document.body.classList.contains('management-mode')&&event.target instanceof Element&&event.target.closest('.collab-rail-toggle')){ @@ -1608,7 +1610,7 @@ function mountNativeChat(){ renderAll(); }).catch(()=>{}); } - if(message.type==='agentflow-chat-open-view'&&['settings','runners','sops','projects','runs','agents','environments','dockerfiles','sandboxes','flow','mcp'].includes(message.view)){ + if(message.type==='agentflow-chat-open-view'&&['settings','runners','sops','projects','runs','agents','sandboxes','flow','mcp'].includes(message.view)){ if(message.view==='settings'&&message.credential){ if(message.credential==='executors'&&message.returnToQuickAccess===true&&activeViewName()==='collaboration'&&location.hash!==QUICK_ACCESS_EXECUTOR_SETTINGS){ history.pushState({quickAccessExecutorReturn:true},'',QUICK_ACCESS_EXECUTOR_SETTINGS); @@ -1650,7 +1652,7 @@ function settingsSidebarExpanded(){ } let settingsSidebarEntryFrame=0; let settingsSidebarWasManaged=false; -const settingsManagementViews=['settings','assistant','projects','bots','sops','flow','runs','aiSchedules','agents','mcp','rules','skills','runners','dockerfiles','environments','sandboxes','guide','platform']; +const settingsManagementViews=['settings','assistant','projects','bots','sops','flow','runs','aiSchedules','agents','mcp','rules','skills','runners','sandboxes','guide','platform']; const settingsRouteMotion=matchMedia('(prefers-reduced-motion: reduce)'); let settingsRouteTransition=null; let settingsRouteApplying=false; @@ -1825,11 +1827,11 @@ function setSettingsSidebarExpanded(expanded){ }); } } -function viewTitles(){return {management:'设置',collaboration:'AI 工作台',issues:'需求列表',aiSchedules:'定时任务',bots:'通道管理',assistant:'AI 助手',runs:'运行记录',approvals:'待我确认',sops:'流程模板',flow:'流程设计',agents:'角色定义',mcp:'能力资产',rules:'能力资产',skills:'能力资产',dockerfiles:'环境资产',environments:'环境资产',sandboxes:'环境资产',observability:'统计',projects:'项目配置',platform:'平台管理',runners:'执行机器',settings:'个人配置',access:'访问密钥',guide:'访问密钥'}} -// 设置侧栏只列一级入口;被合并进同一页的子视图(能力资产、环境资产的类型 Tab, +function viewTitles(){return {management:'设置',collaboration:'AI 工作台',issues:'需求列表',aiSchedules:'定时任务',bots:'通道管理',assistant:'AI 助手',runs:'运行记录',approvals:'待我确认',sops:'流程模板',flow:'流程设计',agents:'角色定义',mcp:'能力资产',rules:'能力资产',skills:'能力资产',sandboxes:'沙箱管理',observability:'统计',projects:'项目配置',platform:'平台管理',runners:'执行机器',settings:'个人配置',access:'访问密钥',guide:'访问密钥'}} +// 设置侧栏只列一级入口;被合并进同一页的子视图(能力资产的类型 Tab, // 从流程模板打开的流程设计)按 data-nav-match 高亮它们所属的入口。 function settingsNavMatches(btn,name){return btn.dataset.view===name||String(btn.dataset.navMatch||'').split(/\s+/).includes(name)} -const assetTypeGroups={capability:['mcp','rules','skills'],environment:['dockerfiles','environments','sandboxes']}; +const assetTypeGroups={capability:['mcp','rules','skills']}; function assetTypeGroup(name){return Object.keys(assetTypeGroups).find(key=>assetTypeGroups[key].includes(name))||''} function syncAssetTypeTabs(name){ const group=assetTypeGroup(name); @@ -1841,7 +1843,7 @@ function restoredView(){ const titles=viewTitles(); const hash=(location.hash||'').replace(/^#\/?/,'').split(/[/?]/)[0]; if(hash==='access')return 'guide'; - if(hash==='assets')return 'dockerfiles'; + if(['assets','dockerfiles','environments'].includes(hash))return 'sandboxes'; if(hash==='playbooks')return 'sops'; if(hash==='management')return 'settings'; if(titles[hash])return hash; @@ -1968,10 +1970,10 @@ function switchView(name){ const titles=viewTitles(); if(name==='dashboard')name='collaboration'; if(name==='access')name='guide'; - if(name==='assets')name='dockerfiles'; + if(['assets','dockerfiles','environments'].includes(name))name='sandboxes'; if(name==='playbooks')name='sops'; if(name==='management')name='settings'; - const assetViews=['rules','skills','dockerfiles','environments','sandboxes']; + const assetViews=['rules','skills','sandboxes']; const targetView=assetViews.includes(name)?'assets':name; if(!titles[name]||!$(`#${targetView}View`)){name='collaboration'} // 手敲 #/platform 或者从别的账号留下的 localStorage 恢复进来,都要挡住。 diff --git a/web/app/access.js b/web/app/access.js index beae42a70..8d840ac8e 100644 --- a/web/app/access.js +++ b/web/app/access.js @@ -275,7 +275,7 @@ async function revokePersonalToken(id){ let commandMatches=[],commandSelectedIndex=0; function commandCatalog(){ - const pages=[['collaboration','AI 工作台','和 AI 对话,派发与跟进任务'],['issues','需求列表','查看进度,触发或重试'],['approvals','待我确认','批准或退回卡住的需求'],['observability','统计','用量分析 · Token 与质量'],['settings','个人配置','账号、模型与执行凭据'],['projects','项目配置','项目、成员和仓库'],['bots','通道管理','企业微信单聊或群聊通知通道'],['sops','流程模板','Issue 修复与需求开发'],['runs','运行记录','查看节点日志和产物'],['aiSchedules','定时任务','提示词任务、SOP 触发与共享任务'],['agents','角色定义','管理角色和能力资产'],['mcp','能力资产 · MCP','添加项目级或个人 MCP'],['rules','能力资产 · 规则','当前项目的行为与执行约束'],['skills','能力资产 · 技能','当前项目的技能和附加文件'],['runners','执行机器','用自己的电脑或 CVM 跑任务'],['dockerfiles','环境资产 · Dockerfile','管理项目容器构建定义'],['environments','环境资产 · 安装脚本','管理隔离环境的工具安装脚本'],['sandboxes','环境资产 · 沙箱','管理项目运行隔离策略'],['guide','访问密钥','创建和撤销访问密钥']].map(([view,title,meta])=>({kind:'页面',title,meta,action:()=>switchView(view)})); + const pages=[['collaboration','AI 工作台','和 AI 对话,派发与跟进任务'],['issues','需求列表','查看进度,触发或重试'],['approvals','待我确认','批准或退回卡住的需求'],['observability','统计','用量分析 · Token 与质量'],['settings','个人配置','账号、模型与执行凭据'],['projects','项目配置','项目、成员和仓库'],['bots','通道管理','企业微信单聊或群聊通知通道'],['sops','流程模板','Issue 修复与需求开发'],['runs','运行记录','查看节点日志和产物'],['aiSchedules','定时任务','提示词任务、SOP 触发与共享任务'],['agents','角色定义','管理角色和能力资产'],['mcp','能力资产 · MCP','添加项目级或个人 MCP'],['rules','能力资产 · 规则','当前项目的行为与执行约束'],['skills','能力资产 · 技能','当前项目的技能和附加文件'],['runners','执行机器','用自己的电脑或 CVM 跑任务'],['sandboxes','沙箱管理','隔离方式、Dockerfile 与环境变量'],['guide','访问密钥','创建和撤销访问密钥']].map(([view,title,meta])=>({kind:'页面',title,meta,action:()=>switchView(view)})); const issues=(state.data.issues||[]).map(i=>({kind:'需求',title:i.title,meta:`${i.priority||'—'} · ${issueStatusLabel(i.status)}`,action:()=>openIssueDetail(i.id)})); const runs=sopRuns(state.data.runs).map(r=>({kind:'运行',title:runIssueTitle(r),meta:`${runDisplayStatus(r)} · ${r.workflowSnapshot?.name||r.workflowId}`,action:()=>openRunFromId(r.id)})); const sops=catalogWorkflows().map(w=>({kind:'SOP',title:w.name,meta:`${w.status==='published'?'已发布':'草稿'} · ${w.nodes?.length||0} 个节点`,action:()=>{state.workflow=clone(w);state.selectedNode=null;switchView('flow')}})); diff --git a/web/app/assets-harness.css b/web/app/assets-harness.css index 0405244ce..b76d28dc7 100644 --- a/web/app/assets-harness.css +++ b/web/app/assets-harness.css @@ -1,4 +1,4 @@ -/* 资产管理页(规则 / 技能 / Dockerfile / 环境安装脚本 / 沙箱)· Harness UI 设计语言 +/* 资产管理页(规则 / 技能 / 沙箱)· Harness UI 设计语言 * (MIT,见 harness-ui-LICENSE.txt)。令牌、按钮与 ⋯ 菜单来自 app/harness-ui.css, * 外层 1200px 居中容器由其设置区规则统一提供。Every rule stays inside #assetsView. */ @@ -338,6 +338,14 @@ #assetsView .asset-field-label, #assetsView .asset-side-card .rule-global-sops > label { display: block; margin: 12px 0 6px; color: var(--hui-muted); font: 500 12px/1.4 var(--hui-sans); } #assetsView .asset-stage .asset-field-label { margin-top: 0; } +/* Sandbox setup fills the main pane as one form column. */ +#assetsView .sandbox-setup { max-width: 680px; } +#assetsView .sandbox-setup .asset-field-label { display: flex; align-items: center; gap: 6px; margin: 18px 0 6px; } +#assetsView .sandbox-setup > .asset-field-label:first-child { margin-top: 0; } +#assetsView .sandbox-setup .asset-field-label label { cursor: pointer; } +#assetsView .sandbox-setup .asset-editor.is-env { min-height: 96px; } +#assetsView .sandbox-setup .field-help { display: inline-grid; place-items: center; box-sizing: border-box; width: 15px; height: 15px; padding: 0; border: 1px solid var(--hui-border-strong); border-radius: 50%; background: transparent; color: var(--hui-tertiary); font: 600 10px/1 var(--hui-sans); cursor: help; transition: border-color .18s var(--hui-ease-flow), color .18s var(--hui-ease-flow); } +#assetsView .sandbox-setup .field-help:is(:hover, :focus-visible) { border-color: var(--hui-accent); color: var(--hui-accent); outline: 0; } #assetsView .asset-field-label small { margin-left: 4px; color: var(--hui-tertiary); font-weight: 400; } #assetsView .asset-input { box-sizing: border-box; @@ -597,11 +605,11 @@ #assetsView .skillhub-drawer.is-open { transition: none; } } -/* 能力资产(MCP / 规则 / 技能)与环境资产(Dockerfile / 安装脚本 / 沙箱)的类型标签: +/* 能力资产(MCP / 规则 / 技能)的类型标签: * 下划线分段,沿用 Bot 记录页的 SlidingTabs 指示层;mcpView 与 assetsView 共用。 */ :is(#mcpView, #assetsView) .asset-type-tabs{display:flex;align-items:flex-end;gap:22px;margin:-6px 0 16px;border-bottom:1px solid var(--hui-border-soft,var(--hui-border))} /* SlidingTabs adds .sliding-tabs[data-sliding-tabs] and the enhanced rule below forces display:flex; - * the hidden group must out-rank it, otherwise both 能力资产 and 环境资产 tab rows show at once. */ + * the hidden group must out-rank it, otherwise the tab row also shows on pages outside its group. */ :is(#mcpView, #assetsView) .asset-type-tabs[hidden], :is(#mcpView, #assetsView) .asset-type-tabs.sliding-tabs[data-sliding-tabs][hidden]{display:none!important} :is(#mcpView, #assetsView) .asset-type-tabs.sliding-tabs[data-sliding-tabs]:not([hidden]){--sliding-surface:transparent;--sliding-text:var(--hui-text);--sliding-muted:var(--hui-muted);display:flex!important;width:auto;height:40px!important;min-height:40px!important;padding:0!important;gap:22px!important;border-radius:0!important;background:transparent!important} diff --git a/web/app/assets.js b/web/app/assets.js index df0f32904..f9e841a09 100644 --- a/web/app/assets.js +++ b/web/app/assets.js @@ -1,24 +1,22 @@ -function assetScopeKey(type){return ({rules:'ruleScope',skills:'skillScope',dockerfiles:'dockerfileScope',environments:'environmentScope',sandboxes:'sandboxScope'})[type]||'ruleScope'} -function isProjectSharedAsset(type){return ['rules','skills','dockerfiles','environments','sandboxes'].includes(type)} +function assetScopeKey(type){return ({rules:'ruleScope',skills:'skillScope',sandboxes:'sandboxScope'})[type]||'ruleScope'} +function isProjectSharedAsset(type){return ['rules','skills','sandboxes'].includes(type)} function assetPageCopy(type=state.assetType){ return ({ rules:{group:'Agent 能力',page:'能力资产',tab:'规则',desc:'维护当前项目的行为约束和执行规则。',create:'新建规则'}, skills:{group:'Agent 能力',page:'能力资产',tab:'技能',desc:'维护当前项目可供角色使用的技能和附加文件。',create:'新建技能'}, - dockerfiles:{group:'运行环境',page:'环境资产',tab:'Dockerfile',desc:'维护当前项目的容器构建定义。',create:'新建 Dockerfile'}, - environments:{group:'运行环境',page:'环境资产',tab:'安装脚本',desc:'维护安装到隔离执行环境中的工具与依赖。',create:'新建安装脚本'}, - sandboxes:{group:'运行环境',page:'环境资产',tab:'沙箱',desc:'维护当前项目的运行隔离方式及环境依赖。',create:'新建沙箱'} - })[type]||{group:'运行环境',page:'环境资产',tab:'Dockerfile',desc:'维护当前项目的容器构建定义。',create:'新建 Dockerfile'}; -} -function assetSharedDescription(type=state.assetType){return type==='rules'?'查看其他项目共享的规则;共享规则只读,可直接绑定到本项目角色。':type==='skills'?'查看其他项目共享的技能;共享技能只读,会自动装入平台上所有对话和定时任务,也可绑定到本项目角色。':'查看其他项目共享的环境资产;共享资产只读,可直接用于本项目。'} -function assetIconName(type=state.assetType){return ({rules:'gate',skills:'skills',dockerfiles:'layers',environments:'terminal',sandboxes:'server'})[type]||'layers'} -function assetRefIconName(type=state.assetType){return ({rules:'robot',skills:'robot',dockerfiles:'server',environments:'server',sandboxes:'workflow'})[type]||'layers'} + sandboxes:{group:'运行环境',page:'沙箱管理',crumb:'沙箱管理',tab:'沙箱',desc:'维护当前项目的运行沙箱:隔离方式、Dockerfile 和环境变量。',create:'新建沙箱'} + })[type]||{group:'运行环境',page:'沙箱管理',crumb:'沙箱管理',tab:'沙箱',desc:'维护当前项目的运行沙箱:隔离方式、Dockerfile 和环境变量。',create:'新建沙箱'}; +} +function assetSharedDescription(type=state.assetType){return type==='rules'?'查看其他项目共享的规则;共享规则只读,可直接绑定到本项目角色。':type==='skills'?'查看其他项目共享的技能;共享技能只读,会自动装入平台上所有对话和定时任务,也可绑定到本项目角色。':'查看其他项目共享的沙箱;共享沙箱只读,可直接用于本项目。'} +function assetIconName(type=state.assetType){return ({rules:'gate',skills:'skills',sandboxes:'server'})[type]||'layers'} +function assetRefIconName(type=state.assetType){return ({rules:'robot',skills:'robot',sandboxes:'workflow'})[type]||'layers'} function assetScopeItems(scope){return (state.data[state.assetType]||[]).filter(item=>scope==='shared'?catalogShared(item.projectId,item.shared):catalogOwned(item.projectId))} function assetMatchesQuery(a,query){const q=String(query||'').trim().toLowerCase();if(!q)return true;return [a?.name,a?.id,a?.description].some(v=>String(v||'').toLowerCase().includes(q))} function assetFilteredItems(){return assetScopeItems(state[assetScopeKey(state.assetType)]).filter(a=>assetMatchesQuery(a,state.assetQuery))} // Owned assets win over a same-id shared copy so the editable one opens. function assetFindVisible(id){if(!id)return null;const owned=assetScopeItems('project').find(x=>x.id===id);if(owned)return {asset:owned,scope:'project'};const shared=assetScopeItems('shared').find(x=>x.id===id);return shared?{asset:shared,scope:'shared'}:null} function assetProjectName(a){return (state.data.projects||[]).find(p=>p.id===a?.projectId)?.name||a?.projectId||'平台'} -function assetIsBuiltin(a,type=state.assetType){return (type==='sandboxes'&&(a?.id==='local'||a?.id==='generic-docker'))||(type==='dockerfiles'&&a?.id==='generic-backend')} +function assetIsBuiltin(a,type=state.assetType){return type==='sandboxes'&&a?.id==='generic-docker'} function assetStatusHTML(a){ if(!catalogOwned(a.projectId))return `来自 ${escapeHTML(assetProjectName(a))}`; return `${a.shared?'已共享':'未共享'}`; @@ -31,9 +29,10 @@ function assetMetaHTML(a){ const src=assetSkillSource(a); if(src){const latest=assetSkillLatest(src);meta.push(latest&&latest!==src.version?`SkillHub v${escapeHTML(src.version)} · 可更新`:`${huiIcon('sparkles')}SkillHub v${escapeHTML(src.version)}`)} } - if(state.assetType==='dockerfiles')meta.push(item('doc',`${(a.content||'').split('\n').length} 行`)); - if(state.assetType==='environments')meta.push(item('variable',`${Object.keys(a.variables||{}).length} 个变量`)); - if(state.assetType==='sandboxes')meta.push(item('server',sandboxDriverOption(a.driver))); + if(state.assetType==='sandboxes'){ + const driver=sandboxDriverOption(a.driver);meta.push(item('server',sandboxDriverLabel(driver))); + if(driver==='docker'&&a.dockerfile?.content)meta.push(item('layers',`Dockerfile ${a.dockerfile.content.trimEnd().split('\n').length} 行`)); + } const refs=assetReferenceNames(a).length; meta.push(item(assetRefIconName(),refs?`${refs} 个${assetRefKindLabel()}引用`:'未被引用')); return meta.join(''); @@ -45,7 +44,7 @@ function assetCardHTML(a){ function assetGridEmptyHTML(){ const kind=assetKindLabel(),copy=assetPageCopy(); if(String(state.assetQuery||'').trim())return `

没有匹配「${escapeHTML(state.assetQuery.trim())}」的${escapeHTML(kind)}

换个关键词试试。

`; - if(state[assetScopeKey(state.assetType)]==='shared'){const hint=['rules','skills'].includes(state.assetType)?'请在资产所属项目中共享,或共享一个引用它的角色。':'请在资产所属项目中共享;共享 SOP 时也会自动共享其环境依赖。';return `
其他项目还没有共享${escapeHTML(kind)}

${hint}

`} + if(state[assetScopeKey(state.assetType)]==='shared'){const hint=['rules','skills'].includes(state.assetType)?'请在资产所属项目中共享,或共享一个引用它的角色。':'请在沙箱所属项目中共享。';return `
其他项目还没有共享${escapeHTML(kind)}

${hint}

`} return `
当前项目还没有${/^[A-Za-z]/.test(kind)?' ':''}${escapeHTML(kind)}

${assetEmptyHint()}

`; } function renderAssetGrid(){ @@ -118,7 +117,7 @@ function assetDetailHeadHTML(a,{creating=false,dirty=false}={}){ function renderAssetDetailHead(a){ const creating=state.selectedAsset==='__new__',copy=assetPageCopy(); const crumbs=$('#assetCrumbs'); - if(crumbs)crumbs.innerHTML=`${escapeHTML(copy.page)} · ${escapeHTML(copy.tab)}${huiIcon('chevron-right')}${escapeHTML(creating?`新建${assetKindLabel()}`:(a.name||a.id))}`; + if(crumbs)crumbs.innerHTML=`${escapeHTML(copy.crumb||`${copy.page} · ${copy.tab}`)}${huiIcon('chevron-right')}${escapeHTML(creating?`新建${assetKindLabel()}`:(a.name||a.id))}`; const head=$('#assetDetailHead');if(!head)return; closeAssetMenu(); head.innerHTML=assetDetailHeadHTML(a,{creating,dirty:!!state.assetDirty}); @@ -256,22 +255,19 @@ async function toggleAssetShare(id){ toast(saved.shared?(state.assetType==='skills'?'已共享,所有对话和定时任务会自动装入':'已共享,其他项目可绑定'):'已取消共享'); }catch(e){toast(e.message)} } -function assetEmptyHint(){return ({rules:'规则是写给 Agent 的行为约束,例如编码规范、禁止事项。建好后在「角色定义」里绑定到角色。',skills:'技能是 Agent 可按需加载的说明和附加文件,例如某个框架的操作手册。建好后在「角色定义」里绑定到角色。',dockerfiles:'Dockerfile 定义沙箱容器的镜像。建好后在「沙箱管理」里选用;也可以直接用「共享」里的现成配置。',environments:'安装脚本在沙箱初始化时把工具装进隔离环境,例如指定版本的 Go、PHP、Node。建好后在「沙箱管理」里选用。',sandboxes:'沙箱决定 SOP 节点在什么隔离环境里执行,由 Dockerfile 和安装脚本组合而成。建好后在流程设置里选用;也可以直接用「共享」里的现成配置。'})[state.assetType]||''} -function assetKindLabel(){return ({rules:'规则',skills:'技能',dockerfiles:'Dockerfile',environments:'环境安装脚本',sandboxes:'沙箱'})[state.assetType]||'资产'} -function assetRefKindLabel(){return ({rules:'角色',skills:'角色',dockerfiles:'沙箱',environments:'沙箱',sandboxes:'流程'})[state.assetType]||'引用'} +function assetEmptyHint(){return ({rules:'规则是写给 Agent 的行为约束,例如编码规范、禁止事项。建好后在「角色定义」里绑定到角色。',skills:'技能是 Agent 可按需加载的说明和附加文件,例如某个框架的操作手册。建好后在「角色定义」里绑定到角色。',sandboxes:'沙箱决定 SOP 节点和对话工作区在什么隔离环境里执行:docker 沙箱自带 Dockerfile,native 沙箱使用执行机器上已安装的工具。建好后在流程设置里选用;也可以直接用「共享」里的现成配置。'})[state.assetType]||''} +function assetKindLabel(){return ({rules:'规则',skills:'技能',sandboxes:'沙箱'})[state.assetType]||'资产'} +function assetRefKindLabel(){return ({rules:'角色',skills:'角色',sandboxes:'流程'})[state.assetType]||'引用'} function assetReferenceNames(a){ if(!a?.id)return []; if(state.assetType==='rules')return (state.data.agents||[]).filter(x=>(x.rules||[]).includes(a.id)).map(x=>x.name||x.id); if(state.assetType==='skills')return (state.data.agents||[]).filter(x=>(x.skills||[]).includes(a.id)).map(x=>x.name||x.id); - if(state.assetType==='dockerfiles')return (state.data.sandboxes||[]).filter(x=>x.dockerfileId===a.id).map(x=>x.name||x.id); - if(state.assetType==='environments')return (state.data.sandboxes||[]).filter(x=>x.environmentId===a.id).map(x=>x.name||x.id); if(state.assetType==='sandboxes')return (state.data.workflows||[]).filter(x=>!catalogGeneric(x)&&x.sandboxProfileId===a.id).map(x=>x.name||x.id); return []; } function assetDeleteBlocked(a){ if(!a?.id)return '无法删除'; - if(state.assetType==='sandboxes'&&(a.id==='local'||a.id==='generic-docker'))return `内置沙箱 ${a.id} 不能删除`; - if(state.assetType==='dockerfiles'&&a.id==='generic-backend')return '内置 Dockerfile generic-backend 不能删除'; + if(state.assetType==='sandboxes'&&a.id==='generic-docker')return `内置沙箱 ${a.id} 不能删除`; if(a.shared)return `共享状态的${assetKindLabel()}不能删除,请先取消共享`; const refs=assetReferenceNames(a); if(refs.length)return `${assetKindLabel()}仍被 ${refs.length} 个${assetRefKindLabel()}引用(${refs.join('、')}),请先解除引用`; @@ -300,14 +296,37 @@ function selectedRuleWorkflowIds(){try{const ids=JSON.parse($('#ruleSOPPicker')? function setRuleWorkflowIds(ids){const host=$('#ruleSOPPicker');if(!host)return;const known=new Set(ruleSOPChoices().map(w=>w.id));host.dataset.ids=JSON.stringify([...new Set((ids||[]).map(id=>String(id||'').trim()).filter(id=>id&&known.has(id)))]);renderRuleSOPPicker();markAssetDirty()} function renderRuleSOPPicker(){const host=$('#ruleSOPPicker');if(!host)return;const sops=ruleSOPChoices();const selected=selectedRuleWorkflowIds();const chosen=new Set(selected);const leftover=sops.filter(w=>!chosen.has(w.id));const tags=selected.map(id=>{const sop=sops.find(w=>w.id===id);const name=sop?.name||id;const nodes=sop?.nodes?.length||0;const label=nodes?`${name} · ${nodes} 个节点`:name;return ``}).join('');const options=leftover.map(w=>``).join('');const placeholder=!sops.length?'暂无可选 SOP':(!leftover.length?'已全部选择':'+ 添加 SOP…');host.innerHTML=`
${tags}
`;host.querySelectorAll('[data-remove-rule-sop]').forEach(b=>b.onclick=()=>setRuleWorkflowIds(selected.filter(id=>id!==b.dataset.removeRuleSop)));const sel=host.querySelector('select');if(sel)sel.onchange=()=>{if(!sel.value)return;setRuleWorkflowIds([...selected,sel.value])}} function bindRuleGlobalPicker(a){const host=$('#ruleSOPPicker');if(!host)return;const known=new Set(ruleSOPChoices().map(w=>w.id));host.dataset.ids=JSON.stringify((Array.isArray(a.workflowIds)?a.workflowIds:[]).filter(id=>known.has(id)));const toggle=document.querySelector('#assetForm [name="global"]');const wrap=$('#ruleSOPPickerWrap');const sync=()=>{if(wrap)wrap.hidden=!(toggle&&toggle.checked)};if(toggle)toggle.onchange=sync;sync();renderRuleSOPPicker()} -function dockerfileOptions(selected){const items=(state.data.dockerfiles||[]).filter(x=>catalogVisible(x.projectId,x.shared));if(!items.length)return ``;return ``+items.map(x=>``).join('')} -function environmentOptions(selected){const items=(state.data.environments||[]).filter(x=>catalogVisible(x.projectId,x.shared));return ``+items.map(x=>``).join('')} // seatbelt / bwrap are the per-OS forms of native; rows saved before the merge still carry them. -function sandboxDriverOption(driver){return ['seatbelt','bwrap','native'].includes(driver)?'native':driver==='docker'?'docker':'local'} -function syncSandboxDriverFields(select){const driver=select?.value||'local';select?.form?.querySelectorAll('[data-sandbox-drivers]').forEach(el=>{el.hidden=!el.dataset.sandboxDrivers.split(' ').includes(driver)})} +// Rows saved as local before it was removed read as native. +function sandboxDriverOption(driver){return ['seatbelt','bwrap','native','local'].includes(driver)?'native':'docker'} +function sandboxDriverLabel(driver){return sandboxDriverOption(driver)==='native'?'系统轻量隔离':'Docker'} +function syncSandboxDriverFields(select){const driver=select?.value||'docker';select?.form?.querySelectorAll('[data-sandbox-drivers]').forEach(el=>{el.hidden=!el.dataset.sandboxDrivers.split(' ').includes(driver)})} function resolveAssetSaveIdentity(items,selectedID,requestedID){if(selectedID!=='__new__'){const existing=(items||[]).find(item=>item.id===selectedID);return existing?{id:existing.id,existing,created:false}:{error:'选中的资产已不存在,请刷新后重试'}}if((items||[]).some(item=>item.id===requestedID))return {error:'该标识已存在,请换一个标识,或回到列表打开已有资产修改'};return {id:requestedID,existing:null,created:true}} -function assetPaneTabs(type=state.assetType){return ({rules:[['edit','编辑'],['preview','预览']],skills:[['files','文件']],dockerfiles:[['content','Dockerfile'],['files','构建上下文']],environments:[['script','install.sh'],['vars','环境变量'],['path','PATH']],sandboxes:[['env','环境变量']]})[type]||[['edit','编辑']]} -function assetPaneHint(type=state.assetType){return ({rules:'支持 Markdown',skills:'每次上传都会完整替换现有文件',dockerfiles:'沙箱初始化时用库里这份 docker build',environments:'脚本把工具装进 $PREFIX',sandboxes:'驱动与执行环境在右侧设置,不要在这里保存凭证'})[type]||''} +function assetPaneTabs(type=state.assetType){return ({rules:[['edit','编辑'],['preview','预览']],skills:[['files','文件']],sandboxes:[['setup','配置']]})[type]||[['edit','编辑']]} +function assetPaneHint(type=state.assetType){return ({rules:'支持 Markdown',skills:'每次上传都会完整替换现有文件',sandboxes:'隔离方式决定沙箱在哪里、怎样执行'})[type]||''} +function assetFieldLabel(text,help,forId=''){return `
${forId?``:`${escapeHTML(text)}`}${help?``:''}
`} +function sandboxSetupHTML(a){const driver=sandboxDriverOption(a.driver);return `
+ ${assetFieldLabel('隔离方式','Docker 在 OCI 容器里执行;系统轻量隔离按执行机器的系统自动选择 seatbelt(macOS)或 bwrap(Linux),可以在用户的执行机器、云端 Runner 或平台本机上运行。')} + +
+ ${assetFieldLabel('Dockerfile','保存在这个沙箱里。沙箱初始化时用它 docker build 出镜像;内容相同的沙箱共用同一个镜像。不要指向仓库目录或现成镜像名。','assetDockerfile')} + + ${assetFieldLabel('构建上下文文件','JSON 对象:键是构建上下文里的相对路径,值是文件内容,和 Dockerfile 一起保存,可在 Dockerfile 里 COPY。','assetDockerfileFiles')} + +
+ + + + + +
+
+
+
系统轻量隔离直接使用执行机器上已安装的语言和工具,系统目录只读,只有工作区可写。需要的设置(如 JAVA_HOME、代理)写进下面的环境变量。仓库从执行机器的仓库缓存共享克隆,不重复下载。
+
+ ${assetFieldLabel('环境变量','JSON 对象,叠加到沙箱基础环境并随资产保存;不要在这里保存凭证。平台凭证、HOME/TMPDIR 和遥测变量优先级更高。')} + +
`} function assetMainPanesHTML(a,{creating,readonly}){ const pane=(key,body)=>`
${body}
`; if(state.assetType==='rules')return pane('edit',``)+pane('preview',`
`); @@ -329,26 +348,13 @@ function assetMainPanesHTML(a,{creating,readonly}){ ${locked?'':`
每次上传都是完全替换:文件夹 / zip 替换为整批文件;单独上传 SKILL.md 会先弹出确认,然后该技能只保留这一份 SKILL.md。单文件 ≤1MB,最多 500 个,单技能 ≤64MB。zip 自动解包并保留可执行位;markdown / 代码 / 图片可直接预览。
`} `); } - if(state.assetType==='dockerfiles')return pane('content',`
正文和附加文件保存在这条 Dockerfile 资产里,写入数据库,和 install.sh 一样。不要指向仓库目录或现成镜像名。沙箱初始化时用库里这份 docker build 出一次性镜像。
`)+pane('files',`
键是构建上下文里的相对路径,值是文件内容;与 Dockerfile 一起保存。
`); - if(state.assetType==='environments')return pane('script',`
脚本保存在环境资产里。Studio 保存即写库;下次沙箱初始化会按库里这份执行,把工具装进 $PREFIX。不要往宿主机写。脚本内容变化后会重新安装。
`)+pane('vars',``)+pane('path',``); - if(state.assetType==='sandboxes')return pane('env',`
叠加到沙箱基础环境并随资产持久化;不要在这里保存凭证。平台凭证、HOME/TMPDIR 和遥测变量拥有更高优先级。
`); + if(state.assetType==='sandboxes')return pane('setup',sandboxSetupHTML(a)); return ''; } function assetBasicFieldsHTML(a,{creating}){ const kind=assetKindLabel(); let html=`
${creating?'创建后不可修改,用于资产引用。':'标识用于资产引用,创建后不可修改。'}
`; if(state.assetType==='rules')html+=`
数值越大越先注入。
${ruleGlobalFields(a)}`; - if(state.assetType==='sandboxes')html+=`
直接在本机 workspace 执行,并继承受控的宿主进程环境。
按执行机器的系统自动选择:macOS 用 seatbelt,Linux 用 bwrap。
选中后沙箱会执行该环境的 install.sh,把工具装进隔离的 $PREFIX,再用 PATH 切换。未选择时,若 workspace 存在 agentflow-environment/ 也会自动启用。
沙箱只引用这条目录资产;初始化时用库里的内容构建临时镜像,结束后删除容器和镜像。
-
- - - - - -
`; return html; } function assetAsideHTML(a,{creating}){ @@ -375,9 +381,7 @@ function renderAssetForm(a){ if(state.assetType==='sandboxes'){ f.elements.driver.onchange=()=>syncSandboxDriverFields(f.elements.driver); syncSandboxDriverFields(f.elements.driver); - f.querySelector('#assetReadOnlyRootFSHelp')?.addEventListener('click',event=>{ - window.HuiTooltip?.show(event.currentTarget); - }); + f.querySelectorAll('.field-help').forEach(button=>button.addEventListener('click',event=>window.HuiTooltip?.show(event.currentTarget))); } f.querySelectorAll('select.asset-select').forEach(sel=>window.enhanceSelect?.(sel)); if(readonly)f.querySelectorAll('input,textarea,select,.repo-picker-tag').forEach(el=>{if(el.type!=='file')el.disabled=true}); @@ -701,10 +705,8 @@ async function openSkillFilePreview(skill, path, opener){ async function saveAsset(e){e.preventDefault();const f=e.currentTarget,items=state.data[state.assetType]||[],projectScoped=isProjectSharedAsset(state.assetType),identity=resolveAssetSaveIdentity(items,state.selectedAsset,f.elements.id.value.trim());if(identity.error)return toast(identity.error);const existing=identity.existing;if(existing&&projectScoped&&catalogForeign(existing.projectId))return toast('共享资产只读');let value={id:identity.id,name:f.elements.name.value.trim(),description:f.elements.description.value,projectId:existing?(existing.projectId||''):(state.projectFilter||''),shared:projectScoped&&!!existing?.shared};if(!value.id||!value.name)return toast('标识和名称不能为空');try{ if(state.assetType==='rules'){const global=!!f.elements.global?.checked;Object.assign(value,{priority:Number(f.elements.priority.value),content:f.elements.content.value,global,workflowIds:global?selectedRuleWorkflowIds():[]})} if(state.assetType==='skills'){/* 文件经独立上传接口承载;此处只提交元数据。服务端会强制保留 Content/Files/FileRefs。 */} - if(state.assetType==='dockerfiles')Object.assign(value,{content:f.elements.content.value,files:JSON.parse(f.elements.files.value||'{}')}); - if(state.assetType==='environments')Object.assign(value,{variables:JSON.parse(f.elements.variables.value||'{}'),pathEntries:lines(f.elements.pathEntries.value),installScript:f.elements.installScript.value}); - if(state.assetType==='sandboxes'){const driver=f.elements.driver.value,sandbox={driver,environment:JSON.parse(f.elements.environment.value||'{}')};if(driver==='docker')Object.assign(sandbox,{dockerfileId:f.elements.dockerfileId.value,readOnlyRootFS:f.elements.readOnlyRootFS.checked});if(driver==='native')Object.assign(sandbox,{environmentId:f.elements.environmentId.value});Object.assign(value,sandbox)} - const endpoints={rules:'rules',skills:'skills',dockerfiles:'dockerfiles',environments:'environments',sandboxes:'sandboxes'};await api(`/api/${endpoints[state.assetType]}`,{method:'PUT',body:JSON.stringify(value)});const i=items.findIndex(x=>x.id===value.id);if(state.assetType==='skills'&&existing)value={...existing,...value,fileRefs:existing.fileRefs||[],content:existing.content||'',files:existing.files||{}};if(i>=0)items[i]=value;else items.push(value);state.selectedAsset=value.id;state.assetDirty=false; + if(state.assetType==='sandboxes'){const driver=f.elements.driver.value,sandbox={driver,environment:JSON.parse(f.elements.environment.value||'{}')};if(driver==='docker')Object.assign(sandbox,{dockerfile:{content:f.elements.dockerfileContent.value,files:JSON.parse(f.elements.dockerfileFiles.value||'{}')},readOnlyRootFS:f.elements.readOnlyRootFS.checked});Object.assign(value,sandbox)} + const endpoints={rules:'rules',skills:'skills',sandboxes:'sandboxes'};await api(`/api/${endpoints[state.assetType]}`,{method:'PUT',body:JSON.stringify(value)});const i=items.findIndex(x=>x.id===value.id);if(state.assetType==='skills'&&existing)value={...existing,...value,fileRefs:existing.fileRefs||[],content:existing.content||'',files:existing.files||{}};if(i>=0)items[i]=value;else items.push(value);state.selectedAsset=value.id;state.assetDirty=false; if(identity.created){history.replaceState(history.state,'',assetViewHash(state.assetType,value.id));state.assetDetailKey='';renderAssets()} else{renderAssetDetailHead(value);refreshAssetAside(value)} renderWorkflowMeta();renderProperties();toast(identity.created?'资产已创建':'资产修改已保存'); diff --git a/web/app/assistant-settings.js b/web/app/assistant-settings.js index 3f177daa0..f409b798f 100644 --- a/web/app/assistant-settings.js +++ b/web/app/assistant-settings.js @@ -1,5 +1,6 @@ -// AI 助手设置:生成中消息的发送方式、主动派发、帮我批准审查模型(跟随当前对话 / 自定义 CLI / 自定义 API),以及每轮自定义规则。只对当前用户生效。 +// AI 助手设置:生成中消息的发送方式、主动派发、对话工作区倾向、帮我批准审查模型(跟随当前对话 / 自定义 CLI / 自定义 API),以及每轮自定义规则。只对当前用户生效。 const ASSISTANT_RULES_MAX=4000; +const ASSISTANT_WORKSPACE_DRIVERS=[['','由 Agent 选择'],['docker','Docker'],['native','系统轻量隔离']]; const ASSISTANT_REVIEW_MODEL_MAX=160; const ASSISTANT_REVIEW_CUSTOM='__custom__'; const ASSISTANT_REVIEW_MODES=[ @@ -153,6 +154,7 @@ function assistantPrefsDraft(form){ proactiveRoles:form.proactiveRoles.checked, proactiveSops:form.proactiveSops.checked, steerOnSend:form.messageDuringGeneration?.value==='steer', + workspaceDriver:form.workspaceDriver.value, approvalReviewMode:mode, approvalReviewModel:String(form.approvalReviewModel?.value||'').trim(), instructions:form.instructions.value.trim(), @@ -171,6 +173,7 @@ function assistantPrefsDirty(form){ if(draft.proactiveRoles!==!!saved.proactiveRoles|| draft.proactiveSops!==!!saved.proactiveSops|| draft.steerOnSend!==!!saved.steerOnSend|| + draft.workspaceDriver!==(saved.workspaceDriver||'')|| draft.instructions!==(saved.instructions||'')|| draft.approvalReviewMode!==savedMode)return true; if(draft.approvalReviewMode==='cli'){ @@ -338,6 +341,10 @@ function assistantPrefsFormHTML(p){ ${assistantPrefsSwitchRow('proactiveRoles','主动派角色','整件事是某个角色的本职(如独立评审、整套测试),或改了高风险代码需要复核时,直接交给这个角色。',p.proactiveRoles)} ${assistantPrefsSwitchRow('proactiveSops','主动走 SOP','遇到要落到仓库的新需求时,先交给项目里用途对得上的 SOP,而不是自己直接改代码。',p.proactiveSops)} +

对话工作区

会话里没有固定运行环境时,AI 助手自己选择在哪类沙箱里打开工作区。

+

帮我批准审查模型

「帮我批准」模式由 AI 独立审查平台及外部操作并直接放行或拒绝,无需人工审批。默认沿用当前对话的 CLI 与模型(最低思考强度);也可指定已配置的 CLI 模型或独立轻量 API 节省 Token。

@@ -409,6 +416,7 @@ function captureAssistantPrefsRenderModel(form){ proactiveRoles:form.proactiveRoles.checked, proactiveSops:form.proactiveSops.checked, steerOnSend:form.messageDuringGeneration?.value==='steer', + workspaceDriver:form.workspaceDriver.value, approvalReviewMode:assistantReviewModeOf({approvalReviewMode:form.approvalReviewMode?.value}), approvalReviewModel:String(form.approvalReviewModel?.value||'').trim(), approvalReviewApi:{ diff --git a/web/app/flows.js b/web/app/flows.js index 12116cd4f..14dbc11db 100644 --- a/web/app/flows.js +++ b/web/app/flows.js @@ -878,7 +878,7 @@ function renderAgentAssetsPanel(a){ const host=$('#agentAssetsPanel');if(!host)return; const d=ensureAgentDraft(a); const generic=catalogGeneric(state.workflow); - const col=(title,sub,name,items,selected)=>{const vis=name==='mcpServers'?(generic?(items||[]):visibleMCPAssets(items)):(name==='rules'||name==='skills'?(items||[]).filter(item=>catalogVisible(item.projectId,item.shared)):visibleAssets(items));const picked=vis.filter(item=>name==='mcpServers'&&generic?genericMCPChecked(item.id,selected):(selected||[]).includes(item.id)).length;const empty=name==='mcpServers'?(generic?'通用模板绑定市场别名(如 github),运行时落到当前项目已安装的 MCP':'这个项目或你的个人范围还没有 MCP,先到「MCP 管理」里添加'):name==='rules'?'这个项目还没有可用规则,先到「规则管理」里添加或共享':name==='skills'?'这个项目还没有可用技能,先到「技能管理」里添加或共享':'这个项目还没有此类配置,先到「环境资产」里添加';return `
${title}${sub}${picked?` · 已选 ${picked}`:''}
${vis.map(x=>``).join('')||`
${empty}
`}
`}; + const col=(title,sub,name,items,selected)=>{const vis=name==='mcpServers'?(generic?(items||[]):visibleMCPAssets(items)):(name==='rules'||name==='skills'?(items||[]).filter(item=>catalogVisible(item.projectId,item.shared)):visibleAssets(items));const picked=vis.filter(item=>name==='mcpServers'&&generic?genericMCPChecked(item.id,selected):(selected||[]).includes(item.id)).length;const empty=name==='mcpServers'?(generic?'通用模板绑定市场别名(如 github),运行时落到当前项目已安装的 MCP':'这个项目或你的个人范围还没有 MCP,先到「MCP 管理」里添加'):name==='rules'?'这个项目还没有可用规则,先到「规则管理」里添加或共享':name==='skills'?'这个项目还没有可用技能,先到「技能管理」里添加或共享':'这个项目还没有此类配置,先到「沙箱管理」里添加';return `
${title}${sub}${picked?` · 已选 ${picked}`:''}
${vis.map(x=>``).join('')||`
${empty}
`}
`}; host.innerHTML=`
平台能力独立开关,不占用 MCP 列表
${col('必须遵守','规则','rules',state.data.rules,d.rules)}${col('怎么干活','技能','skills',state.data.skills,d.skills)}${col('外部工具','MCP','mcpServers',generic?genericTemplateMCPOptions(d.mcpServers):state.data.mcpServers,d.mcpServers)}
运行时 Hook在工具调用前后插一段脚本,比如拦危险命令。一般可以先不配。
`; host.querySelectorAll('[data-asset-filter]').forEach(input=>input.oninput=()=>{const q=input.value.trim().toLowerCase();input.closest('.as-asset-col').querySelectorAll('.as-asset-item').forEach(row=>row.hidden=!!q&&!row.textContent.toLowerCase().includes(q))}); host.querySelectorAll('input[type=checkbox]').forEach(el=>el.onchange=()=>{renderAgentSummary();dirty()}); @@ -1153,8 +1153,7 @@ function sopSandboxChoices(){ return (state.data.sandboxes||[]).filter(s=>s.id&&catalogVisible(s.projectId,s.shared)); } function defaultSOPSandbox(choices=sopSandboxChoices(),preferredId){ - const isolated=choices.filter(s=>sandboxDriverOption(s.driver)!=='local'); - return isolated.find(s=>s.id===preferredId)||isolated.find(s=>catalogOwned(s.projectId))||isolated[0]; + return choices.find(s=>s.id===preferredId)||choices.find(s=>catalogOwned(s.projectId))||choices[0]; } function syncSOPSandboxSelection(){ const select=$('#sopCreateSandbox'),template=(state.data.workflows||[]).find(w=>w.id===state.sopTemplate); diff --git a/web/app/harness-motion.js b/web/app/harness-motion.js index 73c725df0..bef4689e2 100644 --- a/web/app/harness-motion.js +++ b/web/app/harness-motion.js @@ -1150,7 +1150,7 @@ sops: "workflow", runs: "runs", management: "dashboard", runners: "server", settings: "settings", bots: "robot", assistant: "sparkles", projects: "users", flow: "workflow", agents: "user", mcp: "connector", rules: "doc", skills: "skills", - dockerfiles: "layers", environments: "terminal", sandboxes: "server", + sandboxes: "layers", observability: "token", guide: "key", platform: "gate", }; const controls = { diff --git a/web/assets_detail_test.js b/web/assets_detail_test.js index 59c1d21cf..42e9de31e 100644 --- a/web/assets_detail_test.js +++ b/web/assets_detail_test.js @@ -49,8 +49,8 @@ function reset(type, data) { assetType: type, selectedAsset: null, assetQuery: '', - ruleScope: 'project', skillScope: 'project', dockerfileScope: 'project', environmentScope: 'project', sandboxScope: 'project', - data: { projects: [{ id: 'p1', name: '本项目' }, { id: 'p2', name: '平台公共' }], agents: [], sandboxes: [], workflows: [], rules: [], skills: [], dockerfiles: [], environments: [], ...data }, + ruleScope: 'project', skillScope: 'project', sandboxScope: 'project', + data: { projects: [{ id: 'p1', name: '本项目' }, { id: 'p2', name: '平台公共' }], agents: [], sandboxes: [], workflows: [], rules: [], skills: [], ...data }, }; } @@ -80,7 +80,7 @@ for (const html of [own, shared, foreign]) { assert.ok(!/data-(share|delete)-asset/.test(html), 'share/delete moved off the card'); assert.ok(!/class="[^"]*\bopen\b/.test(html), 'card classes must not collide with .open menu state'); } -for (const [type, icon] of [['rules', 'gate'], ['skills', 'skills'], ['dockerfiles', 'layers'], ['environments', 'terminal'], ['sandboxes', 'server']]) { +for (const [type, icon] of [['rules', 'gate'], ['skills', 'skills'], ['sandboxes', 'server']]) { assert.strictEqual(ctx.assetIconName(type), icon); } @@ -128,6 +128,10 @@ reset('sandboxes', { sandboxes: [{ id: 'generic-docker', name: '通用 Docker', head = ctx.assetDetailHeadHTML(ctx.state.data.sandboxes[0], {}); assert.ok(head.includes('内置沙箱 generic-docker 不能删除'), 'builtin reason'); assert.ok(ctx.assetOverviewCardHTML(ctx.state.data.sandboxes[0]).includes('
类型
内置
')); +assert.ok(ctx.assetCardHTML({ id: 'd', projectId: 'p1', driver: 'docker', dockerfile: { content: 'FROM x\nRUN y\n' } }).includes('Dockerfile 2 行')); +assert.ok(ctx.assetCardHTML({ id: 'd', projectId: 'p1', driver: 'docker' }).includes('Docker')); +assert.ok(ctx.assetCardHTML({ id: 'n', projectId: 'p1', driver: 'seatbelt' }).includes('系统轻量隔离')); +assert.ok(ctx.assetCardHTML({ id: 'l', projectId: 'p1', driver: 'local' }).includes('系统轻量隔离'), 'an unmigrated local row reads as native'); reset('skills', {}); ctx.state.selectedAsset = '__new__'; @@ -158,7 +162,7 @@ function fakeForm(values) { return { elements, querySelectorAll: () => [], querySelector: () => null }; } function renderedFieldNames(type, asset) { - const form = { innerHTML: '', elements: { driver: { value: asset.driver || 'local', form: null } }, querySelectorAll: () => [], querySelector: () => null }; + const form = { innerHTML: '', elements: { driver: { value: asset.driver || 'docker', form: null } }, querySelectorAll: () => [], querySelector: () => null }; const saved$ = ctx.$; ctx.$ = sel => (sel === '#assetForm' ? form : null); ctx.state.selectedAsset = asset.id; @@ -188,18 +192,14 @@ async function save(type, existing, values) { { id: 's', ...base }, { id: 's', name: 'N', description: 'D', projectId: 'p1', shared: false }, ['description', 'id', 'name']], - ['dockerfiles', { id: 'd', projectId: 'p1' }, - { id: 'd', ...base, content: 'FROM x', files: '{"a":"b"}' }, - { id: 'd', name: 'N', description: 'D', projectId: 'p1', shared: false, content: 'FROM x', files: { a: 'b' } }, - ['content', 'description', 'files', 'id', 'name']], - ['environments', { id: 'e', projectId: 'p1' }, - { id: 'e', ...base, variables: '{"V":"1"}', pathEntries: 'bin\n sbin ', installScript: 'echo' }, - { id: 'e', name: 'N', description: 'D', projectId: 'p1', shared: false, variables: { V: '1' }, pathEntries: ['bin', 'sbin'], installScript: 'echo' }, - ['description', 'id', 'installScript', 'name', 'pathEntries', 'variables']], - ['sandboxes', { id: 'x', projectId: 'p1', driver: 'docker' }, - { id: 'x', ...base, driver: 'docker', environment: '{}', dockerfileId: 'df', readOnlyRootFS: true, environmentId: 'env' }, - { id: 'x', name: 'N', description: 'D', projectId: 'p1', shared: false, driver: 'docker', environment: {}, dockerfileId: 'df', readOnlyRootFS: true }, - ['description', 'dockerfileId', 'driver', 'environment', 'environmentId', 'id', 'name', 'readOnlyRootFS']], + ['sandboxes', { id: 'x', projectId: 'p1', driver: 'docker', dockerfile: { content: 'FROM old' } }, + { id: 'x', ...base, driver: 'docker', environment: '{}', dockerfileContent: 'FROM x', dockerfileFiles: '{"a":"b"}', readOnlyRootFS: true }, + { id: 'x', name: 'N', description: 'D', projectId: 'p1', shared: false, driver: 'docker', environment: {}, dockerfile: { content: 'FROM x', files: { a: 'b' } }, readOnlyRootFS: true }, + ['description', 'dockerfileContent', 'dockerfileFiles', 'driver', 'environment', 'id', 'name', 'readOnlyRootFS']], + ['sandboxes', { id: 'n', projectId: 'p1', driver: 'native' }, + { id: 'n', ...base, driver: 'native', environment: '{"JAVA_HOME":"/opt/jdk"}', dockerfileContent: 'FROM x', dockerfileFiles: '{}', readOnlyRootFS: true }, + { id: 'n', name: 'N', description: 'D', projectId: 'p1', shared: false, driver: 'native', environment: { JAVA_HOME: '/opt/jdk' } }, + ['description', 'dockerfileContent', 'dockerfileFiles', 'driver', 'environment', 'id', 'name', 'readOnlyRootFS']], ]; for (const [type, existing, values, body, fields] of cases) { assert.deepStrictEqual(await save(type, existing, values), body, `${type} save payload`); diff --git a/web/assistant_settings_test.js b/web/assistant_settings_test.js index 7045b79f0..e40095a57 100644 --- a/web/assistant_settings_test.js +++ b/web/assistant_settings_test.js @@ -65,6 +65,9 @@ assert.match(html, /id="assistantPrefsSave" disabled/); assert.match(html, /