From 56cbfce8e8f71d42fed3b123badaae47a1b94ef6 Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Fri, 27 Nov 2026 20:19:22 +0800 Subject: [PATCH 01/43] =?UTF-8?q?fix(tests):=20=E4=BB=A5=E7=9C=9F=E5=AE=9E?= =?UTF-8?q?=E5=A5=91=E7=BA=A6=E9=87=8D=E6=95=B4=E5=9B=9E=E5=BD=92=E5=B9=B6?= =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E5=87=AD=E6=8D=AE=E4=B8=8E=E4=B8=8A=E4=B8=8B?= =?UTF-8?q?=E6=96=87=E8=BE=B9=E7=95=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 将 GitHub、发布、遥测与清理测试迁入真实模块,保留独立 wire 和 CLI 保护 - 补齐持久恢复、通知隔离、签名入口、原生进程与 Console 回归 - 修复凭据导入路径和 TOML 编码、HTML 尾文丢失及未确认停止的 Context 替代 - 明确开发回归与真实产品验收边界;候选 Rust 验证待 CI --- .github/workflows/ci.yml | 5 +- README.md | 1 + docs/10-prd/acceptance.md | 43 ++ docs/20-product-tdd/context.md | 4 +- native/pi/tests/managed-process.test.mjs | 133 +++++ native/pi/tests/tool-environment.test.mjs | 14 +- src/cli/provider_cmd.rs | 20 +- src/config.rs | 6 +- src/console/mod.rs | 2 + src/console/tests.rs | 361 +++++++++++ src/context.rs | 44 +- src/context/filter_tests.rs | 35 ++ src/context/reading_tests.rs | 74 +-- src/doctor.rs | 23 +- src/doctor/compatibility.rs | 4 +- src/github.rs | 4 + .../github/budget_tests.rs | 23 +- src/group/continuous_tests.rs | 216 +++++-- src/group/dispatch.rs | 12 +- src/producer/ingress.rs | 4 + src/producer/ingress_tests.rs | 168 ++++++ src/profile_materials.rs | 3 + src/profile_materials/tests.rs | 90 +++ src/provider/pi.rs | 4 + src/provider/pi_context.rs | 4 + src/provider/pi_context_tests.rs | 77 +++ src/provider/pi_runtime.rs | 4 + src/provider/pi_runtime_tests.rs | 65 ++ src/provider/pi_tests.rs | 37 ++ src/provider/session.rs | 4 + src/provider/session_tests.rs | 182 ++++++ src/store/gh_writes.rs | 4 + src/store/gh_writes/tests.rs | 251 ++++++++ src/store/mod.rs | 11 +- src/store/replay_tests.rs | 36 +- src/telemetry.rs | 3 + tests/telemetry.rs => src/telemetry/tests.rs | 82 +-- src/tunnel/tests.rs | 11 +- src/webhook.rs | 4 + src/webhook_tests.rs | 115 ++++ src/writer/tests.rs | 119 +++- src/writer/tests/body_edit.rs | 81 ++- src/writer/tests/continuous_collaboration.rs | 5 +- src/writer/tests/handoff.rs | 50 +- src/writer/tests/publication_contract.rs | 67 +++ src/writer/tests/semantic_contract.rs | 6 +- tests/durable_publication.rs | 562 +----------------- tests/multi_repo.rs | 140 ++--- tests/provider_config.rs | 207 +++---- tests/telemetry_cleanup.rs | 77 --- 50 files changed, 2400 insertions(+), 1097 deletions(-) create mode 100644 native/pi/tests/managed-process.test.mjs create mode 100644 src/console/tests.rs create mode 100644 src/context/filter_tests.rs rename tests/github_budget.rs => src/github/budget_tests.rs (95%) create mode 100644 src/producer/ingress_tests.rs create mode 100644 src/profile_materials/tests.rs create mode 100644 src/provider/pi_context_tests.rs create mode 100644 src/provider/pi_runtime_tests.rs create mode 100644 src/provider/pi_tests.rs create mode 100644 src/provider/session_tests.rs create mode 100644 src/store/gh_writes/tests.rs rename tests/telemetry.rs => src/telemetry/tests.rs (85%) create mode 100644 src/webhook_tests.rs create mode 100644 src/writer/tests/publication_contract.rs delete mode 100644 tests/telemetry_cleanup.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 94212d09..eabf12c2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -28,8 +28,11 @@ jobs: - 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 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 diff --git a/README.md b/README.md index 79639401..c7624f70 100644 --- a/README.md +++ b/README.md @@ -144,3 +144,4 @@ For source development, Braid is a single Rust package that produces a portable 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..1c2d8925 100644 --- a/docs/10-prd/acceptance.md +++ b/docs/10-prd/acceptance.md @@ -29,6 +29,49 @@ 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 回归;独立 OTLP 编码器输入 | 浏览器草稿、并发交互、serve 装配和实际 Harness 控制 | +| 原生执行与材料 | Node 真实进程树;Profile snapshot 和 auth 文件重新读取 | 锁定 Pi 安装、插件组合、真实模型工具调用及跨宿主进程行为 | +| 采样与完整敏感证据 | `telemetry` 中真实 SDK→HTTP→protobuf;每次独立子进程初始化 SDK | 生产 Collector 的权限、保留、查询及完整长旅程关联 | + +默认入口与 `.github/workflows/ci.yml` 一致: + +```shell +cargo fmt --check +agent-build cargo check --locked --all-targets +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 另运行 +`cargo test --locked --bin braid --features opentelemetry-otlp/internal-logs telemetry::tests`, +实际启用 SDK 内部错误诊断,验证 Collector 返回的敏感正文不会进入普通日志。 +这不改变发行 binary 的 feature。标为 ignored 的 `telemetry_child` 只供父测试 +用独立子进程调用,父测试负责检查退出状态与所有输出;不能单独计作通过。 + +负向用例应断言错误阶段、类型或关键诊断,并有能够到达该守卫的合法前置条件。 +恢复用例应先让真实 owner 写入,关闭并重新打开,再从消费者取回结果。新缺陷 +修复保留同一输入下修复前红、修复后绿的证据;缺少这种证据时说明原因。删除或 +迁移测试前,核对原断言在保留测试中的归属;仅重复编译同一模块不算额外证明。 + +全绿支持上述局部合同,不授予产品发布资格。真实 campaign 仍按下列场景记录 +`pass`、`fail` 或 `unavailable`,尤其不得把 Provider terminal、HTTP 请求受理或 +命令 `prepared` 回执当作任务完成、持久采用或停止确认。 + ## Campaign Setup Create a real Issue whose description contains a distinguishable design fact, diff --git a/docs/20-product-tdd/context.md b/docs/20-product-tdd/context.md index 8154ab46..f7240429 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/native/pi/tests/managed-process.test.mjs b/native/pi/tests/managed-process.test.mjs new file mode 100644 index 00000000..a8fd650f --- /dev/null +++ b/native/pi/tests/managed-process.test.mjs @@ -0,0 +1,133 @@ +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 assertNotExecuting(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); + assert.ok(!observed.stdout.trim() || /^[ZX]/.test(observed.stdout.trim()), `PID ${pid} still executes: ${observed.stdout}`); +} + +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.doesNotThrow(() => process.kill(leaf, 0)); + const terminal = await finishManagedProcess(child, { observation: 'test_stop', observed_at: Date.now() }); + assert.equal(terminal.status, 'stopped', JSON.stringify(terminal)); + assertNotExecuting(started.payload_pid); + assertNotExecuting(leaf); + 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.doesNotThrow(() => process.kill(started.payload_pid, 0)); + 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..18e9570d 100644 --- a/native/pi/tests/tool-environment.test.mjs +++ b/native/pi/tests/tool-environment.test.mjs @@ -1,22 +1,14 @@ 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'], + ['original XDG directory selects gh configuration', { XDG_CONFIG_HOME: '/operator/xdg' }, '/operator/xdg/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/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 0c51cf26..97cc84b9 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, } @@ -1483,7 +1483,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(); diff --git a/src/console/mod.rs b/src/console/mod.rs index be301dfc..77a13478 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..50f027f8 --- /dev/null +++ b/src/console/tests.rs @@ -0,0 +1,361 @@ +//! 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, + sync::{Arc, Mutex}, +}; + +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 = + Arc::new(Mutex::new(Storage::open(&self.root.join("observations.sqlite3")).unwrap())); + 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(api::ApiState { 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(); + 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"); + 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() + ); + let filtered = collector.get("/api/records?signal=logs&session=log-session&turn=turn-B").await; + assert_eq!(filtered["records"].as_array().unwrap().len(), 1); + assert_eq!(filtered["records"][0]["data"]["body"]["stringValue"], "retained evidence"); + 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; + for (encoding, body, status, reason) in [ + ("br", vec![0xff], StatusCode::UNSUPPORTED_MEDIA_TYPE, "unsupported Content-Encoding: br"), + ("identity", vec![0xff], StatusCode::BAD_REQUEST, "decode OTLP logs protobuf"), + ("gzip", vec![0xff], StatusCode::BAD_REQUEST, "decode gzip OTLP body"), + ] { + expect_error(collector.export("logs", encoding, &body).await, status, 3, reason).await; + } + let wrong_type = collector + .client + .post(format!("{}/v1/logs", collector.url)) + .header("content-type", "application/json") + .body(log_body()) + .send() + .await + .unwrap(); + expect_error(wrong_type, StatusCode::UNSUPPORTED_MEDIA_TYPE, 3, "Content-Type").await; + assert_eq!(collector.get("/api/resources").await["batches"], 0); + let errors = collector.get("/api/receive-errors").await; + assert_eq!(errors["errors"].as_array().unwrap().len(), 4); + let id = errors["errors"][1]["id"].as_i64().unwrap(); + collector.shutdown().await; + collector.start().await; + assert_eq!(collector.get("/api/receive-errors").await, errors); + let body = collector + .client + .get(format!("{}/api/receive-errors/{id}", collector.url)) + .send() + .await + .unwrap() + .error_for_status() + .unwrap() + .bytes() + .await + .unwrap(); + assert_eq!(body.as_ref(), [0xff]); + 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 a50fbb6f..b5b76fdf 100644 --- a/src/context.rs +++ b/src/context.rs @@ -1231,7 +1231,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() { @@ -1258,6 +1258,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() { @@ -2894,3 +2932,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..d0a42656 --- /dev/null +++ b/src/context/filter_tests.rs @@ -0,0 +1,35 @@ +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", + "visible ", false), + ("\n\n@braid", 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.visible_body.as_deref(), + Some(if expected == EventKind::Noop { " current design" } else { " changed design" }) + ); + assert_eq!(admitted.requires_attention, expected == EventKind::Invalidate); + } +} diff --git a/src/writer/tests.rs b/src/writer/tests.rs index c31c0e60..c81f7ca4 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 { root, config, store } + } pub(crate) fn db(&self) -> Connection { Connection::open(self.config.runtime.database()).unwrap() } @@ -87,13 +97,17 @@ impl Fixture { .execute("UPDATE github_write_outbox SET next_attempt_at='2000-01-01T00:00:00Z'", []) .unwrap(); } + fn lose_comment_acknowledgement(&self) { + self.db().execute_batch("UPDATE github_write_outbox SET lifecycle='sending',remote_database_id=NULL; UPDATE write_intents SET lifecycle='pending',remote_database_id=NULL,remote_node_id=NULL;").unwrap(); + } fn receipt(&self, id: &str) -> GhWriteReceipt { 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); } } @@ -126,6 +140,10 @@ struct Remote { comment_reads: usize, writes: usize, limit: Option, + target_status: Option, + commit_requests: Vec, + ref_requests: Vec, + pr_requests: Vec, } async fn server( remote: Arc>, @@ -143,6 +161,7 @@ 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"}); } @@ -158,15 +177,15 @@ async fn server( .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.create_pr && !state.pr_created {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_created=true; 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}}}}}})) }})); @@ -243,11 +262,18 @@ async fn outbox_delivery_recovery_and_rate_deadline_use_production_executor() { fixture.drain(github.clone()).await; assert_eq!(fixture.receipt(&receipt.request_id).lifecycle, "applied"); 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(); + // Reopen SQLite with a fresh actor; recovery may read a completed remote + // mutation even when the installation has lost write permission. + task.abort(); + let (github, task) = server(remote.clone(), false).await; + fixture.lose_comment_acknowledgement(); + assert!(fixture.receipt(&receipt.request_id).remote_database_id.is_none()); + let fixture = fixture.reopen(); fixture.store.recover_writes().unwrap(); fixture.drain(github).await; - assert_eq!(fixture.receipt(&receipt.request_id).lifecycle, "applied"); + let recovered = fixture.receipt(&receipt.request_id); + assert_eq!(recovered.lifecycle, "applied"); + assert_eq!(recovered.remote_database_id.as_deref(), Some("99")); assert_eq!(remote.lock().unwrap().writes, 1); task.abort(); } @@ -327,25 +353,51 @@ async fn issue_source_ensures_pr_with_frozen_plan_and_one_native_activation() { } #[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); 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(); } } @@ -369,8 +421,26 @@ async fn initial_ensure_bootstrap_pr_association_and_restart_do_not_duplicate_mu fixture.drain(github.clone()).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 + { + 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}" + ); + } fixture.db().execute("UPDATE github_write_outbox SET lifecycle='sending'", []).unwrap(); + let fixture = fixture.reopen(); fixture.store.recover_writes().unwrap(); fixture.drain(github).await; assert_eq!(fixture.receipt(&receipt.request_id).lifecycle, "applied"); @@ -427,6 +497,7 @@ async fn source_role_can_publish_related_cross_surface_without_target_profile_ta } } +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 a41dd4cf..6611a646 100644 --- a/src/writer/tests/body_edit.rs +++ b/src/writer/tests/body_edit.rs @@ -268,12 +268,16 @@ async fn changed_association_closed_target_old_context_generation_session_and_hu "profile" => { assert!( resolve_source(&fixture.config, Some("pr-codex"), &fixture.invocation()) - .is_err() + .unwrap_err() + .to_string() + .contains("publication Profile does not match source assignment") ); } "turn" => assert!( resolve_source(&fixture.config, None, &Invocation::Agent("not-current".into())) - .is_err() + .unwrap_err() + .to_string() + .contains("publication turn does not match current runtime worktree") ), _ => unreachable!(), } @@ -331,31 +335,35 @@ 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()); + assert!( + resolve_source(&fixture.config, None, &Invocation::Operator) + .unwrap_err() + .to_string() + .contains("operator entry is unavailable inside an Agent runtime worktree") + ); let receipt = accept(&fixture, &github).await; fixture.drain(github).await; assert_eq!(fixture.receipt(&receipt.request_id).lifecycle, "applied"); @@ -414,7 +422,12 @@ async fn repeated_snapshot_body_edit_does_not_duplicate_attribution_or_protected assert_eq!(remote.lock().unwrap().snapshot.body.as_deref(), Some(body.as_str())); task.abort(); fixture.db().execute("DELETE FROM turns", []).unwrap(); - assert!(resolve_source(&fixture.config, None, &Invocation::Operator).is_err()); + assert!( + resolve_source(&fixture.config, None, &Invocation::Operator) + .unwrap_err() + .to_string() + .contains("operator entry is unavailable inside an Agent runtime worktree") + ); } #[tokio::test] @@ -593,10 +606,13 @@ async fn executor_rejects_missing_existing_request_source_before_mutation() { payload["body"] = json!("Closes #7\n\nCloses #999"); receipt.payload = serde_json::to_string(&payload).unwrap(); let mut mutation_possible = false; - assert!( + let error = edit::execute(&fixture.config, &fixture.store, &github, &receipt, &mut mutation_possible) .await - .is_err() + .unwrap_err(); + assert!( + matches!(error, helpers::WriteFailure::GitHub(GitHubError::GraphQl(ref message)) if message == "body maintenance must retain recognized existing closing and request sources"), + "wrong failure: {error:?}" ); assert!(!mutation_possible); assert_eq!(remote.lock().unwrap().writes, 0); @@ -640,7 +656,14 @@ async fn context_dependent_protected_blocks_fail_closed_but_title_only_is_allowe fixture.drain(github.clone()).await; assert_eq!(fixture.receipt(&receipt.request_id).lifecycle, "applied"); } else { - assert!(result.is_err(), "{protected}"); + let error = result.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}" + ); assert_eq!(remote.lock().unwrap().writes, 0); } } diff --git a/src/writer/tests/continuous_collaboration.rs b/src/writer/tests/continuous_collaboration.rs index 27243c71..687299f5 100644 --- a/src/writer/tests/continuous_collaboration.rs +++ b/src/writer/tests/continuous_collaboration.rs @@ -147,7 +147,10 @@ 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 diff --git a/src/writer/tests/handoff.rs b/src/writer/tests/handoff.rs index 936d6138..92f1eb3a 100644 --- a/src/writer/tests/handoff.rs +++ b/src/writer/tests/handoff.rs @@ -79,7 +79,12 @@ async fn handoff_is_atomic_idempotent_and_uses_next_batch_without_parallel_turns 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'", @@ -92,7 +97,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); @@ -110,7 +121,7 @@ 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 in ["unrelated", "closed", "closed-target", "limited", "old-source"] { let f = Fixture::new(true); bind_pr(&f); let a = handoff(&f, mode).unwrap(); @@ -121,7 +132,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" { @@ -209,7 +220,9 @@ 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") ); assert!( super::super::handoff( @@ -221,10 +234,17 @@ fn handoff_same_key_cannot_change_target_or_impersonate_issue_agent() { request_id: "operator".into() } ) - .is_err() + .unwrap_err() + .to_string() + .contains("operator entry is unavailable inside an Agent runtime worktree") ); 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()); + assert!( + handoff(&f, "pr-source") + .unwrap_err() + .to_string() + .contains("handoff requires an Issue Agent") + ); } #[tokio::test] @@ -359,7 +379,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(); } @@ -651,7 +676,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() @@ -671,7 +698,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/publication_contract.rs b/src/writer/tests/publication_contract.rs new file mode 100644 index 00000000..4725099d --- /dev/null +++ b/src/writer/tests/publication_contract.rs @@ -0,0 +1,67 @@ +use super::*; + +#[tokio::test] +async fn accepted_obligation_converges_after_actor_restart_without_reacceptance() { + let fixture = Fixture::new(false); + let receipt = fixture.comment(); + let fixture = fixture.reopen(); + fixture.store.recover_writes().unwrap(); + 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); + assert_eq!(result.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"); + assert_eq!(remote.lock().unwrap().writes, 1); + task.abort(); +} + +#[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::default())); + let (github, task) = server(remote.clone(), true).await; + fixture.drain(github.clone()).await; + assert_eq!(fixture.receipt(&receipt.request_id).lifecycle, "applied"); + { + 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); + } + fixture.lose_comment_acknowledgement(); + let fixture = fixture.reopen(); + fixture.store.recover_writes().unwrap(); + 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/semantic_contract.rs b/src/writer/tests/semantic_contract.rs index 911d3ec2..43e025db 100644 --- a/src/writer/tests/semantic_contract.rs +++ b/src/writer/tests/semantic_contract.rs @@ -224,7 +224,11 @@ 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); http.abort(); diff --git a/tests/durable_publication.rs b/tests/durable_publication.rs index 20b9b73f..a31de129 100644 --- a/tests/durable_publication.rs +++ b/tests/durable_publication.rs @@ -1,475 +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. -fn enqueue_rocket_removal( - _: &Connection, - _: &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, -} -fn schedule_event( - _: &rusqlite::Transaction<'_>, - _: &str, - _: &str, - _: SchedulerPolicy, - _: bool, - _: &str, -) -> Result<(String, String), StoreError> { - unreachable!("handoff is tested through the production StoreActor") -} -#[path = "../src/store/gh_writes.rs"] -mod gh_writes; -#[path = "../src/store/handoff.rs"] -mod handoff; -#[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(); - } - 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(); - 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() { @@ -491,9 +21,10 @@ fn cli_exits_offline_with_queryable_receipt_and_no_remote_credentials() { 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(); + // 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(&[ @@ -585,88 +116,7 @@ fn gh_read_runs_on_existing_runtime_without_nested_runtime_panic() { "nested runtime panic: {stderr}" ); assert!(!output.status.success(), "read must fail without GitHub credentials"); + assert!(stderr.contains("cannot read GitHub App private key"), "wrong failure: {stderr}"); assert!(output.status.code() != Some(101), "cli panicked: {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/multi_repo.rs b/tests/multi_repo.rs index 47f4542d..6d90c4c5 100644 --- a/tests/multi_repo.rs +++ b/tests/multi_repo.rs @@ -12,61 +12,28 @@ 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"]["additional_repositories"] = 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 { + profile["repository"] = "owner/repository".into(); + profile["workspace"] = 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,7 +45,8 @@ 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"); + fs::write(&path, toml::to_string(&multi_repo_config(&example, &temporary)).unwrap()) + .expect("write multi-repo config"); let output = braid() .args(["config", "check", "--config"]) @@ -90,37 +58,41 @@ fn multi_repository_config_requires_repo_scoped_profiles() { 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); - assert!(!output.status.success()); - assert!(stderr(&output).contains("unconfigured GitHub repository"), "{}", stderr(&output)); + 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(); } diff --git a/tests/provider_config.rs b/tests/provider_config.rs index 208680bc..cbb3b2d4 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", @@ -73,14 +50,12 @@ fn provider_credentials_are_configured_only_through_secret_files() { 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]["provider"] = "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"); @@ -144,29 +120,24 @@ 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["provider"] = "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["llm_providers"] = 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 } @@ -216,7 +187,7 @@ fn reject_config_case(example: &str, directory: &Path, mutate: impl Fn(&Path), e } #[test] -fn pi_materials_are_derived_from_provider_declarations() { +fn profile_inspect_reports_the_selected_pi_route_and_credential_kind() { let example = fs::read_to_string(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("config.example.toml")) .expect("read example"); @@ -231,6 +202,15 @@ fn pi_materials_are_derived_from_provider_declarations() { let directory = temporary.join(name); let output = inspect_profile(&write_pi_config(&example, &directory, &credential_fragment)); assert!(output.status.success(), "{name}: {}", stderr(&output)); + let report = stdout(&output); + let kind = match name { + "api-key" => "ApiKey", + "oauth" => "OAuth", + _ => "None", + }; + assert!(report.contains(&format!("credential: {kind}")), "{report}"); + assert!(report.contains("provider: example-llm"), "{report}"); + assert!(report.contains("model: example-chat"), "{report}"); } let _ = fs::remove_dir_all(&temporary); } @@ -243,42 +223,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, ); @@ -401,12 +372,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,19 +405,23 @@ 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"), ) @@ -461,10 +438,11 @@ fn provider_import_auth_converts_pi_credentials() { 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 _; @@ -481,7 +459,8 @@ fn provider_import_auth_converts_pi_credentials() { 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"]) @@ -531,3 +510,29 @@ fn provider_import_auth_converts_pi_credentials() { assert!(env_home.join("secrets/example-llm.toml").is_file()); 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", "../escaped", "--from"]) + .arg(&source) + .arg("--user-home") + .arg(&user_home) + .output() + .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/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(); - } -} From d2eb3e797f8b8df9adab6d6aff42406f718357dd Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Fri, 27 Nov 2026 20:21:59 +0800 Subject: [PATCH 02/43] =?UTF-8?q?fix(platform):=20=E5=B0=86=E6=9C=80?= =?UTF-8?q?=E7=BB=88=E5=AF=B9=E8=B1=A1=E7=8A=B6=E6=80=81=E4=B8=8E=E5=91=BD?= =?UTF-8?q?=E4=BB=A4=E5=9B=9E=E6=89=A7=E5=8E=9F=E5=AD=90=E6=8F=90=E4=BA=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 为合并请求持久绑定精确 Git intent,重启仅确认已采用的结果 - 授权仍约束 Git CAS;撤销后不重试尚未执行的副作用 - 发布与合并的最终 SQLite 状态、事件及回执共同提交或回滚 - 增加真实 HTTP、Git、SQLite 的故障与恢复回归 --- src/platform/mod.rs | 2 + src/platform/objects.rs | 137 ++++++--- src/platform/objects/commands.rs | 90 +++++- src/platform/tests.rs | 507 +++++++++++++++++++++++++++++++ 4 files changed, 681 insertions(+), 55 deletions(-) create mode 100644 src/platform/tests.rs diff --git a/src/platform/mod.rs b/src/platform/mod.rs index a94cc9d8..dafd3f05 100644 --- a/src/platform/mod.rs +++ b/src/platform/mod.rs @@ -4,6 +4,8 @@ pub mod config; pub mod grants; pub mod objects; pub mod store; +#[cfg(test)] +mod tests; pub mod writes; pub use api::router; pub use config::PlatformConfig; diff --git a/src/platform/objects.rs b/src/platform/objects.rs index 30c5131f..07436bb0 100644 --- a/src/platform/objects.rs +++ b/src/platform/objects.rs @@ -727,7 +727,7 @@ fn validate_writer(tx: &Connection, writer: Option<&Writer>) -> Result<()> { Ok(()) } -#[derive(Debug, Serialize)] +#[derive(Debug, Clone, Serialize, Deserialize)] pub struct MergeResult { pub number: u64, pub merge_commit: String, @@ -735,6 +735,12 @@ pub struct MergeResult { pub recovered: bool, } +#[derive(Serialize, Deserialize)] +struct PreparedMerge { + merge: MergeResult, + writer_item: Option, +} + impl PlatformObjects { pub fn merge_status(&self, number: u64) -> Result> { self.item(number)?; @@ -777,7 +783,13 @@ impl PlatformObjects { })) } - pub fn merge(&mut self, number: u64, source: &Path, author: &str) -> Result { + fn merge( + &mut self, + number: u64, + source: &Path, + author: &str, + request_id: &str, + ) -> Result { self.bind_source(source)?; nonempty(author, "author")?; let item = self.item(number)?; @@ -804,23 +816,14 @@ impl PlatformObjects { ) .optional()?; if let Some((state, Some(commit))) = &receipt { - if state == "applied" { - return Ok(MergeResult { - number, - merge_commit: commit.clone(), - base_ref, - recovered: true, - }); - } - if state == "prepared" && git.refname_to_id(&base_ref)? == git2::Oid::from_str(commit)? + if state == "applied" + || (state == "prepared" + && git.refname_to_id(&base_ref)? == git2::Oid::from_str(commit)?) { - self.finish_merge(number, commit, author)?; - return Ok(MergeResult { - number, - merge_commit: commit.clone(), - base_ref, - recovered: true, - }); + let result = + MergeResult { number, merge_commit: commit.clone(), base_ref, recovered: true }; + self.finish_merge(&result, author, request_id)?; + return Ok(result); } } ensure!( @@ -843,14 +846,17 @@ impl PlatformObjects { } else { self.prepare_merge(&git, &item, expected_base, expected_head)? }; - self.adopt_merge_ref(&git, &item, &base_ref, merge_commit, expected_base, expected_head)?; - self.finish_merge(number, &merge_commit.to_string(), author)?; - Ok(MergeResult { - number, - merge_commit: merge_commit.to_string(), - base_ref, - recovered: false, - }) + let result = self.prepare_merge_request(&item, &base_ref, merge_commit, request_id)?; + self.adopt_merge_ref( + &git, + &item, + &result.base_ref, + git2::Oid::from_str(&result.merge_commit)?, + expected_base, + expected_head, + )?; + self.finish_merge(&result, author, request_id)?; + Ok(result) } fn adopt_merge_ref( @@ -949,25 +955,52 @@ impl PlatformObjects { &tree, &[&base, &head], )?; - self.record_merge( - item.number, - &expected_base.to_string(), - &expected_head.to_string(), - Some(&commit.to_string()), - "prepared", - None, - )?; - let (stored_base,stored_head,stored_commit,state):(String,String,Option,String)=self.connection.query_row("SELECT expected_base,expected_head,merge_commit,lifecycle FROM local_merges WHERE pr_number=?1",[sql_id(item.number)?],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?)))?; + Ok(commit) + } + + fn prepare_merge_request( + &mut self, + item: &Item, + base_ref: &str, + commit: git2::Oid, + request_id: &str, + ) -> Result { + let tx = write_transaction(&mut self.connection)?; + validate_writer(&tx, self.writer.as_ref())?; + validate_revision(&tx, &self.repository, self.revision_guard)?; + tx.execute("INSERT OR IGNORE INTO local_merges(pr_number,expected_base,expected_head,merge_commit,lifecycle,created_at,updated_at) VALUES(?1,?2,?3,?4,'prepared',?5,?5)", params![sql_id(item.number)?,item.base_commit,item.head_commit,commit.to_string(),now()])?; + let (base,head,commit,state):(String,String,Option,String)=tx.query_row("SELECT expected_base,expected_head,merge_commit,lifecycle FROM local_merges WHERE pr_number=?1",[sql_id(item.number)?],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?)))?; ensure!( - stored_base == expected_base.to_string() && stored_head == expected_head.to_string(), + Some(&base) == item.base_commit.as_ref() && Some(&head) == item.head_commit.as_ref(), "another merge intent already owns a different candidate" ); ensure!( matches!(state.as_str(), "prepared" | "applied"), "canonical merge intent is {state}; inspect its persisted failure" ); - git2::Oid::from_str(&stored_commit.context("canonical merge intent lacks a commit")?) - .map_err(Into::into) + let result = MergeResult { + number: item.number, + merge_commit: commit.context("canonical merge intent lacks a commit")?, + base_ref: base_ref.into(), + recovered: false, + }; + // Bind this request to the canonical intent before Git CAS. A retry may + // confirm only this exact commit, without reauthorizing any Git mutation. + let prepared = PreparedMerge { + merge: result.clone(), + writer_item: self.writer.as_ref().map(|writer| writer.item.clone()), + }; + commands::save_control_receipt( + &tx, + &ControlReceipt { + request_id: request_id.into(), + state: "prepared".into(), + result: Some(serde_json::to_value(prepared)?), + error: None, + }, + )?; + tx.commit()?; + Ok(result) } fn record_merge( @@ -987,10 +1020,12 @@ impl PlatformObjects { Ok(()) } - fn finish_merge(&mut self, number: u64, commit: &str, author: &str) -> Result<()> { + fn finish_merge(&mut self, result: &MergeResult, author: &str, request_id: &str) -> Result<()> { + let number = result.number; + let commit = &result.merge_commit; + // Authorization fences the Git CAS. This transaction confirms its adopted + // result, even if the writer was revoked after that irreversible effect. let tx = write_transaction(&mut self.connection)?; - validate_writer(&tx, self.writer.as_ref())?; - validate_revision(&tx, &self.repository, self.revision_guard)?; let source: String = tx.query_row("SELECT source FROM local_space WHERE singleton=1", [], |row| row.get(0))?; pin_commit(&tx, &git2::Repository::open(source)?, number, "merges", commit)?; @@ -998,13 +1033,21 @@ impl PlatformObjects { if applied == 0 { let complete:bool=tx.query_row("SELECT EXISTS(SELECT 1 FROM local_merges WHERE pr_number=?1 AND merge_commit=?2 AND lifecycle='applied')",params![sql_id(number)?,commit],|r|r.get(0))?; ensure!(complete, "prepared merge intent no longer matches this commit"); - tx.commit()?; - return Ok(()); + } else { + tx.execute("UPDATE local_items SET state='closed' WHERE number=?1", [sql_id(number)?])?; + bump(&tx, number)?; + revoke_item_grants(&tx, number)?; + emit(&tx, number, "lifecycle", Some("merged"), author, None, self.writer.as_ref())?; } - tx.execute("UPDATE local_items SET state='closed' WHERE number=?1", [sql_id(number)?])?; - bump(&tx, number)?; - revoke_item_grants(&tx, number)?; - emit(&tx, number, "lifecycle", Some("merged"), author, None, self.writer.as_ref())?; + commands::save_control_receipt( + &tx, + &ControlReceipt { + request_id: request_id.into(), + state: "applied".into(), + result: Some(serde_json::to_value(result)?), + error: None, + }, + )?; tx.commit()?; Ok(()) } diff --git a/src/platform/objects/commands.rs b/src/platform/objects/commands.rs index 124d01b9..31a10767 100644 --- a/src/platform/objects/commands.rs +++ b/src/platform/objects/commands.rs @@ -209,6 +209,11 @@ impl PlatformObjects { { return self.apply_external_request(request, policy); } + if matches!(receipt.state.as_str(), "prepared" | "blocked") + && matches!(request.command, ObjectCommand::Merge { .. }) + { + return self.recover_merge_request(request, policy, receipt); + } return Ok(receipt); } Ok(None) => {} @@ -422,7 +427,7 @@ impl PlatformObjects { let result = match &request.command { ObjectCommand::ConfigureRunRoot { number, delivery_ref, run_id, client_id } => self.configure_run_root(*number, delivery_ref, run_id, client_id, &request.actor, &policy.source).map(|()| serde_json::json!({"root":number,"deliveryRef":delivery_ref,"runId":run_id,"clientId":client_id})), ObjectCommand::Merge { number } => self - .merge(*number, &policy.source, &request.actor) + .merge(*number, &policy.source, &request.actor, &request.request_id) .and_then(|r| serde_json::to_value(r).map_err(Into::into)), ObjectCommand::Publish { number, candidate } => { let commit = match candidate { @@ -431,7 +436,7 @@ impl PlatformObjects { }; commit .and_then(|commit| { - self.publish(*number, &policy.source, &commit, &request.actor) + self.publish_request(request, policy, *number, &commit) }) .and_then(|r| serde_json::to_value(r).map_err(Into::into)) } @@ -449,19 +454,78 @@ impl PlatformObjects { Err(error) => ControlReceipt { request_id: request.request_id.clone(), state: "blocked".into(), - result: None, + result: self.control_receipt(&request.request_id)?.and_then(|r| r.result), error: Some(error.into()), }, }; - self.save_control_receipt(&receipt)?; + // Merge and Publish commit success with their final database facts. + if receipt.state != "applied" + || matches!(request.command, ObjectCommand::ConfigureRunRoot { .. }) + { + self.save_control_receipt(&receipt)?; + } Ok(receipt) } + fn recover_merge_request( + &mut self, + request: &CommandRequest, + policy: &ControlPolicy, + receipt: ControlReceipt, + ) -> Result { + let Some(value) = receipt.result.as_ref() else { + // Older prepared receipts have no request-bound commit evidence. + return Ok(receipt); + }; + let prepared: super::PreparedMerge = + serde_json::from_value(value.clone()).map_err(CommandFailure::rejected)?; + let git = git2::Repository::open(&policy.source).map_err(CommandFailure::rejected)?; + if git + .refname_to_id(&prepared.merge.base_ref) + .map_err(CommandFailure::rejected)? + .to_string() + != prepared.merge.merge_commit + { + return Ok(receipt); + } + self.writer = request.writer.as_ref().zip(prepared.writer_item).map(|(grant, item)| { + super::Writer { grant: grant.clone(), item, actor: request.actor.clone() } + }); + let result = self.finish_merge(&prepared.merge, &request.actor, &request.request_id); + self.writer = None; + result?; + self.control_receipt(&request.request_id)? + .context("completed merge receipt disappeared") + .map_err(Into::into) + } + + fn publish_request( + &mut self, + request: &CommandRequest, + policy: &ControlPolicy, + number: u64, + commit: &str, + ) -> Result { + self.connection.execute_batch("BEGIN IMMEDIATE")?; + let result = (|| { + let item = self.publish(number, &policy.source, commit, &request.actor)?; + self.save_control_receipt(&ControlReceipt { + request_id: request.request_id.clone(), + state: "applied".into(), + result: Some(serde_json::to_value(&item)?), + error: None, + })?; + self.connection.execute_batch("COMMIT")?; + Ok(item) + })(); + if result.is_err() { + let _ = self.connection.execute_batch("ROLLBACK"); + } + result + } + fn save_control_receipt(&self, receipt: &ControlReceipt) -> Result<(), CommandFailure> { - let response = serde_json::to_string(receipt).map_err(CommandFailure::rejected)?; - let error = receipt.error.as_ref().map(|e| e.message.as_str()); - self.connection.execute("UPDATE control_receipts SET state=?1,response_json=?2,error=?3,updated_at=?4 WHERE scope='objects' AND request_id=?5",params![receipt.state,response,error,now(),receipt.request_id]).map_err(CommandFailure::rejected)?; - Ok(()) + save_control_receipt(&self.connection, receipt) } fn persist_rejection( @@ -506,6 +570,16 @@ impl PlatformObjects { } } +pub(super) fn save_control_receipt( + connection: &rusqlite::Connection, + receipt: &ControlReceipt, +) -> Result<(), CommandFailure> { + let response = serde_json::to_string(receipt).map_err(CommandFailure::rejected)?; + let error = receipt.error.as_ref().map(|e| e.message.as_str()); + connection.execute("UPDATE control_receipts SET state=?1,response_json=?2,error=?3,updated_at=?4 WHERE scope='objects' AND request_id=?5",params![receipt.state,response,error,now(),receipt.request_id]).map_err(CommandFailure::rejected)?; + Ok(()) +} + fn ensure_request_id(id: &str) -> Result<(), CommandFailure> { if id.is_empty() || id.len() > 128 diff --git a/src/platform/tests.rs b/src/platform/tests.rs new file mode 100644 index 00000000..a7d080a8 --- /dev/null +++ b/src/platform/tests.rs @@ -0,0 +1,507 @@ +//! Public object protocol over a real Git repository and reopened platform database. +use super::{PlatformConfig, router}; +use reqwest::StatusCode; +use serde_json::{Value, json}; +use std::path::PathBuf; + +struct Fixture { + root: PathBuf, + config: PlatformConfig, + client: reqwest::Client, + server: Option>, + stop: Option>, +} + +impl Fixture { + async fn new() -> Self { + let root = std::env::temp_dir().join(format!("braid-platform-{}", uuid::Uuid::now_v7())); + std::fs::create_dir_all(&root).unwrap(); + let source = root.join("source"); + let git = git2::Repository::init(&source).unwrap(); + commit(&git, "refs/heads/main", "base\n", &[]); + git.set_head("refs/heads/main").unwrap(); + let mut fixture = Self { + config: PlatformConfig { + schema_version: 1, + repository: "contract-space".into(), + source: source.canonicalize().unwrap(), + default_branch: "main".into(), + database: root.join("platform.sqlite3"), + backups: root.join("backups"), + listen: String::new(), + }, + root, + client: reqwest::Client::builder() + .timeout(std::time::Duration::from_secs(5)) + .build() + .unwrap(), + server: None, + stop: None, + }; + fixture.start().await; + fixture + } + + async fn start(&mut self) { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + self.config.listen = listener.local_addr().unwrap().to_string(); + let app = router(&self.config).unwrap(); + 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 restart(&mut self) { + self.shutdown().await; + self.start().await; + } + + async fn shutdown(&mut self) { + self.stop.take().unwrap().send(()).unwrap(); + self.server.take().unwrap().await.unwrap(); + } + + fn url(&self, path: &str) -> String { + format!("http://{}{path}", self.config.listen) + } + + async fn get(&self, path: &str) -> Value { + self.client + .get(self.url(path)) + .send() + .await + .unwrap() + .error_for_status() + .unwrap() + .json() + .await + .unwrap() + } + + async fn post(&self, path: &str, body: &Value) -> (StatusCode, Value) { + let response = self.client.post(self.url(path)).json(body).send().await.unwrap(); + (response.status(), response.json().await.unwrap()) + } + + async fn apply(&self, id: &str, revision: Option, command: Value) -> Value { + let (status, receipt) = self + .post( + "/api/control/commands", + &json!({ + "requestId": id, "expectedRevision": revision, "command": command, + }), + ) + .await; + assert_eq!(status, StatusCode::OK, "{receipt}"); + assert_eq!(receipt["state"], "applied", "{receipt}"); + receipt + } + + async fn create_issue(&self) { + let receipt = self + .apply( + "create", + None, + json!({"type":"createIssue", "title":"Design", "body":"original"}), + ) + .await; + assert_eq!(receipt["result"]["number"], 1); + assert_eq!(receipt["result"]["revision"], 1); + } +} + +impl Drop for Fixture { + fn drop(&mut self) { + if let Some(server) = &self.server { + server.abort(); + } + let _ = std::fs::remove_dir_all(&self.root); + } +} + +fn commit(git: &git2::Repository, reference: &str, body: &str, parents: &[git2::Oid]) -> git2::Oid { + let blob = git.blob(body.as_bytes()).unwrap(); + let mut tree = git.treebuilder(None).unwrap(); + tree.insert("README.md", blob, 0o100_644).unwrap(); + let tree = git.find_tree(tree.write().unwrap()).unwrap(); + let signature = git2::Signature::now("Contract", "contract@example.invalid").unwrap(); + let parents = parents.iter().map(|id| git.find_commit(*id).unwrap()).collect::>(); + let parents = parents.iter().collect::>(); + git.commit(Some(reference), &signature, &signature, "candidate", &tree, &parents).unwrap() +} + +#[tokio::test] +async fn command_receipts_and_revision_conflicts_survive_restart_without_duplicate_events() { + let mut fixture = Fixture::new().await; + fixture.create_issue().await; + let original = fixture.get("/api/control/receipts/create").await; + let events = fixture.get("/api/platform/events?after=0").await; + fixture.restart().await; + let replay = fixture + .apply("create", None, json!({"type":"createIssue", "title":"Design", "body":"original"})) + .await; + assert_eq!(replay, original); + assert_eq!(fixture.get("/api/control/items").await.as_array().unwrap().len(), 1); + assert_eq!(fixture.get("/api/platform/events?after=0").await, events); + + let (status, error) = fixture.post("/api/control/commands", &json!({ + "requestId":"create", "command":{"type":"createIssue", "title":"Different", "body":""}, + })).await; + assert_eq!(status, StatusCode::CONFLICT); + assert_eq!(error["error"]["code"], "conflict"); + assert!(error["error"]["message"].as_str().unwrap().contains("requestId was already used")); + assert_eq!(fixture.get("/api/control/receipts/create").await, original); + + fixture.apply("edit", Some(1), json!({"type":"edit", "number":1, "body":"accepted"})).await; + let events = fixture.get("/api/platform/events?after=0").await; + let stale = json!({"requestId":"stale", "expectedRevision":1, + "command":{"type":"edit", "number":1, "body":"must not overwrite"}}); + let (status, rejection) = fixture.post("/api/control/commands", &stale).await; + assert_eq!(status, StatusCode::CONFLICT); + assert_eq!(rejection["state"], "rejected"); + assert_eq!(rejection["error"]["code"], "conflict"); + assert_eq!(rejection["error"]["message"], "object #1 revision is 2, expected 1"); + fixture.restart().await; + assert_eq!(fixture.get("/api/control/receipts/stale").await, rejection); + let item = fixture.get("/api/control/items/1").await; + assert_eq!(item["item"]["body"], "accepted"); + assert_eq!(item["item"]["revision"], 2); + assert_eq!(fixture.get("/api/platform/events?after=0").await, events); + fixture.shutdown().await; +} + +#[tokio::test] +async fn revoked_writer_cannot_write_with_the_current_object_revision_after_restart() { + let mut fixture = Fixture::new().await; + fixture.create_issue().await; + fixture.apply("assign", Some(1), json!({"type":"assign", "number":1, "actor":"worker"})).await; + let grant_request = json!({"requestId":"grant", "clientId":"harness", "itemNumber":1, + "actor":"worker", "expectedEpoch":0}); + let (status, grant) = fixture.post("/api/platform/grants", &grant_request).await; + assert_eq!(status, StatusCode::OK, "{grant}"); + assert_eq!(grant["epoch"], 1); + let capability = + json!({"grantId":grant["grantId"], "epoch":grant["epoch"], "token":grant["token"]}); + let write = json!({"requestId":"write", "expectedRevision":2, "actor":"worker", "writer":capability, + "command":{"type":"comment", "number":1, "body":"accepted", "replyTo":null}}); + let (status, accepted) = fixture.post("/api/control/commands", &write).await; + assert_eq!(status, StatusCode::OK, "{accepted}"); + assert_eq!(accepted["state"], "applied"); + let (status, revoked) = fixture.post("/api/platform/grants/revoke", &json!({ + "requestId":"revoke", "clientId":"harness", "itemNumber":1, "actor":"worker", "expectedEpoch":1, + })).await; + assert_eq!(status, StatusCode::OK, "{revoked}"); + assert_eq!(revoked, json!({"epoch":2,"lifecycle":"revoked"})); + let events = fixture.get("/api/platform/events?after=0").await; + fixture.restart().await; + let item = fixture.get("/api/control/items/1").await; + assert_eq!(item["item"]["state"], "open"); + assert_eq!(item["item"]["desired_profile"], "worker"); + assert_eq!(item["item"]["revision"], 3); + let (status, rejected) = fixture.post("/api/control/commands", &json!({ + "requestId":"late", "expectedRevision":3, "actor":"worker", "writer":capability, + "command":{"type":"comment", "number":1, "body":"must not be written", "replyTo":null}, + })).await; + assert_eq!(status, StatusCode::CONFLICT); + assert_eq!(rejected["state"], "rejected"); + assert_eq!(rejected["error"]["code"], "rejected"); + assert!( + rejected["error"]["message"].as_str().unwrap().contains("writer grant is stale, revoked") + ); + assert_eq!(fixture.get("/api/control/items/1").await, item); + assert_eq!(fixture.get("/api/platform/events?after=0").await, events); + // A completed old command remains a receipt; replay is not a new late mutation. + let (status, replay) = fixture.post("/api/control/commands", &write).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(replay, accepted); + fixture.shutdown().await; +} + +#[tokio::test] +async fn published_candidate_diff_and_merge_use_the_frozen_commit_after_branch_moves() { + let mut fixture = Fixture::new().await; + fixture.create_issue().await; + let git = git2::Repository::open(&fixture.config.source).unwrap(); + let base = git.refname_to_id("refs/heads/main").unwrap(); + let first = commit(&git, "refs/heads/feature", "first candidate\n", &[base]); + fixture + .apply( + "pr", + None, + json!({"type":"createPR", "title":"Implementation", "body":"", + "head":"feature", "base":"main", "issue":1, "issueRevision":1}), + ) + .await; + let published = commit(&git, "refs/heads/feature", "published candidate\n", &[first]); + fixture + .apply( + "publish", + Some(1), + json!({"type":"publish", "number":2, + "candidate":{"type":"commit", "commit":published.to_string()}}), + ) + .await; + commit(&git, "refs/heads/feature", "later unpublished work\n", &[published]); + git.set_head_detached(base).unwrap(); + fixture.restart().await; + let diff = fixture.get("/api/control/items/2/diff").await; + assert_eq!(diff["number"], 2); + assert_eq!(diff["revision"], 2); + assert_eq!(diff["headCommit"], published.to_string()); + assert_eq!(diff["baseCommit"], base.to_string()); + assert!(diff["diff"].as_str().unwrap().contains("+published candidate")); + assert!(!diff["diff"].as_str().unwrap().contains("later unpublished work")); + let receipt = fixture.apply("merge", Some(2), json!({"type":"merge", "number":2})).await; + let merged = git.refname_to_id("refs/heads/main").unwrap(); + assert_eq!(receipt["result"]["merge_commit"], merged.to_string()); + let commit = git.find_commit(merged).unwrap(); + assert_eq!(commit.parent_count(), 2); + assert_eq!(commit.parent_id(0).unwrap(), base); + assert_eq!(commit.parent_id(1).unwrap(), published); + let tree = commit.tree().unwrap(); + let blob = git.find_blob(tree.get_name("README.md").unwrap().id()).unwrap(); + assert_eq!(blob.content(), b"published candidate\n"); + assert_eq!(fixture.get("/api/control/items/1").await["item"]["state"], "open"); + assert_eq!(fixture.get("/api/control/items/2").await["item"]["state"], "closed"); + let events = fixture.get("/api/platform/events?after=0").await; + fixture.restart().await; + let replay = fixture.apply("merge", Some(2), json!({"type":"merge", "number":2})).await; + assert_eq!(replay, receipt); + assert_eq!(git.refname_to_id("refs/heads/main").unwrap(), merged); + assert_eq!(fixture.get("/api/platform/events?after=0").await, events); + fixture.shutdown().await; +} + +async fn assigned_pr(fixture: &Fixture) -> Value { + fixture.create_issue().await; + let git = git2::Repository::open(&fixture.config.source).unwrap(); + let base = git.refname_to_id("refs/heads/main").unwrap(); + commit(&git, "refs/heads/feature", "candidate\n", &[base]); + git.set_head_detached(base).unwrap(); + fixture + .apply( + "pr", + None, + json!({"type":"createPR", "title":"Implementation", "body":"", + "head":"feature", "base":"main", "issue":1, "issueRevision":1}), + ) + .await; + fixture + .apply("assign-pr", Some(1), json!({"type":"assign", "number":2, "actor":"worker"})) + .await; + let (status, grant) = fixture + .post( + "/api/platform/grants", + &json!({"requestId":"grant-pr", + "clientId":"harness", "itemNumber":2, "actor":"worker", "expectedEpoch":0}), + ) + .await; + assert_eq!(status, StatusCode::OK); + json!({"grantId":grant["grantId"],"epoch":grant["epoch"],"token":grant["token"]}) +} + +#[tokio::test] +async fn adopted_merge_recovers_its_receipt_after_restart_and_writer_revocation() { + let mut fixture = Fixture::new().await; + let capability = assigned_pr(&fixture).await; + let request = json!({"requestId":"merge-lost", "expectedRevision":2, + "actor":"worker", "writer":capability, "command":{"type":"merge", "number":2}}); + let db = rusqlite::Connection::open(&fixture.config.database).unwrap(); + // Git CAS succeeds. Failing final receipt storage must roll back the matching + // SQL effects, while retaining this request's exact prepared Git commit. + db.execute_batch("CREATE TRIGGER lose_receipt BEFORE UPDATE OF response_json ON control_receipts WHEN NEW.request_id='merge-lost' AND NEW.state!='prepared' BEGIN SELECT RAISE(ABORT, 'injected receipt storage failure'); END;").unwrap(); + let before = fixture.get("/api/platform/events?after=0").await; + let (status, failure) = fixture.post("/api/control/commands", &request).await; + assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY); + assert!( + failure["error"]["message"].as_str().unwrap().contains("injected receipt storage failure") + ); + let pending = fixture.get("/api/control/items/2").await; + assert_eq!( + pending["item"]["state"], "open", + "merge completion must commit atomically with its command receipt" + ); + assert_eq!(pending["item"]["revision"], 2); + assert_eq!(pending["merge"]["lifecycle"], "prepared"); + let merged = pending["merge"]["merge_commit"].as_str().unwrap().to_owned(); + let prepared = fixture.get("/api/control/receipts/merge-lost").await; + assert_eq!(prepared["state"], "prepared"); + assert_eq!(prepared["result"]["merge"]["merge_commit"], merged); + assert_eq!(fixture.get("/api/platform/events?after=0").await, before); + let git = git2::Repository::open(&fixture.config.source).unwrap(); + assert_eq!(git.refname_to_id("refs/heads/main").unwrap().to_string(), merged); + db.execute_batch("DROP TRIGGER lose_receipt").unwrap(); + drop(db); + let (status, revoked) = fixture.post("/api/platform/grants/revoke", &json!({ + "requestId":"revoke-pr", "clientId":"harness", "itemNumber":2, "actor":"worker", "expectedEpoch":1, + })).await; + assert_eq!(status, StatusCode::OK, "{revoked}"); + assert_eq!(revoked["lifecycle"], "revoked"); + fixture.restart().await; + // A differently bound payload cannot consume this request's prepared result. + let mut different = request.clone(); + different["actor"] = json!("other-worker"); + let (status, rejected) = fixture.post("/api/control/commands", &different).await; + assert_eq!(status, StatusCode::CONFLICT); + assert!(rejected["error"]["message"].as_str().unwrap().contains("requestId was already used")); + assert_eq!(fixture.get("/api/control/receipts/merge-lost").await, prepared); + let (status, recovered) = fixture.post("/api/control/commands", &request).await; + assert_eq!(status, StatusCode::OK, "{recovered}"); + assert_eq!(recovered["state"], "applied"); + assert_eq!(recovered["result"]["merge_commit"], merged); + assert_eq!(fixture.get("/api/control/receipts/merge-lost").await, recovered); + let item = fixture.get("/api/control/items/2").await; + assert_eq!(item["item"]["state"], "closed"); + assert_eq!(item["item"]["revision"], 3); + assert_eq!(item["merge"]["lifecycle"], "applied"); + let db = rusqlite::Connection::open(&fixture.config.database).unwrap(); + let origins: Vec<(String, String)> = db + .prepare("SELECT actor,origin FROM local_events WHERE detail='merged'") + .unwrap() + .query_map([], |row| Ok((row.get(0)?, row.get(1)?))) + .unwrap() + .collect::>() + .unwrap(); + assert_eq!(origins, [("worker".into(), "agent".into())]); + drop(db); + let events = fixture.get("/api/platform/events?after=0").await; + fixture.restart().await; + assert_eq!(fixture.post("/api/control/commands", &request).await, (StatusCode::OK, recovered)); + assert_eq!(fixture.get("/api/control/items/2").await, item); + assert_eq!(fixture.get("/api/platform/events?after=0").await, events); + assert_eq!(git.refname_to_id("refs/heads/main").unwrap().to_string(), merged); + fixture.shutdown().await; +} + +#[tokio::test] +async fn prepared_merge_does_not_retry_uncommitted_effects_after_writer_revocation() { + let mut fixture = Fixture::new().await; + let capability = assigned_pr(&fixture).await; + let request = json!({"requestId":"merge-pending", "expectedRevision":2, + "actor":"worker", "writer":capability, "command":{"type":"merge", "number":2}}); + let db = rusqlite::Connection::open(&fixture.config.database).unwrap(); + db.execute_batch("CREATE TRIGGER fail_intent BEFORE INSERT ON local_merges BEGIN SELECT RAISE(ABORT, 'injected merge intent failure'); END; + CREATE TRIGGER lose_receipt BEFORE UPDATE OF response_json ON control_receipts WHEN NEW.request_id='merge-pending' BEGIN SELECT RAISE(ABORT, 'injected receipt storage failure'); END;").unwrap(); + let (status, failure) = fixture.post("/api/control/commands", &request).await; + assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY); + assert!( + failure["error"]["message"].as_str().unwrap().contains("injected receipt storage failure") + ); + let item = fixture.get("/api/control/items/2").await; + assert!(item["merge"].is_null()); + assert_eq!(item["item"]["state"], "open"); + let git = git2::Repository::open(&fixture.config.source).unwrap(); + let base = git.refname_to_id("refs/heads/main").unwrap(); + db.execute_batch("DROP TRIGGER fail_intent; DROP TRIGGER lose_receipt;").unwrap(); + drop(db); + let (status, revoked) = fixture.post("/api/platform/grants/revoke", &json!({ + "requestId":"revoke-pr", "clientId":"harness", "itemNumber":2, "actor":"worker", "expectedEpoch":1, + })).await; + assert_eq!(status, StatusCode::OK, "{revoked}"); + assert_eq!(revoked["lifecycle"], "revoked"); + let events = fixture.get("/api/platform/events?after=0").await; + fixture.restart().await; + let (status, pending) = fixture.post("/api/control/commands", &request).await; + assert_eq!(status, StatusCode::ACCEPTED, "{pending}"); + assert_eq!(pending["state"], "prepared"); + assert_eq!(fixture.get("/api/control/items/2").await, item); + assert_eq!(fixture.get("/api/platform/events?after=0").await, events); + assert_eq!(git.refname_to_id("refs/heads/main").unwrap(), base); + fixture.shutdown().await; +} + +#[tokio::test] +async fn a_bound_but_unadopted_merge_cannot_use_retry_to_bypass_revocation() { + let mut fixture = Fixture::new().await; + let capability = assigned_pr(&fixture).await; + let request = json!({"requestId":"merge-locked", "expectedRevision":2, + "actor":"worker", "writer":capability, "command":{"type":"merge", "number":2}}); + let git = git2::Repository::open(&fixture.config.source).unwrap(); + let base = git.refname_to_id("refs/heads/main").unwrap(); + let lock = git.path().join("refs/heads/main.lock"); + std::fs::write(&lock, b"held by contract test").unwrap(); + let (status, blocked) = fixture.post("/api/control/commands", &request).await; + assert_eq!(status, StatusCode::CONFLICT, "{blocked}"); + assert_eq!(blocked["state"], "blocked"); + assert!( + blocked["error"]["message"].as_str().unwrap().contains("base ref compare-and-swap failed") + ); + assert!(blocked["result"]["merge"]["merge_commit"].is_string()); + assert_eq!(git.refname_to_id("refs/heads/main").unwrap(), base); + std::fs::remove_file(lock).unwrap(); + let (status, revoked) = fixture.post("/api/platform/grants/revoke", &json!({ + "requestId":"revoke-pr", "clientId":"harness", "itemNumber":2, "actor":"worker", "expectedEpoch":1, + })).await; + assert_eq!(status, StatusCode::OK, "{revoked}"); + let item = fixture.get("/api/control/items/2").await; + let events = fixture.get("/api/platform/events?after=0").await; + fixture.restart().await; + assert_eq!( + fixture.post("/api/control/commands", &request).await, + (StatusCode::CONFLICT, blocked) + ); + assert_eq!(fixture.get("/api/control/items/2").await, item); + assert_eq!(fixture.get("/api/platform/events?after=0").await, events); + assert_eq!(git.refname_to_id("refs/heads/main").unwrap(), base); + fixture.shutdown().await; +} + +#[tokio::test] +async fn publishing_and_its_receipt_commit_together_or_leave_the_candidate_unchanged() { + let mut fixture = Fixture::new().await; + let capability = assigned_pr(&fixture).await; + let git = git2::Repository::open(&fixture.config.source).unwrap(); + let previous = git.refname_to_id("refs/heads/feature").unwrap(); + let candidate = commit( + &git, + "refs/heads/feature", + "publication +", + &[previous], + ); + let request = json!({"requestId":"publish-lost", "expectedRevision":2, "actor":"worker", "writer":capability, + "command":{"type":"publish", "number":2, "candidate":{"type":"commit", "commit":candidate.to_string()}}}); + let item = fixture.get("/api/control/items/2").await; + let events = fixture.get("/api/platform/events?after=0").await; + let db = rusqlite::Connection::open(&fixture.config.database).unwrap(); + db.execute_batch("CREATE TRIGGER lose_publish_receipt BEFORE UPDATE OF response_json ON control_receipts WHEN NEW.request_id='publish-lost' BEGIN SELECT RAISE(ABORT, 'injected publish receipt failure'); END;").unwrap(); + let (status, failure) = fixture.post("/api/control/commands", &request).await; + assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY); + assert!( + failure["error"]["message"].as_str().unwrap().contains("injected publish receipt failure") + ); + assert_eq!( + fixture.get("/api/control/items/2").await, + item, + "publication must commit atomically with its command receipt" + ); + assert_eq!(fixture.get("/api/platform/events?after=0").await, events); + db.execute_batch("DROP TRIGGER lose_publish_receipt").unwrap(); + drop(db); + fixture.restart().await; + assert_eq!(fixture.get("/api/control/items/2").await, item); + let mut new_request = request.clone(); + new_request["requestId"] = json!("publish-complete"); + let (status, receipt) = fixture.post("/api/control/commands", &new_request).await; + assert_eq!(status, StatusCode::OK, "{receipt}"); + assert_eq!(receipt["result"]["head_commit"], candidate.to_string()); + assert_eq!(receipt["result"]["revision"], 3); + assert_eq!(receipt["result"]["published"], true); + let item = fixture.get("/api/control/items/2").await; + let events = fixture.get("/api/platform/events?after=0").await; + fixture.restart().await; + assert_eq!( + fixture.post("/api/control/commands", &new_request).await, + (StatusCode::OK, receipt) + ); + assert_eq!(fixture.get("/api/control/items/2").await, item); + assert_eq!(fixture.get("/api/platform/events?after=0").await, events); + fixture.shutdown().await; +} From 7705a04d492d0b2a8e35c55783423e4b16388e86 Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Fri, 27 Nov 2026 20:22:35 +0800 Subject: [PATCH 03/43] =?UTF-8?q?chore(audit):=20=E4=B8=B4=E6=97=B6?= =?UTF-8?q?=E8=BF=90=E8=A1=8C=E4=BF=9D=E7=95=99=E6=80=A7=E7=A0=B4=E5=9D=8F?= =?UTF-8?q?=E6=8E=A7=E5=88=B6=E4=B8=8E=E5=B9=B3=E5=8F=B0=E5=9F=BA=E7=BA=BF?= =?UTF-8?q?=E5=AF=B9=E7=85=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 精确断言 mutation 因目标契约失败,并逐字恢复生产源 - 对照完成后移除此任务专用 workflow,不扩大常规 CI 成本 --- .github/workflows/audit-proof.yml | 82 +++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 .github/workflows/audit-proof.yml diff --git a/.github/workflows/audit-proof.yml b/.github/workflows/audit-proof.yml new file mode 100644 index 00000000..a3bf2a97 --- /dev/null +++ b/.github/workflows/audit-proof.yml @@ -0,0 +1,82 @@ +name: audit preservation controls (temporary) + +on: + pull_request: + paths: [.github/workflows/audit-proof.yml] + +permissions: + contents: read + +concurrency: + group: audit-proof-${{ github.head_ref }} + cancel-in-progress: true + +jobs: + controls: + if: github.head_ref == 'feat/pr149-test-audit' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - run: rustup toolchain install 1.93.0 --profile minimal + - name: Confirm keepers reject deliberate owner defects + shell: python + run: | + from pathlib import Path + import subprocess + + def run(test, marker=None): + result = subprocess.run( + ['cargo', 'test', '--locked', '--bin', 'braid', test, '--', '--exact', '--nocapture'], + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) + print(result.stdout, flush=True) + if marker is None: + assert result.returncode == 0, f'candidate failed: {test}' + else: + assert result.returncode != 0, f'mutation survived: {test}' + assert 'test result: FAILED' in result.stdout, 'not a test assertion failure' + assert marker in result.stdout, f'failed for an unexpected reason: {test}' + print(f'CAUGHT CONTROL: {test} / {marker}', flush=True) + + state = 'group::continuous_tests::idle_revision_replaces_memory_then_starts_once_without_a_second_mention' + publication = 'writer::tests::outbox_delivery_recovery_and_rate_deadline_use_production_executor' + merge = 'platform::tests::adopted_merge_recovers_its_receipt_after_restart_and_writer_revocation' + publish = 'platform::tests::publishing_and_its_receipt_commit_together_or_leave_the_candidate_unchanged' + for test in [state, publication, merge, publish]: + run(test) + + controls = [ + ('src/group/dispatch.rs', '\n && !self.sessions.confirmed_stopped(&reset.old_provider_session_id).await', '', + state, 'one replacement after confirmed stop; already closed: true'), + ('src/writer/comment.rs', 'database_id: comment.id.to_string(),\n node_id: comment.node_id.clone(),', + 'database_id: "not-the-remote-id".into(),\n node_id: comment.node_id.clone(),', + publication, 'not-the-remote-id'), + ] + for filename, before, after, test, marker in controls: + path = Path(filename) + original = path.read_bytes() + try: + text = original.decode() + assert text.count(before) == 1, f'ambiguous mutation: {filename}' + path.write_text(text.replace(before, after)) + run(test, marker) + finally: + path.write_bytes(original) + assert path.read_bytes() == original + + baseline = '9d838b9d8443e520da9b6b9229e151bf88b576de' + originals = {Path(name): Path(name).read_bytes() for name in + ['src/platform/objects.rs', 'src/platform/objects/commands.rs']} + try: + for path in originals: + path.write_bytes(subprocess.check_output(['git', 'show', f'{baseline}:{path}'])) + run(merge, 'merge completion must commit atomically with its command receipt') + run(publish, 'publication must commit atomically with its command receipt') + finally: + for path, original in originals.items(): + path.write_bytes(original) + assert path.read_bytes() == original + subprocess.run(['git', 'diff', '--exit-code', '--', 'src'], check=True) + for test in [state, publication, merge, publish]: + run(test) From 1c4ef61840f69a9b5c601895180193224a6fe09e Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Fri, 27 Nov 2026 20:23:40 +0800 Subject: [PATCH 04/43] =?UTF-8?q?fix(audit):=20=E4=BF=AE=E6=AD=A3=E6=B5=8B?= =?UTF-8?q?=E8=AF=95=E6=8F=90=E5=8F=96=E6=96=B9=E5=BC=8F=E5=B9=B6=E6=98=8E?= =?UTF-8?q?=E7=A1=AE=E5=B9=B3=E5=8F=B0=E6=81=A2=E5=A4=8D=E8=BE=B9=E7=95=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 测试直接匹配目标错误,不增加生产Debug接口 - 恢复回执明确标记recovered,维护平台权威说明 - 临时控制先执行全量回归,再执行破坏对照 --- .github/workflows/audit-proof.yml | 1 + docs/20-product-tdd/README.md | 10 ++++++++-- docs/user-manual/local.md | 12 ++++++++++-- src/platform/objects/commands.rs | 3 ++- src/platform/tests.rs | 1 + src/writer/tests/body_edit.rs | 12 +++++++----- 6 files changed, 29 insertions(+), 10 deletions(-) diff --git a/.github/workflows/audit-proof.yml b/.github/workflows/audit-proof.yml index a3bf2a97..b4ae600b 100644 --- a/.github/workflows/audit-proof.yml +++ b/.github/workflows/audit-proof.yml @@ -20,6 +20,7 @@ jobs: with: fetch-depth: 0 - run: rustup toolchain install 1.93.0 --profile minimal + - run: cargo test --locked --all-targets - name: Confirm keepers reject deliberate owner defects shell: python run: | diff --git a/docs/20-product-tdd/README.md b/docs/20-product-tdd/README.md index c0b6b853..451a1c94 100644 --- a/docs/20-product-tdd/README.md +++ b/docs/20-product-tdd/README.md @@ -312,8 +312,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/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/src/platform/objects/commands.rs b/src/platform/objects/commands.rs index 31a10767..31789968 100644 --- a/src/platform/objects/commands.rs +++ b/src/platform/objects/commands.rs @@ -477,7 +477,7 @@ impl PlatformObjects { // Older prepared receipts have no request-bound commit evidence. return Ok(receipt); }; - let prepared: super::PreparedMerge = + let mut prepared: super::PreparedMerge = serde_json::from_value(value.clone()).map_err(CommandFailure::rejected)?; let git = git2::Repository::open(&policy.source).map_err(CommandFailure::rejected)?; if git @@ -491,6 +491,7 @@ impl PlatformObjects { self.writer = request.writer.as_ref().zip(prepared.writer_item).map(|(grant, item)| { super::Writer { grant: grant.clone(), item, actor: request.actor.clone() } }); + prepared.merge.recovered = true; let result = self.finish_merge(&prepared.merge, &request.actor, &request.request_id); self.writer = None; result?; diff --git a/src/platform/tests.rs b/src/platform/tests.rs index a7d080a8..cade6709 100644 --- a/src/platform/tests.rs +++ b/src/platform/tests.rs @@ -355,6 +355,7 @@ async fn adopted_merge_recovers_its_receipt_after_restart_and_writer_revocation( let (status, recovered) = fixture.post("/api/control/commands", &request).await; assert_eq!(status, StatusCode::OK, "{recovered}"); assert_eq!(recovered["state"], "applied"); + assert_eq!(recovered["result"]["recovered"], true); assert_eq!(recovered["result"]["merge_commit"], merged); assert_eq!(fixture.get("/api/control/receipts/merge-lost").await, recovered); let item = fixture.get("/api/control/items/2").await; diff --git a/src/writer/tests/body_edit.rs b/src/writer/tests/body_edit.rs index 6611a646..0ed03bbd 100644 --- a/src/writer/tests/body_edit.rs +++ b/src/writer/tests/body_edit.rs @@ -606,13 +606,15 @@ async fn executor_rejects_missing_existing_request_source_before_mutation() { payload["body"] = json!("Closes #7\n\nCloses #999"); receipt.payload = serde_json::to_string(&payload).unwrap(); let mut mutation_possible = false; - let error = + let Err(helpers::WriteFailure::GitHub(GitHubError::GraphQl(message))) = edit::execute(&fixture.config, &fixture.store, &github, &receipt, &mut mutation_possible) .await - .unwrap_err(); - assert!( - matches!(error, helpers::WriteFailure::GitHub(GitHubError::GraphQl(ref message)) if message == "body maintenance must retain recognized existing closing and request sources"), - "wrong failure: {error:?}" + else { + panic!("expected a GraphQL rejection for the missing existing request source"); + }; + assert_eq!( + message, + "body maintenance must retain recognized existing closing and request sources" ); assert!(!mutation_possible); assert_eq!(remote.lock().unwrap().writes, 0); From d8f7d9f8a82b7de8db348e60b028b6498baf648c Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Fri, 27 Nov 2026 20:28:20 +0800 Subject: [PATCH 05/43] =?UTF-8?q?fix(tests):=20=E4=BF=AE=E6=AD=A3=E9=85=8D?= =?UTF-8?q?=E7=BD=AE=E5=A4=B9=E5=85=B7=E5=B9=B6=E8=A1=A5=E9=BD=90=20schema?= =?UTF-8?q?=20=E4=B8=8E=E8=B0=83=E5=BA=A6=E9=97=A8=E6=A7=9B=E8=AF=81?= =?UTF-8?q?=E6=98=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - TOML 新字段使用显式插入,避免夹具在目标路径前失败 - 用真实 StoreActor 验证损坏数据库拒绝和七/八条阈值、去重、quiet deadline - 处理CI反馈的借用、字段顺序、字面量和局部结构lint --- src/platform/objects.rs | 17 +++-- src/provider/pi_tests.rs | 2 +- src/store/gh_writes/tests.rs | 14 ++-- src/store/mod.rs | 4 ++ src/store/scheduler_tests.rs | 130 +++++++++++++++++++++++++++++++++++ src/store/schema_tests.rs | 103 +++++++++++++++++++++++++++ src/writer/tests.rs | 2 +- tests/multi_repo.rs | 16 +++-- tests/provider_config.rs | 59 ++++++---------- 9 files changed, 286 insertions(+), 61 deletions(-) create mode 100644 src/store/scheduler_tests.rs create mode 100644 src/store/schema_tests.rs diff --git a/src/platform/objects.rs b/src/platform/objects.rs index 07436bb0..0bea1466 100644 --- a/src/platform/objects.rs +++ b/src/platform/objects.rs @@ -815,16 +815,15 @@ impl PlatformObjects { |r| Ok((r.get(0)?, r.get(1)?)), ) .optional()?; - if let Some((state, Some(commit))) = &receipt { - if state == "applied" + if let Some((state, Some(commit))) = &receipt + && (state == "applied" || (state == "prepared" - && git.refname_to_id(&base_ref)? == git2::Oid::from_str(commit)?) - { - let result = - MergeResult { number, merge_commit: commit.clone(), base_ref, recovered: true }; - self.finish_merge(&result, author, request_id)?; - return Ok(result); - } + && git.refname_to_id(&base_ref)? == git2::Oid::from_str(commit)?)) + { + let result = + MergeResult { number, merge_commit: commit.clone(), base_ref, recovered: true }; + self.finish_merge(&result, author, request_id)?; + return Ok(result); } ensure!( receipt.as_ref().is_none_or(|(s, _)| s == "prepared"), diff --git a/src/provider/pi_tests.rs b/src/provider/pi_tests.rs index 5db9a41d..2df990f9 100644 --- a/src/provider/pi_tests.rs +++ b/src/provider/pi_tests.rs @@ -22,7 +22,7 @@ fn oauth_material_is_written_in_the_native_format_with_private_permissions() { } write_pi_auth_json(&root, &config, &oauth).unwrap(); let actual: Value = serde_json::from_slice(&std::fs::read(&auth_path).unwrap()).unwrap(); - let mut expected = json!({"test-llm":{"type":"oauth","access":"PRIVATE_ACCESS","refresh":"PRIVATE_REFRESH","expires":4102444800000_u64}}); + let mut expected = json!({"test-llm":{"type":"oauth","access":"PRIVATE_ACCESS","refresh":"PRIVATE_REFRESH","expires":4_102_444_800_000_u64}}); if account.is_some() { expected["test-llm"]["account"] = json!("operator@example.invalid"); } diff --git a/src/store/gh_writes/tests.rs b/src/store/gh_writes/tests.rs index eae9103a..3644d39d 100644 --- a/src/store/gh_writes/tests.rs +++ b/src/store/gh_writes/tests.rs @@ -43,9 +43,9 @@ fn intent(operation: &'static str) -> NewGhWriteIntent { source: None, } } -fn invalid_data(error: StoreError, expected: &str) { +fn invalid_data(error: &StoreError, expected: &str) { assert!( - matches!(error, StoreError::InvalidData(ref message) if message.contains(expected)), + matches!(error, StoreError::InvalidData(message) if message.contains(expected)), "wrong failure: {error}" ); } @@ -62,7 +62,7 @@ fn offline_acceptance_is_atomic_idempotent_and_publicly_queryable() { let mut conflict = write; conflict.request_digest = "b".repeat(64); invalid_data( - store.prepare_gh_write(conflict).unwrap_err(), + &store.prepare_gh_write(conflict).unwrap_err(), "already used for a different payload", ); drop(store); @@ -107,7 +107,7 @@ fn retry_deadline_survives_actor_restart_and_stale_attempt_cannot_settle() { let third = reopened.claim_github_write(owner.clone()).unwrap().unwrap(); assert_eq!(third.lifecycle, "uncertain"); invalid_data( - reopened.finish_github_write(second, "applied", None, None, None).unwrap_err(), + &reopened.finish_github_write(second, "applied", None, None, None).unwrap_err(), "stale outbox attempt", ); reopened.finish_github_write(third, "applied", Some("123".into()), None, None).unwrap(); @@ -127,11 +127,11 @@ fn expired_or_replaced_runtime_cannot_claim_or_settle() { let first = store.claim_github_write(owner.clone()).unwrap().unwrap(); db.connect().execute(change, []).unwrap(); invalid_data( - store.claim_github_write(owner).unwrap_err(), + &store.claim_github_write(owner).unwrap_err(), "outbox runtime owner expired or replaced", ); invalid_data( - store.finish_github_write(first, "applied", None, None, None).unwrap_err(), + &store.finish_github_write(first, "applied", None, None, None).unwrap_err(), "outbox runtime owner expired or replaced", ); assert_eq!( @@ -216,7 +216,7 @@ fn ensure_plan_and_progress_freeze_and_resume_without_replanning() { 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"] { - store + &store .record_implementation_progress( receipt.intent_id.clone(), ImplementationProgress { diff --git a/src/store/mod.rs b/src/store/mod.rs index 6b0f68fc..14883c51 100644 --- a/src/store/mod.rs +++ b/src/store/mod.rs @@ -31,6 +31,10 @@ mod operational_status; mod operational_status_migration_tests; #[cfg(test)] mod replay_tests; +#[cfg(test)] +mod scheduler_tests; +#[cfg(test)] +mod schema_tests; pub(crate) use implementation_delivery::PrActivation; pub(crate) mod handoff; mod write_execution; diff --git a/src/store/scheduler_tests.rs b/src/store/scheduler_tests.rs new file mode 100644 index 00000000..4bed12ea --- /dev/null +++ b/src/store/scheduler_tests.rs @@ -0,0 +1,130 @@ +use super::{ChangeIdentity, EventKind, IngressEvent, SchedulerPolicy}; +use crate::writer::tests::Fixture; + +fn ordinary_comment(number: u32) -> IngressEvent { + IngressEvent { + identity: ChangeIdentity::ObjectVersion, + delivery_guid: format!("delivery-{number}"), + event_name: "issue_comment".into(), + action: Some("created".into()), + repository_node_id: "repo".into(), + repository: "owner/repository".into(), + work_item_node_id: Some("item".into()), + work_item_kind: Some("issue"), + work_item_number: Some(1), + work_item_state: Some("open".into()), + object_node_id: Some(format!("comment-{number}")), + object_version: Some("2026-01-01T00:00:00Z".into()), + object_digest: Some("a".repeat(64)), + visible_body: Some(format!("Comment {number}")), + actor_node_id: Some("human".into()), + actor_login: Some("human".into()), + kind: EventKind::Wake, + detail: Some("created"), + cross_surface_invalidation: false, + requires_attention: true, + origin: "external", + reference: format!("Comment {number}"), + mention_candidate: false, + reaction_target: None, + known: true, + raw_payload: vec![], + } +} + +#[test] +fn eighth_distinct_input_releases_the_batch_without_waiting_for_quiet() { + let f = Fixture::new(true); + let policy = SchedulerPolicy { quiet_seconds: 3600, event_threshold: 8 }; + for number in 1..=7 { + let admitted = f.store.ingest_event(ordinary_comment(number), policy).unwrap(); + assert!(admitted.event_id.is_some()); + assert_eq!(admitted.batch_lifecycle.as_deref(), Some("pending")); + } + assert_eq!(f.store.advance_scheduler().unwrap(), 0); + assert!( + f.store + .claim_runnable_turn("issue".into(), "issue-codex".into(), vec!["provider".into()]) + .unwrap() + .is_none() + ); + // Both transport redelivery and a new delivery of the same object version + // must leave the threshold count at seven. + assert!(f.store.ingest_event(ordinary_comment(7), policy).unwrap().duplicate); + let mut redelivery = ordinary_comment(7); + redelivery.delivery_guid = "new-delivery-same-comment".into(); + let repeated = f.store.ingest_event(redelivery, policy).unwrap(); + assert!(!repeated.duplicate); + assert!(repeated.event_id.is_none()); + assert_eq!(repeated.event_lifecycle.as_deref(), Some("superseded")); + let status = f.store.runtime_status().unwrap(); + assert_eq!((status.pending_batches, status.runnable_batches), (1, 0)); + assert_eq!(status.batches.len(), 1); + assert_eq!(status.batches[0].event_count, 7); + assert!( + f.store + .claim_runnable_turn("issue".into(), "issue-codex".into(), vec!["provider".into()]) + .unwrap() + .is_none() + ); + + let eighth = f.store.ingest_event(ordinary_comment(8), policy).unwrap(); + assert_eq!(eighth.batch_lifecycle.as_deref(), Some("runnable")); + assert_eq!(f.store.runtime_status().unwrap().batches[0].event_count, 8); + let claim = f + .store + .claim_runnable_turn("issue".into(), "issue-codex".into(), vec!["provider".into()]) + .unwrap() + .expect("the eighth distinct input is sufficient without a clock advance"); + assert_eq!(Some(claim.batch_id), eighth.batch_id); + assert_eq!(claim.references, (1..=8).map(|n| format!("Comment {n}")).collect::>()); + assert_eq!(claim.trigger_kind, "wake_batch"); + assert!(!claim.trusted_mention); + assert!( + f.store + .claim_runnable_turn("issue".into(), "issue-codex".into(), vec!["provider".into()]) + .unwrap() + .is_none() + ); + assert!(f.store.runtime_status().unwrap().batches.is_empty()); +} + +#[test] +fn quiet_deadline_releases_a_subthreshold_batch_only_when_due() { + let f = Fixture::new(true); + let policy = SchedulerPolicy { quiet_seconds: 3600, event_threshold: 8 }; + let admitted = f.store.ingest_event(ordinary_comment(1), policy).unwrap(); + assert_eq!(admitted.batch_lifecycle.as_deref(), Some("pending")); + assert_eq!(f.store.advance_scheduler().unwrap(), 0); + assert!( + f.store + .claim_runnable_turn("issue".into(), "issue-codex".into(), vec!["provider".into()]) + .unwrap() + .is_none() + ); + // Move only the persisted deadline across the clock boundary; real ingestion, + // scheduler advancement and claiming still own every lifecycle transition. + assert_eq!( + f.db() + .execute( + "UPDATE wake_batches SET quiet_deadline='2000-01-01T00:00:00Z' WHERE batch_id=?1", + [admitted.batch_id.as_deref().unwrap()], + ) + .unwrap(), + 1 + ); + assert_eq!(f.store.advance_scheduler().unwrap(), 1); + assert_eq!(f.store.advance_scheduler().unwrap(), 0); + let status = f.store.runtime_status().unwrap(); + assert_eq!((status.pending_batches, status.runnable_batches), (0, 1)); + assert_eq!(status.batches[0].event_count, 1); + let claim = f + .store + .claim_runnable_turn("issue".into(), "issue-codex".into(), vec!["provider".into()]) + .unwrap() + .expect("an expired quiet window is sufficient below the count threshold"); + assert_eq!(Some(claim.batch_id), admitted.batch_id); + assert_eq!(claim.references, vec!["Comment 1"]); + assert_eq!(claim.trigger_kind, "wake_batch"); + assert!(!claim.trusted_mention); +} diff --git a/src/store/schema_tests.rs b/src/store/schema_tests.rs new file mode 100644 index 00000000..860da42c --- /dev/null +++ b/src/store/schema_tests.rs @@ -0,0 +1,103 @@ +use super::{DATABASE_SCHEMA_VERSION, StoreActor, StoreError}; +use rusqlite::Connection; +use std::path::PathBuf; + +#[derive(Clone, Copy, Debug)] +enum InvalidSchema { + Foreign, + Newer, + NonContiguous, + ChangedChecksum, +} + +struct TemporaryRoot(PathBuf); +impl Drop for TemporaryRoot { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +#[test] +fn migration_entry_points_reject_incompatible_databases_without_changing_bytes() { + for case in [ + InvalidSchema::Foreign, + InvalidSchema::Newer, + InvalidSchema::NonContiguous, + InvalidSchema::ChangedChecksum, + ] { + let root = TemporaryRoot( + std::env::temp_dir().join(format!("braid-schema-{}", uuid::Uuid::now_v7())), + ); + std::fs::create_dir_all(&root.0).unwrap(); + let database = root.0.join("state.sqlite3"); + let backups = root.0.join("backups"); + if !matches!(case, InvalidSchema::Foreign) { + let store = StoreActor::start(database.clone(), backups.clone()).unwrap(); + assert_eq!(store.apply().unwrap().current_schema, DATABASE_SCHEMA_VERSION); + assert!(store.plan().unwrap().pending.is_empty()); + drop(store); + } + let db = Connection::open(&database).unwrap(); + match case { + InvalidSchema::Foreign => { + db.execute_batch( + "CREATE TABLE user_data(value TEXT NOT NULL); + INSERT INTO user_data VALUES ('preserve this foreign database');", + ) + .unwrap(); + } + InvalidSchema::Newer => { + db.execute( + "INSERT INTO schema_migrations(version,name,checksum,applied_at) + VALUES (?1,'future-schema',?2,'2026-01-01T00:00:00Z')", + rusqlite::params![DATABASE_SCHEMA_VERSION + 1, "0".repeat(64)], + ) + .unwrap(); + } + InvalidSchema::NonContiguous => { + assert_eq!( + db.execute("DELETE FROM schema_migrations WHERE version=2", []).unwrap(), + 1 + ); + } + InvalidSchema::ChangedChecksum => { + assert_eq!( + db.execute( + "UPDATE schema_migrations SET checksum=?1 WHERE version=1 AND checksum<>?1", + ["0".repeat(64)], + ) + .unwrap(), + 1 + ); + } + } + // Include every committed page in the snapshot, with no WAL left outside it. + db.execute_batch("PRAGMA wal_checkpoint(TRUNCATE); PRAGMA journal_mode=DELETE;").unwrap(); + drop(db); + let before = std::fs::read(&database).unwrap(); + assert!(!before.is_empty()); + let store = StoreActor::start(database.clone(), backups).unwrap(); + for apply in [false, true] { + let result = if apply { store.apply().map(|_| ()) } else { store.plan().map(|_| ()) }; + let error = result.expect_err("invalid schema must be rejected before migration"); + match (case, error) { + (InvalidSchema::Foreign, StoreError::ForeignDatabase { path }) => { + assert_eq!(path, database); + } + (InvalidSchema::Newer, StoreError::NewerSchema { found, supported }) => { + assert_eq!(found, DATABASE_SCHEMA_VERSION + 1); + assert_eq!(supported, DATABASE_SCHEMA_VERSION); + } + (InvalidSchema::NonContiguous, StoreError::NonContiguous { version }) => { + assert_eq!(version, 3); + } + (InvalidSchema::ChangedChecksum, StoreError::ChecksumMismatch { version }) => { + assert_eq!(version, 1); + } + (case, error) => panic!("wrong rejection for {case:?}, apply={apply}: {error:?}"), + } + assert_eq!(std::fs::read(&database).unwrap(), before, "{case:?}, apply={apply}"); + } + drop(store); + } +} diff --git a/src/writer/tests.rs b/src/writer/tests.rs index c81f7ca4..52c48c37 100644 --- a/src/writer/tests.rs +++ b/src/writer/tests.rs @@ -50,7 +50,7 @@ impl Fixture { config.runtime.backups().to_owned(), ) .unwrap(); - Self { root, config, store } + Self { config, store, root } } pub(crate) fn db(&self) -> Connection { Connection::open(self.config.runtime.database()).unwrap() diff --git a/tests/multi_repo.rs b/tests/multi_repo.rs index 6d90c4c5..2419193d 100644 --- a/tests/multi_repo.rs +++ b/tests/multi_repo.rs @@ -14,13 +14,19 @@ fn stderr(output: &std::process::Output) -> String { 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"]["additional_repositories"] = toml::Value::Array(vec![toml::Value::Table( - toml::Table::from_iter([("name".into(), "owner/other".into())]), - )]); + 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 { - profile["repository"] = "owner/repository".into(); - profile["workspace"] = temporary.join("primary-source").to_str().unwrap().into(); + 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() diff --git a/tests/provider_config.rs b/tests/provider_config.rs index cbb3b2d4..01ef1687 100644 --- a/tests/provider_config.rs +++ b/tests/provider_config.rs @@ -51,7 +51,7 @@ fn provider_route_inputs_are_validated_at_cli_and_config_boundaries() { let example_text = fs::read_to_string(&example).expect("read example"); let mut coupled: toml::Value = toml::from_str(&example_text).expect("parse example"); - coupled["profiles"][0]["provider"] = "openai".into(); + 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, toml::to_string(&coupled).unwrap()) @@ -129,13 +129,16 @@ fn write_pi_config(example: &str, directory: &Path, credential_fragment: &str) - for profile in config["profiles"].as_array_mut().unwrap() { profile["adapter_type"] = "pi".into(); profile["adapter_version"] = "1.0.2".into(); - profile["provider"] = "example-llm".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["llm_providers"] = toml::Value::Array(vec![provider]); + config + .as_table_mut() + .unwrap() + .insert("llm_providers".into(), toml::Value::Array(vec![provider])); let path = directory.join("config.toml"); fs::write(&path, toml::to_string(&config).unwrap()).expect("write Pi config"); path @@ -427,13 +430,16 @@ fn provider_import_auth_converts_pi_credentials() { ) .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"); @@ -449,36 +455,18 @@ fn provider_import_auth_converts_pi_credentials() { assert_eq!(fs::metadata(&imported).expect("metadata").permissions().mode() & 0o777, 0o600); } - let output = braid() - .args(["provider", "import-auth", "other-provider", "--from"]) - .arg(&pi_auth) - .args(["--user-home"]) - .arg(&user_home) - .output() - .expect("import API key credential"); + let output = import("other-provider").output().expect("import API key credential"); 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"); 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"); + let output = import("example-llm").output().expect("reject overwrite without force"); assert!(!output.status.success()); assert!(stderr(&output).contains("already exists"), "{}", stderr(&output)); @@ -487,13 +475,8 @@ fn provider_import_auth_converts_pi_credentials() { 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); } From f5d315c75f488a03cb5d73ac29b03e29fab4bf4d Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Fri, 27 Nov 2026 20:28:32 +0800 Subject: [PATCH 06/43] =?UTF-8?q?fix(tests):=20=E5=AF=B9=E6=AD=A3=E7=A1=AE?= =?UTF-8?q?=E7=9A=84=E6=8B=92=E7=BB=9D=E7=BB=93=E6=9E=9C=E4=BC=A0=E5=85=A5?= =?UTF-8?q?=E5=80=9F=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/store/gh_writes/tests.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/store/gh_writes/tests.rs b/src/store/gh_writes/tests.rs index 3644d39d..bf96afff 100644 --- a/src/store/gh_writes/tests.rs +++ b/src/store/gh_writes/tests.rs @@ -216,7 +216,7 @@ fn ensure_plan_and_progress_freeze_and_resume_without_replanning() { 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"] { - &store + store .record_implementation_progress( receipt.intent_id.clone(), ImplementationProgress { @@ -234,7 +234,7 @@ fn ensure_plan_and_progress_freeze_and_resume_without_replanning() { assert_eq!(resumed.pull_request_number, Some(9)); } invalid_data( - store + &store .record_implementation_progress( receipt.intent_id, ImplementationProgress { From 204e6de180aede89a71a552206b09960bbce5d97 Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Fri, 27 Nov 2026 20:33:24 +0800 Subject: [PATCH 07/43] =?UTF-8?q?chore(audit):=20=E5=AE=8C=E6=88=90?= =?UTF-8?q?=E7=A0=B4=E5=9D=8F=E6=8E=A7=E5=88=B6=E5=B9=B6=E7=A7=BB=E9=99=A4?= =?UTF-8?q?=E4=B8=B4=E6=97=B6=E9=AA=8C=E8=AF=81=E5=85=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 四项控制均在目标断言失败,恢复后同keeper通过 - 保留常规双平台回归,删除任务专用workflow避免持续成本 - 更新仍被真实owner使用的GitHub HTTP接缝说明 --- .github/workflows/audit-proof.yml | 83 ----------------------------- tests/support/publication_github.rs | 5 +- 2 files changed, 2 insertions(+), 86 deletions(-) delete mode 100644 .github/workflows/audit-proof.yml diff --git a/.github/workflows/audit-proof.yml b/.github/workflows/audit-proof.yml deleted file mode 100644 index b4ae600b..00000000 --- a/.github/workflows/audit-proof.yml +++ /dev/null @@ -1,83 +0,0 @@ -name: audit preservation controls (temporary) - -on: - pull_request: - paths: [.github/workflows/audit-proof.yml] - -permissions: - contents: read - -concurrency: - group: audit-proof-${{ github.head_ref }} - cancel-in-progress: true - -jobs: - controls: - if: github.head_ref == 'feat/pr149-test-audit' - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - with: - fetch-depth: 0 - - run: rustup toolchain install 1.93.0 --profile minimal - - run: cargo test --locked --all-targets - - name: Confirm keepers reject deliberate owner defects - shell: python - run: | - from pathlib import Path - import subprocess - - def run(test, marker=None): - result = subprocess.run( - ['cargo', 'test', '--locked', '--bin', 'braid', test, '--', '--exact', '--nocapture'], - stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) - print(result.stdout, flush=True) - if marker is None: - assert result.returncode == 0, f'candidate failed: {test}' - else: - assert result.returncode != 0, f'mutation survived: {test}' - assert 'test result: FAILED' in result.stdout, 'not a test assertion failure' - assert marker in result.stdout, f'failed for an unexpected reason: {test}' - print(f'CAUGHT CONTROL: {test} / {marker}', flush=True) - - state = 'group::continuous_tests::idle_revision_replaces_memory_then_starts_once_without_a_second_mention' - publication = 'writer::tests::outbox_delivery_recovery_and_rate_deadline_use_production_executor' - merge = 'platform::tests::adopted_merge_recovers_its_receipt_after_restart_and_writer_revocation' - publish = 'platform::tests::publishing_and_its_receipt_commit_together_or_leave_the_candidate_unchanged' - for test in [state, publication, merge, publish]: - run(test) - - controls = [ - ('src/group/dispatch.rs', '\n && !self.sessions.confirmed_stopped(&reset.old_provider_session_id).await', '', - state, 'one replacement after confirmed stop; already closed: true'), - ('src/writer/comment.rs', 'database_id: comment.id.to_string(),\n node_id: comment.node_id.clone(),', - 'database_id: "not-the-remote-id".into(),\n node_id: comment.node_id.clone(),', - publication, 'not-the-remote-id'), - ] - for filename, before, after, test, marker in controls: - path = Path(filename) - original = path.read_bytes() - try: - text = original.decode() - assert text.count(before) == 1, f'ambiguous mutation: {filename}' - path.write_text(text.replace(before, after)) - run(test, marker) - finally: - path.write_bytes(original) - assert path.read_bytes() == original - - baseline = '9d838b9d8443e520da9b6b9229e151bf88b576de' - originals = {Path(name): Path(name).read_bytes() for name in - ['src/platform/objects.rs', 'src/platform/objects/commands.rs']} - try: - for path in originals: - path.write_bytes(subprocess.check_output(['git', 'show', f'{baseline}:{path}'])) - run(merge, 'merge completion must commit atomically with its command receipt') - run(publish, 'publication must commit atomically with its command receipt') - finally: - for path, original in originals.items(): - path.write_bytes(original) - assert path.read_bytes() == original - subprocess.run(['git', 'diff', '--exit-code', '--', 'src'], check=True) - for test in [state, publication, merge, publish]: - run(test) 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, From f9cf8a518a4bcecd9fa9ddbb713934f5a55cf777 Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sat, 28 Nov 2026 10:23:29 +0800 Subject: [PATCH 08/43] =?UTF-8?q?fix(tests):=20=E7=94=A8=E7=9C=9F=E5=AE=9E?= =?UTF-8?q?=E6=9C=AA=E5=9B=9E=E6=94=B6=E8=BF=9B=E7=A8=8B=E7=BB=84=E9=AA=8C?= =?UTF-8?q?=E8=AF=81=20Tunnel=20=E5=85=B3=E9=97=AD=E8=BE=B9=E7=95=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 由同一夹具持有两个子进程,观察 wrapper 回收前后的组状态 - 只有余下成员被回收后才能确认停止 --- src/tunnel/tests.rs | 69 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) diff --git a/src/tunnel/tests.rs b/src/tunnel/tests.rs index 2f050402..5b220325 100644 --- a/src/tunnel/tests.rs +++ b/src/tunnel/tests.rs @@ -82,6 +82,75 @@ async fn failed_registration_also_closes_the_owned_process_tree() { std::fs::remove_dir_all(root).unwrap(); } +#[cfg(unix)] +#[tokio::test] +async fn closing_reaps_an_exited_wrapper_but_waits_for_remaining_group_members() { + use nix::{ + errno::Errno, + sys::signal::{Signal, kill, killpg}, + unistd::Pid, + }; + + // Both children belong to this test. Keeping the second one unreaped makes + // the otherwise transient zombie-only group deterministic, without mocks. + let mut wrapper = Command::new("/usr/bin/tail") + .args(["-f", "/dev/null"]) + .process_group(0) + .kill_on_drop(true) + .spawn() + .unwrap(); + let mut group = process_group::OwnedGroup::new(&wrapper); + let wrapper_pid = wrapper.id().unwrap(); + let group_id = Pid::from_raw(i32::try_from(wrapper_pid).unwrap()); + let mut member = Command::new("/bin/sh") + .args(["-c", "exit 0"]) + .process_group(group_id.as_raw()) + .kill_on_drop(true) + .spawn() + .unwrap(); + let member_pid = member.id().unwrap(); + wait_for_process_state(member_pid, "Z").await; + kill(group_id, Signal::SIGTERM).unwrap(); + wait_for_process_state(wrapper_pid, "Z").await; + + let close = group.close(&mut wrapper); + tokio::pin!(close); + tokio::select! { + biased; + result = &mut close => panic!("cleanup completed with an unreaped member: {result:?}"), + () = wait_for_process_state(wrapper_pid, "") => {} + } + // Reaping the wrapper alone is insufficient. The other real member still + // owns the group until its parent (this test) consumes its exit status. + assert_ne!(killpg(group_id, None), Err(Errno::ESRCH)); + assert!(member.wait().await.unwrap().success()); + tokio::time::timeout(Duration::from_secs(2), &mut close).await.unwrap().unwrap(); + assert_eq!(killpg(group_id, None), Err(Errno::ESRCH)); +} + +#[cfg(unix)] +async fn wait_for_process_state(pid: u32, expected: &str) { + tokio::time::timeout(Duration::from_secs(2), async { + loop { + let output = Command::new("/bin/ps") + .args(["-p", &pid.to_string(), "-o", "stat="]) + .output() + .await + .unwrap(); + let state = String::from_utf8(output.stdout).unwrap(); + let state = state.trim(); + if (expected.is_empty() && state.is_empty()) + || (!expected.is_empty() && state.starts_with(expected)) + { + return; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); +} + #[tokio::test] async fn signed_probe_requires_ingress_acceptance_not_an_arbitrary_http_success() { use std::sync::{ From d06d6d2b053b5ca03432deed30e35defb73153f4 Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sat, 28 Nov 2026 10:23:52 +0800 Subject: [PATCH 09/43] =?UTF-8?q?fix(tunnel):=20=E7=AD=89=E5=BE=85?= =?UTF-8?q?=E9=80=80=E5=87=BA=E4=B8=AD=E7=9A=84=E8=BF=9B=E7=A8=8B=E7=BB=84?= =?UTF-8?q?=E5=AE=8C=E6=88=90=E5=9B=9E=E6=94=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - macOS 对只剩僵尸的自有进程组可能暂时报 EPERM,在既有 TERM/KILL 期限内继续回收并探测 - 仍以 wrapper 已回收且组消失为成功条件,持续拒绝或超时返回失败 --- src/tunnel/process_group.rs | 38 ++++++++++++++++++++++++++++--------- 1 file changed, 29 insertions(+), 9 deletions(-) diff --git a/src/tunnel/process_group.rs b/src/tunnel/process_group.rs index 9a223416..6f5c6ff7 100644 --- a/src/tunnel/process_group.rs +++ b/src/tunnel/process_group.rs @@ -23,19 +23,34 @@ impl OwnedGroup { } pub(super) async fn close(&mut self, child: &mut Child) -> io::Result<()> { - self.signal(Some(Signal::SIGTERM))?; - if let Ok(result) = timeout(Duration::from_secs(2), self.wait(child)).await { - result?; - } else { - self.signal(Some(Signal::SIGKILL))?; - timeout(Duration::from_secs(2), self.wait(child)).await.map_err(|_| { - io::Error::new(io::ErrorKind::TimedOut, "owned Tunnel process group did not stop") - })??; + if let Err(error) = self.signal_and_wait(child, Signal::SIGTERM).await { + if error.kind() != io::ErrorKind::TimedOut + && error.raw_os_error() != Some(Errno::EPERM as i32) + { + return Err(error); + } + self.signal_and_wait(child, Signal::SIGKILL).await?; } self.armed = false; Ok(()) } + async fn signal_and_wait(&self, child: &mut Child, signal: Signal) -> io::Result<()> { + let denied = match self.signal(Some(signal)) { + Ok(_) => None, + // Darwin also returns EPERM for a group containing only zombies. + // Reap and wait for ESRCH; EPERM itself never proves termination. + Err(error) if error.raw_os_error() == Some(Errno::EPERM as i32) => Some(error), + Err(error) => return Err(error), + }; + match timeout(Duration::from_secs(2), self.wait(child)).await { + Ok(result) => result, + Err(_) => Err(denied.unwrap_or_else(|| { + io::Error::new(io::ErrorKind::TimedOut, "owned Tunnel process group did not stop") + })), + } + } + fn signal(&self, signal: Option) -> io::Result { match killpg(self.id, signal) { Ok(()) => Ok(true), @@ -47,7 +62,12 @@ impl OwnedGroup { async fn wait(&self, child: &mut Child) -> io::Result<()> { loop { let wrapper_gone = child.try_wait()?.is_some(); - if !self.signal(None)? && wrapper_gone { + let group_gone = match self.signal(None) { + Ok(exists) => !exists, + Err(error) if error.raw_os_error() == Some(Errno::EPERM as i32) => false, + Err(error) => return Err(error), + }; + if group_gone && wrapper_gone { return Ok(()); } tokio::time::sleep(Duration::from_millis(10)).await; From e029438f350188a2b212ccd0352539646fe78753 Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sat, 28 Nov 2026 21:43:13 +0800 Subject: [PATCH 10/43] =?UTF-8?q?feat(acceptance):=20=E5=9C=A8=E7=9C=9F?= =?UTF-8?q?=E5=AE=9E=E6=B5=8F=E8=A7=88=E5=99=A8=E3=80=81=E5=8E=9F=E7=94=9F?= =?UTF-8?q?=E5=AE=89=E8=A3=85=E5=92=8C=E5=8F=91=E8=A1=8C=E5=BD=92=E6=A1=A3?= =?UTF-8?q?=E4=B8=8A=E9=AA=8C=E8=AF=81=E4=BA=A4=E4=BB=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 核对并发编辑的冲突、草稿与重新读取 - 从安装入口检查 Pi 执行和停止,发行上传前检验 SHA、包内容和独立数据库 --- .github/workflows/ci.yml | 7 ++ .github/workflows/pi-runtime.yml | 23 ++++ .github/workflows/release.yml | 4 +- .gitignore | 2 + AGENTS.md | 7 ++ docs/10-prd/acceptance.md | 44 +++++++- native/pi/README.md | 9 ++ .../pi/acceptance/installed-runtime.test.mjs | 100 ++++++++++++++++++ scripts/verify-package.sh | 42 ++++++++ tests/browser/draft.test.mjs | 76 +++++++++++++ tests/browser/package-lock.json | 26 +++++ tests/browser/package.json | 7 ++ 12 files changed, 344 insertions(+), 3 deletions(-) create mode 100644 .github/workflows/pi-runtime.yml create mode 100644 native/pi/acceptance/installed-runtime.test.mjs create mode 100755 scripts/verify-package.sh create mode 100644 tests/browser/draft.test.mjs create mode 100644 tests/browser/package-lock.json create mode 100644 tests/browser/package.json diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index eabf12c2..95239ad3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -33,6 +33,13 @@ jobs: - run: cargo check --locked --all-targets - run: cargo clippy --locked --all-targets -- -D warnings - run: cargo test --locked --all-targets + - 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 diff --git a/.github/workflows/pi-runtime.yml b/.github/workflows/pi-runtime.yml new file mode 100644 index 00000000..65ddd4a0 --- /dev/null +++ b/.github/workflows/pi-runtime.yml @@ -0,0 +1,23 @@ +name: pi-runtime +on: + pull_request: + paths: ['native/pi/**', '.github/workflows/pi-runtime.yml'] + push: + branches: [main] + paths: ['native/pi/**', '.github/workflows/pi-runtime.yml'] +permissions: + contents: read + +jobs: + installed-runtime: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 24.15.0 + - name: Exercise an installed Pi runtime without a model + run: | + export BRAID_TEST_PI_INSTALL="$RUNNER_TEMP/pi-background" + node native/pi/install.mjs "$BRAID_TEST_PI_INSTALL" --plugins background + node --test native/pi/acceptance/installed-runtime.test.mjs diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d2201a23..990600a2 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -33,7 +33,9 @@ jobs: env: BRAID_BUILD_TARGET: ${{ matrix.target }} BRAID_RELEASE_TAG: ${{ github.event.inputs.version || github.ref_name }} - run: scripts/package.sh + run: | + scripts/package.sh + scripts/verify-package.sh dist "$BRAID_RELEASE_TAG" "$BRAID_BUILD_TARGET" - uses: actions/upload-artifact@v4 with: name: release-${{ matrix.target }} 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/docs/10-prd/acceptance.md b/docs/10-prd/acceptance.md index 1c2d8925..e16185b3 100644 --- a/docs/10-prd/acceptance.md +++ b/docs/10-prd/acceptance.md @@ -42,8 +42,8 @@ events are never pass oracles. | 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 回归;独立 OTLP 编码器输入 | 浏览器草稿、并发交互、serve 装配和实际 Harness 控制 | -| 原生执行与材料 | Node 真实进程树;Profile snapshot 和 auth 文件重新读取 | 锁定 Pi 安装、插件组合、真实模型工具调用及跨宿主进程行为 | +| 内建对象与观测存储 | `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` 一致: @@ -63,6 +63,23 @@ node --test native/pi/tests/*.test.mjs 这不改变发行 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 安装变更触发独立的 Linux `pi-runtime` 工作流:按 lock 安装 background +插件,启动安装包中的 Node/Pi,以真实 RPC 读取状态、运行工具、关闭执行并离线 +检查回执。安装步骤需要访问发行站点和 npm;模型未参与。其它插件组合和含模型 +会话各自单独记录。发行工作流在每个平台上传前运行 +`scripts/verify-package.sh DIST RELEASE_TAG RUST_TARGET`;它从校验和指定的 +归档中运行 binary,核对版本、示例配置及迁移后重开的数据库。 + 负向用例应断言错误阶段、类型或关键诊断,并有能够到达该守卫的合法前置条件。 恢复用例应先让真实 owner 写入,关闭并重新打开,再从消费者取回结果。新缺陷 修复保留同一输入下修复前红、修复后绿的证据;缺少这种证据时说明原因。删除或 @@ -89,6 +106,29 @@ 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 issue "$ISSUE" --config "$CONFIG" > "$EVIDENCE/issue-default.md" +"$BRAID_BIN" context pr "$PR" --config "$CONFIG" --page-size 1 > "$EVIDENCE/pr.md" +"$BRAID_BIN" context pr "$PR" --config "$CONFIG" > "$EVIDENCE/pr-default.md" +cmp "$EVIDENCE/issue.md" "$EVIDENCE/issue-default.md" +cmp "$EVIDENCE/pr.md" "$EVIDENCE/pr-default.md" +``` + +比对两种分页得到的字节后,再逐项核对独立预期:完整可见正文和后页标记必须 +出现,折叠/删除评论只含各自的元数据,隐藏标记不出现;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/native/pi/README.md b/native/pi/README.md index c8fb8395..a5322569 100644 --- a/native/pi/README.md +++ b/native/pi/README.md @@ -40,6 +40,15 @@ subagents、background、Context7 和 MCPorter 的局部补丁仅随相应插件 仍包含尚无公开接线点的插件内部修复及 owned process/service 登记。 它们不是无补丁上游发行,不应删掉停止或交接能力来换取零补丁。 +对全新安装仅选择 `background` 后,可直接验证交付的 Node、Pi SDK 与扩展、工具环境和停止回执。 +下面的验收使用临时 HOME、离线模型描述和本地 Bash,不需要模型账号。它也会检查新建 +session 文件、结束 RPC 输入后进程正常退出,以及随后从执行目录取得完整停止回执。 + +```sh +node native/pi/install.mjs "$PWD/runtime/pi-background" --plugins background +BRAID_TEST_PI_INSTALL="$PWD/runtime/pi-background" node --test native/pi/acceptance/installed-runtime.test.mjs +``` + 锁定的 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..7d7fa1a7 --- /dev/null +++ b/native/pi/acceptance/installed-runtime.test.mjs @@ -0,0 +1,100 @@ +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'; + +// 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'); + assert.equal(execFileSync(pi, ['--version'], { cwd: root, env, encoding: 'utf8', timeout: 30000 }).trim(), '1.1.0'); + 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.execution_id, id); + assert.equal(state.managed_state.status, 'quiescent'); + assert.equal(state.braid_native_runtime.schema_version, 1); + assert.equal(state.braid_native_runtime.pi_version, '1.1.0'); + for (const required of ['retry_intent', 'settle_extensions', 'owned_inference', 'managed_execution', 'owned_stop']) { + assert.ok(state.braid_native_runtime.capabilities.includes(required), `missing RPC capability ${required}`); + } + assert.equal(state.braid_native_runtime.execution_id, id); + assert.deepEqual(state.braid_native_runtime.extension_errors, []); + 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); + } + // Read the final receipt produced from persisted registrations after EOF. + const output = execFileSync(node, [ + path.join(install, 'managed.mjs'), 'cleanup', '--execution-dir', directory, '--execution-id', id, + ], { cwd: root, env: { HOME: root, PATH: env.PATH }, encoding: 'utf8', timeout: 30000 }); + const offline = JSON.parse(output); + assert.equal(offline.status, 'stopped', output); + assert.equal(offline.execution_id, id); + assert.equal(offline.scope, 'execution'); + assert.equal(offline.coverage, 'registered-process-groups-and-inherited-execution-markers'); + assert.deepEqual(JSON.parse(fs.readFileSync(path.join(directory, 'execution-stop.json'), 'utf8')), offline); +}); diff --git a/scripts/verify-package.sh b/scripts/verify-package.sh new file mode 100755 index 00000000..52f8c4f5 --- /dev/null +++ b/scripts/verify-package.sh @@ -0,0 +1,42 @@ +#!/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" +braid migrate apply --config "$config" +plan=$(braid migrate plan --config "$config") +printf '%s\n' "$plan" | grep -Fx 'pending: none' diff --git a/tests/browser/draft.test.mjs b/tests/browser/draft.test.mjs new file mode 100644 index 00000000..1de9bc1d --- /dev/null +++ b/tests/browser/draft.test.mjs @@ -0,0 +1,76 @@ +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(); + 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" + } +} From bbc82f687bf265f0212c1ced9e838aa196d1c923 Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sat, 28 Nov 2026 21:43:56 +0800 Subject: [PATCH 11/43] =?UTF-8?q?fix(github):=20=E4=BB=85=E4=BB=8E?= =?UTF-8?q?=E6=9C=AC=E6=AC=A1=E5=8F=AF=E6=AF=94=E7=9A=84=E9=99=90=E9=A2=9D?= =?UTF-8?q?=E5=93=8D=E5=BA=94=E8=AE=A1=E7=AE=97=E7=94=A8=E9=87=8F=E5=8F=98?= =?UTF-8?q?=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 用缺失 used、reset 及跨窗口样本验证限额证据 --- src/github/budget_tests.rs | 6 --- src/github/rate_limit.rs | 78 +++++++++++++++++++------------------- 2 files changed, 38 insertions(+), 46 deletions(-) diff --git a/src/github/budget_tests.rs b/src/github/budget_tests.rs index a6917368..f706441c 100644 --- a/src/github/budget_tests.rs +++ b/src/github/budget_tests.rs @@ -258,10 +258,4 @@ async fn graphql_transport_failure_is_deferred_without_repeated_network_requests Err(GitHubError::Delayed(_)) )); disconnect.await.unwrap(); - let installation = limits.installation(1); - let mut budget = installation.lock().await; - for _ in 0..100 { - assert!(budget.check(rate_limit::now(), true).is_err()); - } - assert_eq!(budget.requests, 1, "local paused checks do not count or issue requests"); } diff --git a/src/github/rate_limit.rs b/src/github/rate_limit.rs index 392bdbb6..5f0032d5 100644 --- a/src/github/rate_limit.rs +++ b/src/github/rate_limit.rs @@ -92,10 +92,12 @@ impl Budget { let delta = comparable .then(|| used.zip(self.used).and_then(|(new, old)| new.checked_sub(old))) .flatten(); - self.resource = resource; - self.used = used.or(self.used); + // Admission can retain the last reset hint, but a delta needs two + // consecutive complete samples from the same resource and window. + self.resource = reset.and(resource); + self.used = used; self.remaining = number("x-ratelimit-remaining").or(self.remaining); - self.reset = number("x-ratelimit-reset").or(self.reset); + self.reset = reset.or(self.reset); delta } @@ -126,20 +128,6 @@ impl Budget { mod tests { use super::*; - #[tokio::test] - async fn installation_sharing_and_isolation() { - let limits = RateLimits::default(); - let a = limits.installation(1); - let same = limits.installation(1); - let other = limits.installation(2); - a.lock().await.defer(100, Some(60)); - assert!(same.lock().await.admit(159, false).is_err()); - assert!(other.lock().await.admit(101, false).is_ok()); - assert!(same.lock().await.admit(160, false).is_ok()); - same.lock().await.success(); - assert!(a.lock().await.admit(161, false).is_ok()); - } - #[test] fn primary_reset_reserve_and_used_delta() { let mut budget = Budget::default(); @@ -205,29 +193,39 @@ mod window_tests { use super::*; #[test] - fn used_delta_is_unknown_when_consecutive_responses_lack_resource() { - let mut budget = Budget::default(); - let mut headers = HeaderMap::new(); - headers.insert("x-ratelimit-used", "10".parse().unwrap()); - headers.insert("x-ratelimit-reset", "500".parse().unwrap()); - assert_eq!(budget.observe(&headers), None); - headers.insert("x-ratelimit-used", "12".parse().unwrap()); - assert_eq!(budget.observe(&headers), None); - } - - #[test] - fn used_delta_is_unknown_across_windows_and_resources() { + fn used_delta_requires_two_comparable_complete_header_samples() { + fn headers(used: Option, reset: Option, resource: Option<&str>) -> HeaderMap { + let mut headers = HeaderMap::new(); + if let Some(used) = used { + headers.insert("x-ratelimit-used", used.into()); + } + if let Some(reset) = reset { + headers.insert("x-ratelimit-reset", reset.into()); + } + if let Some(resource) = resource { + headers.insert("x-ratelimit-resource", resource.parse().unwrap()); + } + headers + } let mut budget = Budget::default(); - let mut headers = HeaderMap::new(); - headers.insert("x-ratelimit-used", "10".parse().unwrap()); - headers.insert("x-ratelimit-reset", "500".parse().unwrap()); - headers.insert("x-ratelimit-resource", "graphql".parse().unwrap()); - assert_eq!(budget.observe(&headers), None); - headers.insert("x-ratelimit-used", "12".parse().unwrap()); - assert_eq!(budget.observe(&headers), Some(2)); - headers.insert("x-ratelimit-reset", "600".parse().unwrap()); - assert_eq!(budget.observe(&headers), None); - headers.insert("x-ratelimit-resource", "core".parse().unwrap()); - assert_eq!(budget.observe(&headers), None); + for (used, reset, resource, delta) in [ + (Some(10), Some(500), None, None), + (Some(12), Some(500), None, None), + (Some(12), Some(500), Some("graphql"), None), + (Some(17), Some(500), Some("graphql"), Some(5)), + (Some(20), Some(600), Some("graphql"), None), + (Some(22), Some(600), Some("core"), None), + (None, Some(600), Some("core"), None), + (Some(25), Some(600), Some("core"), None), + (Some(26), None, Some("core"), None), + (Some(29), Some(600), Some("core"), None), + (Some(31), Some(600), Some("core"), Some(2)), + ] { + assert_eq!( + budget.observe(&headers(used, reset, resource)), + delta, + "used={used:?}, reset={reset:?}, resource={resource:?}" + ); + } } } From 7f2e7da85a594f4dccaf766086d9ac7157d36fb1 Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sat, 28 Nov 2026 21:43:56 +0800 Subject: [PATCH 12/43] =?UTF-8?q?fix(platform):=20=E4=BC=A0=E6=92=AD?= =?UTF-8?q?=E7=BB=88=E6=80=81=E5=9B=9E=E6=89=A7=E6=8C=81=E4=B9=85=E5=8C=96?= =?UTF-8?q?=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/platform/objects.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/platform/objects.rs b/src/platform/objects.rs index 2b89dd20..1ef6552d 100644 --- a/src/platform/objects.rs +++ b/src/platform/objects.rs @@ -1178,7 +1178,8 @@ fn settle_merge( result: Some(serde_json::to_value(merge)?), error: None, }, - ) + )?; + Ok(()) } fn was_merged(connection: &Connection, number: u64) -> Result { From 50d183218b60b071b9b86cf5e5da1bfd6805b204 Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sat, 28 Nov 2026 21:43:56 +0800 Subject: [PATCH 13/43] =?UTF-8?q?ref(operations):=20=E4=BB=8E=E7=9C=9F?= =?UTF-8?q?=E5=AE=9E=20CLI=E3=80=81=E6=B3=A8=E5=86=8C=E8=A1=A8=E4=B8=8E=20?= =?UTF-8?q?Git=20=E5=B7=A5=E4=BD=9C=E6=A0=91=E9=AA=8C=E8=AF=81=E6=93=8D?= =?UTF-8?q?=E4=BD=9C=E5=A5=91=E7=BA=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 合并重复入口,核对实例选择、实际持久状态及失败阶段 --- src/health/tests.rs | 34 +++- src/home.rs | 36 +---- src/worktree.rs | 3 + tests/worktree.rs => src/worktree/tests.rs | 48 +++--- tests/assignment.rs | 180 ++++++++------------- tests/headless_setup.rs | 35 ++-- tests/multi_repo.rs | 82 ++++++++++ tests/provider_config.rs | 41 +++-- 8 files changed, 264 insertions(+), 195 deletions(-) rename tests/worktree.rs => src/worktree/tests.rs (56%) diff --git a/src/health/tests.rs b/src/health/tests.rs index 5907d1b0..6d9287cf 100644 --- a/src/health/tests.rs +++ b/src/health/tests.rs @@ -59,7 +59,39 @@ async fn health_tracks_each_repository_and_kind_independently() { reports.push(("owner/one", Issue, None)); let recovered = aggregate(&reports).await; assert_eq!(recovered.provider, "connected"); - assert_eq!(recovered.last_error, None); +} + +#[tokio::test] +async fn provider_recovery_clears_its_own_diagnostic_and_preserves_another_workers_error() { + for other_error in [None, Some("reconciliation failed")] { + let health = health("builtin"); + let (_stop, shutdown) = watch::channel(false); + let (availability, reports) = watch::channel(ProviderAvailability::Starting); + let worker = tokio::spawn(provider_health_worker(health.clone(), reports, shutdown)); + availability.send_replace(ProviderAvailability::Unavailable { + since: tokio::time::Instant::now(), + error: "provider failed".into(), + }); + // The projection must have published the failure before the recovery + // report: a watch receiver can legally coalesce adjacent updates. + tokio::time::timeout(Duration::from_secs(2), async { + while health.snapshot().provider != "unavailable" { + tokio::task::yield_now().await; + } + }) + .await + .expect("health must publish the initial provider failure"); + assert_eq!(health.snapshot().last_error.as_deref(), Some("provider failed")); + if let Some(other) = other_error { + health.update(|snapshot| snapshot.last_error = Some(other.into())); + } + availability.send_replace(ProviderAvailability::Connected); + drop(availability); + worker.await.unwrap(); + let recovered = health.snapshot(); + assert!(recovered.ready); + assert_eq!(recovered.last_error.as_deref(), other_error); + } } #[tokio::test] diff --git a/src/home.rs b/src/home.rs index 0407ccd6..5ad18343 100644 --- a/src/home.rs +++ b/src/home.rs @@ -78,17 +78,13 @@ pub struct UserHome { impl UserHome { /// Resolve the user root from CLI override, env, or default `~/.braid`. pub fn resolve(cli_override: Option<&Path>) -> Result { - if let Some(path) = cli_override { - return Self::new(expand_home(path)?); - } - if let Some(env) = std::env::var_os(BRAID_USER_HOME_ENV) { - return Self::new(PathBuf::from(env)); - } - Self::new(default_user_home()?) - } - - #[allow(clippy::unnecessary_wraps)] - pub fn new(root: PathBuf) -> Result { + let root = if let Some(path) = cli_override { + expand_home(path)? + } else if let Some(env) = std::env::var_os(BRAID_USER_HOME_ENV) { + PathBuf::from(env) + } else { + default_user_home()? + }; let root = if root.is_absolute() { root } else { @@ -306,23 +302,6 @@ pub struct InstanceEntry { pub fn resolve_config_path( cli_config: Option<&Path>, cli_instance: Option<&str>, -) -> Result { - let user = UserHome::resolve(None)?; - resolve_config_path_with_user_home(&user, cli_config, cli_instance) -} - -/// Resolve a config file path from the standard precedence chain, using a -/// caller-supplied user home for testability. -/// -/// Precedence: -/// 1. `cli_config` -/// 2. `BRAID_INSTANCE_HOME` -/// 3. `cli_instance` / `BRAID_INSTANCE` -/// 4. registry default (`default_instance`, or single instance) -pub(crate) fn resolve_config_path_with_user_home( - user: &UserHome, - cli_config: Option<&Path>, - cli_instance: Option<&str>, ) -> Result { if let Some(path) = cli_config { return Ok(path.to_path_buf()); @@ -330,6 +309,7 @@ pub(crate) fn resolve_config_path_with_user_home( if let Some(env) = std::env::var_os(BRAID_INSTANCE_HOME_ENV) { return Ok(PathBuf::from(env).join("config.toml")); } + let user = UserHome::resolve(None)?; let registry = user.load_registry()?; let key = if let Some(key) = cli_instance { 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/tests/assignment.rs b/tests/assignment.rs index cf3eeadb..0fb59765 100644 --- a/tests/assignment.rs +++ b/tests/assignment.rs @@ -1,8 +1,4 @@ -use std::{ - fs, - path::{Path, PathBuf}, - process::Command, -}; +use std::{fs, process::Command}; fn braid() -> Command { Command::new(env!("CARGO_BIN_EXE_braid")) @@ -16,83 +12,25 @@ 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)); +#[test] +fn assignment_reactivation_queues_one_wake_and_preserves_the_blocked_generation() { + 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 +38,58 @@ fn assignment_reactivation_queues_a_new_generation_for_a_blocked_issue() { ) .expect("seed blocked assignment"); - let output = braid() - .args(["assignment", "reactivate", "1", "--kind", "issue", "--config"]) - .arg(&config) - .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)); - - 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); - - 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); + let mut first_receipt = None; + for _ in 0..2 { + let output = braid() + .args(["assignment", "reactivate", "1", "--kind", "issue", "--config"]) + .arg(&config) + .output() + .expect("reactivate blocked assignment"); + 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(); } 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 2419193d..4a2abb14 100644 --- a/tests/multi_repo.rs +++ b/tests/multi_repo.rs @@ -102,3 +102,85 @@ fn multi_repository_config_requires_repo_scoped_profiles() { } 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(["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); + let output = command().args(["doctor", "--json"]).output().unwrap(); + assert!(!output.status.success()); + 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 01ef1687..5273dc18 100644 --- a/tests/provider_config.rs +++ b/tests/provider_config.rs @@ -37,8 +37,15 @@ fn provider_route_inputs_are_validated_at_cli_and_config_boundaries() { .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"); @@ -87,22 +94,19 @@ fn provider_route_inputs_are_validated_at_cli_and_config_boundaries() { 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) @@ -466,9 +470,12 @@ fn provider_import_auth_converts_pi_credentials() { assert!(!output.status.success()); assert!(stderr(&output).contains("has no credential for \"missing\""), "{}", stderr(&output)); + 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)] { @@ -479,6 +486,8 @@ fn provider_import_auth_converts_pi_credentials() { 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. From 613037b1eb323c11161952644ad590a07311b459 Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sat, 28 Nov 2026 21:47:19 +0800 Subject: [PATCH 14/43] =?UTF-8?q?fix(group):=20=E6=92=A4=E9=94=80=E6=B4=BB?= =?UTF-8?q?=E5=8A=A8=E8=81=8C=E8=B4=A3=E6=97=B6=E7=AD=89=E5=BE=85=E5=8E=9F?= =?UTF-8?q?=E4=BB=A3=E5=8E=9F=E7=94=9F=E6=89=A7=E8=A1=8C=E4=B8=8E=E5=86=99?= =?UTF-8?q?=E5=85=A5=E8=B5=84=E6=A0=BC=E6=94=B6=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 从运行中的 worker 执行去抖和停止,事务按原 assignment 结算,未确认停止继续保留义务 - 重开 actor 验证停机依据,迁移保留历史数据并移除观察测试专用入口 --- docs/20-product-tdd/app-server.md | 3 +- docs/20-product-tdd/lifecycle.md | 18 +- src/agent_session.rs | 11 -- src/group/continuous_tests.rs | 184 +++++++++++++++++-- src/group/issue_agent.rs | 59 +----- src/group/pr_agent.rs | 24 +-- src/group/worker.rs | 53 +++++- src/provider/session.rs | 14 -- src/runtime/builtin.rs | 56 ++++-- src/store/mod.rs | 173 +++++++---------- src/store/observations.rs | 5 +- src/store/reconciliation.rs | 65 ++++--- src/store/schema_tests.rs | 38 ++++ src/store/unassignment.rs | 72 ++++++++ src/writer/tests/continuous_collaboration.rs | 75 +++----- src/writer/tests/observation_recovery.rs | 7 +- src/writer/tests/semantic_contract.rs | 4 +- src/writer/tests/turn_start.rs | 31 ++-- 18 files changed, 535 insertions(+), 357 deletions(-) create mode 100644 src/store/unassignment.rs diff --git a/docs/20-product-tdd/app-server.md b/docs/20-product-tdd/app-server.md index 609a2fc1..5cfdc50e 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 进程退出只影响所属句柄。释放旧句柄会取消旧监听任务, diff --git a/docs/20-product-tdd/lifecycle.md b/docs/20-product-tdd/lifecycle.md index 61a113f1..ddd97ebd 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,11 @@ 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 确认原生会话停止和平台执行权限撤销后,才将该代记为 `retired` 并终结 + 尚在运行的 turn。关闭失败保留撤销事件和原代。重新指派创建新一代及新会话。 - 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 +223,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/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/group/continuous_tests.rs b/src/group/continuous_tests.rs index 5ef27bc1..8d6425ae 100644 --- a/src/group/continuous_tests.rs +++ b/src/group/continuous_tests.rs @@ -19,6 +19,7 @@ struct Captured { close_error: Mutex>, close_attempts: Mutex>, closed: tokio::sync::Notify, + steered: tokio::sync::Notify, } struct Factory(Arc); struct Session { @@ -90,13 +91,11 @@ impl AgentSession for Session { _msg: String, _expected: &str, ) -> Result { + self.captured.steered.notify_one(); Err(self.captured.steer_error.lock().unwrap().clone().unwrap_or_else(|| { SessionError::Failed("revision must wait for the safe boundary".into()) })) } - async fn interrupt(&self) -> Result<(), SessionError> { - Ok(()) - } } fn revision() -> IngressEvent { IngressEvent { @@ -211,7 +210,10 @@ async fn soft_pressure_reset_replaces_memory_and_delivers_input_with_publication let publisher = f.store.acquire_runtime_lease("runtime".into(), "publisher".into(), 60).unwrap(); let error = f.store.claim_github_write(publisher.clone()).unwrap_err(); - assert!(matches!(error, crate::store::StoreError::Sqlite(ref sql) if sql.to_string().contains("unavailable publisher")), "{error}"); + assert!( + matches!(error, crate::store::StoreError::Sqlite(ref sql) if sql.to_string().contains("unavailable publisher")), + "{error}" + ); f.db().execute_batch("DROP TRIGGER outbox_offline").unwrap(); let status = f.store.claim_github_write(publisher.clone()).unwrap().unwrap(); assert!(status.content.contains("complete Context without truncation")); @@ -401,11 +403,21 @@ async fn persisted_idle_reset_uses_only_confirmed_native_stop_after_restart() { let captured = Arc::new(Captured::default()); let (github, http) = issue_context_server("Persisted revised contract").await; let collaboration = CollaborationBackend::GitHub(github); - let spec = GroupSpec::new(GroupKind::Issue, &f.config, &f.store, "owner/repository").unwrap(); - f.store.ingest_event(revision(), SchedulerPolicy { quiet_seconds: 0, event_threshold: 1 }).unwrap(); - let reset = f.store.begin_context_reset(None, "issue".into(), "issue-codex".into()).unwrap().unwrap(); + let spec = + GroupSpec::new(GroupKind::Issue, &f.config, &f.store, "owner/repository").unwrap(); + f.store + .ingest_event(revision(), SchedulerPolicy { quiet_seconds: 0, event_threshold: 1 }) + .unwrap(); + let reset = f + .store + .begin_context_reset(None, "issue".into(), "issue-codex".into()) + .unwrap() + .unwrap(); assert_eq!(reset.active_turn_id, None); - assert_eq!(f.store.runtime_status().unwrap().agent_groups[0].session_lifecycle.as_deref(), Some("reset_pending")); + assert_eq!( + f.store.runtime_status().unwrap().agent_groups[0].session_lifecycle.as_deref(), + Some("reset_pending") + ); if confirm_stop { let driver = worker::GroupDriver { store: &f.store, @@ -414,12 +426,20 @@ async fn persisted_idle_reset_uses_only_confirmed_native_stop_after_restart() { spec: &spec, sessions: SessionManager::new(Arc::new(Factory(captured.clone()))), }; - driver.sessions.resume("provider".into(), spec.profile.clone(), "instructions".into()).await.unwrap(); + driver + .sessions + .resume("provider".into(), spec.profile.clone(), "instructions".into()) + .await + .unwrap(); assert!(driver.quiesce_session("provider").await.unwrap()); assert_eq!(*captured.close_attempts.lock().unwrap(), ["provider"]); } drop(f.store); - let store = StoreActor::start(f.config.runtime.database().into(), f.config.runtime.backups().into()).unwrap(); + let store = StoreActor::start( + f.config.runtime.database().into(), + f.config.runtime.backups().into(), + ) + .unwrap(); let driver = worker::GroupDriver { store: &store, config: &f.config, @@ -441,7 +461,13 @@ async fn persisted_idle_reset_uses_only_confirmed_native_stop_after_restart() { assert_eq!(captured.inputs.lock().unwrap().len(), 1); } else { assert_eq!(status.context_resets[0].lifecycle, "blocked"); - assert!(status.agent_groups[0].context_error.as_deref().unwrap().contains("no stop evidence")); + assert!( + status.agent_groups[0] + .context_error + .as_deref() + .unwrap() + .contains("no stop evidence") + ); assert!(captured.memory.lock().unwrap().is_empty()); assert!(driver.start_next_agent_turn().await.is_none()); } @@ -675,10 +701,13 @@ async fn builtin_turn_runs_without_writer_service_and_cannot_mint_after_reassign listen: address.to_string(), }; let offline = Arc::new(AtomicBool::new(true)); + let fence_offline = Arc::new(AtomicBool::new(false)); let routes = crate::platform::router(&platform).unwrap().layer(axum::middleware::from_fn({ let offline = Arc::clone(&offline); + let fence_offline = Arc::clone(&fence_offline); move |request: axum::extract::Request, next: axum::middleware::Next| { let offline = Arc::clone(&offline); + let fence_offline = Arc::clone(&fence_offline); async move { use axum::response::IntoResponse as _; if request.uri().path().starts_with("/api/platform/grants") @@ -686,6 +715,11 @@ async fn builtin_turn_runs_without_writer_service_and_cannot_mint_after_reassign { return StatusCode::SERVICE_UNAVAILABLE.into_response(); } + if request.uri().path() == "/api/platform/executions/fence" + && fence_offline.load(Ordering::Relaxed) + { + return StatusCode::SERVICE_UNAVAILABLE.into_response(); + } next.run(request).await } } @@ -694,6 +728,8 @@ async fn builtin_turn_runs_without_writer_service_and_cannot_mint_after_reassign let mut config = f.config.clone(); config.github = None; + config.profiles.iter_mut().find(|profile| profile.id == "issue-codex").unwrap().workspace = + Some(source.clone()); config.builtin = Some(crate::config::BuiltinConfig { repository: platform.repository.clone(), endpoint: format!("http://{address}").parse().unwrap(), @@ -741,6 +777,7 @@ async fn builtin_turn_runs_without_writer_service_and_cannot_mint_after_reassign platform.reply(issue.number, "Run this turn", "human", None).unwrap(); for pending in platform.events(cursor, 100).unwrap() { store.ingest_builtin_event(pending.event, policy, pending.event_id).unwrap(); + cursor = pending.event_id; } store.advance_scheduler().unwrap(); @@ -778,9 +815,132 @@ async fn builtin_turn_runs_without_writer_service_and_cannot_mint_after_reassign let error = client.writer_grant(writer.clone()).await.unwrap_err(); assert!(error.to_string().contains("writer authority changed"), "{error:#}"); offline.store(true, Ordering::Relaxed); - driver.require_quiesced(&writer.session_id, false).await.unwrap(); + // An immutable unassignment still retires the old generation after a + // reassignment. Native close alone cannot replace the platform's fence. + for pending in platform.events(cursor, 100).unwrap() { + store.ingest_builtin_event(pending.event, policy, pending.event_id).unwrap(); + } + let revoked = || crate::store::UnassignmentTarget::RunningTurn(writer.turn_id.clone()); + fence_offline.store(true, Ordering::Relaxed); + let error = driver.settle_unassignment(revoked()).await.unwrap_err(); + assert!(error.to_string().contains("execution fence unconfirmed"), "{error:#}"); + assert_eq!(*captured.close_attempts.lock().unwrap(), ["provider"]); + assert_eq!(store.runtime_status().unwrap().agent_groups[0].assignment_lifecycle, "active"); + fence_offline.store(false, Ordering::Relaxed); + assert!(driver.settle_unassignment(revoked()).await.unwrap()); + assert_eq!(*captured.close_attempts.lock().unwrap(), ["provider"]); + assert_eq!(store.runtime_status().unwrap().agent_groups[0].assignment_lifecycle, "retired"); client.fence_all_executions().await.unwrap(); let fenced = client.writer_grant(writer).await.unwrap_err(); assert!(fenced.to_string().contains("no current writer authority")); + let reassignment = + store.assignment_candidates("test-space".into(), "issue".into(), 1).unwrap().pop().unwrap(); + assert_eq!(reassignment.action, "assign"); + driver.materialize_issue_assignment(reassignment).await.unwrap(); + let groups = store.runtime_status().unwrap().agent_groups; + assert_eq!(groups.len(), 2); + let retired = groups.iter().find(|group| group.assignment_generation == 1).unwrap(); + let current = groups.iter().find(|group| group.assignment_generation == 2).unwrap(); + assert_eq!(retired.assignment_lifecycle, "retired"); + assert_eq!(current.assignment_lifecycle, "active"); + assert_eq!(current.provider_session_id.as_deref(), Some("fresh-provider")); + assert_eq!(captured.memory.lock().unwrap().len(), 1); + http.abort(); +} + +#[tokio::test] +async fn worker_stops_a_running_unassigned_issue_only_after_its_quiet_window() { + use sha2::{Digest as _, Sha256}; + use tokio::time::{Duration, timeout}; + + let f = Fixture::new(true); + let config = f.config.clone(); + let spec = GroupSpec::new(GroupKind::Issue, &config, &f.store, "owner/repository").unwrap(); + std::fs::create_dir_all(spec.profile.workspace()).unwrap(); + let instructions = provider::issue_system_prompt(&config, &spec.profile, 1); + f.db() + .execute( + "UPDATE provider_sessions SET instruction_revision=?1", + [hex::encode(Sha256::digest(instructions.as_bytes()))], + ) + .unwrap(); + let captured = Arc::new(Captured::default()); + let (github, http) = issue_context_server("Current instructions").await; + let store = Arc::new( + StoreActor::start(config.runtime.database().into(), config.runtime.backups().into()) + .unwrap(), + ); + let policy = SchedulerPolicy { quiet_seconds: 0, event_threshold: 1 }; + let mut wake = revision(); + wake.kind = EventKind::Wake; + wake.cross_surface_invalidation = false; + store.ingest_event(wake, policy).unwrap(); + let (shutdown, stop) = tokio::sync::watch::channel(false); + let (reports, _receiver) = tokio::sync::mpsc::channel(8); + let worker = tokio::spawn(agent_group_worker( + Arc::clone(&store), + github, + config, + spec, + Arc::new(Factory(Arc::clone(&captured))), + reports, + stop, + )); + let limit = Duration::from_secs(5); + timeout(limit, async { + while !f.db().query_row("SELECT EXISTS(SELECT 1 FROM turns WHERE provider_turn_id='after-revision' AND lifecycle='running')", [], |row| row.get::<_, bool>(0)).unwrap() { + tokio::time::sleep(Duration::from_millis(20)).await; + } + }).await.expect("the provider must start a real turn before unassignment"); + let mut unassign = revision(); + unassign.delivery_guid = "assignment-removed".into(); + unassign.identity = crate::store::ChangeIdentity::Occurrence; + unassign.kind = EventKind::Unassign; + unassign.action = Some("unassigned".into()); + unassign.cross_surface_invalidation = false; + unassign.requires_attention = false; + let event = store.ingest_event(unassign, policy).unwrap().event_id.unwrap(); + + // A second provider input acknowledges a worker tick inside the window. + let mut urgent = revision(); + urgent.delivery_guid = "urgent-while-assigned".into(); + urgent.object_version = Some("v3".into()); + urgent.kind = EventKind::Wake; + urgent.cross_surface_invalidation = false; + urgent.mention_candidate = true; + let mention = store.ingest_event(urgent, policy).unwrap().event_id.unwrap(); + store.resolve_mention(mention, true, policy).unwrap(); + timeout(limit, captured.steered.notified()).await.expect("turn stays active during debounce"); + assert!(captured.close_attempts.lock().unwrap().is_empty()); + + *captured.close_error.lock().unwrap() = + Some(SessionError::Unknown("native task still alive".into())); + f.db() + .execute("UPDATE events SET observed_at='2000-01-01T00:00:00Z' WHERE event_id=?1", [&event]) + .unwrap(); + timeout(limit, captured.closed.notified()) + .await + .expect("settled unassignment must stop a running native turn"); + assert_eq!(store.runtime_status().unwrap().agent_groups[0].assignment_lifecycle, "active"); + *captured.close_error.lock().unwrap() = None; + timeout(limit, async { + while store.runtime_status().unwrap().agent_groups[0].assignment_lifecycle != "retired" { + tokio::time::sleep(Duration::from_millis(20)).await; + } + }) + .await + .expect("confirmed native stop must retire the generation"); + let terminal: String = f + .db() + .query_row( + "SELECT lifecycle FROM turns WHERE provider_turn_id='after-revision'", + [], + |row| row.get(0), + ) + .unwrap(); + assert_eq!(terminal, "interrupted"); + assert_eq!(captured.inputs.lock().unwrap().len(), 1); + shutdown.send(true).unwrap(); + worker.await.unwrap().unwrap(); http.abort(); } diff --git a/src/group/issue_agent.rs b/src/group/issue_agent.rs index 5118eda8..7f5ba616 100644 --- a/src/group/issue_agent.rs +++ b/src/group/issue_agent.rs @@ -255,60 +255,6 @@ pub(super) async fn resolve_issue_worktree_ref( } impl GroupDriver<'_> { - /// Retire an explicitly unassigned built-in generation. GitHub unassignments - /// first check current assignees and debounce because webhook assignment flapping - /// can be superseded; built-in events record an authoritative responsibility change. - pub(super) async fn settle_issue_unassignment( - &self, - candidate: AssignmentCandidate, - ) -> Result<()> { - let store = self.store; - let github = self.collaboration; - let config = self.config; - let sessions = &self.sessions; - let repository = if github.is_builtin() { - RepositoryName::local(&candidate.repository) - } else { - candidate.repository.parse::()? - }; - if !github.is_builtin() { - let locator = WorkItemLocator { repository, number: candidate.number }; - let issue = github.materialize_issue(&locator).await?; - if issue - .assignees - .iter() - .any(|assignee| github.assignee_matches(assignee, &self.spec.profile.id)) - { - store.ignore_assignment_event(candidate.event_id)?; - return Ok(()); - } - } - if github.is_builtin() { - for active in - store.provider_resume_candidates(self.spec.profile.id.clone(), "issue".into())? - { - if active.number == candidate.number { - self.quiesce_session(&active.provider_session_id).await?; - } - } - } - let outcome = store.retire_unassigned_work_item( - candidate.event_id, - if github.is_builtin() { 0 } else { config.scheduler.quiet_seconds }, - )?; - if !outcome.settled { - return Ok(()); - } - if let Some(provider_session_id) = &outcome.fenced_provider_session - && let Some(session) = sessions.get(provider_session_id).await - && let Err(error) = session.interrupt().await - { - tracing::warn!(%error, "cannot interrupt retired Issue Agent turn"); - } - tracing::info!(issue = candidate.number, "retired unassigned Issue Agent Group"); - Ok(()) - } - pub(super) async fn materialize_next_issue_assignment(&self) { let store = self.store; let candidate = @@ -321,7 +267,10 @@ impl GroupDriver<'_> { }; let Some(candidate) = candidate else { return }; if candidate.action == "unassign" { - if let Err(error) = self.settle_issue_unassignment(candidate).await { + if let Err(error) = self + .settle_unassignment(crate::store::UnassignmentTarget::Event(candidate.event_id)) + .await + { tracing::error!(%error, "cannot settle Issue unassignment"); } return; diff --git a/src/group/pr_agent.rs b/src/group/pr_agent.rs index 6bfaef53..4808b75e 100644 --- a/src/group/pr_agent.rs +++ b/src/group/pr_agent.rs @@ -298,7 +298,10 @@ impl GroupDriver<'_> { }; let Some(candidate) = candidate else { return }; if candidate.action == "unassign" && self.collaboration.is_builtin() { - if let Err(error) = self.settle_builtin_pr_unassignment(candidate).await { + if let Err(error) = self + .settle_unassignment(crate::store::UnassignmentTarget::Event(candidate.event_id)) + .await + { tracing::error!(%error, "cannot settle built-in PR unassignment"); } return; @@ -308,25 +311,6 @@ impl GroupDriver<'_> { } } - async fn settle_builtin_pr_unassignment(&self, candidate: AssignmentCandidate) -> Result<()> { - // The immutable unassign event retires this generation even if a later - // assignment has already restored the same actor in the current snapshot. - for active in - self.store.provider_resume_candidates(self.spec.profile.id.clone(), "pr".into())? - { - if active.number == candidate.number { - self.quiesce_session(&active.provider_session_id).await?; - } - } - let outcome = self.store.retire_unassigned_work_item(candidate.event_id, 0)?; - if outcome.settled - && let Some(session) = outcome.fenced_provider_session - { - self.quiesce_session(&session).await?; - } - Ok(()) - } - pub(super) async fn materialize_pr_assignment( &self, candidate: AssignmentCandidate, diff --git a/src/group/worker.rs b/src/group/worker.rs index c1e0f266..1b440e67 100644 --- a/src/group/worker.rs +++ b/src/group/worker.rs @@ -172,6 +172,35 @@ impl GroupDriver<'_> { } } + pub(super) async fn settle_unassignment( + &self, + target: crate::store::UnassignmentTarget, + ) -> Result { + let builtin = self.collaboration.is_builtin(); + let quiet = if builtin { 0 } else { self.config.scheduler.quiet_seconds }; + let Some(change) = self.store.due_unassignment(target, quiet)? else { return Ok(false) }; + if !builtin { + let locator = crate::github::WorkItemLocator { + repository: change.repository.parse()?, + number: change.number, + }; + let issue = self.collaboration.materialize_issue(&locator).await?; + if issue + .assignees + .iter() + .any(|actor| self.collaboration.assignee_matches(actor, &self.spec.profile.id)) + { + self.store.ignore_assignment_event(change.event_id)?; + return Ok(false); + } + } + for (session, stopped) in &change.sessions { + self.require_quiesced(session, *stopped).await?; + } + self.store.retire_unassigned_work_item(change)?; + Ok(true) + } + pub(super) async fn retain_sessions( &self, retained: &HashSet, @@ -301,6 +330,9 @@ impl GroupDriver<'_> { ) { let store = self.store; let mut running: Option = None; + // A native close may end the event stream while its independent + // platform fence is still being retried. + let mut settling_unassignment = false; let mut tick = tokio::time::interval(Duration::from_millis(250)); tick.set_missed_tick_behavior(MissedTickBehavior::Delay); let mut recovery = tokio::time::Instant::now(); @@ -318,7 +350,7 @@ impl GroupDriver<'_> { } else { std::future::pending().await } - }, if running.is_some() => { + }, if running.is_some() && !settling_unassignment => { match event { Ok(crate::agent_session::SessionEvent::TurnStarted { provider_turn_id }) => { tracing::debug!(%provider_turn_id, "AgentSession turn started"); @@ -373,7 +405,7 @@ impl GroupDriver<'_> { } } _ = tick.tick() => { - if running.as_ref().is_some_and(|active| active.events.is_closed()) { + if !settling_unassignment && running.as_ref().is_some_and(|active| active.events.is_closed()) { self.fence_running(&mut running, "AgentSession event stream closed").await; } // A closed finite root fences new execution; shutdown owns physical cleanup. @@ -398,6 +430,23 @@ impl GroupDriver<'_> { recovery = tokio::time::Instant::now() + Duration::from_secs(2); } if let Some(active) = &mut running { + if self.spec.kind == GroupKind::Issue || self.collaboration.is_builtin() { + let target = crate::store::UnassignmentTarget::RunningTurn(active.claim.turn_id.clone()); + match self.settle_unassignment(target).await { + Ok(true) => { + settling_unassignment = false; + running = None; + continue; + } + Ok(false) => { settling_unassignment = false; } + Err(error) => { + settling_unassignment = true; + tracing::warn!(%error, "cannot settle active unassignment"); + self.publish_turn_error(&active.claim, "unknown", &error.to_string()); + continue; + } + } + } self.begin_active_context_reset(active).await; if active.reset_id.is_none() && let Some(reason) = self.forward_urgent_steer(active).await { diff --git a/src/provider/session.rs b/src/provider/session.rs index 17c2f69d..db38a4eb 100644 --- a/src/provider/session.rs +++ b/src/provider/session.rs @@ -556,20 +556,6 @@ impl AgentSession for ProviderAgentSession { } } } - - async fn interrupt(&self) -> Result<(), SessionError> { - let _command = self.commands.lock().await; - let (thread, turn) = { - let inner = self.inner.lock().await; - (inner.thread_id.clone(), inner.current_turn_id.clone()) - }; - match (thread, turn) { - (Some(thread), Some(turn)) => { - self.provider.interrupt(&thread, &turn).await.map_err(map_provider_error) - } - _ => Ok(()), - } - } } pub(super) fn map_provider_error(error: ProviderError) -> SessionError { diff --git a/src/runtime/builtin.rs b/src/runtime/builtin.rs index 579a2845..4a8e3010 100644 --- a/src/runtime/builtin.rs +++ b/src/runtime/builtin.rs @@ -904,8 +904,6 @@ mod tests { PlatformConfig, objects::{CommandRequest, ControlReceipt, ObjectCommand, PlatformObjects}, }; - use std::sync::atomic::{AtomicUsize, Ordering}; - use tokio::sync::Notify; const DELIVERY_REF: &str = "refs/heads/delivery"; let fixture = crate::writer::tests::Fixture::new(false); @@ -931,25 +929,21 @@ mod tests { backups: runtime.join("platform-backups"), listen: address.to_string(), }; - let two_open_polls = Arc::new(Notify::new()); + let (completed_reads, mut boundary_reads) = tokio::sync::mpsc::unbounded_channel(); let routes = - crate::platform::router(&declaration).unwrap().layer(axum::middleware::from_fn({ - let two_open_polls = Arc::clone(&two_open_polls); - let boundary_reads = Arc::new(AtomicUsize::new(0)); + crate::platform::router(&declaration).unwrap().layer(axum::middleware::from_fn( move |request: axum::extract::Request, next: axum::middleware::Next| { - let two_open_polls = Arc::clone(&two_open_polls); - let boundary_reads = Arc::clone(&boundary_reads); + let completed_reads = completed_reads.clone(); async move { let boundary = request.uri().path().ends_with("/boundary"); let response = next.run(request).await; - // Event intake reads once, followed by two finite outcome polls. - if boundary && boundary_reads.fetch_add(1, Ordering::Relaxed) == 2 { - two_open_polls.notify_one(); + if boundary && response.status().is_success() { + let _ = completed_reads.send(()); } response } - } - })); + }, + )); let http = tokio::spawn(async move { axum::serve(listener, routes).await.unwrap() }); let mut platform = @@ -998,7 +992,10 @@ mod tests { .unwrap(); assert_eq!(receipt.state, "applied"); std::fs::rename(&offline_directory, &git_directory).unwrap(); - assert!(git.find_reference(DELIVERY_REF).is_err()); + assert_eq!( + git.find_reference(DELIVERY_REF).err().unwrap().code(), + git2::ErrorCode::NotFound + ); let candidate = git .commit( None, @@ -1023,7 +1020,25 @@ mod tests { platform.link(root.number, pr.number, "human").unwrap(); platform.publish(pr.number, &declaration.source, &candidate.to_string(), "human").unwrap(); assert_eq!(git.refname_to_id(DELIVERY_REF).unwrap(), base); - let merged = platform.merge(pr.number, &declaration.source, "human").unwrap().merge_commit; + let receipt: ControlReceipt = client + .post( + "api/control/commands", + &CommandRequest { + request_id: "test-run-merge".into(), + expected_revision: Some(platform.item(pr.number).unwrap().revision), + command: ObjectCommand::Merge { number: pr.number }, + actor: "human".into(), + writer: None, + }, + ) + .await + .unwrap(); + assert_eq!(receipt.state, "applied", "{:?}", receipt.error); + let merged = serde_json::from_value::( + receipt.result.unwrap(), + ) + .unwrap() + .merge_commit; assert_eq!(git.refname_to_id(DELIVERY_REF).unwrap().to_string(), merged); let db = rusqlite::Connection::open(&declaration.database).unwrap(); db.execute_batch("ALTER TABLE local_merges RENAME TO offline_merges").unwrap(); @@ -1033,7 +1048,8 @@ mod tests { assert_eq!(root_view["item"]["number"], root.number); let context = client.context(pr.number).await.unwrap(); assert!(matches!(context, crate::context::CanonicalContext::PullRequest(pr) if pr.merged)); - assert!(platform.set_state(pr.number, true, "human").is_err()); + let error = platform.set_state(pr.number, true, "human").unwrap_err(); + assert!(error.to_string().contains("merged PR cannot be reopened"), "{error:#}"); db.execute_batch("ALTER TABLE offline_merges RENAME TO local_merges").unwrap(); platform.set_state(child.number, false, "human").unwrap(); let outside = platform.create_child_issue("Outside", "Other run", "human", None).unwrap(); @@ -1062,12 +1078,18 @@ mod tests { } let (_availability, provider_status) = watch::channel(ProviderAvailability::Starting); + // Observe this polling loop independently of any earlier object intake. + while boundary_reads.try_recv().is_ok() {} let outcome = finite_outcome(&config, &client, &store, &provider_status); tokio::pin!(outcome); tokio::time::timeout(Duration::from_secs(5), async { tokio::select! { result = &mut outcome => panic!("open root stopped polling: {result:?}"), - () = two_open_polls.notified() => {}, + () = async { + for _ in 0..2 { + boundary_reads.recv().await.expect("boundary observer closed"); + } + } => {}, } }) .await diff --git a/src/store/mod.rs b/src/store/mod.rs index 1d608859..032f244a 100644 --- a/src/store/mod.rs +++ b/src/store/mod.rs @@ -26,7 +26,9 @@ pub use scheduler_status::BatchEligibility; mod builtin; mod builtin_execution; mod run_progress; +mod unassignment; pub use builtin_execution::BuiltinExecutionCommand; +pub(crate) use unassignment::{Unassignment, UnassignmentTarget}; mod runs; pub use runs::RunCommand; mod gh_writes; @@ -480,16 +482,6 @@ pub struct ProfileRecord { pub tags: String, } -/// Outcome of a settled (or not yet settled) native unassignment. -#[derive(Debug, Clone)] -pub struct UnassignmentOutcome { - /// false while the debounce window is still open; the event stays pending. - pub settled: bool, - /// The provider session whose in-flight turn was fenced by the - /// retirement; the caller best-effort interrupts it. - pub fenced_provider_session: Option, -} - #[derive(Debug, Clone)] pub struct AssignmentCandidate { pub event_id: String, @@ -1015,18 +1007,6 @@ impl StoreActor { receiver.recv().map_err(|_| StoreError::ActorStopped)? } - #[cfg(test)] - pub(crate) fn processed_objects( - &self, - work_item: String, - ) -> Result, StoreError> { - let (reply, receiver) = mpsc::channel(); - self.sender - .send(Command::ProcessedObjects(work_item, reply)) - .map_err(|_| StoreError::ActorUnavailable)?; - receiver.recv().map_err(|_| StoreError::ActorStopped)? - } - pub(crate) fn begin_observation( &self, work_item: String, @@ -1334,14 +1314,25 @@ impl StoreActor { receiver.recv().map_err(|_| StoreError::ActorStopped)? } - pub fn retire_unassigned_work_item( + pub(crate) fn due_unassignment( &self, - event_id: String, - debounce_seconds: u64, - ) -> Result { + target: UnassignmentTarget, + quiet_seconds: u64, + ) -> Result, StoreError> { + let (reply, receiver) = mpsc::channel(); + self.sender + .send(Command::DueUnassignment(target, quiet_seconds, reply)) + .map_err(|_| StoreError::ActorUnavailable)?; + receiver.recv().map_err(|_| StoreError::ActorStopped)? + } + + pub(crate) fn retire_unassigned_work_item( + &self, + change: Unassignment, + ) -> Result<(), StoreError> { let (reply, receiver) = mpsc::channel(); self.sender - .send(Command::RetireUnassignedWorkItem(event_id, debounce_seconds, reply)) + .send(Command::RetireUnassignedWorkItem(change.event_id, change.assignment_id, reply)) .map_err(|_| StoreError::ActorUnavailable)?; receiver.recv().map_err(|_| StoreError::ActorStopped)? } @@ -1667,8 +1658,6 @@ enum Command { RecordImplementationProgress(String, ImplementationProgress, Sender>), DueReconciliationWorkItems(u64, Sender, StoreError>>), RecordReconciliation(String, bool, Sender>), - #[cfg(test)] - ProcessedObjects(String, Sender, StoreError>>), BeginObservation(String, Sender>), CommitObservation(Box, Sender>), RecordPublicationVersion(String, String, String, String, Sender>), @@ -1744,7 +1733,8 @@ enum Command { Sender, StoreError>>, ), IgnoreAssignmentEvent(String, Sender>), - RetireUnassignedWorkItem(String, u64, Sender>), + DueUnassignment(UnassignmentTarget, u64, Sender, StoreError>>), + RetireUnassignedWorkItem(String, Option, Sender>), CompleteAgentAssignment( AgentMaterialization, String, @@ -1927,13 +1917,6 @@ fn actor_loop(database: &Path, backups: &Path, receiver: Receiver) { }); let _ = reply.send(result); } - #[cfg(test)] - Command::ProcessedObjects(work_item, reply) => { - let _ = reply.send( - open_read_only(database) - .and_then(|connection| observations::load(&connection, &work_item)), - ); - } Command::BeginObservation(work_item, reply) => { let _ = reply.send(observations::begin(database, &work_item)); } @@ -2095,9 +2078,15 @@ fn actor_loop(database: &Path, backups: &Path, receiver: Receiver) { Command::IgnoreAssignmentEvent(event_id, reply) => { let _ = reply.send(ignore_assignment_event(database, &event_id)); } - Command::RetireUnassignedWorkItem(event_id, debounce_seconds, reply) => { - let _ = - reply.send(retire_unassigned_work_item(database, &event_id, debounce_seconds)); + Command::DueUnassignment(target, quiet_seconds, reply) => { + let _ = reply.send(unassignment::due(database, &target, quiet_seconds)); + } + Command::RetireUnassignedWorkItem(event_id, assignment_id, reply) => { + let _ = reply.send(retire_unassigned_work_item( + database, + &event_id, + assignment_id.as_deref(), + )); } Command::CompleteAgentAssignment( materialization, @@ -4352,83 +4341,55 @@ fn begin_agent_assignment( Ok(Some(materialization)) } -/// Settle a native unassignment after its debounce window: retire the active -/// Agent Group. An in-flight turn is fenced `interrupted`; the caller -/// best-effort interrupts it through the session. The event is consumed once -/// settled; while the debounce window is open the event stays pending. +/// Consume this change and retire its current generation after provider shutdown. fn retire_unassigned_work_item( database: &Path, event_id: &str, - debounce_seconds: u64, -) -> Result { + expected_assignment: Option<&str>, +) -> Result<(), StoreError> { require_current_schema(database)?; let now = now_rfc3339(); let mut connection = open_read_write(database)?; configure_connection(&connection)?; let transaction = connection.transaction()?; - let event = transaction + // Bind retirement to the generation whose native execution was stopped. + // A re-delivered change cannot affect a later assignment of the same item. + let target = transaction .query_row( - "SELECT work_item_node_id,observed_at FROM events - WHERE event_id=?1 AND lifecycle='pending' AND kind='unassign'", - [event_id], - |row| Ok((row.get::<_, Option>(0)?, row.get::<_, String>(1)?)), + "SELECT a.assignment_id,ai.agent_id,a.work_item_node_id FROM events e + JOIN assignments a ON a.work_item_node_id=e.work_item_node_id + JOIN agent_instances ai ON ai.assignment_id=a.assignment_id + WHERE e.event_id=?1 AND e.kind='unassign' AND e.lifecycle='pending' + AND a.assignment_id=?2 AND a.lifecycle IN ('materializing','active','finalizing')", + params![event_id, expected_assignment], + |row| { + Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?, row.get::<_, String>(2)?)) + }, ) .optional()?; - let Some((work_item_node_id, observed_at)) = event else { - transaction.commit()?; - return Ok(UnassignmentOutcome { settled: true, fenced_provider_session: None }); - }; - let observed = OffsetDateTime::parse(&observed_at, &Rfc3339) - .map_err(|error| StoreError::InvalidData(format!("event observed_at: {error}")))?; - let settled = (OffsetDateTime::now_utc() - observed) - >= time::Duration::seconds(i64::try_from(debounce_seconds).unwrap_or(i64::MAX)); - if !settled { - transaction.commit()?; - return Ok(UnassignmentOutcome { settled: false, fenced_provider_session: None }); - } - let active = work_item_node_id - .as_deref() - .map(|node_id| { - transaction - .query_row( - "SELECT a.assignment_id,ai.agent_id FROM assignments a - JOIN agent_instances ai ON ai.assignment_id=a.assignment_id - WHERE a.work_item_node_id=?1 - AND a.lifecycle IN ('materializing','active','finalizing') - ORDER BY a.generation DESC LIMIT 1", - [node_id], - |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)), - ) - .optional() - }) - .transpose()?; - let Some((assignment_id, agent_id)) = active.flatten() else { + let Some((assignment_id, agent_id, work_item_node_id)) = target else { transaction.execute( "UPDATE events SET lifecycle='consumed' WHERE event_id=?1 AND lifecycle='pending'", [event_id], )?; transaction.commit()?; - return Ok(UnassignmentOutcome { settled: true, fenced_provider_session: None }); + return Ok(()); }; - let fenced = transaction - .query_row( - "SELECT ps.provider_session_id FROM provider_sessions ps - JOIN turns t ON t.session_id=ps.session_id - WHERE ps.agent_id=?1 AND t.lifecycle IN ('starting','running') - ORDER BY t.rowid DESC LIMIT 1", - [&agent_id], - |row| row.get::<_, String>(0), - ) - .optional()?; - if let Some(provider_session_id) = &fenced { - transaction.execute( - "UPDATE turns SET lifecycle='interrupted',ended_at=?2 - WHERE lifecycle IN ('starting','running') - AND session_id IN (SELECT session_id FROM provider_sessions WHERE agent_id=?1)", - params![agent_id, now], - )?; - let _ = provider_session_id; + let unconfirmed: bool = transaction.query_row( + "SELECT EXISTS(SELECT 1 FROM provider_sessions WHERE agent_id=?1 + AND lifecycle NOT IN ('retired','replaced') AND execution_stopped_at IS NULL)", + [&agent_id], + |row| row.get(0), + )?; + if unconfirmed { + return Err(StoreError::InvalidData("unassignment lacks a confirmed native stop".into())); } + transaction.execute( + "UPDATE turns SET lifecycle='interrupted',ended_at=?2 + WHERE lifecycle IN ('starting','running') + AND session_id IN (SELECT session_id FROM provider_sessions WHERE agent_id=?1)", + params![agent_id, now], + )?; transaction.execute( "UPDATE provider_sessions SET lifecycle='retired' WHERE agent_id=?1 AND lifecycle NOT IN ('retired','replaced')", @@ -4445,19 +4406,17 @@ fn retire_unassigned_work_item( "UPDATE assignments SET lifecycle='retired',retired_at=?2 WHERE assignment_id=?1", params![assignment_id, now], )?; - if let Some(node_id) = &work_item_node_id { - transaction.execute( - "UPDATE wake_batches SET lifecycle='consumed',updated_at=?2 - WHERE work_item_node_id=?1 AND lifecycle IN ('pending','runnable')", - params![node_id, now], - )?; - } + transaction.execute( + "UPDATE wake_batches SET lifecycle='consumed',updated_at=?2 + WHERE work_item_node_id=?1 AND lifecycle IN ('pending','runnable')", + params![work_item_node_id, now], + )?; transaction.execute( "UPDATE events SET lifecycle='consumed' WHERE event_id=?1 AND lifecycle='pending'", [event_id], )?; transaction.commit()?; - Ok(UnassignmentOutcome { settled: true, fenced_provider_session: fenced }) + Ok(()) } fn ignore_assignment_event(database: &Path, event_id: &str) -> Result<(), StoreError> { diff --git a/src/store/observations.rs b/src/store/observations.rs index b69e9c80..fa4440ea 100644 --- a/src/store/observations.rs +++ b/src/store/observations.rs @@ -77,10 +77,7 @@ pub(crate) struct ObservationCommit { pub policy: SchedulerPolicy, } -pub(super) fn load( - connection: &Connection, - work_item: &str, -) -> Result, StoreError> { +fn load(connection: &Connection, work_item: &str) -> Result, StoreError> { let mut statement = connection.prepare( "SELECT node_id,database_id,object_kind,version,digest,lifecycle,author_node_id, author_login,metadata_digest,title_digest,body_digest,title_event_id diff --git a/src/store/reconciliation.rs b/src/store/reconciliation.rs index e10fdbc1..ea127543 100644 --- a/src/store/reconciliation.rs +++ b/src/store/reconciliation.rs @@ -78,6 +78,13 @@ mod tests { db } + fn due_ids(db: &Connection, now: i64) -> Vec { + let mut items: Vec<_> = + due(db, now, 60).unwrap().into_iter().map(|item| item.node_id).collect(); + items.sort_unstable(); + items + } + #[test] fn hot_cold_observations_and_finalization() { let db = database(); @@ -85,28 +92,11 @@ mod tests { record(&db, id, 100, true).unwrap(); } db.execute("UPDATE work_items SET observed_at=500", []).unwrap(); - assert!(due(&db, 159, 60).unwrap().is_empty()); - let ids = due(&db, 160, 60).unwrap().into_iter().map(|w| w.node_id).collect::>(); - assert_eq!(ids, ["final", "open"]); - assert_eq!(due(&db, 1900, 60).unwrap().len(), 3); + assert!(due_ids(&db, 159).is_empty()); + assert_eq!(due_ids(&db, 160), ["final", "open"]); + assert_eq!(due_ids(&db, 1900), ["closed", "final", "open"]); db.execute("UPDATE assignments SET lifecycle='retired'", []).unwrap(); - assert_eq!(due(&db, 160, 60).unwrap().len(), 1); - } - - #[test] - fn partial_failure_does_not_mark_success_and_rotates() { - let db = database(); - let first = due(&db, 100, 60).unwrap()[0].node_id.clone(); - record(&db, &first, 100, false).unwrap(); - let later = due(&db, 105, 60).unwrap(); - assert_ne!(later[0].node_id, first); - assert!(!later.iter().any(|w| w.node_id == first)); - assert!(!due(&db, 159, 60).unwrap().iter().any(|w| w.node_id == first)); - assert!(due(&db, 160, 60).unwrap().iter().any(|w| w.node_id == first)); - record(&db, &later[0].node_id, 105, true).unwrap(); - // A later failure (even on the same repository) cannot erase success. - record(&db, &first, 160, false).unwrap(); - assert!(!due(&db, 160, 60).unwrap().iter().any(|w| w.node_id == later[0].node_id)); + assert_eq!(due_ids(&db, 160), ["open"]); } #[test] @@ -118,19 +108,19 @@ mod tests { for id in ["open", "closed", "final", "other"] { record(&db, id, 100, true).unwrap(); } - assert_eq!(due(&db, 160, 60).unwrap().len(), 3); + assert_eq!(due_ids(&db, 160), ["closed", "final", "open"]); db.execute( "UPDATE assignments SET lifecycle='active' WHERE work_item_node_id='closed'", [], ) .unwrap(); - assert_eq!(due(&db, 160, 60).unwrap().len(), 3); + assert_eq!(due_ids(&db, 160), ["closed", "final", "open"]); db.execute( "UPDATE assignments SET lifecycle='sleeping' WHERE work_item_node_id='closed'", [], ) .unwrap(); - assert_eq!(due(&db, 160, 60).unwrap().len(), 2); + assert_eq!(due_ids(&db, 160), ["final", "open"]); // Previously attempted repository cannot keep untouched cold history behind it. for id in ["open", "closed", "final"] { record(&db, id, 1900, false).unwrap(); @@ -143,19 +133,26 @@ mod tests { } #[test] - fn failed_refresh_retries_at_hot_interval_without_erasing_success() { + fn failed_traversal_backs_off_without_losing_the_last_success() { let db = database(); + // This closed item has never succeeded. Its failure cannot delay other + // items, start the cold interval, or retry before the hot interval. + record(&db, "closed", 100, false).unwrap(); + assert_eq!(due_ids(&db, 159), ["final", "open"]); + assert_eq!(due_ids(&db, 160), ["closed", "final", "open"]); + + // After an open item succeeds and a refresh fails, closing it reveals + // which persisted timestamp controls the cold interval. record(&db, "open", 100, true).unwrap(); record(&db, "open", 160, false).unwrap(); - assert!(!due(&db, 165, 60).unwrap().iter().any(|w| w.node_id == "open")); - assert!(!due(&db, 219, 60).unwrap().iter().any(|w| w.node_id == "open")); - assert!(due(&db, 220, 60).unwrap().iter().any(|w| w.node_id == "open")); - // Cold history remains cold after success, but a failed due traversal - // can retry after the hot interval rather than another thirty minutes. - record(&db, "closed", 100, true).unwrap(); - record(&db, "closed", 1900, false).unwrap(); - assert!(!due(&db, 1905, 60).unwrap().iter().any(|w| w.node_id == "closed")); - assert!(due(&db, 1960, 60).unwrap().iter().any(|w| w.node_id == "closed")); + assert!(!due_ids(&db, 219).iter().any(|id| id == "open")); + assert!(due_ids(&db, 220).iter().any(|id| id == "open")); + db.execute("UPDATE work_items SET state='CLOSED' WHERE node_id='open'", []).unwrap(); + assert!(!due_ids(&db, 1899).iter().any(|id| id == "open")); + assert!(due_ids(&db, 1900).iter().any(|id| id == "open")); + record(&db, "open", 1900, false).unwrap(); + assert!(!due_ids(&db, 1959).iter().any(|id| id == "open")); + assert!(due_ids(&db, 1960).iter().any(|id| id == "open")); } #[test] diff --git a/src/store/schema_tests.rs b/src/store/schema_tests.rs index 860da42c..6f53da18 100644 --- a/src/store/schema_tests.rs +++ b/src/store/schema_tests.rs @@ -101,3 +101,41 @@ fn migration_entry_points_reject_incompatible_databases_without_changing_bytes() drop(store); } } + +#[test] +fn v1_upgrade_preserves_the_association_and_comment_and_takes_only_one_backup() { + let root = + TemporaryRoot(std::env::temp_dir().join(format!("braid-v1-{}", uuid::Uuid::now_v7()))); + std::fs::create_dir_all(&root.0).unwrap(); + let database = root.0.join("state.sqlite3"); + let backups = root.0.join("backups"); + let mut db = Connection::open(&database).unwrap(); + super::configure_connection(&db).unwrap(); + super::apply_one(&mut db, &super::MIGRATIONS[0]).unwrap(); + db.execute_batch("INSERT INTO repositories(node_id,name_with_owner,observed_at) VALUES ('repo','owner/repo','now'); + INSERT INTO work_items(node_id,repository_node_id,kind,number,state,observed_at) + VALUES ('issue','repo','issue',1,'OPEN','now'),('pr','repo','pr',2,'OPEN','now'); + INSERT INTO associations(issue_node_id,pr_node_id,source,observed_version,active) VALUES ('issue','pr','native','v1',1); + INSERT INTO canonical_objects(node_id,work_item_node_id,object_kind,version,digest,lifecycle,observed_at) + VALUES ('comment','issue','issue_comment','v1',hex(zeroblob(32)),'active','now');").unwrap(); + drop(db); + + let store = StoreActor::start(database.clone(), backups.clone()).unwrap(); + let upgrade = store.apply().unwrap(); + assert_eq!(upgrade.previous_schema, 1); + assert_eq!(upgrade.current_schema, DATABASE_SCHEMA_VERSION); + let backup = upgrade.backup.unwrap(); + drop(store); + let store = StoreActor::start(database.clone(), backups.clone()).unwrap(); + let repeated = store.apply().unwrap(); + assert!(repeated.applied.is_empty()); + assert!(repeated.backup.is_none()); + let files: Vec<_> = + std::fs::read_dir(backups).unwrap().map(|entry| entry.unwrap().path()).collect(); + assert_eq!(files, [backup]); + let db = Connection::open(database).unwrap(); + let association: bool = db.query_row("SELECT active FROM associations WHERE issue_node_id='issue' AND pr_node_id='pr' AND source='native'", [], |row| row.get(0)).unwrap(); + assert!(association); + let comment: String = db.query_row("SELECT lifecycle FROM canonical_objects WHERE node_id='comment' AND work_item_node_id='issue' AND version='v1'", [], |row| row.get(0)).unwrap(); + assert_eq!(comment, "active"); +} diff --git a/src/store/unassignment.rs b/src/store/unassignment.rs new file mode 100644 index 00000000..ca4d278c --- /dev/null +++ b/src/store/unassignment.rs @@ -0,0 +1,72 @@ +use super::{StoreError, open_read_only, require_current_schema}; +use rusqlite::{OptionalExtension as _, params}; +use std::path::Path; + +pub(crate) enum UnassignmentTarget { + Event(String), + RunningTurn(String), +} + +pub(crate) struct Unassignment { + pub event_id: String, + pub(super) assignment_id: Option, + pub repository: String, + pub number: u64, + pub sessions: Vec<(String, bool)>, +} + +/// An active worker only handles the revocation of its own work item. +/// Idle workers preserve the normal order of assignment candidates. +pub(super) fn due( + database: &Path, + target: &UnassignmentTarget, + quiet_seconds: u64, +) -> Result, StoreError> { + require_current_schema(database)?; + let connection = open_read_only(database)?; + let (event, turn) = match target { + UnassignmentTarget::Event(id) => (Some(id), None), + UnassignmentTarget::RunningTurn(id) => (None, Some(id)), + }; + let row = connection.query_row( + "SELECT e.event_id,r.name_with_owner,w.number, + (SELECT latest.observed_at FROM events latest WHERE latest.work_item_node_id=w.node_id + AND latest.lifecycle='pending' AND latest.kind='unassign' ORDER BY latest.rowid DESC LIMIT 1), + (SELECT a.assignment_id FROM assignments a WHERE a.work_item_node_id=w.node_id + AND a.lifecycle IN ('materializing','active','finalizing') ORDER BY a.generation DESC LIMIT 1) + FROM events e JOIN work_items w ON w.node_id=e.work_item_node_id + JOIN repositories r ON r.node_id=w.repository_node_id + WHERE e.kind='unassign' AND e.lifecycle='pending' AND (?1 IS NULL OR e.event_id=?1) + AND e.work_item_node_id=coalesce((SELECT work_item_node_id FROM events WHERE event_id=?1), + (SELECT a.work_item_node_id FROM turns t JOIN provider_sessions ps ON ps.session_id=t.session_id + JOIN agent_instances ai ON ai.agent_id=ps.agent_id JOIN assignments a ON a.assignment_id=ai.assignment_id + WHERE t.turn_id=?2 AND t.lifecycle IN ('starting','running'))) + ORDER BY e.rowid LIMIT 1", + params![event, turn], + |row| Ok(( + row.get::<_, String>(0)?, row.get::<_,String>(1)?, + super::sqlite_i64_to_u64(row.get(2)?, "unassignment Work Item number")?, + row.get::<_,String>(3)?, row.get::<_,Option>(4)?, + )), + ).optional()?; + let Some((event_id, repository, number, latest, assignment_id)) = row else { return Ok(None) }; + let observed = + time::OffsetDateTime::parse(&latest, &time::format_description::well_known::Rfc3339) + .map_err(|error| { + StoreError::InvalidData(format!("unassignment observed_at: {error}")) + })?; + if time::OffsetDateTime::now_utc() - observed + < time::Duration::seconds(i64::try_from(quiet_seconds).unwrap_or(i64::MAX)) + { + return Ok(None); + } + let mut statement = connection.prepare( + "SELECT ps.provider_session_id, ps.execution_stopped_at IS NOT NULL + FROM provider_sessions ps JOIN agent_instances ai ON ai.agent_id=ps.agent_id + WHERE ai.assignment_id=?1 AND ps.lifecycle NOT IN ('retired','replaced')", + )?; + let sessions = statement + .query_map([&assignment_id], |r| Ok((r.get(0)?, r.get(1)?)))? + .collect::, _>>()?; + Ok(Some(Unassignment { event_id, assignment_id, repository, number, sessions })) +} diff --git a/src/writer/tests/continuous_collaboration.rs b/src/writer/tests/continuous_collaboration.rs index ddbed607..587aff16 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, @@ -158,7 +158,7 @@ fn failed_observation_commits_neither_events_nor_frontier() { 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()); } @@ -247,33 +247,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); @@ -396,8 +369,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(); @@ -436,7 +415,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(); @@ -520,24 +499,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/observation_recovery.rs b/src/writer/tests/observation_recovery.rs index a69f8460..53267d00 100644 --- a/src/writer/tests/observation_recovery.rs +++ b/src/writer/tests/observation_recovery.rs @@ -296,8 +296,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 +325,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/semantic_contract.rs b/src/writer/tests/semantic_contract.rs index 1a4d1542..909980a1 100644 --- a/src/writer/tests/semantic_contract.rs +++ b/src/writer/tests/semantic_contract.rs @@ -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(); @@ -231,6 +231,6 @@ async fn contract_restoration_cycles_survive_polling_and_share_a_real_ingress_re "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/turn_start.rs b/src/writer/tests/turn_start.rs index 6c901f9d..98eb7966 100644 --- a/src/writer/tests/turn_start.rs +++ b/src/writer/tests/turn_start.rs @@ -98,7 +98,9 @@ async fn native_start_authorizes_current_publication_before_start_rpc_response() // to an older completed turn with a non-null timestamp. assert!( resolve_source(&fixture.config, Some("issue-codex"), &fixture.invocation()) - .is_err() + .unwrap_err() + .to_string() + .contains("publication source was invalidated or superseded") ); let provider = DelayedProvider::new(reply); let session = ProviderAgentSession::start( @@ -142,14 +144,18 @@ async fn native_start_authorizes_current_publication_before_start_rpc_response() 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() + .unwrap_err() + .to_string() + .contains("publication source was invalidated or superseded") ); assert!( crate::store::publication_source::check( fixture.config.runtime.database(), &resolved ) - .is_err() + .unwrap_err() + .to_string() + .contains("publication source was invalidated or superseded") ); fixture.db().execute("DELETE FROM events WHERE event_id='invalidate'", []).unwrap(); // Terminal arrives before the delayed response: the dispatch @@ -177,17 +183,9 @@ async fn native_start_authorizes_current_publication_before_start_rpc_response() events.recv().await.unwrap(), SessionEvent::TurnTerminal { outcome: TurnOutcome::Completed, .. } )); - assert!(events.try_recv().is_err()); // no duplicated start from the RPC response + assert!(matches!(events.try_recv(), Err(broadcast::error::TryRecvError::Empty))); // no duplicated start from the RPC response crate::store::publication_source::check(fixture.config.runtime.database(), &resolved) .unwrap(); - fixture.db().execute("UPDATE assignments SET generation=2", []).unwrap(); - assert!( - crate::store::publication_source::check( - fixture.config.runtime.database(), - &resolved - ) - .is_err() - ); } } } @@ -221,7 +219,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))); } } From 16d383ea2ec63badb400f92ad8084ac1ce882e57 Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sat, 28 Nov 2026 21:47:20 +0800 Subject: [PATCH 15/43] =?UTF-8?q?ref(publication):=20=E9=80=9A=E8=BF=87?= =?UTF-8?q?=E7=9C=9F=E5=AE=9E=E5=88=86=E9=A1=B5=E3=80=81=E5=8F=91=E5=B8=83?= =?UTF-8?q?=E6=84=8F=E5=9B=BE=E5=8F=8A=E8=A7=82=E5=AF=9F=E8=AF=BB=E5=8F=96?= =?UTF-8?q?=E9=AA=8C=E8=AF=81=E6=81=A2=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 将签名入口与字段所有权归还生产路径,重开账本和网络客户端继续已建 PR - 去掉自造阶段和重复读取接缝,核对拒绝原因和远端写入次数 --- src/context/reading_tests.rs | 28 ++-- src/github/graphql.rs | 10 +- src/producer/ingress_tests.rs | 35 ++++ src/producer/reconcile.rs | 6 +- src/store/gh_writes/tests.rs | 2 +- src/store/operational_status.rs | 23 ++- .../operational_status_migration_tests.rs | 24 +-- src/webhook_tests.rs | 15 ++ src/writer/tests.rs | 158 ++++++++++++------ src/writer/tests/body_edit.rs | 75 +++------ src/writer/tests/handoff.rs | 78 +++------ src/writer/tests/implementation_recovery.rs | 35 +++- src/writer/tests/reaction_feedback.rs | 16 +- src/writer/tests/status_convergence.rs | 1 + 14 files changed, 291 insertions(+), 215 deletions(-) diff --git a/src/context/reading_tests.rs b/src/context/reading_tests.rs index dfd8a0b7..7d0649d7 100644 --- a/src/context/reading_tests.rs +++ b/src/context/reading_tests.rs @@ -21,8 +21,8 @@ fn core(pr: bool, version: usize) -> Value { } value } -fn comment() -> Value { - json!({"id":"C1","fullDatabaseId":"2","author":null,"body":"Complete comment body","createdAt":"2026-01-01","updatedAt":"2026-01-01","lastEditedAt":null,"isMinimized":false,"minimizedReason":null,"isPinned":false}) +fn comment(id: &str, body: &str) -> Value { + json!({"id":id,"fullDatabaseId":if id == "C1" {"2"} else {"3"},"author":null,"body":body,"createdAt":"2026-01-01","updatedAt":"2026-01-01","lastEditedAt":null,"isMinimized":false,"minimizedReason":null,"isPinned":false}) } #[allow(clippy::too_many_lines)] async fn server( @@ -70,8 +70,12 @@ async fn server( ] } { object[field] = page( - if field == "comments" && !multi { - json!([comment()]) + if field == "comments" { + let mut nodes = vec![comment("C1", "First comment")]; + if !multi { + nodes.push(comment("C2", "Complete comment body")); + } + json!(nodes) } else { json!([]) }, @@ -80,7 +84,9 @@ async fn server( } } else if !op.ends_with("Core") { object["items"] = page( - if op.ends_with("Comments") { json!([comment()]) } else { json!([]) }, + if matches!(op, "IssueComments" | "PrComments") && request["variables"]["cursor"] == "next" { + json!([comment("C2", "Complete comment body")]) + } else { json!([]) }, false, ); } @@ -103,7 +109,7 @@ async fn server( let mut repository = json!({"id":"R1","nameWithOwner":"owner/repo"}); repository[if pr { "pullRequest" } else { "issue" }] = object; let mut result = json!({"data":{"repository":repository,"rateLimit":{"cost":1}}}); - if op == "ReviewThreadComments" { result["data"]=json!({"node":{"items":page(json!([comment()]),false)},"rateLimit":{"cost":1}}); } + if op == "ReviewThreadComments" { result["data"]=json!({"node":{"items":page(json!([comment("C1","Review thread discussion")]),false)},"rateLimit":{"cost":1}}); } if fault == Some("partial") && op.ends_with("FirstPages") { result["errors"] = json!([{"message":"incomplete"}]); } @@ -168,9 +174,11 @@ async fn single_page_bill_and_multipage_output_equivalence() { for snapshot in [&single, &multi] { let comments = snapshot[if pr { "conversation" } else { "comments" }].as_array().unwrap(); - assert_eq!(comments.len(), 1); + assert_eq!(comments.len(), 2); assert_eq!(comments[0]["node_id"], "C1"); - assert_eq!(comments[0]["body"], "Complete comment body"); + assert_eq!(comments[0]["body"], "First comment"); + assert_eq!(comments[1]["node_id"], "C2"); + assert_eq!(comments[1]["body"], "Complete comment body"); } assert_eq!(single, multi); assert_eq!(ops.lock().unwrap().len(), 6); @@ -220,8 +228,8 @@ async fn associated_issue_and_review_thread_bodies_are_fully_materialized() { let (client, ops, task) = server(true, false, false, Some("rich")).await; let result = materialize(&client, true).await.unwrap(); assert_eq!(result["associated_issues"][0]["body"], "Full body"); - assert_eq!(result["associated_issues"][0]["comments"][0]["body"], "Complete comment body"); - assert_eq!(result["review_threads"][0]["comments"][0]["body"], "Complete comment body"); + assert_eq!(result["associated_issues"][0]["comments"][1]["body"], "Complete comment body"); + assert_eq!(result["review_threads"][0]["comments"][0]["body"], "Review thread discussion"); assert_eq!(ops.lock().unwrap().len(), 11); task.abort(); } diff --git a/src/github/graphql.rs b/src/github/graphql.rs index cb59ede9..12948bbe 100644 --- a/src/github/graphql.rs +++ b/src/github/graphql.rs @@ -180,15 +180,15 @@ struct GraphQlRequest<'a, V: ?Sized> { } #[derive(Deserialize)] -pub(super) struct GraphQlEnvelope { - pub(super) data: Option, +struct GraphQlEnvelope { + data: Option, #[serde(default)] - pub(super) errors: Vec, + errors: Vec, } #[derive(Deserialize)] -pub(super) struct GraphQlError { - pub(super) message: String, +struct GraphQlError { + message: String, #[serde(rename = "type", default)] kind: Option, } diff --git a/src/producer/ingress_tests.rs b/src/producer/ingress_tests.rs index 676aebfc..bb460ef1 100644 --- a/src/producer/ingress_tests.rs +++ b/src/producer/ingress_tests.rs @@ -166,3 +166,38 @@ async fn signed_same_number_repositories_keep_distinct_events_and_deduplicate_af ]) ); } + +#[tokio::test] +async fn signed_app_comment_mention_does_not_schedule_a_handoff_or_wake() { + const BODY: &str = r#"{"action":"created","repository":{"node_id":"R1","full_name":"owner/repository"},"sender":{"login":"braid[bot]","node_id":"APP"},"issue":{"node_id":"I1","number":1,"state":"open","pull_request":{}},"comment":{"id":7,"node_id":"C1","body":"@braid continue this handoff","created_at":"2026-01-01T00:00:00Z","updated_at":"2026-01-01T00:00:00Z"}}"#; + let db = Database::new(); + let state = db.state(&["owner/repository"]); + db.connect() + .execute_batch( + "INSERT INTO repositories VALUES ('R1','owner/repository',1,'now'); + INSERT INTO work_items(node_id,repository_node_id,kind,number,state,observed_at) + VALUES ('I1','R1','pr',1,'open','now'); + INSERT INTO assignments VALUES ('current','I1',1,'active','now',NULL);", + ) + .unwrap(); + let (status, receipt) = deliver( + &state, + BODY, + Some("sha256=cc52441234b35bf3359ce89a5d58821e6d65ab784f8e87d7880fe4478da628f3"), + "app-echo", + ) + .await; + assert_eq!(status, StatusCode::ACCEPTED, "{receipt}"); + let id: Value = serde_json::from_str(&receipt).unwrap(); + let kind: String = db + .connect() + .query_row( + "SELECT kind FROM events WHERE event_id=?1", + [id["event_id"].as_str().unwrap()], + |row| row.get(0), + ) + .unwrap(); + assert_eq!(kind, "origin_echo"); + assert_eq!(db.count("wake_batches"), 0); + assert_eq!(db.count("pr_handoffs"), 0); +} diff --git a/src/producer/reconcile.rs b/src/producer/reconcile.rs index 30eacf66..2f4d6bf2 100644 --- a/src/producer/reconcile.rs +++ b/src/producer/reconcile.rs @@ -604,7 +604,7 @@ fn current_actor_known(observation: &CanonicalObservation, action: &str) -> bool && observation.author_node_id.is_some()) } -pub(crate) fn observation_unchanged( +fn observation_unchanged( previous: &CanonicalObjectState, observation: &CanonicalObservation, ) -> bool { @@ -621,7 +621,7 @@ pub(crate) fn observation_unchanged( } } -pub(crate) fn reconciled_change( +fn reconciled_change( previous: Option<&CanonicalObjectState>, observation: &CanonicalObservation, ) -> (&'static str, EventKind) { @@ -659,7 +659,7 @@ pub(crate) fn reconciled_change( } } -pub(crate) fn reconciled_event( +fn reconciled_event( observation: &CanonicalObservation, action: &'static str, kind: EventKind, diff --git a/src/store/gh_writes/tests.rs b/src/store/gh_writes/tests.rs index bf96afff..981ce484 100644 --- a/src/store/gh_writes/tests.rs +++ b/src/store/gh_writes/tests.rs @@ -155,7 +155,7 @@ fn legacy_cli_pending_uncertain_sending_all_get_one_execution_obligation() { drop(connection); let store = StoreActor::start(db.path.clone(), db.root.join("backups")).unwrap(); let migrated = store.apply().unwrap(); - assert_eq!(migrated.applied, vec![9, 10, 11, 12, 13, 14]); + assert_eq!(migrated.applied.first(), Some(&9)); assert!(migrated.backup.is_some()); let owner = store.acquire_runtime_lease("runtime".into(), "writer".into(), 3600).unwrap(); let mut seen = std::collections::BTreeMap::new(); diff --git a/src/store/operational_status.rs b/src/store/operational_status.rs index 92be5282..f0db9d2a 100644 --- a/src/store/operational_status.rs +++ b/src/store/operational_status.rs @@ -186,10 +186,7 @@ fn block_unidentified_creates(tx: &rusqlite::Transaction<'_>, now: &str) -> Resu Ok(()) } -pub(super) fn confirmation_after( - confirmed: &str, - failure: Option<&str>, -) -> Result { +fn confirmation_after(confirmed: &str, failure: Option<&str>) -> Result { let Some(failure) = failure else { return Ok(false) }; let parse = |value: &str| { time::OffsetDateTime::parse(value, &time::format_description::well_known::Rfc3339).map_err( @@ -257,3 +254,21 @@ pub(super) fn settle( tx.execute("UPDATE status_comments SET remote_comment_node_id=COALESCE(?3,remote_comment_node_id),remote_comment_database_id=COALESCE(?4,remote_comment_database_id),lifecycle=CASE WHEN write_intent_id=?1 THEN ?2 ELSE lifecycle END,updated_at=CASE WHEN write_intent_id=?1 THEN ?5 ELSE updated_at END WHERE EXISTS(SELECT 1 FROM github_write_outbox o WHERE o.intent_id=?1 AND o.status_work_item_node_id=status_comments.work_item_node_id AND o.status_profile_id=status_comments.profile_id AND o.status_generation=status_comments.assignment_generation)",params![intent,lifecycle,remote_node,remote_id,now])?; Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn status_convergence_confirmation_compares_instants_not_timestamp_strings() { + assert!( + confirmation_after("2000-01-01T00:00:00.1Z", Some("2000-01-01T00:00:00Z")).unwrap() + ); + assert!( + !confirmation_after("2000-01-01T01:00:00+01:00", Some("2000-01-01T00:00:00Z")).unwrap() + ); + assert!(!confirmation_after("2000-01-01T00:00:00Z", None).unwrap()); + assert!(matches!(confirmation_after("not-a-time", Some("2000-01-01T00:00:00Z")), + Err(StoreError::InvalidData(reason)) if reason.contains("invalid operational status confirmation timestamp"))); + } +} diff --git a/src/store/operational_status_migration_tests.rs b/src/store/operational_status_migration_tests.rs index e650c7ed..8b4d0d56 100644 --- a/src/store/operational_status_migration_tests.rs +++ b/src/store/operational_status_migration_tests.rs @@ -1,6 +1,6 @@ use super::{ MIGRATIONS, OperationalCommentCandidate, StoreActor, apply_one, configure_connection, - open_read_write, operational_status, + open_read_write, }; use rusqlite::params; @@ -193,25 +193,3 @@ fn role_migration_preserves_legacy_evidence_and_requires_a_unique_identity() { drop(store); std::fs::remove_dir_all(root).unwrap(); } - -#[test] -fn status_convergence_confirmation_compares_instants_not_timestamp_strings() { - assert!( - operational_status::confirmation_after( - "2000-01-01T00:00:00.1Z", - Some("2000-01-01T00:00:00Z") - ) - .unwrap() - ); - assert!( - !operational_status::confirmation_after( - "2000-01-01T01:00:00+01:00", - Some("2000-01-01T00:00:00Z") - ) - .unwrap() - ); - assert!(!operational_status::confirmation_after("2000-01-01T00:00:00Z", None).unwrap()); - assert!( - operational_status::confirmation_after("not-a-time", Some("2000-01-01T00:00:00Z")).is_err() - ); -} diff --git a/src/webhook_tests.rs b/src/webhook_tests.rs index 84870604..2291e859 100644 --- a/src/webhook_tests.rs +++ b/src/webhook_tests.rs @@ -113,3 +113,18 @@ fn comment_edits_compare_visible_suffix_instead_of_discarding_the_html_block_lin 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/writer/tests.rs b/src/writer/tests.rs index d6a5af5b..3d31a687 100644 --- a/src/writer/tests.rs +++ b/src/writer/tests.rs @@ -125,12 +125,14 @@ enum Authority { SourceClosed, TargetClosed, AssociationRemoved, + AssociationUnavailable, OtherIssue, } #[derive(Default)] struct Remote { authority: Authority, + closing_issue: Option, pr_body: Option, create_pr: bool, target_kind: TargetKind, @@ -188,7 +190,23 @@ async fn server( .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 { @@ -200,6 +218,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(), @@ -219,26 +241,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); @@ -294,22 +312,8 @@ async fn uncertain_comment_recovery_scans_the_remote_conversation_once() { } #[tokio::test] -async fn issue_source_ensures_pr_with_frozen_plan_and_one_native_activation() { +async fn issue_source_adopts_an_existing_pr_with_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, @@ -332,13 +336,6 @@ async fn issue_source_ensures_pr_with_frozen_plan_and_one_native_activation() { 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( @@ -356,6 +353,24 @@ async fn issue_source_ensures_pr_with_frozen_plan_and_one_native_activation() { 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(); match fence { "reset" => { @@ -416,11 +431,22 @@ 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 remote = Arc::new(Mutex::new(Remote { + create_pr: 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!(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); @@ -439,11 +465,27 @@ async fn initial_ensure_bootstrap_pr_association_and_restart_do_not_duplicate_mu "missing durable request: {body}" ); } - fixture.db().execute("UPDATE github_write_outbox SET lifecycle='sending'", []).unwrap(); + 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 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(); } @@ -453,18 +495,15 @@ async fn source_role_can_publish_related_cross_surface_without_target_profile_ta for target_pr in [true, false] { for fence in ["valid", "invalidated", "profile_changed"] { let fixture = Fixture::new(true); - if !target_pr { + 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(); - } - if !target_pr { fixture.db().execute("UPDATE work_items SET kind='pr',number=9", []).unwrap(); } - assert!( - resolve_source(&fixture.config, Some("pr-codex"), &fixture.invocation()).is_err() - ); let receipt = fixture.comment(); match fence { "invalidated" => { @@ -479,6 +518,7 @@ async fn source_role_can_publish_related_cross_surface_without_target_profile_ta _ => {} } 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() })); @@ -491,7 +531,21 @@ async fn source_role_can_publish_related_cross_surface_without_target_profile_ta "{:?}", result.last_error ); - assert_eq!(remote.lock().unwrap().writes, usize::from(fence == "valid")); + let state = remote.lock().unwrap(); + assert_eq!(state.writes, usize::from(fence == "valid")); + if fence == "valid" { + let role = if target_pr { "Issue Agent" } else { "PR Implementation Agent" }; + assert!(state.comments[0]["body"].as_str().unwrap().contains(role)); + } else { + assert!( + result + .last_error + .as_deref() + .unwrap() + .contains("publication source was invalidated or superseded"), + "{fence}: {result:?}" + ); + } task.abort(); } } diff --git a/src/writer/tests/body_edit.rs b/src/writer/tests/body_edit.rs index 5dd18263..a3abc767 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(); @@ -262,9 +242,14 @@ async fn pr_source_corrects_direct_issue_with_pr_attribution_not_profile_target_ #[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"] - { + for (fence, state, reason) in [ + ("unrelated", "rejected", "target is not a permitted directly associated work item"), + ("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))); @@ -286,34 +271,12 @@ 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()) - .unwrap_err() - .to_string() - .contains("publication Profile does not match source assignment") - ); - } - "turn" => assert!( - resolve_source(&fixture.config, None, &Invocation::Agent("not-current".into())) - .unwrap_err() - .to_string() - .contains("publication turn does not match current runtime worktree") - ), _ => 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(); } @@ -340,6 +303,7 @@ async fn preflight_and_mutation_limits_remain_durable_then_converge_after_restar state.limited = false; state.mutation_limited = false; } + let fixture = fixture.reopen(); let (github, task) = body_server(remote.clone()).await; fixture.due(); fixture.drain(github).await; @@ -379,6 +343,21 @@ async fn own_issue_body_edit_and_input_boundaries_use_the_same_acceptance_path() .unwrap_err(); assert!(error.to_string().contains(expected), "wrong failure: {error}"); } + for (profile, invocation, expected) in [ + ( + Some("pr-codex"), + fixture.invocation(), + "publication Profile does not match source assignment", + ), + ( + None, + Invocation::Agent("not-current".into()), + "publication turn does not match current runtime worktree", + ), + ] { + let error = resolve_source(&fixture.config, profile, &invocation).unwrap_err(); + assert!(error.to_string().contains(expected), "{error}"); + } assert!( resolve_source(&fixture.config, None, &Invocation::Operator) .unwrap_err() diff --git a/src/writer/tests/handoff.rs b/src/writer/tests/handoff.rs index b355b718..0ec25f2e 100644 --- a/src/writer/tests/handoff.rs +++ b/src/writer/tests/handoff.rs @@ -159,7 +159,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| { @@ -219,7 +218,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", "closed-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(); @@ -243,11 +248,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(); @@ -345,43 +348,6 @@ fn handoff_same_key_cannot_change_target_or_impersonate_issue_agent() { ); } -#[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] async fn handoff_transaction_rechecks_source_fence_before_any_wake_or_applied_receipt() { let f = Fixture::new(true); @@ -424,17 +390,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(); @@ -509,9 +476,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, diff --git a/src/writer/tests/implementation_recovery.rs b/src/writer/tests/implementation_recovery.rs index 45edf829..ad637978 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( @@ -187,9 +187,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 +206,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 +225,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); @@ -239,8 +250,16 @@ async fn an_unpublished_request_still_requires_its_original_source_authority() { let remote = Arc::new(Mutex::new(Remote { create_pr: 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/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/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!( From acf71e722fa5922de399a748459881d3d8082923 Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sat, 28 Nov 2026 21:47:20 +0800 Subject: [PATCH 16/43] =?UTF-8?q?chore(ci):=20=E5=9C=A8=E6=89=93=E5=8C=85?= =?UTF-8?q?=E5=8F=98=E6=9B=B4=E7=9A=84=20PR=20=E9=AA=8C=E8=AF=81=E5=8F=8C?= =?UTF-8?q?=E5=B9=B3=E5=8F=B0=E5=BD=92=E6=A1=A3=E5=B9=B6=E6=A0=B8=E5=AF=B9?= =?UTF-8?q?=E6=97=A7=E9=85=8D=E7=BD=AE=E7=8A=B6=E6=80=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/release.yml | 22 ++++++++++++++++++++-- docs/10-prd/acceptance.md | 2 +- tests/browser/draft.test.mjs | 1 + tests/multi_repo.rs | 4 ++++ 4 files changed, 26 insertions(+), 3 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 990600a2..35ba3d2f 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,6 +1,17 @@ name: release on: + pull_request: + paths: + - '.github/workflows/release.yml' + - 'scripts/package.sh' + - 'scripts/verify-package.sh' + - 'Cargo.toml' + - 'config.example.toml' + - 'deploy/otel-collector.example.yaml' + - 'LICENSE' + - 'README.md' + - 'CHANGELOG.md' push: tags: - "v*" @@ -11,7 +22,7 @@ on: required: true permissions: - contents: write + contents: read jobs: build: @@ -32,11 +43,15 @@ jobs: shell: bash env: BRAID_BUILD_TARGET: ${{ matrix.target }} - BRAID_RELEASE_TAG: ${{ github.event.inputs.version || github.ref_name }} + 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: | @@ -45,6 +60,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/docs/10-prd/acceptance.md b/docs/10-prd/acceptance.md index e16185b3..8e678863 100644 --- a/docs/10-prd/acceptance.md +++ b/docs/10-prd/acceptance.md @@ -76,7 +76,7 @@ BRAID_BINARY=/absolute/path/to/braid CHROME_BIN=/absolute/path/to/chromium \ Pi 安装变更触发独立的 Linux `pi-runtime` 工作流:按 lock 安装 background 插件,启动安装包中的 Node/Pi,以真实 RPC 读取状态、运行工具、关闭执行并离线 检查回执。安装步骤需要访问发行站点和 npm;模型未参与。其它插件组合和含模型 -会话各自单独记录。发行工作流在每个平台上传前运行 +会话各自单独记录。修改打包入口和包内材料的 PR 以及实际发行均在两个目标平台运行 `scripts/verify-package.sh DIST RELEASE_TAG RUST_TARGET`;它从校验和指定的 归档中运行 binary,核对版本、示例配置及迁移后重开的数据库。 diff --git a/tests/browser/draft.test.mjs b/tests/browser/draft.test.mjs index 1de9bc1d..2051d350 100644 --- a/tests/browser/draft.test.mjs +++ b/tests/browser/draft.test.mjs @@ -63,6 +63,7 @@ test('并发编辑被拒绝后保留本页草稿,重新打开对象可读到 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(); diff --git a/tests/multi_repo.rs b/tests/multi_repo.rs index 4a2abb14..ef6c9524 100644 --- a/tests/multi_repo.rs +++ b/tests/multi_repo.rs @@ -165,10 +165,14 @@ fn instance_selectors_route_to_the_expected_config_and_doctor_names_cross_instan 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()); let report: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); From 51e93760c968915ea6d840a7a6353e8aa5ac5205 Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sat, 28 Nov 2026 21:47:43 +0800 Subject: [PATCH 17/43] =?UTF-8?q?fix(platform):=20=E7=BB=91=E5=AE=9A?= =?UTF-8?q?=E5=90=88=E5=B9=B6=E5=9B=9E=E6=89=A7=E7=9A=84=E5=8E=9F=E8=AF=B7?= =?UTF-8?q?=E6=B1=82=E5=B9=B6=E5=85=BC=E5=AE=B9=E5=B7=B2=E5=AF=BC=E5=85=A5?= =?UTF-8?q?=E7=9A=84=20Local=20=E5=91=BD=E4=BB=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 不同请求不能接管已经移动的 Git ref;原请求重放使用原有授权事实 - 从真实旧格式命令、哈希及独立导入库检验回放,保留权限与修订约束 --- src/console/tests.rs | 129 ++++++++----- src/platform/objects.rs | 56 +++--- src/platform/objects/commands.rs | 39 +++- src/platform/tests.rs | 300 +++++++++++++++++++++++++++---- src/run.rs | 21 +-- tests/console.rs | 101 ++++------- 6 files changed, 456 insertions(+), 190 deletions(-) diff --git a/src/console/tests.rs b/src/console/tests.rs index 50f027f8..f6246a67 100644 --- a/src/console/tests.rs +++ b/src/console/tests.rs @@ -16,11 +16,7 @@ use opentelemetry_proto::tonic::{ use prost::Message as _; use reqwest::StatusCode; use serde_json::Value; -use std::{ - io::Write as _, - path::PathBuf, - sync::{Arc, Mutex}, -}; +use std::{io::Write as _, path::PathBuf}; struct Collector { root: PathBuf, @@ -48,11 +44,10 @@ impl Collector { } async fn start(&mut self) { - let storage = - Arc::new(Mutex::new(Storage::open(&self.root.join("observations.sqlite3")).unwrap())); + 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(api::ApiState { storage }); + let app = api::routes(storage); let (stop, stopped) = tokio::sync::oneshot::channel(); self.stop = Some(stop); self.server = Some(tokio::spawn(async move { @@ -206,6 +201,9 @@ async fn otlp_signals_raw_bytes_duplicates_and_cursor_pages_survive_reopening() 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()), @@ -228,6 +226,8 @@ async fn otlp_signals_raw_bytes_duplicates_and_cursor_pages_survive_reopening() 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()); @@ -255,9 +255,23 @@ async fn otlp_signals_raw_bytes_duplicates_and_cursor_pages_survive_reopening() .unwrap() .is_empty() ); - let filtered = collector.get("/api/records?signal=logs&session=log-session&turn=turn-B").await; - assert_eq!(filtered["records"].as_array().unwrap().len(), 1); - assert_eq!(filtered["records"][0]["data"]["body"]["stringValue"], "retained evidence"); + 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)) @@ -294,41 +308,72 @@ async fn expect_error(response: reqwest::Response, status: StatusCode, code: i32 #[tokio::test] async fn malformed_exports_reach_their_expected_guard_and_retain_rejected_bytes() { let mut collector = Collector::new().await; - for (encoding, body, status, reason) in [ - ("br", vec![0xff], StatusCode::UNSUPPORTED_MEDIA_TYPE, "unsupported Content-Encoding: br"), - ("identity", vec![0xff], StatusCode::BAD_REQUEST, "decode OTLP logs protobuf"), - ("gzip", vec![0xff], StatusCode::BAD_REQUEST, "decode gzip OTLP body"), - ] { - expect_error(collector.export("logs", encoding, &body).await, status, 3, reason).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; } - let wrong_type = collector - .client - .post(format!("{}/v1/logs", collector.url)) - .header("content-type", "application/json") - .body(log_body()) - .send() - .await - .unwrap(); - expect_error(wrong_type, StatusCode::UNSUPPORTED_MEDIA_TYPE, 3, "Content-Type").await; assert_eq!(collector.get("/api/resources").await["batches"], 0); - let errors = collector.get("/api/receive-errors").await; - assert_eq!(errors["errors"].as_array().unwrap().len(), 4); - let id = errors["errors"][1]["id"].as_i64().unwrap(); collector.shutdown().await; collector.start().await; - assert_eq!(collector.get("/api/receive-errors").await, errors); - let body = collector - .client - .get(format!("{}/api/receive-errors/{id}", collector.url)) - .send() - .await - .unwrap() - .error_for_status() - .unwrap() - .bytes() - .await - .unwrap(); - assert_eq!(body.as_ref(), [0xff]); + 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; } diff --git a/src/platform/objects.rs b/src/platform/objects.rs index 1ef6552d..79de5d0f 100644 --- a/src/platform/objects.rs +++ b/src/platform/objects.rs @@ -837,20 +837,27 @@ impl PlatformObjects { |r| Ok((r.get(0)?, r.get(1)?)), ) .optional()?; - if let Some((state, Some(commit))) = &receipt - && (state == "applied" - || (state == "prepared" - && git.refname_to_id(&base_ref)? == git2::Oid::from_str(commit)?)) - { - let result = - MergeResult { number, merge_commit: commit.clone(), base_ref, recovered: true }; - self.finish_merge(&result, author, request_id)?; - return Ok(result); + if let Some((state, commit)) = receipt { + if state == "applied" { + let result = MergeResult { + number, + merge_commit: commit.context("applied merge lacks a commit")?, + base_ref, + recovered: true, + }; + self.finish_merge(&result, author, request_id)?; + return Ok(result); + } + // The owner retries through recover_merge_request with its bound receipt. + // A new request cannot adopt or attribute the original owner's Git effect. + ensure!( + state != "prepared", + "another merge request already owns this prepared intent; inspect its original receipt" + ); + bail!( + "previous merge attempt failed or conflicted; inspect its stored error and create a new PR candidate" + ); } - ensure!( - receipt.as_ref().is_none_or(|(s, _)| s == "prepared"), - "previous merge attempt failed or conflicted; inspect its stored error and create a new PR candidate" - ); ensure!(item.state == "open", "PR #{number} is closed"); ensure!( git.refname_to_id(&base_ref)? == expected_base, @@ -862,11 +869,7 @@ impl PlatformObjects { "head revision moved since this PR candidate was created" ); reject_checked_out(&git, &base_ref)?; - let merge_commit = if let Some((_, Some(commit))) = receipt { - git2::Oid::from_str(&commit)? - } else { - self.prepare_merge(&git, &item, expected_base, expected_head)? - }; + let merge_commit = self.prepare_merge(&git, &item, expected_base, expected_head)?; let result = self.prepare_merge_request(&item, &base_ref, merge_commit, request_id)?; self.adopt_merge_ref( &git, @@ -996,19 +999,18 @@ impl PlatformObjects { let tx = write_transaction(&mut self.connection)?; validate_writer(&tx, self.writer.as_ref())?; validate_revision(&tx, &self.repository, self.revision_guard)?; - tx.execute("INSERT OR IGNORE INTO local_merges(pr_number,expected_base,expected_head,merge_commit,lifecycle,created_at,updated_at) VALUES(?1,?2,?3,?4,'prepared',?5,?5)", params![sql_id(item.number)?,item.base_commit,item.head_commit,commit.to_string(),now()])?; - let (base,head,commit,state):(String,String,Option,String)=tx.query_row("SELECT expected_base,expected_head,merge_commit,lifecycle FROM local_merges WHERE pr_number=?1",[sql_id(item.number)?],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?)))?; - ensure!( - Some(&base) == item.base_commit.as_ref() && Some(&head) == item.head_commit.as_ref(), - "another merge intent already owns a different candidate" - ); + let inserted = tx.execute( + "INSERT INTO local_merges(pr_number,expected_base,expected_head,merge_commit,lifecycle,created_at,updated_at) + VALUES(?1,?2,?3,?4,'prepared',?5,?5) ON CONFLICT(pr_number) DO NOTHING", + params![sql_id(item.number)?, item.base_commit, item.head_commit, commit.to_string(), now()], + )?; ensure!( - matches!(state.as_str(), "prepared" | "applied"), - "canonical merge intent is {state}; inspect its persisted failure" + inserted == 1, + "another merge request already owns this intent; inspect its original receipt" ); let result = MergeResult { number: item.number, - merge_commit: commit.context("canonical merge intent lacks a commit")?, + merge_commit: commit.to_string(), base_ref: base_ref.into(), recovered: false, }; diff --git a/src/platform/objects/commands.rs b/src/platform/objects/commands.rs index 5ace4f90..1cbab29a 100644 --- a/src/platform/objects/commands.rs +++ b/src/platform/objects/commands.rs @@ -20,7 +20,30 @@ pub struct CommandRequest { pub writer: Option, } -#[derive(Debug, Clone, Deserialize, Serialize)] +// Schema-5 Local receipts bound these fields to a Human command. New envelopes +// also bind actor and writer, so the checksums differ after an explicit import. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct LocalRequest { + request_id: String, + expected_revision: Option, + command: ObjectCommand, +} + +impl CommandRequest { + fn matches_imported_receipt(&self, stored: &str, stored_digest: &str) -> bool { + self.actor == "human" + && self.writer.is_none() + && hex::encode(Sha256::digest(stored)) == stored_digest + && serde_json::from_str::(stored).is_ok_and(|prior| { + self.request_id == prior.request_id + && self.expected_revision == prior.expected_revision + && self.command == prior.command + }) + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)] #[serde( tag = "type", rename_all = "camelCase", @@ -89,7 +112,7 @@ pub enum ObjectCommand { }, } -#[derive(Debug, Clone, Deserialize, Serialize)] +#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)] #[serde( tag = "type", rename_all = "camelCase", @@ -268,9 +291,15 @@ impl PlatformObjects { payload: &str, digest: &str, ) -> Result, CommandFailure> { - let existing=self.connection.query_row("SELECT payload_sha256 FROM control_receipts WHERE scope='objects' AND request_id=?1",[&request.request_id],|r|r.get::<_,String>(0)).optional().map_err(CommandFailure::rejected)?; - if let Some(existing) = existing { - if existing != digest { + let existing = self.connection.query_row( + "SELECT payload_sha256,request_json FROM control_receipts WHERE scope='objects' AND request_id=?1", + [&request.request_id], + |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)), + ).optional().map_err(CommandFailure::rejected)?; + if let Some((stored_digest, stored_request)) = existing { + if stored_digest != digest + && !request.matches_imported_receipt(&stored_request, &stored_digest) + { return Err(CommandFailure::conflict( "requestId was already used for a different command", )); diff --git a/src/platform/tests.rs b/src/platform/tests.rs index cade6709..515bc62f 100644 --- a/src/platform/tests.rs +++ b/src/platform/tests.rs @@ -104,6 +104,24 @@ impl Fixture { receipt } + async fn mint(&self, number: u64, id: &str, expected_epoch: u64, run: Option<&str>) -> Value { + let cursor = self.get("/api/platform/events").await["lastSequence"].as_u64().unwrap(); + let (status, grant) = self + .post( + "/api/platform/grants", + &json!({ + "requestId":id, "clientId":"harness", "itemNumber":number, "actor":"worker", + "expectedEpoch":expected_epoch, "runId":run, "authorityCursor":cursor, + "executionId":uuid::Uuid::now_v7().to_string(), + }), + ) + .await; + assert_eq!(status, StatusCode::OK, "{grant}"); + assert_eq!(grant["lifecycle"], "active", "{grant}"); + assert_eq!(grant["epoch"], expected_epoch + 1); + json!({"grantId":grant["grantId"],"epoch":grant["epoch"],"token":grant["token"]}) + } + async fn create_issue(&self) { let receipt = self .apply( @@ -182,13 +200,7 @@ async fn revoked_writer_cannot_write_with_the_current_object_revision_after_rest let mut fixture = Fixture::new().await; fixture.create_issue().await; fixture.apply("assign", Some(1), json!({"type":"assign", "number":1, "actor":"worker"})).await; - let grant_request = json!({"requestId":"grant", "clientId":"harness", "itemNumber":1, - "actor":"worker", "expectedEpoch":0}); - let (status, grant) = fixture.post("/api/platform/grants", &grant_request).await; - assert_eq!(status, StatusCode::OK, "{grant}"); - assert_eq!(grant["epoch"], 1); - let capability = - json!({"grantId":grant["grantId"], "epoch":grant["epoch"], "token":grant["token"]}); + let capability = fixture.mint(1, "grant", 0, None).await; let write = json!({"requestId":"write", "expectedRevision":2, "actor":"worker", "writer":capability, "command":{"type":"comment", "number":1, "body":"accepted", "replyTo":null}}); let (status, accepted) = fixture.post("/api/control/commands", &write).await; @@ -224,6 +236,81 @@ async fn revoked_writer_cannot_write_with_the_current_object_revision_after_rest fixture.shutdown().await; } +#[tokio::test] +async fn object_authority_changes_invalidate_grants_even_when_grant_rows_cannot_be_updated() { + let mut fixture = Fixture::new().await; + fixture.create_issue().await; + fixture.apply("assign", Some(1), json!({"type":"assign","number":1,"actor":"worker"})).await; + let db = rusqlite::Connection::open(&fixture.config.database).unwrap(); + let block_grant_updates = || { + db.execute_batch( + "CREATE TRIGGER publication_offline BEFORE UPDATE ON platform_grants + BEGIN SELECT RAISE(ABORT, 'grant update unavailable'); END;", + ) + .unwrap() + }; + let epoch_path = "/api/platform/grants?clientId=harness&itemNumber=1&actor=worker"; + let unscoped = fixture.mint(1, "unscoped", 0, None).await; + block_grant_updates(); + fixture.apply("reassign", Some(2), json!({"type":"assign","number":1,"actor":"worker"})).await; + assert_eq!(fixture.get(epoch_path).await, json!({"active":false,"epoch":1})); + assert_stale_write(&fixture, "late-after-reassignment", &unscoped).await; + let revision = fixture.get("/api/control/items/1").await["item"]["revision"].as_u64().unwrap(); + fixture + .apply( + "register", + Some(revision), + json!({"type":"configureRunRoot", "number":1, + "deliveryRef":"refs/heads/braid/test", "runId":"test-run", "clientId":"harness"}), + ) + .await; + let public = fixture.get("/api/platform/context/1").await; + let url = "/api/platform/context/1?executionClientId=harness"; + let denied = fixture.client.get(fixture.url(url)).send().await.unwrap(); + assert_eq!(denied.status(), StatusCode::INTERNAL_SERVER_ERROR); + let error: Value = denied.json().await.unwrap(); + assert!( + error["error"]["message"] + .as_str() + .unwrap() + .contains("does not own this registered run scope"), + "{error}" + ); + assert_eq!(fixture.get(&format!("{url}&executionRunId=test-run")).await, public); + db.execute_batch("DROP TRIGGER publication_offline").unwrap(); + let scoped = fixture.mint(1, "scoped", 1, Some("test-run")).await; + block_grant_updates(); + for operation in ["close", "reopen"] { + let revision = + fixture.get("/api/control/items/1").await["item"]["revision"].as_u64().unwrap(); + fixture.apply(operation, Some(revision), json!({"type":operation, "number":1})).await; + } + assert_eq!(fixture.get(epoch_path).await, json!({"active":false,"epoch":2})); + assert_stale_write(&fixture, "late-after-reopen", &scoped).await; + fixture.shutdown().await; +} + +async fn assert_stale_write(fixture: &Fixture, id: &str, writer: &Value) { + let path = "/api/control/items/1"; + let item = fixture.get(path).await; + let (status, body) = fixture + .post( + "/api/control/commands", + &json!({ + "requestId":id, "expectedRevision":item["item"]["revision"], "actor":"worker", + "writer":writer,"command":{"type":"comment","number":1,"body":"stale write"} + }), + ) + .await; + assert_eq!(status, StatusCode::CONFLICT); + assert_eq!(body["state"], "rejected"); + assert!( + body["error"]["message"].as_str().unwrap().contains("writer grant is stale, revoked"), + "{body}" + ); + assert_eq!(fixture.get(path).await, item); +} + #[tokio::test] async fn published_candidate_diff_and_merge_use_the_frozen_commit_after_branch_moves() { let mut fixture = Fixture::new().await; @@ -296,15 +383,7 @@ async fn assigned_pr(fixture: &Fixture) -> Value { fixture .apply("assign-pr", Some(1), json!({"type":"assign", "number":2, "actor":"worker"})) .await; - let (status, grant) = fixture - .post( - "/api/platform/grants", - &json!({"requestId":"grant-pr", - "clientId":"harness", "itemNumber":2, "actor":"worker", "expectedEpoch":0}), - ) - .await; - assert_eq!(status, StatusCode::OK); - json!({"grantId":grant["grantId"],"epoch":grant["epoch"],"token":grant["token"]}) + fixture.mint(2, "grant-pr", 0, None).await } #[tokio::test] @@ -345,6 +424,23 @@ async fn adopted_merge_recovers_its_receipt_after_restart_and_writer_revocation( assert_eq!(status, StatusCode::OK, "{revoked}"); assert_eq!(revoked["lifecycle"], "revoked"); fixture.restart().await; + // Even a newly authorized Human command cannot claim someone else's Git effect. + let (status, other) = fixture + .post( + "/api/control/commands", + &json!({ + "requestId":"other-merge", "expectedRevision":2, "actor":"human", + "command":{"type":"merge","number":2} + }), + ) + .await; + assert_eq!(status, StatusCode::CONFLICT, "new request completed someone else's merge: {other}"); + assert!( + other["error"]["message"].as_str().unwrap().contains("another merge request"), + "{other}" + ); + assert_eq!(fixture.get("/api/control/items/2").await, pending); + assert_eq!(fixture.get("/api/platform/events?after=0").await, before); // A differently bound payload cannot consume this request's prepared result. let mut different = request.clone(); different["actor"] = json!("other-worker"); @@ -362,17 +458,16 @@ async fn adopted_merge_recovers_its_receipt_after_restart_and_writer_revocation( assert_eq!(item["item"]["state"], "closed"); assert_eq!(item["item"]["revision"], 3); assert_eq!(item["merge"]["lifecycle"], "applied"); - let db = rusqlite::Connection::open(&fixture.config.database).unwrap(); - let origins: Vec<(String, String)> = db - .prepare("SELECT actor,origin FROM local_events WHERE detail='merged'") - .unwrap() - .query_map([], |row| Ok((row.get(0)?, row.get(1)?))) - .unwrap() - .collect::>() - .unwrap(); - assert_eq!(origins, [("worker".into(), "agent".into())]); - drop(db); let events = fixture.get("/api/platform/events?after=0").await; + let origins: Vec<_> = events["events"] + .as_array() + .unwrap() + .iter() + .map(|row| &row["event"]) + .filter(|event| event["detail"] == "merged") + .map(|event| (&event["actor_login"], &event["origin"])) + .collect(); + assert_eq!(origins, [(&json!("worker"), &json!("agent"))]); fixture.restart().await; assert_eq!(fixture.post("/api/control/commands", &request).await, (StatusCode::OK, recovered)); assert_eq!(fixture.get("/api/control/items/2").await, item); @@ -388,6 +483,8 @@ async fn prepared_merge_does_not_retry_uncommitted_effects_after_writer_revocati let request = json!({"requestId":"merge-pending", "expectedRevision":2, "actor":"worker", "writer":capability, "command":{"type":"merge", "number":2}}); let db = rusqlite::Connection::open(&fixture.config.database).unwrap(); + let git = git2::Repository::open(&fixture.config.source).unwrap(); + let base = git.refname_to_id("refs/heads/main").unwrap(); db.execute_batch("CREATE TRIGGER fail_intent BEFORE INSERT ON local_merges BEGIN SELECT RAISE(ABORT, 'injected merge intent failure'); END; CREATE TRIGGER lose_receipt BEFORE UPDATE OF response_json ON control_receipts WHEN NEW.request_id='merge-pending' BEGIN SELECT RAISE(ABORT, 'injected receipt storage failure'); END;").unwrap(); let (status, failure) = fixture.post("/api/control/commands", &request).await; @@ -398,8 +495,10 @@ async fn prepared_merge_does_not_retry_uncommitted_effects_after_writer_revocati let item = fixture.get("/api/control/items/2").await; assert!(item["merge"].is_null()); assert_eq!(item["item"]["state"], "open"); - let git = git2::Repository::open(&fixture.config.source).unwrap(); - let base = git.refname_to_id("refs/heads/main").unwrap(); + let receipt = fixture.get("/api/control/receipts/merge-pending").await; + assert_eq!(receipt["state"], "prepared"); + assert!(receipt["result"].is_null()); + assert_eq!(git.refname_to_id("refs/heads/main").unwrap(), base); db.execute_batch("DROP TRIGGER fail_intent; DROP TRIGGER lose_receipt;").unwrap(); drop(db); let (status, revoked) = fixture.post("/api/platform/grants/revoke", &json!({ @@ -460,13 +559,7 @@ async fn publishing_and_its_receipt_commit_together_or_leave_the_candidate_uncha let capability = assigned_pr(&fixture).await; let git = git2::Repository::open(&fixture.config.source).unwrap(); let previous = git.refname_to_id("refs/heads/feature").unwrap(); - let candidate = commit( - &git, - "refs/heads/feature", - "publication -", - &[previous], - ); + let candidate = commit(&git, "refs/heads/feature", "publication\n", &[previous]); let request = json!({"requestId":"publish-lost", "expectedRevision":2, "actor":"worker", "writer":capability, "command":{"type":"publish", "number":2, "candidate":{"type":"commit", "commit":candidate.to_string()}}}); let item = fixture.get("/api/control/items/2").await; @@ -506,3 +599,140 @@ async fn publishing_and_its_receipt_commit_together_or_leave_the_candidate_uncha assert_eq!(fixture.get("/api/platform/events?after=0").await, events); fixture.shutdown().await; } + +#[tokio::test] +async fn imported_local_receipt_replays_the_original_command_and_preserves_the_source() { + let mut fixture = Fixture::new().await; + fixture.shutdown().await; + fixture.config.database = fixture.root.join("imported.sqlite3"); + let legacy = fixture.root.join("legacy.sqlite3"); + let (source, receipt, refused, head) = historical_store(&fixture, &legacy); + let failure = super::store::import(&fixture.config, &legacy).unwrap_err(); + assert!(failure.to_string().contains("source runtime still has an active lease"), "{failure}"); + assert!(!fixture.config.database.exists()); + source.execute("DELETE FROM owner_leases", []).unwrap(); + for (prepare, settle) in [ + ("UPDATE control_receipts SET state='prepared' WHERE request_id='old-comment'", + "UPDATE control_receipts SET state='applied' WHERE request_id='old-comment'"), + ("INSERT INTO local_merges(pr_number,expected_base,expected_head,lifecycle,created_at,updated_at) + SELECT number,base_commit,head_commit,'prepared','then','then' FROM local_items WHERE number=8", + "DELETE FROM local_merges WHERE pr_number=8"), + ] { + source.execute_batch(prepare).unwrap(); + let error = super::store::import(&fixture.config, &legacy).unwrap_err(); + assert!(error.to_string().contains("source contains unresolved prepared"), "{error}"); + assert!(!fixture.config.database.exists()); + source.execute_batch(settle).unwrap(); + } + drop(source); + let original = std::fs::read(&legacy).unwrap(); + super::store::import(&fixture.config, &legacy).unwrap(); + assert_eq!(std::fs::read(&legacy).unwrap(), original); + fixture.start().await; + let ctx = fixture.get("/api/platform/context/7").await; + assert_eq!(ctx["node_id"], "local:contract-space:item:7"); + assert_eq!(ctx["body"], "Design"); + assert_eq!(ctx["comments"][0]["node_id"], "local:contract-space:comment:9"); + assert_eq!(ctx["associated_prs"][0]["number"], 8); + let diff = fixture.get("/api/control/items/8/diff").await; + assert_eq!(diff["headCommit"], head.to_string()); + assert!(diff["diff"].as_str().unwrap().contains("+Legacy implementation")); + let events = fixture.get("/api/platform/events").await; + assert_eq!(events["lastSequence"], 11); + assert_eq!(events["events"][0]["event"]["delivery_guid"], "local:11"); + assert_eq!(fixture.get("/api/control/receipts/old-comment").await, receipt); + let request: Value = serde_json::from_str(REQUEST).unwrap(); + let (status, replay) = fixture.post("/api/control/commands", &request).await; + assert_eq!(status, StatusCode::OK, "same imported command must replay its receipt: {replay}"); + assert_eq!(replay, receipt); + // The public spelling changed from profile to actor. A previously rejected + // assignment stays rejected after import, even though today's platform accepts any actor. + let mut retry: Value = serde_json::from_str(OLD_ASSIGN).unwrap(); + retry["command"] = json!({"type":"assign","number":7,"actor":"unregistered"}); + assert_eq!( + fixture.post("/api/control/commands", &retry).await, + (StatusCode::CONFLICT, refused) + ); + retry["command"]["actor"] = json!("someone-else"); + let (status, conflict) = fixture.post("/api/control/commands", &retry).await; + assert_eq!(status, StatusCode::CONFLICT); + assert!(conflict["error"]["message"].as_str().unwrap().contains("requestId was already used")); + for different in [ + json!({"actor":"other"}), + json!({"writer":{"grantId":"another","epoch":1,"token":"test"}}), + json!({"command":{"type":"comment","number":7,"body":"Changed","replyTo":null}}), + ] { + let mut other = request.clone(); + for (key, value) in different.as_object().unwrap() { + other[key] = value.clone(); + } + let (status, error) = fixture.post("/api/control/commands", &other).await; + assert_eq!(status, StatusCode::CONFLICT, "{error}"); + assert!(error["error"]["message"].as_str().unwrap().contains("requestId was already used")); + } + assert_eq!(fixture.get("/api/platform/context/7").await, ctx); + assert_eq!(fixture.get("/api/platform/events").await, events); + fixture.shutdown().await; +} + +// Schema 5 Local serialized neither actor nor writer. Keep its bytes independent +// of today's command encoder, including the historical field order. +const REQUEST: &str = r#"{"requestId":"old-comment","expectedRevision":1,"command":{"type":"comment","number":7,"body":"Discussion","replyTo":null}}"#; +const OLD_ASSIGN: &str = r#"{"requestId":"old-assign","expectedRevision":2,"command":{"type":"assign","number":7,"profile":"unregistered"}}"#; + +fn historical_store( + fixture: &Fixture, + legacy: &std::path::Path, +) -> (rusqlite::Connection, Value, Value, git2::Oid) { + use sha2::{Digest as _, Sha256}; + + let source = rusqlite::Connection::open(legacy).unwrap(); + for (version, name, migration) in [ + (1, "initial", include_str!("../../migrations/0001_initial.sql")), + (2, "event_kinds", include_str!("../../migrations/0002_event_kinds.sql")), + (3, "turn_errors", include_str!("../../migrations/0003_turn_errors.sql")), + (4, "local_collaboration", include_str!("../../migrations/0004_local_collaboration.sql")), + (5, "control_receipts", include_str!("../../migrations/0005_control_receipts.sql")), + ] { + source.execute_batch(migration).unwrap(); + source + .execute( + "INSERT INTO schema_migrations VALUES(?1,?2,?3,'then')", + rusqlite::params![version, name, hex::encode(Sha256::digest(migration))], + ) + .unwrap(); + } + source.execute_batch( + "INSERT INTO local_items(number,repository,kind,title,body,author,revision,created_at,updated_at) + VALUES(7,'contract-space','issue','Legacy','Design','human',2,'then','then'); + INSERT INTO local_comments(comment_id,item_number,author,body,created_at) + VALUES(9,7,'human','Discussion','then'); + INSERT INTO local_events(event_id,item_number,kind,detail,actor,body,revision,item_state,created_at,consumed_at) + VALUES(11,7,'wake','comment','human','Discussion',2,'open','then','then'); + INSERT INTO owner_leases VALUES('runtime',1,'old','9999-12-31T00:00:00Z');", + ).unwrap(); + source + .execute( + "INSERT INTO local_space VALUES(1,'contract-space',?1)", + [fixture.config.source.to_str().unwrap()], + ) + .unwrap(); + let receipt = json!({"requestId":"old-comment", "state":"applied", "error":null, + "result":{"comment_id":9,"operational":false,"reply_to":null,"author":"human", + "body":"Discussion","created_at":"then"}}); + source.execute("INSERT INTO control_receipts VALUES('objects','old-comment',?1,?2,'applied',?3,NULL,'then','then')", + rusqlite::params![hex::encode(Sha256::digest(REQUEST)), REQUEST, receipt.to_string()]).unwrap(); + let refused = json!({"requestId":"old-assign", "state":"rejected", "result":null, + "error":{"code":"rejected","message":"runtime supports profile issue-codex for issue objects"}}); + source.execute("INSERT INTO control_receipts VALUES('objects','old-assign',?1,?2,'rejected',?3,'runtime supports profile issue-codex for issue objects','then','then')", + rusqlite::params![hex::encode(Sha256::digest(OLD_ASSIGN)), OLD_ASSIGN, refused.to_string()]).unwrap(); + let git = git2::Repository::open(&fixture.config.source).unwrap(); + let base = git.refname_to_id("refs/heads/main").unwrap(); + let head = commit(&git, "refs/heads/legacy", "Legacy implementation\n", &[base]); + source.execute("INSERT INTO local_items(number,repository,kind,title,body,author,head_ref,base_ref, + head_commit,base_commit,created_at,updated_at) VALUES(8,'contract-space','pr','Implementation', + 'Closes #7','human','legacy','main',?1,?2,'then','then')", + rusqlite::params![head.to_string(),base.to_string()]).unwrap(); + source.execute("INSERT INTO local_links VALUES(7,8)", []).unwrap(); + (source, receipt, refused, head) +} diff --git a/src/run.rs b/src/run.rs index f8328f6c..4127f1b6 100644 --- a/src/run.rs +++ b/src/run.rs @@ -431,18 +431,19 @@ mod tests { #[test] fn observability_changes_do_not_change_the_frozen_run_recipe() { - let fixture = crate::writer::tests::Fixture::new(false); - let mut config = fixture.config.clone(); - let frozen = config.runtime.database().with_extension("frozen.toml"); - let original = toml::to_string_pretty(&config).unwrap(); - std::fs::write(&frozen, &original).unwrap(); - config.telemetry.incident_mode = !config.telemetry.incident_mode; - config.telemetry.sample_ratio = 1.0; - check_frozen_recipe(&frozen, &toml::to_string_pretty(&config).unwrap()).unwrap(); + let original = include_str!("../config.example.toml"); + let frozen = + std::env::temp_dir().join(format!("braid-recipe-{}.toml", uuid::Uuid::now_v7())); + std::fs::write(&frozen, original).unwrap(); + let mut requested: toml::Table = original.parse().unwrap(); + requested["telemetry"]["incident_mode"] = true.into(); + requested["telemetry"]["sample_ratio"] = 1.0.into(); + check_frozen_recipe(&frozen, &toml::to_string(&requested).unwrap()).unwrap(); assert_eq!(std::fs::read_to_string(&frozen).unwrap(), original); - config.profiles[0].model = Some("different-model".into()); + requested["profiles"][0]["model"] = "different-model".into(); let error = - check_frozen_recipe(&frozen, &toml::to_string_pretty(&config).unwrap()).unwrap_err(); + check_frozen_recipe(&frozen, &toml::to_string(&requested).unwrap()).unwrap_err(); + std::fs::remove_file(frozen).unwrap(); assert!(error.is::()); } } diff --git a/tests/console.rs b/tests/console.rs index e9546bc5..21c263d8 100644 --- a/tests/console.rs +++ b/tests/console.rs @@ -183,6 +183,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(); @@ -397,7 +403,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 +414,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 +423,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 +432,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 +467,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}" ); } From fe82de33d851d13dffa62f9fd07e42214b9189c0 Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sat, 28 Nov 2026 21:47:43 +0800 Subject: [PATCH 18/43] =?UTF-8?q?ref(provider):=20=E9=80=9A=E8=BF=87?= =?UTF-8?q?=E5=8E=9F=E7=94=9F=E5=8D=8F=E8=AE=AE=E5=B8=A7=E3=80=81=E8=BF=9B?= =?UTF-8?q?=E7=A8=8B=E5=92=8C=20OTLP=20=E5=88=86=E4=BF=A1=E5=8F=B7?= =?UTF-8?q?=E8=AF=81=E6=98=8E=E7=BB=88=E6=80=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- native/pi/tests/managed-process.test.mjs | 13 +-- src/profile_materials/tests.rs | 60 +++++++++++- src/provider/codex.rs | 28 ++++++ src/provider/pi_tests.rs | 43 ++++++++ src/telemetry/tests.rs | 120 +++++++++++++++-------- 5 files changed, 214 insertions(+), 50 deletions(-) diff --git a/native/pi/tests/managed-process.test.mjs b/native/pi/tests/managed-process.test.mjs index a8fd650f..a47afa6b 100644 --- a/native/pi/tests/managed-process.test.mjs +++ b/native/pi/tests/managed-process.test.mjs @@ -69,13 +69,14 @@ function execution(t) { }; } -function assertNotExecuting(pid) { +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); - assert.ok(!observed.stdout.trim() || /^[ZX]/.test(observed.stdout.trim()), `PID ${pid} still executes: ${observed.stdout}`); + 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 => { @@ -92,11 +93,11 @@ test('owned stop reaches a real grandchild and fences later launches', { timeout assert.ok(Number.isInteger(leaf) && leaf > 1); fixture.track(started.payload_pid); fixture.track(leaf); - assert.doesNotThrow(() => process.kill(leaf, 0)); + 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)); - assertNotExecuting(started.payload_pid); - assertNotExecuting(leaf); + 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); @@ -123,7 +124,7 @@ test('ambiguous persisted ownership reports unknown without killing the payload' const result = await cleanupOwnedExecution({ directory: fixture.directory, id: fixture.id }); assert.equal(result.status, 'unknown'); assert.match(result.reason, /another boot identity/); - assert.doesNotThrow(() => process.kill(started.payload_pid, 0)); + 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 { diff --git a/src/profile_materials/tests.rs b/src/profile_materials/tests.rs index 34982685..3d57b732 100644 --- a/src/profile_materials/tests.rs +++ b/src/profile_materials/tests.rs @@ -1,12 +1,16 @@ use super::*; use serde_json::{Value, json}; -fn configuration(root: &Path, kind: CredentialKind) -> Config { +fn configuration(root: &Path, kind: CredentialKind, install: Option<&Path>) -> Config { let mut config: Config = toml::from_str(include_str!("../../config.example.toml")).unwrap(); for runtime in &mut config.runtimes { runtime.adapter_type = "pi".into(); runtime.version = "1.1.0".into(); runtime.home = None; + if let Some(install) = install { + runtime.executable = install.join("pi"); + runtime.native_runtime = Some(install.join("runtime-manifest.json")); + } } for profile in &mut config.profiles { profile.adapter_type = "pi".into(); @@ -60,7 +64,7 @@ fn snapshot_writes_native_model_fields_and_keeps_credentials_out_of_models_json( ] { let directory = root.join(name); fs::create_dir_all(&directory).unwrap(); - let config = configuration(&directory, kind); + let config = configuration(&directory, kind, None); let profile = &config.profiles[0]; let materials = collect(&config, profile).unwrap(); let home_key = uuid::Uuid::now_v7().to_string(); @@ -88,3 +92,55 @@ fn snapshot_writes_native_model_fields_and_keeps_credentials_out_of_models_json( } fs::remove_dir_all(root).unwrap(); } + +#[cfg(unix)] +#[tokio::test] +#[ignore = "installed Pi distribution; run with BRAID_TEST_PI_INSTALL and PI_OFFLINE=1"] +async fn failed_home_binding_stops_the_installed_execution_before_returning() { + let install = PathBuf::from(std::env::var_os("BRAID_TEST_PI_INSTALL").unwrap()); + let root = std::env::temp_dir().join(format!("braid-pi-bind-{}", uuid::Uuid::now_v7())); + let homes = root.join(".braid/pi-homes"); + fs::create_dir_all(&homes).unwrap(); + // A real post-launch metadata write fails after the SDK has opened its session. + fs::write(homes.join("index"), "not a directory").unwrap(); + let config = configuration(&root, CredentialKind::None, Some(&install)); + let profile = config.profiles[0].clone(); + let factories = crate::provider::session_factories(&config).unwrap(); + let factory = &factories[&profile.id]; + let result = factory.start(profile, String::new(), "initial context".into()).await; + + let mut executions = fs::read_dir(root.join(".braid/native-executions")).unwrap(); + let execution = executions.next().unwrap().unwrap(); + assert!(executions.next().is_none()); + let id = execution.file_name(); + let receipt = fs::read(execution.path().join("execution-stop.json")); + if receipt.is_err() { + // Reclaim only this test's execution when an old/broken adapter abandons it. + let cleanup = std::process::Command::new(install.join("bin/node")) + .arg(install.join("managed.mjs")) + .args(["cleanup", "--execution-dir"]) + .arg(execution.path()) + .arg("--execution-id") + .arg(&id) + .output() + .unwrap(); + assert!(cleanup.status.success()); + let cleanup: Value = serde_json::from_slice(&cleanup.stdout).unwrap(); + assert_eq!(cleanup["status"], "stopped", "{cleanup}"); + } + fs::remove_dir_all(root).unwrap(); + assert!( + matches!(result, Err(crate::agent_session::SessionError::Failed(ref reason)) + if reason.contains("cannot bind Pi session native home")), + "{:?}", + result.err() + ); + let receipt: Value = serde_json::from_slice( + &receipt.expect("failed factory construction omitted the owned-stop receipt"), + ) + .unwrap(); + assert_eq!(receipt["execution_id"], id.to_str().unwrap()); + assert_eq!(receipt["scope"], "execution"); + assert_eq!(receipt["status"], "stopped"); + assert_eq!(receipt["coverage"], "registered-process-groups-and-inherited-execution-markers"); +} diff --git a/src/provider/codex.rs b/src/provider/codex.rs index cc650de9..b8414d4c 100644 --- a/src/provider/codex.rs +++ b/src/provider/codex.rs @@ -399,3 +399,31 @@ fn parse_codex_notification(frame: &Value) -> Option { _ => None, } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn retryable_errors_do_not_finish_a_codex_turn_before_its_terminal_frame() { + assert!( + parse_codex_notification(&json!({ + "method":"error","params":{"threadId":"thread-A","turnId":"turn-B", + "error":{"message":"connection lost"},"willRetry":true} + })) + .is_none() + ); + let started = parse_codex_notification(&json!({"method":"turn/started","params":{ + "threadId":"thread-A","turn":{"id":"turn-B","status":"inProgress"} + }})); + assert!(matches!(started, Some(ProviderNotification::TurnStarted { thread_id, turn_id }) + if thread_id == "thread-A" && turn_id == "turn-B")); + let terminal = parse_codex_notification(&json!({"method":"turn/completed","params":{ + "threadId":"thread-A","turn":{"id":"turn-B","status":"failed","error":{"message":"retry exhausted"}} + }})); + assert!( + matches!(terminal, Some(ProviderNotification::TurnCompleted { thread_id, turn_id, status, error: Some(reason) }) + if thread_id == "thread-A" && turn_id == "turn-B" && status == "failed" && reason == "retry exhausted") + ); + } +} diff --git a/src/provider/pi_tests.rs b/src/provider/pi_tests.rs index 2df990f9..2446e33d 100644 --- a/src/provider/pi_tests.rs +++ b/src/provider/pi_tests.rs @@ -35,3 +35,46 @@ fn oauth_material_is_written_in_the_native_format_with_private_permissions() { } std::fs::remove_dir_all(root).unwrap(); } + +#[test] +fn pi_settles_after_retry_and_keeps_terminal_hook_failure_even_when_aborted() { + let mut last_stop = None; + let mut last_error = None; + let mut hook_errors = Vec::new(); + let mut event = |frame: Value| { + parse_pi_event(&frame, "thread", "turn", &mut last_stop, &mut last_error, &mut hook_errors) + }; + for frame in [ + json!({"type":"message_end","message":{"role":"assistant","stopReason":"error","errorMessage":"transient"}}), + json!({"type":"agent_end","willRetry":true}), + json!({"type":"agent_start"}), + json!({"type":"message_end","message":{"role":"assistant","stopReason":"stop"}}), + json!({"type":"message_end","message":{"role":"toolResult"}}), + json!({"type":"agent_end","willRetry":false}), + ] { + assert!(event(frame).is_none(), "intermediate frames must leave the turn open"); + } + assert!(matches!(event(json!({"type":"agent_settled"})), + Some(ProviderNotification::TurnCompleted { thread_id, turn_id, status, error: None }) + if thread_id == "thread" && turn_id == "turn" && status == "completed")); + + assert!(event(json!({"type":"agent_start"})).is_none()); + assert!(matches!(event(json!({"type":"agent_settled"})), + Some(ProviderNotification::TurnCompleted { status, error: Some(_) , .. }) if status == "failed")); + for interrupted in [json!({"aborted":true}), json!({"cancelled":true})] { + assert!(event(json!({"type":"agent_start"})).is_none()); + let mut frame = interrupted; + frame["type"] = "agent_settled".into(); + assert!( + matches!(event(frame), Some(ProviderNotification::TurnCompleted { status, error: None, .. }) + if status == "interrupted") + ); + } + assert!(event(json!({"type":"agent_start"})).is_none()); + assert!(event(json!({ + "type":"extension_error","event":"agent_before_settle","extensionPath":"background.ts","error":"cannot preserve result" + })).is_none()); + assert!(matches!(event(json!({"type":"agent_settled","aborted":true})), + Some(ProviderNotification::TurnCompleted { status, error: Some(reason), .. }) + if status == "failed" && reason.contains("background.ts") && reason.contains("cannot preserve result"))); +} diff --git a/src/telemetry/tests.rs b/src/telemetry/tests.rs index e573727a..b849a20c 100644 --- a/src/telemetry/tests.rs +++ b/src/telemetry/tests.rs @@ -76,11 +76,11 @@ fn telemetry_child() { 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, + github_summary: &format!("summary:{payload}"), + credential: &format!("credential:{payload}"), + provider_transcript: &format!("transcript:{payload}"), + webhook_payload: &format!("webhook:{payload}"), + local_path: &format!("/diagnostic/{payload}"), }), sampled ); @@ -280,57 +280,93 @@ fn verify_otlp(requests: &[(String, Vec)], ratio: &str, probe: bool) { other => panic!("unexpected signal {other}"), } } + verify_payload_records(log_records, &span_ids, ratio == "1", probe); + if ratio == "0" { + assert!(span_ids.is_empty()); + } + let counter = if probe { "braid.telemetry.probes" } else { "braid.runtime.transitions" }; + let metric = metrics + .iter() + .find(|metric| metric.name == counter) + .expect("counter exported even with trace sampling disabled"); + let Some(opentelemetry_proto::tonic::metrics::v1::metric::Data::Sum(sum)) = &metric.data else { + panic!("{counter} is not a counter"); + }; + assert!(sum.data_points.iter().any(|point| matches!(point.value, Some(opentelemetry_proto::tonic::metrics::v1::number_data_point::Value::AsInt(value)) if value > 0))); +} + +fn verify_payload_records( + log_records: Vec, + span_ids: &[(Vec, Vec)], + retained: bool, + probe: bool, +) { let payload = format!("{SENTINEL}{}END", "x".repeat(100_000)); - let mut payload_records = 0; + let mut expected_streams: std::collections::BTreeSet<&str> = if retained && !probe { + ["request", "stdout", "stderr", "cleanup.stdout", "cleanup.stderr"].into() + } else { + std::collections::BTreeSet::new() + }; + let mut payload_events = 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() { + let fields: std::collections::BTreeMap<_, _> = record + .attributes + .iter() + .filter_map(|field| { + use opentelemetry_proto::tonic::common::v1::any_value::Value; + match field.value.as_ref()?.value.as_ref()? { + Value::StringValue(text) => Some((field.key.as_str(), text.as_str())), + _ => None, + } + }) + .collect(); + if !fields.values().any(|value| value.contains(SENTINEL)) { continue; } - payload_records += 1; - assert_eq!(ratio, "1"); + assert!(retained); 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)); + if let Some(&stream) = fields.get("provider.stream") { + assert!(expected_streams.remove(stream), "duplicate or unexpected stream {stream}"); + assert!( + fields.get("provider.transcript") == Some(&payload.as_str()), + "{stream} incomplete" + ); + if stream.starts_with("cleanup.") { + assert_eq!(fields.get("provider.execution.id"), Some(&"execution-test")); + } else { + for (key, expected) in [ + ("braid.provider_session.id", "session-test"), + ("braid.assignment.id", "assignment-test"), + ("braid.turn.id", "turn-test"), + ] { + assert_eq!(fields.get(key), Some(&expected), "{stream}: {key}"); + } } - } - } - assert_eq!( - payload_records, - if ratio == "0" { - 0 - } else if probe { - 1 } else { - 6 + payload_events += 1; + for (field, prefix) in [ + ("github.comment.body", ""), + ("github.comment.summary", "summary:"), + ("credential", "credential:"), + ("provider.transcript", "transcript:"), + ("github.webhook.payload", "webhook:"), + ("local.path", "/diagnostic/"), + ] { + assert!( + fields.get(field).and_then(|value| value.strip_prefix(prefix)) + == Some(payload.as_str()), + "missing, incomplete, or misrouted {field}" + ); + } } - ); - if ratio == "0" { - assert!(span_ids.is_empty()); } - let counter = if probe { "braid.telemetry.probes" } else { "braid.runtime.transitions" }; - let metric = metrics - .iter() - .find(|metric| metric.name == counter) - .expect("counter exported even with trace sampling disabled"); - let Some(opentelemetry_proto::tonic::metrics::v1::metric::Data::Sum(sum)) = &metric.data else { - panic!("{counter} is not a counter"); - }; - assert!(sum.data_points.iter().any(|point| matches!(point.value, Some(opentelemetry_proto::tonic::metrics::v1::number_data_point::Value::AsInt(value)) if value > 0))); + assert!(expected_streams.is_empty(), "missing streams: {expected_streams:?}"); + assert_eq!(payload_events, usize::from(retained)); } From 84ac36207795c410ae495886b36b50f8c50ef3ad Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sat, 28 Nov 2026 21:53:07 +0800 Subject: [PATCH 19/43] =?UTF-8?q?fix(pi):=20=E5=85=B3=E9=97=AD=E6=9E=84?= =?UTF-8?q?=E9=80=A0=E5=A4=B1=E8=B4=A5=E7=9A=84=E6=89=A7=E8=A1=8C=E5=B9=B6?= =?UTF-8?q?=E4=BF=9D=E7=95=99=E5=90=8E=E5=8F=B0=E6=B8=85=E7=90=86=E6=9C=AA?= =?UTF-8?q?=E7=A1=AE=E8=AE=A4=E7=8A=B6=E6=80=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 在工厂交出会话前统一收口错误,按 native 完整回执报告停止 - 使用安装后的 Pi 和公开工具重放失败路径,Linux CI 复用 Rust 产物验证跨语言边界 --- .github/workflows/ci.yml | 17 ++++ .github/workflows/pi-runtime.yml | 23 ----- docs/10-prd/acceptance.md | 4 +- .../pi/acceptance/installed-runtime.test.mjs | 32 +++++++ .../pi-background-bash-1.0.5-braid.patch | 54 +++++++----- src/platform/tests.rs | 2 +- src/provider/factory.rs | 38 ++++++-- src/provider/pi.rs | 86 ++++--------------- src/telemetry/tests.rs | 9 +- src/tunnel/tests.rs | 58 ++++++++----- src/writer/tests.rs | 3 +- 11 files changed, 179 insertions(+), 147 deletions(-) delete mode 100644 .github/workflows/pi-runtime.yml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 95239ad3..80cafe68 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -24,6 +24,8 @@ 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: @@ -33,6 +35,21 @@ jobs: - 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/provider.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 + 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: diff --git a/.github/workflows/pi-runtime.yml b/.github/workflows/pi-runtime.yml deleted file mode 100644 index 65ddd4a0..00000000 --- a/.github/workflows/pi-runtime.yml +++ /dev/null @@ -1,23 +0,0 @@ -name: pi-runtime -on: - pull_request: - paths: ['native/pi/**', '.github/workflows/pi-runtime.yml'] - push: - branches: [main] - paths: ['native/pi/**', '.github/workflows/pi-runtime.yml'] -permissions: - contents: read - -jobs: - installed-runtime: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 - with: - node-version: 24.15.0 - - name: Exercise an installed Pi runtime without a model - run: | - export BRAID_TEST_PI_INSTALL="$RUNNER_TEMP/pi-background" - node native/pi/install.mjs "$BRAID_TEST_PI_INSTALL" --plugins background - node --test native/pi/acceptance/installed-runtime.test.mjs diff --git a/docs/10-prd/acceptance.md b/docs/10-prd/acceptance.md index 8e678863..ff092a94 100644 --- a/docs/10-prd/acceptance.md +++ b/docs/10-prd/acceptance.md @@ -73,9 +73,9 @@ BRAID_BINARY=/absolute/path/to/braid CHROME_BIN=/absolute/path/to/chromium \ node --test tests/browser/draft.test.mjs ``` -Pi 安装变更触发独立的 Linux `pi-runtime` 工作流:按 lock 安装 background +Pi 安装或 Rust 适配器变更时,Linux CI 复用本轮编译并按 lock 安装 background 插件,启动安装包中的 Node/Pi,以真实 RPC 读取状态、运行工具、关闭执行并离线 -检查回执。安装步骤需要访问发行站点和 npm;模型未参与。其它插件组合和含模型 +检查回执。随后故意让真实会话的材料绑定写入失败,核对 Rust 工厂返回前已为该执行留下停止证据。安装步骤需要访问发行站点和 npm,模型未参与。其它插件组合和含模型 会话各自单独记录。修改打包入口和包内材料的 PR 以及实际发行均在两个目标平台运行 `scripts/verify-package.sh DIST RELEASE_TAG RUST_TARGET`;它从校验和指定的 归档中运行 binary,核对版本、示例配置及迁移后重开的数据库。 diff --git a/native/pi/acceptance/installed-runtime.test.mjs b/native/pi/acceptance/installed-runtime.test.mjs index 7d7fa1a7..1c16d671 100644 --- a/native/pi/acceptance/installed-runtime.test.mjs +++ b/native/pi/acceptance/installed-runtime.test.mjs @@ -7,6 +7,7 @@ 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. @@ -98,3 +99,34 @@ test('installed background-only Pi opens a fresh session, serves tools and close assert.equal(offline.coverage, 'registered-process-groups-and-inherited-execution-markers'); assert.deepEqual(JSON.parse(fs.readFileSync(path.join(directory, 'execution-stop.json'), 'utf8')), offline); }); + +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/src/platform/tests.rs b/src/platform/tests.rs index 515bc62f..80076bad 100644 --- a/src/platform/tests.rs +++ b/src/platform/tests.rs @@ -247,7 +247,7 @@ async fn object_authority_changes_invalidate_grants_even_when_grant_rows_cannot_ "CREATE TRIGGER publication_offline BEFORE UPDATE ON platform_grants BEGIN SELECT RAISE(ABORT, 'grant update unavailable'); END;", ) - .unwrap() + .unwrap(); }; let epoch_path = "/api/platform/grants?clientId=harness&itemNumber=1&actor=worker"; let unscoped = fixture.mint(1, "unscoped", 0, None).await; diff --git a/src/provider/factory.rs b/src/provider/factory.rs index d7ff35de..30d42a60 100644 --- a/src/provider/factory.rs +++ b/src/provider/factory.rs @@ -67,7 +67,7 @@ impl SessionFactory for CodexSessions { instructions, Some(context), ) - .await?; + .await; created(session).await } @@ -78,8 +78,7 @@ impl SessionFactory for CodexSessions { instructions: String, ) -> Result { let session = - ProviderAgentSession::resume(self.connection().await?, profile, instructions, id) - .await?; + ProviderAgentSession::resume(self.connection().await?, profile, instructions, id).await; created(session).await } } @@ -114,8 +113,9 @@ impl SessionFactory for PiSessions { ) -> Result { let provider = Arc::new(PiProvider::connect(&self.config)); let session = - ProviderAgentSession::start(provider, profile, instructions, Some(context)).await?; - created(session).await + ProviderAgentSession::start(provider.clone(), profile, instructions, Some(context)) + .await; + finish_pi_session(&provider, session).await } async fn resume( @@ -125,12 +125,34 @@ impl SessionFactory for PiSessions { instructions: String, ) -> Result { let provider = Arc::new(PiProvider::connect(&self.config)); - let session = ProviderAgentSession::resume(provider, profile, instructions, id).await?; - created(session).await + let session = + ProviderAgentSession::resume(provider.clone(), profile, instructions, id).await; + finish_pi_session(&provider, session).await + } +} + +// The factory owns this physical process until a usable session is handed to the group. +// Startup and Context persistence can fail after the native launcher has spawned. +async fn finish_pi_session( + provider: &PiProvider, + session: Result, SessionError>, +) -> Result { + let error = match created(session).await { + Ok(created) => return Ok(created), + Err(error) => error, + }; + match provider.close_failed_construction().await { + Ok(()) => Err(error), + Err(cleanup) => Err(SessionError::Unknown(format!( + "{error}; Pi startup shutdown unconfirmed: {cleanup}" + ))), } } -async fn created(session: Arc) -> Result { +async fn created( + session: Result, SessionError>, +) -> Result { + let session = session?; let id = session .thread_id() .await diff --git a/src/provider/pi.rs b/src/provider/pi.rs index ab438923..824ca238 100644 --- a/src/provider/pi.rs +++ b/src/provider/pi.rs @@ -361,15 +361,9 @@ impl PiProvider { Err(ProviderError::Protocol(message)) } - async fn reject_startup(&self, thread_id: &str, error: ProviderError) -> ProviderError { - match self.close_session(thread_id, true).await { - Ok(()) => { - ProviderError::Protocol(format!("Pi Profile resource handshake failed: {error}")) - } - Err(cleanup) => ProviderError::Unknown(format!( - "Pi Profile resource handshake failed: {error}; owned session shutdown failed: {cleanup}" - )), - } + pub(super) async fn close_failed_construction(&self) -> Result<(), ProviderError> { + let thread_id = self.thread_id.lock().await.clone(); + self.close_session(&thread_id, true).await } async fn verify_profile_resources( @@ -431,7 +425,7 @@ impl AgentProvider for PiProvider { Self::success_or_protocol(&result, "new_session")?; let state_resp = Self::request(&mut state, json!({"type": "get_state"})).await?; - validate_started_runtime(&mut state, &state_resp).await?; + validate_started_runtime(&state, &state_resp)?; let session_file = state_resp .get("data") .and_then(|data| data.get("sessionFile")) @@ -449,11 +443,7 @@ impl AgentProvider for PiProvider { Some(required_string(&state_resp["data"], "sessionId", "Pi get_state")?); *self.thread_id.lock().await = session_file.to_owned(); - if let Err(error) = Self::verify_profile_resources(&mut state, profile, session_file).await - { - drop(state); - return Err(self.reject_startup(session_file, error).await); - } + Self::verify_profile_resources(&mut state, profile, session_file).await?; Ok(ProviderSession { thread_id: session_file.to_owned() }) } @@ -501,17 +491,14 @@ impl AgentProvider for PiProvider { state.process = None; self.spawn(&mut state, profile, profile.workspace(), Some(thread_id))?; let native = Self::request(&mut state, json!({"type":"get_state"})).await?; - validate_started_runtime(&mut state, &native).await?; + validate_started_runtime(&state, &native)?; let resumed_path = required_string(&native["data"], "sessionFile", "Pi get_state")?; if Path::new(&resumed_path) != Path::new(thread_id) { return Err(ProviderError::Protocol("Pi resumed a different session path".into())); } let native_id = required_string(&native["data"], "sessionId", "Pi get_state")?; state.native_session_id = Some(native_id.clone()); - if let Err(error) = Self::verify_profile_resources(&mut state, profile, thread_id).await { - drop(state); - return Err(self.reject_startup(thread_id, error).await); - } + Self::verify_profile_resources(&mut state, profile, thread_id).await?; if let Some(initial) = pending.as_mut() { if has_history && initial.native_session_id != native_id { return Err(ProviderError::Protocol( @@ -537,29 +524,12 @@ impl AgentProvider for PiProvider { async fn start_turn( &self, _thread_id: &str, - profile: &Profile, + _profile: &Profile, event_references: &str, ) -> Result { let mut state = self.state.lock().await; - let did_spawn = state.process.is_none(); - if did_spawn { - let session = state.session.clone(); - self.spawn(&mut state, profile, profile.workspace(), session.as_deref())?; - } - let native = Self::request(&mut state, json!({"type":"get_state"})).await?; validate_managed_state(&state, &native)?; - if did_spawn { - let native_thread_id = state.session.clone().ok_or_else(|| { - ProviderError::Protocol("Pi physical startup has no native session identity".into()) - })?; - if let Err(error) = - Self::verify_profile_resources(&mut state, profile, &native_thread_id).await - { - drop(state); - return Err(self.reject_startup(&native_thread_id, error).await); - } - } if native_is_busy(&native)? { return Err(ProviderError::Deferred( "Pi is streaming, compacting or has queued input".into(), @@ -1021,38 +991,18 @@ fn validate_managed_state(state: &PiState, response: &Value) -> Result<(), Provi Ok(()) } -async fn validate_started_runtime( - state: &mut PiState, - response: &Value, -) -> Result<(), ProviderError> { - let validation = validate_managed_state(state, response).and_then(|()| { - if let Some(execution) = - state.process.as_ref().and_then(|process| process.execution.as_ref()) - { - let managed = execution.state(response)?; - if matches!(managed.status, runtime::ManagedStatus::Unknown) { - return Err(ProviderError::Protocol(format!( - "Pi managed execution is unavailable at startup: {}", - managed.reason.as_deref().unwrap_or("native returned unknown without a reason") - ))); - } - } - Ok(()) - }); - let Err(error) = validation else { return Ok(()) }; - let mut reasons = vec![error.to_string()]; - if let Some(process) = state.process.as_mut() { - drop(process.writer.take()); - if let Err(error) = wait_for_pi_child(process, "", None, "rejected_runtime").await { - reasons.push(error.to_string()); - } - if let Some(execution) = &process.execution - && let Err(error) = execution.cleanup().await - { - reasons.push(error.to_string()); +fn validate_started_runtime(state: &PiState, response: &Value) -> Result<(), ProviderError> { + if let Some(execution) = state.process.as_ref().and_then(|process| process.execution.as_ref()) { + let managed = + execution.state(response).map_err(|error| ProviderError::Unknown(error.to_string()))?; + if matches!(managed.status, runtime::ManagedStatus::Unknown) { + return Err(ProviderError::Unknown(format!( + "Pi managed execution is unavailable at startup: {}", + managed.reason.as_deref().unwrap_or("native returned unknown without a reason") + ))); } } - Err(ProviderError::Unknown(reasons.join("; "))) + Ok(()) } /// Render the Braid OAuth credential into Pi's `auth.json` in the session diff --git a/src/telemetry/tests.rs b/src/telemetry/tests.rs index b849a20c..e234f527 100644 --- a/src/telemetry/tests.rs +++ b/src/telemetry/tests.rs @@ -309,8 +309,15 @@ fn verify_payload_records( }; let mut payload_events = 0; for record in log_records { + let serialized = serde_json::to_string(&record).unwrap(); + if !retained { + assert!( + !serialized.contains(SENTINEL), + "unsampled payload exported in OTLP log record" + ); + } assert!( - !serde_json::to_string(&record).unwrap().contains(RESPONSE_SENTINEL), + !serialized.contains(RESPONSE_SENTINEL), "collector response recursed into OTLP logs" ); let fields: std::collections::BTreeMap<_, _> = record diff --git a/src/tunnel/tests.rs b/src/tunnel/tests.rs index e88a36d5..0a06a2ea 100644 --- a/src/tunnel/tests.rs +++ b/src/tunnel/tests.rs @@ -196,34 +196,48 @@ async fn wait_for_process_state(pid: u32, expected: &str) { #[tokio::test] async fn signed_probe_requires_ingress_acceptance_not_an_arbitrary_http_success() { - use std::sync::{ - Arc, - atomic::{AtomicUsize, Ordering}, + use crate::{ + producer::{IngressState, webhook_handler}, + store::{SchedulerPolicy, StoreActor}, }; - let counter = Arc::new(AtomicUsize::new(0)); - let state = counter.clone(); - let app = axum::Router::new().route( - "/webhook", - axum::routing::post(move || { - let counter = state.clone(); - async move { - if counter.fetch_add(1, Ordering::SeqCst) == 0 { - axum::http::StatusCode::OK - } else { - axum::http::StatusCode::ACCEPTED - } - } - }), - ); + use axum::{http::StatusCode, routing::post}; + use std::sync::Arc; + let root = std::env::temp_dir().join(format!("braid-tunnel-probe-{}", Uuid::now_v7())); + std::fs::create_dir_all(&root).unwrap(); + let database = root.join("probe.sqlite3"); + let store = StoreActor::start(database.clone(), root.join("backups")).unwrap(); + store.apply().unwrap(); + let app = axum::Router::new() + .route("/proxy", post(|| async { StatusCode::OK })) + .route("/webhook", post(webhook_handler)) + .with_state(Arc::new(IngressState { + store: Arc::new(store), + policy: SchedulerPolicy { quiet_seconds: 30, event_threshold: 8 }, + repositories: vec!["owner/repo".into()], + webhook_secret: Arc::new(b"secret".to_vec()), + handle: "braid".into(), + app_actor_node_id: "APP".into(), + app_actor_login: "braid[bot]".into(), + agent_actor_node_ids: vec![], + })); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - let url = format!("http://{}/webhook", listener.local_addr().unwrap()); + let base = format!("http://{}", listener.local_addr().unwrap()); let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); - let error = signed_public_probe_once(&url, b"secret", "owner/repo", "repo") + let error = signed_public_probe_once(&format!("{base}/proxy"), b"secret", "owner/repo", "R1") .await .unwrap_err() .to_string(); assert!(error.contains("HTTP 200 OK, expected 202"), "{error}"); - signed_public_probe_once(&url, b"secret", "owner/repo", "repo").await.unwrap(); - assert_eq!(counter.load(Ordering::SeqCst), 2); + signed_public_probe_once(&format!("{base}/webhook"), b"secret", "owner/repo", "R1") + .await + .unwrap(); + let count: i64 = rusqlite::Connection::open(database).unwrap().query_row( + "SELECT COUNT(*) FROM deliveries WHERE event_name='ping' AND repository_node_id='R1' AND repository_name='owner/repo' AND delivery_guid != ''", + [], + |row| row.get(0), + ).unwrap(); + assert_eq!(count, 1, "signed ping must be durably admitted for the selected repository"); server.abort(); + let _ = server.await; + std::fs::remove_dir_all(root).unwrap(); } diff --git a/src/writer/tests.rs b/src/writer/tests.rs index 3d31a687..b694955f 100644 --- a/src/writer/tests.rs +++ b/src/writer/tests.rs @@ -471,7 +471,8 @@ async fn initial_ensure_bootstrap_pr_association_and_restart_do_not_duplicate_mu 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); From 0e6aec916cfc32ab56fdd45f829c16f241f2e163 Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sat, 28 Nov 2026 21:53:44 +0800 Subject: [PATCH 20/43] =?UTF-8?q?chore(audit):=20=E4=B8=B4=E6=97=B6?= =?UTF-8?q?=E9=AA=8C=E8=AF=81=E7=8B=AC=E7=AB=8B=E5=A4=8D=E5=AE=A1=E6=81=A2?= =?UTF-8?q?=E5=A4=8D=E7=9A=84=E5=A5=91=E7=BA=A6=E4=BC=9A=E5=9B=A0=E7=9B=AE?= =?UTF-8?q?=E6=A0=87=E7=BC=BA=E9=99=B7=E5=A4=B1=E8=B4=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/audit-controls/ci-browser.sh | 27 ++++++++ .github/audit-controls/ci-native.sh | 49 ++++++++++++++ .github/audit-controls/ci-ops.sh | 41 ++++++++++++ .github/audit-controls/ci-publication.sh | 68 ++++++++++++++++++++ .github/audit-controls/ci-state.sh | 46 ++++++++++++++ .github/audit-controls/platform-control.py | 74 ++++++++++++++++++++++ .github/workflows/audit-control-runs.yml | 31 +++++++++ 7 files changed, 336 insertions(+) create mode 100644 .github/audit-controls/ci-browser.sh create mode 100644 .github/audit-controls/ci-native.sh create mode 100755 .github/audit-controls/ci-ops.sh create mode 100755 .github/audit-controls/ci-publication.sh create mode 100644 .github/audit-controls/ci-state.sh create mode 100644 .github/audit-controls/platform-control.py create mode 100644 .github/workflows/audit-control-runs.yml diff --git a/.github/audit-controls/ci-browser.sh b/.github/audit-controls/ci-browser.sh new file mode 100644 index 00000000..2476a799 --- /dev/null +++ b/.github/audit-controls/ci-browser.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +set -euo pipefail +npm ci --prefix tests/browser --ignore-scripts +export CHROME_BIN=/usr/bin/google-chrome +export BRAID_BINARY="$PWD/target/debug/braid" +cargo build --locked +node --test tests/browser/draft.test.mjs +python3 - <<'PY' +from pathlib import Path +p=Path('src/console/web/console.js') +s=p.read_text() +needle="if(e.body?.requestId&&e.body?.state){renderReceipt(e.body);return;}" +assert s.count(needle)==1 +p.write_text(s.replace(needle,"if(e.body?.requestId&&e.body?.state){renderReceipt(e.body);if(current)await select(current.item.number,true);return;}")) +PY +trap 'git restore src/console/web/console.js' EXIT +cargo build --locked +if node --test tests/browser/draft.test.mjs > /tmp/browser-control.log 2>&1; then + echo 'Reloading a rejected edit escaped detection' >&2 + exit 1 +fi +cat /tmp/browser-control.log +grep -F '第一位操作者已保存' /tmp/browser-control.log +grep -F '第二位操作者的草稿' /tmp/browser-control.log +git restore src/console/web/console.js +cargo build --locked +python3 .github/audit-controls/platform-control.py "$BRAID_BINARY" --green diff --git a/.github/audit-controls/ci-native.sh b/.github/audit-controls/ci-native.sh new file mode 100644 index 00000000..3e86059a --- /dev/null +++ b/.github/audit-controls/ci-native.sh @@ -0,0 +1,49 @@ +#!/bin/bash +# Run in an isolated Actions checkout at the candidate commit. +set -euo pipefail +repo="$PWD" +snapshot=$(mktemp -d) +trap 'rm -rf "$snapshot"' EXIT +git archive HEAD | tar -x -C "$snapshot" +export CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-$repo/target}" +cd "$snapshot" +python3 - <<'PY' +from pathlib import Path +for filename, original, wrong in [ + ("src/provider/pi.rs", '"agent_settled" => {', '"agent_settled" | "agent_end" => {'), + ("src/provider/codex.rs", '"turn/started" => {', '"turn/started" | "error" => {'), + ("src/telemetry.rs", 'github.comment.summary = evidence.github_summary,', 'github.comment.summary = evidence.github_body,'), + ("src/tunnel.rs", '.header("X-GitHub-Event", "ping")', '.header("X-GitHub-Event", "unknown")'), +]: + path = Path(filename) + text = path.read_text() + assert text.count(original) == 1, filename + path.write_text(text.replace(original, wrong)) +PY +filters=(provider::pi::tests::pi_settles_after_retry provider::codex::tests::retryable_errors telemetry::tests::telemetry_routes_complete_evidence_only_to_otlp tunnel::tests::signed_probe_requires) +if cargo test --locked --bin braid -- "${filters[@]}" >"$snapshot/red.log" 2>&1; then + cat "$snapshot/red.log" + exit 1 +fi +cat "$snapshot/red.log" +for test_case in "${filters[@]}"; do grep -E "^test ${test_case}.*FAILED" "$snapshot/red.log"; done +for reason in 'intermediate frames must leave the turn open' 'willRetry' 'missing, incomplete, or misrouted github.comment.summary' 'signed ping must be durably admitted'; do + grep -F "$reason" "$snapshot/red.log" +done +for file in src/provider/pi.rs src/provider/codex.rs src/telemetry.rs src/tunnel.rs; do + cp "$repo/$file" "$file" + cmp "$repo/$file" "$file" +done +cargo test --locked --bin braid -- "${filters[@]}" +if [[ -n "${BRAID_TEST_PI_INSTALL:-}" ]]; then + export PI_OFFLINE=1 + for file in src/provider/pi.rs src/provider/factory.rs; do git -C "$repo" show "fe82de3:$file" > "$file"; done + if cargo test --locked --bin braid failed_home_binding_stops_the_installed_execution_before_returning -- --ignored >"$snapshot/construction-red.log" 2>&1; then + cat "$snapshot/construction-red.log" + exit 1 + fi + cat "$snapshot/construction-red.log" + grep -F 'failed factory construction omitted the owned-stop receipt' "$snapshot/construction-red.log" + for file in src/provider/pi.rs src/provider/factory.rs; do cp "$repo/$file" "$file"; cmp "$repo/$file" "$file"; done + cargo test --locked --bin braid failed_home_binding_stops_the_installed_execution_before_returning -- --ignored +fi diff --git a/.github/audit-controls/ci-ops.sh b/.github/audit-controls/ci-ops.sh new file mode 100755 index 00000000..649dc6bb --- /dev/null +++ b/.github/audit-controls/ci-ops.sh @@ -0,0 +1,41 @@ +#!/bin/sh +# From the checkout root, in an isolated CI job. +set -eu +python3 - <<'PY' +from pathlib import Path +import re +import subprocess + +def control(file, before, after, suite, case, expected, pos): + path = Path(file) + original = path.read_bytes() + assert original.count(before.encode()) == 1, f"{file}: mutation anchor changed" + try: + path.write_bytes(original.replace(before.encode(), after.encode(), 1)) + cmd = ["cargo", "test", "--locked", "--test", suite, case, "--", "--exact"] + result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) + print(result.stdout, flush=True) + # The source line and the exact values distinguish the target assertion from setup errors. + line = next(i for i, s in enumerate(Path(f"tests/{suite}.rs").read_text().splitlines(), 1) + if pos in s) + assert result.returncode != 0 and f"test {case} ... FAILED" in result.stdout + assert f"tests/{suite}.rs:{line}:" in result.stdout and re.search(expected, result.stdout) + finally: + path.write_bytes(original) + +control("src/cli/status.rs", "config_schema: config.schema_version,", "config_schema: 3,", + "multi_repo", "instance_selectors_route_to_the_expected_config_and_doctor_names_cross_instance_conflicts", + r"left: Number\(3\)\s+right: 2", 'assert_eq!(status["config_schema"], 2)') + +branch = " if let Some(event_id) = pending {\n transaction.commit()?;\n return Ok(event_id);" +duplicate = """ if let Some(event_id) = pending { + let duplicate = Uuid::now_v7().to_string(); + transaction.execute("INSERT INTO wake_batches(batch_id,work_item_node_id,event_count,quiet_deadline,lifecycle,created_at,updated_at) + VALUES(?1,?2,1,?3,'consumed',?3,?3)", params![duplicate,work_item_node_id,now])?; + transaction.execute("INSERT INTO wake_batch_events(batch_id,event_id,ordinal) VALUES(?1,?2,0)", params![duplicate,event_id])?; + transaction.commit()?; + return Ok(event_id);""" +control("src/store/mod.rs", branch, duplicate, "assignment", + "assignment_reactivation_queues_one_wake_and_preserves_the_blocked_generation", + r"left: 2\s+right: 1", "assert_eq!(batches, 1)") +PY diff --git a/.github/audit-controls/ci-publication.sh b/.github/audit-controls/ci-publication.sh new file mode 100755 index 00000000..a51ecf66 --- /dev/null +++ b/.github/audit-controls/ci-publication.sh @@ -0,0 +1,68 @@ +#!/usr/bin/env bash +set -euo pipefail + +root=$(git rev-parse --show-toplevel) +scratch=$(mktemp -d) +trap 'rm -rf "$scratch"' EXIT +cd "$root" +target_dir=${CARGO_TARGET_DIR:-target} +case "$target_dir" in + /*) export CARGO_TARGET_DIR="$target_dir" ;; + *) export CARGO_TARGET_DIR="$root/$target_dir" ;; +esac + +# Both changes affect only this snapshot. They touch different operations, so +# each target can run against the same compiled test binary. +git archive HEAD | tar -x -C "$scratch" +cd "$scratch" +python3 - <<'PY' +from pathlib import Path + +def replace(path, old, new): + source = Path(path).read_text() + if source.count(old) != 1: + raise RuntimeError(f"expected one control site in {path}") + Path(path).write_text(source.replace(old, new)) + +# Restore the pre-fix sample retention from bbc82f6^. +replace("src/github/rate_limit.rs", + "self.resource = reset.and(resource);\n self.used = used;", + "self.resource = resource;\n self.used = used.or(self.used);") +replace("src/writer/ensure.rs", + " let request_marker = format!", + ' if receipt.stage == "pull_request_ready" {\n' + ' return Err(GitHubError::GraphQl("mutation: lose persisted PR recovery".into()));\n' + ' }\n let request_marker = format!') +PY + +budget=github::rate_limit::window_tests::used_delta_requires_two_comparable_complete_header_samples +restart=writer::tests::initial_ensure_bootstrap_pr_association_and_restart_do_not_duplicate_mutations +run_case() { + cargo test --locked --bin braid "$1" -- --exact --color never +} + +red() { + local name=$1 + shift + local log="$scratch/$name.red" + if run_case "$name" >"$log" 2>&1; then + cat "$log" + echo "mutation survived: $name" >&2 + return 1 + fi + cat "$log" + grep -Fq "test $name ... FAILED" "$log" + for diagnostic do + grep -Fq -- "$diagnostic" "$log" + done +} +red "$budget" 'used=Some(25), reset=Some(600), resource=Some("core")' 'left: Some(3)' 'right: None' +red "$restart" 'mutation: lose persisted PR recovery' 'left: "rejected"' 'right: "applied"' + +for path in src/github/rate_limit.rs src/writer/ensure.rs; do + git -C "$root" show "HEAD:$path" > "$path" +done +for name in "$budget" "$restart"; do + run_case "$name" | tee "$scratch/$name.green" + grep -Fq "test $name ... ok" "$scratch/$name.green" +done diff --git a/.github/audit-controls/ci-state.sh b/.github/audit-controls/ci-state.sh new file mode 100644 index 00000000..06cd7f80 --- /dev/null +++ b/.github/audit-controls/ci-state.sh @@ -0,0 +1,46 @@ +#!/usr/bin/env bash +set -euo pipefail +file= +restore() { [[ -z "$file" ]] || git restore -- "$file"; } +trap restore EXIT +mutate() { + python3 - "$file" "$1" "$2" <<'PY' +from pathlib import Path +import sys +p=Path(sys.argv[1]) +s=p.read_text() +old,new=sys.argv[2:] +assert s.count(old)==1, (p,old,s.count(old)) +p.write_text(s.replace(old,new)) +PY +} +catch_control() { + local test_case="$1" reason="$2" out + out="$(mktemp)" + if cargo test --locked --bin braid "$test_case" -- --nocapture >"$out" 2>&1; then + cat "$out" + return 1 + fi + cat "$out" + grep -E 'test .*FAILED' "$out" >/dev/null + grep -F "$reason" "$out" >/dev/null + rm -f "$out" + restore + file= +} +file=src/group/worker.rs +mutate 'self.quiesce_session(id).await? || recorded_stop' 'self.quiesce_session(id).await? || (recorded_stop && false)' +catch_control persisted_idle_reset_uses_only_confirmed_native_stop_after_restart 'right: "applied"' +file=src/store/reconciliation.rs +mutate 'CASE WHEN ?3 THEN ?2 ELSE reconciled_at END' 'CASE WHEN ?3 THEN ?2 ELSE NULL END' +catch_control failed_traversal_backs_off_without_losing_the_last_success 'due_ids(&db, 1899)' +file=src/store/mod.rs +mutate ' if before.pending.is_empty() {' ' if before.pending.is_empty() { + create_backup(&open_read_only(database)?, backups, before.current_schema)?;' +catch_control v1_upgrade_preserves_the_association_and_comment_and_takes_only_one_backup 'braid.before-v' +for old_table in associations canonical_objects; do + file=src/store/mod.rs + mutate ' let after = plan(database)?;' " if before.current_schema == 1 { connection.execute_batch(\"DELETE FROM ${old_table}\")?; } + let after = plan(database)?;" + catch_control v1_upgrade_preserves_the_association_and_comment_and_takes_only_one_backup 'QueryReturnedNoRows' +done diff --git a/.github/audit-controls/platform-control.py b/.github/audit-controls/platform-control.py new file mode 100644 index 00000000..cf3fa5e6 --- /dev/null +++ b/.github/audit-controls/platform-control.py @@ -0,0 +1,74 @@ +"""Exercise both regressions through just the public CLI/HTTP and a legacy SQLite fixture.""" +import hashlib, http.client, json, socket, sqlite3, subprocess, sys, tempfile, time +from pathlib import Path + +binary=Path(sys.argv[1]).resolve() +green="--green" in sys.argv[2:] +with tempfile.TemporaryDirectory(prefix="braid-platform-control-") as directory: + root=Path(directory) + source=root/"git" + def run(*args): return subprocess.check_output(args, text=True).strip() + run("git","init","-q","-b","main",str(source)) + for key,value in (("user.name","Contract"),("user.email","example@invalid"),("commit.gpgsign","false")): + run("git","-C",str(source),"config",key,value) + run("git","-C",str(source),"commit","--allow-empty","-qm","base") + run("git","-C",str(source),"checkout","-qb","feature") + (source/"body").write_text("candidate\n") + run("git","-C",str(source),"add","body") + run("git","-C",str(source),"commit","-qm","candidate") + with socket.socket() as probe: + probe.bind(("127.0.0.1",0)); port=probe.getsockname()[1] + config=root/"platform.toml" + run(binary,"platform","init","--config",config,"--source",source,"--default-branch","main","--name","demo","--listen",f"127.0.0.1:{port}") + store=root/"old.db" + old=sqlite3.connect(store) + for file in sorted(Path("migrations").glob("000[1-5]*.sql")): + content=file.read_bytes() + version,name=file.stem.split("_",1) + old.executescript(content.decode()) + old.execute("INSERT INTO schema_migrations VALUES(?,?,?,'then')",(int(version),name,hashlib.sha256(content).hexdigest())) + old.execute("INSERT INTO local_space VALUES(1,'demo',?)",(str(source.resolve()),)) + old.execute("INSERT INTO local_items(number,repository,kind,title,body,author,created_at,updated_at) VALUES(7,'demo','issue','Imported','','human','then','then')") + req='{"requestId":"historic","expectedRevision":1,"command":{"type":"assign","number":7,"profile":"old-profile"}}' + orig={"requestId":"historic","state":"rejected","result":None,"error":{"code":"rejected","message":"runtime supports profile issue-codex for issue objects"}} + old.execute("INSERT INTO control_receipts VALUES('objects','historic',?,?,'rejected',?,?,'then','then')",(hashlib.sha256(req.encode()).hexdigest(),req,json.dumps(orig),orig["error"]["message"])) + old.commit();old.close() + run(binary,"platform","import","--config",config,"--from",store) + def call(path,body=None): + c=http.client.HTTPConnection("127.0.0.1",port,timeout=5) + c.request("GET" if body is None else "POST",path,None if body is None else json.dumps(body),{"Host":f"127.0.0.1:{port}","Content-Type":"application/json"}) + r=c.getresponse(); answer=(r.status,json.load(r));c.close();return answer + def command(id,command,revision=None,actor="human"):return call("/api/control/commands",dict(requestId=id,actor=actor,expectedRevision=revision,command=command)) + proc=subprocess.Popen([binary,"platform","serve","--config",config],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL) + try: + for i in range(100): + try: + assert call("/api/platform/repository")[0]==200 + break + except ConnectionRefusedError: time.sleep(.02) + assert call("/api/control/receipts/historic")== (200,orig) + replay=command("historic",dict(type="assign",number=7,actor="old-profile"),1) + print("historical assign with previous profile spelling:",replay,flush=True) + assert replay[0]==409 and ((replay[1]==orig) if green else ("requestId was already used" in replay[1]["error"]["message"] and replay[1].get("state") is None)) + issue=command("new-issue",dict(type="createIssue",title="Task",body=""))[1]["result"]["number"] + pr=command("new-pr",dict(type="createPR",title="Work",body="",head="feature",base="main",issue=issue,issueRevision=1))[1]["result"]["number"] + db=sqlite3.connect(root/"platform.sqlite3") + db.execute("""CREATE TRIGGER lose_receipt BEFORE UPDATE OF response_json ON control_receipts WHEN NEW.request_id='original' AND NEW.state!='prepared' BEGIN SELECT RAISE(ABORT,'injected receipt storage failure'); END""");db.commit() + response=command("original",dict(type="merge",number=pr),1,"first") + assert response[0]==422 and "injected receipt storage failure" in response[1]["error"]["message"], response + before=call(f"/api/control/items/{pr}")[1] + assert before["merge"]["lifecycle"]=="prepared" + assert run("git","-C",str(source),"rev-parse","refs/heads/main")==before["merge"]["merge_commit"] + db.execute("DROP TRIGGER lose_receipt");db.commit();db.close() + followup=command("new-command",dict(type="merge",number=pr),1,"second") + events=call("/api/platform/events")[1]["events"] + actors=[r["event"]["actor_login"] for r in events if r["event"]["detail"]=="merged"] + print("different request ID after original CAS:", followup, "merged actors:", actors,flush=True) + if green: + assert followup[0]==409 and "another merge request" in followup[1]["error"]["message"] and actors==[] + assert command("original",dict(type="merge",number=pr),1,"first")[0]==200 + assert [r["event"]["actor_login"] for r in call("/api/platform/events")[1]["events"] if r["event"]["detail"]=="merged"]==["first"] + else: + assert followup[0]==200 and actors==["second"],(followup,actors) + finally: + proc.terminate();proc.wait(5) diff --git a/.github/workflows/audit-control-runs.yml b/.github/workflows/audit-control-runs.yml new file mode 100644 index 00000000..e9189602 --- /dev/null +++ b/.github/workflows/audit-control-runs.yml @@ -0,0 +1,31 @@ +name: Audit preservation controls +on: + pull_request: + paths: ['.github/audit-controls/**', '.github/workflows/audit-control-runs.yml'] +permissions: + contents: read +jobs: + control: + if: github.head_ref == 'feat/pr149-test-audit' + strategy: + fail-fast: false + matrix: + owner: [native, state, ops, publication, browser] + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha }} + fetch-depth: 0 + persist-credentials: false + - uses: actions/setup-node@v4 + with: + node-version: 24.15.0 + - if: matrix.owner == 'native' + run: | + node native/pi/install.mjs "$RUNNER_TEMP/pi" --plugins background + echo "BRAID_TEST_PI_INSTALL=$RUNNER_TEMP/pi" >> "$GITHUB_ENV" + - env: + OWNER: ${{ matrix.owner }} + CARGO_PROFILE_DEV_DEBUG: 0 + run: bash ".github/audit-controls/ci-$OWNER.sh" From 9d9f0c24e7e10068f800f1484f7b615ade88a02b Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sat, 28 Nov 2026 21:56:33 +0800 Subject: [PATCH 21/43] =?UTF-8?q?fix(group):=20=E9=80=80=E4=BC=91=E5=89=8D?= =?UTF-8?q?=E4=BF=9D=E5=AD=98=E5=81=9C=E6=9C=BA=E6=9C=9F=E9=97=B4=E8=A7=82?= =?UTF-8?q?=E5=AF=9F=E5=88=B0=E7=9A=84=E5=8E=9F=E7=94=9F=E7=BB=88=E6=80=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 写入 fence 暂时失败时持久化同一 turn 的完成或错误证据 - 缺失原生终态保留 Unknown,重试继续使用原 generation --- docs/20-product-tdd/lifecycle.md | 5 +- src/group/continuous_tests.rs | 200 ++++++++++++++++++++----------- src/group/dispatch.rs | 1 + src/group/issue_agent.rs | 5 +- src/group/pr_agent.rs | 5 +- src/group/worker.rs | 131 ++++++++++++++------ src/store/mod.rs | 91 +++++++++++--- src/store/unassignment.rs | 7 ++ 8 files changed, 309 insertions(+), 136 deletions(-) diff --git a/docs/20-product-tdd/lifecycle.md b/docs/20-product-tdd/lifecycle.md index ddd97ebd..93d31a07 100644 --- a/docs/20-product-tdd/lifecycle.md +++ b/docs/20-product-tdd/lifecycle.md @@ -121,8 +121,9 @@ classified as Agent-origin. - GitHub 原生指派模式按 Quiet Window 合并 Issue 撤销指派事件。窗口到期后, Group 重读当前 assignees。若仍已指派则消费这次事件。确认撤销时,正在执行的 worker 和空闲 worker 使用同一停止流程。内建平台直接处理不可撤回的撤销事件。 - Group 确认原生会话停止和平台执行权限撤销后,才将该代记为 `retired` 并终结 - 尚在运行的 turn。关闭失败保留撤销事件和原代。重新指派创建新一代及新会话。 + Group 在关闭期间继续接收原有 turn 的终态。平台撤权暂时失败时,已经收到的终态与 + 错误仍须持久化。原生停止和平台撤权均已确认后,Group 才将该代记为 `retired`; + 此时仍缺 provider 终态的 turn 记为 `unknown`。重新指派创建新一代及新会话。 - 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 diff --git a/src/group/continuous_tests.rs b/src/group/continuous_tests.rs index 8d6425ae..e0b35ef8 100644 --- a/src/group/continuous_tests.rs +++ b/src/group/continuous_tests.rs @@ -18,6 +18,7 @@ struct Captured { steer_error: Mutex>, close_error: Mutex>, close_attempts: Mutex>, + close_terminal: Mutex)>>, closed: tokio::sync::Notify, steered: tokio::sync::Notify, } @@ -38,11 +39,17 @@ impl SessionFactory for Factory { _instructions: String, context: String, ) -> Result { - self.0.memory.lock().unwrap().push(context); + let mut memories = self.0.memory.lock().unwrap(); + memories.push(context); + let id = if memories.len() == 1 { + "fresh-provider".to_owned() + } else { + format!("fresh-provider-{}", memories.len()) + }; Ok(CreatedSession { - id: "fresh-provider".into(), + id: id.clone(), session: Arc::new(Session { - id: "fresh-provider".into(), + id, captured: self.0.clone(), events: broadcast::channel(8).0, }), @@ -76,7 +83,17 @@ impl AgentSession for Session { async fn close(&self) -> Result<(), SessionError> { self.captured.closed.notify_one(); self.captured.close_attempts.lock().unwrap().push(self.id.clone()); - self.captured.close_error.lock().unwrap().clone().map_or(Ok(()), Err) + if let Some(error) = self.captured.close_error.lock().unwrap().clone() { + return Err(error); + } + if let Some((outcome, error)) = self.captured.close_terminal.lock().unwrap().take() { + let _ = self.events.send(SessionEvent::TurnTerminal { + provider_turn_id: "after-revision".into(), + outcome, + error, + }); + } + Ok(()) } async fn send_user_msg(&self, msg: String, steering: bool) -> Result { assert!(!steering); @@ -667,8 +684,24 @@ async fn stopping_native_execution_does_not_wait_for_execution_fence() { } #[tokio::test] -#[allow(clippy::too_many_lines)] async fn builtin_turn_runs_without_writer_service_and_cannot_mint_after_reassignment() { + builtin_running_unassignment(crate::agent_session::TurnOutcome::Completed, None).await; +} + +#[tokio::test] +async fn worker_preserves_a_failed_turn_during_unassignment_while_the_platform_fence_is_offline() { + builtin_running_unassignment( + crate::agent_session::TurnOutcome::Failed, + Some("provider failed while stopping".into()), + ) + .await; +} + +#[allow(clippy::too_many_lines)] +async fn builtin_running_unassignment( + outcome: crate::agent_session::TurnOutcome, + reason: Option, +) { use crate::{ builtin::BuiltinClient, platform::{PlatformConfig, objects::PlatformObjects}, @@ -755,25 +788,33 @@ async fn builtin_turn_runs_without_writer_service_and_cannot_mint_after_reassign store.ingest_builtin_event(pending.event, policy, pending.event_id).unwrap(); cursor = pending.event_id; } - let assignment = - store.assignment_candidates("test-space".into(), "issue".into(), 1).unwrap().pop().unwrap(); - let materialization = store - .begin_agent_assignment( - assignment.event_id, - spec.profile_record.clone(), - Some("old memory".into()), - false, - ) - .unwrap() - .unwrap(); - store - .complete_agent_assignment( - materialization, - "provider".into(), - "old memory".into(), - "instructions".into(), - ) - .unwrap(); + let captured = Arc::new(Captured::default()); + let (shutdown, stop) = tokio::sync::watch::channel(false); + let (reports, _receiver) = tokio::sync::mpsc::channel(8); + let actor = spec.profile.id.clone(); + let worker = tokio::spawn(agent_group_worker_backend( + Arc::clone(&store), + Arc::new(CollaborationBackend::Builtin(Arc::clone(&client))), + config, + spec, + Arc::new(Factory(Arc::clone(&captured))), + reports, + stop, + )); + let limit = std::time::Duration::from_secs(5); + tokio::time::timeout(limit, async { + while !store + .runtime_status() + .unwrap() + .agent_groups + .iter() + .any(|group| group.assignment_generation == 1 && group.assignment_lifecycle == "active") + { + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + } + }) + .await + .expect("assignment materializes before the first user input"); platform.reply(issue.number, "Run this turn", "human", None).unwrap(); for pending in platform.events(cursor, 100).unwrap() { store.ingest_builtin_event(pending.event, policy, pending.event_id).unwrap(); @@ -781,70 +822,87 @@ async fn builtin_turn_runs_without_writer_service_and_cannot_mint_after_reassign } store.advance_scheduler().unwrap(); - let captured = Arc::new(Captured::default()); - let collaboration = CollaborationBackend::Builtin(Arc::clone(&client)); - let driver = worker::GroupDriver { - store: &store, - config: &config, - collaboration: &collaboration, - spec: &spec, - sessions: SessionManager::new(Arc::new(Factory(Arc::clone(&captured)))), - }; - driver - .sessions - .resume("provider".into(), spec.profile.clone(), "instructions".into()) - .await - .unwrap(); - let running = driver.start_next_agent_turn().await.unwrap_or_else(|| { - panic!("writer service must not gate a turn: {:?}", store.runtime_status().unwrap().batches) - }); + let (session_id, turn_id) = tokio::time::timeout(limit, async { + loop { + if let Some(group) = store + .runtime_status() + .unwrap() + .agent_groups + .into_iter() + .find(|group| group.turn_lifecycle.as_deref() == Some("running")) + { + break (group.provider_session_id.unwrap(), group.active_turn_id.unwrap()); + } + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + } + }) + .await + .expect("writer service must not gate a real turn"); assert_eq!(captured.inputs.lock().unwrap().len(), 1); - let writer = BuiltinWriterTurn { - session_id: running.claim.provider_session_id, - turn_id: running.claim.turn_id, - item_number: issue.number, - actor: spec.profile.id.clone(), - }; + let writer = + BuiltinWriterTurn { session_id, turn_id, item_number: issue.number, actor: actor.clone() }; let offline_error = client.writer_grant(writer.clone()).await.unwrap_err(); assert!(offline_error.to_string().contains("503")); // The old turn never minted a grant. Name equality must not revive it // after an unassign/reassign and before those events reach the Harness. - platform.assign(issue.number, Some(&spec.profile.id), "human").unwrap(); + platform.assign(issue.number, Some(&actor), "human").unwrap(); offline.store(false, Ordering::Relaxed); let error = client.writer_grant(writer.clone()).await.unwrap_err(); assert!(error.to_string().contains("writer authority changed"), "{error:#}"); offline.store(true, Ordering::Relaxed); - // An immutable unassignment still retires the old generation after a - // reassignment. Native close alone cannot replace the platform's fence. + *captured.close_terminal.lock().unwrap() = Some((outcome, reason.clone())); + fence_offline.store(true, Ordering::Relaxed); for pending in platform.events(cursor, 100).unwrap() { store.ingest_builtin_event(pending.event, policy, pending.event_id).unwrap(); } - let revoked = || crate::store::UnassignmentTarget::RunningTurn(writer.turn_id.clone()); - fence_offline.store(true, Ordering::Relaxed); - let error = driver.settle_unassignment(revoked()).await.unwrap_err(); - assert!(error.to_string().contains("execution fence unconfirmed"), "{error:#}"); - assert_eq!(*captured.close_attempts.lock().unwrap(), ["provider"]); + // The adapter returned a terminal during close. The worker must retain it + // even across a failed independent fence, before creating another generation. + let turn_state = || { + f.db() + .query_row( + "SELECT lifecycle,error FROM turns WHERE turn_id=?1", + [&writer.turn_id], + |row| Ok((row.get::<_, String>(0)?, row.get::<_, Option>(1)?)), + ) + .unwrap() + }; + tokio::time::timeout(limit, async { + while turn_state().0 != outcome.lifecycle() { + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + } + }) + .await + .expect("observed provider terminal must be durable while the platform fence is offline"); + assert_eq!(turn_state().1, reason); + assert_eq!(*captured.close_attempts.lock().unwrap(), ["fresh-provider"]); assert_eq!(store.runtime_status().unwrap().agent_groups[0].assignment_lifecycle, "active"); fence_offline.store(false, Ordering::Relaxed); - assert!(driver.settle_unassignment(revoked()).await.unwrap()); - assert_eq!(*captured.close_attempts.lock().unwrap(), ["provider"]); - assert_eq!(store.runtime_status().unwrap().agent_groups[0].assignment_lifecycle, "retired"); - client.fence_all_executions().await.unwrap(); - let fenced = client.writer_grant(writer).await.unwrap_err(); - assert!(fenced.to_string().contains("no current writer authority")); - let reassignment = - store.assignment_candidates("test-space".into(), "issue".into(), 1).unwrap().pop().unwrap(); - assert_eq!(reassignment.action, "assign"); - driver.materialize_issue_assignment(reassignment).await.unwrap(); - let groups = store.runtime_status().unwrap().agent_groups; - assert_eq!(groups.len(), 2); + let groups = tokio::time::timeout(limit, async { + loop { + let groups = store.runtime_status().unwrap().agent_groups; + if groups.iter().any(|group| { + group.assignment_generation == 2 && group.assignment_lifecycle == "active" + }) { + break groups; + } + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + } + }) + .await + .expect("retire the old generation and materialize its immutable reassignment"); let retired = groups.iter().find(|group| group.assignment_generation == 1).unwrap(); let current = groups.iter().find(|group| group.assignment_generation == 2).unwrap(); assert_eq!(retired.assignment_lifecycle, "retired"); - assert_eq!(current.assignment_lifecycle, "active"); - assert_eq!(current.provider_session_id.as_deref(), Some("fresh-provider")); - assert_eq!(captured.memory.lock().unwrap().len(), 1); + assert_eq!(current.provider_session_id.as_deref(), Some("fresh-provider-2")); + assert_eq!(turn_state(), (outcome.lifecycle().to_owned(), reason)); + assert_eq!(*captured.close_attempts.lock().unwrap(), ["fresh-provider"]); + assert_eq!(captured.memory.lock().unwrap().len(), 2); + client.fence_all_executions().await.unwrap(); + let fenced = client.writer_grant(writer).await.unwrap_err(); + assert!(fenced.to_string().contains("no current writer authority")); + shutdown.send(true).unwrap(); + worker.await.unwrap().unwrap(); http.abort(); } @@ -938,7 +996,7 @@ async fn worker_stops_a_running_unassigned_issue_only_after_its_quiet_window() { |row| row.get(0), ) .unwrap(); - assert_eq!(terminal, "interrupted"); + assert_eq!(terminal, "unknown", "closing the session alone cannot identify a turn outcome"); assert_eq!(captured.inputs.lock().unwrap().len(), 1); shutdown.send(true).unwrap(); worker.await.unwrap().unwrap(); diff --git a/src/group/dispatch.rs b/src/group/dispatch.rs index fe7dc44c..100f05d3 100644 --- a/src/group/dispatch.rs +++ b/src/group/dispatch.rs @@ -626,6 +626,7 @@ impl GroupDriver<'_> { claim, provider_turn_id, reset_id: None, + stop_terminal: None, events, _admission: admission, }) diff --git a/src/group/issue_agent.rs b/src/group/issue_agent.rs index 7f5ba616..db7d7700 100644 --- a/src/group/issue_agent.rs +++ b/src/group/issue_agent.rs @@ -267,10 +267,7 @@ impl GroupDriver<'_> { }; let Some(candidate) = candidate else { return }; if candidate.action == "unassign" { - if let Err(error) = self - .settle_unassignment(crate::store::UnassignmentTarget::Event(candidate.event_id)) - .await - { + if let Err(error) = self.settle_idle_unassignment(candidate.event_id).await { tracing::error!(%error, "cannot settle Issue unassignment"); } return; diff --git a/src/group/pr_agent.rs b/src/group/pr_agent.rs index 4808b75e..062b3c5a 100644 --- a/src/group/pr_agent.rs +++ b/src/group/pr_agent.rs @@ -298,10 +298,7 @@ impl GroupDriver<'_> { }; let Some(candidate) = candidate else { return }; if candidate.action == "unassign" && self.collaboration.is_builtin() { - if let Err(error) = self - .settle_unassignment(crate::store::UnassignmentTarget::Event(candidate.event_id)) - .await - { + if let Err(error) = self.settle_idle_unassignment(candidate.event_id).await { tracing::error!(%error, "cannot settle built-in PR unassignment"); } return; diff --git a/src/group/worker.rs b/src/group/worker.rs index 1b440e67..53916807 100644 --- a/src/group/worker.rs +++ b/src/group/worker.rs @@ -172,13 +172,13 @@ impl GroupDriver<'_> { } } - pub(super) async fn settle_unassignment( + pub(super) async fn confirmed_unassignment( &self, target: crate::store::UnassignmentTarget, - ) -> Result { + ) -> Result> { let builtin = self.collaboration.is_builtin(); let quiet = if builtin { 0 } else { self.config.scheduler.quiet_seconds }; - let Some(change) = self.store.due_unassignment(target, quiet)? else { return Ok(false) }; + let Some(change) = self.store.due_unassignment(target, quiet)? else { return Ok(None) }; if !builtin { let locator = crate::github::WorkItemLocator { repository: change.repository.parse()?, @@ -191,14 +191,49 @@ impl GroupDriver<'_> { .any(|actor| self.collaboration.assignee_matches(actor, &self.spec.profile.id)) { self.store.ignore_assignment_event(change.event_id)?; - return Ok(false); + return Ok(None); } } + Ok(Some(change)) + } + + pub(super) async fn settle_unassignment( + &self, + change: &crate::store::Unassignment, + mut active: Option<&mut RunningAgentTurn>, + ) -> Result<()> { + let mut stop = Ok(()); for (session, stopped) in &change.sessions { - self.require_quiesced(session, *stopped).await?; + if let Err(error) = self.require_quiesced(session, *stopped).await { + stop = Err(error); + } + } + let terminal = active.as_deref_mut().and_then(RunningAgentTurn::terminal_after_close); + if (stop.is_ok() || terminal.is_some()) + && self.store.settle_unassignment(change, terminal.clone(), stop.is_ok())? + && let (Some(active), Some(terminal)) = (active, terminal) + && matches!( + terminal.outcome, + crate::agent_session::TurnOutcome::Failed + | crate::agent_session::TurnOutcome::Unknown + ) + { + self.enqueue_turn_error( + &active.claim, + terminal.outcome.lifecycle(), + terminal.error.as_deref().unwrap_or("provider did not supply a terminal reason"), + ); } - self.store.retire_unassigned_work_item(change)?; - Ok(true) + stop.map_err(Into::into) + } + + pub(super) async fn settle_idle_unassignment(&self, event: String) -> Result<()> { + if let Some(change) = + self.confirmed_unassignment(crate::store::UnassignmentTarget::Event(event)).await? + { + self.settle_unassignment(&change, None).await?; + } + Ok(()) } pub(super) async fn retain_sessions( @@ -219,6 +254,10 @@ impl GroupDriver<'_> { if let Err(error) = self.store.record_turn_error(claim.turn_id.clone(), reason.to_owned()) { tracing::error!(%error, turn = %claim.turn_id, "cannot retain complete turn error"); } + self.enqueue_turn_error(claim, lifecycle, reason); + } + + fn enqueue_turn_error(&self, claim: &TurnClaim, lifecycle: &str, reason: &str) { if self.spec.profile.status_surfaces.is_empty() { return; } @@ -241,22 +280,16 @@ impl GroupDriver<'_> { return; }; let closed = self.quiesce_session(&active.claim.provider_session_id).await; - let mut terminal = None; - while let Ok(event) = active.events.try_recv() { - if let crate::agent_session::SessionEvent::TurnTerminal { - provider_turn_id, - outcome, - error, - } = event - && provider_turn_id == active.provider_turn_id - { - terminal = Some((outcome, error)); - } - } - let (outcome, error) = terminal.unwrap_or(( - crate::agent_session::TurnOutcome::Unknown, - Some("shutdown did not observe the active turn terminal".into()), - )); + let terminal = active.terminal_after_close(); + let (outcome, error) = terminal.map_or_else( + || { + ( + crate::agent_session::TurnOutcome::Unknown, + Some("shutdown did not observe the active turn terminal".into()), + ) + }, + |terminal| (terminal.outcome, terminal.error), + ); if let Some(reset_id) = active.reset_id { let _ = self.store.mark_context_reset_turn_terminal( reset_id.clone(), @@ -332,7 +365,7 @@ impl GroupDriver<'_> { let mut running: Option = None; // A native close may end the event stream while its independent // platform fence is still being retried. - let mut settling_unassignment = false; + let mut unassignment = None; let mut tick = tokio::time::interval(Duration::from_millis(250)); tick.set_missed_tick_behavior(MissedTickBehavior::Delay); let mut recovery = tokio::time::Instant::now(); @@ -350,7 +383,7 @@ impl GroupDriver<'_> { } else { std::future::pending().await } - }, if running.is_some() && !settling_unassignment => { + }, if running.is_some() && unassignment.is_none() => { match event { Ok(crate::agent_session::SessionEvent::TurnStarted { provider_turn_id }) => { tracing::debug!(%provider_turn_id, "AgentSession turn started"); @@ -405,7 +438,7 @@ impl GroupDriver<'_> { } } _ = tick.tick() => { - if !settling_unassignment && running.as_ref().is_some_and(|active| active.events.is_closed()) { + if unassignment.is_none() && running.as_ref().is_some_and(|active| active.events.is_closed()) { self.fence_running(&mut running, "AgentSession event stream closed").await; } // A closed finite root fences new execution; shutdown owns physical cleanup. @@ -430,22 +463,21 @@ impl GroupDriver<'_> { recovery = tokio::time::Instant::now() + Duration::from_secs(2); } if let Some(active) = &mut running { - if self.spec.kind == GroupKind::Issue || self.collaboration.is_builtin() { + if unassignment.is_none() && (self.spec.kind == GroupKind::Issue || self.collaboration.is_builtin()) { let target = crate::store::UnassignmentTarget::RunningTurn(active.claim.turn_id.clone()); - match self.settle_unassignment(target).await { - Ok(true) => { - settling_unassignment = false; - running = None; - continue; - } - Ok(false) => { settling_unassignment = false; } + match self.confirmed_unassignment(target).await { + Ok(found) => unassignment = found, + Err(error) => { tracing::warn!(%error, "cannot confirm active unassignment"); } + } + } + if let Some(change) = unassignment.as_ref() { + match self.settle_unassignment(change, Some(active)).await { + Ok(()) => { running = None; unassignment = None; } Err(error) => { - settling_unassignment = true; tracing::warn!(%error, "cannot settle active unassignment"); - self.publish_turn_error(&active.claim, "unknown", &error.to_string()); - continue; } } + continue; } self.begin_active_context_reset(active).await; if active.reset_id.is_none() @@ -486,6 +518,7 @@ pub(crate) struct RunningAgentTurn { pub(crate) claim: TurnClaim, pub(crate) provider_turn_id: String, pub(crate) reset_id: Option, + pub(super) stop_terminal: Option, /// The receiver that observed this turn's `TurnStarted`, created before /// the send and handed off with the turn, so the drive loop consumes the /// terminal with no subscription-timing gap. @@ -493,3 +526,27 @@ pub(crate) struct RunningAgentTurn { /// Shared run admission is held until this actual turn reaches terminal or stop. pub(crate) _admission: Option, } + +impl RunningAgentTurn { + /// Keep terminal evidence across a failed fence or database commit. + fn terminal_after_close(&mut self) -> Option { + loop { + match self.events.try_recv() { + Ok(crate::agent_session::SessionEvent::TurnTerminal { + provider_turn_id, + outcome, + error, + }) if provider_turn_id == self.provider_turn_id => { + self.stop_terminal = Some(crate::store::ObservedTurnTerminal { + turn_id: self.claim.turn_id.clone(), + outcome, + error, + }); + } + Ok(_) | Err(tokio::sync::broadcast::error::TryRecvError::Lagged(_)) => {} + Err(_) => break, + } + } + self.stop_terminal.clone() + } +} diff --git a/src/store/mod.rs b/src/store/mod.rs index 032f244a..2f9db90c 100644 --- a/src/store/mod.rs +++ b/src/store/mod.rs @@ -28,7 +28,7 @@ mod builtin_execution; mod run_progress; mod unassignment; pub use builtin_execution::BuiltinExecutionCommand; -pub(crate) use unassignment::{Unassignment, UnassignmentTarget}; +pub(crate) use unassignment::{ObservedTurnTerminal, Unassignment, UnassignmentTarget}; mod runs; pub use runs::RunCommand; mod gh_writes; @@ -1326,13 +1326,21 @@ impl StoreActor { receiver.recv().map_err(|_| StoreError::ActorStopped)? } - pub(crate) fn retire_unassigned_work_item( + pub(crate) fn settle_unassignment( &self, - change: Unassignment, - ) -> Result<(), StoreError> { + change: &Unassignment, + terminal: Option, + stopped: bool, + ) -> Result { let (reply, receiver) = mpsc::channel(); self.sender - .send(Command::RetireUnassignedWorkItem(change.event_id, change.assignment_id, reply)) + .send(Command::SettleUnassignment( + change.event_id.clone(), + change.assignment_id.clone(), + terminal, + stopped, + reply, + )) .map_err(|_| StoreError::ActorUnavailable)?; receiver.recv().map_err(|_| StoreError::ActorStopped)? } @@ -1734,7 +1742,13 @@ enum Command { ), IgnoreAssignmentEvent(String, Sender>), DueUnassignment(UnassignmentTarget, u64, Sender, StoreError>>), - RetireUnassignedWorkItem(String, Option, Sender>), + SettleUnassignment( + String, + Option, + Option, + bool, + Sender>, + ), CompleteAgentAssignment( AgentMaterialization, String, @@ -2081,11 +2095,13 @@ fn actor_loop(database: &Path, backups: &Path, receiver: Receiver) { Command::DueUnassignment(target, quiet_seconds, reply) => { let _ = reply.send(unassignment::due(database, &target, quiet_seconds)); } - Command::RetireUnassignedWorkItem(event_id, assignment_id, reply) => { - let _ = reply.send(retire_unassigned_work_item( + Command::SettleUnassignment(event_id, assignment_id, terminal, stopped, reply) => { + let _ = reply.send(settle_unassignment( database, &event_id, assignment_id.as_deref(), + terminal.as_ref(), + stopped, )); } Command::CompleteAgentAssignment( @@ -4341,12 +4357,14 @@ fn begin_agent_assignment( Ok(Some(materialization)) } -/// Consume this change and retire its current generation after provider shutdown. -fn retire_unassigned_work_item( +/// Keep observed native terminal facts even when revoking platform authority must retry. +fn settle_unassignment( database: &Path, event_id: &str, expected_assignment: Option<&str>, -) -> Result<(), StoreError> { + terminal: Option<&ObservedTurnTerminal>, + stopped: bool, +) -> Result { require_current_schema(database)?; let now = now_rfc3339(); let mut connection = open_read_write(database)?; @@ -4368,13 +4386,39 @@ fn retire_unassigned_work_item( ) .optional()?; let Some((assignment_id, agent_id, work_item_node_id)) = target else { + if !stopped { + return Ok(false); + } transaction.execute( "UPDATE events SET lifecycle='consumed' WHERE event_id=?1 AND lifecycle='pending'", [event_id], )?; transaction.commit()?; - return Ok(()); + return Ok(false); }; + let mut recorded_terminal = false; + if let Some(terminal) = terminal { + let updated = transaction.execute( + "UPDATE turns SET lifecycle=?2,ended_at=?3,error=CASE WHEN ?4 IS NULL THEN error + WHEN error IS NULL THEN ?4 ELSE error || char(10) || ?4 END + WHERE turn_id=?1 AND lifecycle IN ('starting','running') + AND session_id IN (SELECT session_id FROM provider_sessions WHERE agent_id=?5)", + params![terminal.turn_id, terminal.outcome.lifecycle(), now, terminal.error, agent_id], + )?; + recorded_terminal = updated == 1; + if recorded_terminal { + record_terminal_feedback( + &transaction, + &terminal.turn_id, + terminal.outcome.lifecycle(), + &now, + )?; + } + } + if !stopped { + transaction.commit()?; + return Ok(recorded_terminal); + } let unconfirmed: bool = transaction.query_row( "SELECT EXISTS(SELECT 1 FROM provider_sessions WHERE agent_id=?1 AND lifecycle NOT IN ('retired','replaced') AND execution_stopped_at IS NULL)", @@ -4385,7 +4429,8 @@ fn retire_unassigned_work_item( return Err(StoreError::InvalidData("unassignment lacks a confirmed native stop".into())); } transaction.execute( - "UPDATE turns SET lifecycle='interrupted',ended_at=?2 + "UPDATE turns SET lifecycle='unknown',ended_at=?2, + error=coalesce(error || char(10),'') || 'unassignment did not observe the active turn terminal' WHERE lifecycle IN ('starting','running') AND session_id IN (SELECT session_id FROM provider_sessions WHERE agent_id=?1)", params![agent_id, now], @@ -4416,7 +4461,7 @@ fn retire_unassigned_work_item( [event_id], )?; transaction.commit()?; - Ok(()) + Ok(recorded_terminal) } fn ignore_assignment_event(database: &Path, event_id: &str) -> Result<(), StoreError> { @@ -5351,6 +5396,19 @@ fn fence_session_and_request_reset( Ok(()) } +fn record_terminal_feedback( + tx: &rusqlite::Transaction<'_>, + turn_id: &str, + lifecycle: &str, + now: &str, +) -> Result<(), StoreError> { + if lifecycle != "unknown" { + let feedback = if lifecycle == "completed" { "+1" } else { "confused" }; + reaction_feedback::record_turn(tx, turn_id, feedback, now)?; + } + Ok(()) +} + #[allow(clippy::too_many_lines)] fn mark_turn_terminal(database: &Path, turn_id: &str, lifecycle: &str) -> Result<(), StoreError> { require_current_schema(database)?; @@ -5400,10 +5458,7 @@ fn mark_turn_terminal(database: &Path, turn_id: &str, lifecycle: &str) -> Result "UPDATE turns SET lifecycle=?2,ended_at=?3 WHERE turn_id=?1", params![turn_id, lifecycle, now], )?; - if lifecycle != "unknown" { - let feedback = if lifecycle == "completed" { "+1" } else { "confused" }; - reaction_feedback::record_turn(&transaction, turn_id, feedback, &now)?; - } + record_terminal_feedback(&transaction, turn_id, lifecycle, &now)?; let finalization = trigger_kind == "finalization"; let final_assignment_lifecycle = if work_item_kind == "pr" && work_item_state.eq_ignore_ascii_case("merged") { diff --git a/src/store/unassignment.rs b/src/store/unassignment.rs index ca4d278c..cc9cecb4 100644 --- a/src/store/unassignment.rs +++ b/src/store/unassignment.rs @@ -7,6 +7,13 @@ pub(crate) enum UnassignmentTarget { RunningTurn(String), } +#[derive(Clone)] +pub(crate) struct ObservedTurnTerminal { + pub turn_id: String, + pub outcome: crate::agent_session::TurnOutcome, + pub error: Option, +} + pub(crate) struct Unassignment { pub event_id: String, pub(super) assignment_id: Option, From d8e0d90c4d6746f70ff0b0c6f552a397ff335879 Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sat, 28 Nov 2026 21:56:33 +0800 Subject: [PATCH 22/43] =?UTF-8?q?ref(pi):=20=E4=BF=9D=E7=95=99=E7=BB=9F?= =?UTF-8?q?=E4=B8=80=E5=90=AF=E5=8A=A8=E6=B8=85=E7=90=86=E8=B7=AF=E5=BE=84?= =?UTF-8?q?=E7=9A=84=E5=8E=9F=E7=94=9F=E7=8A=B6=E6=80=81=E9=87=87=E6=A0=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/20-product-tdd/app-server.md | 3 +++ native/pi/README.md | 5 +++- src/provider/pi.rs | 42 +++++++++++++++++-------------- 3 files changed, 30 insertions(+), 20 deletions(-) diff --git a/docs/20-product-tdd/app-server.md b/docs/20-product-tdd/app-server.md index 5cfdc50e..c07ef921 100644 --- a/docs/20-product-tdd/app-server.md +++ b/docs/20-product-tdd/app-server.md @@ -177,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/native/pi/README.md b/native/pi/README.md index a5322569..872de058 100644 --- a/native/pi/README.md +++ b/native/pi/README.md @@ -43,10 +43,13 @@ subagents、background、Context7 和 MCPorter 的局部补丁仅随相应插件 对全新安装仅选择 `background` 后,可直接验证交付的 Node、Pi SDK 与扩展、工具环境和停止回执。 下面的验收使用临时 HOME、离线模型描述和本地 Bash,不需要模型账号。它也会检查新建 session 文件、结束 RPC 输入后进程正常退出,以及随后从执行目录取得完整停止回执。 +另一个用例通过 SDK 调用所选插件的 Bash 工具,检查命令退出 0 时仍能报告归属未确认。 ```sh node native/pi/install.mjs "$PWD/runtime/pi-background" --plugins background -BRAID_TEST_PI_INSTALL="$PWD/runtime/pi-background" node --test native/pi/acceptance/installed-runtime.test.mjs +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 cargo test --locked --bin braid failed_home_binding_stops_the_installed_execution_before_returning -- --ignored ``` 锁定的 pi-subagents 0.56.0 对自定义角色 frontmatter 使用字符串列表解析, diff --git a/src/provider/pi.rs b/src/provider/pi.rs index 824ca238..fe43efcd 100644 --- a/src/provider/pi.rs +++ b/src/provider/pi.rs @@ -529,7 +529,7 @@ impl AgentProvider for PiProvider { ) -> Result { let mut state = self.state.lock().await; let native = Self::request(&mut state, json!({"type":"get_state"})).await?; - validate_managed_state(&state, &native)?; + observe_managed_state(&state, &native)?; if native_is_busy(&native)? { return Err(ProviderError::Deferred( "Pi is streaming, compacting or has queued input".into(), @@ -980,27 +980,31 @@ fn native_is_busy(response: &Value) -> Result { Ok(streaming || compacting || pending != 0) } -fn validate_managed_state(state: &PiState, response: &Value) -> Result<(), ProviderError> { - if let Some(execution) = state.process.as_ref().and_then(|process| process.execution.as_ref()) { - let managed = execution.state(response)?; - tracing::info!(name = "braid.provider.execution", provider.kind = "pi", - provider.execution.id = %execution.id, provider.managed.state = ?managed.status, - error.reason = managed.reason.as_deref().unwrap_or(""), - "Pi native managed state observation"); - } - Ok(()) +fn observe_managed_state( + state: &PiState, + response: &Value, +) -> Result, ProviderError> { + let Some(execution) = state.process.as_ref().and_then(|process| process.execution.as_ref()) + else { + return Ok(None); + }; + let managed = execution.state(response)?; + tracing::info!(name = "braid.provider.execution", provider.kind = "pi", + provider.execution.id = %execution.id, provider.managed.state = ?managed.status, + error.reason = managed.reason.as_deref().unwrap_or(""), + "Pi native managed state observation"); + Ok(Some(managed)) } fn validate_started_runtime(state: &PiState, response: &Value) -> Result<(), ProviderError> { - if let Some(execution) = state.process.as_ref().and_then(|process| process.execution.as_ref()) { - let managed = - execution.state(response).map_err(|error| ProviderError::Unknown(error.to_string()))?; - if matches!(managed.status, runtime::ManagedStatus::Unknown) { - return Err(ProviderError::Unknown(format!( - "Pi managed execution is unavailable at startup: {}", - managed.reason.as_deref().unwrap_or("native returned unknown without a reason") - ))); - } + if let Some(managed) = observe_managed_state(state, response) + .map_err(|error| ProviderError::Unknown(error.to_string()))? + && matches!(managed.status, runtime::ManagedStatus::Unknown) + { + return Err(ProviderError::Unknown(format!( + "Pi managed execution is unavailable at startup: {}", + managed.reason.as_deref().unwrap_or("native returned unknown without a reason") + ))); } Ok(()) } From 8b48ac3453bd0e9c3f5a900e2228fad6e38b9a66 Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sat, 28 Nov 2026 21:56:33 +0800 Subject: [PATCH 23/43] =?UTF-8?q?chore(audit):=20=E5=AF=B9=E8=BF=90?= =?UTF-8?q?=E8=A1=8C=E4=B8=AD=E6=92=A4=E9=94=80=E7=9A=84=E6=97=A7=E5=AE=9E?= =?UTF-8?q?=E7=8E=B0=E5=92=8C=E7=BB=88=E6=80=81=E4=B8=A2=E5=A4=B1=E5=81=9A?= =?UTF-8?q?=E5=AE=9A=E7=82=B9=E5=AF=B9=E7=85=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/audit-controls/ci-unassignment.sh | 64 +++++++++++++++++++++++ .github/workflows/audit-control-runs.yml | 2 +- 2 files changed, 65 insertions(+), 1 deletion(-) create mode 100644 .github/audit-controls/ci-unassignment.sh diff --git a/.github/audit-controls/ci-unassignment.sh b/.github/audit-controls/ci-unassignment.sh new file mode 100644 index 00000000..1c300346 --- /dev/null +++ b/.github/audit-controls/ci-unassignment.sh @@ -0,0 +1,64 @@ +#!/usr/bin/env bash +set -euo pipefail +base=5455350a2fe1d95e45b1d973e2c086208e1827e5 +source_dir=$PWD +export CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-$source_dir/target}" +snapshot="$(mktemp -d)" +file= +restore() { [[ -z "$file" ]] || git restore -- "$file"; } +trap 'restore; rm -rf "$snapshot"' EXIT +if ! git cat-file -e "$base^{commit}" 2>/dev/null; then git fetch --no-tags origin "$base"; fi +git archive "$base" | tar -x -C "$snapshot" +python3 - "$snapshot" <<'PY' +from pathlib import Path +import sys +p=Path('src/group/continuous_tests.rs') +new=p.read_text() +old=Path(sys.argv[1])/p +source=old.read_text() +prefix=new[:new.index('#[tokio::test]')] +# The old neutral interface requires one additional unused method. +anchor=' async fn send_user_msg(' +assert prefix.count(anchor)==1 +prefix=prefix.replace(anchor, ' async fn interrupt(&self) -> Result<(), SessionError> { Ok(()) }\n'+anchor) +start=new.index('#[tokio::test]\nasync fn worker_stops_a_running_unassigned_issue_only_after_its_quiet_window') +end=new.find('#[tokio::test]',start+1) +case=new[start:end if end!=-1 else len(new)] +old.write_text(prefix+source[source.index('#[tokio::test]'):]+'\n'+case) +PY +catch_control() { + local manifest="$1" case_name="$2" expected="$3" out + out="$(mktemp)" + if cargo test --locked --manifest-path "$manifest" --bin braid "$case_name" -- --nocapture >"$out" 2>&1; then cat "$out"; return 1; fi + cat "$out" + grep -E 'test .*FAILED' "$out" >/dev/null + grep -F "$expected" "$out" >/dev/null + rm -f "$out" +} +case_name=worker_stops_a_running_unassigned_issue_only_after_its_quiet_window +catch_control "$snapshot/Cargo.toml" "$case_name" 'settled unassignment must stop a running native turn' +file=src/store/mod.rs +python3 - <<'PY' +from pathlib import Path +p=Path('src/store/mod.rs') +s=p.read_text() +old="UPDATE turns SET lifecycle='unknown',ended_at=?2," +assert s.count(old)==1 +p.write_text(s.replace(old,"UPDATE turns SET lifecycle='interrupted',ended_at=?2,")) +PY +catch_control Cargo.toml "$case_name" 'closing the session alone cannot identify a turn outcome' +restore +file=src/group/worker.rs +python3 - <<'PY' +from pathlib import Path +p=Path('src/group/worker.rs') +s=p.read_text() +old='let terminal = active.as_deref_mut().and_then(RunningAgentTurn::terminal_after_close);' +assert s.count(old)==1 +p.write_text(s.replace(old,'let terminal = active.as_deref_mut().and_then(RunningAgentTurn::terminal_after_close).filter(|_| false);')) +PY +for test_case in builtin_turn_runs_without_writer_service_and_cannot_mint_after_reassignment worker_preserves_a_failed_turn_during_unassignment_while_the_platform_fence_is_offline; do + catch_control Cargo.toml "$test_case" 'observed provider terminal must be durable while the platform fence is offline' +done +restore +file= diff --git a/.github/workflows/audit-control-runs.yml b/.github/workflows/audit-control-runs.yml index e9189602..63407b77 100644 --- a/.github/workflows/audit-control-runs.yml +++ b/.github/workflows/audit-control-runs.yml @@ -10,7 +10,7 @@ jobs: strategy: fail-fast: false matrix: - owner: [native, state, ops, publication, browser] + owner: [unassignment] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 From d827c81317e491e2992648d94130e2b25995f2b0 Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sat, 28 Nov 2026 21:59:49 +0800 Subject: [PATCH 24/43] =?UTF-8?q?ref(acceptance):=20=E6=8B=92=E7=BB=9D?= =?UTF-8?q?=E5=A4=B9=E5=B8=A6=E7=8E=B0=E6=88=90=E5=BA=93=E7=9A=84=E5=BD=92?= =?UTF-8?q?=E6=A1=A3=E5=B9=B6=E6=A0=B8=E5=AF=B9=E6=B8=85=E7=90=86=E6=9C=AA?= =?UTF-8?q?=E7=A1=AE=E8=AE=A4=E7=9A=84=E6=9E=84=E9=80=A0=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scripts/verify-package.sh | 7 ++++- src/profile_materials/tests.rs | 52 ++++++++++++++++++++++++++++++---- 2 files changed, 52 insertions(+), 7 deletions(-) diff --git a/scripts/verify-package.sh b/scripts/verify-package.sh index 52f8c4f5..9e457160 100755 --- a/scripts/verify-package.sh +++ b/scripts/verify-package.sh @@ -37,6 +37,11 @@ if [ "$version" != "braid ${2#v}" ]; then fi config="$PWD/config.example.toml" braid config check --config "$config" -braid migrate apply --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/profile_materials/tests.rs b/src/profile_materials/tests.rs index 3d57b732..2ccab661 100644 --- a/src/profile_materials/tests.rs +++ b/src/profile_materials/tests.rs @@ -1,16 +1,21 @@ use super::*; use serde_json::{Value, json}; -fn configuration(root: &Path, kind: CredentialKind, install: Option<&Path>) -> Config { +fn configuration( + root: &Path, + kind: CredentialKind, + executable: Option<&Path>, + manifest: Option<&Path>, +) -> Config { let mut config: Config = toml::from_str(include_str!("../../config.example.toml")).unwrap(); for runtime in &mut config.runtimes { runtime.adapter_type = "pi".into(); runtime.version = "1.1.0".into(); runtime.home = None; - if let Some(install) = install { - runtime.executable = install.join("pi"); - runtime.native_runtime = Some(install.join("runtime-manifest.json")); + if let Some(executable) = executable { + runtime.executable = executable.to_owned(); } + runtime.native_runtime = manifest.map(Path::to_owned); } for profile in &mut config.profiles { profile.adapter_type = "pi".into(); @@ -64,7 +69,7 @@ fn snapshot_writes_native_model_fields_and_keeps_credentials_out_of_models_json( ] { let directory = root.join(name); fs::create_dir_all(&directory).unwrap(); - let config = configuration(&directory, kind, None); + let config = configuration(&directory, kind, None, None); let profile = &config.profiles[0]; let materials = collect(&config, profile).unwrap(); let home_key = uuid::Uuid::now_v7().to_string(); @@ -103,7 +108,12 @@ async fn failed_home_binding_stops_the_installed_execution_before_returning() { fs::create_dir_all(&homes).unwrap(); // A real post-launch metadata write fails after the SDK has opened its session. fs::write(homes.join("index"), "not a directory").unwrap(); - let config = configuration(&root, CredentialKind::None, Some(&install)); + let config = configuration( + &root, + CredentialKind::None, + Some(&install.join("pi")), + Some(&install.join("runtime-manifest.json")), + ); let profile = config.profiles[0].clone(); let factories = crate::provider::session_factories(&config).unwrap(); let factory = &factories[&profile.id]; @@ -144,3 +154,33 @@ async fn failed_home_binding_stops_the_installed_execution_before_returning() { assert_eq!(receipt["status"], "stopped"); assert_eq!(receipt["coverage"], "registered-process-groups-and-inherited-execution-markers"); } + +#[cfg(unix)] +#[tokio::test] +async fn startup_rejection_retains_an_unconfirmed_physical_shutdown() { + use std::os::unix::fs::PermissionsExt as _; + let root = std::env::temp_dir().join(format!("braid-pi-exit-{}", uuid::Uuid::now_v7())); + fs::create_dir_all(&root).unwrap(); + let executable = root.join("pi"); + fs::write(&executable, r#"#!/usr/bin/env python3 +import json, sys +command = json.loads(sys.stdin.readline()) +assert command["type"] == "new_session" +print(json.dumps({"id":command["id"], "success":False, "error":"session creation rejected"}), flush=True) +assert not sys.stdin.read() +sys.exit(29) +"#).unwrap(); + fs::set_permissions(&executable, fs::Permissions::from_mode(0o700)).unwrap(); + let config = configuration(&root, CredentialKind::None, Some(&executable), None); + let profile = config.profiles[0].clone(); + let factories = crate::provider::session_factories(&config).unwrap(); + let factory = &factories[&profile.id]; + let error = factory.start(profile, String::new(), String::new()).await.err().unwrap(); + fs::remove_dir_all(root).unwrap(); + assert!( + matches!(error, crate::agent_session::SessionError::Unknown(ref cause) + if cause.contains("session creation rejected") + && cause.contains("External Pi parent exited with exit status: 29")), + "{error}" + ); +} From ee6e3a3fc59218bc8c0e7adafe0fdac444b97e08 Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sat, 28 Nov 2026 22:02:43 +0800 Subject: [PATCH 25/43] =?UTF-8?q?fix(lifecycle):=20=E4=BF=9D=E7=95=99?= =?UTF-8?q?=E6=92=A4=E9=94=80=E8=AF=81=E6=8D=AE=E5=B9=B6=E5=81=9C=E6=AD=A2?= =?UTF-8?q?=E8=B0=83=E5=BA=A6=E9=80=80=E4=BC=91=E4=BB=A3=E7=9A=84=E5=8E=86?= =?UTF-8?q?=E5=8F=B2=E9=87=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 通过真实多线程 worker 检验 Completed、Failed、Unknown 与停止重试 - 从可调度及有限运行义务排除已退休任务,保留历史审计记录 --- docs/10-prd/acceptance.md | 4 +- src/group/continuous_tests.rs | 78 +++++++++++++++++++++++++++++++++- src/group/worker.rs | 26 +++++++----- src/profile_materials/tests.rs | 53 ++++++++++++++--------- src/runtime/builtin.rs | 4 +- src/store/mod.rs | 14 +++--- src/store/run_progress.rs | 19 +++++---- src/store/unassignment.rs | 2 + 8 files changed, 152 insertions(+), 48 deletions(-) diff --git a/docs/10-prd/acceptance.md b/docs/10-prd/acceptance.md index ff092a94..08be87cd 100644 --- a/docs/10-prd/acceptance.md +++ b/docs/10-prd/acceptance.md @@ -82,7 +82,9 @@ Pi 安装或 Rust 适配器变更时,Linux CI 复用本轮编译并按 lock 负向用例应断言错误阶段、类型或关键诊断,并有能够到达该守卫的合法前置条件。 恢复用例应先让真实 owner 写入,关闭并重新打开,再从消费者取回结果。新缺陷 -修复保留同一输入下修复前红、修复后绿的证据;缺少这种证据时说明原因。删除或 +修复保留同一输入下修复前红、修复后绿的证据。两份 checkout 做对照时,各设独立 +`CARGO_TARGET_DIR`:Cargo 集成测试按固定路径启动 binary,共享 target 曾使另一份 +checkout 的同名产物被当成最新。核对运行的测试名和失败诊断;缺少对照时说明原因。删除或 迁移测试前,核对原断言在保留测试中的归属;仅重复编译同一模块不算额外证明。 全绿支持上述局部合同,不授予产品发布资格。真实 campaign 仍按下列场景记录 diff --git a/src/group/continuous_tests.rs b/src/group/continuous_tests.rs index e0b35ef8..27c87075 100644 --- a/src/group/continuous_tests.rs +++ b/src/group/continuous_tests.rs @@ -492,6 +492,70 @@ async fn persisted_idle_reset_uses_only_confirmed_native_stop_after_restart() { } } +#[tokio::test] +async fn retired_reset_history_cannot_replace_an_execution_or_block_a_finite_run() { + for blocked in [false, true] { + let f = Fixture::new(true); + let mut config = f.config.clone(); + config.scheduler.quiet_seconds = 0; + let captured = Arc::new(Captured::default()); + let (github, http) = issue_context_server("Current contract").await; + let collaboration = CollaborationBackend::GitHub(github); + let spec = GroupSpec::new(GroupKind::Issue, &config, &f.store, "owner/repository").unwrap(); + let driver = worker::GroupDriver { + store: &f.store, + config: &config, + collaboration: &collaboration, + spec: &spec, + sessions: SessionManager::new(Arc::new(Factory(captured.clone()))), + }; + driver + .sessions + .resume("provider".into(), spec.profile.clone(), "instructions".into()) + .await + .unwrap(); + let policy = SchedulerPolicy { quiet_seconds: 0, event_threshold: 1 }; + f.store.ingest_event(revision(), policy).unwrap(); + let reset = f + .store + .begin_context_reset(None, "issue".into(), "issue-codex".into()) + .unwrap() + .unwrap(); + if blocked { + f.store + .fail_context_reset(reset.reset_id.clone(), "old context is unavailable".into()) + .unwrap(); + } + let before = f.store.execution_progress().unwrap(); + assert!(before.unresolved_reset); + assert_eq!(before.blocked_reset.as_deref(), blocked.then_some(reset.reset_id.as_str())); + let mut revoke = revision(); + revoke.delivery_guid = "assignment-removed-during-reset".into(); + revoke.identity = crate::store::ChangeIdentity::Occurrence; + revoke.kind = EventKind::Unassign; + revoke.action = Some("unassigned".into()); + revoke.requires_attention = false; + revoke.cross_surface_invalidation = false; + let event = f.store.ingest_event(revoke, policy).unwrap().event_id.unwrap(); + driver.settle_idle_unassignment(event).await.unwrap(); + let after = f.store.runtime_status().unwrap(); + assert_eq!(after.agent_groups[0].assignment_lifecycle, "retired"); + assert_eq!( + after.context_resets[0].lifecycle, + if blocked { "blocked" } else { "materializing" } + ); + assert!( + !driver.materialize_next_context_reset().await, + "a retired generation cannot start replacement execution" + ); + assert!(captured.memory.lock().unwrap().is_empty()); + let progress = f.store.execution_progress().unwrap(); + assert!(progress.blocked_reset.is_none(), "a historical reset cannot block a finite run"); + assert!(!progress.unresolved_reset, "retired reset history is no longer outstanding work"); + http.abort(); + } +} + #[tokio::test] async fn failed_idle_stop_keeps_the_handle_and_blocks_replacement() { let f = Fixture::new(true); @@ -683,12 +747,12 @@ async fn stopping_native_execution_does_not_wait_for_execution_fence() { http.abort(); } -#[tokio::test] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn builtin_turn_runs_without_writer_service_and_cannot_mint_after_reassignment() { builtin_running_unassignment(crate::agent_session::TurnOutcome::Completed, None).await; } -#[tokio::test] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn worker_preserves_a_failed_turn_during_unassignment_while_the_platform_fence_is_offline() { builtin_running_unassignment( crate::agent_session::TurnOutcome::Failed, @@ -1000,5 +1064,15 @@ async fn worker_stops_a_running_unassigned_issue_only_after_its_quiet_window() { assert_eq!(captured.inputs.lock().unwrap().len(), 1); shutdown.send(true).unwrap(); worker.await.unwrap().unwrap(); + let status: String = f + .db() + .query_row( + "SELECT body FROM operational_status_facts WHERE assignment_id='assignment'", + [], + |row| row.get(0), + ) + .expect("an unobserved turn terminal must publish the configured operational status"); + assert!(status.contains("unknown")); + assert!(status.contains("unassignment did not observe the active turn terminal")); http.abort(); } diff --git a/src/group/worker.rs b/src/group/worker.rs index 53916807..37b14577 100644 --- a/src/group/worker.rs +++ b/src/group/worker.rs @@ -211,18 +211,24 @@ impl GroupDriver<'_> { let terminal = active.as_deref_mut().and_then(RunningAgentTurn::terminal_after_close); if (stop.is_ok() || terminal.is_some()) && self.store.settle_unassignment(change, terminal.clone(), stop.is_ok())? - && let (Some(active), Some(terminal)) = (active, terminal) - && matches!( - terminal.outcome, - crate::agent_session::TurnOutcome::Failed - | crate::agent_session::TurnOutcome::Unknown - ) + && let Some(active) = active { - self.enqueue_turn_error( - &active.claim, - terminal.outcome.lifecycle(), - terminal.error.as_deref().unwrap_or("provider did not supply a terminal reason"), + use crate::agent_session::TurnOutcome; + let (outcome, reason) = terminal.as_ref().map_or( + (TurnOutcome::Unknown, crate::store::MISSING_TERMINAL), + |terminal| { + ( + terminal.outcome, + terminal + .error + .as_deref() + .unwrap_or("provider did not supply a terminal reason"), + ) + }, ); + if matches!(outcome, TurnOutcome::Failed | TurnOutcome::Unknown) { + self.enqueue_turn_error(&active.claim, outcome.lifecycle(), reason); + } } stop.map_err(Into::into) } diff --git a/src/profile_materials/tests.rs b/src/profile_materials/tests.rs index 2ccab661..9b3aacee 100644 --- a/src/profile_materials/tests.rs +++ b/src/profile_materials/tests.rs @@ -126,17 +126,28 @@ async fn failed_home_binding_stops_the_installed_execution_before_returning() { let receipt = fs::read(execution.path().join("execution-stop.json")); if receipt.is_err() { // Reclaim only this test's execution when an old/broken adapter abandons it. - let cleanup = std::process::Command::new(install.join("bin/node")) - .arg(install.join("managed.mjs")) - .args(["cleanup", "--execution-dir"]) - .arg(execution.path()) - .arg("--execution-id") - .arg(&id) - .output() - .unwrap(); - assert!(cleanup.status.success()); - let cleanup: Value = serde_json::from_slice(&cleanup.stdout).unwrap(); - assert_eq!(cleanup["status"], "stopped", "{cleanup}"); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + loop { + let cleanup = tokio::process::Command::new(install.join("bin/node")) + .arg(install.join("managed.mjs")) + .args(["cleanup", "--execution-dir"]) + .arg(execution.path()) + .arg("--execution-id") + .arg(&id) + .output() + .await + .unwrap(); + assert!(cleanup.status.success()); + let cleanup: Value = serde_json::from_slice(&cleanup.stdout).unwrap(); + if cleanup["status"] == "stopped" { + break; + } + // Child exit and OS marker inspection can overlap on the abandoned execution. + assert!( + std::time::Instant::now() < deadline, + "test teardown could not confirm stop: {cleanup}" + ); + } } fs::remove_dir_all(root).unwrap(); assert!( @@ -162,14 +173,18 @@ async fn startup_rejection_retains_an_unconfirmed_physical_shutdown() { let root = std::env::temp_dir().join(format!("braid-pi-exit-{}", uuid::Uuid::now_v7())); fs::create_dir_all(&root).unwrap(); let executable = root.join("pi"); - fs::write(&executable, r#"#!/usr/bin/env python3 -import json, sys -command = json.loads(sys.stdin.readline()) -assert command["type"] == "new_session" -print(json.dumps({"id":command["id"], "success":False, "error":"session creation rejected"}), flush=True) -assert not sys.stdin.read() -sys.exit(29) -"#).unwrap(); + fs::write( + &executable, + r#"#!/bin/sh +IFS= read -r request || exit 20 +case "$request" in *'"new_session"'*) ;; *) exit 21 ;; esac +id=$(printf '%s' "$request" | sed -n 's/.*"id"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p') +printf '{"id":%s,"success":false,"error":"session creation rejected"}\n' "$id" +if IFS= read -r extra; then exit 22; fi +exit 29 +"#, + ) + .unwrap(); fs::set_permissions(&executable, fs::Permissions::from_mode(0o700)).unwrap(); let config = configuration(&root, CredentialKind::None, Some(&executable), None); let profile = config.profiles[0].clone(); diff --git a/src/runtime/builtin.rs b/src/runtime/builtin.rs index 4a8e3010..f7a72958 100644 --- a/src/runtime/builtin.rs +++ b/src/runtime/builtin.rs @@ -891,7 +891,9 @@ mod tests { .try_into() .unwrap(); assert_eq!(turns, 0); - halt.send(true).unwrap(); + if halt.send(true).is_err() { + panic!("runtime exited before the requested stop: {:#?}", runtime.await); + } let error = runtime.await.unwrap().unwrap_err(); assert!(error.to_string().contains("execution fence remains unconfirmed"), "{error:#}"); http.abort(); diff --git a/src/store/mod.rs b/src/store/mod.rs index 2f9db90c..d37e2c3b 100644 --- a/src/store/mod.rs +++ b/src/store/mod.rs @@ -28,7 +28,9 @@ mod builtin_execution; mod run_progress; mod unassignment; pub use builtin_execution::BuiltinExecutionCommand; -pub(crate) use unassignment::{ObservedTurnTerminal, Unassignment, UnassignmentTarget}; +pub(crate) use unassignment::{ + MISSING_TERMINAL, ObservedTurnTerminal, Unassignment, UnassignmentTarget, +}; mod runs; pub use runs::RunCommand; mod gh_writes; @@ -4428,12 +4430,12 @@ fn settle_unassignment( if unconfirmed { return Err(StoreError::InvalidData("unassignment lacks a confirmed native stop".into())); } - transaction.execute( + let missing_terminals = transaction.execute( "UPDATE turns SET lifecycle='unknown',ended_at=?2, - error=coalesce(error || char(10),'') || 'unassignment did not observe the active turn terminal' + error=coalesce(error || char(10),'') || ?3 WHERE lifecycle IN ('starting','running') AND session_id IN (SELECT session_id FROM provider_sessions WHERE agent_id=?1)", - params![agent_id, now], + params![agent_id, now, MISSING_TERMINAL], )?; transaction.execute( "UPDATE provider_sessions SET lifecycle='retired' @@ -4461,7 +4463,7 @@ fn settle_unassignment( [event_id], )?; transaction.commit()?; - Ok(recorded_terminal) + Ok(recorded_terminal || missing_terminals > 0) } fn ignore_assignment_event(database: &Path, event_id: &str) -> Result<(), StoreError> { @@ -4852,7 +4854,7 @@ fn ready_context_reset( JOIN agent_instances ai ON ai.agent_id=cr.agent_id JOIN assignments a ON a.assignment_id=ai.assignment_id JOIN work_items w ON w.node_id=a.work_item_node_id - WHERE cr.lifecycle='materializing' AND w.kind=?1 AND ai.profile_id=?2 + WHERE cr.lifecycle='materializing' AND a.lifecycle!='retired' AND w.kind=?1 AND ai.profile_id=?2 ORDER BY cr.created_at,cr.reset_id LIMIT 1", params![work_item_kind, profile_id], |row| row.get::<_, String>(0), diff --git a/src/store/run_progress.rs b/src/store/run_progress.rs index 556c247a..21bbbe58 100644 --- a/src/store/run_progress.rs +++ b/src/store/run_progress.rs @@ -42,19 +42,20 @@ pub(super) fn execution(database: &Path) -> Result>(0), ) .optional()?; - let unresolved_reset = tx.query_row( - "SELECT EXISTS(SELECT 1 FROM context_resets WHERE lifecycle!='applied')", - [], - |row| row.get(0), - )?; + let unresolved_reset = pending_reset.is_some(); + let blocked_reset = pending_reset.flatten(); tx.commit()?; Ok(ExecutionProgress { blocked_group, blocked_reset, unresolved_reset }) } diff --git a/src/store/unassignment.rs b/src/store/unassignment.rs index cc9cecb4..5ef16e97 100644 --- a/src/store/unassignment.rs +++ b/src/store/unassignment.rs @@ -2,6 +2,8 @@ use super::{StoreError, open_read_only, require_current_schema}; use rusqlite::{OptionalExtension as _, params}; use std::path::Path; +pub(crate) const MISSING_TERMINAL: &str = "unassignment did not observe the active turn terminal"; + pub(crate) enum UnassignmentTarget { Event(String), RunningTurn(String), From 73a9d3f126874284b754e07f5687df1436cccf22 Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sat, 28 Nov 2026 22:02:43 +0800 Subject: [PATCH 26/43] =?UTF-8?q?chore(audit):=20=E5=A4=8D=E9=AA=8C?= =?UTF-8?q?=E9=80=80=E4=BC=91=E4=BB=A3=E9=9A=94=E7=A6=BB=E4=B8=8E=E6=9C=AA?= =?UTF-8?q?=E7=9F=A5=E7=BB=88=E6=80=81=E7=9A=84=E7=A0=B4=E5=9D=8F=E6=8E=A7?= =?UTF-8?q?=E5=88=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/audit-controls/ci-unassignment.sh | 25 +++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/.github/audit-controls/ci-unassignment.sh b/.github/audit-controls/ci-unassignment.sh index 1c300346..60c52ad0 100644 --- a/.github/audit-controls/ci-unassignment.sh +++ b/.github/audit-controls/ci-unassignment.sh @@ -62,3 +62,28 @@ for test_case in builtin_turn_runs_without_writer_service_and_cannot_mint_after_ done restore file= +mutate() { + python3 - "$file" "$1" "$2" <<'PY' +from pathlib import Path +import sys +p=Path(sys.argv[1]) +old,new=sys.argv[2:] +s=p.read_text() +assert s.count(old)==1, (p,old,s.count(old)) +p.write_text(s.replace(old,new)) +PY +} +reset_case=retired_reset_history_cannot_replace_an_execution_or_block_a_finite_run +file=src/store/mod.rs +mutate "AND a.lifecycle!='retired' AND w.kind=?1 AND ai.profile_id=?2" 'AND w.kind=?1 AND ai.profile_id=?2' +catch_control Cargo.toml "$reset_case" 'a retired generation cannot start replacement execution' +restore +file=src/store/run_progress.rs +mutate " AND a.lifecycle!='retired'" '' +catch_control Cargo.toml "$reset_case" 'retired reset history is no longer outstanding work' +restore +file=src/store/mod.rs +mutate ' || missing_terminals > 0' '' +catch_control Cargo.toml "$case_name" 'an unobserved turn terminal must publish the configured operational status' +restore +file= From 91b4c059ce8bda28e96b6a5c980361d3df256891 Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sat, 28 Nov 2026 22:04:34 +0800 Subject: [PATCH 27/43] =?UTF-8?q?ref(tests):=20=E7=94=A8=E6=8C=81=E4=B9=85?= =?UTF-8?q?=E6=B8=B8=E6=A0=87=E7=BB=A7=E7=BB=AD=E8=AF=BB=E5=8F=96=E4=BA=8B?= =?UTF-8?q?=E4=BB=B6=E5=B9=B6=E6=A0=B8=E5=AF=B9=E6=98=BE=E5=BC=8F=E6=81=A2?= =?UTF-8?q?=E5=A4=8D=E8=B5=84=E6=A0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 修正重复投递同一页造成的无关失败,核对实际恢复位置 - 从 CLI 确认关闭、未阻塞历史及活动后继均在正确守卫拒绝 --- docs/20-product-tdd/lifecycle.md | 3 +- src/runtime/builtin.rs | 14 +++++- tests/assignment.rs | 74 ++++++++++++++++++++++++++++---- 3 files changed, 81 insertions(+), 10 deletions(-) diff --git a/docs/20-product-tdd/lifecycle.md b/docs/20-product-tdd/lifecycle.md index 93d31a07..40f63042 100644 --- a/docs/20-product-tdd/lifecycle.md +++ b/docs/20-product-tdd/lifecycle.md @@ -123,7 +123,8 @@ classified as Agent-origin. worker 和空闲 worker 使用同一停止流程。内建平台直接处理不可撤回的撤销事件。 Group 在关闭期间继续接收原有 turn 的终态。平台撤权暂时失败时,已经收到的终态与 错误仍须持久化。原生停止和平台撤权均已确认后,Group 才将该代记为 `retired`; - 此时仍缺 provider 终态的 turn 记为 `unknown`。重新指派创建新一代及新会话。 + 此时仍缺 provider 终态的 turn 记为 `unknown`,并按该 Profile 的配置发布执行状态。 + 该代未完成的 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 diff --git a/src/runtime/builtin.rs b/src/runtime/builtin.rs index f7a72958..915e5103 100644 --- a/src/runtime/builtin.rs +++ b/src/runtime/builtin.rs @@ -810,6 +810,8 @@ mod tests { ); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let address = listener.local_addr().unwrap(); + let resumed = Arc::new(tokio::sync::Notify::new()); + let requested_after_close = Arc::clone(&resumed); let app = Router::new() .route( "/api/platform/repository", @@ -822,7 +824,13 @@ mod tests { ) .route( "/api/platform/events", - get(|| async { + get(move |axum::extract::Query(query): axum::extract::Query>| { + let resumed = Arc::clone(&resumed); + async move { + if query["after"] == 1 { + resumed.notify_one(); + return Json(serde_json::json!({"events": [], "nextAfter": 1, "lastSequence": 1})); + } Json(serde_json::json!({"events": [{ "sequence": 1, "event": { "delivery_guid": "local:1", "event_name": "local", @@ -835,6 +843,7 @@ mod tests { "known": true, "raw_payload": [] } }], "nextAfter": 1, "lastSequence": 1})) + } }), ) .route( @@ -881,6 +890,9 @@ mod tests { }) .await .expect("feed reception must survive a failed execution restore"); + tokio::time::timeout(Duration::from_secs(3), requested_after_close.notified()) + .await + .expect("intake must keep polling from the durable cursor during fence failure"); let events = store.work_item_lifecycle_candidates("test-space".into(), "issue".into(), 1).unwrap(); assert_eq!(events[0].action, "closed"); diff --git a/tests/assignment.rs b/tests/assignment.rs index 0fb59765..cfdfd0aa 100644 --- a/tests/assignment.rs +++ b/tests/assignment.rs @@ -1,4 +1,8 @@ -use std::{fs, process::Command}; +use std::{ + fs, + path::{Path, PathBuf}, + process::{Command, Output}, +}; fn braid() -> Command { Command::new(env!("CARGO_BIN_EXE_braid")) @@ -12,8 +16,7 @@ fn stdout(output: &std::process::Output) -> String { String::from_utf8_lossy(&output.stdout).into_owned() } -#[test] -fn assignment_reactivation_queues_one_wake_and_preserves_the_blocked_generation() { +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"); @@ -38,13 +41,23 @@ fn assignment_reactivation_queues_one_wake_and_preserves_the_blocked_generation( ) .expect("seed blocked assignment"); + (temporary, connection) +} + +fn reactivate(temporary: &Path) -> Output { + braid() + .args(["assignment", "reactivate", "1", "--kind", "issue", "--config"]) + .arg(temporary.join("config.toml")) + .output() + .expect("reactivate blocked assignment") +} + +#[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 = braid() - .args(["assignment", "reactivate", "1", "--kind", "issue", "--config"]) - .arg(&config) - .output() - .expect("reactivate blocked assignment"); + let output = reactivate(&temporary); assert!( output.status.success(), "stdout:\n{}\nstderr:\n{}", @@ -93,3 +106,48 @@ fn assignment_reactivation_queues_one_wake_and_preserves_the_blocked_generation( assert_eq!(assignment, (1, "blocked".into())); fs::remove_dir_all(temporary).unwrap(); } + +#[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(); +} From 0927d8857693a55ab974ca72825d5fec17cda57b Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sat, 28 Nov 2026 22:04:47 +0800 Subject: [PATCH 28/43] =?UTF-8?q?chore(ci):=20=E6=94=B6=E5=9B=9E=E6=9C=AC?= =?UTF-8?q?=E6=AC=A1=E5=AE=A1=E8=AE=A1=E7=9A=84=E4=B8=B4=E6=97=B6=E7=A0=B4?= =?UTF-8?q?=E5=9D=8F=E9=AA=8C=E8=AF=81=E5=85=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/audit-controls/ci-browser.sh | 27 ------- .github/audit-controls/ci-native.sh | 49 ------------ .github/audit-controls/ci-ops.sh | 41 ---------- .github/audit-controls/ci-publication.sh | 68 ----------------- .github/audit-controls/ci-state.sh | 46 ----------- .github/audit-controls/ci-unassignment.sh | 89 ---------------------- .github/audit-controls/platform-control.py | 74 ------------------ .github/workflows/audit-control-runs.yml | 31 -------- 8 files changed, 425 deletions(-) delete mode 100644 .github/audit-controls/ci-browser.sh delete mode 100644 .github/audit-controls/ci-native.sh delete mode 100755 .github/audit-controls/ci-ops.sh delete mode 100755 .github/audit-controls/ci-publication.sh delete mode 100644 .github/audit-controls/ci-state.sh delete mode 100644 .github/audit-controls/ci-unassignment.sh delete mode 100644 .github/audit-controls/platform-control.py delete mode 100644 .github/workflows/audit-control-runs.yml diff --git a/.github/audit-controls/ci-browser.sh b/.github/audit-controls/ci-browser.sh deleted file mode 100644 index 2476a799..00000000 --- a/.github/audit-controls/ci-browser.sh +++ /dev/null @@ -1,27 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail -npm ci --prefix tests/browser --ignore-scripts -export CHROME_BIN=/usr/bin/google-chrome -export BRAID_BINARY="$PWD/target/debug/braid" -cargo build --locked -node --test tests/browser/draft.test.mjs -python3 - <<'PY' -from pathlib import Path -p=Path('src/console/web/console.js') -s=p.read_text() -needle="if(e.body?.requestId&&e.body?.state){renderReceipt(e.body);return;}" -assert s.count(needle)==1 -p.write_text(s.replace(needle,"if(e.body?.requestId&&e.body?.state){renderReceipt(e.body);if(current)await select(current.item.number,true);return;}")) -PY -trap 'git restore src/console/web/console.js' EXIT -cargo build --locked -if node --test tests/browser/draft.test.mjs > /tmp/browser-control.log 2>&1; then - echo 'Reloading a rejected edit escaped detection' >&2 - exit 1 -fi -cat /tmp/browser-control.log -grep -F '第一位操作者已保存' /tmp/browser-control.log -grep -F '第二位操作者的草稿' /tmp/browser-control.log -git restore src/console/web/console.js -cargo build --locked -python3 .github/audit-controls/platform-control.py "$BRAID_BINARY" --green diff --git a/.github/audit-controls/ci-native.sh b/.github/audit-controls/ci-native.sh deleted file mode 100644 index 3e86059a..00000000 --- a/.github/audit-controls/ci-native.sh +++ /dev/null @@ -1,49 +0,0 @@ -#!/bin/bash -# Run in an isolated Actions checkout at the candidate commit. -set -euo pipefail -repo="$PWD" -snapshot=$(mktemp -d) -trap 'rm -rf "$snapshot"' EXIT -git archive HEAD | tar -x -C "$snapshot" -export CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-$repo/target}" -cd "$snapshot" -python3 - <<'PY' -from pathlib import Path -for filename, original, wrong in [ - ("src/provider/pi.rs", '"agent_settled" => {', '"agent_settled" | "agent_end" => {'), - ("src/provider/codex.rs", '"turn/started" => {', '"turn/started" | "error" => {'), - ("src/telemetry.rs", 'github.comment.summary = evidence.github_summary,', 'github.comment.summary = evidence.github_body,'), - ("src/tunnel.rs", '.header("X-GitHub-Event", "ping")', '.header("X-GitHub-Event", "unknown")'), -]: - path = Path(filename) - text = path.read_text() - assert text.count(original) == 1, filename - path.write_text(text.replace(original, wrong)) -PY -filters=(provider::pi::tests::pi_settles_after_retry provider::codex::tests::retryable_errors telemetry::tests::telemetry_routes_complete_evidence_only_to_otlp tunnel::tests::signed_probe_requires) -if cargo test --locked --bin braid -- "${filters[@]}" >"$snapshot/red.log" 2>&1; then - cat "$snapshot/red.log" - exit 1 -fi -cat "$snapshot/red.log" -for test_case in "${filters[@]}"; do grep -E "^test ${test_case}.*FAILED" "$snapshot/red.log"; done -for reason in 'intermediate frames must leave the turn open' 'willRetry' 'missing, incomplete, or misrouted github.comment.summary' 'signed ping must be durably admitted'; do - grep -F "$reason" "$snapshot/red.log" -done -for file in src/provider/pi.rs src/provider/codex.rs src/telemetry.rs src/tunnel.rs; do - cp "$repo/$file" "$file" - cmp "$repo/$file" "$file" -done -cargo test --locked --bin braid -- "${filters[@]}" -if [[ -n "${BRAID_TEST_PI_INSTALL:-}" ]]; then - export PI_OFFLINE=1 - for file in src/provider/pi.rs src/provider/factory.rs; do git -C "$repo" show "fe82de3:$file" > "$file"; done - if cargo test --locked --bin braid failed_home_binding_stops_the_installed_execution_before_returning -- --ignored >"$snapshot/construction-red.log" 2>&1; then - cat "$snapshot/construction-red.log" - exit 1 - fi - cat "$snapshot/construction-red.log" - grep -F 'failed factory construction omitted the owned-stop receipt' "$snapshot/construction-red.log" - for file in src/provider/pi.rs src/provider/factory.rs; do cp "$repo/$file" "$file"; cmp "$repo/$file" "$file"; done - cargo test --locked --bin braid failed_home_binding_stops_the_installed_execution_before_returning -- --ignored -fi diff --git a/.github/audit-controls/ci-ops.sh b/.github/audit-controls/ci-ops.sh deleted file mode 100755 index 649dc6bb..00000000 --- a/.github/audit-controls/ci-ops.sh +++ /dev/null @@ -1,41 +0,0 @@ -#!/bin/sh -# From the checkout root, in an isolated CI job. -set -eu -python3 - <<'PY' -from pathlib import Path -import re -import subprocess - -def control(file, before, after, suite, case, expected, pos): - path = Path(file) - original = path.read_bytes() - assert original.count(before.encode()) == 1, f"{file}: mutation anchor changed" - try: - path.write_bytes(original.replace(before.encode(), after.encode(), 1)) - cmd = ["cargo", "test", "--locked", "--test", suite, case, "--", "--exact"] - result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) - print(result.stdout, flush=True) - # The source line and the exact values distinguish the target assertion from setup errors. - line = next(i for i, s in enumerate(Path(f"tests/{suite}.rs").read_text().splitlines(), 1) - if pos in s) - assert result.returncode != 0 and f"test {case} ... FAILED" in result.stdout - assert f"tests/{suite}.rs:{line}:" in result.stdout and re.search(expected, result.stdout) - finally: - path.write_bytes(original) - -control("src/cli/status.rs", "config_schema: config.schema_version,", "config_schema: 3,", - "multi_repo", "instance_selectors_route_to_the_expected_config_and_doctor_names_cross_instance_conflicts", - r"left: Number\(3\)\s+right: 2", 'assert_eq!(status["config_schema"], 2)') - -branch = " if let Some(event_id) = pending {\n transaction.commit()?;\n return Ok(event_id);" -duplicate = """ if let Some(event_id) = pending { - let duplicate = Uuid::now_v7().to_string(); - transaction.execute("INSERT INTO wake_batches(batch_id,work_item_node_id,event_count,quiet_deadline,lifecycle,created_at,updated_at) - VALUES(?1,?2,1,?3,'consumed',?3,?3)", params![duplicate,work_item_node_id,now])?; - transaction.execute("INSERT INTO wake_batch_events(batch_id,event_id,ordinal) VALUES(?1,?2,0)", params![duplicate,event_id])?; - transaction.commit()?; - return Ok(event_id);""" -control("src/store/mod.rs", branch, duplicate, "assignment", - "assignment_reactivation_queues_one_wake_and_preserves_the_blocked_generation", - r"left: 2\s+right: 1", "assert_eq!(batches, 1)") -PY diff --git a/.github/audit-controls/ci-publication.sh b/.github/audit-controls/ci-publication.sh deleted file mode 100755 index a51ecf66..00000000 --- a/.github/audit-controls/ci-publication.sh +++ /dev/null @@ -1,68 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -root=$(git rev-parse --show-toplevel) -scratch=$(mktemp -d) -trap 'rm -rf "$scratch"' EXIT -cd "$root" -target_dir=${CARGO_TARGET_DIR:-target} -case "$target_dir" in - /*) export CARGO_TARGET_DIR="$target_dir" ;; - *) export CARGO_TARGET_DIR="$root/$target_dir" ;; -esac - -# Both changes affect only this snapshot. They touch different operations, so -# each target can run against the same compiled test binary. -git archive HEAD | tar -x -C "$scratch" -cd "$scratch" -python3 - <<'PY' -from pathlib import Path - -def replace(path, old, new): - source = Path(path).read_text() - if source.count(old) != 1: - raise RuntimeError(f"expected one control site in {path}") - Path(path).write_text(source.replace(old, new)) - -# Restore the pre-fix sample retention from bbc82f6^. -replace("src/github/rate_limit.rs", - "self.resource = reset.and(resource);\n self.used = used;", - "self.resource = resource;\n self.used = used.or(self.used);") -replace("src/writer/ensure.rs", - " let request_marker = format!", - ' if receipt.stage == "pull_request_ready" {\n' - ' return Err(GitHubError::GraphQl("mutation: lose persisted PR recovery".into()));\n' - ' }\n let request_marker = format!') -PY - -budget=github::rate_limit::window_tests::used_delta_requires_two_comparable_complete_header_samples -restart=writer::tests::initial_ensure_bootstrap_pr_association_and_restart_do_not_duplicate_mutations -run_case() { - cargo test --locked --bin braid "$1" -- --exact --color never -} - -red() { - local name=$1 - shift - local log="$scratch/$name.red" - if run_case "$name" >"$log" 2>&1; then - cat "$log" - echo "mutation survived: $name" >&2 - return 1 - fi - cat "$log" - grep -Fq "test $name ... FAILED" "$log" - for diagnostic do - grep -Fq -- "$diagnostic" "$log" - done -} -red "$budget" 'used=Some(25), reset=Some(600), resource=Some("core")' 'left: Some(3)' 'right: None' -red "$restart" 'mutation: lose persisted PR recovery' 'left: "rejected"' 'right: "applied"' - -for path in src/github/rate_limit.rs src/writer/ensure.rs; do - git -C "$root" show "HEAD:$path" > "$path" -done -for name in "$budget" "$restart"; do - run_case "$name" | tee "$scratch/$name.green" - grep -Fq "test $name ... ok" "$scratch/$name.green" -done diff --git a/.github/audit-controls/ci-state.sh b/.github/audit-controls/ci-state.sh deleted file mode 100644 index 06cd7f80..00000000 --- a/.github/audit-controls/ci-state.sh +++ /dev/null @@ -1,46 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail -file= -restore() { [[ -z "$file" ]] || git restore -- "$file"; } -trap restore EXIT -mutate() { - python3 - "$file" "$1" "$2" <<'PY' -from pathlib import Path -import sys -p=Path(sys.argv[1]) -s=p.read_text() -old,new=sys.argv[2:] -assert s.count(old)==1, (p,old,s.count(old)) -p.write_text(s.replace(old,new)) -PY -} -catch_control() { - local test_case="$1" reason="$2" out - out="$(mktemp)" - if cargo test --locked --bin braid "$test_case" -- --nocapture >"$out" 2>&1; then - cat "$out" - return 1 - fi - cat "$out" - grep -E 'test .*FAILED' "$out" >/dev/null - grep -F "$reason" "$out" >/dev/null - rm -f "$out" - restore - file= -} -file=src/group/worker.rs -mutate 'self.quiesce_session(id).await? || recorded_stop' 'self.quiesce_session(id).await? || (recorded_stop && false)' -catch_control persisted_idle_reset_uses_only_confirmed_native_stop_after_restart 'right: "applied"' -file=src/store/reconciliation.rs -mutate 'CASE WHEN ?3 THEN ?2 ELSE reconciled_at END' 'CASE WHEN ?3 THEN ?2 ELSE NULL END' -catch_control failed_traversal_backs_off_without_losing_the_last_success 'due_ids(&db, 1899)' -file=src/store/mod.rs -mutate ' if before.pending.is_empty() {' ' if before.pending.is_empty() { - create_backup(&open_read_only(database)?, backups, before.current_schema)?;' -catch_control v1_upgrade_preserves_the_association_and_comment_and_takes_only_one_backup 'braid.before-v' -for old_table in associations canonical_objects; do - file=src/store/mod.rs - mutate ' let after = plan(database)?;' " if before.current_schema == 1 { connection.execute_batch(\"DELETE FROM ${old_table}\")?; } - let after = plan(database)?;" - catch_control v1_upgrade_preserves_the_association_and_comment_and_takes_only_one_backup 'QueryReturnedNoRows' -done diff --git a/.github/audit-controls/ci-unassignment.sh b/.github/audit-controls/ci-unassignment.sh deleted file mode 100644 index 60c52ad0..00000000 --- a/.github/audit-controls/ci-unassignment.sh +++ /dev/null @@ -1,89 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail -base=5455350a2fe1d95e45b1d973e2c086208e1827e5 -source_dir=$PWD -export CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-$source_dir/target}" -snapshot="$(mktemp -d)" -file= -restore() { [[ -z "$file" ]] || git restore -- "$file"; } -trap 'restore; rm -rf "$snapshot"' EXIT -if ! git cat-file -e "$base^{commit}" 2>/dev/null; then git fetch --no-tags origin "$base"; fi -git archive "$base" | tar -x -C "$snapshot" -python3 - "$snapshot" <<'PY' -from pathlib import Path -import sys -p=Path('src/group/continuous_tests.rs') -new=p.read_text() -old=Path(sys.argv[1])/p -source=old.read_text() -prefix=new[:new.index('#[tokio::test]')] -# The old neutral interface requires one additional unused method. -anchor=' async fn send_user_msg(' -assert prefix.count(anchor)==1 -prefix=prefix.replace(anchor, ' async fn interrupt(&self) -> Result<(), SessionError> { Ok(()) }\n'+anchor) -start=new.index('#[tokio::test]\nasync fn worker_stops_a_running_unassigned_issue_only_after_its_quiet_window') -end=new.find('#[tokio::test]',start+1) -case=new[start:end if end!=-1 else len(new)] -old.write_text(prefix+source[source.index('#[tokio::test]'):]+'\n'+case) -PY -catch_control() { - local manifest="$1" case_name="$2" expected="$3" out - out="$(mktemp)" - if cargo test --locked --manifest-path "$manifest" --bin braid "$case_name" -- --nocapture >"$out" 2>&1; then cat "$out"; return 1; fi - cat "$out" - grep -E 'test .*FAILED' "$out" >/dev/null - grep -F "$expected" "$out" >/dev/null - rm -f "$out" -} -case_name=worker_stops_a_running_unassigned_issue_only_after_its_quiet_window -catch_control "$snapshot/Cargo.toml" "$case_name" 'settled unassignment must stop a running native turn' -file=src/store/mod.rs -python3 - <<'PY' -from pathlib import Path -p=Path('src/store/mod.rs') -s=p.read_text() -old="UPDATE turns SET lifecycle='unknown',ended_at=?2," -assert s.count(old)==1 -p.write_text(s.replace(old,"UPDATE turns SET lifecycle='interrupted',ended_at=?2,")) -PY -catch_control Cargo.toml "$case_name" 'closing the session alone cannot identify a turn outcome' -restore -file=src/group/worker.rs -python3 - <<'PY' -from pathlib import Path -p=Path('src/group/worker.rs') -s=p.read_text() -old='let terminal = active.as_deref_mut().and_then(RunningAgentTurn::terminal_after_close);' -assert s.count(old)==1 -p.write_text(s.replace(old,'let terminal = active.as_deref_mut().and_then(RunningAgentTurn::terminal_after_close).filter(|_| false);')) -PY -for test_case in builtin_turn_runs_without_writer_service_and_cannot_mint_after_reassignment worker_preserves_a_failed_turn_during_unassignment_while_the_platform_fence_is_offline; do - catch_control Cargo.toml "$test_case" 'observed provider terminal must be durable while the platform fence is offline' -done -restore -file= -mutate() { - python3 - "$file" "$1" "$2" <<'PY' -from pathlib import Path -import sys -p=Path(sys.argv[1]) -old,new=sys.argv[2:] -s=p.read_text() -assert s.count(old)==1, (p,old,s.count(old)) -p.write_text(s.replace(old,new)) -PY -} -reset_case=retired_reset_history_cannot_replace_an_execution_or_block_a_finite_run -file=src/store/mod.rs -mutate "AND a.lifecycle!='retired' AND w.kind=?1 AND ai.profile_id=?2" 'AND w.kind=?1 AND ai.profile_id=?2' -catch_control Cargo.toml "$reset_case" 'a retired generation cannot start replacement execution' -restore -file=src/store/run_progress.rs -mutate " AND a.lifecycle!='retired'" '' -catch_control Cargo.toml "$reset_case" 'retired reset history is no longer outstanding work' -restore -file=src/store/mod.rs -mutate ' || missing_terminals > 0' '' -catch_control Cargo.toml "$case_name" 'an unobserved turn terminal must publish the configured operational status' -restore -file= diff --git a/.github/audit-controls/platform-control.py b/.github/audit-controls/platform-control.py deleted file mode 100644 index cf3fa5e6..00000000 --- a/.github/audit-controls/platform-control.py +++ /dev/null @@ -1,74 +0,0 @@ -"""Exercise both regressions through just the public CLI/HTTP and a legacy SQLite fixture.""" -import hashlib, http.client, json, socket, sqlite3, subprocess, sys, tempfile, time -from pathlib import Path - -binary=Path(sys.argv[1]).resolve() -green="--green" in sys.argv[2:] -with tempfile.TemporaryDirectory(prefix="braid-platform-control-") as directory: - root=Path(directory) - source=root/"git" - def run(*args): return subprocess.check_output(args, text=True).strip() - run("git","init","-q","-b","main",str(source)) - for key,value in (("user.name","Contract"),("user.email","example@invalid"),("commit.gpgsign","false")): - run("git","-C",str(source),"config",key,value) - run("git","-C",str(source),"commit","--allow-empty","-qm","base") - run("git","-C",str(source),"checkout","-qb","feature") - (source/"body").write_text("candidate\n") - run("git","-C",str(source),"add","body") - run("git","-C",str(source),"commit","-qm","candidate") - with socket.socket() as probe: - probe.bind(("127.0.0.1",0)); port=probe.getsockname()[1] - config=root/"platform.toml" - run(binary,"platform","init","--config",config,"--source",source,"--default-branch","main","--name","demo","--listen",f"127.0.0.1:{port}") - store=root/"old.db" - old=sqlite3.connect(store) - for file in sorted(Path("migrations").glob("000[1-5]*.sql")): - content=file.read_bytes() - version,name=file.stem.split("_",1) - old.executescript(content.decode()) - old.execute("INSERT INTO schema_migrations VALUES(?,?,?,'then')",(int(version),name,hashlib.sha256(content).hexdigest())) - old.execute("INSERT INTO local_space VALUES(1,'demo',?)",(str(source.resolve()),)) - old.execute("INSERT INTO local_items(number,repository,kind,title,body,author,created_at,updated_at) VALUES(7,'demo','issue','Imported','','human','then','then')") - req='{"requestId":"historic","expectedRevision":1,"command":{"type":"assign","number":7,"profile":"old-profile"}}' - orig={"requestId":"historic","state":"rejected","result":None,"error":{"code":"rejected","message":"runtime supports profile issue-codex for issue objects"}} - old.execute("INSERT INTO control_receipts VALUES('objects','historic',?,?,'rejected',?,?,'then','then')",(hashlib.sha256(req.encode()).hexdigest(),req,json.dumps(orig),orig["error"]["message"])) - old.commit();old.close() - run(binary,"platform","import","--config",config,"--from",store) - def call(path,body=None): - c=http.client.HTTPConnection("127.0.0.1",port,timeout=5) - c.request("GET" if body is None else "POST",path,None if body is None else json.dumps(body),{"Host":f"127.0.0.1:{port}","Content-Type":"application/json"}) - r=c.getresponse(); answer=(r.status,json.load(r));c.close();return answer - def command(id,command,revision=None,actor="human"):return call("/api/control/commands",dict(requestId=id,actor=actor,expectedRevision=revision,command=command)) - proc=subprocess.Popen([binary,"platform","serve","--config",config],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL) - try: - for i in range(100): - try: - assert call("/api/platform/repository")[0]==200 - break - except ConnectionRefusedError: time.sleep(.02) - assert call("/api/control/receipts/historic")== (200,orig) - replay=command("historic",dict(type="assign",number=7,actor="old-profile"),1) - print("historical assign with previous profile spelling:",replay,flush=True) - assert replay[0]==409 and ((replay[1]==orig) if green else ("requestId was already used" in replay[1]["error"]["message"] and replay[1].get("state") is None)) - issue=command("new-issue",dict(type="createIssue",title="Task",body=""))[1]["result"]["number"] - pr=command("new-pr",dict(type="createPR",title="Work",body="",head="feature",base="main",issue=issue,issueRevision=1))[1]["result"]["number"] - db=sqlite3.connect(root/"platform.sqlite3") - db.execute("""CREATE TRIGGER lose_receipt BEFORE UPDATE OF response_json ON control_receipts WHEN NEW.request_id='original' AND NEW.state!='prepared' BEGIN SELECT RAISE(ABORT,'injected receipt storage failure'); END""");db.commit() - response=command("original",dict(type="merge",number=pr),1,"first") - assert response[0]==422 and "injected receipt storage failure" in response[1]["error"]["message"], response - before=call(f"/api/control/items/{pr}")[1] - assert before["merge"]["lifecycle"]=="prepared" - assert run("git","-C",str(source),"rev-parse","refs/heads/main")==before["merge"]["merge_commit"] - db.execute("DROP TRIGGER lose_receipt");db.commit();db.close() - followup=command("new-command",dict(type="merge",number=pr),1,"second") - events=call("/api/platform/events")[1]["events"] - actors=[r["event"]["actor_login"] for r in events if r["event"]["detail"]=="merged"] - print("different request ID after original CAS:", followup, "merged actors:", actors,flush=True) - if green: - assert followup[0]==409 and "another merge request" in followup[1]["error"]["message"] and actors==[] - assert command("original",dict(type="merge",number=pr),1,"first")[0]==200 - assert [r["event"]["actor_login"] for r in call("/api/platform/events")[1]["events"] if r["event"]["detail"]=="merged"]==["first"] - else: - assert followup[0]==200 and actors==["second"],(followup,actors) - finally: - proc.terminate();proc.wait(5) diff --git a/.github/workflows/audit-control-runs.yml b/.github/workflows/audit-control-runs.yml deleted file mode 100644 index 63407b77..00000000 --- a/.github/workflows/audit-control-runs.yml +++ /dev/null @@ -1,31 +0,0 @@ -name: Audit preservation controls -on: - pull_request: - paths: ['.github/audit-controls/**', '.github/workflows/audit-control-runs.yml'] -permissions: - contents: read -jobs: - control: - if: github.head_ref == 'feat/pr149-test-audit' - strategy: - fail-fast: false - matrix: - owner: [unassignment] - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - with: - ref: ${{ github.event.pull_request.head.sha }} - fetch-depth: 0 - persist-credentials: false - - uses: actions/setup-node@v4 - with: - node-version: 24.15.0 - - if: matrix.owner == 'native' - run: | - node native/pi/install.mjs "$RUNNER_TEMP/pi" --plugins background - echo "BRAID_TEST_PI_INSTALL=$RUNNER_TEMP/pi" >> "$GITHUB_ENV" - - env: - OWNER: ${{ matrix.owner }} - CARGO_PROFILE_DEV_DEBUG: 0 - run: bash ".github/audit-controls/ci-$OWNER.sh" From 05fb1e5504e1e7e7b3c6fcfc84b32e7559d3034a Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sat, 28 Nov 2026 22:13:25 +0800 Subject: [PATCH 29/43] =?UTF-8?q?fix(lifecycle):=20=E9=87=8D=E5=90=AF?= =?UTF-8?q?=E6=97=B6=E5=85=88=E7=BB=93=E7=AE=97=E5=B7=B2=E6=9C=89=E5=81=9C?= =?UTF-8?q?=E6=9C=BA=E8=AF=81=E6=98=8E=E7=9A=84=E6=92=A4=E9=94=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 保留原 assignment 和逻辑 turn 身份,阻止已停止的旧会话被恢复或误标 blocked - 分别在有无原生终态的持久断点重开 actor 与 worker,验证状态发布与后继代 --- docs/20-product-tdd/lifecycle.md | 3 +- src/group/continuous_tests.rs | 179 ++++++++++++++++++++++--------- src/group/provider.rs | 5 +- src/group/worker.rs | 19 ++-- src/runtime/builtin.rs | 80 +++++++------- src/store/mod.rs | 4 + src/store/unassignment.rs | 13 ++- 7 files changed, 203 insertions(+), 100 deletions(-) diff --git a/docs/20-product-tdd/lifecycle.md b/docs/20-product-tdd/lifecycle.md index 40f63042..db747454 100644 --- a/docs/20-product-tdd/lifecycle.md +++ b/docs/20-product-tdd/lifecycle.md @@ -124,7 +124,8 @@ classified as Agent-origin. Group 在关闭期间继续接收原有 turn 的终态。平台撤权暂时失败时,已经收到的终态与 错误仍须持久化。原生停止和平台撤权均已确认后,Group 才将该代记为 `retired`; 此时仍缺 provider 终态的 turn 记为 `unknown`,并按该 Profile 的配置发布执行状态。 - 该代未完成的 Context reset 保留在历史中,不再创建会话或阻止有限 run 完成。重新指派创建新一代及新会话。 + 若原生停止已保存而撤销尚未完成,重启的 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 diff --git a/src/group/continuous_tests.rs b/src/group/continuous_tests.rs index 27c87075..7e10211d 100644 --- a/src/group/continuous_tests.rs +++ b/src/group/continuous_tests.rs @@ -15,6 +15,7 @@ use tokio::sync::broadcast; struct Captured { memory: Mutex>, inputs: Mutex>, + resumed: Mutex>, steer_error: Mutex>, close_error: Mutex>, close_attempts: Mutex>, @@ -61,7 +62,7 @@ impl SessionFactory for Factory { _profile: Profile, _instructions: String, ) -> Result { - assert_eq!(id, "provider", "only the existing session is restored"); + self.0.resumed.lock().unwrap().push(id.to_owned()); Ok(CreatedSession { id: id.into(), session: Arc::new(Session { @@ -749,22 +750,31 @@ async fn stopping_native_execution_does_not_wait_for_execution_fence() { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn builtin_turn_runs_without_writer_service_and_cannot_mint_after_reassignment() { - builtin_running_unassignment(crate::agent_session::TurnOutcome::Completed, None).await; + builtin_running_unassignment(Some((crate::agent_session::TurnOutcome::Completed, None)), false) + .await; } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn worker_preserves_a_failed_turn_during_unassignment_while_the_platform_fence_is_offline() { builtin_running_unassignment( - crate::agent_session::TurnOutcome::Failed, - Some("provider failed while stopping".into()), + Some(( + crate::agent_session::TurnOutcome::Failed, + Some("provider failed while stopping".into()), + )), + true, ) .await; } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn restarted_worker_retires_a_stopped_unassignment_without_a_provider_terminal() { + builtin_running_unassignment(None, true).await; +} + #[allow(clippy::too_many_lines)] async fn builtin_running_unassignment( - outcome: crate::agent_session::TurnOutcome, - reason: Option, + terminal: Option<(crate::agent_session::TurnOutcome, Option)>, + restart: bool, ) { use crate::{ builtin::BuiltinClient, @@ -831,21 +841,12 @@ async fn builtin_running_unassignment( repository: platform.repository.clone(), endpoint: format!("http://{address}").parse().unwrap(), }); - let store = Arc::new( - StoreActor::start(config.runtime.database().into(), config.runtime.backups().into()) - .unwrap(), - ); - let lease = store.acquire_runtime_lease("runtime".into(), "fixture".into(), 60).unwrap(); - let client = BuiltinClient::connect(&config, Arc::clone(&store)) - .await - .unwrap() - .with_runtime(lease) - .unwrap(); - let spec = GroupSpec::new(GroupKind::Issue, &config, &store, "test-space").unwrap(); + let (mut store, mut client) = open_worker_runtime(&config, "fixture").await; + let actor = "issue-codex"; let mut platform = PlatformObjects::open(&platform.database, &platform.repository).unwrap(); let issue = platform.create_child_issue("Writer independence", "Read first", "human", None).unwrap(); - platform.assign(issue.number, Some(&spec.profile.id), "human").unwrap(); + platform.assign(issue.number, Some(actor), "human").unwrap(); let policy = SchedulerPolicy { quiet_seconds: 0, event_threshold: 1 }; let mut cursor = 0; for pending in platform.events(cursor, 100).unwrap() { @@ -855,16 +856,19 @@ async fn builtin_running_unassignment( let captured = Arc::new(Captured::default()); let (shutdown, stop) = tokio::sync::watch::channel(false); let (reports, _receiver) = tokio::sync::mpsc::channel(8); - let actor = spec.profile.id.clone(); - let worker = tokio::spawn(agent_group_worker_backend( - Arc::clone(&store), - Arc::new(CollaborationBackend::Builtin(Arc::clone(&client))), - config, - spec, - Arc::new(Factory(Arc::clone(&captured))), - reports, - stop, - )); + let spawn = |store: &Arc, client: &Arc| { + let spec = GroupSpec::new(GroupKind::Issue, &config, store, "test-space").unwrap(); + tokio::spawn(agent_group_worker_backend( + Arc::clone(store), + Arc::new(CollaborationBackend::Builtin(Arc::clone(client))), + config.clone(), + spec, + Arc::new(Factory(Arc::clone(&captured))), + reports.clone(), + stop.clone(), + )) + }; + let mut worker = spawn(&store, &client); let limit = std::time::Duration::from_secs(5); tokio::time::timeout(limit, async { while !store @@ -887,15 +891,21 @@ async fn builtin_running_unassignment( store.advance_scheduler().unwrap(); let (session_id, turn_id) = tokio::time::timeout(limit, async { + use rusqlite::OptionalExtension as _; loop { - if let Some(group) = store - .runtime_status() - .unwrap() - .agent_groups - .into_iter() - .find(|group| group.turn_lifecycle.as_deref() == Some("running")) - { - break (group.provider_session_id.unwrap(), group.active_turn_id.unwrap()); + let running = f + .db() + .query_row( + "SELECT ps.provider_session_id,t.turn_id FROM turns t + JOIN provider_sessions ps ON ps.session_id=t.session_id + WHERE t.lifecycle='running' AND t.provider_turn_id='after-revision'", + [], + |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)), + ) + .optional() + .unwrap(); + if let Some(running) = running { + break running; } tokio::time::sleep(std::time::Duration::from_millis(20)).await; } @@ -904,18 +914,18 @@ async fn builtin_running_unassignment( .expect("writer service must not gate a real turn"); assert_eq!(captured.inputs.lock().unwrap().len(), 1); let writer = - BuiltinWriterTurn { session_id, turn_id, item_number: issue.number, actor: actor.clone() }; + BuiltinWriterTurn { session_id, turn_id, item_number: issue.number, actor: actor.into() }; let offline_error = client.writer_grant(writer.clone()).await.unwrap_err(); - assert!(offline_error.to_string().contains("503")); + assert!(offline_error.to_string().contains("503"), "{offline_error:#}"); // The old turn never minted a grant. Name equality must not revive it // after an unassign/reassign and before those events reach the Harness. - platform.assign(issue.number, Some(&actor), "human").unwrap(); + platform.assign(issue.number, Some(actor), "human").unwrap(); offline.store(false, Ordering::Relaxed); let error = client.writer_grant(writer.clone()).await.unwrap_err(); assert!(error.to_string().contains("writer authority changed"), "{error:#}"); offline.store(true, Ordering::Relaxed); - *captured.close_terminal.lock().unwrap() = Some((outcome, reason.clone())); + captured.close_terminal.lock().unwrap().clone_from(&terminal); fence_offline.store(true, Ordering::Relaxed); for pending in platform.events(cursor, 100).unwrap() { store.ingest_builtin_event(pending.event, policy, pending.event_id).unwrap(); @@ -931,20 +941,60 @@ async fn builtin_running_unassignment( ) .unwrap() }; - tokio::time::timeout(limit, async { - while turn_state().0 != outcome.lifecycle() { - tokio::time::sleep(std::time::Duration::from_millis(20)).await; - } - }) - .await - .expect("observed provider terminal must be durable while the platform fence is offline"); - assert_eq!(turn_state().1, reason); + let (outcome, reason) = if let Some((outcome, reason)) = terminal { + tokio::time::timeout(limit, async { + while turn_state().0 != outcome.lifecycle() { + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + } + }) + .await + .expect("observed provider terminal must be durable while the platform fence is offline"); + assert_eq!(turn_state().1, reason); + (outcome, reason) + } else { + tokio::time::timeout(limit, async { + while !f.db().query_row( + "SELECT execution_stopped_at IS NOT NULL FROM provider_sessions WHERE provider_session_id=?1", + [&writer.session_id], |row| row.get::<_, bool>(0), + ).unwrap() { + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + } + }).await.expect("native stop must reach SQLite before a successful platform fence"); + assert_eq!(turn_state().0, "running"); + ( + crate::agent_session::TurnOutcome::Unknown, + Some("unassignment did not observe the active turn terminal".to_owned()), + ) + }; assert_eq!(*captured.close_attempts.lock().unwrap(), ["fresh-provider"]); assert_eq!(store.runtime_status().unwrap().agent_groups[0].assignment_lifecycle, "active"); - fence_offline.store(false, Ordering::Relaxed); + if restart { + worker.abort(); + assert!(worker.await.unwrap_err().is_cancelled()); + drop(client); + drop(store); + // A dead owner no longer renews its lease. Advance just that deadline. + f.db().execute("UPDATE owner_leases SET expires_at='2000-01-01T00:00:00Z' WHERE owner_id='fixture'", []).unwrap(); + (store, client) = open_worker_runtime(&config, "next-runtime").await; + fence_offline.store(false, Ordering::Relaxed); + client.fence_all_executions().await.unwrap(); + worker = spawn(&store, &client); + } else { + fence_offline.store(false, Ordering::Relaxed); + } let groups = tokio::time::timeout(limit, async { loop { let groups = store.runtime_status().unwrap().agent_groups; + assert!( + groups + .iter() + .all(|g| g.assignment_generation != 1 || g.assignment_lifecycle != "blocked"), + "a stopped unassignment must retire instead of becoming a blocked lost turn" + ); + assert!( + captured.resumed.lock().unwrap().is_empty(), + "a stopped unassignment must never resume its old native session" + ); if groups.iter().any(|group| { group.assignment_generation == 2 && group.assignment_lifecycle == "active" }) { @@ -957,8 +1007,20 @@ async fn builtin_running_unassignment( .expect("retire the old generation and materialize its immutable reassignment"); let retired = groups.iter().find(|group| group.assignment_generation == 1).unwrap(); let current = groups.iter().find(|group| group.assignment_generation == 2).unwrap(); - assert_eq!(retired.assignment_lifecycle, "retired"); + assert_eq!( + retired.assignment_lifecycle, "retired", + "the stopped old generation must retire after recovery" + ); + assert!( + captured.resumed.lock().unwrap().is_empty(), + "a stopped unassignment must never resume its old native session" + ); assert_eq!(current.provider_session_id.as_deref(), Some("fresh-provider-2")); + if let Some(reason) = &reason { + let body: String = f.db().query_row("SELECT body FROM operational_status_facts WHERE assignment_id=(SELECT assignment_id FROM assignments WHERE generation=1)", [], |row| row.get(0)).expect("the failed or unknown old turn must have a configured Operational Status"); + assert!(body.contains(outcome.lifecycle())); + assert!(body.contains(reason)); + } assert_eq!(turn_state(), (outcome.lifecycle().to_owned(), reason)); assert_eq!(*captured.close_attempts.lock().unwrap(), ["fresh-provider"]); assert_eq!(captured.memory.lock().unwrap().len(), 2); @@ -970,6 +1032,23 @@ async fn builtin_running_unassignment( http.abort(); } +async fn open_worker_runtime( + config: &crate::config::Config, + owner: &str, +) -> (Arc, Arc) { + let store = Arc::new( + StoreActor::start(config.runtime.database().into(), config.runtime.backups().into()) + .unwrap(), + ); + let lease = store.acquire_runtime_lease("runtime".into(), owner.into(), 60).unwrap(); + let client = crate::builtin::BuiltinClient::connect(config, Arc::clone(&store)) + .await + .unwrap() + .with_runtime(lease) + .unwrap(); + (store, client) +} + #[tokio::test] async fn worker_stops_a_running_unassigned_issue_only_after_its_quiet_window() { use sha2::{Digest as _, Sha256}; diff --git a/src/group/provider.rs b/src/group/provider.rs index b4301e5f..6622f845 100644 --- a/src/group/provider.rs +++ b/src/group/provider.rs @@ -45,7 +45,8 @@ fn public_error_summary(config: &Config, profile: &Profile, reason: &str) -> Str pub(crate) fn operational_status_turn_error( config: &Config, profile: &Profile, - claim: &TurnClaim, + turn_id: &str, + provider_session_id: &str, lifecycle: &str, reason: &str, ) -> String { @@ -55,7 +56,7 @@ pub(crate) fn operational_status_turn_error( **执行状态:{lifecycle}**\n\n\ Braid turn:`{}`\n\n原生会话:`{}`\n\n{quoted}\n\n\ 此状态描述执行结果,不代表工作项验收结论。", - profile.id, claim.turn_id, claim.provider_session_id, + profile.id, turn_id, provider_session_id, ) } diff --git a/src/group/worker.rs b/src/group/worker.rs index 37b14577..4e3dfaf8 100644 --- a/src/group/worker.rs +++ b/src/group/worker.rs @@ -200,7 +200,7 @@ impl GroupDriver<'_> { pub(super) async fn settle_unassignment( &self, change: &crate::store::Unassignment, - mut active: Option<&mut RunningAgentTurn>, + active: Option<&mut RunningAgentTurn>, ) -> Result<()> { let mut stop = Ok(()); for (session, stopped) in &change.sessions { @@ -208,10 +208,10 @@ impl GroupDriver<'_> { stop = Err(error); } } - let terminal = active.as_deref_mut().and_then(RunningAgentTurn::terminal_after_close); + let terminal = active.and_then(RunningAgentTurn::terminal_after_close); if (stop.is_ok() || terminal.is_some()) && self.store.settle_unassignment(change, terminal.clone(), stop.is_ok())? - && let Some(active) = active + && let Some((turn, session)) = &change.running_turn { use crate::agent_session::TurnOutcome; let (outcome, reason) = terminal.as_ref().map_or( @@ -227,7 +227,7 @@ impl GroupDriver<'_> { }, ); if matches!(outcome, TurnOutcome::Failed | TurnOutcome::Unknown) { - self.enqueue_turn_error(&active.claim, outcome.lifecycle(), reason); + self.enqueue_turn_error(turn, session, outcome.lifecycle(), reason); } } stop.map_err(Into::into) @@ -260,24 +260,25 @@ impl GroupDriver<'_> { if let Err(error) = self.store.record_turn_error(claim.turn_id.clone(), reason.to_owned()) { tracing::error!(%error, turn = %claim.turn_id, "cannot retain complete turn error"); } - self.enqueue_turn_error(claim, lifecycle, reason); + self.enqueue_turn_error(&claim.turn_id, &claim.provider_session_id, lifecycle, reason); } - fn enqueue_turn_error(&self, claim: &TurnClaim, lifecycle: &str, reason: &str) { + fn enqueue_turn_error(&self, turn_id: &str, session: &str, lifecycle: &str, reason: &str) { if self.spec.profile.status_surfaces.is_empty() { return; } if let Err(error) = self.store.enqueue_operational_status( - claim.turn_id.clone(), + turn_id.into(), super::provider::operational_status_turn_error( self.config, &self.spec.profile, - claim, + turn_id, + session, lifecycle, reason, ), ) { - tracing::error!(%error, turn = %claim.turn_id, "cannot publish turn error status"); + tracing::error!(%error, turn = %turn_id, "cannot publish turn error status"); } } diff --git a/src/runtime/builtin.rs b/src/runtime/builtin.rs index 915e5103..64ee1846 100644 --- a/src/runtime/builtin.rs +++ b/src/runtime/builtin.rs @@ -798,21 +798,21 @@ mod tests { use super::*; use axum::{Json, Router, routing::get}; - #[tokio::test] - async fn managed_ingests_while_old_execution_fence_is_unavailable() { - let fixture = crate::writer::tests::Fixture::new(false); - let store = Arc::new( - StoreActor::start( - fixture.config.runtime.database().into(), - fixture.config.runtime.backups().into(), - ) - .unwrap(), - ); - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - let address = listener.local_addr().unwrap(); - let resumed = Arc::new(tokio::sync::Notify::new()); - let requested_after_close = Arc::clone(&resumed); - let app = Router::new() + fn closed_issue_with_unavailable_fence(resumed: Arc) -> Router { + let event = serde_json::json!({ + "sequence": 1, + "event": { + "delivery_guid": "local:1", "event_name": "local", + "repository": "test-space", "repository_node_id": "local:test-space", + "work_item_node_id": "local:test-space:issue:1", "work_item_kind": "issue", + "work_item_number": 1, "work_item_state": "closed", + "kind": "lifecycle", "detail": "closed", + "cross_surface_invalidation": false, "origin": "human", + "reference": "Issue closed", "mention_candidate": false, + "known": true, "raw_payload": [] + } + }); + Router::new() .route( "/api/platform/repository", get(|| async { @@ -825,31 +825,37 @@ mod tests { .route( "/api/platform/events", get(move |axum::extract::Query(query): axum::extract::Query>| { - let resumed = Arc::clone(&resumed); - async move { - if query["after"] == 1 { + let events = if query["after"] == 1 { resumed.notify_one(); - return Json(serde_json::json!({"events": [], "nextAfter": 1, "lastSequence": 1})); - } - Json(serde_json::json!({"events": [{ - "sequence": 1, "event": { - "delivery_guid": "local:1", "event_name": "local", - "repository": "test-space", "repository_node_id": "local:test-space", - "work_item_node_id": "local:test-space:issue:1", "work_item_kind": "issue", - "work_item_number": 1, "work_item_state": "closed", - "kind": "lifecycle", "detail": "closed", - "cross_surface_invalidation": false, "origin": "human", - "reference": "Issue closed", "mention_candidate": false, - "known": true, "raw_payload": [] - } - }], "nextAfter": 1, "lastSequence": 1})) + vec![] + } else { + vec![event.clone()] + }; + async move { + Json(serde_json::json!({"events": events, "nextAfter": 1, "lastSequence": 1})) } }), ) .route( "/api/platform/executions/fence", axum::routing::post(|| async { axum::http::StatusCode::SERVICE_UNAVAILABLE }), - ); + ) + } + + #[tokio::test] + async fn managed_ingests_while_old_execution_fence_is_unavailable() { + let fixture = crate::writer::tests::Fixture::new(false); + let store = Arc::new( + StoreActor::start( + fixture.config.runtime.database().into(), + fixture.config.runtime.backups().into(), + ) + .unwrap(), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let requested_after_close = Arc::new(tokio::sync::Notify::new()); + let app = closed_issue_with_unavailable_fence(Arc::clone(&requested_after_close)); let http = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); let mut config = fixture.config.clone(); config.github = None; @@ -903,10 +909,10 @@ mod tests { .try_into() .unwrap(); assert_eq!(turns, 0); - if halt.send(true).is_err() { - panic!("runtime exited before the requested stop: {:#?}", runtime.await); - } - let error = runtime.await.unwrap().unwrap_err(); + let requested_stop = halt.send(true); + let result = runtime.await.unwrap(); + assert!(requested_stop.is_ok(), "runtime exited before the requested stop: {result:#?}"); + let error = result.unwrap_err(); assert!(error.to_string().contains("execution fence remains unconfirmed"), "{error:#}"); http.abort(); } diff --git a/src/store/mod.rs b/src/store/mod.rs index d37e2c3b..e455cb21 100644 --- a/src/store/mod.rs +++ b/src/store/mod.rs @@ -3547,6 +3547,10 @@ fn provider_resume_candidates( LEFT JOIN turns t ON t.session_id=ps.session_id AND t.lifecycle IN ('starting','running','unknown') WHERE a.lifecycle IN ('active','finalizing') AND ai.profile_id=?1 + AND NOT (ps.execution_stopped_at IS NOT NULL + AND (w.kind='issue' OR EXISTS(SELECT 1 FROM builtin_upstream)) + AND EXISTS(SELECT 1 FROM events e WHERE e.work_item_node_id=w.node_id + AND e.kind='unassign' AND e.lifecycle='pending')) ORDER BY a.assigned_at,a.assignment_id,ps.started_at", )?; let rows = statement.query_map(params![profile_id, work_item_kind], |row| { diff --git a/src/store/unassignment.rs b/src/store/unassignment.rs index 5ef16e97..2418b028 100644 --- a/src/store/unassignment.rs +++ b/src/store/unassignment.rs @@ -22,6 +22,7 @@ pub(crate) struct Unassignment { pub repository: String, pub number: u64, pub sessions: Vec<(String, bool)>, + pub running_turn: Option<(String, String)>, } /// An active worker only handles the revocation of its own work item. @@ -77,5 +78,15 @@ pub(super) fn due( let sessions = statement .query_map([&assignment_id], |r| Ok((r.get(0)?, r.get(1)?)))? .collect::, _>>()?; - Ok(Some(Unassignment { event_id, assignment_id, repository, number, sessions })) + let running_turn = connection + .query_row( + "SELECT t.turn_id,ps.provider_session_id FROM turns t + JOIN provider_sessions ps ON ps.session_id=t.session_id + JOIN agent_instances ai ON ai.agent_id=ps.agent_id + WHERE ai.assignment_id=?1 AND t.lifecycle IN ('starting','running')", + [&assignment_id], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .optional()?; + Ok(Some(Unassignment { event_id, assignment_id, repository, number, sessions, running_turn })) } From 111185707075822a9de89edfb0a6a172420dac2f Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sat, 28 Nov 2026 22:13:25 +0800 Subject: [PATCH 30/43] =?UTF-8?q?chore(audit):=20=E5=9C=A8=E7=9C=9F?= =?UTF-8?q?=E5=AE=9E=E9=87=8D=E5=90=AF=E6=96=AD=E7=82=B9=E5=A4=8D=E9=AA=8C?= =?UTF-8?q?=E6=92=A4=E9=94=80=E4=B8=8E=E7=BB=88=E6=80=81=E8=AF=81=E6=8D=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/audit-controls/ci-unassignment.sh | 96 +++++++++++++++++++++++ .github/workflows/audit-control-runs.yml | 31 ++++++++ 2 files changed, 127 insertions(+) create mode 100644 .github/audit-controls/ci-unassignment.sh create mode 100644 .github/workflows/audit-control-runs.yml diff --git a/.github/audit-controls/ci-unassignment.sh b/.github/audit-controls/ci-unassignment.sh new file mode 100644 index 00000000..3129dc36 --- /dev/null +++ b/.github/audit-controls/ci-unassignment.sh @@ -0,0 +1,96 @@ +#!/usr/bin/env bash +set -euo pipefail +base=5455350a2fe1d95e45b1d973e2c086208e1827e5 +source_dir=$PWD +export CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-$source_dir/target}" +snapshot="$(mktemp -d)" +file= +restore() { [[ -z "$file" ]] || git restore -- "$file"; } +trap 'restore; rm -rf "$snapshot"' EXIT +if ! git cat-file -e "$base^{commit}" 2>/dev/null; then git fetch --no-tags origin "$base"; fi +git archive "$base" | tar -x -C "$snapshot" +python3 - "$snapshot" <<'PY' +from pathlib import Path +import sys +p=Path('src/group/continuous_tests.rs') +new=p.read_text() +old=Path(sys.argv[1])/p +source=old.read_text() +prefix=new[:new.index('#[tokio::test]')] +# The old neutral interface requires one additional unused method. +anchor=' async fn send_user_msg(' +assert prefix.count(anchor)==1 +prefix=prefix.replace(anchor, ' async fn interrupt(&self) -> Result<(), SessionError> { Ok(()) }\n'+anchor) +start=new.index('#[tokio::test]\nasync fn worker_stops_a_running_unassigned_issue_only_after_its_quiet_window') +end=new.find('#[tokio::test]',start+1) +case=new[start:end if end!=-1 else len(new)] +old.write_text(prefix+source[source.index('#[tokio::test]'):]+'\n'+case) +PY +catch_control() { + local manifest="$1" case_name="$2" expected="$3" out + out="$(mktemp)" + if cargo test --locked --manifest-path "$manifest" --bin braid "$case_name" -- --nocapture >"$out" 2>&1; then cat "$out"; return 1; fi + cat "$out" + grep -E 'test .*FAILED' "$out" >/dev/null + grep -F "$expected" "$out" >/dev/null + rm -f "$out" +} +case_name=worker_stops_a_running_unassigned_issue_only_after_its_quiet_window +catch_control "$snapshot/Cargo.toml" "$case_name" 'settled unassignment must stop a running native turn' +file=src/store/mod.rs +python3 - <<'PY' +from pathlib import Path +p=Path('src/store/mod.rs') +s=p.read_text() +old="UPDATE turns SET lifecycle='unknown',ended_at=?2," +assert s.count(old)==1 +p.write_text(s.replace(old,"UPDATE turns SET lifecycle='interrupted',ended_at=?2,")) +PY +catch_control Cargo.toml "$case_name" 'closing the session alone cannot identify a turn outcome' +restore +file=src/group/worker.rs +python3 - <<'PY' +from pathlib import Path +p=Path('src/group/worker.rs') +s=p.read_text() +old='let terminal = active.and_then(RunningAgentTurn::terminal_after_close);' +assert s.count(old)==1 +p.write_text(s.replace(old,'let terminal = active.and_then(RunningAgentTurn::terminal_after_close).filter(|_| false);')) +PY +for test_case in builtin_turn_runs_without_writer_service_and_cannot_mint_after_reassignment worker_preserves_a_failed_turn_during_unassignment_while_the_platform_fence_is_offline; do + catch_control Cargo.toml "$test_case" 'observed provider terminal must be durable while the platform fence is offline' +done +restore +file= +mutate() { + python3 - "$file" "$1" "$2" <<'PY' +from pathlib import Path +import sys +p=Path(sys.argv[1]) +old,new=sys.argv[2:] +s=p.read_text() +assert s.count(old)==1, (p,old,s.count(old)) +p.write_text(s.replace(old,new)) +PY +} +reset_case=retired_reset_history_cannot_replace_an_execution_or_block_a_finite_run +file=src/store/mod.rs +mutate "AND a.lifecycle!='retired' AND w.kind=?1 AND ai.profile_id=?2" 'AND w.kind=?1 AND ai.profile_id=?2' +catch_control Cargo.toml "$reset_case" 'a retired generation cannot start replacement execution' +restore +file=src/store/run_progress.rs +mutate " AND a.lifecycle!='retired'" '' +catch_control Cargo.toml "$reset_case" 'retired reset history is no longer outstanding work' +restore +file=src/store/mod.rs +mutate ' || missing_terminals > 0' '' +catch_control Cargo.toml "$case_name" 'an unobserved turn terminal must publish the configured operational status' +restore +file= +file=src/store/mod.rs +mutate 'AND NOT (ps.execution_stopped_at IS NOT NULL' 'AND NOT (0 AND ps.execution_stopped_at IS NOT NULL' +catch_control Cargo.toml restarted_worker_retires_a_stopped_unassignment_without_a_provider_terminal 'a stopped unassignment must retire instead of becoming a blocked lost turn' +catch_control Cargo.toml worker_preserves_a_failed_turn_during_unassignment_while_the_platform_fence_is_offline 'a stopped unassignment must never resume its old native session' +restore +file= +cargo test --locked --bin braid -- worker_stops_a_running_unassigned_issue_only_after_its_quiet_window builtin_turn_runs_without_writer_service_and_cannot_mint_after_reassignment worker_preserves_a_failed_turn_during_unassignment_while_the_platform_fence_is_offline restarted_worker_retires_a_stopped_unassignment_without_a_provider_terminal retired_reset_history_cannot_replace_an_execution_or_block_a_finite_run managed_ingests_while_old_execution_fence_is_unavailable diff --git a/.github/workflows/audit-control-runs.yml b/.github/workflows/audit-control-runs.yml new file mode 100644 index 00000000..63407b77 --- /dev/null +++ b/.github/workflows/audit-control-runs.yml @@ -0,0 +1,31 @@ +name: Audit preservation controls +on: + pull_request: + paths: ['.github/audit-controls/**', '.github/workflows/audit-control-runs.yml'] +permissions: + contents: read +jobs: + control: + if: github.head_ref == 'feat/pr149-test-audit' + strategy: + fail-fast: false + matrix: + owner: [unassignment] + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha }} + fetch-depth: 0 + persist-credentials: false + - uses: actions/setup-node@v4 + with: + node-version: 24.15.0 + - if: matrix.owner == 'native' + run: | + node native/pi/install.mjs "$RUNNER_TEMP/pi" --plugins background + echo "BRAID_TEST_PI_INSTALL=$RUNNER_TEMP/pi" >> "$GITHUB_ENV" + - env: + OWNER: ${{ matrix.owner }} + CARGO_PROFILE_DEV_DEBUG: 0 + run: bash ".github/audit-controls/ci-$OWNER.sh" From 605aa1d0422742bda0fd0a23557b91780d189e41 Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sat, 28 Nov 2026 22:13:44 +0800 Subject: [PATCH 31/43] =?UTF-8?q?chore(ci):=20=E5=AE=8C=E6=88=90=E6=81=A2?= =?UTF-8?q?=E5=A4=8D=E5=AF=B9=E7=85=A7=E5=90=8E=E4=BF=9D=E7=95=99=E5=B8=B8?= =?UTF-8?q?=E8=A7=84=E9=AA=8C=E6=94=B6=E8=B7=AF=E7=94=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/audit-controls/ci-unassignment.sh | 96 ----------------------- .github/workflows/audit-control-runs.yml | 31 -------- 2 files changed, 127 deletions(-) delete mode 100644 .github/audit-controls/ci-unassignment.sh delete mode 100644 .github/workflows/audit-control-runs.yml diff --git a/.github/audit-controls/ci-unassignment.sh b/.github/audit-controls/ci-unassignment.sh deleted file mode 100644 index 3129dc36..00000000 --- a/.github/audit-controls/ci-unassignment.sh +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail -base=5455350a2fe1d95e45b1d973e2c086208e1827e5 -source_dir=$PWD -export CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-$source_dir/target}" -snapshot="$(mktemp -d)" -file= -restore() { [[ -z "$file" ]] || git restore -- "$file"; } -trap 'restore; rm -rf "$snapshot"' EXIT -if ! git cat-file -e "$base^{commit}" 2>/dev/null; then git fetch --no-tags origin "$base"; fi -git archive "$base" | tar -x -C "$snapshot" -python3 - "$snapshot" <<'PY' -from pathlib import Path -import sys -p=Path('src/group/continuous_tests.rs') -new=p.read_text() -old=Path(sys.argv[1])/p -source=old.read_text() -prefix=new[:new.index('#[tokio::test]')] -# The old neutral interface requires one additional unused method. -anchor=' async fn send_user_msg(' -assert prefix.count(anchor)==1 -prefix=prefix.replace(anchor, ' async fn interrupt(&self) -> Result<(), SessionError> { Ok(()) }\n'+anchor) -start=new.index('#[tokio::test]\nasync fn worker_stops_a_running_unassigned_issue_only_after_its_quiet_window') -end=new.find('#[tokio::test]',start+1) -case=new[start:end if end!=-1 else len(new)] -old.write_text(prefix+source[source.index('#[tokio::test]'):]+'\n'+case) -PY -catch_control() { - local manifest="$1" case_name="$2" expected="$3" out - out="$(mktemp)" - if cargo test --locked --manifest-path "$manifest" --bin braid "$case_name" -- --nocapture >"$out" 2>&1; then cat "$out"; return 1; fi - cat "$out" - grep -E 'test .*FAILED' "$out" >/dev/null - grep -F "$expected" "$out" >/dev/null - rm -f "$out" -} -case_name=worker_stops_a_running_unassigned_issue_only_after_its_quiet_window -catch_control "$snapshot/Cargo.toml" "$case_name" 'settled unassignment must stop a running native turn' -file=src/store/mod.rs -python3 - <<'PY' -from pathlib import Path -p=Path('src/store/mod.rs') -s=p.read_text() -old="UPDATE turns SET lifecycle='unknown',ended_at=?2," -assert s.count(old)==1 -p.write_text(s.replace(old,"UPDATE turns SET lifecycle='interrupted',ended_at=?2,")) -PY -catch_control Cargo.toml "$case_name" 'closing the session alone cannot identify a turn outcome' -restore -file=src/group/worker.rs -python3 - <<'PY' -from pathlib import Path -p=Path('src/group/worker.rs') -s=p.read_text() -old='let terminal = active.and_then(RunningAgentTurn::terminal_after_close);' -assert s.count(old)==1 -p.write_text(s.replace(old,'let terminal = active.and_then(RunningAgentTurn::terminal_after_close).filter(|_| false);')) -PY -for test_case in builtin_turn_runs_without_writer_service_and_cannot_mint_after_reassignment worker_preserves_a_failed_turn_during_unassignment_while_the_platform_fence_is_offline; do - catch_control Cargo.toml "$test_case" 'observed provider terminal must be durable while the platform fence is offline' -done -restore -file= -mutate() { - python3 - "$file" "$1" "$2" <<'PY' -from pathlib import Path -import sys -p=Path(sys.argv[1]) -old,new=sys.argv[2:] -s=p.read_text() -assert s.count(old)==1, (p,old,s.count(old)) -p.write_text(s.replace(old,new)) -PY -} -reset_case=retired_reset_history_cannot_replace_an_execution_or_block_a_finite_run -file=src/store/mod.rs -mutate "AND a.lifecycle!='retired' AND w.kind=?1 AND ai.profile_id=?2" 'AND w.kind=?1 AND ai.profile_id=?2' -catch_control Cargo.toml "$reset_case" 'a retired generation cannot start replacement execution' -restore -file=src/store/run_progress.rs -mutate " AND a.lifecycle!='retired'" '' -catch_control Cargo.toml "$reset_case" 'retired reset history is no longer outstanding work' -restore -file=src/store/mod.rs -mutate ' || missing_terminals > 0' '' -catch_control Cargo.toml "$case_name" 'an unobserved turn terminal must publish the configured operational status' -restore -file= -file=src/store/mod.rs -mutate 'AND NOT (ps.execution_stopped_at IS NOT NULL' 'AND NOT (0 AND ps.execution_stopped_at IS NOT NULL' -catch_control Cargo.toml restarted_worker_retires_a_stopped_unassignment_without_a_provider_terminal 'a stopped unassignment must retire instead of becoming a blocked lost turn' -catch_control Cargo.toml worker_preserves_a_failed_turn_during_unassignment_while_the_platform_fence_is_offline 'a stopped unassignment must never resume its old native session' -restore -file= -cargo test --locked --bin braid -- worker_stops_a_running_unassigned_issue_only_after_its_quiet_window builtin_turn_runs_without_writer_service_and_cannot_mint_after_reassignment worker_preserves_a_failed_turn_during_unassignment_while_the_platform_fence_is_offline restarted_worker_retires_a_stopped_unassignment_without_a_provider_terminal retired_reset_history_cannot_replace_an_execution_or_block_a_finite_run managed_ingests_while_old_execution_fence_is_unavailable diff --git a/.github/workflows/audit-control-runs.yml b/.github/workflows/audit-control-runs.yml deleted file mode 100644 index 63407b77..00000000 --- a/.github/workflows/audit-control-runs.yml +++ /dev/null @@ -1,31 +0,0 @@ -name: Audit preservation controls -on: - pull_request: - paths: ['.github/audit-controls/**', '.github/workflows/audit-control-runs.yml'] -permissions: - contents: read -jobs: - control: - if: github.head_ref == 'feat/pr149-test-audit' - strategy: - fail-fast: false - matrix: - owner: [unassignment] - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - with: - ref: ${{ github.event.pull_request.head.sha }} - fetch-depth: 0 - persist-credentials: false - - uses: actions/setup-node@v4 - with: - node-version: 24.15.0 - - if: matrix.owner == 'native' - run: | - node native/pi/install.mjs "$RUNNER_TEMP/pi" --plugins background - echo "BRAID_TEST_PI_INSTALL=$RUNNER_TEMP/pi" >> "$GITHUB_ENV" - - env: - OWNER: ${{ matrix.owner }} - CARGO_PROFILE_DEV_DEBUG: 0 - run: bash ".github/audit-controls/ci-$OWNER.sh" From 29bf1d4a9bdae59ff097abaaecbf50cea79c4ddd Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sat, 28 Nov 2026 22:20:32 +0800 Subject: [PATCH 32/43] =?UTF-8?q?chore(tests):=20=E8=AE=A9=E6=9C=AA?= =?UTF-8?q?=E7=9F=A5=E7=BB=88=E6=80=81=E5=9B=9E=E5=BD=92=E6=8C=87=E6=98=8E?= =?UTF-8?q?=E6=8C=81=E4=B9=85=E7=8A=B6=E6=80=81=E5=B7=AE=E5=BC=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 同时报告缺行和遗留状态行,断言运维正文中的确切生命周期和原因。 --- src/group/continuous_tests.rs | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/src/group/continuous_tests.rs b/src/group/continuous_tests.rs index 7e10211d..a98e82fa 100644 --- a/src/group/continuous_tests.rs +++ b/src/group/continuous_tests.rs @@ -8,6 +8,7 @@ use crate::{ store::{EventKind, IngressEvent, SchedulerPolicy, StoreActor}, writer::tests::{Fixture, issue_context_server}, }; +use rusqlite::OptionalExtension as _; use std::sync::{Arc, Mutex}; use tokio::sync::broadcast; @@ -891,7 +892,6 @@ async fn builtin_running_unassignment( store.advance_scheduler().unwrap(); let (session_id, turn_id) = tokio::time::timeout(limit, async { - use rusqlite::OptionalExtension as _; loop { let running = f .db() @@ -1143,15 +1143,19 @@ async fn worker_stops_a_running_unassigned_issue_only_after_its_quiet_window() { assert_eq!(captured.inputs.lock().unwrap().len(), 1); shutdown.send(true).unwrap(); worker.await.unwrap().unwrap(); - let status: String = f + let status = f .db() .query_row( "SELECT body FROM operational_status_facts WHERE assignment_id='assignment'", [], - |row| row.get(0), + |row| row.get::<_, String>(0), ) - .expect("an unobserved turn terminal must publish the configured operational status"); - assert!(status.contains("unknown")); - assert!(status.contains("unassignment did not observe the active turn terminal")); + .optional() + .unwrap(); + assert!( + status.as_deref().is_some_and(|body| body.contains("执行状态:unknown") + && body.contains("unassignment did not observe the active turn terminal")), + "an unobserved turn terminal must publish the configured operational status: {status:?}" + ); http.abort(); } From d64644f041b108bce60f131c1df6d64a28aba6bf Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sat, 28 Nov 2026 22:20:32 +0800 Subject: [PATCH 33/43] =?UTF-8?q?chore(audit):=20=E5=8D=95=E7=8B=AC?= =?UTF-8?q?=E9=AA=8C=E8=AF=81=E6=92=A4=E9=94=80=E7=9A=84=E7=8A=B6=E6=80=81?= =?UTF-8?q?=E4=B8=8E=E5=86=B7=E5=90=AF=E5=8A=A8=E6=96=AD=E7=82=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/audit-controls/ci-unassignment.sh | 35 +++++++++++++++++++++++ .github/workflows/audit-control-runs.yml | 31 ++++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 .github/audit-controls/ci-unassignment.sh create mode 100644 .github/workflows/audit-control-runs.yml diff --git a/.github/audit-controls/ci-unassignment.sh b/.github/audit-controls/ci-unassignment.sh new file mode 100644 index 00000000..55dbbd73 --- /dev/null +++ b/.github/audit-controls/ci-unassignment.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +set -euo pipefail +file=src/store/mod.rs +restore() { git restore -- "$file"; } +trap restore EXIT +catch_control() { + local manifest="$1" case_name="$2" expected="$3" out + out="$(mktemp)" + if cargo test --locked --manifest-path "$manifest" --bin braid "$case_name" -- --nocapture >"$out" 2>&1; then cat "$out"; return 1; fi + cat "$out" + grep -E 'test .*FAILED' "$out" >/dev/null + grep -F "$expected" "$out" >/dev/null + rm -f "$out" +} +case_name=worker_stops_a_running_unassigned_issue_only_after_its_quiet_window +mutate() { + python3 - "$file" "$1" "$2" <<'PY' +from pathlib import Path +import sys +p=Path(sys.argv[1]) +old,new=sys.argv[2:] +s=p.read_text() +assert s.count(old)==1, (p,old,s.count(old)) +p.write_text(s.replace(old,new)) +PY +} +mutate ' || missing_terminals > 0' '' +catch_control Cargo.toml "$case_name" 'an unobserved turn terminal must publish the configured operational status' +restore +mutate 'AND NOT (ps.execution_stopped_at IS NOT NULL' 'AND NOT (0 AND ps.execution_stopped_at IS NOT NULL' +catch_control Cargo.toml restarted_worker_retires_a_stopped_unassignment_without_a_provider_terminal 'a stopped unassignment must retire instead of becoming a blocked lost turn' +catch_control Cargo.toml worker_preserves_a_failed_turn_during_unassignment_while_the_platform_fence_is_offline 'a stopped unassignment must never resume its old native session' +restore +file= +cargo test --locked --bin braid -- worker_stops_a_running_unassigned_issue_only_after_its_quiet_window builtin_turn_runs_without_writer_service_and_cannot_mint_after_reassignment worker_preserves_a_failed_turn_during_unassignment_while_the_platform_fence_is_offline restarted_worker_retires_a_stopped_unassignment_without_a_provider_terminal retired_reset_history_cannot_replace_an_execution_or_block_a_finite_run managed_ingests_while_old_execution_fence_is_unavailable diff --git a/.github/workflows/audit-control-runs.yml b/.github/workflows/audit-control-runs.yml new file mode 100644 index 00000000..63407b77 --- /dev/null +++ b/.github/workflows/audit-control-runs.yml @@ -0,0 +1,31 @@ +name: Audit preservation controls +on: + pull_request: + paths: ['.github/audit-controls/**', '.github/workflows/audit-control-runs.yml'] +permissions: + contents: read +jobs: + control: + if: github.head_ref == 'feat/pr149-test-audit' + strategy: + fail-fast: false + matrix: + owner: [unassignment] + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha }} + fetch-depth: 0 + persist-credentials: false + - uses: actions/setup-node@v4 + with: + node-version: 24.15.0 + - if: matrix.owner == 'native' + run: | + node native/pi/install.mjs "$RUNNER_TEMP/pi" --plugins background + echo "BRAID_TEST_PI_INSTALL=$RUNNER_TEMP/pi" >> "$GITHUB_ENV" + - env: + OWNER: ${{ matrix.owner }} + CARGO_PROFILE_DEV_DEBUG: 0 + run: bash ".github/audit-controls/ci-$OWNER.sh" From 5e28b42b146bc1cc2fd640925e19ecb55e17e2a1 Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sat, 28 Nov 2026 22:22:04 +0800 Subject: [PATCH 34/43] =?UTF-8?q?chore(audit):=20=E6=A0=A1=E5=87=86?= =?UTF-8?q?=E4=B8=89=E9=A1=B9=E7=8B=AC=E7=AB=8B=E8=BF=90=E7=BB=B4=E5=9B=9E?= =?UTF-8?q?=E5=BD=92=E4=B8=8E=E8=BF=98=E5=8E=9F=E6=A3=80=E6=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/audit-controls/ci-ops-extra.sh | 47 +++++++++++++++++++++++ .github/audit-controls/ci-unassignment.sh | 1 - .github/workflows/audit-control-runs.yml | 2 +- 3 files changed, 48 insertions(+), 2 deletions(-) create mode 100644 .github/audit-controls/ci-ops-extra.sh diff --git a/.github/audit-controls/ci-ops-extra.sh b/.github/audit-controls/ci-ops-extra.sh new file mode 100644 index 00000000..8453e8c9 --- /dev/null +++ b/.github/audit-controls/ci-ops-extra.sh @@ -0,0 +1,47 @@ +#!/bin/sh +# Run in an isolated checkout root. Exact panic line + output identify each guard. +set -eu +python3 - <<'PY' +from pathlib import Path +import subprocess + +cases = [ + ("src/setup.rs", " user_home.save_registry(®istry)?;", "", + ["--test", "headless_setup"], "no_browser_setup_can_be_completed_from_callback_url", + "tests/headless_setup.rs", 'let summary: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();', + -1, ['unknown instance "demo"', "no instances registered"]), + ("src/worktree.rs", " exclude_private_notes(request, &source)?;", "", + ["--bin", "braid"], "worktree::tests::existing_target_must_share_the_requested_source_repository", + "src/worktree/tests.rs", 'assert_eq!(String::from_utf8(status.stdout).unwrap()', 0, + [r'left: "?? .braid/private-note\n?? change.txt\n"', r'right: "?? change.txt\n"']), + ("src/health.rs", "if error.is_some() || current.last_error == prior_error {", "if error.is_some() {", + ["--bin", "braid"], "health::tests::provider_recovery_clears_its_own_diagnostic_and_preserves_another_workers_error", + "src/health/tests.rs", "assert_eq!(recovered.last_error.as_deref(), other_error);", 0, + ['left: Some("provider failed")', 'right: None']), +] + +def run(target, case): + return subprocess.run(["cargo", "test", "--locked", *target, case, "--", "--exact"], + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) + +for file, original, mutation, target, case, test_source, anchor, offset, evidence in cases: + path = Path(file) + saved = path.read_bytes() + assert saved.count(original.encode()) == 1, f"{file}: mutation anchor changed" + lines = [i for i, line in enumerate(Path(test_source).read_text().splitlines(), 1) if anchor in line] + assert len(lines) == 1, f"{test_source}: assertion anchor changed" + try: + path.write_bytes(saved.replace(original.encode(), mutation.encode(), 1)) + result = run(target, case) + print(result.stdout, flush=True) + assert result.returncode != 0 and f"test {case} ... FAILED" in result.stdout + for detail in [f"{test_source}:{lines[0]+offset}:", *evidence]: + assert detail in result.stdout, f"{case}: missing expected failure {detail!r}" + finally: + path.write_bytes(saved) + +for _, _, _, target, case, *_ in cases: + result = run(target, case) + print(result.stdout, flush=True) + assert result.returncode == 0 and f"test {case} ... ok" in result.stdout +PY diff --git a/.github/audit-controls/ci-unassignment.sh b/.github/audit-controls/ci-unassignment.sh index 55dbbd73..36d1b408 100644 --- a/.github/audit-controls/ci-unassignment.sh +++ b/.github/audit-controls/ci-unassignment.sh @@ -31,5 +31,4 @@ mutate 'AND NOT (ps.execution_stopped_at IS NOT NULL' 'AND NOT (0 AND ps.executi catch_control Cargo.toml restarted_worker_retires_a_stopped_unassignment_without_a_provider_terminal 'a stopped unassignment must retire instead of becoming a blocked lost turn' catch_control Cargo.toml worker_preserves_a_failed_turn_during_unassignment_while_the_platform_fence_is_offline 'a stopped unassignment must never resume its old native session' restore -file= cargo test --locked --bin braid -- worker_stops_a_running_unassigned_issue_only_after_its_quiet_window builtin_turn_runs_without_writer_service_and_cannot_mint_after_reassignment worker_preserves_a_failed_turn_during_unassignment_while_the_platform_fence_is_offline restarted_worker_retires_a_stopped_unassignment_without_a_provider_terminal retired_reset_history_cannot_replace_an_execution_or_block_a_finite_run managed_ingests_while_old_execution_fence_is_unavailable diff --git a/.github/workflows/audit-control-runs.yml b/.github/workflows/audit-control-runs.yml index 63407b77..2bbf0b75 100644 --- a/.github/workflows/audit-control-runs.yml +++ b/.github/workflows/audit-control-runs.yml @@ -10,7 +10,7 @@ jobs: strategy: fail-fast: false matrix: - owner: [unassignment] + owner: [unassignment, ops-extra] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 From 2de3f3bd3cf6293bd4aa0b70a633e8deea2828e8 Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sat, 28 Nov 2026 22:22:23 +0800 Subject: [PATCH 35/43] =?UTF-8?q?chore(ci):=20=E5=B0=86=E4=B8=B4=E6=97=B6?= =?UTF-8?q?=E5=8F=98=E5=BC=82=E5=AF=B9=E7=85=A7=E7=95=99=E5=9C=A8=E5=AE=A1?= =?UTF-8?q?=E8=AE=A1=E8=AE=B0=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/audit-controls/ci-ops-extra.sh | 47 ----------------------- .github/audit-controls/ci-unassignment.sh | 34 ---------------- .github/workflows/audit-control-runs.yml | 31 --------------- 3 files changed, 112 deletions(-) delete mode 100644 .github/audit-controls/ci-ops-extra.sh delete mode 100644 .github/audit-controls/ci-unassignment.sh delete mode 100644 .github/workflows/audit-control-runs.yml diff --git a/.github/audit-controls/ci-ops-extra.sh b/.github/audit-controls/ci-ops-extra.sh deleted file mode 100644 index 8453e8c9..00000000 --- a/.github/audit-controls/ci-ops-extra.sh +++ /dev/null @@ -1,47 +0,0 @@ -#!/bin/sh -# Run in an isolated checkout root. Exact panic line + output identify each guard. -set -eu -python3 - <<'PY' -from pathlib import Path -import subprocess - -cases = [ - ("src/setup.rs", " user_home.save_registry(®istry)?;", "", - ["--test", "headless_setup"], "no_browser_setup_can_be_completed_from_callback_url", - "tests/headless_setup.rs", 'let summary: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();', - -1, ['unknown instance "demo"', "no instances registered"]), - ("src/worktree.rs", " exclude_private_notes(request, &source)?;", "", - ["--bin", "braid"], "worktree::tests::existing_target_must_share_the_requested_source_repository", - "src/worktree/tests.rs", 'assert_eq!(String::from_utf8(status.stdout).unwrap()', 0, - [r'left: "?? .braid/private-note\n?? change.txt\n"', r'right: "?? change.txt\n"']), - ("src/health.rs", "if error.is_some() || current.last_error == prior_error {", "if error.is_some() {", - ["--bin", "braid"], "health::tests::provider_recovery_clears_its_own_diagnostic_and_preserves_another_workers_error", - "src/health/tests.rs", "assert_eq!(recovered.last_error.as_deref(), other_error);", 0, - ['left: Some("provider failed")', 'right: None']), -] - -def run(target, case): - return subprocess.run(["cargo", "test", "--locked", *target, case, "--", "--exact"], - stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) - -for file, original, mutation, target, case, test_source, anchor, offset, evidence in cases: - path = Path(file) - saved = path.read_bytes() - assert saved.count(original.encode()) == 1, f"{file}: mutation anchor changed" - lines = [i for i, line in enumerate(Path(test_source).read_text().splitlines(), 1) if anchor in line] - assert len(lines) == 1, f"{test_source}: assertion anchor changed" - try: - path.write_bytes(saved.replace(original.encode(), mutation.encode(), 1)) - result = run(target, case) - print(result.stdout, flush=True) - assert result.returncode != 0 and f"test {case} ... FAILED" in result.stdout - for detail in [f"{test_source}:{lines[0]+offset}:", *evidence]: - assert detail in result.stdout, f"{case}: missing expected failure {detail!r}" - finally: - path.write_bytes(saved) - -for _, _, _, target, case, *_ in cases: - result = run(target, case) - print(result.stdout, flush=True) - assert result.returncode == 0 and f"test {case} ... ok" in result.stdout -PY diff --git a/.github/audit-controls/ci-unassignment.sh b/.github/audit-controls/ci-unassignment.sh deleted file mode 100644 index 36d1b408..00000000 --- a/.github/audit-controls/ci-unassignment.sh +++ /dev/null @@ -1,34 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail -file=src/store/mod.rs -restore() { git restore -- "$file"; } -trap restore EXIT -catch_control() { - local manifest="$1" case_name="$2" expected="$3" out - out="$(mktemp)" - if cargo test --locked --manifest-path "$manifest" --bin braid "$case_name" -- --nocapture >"$out" 2>&1; then cat "$out"; return 1; fi - cat "$out" - grep -E 'test .*FAILED' "$out" >/dev/null - grep -F "$expected" "$out" >/dev/null - rm -f "$out" -} -case_name=worker_stops_a_running_unassigned_issue_only_after_its_quiet_window -mutate() { - python3 - "$file" "$1" "$2" <<'PY' -from pathlib import Path -import sys -p=Path(sys.argv[1]) -old,new=sys.argv[2:] -s=p.read_text() -assert s.count(old)==1, (p,old,s.count(old)) -p.write_text(s.replace(old,new)) -PY -} -mutate ' || missing_terminals > 0' '' -catch_control Cargo.toml "$case_name" 'an unobserved turn terminal must publish the configured operational status' -restore -mutate 'AND NOT (ps.execution_stopped_at IS NOT NULL' 'AND NOT (0 AND ps.execution_stopped_at IS NOT NULL' -catch_control Cargo.toml restarted_worker_retires_a_stopped_unassignment_without_a_provider_terminal 'a stopped unassignment must retire instead of becoming a blocked lost turn' -catch_control Cargo.toml worker_preserves_a_failed_turn_during_unassignment_while_the_platform_fence_is_offline 'a stopped unassignment must never resume its old native session' -restore -cargo test --locked --bin braid -- worker_stops_a_running_unassigned_issue_only_after_its_quiet_window builtin_turn_runs_without_writer_service_and_cannot_mint_after_reassignment worker_preserves_a_failed_turn_during_unassignment_while_the_platform_fence_is_offline restarted_worker_retires_a_stopped_unassignment_without_a_provider_terminal retired_reset_history_cannot_replace_an_execution_or_block_a_finite_run managed_ingests_while_old_execution_fence_is_unavailable diff --git a/.github/workflows/audit-control-runs.yml b/.github/workflows/audit-control-runs.yml deleted file mode 100644 index 2bbf0b75..00000000 --- a/.github/workflows/audit-control-runs.yml +++ /dev/null @@ -1,31 +0,0 @@ -name: Audit preservation controls -on: - pull_request: - paths: ['.github/audit-controls/**', '.github/workflows/audit-control-runs.yml'] -permissions: - contents: read -jobs: - control: - if: github.head_ref == 'feat/pr149-test-audit' - strategy: - fail-fast: false - matrix: - owner: [unassignment, ops-extra] - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - with: - ref: ${{ github.event.pull_request.head.sha }} - fetch-depth: 0 - persist-credentials: false - - uses: actions/setup-node@v4 - with: - node-version: 24.15.0 - - if: matrix.owner == 'native' - run: | - node native/pi/install.mjs "$RUNNER_TEMP/pi" --plugins background - echo "BRAID_TEST_PI_INSTALL=$RUNNER_TEMP/pi" >> "$GITHUB_ENV" - - env: - OWNER: ${{ matrix.owner }} - CARGO_PROFILE_DEV_DEBUG: 0 - run: bash ".github/audit-controls/ci-$OWNER.sh" From 352c90b117b4f9cf20a41982411be383f7123b48 Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sat, 28 Nov 2026 22:26:19 +0800 Subject: [PATCH 36/43] =?UTF-8?q?ref(tests):=20=E5=A4=8D=E7=94=A8=E4=B8=A4?= =?UTF-8?q?=E7=A7=8D=E6=92=A4=E9=94=80=E5=9C=BA=E6=99=AF=E7=9A=84=E4=BA=8B?= =?UTF-8?q?=E4=BB=B6=E5=A4=B9=E5=85=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 运行中和已有重置记录的撤销共用相同输入字段,同时保留各自的投递标识和结果断言。 --- src/group/continuous_tests.rs | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/src/group/continuous_tests.rs b/src/group/continuous_tests.rs index a98e82fa..f49b32cf 100644 --- a/src/group/continuous_tests.rs +++ b/src/group/continuous_tests.rs @@ -147,6 +147,18 @@ fn revision() -> IngressEvent { } } +fn unassignment(delivery_guid: &str) -> IngressEvent { + IngressEvent { + delivery_guid: delivery_guid.into(), + identity: crate::store::ChangeIdentity::Occurrence, + kind: EventKind::Unassign, + action: Some("unassigned".into()), + requires_attention: false, + cross_surface_invalidation: false, + ..revision() + } +} + #[tokio::test] async fn soft_pressure_reset_replaces_memory_and_delivers_input_with_publication_unavailable() { let f = Fixture::new(true); @@ -531,13 +543,7 @@ async fn retired_reset_history_cannot_replace_an_execution_or_block_a_finite_run let before = f.store.execution_progress().unwrap(); assert!(before.unresolved_reset); assert_eq!(before.blocked_reset.as_deref(), blocked.then_some(reset.reset_id.as_str())); - let mut revoke = revision(); - revoke.delivery_guid = "assignment-removed-during-reset".into(); - revoke.identity = crate::store::ChangeIdentity::Occurrence; - revoke.kind = EventKind::Unassign; - revoke.action = Some("unassigned".into()); - revoke.requires_attention = false; - revoke.cross_surface_invalidation = false; + let revoke = unassignment("assignment-removed-during-reset"); let event = f.store.ingest_event(revoke, policy).unwrap().event_id.unwrap(); driver.settle_idle_unassignment(event).await.unwrap(); let after = f.store.runtime_status().unwrap(); @@ -1093,13 +1099,7 @@ async fn worker_stops_a_running_unassigned_issue_only_after_its_quiet_window() { tokio::time::sleep(Duration::from_millis(20)).await; } }).await.expect("the provider must start a real turn before unassignment"); - let mut unassign = revision(); - unassign.delivery_guid = "assignment-removed".into(); - unassign.identity = crate::store::ChangeIdentity::Occurrence; - unassign.kind = EventKind::Unassign; - unassign.action = Some("unassigned".into()); - unassign.cross_surface_invalidation = false; - unassign.requires_attention = false; + let unassign = unassignment("assignment-removed"); let event = store.ingest_event(unassign, policy).unwrap().event_id.unwrap(); // A second provider input acknowledges a worker tick inside the window. From 27c31ac74dde66719d6d60240fedefba754f8597 Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sun, 29 Nov 2026 00:17:45 +0800 Subject: [PATCH 37/43] =?UTF-8?q?fix(github):=20=E8=AF=86=E5=88=AB?= =?UTF-8?q?=E6=B3=A8=E9=87=8A=E9=97=AD=E5=90=88=E5=90=8E=E5=90=8C=E4=B8=80?= =?UTF-8?q?=E8=A1=8C=E7=9A=84=E5=8F=AF=E8=A7=81=E6=8F=90=E5=8F=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 复用 Markdown 注释过滤,继续排除代码和链接地址。 --- src/webhook.rs | 4 +++- src/webhook_tests.rs | 5 ++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/src/webhook.rs b/src/webhook.rs index aea05dd3..4a6d3d7d 100644 --- a/src/webhook.rs +++ b/src/webhook.rs @@ -424,8 +424,10 @@ fn object_digest(node_id: &str, version: &str, body: Option<&str>) -> String { pub fn has_visible_mention(markdown: &str, handle: &str) -> bool { let mention = if handle.starts_with('@') { handle.to_owned() } else { format!("@{handle}") }; + // A CommonMark comment block can include visible prose after its closing delimiter. + let visible = markdown.contains("", false), - ("\n\n@braid", true), + (" @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}"); From 38ff5f469832559c11700b8e6a76af4091bf8fe7 Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sun, 29 Nov 2026 00:17:45 +0800 Subject: [PATCH 38/43] =?UTF-8?q?ref(tests):=20=E5=88=A0=E9=99=A4=E9=87=8D?= =?UTF-8?q?=E5=A4=8D=E9=AA=8C=E8=AF=81=E5=92=8C=E6=B5=8B=E8=AF=95=E4=B8=93?= =?UTF-8?q?=E7=94=A8=E7=94=9F=E4=BA=A7=E5=88=86=E6=94=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 由实际调用方验证发布意图、调度期限、撤销和原生停机。 - 缩减 SDK、CLI、Console 和迁移的重复运行,保留各自的独立断言。 --- .github/workflows/ci.yml | 4 +- docs/10-prd/acceptance.md | 14 +- native/pi/README.md | 4 +- .../pi/acceptance/installed-runtime.test.mjs | 18 - native/pi/tests/tool-environment.test.mjs | 1 - src/config.rs | 2 - src/context/reading_tests.rs | 34 +- src/doctor.rs | 21 +- src/github/budget_tests.rs | 78 +-- src/github/rate_limit.rs | 28 +- src/group/continuous_tests.rs | 144 ++---- src/health/tests.rs | 135 ++---- src/platform/tests.rs | 117 ++--- src/producer/ingress_tests.rs | 19 +- src/profile_materials/tests.rs | 25 +- src/provider/pi_runtime_tests.rs | 11 +- src/provider/session_tests.rs | 57 +-- src/runtime/builtin.rs | 17 +- src/store/gh_writes.rs | 71 +-- src/store/gh_writes/tests.rs | 76 ++- src/store/handoff_inputs.rs | 5 +- src/store/implementation_delivery.rs | 11 +- src/store/mod.rs | 10 +- .../operational_status_migration_tests.rs | 13 +- src/store/reconciliation.rs | 39 +- src/store/scheduler_tests.rs | 72 +-- src/store/schema_tests.rs | 4 +- src/telemetry.rs | 3 +- src/telemetry/tests.rs | 239 ++++----- src/tunnel/tests.rs | 36 +- src/webhook_tests.rs | 4 - src/writer/prepare.rs | 12 +- src/writer/tests.rs | 175 +++---- src/writer/tests/body_edit.rs | 459 ++++++++---------- src/writer/tests/continuous_collaboration.rs | 27 +- src/writer/tests/handoff.rs | 69 +-- src/writer/tests/observation_recovery.rs | 23 +- src/writer/tests/publication_contract.rs | 28 +- src/writer/tests/semantic_contract.rs | 2 +- src/writer/tests/turn_start.rs | 169 +++---- tests/console.rs | 51 +- tests/durable_publication.rs | 80 ++- tests/multi_repo.rs | 7 - tests/provider_config.rs | 68 +-- 44 files changed, 814 insertions(+), 1668 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 80cafe68..26051586 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -59,4 +59,6 @@ jobs: 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 + 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/docs/10-prd/acceptance.md b/docs/10-prd/acceptance.md index 08be87cd..a1c8909c 100644 --- a/docs/10-prd/acceptance.md +++ b/docs/10-prd/acceptance.md @@ -57,9 +57,10 @@ node --test native/pi/tests/*.test.mjs ``` `agent-build` 是本机编译串行入口;CI 直接运行相同 Cargo 命令。局部迭代可加 -`--bin braid <模块名>::` 或 `--test <文件名>` 筛选。Linux CI 另运行 -`cargo test --locked --bin braid --features opentelemetry-otlp/internal-logs telemetry::tests`, -实际启用 SDK 内部错误诊断,验证 Collector 返回的敏感正文不会进入普通日志。 +`--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` 只供父测试 用独立子进程调用,父测试负责检查退出状态与所有输出;不能单独计作通过。 @@ -74,9 +75,10 @@ BRAID_BINARY=/absolute/path/to/braid CHROME_BIN=/absolute/path/to/chromium \ ``` Pi 安装或 Rust 适配器变更时,Linux CI 复用本轮编译并按 lock 安装 background -插件,启动安装包中的 Node/Pi,以真实 RPC 读取状态、运行工具、关闭执行并离线 -检查回执。随后故意让真实会话的材料绑定写入失败,核对 Rust 工厂返回前已为该执行留下停止证据。安装步骤需要访问发行站点和 npm,模型未参与。其它插件组合和含模型 -会话各自单独记录。修改打包入口和包内材料的 PR 以及实际发行均在两个目标平台运行 +插件。Node 验证安装包中的真实 RPC、工具执行和 EOF 退出。Rust 工厂用例使材料绑定 +在原生启动后失败,并读取工厂返回前留在该执行目录的停止回执。安装步骤需要访问发行 +站点和 npm。其它插件组合和含模型会话各自单独记录。修改打包入口和包内材料的 PR +以及实际发行均在两个目标平台运行 `scripts/verify-package.sh DIST RELEASE_TAG RUST_TARGET`;它从校验和指定的 归档中运行 binary,核对版本、示例配置及迁移后重开的数据库。 diff --git a/native/pi/README.md b/native/pi/README.md index 872de058..fb7d12ad 100644 --- a/native/pi/README.md +++ b/native/pi/README.md @@ -42,14 +42,14 @@ subagents、background、Context7 和 MCPorter 的局部补丁仅随相应插件 对全新安装仅选择 `background` 后,可直接验证交付的 Node、Pi SDK 与扩展、工具环境和停止回执。 下面的验收使用临时 HOME、离线模型描述和本地 Bash,不需要模型账号。它也会检查新建 -session 文件、结束 RPC 输入后进程正常退出,以及随后从执行目录取得完整停止回执。 +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 cargo test --locked --bin braid failed_home_binding_stops_the_installed_execution_before_returning -- --ignored +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 使用字符串列表解析, diff --git a/native/pi/acceptance/installed-runtime.test.mjs b/native/pi/acceptance/installed-runtime.test.mjs index 1c16d671..0665da34 100644 --- a/native/pi/acceptance/installed-runtime.test.mjs +++ b/native/pi/acceptance/installed-runtime.test.mjs @@ -60,15 +60,7 @@ test('installed background-only Pi opens a fresh session, serves tools and close assert.equal(state.sessionFile, session); assert.equal(state.model.provider, 'fixture'); assert.equal(state.model.id, 'offline'); - assert.equal(state.managed_state.execution_id, id); assert.equal(state.managed_state.status, 'quiescent'); - assert.equal(state.braid_native_runtime.schema_version, 1); - assert.equal(state.braid_native_runtime.pi_version, '1.1.0'); - for (const required of ['retry_intent', 'settle_extensions', 'owned_inference', 'managed_execution', 'owned_stop']) { - assert.ok(state.braid_native_runtime.capabilities.includes(required), `missing RPC capability ${required}`); - } - assert.equal(state.braid_native_runtime.execution_id, id); - assert.deepEqual(state.braid_native_runtime.extension_errors, []); assert.deepEqual(state.braid_native_runtime.extensions, [ path.join(install, 'node_modules/pi-background-bash/extensions/background-bash.ts'), ]); @@ -88,16 +80,6 @@ test('installed background-only Pi opens a fresh session, serves tools and close assert.equal(signal, null, stderr); assert.equal(code, 0, stderr); } - // Read the final receipt produced from persisted registrations after EOF. - const output = execFileSync(node, [ - path.join(install, 'managed.mjs'), 'cleanup', '--execution-dir', directory, '--execution-id', id, - ], { cwd: root, env: { HOME: root, PATH: env.PATH }, encoding: 'utf8', timeout: 30000 }); - const offline = JSON.parse(output); - assert.equal(offline.status, 'stopped', output); - assert.equal(offline.execution_id, id); - assert.equal(offline.scope, 'execution'); - assert.equal(offline.coverage, 'registered-process-groups-and-inherited-execution-markers'); - assert.deepEqual(JSON.parse(fs.readFileSync(path.join(directory, 'execution-stop.json'), 'utf8')), offline); }); test('installed background bash reports an unverified stop even when the command exits zero', async t => { diff --git a/native/pi/tests/tool-environment.test.mjs b/native/pi/tests/tool-environment.test.mjs index 18e9570d..a71bd240 100644 --- a/native/pi/tests/tool-environment.test.mjs +++ b/native/pi/tests/tool-environment.test.mjs @@ -4,7 +4,6 @@ import { preserveToolConfig } from '../tool-environment.mjs'; for (const [name, environment, expected] of [ ['explicit gh directory takes precedence over XDG', { GH_CONFIG_DIR: '/operator/gh', XDG_CONFIG_HOME: '/operator/xdg' }, '/operator/gh'], - ['original XDG directory selects gh configuration', { XDG_CONFIG_HOME: '/operator/xdg' }, '/operator/xdg/gh'], ['absent GH and XDG use the caller home', {}, '/operator/home/.config/gh'], ]) { test(name, () => { diff --git a/src/config.rs b/src/config.rs index 2388c8a1..68e8e77a 100644 --- a/src/config.rs +++ b/src/config.rs @@ -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/context/reading_tests.rs b/src/context/reading_tests.rs index 7d0649d7..a962140c 100644 --- a/src/context/reading_tests.rs +++ b/src/context/reading_tests.rs @@ -168,19 +168,17 @@ async fn single_page_bill_and_multipage_output_equivalence() { assert_eq!(ops.lock().unwrap().len(), 5); assert_eq!(ops.lock().unwrap().iter().filter(|op| op.ends_with("Core")).count(), 2); assert_eq!(single["body"], "Full body"); + let comments = single[if pr { "conversation" } else { "comments" }].as_array().unwrap(); + assert_eq!(comments.len(), 2); + assert_eq!(comments[0]["node_id"], "C1"); + assert_eq!(comments[0]["body"], "First comment"); + assert_eq!(comments[1]["node_id"], "C2"); + assert_eq!(comments[1]["body"], "Complete comment body"); task.abort(); + let (client, ops, task) = server(pr, true, false, None).await; let multi = materialize(&client, pr).await.unwrap(); - for snapshot in [&single, &multi] { - let comments = - snapshot[if pr { "conversation" } else { "comments" }].as_array().unwrap(); - assert_eq!(comments.len(), 2); - assert_eq!(comments[0]["node_id"], "C1"); - assert_eq!(comments[0]["body"], "First comment"); - assert_eq!(comments[1]["node_id"], "C2"); - assert_eq!(comments[1]["body"], "Complete comment body"); - } - assert_eq!(single, multi); + assert_eq!(multi, single); assert_eq!(ops.lock().unwrap().len(), 6); task.abort(); } @@ -193,15 +191,15 @@ async fn drift_discards_and_retries_whole_snapshot_and_partial_errors_fail() { assert_eq!(snapshot["updated_at"], "1"); assert_eq!(ops.lock().unwrap().len(), 10); task.abort(); - let (client, ops, task) = server(pr, false, false, Some("partial")).await; - let error = materialize(&client, pr).await.unwrap_err(); - assert!( - matches!(error, ContextError::GitHub(GitHubError::GraphQl(ref message)) if message == "incomplete"), - "wrong failure: {error}" - ); - assert_eq!(ops.lock().unwrap().len(), 3); - task.abort(); } + let (client, ops, task) = server(false, false, false, Some("partial")).await; + let error = materialize(&client, false).await.unwrap_err(); + assert!( + matches!(error, ContextError::GitHub(GitHubError::GraphQl(ref message)) if message == "incomplete"), + "wrong failure: {error}" + ); + assert_eq!(ops.lock().unwrap().len(), 3); + task.abort(); } #[tokio::test] diff --git a/src/doctor.rs b/src/doctor.rs index 6d5b4435..214a06cb 100644 --- a/src/doctor.rs +++ b/src/doctor.rs @@ -539,20 +539,13 @@ fn otlp_check(config: &Config) -> Check { mod tests { use super::{Check, CheckState, report_ready}; - fn check(name: &str, state: CheckState) -> Check { - Check { name: name.into(), state, detail: String::new() } - } - #[test] - fn readiness_only_tolerates_unavailable_optional_otlp() { - for (name, state, ready) in [ - ("OTLP endpoint", CheckState::Unavailable, true), - ("OTLP endpoint", CheckState::Fail, false), - ("GitHub App", CheckState::Unavailable, false), - ("GitHub App", CheckState::Pass, true), - ] { - let checks = vec![check("SQLite", CheckState::Pass), check(name, state)]; - assert_eq!(report_ready(&checks), ready, "{name} {state:?}"); - } + fn unavailable_required_service_prevents_readiness() { + let github = Check { + name: "GitHub App".into(), + state: CheckState::Unavailable, + detail: "temporarily offline".into(), + }; + assert!(!report_ready(&[github])); } } diff --git a/src/github/budget_tests.rs b/src/github/budget_tests.rs index f706441c..67351ac2 100644 --- a/src/github/budget_tests.rs +++ b/src/github/budget_tests.rs @@ -47,27 +47,6 @@ fn response(status: u16, headers: &[(&str, String)], body: &str) -> Response GitHubError - // conversion, rather than the raw GraphQL decoder. Outbox and writer retain - // a write as uncertain iff this same is_unavailable classification holds. - let (client, count, task) = server(vec![ - response(429, &[], r#"{"message":"Too many requests"}"#), - response(200, &[], r#"{"ok":true}"#), - ]) - .await; - let error = client.post::<_, Value>("/graphql", None::<&()>).await.unwrap_err(); - let error = GitHubError::from(error); - assert!(error.is_unavailable(), "REST rate limits must not permanently reject a write"); - assert!(matches!(error, GitHubError::Http { .. })); - assert_eq!(count.load(Ordering::SeqCst), 1, "no hidden transport retries"); - let result = client.post::<_, Value>("/graphql", None::<&()>).await.unwrap(); - assert_eq!(result["ok"], true); - assert_eq!(count.load(Ordering::SeqCst), 2); - task.abort(); -} - #[tokio::test] async fn graphql_secondary_headers_block_queued_same_installation_but_not_another() { let (client, count, task) = server(vec![ @@ -81,7 +60,6 @@ async fn graphql_secondary_headers_block_queued_same_installation_but_not_anothe graphql::request::<_, Value>(&client, &limits, 1, false, "query{viewer{id}}", &()), ); let first = first.unwrap_err(); - assert!(first.is_unavailable(), "the first limit response must preserve write retries"); assert!(matches!(first, GitHubError::Delayed(_))); assert!(matches!(queued, Err(GitHubError::Delayed(_)))); assert_eq!(count.load(Ordering::SeqCst), 1); @@ -98,21 +76,13 @@ async fn graphql_response_headers_reserve_budget_and_primary_limit() { let (client, count, task) = server(vec![ response( 200, - &[ - ("x-ratelimit-remaining", "100".into()), - ("x-ratelimit-used", "4900".into()), - ("x-ratelimit-reset", reset.to_string()), - ], + &[("x-ratelimit-remaining", "100".into()), ("x-ratelimit-reset", reset.to_string())], r#"{"data":{"ok":true}}"#, ), response( 200, - &[ - ("x-ratelimit-remaining", "0".into()), - ("x-ratelimit-used", "5000".into()), - ("x-ratelimit-reset", reset.to_string()), - ], - r#"{"errors":[{"message":"API rate limit exceeded"}]}"#, + &[("x-ratelimit-remaining", "0".into()), ("x-ratelimit-reset", reset.to_string())], + r#"{"errors":[{"message":"request refused"}]}"#, ), ]) .await; @@ -128,7 +98,6 @@ async fn graphql_response_headers_reserve_budget_and_primary_limit() { graphql::request::<_, Value>(&client, &limits, 1, false, "query{viewer{id}}", &()) .await .unwrap_err(); - assert!(first_limit.is_unavailable()); assert!(matches!(first_limit, GitHubError::Delayed(_))); assert!(matches!( graphql::request::<_, Value>(&client, &limits, 1, false, "query{viewer{id}}", &()).await, @@ -143,48 +112,19 @@ async fn graphql_response_headers_reserve_budget_and_primary_limit() { } #[tokio::test] -async fn graphql_partial_data_is_rejected_and_unhinted_http_limit_backs_off() { +async fn graphql_and_http_limit_responses_defer_the_installation() { let (client, count, task) = server(vec![ - response( - 200, - &[], - r#"{"data":{"connection":[1]},"errors":[{"message":"one page unavailable"}]}"#, - ), + response(200, &[], r#"{"errors":[{"type":"RATE_LIMITED","message":"budget exhausted"}]}"#), + response(403, &[("retry-after", "60".into())], "secondary limit, not JSON"), response( 403, &[], - r#"{"message":"API rate limit already exceeded for installation ID 1"}"#, + r#"{"message":"API rate limit already exceeded for installation ID 3"}"#, ), ]) .await; let limits = rate_limit::RateLimits::default(); - assert!(matches!( - graphql::request::<_, Value>(&client, &limits, 1, false, "query{viewer{id}}", &()).await, - Err(GitHubError::GraphQl(_)) - )); - let first_limit = - graphql::request::<_, Value>(&client, &limits, 1, false, "query{viewer{id}}", &()) - .await - .unwrap_err(); - assert!(first_limit.is_unavailable()); - assert!(matches!(first_limit, GitHubError::Delayed(_))); - assert!(matches!( - graphql::request::<_, Value>(&client, &limits, 1, false, "query{viewer{id}}", &()).await, - Err(GitHubError::Delayed(_)) - )); - assert_eq!(count.load(Ordering::SeqCst), 2); - task.abort(); -} - -#[tokio::test] -async fn structured_graphql_limit_and_hinted_http_denial_are_retryable() { - let (client, count, task) = server(vec![ - response(200, &[], r#"{"errors":[{"type":"RATE_LIMITED","message":"budget exhausted"}]}"#), - response(403, &[("retry-after", "60".into())], "secondary limit, not JSON"), - ]) - .await; - let limits = rate_limit::RateLimits::default(); - for installation in [1, 2] { + for installation in [1, 2, 3] { let error = graphql::request::<_, Value>( &client, &limits, @@ -210,7 +150,7 @@ async fn structured_graphql_limit_and_hinted_http_denial_are_retryable() { Err(GitHubError::Delayed(_)) )); } - assert_eq!(count.load(Ordering::SeqCst), 2); + assert_eq!(count.load(Ordering::SeqCst), 3); task.abort(); } diff --git a/src/github/rate_limit.rs b/src/github/rate_limit.rs index 5f0032d5..aac1782e 100644 --- a/src/github/rate_limit.rs +++ b/src/github/rate_limit.rs @@ -128,25 +128,6 @@ impl Budget { mod tests { use super::*; - #[test] - fn primary_reset_reserve_and_used_delta() { - let mut budget = Budget::default(); - let mut headers = HeaderMap::new(); - headers.insert("x-ratelimit-used", "4900".parse().unwrap()); - headers.insert("x-ratelimit-resource", "graphql".parse().unwrap()); - headers.insert("x-ratelimit-remaining", "100".parse().unwrap()); - headers.insert("x-ratelimit-reset", "500".parse().unwrap()); - assert_eq!(budget.observe(&headers), None); - assert!(budget.admit(100, true).is_err()); - assert!(budget.admit(100, false).is_ok()); - headers.insert("x-ratelimit-used", "5000".parse().unwrap()); - headers.insert("x-ratelimit-remaining", "0".parse().unwrap()); - assert_eq!(budget.observe(&headers), Some(100)); - budget.defer(100, None); - assert!(budget.admit(499, false).is_err()); - assert!(budget.admit(500, true).is_ok()); - } - #[test] fn missing_reset_does_not_park_reserve_and_primary_respects_both_hints() { let mut budget = Budget::default(); @@ -176,15 +157,16 @@ mod tests { #[test] fn missing_hints_backoff_is_bounded_and_recovers() { let mut budget = Budget::default(); - for _ in 0..100 { + for range in [10..=12, 20..=25, 40..=50, 80..=100, 160..=200, 300..=375, 300..=375] { budget.defer(1000, None); - assert!((1010..=1375).contains(&budget.until)); - assert!(budget.admit(1001, false).is_err()); + let delay = budget.retry_after(1000); + assert!(range.contains(&delay), "expected {range:?}s, got {delay}s"); } + assert!(budget.admit(1001, false).is_err()); assert!(budget.admit(1375, false).is_ok()); budget.success(); budget.defer(1400, None); - assert!((1410..=1412).contains(&budget.until)); + assert!((10..=12).contains(&budget.retry_after(1400))); } } diff --git a/src/group/continuous_tests.rs b/src/group/continuous_tests.rs index f49b32cf..546b8d9b 100644 --- a/src/group/continuous_tests.rs +++ b/src/group/continuous_tests.rs @@ -216,6 +216,7 @@ async fn soft_pressure_reset_replaces_memory_and_delivers_input_with_publication ); // Resetting an idle session is not an acknowledgement of the work input. assert_eq!(f.store.runtime_status().unwrap().batches.len(), 1); + f.store.advance_scheduler().unwrap(); assert!(driver.start_next_agent_turn().await.is_none(), "ordinary revision must keep debounce"); f.db().execute("UPDATE wake_batches SET quiet_deadline='2000-01-01T00:00:00Z' WHERE lifecycle='pending'",[]).unwrap(); f.store.advance_scheduler().unwrap(); @@ -660,101 +661,6 @@ async fn rejected_steer_stops_retrying_while_unknown_steer_retains_its_input() { } } -#[tokio::test] -async fn stopping_native_execution_does_not_wait_for_execution_fence() { - use axum::{ - Json, Router, - http::StatusCode, - routing::{get, post}, - }; - use tokio::sync::Notify; - - let f = Fixture::new(false); - let store = Arc::new( - StoreActor::start(f.config.runtime.database().into(), f.config.runtime.backups().into()) - .unwrap(), - ); - let entered = Arc::new(Notify::new()); - let release = Arc::new(Notify::new()); - let routes = Router::new() - .route("/api/platform/repository", get(|| async { - Json(serde_json::json!({"repository":"test-space","spaceId":"space","executionFences":true,"nodeId":"local:test-space","defaultBranch":"main"})) - })) - .route("/api/platform/executions/fence", post({ - let (entered, release) = (entered.clone(), release.clone()); - move || { - let (entered, release) = (entered.clone(), release.clone()); - async move { - entered.notify_one(); - release.notified().await; - (StatusCode::SERVICE_UNAVAILABLE, "fence service offline") - } - } - })); - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - let address = listener.local_addr().unwrap(); - let http = tokio::spawn(async move { axum::serve(listener, routes).await.unwrap() }); - let mut config = f.config.clone(); - config.github = None; - config.builtin = Some(crate::config::BuiltinConfig { - repository: "test-space".into(), - endpoint: format!("http://{address}").parse().unwrap(), - }); - let lease = store.acquire_runtime_lease("runtime".into(), "fixture".into(), 60).unwrap(); - let collaboration = CollaborationBackend::Builtin( - crate::builtin::BuiltinClient::connect(&config, Arc::clone(&store)) - .await - .unwrap() - .with_runtime(lease) - .unwrap(), - ); - let spec = GroupSpec::new(GroupKind::Issue, &config, &store, "test-space").unwrap(); - f.db().execute_batch( - "INSERT INTO repositories VALUES('local:test-space','test-space',1,'now'); - INSERT INTO work_items(node_id,repository_node_id,kind,number,state,observed_at) - VALUES('fixture-item','local:test-space','issue',1,'open','now'); - INSERT INTO assignments VALUES('fixture-assignment','fixture-item',1,'active','now',NULL);" - ).unwrap(); - f.db().execute( - "INSERT INTO agent_instances(agent_id,assignment_id,profile_id,profile_revision,role,lifecycle) - SELECT 'fixture-agent','fixture-assignment',profile_id,revision,'issue','idle' - FROM profiles WHERE profile_id=?1", - [&spec.profile.id], - ).unwrap(); - f.db().execute( - "INSERT INTO provider_sessions(session_id,agent_id,provider_kind,provider_session_id, - context_revision,instruction_revision,lifecycle,started_at,builtin_execution_id,builtin_execution_owner) - VALUES('fixture-session','fixture-agent','codex','provider','memory','instructions','idle','now',?1,'fixture')", - [uuid::Uuid::now_v7().to_string()], - ).unwrap(); - let captured = Arc::new(Captured::default()); - let driver = worker::GroupDriver { - store: &store, - config: &config, - collaboration: &collaboration, - spec: &spec, - sessions: SessionManager::new(Arc::new(Factory(captured.clone()))), - }; - driver - .sessions - .resume("provider".into(), spec.profile.clone(), "instructions".into()) - .await - .unwrap(); - - let (stop, ()) = tokio::time::timeout(std::time::Duration::from_secs(3), async { - tokio::join!(driver.quiesce_session("provider"), async { - entered.notified().await; - captured.closed.notified().await; - assert!(driver.sessions.confirmed_stopped("provider").await); - release.notify_one(); - }) - }) - .await - .expect("native close must finish while the fence response is withheld"); - assert!(stop.unwrap_err().to_string().contains("execution fence unconfirmed")); - http.abort(); -} - #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn builtin_turn_runs_without_writer_service_and_cannot_mint_after_reassignment() { builtin_running_unassignment(Some((crate::agent_session::TurnOutcome::Completed, None)), false) @@ -814,14 +720,22 @@ async fn builtin_running_unassignment( backups: root.join("platform-backups"), listen: address.to_string(), }; - let offline = Arc::new(AtomicBool::new(true)); + let offline = Arc::new(AtomicBool::new(!restart)); let fence_offline = Arc::new(AtomicBool::new(false)); + // A missing terminal is the cold-recovery case. Hold the first fence response + // there so only the native side can produce the observed durable stop. + let fence_entered = Arc::new(tokio::sync::Notify::new()); + let fence_response = Arc::new(tokio::sync::Semaphore::new(usize::from(terminal.is_some()))); let routes = crate::platform::router(&platform).unwrap().layer(axum::middleware::from_fn({ let offline = Arc::clone(&offline); let fence_offline = Arc::clone(&fence_offline); + let fence_entered = Arc::clone(&fence_entered); + let fence_response = Arc::clone(&fence_response); move |request: axum::extract::Request, next: axum::middleware::Next| { let offline = Arc::clone(&offline); let fence_offline = Arc::clone(&fence_offline); + let fence_entered = Arc::clone(&fence_entered); + let fence_response = Arc::clone(&fence_response); async move { use axum::response::IntoResponse as _; if request.uri().path().starts_with("/api/platform/grants") @@ -832,6 +746,8 @@ async fn builtin_running_unassignment( if request.uri().path() == "/api/platform/executions/fence" && fence_offline.load(Ordering::Relaxed) { + fence_entered.notify_one(); + let _permit = fence_response.acquire().await.unwrap(); return StatusCode::SERVICE_UNAVAILABLE.into_response(); } next.run(request).await @@ -850,7 +766,8 @@ async fn builtin_running_unassignment( }); let (mut store, mut client) = open_worker_runtime(&config, "fixture").await; let actor = "issue-codex"; - let mut platform = PlatformObjects::open(&platform.database, &platform.repository).unwrap(); + let platform_database = platform.database.clone(); + let mut platform = PlatformObjects::open(&platform_database, &platform.repository).unwrap(); let issue = platform.create_child_issue("Writer independence", "Read first", "human", None).unwrap(); platform.assign(issue.number, Some(actor), "human").unwrap(); @@ -921,16 +838,19 @@ async fn builtin_running_unassignment( assert_eq!(captured.inputs.lock().unwrap().len(), 1); let writer = BuiltinWriterTurn { session_id, turn_id, item_number: issue.number, actor: actor.into() }; - let offline_error = client.writer_grant(writer.clone()).await.unwrap_err(); - assert!(offline_error.to_string().contains("503"), "{offline_error:#}"); + if !restart { + let error = client.writer_grant(writer.clone()).await.unwrap_err(); + assert!(error.to_string().contains("503"), "{error:#}"); + } // The old turn never minted a grant. Name equality must not revive it // after an unassign/reassign and before those events reach the Harness. platform.assign(issue.number, Some(actor), "human").unwrap(); - offline.store(false, Ordering::Relaxed); - let error = client.writer_grant(writer.clone()).await.unwrap_err(); - assert!(error.to_string().contains("writer authority changed"), "{error:#}"); - offline.store(true, Ordering::Relaxed); + if !restart { + offline.store(false, Ordering::Relaxed); + let error = client.writer_grant(writer.clone()).await.unwrap_err(); + assert!(error.to_string().contains("writer authority changed"), "{error:#}"); + } captured.close_terminal.lock().unwrap().clone_from(&terminal); fence_offline.store(true, Ordering::Relaxed); for pending in platform.events(cursor, 100).unwrap() { @@ -959,13 +879,15 @@ async fn builtin_running_unassignment( (outcome, reason) } else { tokio::time::timeout(limit, async { + fence_entered.notified().await; while !f.db().query_row( "SELECT execution_stopped_at IS NOT NULL FROM provider_sessions WHERE provider_session_id=?1", [&writer.session_id], |row| row.get::<_, bool>(0), ).unwrap() { tokio::time::sleep(std::time::Duration::from_millis(20)).await; } - }).await.expect("native stop must reach SQLite before a successful platform fence"); + }).await.expect("native stop must reach SQLite while the fence response is withheld"); + fence_response.add_permits(1); assert_eq!(turn_state().0, "running"); ( crate::agent_session::TurnOutcome::Unknown, @@ -1030,9 +952,17 @@ async fn builtin_running_unassignment( assert_eq!(turn_state(), (outcome.lifecycle().to_owned(), reason)); assert_eq!(*captured.close_attempts.lock().unwrap(), ["fresh-provider"]); assert_eq!(captured.memory.lock().unwrap().len(), 2); - client.fence_all_executions().await.unwrap(); - let fenced = client.writer_grant(writer).await.unwrap_err(); - assert!(fenced.to_string().contains("no current writer authority")); + if !restart { + let execution: (String, String) = f.db().query_row( + "SELECT client_id,builtin_execution_id FROM builtin_upstream,turns WHERE turn_id=?1", + [&writer.turn_id], |row| Ok((row.get(0)?, row.get(1)?)), + ).unwrap(); + let fenced: bool = rusqlite::Connection::open(&platform_database).unwrap().query_row( + "SELECT EXISTS(SELECT 1 FROM execution_fences WHERE client_id=?1 AND execution_id=?2)", + (&execution.0, &execution.1), |row| row.get(0), + ).unwrap(); + assert!(fenced, "the platform must persist the old execution fence before replacement"); + } shutdown.send(true).unwrap(); worker.await.unwrap().unwrap(); http.abort(); diff --git a/src/health/tests.rs b/src/health/tests.rs index 6d9287cf..05f7d57c 100644 --- a/src/health/tests.rs +++ b/src/health/tests.rs @@ -5,10 +5,10 @@ use crate::group::{ }; use tokio::{sync::mpsc, time::Duration}; -fn health(ingress: &str) -> Health { +fn health() -> Health { Health::new(HealthSnapshot { ready: false, - ingress: ingress.into(), + ingress: "builtin".into(), repository: "owner/one, owner/two".into(), tunnel: "disabled", webhook_url: None, @@ -21,50 +21,58 @@ fn health(ingress: &str) -> Health { }) } -async fn aggregate(reports: &[(&str, GroupKind, Option<&str>)]) -> HealthSnapshot { - let health = health("github"); - let (sender, receiver) = mpsc::channel(8); - for &(repository, group, error) in reports { - sender - .send(ProviderReport { +#[tokio::test] +async fn provider_availability_tracks_each_group_and_preserves_the_outage_start() { + use ProviderAvailability::{Connected, Starting, Unavailable}; + + let (_stop, shutdown) = watch::channel(false); + let (reports, receiver) = mpsc::channel(8); + let (availability, mut status) = watch::channel(Starting); + let tracker = tokio::spawn(track_provider_availability(4, receiver, availability, shutdown)); + let send = |repository: &str, group: GroupKind, error: Option<&str>| { + reports + .try_send(ProviderReport { repository: repository.into(), group, error: error.map(str::to_owned), }) + .unwrap(); + }; + tokio::time::timeout(Duration::from_secs(2), async { + send("owner/one", Issue, Some("offline")); + let Unavailable { since: first_failure, .. } = + *status.wait_for(|s| matches!(s, Unavailable { .. })).await.unwrap() + else { + unreachable!() + }; + send("owner/one", Pr, None); + send("owner/one", Issue, Some("retry")); + let retry = status + .wait_for(|s| matches!(s, Unavailable { error, .. } if error == "retry")) .await .unwrap(); - } - drop(sender); - let (_stop, shutdown) = watch::channel(false); - let (availability, provider_status) = watch::channel(ProviderAvailability::Starting); - tokio::join!( - track_provider_availability(4, receiver, availability, shutdown.clone()), - provider_health_worker(health.clone(), provider_status, shutdown), - ); - health.snapshot() -} - -#[tokio::test] -async fn health_tracks_each_repository_and_kind_independently() { - let mut reports = vec![("owner/one", Issue, None), ("owner/one", Pr, None)]; - assert_eq!(aggregate(&reports).await.provider, "starting"); - reports.extend([("owner/two", Issue, None), ("owner/two", Pr, None)]); - assert_eq!(aggregate(&reports).await.provider, "connected"); - - reports[0].2 = Some("first repository unavailable"); - let failed = aggregate(&reports).await; - assert_eq!(failed.provider, "unavailable"); - assert_eq!(failed.last_error.as_deref(), Some("first repository unavailable")); + assert!(matches!(*retry, Unavailable { since, .. } if since == first_failure)); + drop(retry); - reports.push(("owner/one", Issue, None)); - let recovered = aggregate(&reports).await; - assert_eq!(recovered.provider, "connected"); + send("owner/one", Issue, None); + status.wait_for(|s| matches!(s, Starting)).await.unwrap(); + send("owner/two", Issue, None); + send("owner/two", Pr, None); + status.wait_for(|s| matches!(s, Connected)).await.unwrap(); + }) + .await + .expect("provider availability must advance without an operator health consumer"); + send("owner/one", Issue, Some("still offline")); + send("owner/two", Pr, None); + drop(reports); + tracker.await.unwrap(); + assert!(matches!(&*status.borrow(), Unavailable { error, .. } if error == "still offline")); } #[tokio::test] async fn provider_recovery_clears_its_own_diagnostic_and_preserves_another_workers_error() { for other_error in [None, Some("reconciliation failed")] { - let health = health("builtin"); + let health = health(); let (_stop, shutdown) = watch::channel(false); let (availability, reports) = watch::channel(ProviderAvailability::Starting); let worker = tokio::spawn(provider_health_worker(health.clone(), reports, shutdown)); @@ -89,65 +97,8 @@ async fn provider_recovery_clears_its_own_diagnostic_and_preserves_another_worke drop(availability); worker.await.unwrap(); let recovered = health.snapshot(); + assert_eq!(recovered.provider, "connected"); assert!(recovered.ready); assert_eq!(recovered.last_error.as_deref(), other_error); } } - -#[tokio::test] -async fn provider_control_advances_while_health_projection_is_paused() { - let health = health("builtin"); - let earlier_snapshot = health.snapshot(); - let (_stop, shutdown) = watch::channel(false); - let (reports, receiver) = mpsc::channel(1); - let (availability, mut control) = watch::channel(ProviderAvailability::Starting); - let tracker = - tokio::spawn(track_provider_availability(1, receiver, availability, shutdown.clone())); - let projection = provider_health_worker(health.clone(), control.clone(), shutdown); - - let send = |error: Option<&str>| { - reports.send(ProviderReport { - repository: "owner/one".into(), - group: Issue, - error: error.map(str::to_owned), - }) - }; - tokio::time::timeout(Duration::from_secs(2), async { - send(Some("first failure")).await.unwrap(); - control.changed().await.unwrap(); - let initial_failure = match &*control.borrow() { - ProviderAvailability::Unavailable { since, error } => { - assert_eq!(error, "first failure"); - *since - } - status => panic!("expected unavailable, got {status:?}"), - }; - for _ in 0..3 { - send(Some("retry failure")).await.unwrap(); - control.changed().await.unwrap(); - match &*control.borrow() { - ProviderAvailability::Unavailable { since, error } => { - assert_eq!(*since, initial_failure); - assert_eq!(error, "retry failure"); - } - status => panic!("expected unavailable during recovery, got {status:?}"), - } - } - send(None).await.unwrap(); - control.changed().await.unwrap(); - assert!(matches!(*control.borrow(), ProviderAvailability::Connected)); - }) - .await - .unwrap(); - - assert_eq!(health.snapshot().provider, "starting"); - drop(reports); - tracker.await.unwrap(); - projection.await; - let latest = health.snapshot(); - assert_eq!(latest.provider, "connected"); - assert!(latest.ready); - assert_eq!(latest.last_error, None); - assert_eq!(earlier_snapshot.provider, "starting"); - assert!(!earlier_snapshot.ready); -} diff --git a/src/platform/tests.rs b/src/platform/tests.rs index 80076bad..0f780805 100644 --- a/src/platform/tests.rs +++ b/src/platform/tests.rs @@ -122,16 +122,13 @@ impl Fixture { json!({"grantId":grant["grantId"],"epoch":grant["epoch"],"token":grant["token"]}) } - async fn create_issue(&self) { - let receipt = self - .apply( - "create", - None, - json!({"type":"createIssue", "title":"Design", "body":"original"}), - ) - .await; - assert_eq!(receipt["result"]["number"], 1); - assert_eq!(receipt["result"]["revision"], 1); + async fn create_issue(&self) -> Value { + self.apply( + "create", + None, + json!({"type":"createIssue", "title":"Design", "body":"original"}), + ) + .await } } @@ -158,8 +155,9 @@ fn commit(git: &git2::Repository, reference: &str, body: &str, parents: &[git2:: #[tokio::test] async fn command_receipts_and_revision_conflicts_survive_restart_without_duplicate_events() { let mut fixture = Fixture::new().await; - fixture.create_issue().await; - let original = fixture.get("/api/control/receipts/create").await; + let original = fixture.create_issue().await; + assert_eq!(original["result"]["number"], 1); + assert_eq!(original["result"]["revision"], 1); let events = fixture.get("/api/platform/events?after=0").await; fixture.restart().await; let replay = fixture @@ -195,47 +193,6 @@ async fn command_receipts_and_revision_conflicts_survive_restart_without_duplica fixture.shutdown().await; } -#[tokio::test] -async fn revoked_writer_cannot_write_with_the_current_object_revision_after_restart() { - let mut fixture = Fixture::new().await; - fixture.create_issue().await; - fixture.apply("assign", Some(1), json!({"type":"assign", "number":1, "actor":"worker"})).await; - let capability = fixture.mint(1, "grant", 0, None).await; - let write = json!({"requestId":"write", "expectedRevision":2, "actor":"worker", "writer":capability, - "command":{"type":"comment", "number":1, "body":"accepted", "replyTo":null}}); - let (status, accepted) = fixture.post("/api/control/commands", &write).await; - assert_eq!(status, StatusCode::OK, "{accepted}"); - assert_eq!(accepted["state"], "applied"); - let (status, revoked) = fixture.post("/api/platform/grants/revoke", &json!({ - "requestId":"revoke", "clientId":"harness", "itemNumber":1, "actor":"worker", "expectedEpoch":1, - })).await; - assert_eq!(status, StatusCode::OK, "{revoked}"); - assert_eq!(revoked, json!({"epoch":2,"lifecycle":"revoked"})); - let events = fixture.get("/api/platform/events?after=0").await; - fixture.restart().await; - let item = fixture.get("/api/control/items/1").await; - assert_eq!(item["item"]["state"], "open"); - assert_eq!(item["item"]["desired_profile"], "worker"); - assert_eq!(item["item"]["revision"], 3); - let (status, rejected) = fixture.post("/api/control/commands", &json!({ - "requestId":"late", "expectedRevision":3, "actor":"worker", "writer":capability, - "command":{"type":"comment", "number":1, "body":"must not be written", "replyTo":null}, - })).await; - assert_eq!(status, StatusCode::CONFLICT); - assert_eq!(rejected["state"], "rejected"); - assert_eq!(rejected["error"]["code"], "rejected"); - assert!( - rejected["error"]["message"].as_str().unwrap().contains("writer grant is stale, revoked") - ); - assert_eq!(fixture.get("/api/control/items/1").await, item); - assert_eq!(fixture.get("/api/platform/events?after=0").await, events); - // A completed old command remains a receipt; replay is not a new late mutation. - let (status, replay) = fixture.post("/api/control/commands", &write).await; - assert_eq!(status, StatusCode::OK); - assert_eq!(replay, accepted); - fixture.shutdown().await; -} - #[tokio::test] async fn object_authority_changes_invalidate_grants_even_when_grant_rows_cannot_be_updated() { let mut fixture = Fixture::new().await; @@ -254,7 +211,7 @@ async fn object_authority_changes_invalidate_grants_even_when_grant_rows_cannot_ block_grant_updates(); fixture.apply("reassign", Some(2), json!({"type":"assign","number":1,"actor":"worker"})).await; assert_eq!(fixture.get(epoch_path).await, json!({"active":false,"epoch":1})); - assert_stale_write(&fixture, "late-after-reassignment", &unscoped).await; + assert_stale_write(&fixture, 1, "late-after-reassignment", &unscoped).await; let revision = fixture.get("/api/control/items/1").await["item"]["revision"].as_u64().unwrap(); fixture .apply( @@ -286,29 +243,30 @@ async fn object_authority_changes_invalidate_grants_even_when_grant_rows_cannot_ fixture.apply(operation, Some(revision), json!({"type":operation, "number":1})).await; } assert_eq!(fixture.get(epoch_path).await, json!({"active":false,"epoch":2})); - assert_stale_write(&fixture, "late-after-reopen", &scoped).await; + assert_stale_write(&fixture, 1, "late-after-reopen", &scoped).await; fixture.shutdown().await; } -async fn assert_stale_write(fixture: &Fixture, id: &str, writer: &Value) { - let path = "/api/control/items/1"; - let item = fixture.get(path).await; +async fn assert_stale_write(fixture: &Fixture, number: u64, id: &str, writer: &Value) { + let path = format!("/api/control/items/{number}"); + let item = fixture.get(&path).await; let (status, body) = fixture .post( "/api/control/commands", &json!({ "requestId":id, "expectedRevision":item["item"]["revision"], "actor":"worker", - "writer":writer,"command":{"type":"comment","number":1,"body":"stale write"} + "writer":writer,"command":{"type":"comment","number":number,"body":"stale write"} }), ) .await; assert_eq!(status, StatusCode::CONFLICT); assert_eq!(body["state"], "rejected"); + assert_eq!(body["error"]["code"], "rejected"); assert!( body["error"]["message"].as_str().unwrap().contains("writer grant is stale, revoked"), "{body}" ); - assert_eq!(fixture.get(path).await, item); + assert_eq!(fixture.get(&path).await, item); } #[tokio::test] @@ -346,6 +304,7 @@ async fn published_candidate_diff_and_merge_use_the_frozen_commit_after_branch_m assert!(diff["diff"].as_str().unwrap().contains("+published candidate")); assert!(!diff["diff"].as_str().unwrap().contains("later unpublished work")); let receipt = fixture.apply("merge", Some(2), json!({"type":"merge", "number":2})).await; + assert_eq!(fixture.get("/api/control/receipts/merge").await, receipt); let merged = git.refname_to_id("refs/heads/main").unwrap(); assert_eq!(receipt["result"]["merge_commit"], merged.to_string()); let commit = git.find_commit(merged).unwrap(); @@ -357,16 +316,10 @@ async fn published_candidate_diff_and_merge_use_the_frozen_commit_after_branch_m assert_eq!(blob.content(), b"published candidate\n"); assert_eq!(fixture.get("/api/control/items/1").await["item"]["state"], "open"); assert_eq!(fixture.get("/api/control/items/2").await["item"]["state"], "closed"); - let events = fixture.get("/api/platform/events?after=0").await; - fixture.restart().await; - let replay = fixture.apply("merge", Some(2), json!({"type":"merge", "number":2})).await; - assert_eq!(replay, receipt); - assert_eq!(git.refname_to_id("refs/heads/main").unwrap(), merged); - assert_eq!(fixture.get("/api/platform/events?after=0").await, events); fixture.shutdown().await; } -async fn assigned_pr(fixture: &Fixture) -> Value { +async fn open_pr(fixture: &Fixture) { fixture.create_issue().await; let git = git2::Repository::open(&fixture.config.source).unwrap(); let base = git.refname_to_id("refs/heads/main").unwrap(); @@ -380,6 +333,10 @@ async fn assigned_pr(fixture: &Fixture) -> Value { "head":"feature", "base":"main", "issue":1, "issueRevision":1}), ) .await; +} + +async fn assigned_pr(fixture: &Fixture) -> Value { + open_pr(fixture).await; fixture .apply("assign-pr", Some(1), json!({"type":"assign", "number":2, "actor":"worker"})) .await; @@ -422,8 +379,9 @@ async fn adopted_merge_recovers_its_receipt_after_restart_and_writer_revocation( "requestId":"revoke-pr", "clientId":"harness", "itemNumber":2, "actor":"worker", "expectedEpoch":1, })).await; assert_eq!(status, StatusCode::OK, "{revoked}"); - assert_eq!(revoked["lifecycle"], "revoked"); + assert_eq!(revoked, json!({"epoch":2,"lifecycle":"revoked"})); fixture.restart().await; + assert_stale_write(&fixture, 2, "late-after-revocation", &capability).await; // Even a newly authorized Human command cannot claim someone else's Git effect. let (status, other) = fixture .post( @@ -477,11 +435,11 @@ async fn adopted_merge_recovers_its_receipt_after_restart_and_writer_revocation( } #[tokio::test] -async fn prepared_merge_does_not_retry_uncommitted_effects_after_writer_revocation() { +async fn prepared_merge_without_a_bound_commit_does_not_reexecute_on_retry() { let mut fixture = Fixture::new().await; - let capability = assigned_pr(&fixture).await; - let request = json!({"requestId":"merge-pending", "expectedRevision":2, - "actor":"worker", "writer":capability, "command":{"type":"merge", "number":2}}); + open_pr(&fixture).await; + let request = json!({"requestId":"merge-pending", "expectedRevision":1, + "command":{"type":"merge", "number":2}}); let db = rusqlite::Connection::open(&fixture.config.database).unwrap(); let git = git2::Repository::open(&fixture.config.source).unwrap(); let base = git.refname_to_id("refs/heads/main").unwrap(); @@ -501,11 +459,6 @@ async fn prepared_merge_does_not_retry_uncommitted_effects_after_writer_revocati assert_eq!(git.refname_to_id("refs/heads/main").unwrap(), base); db.execute_batch("DROP TRIGGER fail_intent; DROP TRIGGER lose_receipt;").unwrap(); drop(db); - let (status, revoked) = fixture.post("/api/platform/grants/revoke", &json!({ - "requestId":"revoke-pr", "clientId":"harness", "itemNumber":2, "actor":"worker", "expectedEpoch":1, - })).await; - assert_eq!(status, StatusCode::OK, "{revoked}"); - assert_eq!(revoked["lifecycle"], "revoked"); let events = fixture.get("/api/platform/events?after=0").await; fixture.restart().await; let (status, pending) = fixture.post("/api/control/commands", &request).await; @@ -588,15 +541,7 @@ async fn publishing_and_its_receipt_commit_together_or_leave_the_candidate_uncha assert_eq!(receipt["result"]["head_commit"], candidate.to_string()); assert_eq!(receipt["result"]["revision"], 3); assert_eq!(receipt["result"]["published"], true); - let item = fixture.get("/api/control/items/2").await; - let events = fixture.get("/api/platform/events?after=0").await; - fixture.restart().await; - assert_eq!( - fixture.post("/api/control/commands", &new_request).await, - (StatusCode::OK, receipt) - ); - assert_eq!(fixture.get("/api/control/items/2").await, item); - assert_eq!(fixture.get("/api/platform/events?after=0").await, events); + assert_eq!(fixture.get("/api/control/receipts/publish-complete").await, receipt); fixture.shutdown().await; } diff --git a/src/producer/ingress_tests.rs b/src/producer/ingress_tests.rs index bb460ef1..e82634d1 100644 --- a/src/producer/ingress_tests.rs +++ b/src/producer/ingress_tests.rs @@ -98,10 +98,6 @@ async fn webhook_rejects_unverified_bytes_and_unconfigured_repository_before_dur assert_eq!(db.count("deliveries"), 0); assert_eq!(db.count("events"), 0); assert_eq!(db.count("work_items"), 0); - let (status, body) = deliver(&state, PRIMARY, Some(PRIMARY_SIGNATURE), "accepted").await; - assert_eq!(status, StatusCode::ACCEPTED, "{body}"); - assert_eq!(serde_json::from_str::(&body).unwrap()["duplicate"], false); - assert_eq!(db.count("deliveries"), 1); } #[tokio::test] @@ -168,7 +164,7 @@ async fn signed_same_number_repositories_keep_distinct_events_and_deduplicate_af } #[tokio::test] -async fn signed_app_comment_mention_does_not_schedule_a_handoff_or_wake() { +async fn signed_app_comment_is_consumed_without_waking_the_active_pr() { const BODY: &str = r#"{"action":"created","repository":{"node_id":"R1","full_name":"owner/repository"},"sender":{"login":"braid[bot]","node_id":"APP"},"issue":{"node_id":"I1","number":1,"state":"open","pull_request":{}},"comment":{"id":7,"node_id":"C1","body":"@braid continue this handoff","created_at":"2026-01-01T00:00:00Z","updated_at":"2026-01-01T00:00:00Z"}}"#; let db = Database::new(); let state = db.state(&["owner/repository"]); @@ -188,16 +184,7 @@ async fn signed_app_comment_mention_does_not_schedule_a_handoff_or_wake() { ) .await; assert_eq!(status, StatusCode::ACCEPTED, "{receipt}"); - let id: Value = serde_json::from_str(&receipt).unwrap(); - let kind: String = db - .connect() - .query_row( - "SELECT kind FROM events WHERE event_id=?1", - [id["event_id"].as_str().unwrap()], - |row| row.get(0), - ) - .unwrap(); - assert_eq!(kind, "origin_echo"); + let receipt: Value = serde_json::from_str(&receipt).unwrap(); + assert_eq!(receipt["event_lifecycle"], "consumed"); assert_eq!(db.count("wake_batches"), 0); - assert_eq!(db.count("pr_handoffs"), 0); } diff --git a/src/profile_materials/tests.rs b/src/profile_materials/tests.rs index 9b3aacee..7a5cbe99 100644 --- a/src/profile_materials/tests.rs +++ b/src/profile_materials/tests.rs @@ -62,11 +62,7 @@ compat = { supports_store = false, max_tokens_field = "max_completion_tokens" } #[test] fn snapshot_writes_native_model_fields_and_keeps_credentials_out_of_models_json() { let root = std::env::temp_dir().join(format!("braid-pi-models-{}", uuid::Uuid::now_v7())); - for (name, kind) in [ - ("api-key", CredentialKind::ApiKey), - ("oauth", CredentialKind::OAuth), - ("none", CredentialKind::None), - ] { + for (name, kind) in [("api-key", CredentialKind::ApiKey), ("oauth", CredentialKind::OAuth)] { let directory = root.join(name); fs::create_dir_all(&directory).unwrap(); let config = configuration(&directory, kind, None, None); @@ -87,13 +83,18 @@ fn snapshot_writes_native_model_fields_and_keeps_credentials_out_of_models_json( expected["providers"]["test-llm"]["apiKey"] = json!("$BRAID_PROVIDER_API_KEY"); } assert_eq!(actual, expected, "{name}"); - // Resume uses this same frozen home; it must not silently overwrite a - // changed model route just because the identity file still matches. - fs::write(home.join("models.json"), br#"{"providers":{}}"#).unwrap(); - let error = - snapshot(&config, profile, &directory, &home_key, &materials.digest).unwrap_err(); - assert!(error.to_string().contains("Pi native material snapshot changed at"), "{error}"); - assert_eq!(fs::read(home.join("models.json")).unwrap(), br#"{"providers":{}}"#); + if kind == CredentialKind::ApiKey { + // Resume uses this same frozen home; it must not silently overwrite a + // changed model route just because the identity file still matches. + fs::write(home.join("models.json"), br#"{"providers":{}}"#).unwrap(); + let error = + snapshot(&config, profile, &directory, &home_key, &materials.digest).unwrap_err(); + assert!( + error.to_string().contains("Pi native material snapshot changed at"), + "{error}" + ); + assert_eq!(fs::read(home.join("models.json")).unwrap(), br#"{"providers":{}}"#); + } } fs::remove_dir_all(root).unwrap(); } diff --git a/src/provider/pi_runtime_tests.rs b/src/provider/pi_runtime_tests.rs index a1f1fbbc..dc0b25cf 100644 --- a/src/provider/pi_runtime_tests.rs +++ b/src/provider/pi_runtime_tests.rs @@ -12,9 +12,9 @@ async fn cleanup_receipt_requires_every_stop_proof_without_exposing_raw_output() "coverage": "registered-process-groups-and-inherited-execution-markers", "private": "PRIVATE_CLEANUP_SENTINEL" }); - for case in ["valid", "exit", "status", "execution_id", "scope", "coverage", "malformed"] { + for case in ["exit", "status", "execution_id", "scope", "coverage", "malformed"] { let mut candidate = receipt.clone(); - if !matches!(case, "valid" | "exit" | "malformed") { + if !matches!(case, "exit" | "malformed") { candidate[case] = Value::String("wrong".into()); } let stdout = if case == "malformed" { @@ -41,12 +41,7 @@ async fn cleanup_receipt_requires_every_stop_proof_without_exposing_raw_output() owner: PathBuf::new(), start_id: "test".into(), }; - let result = execution.cleanup().await; - if case == "valid" { - result.unwrap(); - continue; - } - let error = result.unwrap_err(); + let error = execution.cleanup().await.unwrap_err(); if case == "malformed" { assert!( matches!(&error, ProviderError::Protocol(message) if message.contains("stage=decode")) diff --git a/src/provider/session_tests.rs b/src/provider/session_tests.rs index f2221623..a9b51f4e 100644 --- a/src/provider/session_tests.rs +++ b/src/provider/session_tests.rs @@ -1,14 +1,10 @@ use super::*; use crate::provider::{ProviderSession, ProviderTurn}; -use tokio::sync::{mpsc, oneshot}; - -type StartReply = oneshot::Sender>; /// Only the external provider is controlled. The production adapter owns /// notification ordering, deduplication, availability and stop confirmation. struct ControlledProvider { notifications: broadcast::Sender, - starts: mpsc::Sender, } #[async_trait::async_trait] @@ -37,11 +33,9 @@ impl AgentProvider for ControlledProvider { &self, _: &str, _: &Profile, - _: &str, + input: &str, ) -> Result { - let (reply, response) = oneshot::channel(); - self.starts.send(reply).await.unwrap(); - response.await.unwrap() + Ok(ProviderTurn { turn_id: format!("native-{input}") }) } async fn steer(&self, _: &str, _: &str, _: &str) -> Result<(), ProviderError> { unreachable!("this fixture does not steer") @@ -51,10 +45,8 @@ impl AgentProvider for ControlledProvider { } } -async fn fixture() --> (Arc, Arc, mpsc::Receiver) { - let (starts, requests) = mpsc::channel(1); - let provider = Arc::new(ControlledProvider { notifications: broadcast::channel(32).0, starts }); +async fn fixture() -> (Arc, Arc) { + let provider = Arc::new(ControlledProvider { notifications: broadcast::channel(32).0 }); let config: crate::config::Config = toml::from_str(include_str!("../../config.example.toml")).unwrap(); let session = ProviderAgentSession::start( @@ -65,18 +57,11 @@ async fn fixture() ) .await .unwrap(); - (provider, session, requests) + (provider, session) } -async fn start( - session: &Arc, - requests: &mut mpsc::Receiver, - turn: &str, -) { - let sender = session.clone(); - let sending = tokio::spawn(async move { sender.send_user_msg("input".into(), false).await }); - requests.recv().await.unwrap().send(Ok(ProviderTurn { turn_id: turn.into() })).unwrap(); - assert_eq!(sending.await.unwrap().unwrap(), SendResult::Started); +async fn start(session: &ProviderAgentSession, turn: &str) { + assert_eq!(session.send_user_msg(turn.into(), false).await.unwrap(), SendResult::Started); } async fn next(events: &mut broadcast::Receiver) -> SessionEvent { @@ -88,26 +73,26 @@ async fn next(events: &mut broadcast::Receiver) -> SessionEvent { #[tokio::test] async fn stale_and_duplicate_notifications_cannot_settle_the_next_turn() { - let (provider, session, mut requests) = fixture().await; + let (provider, session) = fixture().await; let mut events = session.events(); - start(&session, &mut requests, "first").await; + start(&session, "first").await; assert!( - matches!(next(&mut events).await, SessionEvent::TurnStarted { provider_turn_id } if provider_turn_id == "first") + matches!(next(&mut events).await, SessionEvent::TurnStarted { provider_turn_id } if provider_turn_id == "native-first") ); let completed = ProviderNotification::TurnCompleted { thread_id: "thread".into(), - turn_id: "first".into(), + turn_id: "native-first".into(), status: "completed".into(), error: None, }; provider.notifications.send(completed.clone()).unwrap(); assert!( - matches!(next(&mut events).await, SessionEvent::TurnTerminal { provider_turn_id, outcome: TurnOutcome::Completed, error: None } if provider_turn_id == "first") + matches!(next(&mut events).await, SessionEvent::TurnTerminal { provider_turn_id, outcome: TurnOutcome::Completed, error: None } if provider_turn_id == "native-first") ); - start(&session, &mut requests, "second").await; + start(&session, "second").await; assert!( - matches!(next(&mut events).await, SessionEvent::TurnStarted { provider_turn_id } if provider_turn_id == "second") + matches!(next(&mut events).await, SessionEvent::TurnStarted { provider_turn_id } if provider_turn_id == "native-second") ); // The final current terminal is a stream barrier: all earlier frames have // been consumed when it arrives, so absence checks do not race the listener. @@ -116,14 +101,14 @@ async fn stale_and_duplicate_notifications_cannot_settle_the_next_turn() { .notifications .send(ProviderNotification::TurnStarted { thread_id: "thread".into(), - turn_id: "first".into(), + turn_id: "native-first".into(), }) .unwrap(); provider .notifications .send(ProviderNotification::TurnCompleted { thread_id: "another-thread".into(), - turn_id: "second".into(), + turn_id: "native-second".into(), status: "completed".into(), error: None, }) @@ -132,13 +117,13 @@ async fn stale_and_duplicate_notifications_cannot_settle_the_next_turn() { .notifications .send(ProviderNotification::TurnCompleted { thread_id: "thread".into(), - turn_id: "second".into(), + turn_id: "native-second".into(), status: "failed".into(), error: Some("provider rejected the model".into()), }) .unwrap(); assert!( - matches!(next(&mut events).await, SessionEvent::TurnTerminal { provider_turn_id, outcome: TurnOutcome::Failed, error: Some(error) } if provider_turn_id == "second" && error == "provider rejected the model") + matches!(next(&mut events).await, SessionEvent::TurnTerminal { provider_turn_id, outcome: TurnOutcome::Failed, error: Some(error) } if provider_turn_id == "native-second" && error == "provider rejected the model") ); assert!(matches!(events.try_recv(), Err(broadcast::error::TryRecvError::Empty))); session.close().await.unwrap(); @@ -147,10 +132,10 @@ async fn stale_and_duplicate_notifications_cannot_settle_the_next_turn() { #[tokio::test] async fn disconnect_latches_unavailability_and_does_not_prove_an_active_turn_stopped() { for active in [false, true] { - let (provider, session, mut requests) = fixture().await; + let (provider, session) = fixture().await; let mut events = session.events(); if active { - start(&session, &mut requests, "running").await; + start(&session, "running").await; assert!(matches!(next(&mut events).await, SessionEvent::TurnStarted { .. })); } provider.notifications.send(ProviderNotification::Disconnected).unwrap(); @@ -163,7 +148,7 @@ async fn disconnect_latches_unavailability_and_does_not_prove_an_active_turn_sto .unwrap(); if active { assert!( - matches!(next(&mut events).await, SessionEvent::TurnTerminal { provider_turn_id, outcome: TurnOutcome::Unknown, error: Some(error) } if provider_turn_id == "running" && error == "provider disconnected") + matches!(next(&mut events).await, SessionEvent::TurnTerminal { provider_turn_id, outcome: TurnOutcome::Unknown, error: Some(error) } if provider_turn_id == "native-running" && error == "provider disconnected") ); let error = session.close().await.unwrap_err(); assert!( diff --git a/src/runtime/builtin.rs b/src/runtime/builtin.rs index 64ee1846..dd9b5900 100644 --- a/src/runtime/builtin.rs +++ b/src/runtime/builtin.rs @@ -845,13 +845,7 @@ mod tests { #[tokio::test] async fn managed_ingests_while_old_execution_fence_is_unavailable() { let fixture = crate::writer::tests::Fixture::new(false); - let store = Arc::new( - StoreActor::start( - fixture.config.runtime.database().into(), - fixture.config.runtime.backups().into(), - ) - .unwrap(), - ); + let store = &fixture.store; let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let address = listener.local_addr().unwrap(); let requested_after_close = Arc::new(tokio::sync::Notify::new()); @@ -888,7 +882,7 @@ mod tests { .last_error .as_deref() .is_some_and(|error| error.contains("execution fence")); - if watching_fence && client_cursor(&store).is_ok_and(|cursor| cursor == 1) { + if watching_fence && client_cursor(store).is_ok_and(|cursor| cursor == 1) { break; } tokio::time::sleep(Duration::from_millis(20)).await; @@ -902,13 +896,6 @@ mod tests { let events = store.work_item_lifecycle_candidates("test-space".into(), "issue".into(), 1).unwrap(); assert_eq!(events[0].action, "closed"); - let turns: u64 = fixture - .db() - .query_row("SELECT COUNT(*) FROM turns", [], |row| row.get::<_, i64>(0)) - .unwrap() - .try_into() - .unwrap(); - assert_eq!(turns, 0); let requested_stop = halt.send(true); let result = runtime.await.unwrap(); assert!(requested_stop.is_ok(), "runtime exited before the requested stop: {result:#?}"); diff --git a/src/store/gh_writes.rs b/src/store/gh_writes.rs index ac5c9232..56187b56 100644 --- a/src/store/gh_writes.rs +++ b/src/store/gh_writes.rs @@ -45,7 +45,7 @@ pub struct GhWriteReceipt { #[derive(Debug, Clone)] pub struct NewImplementationRequest { pub root_intent_id: Option, - pub write: NewGhWriteIntent, + pub intent_id: String, pub comment_database_id: u64, pub comment_node_id: String, pub issue_node_id: String, @@ -176,57 +176,18 @@ pub(super) fn prepare_implementation_request( request: &NewImplementationRequest, ) -> Result { require_current_schema(database)?; - validate_gh_write(&request.write)?; - if request.write.operation != "pr_ensure" || request.comment_database_id == 0 { + if request.comment_database_id == 0 { return Err(StoreError::InvalidData("invalid implementation request intent".into())); } let mut connection = open_read_write(database)?; configure_connection(&connection)?; let transaction = connection.transaction()?; - let existing = transaction - .query_row( - "SELECT intent_id,request_digest FROM write_intents WHERE request_key=?1", - [&request.write.request_key], - |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)), - ) - .optional()?; - let intent_id = if let Some((intent_id, digest)) = existing { - if digest != request.write.request_digest { - return Err(StoreError::InvalidData(format!( - "Implementation Request {} was already planned with different arguments", - request.comment_database_id - ))); - } - intent_id - } else { - let intent_id = Uuid::now_v7().to_string(); - let now = now_rfc3339(); - transaction.execute( - "INSERT INTO write_intents( - intent_id,operation,request_digest,lifecycle,attempts,created_at,updated_at, - request_key,repository,target,profile_id,role,payload,source_binding - ) VALUES (?1,'pr_ensure',?2,'pending',0,?3,?3,?4,?5,?6,?7,?8,?9,?10)", - params![ - intent_id, - request.write.request_digest, - now, - request.write.request_key, - request.write.repository, - request.write.target, - request.write.profile_id, - request.write.role, - request.write.payload, - request - .write - .source - .as_ref() - .map(serde_json::to_string) - .transpose() - .map_err(|e| StoreError::InvalidData(e.to_string()))?, - ], - )?; - intent_id - }; + let intent_id = &request.intent_id; + let repository: String = transaction.query_row( + "SELECT repository FROM write_intents WHERE intent_id=?1 AND operation='pr_ensure'", + [intent_id], + |row| row.get(0), + )?; let now = now_rfc3339(); let inserted = transaction.execute( "INSERT OR IGNORE INTO implementation_requests( @@ -235,7 +196,7 @@ pub(super) fn prepare_implementation_request( ) VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,'planned',?11)", params![ intent_id, - request.write.repository, + repository, sqlite_u64(request.comment_database_id, "Implementation Request comment ID",)?, request.comment_node_id, request.issue_node_id, @@ -250,7 +211,7 @@ pub(super) fn prepare_implementation_request( if inserted == 1 && let Some(root) = &request.root_intent_id { - let valid: bool = transaction.query_row("SELECT EXISTS(SELECT 1 FROM implementation_requests WHERE intent_id=?1 AND root_intent_id IS NULL AND repository=?2 AND issue_node_id=?3 AND head_ref=?4 AND base_ref=?5 AND pr_profile_id=?6 AND pull_request_node_id IS NOT NULL AND pull_request_number IS NOT NULL)",params![root,request.write.repository,request.issue_node_id,request.head_ref,request.base_ref,request.pr_profile_id],|r|r.get(0))?; + let valid: bool = transaction.query_row("SELECT EXISTS(SELECT 1 FROM implementation_requests WHERE intent_id=?1 AND root_intent_id IS NULL AND repository=?2 AND issue_node_id=?3 AND head_ref=?4 AND base_ref=?5 AND pr_profile_id=?6 AND pull_request_node_id IS NOT NULL AND pull_request_number IS NOT NULL)",params![root,repository,request.issue_node_id,request.head_ref,request.base_ref,request.pr_profile_id],|r|r.get(0))?; if !valid { return Err(StoreError::InvalidData( "continuation differs from the managed implementation identity".into(), @@ -258,13 +219,11 @@ pub(super) fn prepare_implementation_request( } transaction.execute("UPDATE implementation_requests SET root_intent_id=?2,stage='activation_pending',bootstrap_authored_at=(SELECT bootstrap_authored_at FROM implementation_requests WHERE intent_id=?2),pull_request_database_id=(SELECT pull_request_database_id FROM implementation_requests WHERE intent_id=?2),pull_request_node_id=(SELECT pull_request_node_id FROM implementation_requests WHERE intent_id=?2),pull_request_number=(SELECT pull_request_number FROM implementation_requests WHERE intent_id=?2) WHERE intent_id=?1",params![intent_id,root])?; } - enqueue(&transaction, &intent_id)?; - let receipt = - implementation_request_receipt_on(&transaction, &intent_id)?.ok_or_else(|| { - StoreError::InvalidData(format!( - "implementation request {intent_id} disappeared during prepare" - )) - })?; + let receipt = implementation_request_receipt_on(&transaction, intent_id)?.ok_or_else(|| { + StoreError::InvalidData(format!( + "implementation request {intent_id} disappeared during prepare" + )) + })?; transaction.commit()?; Ok(receipt) } diff --git a/src/store/gh_writes/tests.rs b/src/store/gh_writes/tests.rs index 981ce484..7d69c05b 100644 --- a/src/store/gh_writes/tests.rs +++ b/src/store/gh_writes/tests.rs @@ -51,34 +51,25 @@ fn invalid_data(error: &StoreError, expected: &str) { } #[test] -fn offline_acceptance_is_atomic_idempotent_and_publicly_queryable() { +fn failed_outbox_enqueue_rolls_back_the_accepted_intent() { let db = Database::new(); let store = db.store(); - let write = intent("comment_create"); - let first = store.prepare_gh_write(write.clone()).unwrap(); - assert!(first.request_id.starts_with("request-")); - assert_ne!(first.request_id, first.intent_id); - assert_eq!(first.request_id, store.prepare_gh_write(write.clone()).unwrap().request_id); - let mut conflict = write; - conflict.request_digest = "b".repeat(64); - invalid_data( - &store.prepare_gh_write(conflict).unwrap_err(), - "already used for a different payload", + db.connect() + .execute_batch( + "CREATE TRIGGER refuse_outbox BEFORE INSERT ON github_write_outbox + BEGIN SELECT RAISE(ABORT, 'outbox unavailable'); END;", + ) + .unwrap(); + let error = store.prepare_gh_write(intent("comment_create")).unwrap_err(); + assert!( + matches!(error, StoreError::Sqlite(ref cause) if cause.to_string().contains("outbox unavailable")), + "{error}" ); drop(store); - let reopened = db.store(); - assert_eq!( - reopened.gh_write_receipt(first.request_id).unwrap().unwrap().intent_id, - first.intent_id - ); - for table in ["write_intents", "github_write_outbox"] { - assert_eq!( - db.connect() - .query_row(&format!("SELECT COUNT(*) FROM {table}"), [], |r| r.get::<_, i64>(0)) - .unwrap(), - 1 - ); - } + let connection = db.connect(); + let stranded: i64 = + connection.query_row("SELECT count(*) FROM write_intents", [], |row| row.get(0)).unwrap(); + assert_eq!(stranded, 0, "a failed enqueue cannot leave a durable request"); } #[test] @@ -190,11 +181,10 @@ fn legacy_cli_pending_uncertain_sending_all_get_one_execution_obligation() { fn ensure_plan_and_progress_freeze_and_resume_without_replanning() { let db = Database::new(); let store = db.store(); - let write = intent("pr_ensure"); - let receipt = store.prepare_gh_write(write.clone()).unwrap(); + let receipt = store.prepare_gh_write(intent("pr_ensure")).unwrap(); let mut plan = NewImplementationRequest { root_intent_id: None, - write, + intent_id: receipt.intent_id.clone(), comment_database_id: 7, comment_node_id: "comment".into(), issue_node_id: "issue".into(), @@ -215,24 +205,18 @@ fn ensure_plan_and_progress_freeze_and_resume_without_replanning() { 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"] { - store - .record_implementation_progress( - receipt.intent_id.clone(), - 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 = - store.implementation_request_receipt(receipt.intent_id.clone()).unwrap().unwrap(); - assert_eq!(resumed.stage, stage); - assert_eq!(resumed.pull_request_number, Some(9)); - } + store + .record_implementation_progress( + receipt.intent_id.clone(), + ImplementationProgress { + stage: "pull_request_ready", + bootstrap_commit_sha: None, + pull_request_database_id: Some(88), + pull_request_node_id: Some("pr".into()), + pull_request_number: Some(9), + }, + ) + .unwrap(); invalid_data( &store .record_implementation_progress( @@ -246,6 +230,6 @@ fn ensure_plan_and_progress_freeze_and_resume_without_replanning() { }, ) .unwrap_err(), - "cannot move backward from activation_pending to planned", + "cannot move backward from pull_request_ready to planned", ); } diff --git a/src/store/handoff_inputs.rs b/src/store/handoff_inputs.rs index 1c3dbb77..41d596c3 100644 --- a/src/store/handoff_inputs.rs +++ b/src/store/handoff_inputs.rs @@ -163,10 +163,7 @@ mod migration_tests { drop(db); let store = StoreActor::start(database.clone(), root.join("backups")).unwrap(); - assert_eq!( - store.apply().unwrap().applied, - (19..=crate::store::DATABASE_SCHEMA_VERSION).collect::>() - ); + store.apply().unwrap(); let db = open_read_write(&database).unwrap(); let pending_target: String = db.query_row( "SELECT target_assignment_id FROM pr_handoffs WHERE intent_id='pending' AND event_id IS NULL", diff --git a/src/store/implementation_delivery.rs b/src/store/implementation_delivery.rs index 29c2fdf0..7984f738 100644 --- a/src/store/implementation_delivery.rs +++ b/src/store/implementation_delivery.rs @@ -150,12 +150,7 @@ mod tests { } drop(db); let store = StoreActor::start(database.clone(), root.join("backups")).unwrap(); - let result = store.apply().unwrap(); - assert_eq!( - result.applied, - (12..=crate::store::DATABASE_SCHEMA_VERSION).collect::>() - ); - assert!(result.backup.is_some()); + store.apply().unwrap(); let db = open_read_write(&database).unwrap(); for (id, expected) in [("missing", "pending"), ("complete", "applied"), ("unpublished", "applied")] @@ -186,10 +181,6 @@ mod tests { .unwrap(), "pr" ); - assert_eq!( - db.query_row("PRAGMA integrity_check", [], |r| r.get::<_, String>(0)).unwrap(), - "ok" - ); drop(db); drop(store); std::fs::remove_dir_all(root).unwrap(); diff --git a/src/store/mod.rs b/src/store/mod.rs index e455cb21..769e9be3 100644 --- a/src/store/mod.rs +++ b/src/store/mod.rs @@ -829,7 +829,7 @@ impl StoreActor { receiver.recv().map_err(|_| StoreError::ActorStopped)? } - pub fn advance_scheduler(&self) -> Result { + pub fn advance_scheduler(&self) -> Result<(), StoreError> { let (reply, receiver) = mpsc::channel(); self.sender .send(Command::AdvanceScheduler(reply)) @@ -1638,7 +1638,7 @@ enum Command { ), MentionCandidates(String, usize, Sender, StoreError>>), ResolveMention(String, bool, SchedulerPolicy, Sender>), - AdvanceScheduler(Sender>), + AdvanceScheduler(Sender>), RuntimeStatus(Sender>), ExecutionProgress(Sender>), PublicationProgress(Sender>), @@ -3134,16 +3134,16 @@ fn resolve_mention( Ok(()) } -fn advance_scheduler(database: &Path) -> Result { +fn advance_scheduler(database: &Path) -> Result<(), StoreError> { require_current_schema(database)?; let connection = open_read_write(database)?; configure_connection(&connection)?; - let changed = connection.execute( + connection.execute( "UPDATE wake_batches SET lifecycle='runnable',updated_at=?1 WHERE lifecycle='pending' AND quiet_deadline<=?1", [now_rfc3339()], )?; - Ok(u64::try_from(changed).expect("SQLite change count fits u64")) + Ok(()) } fn runtime_status(database: &Path) -> Result { diff --git a/src/store/operational_status_migration_tests.rs b/src/store/operational_status_migration_tests.rs index 8b4d0d56..d4d57727 100644 --- a/src/store/operational_status_migration_tests.rs +++ b/src/store/operational_status_migration_tests.rs @@ -19,9 +19,7 @@ fn status_convergence_upgrades_an_already_published_schema12_failure_without_a_n db.execute("INSERT INTO status_comments VALUES('item','profile',1,'status-node','7120481524','old-publication',?1,'applied','2001-01-01T00:00:00Z')",["b".repeat(64)]).unwrap(); drop(db); let store = StoreActor::start(database.clone(), root.join("backups")).unwrap(); - let migrated = store.apply().unwrap(); - assert_eq!(migrated.applied, (13..=crate::store::DATABASE_SCHEMA_VERSION).collect::>()); - assert!(migrated.backup.is_some()); + store.apply().unwrap(); assert_eq!( store.reconcile_operational_comment_roles("item".into(), vec![]).unwrap(), ["status-node".to_owned()].into() @@ -66,10 +64,6 @@ fn status_convergence_upgrades_an_already_published_schema12_failure_without_a_n .unwrap(), 1 ); - assert_eq!( - db.query_row("PRAGMA integrity_check", [], |r| r.get::<_, String>(0)).unwrap(), - "ok" - ); let violations: i64 = db .query_row("SELECT count(*) FROM pragma_foreign_key_check", params![], |r| r.get(0)) .unwrap(); @@ -120,10 +114,7 @@ fn role_migration_preserves_legacy_evidence_and_requires_a_unique_identity() { } drop(db); let store = StoreActor::start(database.clone(), root.join("backups")).unwrap(); - assert_eq!( - store.apply().unwrap().applied, - (18..=crate::store::DATABASE_SCHEMA_VERSION).collect::>() - ); + store.apply().unwrap(); let candidate = |node, body, created| { OperationalCommentCandidate::from_discussion("app", Some("app"), node, Some(body), created) .unwrap() diff --git a/src/store/reconciliation.rs b/src/store/reconciliation.rs index ea127543..3f6c53d0 100644 --- a/src/store/reconciliation.rs +++ b/src/store/reconciliation.rs @@ -66,8 +66,7 @@ pub fn record( mod tests { use super::*; - fn database() -> Connection { - let db = Connection::open_in_memory().unwrap(); + fn database(db: Connection) -> Connection { db.execute_batch("CREATE TABLE repositories(node_id TEXT,name_with_owner TEXT); CREATE TABLE work_items(node_id TEXT,repository_node_id TEXT,kind TEXT,number INTEGER,state TEXT,observed_at INTEGER); CREATE TABLE assignments(work_item_node_id TEXT,lifecycle TEXT); @@ -86,22 +85,28 @@ mod tests { } #[test] - fn hot_cold_observations_and_finalization() { - let db = database(); + fn traversal_deadlines_survive_observations_and_restart() { + let path = std::env::temp_dir() + .join(format!("braid-reconciliation-{}.sqlite", uuid::Uuid::now_v7())); + let db = database(Connection::open(&path).unwrap()); for id in ["open", "closed", "final"] { record(&db, id, 100, true).unwrap(); } db.execute("UPDATE work_items SET observed_at=500", []).unwrap(); + drop(db); + let db = Connection::open(&path).unwrap(); assert!(due_ids(&db, 159).is_empty()); assert_eq!(due_ids(&db, 160), ["final", "open"]); assert_eq!(due_ids(&db, 1900), ["closed", "final", "open"]); db.execute("UPDATE assignments SET lifecycle='retired'", []).unwrap(); assert_eq!(due_ids(&db, 160), ["open"]); + drop(db); + std::fs::remove_file(path).unwrap(); } #[test] fn assignment_facts_and_repository_rotation() { - let db = database(); + let db = database(Connection::open_in_memory().unwrap()); db.execute_batch("INSERT INTO repositories VALUES('other','o/other'); INSERT INTO work_items(node_id,repository_node_id,kind,number,state) VALUES('other','other','issue',4,'CLOSED'); INSERT INTO assignments VALUES('closed','materializing');").unwrap(); @@ -134,7 +139,7 @@ mod tests { #[test] fn failed_traversal_backs_off_without_losing_the_last_success() { - let db = database(); + let db = database(Connection::open_in_memory().unwrap()); // This closed item has never succeeded. Its failure cannot delay other // items, start the cold interval, or retry before the hot interval. record(&db, "closed", 100, false).unwrap(); @@ -154,26 +159,4 @@ mod tests { assert!(!due_ids(&db, 1959).iter().any(|id| id == "open")); assert!(due_ids(&db, 1960).iter().any(|id| id == "open")); } - - #[test] - fn success_survives_connection_restart() { - let path = std::env::temp_dir() - .join(format!("braid-reconciliation-{}.sqlite", uuid::Uuid::now_v7())); - let db = database(); - let mut backup = Connection::open(&path).unwrap(); - rusqlite::backup::Backup::new(&db, &mut backup) - .unwrap() - .run_to_completion(100, std::time::Duration::ZERO, None) - .unwrap(); - drop(backup); - { - let reopened = Connection::open(&path).unwrap(); - record(&reopened, "closed", 100, true).unwrap(); - } - let reopened = Connection::open(&path).unwrap(); - assert!(!due(&reopened, 1899, 60).unwrap().iter().any(|w| w.node_id == "closed")); - assert!(due(&reopened, 1900, 60).unwrap().iter().any(|w| w.node_id == "closed")); - drop(reopened); - std::fs::remove_file(path).unwrap(); - } } diff --git a/src/store/scheduler_tests.rs b/src/store/scheduler_tests.rs index 4bed12ea..a6d587d9 100644 --- a/src/store/scheduler_tests.rs +++ b/src/store/scheduler_tests.rs @@ -36,18 +36,14 @@ fn ordinary_comment(number: u32) -> IngressEvent { fn eighth_distinct_input_releases_the_batch_without_waiting_for_quiet() { let f = Fixture::new(true); let policy = SchedulerPolicy { quiet_seconds: 3600, event_threshold: 8 }; - for number in 1..=7 { - let admitted = f.store.ingest_event(ordinary_comment(number), policy).unwrap(); - assert!(admitted.event_id.is_some()); - assert_eq!(admitted.batch_lifecycle.as_deref(), Some("pending")); + for number in 1..=6 { + f.store.ingest_event(ordinary_comment(number), policy).unwrap(); } - assert_eq!(f.store.advance_scheduler().unwrap(), 0); - assert!( - f.store - .claim_runnable_turn("issue".into(), "issue-codex".into(), vec!["provider".into()]) - .unwrap() - .is_none() - ); + // A new ordinary input re-arms an expiring quiet window. + f.db().execute("UPDATE wake_batches SET quiet_deadline='2000-01-01T00:00:00Z'", []).unwrap(); + let seventh = f.store.ingest_event(ordinary_comment(7), policy).unwrap(); + assert_eq!(seventh.batch_lifecycle.as_deref(), Some("pending")); + f.store.advance_scheduler().unwrap(); // Both transport redelivery and a new delivery of the same object version // must leave the threshold count at seven. assert!(f.store.ingest_event(ordinary_comment(7), policy).unwrap().duplicate); @@ -57,10 +53,6 @@ fn eighth_distinct_input_releases_the_batch_without_waiting_for_quiet() { assert!(!repeated.duplicate); assert!(repeated.event_id.is_none()); assert_eq!(repeated.event_lifecycle.as_deref(), Some("superseded")); - let status = f.store.runtime_status().unwrap(); - assert_eq!((status.pending_batches, status.runnable_batches), (1, 0)); - assert_eq!(status.batches.len(), 1); - assert_eq!(status.batches[0].event_count, 7); assert!( f.store .claim_runnable_turn("issue".into(), "issue-codex".into(), vec!["provider".into()]) @@ -70,7 +62,6 @@ fn eighth_distinct_input_releases_the_batch_without_waiting_for_quiet() { let eighth = f.store.ingest_event(ordinary_comment(8), policy).unwrap(); assert_eq!(eighth.batch_lifecycle.as_deref(), Some("runnable")); - assert_eq!(f.store.runtime_status().unwrap().batches[0].event_count, 8); let claim = f .store .claim_runnable_turn("issue".into(), "issue-codex".into(), vec!["provider".into()]) @@ -78,53 +69,4 @@ fn eighth_distinct_input_releases_the_batch_without_waiting_for_quiet() { .expect("the eighth distinct input is sufficient without a clock advance"); assert_eq!(Some(claim.batch_id), eighth.batch_id); assert_eq!(claim.references, (1..=8).map(|n| format!("Comment {n}")).collect::>()); - assert_eq!(claim.trigger_kind, "wake_batch"); - assert!(!claim.trusted_mention); - assert!( - f.store - .claim_runnable_turn("issue".into(), "issue-codex".into(), vec!["provider".into()]) - .unwrap() - .is_none() - ); - assert!(f.store.runtime_status().unwrap().batches.is_empty()); -} - -#[test] -fn quiet_deadline_releases_a_subthreshold_batch_only_when_due() { - let f = Fixture::new(true); - let policy = SchedulerPolicy { quiet_seconds: 3600, event_threshold: 8 }; - let admitted = f.store.ingest_event(ordinary_comment(1), policy).unwrap(); - assert_eq!(admitted.batch_lifecycle.as_deref(), Some("pending")); - assert_eq!(f.store.advance_scheduler().unwrap(), 0); - assert!( - f.store - .claim_runnable_turn("issue".into(), "issue-codex".into(), vec!["provider".into()]) - .unwrap() - .is_none() - ); - // Move only the persisted deadline across the clock boundary; real ingestion, - // scheduler advancement and claiming still own every lifecycle transition. - assert_eq!( - f.db() - .execute( - "UPDATE wake_batches SET quiet_deadline='2000-01-01T00:00:00Z' WHERE batch_id=?1", - [admitted.batch_id.as_deref().unwrap()], - ) - .unwrap(), - 1 - ); - assert_eq!(f.store.advance_scheduler().unwrap(), 1); - assert_eq!(f.store.advance_scheduler().unwrap(), 0); - let status = f.store.runtime_status().unwrap(); - assert_eq!((status.pending_batches, status.runnable_batches), (0, 1)); - assert_eq!(status.batches[0].event_count, 1); - let claim = f - .store - .claim_runnable_turn("issue".into(), "issue-codex".into(), vec!["provider".into()]) - .unwrap() - .expect("an expired quiet window is sufficient below the count threshold"); - assert_eq!(Some(claim.batch_id), admitted.batch_id); - assert_eq!(claim.references, vec!["Comment 1"]); - assert_eq!(claim.trigger_kind, "wake_batch"); - assert!(!claim.trusted_mention); } diff --git a/src/store/schema_tests.rs b/src/store/schema_tests.rs index 6f53da18..689baba1 100644 --- a/src/store/schema_tests.rs +++ b/src/store/schema_tests.rs @@ -33,8 +33,7 @@ fn migration_entry_points_reject_incompatible_databases_without_changing_bytes() let backups = root.0.join("backups"); if !matches!(case, InvalidSchema::Foreign) { let store = StoreActor::start(database.clone(), backups.clone()).unwrap(); - assert_eq!(store.apply().unwrap().current_schema, DATABASE_SCHEMA_VERSION); - assert!(store.plan().unwrap().pending.is_empty()); + store.apply().unwrap(); drop(store); } let db = Connection::open(&database).unwrap(); @@ -75,7 +74,6 @@ fn migration_entry_points_reject_incompatible_databases_without_changing_bytes() db.execute_batch("PRAGMA wal_checkpoint(TRUNCATE); PRAGMA journal_mode=DELETE;").unwrap(); drop(db); let before = std::fs::read(&database).unwrap(); - assert!(!before.is_empty()); let store = StoreActor::start(database.clone(), backups).unwrap(); for apply in [false, true] { let result = if apply { store.apply().map(|_| ()) } else { store.plan().map(|_| ()) }; diff --git a/src/telemetry.rs b/src/telemetry.rs index 5940c3dc..395b6518 100644 --- a/src/telemetry.rs +++ b/src/telemetry.rs @@ -417,7 +417,7 @@ pub fn emit_provider_payload( native_turn: Option<&str>, stream: &str, payload: &str, -) -> bool { +) { let span = observation_span(native_thread, native_turn); let correlated = span.is_some(); let generation = evidence_health().runtime_generation; @@ -476,7 +476,6 @@ pub fn emit_provider_payload( "sampled complete provider evidence" ); } - sampled } /// Cleanup has an execution identity, not a fabricated provider session/turn. diff --git a/src/telemetry/tests.rs b/src/telemetry/tests.rs index e234f527..8f8c8e5d 100644 --- a/src/telemetry/tests.rs +++ b/src/telemetry/tests.rs @@ -1,20 +1,18 @@ use crate::{config, telemetry}; -use opentelemetry::trace::TraceContextExt as _; +use axum::{ + Router, + body::Bytes, + http::{StatusCode, Uri, header}, + routing::post, +}; 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 _; +use std::sync::mpsc; +use tokio::process::Command; const SENTINEL: &str = "PRIVATE_PAYLOAD_SENTINEL_"; const RESPONSE_SENTINEL: &str = "PRIVATE_COLLECTOR_RESPONSE_SENTINEL"; @@ -56,34 +54,26 @@ fn telemetry_child() { profile_digest: "digest-test".into(), }); telemetry::begin_turn("session-test", "turn-test"); + telemetry::emit_provider_payload("pi", "session-test", None, "request", &payload); 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 - ), - std::env::var("BRAID_TEST_RETAIN").unwrap() == "1" - ); - } + telemetry::emit_provider_payload( + "pi", + "session-test", + Some("native-turn-test"), + "stdout", + &payload, + ); 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: &format!("summary:{payload}"), - credential: &format!("credential:{payload}"), - provider_transcript: &format!("transcript:{payload}"), - webhook_payload: &format!("webhook:{payload}"), - local_path: &format!("/diagnostic/{payload}"), - }), - sampled - ); + telemetry::emit_payload_event(&telemetry::PayloadEvidence { + github_body: &payload, + github_summary: &format!("summary:{payload}"), + credential: &format!("credential:{payload}"), + provider_transcript: &format!("transcript:{payload}"), + webhook_payload: &format!("webhook:{payload}"), + local_path: &format!("/diagnostic/{payload}"), + }); 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()); @@ -95,146 +85,96 @@ fn telemetry_child() { guard.shutdown().unwrap(); } -#[test] -fn telemetry_routes_complete_evidence_only_to_otlp() { - for format in ["text", "json"] { - for (ratio, incident, retained) in [("0", false, "0"), ("1", false, "1"), ("0", true, "1")] - { - verify(format, ratio, incident, retained, false, false, "trace"); - } - } - verify("json", "1", false, "1", false, true, "trace"); +#[tokio::test] +async fn telemetry_routes_complete_evidence_only_to_otlp() { + verify(Scenario::Runtime, "text", "0", StatusCode::OK, false).await; + verify(Scenario::Incident, "json", "0", StatusCode::OK, true).await; } -// 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", false, "1", true, true, rust_log); - verify(format, "1", false, "1", true, false, rust_log); - } - } +// The internal-logs CI feature makes the SDK emit its raw rejection diagnostic. +#[tokio::test] +async fn telemetry_isolates_collector_rejection_bodies_from_ordinary_diagnostics() { + // A redirect without Location reaches OTLP's error diagnostic with the body intact. + verify(Scenario::Runtime, "json", "1", StatusCode::MULTIPLE_CHOICES, true).await; + verify(Scenario::Probe, "text", "1", StatusCode::MULTIPLE_CHOICES, true).await; } -type Requests = Arc)>>>; +#[derive(Clone, Copy, PartialEq, Eq)] +enum Scenario { + Runtime, + Incident, + Probe, +} -fn verify( - format: &str, - ratio: &str, - incident: bool, - retained: &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(); +async fn verify(scenario: Scenario, format: &str, ratio: &str, status: StatusCode, retained: bool) { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.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]); + let (received, requests) = mpsc::channel(); + let probe = scenario == Scenario::Probe; + let app = Router::new().route( + "/v1/{signal}", + post(move |uri: Uri, body: Bytes| { + let status = if probe && uri.path() == "/v1/metrics" { StatusCode::OK } else { status }; + received.send((uri.path().to_owned(), body.to_vec())).unwrap(); + async move { + let response = if status.is_success() { "" } else { RESPONSE_SENTINEL }; + (status, [(header::CONTENT_TYPE, "application/x-protobuf")], response) } - 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 server = tokio::spawn(axum::serve(listener, app).into_future()); let mut command = Command::new(std::env::current_exe().unwrap()); command .args(["--ignored", "--exact", "telemetry::tests::telemetry_child", "--nocapture"]) .env("BRAID_TEST_OTLP", &endpoint) .env("BRAID_TEST_FORMAT", format) .env("BRAID_TEST_RATIO", ratio) - .env("BRAID_TEST_INCIDENT", if incident { "1" } else { "0" }) - .env("BRAID_TEST_RETAIN", retained) + .env("BRAID_TEST_INCIDENT", if scenario == Scenario::Incident { "1" } else { "0" }) .env_remove("BRAID_TEST_PROBE") - .env("RUST_LOG", rust_log); + .env("RUST_LOG", "trace,opentelemetry-otlp=trace,opentelemetry_sdk=trace"); if probe { command.env("BRAID_TEST_PROBE", "1"); } - let output = command.output().unwrap(); - done.store(true, Ordering::Relaxed); - server.join().unwrap(); + let output = command.output().await.unwrap(); + server.abort(); 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})" - ); + assert!(!stderr.contains(SENTINEL), "payload leaked to {format} stderr"); + assert!(!stderr.contains(RESPONSE_SENTINEL), "collector response leaked to {format} stderr"); if !probe { assert!(stderr.contains("ordinary diagnostic after evidence"), "{stderr}"); } - if fail { + if !status.is_success() { 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}"); + let failed = format!("signal={signal} stage=sdk_export outcome=failed"); + assert_eq!(stderr.contains(&failed), !probe || signal != "metrics", "{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_probe(&output.stdout); } } - verify_otlp(&requests.lock().unwrap(), retained, probe); + verify_otlp(&requests.try_iter().collect::>(), retained, probe); +} + +fn verify_probe(output: &[u8]) { + let stdout = String::from_utf8_lossy(output); + 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, succeeded) in [("logs", false), ("traces", false), ("metrics", true)] { + let report = signals.iter().find(|report| report["signal"] == signal).unwrap(); + assert_eq!(report["successful_batches"], u64::from(succeeded), "{signal}"); + assert_eq!(report["failed_batches"], u64::from(!succeeded), "{signal}"); + assert_eq!(report["failed_records"].as_u64().unwrap() > 0, !succeeded, "{signal}"); + assert!(report["queue_dropped_records"].is_null(), "{signal}"); + } } -fn verify_otlp(requests: &[(String, Vec)], ratio: &str, probe: bool) { +fn verify_otlp(requests: &[(String, Vec)], retained: bool, probe: bool) { let mut log_records = Vec::new(); let mut span_ids = Vec::new(); let mut metrics = Vec::new(); @@ -280,10 +220,19 @@ fn verify_otlp(requests: &[(String, Vec)], ratio: &str, probe: bool) { other => panic!("unexpected signal {other}"), } } - verify_payload_records(log_records, &span_ids, ratio == "1", probe); - if ratio == "0" { + if !retained { + use opentelemetry_proto::tonic::common::v1::any_value::Value; + assert!(span_ids.is_empty()); + assert!( + log_records.iter().any(|record| matches!( + record.body.as_ref().and_then(|body| body.value.as_ref()), + Some(Value::StringValue(message)) if message == "session evidence sampling decision" + )), + "ordinary session observation must reach OTLP even with evidence sampling disabled" + ); } + verify_payload_records(log_records, &span_ids, retained, probe); let counter = if probe { "braid.telemetry.probes" } else { "braid.runtime.transitions" }; let metric = metrics .iter() @@ -303,7 +252,7 @@ fn verify_payload_records( ) { let payload = format!("{SENTINEL}{}END", "x".repeat(100_000)); let mut expected_streams: std::collections::BTreeSet<&str> = if retained && !probe { - ["request", "stdout", "stderr", "cleanup.stdout", "cleanup.stderr"].into() + ["request", "stdout", "cleanup.stdout", "cleanup.stderr"].into() } else { std::collections::BTreeSet::new() }; diff --git a/src/tunnel/tests.rs b/src/tunnel/tests.rs index 0a06a2ea..6b3d7a6e 100644 --- a/src/tunnel/tests.rs +++ b/src/tunnel/tests.rs @@ -8,28 +8,6 @@ async fn start_fake_tunnel(executable: &Path) -> Result&2\nexec /usr/bin/tail -f /dev/null\n").unwrap(); - std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o700)).unwrap(); - let mut tunnel = start_fake_tunnel(&executable).await.unwrap(); - if tunnel.failure().is_none() { - tokio::time::timeout(Duration::from_secs(2), tunnel.failure.changed()) - .await - .unwrap() - .unwrap(); - } - assert_eq!(tunnel.failure(), Some("tunnel_not_found")); - assert!(!tunnel.has_exited().unwrap()); - tunnel.stop().await.unwrap(); - std::fs::remove_dir_all(directory).unwrap(); -} - #[cfg(unix)] #[derive(Clone, Copy)] enum Registration { @@ -45,7 +23,7 @@ fn tree_script(root: &std::path::Path, registration: Registration) -> std::path: let quote = |text: &str| format!("'{}'", text.replace('\'', "'\\''")); let script = root.join("wrangler"); let output = if matches!(registration, Registration::Success) { - "printf '%s\\n' 'https://tree.trycloudflare.com' 'Registered tunnel connection'" + "printf '%s\\n' 'https://tree.trycloudflare.com' 'Registered tunnel connection'; printf '%s\\n' 'ERR Unauthorized: Tunnel not found' >&2" } else { "printf '%s\\n' 'starting without a public URL'" }; @@ -60,7 +38,7 @@ fn tree_script(root: &std::path::Path, registration: Registration) -> std::path: #[cfg(unix)] #[tokio::test] -async fn stopping_a_tunnel_reaps_the_owned_wrapper_and_grandchild_group() { +async fn a_live_tunnel_reports_loss_of_registration_and_stops_its_process_group() { use nix::{ errno::Errno, sys::signal::{kill, killpg}, @@ -68,13 +46,21 @@ async fn stopping_a_tunnel_reaps_the_owned_wrapper_and_grandchild_group() { }; let root = std::env::temp_dir().join(format!("braid-tunnel-tree-{}", Uuid::now_v7())); let script = tree_script(&root, Registration::Success); - let tunnel = start_fake_tunnel(&script).await.unwrap(); + let mut tunnel = start_fake_tunnel(&script).await.unwrap(); let group = Pid::from_raw(i32::try_from(tunnel.child.id().unwrap()).unwrap()); let leaf = Pid::from_raw( std::fs::read_to_string(root.join("leaf.pid")).unwrap().trim().parse().unwrap(), ); assert_ne!(group, getpgrp(), "the Tunnel must not share Braid's process group"); assert!(kill(leaf, None).is_ok()); + if tunnel.failure().is_none() { + tokio::time::timeout(Duration::from_secs(2), tunnel.failure.changed()) + .await + .unwrap() + .unwrap(); + } + assert_eq!(tunnel.failure(), Some("tunnel_not_found")); + assert!(!tunnel.has_exited().unwrap()); tunnel.stop().await.unwrap(); assert_eq!(killpg(group, None), Err(Errno::ESRCH)); assert_eq!(kill(leaf, None), Err(Errno::ESRCH)); diff --git a/src/webhook_tests.rs b/src/webhook_tests.rs index e0ffa615..ff7ecb60 100644 --- a/src/webhook_tests.rs +++ b/src/webhook_tests.rs @@ -109,10 +109,6 @@ fn comment_edits_compare_visible_suffix_instead_of_discarding_the_html_block_lin edited["comment"]["body"] = json!(body); let admitted = parse(&edited, "issue_comment"); assert_eq!(admitted.kind, expected, "{body}"); - assert_eq!( - admitted.visible_body.as_deref(), - Some(if expected == EventKind::Noop { " current design" } else { " changed design" }) - ); assert_eq!(admitted.requires_attention, expected == EventKind::Invalidate); } } 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 b694955f..bd3d49d3 100644 --- a/src/writer/tests.rs +++ b/src/writer/tests.rs @@ -97,9 +97,6 @@ impl Fixture { .execute("UPDATE github_write_outbox SET next_attempt_at='2000-01-01T00:00:00Z'", []) .unwrap(); } - fn lose_comment_acknowledgement(&self) { - self.db().execute_batch("UPDATE github_write_outbox SET lifecycle='sending',remote_database_id=NULL; UPDATE write_intents SET lifecycle='pending',remote_database_id=NULL,remote_node_id=NULL;").unwrap(); - } fn receipt(&self, id: &str) -> GhWriteReceipt { self.store.gh_write_receipt(id.into()).unwrap().unwrap() } @@ -140,6 +137,7 @@ struct Remote { head_created: bool, comments: Vec, comment_reads: usize, + lose_comment_response: bool, writes: usize, limit: Option, target_status: Option, @@ -172,7 +170,9 @@ async fn server( .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; 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"})) })) @@ -274,24 +274,33 @@ 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); - // Reopen SQLite with a fresh actor; recovery may read a completed remote - // mutation even when the installation has lost write permission. task.abort(); - let (github, task) = server(remote.clone(), false).await; - fixture.lose_comment_acknowledgement(); - assert!(fixture.receipt(&receipt.request_id).remote_database_id.is_none()); + // A read-only installation can recognize a POST whose response was lost. let fixture = fixture.reopen(); fixture.store.recover_writes().unwrap(); - fixture.drain(github).await; + 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"); + 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"); assert_eq!(remote.lock().unwrap().writes, 1); task.abort(); } @@ -311,44 +320,6 @@ async fn uncertain_comment_recovery_scans_the_remote_conversation_once() { http.abort(); } -#[tokio::test] -async fn issue_source_adopts_an_existing_pr_with_one_native_activation() { - let fixture = Fixture::new(true); - 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"); - 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 completed_turn_can_publish_but_source_fences_reject_before_mutation() { for fence in ["completed", "reset", "invalidation", "replacement"] { @@ -431,6 +402,9 @@ async fn initial_ensure_bootstrap_pr_association_and_restart_do_not_duplicate_mu }, ) .unwrap(); + 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 { create_pr: true, authority: Authority::AssociationUnavailable, @@ -493,62 +467,51 @@ async fn initial_ensure_bootstrap_pr_association_and_restart_do_not_duplicate_mu #[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 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(); - 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 { - 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 fence == "valid" { "applied" } else { "rejected" }, - "{:?}", - result.last_error + 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!( + result + .last_error + .as_deref() + .unwrap() + .contains("publication source was invalidated or superseded"), + "{result:?}" ); - let state = remote.lock().unwrap(); - assert_eq!(state.writes, usize::from(fence == "valid")); - if fence == "valid" { - let role = if target_pr { "Issue Agent" } else { "PR Implementation Agent" }; - assert!(state.comments[0]["body"].as_str().unwrap().contains(role)); - } else { - assert!( - result - .last_error - .as_deref() - .unwrap() - .contains("publication source was invalidated or superseded"), - "{fence}: {result:?}" - ); - } - 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(); } } diff --git a/src/writer/tests/body_edit.rs b/src/writer/tests/body_edit.rs index a3abc767..c474cdb0 100644 --- a/src/writer/tests/body_edit.rs +++ b/src/writer/tests/body_edit.rs @@ -224,26 +224,8 @@ 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() - { +async fn changed_snapshot_or_source_rejects_an_admitted_edit_before_mutation() { for (fence, state, reason) in [ - ("unrelated", "rejected", "target is not a permitted directly associated work item"), ("closed", "conflict", "canonical title/body changed since snapshot"), ("context", "rejected", "publication source was invalidated or superseded"), ("generation", "rejected", "publication source was invalidated or superseded"), @@ -256,7 +238,6 @@ async fn changed_association_closed_target_old_context_generation_session_and_hu 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 @@ -282,35 +263,25 @@ async fn changed_association_closed_target_old_context_generation_session_and_hu } } #[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 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(); - } +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] @@ -343,31 +314,20 @@ async fn own_issue_body_edit_and_input_boundaries_use_the_same_acceptance_path() .unwrap_err(); assert!(error.to_string().contains(expected), "wrong failure: {error}"); } - for (profile, invocation, expected) in [ - ( - Some("pr-codex"), - fixture.invocation(), - "publication Profile does not match source assignment", - ), - ( - None, - Invocation::Agent("not-current".into()), - "publication turn does not match current runtime worktree", - ), - ] { - let error = resolve_source(&fixture.config, profile, &invocation).unwrap_err(); - assert!(error.to_string().contains(expected), "{error}"); - } - assert!( - resolve_source(&fixture.config, None, &Invocation::Operator) - .unwrap_err() - .to_string() - .contains("operator entry is unavailable inside an Agent runtime worktree") - ); + 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(); } @@ -393,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, @@ -412,187 +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) - .unwrap_err() - .to_string() - .contains("operator entry is unavailable inside an Agent runtime worktree") - ); } #[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 { - let error = result.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}" - ); - 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 587aff16..4fcd2908 100644 --- a/src/writer/tests/continuous_collaboration.rs +++ b/src/writer/tests/continuous_collaboration.rs @@ -170,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(), diff --git a/src/writer/tests/handoff.rs b/src/writer/tests/handoff.rs index 0ec25f2e..f2e17392 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(); @@ -50,6 +50,7 @@ async fn handoff_is_atomic_idempotent_and_uses_next_batch_without_parallel_turns ); // Restart recovery cannot create a second logical event. f.db().execute("UPDATE github_write_outbox SET lifecycle='sending'", []).unwrap(); + let f = f.reopen(); f.store.recover_writes().unwrap(); f.due(); f.drain(github.clone()).await; @@ -59,19 +60,8 @@ async fn handoff_is_atomic_idempotent_and_uses_next_batch_without_parallel_turns 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(); } @@ -287,22 +277,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(); } @@ -325,20 +299,6 @@ fn handoff_same_key_cannot_change_target_or_impersonate_issue_agent() { .to_string() .contains("already used for a different payload") ); - assert!( - super::super::handoff( - &f.config, - &f.store, - &HandoffRequest { - invocation: Invocation::Operator, - target: "owner/repository#9".parse().unwrap(), - request_id: "operator".into() - } - ) - .unwrap_err() - .to_string() - .contains("operator entry is unavailable inside an Agent runtime worktree") - ); 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") @@ -581,17 +541,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 diff --git a/src/writer/tests/observation_recovery.rs b/src/writer/tests/observation_recovery.rs index 53267d00..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 }, }) diff --git a/src/writer/tests/publication_contract.rs b/src/writer/tests/publication_contract.rs index 4725099d..84188894 100644 --- a/src/writer/tests/publication_contract.rs +++ b/src/writer/tests/publication_contract.rs @@ -1,33 +1,14 @@ use super::*; #[tokio::test] -async fn accepted_obligation_converges_after_actor_restart_without_reacceptance() { +async fn ambiguous_comment_recovery_records_ambiguity_without_another_mutation() { let fixture = Fixture::new(false); let receipt = fixture.comment(); - let fixture = fixture.reopen(); - fixture.store.recover_writes().unwrap(); - let remote = Arc::new(Mutex::new(Remote::default())); + let remote = Arc::new(Mutex::new(Remote { lose_comment_response: true, ..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); - assert_eq!(result.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"); - assert_eq!(remote.lock().unwrap().writes, 1); task.abort(); -} - -#[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::default())); - let (github, task) = server(remote.clone(), true).await; - fixture.drain(github.clone()).await; - assert_eq!(fixture.receipt(&receipt.request_id).lifecycle, "applied"); + assert_eq!(fixture.receipt(&receipt.request_id).lifecycle, "uncertain"); { let mut remote = remote.lock().unwrap(); let mut duplicate = remote.comments[0].clone(); @@ -35,9 +16,10 @@ async fn ambiguous_comment_recovery_records_ambiguity_without_another_mutation() duplicate["node_id"] = json!("second-comment"); remote.comments.push(duplicate); } - fixture.lose_comment_acknowledgement(); 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"); diff --git a/src/writer/tests/semantic_contract.rs b/src/writer/tests/semantic_contract.rs index 909980a1..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()), diff --git a/src/writer/tests/turn_start.rs b/src/writer/tests/turn_start.rs index 98eb7966..2f7946a2 100644 --- a/src/writer/tests/turn_start.rs +++ b/src/writer/tests/turn_start.rs @@ -80,113 +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()) - .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() - .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()) - .unwrap_err() - .to_string() - .contains("publication source was invalidated or superseded") - ); - assert!( - crate::store::publication_source::check( - fixture.config.runtime.database(), - &resolved - ) - .unwrap_err() - .to_string() - .contains("publication source was invalidated or superseded") - ); - 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!(matches!(events.try_recv(), Err(broadcast::error::TryRecvError::Empty))); // 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(); - } + 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 } } diff --git a/tests/console.rs b/tests/console.rs index 21c263d8..c274cbbb 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}")) @@ -237,7 +198,17 @@ 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")); + // An empty protobuf message is a valid ExportLogsServiceRequest. + let export = client + .post(format!("{endpoint}/v1/logs")) + .header("content-type", "application/x-protobuf") + .send() + .unwrap(); + assert_eq!(export.status(), StatusCode::SERVICE_UNAVAILABLE); let issue = client .post(format!("{endpoint}/api/control/commands")) diff --git a/tests/durable_publication.rs b/tests/durable_publication.rs index a31de129..3127ef2b 100644 --- a/tests/durable_publication.rs +++ b/tests/durable_publication.rs @@ -9,25 +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"]); + 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, 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", @@ -42,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(); } @@ -111,12 +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!(stderr.contains("cannot read GitHub App private key"), "wrong failure: {stderr}"); - assert!(output.status.code() != Some(101), "cli panicked: {stderr}"); + assert_eq!(output.status.code(), Some(1), "{stderr}"); fs::remove_dir_all(dir).unwrap(); } diff --git a/tests/multi_repo.rs b/tests/multi_repo.rs index ef6c9524..01b149ab 100644 --- a/tests/multi_repo.rs +++ b/tests/multi_repo.rs @@ -54,13 +54,6 @@ fn multi_repository_config_requires_repo_scoped_profiles() { fs::write(&path, toml::to_string(&multi_repo_config(&example, &temporary)).unwrap()) .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)); - let output = braid() .args(["profile", "inspect", "--config"]) .arg(&path) diff --git a/tests/provider_config.rs b/tests/provider_config.rs index 5273dc18..e5c611db 100644 --- a/tests/provider_config.rs +++ b/tests/provider_config.rs @@ -49,13 +49,6 @@ fn provider_route_inputs_are_validated_at_cli_and_config_boundaries() { } 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 mut coupled: toml::Value = toml::from_str(&example_text).expect("parse example"); coupled["profiles"][0].as_table_mut().unwrap().insert("provider".into(), "openai".into()); @@ -155,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"]) @@ -193,35 +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 profile_inspect_reports_the_selected_pi_route_and_credential_kind() { - 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 report = stdout(&output); - let kind = match name { - "api-key" => "ApiKey", - "oauth" => "OAuth", - _ => "None", - }; - assert!(report.contains(&format!("credential: {kind}")), "{report}"); - assert!(report.contains("provider: example-llm"), "{report}"); - assert!(report.contains("model: example-chat"), "{report}"); - } - let _ = fs::remove_dir_all(&temporary); -} - #[test] fn pi_derivation_rejects_bad_provider_surfaces() { let example = @@ -300,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] @@ -459,7 +416,12 @@ fn provider_import_auth_converts_pi_credentials() { assert_eq!(fs::metadata(&imported).expect("metadata").permissions().mode() & 0o777, 0o600); } - let output = import("other-provider").output().expect("import API key credential"); + let output = braid() + .args(["provider", "import-auth", "other-provider", "--from"]) + .arg(&pi_auth) + .env("BRAID_USER_HOME", &user_home) + .output() + .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"); @@ -490,16 +452,6 @@ fn provider_import_auth_converts_pi_credentials() { 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 output = braid() - .args(["provider", "import-auth", "example-llm", "--from"]) - .arg(&pi_auth) - .env("BRAID_USER_HOME", &env_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); } From dcd2269feef8928879816918fef3aa9d2973a3cf Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sun, 29 Nov 2026 00:21:00 +0800 Subject: [PATCH 39/43] =?UTF-8?q?ref(tests):=20=E7=94=A8=E4=B8=80=E4=B8=AA?= =?UTF-8?q?=E7=8A=B6=E6=80=81=E8=A1=A8=E8=BE=BE=E8=BF=9C=E7=AB=AF=20PR=20?= =?UTF-8?q?=E6=98=AF=E5=90=A6=E5=AD=98=E5=9C=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - POST 成功后清除缺失状态,复用已存在以及首次创建两个场景的同一事实。 --- src/writer/tests.rs | 7 +++---- src/writer/tests/implementation_recovery.rs | 6 +++--- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/src/writer/tests.rs b/src/writer/tests.rs index bd3d49d3..4670c700 100644 --- a/src/writer/tests.rs +++ b/src/writer/tests.rs @@ -131,9 +131,8 @@ 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, @@ -179,7 +178,7 @@ async fn server( .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 |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_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 _; @@ -406,7 +405,7 @@ async fn initial_ensure_bootstrap_pr_association_and_restart_do_not_duplicate_mu assert_eq!(source.profile_id, "issue-codex"); assert_eq!(source.role, "issue_agent"); let remote = Arc::new(Mutex::new(Remote { - create_pr: true, + pr_missing: true, authority: Authority::AssociationUnavailable, ..Remote::default() })); diff --git a/src/writer/tests/implementation_recovery.rs b/src/writer/tests/implementation_recovery.rs index ad637978..c15f2a85 100644 --- a/src/writer/tests/implementation_recovery.rs +++ b/src/writer/tests/implementation_recovery.rs @@ -122,7 +122,7 @@ fn ledger_errors_distinguish_retryable_contention_and_actor_loss_from_invalid_wr 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"); @@ -160,7 +160,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); @@ -247,7 +247,7 @@ 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_rejected( From 5d384839279ec4af6043d46328303784de941bd0 Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sun, 29 Nov 2026 00:29:42 +0800 Subject: [PATCH 40/43] =?UTF-8?q?fix(tests):=20=E6=8E=A5=E5=8F=97=E7=BB=88?= =?UTF-8?q?=E6=80=81=E5=89=8D=E5=B7=B2=E8=90=BD=E7=9B=98=E7=9A=84=E8=BE=93?= =?UTF-8?q?=E5=85=A5=E8=AF=8A=E6=96=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - macOS 暴露撤销与转向的合法时序。分别核对 Unknown 生命周期与追加的精确终态原因。 --- src/group/continuous_tests.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/group/continuous_tests.rs b/src/group/continuous_tests.rs index 546b8d9b..d8a40eeb 100644 --- a/src/group/continuous_tests.rs +++ b/src/group/continuous_tests.rs @@ -949,7 +949,15 @@ async fn builtin_running_unassignment( assert!(body.contains(outcome.lifecycle())); assert!(body.contains(reason)); } - assert_eq!(turn_state(), (outcome.lifecycle().to_owned(), reason)); + let (lifecycle, error) = turn_state(); + assert_eq!(lifecycle, outcome.lifecycle()); + if outcome == crate::agent_session::TurnOutcome::Unknown { + // The worker may already have recorded a steer rejection on this turn. + // Retirement must append its own terminal reason to any earlier diagnosis. + assert_eq!(error.as_deref().and_then(|body| body.lines().last()), reason.as_deref()); + } else { + assert_eq!(error, reason); + } assert_eq!(*captured.close_attempts.lock().unwrap(), ["fresh-provider"]); assert_eq!(captured.memory.lock().unwrap().len(), 2); if !restart { From 5ebea827d61a05d9676b898577d149edd5aaf6c2 Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sun, 29 Nov 2026 00:38:31 +0800 Subject: [PATCH 41/43] =?UTF-8?q?fix(tests):=20=E6=8C=89=E8=BF=BD=E5=8A=A0?= =?UTF-8?q?=E8=AF=AD=E4=B9=89=E6=A0=B8=E5=AF=B9=E5=8E=9F=E7=94=9F=E7=BB=88?= =?UTF-8?q?=E6=80=81=E5=8E=9F=E5=9B=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Failed 和 Unknown 都可能跟在真实输入拒绝之后。终态前后分别核对精确原因,Completed 的生命周期独立验证。 --- src/group/continuous_tests.rs | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/src/group/continuous_tests.rs b/src/group/continuous_tests.rs index d8a40eeb..6eed6bf8 100644 --- a/src/group/continuous_tests.rs +++ b/src/group/continuous_tests.rs @@ -867,6 +867,11 @@ async fn builtin_running_unassignment( ) .unwrap() }; + // The turn may already carry an input rejection. A terminal error is + // appended to that diagnosis, and a successful terminal adds no reason. + let assert_terminal_reason = |error: Option<&str>, reason: &str| { + assert_eq!(error.and_then(|body| body.lines().last()), Some(reason), "{error:?}"); + }; let (outcome, reason) = if let Some((outcome, reason)) = terminal { tokio::time::timeout(limit, async { while turn_state().0 != outcome.lifecycle() { @@ -875,7 +880,9 @@ async fn builtin_running_unassignment( }) .await .expect("observed provider terminal must be durable while the platform fence is offline"); - assert_eq!(turn_state().1, reason); + if let Some(reason) = &reason { + assert_terminal_reason(turn_state().1.as_deref(), reason); + } (outcome, reason) } else { tokio::time::timeout(limit, async { @@ -951,12 +958,8 @@ async fn builtin_running_unassignment( } let (lifecycle, error) = turn_state(); assert_eq!(lifecycle, outcome.lifecycle()); - if outcome == crate::agent_session::TurnOutcome::Unknown { - // The worker may already have recorded a steer rejection on this turn. - // Retirement must append its own terminal reason to any earlier diagnosis. - assert_eq!(error.as_deref().and_then(|body| body.lines().last()), reason.as_deref()); - } else { - assert_eq!(error, reason); + if let Some(reason) = &reason { + assert_terminal_reason(error.as_deref(), reason); } assert_eq!(*captured.close_attempts.lock().unwrap(), ["fresh-provider"]); assert_eq!(captured.memory.lock().unwrap().len(), 2); From b463cfcd3c848f2bfd9cd14570d1c5fcc1a442b8 Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sun, 29 Nov 2026 01:13:31 +0800 Subject: [PATCH 42/43] =?UTF-8?q?ref(tests):=20=E5=A4=8D=E6=A0=B8=E5=90=84?= =?UTF-8?q?=E5=B1=82=E8=AF=81=E6=98=8E=E5=B9=B6=E6=94=B6=E6=95=9B=E9=87=8D?= =?UTF-8?q?=E5=A4=8D=E9=AA=8C=E6=94=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 用真实 claim 与重开、快照正文差异和平台 fence 重试验证恢复的独立承诺。 - 移除伪造的已应用回执和重复读取,保留真实浏览器、已安装 SDK 和发行包的独有边界。 - 由严格 Clippy 承担同配置的编译门禁,按安装产物自带的 Node 跑原生插件。 --- .github/workflows/ci.yml | 5 +- .github/workflows/release.yml | 2 + docs/10-prd/acceptance.md | 12 +- .../pi/acceptance/installed-runtime.test.mjs | 4 +- src/context/filter_tests.rs | 1 - src/context/reading_tests.rs | 16 +- src/github/budget_tests.rs | 4 - src/group/continuous_tests.rs | 169 +++++++++--------- src/platform/tests.rs | 34 +++- src/runtime/builtin.rs | 15 -- src/store/implementation_delivery.rs | 13 +- src/store/replay_tests.rs | 12 +- src/writer/tests.rs | 26 ++- src/writer/tests/handoff.rs | 9 +- src/writer/tests/implementation_recovery.rs | 12 +- tests/console.rs | 9 +- 16 files changed, 170 insertions(+), 173 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 26051586..fb9c6d7a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -32,7 +32,6 @@ jobs: node-version: 24.15.0 - 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 @@ -43,12 +42,12 @@ jobs: PI_OFFLINE: '1' run: | if git cat-file -e "$BASE_SHA^{commit}" 2>/dev/null && - git diff --quiet "$BASE_SHA" HEAD -- native/pi src/provider.rs src/provider src/profile_materials.rs src/profile_materials src/agent_session.rs Cargo.toml Cargo.lock .github/workflows/ci.yml; then + 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 - node --test native/pi/acceptance/installed-runtime.test.mjs + "$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' diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 35ba3d2f..db7315ba 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -7,6 +7,8 @@ on: - 'scripts/package.sh' - 'scripts/verify-package.sh' - 'Cargo.toml' + - 'Cargo.lock' + - 'rust-toolchain.toml' - 'config.example.toml' - 'deploy/otel-collector.example.yaml' - 'LICENSE' diff --git a/docs/10-prd/acceptance.md b/docs/10-prd/acceptance.md index a1c8909c..bd639259 100644 --- a/docs/10-prd/acceptance.md +++ b/docs/10-prd/acceptance.md @@ -50,7 +50,6 @@ events are never pass oracles. ```shell cargo fmt --check -agent-build cargo check --locked --all-targets agent-build cargo clippy --locked --all-targets -- -D warnings agent-build cargo test --locked --all-targets node --test native/pi/tests/*.test.mjs @@ -75,10 +74,9 @@ BRAID_BINARY=/absolute/path/to/braid CHROME_BIN=/absolute/path/to/chromium \ ``` Pi 安装或 Rust 适配器变更时,Linux CI 复用本轮编译并按 lock 安装 background -插件。Node 验证安装包中的真实 RPC、工具执行和 EOF 退出。Rust 工厂用例使材料绑定 +插件。安装包自带的 Node 验证真实 RPC、工具执行和 EOF 退出。Rust 工厂用例使材料绑定 在原生启动后失败,并读取工厂返回前留在该执行目录的停止回执。安装步骤需要访问发行 -站点和 npm。其它插件组合和含模型会话各自单独记录。修改打包入口和包内材料的 PR -以及实际发行均在两个目标平台运行 +站点和 npm。其它插件组合和含模型会话各自单独记录。修改打包入口、编译锁或包内材料的 PR,以及实际发行均在两个目标平台运行 `scripts/verify-package.sh DIST RELEASE_TAG RUST_TARGET`;它从校验和指定的 归档中运行 binary,核对版本、示例配置及迁移后重开的数据库。 @@ -119,14 +117,10 @@ other. ```shell "$BRAID_BIN" context issue "$ISSUE" --config "$CONFIG" --page-size 1 > "$EVIDENCE/issue.md" -"$BRAID_BIN" context issue "$ISSUE" --config "$CONFIG" > "$EVIDENCE/issue-default.md" "$BRAID_BIN" context pr "$PR" --config "$CONFIG" --page-size 1 > "$EVIDENCE/pr.md" -"$BRAID_BIN" context pr "$PR" --config "$CONFIG" > "$EVIDENCE/pr-default.md" -cmp "$EVIDENCE/issue.md" "$EVIDENCE/issue-default.md" -cmp "$EVIDENCE/pr.md" "$EVIDENCE/pr-default.md" ``` -比对两种分页得到的字节后,再逐项核对独立预期:完整可见正文和后页标记必须 +逐项用真实 GitHub 页面和预先记录的预期核对输出。完整可见正文和后页标记必须 出现,折叠/删除评论只含各自的元数据,隐藏标记不出现;PR 的关联 Issue 身份与 数量符合 GitHub,已关闭 Issue 的旧正文不出现。记录每项输入、对象身份和 pass/fail/unavailable。对超过 hard limit 的独立配置,分别保留 stdout、stderr diff --git a/native/pi/acceptance/installed-runtime.test.mjs b/native/pi/acceptance/installed-runtime.test.mjs index 0665da34..581b8092 100644 --- a/native/pi/acceptance/installed-runtime.test.mjs +++ b/native/pi/acceptance/installed-runtime.test.mjs @@ -33,7 +33,9 @@ test('installed background-only Pi opens a fresh session, serves tools and close }; const pi = path.join(install, 'pi'); const node = path.join(install, 'bin/node'); - assert.equal(execFileSync(pi, ['--version'], { cwd: root, env, encoding: 'utf8', timeout: 30000 }).trim(), '1.1.0'); + 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', diff --git a/src/context/filter_tests.rs b/src/context/filter_tests.rs index d0a42656..aacd9cc9 100644 --- a/src/context/filter_tests.rs +++ b/src/context/filter_tests.rs @@ -27,7 +27,6 @@ fn comment_like_code_and_html_attribute_values_remain_literal() { "``", "```html\n\n```", " \n", - "\">visible", "visible