diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 94212d09..fb9c6d7a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -24,12 +24,40 @@ jobs: runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v4 + with: + fetch-depth: 2 - run: rustup toolchain install 1.93.0 --profile minimal --component clippy,rustfmt --target ${{ matrix.target }} - uses: actions/setup-node@v4 with: node-version: 24.15.0 - - run: node --test native/pi/tests/tool-environment.test.mjs + - run: node --test native/pi/tests/*.test.mjs - run: cargo fmt --check - - run: cargo check --locked --all-targets - run: cargo clippy --locked --all-targets -- -D warnings - run: cargo test --locked --all-targets + - name: Verify the installed Pi runtime and factory cleanup + if: matrix.name == 'linux' + env: + BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.before }} + BRAID_TEST_PI_INSTALL: ${{ runner.temp }}/pi-background + PI_OFFLINE: '1' + run: | + if git cat-file -e "$BASE_SHA^{commit}" 2>/dev/null && + git diff --quiet "$BASE_SHA" HEAD -- native/pi src/config.rs src/provider src/profile_materials.rs src/profile_materials src/agent_session.rs Cargo.toml Cargo.lock .github/workflows/ci.yml; then + echo 'Installed Pi inputs unchanged' + exit 0 + fi + node native/pi/install.mjs "$BRAID_TEST_PI_INSTALL" --plugins background + "$BRAID_TEST_PI_INSTALL/bin/node" --test native/pi/acceptance/installed-runtime.test.mjs + cargo test --locked --bin braid profile_materials::tests::failed_home_binding_stops_the_installed_execution_before_returning -- --ignored --exact + - name: Verify conflicting Console edits in two browser pages + if: matrix.name == 'linux' + env: + CHROME_BIN: /usr/bin/google-chrome + run: | + npm ci --prefix tests/browser --ignore-scripts + node --test tests/browser/draft.test.mjs + - name: Verify OTLP internal diagnostics stay out of ordinary logs + if: matrix.name == 'linux' + run: >- + cargo test --locked --bin braid --features opentelemetry-otlp/internal-logs + telemetry::tests::telemetry_isolates_collector_rejection_bodies_from_ordinary_diagnostics -- --exact diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d2201a23..db7315ba 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,6 +1,19 @@ name: release on: + pull_request: + paths: + - '.github/workflows/release.yml' + - 'scripts/package.sh' + - 'scripts/verify-package.sh' + - 'Cargo.toml' + - 'Cargo.lock' + - 'rust-toolchain.toml' + - 'config.example.toml' + - 'deploy/otel-collector.example.yaml' + - 'LICENSE' + - 'README.md' + - 'CHANGELOG.md' push: tags: - "v*" @@ -11,7 +24,7 @@ on: required: true permissions: - contents: write + contents: read jobs: build: @@ -32,9 +45,15 @@ jobs: shell: bash env: BRAID_BUILD_TARGET: ${{ matrix.target }} - BRAID_RELEASE_TAG: ${{ github.event.inputs.version || github.ref_name }} - run: scripts/package.sh + BRAID_RELEASE_TAG: ${{ github.event.inputs.version || (github.event_name == 'push' && github.ref_name) || '' }} + run: | + if [[ -z "$BRAID_RELEASE_TAG" ]]; then + BRAID_RELEASE_TAG=$(python3 -c 'import tomllib; print("v" + tomllib.load(open("Cargo.toml", "rb"))["package"]["version"])') + fi + scripts/package.sh + scripts/verify-package.sh dist "$BRAID_RELEASE_TAG" "$BRAID_BUILD_TARGET" - uses: actions/upload-artifact@v4 + if: github.event_name != 'pull_request' with: name: release-${{ matrix.target }} path: | @@ -43,6 +62,9 @@ jobs: if-no-files-found: error release: + if: github.event_name != 'pull_request' + permissions: + contents: write needs: build runs-on: ubuntu-latest steps: diff --git a/.gitignore b/.gitignore index cac6f90b..edf4fcf8 100644 --- a/.gitignore +++ b/.gitignore @@ -13,3 +13,5 @@ svc.local.json AGENTS.local.md # svc:end local-config + +/tests/browser/node_modules/ diff --git a/AGENTS.md b/AGENTS.md index 5c061937..9f11ba08 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -68,6 +68,13 @@ this repository; do not modify user-scope Agent instructions. - Product acceptance is real black-box GitHub-to-Agent behavior. Compile, formatting, lint, protocol probes, and diagnostic scripts support delivery but do not substitute for `docs/10-prd/acceptance.md`. +- Route regressions through the owner of the decision. Use the built binary for + CLI, process and browser contracts, and the existing binary unit target for + private Rust modules. Importing source files into integration tests registers + their unit tests again under a different executable. +- A restart claim needs a durable write and a fresh reader. Assert the reason for + rejection with otherwise valid prerequisites. When retiring a fixture, check + its callers outside tests and remove any accessors needed solely by that fixture. - The Agent may make coherent verified commits in this repository without per-commit approval. Pushes, releases, external GitHub mutations, and changes outside this repository retain their own authority gates. diff --git a/README.md b/README.md index d5d0cfe3..d4cc6c95 100644 --- a/README.md +++ b/README.md @@ -147,3 +147,4 @@ repository workflow, see the [documentation index](docs/index.md) and Braid 使用编译、回归测试、实际操作及获授权实验取得反馈。测试验证局部行为和故障边界;真实 GitHub、provider 和 OTel 原始证据及人工判断构成产品验收依据。 +开发验证命令、测试归属及不能由本地回归证明的范围见[验证分层](docs/10-prd/acceptance.md#开发回归与产品验收的分层)。 diff --git a/docs/10-prd/acceptance.md b/docs/10-prd/acceptance.md index e1703e97..bd639259 100644 --- a/docs/10-prd/acceptance.md +++ b/docs/10-prd/acceptance.md @@ -29,6 +29,68 @@ events are never pass oracles. 验收按本页描述操作真实产品并保留原始证据。自动测试、模拟和包 smoke 可验证 局部实现,但不能替代本页的真实产品验收。GitHub 对象和人工判断仍是产品验收依据。 +## 开发回归与产品验收的分层 + +修改代码时,先运行所属边界的回归,再由 CI 验证 macOS arm64 和 Linux x86_64。 +每个测试须能指出具体可信回归;不同层保护不同风险时分别保留。不要为了减少 +测试数量删除协议、数据库兼容、授权或停止证明,也不要把测试自建的配置、状态机 +或回执当作生产实现的证明。 + +| 契约 | 主要自动证明归属 | 仍需真实验收的部分 | +| --- | --- | --- | +| 配置、凭据导入、headless setup、公开回执 | `tests/` 中实际 binary 子进程;配置与 doctor 的局部不变式 | GitHub App 转换、登录、provider 认证与安装后的工具环境 | +| GitHub 准入、完整读取、发布及 uncertain 写入 | `producer`、`context`、`github`、`writer` 的生产 owner,外部 HTTP 固定夹具 | 实际 webhook、GitHub 权限、native 关联及跨仓库行为 | +| durable intent、租约、迁移和重放 | `store` 的真实 SQLite actor;旧 schema 建库、备份还原、关闭重开 | 已发布旧 binary 升级及现场恢复,不能以直接造库代替 | +| Context 替换和 provider 事件 | `group`、`provider` 的真实编排;受控外部会话通知和停止回执 | 真实模型消费新 Context、适配器后台执行停止、长轮次中撤销职责 | +| 内建对象与观测存储 | `platform`、`console` 的 HTTP→SQLite/Git 回归、真实 Console 二进制和两页并发编辑;独立 OTLP 编码器输入 | 完整操作旅程、实际 Harness 与跨宿主运行 | +| 原生执行与材料 | Node 真实进程树、已安装的 Pi background 插件与 RPC;Profile snapshot 和 auth 文件重新读取 | 其余插件组合、真实模型工具调用及跨宿主进程行为 | +| 采样与完整敏感证据 | `telemetry` 中真实 SDK→HTTP→protobuf;每次独立子进程初始化 SDK | 生产 Collector 的权限、保留、查询及完整长旅程关联 | + +默认入口与 `.github/workflows/ci.yml` 一致: + +```shell +cargo fmt --check +agent-build cargo clippy --locked --all-targets -- -D warnings +agent-build cargo test --locked --all-targets +node --test native/pi/tests/*.test.mjs +``` + +`agent-build` 是本机编译串行入口;CI 直接运行相同 Cargo 命令。局部迭代可加 +`--bin braid <模块名>::` 或 `--test <文件名>` 筛选。Linux CI 另启用 +`opentelemetry-otlp/internal-logs`,单独复跑 +`telemetry::tests::telemetry_isolates_collector_rejection_bodies_from_ordinary_diagnostics`, +验证 SDK 开启内部诊断时,Collector 返回的敏感正文仍不会进入普通日志。 +这不改变发行 binary 的 feature。标为 ignored 的 `telemetry_child` 只供父测试 +用独立子进程调用,父测试负责检查退出状态与所有输出;不能单独计作通过。 + +Linux CI 在同一次 Cargo 构建后启动一个独立平台,从两个 Chromium 页面编辑同一 +Issue。先提交的一页保存成功,过期页面显示该对象的修订冲突并保留正文;取消刷新 +保留草稿,确认放弃后重新打开才读到已提交正文。复跑时使用本次构建的二进制: + +```shell +npm ci --prefix tests/browser --ignore-scripts +BRAID_BINARY=/absolute/path/to/braid CHROME_BIN=/absolute/path/to/chromium \ + node --test tests/browser/draft.test.mjs +``` + +Pi 安装或 Rust 适配器变更时,Linux CI 复用本轮编译并按 lock 安装 background +插件。安装包自带的 Node 验证真实 RPC、工具执行和 EOF 退出。Rust 工厂用例使材料绑定 +在原生启动后失败,并读取工厂返回前留在该执行目录的停止回执。安装步骤需要访问发行 +站点和 npm。其它插件组合和含模型会话各自单独记录。修改打包入口、编译锁或包内材料的 PR,以及实际发行均在两个目标平台运行 +`scripts/verify-package.sh DIST RELEASE_TAG RUST_TARGET`;它从校验和指定的 +归档中运行 binary,核对版本、示例配置及迁移后重开的数据库。 + +负向用例应断言错误阶段、类型或关键诊断,并有能够到达该守卫的合法前置条件。 +恢复用例应先让真实 owner 写入,关闭并重新打开,再从消费者取回结果。新缺陷 +修复保留同一输入下修复前红、修复后绿的证据。两份 checkout 做对照时,各设独立 +`CARGO_TARGET_DIR`:Cargo 集成测试按固定路径启动 binary,共享 target 曾使另一份 +checkout 的同名产物被当成最新。核对运行的测试名和失败诊断;缺少对照时说明原因。删除或 +迁移测试前,核对原断言在保留测试中的归属;仅重复编译同一模块不算额外证明。 + +全绿支持上述局部合同,不授予产品发布资格。真实 campaign 仍按下列场景记录 +`pass`、`fail` 或 `unavailable`,尤其不得把 Provider terminal、HTTP 请求受理或 +命令 `prepared` 回执当作任务完成、持久采用或停止确认。 + ## Campaign Setup Create a real Issue whose description contains a distinguishable design fact, @@ -46,6 +108,25 @@ installation exposes native Agent App assignment or uses the Trusted Braid Mention fallback; the campaign must not claim one mode while exercising the other. +### 固定真实 Context 夹具 + +在专用 campaign 配置上记录 Issue、PR、直接关联的已关闭 Issue、可见评论、 +折叠/删除评论 ID、一个仅出现在第二页的评论标记,以及各自的预期正文片段。 +独立预期来自操作者预先创建的工作项和 GitHub 页面。固定夹具后,在权限受限的 +证据目录执行以下公开命令。命令会在 campaign 的本地账本中记录读取到的修订。 + +```shell +"$BRAID_BIN" context issue "$ISSUE" --config "$CONFIG" --page-size 1 > "$EVIDENCE/issue.md" +"$BRAID_BIN" context pr "$PR" --config "$CONFIG" --page-size 1 > "$EVIDENCE/pr.md" +``` + +逐项用真实 GitHub 页面和预先记录的预期核对输出。完整可见正文和后页标记必须 +出现,折叠/删除评论只含各自的元数据,隐藏标记不出现;PR 的关联 Issue 身份与 +数量符合 GitHub,已关闭 Issue 的旧正文不出现。记录每项输入、对象身份和 +pass/fail/unavailable。对超过 hard limit 的独立配置,分别保留 stdout、stderr +和退出码:必须因 Context 超限失败且 stdout 没有部分正文。缺少对应夹具时 +该项为 unavailable。关于 Agent 实际收到、采用哪版 Context,按旅程 1、3、4 取证。 + ## Required Journeys ### 1. Activation and Initial Context diff --git a/docs/20-product-tdd/README.md b/docs/20-product-tdd/README.md index bccccd9a..1269799c 100644 --- a/docs/20-product-tdd/README.md +++ b/docs/20-product-tdd/README.md @@ -324,8 +324,14 @@ Console 的 OTLP Collector 保存原始传输批次与完整解码记录,使 平台通过有类型的应用命令修改对象。命令 request ID、内容摘要、预期 revision 与回执持久保存在平台库;普通对象变更与事件、回执一起提交, -并发正文修改不会覆盖新 revision。发布和合并保留 Git/SQLite 意图边界,不能用 -外层数据库事务假装跨系统原子化。浏览器只能选择固定 source 或由 Harness 验证的候选,不能提供任意路径。 +并发正文修改不会覆盖新 revision。发布候选的对象更新、事件与成功回执也在同一 +SQLite 事务提交;Git 保留引用不代替数据库中的候选事实。合并在 Git CAS 前将 +请求 ID、精确合并 commit 与原 writer 来源绑定到持久意图;CAS 仍验证当前授权和 +revision。最终合并状态、对象关闭、撤权、事件与成功回执一起提交。相同请求的恢复 +只在当前目标引用等于绑定 commit 时确认已发生的效果,不重放 Git CAS,也不恢复 +writer 权限;原 writer 来源仅用于保持事件归属。旧无绑定回执或目标引用已经前移时 +保留未完成状态,交由操作者核实,不以 revision 推断结果归属。这一边界不提供跨 +Git/SQLite 的原子事务。浏览器只能选择固定 source 或由 Harness 验证的候选,不能提供任意路径。 `console::runtime` 持有实际 runtime task、停止通道与启动 generation。Collector 、平台和控制端点持续存活,Harness 可单独停止。GitHub 与内建上游通过统一 runtime 接口托管。请求接受不等于任务已就绪或已停止; diff --git a/docs/20-product-tdd/app-server.md b/docs/20-product-tdd/app-server.md index 609a2fc1..c07ef921 100644 --- a/docs/20-product-tdd/app-server.md +++ b/docs/20-product-tdd/app-server.md @@ -28,10 +28,9 @@ manifest 的文件。旧材料可由 operator 显式配置 `GH_CONFIG_DIR` 作 | `SessionFactory::start/resume` | 创建或恢复会话并返回中立句柄。Codex 内部共享 app-server,Pi 每个会话持有独立进程;上层接口相同。 | | `send_user_msg(msg, steering)` | Idle 时申请启动 turn;已知拒收返回 Deferred,queue 保留输入。Acknowledged 只代表原生执行明确接纳,结果不明返回具体 Unknown。 | | `steer_user_msg(msg, expected_turn_id)` | 只向已观察且仍匹配的 active turn 投递,不偷换为新 turn;明确拒收返回 Deferred,结果不明保留具体 Unknown。 | -| `interrupt()` | 尝试停止已观察到的 active turn;terminal 仍通过事件流返回。 | | `events()` | 将 provider 的响应与通知去重为 TurnStarted / TurnTerminal;dispatch 前订阅,同一 receiver 随 RunningAgentTurn 交给 driver。失效的 active handle 合成 Unknown,不能伪造失败。 | | `is_unavailable()` | 句柄失效后永久返回 true;idle 或晚订阅也可观察。恢复创建新句柄,不复活旧句柄。 | -| `close()` | 确认所属执行停止后释放资源;失败保留句柄与具体原因,阻断替代执行,不能影响其它会话。 | +| `close()` | adapter 先请求中断所属活动 turn,再确认执行停止并释放资源。关闭失败时保留句柄与原因,阻止替代执行。 | 具体 `AgentProvider` 接口只在 adapter 内使用。共享 Codex 进程退出会使其所有 句柄失效;独立 Pi 进程退出只影响所属句柄。释放旧句柄会取消旧监听任务, @@ -178,6 +177,9 @@ execution 静止,长期服务 busy 也不统一阻断普通输入。 锁定材料关闭先请求 owned stop,再释放 stdin 发送 EOF、等待父进程,最后用固定 Node 执行同一材料的离线清理并核对 exact execution 回执。Mac 与 Linux 都核对 OS 出生身份、 登记进程组和继承 execution 标记;身份或停止范围不明时返回 unknown。 +工厂创建或恢复 Pi 会话时,物理执行在句柄交给 Group 前归工厂所有。握手、会话绑定或初始 +Context 持久化失败后,工厂等待同一执行的关闭结果;清理未确认时,返回构造与清理两者的原因。 +原生 background Bash 工具各自记录命令退出码与进程树收口证据;清理不明时向调用者报告错误。 这不构成安全沙箱,也不追踪主动擦除标记、脱离登记范围的进程或撤销已发出的外部请求。 外部基础 Pi 仍使用 abort 与父退出依据,不声称具备插件后代清理合同。 diff --git a/docs/20-product-tdd/context.md b/docs/20-product-tdd/context.md index 6ef64417..c85ec81c 100644 --- a/docs/20-product-tdd/context.md +++ b/docs/20-product-tdd/context.md @@ -105,7 +105,9 @@ changes to them produce Event References when subscribed. Braid preserves original Markdown bytes except for actual HTML comment nodes. The Context projector parses GitHub Flavored Markdown, obtains source ranges for HTML inline/block comments beginning with `` inside fenced or inline +the original UTF-8 body. A block's closing line can also contain visible text; +only its actual comment delimiters and contents are removed, preserving that +suffix and any HTML attribute values. Text that resembles `` inside fenced or inline code remains. Malformed HTML that the parser does not recognize as a comment is ordinary visible text. diff --git a/docs/20-product-tdd/lifecycle.md b/docs/20-product-tdd/lifecycle.md index 61a113f1..db747454 100644 --- a/docs/20-product-tdd/lifecycle.md +++ b/docs/20-product-tdd/lifecycle.md @@ -20,7 +20,7 @@ Each Work Item/Profile pair has an Assignment Generation and one state: | `debouncing` | Wake Events are accumulating against one quiet deadline/count. | | `running` | One provider turn is active. | | `reset_pending` | Current Context was invalidated; old output is fenced while interruption/terminal converges. | -| `sleeping` | Closed/unassigned lifecycle retained for possible reopen/reassignment policy. | +| `sleeping` | Closed lifecycle retained for a possible reopen. | | `retired` | Merged PR or superseded generation; no automatic resume. | | `blocked` | Complete Context, Profile, provider, worktree, or external authority is unavailable. | @@ -118,11 +118,14 @@ classified as Agent-origin. ## Assignment and Terminal Lifecycle -- In native Agent App assignment mode, Issue unassignment starts/resets the - same Quiet Window. Once settled, Braid safely interrupts an active turn, - archives its physical session, and moves the generation to `sleeping`. - Reassignment starts a new generation/session. Ordinary-App mention fallback - does not fabricate assign/unassign lifecycle events. +- GitHub 原生指派模式按 Quiet Window 合并 Issue 撤销指派事件。窗口到期后, + Group 重读当前 assignees。若仍已指派则消费这次事件。确认撤销时,正在执行的 + worker 和空闲 worker 使用同一停止流程。内建平台直接处理不可撤回的撤销事件。 + Group 在关闭期间继续接收原有 turn 的终态。平台撤权暂时失败时,已经收到的终态与 + 错误仍须持久化。原生停止和平台撤权均已确认后,Group 才将该代记为 `retired`; + 此时仍缺 provider 终态的 turn 记为 `unknown`,并按该 Profile 的配置发布执行状态。 + 若原生停止已保存而撤销尚未完成,重启的 worker 沿原顺序结算撤销并确认平台 fence, + 保留已观察的终态,不恢复旧物理会话。该代未完成的 Context reset 保留在历史中,不再创建会话或阻止有限 run 完成。重新指派创建新一代及新会话。 - Issue/PR close or PR merge never interrupts the current turn. The lifecycle event grants exactly one Finalization Turn after the current terminal, or immediately when idle. Afterwards closed Issue and closed-unmerged PR groups @@ -223,10 +226,8 @@ Responsibilities do not overlap: - **`AgentSession`** only dispatches: idle, it starts a new turn; running and `steering`, it forwards input only to the expected active turn; running and not steering, it defers without accepting the message. It never queues; - redelivery is the queue's job. `interrupt()` is - the control-plane sibling of steering — an immediate operation on the - observed in-flight turn that carries termination rather than input; the - terminal still arrives via the event stream. + redelivery is the queue's job. The adapter handles native interruption as part + of confirming session shutdown. - **Group** 决定 Work Item 的物化、恢复、Context replacement、睡眠和退役, `SessionManager` 只索引中立句柄。替换完整 Context 不等于创建新的逻辑 Agent; adapter 的物理 ID 是可替换的执行绑定。 diff --git a/docs/user-manual/local.md b/docs/user-manual/local.md index 71350305..6a907a58 100644 --- a/docs/user-manual/local.md +++ b/docs/user-manual/local.md @@ -63,8 +63,16 @@ PR 保存固定的 base/head 提交;发布候选交接完整 commit OID,不 候选接续。合并是显式的候选采纳动作,不自动验收或关闭关联 Issue;拒绝冲突、 base 移动及不安全的检出状态。合并前将 source 和其它 worktree 切离目标 base。 -Git 引用与 SQLite 不是同一事务。合并意图持久保存,重复同一请求回读原回执; -若引用更新而记录未完成,重试核对实际引用后收敛,不重复应用代码。 +Git 引用与 SQLite 不是同一事务。平台在移动 Git 引用前,将请求 ID 与合并意图的 +精确 commit 一起持久保存;合并完成的对象状态、事件和成功回执在同一数据库事务中 +提交。若 Git 引用已更新而最终记录失败,保留原请求重试;只有当前目标引用仍指向 +该请求绑定的 commit 时,平台才补齐记录。此确认可以在原 writer 已撤权后完成, +不会重新移动 Git 引用或授予写权限。未被采用的合并不会借重试绕过撤权。 +候选发布的对象更新、事件和成功回执也一起提交,回执保存失败不会留下已发布状态。 + +旧版本遗留、未绑定精确 commit 的 prepared 回执,以及目标引用已经继续前移的 +未完成合并,不能自动判定归属。保留数据库、Git 引用和原请求现场,核实后再处理; +不要改写 request ID 或预期 revision 来冒充原请求恢复。 ## 从旧 Local 实例迁移 diff --git a/native/pi/README.md b/native/pi/README.md index c8fb8395..fb7d12ad 100644 --- a/native/pi/README.md +++ b/native/pi/README.md @@ -40,6 +40,18 @@ subagents、background、Context7 和 MCPorter 的局部补丁仅随相应插件 仍包含尚无公开接线点的插件内部修复及 owned process/service 登记。 它们不是无补丁上游发行,不应删掉停止或交接能力来换取零补丁。 +对全新安装仅选择 `background` 后,可直接验证交付的 Node、Pi SDK 与扩展、工具环境和停止回执。 +下面的验收使用临时 HOME、离线模型描述和本地 Bash,不需要模型账号。它也会检查新建 +session 文件和结束 RPC 输入后的进程退出。Rust 工厂用例在绑定失败时核对执行目录的离线停止回执。 +另一个用例通过 SDK 调用所选插件的 Bash 工具,检查命令退出 0 时仍能报告归属未确认。 + +```sh +node native/pi/install.mjs "$PWD/runtime/pi-background" --plugins background +export BRAID_TEST_PI_INSTALL="$PWD/runtime/pi-background" +"$BRAID_TEST_PI_INSTALL/bin/node" --test native/pi/acceptance/installed-runtime.test.mjs +PI_OFFLINE=1 agent-build cargo test --locked --bin braid failed_home_binding_stops_the_installed_execution_before_returning -- --ignored +``` + 锁定的 pi-subagents 0.56.0 对自定义角色 frontmatter 使用字符串列表解析, `fallbackModels: []` 和 `fallbackModels: false` 都会成为模型名称,不能用于禁用回退。 只有主模型时省略该字段;需要限制模型范围时配置插件的 modelScope,并通过实际 diff --git a/native/pi/acceptance/installed-runtime.test.mjs b/native/pi/acceptance/installed-runtime.test.mjs new file mode 100644 index 00000000..581b8092 --- /dev/null +++ b/native/pi/acceptance/installed-runtime.test.mjs @@ -0,0 +1,116 @@ +import assert from 'node:assert/strict'; +import { execFileSync, spawn } from 'node:child_process'; +import { randomUUID } from 'node:crypto'; +import { once } from 'node:events'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import readline from 'node:readline'; +import test from 'node:test'; +import { pathToFileURL } from 'node:url'; + +// Install once with --plugins background, then run against that candidate. +// This is a distribution test; the regular source tests need no npm install. +test('installed background-only Pi opens a fresh session, serves tools and closes the execution', async t => { + const candidate = process.env.BRAID_TEST_PI_INSTALL; + assert.ok(candidate && path.isAbsolute(candidate), 'set BRAID_TEST_PI_INSTALL to an absolute background-only installation'); + const install = fs.realpathSync(candidate); + const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'braid-pi-smoke-'))); + t.after(() => fs.rmSync(root, { recursive: true, force: true })); + const agentDir = path.join(root, 'pi-home'); + fs.mkdirSync(agentDir); + fs.writeFileSync(path.join(agentDir, 'models.json'), JSON.stringify({ + providers: { fixture: { baseUrl: 'http://127.0.0.1:1/v1', api: 'openai-completions', models: [{ id: 'offline' }] } }, + })); + const id = randomUUID(); + const start = randomUUID(); + const directory = path.join(root, 'execution'); + const session = path.join(root, 'fresh.jsonl'); + const env = { + PATH: '/usr/bin:/bin', HOME: root, PI_OFFLINE: '1', PI_CODING_AGENT_DIR: agentDir, + XDG_CONFIG_HOME: path.join(root, 'operator-config'), + BRAID_NATIVE_EXECUTION_DIR: directory, BRAID_NATIVE_EXECUTION_ID: id, BRAID_NATIVE_LAUNCH_START_ID: start, + }; + const pi = path.join(install, 'pi'); + const node = path.join(install, 'bin/node'); + const packageConfig = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')); + const expectedVersion = packageConfig.dependencies['@earendil-works/pi-coding-agent']; + assert.equal(execFileSync(pi, ['--version'], { cwd: root, env, encoding: 'utf8', timeout: 30000 }).trim(), expectedVersion); + const child = spawn(node, [ + path.join(install, 'process-owner.mjs'), 'launch', '--start-id', start, '--kind', 'root', '--', + pi, '--mode', 'rpc', '--session', session, '--provider', 'fixture', '--model', 'offline', + ], { cwd: root, env, detached: true, timeout: 30000 }); + const closed = once(child, 'close'); + let stderr = ''; + child.stderr.setEncoding('utf8').on('data', text => { stderr += text; }); + const responses = readline.createInterface({ input: child.stdout })[Symbol.asyncIterator](); + const request = async (type, fields = {}) => { + child.stdin.write(JSON.stringify({ id: type, type, ...fields }) + '\n'); + for (;;) { + const line = await responses.next(); + assert.equal(line.done, false, `Pi exited before ${type}: ${stderr}`); + const reply = JSON.parse(line.value); + if (reply.type !== 'response') continue; + assert.equal(reply.id, type); + assert.equal(reply.command, type); + assert.equal(reply.success, true, JSON.stringify(reply)); + return reply.data; + } + }; + try { + const state = await request('get_state'); + assert.equal(state.sessionFile, session); + assert.equal(state.model.provider, 'fixture'); + assert.equal(state.model.id, 'offline'); + assert.equal(state.managed_state.status, 'quiescent'); + assert.deepEqual(state.braid_native_runtime.extensions, [ + path.join(install, 'node_modules/pi-background-bash/extensions/background-bash.ts'), + ]); + const bash = await request('bash', { command: 'printf "%s\n%s" "$GH_CONFIG_DIR" "$XDG_CONFIG_HOME"', excludeFromContext: true }); + assert.equal(bash.exitCode, 0, JSON.stringify(bash)); + assert.equal(bash.output, [path.join(root, 'operator-config/gh'), path.join(directory, 'config')].join('\n')); + const handoff = await request('yield_stoppable_services'); + assert.equal(handoff.managed_state.status, 'quiescent'); + assert.equal(handoff.managed_state.execution_id, id); + const receipt = await request('stop_owned_execution'); + assert.equal(receipt.status, 'stopped', JSON.stringify(receipt)); + assert.equal(receipt.execution_id, id); + assert.equal(receipt.scope, 'root-descendants'); + } finally { + child.stdin.end(); + const [code, signal] = await closed; + assert.equal(signal, null, stderr); + assert.equal(code, 0, stderr); + } +}); + +test('installed background bash reports an unverified stop even when the command exits zero', async t => { + const install = fs.realpathSync(process.env.BRAID_TEST_PI_INSTALL); + const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'braid-pi-tool-'))); + t.after(() => fs.rmSync(root, { recursive: true, force: true })); + const directory = path.join(root, 'execution'); + const id = randomUUID(); + t.mock.property(process, 'env', { + HOME: root, PATH: '/usr/bin:/bin', PI_OFFLINE: '1', + BRAID_NATIVE_EXECUTION_ID: id, BRAID_NATIVE_EXECUTION_DIR: directory, + }); + await import(pathToFileURL(path.join(install, 'managed.mjs'))); + const sdk = await import(pathToFileURL(path.join(install, 'node_modules/@earendil-works/pi-coding-agent/dist/index.js'))); + const plugin = path.join(install, 'node_modules/pi-background-bash/extensions/background-bash.ts'); + const { extensions, errors } = await sdk.discoverAndLoadExtensions([plugin], root, root); + assert.deepEqual(errors, []); + const bash = extensions.find(extension => extension.tools.has('bash')).tools.get('bash').definition; + const invoke = () => bash.execute('foreground', { command: 'printf completed' }, undefined, undefined, { cwd: root }); + const result = await invoke(); + assert.deepEqual(result.content, [{ type: 'text', text: 'completed' }]); + + // A damaged registration prevents proving scope even after this new command exits. + fs.writeFileSync(path.join(directory, 'processes/damaged.json'), '{}'); + await assert.rejects(invoke, /Managed bash cleanup is unknown: Invalid native ownership record: damaged\.json/); + const terminal = fs.readdirSync(path.join(directory, 'terminals')) + .map(file => JSON.parse(fs.readFileSync(path.join(directory, 'terminals', file), 'utf8'))) + .find(record => record.terminal.status === 'unknown'); + assert.equal(terminal.execution_id, id); + assert.equal(terminal.close.exit_code, 0); + assert.match(terminal.terminal.reason, /Invalid native ownership record: damaged\.json/); +}); diff --git a/native/pi/patches/pi-background-bash-1.0.5-braid.patch b/native/pi/patches/pi-background-bash-1.0.5-braid.patch index bb68cfc6..d5498a7a 100644 --- a/native/pi/patches/pi-background-bash-1.0.5-braid.patch +++ b/native/pi/patches/pi-background-bash-1.0.5-braid.patch @@ -268,13 +268,25 @@ writePbbJob(job, { pid: child.pid, pgid: child.pid, runner: "pbb" }); const append = (chunk: Buffer) => { -@@ -616,15 +648,16 @@ +@@ -616,15 +648,28 @@ finish({ status: "error", error, body: error.message, details: undefined, outcome: "error", exitCode: null }); }); - child.on("close", (code, signalName) => { + child.on("close", async (code, signalName) => { -+ await managedRuntime?.finishManagedProcess(child, { exit_code: code, signal: signalName, observed_at: Date.now() }); ++ if (managedRuntime) { ++ let terminal; ++ try { ++ terminal = await managedRuntime.finishManagedProcess(child, { exit_code: code, signal: signalName, observed_at: Date.now() }); ++ } catch (error) { ++ terminal = { status: "unknown", reason: error instanceof Error ? error.message : String(error) }; ++ } ++ if (terminal?.status !== "stopped") { ++ const body = completionBody(output, `Managed bash cleanup is unknown: ${terminal?.reason ?? "missing terminal receipt"}`); ++ finish({ status: "error", error: new Error(body), body, details: undefined, outcome: "error", exitCode: code, signal: signalName ?? undefined }); ++ return; ++ } ++ } if (timedOut) { const body = completionBody(output, `Command timed out after ${params.timeout} seconds`); - finish({ status: "error", error: new Error(body), body, details: undefined, outcome: "timeout", exitCode: null }); @@ -288,7 +300,7 @@ return; } if (code === 0) { -@@ -682,7 +715,7 @@ +@@ -682,7 +727,7 @@ } function writeForegroundFullOutput(body: string): string { @@ -297,7 +309,7 @@ mkdirSync(dir, { recursive: true }); const path = join(dir, `${new Date().toISOString().replace(/[:.]/g, "-")}-${randomUUID().slice(0, 8)}.log`); writeFileSync(path, body); -@@ -743,7 +776,7 @@ +@@ -743,7 +788,7 @@ const pendingBackgroundResultFollowUps: PendingBackgroundResultFollowUp[] = []; @@ -306,7 +318,7 @@ if (shuttingDown) return; repairDetachedBackgroundToolResults(item.job.repairContext, item.job.toolCallId, { rewriteFile: item.job.repairContext?.isIdle?.() === true }); pi.sendMessage( -@@ -753,14 +786,25 @@ +@@ -753,14 +798,25 @@ display: true, details: item.details, }, @@ -335,7 +347,7 @@ } function sendBackgroundResultFollowUp(pi: ExtensionAPI, job: ActiveJob, content: string, details: BackgroundBashDetails): void { -@@ -783,12 +827,11 @@ +@@ -783,12 +839,11 @@ } function deliverBackgroundResult(pi: ExtensionAPI, job: ActiveJob, completed: CompletedBashRun, cwd: string) { @@ -351,7 +363,7 @@ const body = truncateBackgroundBody(job, completed.body); const content = buildXmlResult(job, completed.outcome, completed.exitCode, durationMs, body); const details: BackgroundBashDetails = { -@@ -809,6 +852,7 @@ +@@ -809,6 +864,7 @@ instanceId: job.pbb.instanceId, lane: job.pbb.lane, globalJobId: `${job.pbb.instanceId}:${job.id}`, @@ -359,7 +371,7 @@ pbbCursor: job.lastEventId, } : {}), -@@ -884,6 +928,7 @@ +@@ -884,6 +940,7 @@ instanceId: job.pbb.instanceId, lane: job.pbb.lane, globalJobId: `${job.pbb.instanceId}:${job.id}`, @@ -367,7 +379,7 @@ pbbCursor: job.lastEventId, } : {}), -@@ -898,8 +943,6 @@ +@@ -898,8 +955,6 @@ job.abortController.abort(); if (job.runner === "pbb") killProcessGroup(job.pgid ?? job.pid, "SIGTERM"); } @@ -376,7 +388,7 @@ } function installProcessHooks() { -@@ -908,7 +951,17 @@ +@@ -908,7 +963,17 @@ // Best-effort last resort. Normal cleanup happens on Pi's session_shutdown event; // do not install SIGINT/SIGTERM handlers here because that would interfere with // Pi's own process-level signal handling. @@ -395,7 +407,7 @@ } function restoreJobCounterFromSession(ctx: { sessionManager?: { getEntries?: () => unknown[] } }) { -@@ -917,7 +970,8 @@ +@@ -917,7 +982,8 @@ for (const entry of entries as Array>) { const details = entry.details as Record | undefined; const content = typeof entry.content === "string" ? entry.content : undefined; @@ -405,7 +417,7 @@ for (const candidate of candidates) { const n = parseJobNumber(candidate); if (n !== undefined) max = Math.max(max, n); -@@ -926,8 +980,40 @@ +@@ -926,8 +992,40 @@ nextJobNumber = Math.max(nextJobNumber, max + 1); } @@ -447,7 +459,7 @@ pi.registerMessageRenderer(CUSTOM_TYPE, (message, options, theme) => { const details = message.details; -@@ -949,16 +1035,41 @@ +@@ -949,16 +1047,41 @@ }); pi.on("session_shutdown", async () => { @@ -496,7 +508,7 @@ }); pi.on("context", (event) => { -@@ -966,19 +1077,84 @@ +@@ -966,19 +1089,84 @@ if (messages) return { messages }; }); @@ -591,7 +603,7 @@ parameters: schema, async execute(toolCallId, params, signal, onUpdate, ctx): Promise> { const autoAfterSeconds = getAutoBackgroundAfterSeconds(ctx.cwd); -@@ -987,7 +1163,7 @@ +@@ -987,7 +1175,7 @@ throw new Error("Command aborted"); } @@ -600,7 +612,7 @@ if (activeJobs.size >= MAX_ACTIVE_JOBS) { throw new Error(`Too many bash jobs running (${activeJobs.size}/${MAX_ACTIVE_JOBS}). Wait for one to finish before starting another.`); } -@@ -996,6 +1172,8 @@ +@@ -996,6 +1184,8 @@ id: formatJobId(nextJobNumber++), command: params.command, toolCallId, @@ -609,7 +621,7 @@ abortController: new AbortController(), startedAt: Date.now(), cwd: ctx.cwd, -@@ -1009,20 +1187,32 @@ +@@ -1009,20 +1199,32 @@ id: job.id, text: job.command, startedAt: job.startedAt, @@ -645,7 +657,7 @@ details: runningJobDetails(job, ctx.cwd), }; } -@@ -1041,7 +1231,8 @@ +@@ -1041,7 +1243,8 @@ if (signal?.aborted) forwardAbort(); else signal?.addEventListener("abort", forwardAbort, { once: true }); try { @@ -655,7 +667,7 @@ if (completed.status === "success") return truncateForegroundResult(job, completed); rethrowBashError(completed, job); } finally { -@@ -1078,6 +1269,7 @@ +@@ -1078,6 +1281,7 @@ latestBody = getText(update); if (!backgrounded) onUpdate?.(update); }); @@ -663,7 +675,7 @@ const winner = await Promise.race([completedPromise, waitForBackgroundThreshold(autoAfterSeconds)]); if (winner !== "background") { -@@ -1093,6 +1285,8 @@ +@@ -1093,6 +1297,8 @@ job.id = formatJobId(nextJobNumber++); job.cwd = ctx.cwd; job.pbb = pbbIdentity(ctx); @@ -672,7 +684,7 @@ activeJobs.set(job.id, job); recordPbbJobStarted(job, ctx.cwd); appendPbbLogDelta(job, latestBody); -@@ -1100,19 +1294,20 @@ +@@ -1100,19 +1306,20 @@ id: job.id, text: job.command, startedAt: job.startedAt, diff --git a/native/pi/tests/managed-process.test.mjs b/native/pi/tests/managed-process.test.mjs new file mode 100644 index 00000000..a47afa6b --- /dev/null +++ b/native/pi/tests/managed-process.test.mjs @@ -0,0 +1,134 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { randomUUID } from 'node:crypto'; +import { once } from 'node:events'; +import { spawnSync } from 'node:child_process'; +import { processIdentity, processMarkers } from '../process-owner.mjs'; + +// A test launched by Braid may inherit its operator's execution markers. Do +// not let module initialization allocate a socket alias in that execution. +const inheritedMcporter = process.env.BRAID_NATIVE_MCPORTER_ENABLED; +delete process.env.BRAID_NATIVE_MCPORTER_ENABLED; +let managed; +try { managed = await import('../managed.mjs'); } +finally { + if (inheritedMcporter !== undefined) process.env.BRAID_NATIVE_MCPORTER_ENABLED = inheritedMcporter; +} +const { spawnManaged, waitManagedStartup, finishManagedProcess, cleanupOwnedExecution } = managed; + +function execution(t) { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'braid-managed-')); + const id = randomUUID(); + const keys = ['BRAID_NATIVE_EXECUTION_DIR', 'BRAID_NATIVE_EXECUTION_ID', 'BRAID_NATIVE_START_ID', 'BRAID_NATIVE_LAUNCH_START_ID']; + const original = Object.fromEntries(keys.map(key => [key, process.env[key]])); + process.env.BRAID_NATIVE_EXECUTION_DIR = directory; + process.env.BRAID_NATIVE_EXECUTION_ID = id; + delete process.env.BRAID_NATIVE_START_ID; + delete process.env.BRAID_NATIVE_LAUNCH_START_ID; + const children = []; + const owned = []; + const track = pid => { + const identity = processIdentity(pid); + if (identity) owned.push(identity); + }; + t.after(async () => { + try { + const receipt = await cleanupOwnedExecution({ directory, id }); + // Test teardown must also recover a broken cleanup implementation. + // Identity helpers are used only for emergency cleanup, never as the + // oracle that decides whether the production stop was correct. + for (const identity of owned) { + const current = processIdentity(identity.pid); + if (current?.starttime === identity.starttime && !/^[ZX]/.test(current.state)) { + if (processMarkers(identity.pid).owner !== id) continue; + try { process.kill(identity.pid, 'SIGKILL'); } + catch (error) { if (error.code !== 'ESRCH') throw error; } + } + } + await Promise.all(children.map(child => child.managedClose)); + assert.equal(receipt.status, 'stopped', JSON.stringify(receipt)); + } finally { + for (const key of keys) { + if (original[key] === undefined) delete process.env[key]; + else process.env[key] = original[key]; + } + fs.rmSync(directory, { recursive: true, force: true }); + } + }); + return { + directory, id, track, + spawn(code) { + const child = spawnManaged(process.execPath, ['-e', code], { stdio: ['ignore', 'pipe', 'ignore'] }); + children.push(child); + if (child.pid) track(child.pid); + return child; + }, + }; +} + +function isExecuting(pid) { + // Independent OS observation: do not reuse managed.mjs's process selector + // as the expected value for its own stop decision. Zombies cannot execute. + const observed = spawnSync('/bin/ps', ['-p', String(pid), '-o', 'stat='], { encoding: 'utf8' }); + assert.equal(observed.error, undefined); + assert.ok(observed.status === 0 || observed.status === 1, observed.stderr); + const state = observed.stdout.trim(); + return Boolean(state) && !/^[ZX]/.test(state); +} + +test('owned stop reaches a real grandchild and fences later launches', { timeout: 20000 }, async t => { + const fixture = execution(t); + const child = fixture.spawn(` + const { spawn } = require('node:child_process'); + const leaf = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { stdio: 'ignore' }); + process.stdout.write(String(leaf.pid) + '\\n'); + setInterval(() => {}, 1000); + `); + const output = once(child.stdout, 'data', { signal: AbortSignal.timeout(5000) }); + const started = await waitManagedStartup(child, 5000); + const leaf = Number(String((await output)[0]).trim()); + assert.ok(Number.isInteger(leaf) && leaf > 1); + fixture.track(started.payload_pid); + fixture.track(leaf); + assert.equal(isExecuting(leaf), true); + const terminal = await finishManagedProcess(child, { observation: 'test_stop', observed_at: Date.now() }); + assert.equal(terminal.status, 'stopped', JSON.stringify(terminal)); + assert.equal(isExecuting(started.payload_pid), false); + assert.equal(isExecuting(leaf), false); + await child.managedClose; + const persisted = JSON.parse(fs.readFileSync(path.join(fixture.directory, 'terminals', `${started.start_id}.json`), 'utf8')); + assert.equal(persisted.execution_id, fixture.id); + assert.equal(persisted.terminal.status, 'stopped'); + + const stopped = await cleanupOwnedExecution({ directory: fixture.directory, id: fixture.id }); + assert.equal(stopped.status, 'stopped', JSON.stringify(stopped)); + const marker = path.join(fixture.directory, 'should-not-launch'); + const rejected = fixture.spawn(`require('node:fs').writeFileSync(${JSON.stringify(marker)}, 'ran')`); + await assert.rejects(waitManagedStartup(rejected, 5000), /start_rejected.*execution_stopping/); + await rejected.managedClose; + assert.equal(fs.existsSync(marker), false); +}); + +test('ambiguous persisted ownership reports unknown without killing the payload', { timeout: 20000 }, async t => { + const fixture = execution(t); + const child = fixture.spawn('setInterval(() => {}, 1000)'); + const started = await waitManagedStartup(child, 5000); + fixture.track(started.payload_pid); + const original = fs.readFileSync(started.process_record, 'utf8'); + const record = JSON.parse(original); + fs.writeFileSync(started.process_record, JSON.stringify({ ...record, boot_id: 'different-boot' })); + try { + const result = await cleanupOwnedExecution({ directory: fixture.directory, id: fixture.id }); + assert.equal(result.status, 'unknown'); + assert.match(result.reason, /another boot identity/); + assert.equal(isExecuting(started.payload_pid), true); + const persisted = JSON.parse(fs.readFileSync(path.join(fixture.directory, 'execution-stop.json'), 'utf8')); + assert.equal(persisted.status, 'unknown'); + } finally { + // Restore the actual launcher's identity before teardown performs real stop. + fs.writeFileSync(started.process_record, original); + } +}); diff --git a/native/pi/tests/tool-environment.test.mjs b/native/pi/tests/tool-environment.test.mjs index 2064b8c8..a71bd240 100644 --- a/native/pi/tests/tool-environment.test.mjs +++ b/native/pi/tests/tool-environment.test.mjs @@ -1,22 +1,13 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import { execFileSync } from 'node:child_process'; import { preserveToolConfig } from '../tool-environment.mjs'; for (const [name, environment, expected] of [ - ['explicit gh directory wins', { GH_CONFIG_DIR: '/operator/gh', XDG_CONFIG_HOME: '/operator/xdg' }, '/operator/gh'], - ['original XDG path survives execution isolation', { XDG_CONFIG_HOME: '/operator/xdg' }, '/operator/xdg/gh'], - ['default home path survives execution isolation', {}, '/operator/home/.config/gh'], + ['explicit gh directory takes precedence over XDG', { GH_CONFIG_DIR: '/operator/gh', XDG_CONFIG_HOME: '/operator/xdg' }, '/operator/gh'], + ['absent GH and XDG use the caller home', {}, '/operator/home/.config/gh'], ]) { test(name, () => { preserveToolConfig(environment, '/operator/home'); - environment.XDG_CONFIG_HOME = '/execution/private/config'; assert.equal(environment.GH_CONFIG_DIR, expected); - // The same explicit locator reaches a git credential-helper subprocess. - const actual = execFileSync(process.execPath, ['-e', 'process.stdout.write(process.env.GH_CONFIG_DIR)'], { - env: { ...process.env, ...environment }, encoding: 'utf8', - }); - assert.equal(actual, expected); - assert.equal(environment.XDG_CONFIG_HOME, '/execution/private/config'); }); } diff --git a/scripts/verify-package.sh b/scripts/verify-package.sh new file mode 100755 index 00000000..9e457160 --- /dev/null +++ b/scripts/verify-package.sh @@ -0,0 +1,47 @@ +#!/bin/sh +# Check a native release archive as its consumer, away from the checkout. +set -eu + +if [ "$#" -ne 3 ]; then + echo 'Usage: verify-package.sh DIST_DIRECTORY RELEASE_TAG RUST_TARGET' >&2 + exit 2 +fi +dist=$(CDPATH= cd -- "$1" && pwd) +artifact="braid-$2-$3" +archive="$artifact.tar.gz" +cd "$dist" +if ! verified=$(shasum -a 256 -c "$archive.sha256"); then + printf 'SHA-256 verification failed for %s: %s\n' "$archive" "$verified" >&2 + exit 1 +fi +if [ "$verified" != "$archive: OK" ]; then + printf 'Checksum must identify %s (got %s)\n' "$archive" "$verified" >&2 + exit 1 +fi +install_root=$(mktemp -d) +trap 'rm -rf "$install_root"' EXIT +tar -xzf "$archive" -C "$install_root" +cd "$install_root/$artifact" +for entry in LICENSE README.md CHANGELOG.md deploy/otel-collector.example.yaml; do + if [ ! -s "$entry" ]; then + printf 'Required release file is missing or empty: %s\n' "$entry" >&2 + exit 1 + fi +done +# The packaged executable must run without a checkout, Rust toolchain or user config. +braid() { env -i HOME="$install_root" PATH=/usr/bin:/bin ./bin/braid "$@"; } +version=$(braid --version) +if [ "$version" != "braid ${2#v}" ]; then + printf 'Expected braid %s, installed binary reported %s\n' "${2#v}" "$version" >&2 + exit 1 +fi +config="$PWD/config.example.toml" +braid config check --config "$config" +applied=$(braid migrate apply --config "$config") +printf '%s\n' "$applied" +if ! printf '%s\n' "$applied" | grep -Eq '^schema: 0 -> [1-9][0-9]*$'; then + echo 'Clean installation must migrate a fresh database from schema 0' >&2 + exit 1 +fi +plan=$(braid migrate plan --config "$config") +printf '%s\n' "$plan" | grep -Fx 'pending: none' diff --git a/src/agent_session.rs b/src/agent_session.rs index 813a3217..d3610de8 100644 --- a/src/agent_session.rs +++ b/src/agent_session.rs @@ -106,17 +106,6 @@ pub trait AgentSession: Send + Sync { msg: String, expected_turn_id: &str, ) -> Result; - - /// Best-effort termination of the in-flight turn — the control-plane - /// sibling of steering: both are immediate operations addressed to the - /// observed active turn, but `interrupt` carries control (terminate) - /// rather than input. - /// - /// Idempotent at the state-machine boundary: no in-flight turn (or a turn - /// that already completed) is `Ok(())`. The terminal still arrives through - /// the event stream — `Interrupted` when honored, or the natural outcome - /// if the turn completed first — so callers never wait on a side channel. - async fn interrupt(&self) -> Result<(), SessionError>; } /// An adapter-created handle and the opaque identity to bind in the durable store. diff --git a/src/cli/provider_cmd.rs b/src/cli/provider_cmd.rs index 064889ff..e9e0e52d 100644 --- a/src/cli/provider_cmd.rs +++ b/src/cli/provider_cmd.rs @@ -2,7 +2,6 @@ //! provider credential files. The resulting Braid-schema file is the only //! credential input; Pi's auth.json remains an adapter-owned runtime format. use std::{ - fmt::Write as _, fs::OpenOptions, io::Write as _, path::{Path, PathBuf}, @@ -11,7 +10,7 @@ use std::{ use anyhow::{Context as _, Result, bail}; use clap::Args; -use crate::config::{OAuthCredentialFile, validate_token}; +use crate::config::{OAuthCredentialFile, ProviderSecretFile, validate_token}; use crate::home::UserHome; #[derive(Debug, Args)] @@ -32,6 +31,12 @@ pub(crate) struct ProviderImportAuth { pub fn import_auth(arguments: &ProviderImportAuth) -> Result<()> { validate_token("provider id", &arguments.provider_id) .map_err(|error| anyhow::anyhow!(error.to_string()))?; + // The id becomes a filename, unlike provider ids used only for routing. + if arguments.provider_id.contains(['/', '\\']) + || matches!(arguments.provider_id.as_str(), "." | "..") + { + bail!("provider id must be a single file name, without path separators"); + } let user_home = UserHome::resolve(Some(&arguments.user_home))?; let from = arguments.from.canonicalize().context("cannot resolve Pi auth.json source")?; let (rendered, kind_label) = convert_credential(&from, &arguments.provider_id)?; @@ -135,14 +140,7 @@ fn convert_oauth( } let oauth = OAuthCredentialFile { access, refresh, expires, account: account.map(str::to_owned) }; - let mut text = format!( - "access = {:?}\nrefresh = {:?}\nexpires = {}\n", - oauth.access, oauth.refresh, oauth.expires - ); - if let Some(account) = &oauth.account { - writeln!(text, "account = {account:?}").expect("write to string cannot fail"); - } - Ok((text, "oauth")) + Ok((toml::to_string(&oauth)?, "oauth")) } fn convert_api_key( @@ -156,7 +154,7 @@ fn convert_api_key( if key.trim().is_empty() { bail!("api_key credential {provider_id:?} in {} is empty", from.display()); } - Ok((format!("provider_api_key = {key:?}\n"), "api_key")) + Ok((toml::to_string(&ProviderSecretFile { provider_api_key: key.into() })?, "api_key")) } fn required_string(entry: &serde_json::Value, field: &str) -> Result { diff --git a/src/config.rs b/src/config.rs index 3c97eddf..68e8e77a 100644 --- a/src/config.rs +++ b/src/config.rs @@ -554,8 +554,8 @@ pub struct WebhookSecretFile { pub webhook_secret: String, } -/// Secrets file referenced by `[[llm_providers]].api_key_file`. -#[derive(Debug, Deserialize)] +/// Braid API-key schema referenced by `llm_providers[].credential.file`. +#[derive(Debug, Deserialize, Serialize)] pub struct ProviderSecretFile { pub provider_api_key: String, } @@ -1482,7 +1482,7 @@ mod tests { let mut config = example(); config.instance.key = " owner ".into(); - assert!(config.validate().is_err()); + assert!(config.validate().unwrap_err().to_string().contains("instance.key")); let mut config = example(); config.github.as_mut().unwrap().repository = "owner/repo?query".into(); @@ -1495,13 +1495,11 @@ mod tests { std::env::temp_dir().join(format!("braid-secrets-{}.toml", uuid::Uuid::now_v7())); for (kind, contents) in [ ("webhook", "webhook_secret = \"sensitive-marker"), - ("api_key", "provider_api_key = \"sensitive-marker"), ("oauth", "access = \"token\"\nrefresh = \"token\"\nexpires = \"sensitive-marker\""), ] { fs::write(&path, contents).expect("write malformed credential"); let result = match kind { "webhook" => load_webhook_secret_file(&path).map(|_| ()), - "api_key" => load_provider_secret_file(&path).map(|_| ()), _ => load_oauth_file(&path).map(|_| ()), }; let message = result.unwrap_err().to_string(); diff --git a/src/console/mod.rs b/src/console/mod.rs index 3290f067..9a57f501 100644 --- a/src/console/mod.rs +++ b/src/console/mod.rs @@ -4,6 +4,8 @@ mod harness; mod proxy; mod runtime; mod storage; +#[cfg(test)] +mod tests; use crate::{config::Config, store::StoreActor, telemetry::TelemetryGuard}; use anyhow::{Context as _, Result, bail}; diff --git a/src/console/tests.rs b/src/console/tests.rs new file mode 100644 index 00000000..f6246a67 --- /dev/null +++ b/src/console/tests.rs @@ -0,0 +1,406 @@ +//! Collector HTTP contracts. Inputs use the standard OTLP encoder, not Braid's decoder. +use super::{api, storage::Storage}; +use opentelemetry_proto::tonic::{ + collector::{ + logs::v1::ExportLogsServiceRequest, metrics::v1::ExportMetricsServiceRequest, + trace::v1::ExportTraceServiceRequest, + }, + common::v1::{AnyValue, KeyValue, any_value}, + logs::v1::{LogRecord, ResourceLogs, ScopeLogs}, + metrics::v1::{ + Gauge, Metric, NumberDataPoint, ResourceMetrics, ScopeMetrics, metric, number_data_point, + }, + resource::v1::Resource, + trace::v1::{ResourceSpans, ScopeSpans, Span}, +}; +use prost::Message as _; +use reqwest::StatusCode; +use serde_json::Value; +use std::{io::Write as _, path::PathBuf}; + +struct Collector { + root: PathBuf, + url: String, + client: reqwest::Client, + stop: Option>, + server: Option>, +} + +impl Collector { + async fn new() -> Self { + let root = std::env::temp_dir().join(format!("braid-collector-{}", uuid::Uuid::now_v7())); + let mut collector = Self { + root, + url: String::new(), + client: reqwest::Client::builder() + .timeout(std::time::Duration::from_secs(5)) + .build() + .unwrap(), + stop: None, + server: None, + }; + collector.start().await; + collector + } + + async fn start(&mut self) { + let storage = Storage::open(&self.root.join("observations.sqlite3")); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + self.url = format!("http://{}", listener.local_addr().unwrap()); + let app = api::routes(storage); + let (stop, stopped) = tokio::sync::oneshot::channel(); + self.stop = Some(stop); + self.server = Some(tokio::spawn(async move { + axum::serve(listener, app) + .with_graceful_shutdown(async { + let _ = stopped.await; + }) + .await + .unwrap(); + })); + } + + async fn shutdown(&mut self) { + self.stop.take().unwrap().send(()).unwrap(); + self.server.take().unwrap().await.unwrap(); + } + + async fn get(&self, path: &str) -> Value { + self.client + .get(format!("{}{path}", self.url)) + .send() + .await + .unwrap() + .error_for_status() + .unwrap() + .json() + .await + .unwrap() + } + + async fn export(&self, signal: &str, encoding: &str, body: &[u8]) -> reqwest::Response { + self.client + .post(format!("{}/v1/{signal}", self.url)) + .header("content-type", "application/x-protobuf") + .header("content-encoding", encoding) + .body(body.to_vec()) + .send() + .await + .unwrap() + } +} + +impl Drop for Collector { + fn drop(&mut self) { + if let Some(server) = &self.server { + server.abort(); + } + let _ = std::fs::remove_dir_all(&self.root); + } +} + +fn attribute(key: &str, value: &str) -> KeyValue { + KeyValue { + key: key.into(), + value: Some(AnyValue { value: Some(any_value::Value::StringValue(value.into())) }), + ..KeyValue::default() + } +} + +fn resource() -> Resource { + Resource { + attributes: vec![ + attribute("service.instance.id", "instance-A"), + attribute("service.name", "contract-service"), + attribute("braid.session.id", "resource-session"), + ], + ..Resource::default() + } +} + +fn trace_body() -> Vec { + ExportTraceServiceRequest { + resource_spans: vec![ResourceSpans { + resource: Some(resource()), + scope_spans: vec![ScopeSpans { + spans: vec![Span { + trace_id: vec![0x11; 16], + span_id: vec![0x22; 8], + name: "contract-span".into(), + start_time_unix_nano: 100, + end_time_unix_nano: 200, + attributes: vec![ + attribute("braid.provider_session.id", "span-session"), + attribute("braid.turn.id", "turn-A"), + ], + ..Span::default() + }], + ..ScopeSpans::default() + }], + ..ResourceSpans::default() + }], + } + .encode_to_vec() +} + +fn log_body() -> Vec { + ExportLogsServiceRequest { + resource_logs: vec![ResourceLogs { + resource: Some(resource()), + scope_logs: vec![ScopeLogs { + log_records: vec![LogRecord { + body: Some(AnyValue { + value: Some(any_value::Value::StringValue("retained evidence".into())), + }), + trace_id: vec![0x11; 16], + span_id: vec![0x22; 8], + time_unix_nano: 150, + attributes: vec![ + attribute("braid.session.id", "log-session"), + attribute("braid.turn.id", "turn-B"), + ], + ..LogRecord::default() + }], + ..ScopeLogs::default() + }], + ..ResourceLogs::default() + }], + } + .encode_to_vec() +} + +fn metric_body() -> Vec { + ExportMetricsServiceRequest { + resource_metrics: vec![ResourceMetrics { + resource: Some(resource()), + scope_metrics: vec![ScopeMetrics { + metrics: vec![Metric { + name: "contract.gauge".into(), + data: Some(metric::Data::Gauge(Gauge { + data_points: vec![NumberDataPoint { + time_unix_nano: 150, + value: Some(number_data_point::Value::AsInt(42)), + ..NumberDataPoint::default() + }], + })), + ..Metric::default() + }], + ..ScopeMetrics::default() + }], + ..ResourceMetrics::default() + }], + } + .encode_to_vec() +} + +#[tokio::test] +async fn otlp_signals_raw_bytes_duplicates_and_cursor_pages_survive_reopening() { + let mut collector = Collector::new().await; + let trace = trace_body(); + let mut gzip = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); + gzip.write_all(&log_body()).unwrap(); + let log = gzip.finish().unwrap(); + let metric = metric_body(); + let millis = + || std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_millis(); + let earliest = millis(); + for (signal, encoding, body) in [ + ("traces", "identity", trace.as_slice()), + ("logs", "gzip", log.as_slice()), + ("metrics", "identity", metric.as_slice()), + ("traces", "identity", trace.as_slice()), + ] { + let response = collector.export(signal, encoding, body).await; + assert_eq!(response.status(), StatusCode::OK); + assert_eq!(response.headers()["content-type"], "application/x-protobuf"); + assert!(response.bytes().await.unwrap().is_empty()); + } + let page = collector.get("/api/records?limit=2&instance=instance-A").await; + let first = page["records"].as_array().unwrap(); + assert_eq!(first.len(), 2); + assert_eq!(first[0]["signal"], "traces"); + assert_eq!(first[0]["session"], "span-session"); + assert_eq!(first[0]["turn_id"], "turn-A"); + assert_eq!(first[0]["trace_id"], "11111111111111111111111111111111"); + assert_eq!(first[0]["data"]["name"], "contract-span"); + assert_eq!(first[1]["signal"], "logs"); + assert_eq!(first[1]["session"], "log-session"); + assert_eq!(first[1]["data"]["body"]["stringValue"], "retained evidence"); + assert_eq!(first[1]["data"]["timeUnixNano"], "150"); + assert!((earliest..=millis()).contains(&u128::from(first[1]["received_at"].as_u64().unwrap()))); + for record in first { + assert_eq!(record["service"], "contract-service"); + assert!(record["duplicate_of"].is_null()); + } + let cursor = page["next_after"].as_i64().unwrap(); + let first_batch = first[0]["batch_id"].clone(); + let log_batch = first[1]["batch_id"].as_i64().unwrap(); + collector.shutdown().await; + collector.start().await; + assert_eq!(collector.get("/api/records?limit=2&instance=instance-A").await, page); + let page = + collector.get(&format!("/api/records?after={cursor}&limit=2&instance=instance-A")).await; + let remaining = page["records"].as_array().unwrap(); + assert_eq!(remaining.len(), 2); + assert_eq!(remaining[0]["signal"], "metrics"); + assert_eq!(remaining[0]["session"], "resource-session"); + assert_eq!(remaining[0]["data"]["name"], "contract.gauge"); + assert_eq!(remaining[0]["data"]["gauge"]["dataPoints"][0]["asInt"], 42); + assert_eq!(remaining[1]["signal"], "traces"); + assert_eq!(remaining[1]["duplicate_of"], first_batch); + let cursor = page["next_after"].as_i64().unwrap(); + assert!( + collector.get(&format!("/api/records?after={cursor}")).await["records"] + .as_array() + .unwrap() + .is_empty() + ); + for (filter, expected) in [ + ("signal=logs", vec!["logs"]), + ("session=span-session", vec!["traces", "traces"]), + ("turn=turn-B", vec!["logs"]), + ("trace=11111111111111111111111111111111", vec!["traces", "logs", "traces"]), + ("instance=absent", vec![]), + ("signal=logs&turn=turn-A", vec![]), + ] { + let page = collector.get(&format!("/api/records?{filter}")).await; + let signals = page["records"] + .as_array() + .unwrap() + .iter() + .map(|record| record["signal"].as_str().unwrap()) + .collect::>(); + assert_eq!(signals, expected, "{filter}"); + } + let raw = collector + .client + .get(format!("{}/api/batches/{log_batch}", collector.url)) + .send() + .await + .unwrap(); + assert_eq!(raw.status(), StatusCode::OK); + assert_eq!(raw.headers()["x-otlp-content-encoding"], "gzip"); + assert_eq!(raw.bytes().await.unwrap().as_ref(), log); + let resources = collector.get("/api/resources").await; + assert_eq!(resources["batches"], 4); + assert_eq!(resources["records"], 4); + assert_eq!(resources["duplicate_batches"], 1); + collector.shutdown().await; +} + +// google.rpc.Status field numbers are an independent HTTP error wire contract. +#[derive(prost::Message)] +struct ErrorStatus { + #[prost(int32, tag = "1")] + code: i32, + #[prost(string, tag = "2")] + message: String, +} + +async fn expect_error(response: reqwest::Response, status: StatusCode, code: i32, reason: &str) { + assert_eq!(response.status(), status); + assert_eq!(response.headers()["content-type"], "application/x-protobuf"); + let error = ErrorStatus::decode(response.bytes().await.unwrap()).unwrap(); + assert_eq!(error.code, code); + assert!(error.message.contains(reason), "{}", error.message); +} + +#[tokio::test] +async fn malformed_exports_reach_their_expected_guard_and_retain_rejected_bytes() { + let mut collector = Collector::new().await; + let valid = log_body(); + let invalid = [ + ( + "application/x-protobuf", + "br", + &[1][..], + StatusCode::UNSUPPORTED_MEDIA_TYPE, + "unsupported Content-Encoding: br", + ), + ( + "application/x-protobuf", + "identity", + &[0xff][..], + StatusCode::BAD_REQUEST, + "decode OTLP logs protobuf", + ), + ( + "application/x-protobuf", + "gzip", + &[0x1f, 0x00][..], + StatusCode::BAD_REQUEST, + "decode gzip OTLP body", + ), + ( + "application/json", + "identity", + valid.as_slice(), + StatusCode::UNSUPPORTED_MEDIA_TYPE, + "Content-Type", + ), + ]; + for (content_type, encoding, body, status, reason) in invalid { + let response = collector + .client + .post(format!("{}/v1/logs", collector.url)) + .header("content-type", content_type) + .header("content-encoding", encoding) + .body(body.to_vec()) + .send() + .await + .unwrap(); + expect_error(response, status, 3, reason).await; + } + assert_eq!(collector.get("/api/resources").await["batches"], 0); + collector.shutdown().await; + collector.start().await; + let page = collector.get("/api/receive-errors").await; + let errors = page["errors"].as_array().unwrap(); + assert_eq!(errors.len(), invalid.len()); + for (error, (_, _, body, status, reason)) in errors.iter().zip(invalid) { + assert_eq!(error["status"], status.as_u16()); + assert!(error["reason"].as_str().unwrap().contains(reason)); + let id = error["id"].as_i64().unwrap(); + let raw = collector + .client + .get(format!("{}/api/receive-errors/{id}", collector.url)) + .send() + .await + .unwrap() + .error_for_status() + .unwrap() + .bytes() + .await + .unwrap(); + assert_eq!(raw.as_ref(), body, "{reason}"); + } + collector.shutdown().await; +} + +#[tokio::test] +async fn record_storage_failure_is_retryable_and_does_not_leave_a_partial_batch() { + let mut collector = Collector::new().await; + let db = rusqlite::Connection::open(collector.root.join("observations.sqlite3")).unwrap(); + // Fail after the batch INSERT through SQLite itself, without replacing the storage owner. + db.execute_batch("CREATE TRIGGER fail_record BEFORE INSERT ON console_records BEGIN SELECT RAISE(ABORT, 'injected record storage failure'); END;").unwrap(); + expect_error( + collector.export("logs", "identity", &log_body()).await, + StatusCode::SERVICE_UNAVAILABLE, + 14, + "injected record storage failure", + ) + .await; + let resources = collector.get("/api/resources").await; + assert_eq!(resources["records"], 0); + assert_eq!(resources["batches"], 0); + assert_eq!(resources["receive_errors"], 1); + db.execute_batch("DROP TRIGGER fail_record").unwrap(); + drop(db); + let response = collector.export("logs", "identity", &log_body()).await; + assert_eq!(response.status(), StatusCode::OK); + let records = collector.get("/api/records").await; + assert_eq!(records["records"].as_array().unwrap().len(), 1); + assert_eq!(records["records"][0]["data"]["body"]["stringValue"], "retained evidence"); + assert_eq!(collector.get("/api/resources").await["duplicate_batches"], 0); + collector.shutdown().await; +} diff --git a/src/context.rs b/src/context.rs index 344954bf..37c31f62 100644 --- a/src/context.rs +++ b/src/context.rs @@ -1332,7 +1332,7 @@ pub fn filter_html_comments(markdown: &str) -> String { _ => false, }; if is_comment && let Some(range) = source_range(markdown, &line_offsets, data.sourcepos) { - ranges.push(range); + comment_ranges(markdown, range, &mut ranges); } } if ranges.is_empty() { @@ -1359,6 +1359,44 @@ pub fn filter_html_comments(markdown: &str) -> String { visible } +// A CommonMark HTML block includes the rest of its closing line. Remove the +// comments inside that block, not visible text following the closing delimiter. +fn comment_ranges(markdown: &str, (start, end): (usize, usize), ranges: &mut Vec<(usize, usize)>) { + let source = &markdown[start..end]; + let bytes = source.as_bytes(); + let mut cursor = 0; + while cursor < bytes.len() { + if bytes[cursor..].starts_with(b"") + .map_or(bytes.len(), |offset| cursor + 4 + offset + 3); + ranges.push((start + cursor, start + comment_end)); + cursor = comment_end; + } else if bytes[cursor] == b'<' + && (bytes.get(cursor + 1).is_some_and(u8::is_ascii_alphabetic) + || bytes.get(cursor + 1) == Some(&b'/') + && bytes.get(cursor + 2).is_some_and(u8::is_ascii_alphabetic)) + { + // A comment delimiter in an HTML attribute is literal attribute + // content. Skip the tag while respecting its quoted values. + let mut quote = None; + cursor += 1; + while cursor < bytes.len() { + let byte = bytes[cursor]; + cursor += 1; + match (quote, byte) { + (None, b'>') => break, + (None, b'\'' | b'"') => quote = Some(byte), + (Some(delimiter), _) if byte == delimiter => quote = None, + _ => {} + } + } + } else { + cursor += 1; + } + } +} + fn line_offsets(markdown: &str) -> Vec { let mut offsets = vec![0]; for (offset, byte) in markdown.bytes().enumerate() { @@ -3017,3 +3055,7 @@ struct PrFirstRepository { #[cfg(test)] #[path = "context/reading_tests.rs"] mod reading_tests; + +#[cfg(test)] +#[path = "context/filter_tests.rs"] +mod filter_tests; diff --git a/src/context/filter_tests.rs b/src/context/filter_tests.rs new file mode 100644 index 00000000..aacd9cc9 --- /dev/null +++ b/src/context/filter_tests.rs @@ -0,0 +1,34 @@ +use super::filter_html_comments; + +#[test] +fn html_comments_preserve_surrounding_visible_markdown_bytes() { + for (markdown, expected) in [ + (" visible suffix", " visible suffix"), + ("visibletail", "visibletail"), + ("\nvisible", "\nvisible"), + ("before after", "before after"), + ("前文 后文\r\n", "前文 后文\r\n"), + (" suffix\nnext", " suffix\nnext"), + (" x < 3 tail", " x < 3 tail"), + (" x tail", " x \">visibletail", + "\">visibletail", + ), + ("`", + "```html\n\n```", + " \n", + "visible ", false), + (" @braid", true), + (" `@braid`", false), + (" [review](/@braid)", false), + (" [@braid](/review)", true), + ] { + for handle in ["braid", "@braid"] { + assert_eq!(has_visible_mention(body, handle), expected, "{body:?}, {handle}"); + } + } +} + +#[test] +fn opening_body_mention_remains_pending_and_agent_echo_cannot_request_attention() { + let mut opening = payload(); + opening.as_object_mut().unwrap().remove("comment"); + opening["action"] = json!("opened"); + opening["issue"]["body"] = json!("@braid discuss this design"); + let admitted = parse(&opening, "issues"); + assert_eq!(admitted.kind, EventKind::Mention); + assert!(admitted.mention_candidate); + assert!(admitted.requires_attention); + assert_eq!(admitted.origin, "external"); + for (node, login) in + [("APP", "renamed-bot"), ("renamed-node", "braid[bot]"), ("AGENT", "coding-agent")] + { + let mut echo = payload(); + echo["sender"] = json!({"node_id":node,"login":login}); + let admitted = parse(&echo, "issue_comment"); + assert_eq!(admitted.kind, EventKind::OriginEcho); + assert_eq!(admitted.origin, "agent"); + assert!(!admitted.mention_candidate); + assert!(!admitted.requires_attention); + assert!(admitted.reaction_target.is_none()); + } + let human = parse(&payload(), "issue_comment"); + assert_eq!(human.kind, EventKind::Wake); + assert!(human.mention_candidate); + assert!(human.requires_attention); + let reaction = human.reaction_target.unwrap(); + assert_eq!(reaction.kind, "issue_comment"); + assert_eq!(reaction.database_id, "7"); +} + +#[test] +fn comment_edits_compare_visible_suffix_instead_of_discarding_the_html_block_line() { + for (body, expected) in [ + (" current design", EventKind::Noop), + (" changed design", EventKind::Invalidate), + ] { + let mut edited = payload(); + edited["action"] = json!("edited"); + edited["changes"] = json!({"body":{"from":" current design"}}); + edited["comment"]["body"] = json!(body); + let admitted = parse(&edited, "issue_comment"); + assert_eq!(admitted.kind, expected, "{body}"); + assert_eq!(admitted.requires_attention, expected == EventKind::Invalidate); + } +} + +#[test] +fn human_edit_of_a_braid_authored_body_is_not_an_echo_or_an_urgent_mention() { + let mut revision = payload(); + revision.as_object_mut().unwrap().remove("comment"); + revision["action"] = json!("edited"); + revision["changes"] = json!({"body":{"from":"old requirements"}}); + revision["issue"]["body"] = + json!("> **Braid Agent · Braid**\n> Issue Agent\n\nRevised requirements"); + let event = parse(&revision, "issues"); + assert_eq!(event.kind, EventKind::Invalidate); + assert!(event.requires_attention); + assert!(!event.mention_candidate); + assert_eq!(event.origin, "external"); +} diff --git a/src/worktree.rs b/src/worktree.rs index 395c7304..bd433042 100644 --- a/src/worktree.rs +++ b/src/worktree.rs @@ -221,3 +221,6 @@ pub(crate) fn normalized_github_repository(remote: &str) -> Option { let repository = path.strip_suffix(".git").unwrap_or(path).trim_matches('/'); (repository.split('/').count() == 2).then(|| repository.to_ascii_lowercase()) } + +#[cfg(test)] +mod tests; diff --git a/tests/worktree.rs b/src/worktree/tests.rs similarity index 56% rename from tests/worktree.rs rename to src/worktree/tests.rs index 97c8c846..23ac1358 100644 --- a/tests/worktree.rs +++ b/src/worktree/tests.rs @@ -1,9 +1,4 @@ -#![allow(dead_code)] - -#[path = "../src/worktree.rs"] -mod worktree; - -use std::path::Path; +use super::*; fn initialize(path: &Path) { let repository = git2::Repository::init(path).unwrap(); @@ -23,7 +18,7 @@ async fn existing_target_must_share_the_requested_source_repository() { initialize(&source); initialize(&wrong); let git = which::which("git").unwrap(); - let mut request = worktree::WorktreeRequest { + let mut request = WorktreeRequest { source: &source, target: &wrong, repository: "owner/repository", @@ -33,16 +28,32 @@ async fn existing_target_must_share_the_requested_source_repository() { head_ref: "main", local_branch: "main", }; - assert!(matches!( - worktree::provision(&request), - Err(worktree::WorktreeError::TargetConflict(_)) - )); + assert!(matches!(provision(&request), Err(WorktreeError::TargetConflict(_)))); request.target = ⌖ request.local_branch = "agent"; - let created = worktree::provision(&request).unwrap(); + let created = provision(&request).unwrap(); assert_eq!(created.path, target.canonicalize().unwrap()); - assert_eq!(worktree::provision(&request).unwrap().path, created.path); + assert_eq!(provision(&request).unwrap().path, created.path); + std::fs::create_dir(target.join(".braid")).unwrap(); + std::fs::write(target.join(".braid/private-note"), "private").unwrap(); + std::fs::write(target.join("change.txt"), "public").unwrap(); + let status = std::process::Command::new(&git) + .arg("-C") + .arg(&target) + .args([ + "-c", + "core.excludesfile=/dev/null", + "status", + "--porcelain", + "--untracked-files=all", + ]) + .output() + .unwrap(); + assert!(status.status.success()); + assert_eq!(String::from_utf8(status.stdout).unwrap(), "?? change.txt\n"); + request.local_branch = "different-agent"; + assert!(matches!(provision(&request), Err(WorktreeError::TargetConflict(_)))); std::fs::remove_dir_all(root).unwrap(); } @@ -53,16 +64,15 @@ fn github_remote_identity_is_exact() { "ssh://git@github.com/owner/repo.git", "git@github.com:owner/repo.git", ] { - assert_eq!(worktree::normalized_github_repository(remote).as_deref(), Some("owner/repo")); + assert_eq!(normalized_github_repository(remote).as_deref(), Some("owner/repo")); } for remote in ["https://example.invalid/owner/repo.git", "https://github.com/owner/repo/issues/1"] { - assert_eq!(worktree::normalized_github_repository(remote), None); + assert_eq!(normalized_github_repository(remote), None); } - assert_ne!( - worktree::normalized_github_repository("https://github.com/owner/repo-backup.git") - .as_deref(), - Some("owner/repo") + assert_eq!( + normalized_github_repository("https://github.com/owner/repo-backup.git").as_deref(), + Some("owner/repo-backup") ); } diff --git a/src/writer/prepare.rs b/src/writer/prepare.rs index 6340e7db..bc2e9da3 100644 --- a/src/writer/prepare.rs +++ b/src/writer/prepare.rs @@ -89,17 +89,7 @@ async fn prepare_plan( store .prepare_implementation_request(NewImplementationRequest { root_intent_id: root, - write: NewGhWriteIntent { - request_key: format!("pr_ensure\0{}\0{}", repository, request.comment_id), - operation: "pr_ensure", - repository: repository.to_string(), - target: accepted.target.clone(), - profile_id: profile.id.clone(), - role: "PR Implementation Agent".into(), - payload: accepted.payload.clone(), - source: accepted.source.clone(), - request_digest: helpers::digest(&accepted.payload), - }, + intent_id: accepted.intent_id.clone(), comment_database_id: request.comment_id, comment_node_id: comment.node_id, issue_node_id: issue.node_id, diff --git a/src/writer/tests.rs b/src/writer/tests.rs index 519e1f4b..d853a0b2 100644 --- a/src/writer/tests.rs +++ b/src/writer/tests.rs @@ -14,9 +14,9 @@ use std::{ }; pub(crate) struct Fixture { - root: PathBuf, pub(crate) config: Config, pub(crate) store: StoreActor, + root: TemporaryRoot, } impl Fixture { pub(crate) fn new(source: bool) -> Self { @@ -36,12 +36,22 @@ impl Fixture { ) .unwrap(); store.apply().unwrap(); - let fixture = Self { root, config, store }; + let fixture = Self { root: TemporaryRoot(root), config, store }; if source { fixture.bind_source(); } fixture } + fn reopen(self) -> Self { + let Self { root, config, store } = self; + drop(store); + let store = StoreActor::start( + config.runtime.database().to_owned(), + config.runtime.backups().to_owned(), + ) + .unwrap(); + Self { config, store, root } + } pub(crate) fn db(&self) -> Connection { Connection::open(self.config.runtime.database()).unwrap() } @@ -91,9 +101,10 @@ impl Fixture { self.store.gh_write_receipt(id.into()).unwrap().unwrap() } } -impl Drop for Fixture { +struct TemporaryRoot(PathBuf); +impl Drop for TemporaryRoot { fn drop(&mut self) { - let _ = std::fs::remove_dir_all(&self.root); + let _ = std::fs::remove_dir_all(&self.0); } } @@ -111,21 +122,27 @@ enum Authority { SourceClosed, TargetClosed, AssociationRemoved, + AssociationUnavailable, OtherIssue, } #[derive(Default)] struct Remote { authority: Authority, + closing_issue: Option, pr_body: Option, - create_pr: bool, + pr_missing: bool, target_kind: TargetKind, - pr_created: bool, head_created: bool, comments: Vec, - comment_reads: usize, + comment_requests: Vec<&'static str>, + lose_comment_response: bool, writes: usize, limit: Option, + target_status: Option, + commit_requests: Vec, + ref_requests: Vec, + pr_requests: Vec, } async fn server( remote: Arc>, @@ -143,33 +160,52 @@ async fn server( .route("/repos/owner/repository/issues/1", get(move || { let remote=target.clone(); async move { use axum::response::IntoResponse as _; if remote.lock().unwrap().limit.is_some() { return (axum::http::StatusCode::TOO_MANY_REQUESTS, [("retry-after","120")], Json(json!({"message":"rate limit"}))).into_response(); } + if let Some(status) = remote.lock().unwrap().target_status { return (status, Json(json!({"message":"target unavailable"}))).into_response(); } let mut item = json!({"id":1,"node_id":"item","number":1,"title":"Issue","state":"open","html_url":"https://github.com/owner/repository/issues/1"}); if remote.lock().unwrap().authority==Authority::SourceClosed {item["state"]=json!("closed");} if matches!(remote.lock().unwrap().target_kind, TargetKind::PullRequest) { item["pull_request"] = json!({"url":"pr"}); } Json(item).into_response() }})) - .route("/repos/owner/repository/issues/1/comments", get(move || { let remote=listing.clone(); async move { let mut state=remote.lock().unwrap(); state.comment_reads+=1; Json(state.comments.clone()) } }).post(move |Json(body): Json| { let remote=writing.clone(); async move { - let mut remote=remote.lock().unwrap(); remote.writes+=1; + .route("/repos/owner/repository/issues/1/comments", get(move || { let remote=listing.clone(); async move { let mut state=remote.lock().unwrap(); state.comment_requests.push("GET"); Json(state.comments.clone()) } }).post(move |Json(body): Json| { let remote=writing.clone(); async move { + let mut remote=remote.lock().unwrap(); remote.comment_requests.push("POST"); remote.writes+=1; let comment=json!({"id":99,"node_id":"comment","url":"https://api.github.com/repos/owner/repository/issues/comments/99","html_url":"https://github.com/owner/repository/issues/1#issuecomment-99","issue_url":"https://api.github.com/repos/owner/repository/issues/1","body":body["body"],"created_at":time::OffsetDateTime::now_utc().format(&time::format_description::well_known::Rfc3339).unwrap(),"updated_at":"now","user":{"login":"braid[bot]","id":1,"node_id":"app","type":"Bot","site_admin":false,"avatar_url":"https://example.invalid","url":"https://example.invalid","html_url":"https://example.invalid"}}); - remote.comments.push(comment); Json(json!({"id":99,"node_id":"comment"})) + remote.comments.push(comment); + if remote.lose_comment_response { return Err(axum::http::StatusCode::SERVICE_UNAVAILABLE); } + Ok(Json(json!({"id":99,"node_id":"comment"}))) }})) .route("/repos/owner/repository/issues/comments/99",axum::routing::patch(move |Json(body):Json|{let remote=updating.clone();async move{let mut remote=remote.lock().unwrap();remote.writes+=1;remote.comments.last_mut().unwrap()["body"]=body["body"].clone();Json(json!({"id":99,"node_id":"comment"}))}})) .route("/repos/owner/repository/issues/comments/7", get(|| async { Json(json!({"id":7,"node_id":"request-comment","url":"https://api.github.com/repos/owner/repository/issues/comments/7","html_url":"https://github.com/owner/repository/issues/1#issuecomment-7","issue_url":"https://api.github.com/repos/owner/repository/issues/1","body":"implement","created_at":"now","updated_at":"now"})) })) .route("/repos/owner/repository/issues/comments/8",get(move||{let remote=continuation.clone();async move{let number=if remote.lock().unwrap().authority==Authority::OtherIssue {2}else{1};Json(json!({"id":8,"node_id":"followup-comment","html_url":format!("https://github.com/owner/repository/issues/{number}#issuecomment-8"),"issue_url":format!("https://api.github.com/repos/owner/repository/issues/{number}"),"body":"continue current implementation","created_at":"now","updated_at":"now"}))}})) .route("/repos/owner/repository/issues/2",get(||async{Json(json!({"id":2,"node_id":"other-issue","number":2,"title":"Other issue","state":"open","html_url":"https://github.com/owner/repository/issues/2"}))})) .route("/repos/owner/repository", get(|| async { Json(json!({"default_branch":"main"})) })) - .route("/repos/owner/repository/pulls", get({ let pr=pr.clone(); let remote=remote.clone(); move || { let mut pr=pr.clone(); let remote=remote.clone(); async move { let state=remote.lock().unwrap(); if let Some(body)=&state.pr_body {pr["body"]=json!(body);} Json(if state.create_pr && !state.pr_created {json!([])} else {json!([pr])}) } }}).post({ let pr=pr.clone(); let remote=remote.clone(); move || {let pr=pr.clone(); let remote=remote.clone(); async move { let mut state=remote.lock().unwrap(); state.pr_created=true; state.writes+=1; Json(pr) }}})) + .route("/repos/owner/repository/pulls", get({ let pr=pr.clone(); let remote=remote.clone(); move || { let mut pr=pr.clone(); let remote=remote.clone(); async move { let state=remote.lock().unwrap(); if let Some(body)=&state.pr_body {pr["body"]=json!(body);} Json(if state.pr_missing {json!([])} else {json!([pr])}) } }}).post({ let pr=pr.clone(); let remote=remote.clone(); move |Json(body): Json| {let pr=pr.clone(); let remote=remote.clone(); async move { let mut state=remote.lock().unwrap(); state.pr_requests.push(body); state.pr_missing=false; state.writes+=1; Json(pr) }}})) .route("/repos/owner/repository/git/ref/heads/main",get(|| async {Json(json!({"ref":"refs/heads/main","object":{"sha":"base"}}))})) .route("/repos/owner/repository/git/ref/heads/head",get({let remote=remote.clone(); move || {let remote=remote.clone(); async move { use axum::response::IntoResponse as _; if remote.lock().unwrap().head_created {Json(json!({"ref":"refs/heads/head","object":{"sha":"new"}})).into_response()} else {(axum::http::StatusCode::NOT_FOUND,Json(json!({"message":"missing"}))).into_response()} }}})) .route("/repos/owner/repository/git/commits/base",get(|| async {Json(json!({"sha":"base","tree":{"sha":"tree"}}))})) - .route("/repos/owner/repository/git/commits",post({let remote=remote.clone(); move || {let remote=remote.clone(); async move {remote.lock().unwrap().writes+=1; Json(json!({"sha":"new","tree":{"sha":"tree"}}))}}})) - .route("/repos/owner/repository/git/refs",post({let remote=remote.clone(); move || {let remote=remote.clone(); async move {let mut state=remote.lock().unwrap(); state.head_created=true; state.writes+=1; Json(json!({"ref":"refs/heads/head","object":{"sha":"new"}}))}}})) + .route("/repos/owner/repository/git/commits",post({let remote=remote.clone(); move |Json(body): Json| {let remote=remote.clone(); async move {let mut state=remote.lock().unwrap(); state.commit_requests.push(body); state.writes+=1; Json(json!({"sha":"new","tree":{"sha":"tree"}}))}}})) + .route("/repos/owner/repository/git/refs",post({let remote=remote.clone(); move |Json(body): Json| {let remote=remote.clone(); async move {let mut state=remote.lock().unwrap(); state.ref_requests.push(body); state.head_created=true; state.writes+=1; Json(json!({"ref":"refs/heads/head","object":{"sha":"new"}}))}}})) .route("/repos/owner/repository/pulls/9", get(move || {let mut pr=pr.clone();let remote=pr_read.clone(); async move {let remote=remote.lock().unwrap();if remote.authority==Authority::TargetClosed{pr["state"]=json!("closed");} if let Some(body)=&remote.pr_body{pr["body"]=json!(body);}Json(pr)}})) - .route("/graphql", post(move||{let remote=associations.clone(); async move {let nodes=if remote.lock().unwrap().authority==Authority::AssociationRemoved{json!([])}else{json!([{"number":1,"repository":{"nameWithOwner":"owner/repository"}}])};Json(json!({"data":{"repository":{"pullRequest":{"closingIssuesReferences":{"nodes":nodes,"pageInfo":{"hasNextPage":false,"endCursor":null}}}}}})) }})); + .route("/graphql", post(move || { + let remote = associations.clone(); + async move { + let state = remote.lock().unwrap(); + if state.authority == Authority::AssociationUnavailable { + return Err(axum::http::StatusCode::SERVICE_UNAVAILABLE); + } + let nodes = if state.authority == Authority::AssociationRemoved { + json!([]) + } else { + json!([{"number":state.closing_issue.unwrap_or(1),"repository":{"nameWithOwner":"owner/repository"}}]) + }; + Ok(Json(json!({"data":{"repository":{"pullRequest":{"closingIssuesReferences":{ + "nodes":nodes, "pageInfo":{"hasNextPage":false,"endCursor":null} + }}}}}))) + } + })); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let address = listener.local_addr().unwrap(); let task = tokio::spawn(async move { @@ -181,6 +217,10 @@ async fn server( .add_retry_config(octocrab::service::middleware::retry::RetryConfig::None) .build() .unwrap(); + (Arc::new(publication_client(client, permission)), task) +} + +fn publication_client(client: octocrab::Octocrab, permission: bool) -> GitHubClient { let identity = crate::github::GitHubIdentity { app_id: 1, app_slug: "braid".into(), @@ -200,26 +240,22 @@ async fn server( BTreeMap::new() }, }; - ( - Arc::new(GitHubClient::publication_test_client( - client, - identity, - crate::config::GitHubConfig { - app_id: 1, - private_key_file: PathBuf::new(), - projects_v2_enabled: false, - repository: "owner/repository".into(), - additional_repositories: Vec::new(), - handle: "braid".into(), - api_version: "2022-11-28".into(), - webhook_secret_environment: None, - webhook_secret_file: None, - }, - )), - task, + GitHubClient::publication_test_client( + client, + identity, + crate::config::GitHubConfig { + app_id: 1, + private_key_file: PathBuf::new(), + projects_v2_enabled: false, + repository: "owner/repository".into(), + additional_repositories: Vec::new(), + handle: "braid".into(), + api_version: "2022-11-28".into(), + webhook_secret_environment: None, + webhook_secret_file: None, + }, ) } - #[tokio::test] async fn outbox_delivery_recovery_and_rate_deadline_use_production_executor() { let fixture = Fixture::new(false); @@ -237,14 +273,30 @@ async fn outbox_delivery_recovery_and_rate_deadline_use_production_executor() { assert!(deadline > time::OffsetDateTime::now_utc() + time::Duration::seconds(110)); assert_eq!(remote.lock().unwrap().writes, 0); task.abort(); - remote.lock().unwrap().limit = None; + let fixture = fixture.reopen(); + { + let mut remote = remote.lock().unwrap(); + remote.limit = None; + remote.lose_comment_response = true; + } let (github, task) = server(remote.clone(), true).await; fixture.due(); - fixture.drain(github.clone()).await; - assert_eq!(fixture.receipt(&receipt.request_id).lifecycle, "applied"); + fixture.drain(github).await; + let result = fixture.receipt(&receipt.request_id); + assert_eq!(result.lifecycle, "uncertain", "{result:?}"); + assert!(result.remote_database_id.is_none()); assert_eq!(remote.lock().unwrap().writes, 1); - // Simulate remote success before local acknowledgement persisted, then restart recovery. - fixture.db().execute("UPDATE github_write_outbox SET lifecycle='sending'", []).unwrap(); + task.abort(); + // A read-only installation can recognize a POST whose response was lost. + let fixture = fixture.reopen(); + fixture.store.recover_writes().unwrap(); + fixture.due(); + let (github, task) = server(remote.clone(), false).await; + fixture.drain(github.clone()).await; + let recovered = fixture.receipt(&receipt.request_id); + assert_eq!(recovered.lifecycle, "applied", "{recovered:?}"); + assert_eq!(recovered.remote_database_id.as_deref(), Some("99")); + let fixture = fixture.reopen(); fixture.store.recover_writes().unwrap(); fixture.drain(github).await; assert_eq!(fixture.receipt(&receipt.request_id).lifecycle, "applied"); @@ -253,99 +305,96 @@ async fn outbox_delivery_recovery_and_rate_deadline_use_production_executor() { } #[tokio::test] -async fn uncertain_comment_recovery_scans_the_remote_conversation_once() { +async fn uncertain_comment_can_be_created_after_a_canonical_read_finds_no_match() { let fixture = Fixture::new(false); let receipt = fixture.comment(); - fixture.db().execute("UPDATE github_write_outbox SET lifecycle='uncertain'", []).unwrap(); + let owner = fixture + .store + .acquire_runtime_lease("runtime".into(), "before-restart".into(), 3600) + .unwrap(); + let attempt = fixture.store.claim_github_write(owner.clone()).unwrap().unwrap(); + assert_eq!(attempt.intent_id, receipt.intent_id); + // The process exits after claiming the write, before sending a request. + fixture.store.release_runtime_lease(owner).unwrap(); + let fixture = fixture.reopen(); + assert_eq!(fixture.store.recover_writes().unwrap(), 1); + let remote = Arc::new(Mutex::new(Remote::default())); let (github, http) = server(remote.clone(), true).await; fixture.drain(github).await; - assert_eq!(fixture.receipt(&receipt.request_id).lifecycle, "applied"); + let result = fixture.receipt(&receipt.request_id); + assert_eq!(result.lifecycle, "applied"); + assert_eq!(result.remote_database_id.as_deref(), Some("99")); let remote = remote.lock().unwrap(); - assert_eq!(remote.comment_reads, 1); + assert_eq!(remote.comment_requests.first(), Some(&"GET")); assert_eq!(remote.writes, 1); http.abort(); } #[tokio::test] -async fn issue_source_ensures_pr_with_frozen_plan_and_one_native_activation() { - let fixture = Fixture::new(true); - assert!( - create_comment( - &fixture.config, - &fixture.store, - CommentCreateRequest { - invocation: fixture.invocation(), - target: "owner/repository#1".parse().unwrap(), - profile_id: "pr-codex".into(), - body: "forged".into(), - request_id: None - } - ) - .is_err() - ); - let receipt = ensure_pull_request( - &fixture.config, - &fixture.store, - PullRequestEnsureRequest { - invocation: fixture.invocation(), - repository: "owner/repository".parse().unwrap(), - comment_id: 7, - head: Some("head".into()), - }, - ) - .unwrap(); - assert_eq!(receipt.source.as_ref().unwrap().profile_id, "issue-codex"); - assert_eq!(receipt.source.as_ref().unwrap().role, "issue_agent"); - let remote = Arc::new(Mutex::new(Remote::default())); - let (github, task) = server(remote.clone(), true).await; - fixture.drain(github.clone()).await; - let result = fixture.receipt(&receipt.request_id); - assert_eq!(result.lifecycle, "applied", "{:?}", result.last_error); - let plan = - fixture.store.implementation_request_receipt(receipt.intent_id.clone()).unwrap().unwrap(); - assert_eq!(plan.head_ref, "head"); - assert_eq!(plan.stage, "activation_pending"); - for stage in ["head_ready", "pull_request_ready", "associated", "activation_pending"] { - fixture.db().execute("UPDATE implementation_requests SET stage=?1", [stage]).unwrap(); - fixture.db().execute("UPDATE github_write_outbox SET lifecycle='sending'", []).unwrap(); - fixture.store.recover_writes().unwrap(); - fixture.drain(github.clone()).await; - assert_eq!(fixture.receipt(&receipt.request_id).lifecycle, "applied"); - } - let count: i64 = fixture - .db() - .query_row( - "SELECT COUNT(*) FROM deliveries WHERE delivery_guid LIKE 'braid-pr-ensure-%'", - [], - |row| row.get(0), - ) - .unwrap(); - assert_eq!(count, 1); - assert_eq!(remote.lock().unwrap().writes, 0); - task.abort(); -} - -#[tokio::test] -async fn source_invalidation_and_missing_permissions_reject_before_mutation() { - for invalidated in [false, true] { +async fn completed_turn_can_publish_but_source_fences_reject_before_mutation() { + for fence in ["completed", "reset", "invalidation", "replacement"] { let fixture = Fixture::new(true); + if fence == "completed" { + let error = create_comment( + &fixture.config, + &fixture.store, + CommentCreateRequest { + invocation: fixture.invocation(), + target: "owner/repository#1".parse().unwrap(), + profile_id: "pr-codex".into(), + body: "forged".into(), + request_id: None, + }, + ) + .unwrap_err(); + assert!( + error.to_string().contains("publication Profile does not match source assignment"), + "{error}" + ); + } let receipt = fixture.comment(); - if invalidated { - fixture - .db() - .execute("UPDATE provider_sessions SET lifecycle='reset_pending'", []) - .unwrap(); + match fence { + "reset" => { + fixture + .db() + .execute("UPDATE provider_sessions SET lifecycle='reset_pending'", []) + .unwrap(); + } + "invalidation" => { + fixture.db().execute("INSERT INTO events(event_id,work_item_node_id,origin,reference,lifecycle,observed_at,kind) VALUES ('invalidate','item','human','changed','pending','now','invalidate')", []).unwrap(); + } + "replacement" => { + fixture.db().execute_batch("UPDATE assignments SET lifecycle='retired'; INSERT INTO assignments VALUES ('replacement','item',2,'active','now',NULL);").unwrap(); + } + _ => {} } - if invalidated { - // No environment flag is needed to reject a stale cwd binding. - assert!(resolve_source(&fixture.config, None, &fixture.invocation()).is_err()); + if fence != "completed" { + let error = resolve_source(&fixture.config, None, &fixture.invocation()).unwrap_err(); + assert!( + error.to_string().contains("publication source was invalidated or superseded"), + "{fence}: {error}" + ); } let remote = Arc::new(Mutex::new(Remote::default())); - let (github, task) = server(remote.clone(), invalidated).await; + let (github, task) = server(remote.clone(), true).await; fixture.drain(github).await; - assert_eq!(fixture.receipt(&receipt.request_id).lifecycle, "rejected"); - assert_eq!(remote.lock().unwrap().writes, 0); + let result = fixture.receipt(&receipt.request_id); + assert_eq!( + result.lifecycle, + if fence == "completed" { "applied" } else { "rejected" }, + "{fence}: {:?}", + result.last_error + ); + if fence != "completed" { + assert!( + result + .last_error + .unwrap() + .contains("publication source was invalidated or superseded") + ); + } + assert_eq!(remote.lock().unwrap().writes, usize::from(fence == "completed")); task.abort(); } } @@ -364,69 +413,120 @@ async fn initial_ensure_bootstrap_pr_association_and_restart_do_not_duplicate_mu }, ) .unwrap(); - let remote = Arc::new(Mutex::new(Remote { create_pr: true, ..Remote::default() })); + let source = receipt.source.as_ref().unwrap(); + assert_eq!(source.profile_id, "issue-codex"); + assert_eq!(source.role, "issue_agent"); + let remote = Arc::new(Mutex::new(Remote { + pr_missing: true, + authority: Authority::AssociationUnavailable, + ..Remote::default() + })); let (github, task) = server(remote.clone(), true).await; - fixture.drain(github.clone()).await; + fixture.drain(github).await; let result = fixture.receipt(&receipt.request_id); - assert_eq!(result.lifecycle, "applied", "{:?}", result.last_error); - assert_eq!(remote.lock().unwrap().writes, 3); // commit, ref, PR - fixture.db().execute("UPDATE github_write_outbox SET lifecycle='sending'", []).unwrap(); + assert_eq!(result.lifecycle, "uncertain", "{result:?}"); + assert!(result.last_error.as_deref().unwrap().contains("503"), "{result:?}"); + let plan = + fixture.store.implementation_request_receipt(receipt.intent_id.clone()).unwrap().unwrap(); + assert_eq!(plan.stage, "pull_request_ready"); + assert_eq!(plan.pull_request_number, Some(9)); + assert!(!plan.activation_delivered); + task.abort(); + { + let remote = remote.lock().unwrap(); + assert_eq!(remote.writes, 3); + assert_eq!(remote.commit_requests.len(), 1); + assert_eq!(remote.commit_requests[0]["tree"], "tree"); + assert_eq!(remote.commit_requests[0]["parents"], json!(["base"])); + assert_eq!(remote.ref_requests, vec![json!({"ref":"refs/heads/head","sha":"new"})]); + assert_eq!(remote.pr_requests.len(), 1); + assert_eq!(remote.pr_requests[0]["head"], "head"); + assert_eq!(remote.pr_requests[0]["base"], "main"); + assert_eq!(remote.pr_requests[0]["draft"], true); + let body = remote.pr_requests[0]["body"].as_str().unwrap(); + assert!(body.contains("Closes #1"), "missing Issue association: {body}"); + assert!( + body.contains("https://github.com/owner/repository/issues/comments/7"), + "missing durable request: {body}" + ); + } + remote.lock().unwrap().authority = Authority::Intact; + let fixture = fixture.reopen(); fixture.store.recover_writes().unwrap(); + fixture.due(); + let (github, task) = server(remote.clone(), true).await; fixture.drain(github).await; - assert_eq!(fixture.receipt(&receipt.request_id).lifecycle, "applied"); + let result = fixture.receipt(&receipt.request_id); + assert_eq!(result.lifecycle, "applied", "{result:?}"); + let delivered = + fixture.store.implementation_request_receipt(receipt.intent_id).unwrap().unwrap(); + assert!(delivered.activation_delivered); + assert_eq!( + fixture + .db() + .query_row( + "SELECT count(*) FROM events WHERE kind='assign' AND detail='pr_ensure'", + [], + |row| row.get::<_, i64>(0) + ) + .unwrap(), + 1 + ); assert_eq!(remote.lock().unwrap().writes, 3); task.abort(); } #[tokio::test] async fn source_role_can_publish_related_cross_surface_without_target_profile_tags() { - for target_pr in [true, false] { - for fence in ["valid", "invalidated", "profile_changed"] { - let fixture = Fixture::new(true); - if !target_pr { - fixture - .db() - .execute("UPDATE agent_instances SET role='pr_implementation_agent'", []) - .unwrap(); - } - if !target_pr { - fixture.db().execute("UPDATE work_items SET kind='pr',number=9", []).unwrap(); - } + for (target_pr, profile_changed) in [(true, false), (false, false), (true, true)] { + let fixture = Fixture::new(true); + if target_pr { + fixture.db().execute("UPDATE work_items SET number=7", []).unwrap(); + } else { + fixture + .db() + .execute("UPDATE agent_instances SET role='pr_implementation_agent'", []) + .unwrap(); + fixture.db().execute("UPDATE work_items SET kind='pr',number=9", []).unwrap(); + } + let receipt = fixture.comment(); + if profile_changed { + fixture.db().execute_batch("INSERT INTO profiles SELECT 'pr-codex', revision, effective_digest, provider_kind, tags FROM profiles WHERE profile_id='issue-codex'; UPDATE agent_instances SET profile_id='pr-codex';").unwrap(); + } + let remote = Arc::new(Mutex::new(Remote { + closing_issue: Some(if target_pr { 7 } else { 1 }), + target_kind: if target_pr { TargetKind::PullRequest } else { TargetKind::Issue }, + ..Remote::default() + })); + let (github, task) = server(remote.clone(), true).await; + fixture.drain(github).await; + let result = fixture.receipt(&receipt.request_id); + assert_eq!( + result.lifecycle, + if profile_changed { "rejected" } else { "applied" }, + "{:?}", + result.last_error + ); + let state = remote.lock().unwrap(); + assert_eq!(state.writes, usize::from(!profile_changed)); + if profile_changed { assert!( - resolve_source(&fixture.config, Some("pr-codex"), &fixture.invocation()).is_err() + result + .last_error + .as_deref() + .unwrap() + .contains("publication source was invalidated or superseded"), + "{result:?}" ); - let receipt = fixture.comment(); - match fence { - "invalidated" => { - fixture - .db() - .execute("UPDATE provider_sessions SET lifecycle='reset_pending'", []) - .unwrap(); - } - "profile_changed" => { - fixture.db().execute_batch("INSERT INTO profiles SELECT 'pr-codex', revision, effective_digest, provider_kind, tags FROM profiles WHERE profile_id='issue-codex'; UPDATE agent_instances SET profile_id='pr-codex';").unwrap(); - } - _ => {} - } - let remote = Arc::new(Mutex::new(Remote { - target_kind: if target_pr { TargetKind::PullRequest } else { TargetKind::Issue }, - ..Remote::default() - })); - let (github, task) = server(remote.clone(), true).await; - fixture.drain(github).await; - let result = fixture.receipt(&receipt.request_id); - assert_eq!( - result.lifecycle, - if fence == "valid" { "applied" } else { "rejected" }, - "{:?}", - result.last_error - ); - assert_eq!(remote.lock().unwrap().writes, usize::from(fence == "valid")); - task.abort(); + } else { + let role = if target_pr { "Issue Agent" } else { "PR Implementation Agent" }; + assert!(state.comments[0]["body"].as_str().unwrap().contains(role)); } + task.abort(); } } +mod publication_contract; mod turn_start; mod body_edit; diff --git a/src/writer/tests/body_edit.rs b/src/writer/tests/body_edit.rs index 718d1b15..c474cdb0 100644 --- a/src/writer/tests/body_edit.rs +++ b/src/writer/tests/body_edit.rs @@ -171,27 +171,7 @@ pub(super) async fn body_server( .add_retry_config(octocrab::service::middleware::retry::RetryConfig::None) .build() .unwrap(); - let (template, other) = server(Arc::new(Mutex::new(Remote::default())), true).await; - other.abort(); - let config = crate::config::GitHubConfig { - app_id: 1, - private_key_file: PathBuf::new(), - projects_v2_enabled: false, - repository: "owner/repository".into(), - additional_repositories: Vec::new(), - handle: "braid".into(), - api_version: "2022-11-28".into(), - webhook_secret_environment: None, - webhook_secret_file: None, - }; - ( - Arc::new(GitHubClient::publication_test_client( - client, - template.identity().clone(), - config, - )), - task, - ) + (Arc::new(publication_client(client, true)), task) } pub(super) fn pr_source(fixture: &Fixture, own_pr: bool) { fixture.db().execute("UPDATE agent_instances SET role='pr_implementation_agent'", []).unwrap(); @@ -244,34 +224,20 @@ async fn own_pr_edit_preserves_marker_closing_and_recovers_unconfirmed_success_w task.abort(); } #[tokio::test] -async fn pr_source_corrects_direct_issue_with_pr_attribution_not_profile_target_tag() { - let fixture = Fixture::new(true); - pr_source(&fixture, false); - let remote = Arc::new(Mutex::new(BodyRemote::new(false))); - let (github, task) = body_server(remote.clone()).await; - let receipt = accept(&fixture, &github).await; - fixture.drain(github).await; - let result = fixture.receipt(&receipt.request_id); - assert_eq!(result.lifecycle, "applied", "{:?}", result.last_error); - assert_eq!(result.role, "PR Implementation Agent"); - assert!( - remote.lock().unwrap().snapshot.body.as_ref().unwrap().contains("PR Implementation Agent") - ); - task.abort(); -} -#[tokio::test] -async fn changed_association_closed_target_old_context_generation_session_and_human_edits_never_mutate() - { - for fence in - ["unrelated", "closed", "context", "generation", "session", "human", "profile", "turn"] - { +async fn changed_snapshot_or_source_rejects_an_admitted_edit_before_mutation() { + for (fence, state, reason) in [ + ("closed", "conflict", "canonical title/body changed since snapshot"), + ("context", "rejected", "publication source was invalidated or superseded"), + ("generation", "rejected", "publication source was invalidated or superseded"), + ("session", "rejected", "publication source was invalidated or superseded"), + ("human", "conflict", "canonical title/body changed since snapshot"), + ] { let fixture = Fixture::new(true); pr_source(&fixture, false); let remote = Arc::new(Mutex::new(BodyRemote::new(false))); let (github, task) = body_server(remote.clone()).await; let receipt = accept(&fixture, &github).await; match fence { - "unrelated" => remote.lock().unwrap().associated = false, "closed" => remote.lock().unwrap().snapshot.state = "closed".into(), "context" => { fixture @@ -286,63 +252,36 @@ async fn changed_association_closed_target_old_context_generation_session_and_hu fixture.db().execute("INSERT INTO provider_sessions(session_id,agent_id,provider_kind,provider_session_id,context_revision,instruction_revision,lifecycle,started_at) VALUES ('new','agent','codex','new','context','instructions','idle','now')",[]).unwrap(); } "human" => remote.lock().unwrap().snapshot.body = Some("Human new design".into()), - "profile" => { - assert!( - resolve_source(&fixture.config, Some("pr-codex"), &fixture.invocation()) - .is_err() - ); - } - "turn" => assert!( - resolve_source(&fixture.config, None, &Invocation::Agent("not-current".into())) - .is_err() - ), _ => unreachable!(), } - if matches!(fence, "profile" | "turn") { - task.abort(); - continue; - } fixture.drain(github).await; let result = fixture.receipt(&receipt.request_id); - assert_eq!( - result.lifecycle, - if matches!(fence, "human" | "closed") { "conflict" } else { "rejected" }, - "{fence}: {:?}", - result.last_error - ); + assert_eq!(result.lifecycle, state, "{fence}: {:?}", result.last_error); + assert!(result.last_error.as_deref().unwrap().contains(reason), "{fence}: {result:?}"); assert_eq!(remote.lock().unwrap().writes, 0, "{fence}"); task.abort(); } } #[tokio::test] -async fn preflight_and_mutation_limits_remain_durable_then_converge_after_restart() { - for mutation in [false, true] { - let fixture = Fixture::new(true); - pr_source(&fixture, true); - let remote = Arc::new(Mutex::new(BodyRemote::new(true))); - let (github, task) = body_server(remote.clone()).await; - let receipt = accept(&fixture, &github).await; - { - let mut state = remote.lock().unwrap(); - state.limited = !mutation; - state.mutation_limited = mutation; - } - fixture.drain(github).await; - assert_eq!(fixture.receipt(&receipt.request_id).lifecycle, "pending"); - assert_eq!(remote.lock().unwrap().writes, 0); - task.abort(); - { - let mut state = remote.lock().unwrap(); - state.limited = false; - state.mutation_limited = false; - } - let (github, task) = body_server(remote.clone()).await; - fixture.due(); - fixture.drain(github).await; - assert_eq!(fixture.receipt(&receipt.request_id).lifecycle, "applied"); - assert_eq!(remote.lock().unwrap().writes, 1); - task.abort(); - } +async fn rate_limited_patch_converges_after_restart() { + let fixture = Fixture::new(true); + pr_source(&fixture, true); + let remote = Arc::new(Mutex::new(BodyRemote::new(true))); + let (github, task) = body_server(remote.clone()).await; + let receipt = accept(&fixture, &github).await; + remote.lock().unwrap().mutation_limited = true; + fixture.drain(github).await; + assert_eq!(fixture.receipt(&receipt.request_id).lifecycle, "pending"); + assert_eq!(remote.lock().unwrap().writes, 0); + task.abort(); + remote.lock().unwrap().mutation_limited = false; + let fixture = fixture.reopen(); + let (github, task) = body_server(remote.clone()).await; + fixture.due(); + fixture.drain(github).await; + assert_eq!(fixture.receipt(&receipt.request_id).lifecycle, "applied"); + assert_eq!(remote.lock().unwrap().writes, 1); + task.abort(); } #[tokio::test] @@ -352,35 +291,43 @@ async fn own_issue_body_edit_and_input_boundaries_use_the_same_acceptance_path() let (github, task) = body_server(remote.clone()).await; let target: WorkItemLocator = "owner/repository#1".parse().unwrap(); let snapshot = edit::read_snapshot(&github, &target).await.unwrap(); - for (title, body) in [ - (Some(String::new()), None), - (Some("x".repeat(257)), None), - (None, Some(String::new())), - (None, Some("界".repeat(20_001))), - (None, None), + for (title, body, expected) in [ + (Some(String::new()), None, "title must contain 1-256 bytes"), + (Some("x".repeat(257)), None, "title must contain 1-256 bytes"), + (None, Some(String::new()), "body must not be empty"), + (None, Some("界".repeat(20_001)), "Braid's safe limit is 60000"), + (None, None, "edit requires --title or --body-file"), ] { - assert!( - edit( - &fixture.config, - &fixture.store, - EditRequest { - invocation: fixture.invocation(), - target: target.clone(), - profile_id: "issue-codex".into(), - snapshot: snapshot.clone(), - title, - body, - request_id: "invalid".into() - } - ) - .is_err() - ); + let error = edit( + &fixture.config, + &fixture.store, + EditRequest { + invocation: fixture.invocation(), + target: target.clone(), + profile_id: "issue-codex".into(), + snapshot: snapshot.clone(), + title, + body, + request_id: "invalid".into(), + }, + ) + .unwrap_err(); + assert!(error.to_string().contains(expected), "wrong failure: {error}"); } - assert!(resolve_source(&fixture.config, None, &Invocation::Operator).is_err()); + let wrong_turn = Invocation::Agent("not-current".into()); + let error = resolve_source(&fixture.config, None, &wrong_turn).unwrap_err(); + assert!(error.to_string().contains("publication turn does not match current runtime worktree")); let receipt = accept(&fixture, &github).await; fixture.drain(github).await; assert_eq!(fixture.receipt(&receipt.request_id).lifecycle, "applied"); assert!(remote.lock().unwrap().snapshot.body.as_ref().unwrap().contains("Issue Agent")); + fixture.db().execute("DELETE FROM turns", []).unwrap(); + let error = resolve_source(&fixture.config, None, &Invocation::Operator).unwrap_err(); + assert!( + error + .to_string() + .contains("operator entry is unavailable inside an Agent runtime worktree") + ); task.abort(); } @@ -406,16 +353,38 @@ async fn unconfirmed_success_followed_by_human_edit_is_conflict_not_success_or_o } #[tokio::test] -async fn repeated_snapshot_body_edit_does_not_duplicate_attribution_or_protected_prefix() { +async fn ordinary_fixed_resolved_prose_code_lists_links_and_new_closing_text_are_applied() { + let body = r"Fixed pagination bug + +Resolved review feedback + +```rust +// Fixed pagination bug +let resolved = true; +``` + +- Fixed pagination bug +- Resolved review feedback + +[Fixed pagination bug](https://example.com/fixed) and [Resolved review feedback](https://example.com/resolved) + +Closes #999 + +resolves [#999](https://github.com/owner/repository/issues/999)"; let fixture = Fixture::new(true); pr_source(&fixture, true); let remote = Arc::new(Mutex::new(BodyRemote::new(true))); let (github, task) = body_server(remote.clone()).await; - let receipt = accept(&fixture, &github).await; - fixture.drain(github.clone()).await; - assert_eq!(fixture.receipt(&receipt.request_id).lifecycle, "applied"); - let body = remote.lock().unwrap().snapshot.body.clone().unwrap(); let target: WorkItemLocator = "owner/repository#1".parse().unwrap(); + // Ordinary words in the existing body are not frozen either. + remote + .lock() + .unwrap() + .snapshot + .body + .as_mut() + .unwrap() + .push_str("\n\nFixed previous bug\n\n- Resolved previous feedback\n\n```rust\n// Fixed previous bug\n```\n\nFixed [previous pagination bug](https://example.com/fixed)"); let receipt = edit( &fixture.config, &fixture.store, @@ -425,182 +394,151 @@ async fn repeated_snapshot_body_edit_does_not_duplicate_attribution_or_protected profile_id: "issue-codex".into(), snapshot: edit::read_snapshot(&github, &target).await.unwrap(), title: None, - body: Some(body.clone()), - request_id: "repeat".into(), + body: Some(body.into()), + request_id: "ordinary".into(), }, ) .unwrap(); fixture.drain(github).await; - assert_eq!(fixture.receipt(&receipt.request_id).lifecycle, "applied"); - assert_eq!(remote.lock().unwrap().snapshot.body.as_deref(), Some(body.as_str())); + let result = fixture.receipt(&receipt.request_id); + assert_eq!(result.lifecycle, "applied", "{body}: {:?}", result.last_error); + let state = remote.lock().unwrap(); + assert_eq!(state.writes, 1); + let rendered = state.snapshot.body.as_ref().unwrap(); + assert!(rendered.contains(body)); + assert!(rendered.contains("Closes #7")); + assert!(rendered.contains("Implementation request:")); + assert!(!rendered.contains("previous")); task.abort(); - fixture.db().execute("DELETE FROM turns", []).unwrap(); - assert!(resolve_source(&fixture.config, None, &Invocation::Operator).is_err()); } #[tokio::test] -async fn ordinary_fixed_resolved_prose_code_lists_links_and_new_closing_text_are_applied() { - for body in [ - "Fixed pagination bug", - "Resolved review feedback", - "```rust\n// Fixed pagination bug\nlet resolved = true;\n```", - "- Fixed pagination bug\n- Resolved review feedback", - "[Fixed pagination bug](https://example.com/fixed) and [Resolved review feedback](https://example.com/resolved)", - "New scope\n\nCloses #999", - "resolves [#999](https://github.com/owner/repository/issues/999)", - ] { - let fixture = Fixture::new(true); - pr_source(&fixture, true); - let remote = Arc::new(Mutex::new(BodyRemote::new(true))); - let (github, task) = body_server(remote.clone()).await; - let target: WorkItemLocator = "owner/repository#1".parse().unwrap(); - // Ordinary words in the existing body are not frozen either. - remote - .lock() - .unwrap() - .snapshot - .body - .as_mut() - .unwrap() - .push_str("\n\nFixed previous bug\n\n- Resolved previous feedback\n\n```rust\n// Fixed previous bug\n```\n\nFixed [previous pagination bug](https://example.com/fixed)"); +async fn new_pr_body_references_authorize_issue_edits_only_after_canonical_confirmation() { + let fixture = Fixture::new(true); + pr_source(&fixture, true); + let remote = Arc::new(Mutex::new(BodyRemote::new(true))); + let (github, task) = body_server(remote.clone()).await; + let own: WorkItemLocator = "owner/repository#1".parse().unwrap(); + let receipt = edit( + &fixture.config, + &fixture.store, + EditRequest { + invocation: fixture.invocation(), + target: own.clone(), + profile_id: "issue-codex".into(), + snapshot: edit::read_snapshot(&github, &own).await.unwrap(), + title: None, + body: Some("Closes #999".into()), + request_id: "new-source".into(), + }, + ) + .unwrap(); + fixture.drain(github.clone()).await; + assert_eq!(fixture.receipt(&receipt.request_id).lifecycle, "applied"); + assert_eq!(remote.lock().unwrap().writes, 1); + let issue: WorkItemLocator = "owner/repository#999".parse().unwrap(); + for confirmed in [false, true] { + remote.lock().unwrap().associated_999 = confirmed; let receipt = edit( &fixture.config, &fixture.store, EditRequest { invocation: fixture.invocation(), - target: target.clone(), + target: issue.clone(), profile_id: "issue-codex".into(), - snapshot: edit::read_snapshot(&github, &target).await.unwrap(), + snapshot: edit::read_snapshot(&github, &issue).await.unwrap(), title: None, - body: Some(body.into()), - request_id: "ordinary".into(), + body: Some("Corrected design".into()), + request_id: format!("issue-{confirmed}"), }, ) .unwrap(); - fixture.drain(github).await; + fixture.drain(github.clone()).await; let result = fixture.receipt(&receipt.request_id); - assert_eq!(result.lifecycle, "applied", "{body}: {:?}", result.last_error); + assert_eq!( + result.lifecycle, + if confirmed { "applied" } else { "rejected" }, + "{:?}", + result.last_error + ); let state = remote.lock().unwrap(); - assert_eq!(state.writes, 1); - let rendered = state.snapshot.body.as_ref().unwrap(); - assert!(rendered.contains(body)); - assert!(rendered.contains("Closes #7")); - assert!(rendered.contains("Implementation request:")); - assert!(!rendered.contains("previous")); - task.abort(); + assert_eq!(state.writes_999, usize::from(confirmed)); + if confirmed { + assert_eq!(result.role, "PR Implementation Agent"); + let body = state.issue_999.body.as_deref().unwrap(); + assert!( + body.contains("PR Implementation Agent") && body.contains("Corrected design"), + "{body}" + ); + } else { + assert!( + result + .last_error + .as_deref() + .unwrap() + .contains("target is not a permitted directly associated work item") + ); + } } + let assignments: i64 = + fixture.db().query_row("SELECT count(*) FROM assignments", [], |row| row.get(0)).unwrap(); + assert_eq!(assignments, 1, "body edits never activate another Group"); + task.abort(); } #[tokio::test] -async fn new_pr_body_references_authorize_issue_edits_only_after_canonical_confirmation() { - for body in ["Closes #999", "See #999; closing work will follow"] { +async fn heading_closing_and_ensure_blocks_survive_fences_comments_and_repeated_edits() { + for (protected, replacement) in [ + ( + "## Closes #7 ##\n\n## Implementation request: https://github.com/owner/repository/issues/comments/7 ##", + "```rust\nunclosed", + ), + ( + "Closes #7\n========\n\nImplementation request: https://github.com/owner/repository/issues/comments/7\n--------", + "", ] { - let fixture = Fixture::new(true); - pr_source(&fixture, true); - let remote = Arc::new(Mutex::new(BodyRemote::new(true))); remote.lock().unwrap().snapshot.body = Some(protected.into()); - let (github, task) = body_server(remote.clone()).await; - let target: WorkItemLocator = "owner/repository#1".parse().unwrap(); - let snapshot = edit::read_snapshot(&github, &target).await.unwrap(); - for body in [Some("Scope update".into()), None] { - let title_only = body.is_none(); - let result = edit( - &fixture.config, - &fixture.store, - EditRequest { - invocation: fixture.invocation(), - target: target.clone(), - profile_id: "issue-codex".into(), - snapshot: snapshot.clone(), - title: Some("Current title".into()), - body, - request_id: "boundary".into(), - }, - ); - if title_only { - let receipt = result.unwrap(); - fixture.drain(github.clone()).await; - assert_eq!(fixture.receipt(&receipt.request_id).lifecycle, "applied"); - } else { - assert!(result.is_err(), "{protected}"); - assert_eq!(remote.lock().unwrap().writes, 0); - } - } - let state = remote.lock().unwrap(); - assert_eq!(state.writes, 1); - assert_eq!(state.snapshot.body.as_deref(), Some(protected)); - task.abort(); + let error = edit( + &fixture.config, + &fixture.store, + EditRequest { + invocation: fixture.invocation(), + target: target.clone(), + profile_id: "issue-codex".into(), + snapshot: edit::read_snapshot(&github, &target).await.unwrap(), + title: None, + body: Some("Scope update".into()), + request_id: "boundary".into(), + }, + ) + .unwrap_err() + .to_string(); + assert!( + error + == "body maintenance requires self-contained paragraph/heading closing and request blocks without links or HTML; keep this body unchanged" + || error + == "body maintenance cannot change context-dependent closing or request blocks", + "{protected}: {error}" + ); } + let old_body = remote.lock().unwrap().snapshot.body.clone(); + let snapshot = edit::read_snapshot(&github, &target).await.unwrap(); + let receipt = edit( + &fixture.config, + &fixture.store, + EditRequest { + invocation: fixture.invocation(), + target, + profile_id: "issue-codex".into(), + snapshot, + title: Some("Current title".into()), + body: None, + request_id: "title-only".into(), + }, + ) + .unwrap(); + fixture.drain(github).await; + assert_eq!(fixture.receipt(&receipt.request_id).lifecycle, "applied"); + let state = remote.lock().unwrap(); + assert_eq!(state.writes, 1); + assert_eq!(state.snapshot.title, "Current title"); + assert_eq!(state.snapshot.body, old_body); + task.abort(); } diff --git a/src/writer/tests/continuous_collaboration.rs b/src/writer/tests/continuous_collaboration.rs index 1ff27297..4fcd2908 100644 --- a/src/writer/tests/continuous_collaboration.rs +++ b/src/writer/tests/continuous_collaboration.rs @@ -78,7 +78,7 @@ async fn another_context_read_cannot_acknowledge_a_revision_before_delivery() { comments: vec![], }) .unwrap(); - assert_eq!(f.store.processed_objects("item".into()).unwrap()[0].version, old_version); + assert_eq!(f.store.begin_observation("item".into()).unwrap().objects[0].version, old_version); let observation = CanonicalObservation { unedited_creation: false, created_at: None, @@ -150,12 +150,15 @@ fn failed_observation_commits_neither_events_nor_frontier() { events: vec![revision("v2", "new")], policy: SchedulerPolicy { quiet_seconds: 30, event_threshold: 8 }, }); - assert!(result.is_err()); + assert!( + matches!(result, Err(crate::store::StoreError::InvalidData(ref reason)) if reason == "complete observation has no root"), + "{result:?}" + ); assert_eq!( f.db().query_row("SELECT count(*) FROM events", [], |r| r.get::<_, i64>(0)).unwrap(), 0 ); - assert!(f.store.processed_objects("item".into()).unwrap().is_empty()); + assert!(f.store.begin_observation("item".into()).unwrap().objects.is_empty()); assert!(f.store.runtime_status().unwrap().batches.is_empty()); } @@ -167,27 +170,22 @@ fn independent_pr_ensures_deliver_two_activations_and_retry_one_identity() { let owner = f.store.acquire_runtime_lease("runtime".into(), "activation-test".into(), 3600).unwrap(); for number in [9, 10] { - let payload = serde_json::to_string(&AcceptedRequest::Ensure { - comment_id: number, - head: Some(format!("head-{number}")), - profile: profile.clone(), - }) + let receipt = ensure_pull_request( + &f.config, + &f.store, + PullRequestEnsureRequest { + invocation: Invocation::Operator, + repository: "owner/repository".parse().unwrap(), + comment_id: number, + head: Some(format!("head-{number}")), + }, + ) .unwrap(); let plan = f .store .prepare_implementation_request(NewImplementationRequest { root_intent_id: None, - write: NewGhWriteIntent { - request_key: format!("ensure-{number}"), - operation: "pr_ensure", - repository: "owner/repository".into(), - target: format!("https://github.com/owner/repository/issues/comments/{number}"), - profile_id: profile.id.clone(), - role: "Operator".into(), - request_digest: helpers::digest(&payload), - payload, - source: None, - }, + intent_id: receipt.intent_id, comment_database_id: number, comment_node_id: format!("comment-{number}"), issue_node_id: "item".into(), @@ -244,33 +242,6 @@ fn independent_pr_ensures_deliver_two_activations_and_retry_one_identity() { ); } -#[test] -fn human_edit_of_a_braid_authored_body_is_not_an_echo_or_an_urgent_mention() { - use crate::webhook::{self, ActorPolicy, WebhookHeaders}; - use hmac::{Hmac, KeyInit as _, Mac as _}; - let body=serde_json::to_vec(&json!({"action":"edited","sender":{"login":"human","node_id":"human"},"repository":{"node_id":"repo","full_name":"owner/repository"},"issue":{"node_id":"item","number":1,"title":"Design","state":"open","body":"> **Braid Agent · Braid**\n> Issue Agent\n\nRevised requirements","updated_at":"v2"},"changes":{"body":{"from":"old requirements"}}})).unwrap(); - let mut mac = Hmac::::new_from_slice(b"secret").unwrap(); - mac.update(&body); - let signature = format!("sha256={}", hex::encode(mac.finalize().into_bytes())); - let event = webhook::parse_verified( - WebhookHeaders { - signature: Some(&signature), - delivery: Some("revision"), - event: Some("issues"), - }, - &body, - b"secret", - &["owner/repository".into()], - "braid", - ActorPolicy { app_node_id: "app", app_login: "braid[bot]", agent_node_ids: &[] }, - ) - .unwrap(); - assert_eq!(event.kind, EventKind::Invalidate); - assert!(event.requires_attention); - assert!(!event.mention_candidate); - assert_eq!(event.origin, "external"); -} - #[test] fn interrupted_revision_coalesces_attention_into_one_continuation() { let f = Fixture::new(true); @@ -393,8 +364,14 @@ async fn root_edits_use_field_provenance_when_publication_evidence_is_unavailabl let remote = Arc::new(Mutex::new(remote)); let (github, task) = body_edit::body_server(remote.clone()).await; let previous = observe_issue(&f, &github, false).await; - let previous_fields = - f.store.processed_objects("item".into()).unwrap().remove(0).root_fields.unwrap(); + let previous_fields = f + .store + .begin_observation("item".into()) + .unwrap() + .objects + .remove(0) + .root_fields + .unwrap(); assert_eq!(Some(previous_fields.clone()), previous.root_fields()); { let mut state = remote.lock().unwrap(); @@ -433,7 +410,7 @@ async fn root_edits_use_field_provenance_when_publication_evidence_is_unavailabl [], |r| Ok((r.get(0)?,r.get(1)?)), ).unwrap(); assert_eq!(edited, (expected.into(), expected == "invalidate"), "{mode}"); - let processed = f.store.processed_objects("item".into()).unwrap().remove(0); + let processed = f.store.begin_observation("item".into()).unwrap().objects.remove(0); assert_eq!(processed.root_fields, current.root_fields(), "{mode}"); assert_ne!(previous_fields.body_digest, processed.root_fields.unwrap().body_digest); task.abort(); @@ -517,24 +494,20 @@ async fn native_association_changes_are_visible_without_a_root_version_change() let after = crate::context::CanonicalContext::PullRequest( crate::context::materialize_pull_request(&github, &locator, 100).await.unwrap(), ); - let before = crate::context::canonical_observations(&before).remove(0); - let after = crate::context::canonical_observations(&after).remove(0); - assert_eq!(before.version, after.version); - assert_eq!(before.body, after.body); - assert_ne!(before.metadata_digest, after.metadata_digest); - let prior = CanonicalObjectState { - root_fields: before.root_fields(), - node_id: before.object_node_id, - database_id: Some(before.database_id), - object_kind: "pr".into(), - version: before.version, - digest: before.digest, - lifecycle: "open".into(), - author_node_id: None, - author_login: None, - metadata_digest: before.metadata_digest, - }; - assert!(!reconcile::observation_unchanged(&prior, &after)); + let f = Fixture::new(false); + super::semantic_contract::observe(&f, &github, &before); + super::semantic_contract::observe(&f, &github, &after); + super::semantic_contract::observe(&f, &github, &after); + let edits: i64 = f + .db() + .query_row( + "SELECT count(*) FROM events WHERE work_item_node_id='pr' AND object_node_id='pr' + AND kind='invalidate' AND detail='edited' AND requires_attention=1", + [], + |row| row.get(0), + ) + .unwrap(); + assert_eq!(edits, 1, "losing a native edge must deliver exactly one PR invalidation"); http.abort(); } diff --git a/src/writer/tests/handoff.rs b/src/writer/tests/handoff.rs index b89b4f12..66f7bbf0 100644 --- a/src/writer/tests/handoff.rs +++ b/src/writer/tests/handoff.rs @@ -33,7 +33,7 @@ fn claim(f: &Fixture) -> Option { } #[tokio::test] -async fn handoff_is_atomic_idempotent_and_uses_next_batch_without_parallel_turns() { +async fn handoffs_debounce_together_and_redelivery_does_not_duplicate_their_inputs() { let f = Fixture::new(true); bind_pr(&f); let a = handoff(&f, "stable").unwrap(); @@ -48,30 +48,13 @@ async fn handoff_is_atomic_idempotent_and_uses_next_batch_without_parallel_turns f.db().query_row("SELECT urgent FROM wake_batches", [], |r| r.get::<_, i64>(0)).unwrap(), 0 ); - // Restart recovery cannot create a second logical event. - f.db().execute("UPDATE github_write_outbox SET lifecycle='sending'", []).unwrap(); - f.store.recover_writes().unwrap(); - f.due(); - f.drain(github.clone()).await; - assert_eq!(count(&f, "events"), 1); let b = handoff(&f, "second").unwrap(); - f.drain(github.clone()).await; + f.drain(github).await; assert_eq!(f.receipt(&b.request_id).lifecycle, "applied"); assert_eq!(count(&f, "wake_batches"), 1); // merge existing pending runnable(&f); - let first = claim(&f).unwrap(); - f.store.mark_turn_started(first.turn_id.clone(), "native-first".into()).unwrap(); - let c = handoff(&f, "while-running").unwrap(); - f.drain(github).await; - assert_eq!(f.receipt(&c.request_id).lifecycle, "applied"); - runnable(&f); - assert!(claim(&f).is_none()); - // Even if merged with an already-urgent batch, handoff input may only be - // sent after the running turn, where complete Context can be refreshed. - f.db().execute("UPDATE wake_batches SET urgent=1 WHERE lifecycle='runnable'", []).unwrap(); - assert!(f.store.claim_urgent_steer(first.turn_id.clone()).unwrap().is_none()); - f.store.mark_turn_terminal(first.turn_id, "completed".into()).unwrap(); - assert!(claim(&f).is_some()); + let turn = claim(&f).unwrap(); + assert_eq!(turn.references.len(), 2); task.abort(); } @@ -159,7 +142,6 @@ async fn accepted_handoff_waits_for_next_turn_and_survives_unavailable_publisher .await .unwrap(); assert!(prepared.is_none(), "canonical disassociation retires the handoff"); - assert!(recorder.inputs.lock().unwrap().is_empty()); let lifecycle: String = f .db() .query_row("SELECT lifecycle FROM events WHERE detail='pr_handoff'", [], |r| { @@ -177,7 +159,12 @@ async fn accepted_handoff_waits_for_next_turn_and_survives_unavailable_publisher async fn handoff_rejects_local_authority_and_generation_changes() { let unassigned = Fixture::new(true); unassigned.db().execute("INSERT INTO work_items(node_id,repository_node_id,kind,number,state,observed_at) VALUES ('pr','repo','pr',9,'open','now')", []).unwrap(); - assert!(handoff(&unassigned, "no-assignment").is_err()); + assert!( + handoff(&unassigned, "no-assignment") + .unwrap_err() + .to_string() + .contains("handoff target needs a current active schedulable PR generation") + ); for sql in [ "UPDATE assignments SET lifecycle='blocked' WHERE assignment_id='pr-assignment'", "UPDATE assignments SET lifecycle='finalizing' WHERE assignment_id='pr-assignment'", @@ -190,7 +177,13 @@ async fn handoff_rejects_local_authority_and_generation_changes() { let f = Fixture::new(true); bind_pr(&f); f.db().execute(sql, []).unwrap(); - assert!(handoff(&f, "reject").is_err(), "{sql}"); + let expected = if sql.contains("node_id='item'") { + "handoff requires an active Issue Agent on its OPEN Issue" + } else { + "handoff target needs a current active schedulable PR generation" + }; + let error = handoff(&f, "reject").unwrap_err(); + assert!(error.to_string().contains(expected), "{sql}: {error}"); assert_eq!(count(&f, "pr_handoffs"), 0); } let f = Fixture::new(true); @@ -208,7 +201,13 @@ async fn handoff_rejects_local_authority_and_generation_changes() { #[tokio::test] async fn handoff_remote_validation_never_schedules_before_confirmation() { - for mode in ["unrelated", "closed", "merged-target", "limited", "old-source"] { + for (mode, lifecycle, reason) in [ + ("unrelated", "rejected", "handoff requires GitHub-confirmed direct association"), + ("closed", "rejected", "handoff requires an OPEN Issue and OPEN unmerged PR"), + ("closed-target", "rejected", "handoff requires an OPEN Issue and OPEN unmerged PR"), + ("limited", "pending", "429"), + ("old-source", "rejected", "publication source was invalidated or superseded"), + ] { let f = Fixture::new(true); bind_pr(&f); let a = handoff(&f, mode).unwrap(); @@ -219,7 +218,7 @@ async fn handoff_remote_validation_never_schedules_before_confirmation() { if mode == "closed" { state.snapshot.state = "closed".into(); } - if mode == "merged-target" { + if mode == "closed-target" { state.pr_closed = true; } if mode == "limited" { @@ -232,11 +231,9 @@ async fn handoff_remote_validation_never_schedules_before_confirmation() { } let (github, task) = body_edit::body_server(Arc::new(Mutex::new(state))).await; f.drain(github).await; - assert_eq!( - f.receipt(&a.request_id).lifecycle, - if mode == "limited" { "pending" } else { "rejected" }, - "{mode}" - ); + let receipt = f.receipt(&a.request_id); + assert_eq!(receipt.lifecycle, lifecycle, "{mode}: {receipt:?}"); + assert!(receipt.last_error.as_deref().unwrap().contains(reason), "{mode}: {receipt:?}"); assert_eq!(count(&f, "events"), 0); assert_eq!(count(&f, "wake_batches"), 0); task.abort(); @@ -273,22 +270,6 @@ async fn applied_issue_design_is_materialized_at_handoff_safe_boundary_not_from_ assert!(reference.contains("Scope, verification, risks"), "{reference}"); assert!(reference.contains("Current canonical Context")); assert!(!reference.contains("old-pr-context")); - // Association deletion after acceptance cannot deliver an old cached Issue. - remote.lock().unwrap().associated = false; - let mut denied = String::new(); - assert!( - crate::group::input::append_current_context( - f.config.runtime.database(), - &collaboration, - &f.store, - f.config.profile("issue-codex").unwrap(), - &turn, - &mut denied - ) - .await - .is_ok_and(|d| matches!(d, crate::group::input::RefreshDisposition::Retire(_))) - ); - assert!(denied.is_empty()); task.abort(); } @@ -307,59 +288,17 @@ fn handoff_same_key_cannot_change_target_or_impersonate_issue_agent() { request_id: "stable".into() } ) - .is_err() + .unwrap_err() + .to_string() + .contains("already used for a different payload") ); + f.db().execute_batch("UPDATE agent_instances SET role='pr_implementation_agent' WHERE agent_id='agent'; UPDATE work_items SET kind='pr',number=10 WHERE node_id='item';").unwrap(); assert!( - super::super::handoff( - &f.config, - &f.store, - &HandoffRequest { - invocation: Invocation::Operator, - target: "owner/repository#9".parse().unwrap(), - request_id: "operator".into() - } - ) - .is_err() + handoff(&f, "pr-source") + .unwrap_err() + .to_string() + .contains("handoff requires an Issue Agent") ); - f.db().execute_batch("UPDATE agent_instances SET role='pr_implementation_agent' WHERE agent_id='agent'; UPDATE work_items SET kind='pr',number=10 WHERE node_id='item';").unwrap(); - assert!(handoff(&f, "pr-source").is_err()); -} - -#[tokio::test] -async fn app_comment_with_mention_is_not_a_handoff() { - let f = Fixture::new(true); - bind_pr(&f); - let event = IngressEvent { - identity: crate::store::ChangeIdentity::Occurrence, - delivery_guid: "app-echo".into(), - event_name: "issue_comment".into(), - action: Some("created".into()), - repository_node_id: "repo".into(), - repository: "owner/repository".into(), - work_item_node_id: Some("pr".into()), - work_item_kind: Some("pr"), - work_item_number: Some(9), - work_item_state: Some("open".into()), - object_node_id: Some("app-comment".into()), - object_version: None, - object_digest: None, - visible_body: Some("@braid please continue".into()), - actor_node_id: Some("app".into()), - actor_login: Some("braid[bot]".into()), - kind: crate::store::EventKind::OriginEcho, - detail: None, - cross_surface_invalidation: false, - requires_attention: true, - origin: "agent", - reference: "owner/repository#9".into(), - mention_candidate: false, - reaction_target: None, - known: true, - raw_payload: vec![], - }; - f.store.ingest_event(event, SchedulerPolicy { quiet_seconds: 0, event_threshold: 1 }).unwrap(); - assert_eq!(count(&f, "wake_batches"), 0); - assert_eq!(count(&f, "pr_handoffs"), 0); } #[tokio::test] @@ -404,17 +343,18 @@ async fn refresh_failure_defers_and_merges_an_arriving_handoff_without_losing_in remote.lock().unwrap().limited = true; let backend = crate::collaboration::CollaborationBackend::GitHub(github); let mut input = String::new(); + let result = crate::group::input::append_current_context( + f.config.runtime.database(), + &backend, + &f.store, + f.config.profile("issue-codex").unwrap(), + &first, + &mut input, + ) + .await; assert!( - crate::group::input::append_current_context( - f.config.runtime.database(), - &backend, - &f.store, - f.config.profile("issue-codex").unwrap(), - &first, - &mut input - ) - .await - .is_err() + matches!(result, Err(ref error) if error.to_string().contains("503")), + "expected canonical HTTP 503" ); assert!(input.is_empty()); f.store.defer_turn_claim(first.turn_id).unwrap(); @@ -457,7 +397,12 @@ async fn uncertain_issue_design_is_not_handed_off_as_published() { remote.lock().unwrap().lose_response = true; f.drain(github).await; assert_eq!(f.receipt(&edit.request_id).lifecycle, "uncertain"); - assert!(handoff(&f, "must-wait").is_err()); + assert!( + handoff(&f, "must-wait") + .unwrap_err() + .to_string() + .contains("Issue design edit is not confirmed applied") + ); assert_eq!(count(&f, "pr_handoffs"), 0); task.abort(); } @@ -484,9 +429,6 @@ impl crate::agent_session::AgentSession for RecordingSession { async fn close(&self) -> std::result::Result<(), crate::agent_session::SessionError> { Ok(()) } - async fn interrupt(&self) -> std::result::Result<(), crate::agent_session::SessionError> { - Ok(()) - } async fn steer_user_msg( &self, _: String, @@ -592,17 +534,16 @@ async fn canonical_invalid_handoff_retires_only_itself_and_survivors_really_send } let turn = if mode == "new-generation" { let backend = crate::collaboration::CollaborationBackend::GitHub(github.clone()); - assert!( - crate::group::input::prepare_input( - &f.config, - &backend, - &f.store, - f.config.profile("issue-codex").unwrap(), - turn.clone() - ) - .await - .is_err() - ); + let error = crate::group::input::prepare_input( + &f.config, + &backend, + &f.store, + f.config.profile("issue-codex").unwrap(), + turn.clone(), + ) + .await + .unwrap_err(); + assert!(format!("{error:#}").contains("503"), "{error:#}"); f.store.defer_turn_claim(turn.turn_id).unwrap(); remote.lock().unwrap().limited = false; // The failed transport keeps its real installation cooldown. A @@ -749,7 +690,9 @@ async fn retirement_is_fenced_atomic_and_preserves_other_handoff_and_historical_ } ] ) - .is_err() + .unwrap_err() + .to_string() + .contains("handoff retirement membership changed") ); assert_eq!( f.db() @@ -769,7 +712,10 @@ async fn retirement_is_fenced_atomic_and_preserves_other_handoff_and_historical_ send_prepared(&f, &backend, remaining, &recorder).await; assert!(recorder.inputs.lock().unwrap()[0].contains("Current canonical Context")); // No mutation using a stale claim after the provider boundary. - assert!(f.store.retire_handoff_inputs(turn, vec![input]).is_err()); + assert!(matches!( + f.store.retire_handoff_inputs(turn, vec![input]), + Err(crate::store::StoreError::Sqlite(rusqlite::Error::QueryReturnedNoRows)) + )); assert_eq!(count(&f, "pr_handoffs"), 2); assert_eq!(f.receipt(&first.request_id).lifecycle, "applied"); task.abort(); diff --git a/src/writer/tests/implementation_recovery.rs b/src/writer/tests/implementation_recovery.rs index 45edf829..7218cd33 100644 --- a/src/writer/tests/implementation_recovery.rs +++ b/src/writer/tests/implementation_recovery.rs @@ -95,7 +95,7 @@ fn ensure_rejects_invalid_ref_components_before_accepting_an_obligation() { } #[test] -fn temporary_ledger_contention_preserves_the_publication_obligation() { +fn ledger_errors_distinguish_retryable_contention_and_actor_loss_from_invalid_writes() { use crate::store::StoreError; for code in [rusqlite::ffi::SQLITE_BUSY, rusqlite::ffi::SQLITE_LOCKED] { let error = StoreError::Sqlite(rusqlite::Error::SqliteFailure( @@ -122,7 +122,7 @@ fn temporary_ledger_contention_preserves_the_publication_obligation() { async fn a_published_request_recovers_delivery_without_replaying_fenced_mutations() { let f = Fixture::new(true); let receipt = request(&f, 7); - let remote = Arc::new(Mutex::new(Remote { create_pr: true, ..Remote::default() })); + let remote = Arc::new(Mutex::new(Remote { pr_missing: true, ..Remote::default() })); let (github, http) = server(remote.clone(), true).await; f.drain(github.clone()).await; assert_eq!(f.receipt(&receipt.request_id).lifecycle, "applied"); @@ -131,7 +131,7 @@ async fn a_published_request_recovers_delivery_without_replaying_fenced_mutation legacy_gap(&f, &receipt); replace_source(&f); remote.lock().unwrap().pr_body = Some("Current scope, no historical discovery marker".into()); - f.drain(github.clone()).await; + f.drain(github).await; let result = f.receipt(&receipt.request_id); assert_eq!(result.lifecycle, "applied", "{:?}", result.last_error); assert!( @@ -143,16 +143,6 @@ async fn a_published_request_recovers_delivery_without_replaying_fenced_mutation ); assert_eq!(activations(&f), 1); assert_eq!(remote.lock().unwrap().writes, writes); - f.db() - .execute( - "UPDATE github_write_outbox SET lifecycle='sending' WHERE intent_id=?1", - [receipt.intent_id], - ) - .unwrap(); - f.store.recover_writes().unwrap(); - f.drain(github).await; - assert_eq!(activations(&f), 1); - assert_eq!(remote.lock().unwrap().writes, writes); http.abort(); } @@ -160,7 +150,7 @@ async fn a_published_request_recovers_delivery_without_replaying_fenced_mutation async fn a_followup_comment_reuses_the_original_managed_implementation_identity() { let f = Fixture::new(true); let original = request(&f, 7); - let remote = Arc::new(Mutex::new(Remote { create_pr: true, ..Remote::default() })); + let remote = Arc::new(Mutex::new(Remote { pr_missing: true, ..Remote::default() })); let (github, http) = server(remote.clone(), true).await; f.drain(github.clone()).await; legacy_gap(&f, &original); @@ -187,9 +177,17 @@ async fn a_followup_comment_reuses_the_original_managed_implementation_identity( #[tokio::test] async fn recovery_revalidates_the_current_open_source_target_and_association() { - for authority in - [Authority::SourceClosed, Authority::TargetClosed, Authority::AssociationRemoved] - { + for (authority, reason) in [ + ( + Authority::SourceClosed, + "implementation source Issue is no longer the same open work item", + ), + (Authority::TargetClosed, "implementation request PR is no longer open"), + ( + Authority::AssociationRemoved, + "managed implementation is no longer directly associated with its source Issue", + ), + ] { let f = Fixture::new(true); let receipt = request(&f, 7); let remote = Arc::new(Mutex::new(Remote::default())); @@ -198,7 +196,7 @@ async fn recovery_revalidates_the_current_open_source_target_and_association() { legacy_gap(&f, &receipt); remote.lock().unwrap().authority = authority; f.drain(github).await; - assert_eq!(f.receipt(&receipt.request_id).lifecycle, "rejected"); + assert_rejected(&f.receipt(&receipt.request_id), reason); assert_eq!(activations(&f), 0); assert_eq!(remote.lock().unwrap().writes, 0); http.abort(); @@ -217,13 +215,16 @@ async fn recovery_cannot_replace_a_blocked_generation_or_adopt_another_issue() { if blocked { f.db().execute("INSERT INTO assignments(assignment_id,work_item_node_id,generation,lifecycle,assigned_at) VALUES('withdrawn','pr',1,'blocked','now')",[]).unwrap(); f.drain(github).await; - assert_eq!(f.receipt(&original.request_id).lifecycle, "rejected"); + assert_rejected(&f.receipt(&original.request_id), "existing PR assignment is blocked"); } else { f.db().execute("UPDATE github_write_outbox SET next_attempt_at='2099-01-01T00:00:00Z' WHERE intent_id=?1",[&original.intent_id]).unwrap(); remote.lock().unwrap().authority = Authority::OtherIssue; let foreign = request(&f, 8); f.drain(github).await; - assert_eq!(f.receipt(&foreign.request_id).lifecycle, "rejected"); + assert_rejected( + &f.receipt(&foreign.request_id), + "initial PR ensure must originate from its own Issue source", + ); } assert_eq!(activations(&f), 0); assert_eq!(remote.lock().unwrap().writes, 0); @@ -236,11 +237,19 @@ async fn an_unpublished_request_still_requires_its_original_source_authority() { let f = Fixture::new(true); let receipt = request(&f, 7); replace_source(&f); - let remote = Arc::new(Mutex::new(Remote { create_pr: true, ..Remote::default() })); + let remote = Arc::new(Mutex::new(Remote { pr_missing: true, ..Remote::default() })); let (github, http) = server(remote.clone(), true).await; f.drain(github).await; - assert_eq!(f.receipt(&receipt.request_id).lifecycle, "rejected"); + assert_rejected( + &f.receipt(&receipt.request_id), + "publication source was invalidated or superseded", + ); assert_eq!(remote.lock().unwrap().writes, 0); assert_eq!(activations(&f), 0); http.abort(); } + +fn assert_rejected(receipt: &GhWriteReceipt, reason: &str) { + assert_eq!(receipt.lifecycle, "rejected", "{receipt:?}"); + assert!(receipt.last_error.as_deref().unwrap().contains(reason), "{receipt:?}"); +} diff --git a/src/writer/tests/observation_recovery.rs b/src/writer/tests/observation_recovery.rs index a69f8460..938c245c 100644 --- a/src/writer/tests/observation_recovery.rs +++ b/src/writer/tests/observation_recovery.rs @@ -25,24 +25,6 @@ fn comment(node: &str, body: &str) -> CommentSnapshot { deleted: false, } } -fn stored(o: &context::CanonicalObservation) -> crate::store::CanonicalObjectState { - crate::store::CanonicalObjectState { - node_id: o.object_node_id.clone(), - database_id: Some(o.database_id.clone()), - object_kind: o.object_kind.into(), - version: o.version.clone(), - digest: o.digest.clone(), - lifecycle: if matches!(o.object_kind, "issue" | "pr") { - o.work_item_state.to_ascii_lowercase() - } else { - o.lifecycle.into() - }, - author_node_id: o.author_node_id.clone(), - author_login: o.author_login.clone(), - metadata_digest: o.metadata_digest.clone(), - root_fields: o.root_fields(), - } -} fn scope(c: &CanonicalContext) -> ReconcileScope { let o = context::canonical_observations(c).remove(0); ReconcileScope { @@ -89,7 +71,10 @@ fn seed(f: &Fixture, c: &CanonicalContext) { f.store .commit_observation(ObservationCommit { basis: f.store.begin_observation(root).unwrap(), - current: context::canonical_observations(c).iter().map(stored).collect(), + current: context::canonical_observations(c) + .iter() + .map(super::semantic_contract::processed) + .collect(), events: vec![], policy: SchedulerPolicy { quiet_seconds: 30, event_threshold: 8 }, }) @@ -296,8 +281,9 @@ async fn a_legacy_local_tombstone_is_corrected_by_presence_without_waking_for_st assert_eq!(observe(&f, &github, &c, basis).unwrap(), 1); let restored = f .store - .processed_objects("item".into()) + .begin_observation("item".into()) .unwrap() + .objects .into_iter() .find(|o| o.node_id == "comment") .unwrap(); @@ -324,10 +310,10 @@ async fn an_admitted_delete_during_the_api_read_rejects_the_whole_old_snapshot() SchedulerPolicy { quiet_seconds: 30, event_threshold: 8 }, ) .unwrap(); - let expected = f.store.processed_objects("item".into()).unwrap(); + let expected = f.store.begin_observation("item".into()).unwrap().objects; let error = observe(&f, &github, &c, basis).unwrap_err().to_string(); assert!(error.contains("events arrived during canonical traversal"), "{error}"); - assert_eq!(f.store.processed_objects("item".into()).unwrap(), expected); + assert_eq!(f.store.begin_observation("item".into()).unwrap().objects, expected); http.abort(); } diff --git a/src/writer/tests/publication_contract.rs b/src/writer/tests/publication_contract.rs new file mode 100644 index 00000000..84188894 --- /dev/null +++ b/src/writer/tests/publication_contract.rs @@ -0,0 +1,49 @@ +use super::*; + +#[tokio::test] +async fn ambiguous_comment_recovery_records_ambiguity_without_another_mutation() { + let fixture = Fixture::new(false); + let receipt = fixture.comment(); + let remote = Arc::new(Mutex::new(Remote { lose_comment_response: true, ..Remote::default() })); + let (github, task) = server(remote.clone(), true).await; + fixture.drain(github).await; + task.abort(); + assert_eq!(fixture.receipt(&receipt.request_id).lifecycle, "uncertain"); + { + let mut remote = remote.lock().unwrap(); + let mut duplicate = remote.comments[0].clone(); + duplicate["id"] = json!(100); + duplicate["node_id"] = json!("second-comment"); + remote.comments.push(duplicate); + } + let fixture = fixture.reopen(); + fixture.store.recover_writes().unwrap(); + fixture.due(); + let (github, task) = server(remote.clone(), true).await; + fixture.drain(github).await; + let result = fixture.receipt(&receipt.request_id); + assert_eq!(result.lifecycle, "ambiguous"); + assert!(result.last_error.unwrap().contains("multiple matching App comments")); + assert_eq!(remote.lock().unwrap().writes, 1); + task.abort(); +} + +#[tokio::test] +async fn permission_and_missing_target_are_rejected_by_the_production_executor() { + for (permission, target_status, reason) in [ + (false, None, "lacks required permissions: issues"), + (true, Some(axum::http::StatusCode::NOT_FOUND), "GitHub returned 404"), + ] { + let fixture = Fixture::new(false); + let receipt = fixture.comment(); + let remote = Arc::new(Mutex::new(Remote { target_status, ..Remote::default() })); + let (github, task) = server(remote.clone(), permission).await; + fixture.drain(github.clone()).await; + let result = fixture.receipt(&receipt.request_id); + assert_eq!(result.lifecycle, "rejected"); + assert!(result.last_error.as_deref().unwrap().contains(reason), "{:?}", result.last_error); + fixture.drain(github).await; + assert_eq!(remote.lock().unwrap().writes, 0); + task.abort(); + } +} diff --git a/src/writer/tests/reaction_feedback.rs b/src/writer/tests/reaction_feedback.rs index 518bec10..45efc768 100644 --- a/src/writer/tests/reaction_feedback.rs +++ b/src/writer/tests/reaction_feedback.rs @@ -53,7 +53,8 @@ fn accepted_input_and_turn_terminal_survive_a_missing_publication_table() { assert_eq!(intents, ["eyes", "rocket", expected]); let owner = f.store.acquire_runtime_lease("runtime".into(), "publisher".into(), 60).unwrap(); - assert!(f.store.claim_github_write(owner.clone()).is_err()); + let error = f.store.claim_github_write(owner.clone()).unwrap_err(); + assert!(error.to_string().contains("no such table: github_write_outbox"), "{error}"); db.execute_batch("ALTER TABLE unavailable_outbox RENAME TO github_write_outbox").unwrap(); for content in ["eyes", expected] { let write = f.store.claim_github_write(owner.clone()).unwrap().unwrap(); @@ -118,14 +119,21 @@ fn context_reset_commits_with_publisher_unavailable_and_clears_a_late_rocket() { assert_eq!(lifecycles, ("interrupted".into(), "materializing".into())); db.execute_batch("ALTER TABLE unavailable_outbox RENAME TO github_write_outbox").unwrap(); - let rocket = if restarted { + drop(db); + let (f, owner, rocket) = if restarted { + f.store.release_runtime_lease(owner).unwrap(); + let f = f.reopen(); + let owner = f + .store + .acquire_runtime_lease("runtime".into(), "new publisher".into(), 60) + .unwrap(); f.store.recover_writes().unwrap(); let retry = f.store.claim_github_write(owner.clone()).unwrap().unwrap(); assert_eq!(retry.intent_id, rocket.intent_id); assert_eq!(retry.lifecycle, "uncertain"); - retry + (f, owner, retry) } else { - rocket + (f, owner, rocket) }; f.store.finish_github_write(rocket, "applied", Some("92".into()), None, None).unwrap(); let removal = f.store.claim_github_write(owner.clone()).unwrap().unwrap(); diff --git a/src/writer/tests/semantic_contract.rs b/src/writer/tests/semantic_contract.rs index fb997e1f..47a2768a 100644 --- a/src/writer/tests/semantic_contract.rs +++ b/src/writer/tests/semantic_contract.rs @@ -25,7 +25,7 @@ fn comment(body: &str) -> CommentSnapshot { deleted: false, } } -fn processed(o: &context::CanonicalObservation) -> CanonicalObjectState { +pub(super) fn processed(o: &context::CanonicalObservation) -> CanonicalObjectState { CanonicalObjectState { node_id: o.object_node_id.clone(), database_id: Some(o.database_id.clone()), @@ -43,7 +43,7 @@ fn processed(o: &context::CanonicalObservation) -> CanonicalObjectState { root_fields: o.root_fields(), } } -fn observe(f: &Fixture, github: &GitHubClient, current: &CanonicalContext) -> usize { +pub(super) fn observe(f: &Fixture, github: &GitHubClient, current: &CanonicalContext) -> usize { let observations = context::canonical_observations(current); let root = &observations[0]; let basis = f.store.begin_observation(root.work_item_node_id.clone()).unwrap(); @@ -225,8 +225,12 @@ async fn contract_restoration_cycles_survive_polling_and_share_a_real_ingress_re events: vec![invalid], policy: policy() }) - .is_err() + .unwrap_err() + .to_string() + .contains( + "state receipt cannot acknowledge changed metadata or an unproven transition" + ) ); - assert_eq!(f.store.processed_objects("pr".into()).unwrap(), expected); + assert_eq!(f.store.begin_observation("pr".into()).unwrap().objects, expected); http.abort(); } diff --git a/src/writer/tests/status_convergence.rs b/src/writer/tests/status_convergence.rs index c31c313c..35dfb45a 100644 --- a/src/writer/tests/status_convergence.rs +++ b/src/writer/tests/status_convergence.rs @@ -172,6 +172,7 @@ async fn ambiguous_create_blocks_only_that_comments_successor_after_restart() { } f.store.release_runtime_lease(owner).unwrap(); replacement(&f, "completed"); + let f = f.reopen(); f.store.recover_writes().unwrap(); f.drain(github.clone()).await; assert_eq!( diff --git a/src/writer/tests/turn_start.rs b/src/writer/tests/turn_start.rs index 6c901f9d..2f7946a2 100644 --- a/src/writer/tests/turn_start.rs +++ b/src/writer/tests/turn_start.rs @@ -80,115 +80,78 @@ impl AgentProvider for DelayedProvider { } #[tokio::test] -#[allow(clippy::too_many_lines)] async fn native_start_authorizes_current_publication_before_start_rpc_response() { - for old_completed in [false, true] { - for reply in [Reply::Success, Reply::LateError] { - let fixture = Fixture::new(true); - if old_completed { - fixture + for reply in [Reply::Success, Reply::LateError] { + let fixture = Fixture::new(true); + fixture.db().execute("UPDATE turns SET started_at='2099-01-01T00:00:00Z'", []).unwrap(); + fixture.db().execute_batch("UPDATE provider_sessions SET lifecycle='running'; INSERT INTO turns(turn_id,session_id,context_revision,trigger_kind,lifecycle) VALUES ('current','session','context','wake','starting');").unwrap(); + // An unobserved starting turn must fence publication, not fall back + // to an older completed turn with a non-null timestamp. + assert!( + resolve_source(&fixture.config, Some("issue-codex"), &fixture.invocation()) + .unwrap_err() + .to_string() + .contains("publication source was invalidated or superseded") + ); + let provider = DelayedProvider::new(reply); + let session = ProviderAgentSession::start( + provider.clone(), + fixture.config.profile("issue-codex").unwrap().clone(), + String::new(), + None, + ) + .await + .unwrap(); + let mut events = session.events(); + let mut witness = session.events(); + let start = crate::group::turn_start::send_and_observe( + &fixture.store, + "current", + "session", + session.as_ref(), + &mut events, + "event references".into(), + ); + let publish_before_response = async { + loop { + let lifecycle: String = fixture .db() - .execute("UPDATE turns SET started_at='2099-01-01T00:00:00Z'", []) - .unwrap(); - } else { - fixture.db().execute("DELETE FROM turns", []).unwrap(); - } - fixture.db().execute_batch("UPDATE provider_sessions SET lifecycle='running'; INSERT INTO turns(turn_id,session_id,context_revision,trigger_kind,lifecycle) VALUES ('current','session','context','wake','starting');").unwrap(); - // An unobserved starting turn must fence publication, not fall back - // to an older completed turn with a non-null timestamp. - assert!( - resolve_source(&fixture.config, Some("issue-codex"), &fixture.invocation()) - .is_err() - ); - let provider = DelayedProvider::new(reply); - let session = ProviderAgentSession::start( - provider.clone(), - fixture.config.profile("issue-codex").unwrap().clone(), - String::new(), - None, - ) - .await - .unwrap(); - let mut events = session.events(); - let mut witness = session.events(); - let start = crate::group::turn_start::send_and_observe( - &fixture.store, - "current", - "session", - session.as_ref(), - &mut events, - "event references".into(), - ); - let publish_before_response = async { - loop { - let lifecycle: String = fixture - .db() - .query_row("SELECT lifecycle FROM turns WHERE turn_id='current'", [], |r| { - r.get(0) - }) - .unwrap(); - if lifecycle == "running" { - break; - } - tokio::task::yield_now().await; - } - let resolved = - resolve_source(&fixture.config, Some("issue-codex"), &fixture.invocation()) - .unwrap() - .unwrap(); - assert_eq!(resolved.turn_id, "current"); - let receipt = fixture.comment(); // same production acceptance path used by the CLI - assert_eq!(receipt.source.unwrap().turn_id, "current"); - fixture.db().execute("INSERT INTO events(event_id,work_item_node_id,origin,reference,lifecycle,observed_at,kind) VALUES ('invalidate','item','human','changed','pending','now','invalidate')", []).unwrap(); - assert!( - resolve_source(&fixture.config, Some("issue-codex"), &fixture.invocation()) - .is_err() - ); - assert!( - crate::store::publication_source::check( - fixture.config.runtime.database(), - &resolved - ) - .is_err() - ); - fixture.db().execute("DELETE FROM events WHERE event_id='invalidate'", []).unwrap(); - // Terminal arrives before the delayed response: the dispatch - // helper must leave it available to its running-turn consumer. - provider - .notifications - .send(ProviderNotification::TurnCompleted { - thread_id: "provider".into(), - turn_id: "native-current".into(), - status: "completed".into(), - error: None, + .query_row("SELECT lifecycle FROM turns WHERE turn_id='current'", [], |r| { + r.get(0) }) .unwrap(); - while !matches!(witness.recv().await.unwrap(), SessionEvent::TurnTerminal { .. }) {} - provider.release.notify_one(); - resolved - }; - let (started, resolved) = tokio::time::timeout(Duration::from_secs(5), async { - tokio::join!(start, publish_before_response) - }) - .await - .unwrap(); - assert_eq!(started.unwrap().as_deref(), Some("native-current")); - assert!(matches!( - events.recv().await.unwrap(), - SessionEvent::TurnTerminal { outcome: TurnOutcome::Completed, .. } - )); - assert!(events.try_recv().is_err()); // no duplicated start from the RPC response - crate::store::publication_source::check(fixture.config.runtime.database(), &resolved) + if lifecycle == "running" { + break; + } + tokio::task::yield_now().await; + } + let receipt = fixture.comment(); + assert_eq!(receipt.source.unwrap().turn_id, "current"); + // Terminal arrives before the delayed response: the dispatch + // helper must leave it available to its running-turn consumer. + provider + .notifications + .send(ProviderNotification::TurnCompleted { + thread_id: "provider".into(), + turn_id: "native-current".into(), + status: "completed".into(), + error: None, + }) .unwrap(); - fixture.db().execute("UPDATE assignments SET generation=2", []).unwrap(); - assert!( - crate::store::publication_source::check( - fixture.config.runtime.database(), - &resolved - ) - .is_err() - ); - } + while !matches!(witness.recv().await.unwrap(), SessionEvent::TurnTerminal { .. }) {} + provider.release.notify_one(); + }; + let (started, ()) = tokio::time::timeout(Duration::from_secs(5), async { + tokio::join!(start, publish_before_response) + }) + .await + .unwrap(); + assert_eq!(started.unwrap().as_deref(), Some("native-current")); + assert!(matches!( + events.recv().await.unwrap(), + SessionEvent::TurnTerminal { outcome: TurnOutcome::Completed, .. } + )); + assert!(matches!(events.try_recv(), Err(broadcast::error::TryRecvError::Empty))); // no duplicated start from the RPC response } } @@ -221,7 +184,12 @@ async fn unobserved_deferred_and_unknown_start_never_authorize_publication() { Reply::Unknown => assert!(matches!(result, Err(SessionError::Unknown(_)))), _ => unreachable!(), } - assert!(resolve_source(&fixture.config, None, &fixture.invocation()).is_err()); - assert!(events.try_recv().is_err()); + assert!( + resolve_source(&fixture.config, None, &Invocation::Agent("turn".into())) + .unwrap_err() + .to_string() + .contains("publication source was invalidated or superseded") + ); + assert!(matches!(events.try_recv(), Err(broadcast::error::TryRecvError::Empty))); } } diff --git a/tests/assignment.rs b/tests/assignment.rs index cf3eeadb..cfdfd0aa 100644 --- a/tests/assignment.rs +++ b/tests/assignment.rs @@ -1,7 +1,7 @@ use std::{ fs, path::{Path, PathBuf}, - process::Command, + process::{Command, Output}, }; fn braid() -> Command { @@ -16,83 +16,24 @@ fn stdout(output: &std::process::Output) -> String { String::from_utf8_lossy(&output.stdout).into_owned() } -fn executable(path: &Path, contents: &str) { - fs::write(path, contents).expect("write executable"); - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt as _; - let mut permissions = fs::metadata(path).expect("metadata").permissions(); - permissions.set_mode(0o755); - fs::set_permissions(path, permissions).expect("chmod executable"); - } -} - -fn initialize(temporary: &Path) -> PathBuf { - let source = temporary.join("source"); - let harness = temporary.join("harness"); - fs::create_dir_all(&source).expect("create source"); - fs::create_dir_all(&harness).expect("create harness"); - fs::write(source.join("README.md"), "demo\n").expect("write source"); - for args in [ - vec!["init", "-q", "-b", "main"], - vec!["add", "README.md"], - vec![ - "-c", - "user.email=braid@example.invalid", - "-c", - "user.name=Braid Test", - "commit", - "-q", - "-m", - "init", - ], - ] { - let output = - Command::new("git").arg("-C").arg(&source).args(args).output().expect("run git"); - assert!(output.status.success(), "{}", stderr(&output)); - } - let pi = temporary.join("fake-pi"); - executable(&pi, "#!/bin/sh\necho 'pi 1.2.3'\n"); - let config = harness.join("config.toml"); - let output = braid() - .args(["init", "--source"]) - .arg(&source) - .args(["--config"]) - .arg(&config) - .args(["--name", "demo", "--adapter", "pi", "--executable"]) - .arg(&pi) - .args([ - "--model", - "example-chat", - "--llm-provider", - "example-llm", - "--llm-credential-kind", - "none", - "--llm-base-url", - "https://llm.example.invalid/v1", - ]) - .output() - .expect("initialize config"); - assert!(output.status.success(), "{}", stderr(&output)); +fn blocked_issue() -> (PathBuf, rusqlite::Connection) { + let temporary = + std::env::temp_dir().join(format!("braid-assignment-reactivate-{}", uuid::Uuid::now_v7())); + fs::create_dir_all(&temporary).expect("create test directory"); + let config = temporary.join("config.toml"); + fs::write(&config, include_str!("../config.example.toml")).expect("write config"); let output = braid() .args(["migrate", "apply", "--config"]) .arg(&config) .output() .expect("apply migrations"); assert!(output.status.success(), "{}", stderr(&output)); - config -} -#[test] -fn assignment_reactivation_queues_a_new_generation_for_a_blocked_issue() { - let temporary = - std::env::temp_dir().join(format!("braid-assignment-reactivate-{}", std::process::id())); - let config = initialize(&temporary); - let database = temporary.join("harness/state/braid.sqlite3"); + let database = temporary.join("state/braid.sqlite3"); let connection = rusqlite::Connection::open(&database).expect("open database"); connection .execute_batch( - "INSERT INTO repositories(node_id,name_with_owner,observed_at) VALUES ('repo-demo','demo','2026-01-01T00:00:00Z'); + "INSERT INTO repositories(node_id,name_with_owner,observed_at) VALUES ('repo-demo','owner/repository','2026-01-01T00:00:00Z'); INSERT INTO work_items(node_id,repository_node_id,kind,number,state,observed_at) VALUES ('issue-1','repo-demo','issue',1,'open','2026-01-01T00:00:00Z'); INSERT INTO assignments(assignment_id,work_item_node_id,generation,lifecycle,assigned_at,retired_at) @@ -100,48 +41,113 @@ fn assignment_reactivation_queues_a_new_generation_for_a_blocked_issue() { ) .expect("seed blocked assignment"); - let output = braid() + (temporary, connection) +} + +fn reactivate(temporary: &Path) -> Output { + braid() .args(["assignment", "reactivate", "1", "--kind", "issue", "--config"]) - .arg(&config) + .arg(temporary.join("config.toml")) .output() - .expect("reactivate blocked assignment"); - assert!(output.status.success(), "stdout:\n{}\nstderr:\n{}", stdout(&output), stderr(&output)); - assert!(stdout(&output).contains("new generation"), "{}", stdout(&output)); + .expect("reactivate blocked assignment") +} - let (kind, detail, lifecycle, trusted): (String, String, String, i64) = connection - .query_row( - "SELECT kind,detail,lifecycle,trusted_mention FROM events WHERE detail='operator_reactivation'", - [], - |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)), - ) - .expect("read reactivation event"); - assert_eq!( - (kind.as_str(), detail.as_str(), lifecycle.as_str(), trusted), - ("mention", "operator_reactivation", "pending", 0) - ); - let batches: i64 = connection - .query_row( - "SELECT COUNT(*) FROM wake_batches wb - JOIN wake_batch_events wbe ON wbe.batch_id=wb.batch_id - JOIN events e ON e.event_id=wbe.event_id - WHERE e.detail='operator_reactivation'", - [], - |row| row.get(0), - ) - .expect("count wake batches"); - assert_eq!(batches, 1); +#[test] +fn assignment_reactivation_queues_one_wake_and_preserves_the_blocked_generation() { + let (temporary, connection) = blocked_issue(); + let mut first_receipt = None; + for _ in 0..2 { + let output = reactivate(&temporary); + assert!( + output.status.success(), + "stdout:\n{}\nstderr:\n{}", + stdout(&output), + stderr(&output) + ); + let events: Vec<_> = connection + .prepare( + "SELECT event_id,kind,lifecycle,trusted_mention FROM events + WHERE work_item_node_id='issue-1' AND detail='operator_reactivation'", + ) + .unwrap() + .query_map([], |row| { + Ok(( + row.get::<_, String>(0)?, + row.get::<_, String>(1)?, + row.get::<_, String>(2)?, + row.get::<_, i64>(3)?, + )) + }) + .unwrap() + .collect::>() + .unwrap(); + let [(event, kind, lifecycle, trusted)] = events.as_slice() else { + panic!("expected exactly one operator reactivation event, got {events:?}"); + }; + if let Some(previous) = &first_receipt { + assert_eq!(event, previous, "retry must reuse the first durable event"); + } else { + first_receipt = Some(event.clone()); + } + assert!(stdout(&output).contains(event), "CLI receipt must identify the durable event"); + assert_eq!((kind.as_str(), lifecycle.as_str(), *trusted), ("mention", "pending", 0)); + let batches: i64 = connection.query_row( + "SELECT COUNT(*) FROM wake_batch_events e JOIN wake_batches b ON b.batch_id=e.batch_id + WHERE e.event_id=?1 AND b.work_item_node_id='issue-1'", + [event], |row| row.get(0), + ).unwrap(); + assert_eq!(batches, 1); + } + let assignment: (i64, String) = connection.query_row( + "SELECT generation,lifecycle FROM assignments WHERE work_item_node_id='issue-1' ORDER BY generation DESC LIMIT 1", + [], + |row| Ok((row.get(0)?, row.get(1)?)), + ).unwrap(); + assert_eq!(assignment, (1, "blocked".into())); + fs::remove_dir_all(temporary).unwrap(); +} - let second = braid() - .args(["assignment", "reactivate", "1", "--kind", "issue", "--config"]) - .arg(&config) - .output() - .expect("reactivate blocked assignment twice"); - assert!(second.status.success(), "{}", stderr(&second)); - let event_count: i64 = connection - .query_row("SELECT COUNT(*) FROM events WHERE detail='operator_reactivation'", [], |row| { - row.get(0) - }) - .expect("count reactivation events"); - let _ = fs::remove_dir_all(&temporary); - assert_eq!(event_count, 1); +#[test] +fn reactivation_refuses_closed_items_unblocked_history_and_a_live_successor() { + let (temporary, connection) = blocked_issue(); + connection.execute( + "INSERT INTO assignments(assignment_id,work_item_node_id,generation,lifecycle,assigned_at) + VALUES ('successor','issue-1',2,'retired','2026-01-02T00:00:00Z')", + [], + ).unwrap(); + let busy = "owner/repository#1 already has a materializing, active, or finalizing assignment"; + for (state, history, successor, reason) in [ + ("closed", "blocked", "retired", "cannot reactivate owner/repository#1 while it is closed"), + ( + "open", + "retired", + "retired", + "owner/repository#1 has no blocked assignment to reactivate", + ), + ("open", "blocked", "materializing", busy), + ("open", "blocked", "active", busy), + ("open", "blocked", "finalizing", busy), + ] { + connection + .execute("UPDATE work_items SET state=?1 WHERE node_id='issue-1'", [state]) + .unwrap(); + connection + .execute( + "UPDATE assignments SET lifecycle=CASE generation WHEN 1 THEN ?1 ELSE ?2 END", + [history, successor], + ) + .unwrap(); + let result = reactivate(&temporary); + assert!(!result.status.success(), "{state}/{history}/{successor}: {}", stdout(&result)); + assert!(stderr(&result).contains(reason), "{}", stderr(&result)); + let durable: (i64, i64) = connection + .query_row( + "SELECT (SELECT COUNT(*) FROM events), (SELECT COUNT(*) FROM wake_batches)", + [], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .unwrap(); + assert_eq!(durable, (0, 0), "{state}/{history}/{successor} must not queue work"); + } + fs::remove_dir_all(temporary).unwrap(); } diff --git a/tests/browser/draft.test.mjs b/tests/browser/draft.test.mjs new file mode 100644 index 00000000..2051d350 --- /dev/null +++ b/tests/browser/draft.test.mjs @@ -0,0 +1,77 @@ +import assert from 'node:assert/strict'; +import { execFileSync, spawn } from 'node:child_process'; +import { once } from 'node:events'; +import { mkdtemp, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { createInterface } from 'node:readline'; +import test from 'node:test'; +import { chromium } from 'playwright-core'; + +test('并发编辑被拒绝后保留本页草稿,重新打开对象可读到已提交正文', async (t) => { + const root = await mkdtemp(path.join(tmpdir(), 'braid-console-draft-')); + const binary = path.resolve(process.env.BRAID_BINARY || 'target/debug/braid'); + const config = path.join(root, 'platform.toml'); + const checkout = path.join(root, 'source'); + let server, exited, browser; + t.after(async () => { + try { + await browser?.close(); + } finally { + server?.kill('SIGKILL'); + await exited; + await rm(root, { recursive: true, force: true }); + } + }); + execFileSync('git', ['init', '-q', '-b', 'main', checkout]); + execFileSync('git', ['-C', checkout, '-c', 'user.name=Braid', '-c', 'user.email=test@example.invalid', + '-c', 'commit.gpgsign=false', 'commit', '-q', '--allow-empty', '-m', 'fixture']); + execFileSync(binary, ['platform', 'init', '--name', 'fixture', '--listen', '127.0.0.1:0', + '--source', checkout, '--config', config]); + + server = spawn(binary, ['console', '--platform-config', config, '--listen', '127.0.0.1:0', + '--database', path.join(root, 'console.sqlite3')], { stdio: ['ignore', 'pipe', 'inherit'] }); + exited = once(server, 'exit'); + const lines = createInterface({ input: server.stdout }); + const [line] = await Promise.race([ + once(lines, 'line', { signal: AbortSignal.timeout(15_000) }), + exited.then(([code]) => { throw new Error(`Console 在报告监听地址前退出,退出码 ${code}`); }), + ]); + const endpoint = line.match(/^Braid Console (http:\/\/127\.0\.0\.1:\d+)$/)?.[1]; + assert.ok(endpoint, line); + browser = await chromium.launch({ executablePath: process.env.CHROME_BIN }); + const context = await browser.newContext(); + context.setDefaultTimeout(10_000); + const first = await context.newPage(); + const second = await context.newPage(); + const url = endpoint + '/#objects'; + await first.goto(url); + await first.getByLabel('标题', { exact: true }).fill('并发编辑'); + await first.getByLabel('正文', { exact: true }).fill('原始正文'); + await first.getByRole('button', { name: '创建', exact: true }).click(); + const item = { name: '#1 并发编辑', exact: true }; + await first.getByRole('button', item).click(); + await second.goto(url); + await second.getByRole('button', item).click(); + const editor = (page) => page.locator('section').filter({ + has: page.getByRole('heading', { name: '编辑与控制', exact: true }), + }).getByLabel('正文', { exact: true }); + const save = { name: '保存标题与正文', exact: true }; + await editor(second).fill('第二位操作者的草稿'); + await editor(first).fill('第一位操作者已保存'); + await first.getByRole('button', save).click(); + await first.getByText('第一位操作者已保存', { exact: true }).filter({ visible: true }).first().waitFor(); + await second.getByRole('button', save).click(); + await second.getByRole('status').getByText(/object #1 revision is \d+, expected \d+/).waitFor(); + await second.getByRole('button', save).and(second.locator(':enabled')).waitFor(); + assert.equal(await editor(second).inputValue(), '第二位操作者的草稿'); + + await second.getByRole('button', { name: '刷新', exact: true }).click(); + const confirm = second.getByRole('alertdialog'); + await confirm.getByRole('button', { name: '取消', exact: true }).click(); + assert.equal(await editor(second).inputValue(), '第二位操作者的草稿'); + await second.getByRole('button', { name: '刷新', exact: true }).click(); + await confirm.getByRole('button', { name: '继续', exact: true }).click(); + await second.getByRole('button', item).click(); + assert.equal(await editor(second).inputValue(), '第一位操作者已保存'); +}); diff --git a/tests/browser/package-lock.json b/tests/browser/package-lock.json new file mode 100644 index 00000000..ce5e61ac --- /dev/null +++ b/tests/browser/package-lock.json @@ -0,0 +1,26 @@ +{ + "name": "braid-console-acceptance", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "braid-console-acceptance", + "devDependencies": { + "playwright-core": "1.65.1" + } + }, + "node_modules/playwright-core": { + "version": "1.65.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.65.1.tgz", + "integrity": "sha512-hqPpz7blSMPxWVdoeE1yiBSzXsKiVOd2k+kjCvmUywD2GPO2Dd9HfcWnq9NN0GHbNZDFgZ9JfBFr+X5/BLo0qw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=20" + } + } + } +} diff --git a/tests/browser/package.json b/tests/browser/package.json new file mode 100644 index 00000000..f6a63271 --- /dev/null +++ b/tests/browser/package.json @@ -0,0 +1,7 @@ +{ + "name": "braid-console-acceptance", + "private": true, + "devDependencies": { + "playwright-core": "1.65.1" + } +} diff --git a/tests/console.rs b/tests/console.rs index e9546bc5..fc7abc7d 100644 --- a/tests/console.rs +++ b/tests/console.rs @@ -13,7 +13,6 @@ use nix::{ sys::signal::{Signal, kill}, unistd::Pid, }; -use prost::Message as _; use reqwest::{StatusCode, blocking::Client}; use serde_json::{Value, json}; @@ -134,44 +133,6 @@ fn serve(platform: &Path, harness: &Path, database: &Path) -> Command { command } -#[derive(prost::Message)] -struct OtlpStatus { - #[prost(int32, tag = "1")] - code: i32, - #[prost(string, tag = "2")] - message: String, -} - -fn assert_observation_unavailable(client: &Client, console: &str) { - for path in [ - "/api/status", - "/api/resources", - "/api/records", - "/api/batches/1", - "/api/receive-errors", - "/api/receive-errors/1", - ] { - let response = client.get(format!("{console}{path}")).send().unwrap(); - assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE, "{path}"); - let body: Value = response.json().unwrap(); - assert!(body["error"].as_str().unwrap().contains("observation database unavailable")); - } - for signal in ["traces", "logs", "metrics"] { - // The default Export*ServiceRequest encodes as an empty protobuf message. - let response = client - .post(format!("{console}/v1/{signal}")) - .header("content-type", "application/x-protobuf") - .body(Vec::new()) - .send() - .unwrap(); - assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE, "{signal}"); - assert_eq!(response.headers()["content-type"], "application/x-protobuf"); - let status = OtlpStatus::decode(response.bytes().unwrap()).unwrap(); - assert_eq!(status.code, 14); - assert!(status.message.contains("observation database unavailable")); - } -} - fn get(client: &Client, console: &str, path: &str) -> Value { client .get(format!("{console}{path}")) @@ -183,6 +144,12 @@ fn get(client: &Client, console: &str, path: &str) -> Value { .unwrap() } +fn assert_conflict(response: reqwest::blocking::Response, reason: &str) { + assert_eq!(response.status(), StatusCode::CONFLICT); + let body: Value = response.json().unwrap(); + assert!(body["error"]["message"].as_str().unwrap().contains(reason), "{body}"); +} + fn runtime_command(client: &Client, console: &str, command: &Value) { let response = client.post(format!("{console}/api/runtime/commands")).json(command).send().unwrap(); @@ -231,7 +198,10 @@ fn console_controls_keep_working_when_the_observation_database_cannot_open() { let capabilities = get(&client, &endpoint, "/api/console"); assert_eq!(capabilities["platform"]["managed"], true); assert_eq!(capabilities["harness"]["configured"], true); - assert_observation_unavailable(&client, &endpoint); + let resources = client.get(format!("{endpoint}/api/resources")).send().unwrap(); + assert_eq!(resources.status(), StatusCode::SERVICE_UNAVAILABLE); + let error: Value = resources.json().unwrap(); + assert!(error["error"].as_str().unwrap().contains("observation database unavailable")); let issue = client .post(format!("{endpoint}/api/control/commands")) @@ -325,7 +295,6 @@ fn object_cli_mints_on_first_write_and_platform_fences_a_delayed_mint() { command.args(["object", "--config"]).arg(&harness).current_dir(root.0.join("source")); command }; - checked(base().env_remove("BRAID_AGENT").args(["show", "1"])); let database = rusqlite::Connection::open(root.0.join("harness/state/braid.sqlite3")).unwrap(); database.execute_batch( @@ -361,6 +330,7 @@ fn object_cli_mints_on_first_write_and_platform_fences_a_delayed_mint() { ) .unwrap(); + checked(base().env("BRAID_AGENT", "1").args(["show", "1"])); let client_id: String = database.query_row("SELECT client_id FROM builtin_upstream", [], |r| r.get(0)).unwrap(); let epoch = || { @@ -397,7 +367,9 @@ fn object_cli_mints_on_first_write_and_platform_fences_a_delayed_mint() { [], |row| Ok((row.get(0)?,row.get(1)?,row.get(2)?,row.get(3)?)), ).unwrap(); - assert_eq!(fence(&execution_id), fence(&execution_id)); + for _ in 0..2 { + assert_eq!(fence(&execution_id), json!({"executionId":execution_id,"clientId":client_id})); + } assert_eq!(epoch(), json!({"active":false,"epoch":granted_epoch})); // Fence after mint: old receipts and a valid old token cannot reopen execution. @@ -406,7 +378,7 @@ fn object_cli_mints_on_first_write_and_platform_fences_a_delayed_mint() { "executionId":execution_id}); let replay = client.post(format!("{endpoint}/api/platform/grants")).json(&prior_mint).send().unwrap(); - assert_eq!(replay.status(), StatusCode::CONFLICT); + assert_conflict(replay, "execution attempt is fenced"); let revision = get(&client, &endpoint, "/api/control/items/1")["item"]["revision"].clone(); let old_write = client .post(format!("{endpoint}/api/control/commands")) @@ -415,7 +387,7 @@ fn object_cli_mints_on_first_write_and_platform_fences_a_delayed_mint() { "command":{"type":"comment","number":1,"body":"Fenced turn"}})) .send() .unwrap(); - assert_eq!(old_write.status(), StatusCode::CONFLICT); + assert_conflict(old_write, "writer grant is stale, revoked"); // Fence before mint: no corresponding publication row needs to exist. let late_execution = uuid::Uuid::now_v7().to_string(); @@ -424,79 +396,19 @@ fn object_cli_mints_on_first_write_and_platform_fences_a_delayed_mint() { "itemNumber":1,"expectedEpoch":granted_epoch,"authorityCursor":cursor(), "executionId":late_execution}); let late = client.post(format!("{endpoint}/api/platform/grants")).json(&mint).send().unwrap(); - assert_eq!(late.status(), StatusCode::CONFLICT); + assert_conflict(late, "execution attempt is fenced"); assert_eq!(epoch(), json!({"active":false,"epoch":granted_epoch})); - let mint_open_execution = |request_id: &str, expected_epoch: i64, run_id: Option<&str>| { - let response: Value = client - .post(format!("{endpoint}/api/platform/grants")) - .json(&json!({ - "requestId":request_id, "clientId":client_id, "actor":"issue-codex", - "itemNumber":1, "expectedEpoch":expected_epoch, "authorityCursor":cursor(), - "executionId":uuid::Uuid::now_v7().to_string(), "runId":run_id - })) - .send() - .unwrap() - .error_for_status() - .unwrap() - .json() - .unwrap(); - assert_eq!(response["lifecycle"], "active", "{response}"); - let epoch = response["epoch"].as_i64().unwrap(); - (epoch, json!({"grantId":response["grantId"],"epoch":epoch,"token":response["token"]})) - }; - let stale_write = |request_id: &str, writer: &Value| { - let revision = get(&client, &endpoint, "/api/control/items/1")["item"]["revision"].clone(); - let response = client - .post(format!("{endpoint}/api/control/commands")) - .json(&json!({"requestId":request_id,"actor":"issue-codex","expectedRevision":revision, - "writer":writer,"command":{"type":"comment","number":1,"body":"stale write"}})) - .send() - .unwrap(); - assert_eq!(response.status(), StatusCode::CONFLICT); - }; - let platform_database = rusqlite::Connection::open( - platform.parent().unwrap().join(settings["database"].as_str().unwrap()), - ) - .unwrap(); - let disable_grant_updates = || { - platform_database - .execute_batch( - "CREATE TRIGGER publication_offline BEFORE UPDATE ON platform_grants - BEGIN SELECT RAISE(ABORT, 'grant update unavailable'); END;", - ) - .unwrap(); - }; - let (before_assignment, old_authority) = - mint_open_execution("before-reassignment", granted_epoch, None); - disable_grant_updates(); - object_command("reassign", json!({"type":"assign","number":1,"actor":"issue-codex"})); - assert_eq!(epoch(), json!({"active":false,"epoch":before_assignment})); - stale_write("stale-after-reassignment", &old_authority); object_command( "configure-root", json!({"type":"configureRunRoot", "number":1, "deliveryRef":"refs/heads/braid/test", "runId":"test-run", "clientId":client_id}), ); - let context_url = format!("{endpoint}/api/platform/context/1"); - assert!(client.get(&context_url).send().unwrap().status().is_success()); - let mut owner = reqwest::Url::parse(&context_url).unwrap(); - owner.query_pairs_mut().append_pair("executionClientId", &client_id); - assert!(!client.get(owner.clone()).send().unwrap().status().is_success()); - owner.query_pairs_mut().append_pair("executionRunId", "test-run"); - let response = client.get(owner).send().unwrap(); - assert!(response.status().is_success(), "{}", response.text().unwrap()); - platform_database.execute_batch("DROP TRIGGER publication_offline").unwrap(); - let (scoped_epoch, scoped_authority) = - mint_open_execution("before-scope-close", before_assignment, Some("test-run")); - disable_grant_updates(); - object_command("close-root", json!({"type":"close","number":1})); - object_command("reopen-root", json!({"type":"reopen","number":1})); - assert_eq!(epoch(), json!({"active":false,"epoch":scoped_epoch})); - stale_write("stale-after-scope-reopen", &scoped_authority); - // The bound configuration remains the same after loss of the Git checkout. let source = root.0.join("source"); + let online = get(&client, &endpoint, "/api/platform/scope/1"); + assert_eq!(online["root"]["number"], 1); + let last_online = cursor(); fs::rename(source.join(".git"), source.join(".git.offline")).unwrap(); drop(active_platform); let _reopened_platform = Console( @@ -519,10 +431,21 @@ fn object_cli_mints_on_first_write_and_platform_fences_a_delayed_mint() { "git-offline-comment", json!({"type":"comment","number":1,"body":"Git-independent"}), ); - assert!(get(&client, &endpoint, "/api/platform/events")["lastSequence"].is_number()); + let events = get(&client, &endpoint, &format!("/api/platform/events?after={last_online}")); + assert!( + events["events"] + .as_array() + .unwrap() + .iter() + .any(|row| row["event"]["visible_body"] == "Git-independent") + ); assert_eq!(get(&client, &endpoint, "/api/platform/scope/1/boundary")["rootOpen"], true); - assert_eq!( - client.get(format!("{endpoint}/api/platform/scope/1")).send().unwrap().status(), - StatusCode::INTERNAL_SERVER_ERROR + let offline = client.get(format!("{endpoint}/api/platform/scope/1")).send().unwrap(); + assert_eq!(offline.status(), StatusCode::INTERNAL_SERVER_ERROR); + let body: Value = offline.json().unwrap(); + assert_eq!(body["error"]["code"], "unavailable"); + assert!( + body["error"]["message"].as_str().unwrap().contains("could not find repository"), + "{body}" ); } diff --git a/tests/durable_publication.rs b/tests/durable_publication.rs index 7f04c143..3127ef2b 100644 --- a/tests/durable_publication.rs +++ b/tests/durable_publication.rs @@ -1,520 +1,5 @@ -// Support shims retain production Result signatures. -#![allow(dead_code, clippy::unnecessary_wraps)] -#[path = "../src/telemetry/github.rs"] -pub mod github_metrics; -mod telemetry { - pub use super::github_metrics as github; -} -use rusqlite::{Connection, OptionalExtension, params}; -use std::{ - fs, - path::{Path, PathBuf}, -}; -use time::{OffsetDateTime, format_description::well_known::Rfc3339}; -#[derive(Debug, thiserror::Error)] -enum StoreError { - #[error("{0}")] - InvalidData(String), - #[error(transparent)] - Sqlite(#[from] rusqlite::Error), -} -#[derive(Clone, Debug)] -struct RuntimeLease { - scope: String, - generation: u64, - owner_id: String, -} -#[derive(Clone, Debug)] -struct PendingGitHubWrite { - intent_id: String, - repository: String, - target_kind: String, - target_database_id: String, - operation: String, - content: String, - remote_database_id: Option, - lifecycle: String, - created_at: String, - attempt: i64, - owner: RuntimeLease, - retry_after: u64, - recovery_until: String, -} -fn now_rfc3339() -> String { - OffsetDateTime::now_utc().format(&Rfc3339).unwrap() -} -fn deadline_rfc3339(seconds: u64) -> Result { - Ok((OffsetDateTime::now_utc() + time::Duration::seconds(i64::try_from(seconds).unwrap())) - .format(&Rfc3339) - .unwrap()) -} -fn open_read_only(path: &Path) -> Result { - Ok(Connection::open(path)?) -} -fn open_read_write(path: &Path) -> Result { - open_read_only(path) -} -fn configure_connection(connection: &Connection) -> Result<(), StoreError> { - Ok(connection.execute_batch("PRAGMA foreign_keys=ON;")?) -} -fn require_current_schema(_: &Path) -> Result<(), StoreError> { - Ok(()) -} -fn sqlite_u64(value: u64, _: &str) -> Result { - i64::try_from(value).map_err(|e| StoreError::InvalidData(e.to_string())) -} -fn sqlite_i64_to_u64(value: i64, _: &str) -> rusqlite::Result { - Ok(u64::try_from(value).unwrap()) -} -// Operational-status/reaction projections are outside this deep-module harness. -mod reaction_feedback { - use super::StoreError; - use rusqlite::Transaction; - - pub(super) fn project(_: &Transaction<'_>) -> Result<(), StoreError> { - Ok(()) - } - - pub(super) fn rocket_clear_requested_at( - _: &Transaction<'_>, - _: &str, - _: &str, - _: &str, - _: &str, - ) -> Result, StoreError> { - Ok(None) - } - - pub(super) fn enqueue_rocket_removal( - _: &Transaction<'_>, - _: &str, - _: &str, - _: &str, - _: &str, - ) -> Result<(), StoreError> { - Ok(()) - } -} -fn settle_operational_status( - _: &Connection, - _: &str, - _: &str, - _: Option<&str>, - _: Option<&str>, - _: &str, -) -> Result<(), StoreError> { - Ok(()) -} -// Handoff scheduling has production actor/HTTP coverage in writer::tests; -// this harness only exercises publication ledger/execution mechanics. -#[derive(Clone, Copy)] -struct SchedulerPolicy { - quiet_seconds: u64, - event_threshold: u32, -} -mod handoff_inputs { - use super::{SchedulerPolicy, StoreError}; - - pub(super) struct NewHandoffInput<'a> { - pub(super) source_repository: &'a str, - pub(super) source_number: i64, - pub(super) target_work_item: &'a str, - pub(super) target_assignment: &'a str, - pub(super) target_generation: i64, - } - - pub(super) fn accept( - _: &rusqlite::Transaction<'_>, - _: NewHandoffInput<'_>, - _: SchedulerPolicy, - ) -> Result { - unreachable!("handoff is tested through the production StoreActor") - } -} -#[path = "../src/store/gh_writes.rs"] -mod gh_writes; -#[path = "../src/store/handoff.rs"] -mod handoff; -mod operational_roles { - pub(super) fn declare( - _: &rusqlite::Transaction<'_>, - _: &str, - _: &str, - _: i64, - body: &str, - ) -> Result { - Ok(body.to_owned()) - } -} -#[path = "../src/store/operational_status.rs"] -mod operational_status; -#[path = "../src/store/publication_source.rs"] -mod publication_source; -#[path = "../src/store/write_execution.rs"] -mod write_execution; -use gh_writes::*; -use write_execution::*; -struct Database(PathBuf); -impl Database { - fn new(migrate: bool) -> Self { - let path = - std::env::temp_dir().join(format!("braid-publication-{}.sqlite", uuid::Uuid::now_v7())); - let connection = Connection::open(&path).unwrap(); - connection.execute_batch(include_str!("../migrations/0001_initial.sql")).unwrap(); - connection.execute_batch(include_str!("../migrations/0002_event_kinds.sql")).unwrap(); - if migrate { - connection - .execute_batch(include_str!("../migrations/0009_durable_publication.sql")) - .unwrap(); - connection - .execute_batch(include_str!("../migrations/0011_collaboration_inputs.sql")) - .unwrap(); - connection - .execute_batch(include_str!("../migrations/0012_implementation_delivery.sql")) - .unwrap(); - connection - .execute_batch(include_str!( - "../migrations/0013_operational_status_convergence.sql" - )) - .unwrap(); - connection - .execute_batch(include_str!("../migrations/0022_operational_status_facts.sql")) - .unwrap(); - } - Self(path) - } - fn connect(&self) -> Connection { - Connection::open(&self.0).unwrap() - } - fn owner(&self) -> RuntimeLease { - self.connect() - .execute( - "INSERT OR REPLACE INTO owner_leases VALUES ('runtime',1,'owner',?1)", - [deadline_rfc3339(3600).unwrap()], - ) - .unwrap(); - RuntimeLease { scope: "runtime".into(), generation: 1, owner_id: "owner".into() } - } -} -impl Drop for Database { - fn drop(&mut self) { - fs::remove_file(&self.0).unwrap(); - } -} -fn intent(operation: &'static str) -> NewGhWriteIntent { - NewGhWriteIntent { - request_key: "stable-key".into(), - operation, - repository: "owner/repository".into(), - target: "owner/repository#1".into(), - profile_id: "profile".into(), - role: "pending_validation".into(), - payload: "raw body".into(), - request_digest: "a".repeat(64), - source: None, - } -} -#[test] -fn offline_acceptance_is_atomic_idempotent_and_publicly_queryable() { - let db = Database::new(true); - let write = intent("comment_create"); - let first = prepare_gh_write(&db.0, &write).unwrap(); - assert!(first.request_id.starts_with("request-")); - assert_ne!(first.request_id, first.intent_id); - assert_eq!(first.request_id, prepare_gh_write(&db.0, &write).unwrap().request_id); - assert_eq!( - gh_write_receipt(&db.0, &first.request_id).unwrap().unwrap().intent_id, - first.intent_id - ); - let mut conflict = write; - conflict.request_digest = "b".repeat(64); - assert!(prepare_gh_write(&db.0, &conflict).is_err()); - let count: i64 = db - .connect() - .query_row("SELECT COUNT(*) FROM github_write_outbox", [], |r| r.get(0)) - .unwrap(); - assert_eq!(count, 1); -} -#[test] -fn preflight_limit_survives_exit_and_reset_deadline_then_restart_recovers_attempt_fence() { - let db = Database::new(true); - let owner = db.owner(); - prepare_gh_write(&db.0, &intent("comment_create")).unwrap(); - let mut first = claim_github_write(&db.0, &owner).unwrap().unwrap(); - first.retry_after = 3600; - finish_github_write(&db.0, &first, "pending", None, None, Some("limit before mutation")) - .unwrap(); - assert!(claim_github_write(&db.0, &owner).unwrap().is_none()); - db.connect() - .execute("UPDATE github_write_outbox SET next_attempt_at='2000-01-01T00:00:00Z'", []) - .unwrap(); - let second = claim_github_write(&db.0, &owner).unwrap().unwrap(); - recover_writes(&db.0).unwrap(); - let third = claim_github_write(&db.0, &owner).unwrap().unwrap(); - assert_eq!(third.lifecycle, "uncertain"); - assert!(finish_github_write(&db.0, &second, "applied", None, None, None).is_err()); - finish_github_write(&db.0, &third, "applied", Some("123"), None, None).unwrap(); - assert!(claim_github_write(&db.0, &owner).unwrap().is_none()); -} -#[test] -fn expired_or_replaced_runtime_cannot_claim_or_settle() { - let db = Database::new(true); - let owner = db.owner(); - prepare_gh_write(&db.0, &intent("comment_create")).unwrap(); - let first = claim_github_write(&db.0, &owner).unwrap().unwrap(); - db.connect().execute("UPDATE owner_leases SET owner_id='new',generation=2", []).unwrap(); - assert!(claim_github_write(&db.0, &owner).is_err()); - assert!(finish_github_write(&db.0, &first, "applied", None, None, None).is_err()); -} -#[test] -fn legacy_cli_pending_uncertain_sending_all_get_one_execution_obligation() { - let db = Database::new(false); - for state in ["pending", "uncertain", "sending"] { - db.connect().execute("INSERT INTO write_intents(intent_id,operation,request_digest,lifecycle,created_at,updated_at,request_key,repository,target,profile_id,role,payload) VALUES (?1,'comment_create',?2,?1,'2026-01-01T00:00:00Z','2026-01-01T00:00:00Z',?1,'owner/repository','owner/repository#1','profile','Issue Agent','body')",params![state,"a".repeat(64)]).unwrap(); - } - db.connect().execute_batch(include_str!("../migrations/0009_durable_publication.sql")).unwrap(); - db.connect() - .execute_batch(include_str!("../migrations/0011_collaboration_inputs.sql")) - .unwrap(); - db.connect() - .execute_batch(include_str!("../migrations/0012_implementation_delivery.sql")) - .unwrap(); - db.connect() - .execute_batch(include_str!("../migrations/0013_operational_status_convergence.sql")) - .unwrap(); - db.connect() - .execute_batch(include_str!("../migrations/0022_operational_status_facts.sql")) - .unwrap(); - let owner = db.owner(); - for _ in 0..3 { - let write = claim_github_write(&db.0, &owner).unwrap().unwrap(); - assert_ne!(write.lifecycle, "sending"); - finish_github_write(&db.0, &write, "applied", None, None, None).unwrap(); - } - assert!(claim_github_write(&db.0, &owner).unwrap().is_none()); -} -#[test] -fn ensure_plan_and_progress_freeze_and_resume_without_replanning() { - let db = Database::new(true); - let write = intent("pr_ensure"); - let receipt = prepare_gh_write(&db.0, &write).unwrap(); - let mut plan = NewImplementationRequest { - root_intent_id: None, - write, - comment_database_id: 7, - comment_node_id: "comment".into(), - issue_node_id: "issue".into(), - issue_number: 1, - issue_title: "title".into(), - base_ref: "main".into(), - head_ref: "head".into(), - pr_profile_id: "profile".into(), - }; - let first = prepare_implementation_request(&db.0, &plan).unwrap(); - plan.base_ref = "changed".into(); - plan.head_ref = "changed".into(); - plan.pr_profile_id = "changed".into(); - let frozen = prepare_implementation_request(&db.0, &plan).unwrap(); - assert_eq!(frozen.base_ref, "main"); - assert_eq!(frozen.head_ref, "head"); - assert_eq!(frozen.pr_profile_id, "profile"); - assert_eq!(first.bootstrap_authored_at, frozen.bootstrap_authored_at); - for stage in ["head_ready", "pull_request_ready", "associated", "activation_pending"] { - record_implementation_progress( - &db.0, - &receipt.intent_id, - &ImplementationProgress { - stage, - bootstrap_commit_sha: None, - pull_request_database_id: Some(88), - pull_request_node_id: Some("pr".into()), - pull_request_number: Some(9), - }, - ) - .unwrap(); - let resumed = implementation_request_receipt(&db.0, &receipt.intent_id).unwrap().unwrap(); - assert_eq!(resumed.stage, stage); - assert_eq!(resumed.pull_request_number, Some(9)); - } - assert!( - record_implementation_progress( - &db.0, - &receipt.intent_id, - &ImplementationProgress { - stage: "planned", - bootstrap_commit_sha: None, - pull_request_database_id: None, - pull_request_node_id: None, - pull_request_number: None - } - ) - .is_err() - ); -} - -mod config { - #[derive(Clone)] - pub struct GitHubConfig { - pub app_id: u64, - pub api_version: String, - pub private_key_file: std::path::PathBuf, - pub projects_v2_enabled: bool, - } -} -#[path = "../src/github.rs"] -mod github; -use github::{GitHubClient, GitHubError}; -struct Config; -fn check_source(_: &Config, _: &GhWriteReceipt) -> Result<(), GitHubError> { - Ok(()) -} -// Source/target authorization is covered by the production writer actor tests. -mod edit { - use super::{Config, GhWriteReceipt, GitHubClient, GitHubError}; - #[allow(clippy::unused_async)] // Match the production authorization boundary. - pub async fn authorize( - _: &Config, - _: &GitHubClient, - _: &GhWriteReceipt, - _: bool, - ) -> Result<(), GitHubError> { - Ok(()) - } -} -mod helpers { - use crate::github::GitHubError; - #[derive(Debug)] - pub struct RemoteWrite { - pub database_id: String, - pub node_id: String, - } - #[derive(Debug)] - pub enum WriteFailure { - GitHub(GitHubError), - Ambiguous(String), - } - impl From for WriteFailure { - fn from(error: GitHubError) -> Self { - Self::GitHub(error) - } - } - pub type WriteResult = Result; -} -#[path = "../src/writer/comment.rs"] -mod comment; - -async fn comment_server( - comments: serde_json::Value, - permission: bool, - target_status: u16, -) -> ( - github::GitHubClient, - std::sync::Arc, - tokio::task::JoinHandle<()>, -) { - use axum::{Json, Router, routing::get}; - use std::sync::{ - Arc, - atomic::{AtomicUsize, Ordering}, - }; - let writes = Arc::new(AtomicUsize::new(0)); - let count = Arc::clone(&writes); - let router = Router::new().route( - "/repos/owner/repository/issues/1/comments", - get(move || { - let comments = comments.clone(); - async move { Json(comments) } - }) - .post(move || { - count.fetch_add(1, Ordering::SeqCst); - async { Json(serde_json::json!({"id":99,"node_id":"comment-99"})) } - }), - ); - let router = router.route("/repos/owner/repository/issues/1", get(move || async move { - use axum::response::IntoResponse as _; - if target_status != 200 { return (axum::http::StatusCode::from_u16(target_status).unwrap(), Json(serde_json::json!({"message":"target unavailable"}))).into_response(); } - Json(serde_json::json!({"id":1,"node_id":"issue","number":1,"title":"Issue","html_url":"https://github.com/owner/repository/issues/1","state":"open","pull_request":null})).into_response() - })); - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - let address = listener.local_addr().unwrap(); - let task = tokio::spawn(async move { - axum::serve(listener, router).await.unwrap(); - }); - let http = octocrab::Octocrab::builder() - .base_uri(format!("http://{address}")) - .unwrap() - .add_retry_config(octocrab::service::middleware::retry::RetryConfig::None) - .build() - .unwrap(); - let identity = github::GitHubIdentity { - app_id: 1, - app_slug: "braid".into(), - installation_id: 1, - repository: "owner/repository".into(), - repository_node_id: "repo".into(), - actor_node_id: "app".into(), - actor_login: "braid[bot]".into(), - token_expires_at: String::new(), - permissions: if permission { - std::collections::BTreeMap::from([("issues".into(), "write".into())]) - } else { - std::collections::BTreeMap::new() - }, - }; - let github = github::GitHubClient::publication_test_client( - http, - identity, - config::GitHubConfig { - app_id: 1, - api_version: "2022-11-28".into(), - private_key_file: PathBuf::new(), - projects_v2_enabled: false, - }, - ); - (github, writes, task) -} -fn remote_comment(id: u64) -> serde_json::Value { - serde_json::json!({"id":id,"node_id":format!("comment-{id}"),"url":"https://api.github.com/repos/owner/repository/issues/comments/1","html_url":"https://github.com/owner/repository/issues/1#issuecomment-1","issue_url":"https://api.github.com/repos/owner/repository/issues/1","body":"raw body","created_at":now_rfc3339(),"updated_at":now_rfc3339(),"user":{"login":"braid[bot]","id":1,"node_id":"app","avatar_url":"https://example.invalid/avatar","url":"https://api.github.com/users/braid","html_url":"https://github.com/apps/braid","type":"Bot","site_admin":false}}) -} -#[tokio::test] -async fn successful_unacknowledged_comment_is_recovered_without_a_second_mutation() { - let db = Database::new(true); - let owner = db.owner(); - let mut receipt = prepare_gh_write(&db.0, &intent("comment_create")).unwrap(); - claim_github_write(&db.0, &owner).unwrap().unwrap(); - recover_writes(&db.0).unwrap(); - let write = claim_github_write(&db.0, &owner).unwrap().unwrap(); - receipt.attempts = 1; - let (github, writes, task) = - comment_server(serde_json::json!([remote_comment(77)]), false, 200).await; - let recovered = - comment::converge_comment(&Config, &github, 1, &receipt, &mut true).await.unwrap(); - assert_eq!(recovered.database_id, "77"); - assert_eq!(writes.load(std::sync::atomic::Ordering::SeqCst), 0); - finish_github_write( - &db.0, - &write, - "applied", - Some(&recovered.database_id), - Some(&recovered.node_id), - None, - ) - .unwrap(); - task.abort(); -} -#[tokio::test] -async fn ambiguous_comment_recovery_never_mutates() { - let db = Database::new(true); - let mut receipt = prepare_gh_write(&db.0, &intent("comment_create")).unwrap(); - receipt.attempts = 1; - let (github, writes, task) = - comment_server(serde_json::json!([remote_comment(77), remote_comment(78)]), false, 200) - .await; - let result = comment::converge_comment(&Config, &github, 1, &receipt, &mut true).await; - assert!(matches!(result, Err(helpers::WriteFailure::Ambiguous(_)))); - assert_eq!(writes.load(std::sync::atomic::Ordering::SeqCst), 0); - task.abort(); -} +//! Real CLI subprocess contracts; store and HTTP contracts live with their owners. +use std::fs; #[test] fn cli_exits_offline_with_queryable_receipt_and_no_remote_credentials() { @@ -524,24 +9,27 @@ fn cli_exits_offline_with_queryable_receipt_and_no_remote_credentials() { let path = dir.join("config.toml"); let example = include_str!("../config.example.toml"); fs::write(&path, example.replace("/absolute/path/to/instance", dir.to_str().unwrap())).unwrap(); - let run = |args: &[&str]| { - let output = Command::new(env!("CARGO_BIN_EXE_braid")) + let command = |args: &[&str]| { + Command::new(env!("CARGO_BIN_EXE_braid")) .args(args) .arg("--config") .arg(&path) .env_remove("BRAID_AGENT") .output() - .unwrap(); + .unwrap() + }; + let success = |output: std::process::Output| { assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr)); output }; - run(&["migrate", "apply"]); - let snapshot: github::BodySnapshot = serde_json::from_value(serde_json::json!({"id":1,"node_id":"item","title":"Title","body":"Closes #2\n\nImplementation request: durable-marker","state":"open","updated_at":"version-1","pull_request":{}})).unwrap(); + success(command(&["migrate", "apply"])); + // Fixed wire-format fixture: the CLI must validate a digest independently + // of its own BodySnapshot serializer. let snapshot_file = dir.join("snapshot.json"); - fs::write(&snapshot_file,serde_json::to_string(&serde_json::json!({"target":"owner/repository#1","digest":snapshot.digest(),"snapshot":snapshot})).unwrap()).unwrap(); + fs::write(&snapshot_file, r#"{"target":"owner/repository#1","digest":"654f4b4e1aab7eab9d8087cec18f7c5d0a5424cfda1a516feb436b277683196a","snapshot":{"id":1,"node_id":"item","title":"Title","body":"Closes #2\n\nImplementation request: durable-marker","state":"open","updated_at":"version-1","pull_request":{}}}"#).unwrap(); let body_file = dir.join("body.md"); fs::write(&body_file, "Implementation scope and verification").unwrap(); - let edited = run(&[ + let edited = success(command(&[ "gh", "pr", "edit", @@ -556,54 +44,41 @@ fn cli_exits_offline_with_queryable_receipt_and_no_remote_credentials() { "--request-id", "offline-body", "--json", - ]); + ])); let edited: serde_json::Value = serde_json::from_slice(&edited.stdout).unwrap(); assert_eq!(edited["state"], "queued"); assert_eq!(edited["operation"], "body_edit"); assert_eq!(edited["role"], "Operator"); - let status = run(&["gh", "status", edited["request_id"].as_str().unwrap(), "--json"]); - assert_eq!( - serde_json::from_slice::(&status.stdout).unwrap()["state"], - "queued" - ); - let output = run(&[ - "gh", - "comment", - "create", - "--operator", - "owner/repository#1", - "--profile", - "issue-codex", - "--request-id", - "offline", - "--body", - "Offline update", - "--json", - ]); + let comment = |body: &str| { + command(&[ + "gh", + "comment", + "create", + "--operator", + "owner/repository#1", + "--profile", + "issue-codex", + "--request-id", + "offline", + "--body", + body, + "--json", + ]) + }; + let output = success(comment("Offline update")); let receipt: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); assert_eq!(receipt["state"], "queued"); assert!(receipt.get("intent_id").is_none()); let id = receipt["request_id"].as_str().unwrap(); - let output = run(&["gh", "status", id, "--json"]); + let output = success(command(&["gh", "status", id, "--json"])); let status: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); assert_eq!(status["request_id"], id); assert_eq!(status["state"], "queued"); - let output = run(&[ - "gh", - "comment", - "create", - "--operator", - "owner/repository#1", - "--profile", - "issue-codex", - "--request-id", - "offline", - "--body", - "Offline update", - "--json", - ]); - let duplicate: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); - assert_eq!(duplicate["request_id"], id); + // A changed body with the same explicit key must conflict across CLI invocations. + let conflict = comment("A different update"); + assert_eq!(conflict.status.code(), Some(1)); + let stderr = String::from_utf8_lossy(&conflict.stderr); + assert!(stderr.contains("already used for a different payload"), "{stderr}"); fs::remove_dir_all(dir).unwrap(); } @@ -625,93 +100,7 @@ fn gh_read_runs_on_existing_runtime_without_nested_runtime_panic() { .output() .unwrap(); let stderr = String::from_utf8_lossy(&output.stderr); - assert!( - !stderr.contains("Cannot start a runtime from within a runtime"), - "nested runtime panic: {stderr}" - ); - assert!(!output.status.success(), "read must fail without GitHub credentials"); - assert!(output.status.code() != Some(101), "cli panicked: {stderr}"); + assert!(stderr.contains("cannot read GitHub App private key"), "wrong failure: {stderr}"); + assert_eq!(output.status.code(), Some(1), "{stderr}"); fs::remove_dir_all(dir).unwrap(); } - -#[test] -fn completed_turn_keeps_obligation_but_invalidation_and_generation_replace_fence_it() { - let db = Database::new(true); - let connection = db.connect(); - connection.execute_batch("INSERT INTO repositories VALUES ('repo','owner/repository',1,'now'); INSERT INTO work_items VALUES ('item','repo','issue',1,'open','context','now'); INSERT INTO profiles VALUES ('profile',1,'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa','pi','issue'); INSERT INTO assignments VALUES ('assignment','item',1,'active','now',NULL); INSERT INTO agent_instances(agent_id,assignment_id,profile_id,profile_revision,role,lifecycle) VALUES ('agent','assignment','profile',1,'issue_agent','idle'); INSERT INTO provider_sessions(session_id,agent_id,provider_kind,provider_session_id,context_revision,instruction_revision,lifecycle,started_at) VALUES ('session','agent','pi','provider','context','instructions','idle','now'); INSERT INTO turns(turn_id,session_id,context_revision,trigger_kind,lifecycle) VALUES ('turn','session','context','wake','completed');").unwrap(); - let source = publication_source::PublicationSource { - agent_id: "agent".into(), - assignment_id: "assignment".into(), - generation: 1, - profile_id: "profile".into(), - role: "issue_agent".into(), - profile_revision: 1, - session_id: "session".into(), - turn_id: "turn".into(), - context_revision: "context".into(), - }; - connection.execute("INSERT INTO worktrees(worktree_id,agent_id,path,repository_node_id,lifecycle,observed_at) VALUES ('tree','agent','/source','repo','active','now')", []).unwrap(); - assert!(publication_source::check(&db.0, &source).is_ok()); - connection.execute("INSERT INTO events(event_id,work_item_node_id,origin,reference,lifecycle,observed_at,kind) VALUES ('invalidate','item','human','changed','pending','now','invalidate')", []).unwrap(); - assert!(publication_source::check(&db.0, &source).is_err()); - connection.execute("DELETE FROM events WHERE event_id='invalidate'", []).unwrap(); - connection.execute("UPDATE provider_sessions SET lifecycle='reset_pending'", []).unwrap(); - assert!(publication_source::check(&db.0, &source).is_err()); - connection.execute("UPDATE provider_sessions SET lifecycle='idle'", []).unwrap(); - connection.execute("UPDATE assignments SET lifecycle='retired'", []).unwrap(); - connection - .execute("INSERT INTO assignments VALUES ('replacement','item',2,'active','now',NULL)", []) - .unwrap(); - assert!(publication_source::check(&db.0, &source).is_err()); -} - -#[tokio::test] -async fn permission_and_target_failures_do_not_mutate_and_preflight_limit_stays_pending() { - for (permission, status) in [(false, 200), (true, 404), (true, 429)] { - let db = Database::new(true); - let owner = db.owner(); - let receipt = prepare_gh_write(&db.0, &intent("comment_create")).unwrap(); - let write = claim_github_write(&db.0, &owner).unwrap().unwrap(); - let (github, writes, task) = - comment_server(serde_json::json!([]), permission, status).await; - let mut mutation = false; - let result = comment::converge_comment(&Config, &github, 1, &receipt, &mut mutation).await; - assert!(result.is_err()); - assert!(!mutation); - assert_eq!(writes.load(std::sync::atomic::Ordering::SeqCst), 0); - let helpers::WriteFailure::GitHub(error) = result.unwrap_err() else { - panic!("expected target/permission error") - }; - let state = if error.is_unavailable() { "pending" } else { "rejected" }; - assert_eq!(state, if status == 429 { "pending" } else { "rejected" }); - finish_github_write(&db.0, &write, state, None, None, Some(&error.to_string())).unwrap(); - assert!(claim_github_write(&db.0, &owner).unwrap().is_none()); - task.abort(); - } -} -#[tokio::test] -async fn accepted_obligation_converges_from_reopened_database_without_cli_execution() { - let db = Database::new(true); - let receipt = prepare_gh_write(&db.0, &intent("comment_create")).unwrap(); - // No connection or execution owner survives acceptance. A new runtime owns delivery. - let owner = db.owner(); - recover_writes(&db.0).unwrap(); - let write = claim_github_write(&db.0, &owner).unwrap().unwrap(); - let (github, writes, task) = comment_server(serde_json::json!([]), true, 200).await; - let remote = - comment::converge_comment(&Config, &github, 1, &receipt, &mut false).await.unwrap(); - finish_github_write( - &db.0, - &write, - "applied", - Some(&remote.database_id), - Some(&remote.node_id), - None, - ) - .unwrap(); - assert_eq!(gh_write_receipt(&db.0, &receipt.request_id).unwrap().unwrap().lifecycle, "applied"); - assert_eq!(writes.load(std::sync::atomic::Ordering::SeqCst), 1); - recover_writes(&db.0).unwrap(); - assert!(claim_github_write(&db.0, &owner).unwrap().is_none()); - task.abort(); -} diff --git a/tests/headless_setup.rs b/tests/headless_setup.rs index 4c8ac8ec..63563eba 100644 --- a/tests/headless_setup.rs +++ b/tests/headless_setup.rs @@ -41,7 +41,7 @@ if [ "$1" = "api" ] && [ "$2" = "user" ]; then fi case "$2" in app-manifests/*/conversions) - if [ -n "$BRAID_TEST_CONVERSIONS" ]; then touch "$BRAID_TEST_CONVERSIONS"; fi + printf '%s\n' "$2" >> "$BRAID_TEST_CONVERSIONS" cat <<'JSON' {"id":123456,"slug":"braid-of-testuser","name":"braid-of-testuser","pem":"-----BEGIN PRIVATE KEY-----\nTEST\n-----END PRIVATE KEY-----\n","webhook_secret":"webhook","html_url":"https://github.com/apps/braid-of-testuser"} JSON @@ -81,6 +81,9 @@ fn setup_command(fake_bin: &Path, home: &Path) -> Command { let path = format!("{}:{}", fake_bin.display(), std::env::var("PATH").unwrap_or_default()); command .env("PATH", path) + .env("TMPDIR", fake_bin) + .env("BRAID_TEST_BROWSER", fake_bin.join("browser-opened")) + .env("BRAID_TEST_CONVERSIONS", fake_bin.join("conversions")) .args(["setup", "testuser/repository", "--adapter", "pi", "--instance", "demo"]) .arg("--user-home") .arg(home); @@ -121,12 +124,9 @@ fn no_browser_setup_can_be_completed_from_callback_url() { let draft_path = home.join("setup-drafts/demo.toml"); let draft = fs::read_to_string(&draft_path).expect("read setup draft"); - assert!(draft.contains("repository = \"testuser/repository\""), "{draft}"); - let state = draft - .lines() - .find_map(|line| line.strip_prefix("state = \"")?.strip_suffix('\"')) - .expect("draft state") - .to_owned(); + let draft: toml::Value = toml::from_str(&draft).expect("decode saved draft"); + assert_eq!(draft["repository"].as_str(), Some("testuser/repository")); + let state = draft["state"].as_str().expect("saved callback state"); let wrong = setup_command(&fake_bin, &home) .args([ @@ -145,11 +145,12 @@ fn no_browser_setup_can_be_completed_from_callback_url() { assert!(!wrong.status.success()); assert!(stderr(&wrong).contains("state does not match"), "{}", stderr(&wrong)); + let conversions = fake_bin.join("conversions"); + assert!(!conversions.exists(), "invalid state must leave the one-use code unconsumed"); let callback = format!("http://127.0.0.1/callback?code=code123&state={state}"); let output = setup_command(&fake_bin, &home) .current_dir(&fake_bin) .env("BRAID_TEST_AVATAR_URL", avatar_url) - .env("BRAID_TEST_BROWSER", temporary.join("browser-opened")) .args([ "--model", "example-chat", @@ -169,22 +170,26 @@ fn no_browser_setup_can_be_completed_from_callback_url() { assert!(!draft_path.exists()); assert!(home.join("instances/demo/braid-of-testuser-logo.png").is_file()); avatar_server.join().expect("avatar server"); - assert!(!temporary.join("browser-opened").exists()); + assert!(!fake_bin.join("browser-opened").exists()); + assert_eq!(fs::read_to_string(conversions).unwrap(), "app-manifests/code123/conversions\n"); assert_eq!( fs::read_to_string(home.join("instances/demo/secrets.toml")).expect("webhook secret"), "webhook_secret = \"webhook\"\n" ); assert!(stdout(&output).contains("braid migrate apply --instance demo")); - let config = home.join("instances/demo/config.toml"); - assert!(config.is_file()); let output = braid() - .args(["config", "check", "--config"]) - .arg(&config) + .env_remove("BRAID_CONFIG") + .env_remove("BRAID_INSTANCE_HOME") + .env("BRAID_USER_HOME", &home) + .args(["config", "check", "--instance", "demo", "--json"]) .output() - .expect("check completed config"); - let _ = fs::remove_dir_all(&temporary); + .expect("resolve the newly registered instance"); assert!(output.status.success(), "{}", stderr(&output)); + let summary: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(summary["instance_key"], "demo"); + assert_eq!(summary["repository"], "testuser/repository"); + let _ = fs::remove_dir_all(&temporary); } #[test] diff --git a/tests/multi_repo.rs b/tests/multi_repo.rs index 47f4542d..01b149ab 100644 --- a/tests/multi_repo.rs +++ b/tests/multi_repo.rs @@ -12,61 +12,34 @@ fn stderr(output: &std::process::Output) -> String { String::from_utf8_lossy(&output.stderr).into_owned() } -fn multi_repo_config(example: &str, temporary: &Path) -> String { - let other_workspace = temporary.join("other-source"); - let primary_workspace = temporary.join("primary-source"); - let config = example - .replacen( - "repository = \"owner/repository\"", - "repository = \"owner/repository\"\nadditional_repositories = [{ name = \"owner/other\" }]", - 1, - ) - .replace( - "adapter_version = \"codex-cli 0.147.0-alpha.6.5\"\nmodel = \"example-model\"", - &format!( - "adapter_version = \"codex-cli 0.147.0-alpha.6.5\"\nrepository = \"owner/repository\"\nworkspace = \"{}\"\nmodel = \"example-model\"", - primary_workspace.display() - ), - ); - config.replacen( - "[profile_selection]", - &format!( - "[[profiles]]\n\ - id = \"issue-other\"\n\ - display_name = \"Other issue agent\"\n\ - tags = [\"issue\"]\n\ - adapter_type = \"codex\"\n\ - adapter_version = \"codex-cli 0.147.0-alpha.6.5\"\n\ - repository = \"owner/other\"\n\ - model = \"example-model\"\n\ - user_instructions = \"Serve the other repository.\"\n\ - workspace = \"{}\"\n\ - github_actor_node_id = \"MDQ6VXNlcjEyMzQ1\"\n\ - status_surfaces = [\"issue\"]\n\ - github_context_soft_ratio = 0.8\n\ - github_context_hard_bytes = 100000\n\ - \n\ - [[profiles]]\n\ - id = \"pr-other\"\n\ - display_name = \"Other implementation agent\"\n\ - tags = [\"pr\", \"implementation\"]\n\ - adapter_type = \"codex\"\n\ - adapter_version = \"codex-cli 0.147.0-alpha.6.5\"\n\ - repository = \"owner/other\"\n\ - model = \"example-model\"\n\ - user_instructions = \"Implement in the other repository.\"\n\ - workspace = \"{}\"\n\ - github_actor_node_id = \"MDQ6VXNlcjEyMzQ1\"\n\ - status_surfaces = [\"pr\"]\n\ - github_context_soft_ratio = 0.8\n\ - github_context_hard_bytes = 100000\n\ - \n\ - [profile_selection]", - other_workspace.display(), - other_workspace.display() - ), - 1, - ) +fn multi_repo_config(example: &str, temporary: &Path) -> toml::Value { + let mut config: toml::Value = toml::from_str(example).expect("parse starter config"); + config["github"].as_table_mut().unwrap().insert( + "additional_repositories".into(), + toml::Value::Array(vec![toml::Value::Table(toml::Table::from_iter([( + "name".into(), + "owner/other".into(), + )]))]), + ); + let profiles = config["profiles"].as_array_mut().unwrap(); + for profile in &mut *profiles { + let profile = profile.as_table_mut().unwrap(); + profile.insert("repository".into(), "owner/repository".into()); + profile + .insert("workspace".into(), temporary.join("primary-source").to_str().unwrap().into()); + } + let other_profiles: Vec<_> = profiles + .iter() + .map(|profile| { + let mut other = profile.clone(); + other["id"] = format!("{}-other", profile["id"].as_str().unwrap()).into(); + other["repository"] = "owner/other".into(); + other["workspace"] = temporary.join("other-source").to_str().unwrap().into(); + other + }) + .collect(); + profiles.extend(other_profiles); + config } #[test] @@ -78,49 +51,133 @@ fn multi_repository_config_requires_repo_scoped_profiles() { std::env::temp_dir().join(format!("braid-multi-repo-config-{}", std::process::id())); fs::create_dir_all(&temporary).expect("create temporary directory"); let path = temporary.join("config.toml"); - fs::write(&path, multi_repo_config(&example, &temporary)).expect("write multi-repo config"); - - let output = braid() - .args(["config", "check", "--config"]) - .arg(&path) - .output() - .expect("check multi-repository config"); - assert!(output.status.success(), "{}", stderr(&output)); + fs::write(&path, toml::to_string(&multi_repo_config(&example, &temporary)).unwrap()) + .expect("write multi-repo config"); let output = braid() .args(["profile", "inspect", "--config"]) .arg(&path) - .args(["--profile", "issue-other"]) + .args(["--profile", "issue-codex-other", "--json"]) .output() .expect("inspect repo-scoped profile"); assert!(output.status.success(), "{}", stderr(&output)); - let missing_binding = fs::read_to_string(&path).expect("read multi config").replacen( - "repository = \"owner/repository\"\nworkspace", - "workspace", - 1, - ); - fs::write(&path, missing_binding).expect("remove one repository binding"); - let output = braid() - .args(["config", "check", "--config"]) - .arg(&path) - .output() - .expect("reject omitted repository binding"); - assert!(!output.status.success()); - assert!(stderr(&output).contains("requires an explicit repository"), "{}", stderr(&output)); + let profile: serde_json::Value = serde_json::from_slice(&output.stdout).expect("profile JSON"); + assert_eq!(profile["id"], "issue-codex-other"); + assert_eq!(profile["repository"], "owner/other"); + assert_eq!(profile["workspace"], temporary.join("other-source").to_str().unwrap()); - let unconfigured = multi_repo_config(&example, &temporary).replacen( - "repository = \"owner/other\"", - "repository = \"owner/unconfigured\"", - 1, - ); - fs::write(&path, unconfigured).expect("write unconfigured repository binding"); - let output = braid() - .args(["config", "check", "--config"]) - .arg(&path) - .output() - .expect("reject unconfigured repository binding"); - let _ = fs::remove_dir_all(&temporary); + for (case, expected) in [ + ("omitted", "requires an explicit repository"), + ("unconfigured", "unconfigured GitHub repository"), + ("workspace", "must share one source checkout"), + ] { + let mut candidate = multi_repo_config(&example, &temporary); + let profile = candidate["profiles"][0].as_table_mut().unwrap(); + match case { + "omitted" => { + profile.remove("repository"); + } + "unconfigured" => { + profile.insert("repository".into(), "owner/unconfigured".into()); + } + _ => { + profile.insert( + "workspace".into(), + temporary.join("different-source").to_str().unwrap().into(), + ); + } + } + fs::write(&path, toml::to_string(&candidate).unwrap()).expect("write invalid config"); + let output = braid().args(["config", "check", "--config"]).arg(&path).output().unwrap(); + assert!(!output.status.success(), "{case}"); + assert!(stderr(&output).contains(expected), "{case}: {}", stderr(&output)); + } + fs::remove_dir_all(&temporary).unwrap(); +} + +#[test] +fn instance_selectors_route_to_the_expected_config_and_doctor_names_cross_instance_conflicts() { + let home = std::env::temp_dir().join(format!("braid-instances-{}", uuid::Uuid::now_v7())); + let mut entries = Vec::new(); + for (key, app_id, schema) in [("first", 100, 3), ("second", 200, 2)] { + let directory = home.join(key); + fs::create_dir_all(&directory).unwrap(); + let mut config: toml::Value = + toml::from_str(include_str!("../config.example.toml")).unwrap(); + config["schema_version"] = schema.into(); + config["instance"]["key"] = key.into(); + config["github"]["app_id"] = app_id.into(); + config["github"]["private_key_file"] = + directory.join("missing.pem").to_str().unwrap().into(); + config["runtimes"][0]["executable"] = "/usr/bin/false".into(); + config["tools"]["gh"] = "/usr/bin/false".into(); + config["tools"]["wrangler"] = "/usr/bin/false".into(); + fs::write(directory.join("config.toml"), toml::to_string(&config).unwrap()).unwrap(); + entries.push(format!( + "[[instances]]\nkey='{key}'\nhome='{key}'\ngithub_app_id={app_id}\nrepository='owner/repository'\n" + )); + } + fs::write( + home.join("registry.toml"), + format!("schema_version=1\ndefault_instance='first'\n{}", entries.join("\n")), + ) + .unwrap(); + let second_dir = home.join("second"); + let first_config = home.join("first/config.toml"); + let command = || { + let mut command = braid(); + command.env_clear().env("PATH", "/usr/bin:/bin").env("BRAID_USER_HOME", &home); + command + }; + for (args, instance, override_home, expected) in [ + (vec![], None, None, "first"), + (vec![], Some("second"), None, "second"), + (vec!["--instance", "second"], Some("first"), None, "second"), + (vec!["--instance", "first"], None, Some(&second_dir), "second"), + ( + vec!["--config", first_config.to_str().unwrap()], + Some("second"), + Some(&second_dir), + "first", + ), + ] { + let mut command = command(); + if let Some(value) = instance { + command.env("BRAID_INSTANCE", value); + } + if let Some(value) = override_home { + command.env("BRAID_INSTANCE_HOME", value); + } + let output = command.args(["config", "check", "--json"]).args(args).output().unwrap(); + assert!(output.status.success(), "{}", stderr(&output)); + let summary: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(summary["instance_key"], expected); + assert_eq!( + summary["database"], + home.join(expected).join("state/braid.sqlite3").to_str().unwrap() + ); + } + let output = command().args(["migrate", "apply", "--instance", "second"]).output().unwrap(); + assert!(output.status.success(), "{}", stderr(&output)); + let output = command().args(["status", "--instance", "second", "--json"]).output().unwrap(); + assert!(output.status.success(), "{}", stderr(&output)); + let status: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(status["config_schema"], 2); + assert_eq!(status["database"]["pending_migrations"], 0); + assert!(status["database"]["schema_version"].as_u64().unwrap() > 0); + let output = command().args(["doctor", "--json"]).output().unwrap(); assert!(!output.status.success()); - assert!(stderr(&output).contains("unconfigured GitHub repository"), "{}", stderr(&output)); + let report: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); + let ports = report["checks"] + .as_array() + .unwrap() + .iter() + .find(|c| c["name"] == "instance ports") + .unwrap(); + assert_eq!(ports["state"], "fail"); + let detail = ports["detail"].as_str().unwrap(); + assert!(detail.contains("8080 on second ingress"), "{detail}"); + assert!(detail.contains("8081 on second health"), "{detail}"); + fs::remove_dir_all(home).unwrap(); } diff --git a/tests/provider_config.rs b/tests/provider_config.rs index 208680bc..e5c611db 100644 --- a/tests/provider_config.rs +++ b/tests/provider_config.rs @@ -17,30 +17,7 @@ fn stderr(output: &std::process::Output) -> String { } #[test] -fn provider_credentials_are_configured_only_through_secret_files() { - let output = braid().args(["setup", "--help"]).output().expect("run setup help"); - assert!(output.status.success(), "{}", stderr(&output)); - let help = stdout(&output); - assert!(help.contains("--adapter "), "{help}"); - assert!(help.contains("--llm-provider "), "{help}"); - assert!(help.contains("--reasoning "), "{help}"); - assert!(help.contains("--llm-credential-kind "), "{help}"); - assert!(help.contains("--llm-credential-file "), "{help}"); - assert!(!help.contains("--api-key-file")); - assert!(!help.contains("--api-key-environment")); - assert!(!help.contains("deepseek-chat")); - - let output = braid().args(["init", "--help"]).output().expect("run init help"); - assert!(output.status.success(), "{}", stderr(&output)); - let help = stdout(&output); - assert!(help.contains("--llm-provider "), "{help}"); - assert!(help.contains("--reasoning "), "{help}"); - assert!(help.contains("--llm-credential-kind "), "{help}"); - assert!(help.contains("--llm-credential-file "), "{help}"); - assert!(!help.contains("--api-key-file")); - assert!(!help.contains("--api-key-environment")); - assert!(!help.contains("deepseek-chat")); - +fn provider_route_inputs_are_validated_at_cli_and_config_boundaries() { let output = braid() .args([ "init", @@ -60,27 +37,25 @@ fn provider_credentials_are_configured_only_through_secret_files() { .output() .expect("run init without provider and credential kind"); assert!(!output.status.success()); - for required in ["--llm-provider ", "--llm-credential-kind "] { - assert!(stderr(&output).contains(required), "{required}: {}", stderr(&output)); + let diagnostic = stderr(&output); + let error = + diagnostic.lines().take_while(|line| !line.starts_with("Usage:")).collect::>(); + for required in [ + "--llm-provider ", + "--llm-credential-kind ", + "--llm-base-url ", + ] { + assert!(error.iter().any(|line| line.trim() == required), "{required}: {diagnostic}"); } let example = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("config.example.toml"); - let output = braid() - .args(["config", "check", "--config"]) - .arg(&example) - .output() - .expect("check file-based example"); - assert!(output.status.success(), "{}", stderr(&output)); - let example_text = fs::read_to_string(&example).expect("read example"); - let coupled = example_text.replacen( - "adapter_version = \"codex-cli 0.147.0-alpha.6.5\"\nmodel = \"example-model\"", - "adapter_version = \"codex-cli 0.147.0-alpha.6.5\"\n\nprovider = \"openai\"\n\nmodel = \"example-model\"", - 1, - ); + let mut coupled: toml::Value = toml::from_str(&example_text).expect("parse example"); + coupled["profiles"][0].as_table_mut().unwrap().insert("provider".into(), "openai".into()); let coupled_path = std::env::temp_dir() .join(format!("braid-coupled-provider-config-{}.toml", std::process::id())); - fs::write(&coupled_path, &coupled).expect("write adapter-coupled config"); + fs::write(&coupled_path, toml::to_string(&coupled).unwrap()) + .expect("write adapter-coupled config"); let output = braid() .args(["config", "check", "--config"]) .arg(&coupled_path) @@ -94,7 +69,8 @@ fn provider_credentials_are_configured_only_through_secret_files() { stderr(&output) ); - let legacy_codex = coupled.replacen("schema_version = 3", "schema_version = 2", 1); + coupled["schema_version"] = 2.into(); + let legacy_codex = toml::to_string(&coupled).unwrap(); let legacy_codex_path = std::env::temp_dir() .join(format!("braid-legacy-codex-provider-config-{}.toml", std::process::id())); fs::write(&legacy_codex_path, legacy_codex).expect("write legacy Codex config"); @@ -111,22 +87,19 @@ fn provider_credentials_are_configured_only_through_secret_files() { fn schema3_rejects_legacy_provider_surfaces() { let example = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("config.example.toml"); let example_text = fs::read_to_string(&example).expect("read example"); - for (name, fragment, expected) in [ - ( - "environment", - "[[llm_providers]]\n\nid = \"example-llm\"\n\napi_key_environment = \"DEEPSEEK_API_KEY\"\n\n[tools]", - "unknown field `api_key_environment`", - ), - ( - "api_key_file", - "[[llm_providers]]\nid = \"example-llm\"\napi_key_file = \"/absolute/path/to/user/secrets/example-llm.toml\"\n\n[tools]", - "uses legacy api_key_file", - ), + for (field, value, expected) in [ + ("api_key_environment", "PROVIDER_KEY", "unknown field `api_key_environment`"), + ("api_key_file", "/absolute/path/to/key.toml", "uses legacy api_key_file"), ] { let path = std::env::temp_dir() - .join(format!("braid-legacy-{name}-config-{}.toml", std::process::id())); - fs::write(&path, example_text.replacen("[tools]", fragment, 1)) - .expect("write legacy config"); + .join(format!("braid-legacy-{field}-config-{}.toml", std::process::id())); + let mut config: toml::Table = toml::from_str(&example_text).unwrap(); + let provider = toml::Table::from_iter([ + ("id".into(), "example-llm".into()), + (field.into(), value.into()), + ]); + config.insert("llm_providers".into(), vec![toml::Value::Table(provider)].into()); + fs::write(&path, toml::to_string(&config).unwrap()).expect("write legacy config"); let output = braid() .args(["config", "check", "--config"]) .arg(&path) @@ -144,29 +117,27 @@ fn schema3_rejects_legacy_provider_surfaces() { /// cases. fn write_pi_config(example: &str, directory: &Path, credential_fragment: &str) -> PathBuf { fs::create_dir_all(directory).expect("create Pi material directory"); - let config = example - .replace("adapter_type = \"codex\"", "adapter_type = \"pi\"") - .replace("version = \"codex-cli 0.147.0-alpha.6.5\"", "version = \"1.0.2\"") - .replace("adapter_version = \"codex-cli 0.147.0-alpha.6.5\"", "adapter_version = \"1.0.2\"") - .replace("model = \"example-model\"", "model = \"example-chat\"") - .replace( - "adapter_version = \"1.0.2\"\nmodel = \"example-chat\"", - "adapter_version = \"1.0.2\"\nprovider = \"example-llm\"\nmodel = \"example-chat\"", - ) - .replacen( - "home = \"/absolute/path/to/instance/provider/codex\"", - &format!("home = \"{}\"", directory.display()), - 1, - ) - .replacen( - "[tools]", - &format!( - "[[llm_providers]]\nid = \"example-llm\"\nbase_url = \"https://llm.example.invalid/v1\"\ncredential = {credential_fragment}\n\n[[llm_providers.models]]\nid = \"example-chat\"\n\n[tools]" - ), - 1, - ); + let mut config: toml::Value = toml::from_str(example).expect("parse starter config"); + for runtime in config["runtimes"].as_array_mut().unwrap() { + runtime["adapter_type"] = "pi".into(); + runtime["version"] = "1.0.2".into(); + runtime["home"] = directory.to_str().unwrap().into(); + } + for profile in config["profiles"].as_array_mut().unwrap() { + profile["adapter_type"] = "pi".into(); + profile["adapter_version"] = "1.0.2".into(); + profile.as_table_mut().unwrap().insert("provider".into(), "example-llm".into()); + profile["model"] = "example-chat".into(); + } + let provider: toml::Value = toml::from_str(&format!( + "id = \"example-llm\"\nbase_url = \"https://llm.example.invalid/v1\"\ncredential = {credential_fragment}\n[[models]]\nid = \"example-chat\"\n" + )).unwrap(); + config + .as_table_mut() + .unwrap() + .insert("llm_providers".into(), toml::Value::Array(vec![provider])); let path = directory.join("config.toml"); - fs::write(&path, config).expect("write Pi config"); + fs::write(&path, toml::to_string(&config).unwrap()).expect("write Pi config"); path } @@ -177,17 +148,6 @@ fn api_key_credential(directory: &Path) -> String { format!("{{ kind = \"api_key\", file = \"{}\" }}", secret.display()) } -fn oauth_credential(directory: &Path) -> String { - fs::create_dir_all(directory).expect("create credential directory"); - let secret = directory.join("oauth.toml"); - fs::write( - &secret, - "access = \"test-access\"\nrefresh = \"test-refresh\"\nexpires = 4102444800000\naccount = \"tester\"\n", - ) - .expect("write oauth credential"); - format!("{{ kind = \"oauth\", file = \"{}\" }}", secret.display()) -} - fn inspect_profile(config: &Path) -> std::process::Output { braid() .args(["profile", "inspect", "--config"]) @@ -215,26 +175,6 @@ fn reject_config_case(example: &str, directory: &Path, mutate: impl Fn(&Path), e assert!(stderr(&output).contains(expected), "{expected}: {}", stderr(&output)); } -#[test] -fn pi_materials_are_derived_from_provider_declarations() { - let example = - fs::read_to_string(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("config.example.toml")) - .expect("read example"); - let temporary = - std::env::temp_dir().join(format!("braid-pi-provider-materials-{}", std::process::id())); - - for (name, credential_fragment) in [ - ("api-key", api_key_credential(&temporary.join("api-key"))), - ("oauth", oauth_credential(&temporary.join("oauth"))), - ("none", "{ kind = \"none\" }".to_owned()), - ] { - let directory = temporary.join(name); - let output = inspect_profile(&write_pi_config(&example, &directory, &credential_fragment)); - assert!(output.status.success(), "{name}: {}", stderr(&output)); - } - let _ = fs::remove_dir_all(&temporary); -} - #[test] fn pi_derivation_rejects_bad_provider_surfaces() { let example = @@ -243,42 +183,33 @@ fn pi_derivation_rejects_bad_provider_surfaces() { let temporary = std::env::temp_dir().join(format!("braid-pi-derivation-rejects-{}", std::process::id())); - for (name, needle, replacement, expected) in [ - ( - "missing-provider", - "\nprovider = \"example-llm\"", - "", - "requires provider for the Pi adapter", - ), - ( - "missing-model", - "\nmodel = \"example-chat\"", - "", - "requires an explicit model for the Pi adapter", - ), - ( - "missing-base-url", - "\nbase_url = \"https://llm.example.invalid/v1\"", - "", - "requires base_url for Pi models.json derivation", - ), - ( - "undeclared-model", - "\nid = \"example-chat\"", - "\nid = \"other-model\"", - "is not declared in llm_providers", - ), + for (name, expected) in [ + ("missing-provider", "requires provider for the Pi adapter"), + ("missing-model", "requires an explicit model for the Pi adapter"), + ("missing-base-url", "requires base_url for Pi models.json derivation"), + ("undeclared-model", "is not declared in llm_providers"), ] { reject_config_case( &example, &temporary.join(name), - |config| { - let mutated = fs::read_to_string(config).expect("read Pi config").replacen( - needle, - replacement, - 1, - ); - fs::write(config, mutated).expect("mutate config"); + |path| { + let mut config: toml::Value = + toml::from_str(&fs::read_to_string(path).unwrap()).unwrap(); + match name { + "missing-provider" => { + config["profiles"][0].as_table_mut().unwrap().remove("provider"); + } + "missing-model" => { + config["profiles"][0].as_table_mut().unwrap().remove("model"); + } + "missing-base-url" => { + config["llm_providers"][0].as_table_mut().unwrap().remove("base_url"); + } + _ => { + config["llm_providers"][0]["models"][0]["id"] = "other-model".into(); + } + } + fs::write(path, toml::to_string(&config).unwrap()).unwrap(); }, expected, ); @@ -322,6 +253,10 @@ fn pi_derivation_rejects_bad_provider_surfaces() { let output = inspect_profile(&config); let _ = fs::remove_dir_all(&temporary); assert!(output.status.success(), "{}", stderr(&output)); + let report = stdout(&output); + for line in ["provider: example-llm", "model: example-chat", "credential: ApiKey"] { + assert!(report.lines().any(|printed| printed == line), "{report}"); + } } #[test] @@ -401,12 +336,14 @@ fn init_generates_an_explicit_keyless_pi_route() { .expect("run keyless Pi init"); assert!(output.status.success(), "{}", stderr(&output)); let generated = fs::read_to_string(&config).expect("read generated config"); - assert!(generated.contains("provider = \"example-llm\""), "{generated}"); - assert!(generated.contains("model = \"example-chat\""), "{generated}"); - assert!(generated.contains("kind = \"none\""), "{generated}"); - assert!(!generated.contains("api_key_file"), "{generated}"); - assert!(!generated.contains("protocol"), "{generated}"); - assert!(!generated.contains("allowances"), "{generated}"); + let parsed: toml::Value = toml::from_str(&generated).expect("init writes valid TOML"); + let profiles = parsed["profiles"].as_array().expect("generated profiles"); + assert!(!profiles.is_empty()); + for profile in profiles { + assert_eq!(profile["provider"].as_str(), Some("example-llm")); + assert_eq!(profile["model"].as_str(), Some("example-chat")); + } + assert_eq!(parsed["llm_providers"][0]["credential"]["kind"].as_str(), Some("none")); fs::write(&config, generated.replace("http://127.0.0.1:4318", "http://127.0.0.1:9")) .expect("make OTLP endpoint unavailable"); fs::create_dir_all(harness.join("state/backups")).expect("create runtime directories"); @@ -432,39 +369,47 @@ fn provider_import_auth_converts_pi_credentials() { std::env::temp_dir().join(format!("braid-provider-import-auth-{}", std::process::id())); let user_home = temporary.join("user-home"); let pi_auth = temporary.join("auth.json"); + let access = "access\0token\n\"\\"; + let refresh = "refresh\u{0008}token"; + let account = "测试\u{0085}account"; + let api_key = "key\0\u{0008}\n\"\\"; fs::create_dir_all(&temporary).expect("create temporary directory"); fs::write( &pi_auth, serde_json::to_string_pretty(&serde_json::json!({ "example-llm": { "type": "oauth", - "access": "access-token", - "refresh": "refresh-token", + "access": access, + "refresh": refresh, "expires": 4_102_444_800_000_u64, - "account": "tester@example.com", + "account": account, "vendor_specific": "dropped-with-warning" }, - "other-provider": {"type": "api_key", "key": "other-key"} + "other-provider": {"type": "api_key", "key": api_key} })) .expect("encode auth.json"), ) .expect("write fake Pi auth.json"); - let output = braid() - .args(["provider", "import-auth", "example-llm", "--from"]) - .arg(&pi_auth) - .args(["--user-home"]) - .arg(&user_home) - .output() - .expect("import OAuth credential"); + let import = |provider| { + let mut command = braid(); + command + .args(["provider", "import-auth", provider, "--from"]) + .arg(&pi_auth) + .arg("--user-home") + .arg(&user_home); + command + }; + let output = import("example-llm").output().expect("import OAuth credential"); assert!(output.status.success(), "stdout:\n{}\nstderr:\n{}", stdout(&output), stderr(&output)); assert!(stderr(&output).contains("dropping provider-specific OAuth field \"vendor_specific\"")); let imported = user_home.join("secrets/example-llm.toml"); let text = fs::read_to_string(&imported).expect("read imported credential"); - assert!(text.contains("access = \"access-token\""), "{text}"); - assert!(text.contains("refresh = \"refresh-token\""), "{text}"); - assert!(text.contains("expires = 4102444800000"), "{text}"); - assert!(text.contains("account = \"tester@example.com\""), "{text}"); + let parsed: toml::Value = toml::from_str(&text).expect("import must write valid TOML"); + assert_eq!(parsed["access"].as_str(), Some(access)); + assert_eq!(parsed["refresh"].as_str(), Some(refresh)); + assert_eq!(parsed["expires"].as_integer(), Some(4_102_444_800_000)); + assert_eq!(parsed["account"].as_str(), Some(account)); #[cfg(unix)] { use std::os::unix::fs::PermissionsExt as _; @@ -474,60 +419,64 @@ fn provider_import_auth_converts_pi_credentials() { let output = braid() .args(["provider", "import-auth", "other-provider", "--from"]) .arg(&pi_auth) - .args(["--user-home"]) - .arg(&user_home) + .env("BRAID_USER_HOME", &user_home) .output() - .expect("import API key credential"); + .expect("import API key into the environment-selected user home"); assert!(output.status.success(), "{}", stderr(&output)); let imported_key = fs::read_to_string(user_home.join("secrets/other-provider.toml")) .expect("read imported api key"); - assert_eq!(imported_key, "provider_api_key = \"other-key\"\n"); + let parsed: toml::Value = toml::from_str(&imported_key).expect("API key is valid TOML"); + assert_eq!(parsed["provider_api_key"].as_str(), Some(api_key)); - let output = braid() - .args(["provider", "import-auth", "missing", "--from"]) - .arg(&pi_auth) - .args(["--user-home"]) - .arg(&user_home) - .output() - .expect("reject missing provider"); + let output = import("missing").output().expect("reject missing provider"); assert!(!output.status.success()); assert!(stderr(&output).contains("has no credential for \"missing\""), "{}", stderr(&output)); - let output = braid() - .args(["provider", "import-auth", "example-llm", "--from"]) - .arg(&pi_auth) - .args(["--user-home"]) - .arg(&user_home) - .output() - .expect("reject overwrite without force"); + fs::write(&pi_auth, r#"{"example-llm":{"type":"api_key","key":"rotated"}}"#) + .expect("rotate the source credential"); + let output = import("example-llm").output().expect("reject overwrite without force"); assert!(!output.status.success()); assert!(stderr(&output).contains("already exists"), "{}", stderr(&output)); + assert_eq!(fs::read_to_string(&imported).unwrap(), text); #[cfg(unix)] { use std::os::unix::fs::PermissionsExt as _; fs::set_permissions(&imported, fs::Permissions::from_mode(0o644)) .expect("simulate an existing unprotected credential"); - let output = braid() - .args(["provider", "import-auth", "example-llm", "--force", "--from"]) - .arg(&pi_auth) - .args(["--user-home"]) - .arg(&user_home) - .output() - .expect("replace an existing credential"); + let output = + import("example-llm").arg("--force").output().expect("replace an existing credential"); assert!(output.status.success(), "{}", stderr(&output)); assert_eq!(fs::metadata(&imported).expect("metadata").permissions().mode() & 0o777, 0o600); + let rotated: toml::Value = toml::from_str(&fs::read_to_string(&imported).unwrap()).unwrap(); + assert_eq!(rotated["provider_api_key"].as_str(), Some("rotated")); } - // BRAID_USER_HOME is honored without an explicit --user-home flag. - let env_home = temporary.join("env-home"); + let _ = fs::remove_dir_all(&temporary); +} + +#[test] +fn provider_import_rejects_ids_that_escape_the_secrets_directory() { + let temporary = + std::env::temp_dir().join(format!("braid-import-path-{}", uuid::Uuid::now_v7())); + let user_home = temporary.join("home"); + fs::create_dir_all(&temporary).unwrap(); + let source = temporary.join("auth.json"); + fs::write(&source, r#"{"../escaped":{"type":"api_key","key":"synthetic-key"}}"#).unwrap(); let output = braid() - .args(["provider", "import-auth", "example-llm", "--from"]) - .arg(&pi_auth) - .env("BRAID_USER_HOME", &env_home) + .args(["provider", "import-auth", "../escaped", "--from"]) + .arg(&source) + .arg("--user-home") + .arg(&user_home) .output() - .expect("import honors BRAID_USER_HOME"); - assert!(output.status.success(), "{}", stderr(&output)); - assert!(env_home.join("secrets/example-llm.toml").is_file()); - let _ = fs::remove_dir_all(&temporary); + .unwrap(); + let escaped = user_home.join("escaped.toml").exists(); + fs::remove_dir_all(&temporary).unwrap(); + assert!(!output.status.success(), "a provider id must not become a path"); + assert!( + stderr(&output).contains("provider id must be a single file name"), + "{}", + stderr(&output) + ); + assert!(!escaped, "credential escaped the secrets directory"); } diff --git a/tests/support/publication_github.rs b/tests/support/publication_github.rs index d8fbc937..b65c25d9 100644 --- a/tests/support/publication_github.rs +++ b/tests/support/publication_github.rs @@ -1,8 +1,7 @@ -// This constructor exists only in the integration-test compilation of github.rs. -// Production client construction and endpoint selection remain unchanged. +// Owner-local tests use a loopback HTTP client while retaining production +// request, permission, rate-limit and recovery behavior. use super::*; impl GitHubClient { - #[allow(dead_code)] pub fn publication_test_client( client: Octocrab, identity: GitHubIdentity, diff --git a/tests/telemetry.rs b/tests/telemetry.rs deleted file mode 100644 index 9930a154..00000000 --- a/tests/telemetry.rs +++ /dev/null @@ -1,334 +0,0 @@ -#![allow(dead_code)] -mod config { - #[derive(Clone, Copy)] - pub enum LogFormat { - Text, - Json, - } - pub struct TelemetryConfig { - pub endpoint: url::Url, - pub service_name: String, - pub export_timeout_seconds: u64, - pub sample_ratio: f64, - pub incident_mode: bool, - pub log_format: LogFormat, - } - impl TelemetryConfig { - pub fn effective_sample_ratio(&self) -> f64 { - self.sample_ratio - } - } -} -#[path = "../src/telemetry.rs"] -mod telemetry; - -use opentelemetry::trace::TraceContextExt as _; -use opentelemetry_proto::tonic::collector::{ - logs::v1::ExportLogsServiceRequest, metrics::v1::ExportMetricsServiceRequest, - trace::v1::ExportTraceServiceRequest, -}; -use prost::Message as _; -use std::{ - io::{Read as _, Write as _}, - process::Command, - sync::{ - Arc, Mutex, - atomic::{AtomicBool, Ordering}, - }, -}; -use tracing_opentelemetry::OpenTelemetrySpanExt as _; - -const SENTINEL: &str = "PRIVATE_PAYLOAD_SENTINEL_"; -const RESPONSE_SENTINEL: &str = "PRIVATE_COLLECTOR_RESPONSE_SENTINEL"; - -#[test] -fn telemetry_child() { - let Ok(endpoint) = std::env::var("BRAID_TEST_OTLP") else { - return; - }; - let config = config::TelemetryConfig { - endpoint: endpoint.parse().unwrap(), - service_name: "braid-test".into(), - export_timeout_seconds: 1, - sample_ratio: std::env::var("BRAID_TEST_RATIO").unwrap().parse().unwrap(), - incident_mode: false, - log_format: if std::env::var("BRAID_TEST_FORMAT").unwrap() == "json" { - config::LogFormat::Json - } else { - config::LogFormat::Text - }, - }; - let payload = format!("{SENTINEL}{}END", "x".repeat(100_000)); - if std::env::var("BRAID_TEST_PROBE").is_ok() { - let result = telemetry::run_probe(&config, &payload).unwrap(); - println!("{}", serde_json::to_string(&result).unwrap()); - return; - } - let guard = telemetry::TelemetryGuard::install(&config, "test").unwrap(); - telemetry::set_runtime_generation(Some("generation-test".into())); - telemetry::register_session(telemetry::SessionIdentity { - work_item_kind: "issue".into(), - work_item_number: 42, - assignment_id: "assignment-test".into(), - assignment_generation: 1, - provider_session_id: "session-test".into(), - provider_kind: "pi".into(), - context_revision: "context-test".into(), - profile_id: "profile-test".into(), - profile_revision: 1, - profile_digest: "digest-test".into(), - }); - telemetry::begin_turn("session-test", "turn-test"); - telemetry::bind_provider_turn("session-test", "native-turn-test"); - for stream in ["request", "stdout", "stderr"] { - assert_eq!( - telemetry::emit_provider_payload( - "pi", - "session-test", - Some("native-turn-test"), - stream, - &payload - ), - config.sample_ratio > 0.5 - ); - } - let root = tracing::info_span!("test.root"); - let sampled = root.context().span().is_recording(); - { - let _entered = root.enter(); - assert_eq!( - telemetry::emit_payload_event(&telemetry::PayloadEvidence { - github_body: &payload, - github_summary: &payload, - credential: &payload, - provider_transcript: &payload, - webhook_payload: &payload, - local_path: &payload, - }), - sampled - ); - telemetry::emit_provider_cleanup("execution-test", payload.as_bytes(), payload.as_bytes()); - // Evidence-target spans must not leak through fmt's inherited context. - let secret = tracing::info_span!(target: "braid::evidence", "evidence.test", credential = payload.as_str()); - let _secret = secret.enter(); - tracing::info!("ordinary diagnostic after evidence"); - } - drop(root); - telemetry::set_runtime_generation(None); - guard.shutdown().unwrap(); -} - -#[test] -fn telemetry_routes_complete_evidence_only_to_otlp() { - for format in ["text", "json"] { - for ratio in ["0", "1"] { - verify(format, ratio, false, false, "trace"); - } - } - verify("json", "1", false, true, "trace"); -} - -// Also run with --features opentelemetry-otlp/internal-logs to exercise its raw -// response_body diagnostic, which is disabled in the production feature set. -#[test] -fn telemetry_isolates_collector_rejection_bodies_from_ordinary_diagnostics() { - for format in ["text", "json"] { - for rust_log in ["debug", "trace", "trace,opentelemetry-otlp=trace,opentelemetry_sdk=trace"] - { - verify(format, "1", true, true, rust_log); - verify(format, "1", true, false, rust_log); - } - } -} - -type Requests = Arc)>>>; - -fn verify(format: &str, ratio: &str, fail: bool, probe: bool, rust_log: &str) { - let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); - listener.set_nonblocking(true).unwrap(); - let endpoint = format!("http://{}", listener.local_addr().unwrap()); - let requests: Requests = Arc::default(); - let done = Arc::new(AtomicBool::new(false)); - let received = Arc::clone(&requests); - let stop = Arc::clone(&done); - let server = std::thread::spawn(move || { - while !stop.load(Ordering::Relaxed) { - let Ok((mut socket, _)) = listener.accept() else { - std::thread::sleep(std::time::Duration::from_millis(5)); - continue; - }; - socket.set_nonblocking(false).unwrap(); - socket.set_read_timeout(Some(std::time::Duration::from_secs(5))).unwrap(); - let mut buffer = Vec::new(); - let header_end = loop { - let mut chunk = [0; 8192]; - let count = socket.read(&mut chunk).unwrap(); - assert!(count > 0); - buffer.extend_from_slice(&chunk[..count]); - if let Some(offset) = buffer.windows(4).position(|window| window == b"\r\n\r\n") { - break offset + 4; - } - }; - let headers = String::from_utf8_lossy(&buffer[..header_end]); - let path = headers.split_whitespace().nth(1).unwrap().to_owned(); - let length: usize = headers - .lines() - .find_map(|line| { - line.to_lowercase() - .strip_prefix("content-length:") - .map(|value| value.trim().parse().unwrap()) - }) - .unwrap(); - while buffer.len() < header_end + length { - let mut chunk = [0; 8192]; - let count = socket.read(&mut chunk).unwrap(); - assert!(count > 0); - buffer.extend_from_slice(&chunk[..count]); - } - received.lock().unwrap().push((path, buffer[header_end..].to_vec())); - // reqwest rejects 4xx/5xx before OTLP can inspect the body. A 300 - // without Location reaches OTLP's non-2xx StatusError diagnostic. - let status = if fail { "300 Multiple Choices" } else { "200 OK" }; - // Rejections can echo credentials or the original evidence payload. - let response = if fail { - format!("{RESPONSE_SENTINEL}: credential={SENTINEL}echoed") - } else { - String::new() - }; - write!(socket, "HTTP/1.1 {status}\r\nContent-Type: application/x-protobuf\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{response}", response.len()).unwrap(); - } - }); - let mut command = Command::new(std::env::current_exe().unwrap()); - command - .args(["--exact", "telemetry_child", "--nocapture"]) - .env("BRAID_TEST_OTLP", &endpoint) - .env("BRAID_TEST_FORMAT", format) - .env("BRAID_TEST_RATIO", ratio) - .env("RUST_LOG", rust_log); - if probe { - command.env("BRAID_TEST_PROBE", "1"); - } - let output = command.output().unwrap(); - done.store(true, Ordering::Relaxed); - server.join().unwrap(); - let stderr = String::from_utf8_lossy(&output.stderr); - assert!(output.status.success(), "{stderr}"); - assert!(!stderr.contains(SENTINEL), "payload leaked to {format} stderr ({rust_log})"); - assert!( - !stderr.contains(RESPONSE_SENTINEL), - "collector response leaked to {format} stderr ({rust_log})" - ); - if !probe { - assert!(stderr.contains("ordinary diagnostic after evidence"), "{stderr}"); - } - if fail { - assert!(!stderr.contains("HttpClient.StatusError"), "{stderr}"); - assert!(!stderr.contains("opentelemetry_sdk"), "{stderr}"); - assert!(stderr.contains("stage=sdk_export outcome=failed"), "{stderr}"); - for signal in ["logs", "traces", "metrics"] { - assert!(stderr.contains(&format!("signal={signal}")), "{stderr}"); - } - if probe { - let stdout = String::from_utf8_lossy(&output.stdout); - let result: serde_json::Value = - stdout.lines().find_map(|line| serde_json::from_str(line).ok()).unwrap(); - let signals = result["signals"].as_array().unwrap(); - assert_eq!(signals.len(), 3); - for signal in signals { - assert_eq!(signal["failed_batches"], 1); - assert!(signal["failed_records"].as_u64().unwrap() > 0); - assert_eq!(signal["successful_batches"], 0); - assert!(signal["queue_dropped_records"].is_null()); - } - } - } - verify_otlp(&requests.lock().unwrap(), ratio, probe); -} - -fn verify_otlp(requests: &[(String, Vec)], ratio: &str, probe: bool) { - let mut log_records = Vec::new(); - let mut span_ids = Vec::new(); - for (path, body) in requests { - match path.as_str() { - "/v1/logs" => { - for resource in - ExportLogsServiceRequest::decode(body.as_slice()).unwrap().resource_logs - { - for scope in resource.scope_logs { - assert!( - !scope.scope.as_ref().unwrap().name.starts_with("opentelemetry"), - "raw SDK/exporter diagnostics recursed into OTLP logs" - ); - log_records.extend(scope.log_records); - } - } - } - "/v1/traces" => { - for resource in - ExportTraceServiceRequest::decode(body.as_slice()).unwrap().resource_spans - { - for scope in resource.scope_spans { - for span in scope.spans { - assert!( - !serde_json::to_string(&span).unwrap().contains(SENTINEL), - "evidence duplicated into spans" - ); - span_ids.push((span.trace_id, span.span_id)); - } - } - } - } - "/v1/metrics" => { - ExportMetricsServiceRequest::decode(body.as_slice()).unwrap(); - } - other => panic!("unexpected signal {other}"), - } - } - let payload = format!("{SENTINEL}{}END", "x".repeat(100_000)); - let mut payload_records = 0; - for record in log_records { - assert!( - !serde_json::to_string(&record).unwrap().contains(RESPONSE_SENTINEL), - "collector response recursed into OTLP logs" - ); - let matches: Vec<_> = record.attributes.iter().filter(|attribute| { - attribute.value.as_ref().is_some_and(|value| matches!(&value.value, Some(opentelemetry_proto::tonic::common::v1::any_value::Value::StringValue(text)) if text.contains(SENTINEL))) - }).collect(); - if matches.is_empty() { - continue; - } - payload_records += 1; - assert_eq!(ratio, "1"); - assert!( - span_ids.contains(&(record.trace_id.clone(), record.span_id.clone())), - "payload missing exported parent" - ); - for attribute in matches { - let text = serde_json::to_value(attribute.value.as_ref().unwrap()).unwrap().to_string(); - assert!(text.contains(&payload), "incomplete {}", attribute.key); - } - if record.attributes.iter().any(|attribute| attribute.key == "provider.stream") - && !record.attributes.iter().any(|attribute| attribute.key == "provider.execution.id") - { - for key in ["braid.provider_session.id", "braid.assignment.id", "braid.turn.id"] { - assert!(record.attributes.iter().any(|attribute| attribute.key == key)); - } - } - } - assert_eq!( - payload_records, - if ratio == "0" { - 0 - } else if probe { - 1 - } else { - 6 - } - ); - if ratio == "0" { - assert!(span_ids.is_empty()); - } - if probe { - assert!(requests.iter().any(|(path, _)| path == "/v1/metrics")); - } -} diff --git a/tests/telemetry_cleanup.rs b/tests/telemetry_cleanup.rs deleted file mode 100644 index 970d7e71..00000000 --- a/tests/telemetry_cleanup.rs +++ /dev/null @@ -1,77 +0,0 @@ -#![allow(dead_code)] -use serde_json::Value; -use std::{path::PathBuf, time::Duration}; -use tokio::{process::Command, time::timeout}; - -struct PiConfig { - native_runtime: Option, - executable: PathBuf, -} -#[derive(Debug, thiserror::Error)] -enum ProviderError { - #[error("{0}")] - Protocol(String), - #[error("{0}")] - Unknown(String), - #[error("{method}")] - Timeout { method: String }, - #[error(transparent)] - Io(#[from] std::io::Error), -} -mod telemetry { - pub fn emit_provider_cleanup(_: &str, _: &[u8], _: &[u8]) {} -} -mod provider_runtime { - include!("../src/provider/pi_runtime.rs"); - - #[tokio::test] - async fn cleanup_receipt_still_requires_every_stop_proof_and_never_errors_with_raw_output() { - let directory = std::env::temp_dir().join(format!("braid-cleanup-{}", std::process::id())); - std::fs::create_dir_all(&directory).unwrap(); - let receipt = serde_json::json!({ - "status": "stopped", "execution_id": "execution-test", "scope": "execution", - "coverage": "registered-process-groups-and-inherited-execution-markers", - "private": "PRIVATE_CLEANUP_SENTINEL" - }); - for case in ["valid", "exit", "status", "execution_id", "scope", "coverage", "malformed"] { - let mut candidate = receipt.clone(); - if !matches!(case, "valid" | "exit" | "malformed") { - candidate[case] = Value::String("wrong".into()); - } - let stdout = if case == "malformed" { - "PRIVATE_CLEANUP_SENTINEL".to_owned() - } else { - candidate.to_string() - }; - let module = directory.join("cleanup.sh"); - std::fs::write( - &module, - format!( - "printf '%s' '{stdout}'\nprintf '%s' 'PRIVATE_CLEANUP_SENTINEL' >&2\nexit {}\n", - u8::from(case == "exit") - ), - ) - .unwrap(); - let execution = Execution { - pi_version: "test".into(), - id: "execution-test".into(), - directory: directory.clone(), - extensions: BTreeSet::new(), - node: "/bin/sh".into(), - module, - owner: PathBuf::new(), - start_id: "test".into(), - }; - let result = execution.cleanup().await; - if case == "valid" { - result.unwrap(); - } else { - let error = result.unwrap_err().to_string(); - assert!(!error.contains("PRIVATE_CLEANUP_SENTINEL"), "{case}: {error}"); - assert!(error.contains("execution-test"), "{error}"); - assert!(error.contains("stage="), "{error}"); - } - } - std::fs::remove_dir_all(directory).unwrap(); - } -}