diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..67d3ca8a --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Unified patches retain upstream context markers and indentation. +native/pi/patches/*.patch -whitespace diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 30cff0bc..fb9c6d7a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -10,13 +10,54 @@ permissions: jobs: rust: - runs-on: macos-15 + name: ${{ matrix.name }} + strategy: + fail-fast: false + matrix: + include: + - name: rust + os: macos-15 + target: aarch64-apple-darwin + - name: linux + os: ubuntu-latest + target: x86_64-unknown-linux-gnu + runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v4 - - run: rustup toolchain install 1.93.0 --profile minimal --component clippy,rustfmt --target aarch64-apple-darwin + with: + fetch-depth: 2 + - run: rustup toolchain install 1.93.0 --profile minimal --component clippy,rustfmt --target ${{ matrix.target }} + - uses: actions/setup-node@v4 + with: + node-version: 24.15.0 + - run: node --test native/pi/tests/*.test.mjs - run: cargo fmt --check - - run: cargo check --locked --all-targets - run: cargo clippy --locked --all-targets -- -D warnings - - run: | - archive=$(scripts/package.sh) - scripts/tests/00_clean_install.sh "$archive" + - run: cargo test --locked --all-targets + - name: Verify the installed Pi runtime and factory cleanup + if: matrix.name == 'linux' + env: + BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.before }} + BRAID_TEST_PI_INSTALL: ${{ runner.temp }}/pi-background + PI_OFFLINE: '1' + run: | + if git cat-file -e "$BASE_SHA^{commit}" 2>/dev/null && + git diff --quiet "$BASE_SHA" HEAD -- native/pi src/config.rs src/provider src/profile_materials.rs src/profile_materials src/agent_session.rs Cargo.toml Cargo.lock .github/workflows/ci.yml; then + echo 'Installed Pi inputs unchanged' + exit 0 + fi + node native/pi/install.mjs "$BRAID_TEST_PI_INSTALL" --plugins background + "$BRAID_TEST_PI_INSTALL/bin/node" --test native/pi/acceptance/installed-runtime.test.mjs + cargo test --locked --bin braid profile_materials::tests::failed_home_binding_stops_the_installed_execution_before_returning -- --ignored --exact + - name: Verify conflicting Console edits in two browser pages + if: matrix.name == 'linux' + env: + CHROME_BIN: /usr/bin/google-chrome + run: | + npm ci --prefix tests/browser --ignore-scripts + node --test tests/browser/draft.test.mjs + - name: Verify OTLP internal diagnostics stay out of ordinary logs + if: matrix.name == 'linux' + run: >- + cargo test --locked --bin braid --features opentelemetry-otlp/internal-logs + telemetry::tests::telemetry_isolates_collector_rejection_bodies_from_ordinary_diagnostics -- --exact diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 00000000..db7315ba --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,97 @@ +name: release + +on: + pull_request: + paths: + - '.github/workflows/release.yml' + - 'scripts/package.sh' + - 'scripts/verify-package.sh' + - 'Cargo.toml' + - 'Cargo.lock' + - 'rust-toolchain.toml' + - 'config.example.toml' + - 'deploy/otel-collector.example.yaml' + - 'LICENSE' + - 'README.md' + - 'CHANGELOG.md' + push: + tags: + - "v*" + workflow_dispatch: + inputs: + version: + description: "Release tag (for example v0.3.3)" + required: true + +permissions: + contents: read + +jobs: + build: + strategy: + matrix: + include: + - os: macos-15 + target: aarch64-apple-darwin + - os: ubuntu-latest + target: x86_64-unknown-linux-gnu + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.inputs.version || github.ref }} + - run: rustup toolchain install 1.93.0 --profile minimal --target ${{ matrix.target }} + - name: Package release artifact + shell: bash + env: + BRAID_BUILD_TARGET: ${{ matrix.target }} + 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: | + dist/braid-*.tar.gz + dist/braid-*.tar.gz.sha256 + if-no-files-found: error + + release: + if: github.event_name != 'pull_request' + permissions: + contents: write + needs: build + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.inputs.version || github.ref }} + - uses: actions/download-artifact@v4 + with: + path: dist + - name: Create GitHub Release + shell: bash + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + RELEASE_TAG: ${{ github.event.inputs.version || github.ref_name }} + run: | + set -euo pipefail + tag="$RELEASE_TAG" + version="${tag#v}" + awk -v section="[${version}]" ' + $1 == "##" && $2 == section { include = 1; next } + include && /^## \[/ { exit } + include { print } + ' CHANGELOG.md > release-notes.md + test -s release-notes.md + assets=(dist/release-*/*.tar.gz dist/release-*/*.tar.gz.sha256) + if gh release view "$tag" >/dev/null 2>&1; then + gh release upload "$tag" "${assets[@]}" --clobber + else + gh release create "$tag" "${assets[@]}" --title "$tag" --notes-file release-notes.md + fi 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 6d160ba3..9f11ba08 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,7 +1,8 @@ # Braid Project Instructions -This repository implements Braid: GitHub Issue and pull-request state become the -durable working memory of local Coding Agents. Apply these instructions only in +This repository implements Braid: collaboration Issue and pull-request state become +the durable working memory of Coding Agents. GitHub and the built-in platform are +peer upstreams; the Web Console belongs to Braid as a whole. Apply these instructions only in this repository; do not modify user-scope Agent instructions. ## Knowledge Owners @@ -20,6 +21,9 @@ this repository; do not modify user-scope Agent instructions. - Project vocabulary: `docs/10-prd/glossary.md` - Volatile task control: `tasks/`; retain at most one active packet and delete it when the task closes after promoting binding truth. +- Optional collaboration method: `skills/README.md` lists independent skills + with name, description and file path. Discover and read them on demand; do not + inline skill bodies into prompts or make them a runtime prerequisite. ## GitHub Working Memory Protocol @@ -64,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/CHANGELOG.md b/CHANGELOG.md index 0c8bd2bd..9173667e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,160 @@ All notable changes to Braid are recorded here. The project follows Semantic Versioning once release artifacts are published. +## [Unreleased] + +### Added + +- `braid gh status` 可按公开 request ID 查询发布回执。CLI 本地接收与唯一 outbox + 执行义务原子落库;前置读取限流、CLI 退出及服务重启后仍能继续收敛,结果不确定时 + 先核对远端,避免重复评论或 PR。 +- `braid gh pr|issue read/edit` 通过 canonical snapshot 维护标题和正文;PR Agent + 可修正当前直接关联的开放 Issue,仍保留 PR 角色归因。编辑检查已读版本并保护已识别 + 的 ensure/closing 来源;不声称 GitHub 支持原子 CAS 或关系集合恒定。 +- `braid gh pr handoff` 显式交付 Issue 新设计到已有关联 PR 的下一安全边界,按稳定 + request ID 去重并绑定目标 generation;不创建 Group、不打断当前 turn,也不从 + App 评论或 `@braid` 推断交接。已失效的交接输入不再阻塞同批合法输入或 Finalization。 + +### Changed + +- 持续协作合同改为:有效职责内的相关外部修订既更新记忆,也保留待处理输入。 + 空闲时不再只换 session 后静默结束;运行中与 continuation 合并,不额外并行。 + 所有新 turn 在安全边界取得完整当前 Context,读取失败保留批次并公开等待原因。 +- `braid gh pr ensure` 的 applied 回执必须绑定该请求、该 PR 的持久 activation 事件; + `gh status` 单独显示 activation 交付状态,不把 PR 存在或交付成功当作实现完成。 + 历史缺失的 activation 仅按已固定 PR 的原授权恢复,不从任意关联激活旧任务。 +- Agent 的 `braid gh` 写命令必须携带当前 runtime 输入提供的 `--source-turn`; + `--profile` 不能替换 source 身份。人工调用使用显式 `--operator`,且不能在已登记 + Agent worktree 内降级为人工身份。旧脚本需按新 help 更新。 +- 完整采样证据仅进入专用 OTLP logs,不再复制到普通 Text/JSON journal 或 trace + events。启用 payload 留存的后端必须接收 logs,并明确访问、保留和销毁策略。 + 新增仅供短期 loopback 验证的 Collector→LGTM 模板,无默认二次抽样;SDK 导出统计 + 不等于持久存储确认,未知丢弃数不显示为零。 +- GraphQL 增加 operation、前后台、配额窗口和真实返回 cost 归因;REST/App-token + 不在该统计覆盖内。完整 Context 首屏静态合并后,无项目、关联或线程的单页 mock + HTTP 账单由 Issue 13→5、PR 10→5;保留分页和前后 marker,不推断线上 points 同降。 +- `status` 分开显示原始 runnable 数、durable 领取资格及当前/历史代;物理 provider + 可用性仍明确未知,不因对象 closed/merged 就删除可能合法的 Finalization。 +- Harness schema 升至 **14**;配置 schema 保持 3。处理基线与普通 Context 投影分开, + 完整观察的事件和基线原子提交;发生身份与版本身份分开,接单复用记录可追溯。 + 升级前须停止旧 runtime 并执行带备份的迁移。旧 binary 不能打开升级后的账本;回滚需停止新 runtime, + 将升级前备份恢复到独立 runtime 目录,不支持 down migration。 + +### Fixed + +- 修复多仓库健康状态覆盖与 mention 权限故障互相阻塞;失败轮次重放保留完整事件引用, + 明确拒绝的 steer 不再重复发送,Context replacement/reopen 校验原 Profile revision。 +- 修复 worktree 仓库身份验证、超时子进程清理和 Tunnel 停止失败的传播;删除无用 Provider 转发层。 +- 安装在创建 App 前完成本地预检,保留 GitHub 返回的 webhook secret,头像下载移出 async executor; + 凭据解析错误不输出秘密,强制导入收紧文件权限。修正首次迁移与 Pi 参数指引。 +- 发布统一使用打包脚本,按所选 tag 构建并校验版本,支持外置 target 目录;CI 与发布改用仍受支持的 macOS 15 runner。 +- Console 分页保持已应用筛选,导航保留未提交的 run 草稿,并同步运行表单边界。 +- 已确认接手或正常终止的新 generation 会收敛旧 Operational Status:沿原 comment + 展示最后确认时间与明确的历史/接替关系,不把旧 blocked generation 伪装成复活, + 也不声称代码、review 或产品完成。唯一 outbox 从持久账本补偿重启,发送中旧 create + 的回执不会丢失,uncertain 先对账再更新;重复故障与旧代晚到不会产生重复 comment。 +- Operational Status 的展示过滤不再被当作删除证据;完整成员集合与 Agent 投影分开。 + 本地 tombstone 不是上游 updatedAt,当前正向完整观察可安全纠正;读取前事件栅栏 + 防止提交期间的新 delete 被旧快照覆盖,冲突会说明 node、版本、状态和来源。 +- 已固定 PR 的未交付 ensure 可恢复原职责,不因旧 Source Context 替换而永久丢失; + 任何远端写入仍受原 Source fence 约束。后续评论显式复用受管 head 时续接原请求, + 不因新 marker 创建重复 PR;关闭、移除关联或已有撤销/阻塞历史仍严格拒绝。 +- doctor 增加只读 Session 材料/指令兼容性预检,候选配置不匹配或回退后仍 blocked + 会明确失败,不改既有 generation,也不把文件完整性验证误称默认 gh/Git 认证已验证。 +- 普通 Context/关联 PR 读取不再提前消费 Issue 的变更;stale 判定不再依赖可被读取 + 覆盖的投影。无版本的反复恢复不会撞键,隐藏 HTML/时间变化不会制造语义工作。 + Human 保留旧 Braid 署名的编辑也不再被误判为 OriginEcho。 +- Quick Tunnel 独立监督明确失效、签名入口和 App URL,同步或重建失败持续暴露降级; + 不靠重启 Agent 自愈。Unix 候选单独拥有 wrapper/cloudflared 进程组,失败构造和停止 + 收口附属树;停止未确认时阻断新候选。health 不是进程存活的别名。 +- Pi 原生入口保留普通 gh 原有配置定位,避免 execution-local XDG 目录隐藏凭据; + Git 的 gh credential helper 继承同一路径,不复制凭据。新材料须独立安装并验证 manifest。 +- GitHub 巡检不再每分钟完整重读所有历史 Work Item:OPEN 或仍有存活 Assignment + 的条目默认 60 秒,已完成收尾的终态历史项 30 分钟。Schema 8 独立记录完整成功与 + 尝试时钟,失败不导致每 5 秒本地检查都重新联网;跨仓库按最久未尝试优先,单项 + 失败不阻断后续对象,成功项不因其他项失败或重启反复读取。升级需要迁移数据库。 +- GraphQL 请求统一采集 installation 预算并共享准入/冷却。后台保留前台余量,遵守 + reset/Retry-After,缺提示限流和网络错误有界退避、到期自动探测;首次限流即保留 + 写入重试资格。已准入请求含响应解析限时 30 秒;关闭隐式 transport 重试,REST + 429 仍交由持久写入队列恢复。派生客户端共享自动刷新 token 缓存,而不是复制缓存。 + 此机制不协调进程外消费者,不自动解除业务 blocked,也不声称已测得线上节省量。 + +## [0.3.3] - 2026-10-13 + +### Changed + +- Runtime adapter 与 LLM provider 解耦:`setup`/`init` 使用 `--adapter` + 选择 Pi/Codex;Pi 需要显式 `--llm-provider` 和 `--model`,仅使用 API key + 的 route 才需要 `--api-key-file`。Codex 继续使用隔离 provider home,不再 + 生成或引用伪造的 LLM API key 文件。Braid 不再生成硬编码 reasoning、协议 + 或费用配方。 +- Provider 凭据改为显式 `credential = { kind = "api_key" | "oauth" | "none", file }` + 声明,文件为 Braid schema(`provider_api_key` 或 OAuth token set),不是任何 + runtime 的文件格式。Pi adapter 在材料化时转换:`api_key` 注入 + `BRAID_PROVIDER_API_KEY`,`oauth` 渲染 session home 的 `auth.json`,`none` + 显式 keyless。凭据为静态秘密,内容 hash 进入 Profile 有效版本。 +- 新增 `braid provider import-auth` 一次性把 Pi 原生 `auth.json` 转换进 Braid + secrets;runtime home 中的 `auth.json` 一律拒绝并指向该工具。 +- Pi 的 `models.json` 改为由 Pi adapter 从 `llm_providers` 声明派生:`base_url`、 + 可选 `api` 与 `[[llm_providers.models]]` 能力元数据按声明渲染,`apiKey` 仅在 + `credential.kind = "api_key"` 时出现。模板或 runtime home 中的 `models.json` + 在 schema 3 被明确拒绝;schema 2 保持旧模板路径可读。 +- `setup`/`init` 不再支持 `--api-key-environment`/`api_key_environment` 与 + `--api-key-file`/`api_key_file`(schema 3);改用 + `--llm-credential-kind` 与 `--llm-credential-file`。schema 2 的旧字段继续 + 惰性兼容。Pi 原生材料统一引用 Braid 管理的进程内 `BRAID_PROVIDER_API_KEY`, + 旧配置须显式迁移,不会自动导入旧环境变量。 +- 一个 GitHub instance 可以服务多个显式配置的 repository。GitHub App、 + webhook、进程与 runtime catalogs 共享;Profile、workspace、调度、worktree、 + mention、outbox、reconcile 和 `pr ensure` 均按 repository 路由。多仓库配置 + 中每个 Profile 必须声明 repository 和显式 workspace,`braid gh pr ensure` + 必须显式 `--repository`。 +- `setup --no-browser` 改为可完成的 headless 两段流程:保留 pending setup + draft,随后用完整 `--callback-url` 完成 App conversion 和 instance 写入; + state 不匹配会拒绝。setup 默认 webhook 事件补齐 `issue_dependencies` 和 + `pull_request_review_thread`,Linux 下不再硬编码 Homebrew `gh` 路径。 +- 新增 `braid assignment reactivate`:对已 blocked 的 open Work Item 显式 + 排队新的 activation generation;不会静默恢复不兼容 Profile session。 +- Release workflow 同时构建 macOS arm64 和 Linux x86_64 预编译产物;doctor + 的不可达 OTLP endpoint 降级为可选警告,不再阻断本机 runtime readiness。 + +### Fixed + +- dogfood 修复:新增 repository 的首次 reconcile 不再因 repositories 行缺失 + 触发外键失败(begin 时 upsert),无 tracked work item 的仓库跳过空转周期, + 且任一仓库的 reconcile 失败不再中止其他仓库。 +- GitHub 连接建立改为每步 30 秒有界超时并携带操作上下文,网络故障时启动 + 不再静默挂起数分钟;App webhook 恢复与隧道修复同样有界,systemd 停止 + 不再因断网挂起。 +- `braid profile inspect` 明确标注 models.json 由 `llm_providers` 声明派生, + runtime home / template 标签收窄为 settings/agents 来源。 + +本版本不新增数据库 migration;配置 schema 保持 3。使用旧环境变量字段或 +在 schema 3 的非 Pi Profile 上声明 provider 的配置会被明确拒绝;schema 2 +Codex 配置中的旧 provider 标签及 LLM 协议/费用元数据仅作为惰性迁移字段读取。 + +## [Unreleased pre-0.3.3] + +- 有限 run 的 Issue 指派保留真实执行输入,首次轮次前处理已有 Context reset;普通 serve 指派仍保持空闲会话合同。 +- 受控 Pi background Bash 使用非登录 shell,原生入口移除 BASH_ENV/ENV,工具路径与缓存由实例明确提供。 +- 内建协作的 Harness ledger 写命令先取得 IMMEDIATE 事务准入,纯读仍为 DEFERRED;绑定错误保留账本路径与 SQLite extended code。 + +- 新增与常驻 `serve` 并列的 `braid run`:从顶层 root Issue 或 description 驱动自主拆分、指派、PR 实现与交付,首版接入独立 built-in 平台。 +- 平台原子保存父子 Issue,冻结 run/client/交付分支边界;范围关闭和 pending 授权撤销保留停止门控。Console 通过共享接口控制 run,支持原输入接续与独立终态展示。 +- Harness schema 7 保存有限运行身份和结果,平台 schema 3 增加任务树与范围授权。配置 schema 保持 3,旧迁移不改写。 + +- 内建协作平台与 GitHub 作为 Harness 的同层上游。平台独立配置、schema、对象库 + 与 HTTP API,不再依赖 Harness 会话表或 `local` 运行模式。 +- Web Console 属于整个 Braid,集成 OTLP 三信号原始证据与可视化,直接控制任一 + 上游的 Harness,并可便捷托管独立平台;停止 Harness 不关闭平台或 Collector。 +- Harness 自存上游事件游标及写入授权。平台 grant、对象 revision、命令回执与 + Git 候选意图保留并发和停止边界,过期执行不能继续发布。 +- 配置 schema 3 使用互斥 `[github]` / `[builtin]`;原 GitHub schema 2 配置可继续 + 读取。旧 `[local]` 必须停止后显式导入平台,保留原对象身份、历史与回执。 +- Harness 数据库 schema 6 曾增加接入状态,平台 schema 独立演进。旧迁移保持不可变, + 新版本使用前须迁移,旧二进制不能读取更新后的 Harness 数据库。 +- 修复输入接纳、首次 Context 持久化、完整错误保存与停止证明不足时的恢复门控。 + ## [0.3.2] - 2026-09-19 ### Changed @@ -334,6 +488,10 @@ Versioning once release artifacts are published. ## [Unreleased] +- 新增与常驻 `serve` 并列的 `braid run`:从顶层 root Issue 或 description 驱动自主拆分、指派、PR 实现与交付,首版接入独立 built-in 平台。 +- 平台原子保存父子 Issue,冻结 run/client/交付分支边界;范围关闭和 pending 授权撤销保留停止门控。Console 通过共享接口控制 run,支持原输入接续与独立终态展示。 +- Harness schema 7 保存有限运行身份和结果,平台 schema 3 增加任务树与范围授权。配置 schema 保持 3,旧迁移不改写。 + ### Changed - Replaced the withdrawn Python turn-mirroring prototype with a Rust runtime diff --git a/Cargo.lock b/Cargo.lock index 9e81c9db..e42796c7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -233,7 +233,7 @@ dependencies = [ [[package]] name = "braid" -version = "0.3.2" +version = "0.3.3" dependencies = [ "anyhow", "async-trait", @@ -241,17 +241,21 @@ dependencies = [ "clap", "comrak", "dirs", + "flate2", "fs2", "git2", "hex", "hmac 0.13.0", "image", "jsonwebtoken", + "nix", "octocrab", "opentelemetry", "opentelemetry-appender-tracing", "opentelemetry-otlp", + "opentelemetry-proto", "opentelemetry_sdk", + "prost", "rand 0.10.2", "reqwest", "rusqlite", @@ -474,6 +478,18 @@ dependencies = [ "typed-arena", ] +[[package]] +name = "const-hex" +version = "1.19.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e59eef12462b0f9b0a3620219be5d639afd79fe39dff0a42c3997061f9298b4" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "proptest", + "serde_core", +] + [[package]] name = "const-oid" version = "0.9.6" @@ -1646,6 +1662,18 @@ dependencies = [ "pxfm", ] +[[package]] +name = "nix" +version = "0.32.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77730ed34f01f4990cb2ea67fec715ecebc6fab9a6396cf83c5529b13f581bdc" +dependencies = [ + "bitflags", + "cfg-if", + "cfg_aliases", + "libc", +] + [[package]] name = "nu-ansi-term" version = "0.50.3" @@ -1837,9 +1865,12 @@ version = "0.32.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "56d658ba1faf63f7b9c492cfbe6e0ec365440a16132d3270c1065f7b33f1b638" dependencies = [ + "base64", + "const-hex", "opentelemetry", "opentelemetry_sdk", "prost", + "serde", ] [[package]] @@ -2066,6 +2097,21 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "proptest" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b45fcc2344c680f5025fe57779faef368840d0bd1f42f216291f0dc4ace4744" +dependencies = [ + "bitflags", + "num-traits", + "rand 0.9.5", + "rand_chacha 0.9.0", + "rand_xorshift", + "regex-syntax", + "unarray", +] + [[package]] name = "prost" version = "0.14.4" @@ -2258,6 +2304,15 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "rand_xorshift" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "513962919efc330f829edb2535844d1b912b0fbe2ca165d613e4e8788bb05a5a" +dependencies = [ + "rand_core 0.9.5", +] + [[package]] name = "redox_users" version = "0.5.2" @@ -3205,6 +3260,12 @@ version = "1.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" +[[package]] +name = "unarray" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" + [[package]] name = "unicode-ident" version = "1.0.24" diff --git a/Cargo.toml b/Cargo.toml index b60eedf6..24879a59 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "braid" -version = "0.3.2" +version = "0.3.3" edition = "2024" rust-version = "1.93" description = "GitHub working memory for local coding agents" @@ -24,6 +24,9 @@ jsonwebtoken = { version = "10.4", features = ["use_pem"] } opentelemetry = { version = "0.32", features = ["logs", "metrics", "trace"] } opentelemetry-appender-tracing = "0.32" opentelemetry-otlp = { version = "0.32", default-features = false, features = ["http-proto", "reqwest-blocking-client", "logs", "metrics", "trace"] } +opentelemetry-proto = { version = "0.32", default-features = false, features = ["gen-tonic-messages", "with-serde", "trace", "logs", "metrics"] } +prost = "0.14" +flate2 = "1.1" opentelemetry_sdk = { version = "0.32", features = ["logs", "metrics", "trace"] } rusqlite = { version = "0.40", features = ["backup", "bundled"] } reqwest = { version = "0.13", default-features = false, features = ["blocking", "json", "rustls"] } @@ -48,6 +51,11 @@ octocrab = "0.54.1" git2 = "0.21.0" image = { version = "0.25", default-features = false, features = ["png", "jpeg"] } +# Safe process-group signals are needed in synchronous cancellation cleanup; +# killing only Wrangler's direct PID leaves its cloudflared descendants alive. +[target.'cfg(unix)'.dependencies] +nix = { version = "0.32", features = ["signal", "process"] } + [profile.release] codegen-units = 1 lto = "thin" diff --git a/README.md b/README.md index ed2c8218..d4cc6c95 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@

- Braid logo + Braid logo

Braid

@@ -10,7 +10,7 @@

Braid gives local coding agents a different way to work on long-running software tasks:
- build their context from the current state of GitHub Issues and pull requests,
+ build their context from the current state of Issues and pull requests on GitHub or the built-in platform,
instead of treating an ever-growing conversation as the project's memory.

@@ -47,11 +47,11 @@ The model has three deliberately different parts: | | Responsibility | | --- | --- | -| **GitHub** | Shared, editable working memory: current requirements, decisions, discussion, and relationships. | +| **GitHub or built-in platform** | Shared, editable working memory: current requirements, decisions, discussion, and relationships. | | **Git worktree** | Durable task-local code and working files, preserved across compatible provider-session replacements. | | **Provider session** | Replaceable execution context used by the coding agent, not the authority for the task. | -Braid is a local Rust application. It uses a GitHub App for the collaboration boundary, and supports coding-agent providers through runtime adapters. It does not require a hosted Braid service. +Braid is a local Rust application. It connects to GitHub through a GitHub App or to the built-in collaboration platform through its object API, and supports coding-agent providers through runtime adapters. It does not require a hosted Braid service. ## Get started @@ -65,12 +65,18 @@ brew install xiaoland/braid/braid **2. Set up your GitHub App and agent** -For example, using Pi with a DeepSeek API key available as `DEEPSEEK_API_KEY`: +For example, using Pi with an explicitly selected LLM provider and an existing +secret file when that model route needs one: ```sh -braid setup owner/repository --provider pi --model deepseek-chat --api-key-environment DEEPSEEK_API_KEY +braid setup owner/repository --adapter pi --model \ + --llm-provider --llm-base-url \ + --llm-credential-kind api_key --llm-credential-file /absolute/path/to/secrets/.toml ``` +The setup guide documents the secret file format and permissions. Codex setups +use the isolated Codex home instead and do not take LLM provider arguments. + Follow the printed GitHub App installation link, then check the instance and start the local runtime: ```sh @@ -88,6 +94,28 @@ A repository maintainer can activate Braid by posting a visible, trusted `@braid > [!NOTE] > Braid is an early-stage, local-first project. Review the [supported scope](docs/10-prd/scope.md) and [deployment guide](docs/40-deployment/README.md) before relying on it for unattended work. +## 内建协作平台 + +内建平台与 GitHub 是 Harness 的两种上游。平台独立持有仓库、Issue、PR、讨论 +和事件;Harness 单独接入并执行 Agent,不以 `local` 运行模式拥有协作对象。 +Web Console 属于整个 Braid,平台配置与 Harness 配置可分别装配。 + +先声明平台,再声明 Harness;[内建平台指南](docs/user-manual/local.md)包含启动、 +对象操作、候选发布和旧 Local 数据迁移。 + +```shell +braid platform init --source /absolute/path/to/repository --config /absolute/path/to/platform.toml --name demo +braid init --source /absolute/path/to/repository --config /absolute/path/to/harness/config.toml --name demo --endpoint http://127.0.0.1:18082 --adapter pi --executable /absolute/path/to/pi --model --llm-provider --llm-base-url --llm-credential-kind api_key --llm-credential-file /absolute/path/to/user/secrets/.toml +braid migrate apply --config /absolute/path/to/harness/config.toml +braid console --platform-config /absolute/path/to/platform.toml --config /absolute/path/to/harness/config.toml --database /absolute/path/to/observations.sqlite3 +``` + +## 本地 Web Console + +内置 Console 接收 OTLP HTTP/protobuf,持久保存 traces、logs、metrics 的原始证据, +并提供浏览器可视化。Console 接入平台对象 API 和统一 Harness 控制接口,支持 +GitHub 或内建上游,不经 CLI 子进程;停止 Harness 后 Collector 和平台仍可使用。操作方法和数据边界见[Console 指南](docs/user-manual/console.md)。 + ## Design boundaries - **Current state over transcript history.** Braid deterministically projects the GitHub objects that matter to a task; it does not ask another model to invent a replacement summary. @@ -101,6 +129,11 @@ A repository maintainer can activate Braid by posting a visible, trusted `@braid | Start here | For | | --- | --- | | [Setup guide](docs/user-manual/setup.md) | GitHub App bootstrap, provider credentials, activation, and local runtime. | +| [Built-in platform](docs/user-manual/local.md) | Platform and Harness setup, objects, candidate publication, and migration. | +| [自主 root 运行](docs/user-manual/run.md) | One root Issue or description drives Agent decomposition, implementation, and a bounded delivery lifecycle. | +| [Web Console](docs/user-manual/console.md) | OTLP collection, visualization, and Harness control for either upstream. | +| [独立协作技能](skills/README.md) | 按需采用 braid-collaboration 方法材料;不自动安装、加载或绑定软件。 | +| [Agent Profile](docs/user-manual/profiles.md) | Pi 技能、原生角色材料的明确选择与恢复身份。 | | [Product model](docs/10-prd/README.md) | Purpose, working memory, Issue/PR collaboration, and current product scope. | | [Context design](docs/20-product-tdd/context.md) | Current-state projection, revisions, invalidation, and replacement. | | [Runtime lifecycle](docs/20-product-tdd/lifecycle.md) | Events, scheduling, sessions, and recoverability. | @@ -112,3 +145,6 @@ For source development, run `cargo build --locked` from the checkout and invoke repository workflow, see the [documentation index](docs/index.md) and [`AGENTS.md`](AGENTS.md). See the [MIT license](LICENSE). + +Braid 使用编译、回归测试、实际操作及获授权实验取得反馈。测试验证局部行为和故障边界;真实 GitHub、provider 和 OTel 原始证据及人工判断构成产品验收依据。 +开发验证命令、测试归属及不能由本地回归证明的范围见[验证分层](docs/10-prd/acceptance.md#开发回归与产品验收的分层)。 diff --git a/config.example.toml b/config.example.toml index 3158b5da..614fe5b3 100644 --- a/config.example.toml +++ b/config.example.toml @@ -1,4 +1,4 @@ -schema_version = 2 +schema_version = 3 [instance] key = "owner" @@ -12,6 +12,10 @@ auto_migrate = false [github] app_id = 123456 repository = "owner/repository" +# One instance can serve additional repositories. In that mode every Profile +# must declare its repository and explicit workspace; do not add repositories +# that should not share this App/webhook/process lifecycle. +# additional_repositories = [{ name = "owner/second" }] handle = "braid" api_version = "2022-11-28" private_key_file = "/absolute/path/to/instance/github-app.pem" @@ -23,6 +27,7 @@ projects_v2_enabled = false [scheduler] quiet_seconds = 30 event_threshold = 8 +# Minimum successful hot-traversal interval; local due checks run at most 5s apart. reconciliation_seconds = 60 [[runtimes]] @@ -33,34 +38,36 @@ home = "/absolute/path/to/instance/provider/codex" stable_schema_sha256 = "7d79fe309dd7520843459070f3884ecf0e39cee2620c1c49aad6efb4eca76ecb" experimental_schema_sha256 = "a14d4878fe7b8cdd31059dbca11d7167d8cfd06effa2f7991b5364439063a5c8" -# Alternative: Pi runtime with DeepSeek +# Alternative: Pi runtime with an explicitly declared LLM provider. Pi owns +# model routing, so the provider id and credential reference are user choices; +# Braid does not infer them from the adapter. credential.kind is one of +# api_key (Braid-schema provider_api_key file), oauth (Braid-schema OAuth token +# set rendered into the session home auth.json), or none (explicit keyless). # [[runtimes]] # adapter_type = "pi" -# version = "0.84.3" +# version = "1.0.2" # executable = "/usr/local/bin/pi" # home = "/absolute/path/to/instance/provider/pi" - -[[llm_providers]] -id = "openai" -protocol = "openai" -api_key_file = "/absolute/path/to/user/secrets/openai.toml" - -[[llm_providers.models]] -model_id = "gpt-5.6-sol" -input_cost = 0.0 -output_cost = 0.0 -cache_input_cost = 0.0 - -[[llm_providers]] -id = "deepseek" -protocol = "openai-compatible" -api_key_file = "/absolute/path/to/user/secrets/deepseek.toml" - -[[llm_providers.models]] -model_id = "deepseek-chat" -input_cost = 0.0 -output_cost = 0.0 -cache_input_cost = 0.0 +# For the locked native material, select /pi above and declare: +# native_runtime = "/absolute/path/to/install/runtime-manifest.json" +# +# [[llm_providers]] +# id = "example-llm" +# base_url = "https://llm.example.invalid/v1" +# api = "openai-completions" +# credential = { kind = "api_key", file = "/absolute/path/to/user/secrets/example-llm.toml" } +# +# The Pi adapter derives models.json from this entry: baseUrl and the declared +# models below; apiKey only appears when credential.kind is api_key. Do not put +# models.json in a native template or runtime home — schema 3 rejects it. +# +# [[llm_providers.models]] +# id = "example-chat" +# name = "Example Chat" +# reasoning = true +# input = ["text"] +# context_window = 1000000 +# max_tokens = 131072 [tools] git = "/usr/bin/git" @@ -85,9 +92,10 @@ display_name = "Codex design partner" tags = ["issue"] adapter_type = "codex" adapter_version = "codex-cli 0.147.0-alpha.6.5" -provider = "openai" -model = "gpt-5.6-sol" -reasoning = "high" +model = "example-model" +# Profiles in a multi-repository config also declare: +# repository = "owner/repository" (or another configured repository) +# workspace = "/absolute/path/to/that-repository-source-checkout" user_instructions = "Keep design discussion concise and maintain the Issue description as working memory." # Optional. The source Git checkout of the configured repository, shared by # all profiles as the worktree provisioning source (one repository = one @@ -105,9 +113,7 @@ display_name = "Codex implementation agent" tags = ["pr", "implementation"] adapter_type = "codex" adapter_version = "codex-cli 0.147.0-alpha.6.5" -provider = "openai" -model = "gpt-5.6-sol" -reasoning = "high" +model = "example-model" user_instructions = "Implement from linked Issue working memory and keep GitHub comments brief." # workspace: see the issue profile above; omit it to share the default # instance source checkout. diff --git a/deploy/compose.observability.dogfood.yaml b/deploy/compose.observability.dogfood.yaml new file mode 100644 index 00000000..a950f438 --- /dev/null +++ b/deploy/compose.observability.dogfood.yaml @@ -0,0 +1,22 @@ +# Controlled single-host dogfood, not a multi-tenant production security boundary. +# Apply AFTER compose.observability.yaml, from a private managed directory. +services: + lgtm: + restart: unless-stopped + environment: + GF_AUTH_ANONYMOUS_ENABLED: "false" + GF_AUTH_BASIC_ENABLED: "true" + GF_USERS_ALLOW_SIGN_UP: "false" + GF_SECURITY_ADMIN_PASSWORD__FILE: /run/secrets/grafana_admin_password + secrets: [grafana_admin_password] + volumes: + - data:/data + - ./start-dogfood-lgtm.sh:/otel-lgtm/start-dogfood-lgtm.sh:ro + command: ["bash", "/otel-lgtm/start-dogfood-lgtm.sh"] + collector: + restart: unless-stopped +secrets: + grafana_admin_password: + file: ./grafana-admin-password +volumes: + data: {} diff --git a/deploy/compose.observability.yaml b/deploy/compose.observability.yaml new file mode 100644 index 00000000..1b7e5a5b --- /dev/null +++ b/deploy/compose.observability.yaml @@ -0,0 +1,24 @@ +# Disposable local verification, NOT a public or production Grafana deployment. +# No host mounts or persistent volumes. `down -v` destroys this evidence store. +services: + lgtm: + image: grafana/otel-lgtm:0.11.0 + ports: + - "127.0.0.1:3300:3000" + environment: + ENABLE_LOGS_ALL: "false" + volumes: + - ./loki.observability.yaml:/otel-lgtm/loki-config.yaml:ro + networks: [observability] + collector: + image: otel/opentelemetry-collector-contrib:0.161.0 + command: ["--config=/etc/otelcol/config.yaml"] + volumes: + - ./otel-collector.example.yaml:/etc/otelcol/config.yaml:ro + ports: + - "127.0.0.1:14318:4318" + - "127.0.0.1:18888:8888" + depends_on: [lgtm] + networks: [observability] +networks: + observability: {} diff --git a/deploy/loki.observability.yaml b/deploy/loki.observability.yaml new file mode 100644 index 00000000..37ddf317 --- /dev/null +++ b/deploy/loki.observability.yaml @@ -0,0 +1,61 @@ +auth_enabled: false + +server: + http_listen_port: 3100 + +common: + instance_addr: 127.0.0.1 + path_prefix: /data/loki + storage: + filesystem: + chunks_directory: /data/loki/chunks + rules_directory: /data/loki/rules + replication_factor: 1 + ring: + kvstore: + store: inmemory + +schema_config: + configs: + - from: 2020-10-24 + store: tsdb + object_store: filesystem + schema: v13 + index: + prefix: index_ + period: 24h + +ruler: + alertmanager_url: http://localhost:9093 + +pattern_ingester: + lifecycler: + min_ready_duration: 1s + +ingester: + lifecycler: + min_ready_duration: 1s + +frontend: + scheduler_dns_lookup_period: 1s + address: 127.0.0.1 + +query_scheduler: + use_scheduler_ring: false + +# Full evidence lives in OTLP log attributes (Loki structured metadata). +# Loki's default 64KB metadata limit rejects ordinary long tool results. +# Reject oversized records explicitly; never truncate retained evidence. +limits_config: + max_structured_metadata_size: 64MB + max_structured_metadata_entries_count: 4096 + max_line_size: 16MB + max_line_size_truncate: false + ingestion_rate_mb: 64 + ingestion_burst_size_mb: 128 + retention_period: 24h + +compactor: + working_directory: /data/loki/compactor + retention_enabled: true + delete_request_store: filesystem diff --git a/deploy/otel-collector.example.yaml b/deploy/otel-collector.example.yaml index bc53de3e..99919425 100644 --- a/deploy/otel-collector.example.yaml +++ b/deploy/otel-collector.example.yaml @@ -1,48 +1,40 @@ -# Example OpenTelemetry Collector configuration for Braid. -# -# This is optional external infrastructure, not a required part of Braid. It -# demonstrates outcome-aware tail sampling: keep all error traces and 10% of -# successful traces. The portable Braid binary exports 100% when -# telemetry.sample_ratio=1.0; use this Collector to reduce backend volume. -# See docs/40-deployment/README.md for operator guidance. -# -# Run Braid with telemetry.sample_ratio=1.0 when using this optional -# outcome-aware Collector policy. The portable Braid binary does not require it. +# Run with compose.observability.yaml; private container network only. +# Braid -> Collector -> queryable LGTM. No second sampling decision. +# Outside Compose, replace lgtm with an explicitly authorized OTLP backend, +# bind receivers to loopback, and configure TLS/auth for non-loopback transport. receivers: otlp: protocols: http: - endpoint: 127.0.0.1:4318 + endpoint: 0.0.0.0:4318 processors: batch: {} - tail_sampling: - decision_wait: 10s - policies: - - name: retain-errors - type: status_code - status_code: - status_codes: [ERROR] - - name: retain-ten-percent - type: probabilistic - probabilistic: - sampling_percentage: 10 exporters: - debug: - verbosity: basic + otlphttp/lgtm: + endpoint: http://lgtm:4318 + # Logs contain complete sensitive evidence. Never use a debug exporter. service: + telemetry: + metrics: + readers: + - pull: + exporter: + prometheus: + host: 0.0.0.0 + port: 8888 pipelines: traces: receivers: [otlp] - processors: [tail_sampling, batch] - exporters: [debug] + processors: [batch] + exporters: [otlphttp/lgtm] logs: receivers: [otlp] processors: [batch] - exporters: [debug] + exporters: [otlphttp/lgtm] metrics: receivers: [otlp] processors: [batch] - exporters: [debug] + exporters: [otlphttp/lgtm] diff --git a/deploy/start-dogfood-lgtm.sh b/deploy/start-dogfood-lgtm.sh new file mode 100644 index 00000000..19a382dc --- /dev/null +++ b/deploy/start-dogfood-lgtm.sh @@ -0,0 +1,20 @@ +#!/bin/bash +# Pinned otel-lgtm:0.11.0 has no retention env knobs for Tempo/Prometheus. +# Change only its container-local defaults, never the source verification files. +set -eu +cd /otel-lgtm +# LGTM invokes the Grafana binary directly, bypassing grafana/docker run.sh's +# __FILE expansion. Read the mounted bootstrap secret here without logging it. +export GF_SECURITY_ADMIN_PASSWORD="$(cat "${GF_SECURITY_ADMIN_PASSWORD__FILE:?}")" +if ! grep -q -- '--storage.tsdb.retention.time=7d' run-prometheus.sh; then + sed -i '/--storage.tsdb.path=/a\ --storage.tsdb.retention.time=7d \\' run-prometheus.sh +fi +if ! grep -q '^compactor:' tempo-config.yaml; then + cat >> tempo-config.yaml <<'EOF' + +compactor: + compaction: + block_retention: 168h +EOF +fi +exec ./run-all.sh diff --git a/docs/10-prd/README.md b/docs/10-prd/README.md index 4b7118b9..815bbe3d 100644 --- a/docs/10-prd/README.md +++ b/docs/10-prd/README.md @@ -1,13 +1,13 @@ # Product Truth -Braid turns a GitHub Issue or pull request into the durable working memory of a -local Coding Agent. GitHub holds the current collaboration state; provider +Braid turns an Issue or pull request into the durable working memory of a +local Coding Agent. GitHub or the built-in collaboration platform holds current collaboration state; provider sessions are replaceable execution contexts built from that state. The project vocabulary is owned by [`glossary.md`](glossary.md). This directory owns product purpose, promises, workflows, and exclusions. The cross-unit realization is owned by [`../20-product-tdd/`](../20-product-tdd/), -and [`acceptance.md`](acceptance.md) defines the product acceptance campaign. +and the real operation criteria in [`acceptance.md`](acceptance.md) determine acceptance. - [`glossary.md`](glossary.md) — project vocabulary. - [`purpose.md`](purpose.md) — why Braid exists and the pressure it relieves. diff --git a/docs/10-prd/acceptance.md b/docs/10-prd/acceptance.md index 4d738323..bd639259 100644 --- a/docs/10-prd/acceptance.md +++ b/docs/10-prd/acceptance.md @@ -1,9 +1,8 @@ # End-to-End Acceptance -Braid is accepted only through real GitHub Work Items, the packaged Rust -binary, a real public webhook path, a real Codex app-server, and observable -Agent behavior. Unit/component/fake transport checks may diagnose code but do -not satisfy this contract. +本文件持有真实产品验收判据。GitHub 后端的下述 campaign 要求真实工作项、 +发行 binary、公网 webhook、原生执行器及可观察 Agent 行为;内建平台的入口与 +判别事实见末尾内建空间章节。编译和机械对象操作各自只支持它们实际覆盖的结论。 ## Boundary and Fixture @@ -27,9 +26,70 @@ control, provider executable, Git, installed artifact, and OTLP export. SQLite inspection, internal Rust APIs, fake providers/GitHub, and hand-injected inbox events are never pass oracles. -Acceptance helpers under [`../../scripts/tests/`](../../scripts/tests/) remain -operator scripts until the workflow stabilizes. GitHub objects and Human -verdicts are the product oracle. +验收按本页描述操作真实产品并保留原始证据。自动测试、模拟和包 smoke 可验证 +局部实现,但不能替代本页的真实产品验收。GitHub 对象和人工判断仍是产品验收依据。 + +## 开发回归与产品验收的分层 + +修改代码时,先运行所属边界的回归,再由 CI 验证 macOS arm64 和 Linux x86_64。 +每个测试须能指出具体可信回归;不同层保护不同风险时分别保留。不要为了减少 +测试数量删除协议、数据库兼容、授权或停止证明,也不要把测试自建的配置、状态机 +或回执当作生产实现的证明。 + +| 契约 | 主要自动证明归属 | 仍需真实验收的部分 | +| --- | --- | --- | +| 配置、凭据导入、headless setup、公开回执 | `tests/` 中实际 binary 子进程;配置与 doctor 的局部不变式 | GitHub App 转换、登录、provider 认证与安装后的工具环境 | +| GitHub 准入、完整读取、发布及 uncertain 写入 | `producer`、`context`、`github`、`writer` 的生产 owner,外部 HTTP 固定夹具 | 实际 webhook、GitHub 权限、native 关联及跨仓库行为 | +| durable intent、租约、迁移和重放 | `store` 的真实 SQLite actor;旧 schema 建库、备份还原、关闭重开 | 已发布旧 binary 升级及现场恢复,不能以直接造库代替 | +| Context 替换和 provider 事件 | `group`、`provider` 的真实编排;受控外部会话通知和停止回执 | 真实模型消费新 Context、适配器后台执行停止、长轮次中撤销职责 | +| 内建对象与观测存储 | `platform`、`console` 的 HTTP→SQLite/Git 回归、真实 Console 二进制和两页并发编辑;独立 OTLP 编码器输入 | 完整操作旅程、实际 Harness 与跨宿主运行 | +| 原生执行与材料 | Node 真实进程树、已安装的 Pi background 插件与 RPC;Profile snapshot 和 auth 文件重新读取 | 其余插件组合、真实模型工具调用及跨宿主进程行为 | +| 采样与完整敏感证据 | `telemetry` 中真实 SDK→HTTP→protobuf;每次独立子进程初始化 SDK | 生产 Collector 的权限、保留、查询及完整长旅程关联 | + +默认入口与 `.github/workflows/ci.yml` 一致: + +```shell +cargo fmt --check +agent-build cargo clippy --locked --all-targets -- -D warnings +agent-build cargo test --locked --all-targets +node --test native/pi/tests/*.test.mjs +``` + +`agent-build` 是本机编译串行入口;CI 直接运行相同 Cargo 命令。局部迭代可加 +`--bin braid <模块名>::` 或 `--test <文件名>` 筛选。Linux CI 另启用 +`opentelemetry-otlp/internal-logs`,单独复跑 +`telemetry::tests::telemetry_isolates_collector_rejection_bodies_from_ordinary_diagnostics`, +验证 SDK 开启内部诊断时,Collector 返回的敏感正文仍不会进入普通日志。 +这不改变发行 binary 的 feature。标为 ignored 的 `telemetry_child` 只供父测试 +用独立子进程调用,父测试负责检查退出状态与所有输出;不能单独计作通过。 + +Linux CI 在同一次 Cargo 构建后启动一个独立平台,从两个 Chromium 页面编辑同一 +Issue。先提交的一页保存成功,过期页面显示该对象的修订冲突并保留正文;取消刷新 +保留草稿,确认放弃后重新打开才读到已提交正文。复跑时使用本次构建的二进制: + +```shell +npm ci --prefix tests/browser --ignore-scripts +BRAID_BINARY=/absolute/path/to/braid CHROME_BIN=/absolute/path/to/chromium \ + node --test tests/browser/draft.test.mjs +``` + +Pi 安装或 Rust 适配器变更时,Linux CI 复用本轮编译并按 lock 安装 background +插件。安装包自带的 Node 验证真实 RPC、工具执行和 EOF 退出。Rust 工厂用例使材料绑定 +在原生启动后失败,并读取工厂返回前留在该执行目录的停止回执。安装步骤需要访问发行 +站点和 npm。其它插件组合和含模型会话各自单独记录。修改打包入口、编译锁或包内材料的 PR,以及实际发行均在两个目标平台运行 +`scripts/verify-package.sh DIST RELEASE_TAG RUST_TARGET`;它从校验和指定的 +归档中运行 binary,核对版本、示例配置及迁移后重开的数据库。 + +负向用例应断言错误阶段、类型或关键诊断,并有能够到达该守卫的合法前置条件。 +恢复用例应先让真实 owner 写入,关闭并重新打开,再从消费者取回结果。新缺陷 +修复保留同一输入下修复前红、修复后绿的证据。两份 checkout 做对照时,各设独立 +`CARGO_TARGET_DIR`:Cargo 集成测试按固定路径启动 binary,共享 target 曾使另一份 +checkout 的同名产物被当成最新。核对运行的测试名和失败诊断;缺少对照时说明原因。删除或 +迁移测试前,核对原断言在保留测试中的归属;仅重复编译同一模块不算额外证明。 + +全绿支持上述局部合同,不授予产品发布资格。真实 campaign 仍按下列场景记录 +`pass`、`fail` 或 `unavailable`,尤其不得把 Provider terminal、HTTP 请求受理或 +命令 `prepared` 回执当作任务完成、持久采用或停止确认。 ## Campaign Setup @@ -48,6 +108,25 @@ installation exposes native Agent App assignment or uses the Trusted Braid Mention fallback; the campaign must not claim one mode while exercising the other. +### 固定真实 Context 夹具 + +在专用 campaign 配置上记录 Issue、PR、直接关联的已关闭 Issue、可见评论、 +折叠/删除评论 ID、一个仅出现在第二页的评论标记,以及各自的预期正文片段。 +独立预期来自操作者预先创建的工作项和 GitHub 页面。固定夹具后,在权限受限的 +证据目录执行以下公开命令。命令会在 campaign 的本地账本中记录读取到的修订。 + +```shell +"$BRAID_BIN" context issue "$ISSUE" --config "$CONFIG" --page-size 1 > "$EVIDENCE/issue.md" +"$BRAID_BIN" context pr "$PR" --config "$CONFIG" --page-size 1 > "$EVIDENCE/pr.md" +``` + +逐项用真实 GitHub 页面和预先记录的预期核对输出。完整可见正文和后页标记必须 +出现,折叠/删除评论只含各自的元数据,隐藏标记不出现;PR 的关联 Issue 身份与 +数量符合 GitHub,已关闭 Issue 的旧正文不出现。记录每项输入、对象身份和 +pass/fail/unavailable。对超过 hard limit 的独立配置,分别保留 stdout、stderr +和退出码:必须因 Context 超限失败且 stdout 没有部分正文。缺少对应夹具时 +该项为 unavailable。关于 Agent 实际收到、采用哪版 Context,按旅程 1、3、4 取证。 + ## Required Journeys ### 1. Activation and Initial Context @@ -103,8 +182,13 @@ Codex thread, and inject current complete Context. The replacement must contain new description/comment bodies, only metadata for the minimized/deleted comments, and no stale body or provider transcript. -Repeat equivalent lifecycle on an idle group. Context/session is replaced but -no turn starts until a Wake Event. Unminimizing the comment restores its body and +Repeat equivalent lifecycle on an idle active group without posting another +comment or mention. Context/session replacement must preserve one ordinary +pending input, and after debounce the Agent must handle the revised agreement. +Its observable behavior must use the new description, not the superseded +requirement; it may discuss, revise, clarify or explicitly wait. Repeat delivery +and restart while waiting: neither may silently settle the input or add a second +turn for the same revision. Unminimizing the comment restores its body and creates a Wake Event. Older-after-newer webhook redelivery must not regress the projection or create a duplicate turn. @@ -116,8 +200,10 @@ Draft PR, native association, ActivationIntent, PR Agent generation, PR Profile, and dedicated worktree must result. When the selected branch initially equals base, the PR contains exactly one Braid App bootstrap commit whose tree equals its parent and whose message identifies the request comment; it changes no -file. A second distinct request comment may create a second PR; 1:N and N:1 -associations must not be rejected. +file. A second distinct request comment must independently deliver activation to its +own PR and start that authorized PR Agent; 1:N and N:1 associations must not be +rejected. An applied ensure receipt must report durable activation delivery, +separately from provider readiness/completion. PR existence alone is not pass. The PR Agent's initial Context must contain all current directly Associated Issues followed by the PR section. Open Issues are complete; a closed Issue is @@ -133,6 +219,14 @@ and must refresh Context before that turn, but must not interrupt the active PR turn. Close the Issue: its description/comments disappear from future PR Context while reference/state remain. Reopen restores full Context. +在受控旧版 fixture 上重现“PR 已创建、激活未送达”的历史缺口,再升级:使用旧版 +对同仓库第二个不同 Implementation Request 创建 PR,以公开 receipt/status 记录缺失, +不用 SQL 制造状态。升级前先修订 Issue、更换原 Source Context;新版仍应安全补交 +固定 PR 的原实现职责,不重推分支、不建重复 PR,首个 PR turn 必须读取当前设计与 +已接收的 review。另测源或目标关闭、关联移除、目标已有 blocked/retired 历史,均 +不能因恢复而自动解阻或新增 generation。后续评论复用同一受管 head 时,回执应沿用 +原 implementation request;不同 head 的独立请求仍支持多个 PR。 + ### 5. Origin and Working-Memory Maintenance Use `braid gh` from each Agent to update its description/body and create one @@ -146,6 +240,11 @@ match suppresses self-wake/reset. Repeat under an unconfigured/shared Human identity: it remains allowed but is processed as a normal external change and may wake/invalidate. This is the explicit autonomy/attribution tradeoff. +Have the Human revise an Agent-maintained description while preserving its old +Braid attribution block. It must still be handled as a Human revision. Repeat +with webhook delivery unavailable so canonical reconciliation observes it; +original authorship and displayed attribution must not suppress the newer input. + ### 6. Close, Merge, Reopen, and Finalization Close an active Issue and an active PR without merging. Current turns must not @@ -171,6 +270,14 @@ Exercise duplicate delivery, temporary tunnel loss, 60-second reconciliation, and an out-of-order edit. GitHub state must converge without duplicate logical turns, reactions, status comments, or `pr ensure` PRs. +While the Issue Agent is idle, lose a body-edit webhook and let another complete +Context read (including an associated PR read) see the new description first. +Periodic reconciliation must still deliver the changed agreement to the Issue +Agent without an extra mention. Repeat with only a timestamp or hidden HTML +comment changed: no new work is required. Recover the Tunnel without restarting +Agent execution: the public signed ingress and the App's registered URL must +agree before reporting connected; failures must be visibly degraded. + Restart Braid while debouncing, while a reaction/status write is uncertain, and while a provider turn is active. Repository owner lease, batches, outbox, and same compatible physical thread must converge without parallel turns. Disconnect @@ -178,6 +285,21 @@ app-server without terminal evidence: Braid keeps the turn unknown, preserves the trusted mention's `rocket`, and updates Operational Status rather than claiming success/failure. +在可复用旧版 fixture 中发布一条真实 Operational Status,观察其 webhook 被接收后 +读取完整 Context。该 comment 可以不进入 Agent Context,但不能因此被认成 GitHub +已删除。升级后,旧错误 tombstone 对应的评论仍在 canonical API 中可见时,对账应 +自行恢复且 status 本身不产生业务 turn;不允许通过直接改库作为 pass oracle。对真正 +较新 edit、读取期间到达的 delete,保留乱序保护并以安全元数据说明冲突来源。 + +公开状态恢复验收:保留一个已发布 Provider unavailable 的旧 generation,再通过 +受支持入口建立新 generation。仅 assignment/materialization 完成不能显示恢复; +Provider 确认接手或正常终止后,原 status comment 应更新为带最后确认时间、明确 +新 generation 接替的历史故障。旧 generation 仍 blocked,新状态不暗示实现完成。 +在已有恢复结果但未更新评论的现场升级,也应只靠账本补偿,不需要再调用模型。 +重启、同一故障重复发布及旧代故障晚到,均不新增重复 comment 或恢复旧职责。 +旧 create 已远端成功而本地回执未落库时,必须先对账并沿原 comment 更新,不能以 +再次 POST 掩盖恢复;blocked、unknown 或未被 Provider 接受的新代不能通过此验收。 + ### 9. Telemetry, Migration, and Distribution With sample ratio 1.0, the retained OTLP trace must correlate webhook receipt, @@ -203,8 +325,14 @@ restore the pre-migration backup rather than executing a down migration. observable by 45 seconds absent recorded GitHub/provider outage; - eight-event threshold or trusted mention: provider acceptance/reaction by 15 seconds; -- reconciliation-only missed event: observable processing by 105 seconds with - a 60-second interval; +- reconciliation-only missed event on OPEN/live-assignment Work Items: observable + processing by 110 seconds under normal budget with a 60-second successful + traversal interval (includes up to five seconds of local due-check delay); +- closed/merged history without materializing/active/finalizing Assignments: + missed-event recovery is due 30 minutes after the last complete traversal, + plus up to five seconds of local due-check delay and processing time; quota or + network pressure explicitly reports degraded/delayed instead of meeting these + normal-budget timing targets; - unassignment and Cross-surface description invalidation: debounce before retirement/interruption. @@ -218,3 +346,64 @@ assertions but cannot substitute for public product behavior. The golden Issue-to-PR journey must pass without corrective operator action. A fresh installation and fixture must pass the entire campaign three consecutive times before the implementation PR becomes ready. + +## 多 repository instance 的验收边界 + +多仓库验收使用同一个 GitHub App、一个 webhook/tunnel 入口和两个已配置 +repository。两个 repository 使用不同的 Profile/user_instructions 与独立 +source checkout,最好包含相同 Issue 编号以证明裸 number 不成为身份。分别 +触发 trusted mention,核对:事件只进入所属 repository 的队列;Context 标题、 +正文和评论不混入另一仓库;worktree 路径按 repository 隔离;comment/reaction、 +status 和 `pr ensure` 都使用目标 repository 的 scoped client。第三个已安装但 +未配置 repository 的 signed delivery 必须在调度前拒绝。跨 repository native +association 仍按既有 PR Context 合同由目标 PR 的 scoped client 读取;它不会把 +另一个 repository 纳入调度、Profile 绑定或共享工作图。当前 MVP 桥接仍要求 +同一 instance 的 Profiles 使用相同 adapter_type,不宣称混合 Codex/Pi 多仓库。 + +## 内建空间的验收边界 + +内建平台的操作验收从公开 `platform/init/object/serve` 入口进行:没有 GitHub App 配置时, +创建、指派、讨论、关联 PR、发布与采用实际候选,重启后仍能读写并投递剩余输入。 +核对对象、队列、Git 引用和具体执行状态。机械对象操作不代替模型实际消费和 +多 Agent 协作效果;需要判断完整 Agent 工作经历时,应在获授权的真实模型任务上 +沿同一流程取证,不构造 provider 或修改私有执行状态。当前隔离操作结果归任务 +记录,不据此宣称完成下述 GitHub campaign 或完整模型验收。 + +## Braid Console 的实际验收 + +Braid Console 不依赖 Factory。内建平台场景使用独立真实 Git checkout,先只配置 +平台而不启动 Harness,实际创建并讨论 Issue,再接入仅传输 Harness,核对对象 revision、事件和 +命令回执;两个页面并发编辑时旧 revision 必须明确冲突且保留草稿。同一 request +ID 取回同一结果,不重复创建;不同命令不能复用该 ID。 + +通过页面从真实候选分支建立关联 PR,阅读实际 diff,明确发布配置 source 或 +登记 worktree 的已提交候选,再合并至未被 checkout 的 base。核对发布 OID、 +持久合并意图、base 新提交及具体失败;对象关闭和原生执行停止分别取证。 + +由真实 OpenTelemetry SDK 向 Console 发送三信号,核对原始封包、解码属性、 +采样边界、接收与发生时间,以及原件下载。重发保留传输事实;坏 protobuf、gzip +和超限请求保留具体状态与原因,Collector 重启后仍可按游标阅读旧记录。真实 +存储不可用返回可重试 503,不把正常遥测批次误判为坏数据。 + +通过页面启动和停止 runtime,接受回执不能代替就绪或停止确认。runtime 已停 +时 Collector 与对象接口继续可用;未确认停止不可启动替代执行。完整 Agent +验收还需获授权的真实 provider/session/turn 运行,编译及无模型操作不替代这一 +证明。本轮不推导新的模型、GitHub 或发布授权。 + +平台与 Harness 边界必须通过实际操作取得反馈:平台无 Harness 时可持续读写; +停止并更换 Harness 后同一对象、历史和事件仍存在,新消费者拥有独立 cursor; +撤销 writer grant 后,相同 actor 和对象 revision 的迟到命令拒绝。旧 Local 数据 +显式导入保留身份及回执,原数据库保留且旧写入口不能继续使用。Console 对任一 +上游提供同一 Harness 控制合同;没有真实 GitHub 授权时只核对配置/入口,不宣称 +完成 GitHub 网络或 Agent 全链路验收。 + +## Root 自主运行验收 + +有限运行需要独立的真实模型资格。仅传入 description,由 root 自行形成可分工子项、 +实际指派、创建并实现 PR,消费依赖成果并形成明确交付 commit;开发 Agent 不代写业务答案。 +在同一记录中分别确认创建、启动、成果采用和终态,不以手动对象操作或编译代替自主行为。 + +另外实际核对 root 提前关闭、静默未完成、合并冲突、停止和同 run 接续:提前关闭须保留 +未完义务且撤销旧 writer,静默不报完成,未确认停止不得替代,同一输入不重复建 root。 +普通 serve 与其对象无关的运行保持原合同;并发参数只按在途 Braid turns 判断,不冒称 +验证了原生 subagents/background 或宿主总资源上限。候选应用的实际业务验收单独保留。 diff --git a/docs/10-prd/glossary.md b/docs/10-prd/glossary.md index fe243df6..7742e63e 100644 --- a/docs/10-prd/glossary.md +++ b/docs/10-prd/glossary.md @@ -22,7 +22,7 @@ | Dependency Dirty | PR 的直接 Associated Issue 发生非 description 变化。它不打断当前 PR turn;Braid 在下一次 PR turn 前重新 materialize PR Context,并按规则投递 Event Reference。 | | Cross-surface Hard Invalidation | 非 Agent-origin 的直接 Associated Issue description 变化。Braid 先按 debounce 聚合,窗口结束后 fence/interrupt 当前 PR turn,并用最新 Issue Context 替换 PR Provider Context。 | | Agent-origin Event | 由当前 Agent 通过 Braid 写入关联,或由该 Agent Profile 明确配置且经 GitHub node identity 验证的独立 Agent actor 产生的变化;进入未来 canonical Context,但不反向唤醒或 reset Agent。无法可靠归因的直接写入按外部变化处理。 | -| Agent Profile | Braid 管理的不可变 Agent 配置,包含 provider、model、reasoning、user instructions、tools、skills、MCP 等。 | +| Agent Profile | Braid 管理的版本化 Agent 配置,包含 runtime adapter、可选 model/reasoning、user instructions 和支持的原生材料选择;只有 Pi Profile 额外引用 LLM provider。有效版本包括实际选中材料的内容身份;不是 Factory preset,也不是 Pi 内部 subagent 角色。 | | Profile User Instructions | Agent Profile 提供的行为、风格与专长指令。它们在创建 Provider Session 时加入 Effective Agent Instructions,并与 Braid 的工作记忆、角色和协作说明共同构成实际指令。 | | Profile Tag | Agent Profile 声明适用面的 tag-like 类型,例如 `issue`、`pr`;同一 Profile 可同时拥有多个 tag,也可以只适用于 Issue。 | | Braid System Prompt | Braid 在创建 Provider Session 时注入的高优先级、版本化指令,包括 Braid/CLI 的存在、GitHub Working Memory 协议,以及按 Issue/PR surface 选择的角色与任务说明。它帮助 Agent 使用产品能力,而不是把 Braid 变成限制 Agent 的权限沙箱。 | diff --git a/docs/10-prd/objects.md b/docs/10-prd/objects.md index a404f3bc..87f0b868 100644 --- a/docs/10-prd/objects.md +++ b/docs/10-prd/objects.md @@ -25,15 +25,23 @@ The exact projection is the [Context contract](../20-product-tdd/context.md). ### Agent Profiles and Groups -An Agent Profile is a versioned Braid configuration containing a provider, -model, reasoning setting, Profile User Instructions, cwd/workspace policy, -sandbox/approval settings, and optional tools, skills, MCP, or other -provider-specific resources. Tags declare whether it can serve `issue`, `pr`, +An Agent Profile is a versioned Braid configuration containing a runtime +adapter, model, optional reasoning setting, Profile User Instructions, +cwd/workspace policy, and supported adapter resources. A Pi Profile also names +its explicit LLM provider and, only when that route uses an API key, a secret +file reference. Tags declare whether it can serve `issue`, `pr`, or both. The Profile `workspace` names a clean source checkout, never the Agent's cwd: every Agent Group session runs in a dedicated generation-scoped Braid worktree (the Issue's sole Development branch when unambiguous, otherwise the default branch; the PR head for a PR Agent). +Pi Profile 可以明确选择独立技能和原生角色材料。根会话模型与推理仍由 Profile +决定;仅当声明 reasoning 时覆盖原生偏好,Pi 内部 subagent 角色不是可指派的 Braid Profile。材料安装、Profile 选择 +与会话实际装载分别需要依据;材料变化不得在保持旧 Profile 身份的情况下恢复 +原生历史。工具和 MCP 由已支持的原生安装能力提供,目前没有跨 provider 的 +tools/MCP 或 sandbox/approval Profile 配置接口。Factory preset 与 variant 属于 +消费方的装配,不属于 Braid 的 Profile 对象。 + Braid adds its own versioned System Prompt when materializing a Provider Session. It explains GitHub Working Memory, Braid and `braid gh`, concise public comments, and the Issue- or PR-specific role. GitHub Context remains delimited @@ -48,3 +56,11 @@ sub-agent roles. MVP acceptance deliberately uses: Multi-Agent fan-out is not rejected, but cross-peer ordering, semantic merge, arbitration, and convergence are outside the MVP correctness claim. + +### 内建空间的对象 + +Local Issue 和 PR 共享递增编号,使用稳定空间名称标识;编号不是 GitHub ID。 +正文、评论、负责人及关联由 Braid 持久保存。当前沿用一个 Issue Profile 与默认 +PR Profile,拒绝指派到没有对应执行者的配置。Issue 指派物化会话,后续评论唤醒 +设计工作;PR 指派启动实施。关闭与重开沿用当前逻辑会话生命周期,空间本身持续 +存在。评论和描述是工作数据,不获得系统指令权限。 diff --git a/docs/10-prd/publication.md b/docs/10-prd/publication.md index 0eea8339..27b3f90c 100644 --- a/docs/10-prd/publication.md +++ b/docs/10-prd/publication.md @@ -36,3 +36,104 @@ capabilities. Correlated Braid App writes and writes made by a Profile's explicitly configured stable GitHub actor are Agent-origin. An uncorrelated write from any other identity is treated as an external GitHub change and may therefore wake or invalidate the Agent. + +## Durable Publication Receipts + +`braid gh comment create`, `braid gh pr ensure`, and body edits accept valid local requests +before connecting to GitHub. Acceptance atomically creates one durable execution +obligation. The command exits with `queued` and a stable public request ID even +when the service is offline or remote validation is rate-limited. The service, +not the CLI process, owns convergence after CLI exit and runtime restart. +Query with `braid gh status --config [--json]`; never resubmit +a body merely to learn its status. Reusing a key with the same request returns +the original receipt; different content conflicts. + +Queued/retrying work has not been confirmed published. `uncertain` means a remote +mutation may have happened; Braid reconciles the exact App-authored target/body +and creation window before deciding to resend. Multiple candidates are +`ambiguous`, permanent authorization/target failures are `rejected`, and neither +is retried forever. `applied` for ensure includes native association and initial +Activation, not just PR creation. Internal intent and node IDs are not public +request IDs and are not included in the receipt. + +Acceptance is not remote authorization. The public role comes from the source +Group, never the target kind or Profile tags. Tags select eligible roles; they +are not target permissions. Agent mutations require the `--source-turn` reference +supplied in the current runtime prompt. It is only a selector: Braid independently +checks actual cwd, durable worktree, repository, assignment generation, Profile +revision/materials, session, turn and Context fence. `--profile` can only assert +that identity. Removing `BRAID_AGENT` does not enable an implicit human fallback. +An explicit `--operator` entry outside Agent worktrees is audited as Operator; +this is an honest runtime boundary, not an OS sandbox against same-UID attackers. +Ordinary completed turns retain accepted obligations; session/Context/generation +replacement or invalidation forbids further old-source mutations. Recovery can +still confirm a mutation that already happened. + +## Canonical Body Maintenance + +Issue Agents maintain their own open Issue. PR Implementation Agents maintain +their own open PR title/body and may correct the design of its currently native, +directly associated open Issues. The latter still carries PR Implementation +Agent attribution. Relevant direct cross-surface comments remain allowed; this +does not authorize unrelated targets or add dedicated relationship, +close/merge/ready, or Group-scheduling commands. + +Read a canonical snapshot, inspect it, then submit an offline-durable edit: + +```shell +braid gh pr read owner/repository#123 --output /tmp/pr-snapshot.json +braid gh pr edit owner/repository#123 --profile pr-codex \ + --source-turn TURN_FROM_RUNTIME_PROMPT --snapshot /tmp/pr-snapshot.json \ + --body-file /tmp/pr-body.md --title 'Current scope' --request-id delivery-update-1 +# Use `issue read` / `issue edit` for an Issue. Query the returned request ID. +``` + +The snapshot carries the canonical version/digest; callers need not guess one. +Title and body are optional independently; empty supplied values and oversized +UTF-8 bytes are rejected. Title-only edits retain the body. Body edits add exactly +one source attribution and retain recognized existing ensure-request metadata and +explicit closing-source Markdown blocks, including ATX and Setext headings. +Protection is of existing data, not words: ordinary “Fixed pagination bug”, +“Resolved review feedback”, code, lists and links are valid replacement content. +Recognized existing sources are preserved as complete original blocks, prefixed +before replacement content so unclosed new fences/comments cannot hide them. +Self-contained top-level paragraphs and headings are supported; an existing +source with links/reference dependencies, HTML or nested/list/code-block context +is explicitly refused when it cannot be safely preserved. Title-only edits can +retain such a body unchanged. This is a bounded source-preservation safeguard, +not a reproduction of GitHub's private parser or proof that arbitrary Markdown +has an unchanged relationship set. + +`braid gh` provides identity and attribution, not a Markdown semantic permission +sandbox. An authorized body edit may explicitly add GitHub-native closing text. +This revises the earlier, undelivered keyword freeze and no-relationship-change +restriction. Only GitHub's canonical native direct associations authorize later +cross-surface maintenance: new body text is never itself permission to edit +another Issue. Once GitHub confirms a new edge, that Issue can enter the PR +Agent's maintainable set under the same open-state, source and Context fences. +Ordinary references or closing words alone grant nothing. Body maintenance does +not create, activate or schedule another Group; explicit handoff's direct-edge, +active-target and generation requirements remain separate. The executor +revalidates target state, association and source before mutation and compares the +canonical snapshot again after validation. An external +edit produces a `conflict` receipt, never a blind overwrite. GitHub does not offer +atomic compare-and-swap here: a concurrent edit in the final read/PATCH interval +remains possible; Braid does not simulate CAS with a write-then-rollback. +An `applied` body receipt confirms content, not an invariant relationship set. +After an uncertain send, exact remote title/body is reconciled +before retry; different external content is conflict, not claimed success. No +second execution queue or schema authority is introduced. + +### Handoff receipts + +`pr handoff TARGET --request-id KEY --source-turn TURN` is Agent-only. Acceptance +is local and durable in the same intent/outbox used for publication. The key is +namespaced by source assignment/generation and binds the first explicit target's +current assignment. Same-key retries return the same receipt; changing target or +request content conflicts. Replacement target generations are never substituted. +An unresolved (`queued`/`sending`/`uncertain`/`ambiguous`) Issue body edit is a clear +refusal boundary: confirm publication first rather than assuming queued design +was published. `braid gh status REQUEST_ID` checks delivery. Handoff `applied` +means only that a Wake was durably delivered to the PR batch, not that design +implementation or acceptance has completed. Preflight rate limits keep the +request pending without creating runnable work. diff --git a/docs/10-prd/purpose.md b/docs/10-prd/purpose.md index a6049ec6..1ed96b5f 100644 --- a/docs/10-prd/purpose.md +++ b/docs/10-prd/purpose.md @@ -19,3 +19,13 @@ Braid makes the collaboration surface itself the compacted memory: An Agent may therefore replace a stale provider session without losing the team's current understanding. Humans can correct that memory with ordinary GitHub edits instead of manipulating a private Agent transcript. + +在一项已明确激活、仍然有效的职责内,Braid 还负责让当前协作约定的相关变化 +可靠到达负责的 Agent。更新记忆、持久接收待处理输入、Agent 实际接手是不同的 +产品结果;不能因会话空闲、另一条读取路径先看见新版或入口故障而静默丢失输入。 +Agent 可以讨论、修订、实施、澄清或明确等待,并不需要每次变化都修改代码。 +Human 不应为了补偿内部投递问题再发一次 `@braid`。 + +快速连续变化可以合并,处理当前有效版本;Braid 不保证还原 GitHub 未被观察到的 +每个中间版本,也不承诺每次编辑各开一轮。新任务或新角色仍需明确授权,关联本身 +不激活另一个 Agent,正文仍是工作数据,Human 的审查、合并和关闭权不变。 diff --git a/docs/10-prd/scheduling.md b/docs/10-prd/scheduling.md index f923a8a9..649361e6 100644 --- a/docs/10-prd/scheduling.md +++ b/docs/10-prd/scheduling.md @@ -10,10 +10,21 @@ Replacing or removing a fact already present in a Work Item's Context is Hard Invalidation. Braid fences the stale Context Revision immediately. If a turn is active, it requests safe interruption, discards later stale Agent output, starts a fresh physical Provider Session with current Context, and continues once -with the invalidation reference. If idle, it replaces Context without starting -a turn. Rapid Cross-surface edits to an open Associated Issue description wait -for debounce before interrupting a PR turn. Other Associated Issue changes mark -the dependency dirty and are incorporated before the next PR turn. +with the invalidation reference. Context freshness and attention are independent: +a relevant external revision both invalidates old memory and leaves durable work +for the still-active responsibility. If idle, replacement preserves one ordinary +debounced batch; if running, replacement and pending input coalesce into one +continuation, not a second parallel turn. No second Human mention is required. +Rapid Cross-surface edits to an open Associated Issue description wait for +debounce before interrupting a PR turn and remain input for an idle active PR +Agent too. Other Associated Issue changes mark the dependency dirty and are +incorporated before the next PR turn. + +Timestamp-only and HTML-comment-only changes carry no new semantic input. +Repeated observations/redeliveries of the same change do not schedule another +turn. Closed, sleeping, dormant or retired responsibilities are not activated by +ordinary revisions. An unavailable executor or Context must leave an observable +pending/blocked obligation, not pretend that memory replacement handled it. Every newly ingested external comment receives Braid's `eyes` reaction. Only a Trusted Braid Mention has turn-lifecycle reactions on that same comment: @@ -27,3 +38,16 @@ Trusted Braid Mention has turn-lifecycle reactions on that same comment: Ordinary debounced turns never receive active or terminal reactions. Their operational failures use one mutable Operational Status Comment instead, so the normal collaboration model does not look like a request/response pipeline. + +Explicit Issue→existing PR handoff is one internal ordinary Wake reference, not +a mention, activation, steer or interrupt. It merges pending/runnable batches +under the usual quiet/count policy. A running target receives it in a subsequent +batch, never a parallel turn. Before that batch's provider input, Braid freshly +materializes complete canonical PR Context including directly associated OPEN +Issue bodies/discussion. Read failures defer the unsent claim; no cached/partial +Context is substituted, and no 60-second reconciliation poll is required. +OriginEcho suppression and trusted mention rules remain unchanged: an App +comment containing `@braid` does not implicitly hand off anything. +A batch that includes a handoff cannot be forwarded as an in-turn urgent steer, +even if it also contains a trusted mention: that combined input waits for the +next safe turn boundary and retains its existing runnable/urgent status. diff --git a/docs/10-prd/scope.md b/docs/10-prd/scope.md index a40fce59..0264ac5a 100644 --- a/docs/10-prd/scope.md +++ b/docs/10-prd/scope.md @@ -1,11 +1,41 @@ ## Scope and Exclusions -The MVP includes Codex and Pi runtime adapters, macOS arm64, real GitHub, SQLite, a free +The MVP includes Codex app-server, macOS arm64, real GitHub, SQLite, a free Cloudflare tunnel for acceptance, `braid gh` writes, packaged installation, OpenTelemetry, and the Issue-to-PR workflow above. Linux x86_64 follows with the same contract. -The MVP does not promise a Claude adapter, hosted ingress, deterministic +当前实现还提供 Pi adapter,使用实际支持 prompt 接收回执、get_state、get_entries、 +agent_settled 和 abort 收口的原生协议。它不承诺任意 Pi 版本、扩展或脱离原生管理 +的后台执行都能安全接续;缺失协议能力或停止依据时明确阻断。 + +The MVP does not promise Claude adapters, hosted ingress, deterministic multi-Agent merge, automatic merge, universal GitHub CLI parity, automatic semantic readiness/acceptance, or recovery of a provider transcript that the provider itself has lost. + +内建协作平台与 GitHub 处于同一生态位,是 Harness 的另一种上游对象权威。 +它独立承载仓库、Issue、PR、正文、评论、指派、事件及真实 Git 候选,即使没有 +启动 Harness 也可讨论和维护工作项。Harness 接入一个上游,复用调度、记忆投影 +及原生执行;停止或更换执行不改变平台对象身份和历史。候选发布与手工合并 +独立于模型终态或产品验收。不承诺 GitHub API 全兼容、双向同步、远程用户权限 +系统或自动验收。 + +## Braid Web Console + +Web Console 属于整个 Braid,接收 OTLP、保存并可视化观测证据,统一阅读和 +控制平台及 Harness。GitHub 与内建平台使用同一个 Harness 运行控制入口; +内建平台可独立启动,也可由 Console 便捷装配。对象、执行和观测分别保留 +权威,不把遥测缺失当作工作完成。Console 不依赖 Factory,不执行 Braid CLI +作为后端桥,也不承担实验/赛事调度。 + +## Root 驱动的自主运行 + +`serve` 常驻处理协作输入;`run` 以一个 root Issue 或 description 为业务输入, +由 root Agent 自主拆分 Issue、指派、创建 PR、消费成果并组织交付。run 属于 Harness, +首版接入 built-in 平台;平台仍与 GitHub 同层,不被重新定义为运行模式。 + +完成以 root 的交付声明、范围内义务收敛、真实交付 commit 和执行停止确认为依据。 +无新事件或模型轮次结束不等于完成;提前关闭 root 不能忽略未完成子项。 +运行结果不代替应用验收。运行权限限定当前 root 后代与关联 PR 和明确交付分支, +不默认合并用户主分支,也不将 Factory 的业务阶段、模型配方或评分流程内置。 diff --git a/docs/10-prd/workflow.md b/docs/10-prd/workflow.md index bf8b4eae..78c5b81c 100644 --- a/docs/10-prd/workflow.md +++ b/docs/10-prd/workflow.md @@ -11,19 +11,36 @@ included metadata, and unfolded content are Wake Events. They accumulate until the Quiet Window expires or the count threshold is reached. The Issue Agent receives one current Context plus coalesced Event References and decides whether to discuss, update the design description, wait, or request -implementation. +implementation. Relevant external revisions to existing working memory are also +inputs to an already-active responsibility. Replacing an idle session does not +settle that input: Braid supplies the current agreement at the next safe boundary +without requiring another Human mention. ### Implement An Issue Agent or Human may request implementation through a concise Issue comment. `braid gh pr ensure` uses that comment's GitHub ID as the -Implementation Request key, so concurrent calls for the same request converge -on one Draft PR. It establishes native Issue association and PR Activation. If +creation idempotency key, so concurrent calls for the same request converge +on one Draft PR. 创建后,原 Implementation Request 与固定的 PR 身份承担长期协作义务, +而不是要求每条催办评论另建一个 PR。后续评论显式复用同一个受管 head 时,只有在 +原计划、源 Issue、固定 PR node、base/head、PR Profile 与 canonical 直接关联都一致 +且双方仍 OPEN 的条件下才续接原请求。不同 head 的独立请求仍允许形成 1:N。 +续接 ensure 不表示新的设计输入已被执行;已激活 PR 的后续处理沿 review Wake/显式 +handoff 交付,不隐式增加 turn。 It establishes native Issue association and PR Activation. If the selected remote head has no difference from base, Braid creates an App-authored empty bootstrap commit with the same tree, so GitHub can open the Draft PR before implementation changes exist. This public commit changes no file and records the Implementation Request; the PR Agent then implements in -the resulting branch/worktree. +the resulting branch/worktree. An applied ensure receipt must confirm durable +delivery of the activation to that exact PR, not merely that the PR exists. +Activation delivery is distinct from executor readiness or implementation +completion; any blocked handover must remain diagnosable. + +已固定 PR 的激活交付未完成时,恢复的是原来已授权的职责承诺。Source Context +替换仍禁止旧输出继续远端写入,但不会让已发布 PR 的交接永远依赖旧 turn 存活。 +恢复前重验当前 OPEN 状态、精确身份、关联与 Profile;已有匹配的 active/materializing +角色可以幂等采用,已有 blocked/sleeping/retired/finalizing 历史不能被 ensure 自动 +解阻或换代。这与“任意关联自动激活 PR”不同。 PR Profile selection is deterministic: use the sole eligible `pr` Profile, or the configured default when several exist; otherwise leave activation visibly @@ -54,3 +71,29 @@ closed-unmerged PR sleeps and a merged PR retires. A mention on a closed Work Item does not wake the sleeping group; Reopen is the designed re-entry. Reopen rematerializes Context and starts one ordinary debounced turn. Duplicate deliveries never grant extra finalization turns. + +### Maintaining accepted working memory + +Use the source-bound `braid gh pr read` / `issue read --output PATH` snapshot and +`pr edit` / `issue edit --snapshot PATH` workflow described in +[Publication](publication.md#canonical-body-maintenance). Keep accepted Issue +design and PR implementation scope, verification and risks in their respective +bodies. A PR Agent correcting its current directly associated open Issue remains +publicly a PR Implementation Agent. Confirm the returned receipt is applied; +queued design is not yet published. This maintenance action does not create, +activate or schedule another Group. Authorized body text can change GitHub-native associations; only +a subsequent canonical direct-edge confirmation, never submitted body text, +authorizes maintenance of a newly associated open Issue under the existing +source/Context fences. There is no dedicated association, close/merge/ready or +handoff operation added by body maintenance. + +### Explicit follow-up to an existing PR + +After confirming the Issue design edit receipt is `applied`, its bound Issue +Agent can request `braid gh pr handoff OWNER/REPO#N --request-id STABLE_KEY +--source-turn TURN`. The source Issue must be OPEN; the same-repository PR must +be OPEN/unmerged, GitHub-confirmed directly associated, and already have a current +active schedulable PR assignment. This never creates or reactivates a Group, +unblocks it, reopens it, or enters finalization. Submitted closing text and plain +references are not evidence of a native edge. The Issue body remains the design +source; handoff does not copy a second design authority. diff --git a/docs/20-product-tdd/README.md b/docs/20-product-tdd/README.md index 95243841..1269799c 100644 --- a/docs/20-product-tdd/README.md +++ b/docs/20-product-tdd/README.md @@ -1,4 +1,4 @@ -# Product TDD: GitHub Working Memory Runtime +# Product TDD: Working Memory Runtime This document owns Braid's cross-unit authority, topology, state ownership, and Rust realization. It deliberately excludes unit algorithms that are evident @@ -20,43 +20,85 @@ from typed code and external wire details owned by the linked contracts. ## Authority and Topology ```text -GitHub webhook ──verify/durable ingest──┐ - ├─> canonical object ledger -GitHub GraphQL/REST reconciliation ────┘ │ - v - Context materializer - │ - canonical diff + Event References - │ - event classifier / debounce scheduler - │ - Agent Group + logical session manager - │ - provider adapter (Codex v1) - -Agent ── braid gh ──> Braid write outbox ──> GitHub ──> origin-correlated echo -Agent ── ordinary gh/git ─────────────────> GitHub ──> ordinary external event - -Quick Tunnel ──> loopback webhook ingress -OTel SDK ──sampled OTLP──> operator-selected endpoint +GitHub (object authority) ── webhook / canonical API ──┐ + ├─> Harness collaboration adapter +Built-in platform (object authority) ── HTTP / events ┘ │ + v + Harness ledger / event cursor + │ + Context / scheduler / Agent Group + │ + provider / worktree + +Agent ── Harness gateway / writer grant ──> selected platform API +Harness outbox ── idempotent write ───────> selected platform API + +Braid Web Console ── object API ─────────> built-in platform + ├─ runtime controller ─> Harness (either upstream) + └─ OTLP Collector ──────> independent observation store / visualization + +Platform, Harness and observations each own their database and lifecycle. +Quick Tunnel is optional GitHub webhook connectivity, not a Harness mode. ``` - **GitHub** owns current Issue/PR bodies, metadata, relationships, comments, - reviews, lifecycle, identity, and App permissions. -- **GitHub Context** is a deterministic, complete projection of that state plus + reviews, lifecycle, identity, and App permissions for every explicitly + configured repository. A multi-repository GitHub instance shares only the App, + webhook ingress, process, runtime catalogs, and observability; repository + remains part of every scheduling, Profile, workspace, write, resume, and + reconciliation decision. It never creates a cross-repository work graph. +- **Built-in platform** independently owns its Issue/PR state, actors, event sequence, + candidate commits and command receipts; its SQLite is collaboration authority. +- **Collaboration Context** is a deterministic, complete projection of upstream state plus durable deletion tombstones. It is the collaboration memory authority. - **Provider** owns physical session data, model execution, provider-native - compaction, turn lifecycle, and resume availability. + compaction, turn lifecycle, and resume availability. Pi 的锁定原生材料同时拥有 + plugin 后台结果、物理执行登记及 owned 停止回执;Core turn idle 不推导这些义务 + 已收口。材料的版本与启动合同见 [provider 技术说明](app-server.md)。 - **Coding Agent** owns interpretation, design/implementation choices, code, verification, and its Git/GitHub operations. -- **Braid** owns canonical reads, projection, logical Agent Group/session +- **Braid Harness** owns canonical reads, projection, logical Agent Group/session generations, scheduling, Context fencing/replacement, provider addressing, - PR worktree provisioning, Braid-authored GitHub writes, and mechanical + PR worktree provisioning, Braid-authored upstream writes, and mechanical idempotency/reconciliation. -SQLite stores enough canonical object metadata and lifecycle tombstones to +Harness SQLite stores enough canonical object metadata and lifecycle tombstones to compare versions, but it does not become an alternate Issue/PR or provider -transcript authority. A full Context is rebuilt from GitHub before every turn. +transcript authority. A full Context is rebuilt from the selected upstream before every turn. + +## 协作平台与 Harness + +一个 Harness 恰好接入 `[github]` 或 `[builtin]`。GitHub 和内建平台拥有上游 +对象权威,不双写或自动同步。内建平台有自己的配置、schema、SQLite 与 API, +持有仓库、Issue/PR、评论、指派、关联、revision、候选、合并意图及对象回执。 +平台不读取 Profile、assignment、session、turn 或 worktree 执行表。 + +Harness 的 `collaboration` adapter 从所选上游取得当前对象与默认分支,Group、 +Context、queue、provider 和停止证明共用。内建 adapter 使用 HTTP 平台接口, +在自己的 ledger 保存平台身份、事件 cursor 和 delivery 去重。平台对象变化 +与稳定事件原子提交,事件不因某一消费者读过而消失。Harness 在同一事务接纳 +事件并推进自己的 cursor。平台对象提交指派和生命周期时只记录权威事件。 +签发及使用 grant 时用该事件版本和 run root 版本判定有效性,重放旧身份不能恢复授权。 +输入和执行独立记录状态与反馈义务,outbox 通过幂等接口领取并写回平台。 + +平台 actor 与 Harness Profile 分别拥有含义。内建轮次认领时保存已接纳事件位置, +发送原生 prompt 时通过只读 Context 核验当前指派和 run 范围,无需请求 writer grant。 +Harness 在首次发送轮次前保存不可复用的执行代次,并绑定当前 runtime lease。 +Agent 首次写入时,gateway 使用当前工作区和精确 session/turn 身份,按认领时的 +事件位置和执行代次申请 grant。平台签发和提交事务都检查代次封禁,另核验适用的 +指派、生命周期、run root、grant epoch、对象 revision 和 request ID。 + +Harness 先关闭该代次的本地授权入口,再分别请求平台的永久封禁和原生停止。 +平台封禁接受从未申请 grant 的代次,并与签发及最终提交串行化。封禁路径不读取 +grant、发布意图或回执。替代执行要求已确认的平台封禁和原生停止。原生恢复必须 +使用新的代次。封禁前已提交的命令属于合法历史。 + +PR 交接固定 commit OID。Harness 验证工作树责任,平台只在绑定 Git 对象库中 +验证提交并保留可达引用。首版要求两者能访问同一 Git 对象库,不提供远程 +Git 托管。对象和范围查询从平台对象读取身份,候选采用回执用于交付判定。 +合并用持久意图与 ref CAS 处理 SQLite/Git 边界;模型 Completed 不 +意味着候选被采用或 Issue 完成。旧 local:*对象与事件身份在显式导入时保留, +历史迁移不可变;平台与 Harness 的 schema 此后各自演进。 ## Single Source of Truth for Schema @@ -70,16 +112,15 @@ against it. truth for the config schema. `braid setup` builds a `Config` value and serializes it, rather than formatting a template. If the type changes, the compiler forces the generator to change with it. -- **Round-trip tests for generated artifacts**: Any code that emits a -structured file a Human might edit must be covered by a test that parses the -output back through the canonical type and validates it. +- **Generated artifacts**: 配置由 canonical Rust type 序列化;编译、回归测试与实际公开 + 命令操作核实消费者能解析和使用产物。 - **No parallel string templates**: Do not maintain a separate text template for a file whose shape is already defined by a Rust type. Avoid `format!`-based generators for config, manifest, or protocol files. - **ROI boundary**: Not every documentation snippet is a schema instance. Only canonical or generated artifacts participate in SSoT validation. For example, `config.example.toml` is the canonical starter template, so it is -loaded through `Config::load` in tests; a partial snippet in a runbook is not. +loaded through `Config::load` by the public configuration command; a partial snippet in a runbook is not. - **Migrations are the exception**: SQLite schema is forward-only, immutable, and checksum-verified; it is not derived from Rust structs because the database must outlive any single binary version. @@ -93,10 +134,9 @@ crates. Modules are deep and align with authority boundaries: | --- | --- | | `home` | User root resolution, instance registry, `~/.braid` layout, port allocation, and config-path precedence. | | `config` | Versioned config/Profile loading, validation, effective defaults, and diagnostic projection. | -| `github::webhook` | Raw-body HMAC verification and typed open-enum webhook admission. | -| `github::client` | GitHub App auth, bounded typed GraphQL pagination, REST writes, reactions, and canonical rereads. | +| `webhook` | Raw-body HMAC verification and typed open-enum webhook admission. | +| `github` | GitHub App auth, bounded typed GraphQL pagination, REST writes, reactions, and canonical rereads. | | `context` | Canonical snapshot model, HTML-comment removal, deterministic Markdown rendering, budget, and revision. | -| `events` | Canonical diff classification and compact Event Reference rendering. | | `store` | One dedicated SQLite actor, transactions, migrations, leases, ledgers, sessions, batches, and outbox. | | `producer` | Webhook/GraphQL observation、canonical diff 与事件分类;独立的 `mentions` 循环补全 GitHub 权限事实并保留失败 backoff。 | | `queue` | 独立推进 Quiet Window、count、urgent 与批次状态;通过 store 领取可运行 turn,不执行网络权限查询或持有会话事件 receiver。 | @@ -138,31 +178,15 @@ best-effort one-way projection from it. Nonessential state is not persisted. | State | Authority | Projections | | --- | --- | --- | | Work Items, assignments, turns, context ledger/resets, queue/batches, outbox, owner lease | Durable store (SQLite) | In-memory `RunningAgentTurn` (claim cache for the in-flight turn), health snapshot | -| GitHub canonical state | GitHub | `canonical_objects` / `sync_cursors` snapshots for diffing | +| GitHub canonical state | GitHub (per configured repository) | `canonical_objects` is the latest Context/tombstone projection; `processed_objects` is the separate event-processing acknowledgement frontier | | Physical session identity (`provider_session_id`) | Durable store (`provider_sessions`) | `SessionManager` 的 opaque key 与 adapter 寻址;句柄可替换,assignment 与 worktree 连续性不依赖连接 | | Current provider turn | Provider process | `SessionEvent` stream (exactly one `TurnStarted`/`TurnTerminal` per turn; receiver handed off with the turn, never re-subscribed) → durable store; 恢复时 fencing 遗留的 starting/running turn | | Provider connectivity | Provider connection | adapter 内部观察连接退出 → 受影响句柄的 latched availability;runtime 汇总各 driver 的恢复结果,成功不能覆盖另一方的失败 | | Worktree presence | Filesystem + git | `worktrees` table (refreshed by inspection at prepare time) | -Selected dependency baseline, verified against crates.io on 2026-08-13: - -- Tokio 1.53 for async runtime/process/I/O/signal ownership; -- Axum 0.8 for loopback HTTP and Reqwest 0.13 with rustls for GitHub/OTLP HTTP; -- Serde 1.0 and serde_json 1.0 for external JSON boundaries; -- rusqlite 0.40 with bundled SQLite, used only by a dedicated blocking DB - actor so network awaits never occur inside transactions; -- Clap 4.6 (with `env` feature), `serde_path_to_error` for TOML error paths, - `thiserror` for boundary errors, and `anyhow` only at CLI/runtime - composition boundaries; -- HMAC 0.13/SHA-2 0.11 for webhook verification and context revisions, - `jsonwebtoken` 11 for GitHub App JWTs; -- Comrak 0.54 to identify actual Markdown HTML comment nodes while preserving - code literals; -- OpenTelemetry/SDK/OTLP 0.32 plus tracing-opentelemetry 0.33; -- UUID 1.24, `time` 0.3, and `url` for typed identities and timestamps. - -Versions become lower/upper compatible ranges in `Cargo.toml`; `Cargo.lock` is -committed for the released binary. Rust 1.93 is the first verified toolchain. +依赖、feature 与兼容版本范围由 `Cargo.toml` 持有,发行 binary 的解析版本由 +已提交的 `Cargo.lock` 固定;不在本文重复维护版本表。工具链由 +`rust-toolchain.toml` 固定,最低 Rust 版本见 `Cargo.toml`。 ## Cross-Unit Invariants @@ -189,29 +213,45 @@ committed for the released binary. Rust 1.93 is the first verified toolchain. mutation has a durable intent before leaving the process. 10. Provider terminal means only that a turn ended; it never proves task, implementation, review, or acceptance success. +11. Observation, input delivery and execution are different commitments. A + Context projection read cannot acknowledge pending collaboration input. + Classified events and their processed frontier commit atomically; Context + replacement preserves independently recorded attention. +12. An applied implementation request has an exact durable activation event for + its target PR. PR existence, activation delivery, executor readiness and + Human acceptance are not interchangeable. ## Durable State and Migrations SQLite starts in WAL mode with foreign keys, a busy timeout, and FULL -synchronous durability. One DB actor serializes writes. Schema v1 owns: +synchronous durability. One DB actor serializes writes. The Harness ledger owns: - `schema_migrations(version, name, checksum, applied_at)`; - `owner_leases(scope, generation, owner_id, expires_at)`; - `repositories` and `work_items` keyed by stable GitHub node IDs; - `profiles` with immutable revision and effective-config digest; - `assignments` and `agent_instances` with group/profile/generation/lifecycle; -- `provider_sessions` and `turns` with opaque provider IDs and Context revision; +- `provider_sessions` and `turns` with opaque provider IDs and the session's + Context-replacement fence revision; ordinary additive input does not replace + that fence with the latest projection revision; - `worktrees` for the default PR Implementation Agent workspace; - `associations` for direct Issue↔PR edges and their observed version; - `issue_context_sources` for one exact visible-description comparison state per Issue, independent of association fan-out; -- `canonical_objects` for latest object version/lifecycle, the internal - reconciliation equality fingerprint, and deletion tombstones; -- `deliveries` and `events` for webhook/reconciliation dedupe/classification; -- `scheduler_batches` and `batch_events` for quiet/count/urgent state; -- `write_intents`, `reaction_targets`, and `status_comments` for Braid-owned - GitHub convergence; -- `sync_cursors` for repository reconciliation. +- `canonical_objects` for the latest observed Context metadata and tombstones; +- `processed_objects` for the separately acknowledged complete observation and + semantic equality fingerprint, including root title and body fingerprints, + committed atomically with its event decisions; +- `publication_versions` for the exact version and content observed when + settling an edit intent. Echo classification uses upstream authorship; +- `deliveries` and `events` for webhook/reconciliation dedupe/classification and + independently recorded attention; +- `implementation_requests.activation_event_id` for durable PR activation delivery; +- `wake_batches` and `wake_batch_events` for quiet/count/urgent state; events may + belong to a consumed historical batch and its later replay batch; +- `github_write_outbox` and `status_comments` for Braid-owned GitHub convergence; +- `work_items.reconciled_at` and `reconcile_attempted_at` for complete traversal + success and retry scheduling. Migration files are embedded, monotonically numbered, forward-only, and never edited after release. Startup takes an exclusive migration lease, verifies all @@ -229,9 +269,9 @@ worktree that Braid provisions from that checkout under the configurable generations use a changed location — SQLite records each worktree's actual path): -- PR Agent Group: `runtime.root/worktrees/pr-/-g`, +- PR Agent Group: `/--/pr-/-g`, bound to the fetched PR head; -- Issue Agent Group: `runtime.root/worktrees/issue-/-g`, +- Issue Agent Group: `/--/issue-/-g`, bound to the Issue's sole same-repository Development linked branch when exactly one exists, otherwise to the repository default branch (`refs/remotes/origin/`). Several Development branches are not an @@ -273,3 +313,37 @@ are outside it and converge only when GitHub reports them. - Packaging, OTel, tunnel, migration, and operation: [`../40-deployment/README.md`](../40-deployment/README.md) - External acceptance oracle: [`../10-prd/acceptance.md`](../10-prd/acceptance.md) + +## Console 与控制边界 + +Console 的 OTLP Collector 保存原始传输批次与完整解码记录,使用独立数据库, +不能写回对象或执行权威。资源身份、runtime generation、session、turn 与原生 +协议身份显式关联;采样和未关联记录可能留下证据缺口。观测库启动失败时,Collector 和证据读取 +返回不可用,权威控制和平台 API 仍可启动。Web 查询分页 +读取该读模型,当前对象来自协作平台 API,执行状态来自 Harness ledger 与 runtime manager。 + +平台通过有类型的应用命令修改对象。命令 request ID、内容摘要、预期 revision +与回执持久保存在平台库;普通对象变更与事件、回执一起提交, +并发正文修改不会覆盖新 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 接口托管。请求接受不等于任务已就绪或已停止; +监督器等待所有 Group/provider 停止结果,失败进入 blocked 并禁止新执行覆盖。 +Console 不调用 CLI,也不复制 Factory 的实验、赛事或容器生命周期。 + +## Root 运行入口 + +有限 `run` 与常驻 `serve` 是 Harness 的运行方式,平台仍是独立上游。`run` +复用调度、原生 provider 和停止屏障,以独立 ledger 隔离一项 root 工作。父子 Issue、 +关联 PR、交付 ref 和 grant 边界由平台保存;输入绑定、执行状态和终态由 Harness 保存。 +范围登记与开放状态的查询使用对象账本。首个范围候选按需建立交付分支, +关闭后的运行判定读取实际 Git 交付证据。 +Console 调用同一应用入口并读取当前 run ledger,OTLP 不承担终态权威。 +具体准入、关闭及接续合同见[生命周期说明](lifecycle.md#有限-root-运行),输入与操作见[run 指南](../user-manual/run.md)。 diff --git a/docs/20-product-tdd/app-server.md b/docs/20-product-tdd/app-server.md index 6106a03e..c07ef921 100644 --- a/docs/20-product-tdd/app-server.md +++ b/docs/20-product-tdd/app-server.md @@ -10,15 +10,27 @@ Group 不根据 backend 决定连接数量或故障范围。 创建结果包含 opaque provider session ID 与中立句柄,store 保存它与 Agent/assignment 的绑定。Resume 返回同一持久化身份的新句柄,不改变 assignment 或 worktree。 +两种上游的 Codex 与 Pi 子进程都取得当前 Harness 配置的绝对路径 +`BRAID_CONFIG` 和 `BRAID_AGENT=1`。原生工具因此使用所属运行的配置,不能因 +GitHub 接入而遗漏路径、继承宿主的其它实例或自行寻找旧运行配置。这提供明确 +绑定,不构成对同账户进程的文件系统隔离。 + +锁定 Pi 入口在建立 execution-local XDG 目录前,保留普通 `gh` 的配置定位: +显式 `GH_CONFIG_DIR` 优先,否则固定原有 `XDG_CONFIG_HOME/gh` 或 Unix 默认 +`$HOME/.config/gh`。Git 的 `gh auth git-credential` 子进程继承同一路径,不复制 +凭据值或整个宿主 XDG 配置。该修正需要新建不可变 Pi 材料安装;不要原地修改已冻结 +manifest 的文件。旧材料可由 operator 显式配置 `GH_CONFIG_DIR` 作为过渡。 + + | Core method | Adapter behavior | | --- | --- | | `SessionFactory::check()` | 检查 adapter 的启动前置条件;共享运行资源由 adapter 自己维护。 | | `SessionFactory::start/resume` | 创建或恢复会话并返回中立句柄。Codex 内部共享 app-server,Pi 每个会话持有独立进程;上层接口相同。 | -| `send_user_msg(msg, steering)` | Idle 时启动 turn;running 且 steering 时发送 steer;否则返回 Acknowledged,由 queue 保留后续输入。 | -| `interrupt()` | 尝试停止已观察到的 active turn;terminal 仍通过事件流返回。 | +| `send_user_msg(msg, steering)` | Idle 时申请启动 turn;已知拒收返回 Deferred,queue 保留输入。Acknowledged 只代表原生执行明确接纳,结果不明返回具体 Unknown。 | +| `steer_user_msg(msg, expected_turn_id)` | 只向已观察且仍匹配的 active turn 投递,不偷换为新 turn;明确拒收返回 Deferred,结果不明保留具体 Unknown。 | | `events()` | 将 provider 的响应与通知去重为 TurnStarted / TurnTerminal;dispatch 前订阅,同一 receiver 随 RunningAgentTurn 交给 driver。失效的 active handle 合成 Unknown,不能伪造失败。 | | `is_unavailable()` | 句柄失效后永久返回 true;idle 或晚订阅也可观察。恢复创建新句柄,不复活旧句柄。 | -| `close()` | 停止使用该句柄,尝试 interrupt,取消监听并释放资源;不能影响其他会话。 | +| `close()` | adapter 先请求中断所属活动 turn,再确认执行停止并释放资源。关闭失败时保留句柄与原因,阻止替代执行。 | 具体 `AgentProvider` 接口只在 adapter 内使用。共享 Codex 进程退出会使其所有 句柄失效;独立 Pi 进程退出只影响所属句柄。释放旧句柄会取消旧监听任务, @@ -117,6 +129,64 @@ Only `turn/completed` is terminal. Its status is retryable and is not terminal. Disconnect without a terminal leaves the turn unknown. Provider terminal state never proves product success. +Pi 通过 `--append-system-prompt` 注入 Braid 与 Profile 指令,保留核心默认系统提示。 +`message_end` 只更新最近一条 assistant 消息的 `stopReason`,不结束 turn;Pi 仍可能 +持久化、压缩或重试。Adapter 等待 `agent_settled`,只有最终 `stopReason=stop` 才报告 +completed;`length`、错误或缺少停止原因均报告 failed。每次 `agent_start` 清空上一轮 +停止原因,避免沿用旧 turn 的成功状态。 +Pi 1.1.0 的原生 settled `aborted=true` 报告 interrupted;消费端也识别保留的旧材料 +`cancelled=true` 与外部 Pi 的 `stopReason=aborted`,供关闭和 Context reset 保存实际中断结果。 + +Pi 的初始 GitHub Context 是用户数据,仅在尚未进入原生历史时随首条输入送入; +后续 turn 不重复拼接 Braid/Profile 指令或这份 Context。由于 Pi 的 RPC 没有持久 +注入接口,会话路径也可能在首次 prompt 前尚未落盘,Braid 在原生 session 文件旁 +保存 `.braid-context` 固定初始输入。保存成功才完成 Context 物化;恢复时核对原生 +session 身份和 `get_entries` 的当前分支祖先中的实际 user message,决定是否仍需 +注入。工具引用、其它分支或 ACK 本身都不证明消费;无法核对时明确失败。旁文件 +不是新的当前 Context 权威,也不据此重发结果未知的事件输入。 + +Pi 的锁定原生材料由 `native/pi/` 交付,CLI 与 RPC 使用同一安装入口。 +受管材料通过 Pi 根包的公开 SDK 创建 runtime,Braid 自有 host 接线负责材料边界、 +受控 Bash 和推理交接;标准 RPC 与 print 仍由 Pi 的公开实现处理。 +实际运行握手的版本来自已加载 SDK 的 VERSION,能力来自 host 实现,不能回显 +manifest 的声明来冒充实际能力。Rust 将实际版本与冻结 manifest 核对。 +周期 readiness 仅检查可执行入口与凭据,不重复遍历整份安装的文件哈希。 +每次新建或恢复物理 Pi 前,以及显式 doctor,仍完整校验材料;readiness 成功 +不能当作安装目录当前完整性证明。 +`RuntimeEntry.native_runtime` 指向相邻 `runtime-manifest.json`;adapter 在启动前 +核对所有声明文件、入口与固定 Node 的 SHA-256,启动后通过 `get_state` 核对当前 +execution ID 和实际生命周期能力。`doctor` 的静态材料检查不能代替这个 live 握手。 +外部 Pi 保留基础接入,关闭环境自动扩展发现;需要插件共同合同时必须使用声明材料, +不能继承宿主的未锁定插件。 + +Pi 1.1.0 的 session observer 提供 `agent_end.willRetry`;扩展不依赖该字段, +改在公开的 `agent_before_settle` 边界完成结果交接,该边界位于自动重试和压缩之后。 +自有接线保留 extension_error,最终终态仍以原生 settled 为准。 +最终模型错误后,尚未消费的 steering/follow-up 输入先保存到原生历史的 Braid +custom entry,再从 Pi 队列移出,阻止错误后自主推理;下次明确输入前恢复这些义务。 +保存或恢复失败须报告具体错误并阻断继续。终态扩展 hook 失败会请求公开 abort, +保留错误触发停止的独立事实;原始 aborted 标记不改写,错误事实仍优先判 failed。 +插件不能自行越过 Braid 发起下一轮推理;后台有限工作 +和长期服务分别登记,结果未被消费时仍属于 busy。异步 subagent 的返回必须等待 +真实 child 启动回执;runner PID 不等于 child 已启动,启动失败保留具体原因和 +清理结果。Core 的 turn idle 不代表 managed +execution 静止,长期服务 busy 也不统一阻断普通输入。 + +每次 Pi 物理启动取得新的 execution/start ID,所属工作目录下的 +`.braid/native-executions/` 保存进程登记、结果和停止回执。 +锁定材料关闭先请求 owned stop,再释放 stdin 发送 EOF、等待父进程,最后用固定 Node +执行同一材料的离线清理并核对 exact execution 回执。Mac 与 Linux 都核对 OS 出生身份、 +登记进程组和继承 execution 标记;身份或停止范围不明时返回 unknown。 +工厂创建或恢复 Pi 会话时,物理执行在句柄交给 Group 前归工厂所有。握手、会话绑定或初始 +Context 持久化失败后,工厂等待同一执行的关闭结果;清理未确认时,返回构造与清理两者的原因。 +原生 background Bash 工具各自记录命令退出码与进程树收口证据;清理不明时向调用者报告错误。 +这不构成安全沙箱,也不追踪主动擦除标记、脱离登记范围的进程或撤销已发出的外部请求。 +外部基础 Pi 仍使用 abort 与父退出依据,不声称具备插件后代清理合同。 + +Codex 关闭保留共享 app-server,只接受目标 turn 的确定终态作为停止依据。 +停止失败向 Group 返回具体错误,不能吞掉错误后仅凭数据库 fence 启动替代会话。 +强制清理成功保留原关闭失败,不能改写为正常停止。 + Braid does not publish item/delta/tool/reasoning/assistant activity to GitHub. Those protocol events are retained only in sampled full-fidelity telemetry and provider-owned history. Agent public prose is created by the Agent through @@ -126,8 +196,11 @@ GitHub. `thread/resume` is used only after transport/process restart when the persisted physical thread ID, Context Revision, effective instruction revision, Profile -revision, cwd, and sandbox remain compatible. If any differs, Braid executes -the normal fresh-session Context materialization path. An empty thread that has +revision and cwd remain compatible. A persisted Profile or instruction revision +mismatch blocks resume with an Operational Status update; it does not silently +start a replacement under new materials. Context changes use the normal +fresh-session Context materialization path after the old execution is stopped. +An empty thread that has not yet materialized a rollout is not considered resumable; assignment startup must complete context injection before the session becomes `idle`. diff --git a/docs/20-product-tdd/context.md b/docs/20-product-tdd/context.md index 27ceed67..c85ec81c 100644 --- a/docs/20-product-tdd/context.md +++ b/docs/20-product-tdd/context.md @@ -6,12 +6,19 @@ in Issue Context and PR Context, see `docs/10-prd/objects.md` and `docs/10-prd/workflow.md`. It does not own webhook scheduling or provider history. +Local 后端使用同一 canonical snapshot 和渲染合同,在单个 SQLite 读取事务中 +取得正文、讨论及直接关联对象。内部身份带 `local:` 前缀,对外标为 +`Braid Issue: #` 或 `Braid PR: #`。GitHub 后端 +保留下述分页与漂移核对,Local 不伪装网络分页、远端权限或 GitHub ID。 + ## Materialization Transaction For one Work Item Braid reads every required GitHub connection to exhaustion, then checks the root object `updatedAt` and relationship version again. If the root or association graph changed during the read, it discards the partial -snapshot and retries a bounded number of times. Missing permission, unsupported +snapshot and retries a bounded number of times. Stateless first-page connection +combination changes only the HTTP grouping: continuation cursors, full bodies, +association expansion and before/after marker checks remain mandatory. Missing permission, unsupported union members, pagination failure, or repeated drift produces `context-unavailable`; Braid never emits a partial Context. @@ -91,15 +98,36 @@ changes to them produce Event References when subscribed. ## Body Filtering +内建 `object context` 使用此 projector,供 Agent 重新读取设计与讨论。 +`object show` 返回平台原始对象,供对象及操作元数据检查,不承诺移除 HTML 注释; +该过滤不是原始对象、provider history 或任意工具读取的机密隔离边界。 + 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. -Operational Status Comments are excluded by their persisted GitHub comment IDs. -Agent comments remain included. No hidden marker is required. +GitHub Operational Status Comments are excluded by their persisted comment IDs. +Before publication, Braid declares a stable role for the Work Item, Profile, +and assignment generation, and records the digest of each complete rendered +body. The body carries the role identifier in an HTML comment. A complete +canonical conversation read can bind the role to a GitHub comment when its App +actor, Work Item, role identifier, and full body match the declaration and +identify a single comment. Both Context and reconciliation use this binding, +including when the first POST succeeded and its publication receipt was lost. +The role marker carries only the identifier. Regular Agent discussion remains +included. + +Upgrades preserve known historical comment IDs. For an unresolved legacy +create, canonical observation can bind a unique same-App, same-Work Item comment +with the recorded full body and a creation time in the recovery window. When +multiple identities match, Braid leaves the role unbound. A previously bound +role continues to identify the same comment after edits, minimization, or +deletion. ## Snapshot, Revision, and Version Ordering @@ -161,3 +189,12 @@ state and makes no replace/inject decisions. This keeps the Profile as plain configuration and avoids coupling the core runtime to provider-specific compaction or resume rules. + +有效 Profile 版本不仅覆盖 Profile 声明,还覆盖 adapter 合同、锁定原生安装 +manifest,以及选中技能与原生模板的内容身份。材料的路径相同不证明内容兼容。 +凭据值和派生 execution/worktree/home 路径不参与语义材料摘要;原生实际启动 +仍核对所选材料与物化身份一致。完整文件读取不放回周期 readiness 循环。 + +旧会话版本与当前有效版本不同会明确 blocked,保持旧记录,不自动覆盖其材料 +或借用旧历史新开执行。所选材料身份还用于启动诊断,但它不是模型实际使用某项 +技能或原生角色的证明;后者需实际原生装载及执行记录。 diff --git a/docs/20-product-tdd/github.md b/docs/20-product-tdd/github.md index fdfd9971..edd4a80c 100644 --- a/docs/20-product-tdd/github.md +++ b/docs/20-product-tdd/github.md @@ -45,6 +45,10 @@ external activity. - Persist `X-GitHub-Delivery`, `X-GitHub-Event`, action, repository/object IDs, actor, receipt time, and raw payload before acknowledging. Redelivery retains the delivery GUID. +- The repository in the payload must be one of the explicitly configured + repositories for this instance. A signed delivery from another installed + repository is rejected before scheduling rather than routed through a default + repository. - Return 2xx within GitHub's ten-second deadline only after durable ingest. GitHub does not automatically retry failed deliveries; reconciliation and explicit redelivery remain required. @@ -62,7 +66,7 @@ contract; consumers never see GitHub event names or actions: | First Trusted Braid Mention on a dormant Work Item | `mention`, consumed as `assign` (activates the group, exactly like native assignment) | | `issues.unassigned` (canonical-reread confirmed) | `unassign` | | Comment/review created, `pull_request.synchronize`, review requested; Trusted Braid Mention on an already-active Work Item | `mention` / `wake` | -| Body/description/comment edits or deletions, review dismissed, review thread resolved | `invalidate` | +| Relevant external body/description/comment edits or deletions, review dismissed, review thread resolved | `invalidate` with durable `requires_attention` | | `closed` / `reopened` / `merged` | `lifecycle` | | Correlated Braid App or Profile-actor writes | `origin_echo` (recorded, never wakes or invalidates the same Agent) | | `ping`, unknown variants | `noop` (recorded as reconciliation evidence) | @@ -144,6 +148,23 @@ review-thread resolution. Braid paginates every connection to completion: - PR conversation comments, reviews, and every review thread/comment page with resolution/collapse/outdated/path/line metadata. +Context snapshot connections share one stateless first-page GraphQL operation +(`IssueFirstPages` / `PrFirstPages`). Each connection with `hasNextPage` continues +independently using its existing cursor query; Project V2 is selected only when +enabled. Root and complete native-association markers still bracket every read. +There is no cross-round cache or root-marker shortcut. Associated Issues, project +field values and review-thread comments retain their complete independent reads. +Partial data/errors and unknown unions fail the snapshot, not merely one section. + +The local HTTP bill (Projects disabled, single page, empty associations/threads, +no drift) is Issue **13 → 5** and PR **10 → 5** requests. Previously association +connections were read three times (before marker, snapshot, after marker); they +still are, but the snapshot read now shares the first-page operation. Two root +reads and two association-marker reads remain deliberately separate. A comments +continuation adds one request; a full drift retry repeats the bill. An open +associated Issue adds its own Issue bill and each thread/project field connection +adds its pages. These are mock HTTP counts, **not measured GitHub point savings**. + REST supplements GraphQL for endpoints or lifecycle evidence not exposed in a stable query. Requests pin an explicit supported API version. @@ -173,10 +194,132 @@ See GitHub's [linking contract](https://docs.github.com/en/issues/tracking-your- ## Reconciliation and Tombstones -Webhook is an observation, not a complete history. Reconciliation runs every -60 seconds by default, separately from debounce, and after reconnect, unknown -variants, delivery gaps, or outbox uncertainty. It rereads active Work Items, -direct associations, and all Context connections. +Schema 11 separates the latest Context/tombstone projection (`canonical_objects`) +from the producer's processed frontier (`processed_objects`). A projection read, +including reading an associated Issue through a PR, cannot advance the latter. +The producer classifies one complete observation outside SQLite, then atomically +compares its expected frontier, admits all resulting events, and commits the new +frontier. Failure or a changed precondition commits neither. Network awaits never +occur inside that transaction. The frontier is an acknowledgement of classified +input, not a second current-content authority or another execution queue. +完整观察在 API 遍历前取得 processed frontier 与已接纳事件 watermark,提交时同时 +校验;读取期间新 delete 等事件到达会拒绝整个旧快照。缺失是负向观察,不是更晚的 +上游 updatedAt;本地 tombstone 的时间不能压过 API 当前仍可见对象。正向完整观察 +可以纠正它,旧 webhook 不可直接复活 tombstone,真正较新的正向 edit 仍受保护。 +冲突报告包含 node、类型、双方版本、对象状态与证据来源,不包含正文。 + +Context 的完整成员集合必须先维护 ledger,再作 Agent 展示过滤。Operational Status +是受管输出;过滤它不表示删除,它的恢复也不产生业务 Wake。展示投影不能充当缺失 +推断的输入。这一约束同样适用于 Issue 与 PR conversation。 + +Event staleness likewise uses admitted change evidence and the processed frontier, +never a Context cache row. Root synchronize/assignment hints do not acknowledge +body changes. Comparable upstream timestamps may reject older facts; lifecycle +suffixes and review-thread projection strings are not lexical clocks. A complete +snapshot older than a classified fact is retried without advancing its frontier. + +A correlated title/body version proves only those published fields. A separate +root metadata fingerprint includes relevant non-body facts and native PR edges; +a metadata/edge change can require attention even when `updatedAt` and body did +not change. Missing action provenance is handled conservatively rather than +turning the entire root into an Agent echo. + +Change identity also distinguishes a versioned object from an occurrence. +GitHub delivery GUIDs and built-in event sequences identify occurrences; +returning to the same unversioned thread state is not a redelivery. Complete +observation transitions are committed under their expected frontier and may +reuse the latest matching admitted state transition when non-state metadata is +unchanged. `deliveries.effect_event_id` records that reuse explicitly. A missing +new event is therefore not silently treated as successful delivery: its existing +cause must be bound and auditable. PR activation separately requires its exact +request/target event, not an arbitrary dedupe collision. + +Visible semantic fingerprints exclude timestamp-only and filtered HTML-comment +changes. Versioned raw-content evidence remains separate for correlation and +ordering. Original comment authorship is usable only for an API-proven unedited +creation; an edited comment's unknown current actor cannot inherit the creator's +trusted-mention authority. Already-active responsibilities still receive ordinary +attention for real revisions when the current action actor is unknown. + +Root Issue and PR reconciliation retains separate fingerprints for title and body. +An edit qualifies as an Agent echo only when every changed field has matching +native authorship evidence. A title change uses the observed rename transition and +a body change uses the observed editor evidence. A matching signed webhook can +supply a field's previous value and actor. Changes in other canonical metadata +and changes with unresolved authorship retain external attention. Publication +receipts establish command outcomes, while reconciliation uses upstream +authorship evidence independently. + +迁移建立新的观察边界,不能据此证明历史丢失输入已执行。Schema 12 将已接受且 +固定精确 PR、却没有 activation receipt 的错误 applied ensure 重新交给唯一 outbox。 +这是原请求的交付恢复,不根据任意 native 关联新建职责;当前 canonical 源/目标、 +Profile、生命周期与读取期间事件栅栏都必须重新验证,撤销/阻塞的角色不被自动重建。 + +Webhook 是观察,不是完整历史。巡检在正常预算下按两档到期:OPEN Work Item, +或仍有 materializing/active/finalizing Assignment 的条目,完整巡检成功后默认 +60 秒再次到期;其他已关闭或合并的历史条目为 **30 分钟**。关闭不意味着收尾已 +完成,finalizing 不降频。历史条目的 reopen webhook 若丢失,可能需要 30 分钟 +加上扫描、网络和配额等待时间才能恢复。Webhook 与前台 Context/turn 语义不变。 + +`scheduler.reconciliation_seconds` 是 hot 条目的最小成功间隔,不是 worker tick。 +worker 每 `min(reconciliation_seconds, 5)` 秒检查本地到期事实与已知预算;本地 +检查本身不请求 GitHub。检查额外延迟至多 5 秒,不包括其他对象遍历及网络/预算 +等待。正常预算下的周期不是独立于 GitHub 可用性的硬 SLA。 + +Schema 8 分别持久化完整成功时间和尝试时间。Webhook、关联读取、Context Revision +写入与普通 `observed_at` 不推进成功时间;失败或部分读取也不算成功。尝试之间 +至少间隔一个 hot 周期,避免每 5 秒检查变成每 5 秒重试。成功项不会因后续条目 +失败或进程重启被重新全读。到期项跨仓库按最久未尝试优先,每次尝试保留巡检回执, +单项失败不阻断后续条目。没有实际遍历的空检查不清除已有降级健康状态。 + +巡检仍完整读取直接关联和全部 Context connection,不使用跨轮 Context 缓存, +也不根据根对象 `updatedAt` 跳过子连接。只有完整物化后才能推断 tombstone, +不能把预算中止的部分列表当作删除证据。 + +### Installation GraphQL budget + +实例内显式共享一个按 installation 分组的准入 owner。运行期仓库客户端及 +`for_repository` 派生客户端共享它,不同 installation 独立。每个安装的锁覆盖 +GraphQL 请求至响应记账,确认限流后排队请求不能继续穿透。派生客户端用 +`Arc` 共享自动刷新 token 缓存,而不是复制缓存或每次重新签发 token。 +同 installation 的跨仓库派生也无需重复完整 App connect/token/viewer 初始化。 + +所有 GraphQL 调用(含启动时 repository/viewer 身份读取)统一走 raw transport。 +准入失败立即返回,不在请求内 sleep 或循环重试;每个已准入请求及 body decode +合计限时 30 秒。Octocrab transport 隐式重试关闭,REST 429/5xx 仍是可恢复错误, +由持久 outbox 重试,而不是永久拒绝。App discovery/token 和 REST 不受 GraphQL +预算控制。首次确认限流即返回可恢复错误,不能等到后续本地拒绝时才允许写入重试。 +明确的权限拒绝仍是权限错误,不作为 installation 耗尽处理。 + +响应 DEBUG 记录可信静态 operation、foreground/background class、installation、 +response resource、请求计数、request ID、HTTP status、latency、used、remaining/reset +配额窗口;repository/work item 仅在日志/span,不是 metric 标签。普通成功不再逐条 +INFO 刷预算;准入/限流/失败保留 WARN 事件及响应元数据(若已收到),不包含正文、 +token 或 variables。采样证据路由不变。header used delta 仅在可比 resource/reset +窗口内计算,仍可能包含别的消费者,**不是单 operation cost**。 + +Braid-owned Context/identity queries显式选择 `rateLimit { cost }`,仅服务器实际返回 +的值被计入 `braid.github.graphql.points`;缺少该字段是 unknown,不推测为零。 +`braid.github.requests` 与 `braid.github.request.duration` 按低基数 +operation/class/resource/outcome/cost_known 聚合,独立记录已准入请求与单调时长。 +这些指标及上述归因日志的 coverage **仅为 Braid GraphQL transport**,包括 canonical +Context 完整遍历;`resource=graphql` 是固定的 metric 标签。REST(包括 `write_rest`) +和 App/installation-token 请求不在此测量范围,其请求数、时长和成本仍为 unknown, +不能把这些指标视为所有 GitHub 调用的总账。 +未收响应/失败也有请求计数;本地准入拒绝没有 HTTP 请求,不计入 requests。 +任意未识别 query 名归为 `other`,不改写调用者 query,不把其名字变成无限标签。 + +主限额耗尽等待 reset,次级限流遵守 `Retry-After` 秒数。缺少提示的限流和网络 +故障从 10 秒开始指数退避,上限 300 秒加至多 25% 抖动;后续失败不能缩短已收到 +的服务端冷却期限。到期仅允许串行探测,成功响应重置退避。后台在剩余点数不大于 +100 时让出余量;缺少 reset 则有界冷却后探测,不永久停摆。这只是前台余量, +不是保证任何大 Context 都能在剩余配额中完成。 + +预算不足时巡检报告 `degraded/delayed`,保留未完成条目供后续尝试,不强行追赶。 +预算/冷却只在进程内共享,不持久化:重启保留对象成功时钟,但首次响应前不知道 +剩余额度;独立 CLI 和其他消费者仍可能耗尽共享 installation 配额。自动恢复只 +涵盖仍有重试入口的操作,不自动解除业务 `blocked`(操作边界见部署文档)。 +本地 HTTP/时钟回归验证机制,**不是线上 installation 消耗测量**。 An object previously observed but now missing becomes a tombstone carrying only stable ID, last known author/time metadata, and `deleted`. Local state never @@ -217,29 +360,26 @@ The first shipped write vertical is intentionally small and recoverable: ```shell braid gh comment create owner/repository#123 \ --config /absolute/path/to/braid.toml \ - --profile issue-codex \ + --profile issue-codex --source-turn TURN_FROM_RUNTIME_PROMPT \ --request-id stable-agent-message-key \ --body 'Concise public update' -braid gh pr ensure --comment 123456789 \ +braid gh pr ensure --comment 123456789 --source-turn TURN_FROM_RUNTIME_PROMPT \ --config /absolute/path/to/braid.toml ``` -`comment create` derives the public role from the canonical Issue/PR target and -the Profile tags. The writer prepends one attribution block and removes exact +`comment create` derives the public role from its durable source Group, not the +canonical target or Profile tags. Tags only select role eligibility. The writer prepends one attribution block and removes exact repetitions of that generated block from the start of the supplied body, so a caller retry or model mistake cannot duplicate it. `--request-id` is optional; -exact attributed body content provides the fallback retry identity, while an +exact locally accepted request content provides the fallback retry identity, while an explicit value lets the Agent name retry intent. Command results expose only bounded operation/target/Profile/lifecycle and semantic GitHub comment/PR references. Internal write IDs, node IDs, digests, and retry counters remain in -SQLite and never enter Agent tool output. `pr ensure` accepts an optional -explicit `--head`, then the -sole same-repository Development branch, then its deterministic -request-comment-derived branch. - -`pr ensure` first selects an explicit requested head, the sole unambiguous -Development linked branch, or a deterministic request-comment-derived ref. It +SQLite and never enter Agent tool output. `pr ensure` accepts an optional explicit `--head` and, in a multi-repository +instance, requires `--repository`. It first selects an explicit requested head, +the sole unambiguous Development linked branch, or a deterministic +request-comment-derived ref. It compares that head to the intended base. When GitHub has no differing commit, Braid uses the Git Data API to create a commit with the current head tree and parent, message `chore(braid): initialize implementation request `, and @@ -252,6 +392,54 @@ requires Contents write for App installation [commit](https://docs.github.com/en/rest/git/commits) and [reference](https://docs.github.com/en/rest/git/refs) creation. +### Durable acceptance and one executor + +`comment create` and `pr ensure` perform local configuration, format, Profile and +available source-binding checks before any GitHub await. One transaction records +an immutable request in `write_intents` and its execution obligation in +`github_write_outbox`. The CLI never claims or mutates; it immediately returns +`queued` and a stable public `request-…` ID, including when the service is offline. +`braid gh status --config --json` retrieves the receipt without +resubmitting body content. The public ID is separate from the internal intent ID. +Receipt projections include operation, target, lifecycle, ensure stage/head/base, +and confirmed GitHub references; queued is not published. Same key and digest +returns the same receipt; a changed request conflicts. Raw comment content and a +Profile snapshot are accepted as a typed, not-yet-target-validated request. +Canonical target kind, operation/source association and installation write permissions +are still verified before mutation. This does not expand operation/target rights. + +Only the runtime-owned outbox claims and settles writes, with runtime generation, +owner ID and monotonically increasing attempt fences. Network awaits never run +inside SQLite transactions. A known pre-mutation failure stays pending; uncertain +execution requires canonical recovery, never blind replay. Per-task durable +`next_attempt_at` honors the shared installation reset/cooldown and bounded +exponential backoff; the 250ms local worker tick is not a quota probe. Restart +recovers sending work as uncertain, including migrated legacy CLI obligations. +Reactions and operational status continue on the same executor; Built-in uses +its existing upstream adapter and the same fenced claim/settlement API. + +Ensure accepts raw comment ID/head/Profile before planning. Remote planning freezes +base/head, request comment and Issue identity, bootstrap authored time and PR +Profile once in `implementation_requests`. That table is domain progress, not +another queue. Recovery reuses `planned → head_ready → pull_request_ready → +associated → activation_pending`, including a confirmed PR number even when it +is no longer in open-PR listings. Native association and the delivery-key-idempotent +initial Activation must finish before applied. Changed activation Profile +configuration is rejected rather than silently activating another Profile. + +`PublicationSource` is the typed extension seam for source-aware maintenance: +agent/assignment/generation, Profile/revision, session/turn and Context revision +are captured from durable worktree/session state and rechecked before mutation. +Completed turns retain accepted obligations; pending invalidations, replaced +sessions and newer assignment generations fence old output. An uncertain comment +is first looked up and acknowledged if uniquely found, even if the source was +subsequently fenced; it is never resent under a stale fence. Current launchers +only supply `BRAID_AGENT`, not a runtime-signed invocation handle. Worktree lookup +is therefore a provenance check, **not** an environment-based authority proof or +an OS sandbox. The source-aware memory component must provide an explicit bound +invocation/operator distinction; removing an environment variable cannot be +claimed to be securely prevented by this layer. + Every Braid-owned mutation first commits an immutable write intent. States are `pending`, `sending`, `uncertain`, `applied`, `conflict`, `ambiguous`, `rejected`, and `superseded`. A timeout becomes `uncertain`; Braid rereads @@ -275,3 +463,113 @@ key, excludes its ID from Context, and never hides debug metadata in the body. Profiles choose Issue, PR, or both direct surfaces. Status covers context pressure/unavailability, provider/transport unknown, blocked Profile/worktree, and ambiguous/rejected Braid writes. + +公开故障投影不是只追加的告警。唯一 outbox owner 领取写入前,按持久账本对账已有 +status:最新 active generation 的当前 Session 中,Provider 已接受的 running turn +或正常 completed turn 才是接手证据;仅创建 assignment、替换记忆或工作树干净不算。 +同代在故障之后有新的确认,可将原 comment 标为恢复;新代确认后,旧代 comment +标为有时间的历史故障并说明由哪代、哪个 Profile 接替,旧代并未被解阻。正文明确 +这是最后确认的执行状态,不是代码、review 或产品完成,也不是持续可用保证。 +正常 turn 不因此新增评论;重启从账本补偿,没有额外队列或周期性模型调用。 + +status 的 desired publication 与远端 comment 身份分开。每个 outbox publication +持久绑定原 status key;旧 create 在发送中或 uncertain 时,新投影等待它对账,旧 +回执仍能补回 remote ID,但不能覆盖较新投影的生命周期。确认 ID 后新投影改为 +更新同一 comment;未发送旧投影可 supersede。重复故障不更换回执指针,故障恢复后 +再次发生则是新的 publication,不由正文永久去重。已被新代接替的旧代故障晚到, +不会把公开状态降回当前失败。若旧 create 的恢复匹配到多个 App 评论,则远端身份不唯一: +同一工作项、Profile 和 generation 的后续 create 也记为 ambiguous,不再 POST,更不猜测 +PATCH 目标;不影响其他键。只有已确认的远端身份才允许更新原评论。Schema 13 对已有 status/outbox 回填映射,不改职责状态。 + +For initial `pr ensure`, the source is the calling Issue assignment; the frozen +PR Profile selects the new implementation role and must not replace that source. +Cwd/session resolution checks the durable source role and treats an explicit +comment Profile as an assertion, not an identity override. REST publication shares +installation cooldown/admission with GraphQL while keeping REST response counters +out of GraphQL point accounting; server Retry-After/reset deadlines reach the +outbox's durable next-attempt deadline. + +### Source-bound title/body maintenance + +`PublicationSource` remains the single durable provenance model in +`write_intents.source_binding`. Agent CLI entry requires a runtime-prompt +`--source-turn`; resolution cross-checks the actual canonical cwd with the active +worktree, assignment generation/repository/role, configured Profile materials +revision, current session and Context revision, observed running or completed +turn, invalidation and replacement fences. An unobserved starting turn never +borrows an older completed identity. The selector is not a bearer capability. +`--operator` is explicit, forbidden in Agent runtime worktrees, and recorded as +Operator. This does not claim hostile same-UID process isolation. + +`pr read`/`issue read --output PATH` exports a typed canonical title/body snapshot +including updated version and SHA-256 digest. `pr edit`/`issue edit --snapshot PATH` +accepts `--title` and/or `--body-file`, with Profile assertion, invocation binding +and stable `--request-id`. It serializes `AcceptedRequest::Edit` into the existing +intent + unique `agent_write` outbox transaction before any GitHub access. No +migration or additional executor is required. Only the existing runtime owner +may execute; all existing attempt/restart/installation cooldown fences apply. + +The own-Item permission and native direct cross-surface association are checked +separately from source attribution. PR source may edit only its own PR or its +current directly associated OPEN Issue; Issue source may edit only its own Issue. +Related comments remain valid in both directions. The source role never changes +to the target's role. PR ensure additionally requires its Issue source to own the +request comment's Issue. + +Before body mutation the executor reads a canonical snapshot, rejects a changed +digest as `conflict`, revalidates target state/association/installation rights, +reads again, and checks the source/owner fence immediately before PATCH. It +preserves recognized existing ensure-request metadata and explicit closing-source +blocks (including ATX/Setext headings) when rendering source attribution once. +Complete supported top-level paragraphs/headings are prefixed before replacement +Markdown, outside new unclosed fences/comments. Context-dependent existing sources +that cannot be reliably preserved are refused for body replacement; title-only +edits retain them unchanged. Neither ordinary closing words nor new code, lists +or links are forbidden. This is bounded preservation of known sources, not an +emulation of GitHub's private parser or a guarantee that relationship sets cannot +change. + +An authorized body may add native closing text. `braid gh` is an identity surface, +not a Markdown semantic sandbox, and adds no dedicated relationship operation. +New body text never supplies authorization to edit a different Issue: execution +queries current GitHub canonical direct edges. A GitHub-confirmed new edge can +expand the PR Agent's maintainable open Issue set under existing source/Context +fences. Plain references and closing words alone grant no authority or Group +activation/scheduling. Canonical graph reconciliation remains independent of +Agent-origin wake suppression; explicit handoff constraints remain separate. +No write-then-rollback is used to simulate CAS. An applied edit confirms content, +not relationship-set equality. + +PATCH's returned title/body must match; an unconfirmed send +stays uncertain and is read back before retry. Exact resulting content confirms +applied even if authority has since expired; any different version is a conflict, +not proof of success. This is optimistic conflict checking, not atomic GitHub CAS; +the final read/PATCH interval remains a documented concurrency limitation. + +### Explicit existing-generation PR handoff + +`writer::handoff` uses the source-bound `Invocation`, `AcceptedRequest` and +`github_write_outbox` during admission. Once accepted, Schema 19 keeps the +source Issue, target assignment generation and next-turn-only constraint in the +input ledger. The handoff receipt references that event. +Operator/PR sources, inactive/blocked/missing targets, finalizing +assignments and non-OPEN sources/targets are refused. Queued/uncertain Issue +body edits must be resolved before acceptance/delivery; no workflow DAG is added. +The existing GitHub reads recheck OPEN state and native `closingIssuesReferences` +within the connected repository installation, never comments or request Markdown. +All network awaits are outside SQLite transactions. + +In the outbox attempt settlement transaction, Braid rechecks the source fence, +current target assignment and scheduling eligibility; inserts the ordinary +`wake/pr_handoff` event once; merges its batch with normal quiet/count; and commits +the receipt/outbox state. A stale fence rejects admission before delivery. At +dispatch, the input ledger supplies the frozen constraint. The worker +materializes and renders the current PR and associated Issue Context before +provider send. An urgent steer receipt acknowledges the event IDs actually +sent. An accepted handoff arriving during that call remains queued for the next +ordinary turn. +Failure defers the unsent claim. This appends current working data to the existing +session, not a Context reset, urgent steer or parallel turn; it does not advance +the session's replacement fence. The boundary rechecks the bound target and +requires each handoff source still appear as an OPEN directly associated Issue. +No transport, pagination, canonical query or OriginEcho rule changes are involved. diff --git a/docs/20-product-tdd/lifecycle.md b/docs/20-product-tdd/lifecycle.md index e75ca26d..db747454 100644 --- a/docs/20-product-tdd/lifecycle.md +++ b/docs/20-product-tdd/lifecycle.md @@ -4,6 +4,10 @@ This document owns the mechanical transition model from GitHub canonical changes to Context replacement, provider turns, reactions, and shutdown. Product interpretation remains with the Agent. +Local 对象写入生成同一组内部事件,经持久事件桥接进入现有调度。关闭、重开、 +撤销指派及 Context 更换复用本合同;本地空间不因所有对象关闭而结束。对象与 +事件身份带独立 Local namespace,不将本地数据库当作 GitHub 当前正文权威。 + ## Agent Group Lifecycle Each Work Item/Profile pair has an Assignment Generation and one state: @@ -16,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. | @@ -41,11 +45,11 @@ names alone: | Previously absent included scalar/set value added | Wake | Add reference; debounce/count. | | Comment/thread unminimized or unresolved | Wake | Restored body enters Context; debounce/count. | | PR synchronize, checks terminal, reviewer request change, or other excluded implementation fact | Wake reference | Does not enter Context; debounce/count. | -| Existing visible body/title/description edited or cleared | Hard Invalidation | Replace Context; continue only if a turn was interrupted. | -| Included scalar replaced/cleared or set member removed | Hard Invalidation | Same. Dedicated close/unassign rules take precedence. | -| Comment/review deleted or minimized; review thread resolved | Hard Invalidation | Remove body, retain lifecycle metadata, replace Context. | +| Existing visible body/title/description edited or cleared | Hard Invalidation + attention | Fence/replace Context; retain one ordinary input when idle, coalesce one continuation when running. | +| Included scalar replaced/cleared or set member removed | Hard Invalidation + attention | Same. Dedicated close/unassign rules take precedence. | +| Comment/review deleted or minimized; review thread resolved | Hard Invalidation + attention | Remove stale body, retain metadata and an input to consider the revision. | | Direct Issue↔PR association graph changes | Hard Invalidation for affected PR groups; addition also Wake | Rebuild full direct graph. | -| Non-Agent edit to an open direct Associated Issue description | Cross-surface Hard Invalidation | Debounce edits, then interrupt/fence active PR and replace Context. | +| Non-Agent edit to an open direct Associated Issue description | Cross-surface Hard Invalidation + attention | Debounce, fence/replace active PR Context; an idle active PR also retains the input. | | Other included direct Associated Issue change | Dependency Dirty plus Wake when Human-origin | No active PR interruption; rematerialize before next PR turn. | | Closed Associated Issue body/comment change | No PR effect | Content is excluded until reopen. | | Correlated Braid App Agent write, or write by the Profile's configured stable GitHub node identity | Agent-origin | Update canonical ledger; no wake/reset of originating group. | @@ -58,7 +62,10 @@ Each group has one pending batch. A Wake Event starts/resets a 30-second Quiet Window and increments the unsuperseded Wake count. The batch becomes runnable when no Wake arrives for 30 seconds or the count reaches eight. Both values are Profile-overridable. Lifecycle/invalidation refs can join the batch without -turning into Wake Events. +turning into Wake Events. `requires_attention` separately records whether a +revision still owes ordinary input delivery; consuming an invalidation for +Context replacement does not consume that batch. It never activates a dormant +or closed responsibility. A Trusted Braid Mention is an exact configured handle in visible Markdown prose from a current repository `MAINTAIN` or `ADMIN` actor. Code spans/blocks, @@ -83,7 +90,8 @@ canonical diff -> create fresh physical Provider Session -> inject complete current GitHub Context -> if an active turn was interrupted: start one continuation turn with refs - else: return idle unless the batch independently contains Wake/urgent input + else: preserve the ordinary attention batch and its original quiet deadline + -> dispatch at most one turn with current Context when that batch is runnable ``` Output emitted after fencing is retained in provider/telemetry evidence but is @@ -100,15 +108,24 @@ Title/label/project changes with the same visible body, HTML-comment-only edits, closed Issues, inactive edges, and inactive PR Agent Groups do not create this invalidation. The derived reference enters the PR's ordinary Quiet Window/count batch; the Wrapper never infers semantic urgency -from the edited prose. +from the edited prose. Other relevant source revisions with unchanged visible +body create an ordinary dependency Wake, not an interruption. + +Origin is established by this action's verified actor or by an exact correlated +publication version/content. Creator identity and a retained Braid attribution +block cannot establish who made an edit. Unknown edit origin is not silently +classified as Agent-origin. ## Assignment and Terminal Lifecycle -- In native Agent App assignment mode, Issue unassignment starts/resets the - same Quiet Window. Once settled, Braid safely interrupts an active turn, - archives its physical session, and moves the generation to `sleeping`. - Reassignment starts a new generation/session. Ordinary-App mention fallback - does not fabricate assign/unassign lifecycle events. +- GitHub 原生指派模式按 Quiet Window 合并 Issue 撤销指派事件。窗口到期后, + Group 重读当前 assignees。若仍已指派则消费这次事件。确认撤销时,正在执行的 + worker 和空闲 worker 使用同一停止流程。内建平台直接处理不可撤回的撤销事件。 + Group 在关闭期间继续接收原有 turn 的终态。平台撤权暂时失败时,已经收到的终态与 + 错误仍须持久化。原生停止和平台撤权均已确认后,Group 才将该代记为 `retired`; + 此时仍缺 provider 终态的 turn 记为 `unknown`,并按该 Profile 的配置发布执行状态。 + 若原生停止已保存而撤销尚未完成,重启的 worker 沿原顺序结算撤销并确认平台 fence, + 保留已观察的终态,不恢复旧物理会话。该代未完成的 Context reset 保留在历史中,不再创建会话或阻止有限 run 完成。重新指派创建新一代及新会话。 - Issue/PR close or PR merge never interrupts the current turn. The lifecycle event grants exactly one Finalization Turn after the current terminal, or immediately when idle. Afterwards closed Issue and closed-unmerged PR groups @@ -117,6 +134,11 @@ from the edited prose. needed, and queues one normal debounced Wake turn. - Delivery duplicates and events received while sleeping cannot grant a second Finalization Turn. +- GitHub reconciliation keeps closed roots hot while their Assignment is still + materializing, active, or finalizing. Only terminal history without a live + Assignment moves to the 30-minute recovery interval. Installation budget + pressure delays canonical reads and is exposed as degraded/delayed health; + it introduces no new Agent Group lifecycle state (see `github.md`). ## Reaction State @@ -132,18 +154,36 @@ the exact Trusted Braid Mention comment owns a turn cycle: | transport/provider outcome unknown | `eyes`, `rocket` plus Operational Status Comment | Ordinary turns never receive `rocket`, `+1`, or `confused`. Braid manages only -its own App reactions and never removes Human reactions. Reaction writes are -desired-state outbox operations; target deletion produces a tombstone, not a -replacement comment. +its own App reactions. Event admission records `eyes` with the exact reaction +target. Native start, terminal, and Context reset record their feedback with the +corresponding turn transition. The publisher consumes those durable requests and +owns the outbox attempts and receipts. An accepted event and a recorded turn +transition remain available during an outbox failure. A reset retains the +request to clear `rocket` before its remote ID is known, so a late successful +receipt can still be removed. Target deletion produces a tombstone. ## Provider and Transport Unknown 连接丢失只证明旧执行结果未知,不能据此生成成功/失败 reaction。Core 将旧 turn -记为 Unknown 并 fence 旧会话,发布 Operational Status;随后物化完整当前 Context, -保留 assignment 和 worktree,将已接收输入重新送入调度。它不会盲目重发未知结果的 -provider RPC,也不承诺任意外部副作用 exactly-once。历史 Unknown 记录不因恢复成功消失。 -若断连发生在已经 interrupting 的 Context reset 中,Unknown 同样使 reset 进入 -materializing,继续既有 continuation 规则,不能让 reset 永久等待。 +记为 Unknown 并发布 Operational Status。账本 fence 不能阻止旧执行通过 Git、GitHub +或 shell 继续产生副作用;替代执行启动前必须取得 adapter 的停止成功结果。停止失败 +或无法确认时保留旧句柄和现场,将工作项阻断并公开原因,不重发结果未知的原生 RPC。 +成功取得 adapter 的原生停止回执后,Harness 按原会话持久保存停止事实。Context +reset 或 reopen 可以凭原句柄取得新回执,或在冷启动后使用为旧会话保存的回执。 +进入 reset_pending 或 idle 本身不能证明停止。同一物理会话恢复前先清除旧停止 +记录。内建平台封禁旧执行代次与原生停止分别尝试并确认,两项都成立才允许替代。 +重放只接续 canonical Event References,旧执行已发生的外部副作用继续保留。 + +Context reset 可以记录待物化状态,但只有旧执行停止成功才创建替代会话。Pi 锁定材料先 +收口 owned 执行,再释放 stdin 管道句柄以发送 EOF,等待父进程退出并核对离线后代清理 +回执;外部基础 Pi 等待原生 abort 和父进程退出。Unix 管道的 +异步 shutdown 不会关闭该句柄,不能代替释放。进程观测记录实际 PID、原生会话、 +runtime generation、退出状态或具体等待错误;失败后的强制清理保留原失败和清理 +结果,不将父进程退出追认为工具停止成功。单独杀父进程不证明其工具已停止。 +Core idle 表示 turn 与 Wake batch 状态,不能推导插件后台结果已消费或进程静止; +managed 执行状态由 Pi 材料独立记录,生命周期边界见 [provider 合同](app-server.md)。 +Codex 保留共享连接,等待目标 turn 的真实终态;连接丢失或通知缺失时不杀其它健康 +会话来换取恢复。停止不能撤销已经发出的外部请求或收回脱离原生管理的后台服务。 ## AgentSession Event Stream @@ -158,6 +198,11 @@ event stream, not raw provider notifications. Each active session yields a Delivery semantics are part of the contract: +普通 Failed 与 Unknown 都沿配置的 Operational Status surface 发布故障记录,包含 +对应 turn、原生会话和具体原因。完整错误先存入 `turns.error`,再生成有界公开摘要; +公开内容移除配置中实际使用的 provider key,本地原始错误仍属于敏感运行材料。 +数据库 schema 3 通过新增迁移保存该字段,旧的已发布迁移保持不变。 + - **Exactly-once per fact.** One `TurnStarted`, then exactly one `TurnTerminal` — including session death, where the adapter synthesizes `Unknown` for the in-flight turn before going quiet. There is no second @@ -170,7 +215,7 @@ Delivery semantics are part of the contract: Core 使用句柄的 latched `is_unavailable()`,包括 idle 与晚订阅情形。 一个句柄失效不触发全局 epoch,也不重建健康的同类会话。 - **持久化恢复兜底。** 恢复缺失/失效句柄之前,Group 将遗留的 starting/running - turn 记为 Unknown。只向具备可用句柄的 opaque session ID 领取 runnable turn; + turn 记为 Unknown 并阻断缺少停止依据的恢复。只向具备可用句柄的 opaque session ID 领取 runnable turn; 不可用会话的输入保留待处理,不占住其他可用会话。 Responsibilities do not overlap: @@ -179,13 +224,35 @@ Responsibilities do not overlap: debounce, batching, urgency, and retry — an unsent batch simply remains runnable. - **`AgentSession`** only dispatches: idle, it starts a new turn; running and - `steering`, it forwards the steer; running and not steering, it drops 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. + `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. The adapter handles native interruption as part + of confirming session shutdown. - **Group** 决定 Work Item 的物化、恢复、Context replacement、睡眠和退役, `SessionManager` 只索引中立句柄。替换完整 Context 不等于创建新的逻辑 Agent; adapter 的物理 ID 是可替换的执行绑定。 - **Adapter** 管理进程、连接、物理会话和通知翻译,不读取 GitHub、不操作业务 store。 - Group 释放旧句柄时,adapter 清理其资源;Codex 共享连接和 Pi 独立进程都服从同一契约。 + Group 释放旧句柄时,adapter 必须报告停止是否成功;失败不删除句柄、不启动替代执行。 + Codex 共享连接和 Pi 独立进程都服从同一契约。 + +## 有限 root 运行 + +`run` 复用 built-in workers、provider、执行封禁与 shutdown,独立的 Harness ledger +隔离当前 run 与常驻 serve 的旧指派。平台原子保存父子 Issue,固定 root 的 run ID、Harness client 身份和交付 ref, +并据此扩展协调 writer 的范围;执行身份和终态仍归 Harness,平台没有第二份运行工作图。 +仅注册 run root 的关闭会立即撤销整个后代范围 grants,普通 serve 的对象关系保持原合同。 + +有限 run 的 Issue 指派保留真实 wake 批次,直接授权设计工作;普通 serve 指派仍只创建空闲会话。新会话在首轮认领前先处理已排队的 Context reset,reset 不消费独立的指派输入。 + +root 的职责只在 run 中显式注入。子项生命周期、候选发布、讨论和设计更新回流到祖先;讨论和设计通知只携带对象及变化类型,不复制正文。 +以 writer 对象识别自身回流,不能用 profile 判断,因为 root 与子项可能共用 profile。普通 Agent 评论 +仍不要求公开应答或制造新一轮循环。统一准入在认领 turn 之前取得许可,并持续持有至 +真实 terminal、reset 或停止;限制的是在途 Braid turns,不是物理会话总数。 + +运行准备、事件摄取和开放 root 的轮询使用平台 SQLite 范围查询,读取成员和注册身份。 +root 开放时静默不形成终态。root 关闭后关闭执行准入,再读取包含交付 ref 和合并事实的 +报告,依据对象及未决写入决定 completed 或具体 blocked。交付 Git 读取失败保留明确 +诊断。终态使用执行封禁与原生停止屏障确认收尾。 +failed、stopped、blocked 与完成分开,停止确认不完整禁止覆盖执行。输入及执行 +相关的解析配置绑定 run ID。遥测配置可为该次执行单独调整,保留原始冻结文件; +接续不得借同一身份更换需求、创建重复 root 或隐式接管无关工作。 diff --git a/docs/40-deployment/README.md b/docs/40-deployment/README.md index 1c8978b9..5c8bb546 100644 --- a/docs/40-deployment/README.md +++ b/docs/40-deployment/README.md @@ -6,45 +6,62 @@ GitHub mutation authority by itself. ## Supported Shape -The packaged macOS arm64 `braid` archive has a SHA-256 checksum. The binary runs -without Python, PDM, Cargo, or a source checkout. Linux x86_64 is the next target. +The supported packaged artifacts are checksummed macOS arm64 and +Linux x86_64 `braid` binaries produced by the release workflow from the same +locked source. They run without Python, PDM, Cargo, or a source checkout. Runtime prerequisites remain explicit: - Git and `gh` for Agent workflows; -- the configured Codex or Pi executable and its credentials; +- pinned Codex executable and authenticated provider home; - Wrangler for the free Quick Tunnel acceptance path; - GitHub App ID/private key/webhook secret and installation; - optional OTLP endpoint; full campaign acceptance requires one. Release artifacts include `braid`, `LICENSE`, `README`, default config example, -OTel Collector example for optional tail sampling, SHA-256 checksums, and +OTel Collector example for a queryable OTLP backend, SHA-256 checksums, and release notes generated from `CHANGELOG.md` under SemVer. +Pi 可使用外部基础 CLI 或 [锁定原生材料](../../native/pi/README.md)。需要 +subagents/background 的共同结果与停止合同时,先安装材料并明确选用插件, +配置 `[[runtimes]].executable` 与 `native_runtime` 为同一安装的入口与 manifest。 +`doctor` 校验文件身份,实际启动核对 live 能力;安装或升级不修改系统全局 Pi。 + ## Configuration The instance `config.toml` is versioned independently from binary and -database schema. It -contains no secret values; secrets use file references or environment-variable -names. The main sections are: +database schema. It contains no secret values. Provider credentials always use +explicit `credential = { kind, file }` references (Braid-schema `api_key` / +`oauth` files, or `none`); the GitHub webhook secret separately supports a file +reference or environment-variable name. The main sections are: -- GitHub App/repository/handle, API version, webhook and reconciliation; +- GitHub App/repository or explicitly configured multi-repository set, + handle, API version, webhook and reconciliation; - the instance key under `[instance]`; - Profile definitions/tags/default PR Profile/context byte budgets/status surfaces/provider/workspace/resources; - scheduler quiet/count settings; -- `[[runtimes]]` adapter executables/version pins and provider home; -- `[[llm_providers]]` provider credentials (file references, not values); +- `[[runtimes]]` adapter executables/version pins and adapter home; +- optional `[[llm_providers]]` for Pi profiles: explicit `credential` (file + references, not values) plus `base_url`/`api`/`models` declarations from which + the Pi adapter derives `models.json`; Codex profiles do not declare them; - SQLite/runtime/worktree directories; - loopback ingress/health ports and Wrangler path; - OTLP endpoint/protocol, trace sample ratio, and incident override; - log format and bounded health/status settings. `braid config check` prints the effective non-secret declaration and validates -its static invariants. `braid doctor` probes filesystem, SQLite, GitHub, -Git/gh, OTLP, Wrangler, and the configured adapters and credentials. For Codex -it also checks the app-server schema. Profiles expose +its static invariants. Single-repository GitHub configs may omit +`profile.repository`; a config with `github.additional_repositories` requires +every Profile to declare its repository and explicit workspace. The App and +webhook secret stay instance-level, while Profiles, scheduling, worktrees, and +writes remain repository-scoped. `braid doctor` runs filesystem, SQLite, +GitHub, Codex +schema, Git/gh, OTLP, and Wrangler precondition probes. Profiles expose their effective mapped provider settings through `braid profile inspect`. +Pi Profile 的可选技能、原生模板、独立 home 和有效身份操作见 +[Profile 指南](../user-manual/profiles.md)。协作技能包独立交付,不属于默认运行材料。 + ## Filesystem Layout Braid keeps one user root outside repository worktrees, default `~/.braid`. @@ -53,24 +70,31 @@ Everything below is scoped by trust boundary: ```text ~/.braid/ registry.toml # instance registry (SSoT) + config.toml # optional user defaults (future) secrets/ # user-level provider API keys instances// - config.toml # instance config, schema version 2 + config.toml # Harness config, schema version 3 (GitHub v2 still readable) github-app.pem # GitHub App private key secrets.toml # webhook secret - source/ # repository checkout used to provision worktrees + source/ # repository checkout used to provision worktrees state/ braid.sqlite3 backups/ - worktrees/ + worktrees/--//-g/ provider/ # adapter home (e.g. Codex provider state) + logs/ # optional sampled-log export ``` The default `runtime.root` is `/state`. `braid setup` writes `instances/` explicitly with the layout above. Multiple instances share the same user root but have isolated databases, webhooks, and worktrees. -The [worktree contract](../20-product-tdd/README.md#durable-state-and-migrations) -describes generation paths and overrides. +A provider credential file is Braid schema (`provider_api_key = "..."` for +`api_key`, or an `access`/`refresh`/`expires` token set for `oauth`) and must +be mode `0600`. Its path and provider id are explicit user choices. The Pi +adapter converts it at session materialization — injecting `api_key` as the +managed environment reference or rendering `oauth` into the session home +`auth.json`; `kind = "none"` injects nothing. Runtime homes never carry +`auth.json`; convert existing ones once with `braid provider import-auth`. ## Database Lifecycle @@ -98,28 +122,202 @@ evidence—including GitHub bodies/summaries, raw webhook, provider transcript, credentials, API results, and local paths—is attached only to recording spans as log/event bodies rather than high-cardinality metric labels. +Full sampled payload events use the dedicated `braid::evidence` target and go +only to OTLP logs. They are not copied into trace events or ordinary Text/JSON +stderr/journal. JSON formatting does not inherit span fields; evidence must +never be placed in ordinary span attributes. Provider chunks do not generate +per-chunk ordinary summary logs: lifecycle/session diagnostics and the low-cardinality +payload sampling/identity counters provide coverage without journal amplification. + Sampling controls volume, not confidentiality. An OTLP backend receives the -same sensitive material as the runtime and is configured/retained accordingly. -The portable binary does not promise outcome-aware tail sampling. Operators who -need “all errors plus 10% normal” route 100% from Braid to an OpenTelemetry -Collector tail-sampling processor; the Collector remains optional external -infrastructure. +same sensitive material as the runtime, including credentials and complete tools' +output, without truncation. Backend access, backups, retention and destruction +must be authorized for that data. Do not replace evidence with incident-only +logging or a debug exporter. The default Collector example forwards all three +signals to a queryable LGTM-compatible OTLP backend and does **not** sample +again. Default Braid `0.10` therefore remains 10%, not 1%. Use +`sample_ratio = 1.0` during a controlled dogfood/acceptance window. Optional tail +sampling requires a deliberately different policy with Braid at 100%; a +trace-only tail sampler does not automatically sample correlated logs. + +### Disposable loopback verification backend + +From a checkout, with a **local** Docker daemon and Compose: + +```sh +docker compose -p braid-observability -f deploy/compose.observability.yaml config --quiet +docker compose -p braid-observability -f deploy/compose.observability.yaml up -d +``` + +The version-pinned LGTM container stores logs in Loki, traces in Tempo, and +metrics in Prometheus. The separate Collector uses +`deploy/otel-collector.example.yaml`, not stdout/debug export. Set the instance: -The selected Rust SDK behavior was compiled and measured on 2026-08-13: -parent-based 10% sampling exported 945 of 10,000 independent traces, and every -retained span preserved all five controlled full-payload attributes. +```toml +[telemetry] +endpoint = "http://127.0.0.1:14318" +sample_ratio = 1.0 +incident_mode = false +``` + +Do not overwrite other existing telemetry keys. Run: + +```sh +braid telemetry probe --config /path/to/config.toml --marker DOGFOOD2_CONTROLLED_PROBE --json +curl -fsS http://127.0.0.1:18888/metrics | grep -E 'otelcol_(receiver|exporter)_.*(accepted|refused|sent|failed)' +``` + +`probe` reports the trace ID plus per-signal endpoint and SDK export call +success/failure counts after flushing. `payload_emitted` means submitted to the +logging layer, not receipt. `successful_batches` means the SDK exporter returned +success, not a durable backend acknowledgement. Partial rejection, queue drops, +retry counts and HTTP/connection sub-stages are not exposed by this SDK boundary; +`queue_dropped_records: null` means unknown, **not zero**. Failure diagnostics +state endpoint/signal/stage and records in failed calls without recursively +exporting themselves or printing remote response bodies. A metrics record here +counts one ResourceMetrics envelope, not individual datapoints. All signals are +flushed even if one fails; optional OTLP failure does not fail business work. +`doctor` connectivity and one successful probe do not prove sustained delivery. +Monitor Collector receiver refusal/export failure and backend query results +throughout a real turn. + +Open **http://127.0.0.1:3300**, Grafana login `admin` / `admin` (local test only), +then Explore: + +1. Loki: `{service_name="braid"} | trace_id=""`. + If the configured service name differs, use it instead. Structured metadata + includes `trace_id` and normalized OTLP attribute names. To find a session, + use `{service_name="braid"} | braid_provider_session_id=""`. + Open the matching record and inspect `provider_transcript` / `credential` / + `github_webhook_payload`; their complete values live in log attributes, + not the short message body. Record the trace ID from the session log. +2. Tempo: select trace-ID query and paste that ID. Verify root/child spans + and session/turn association; payloads intentionally are not span events. +3. Prometheus: query `braid_telemetry_probes_total` after a probe, or + `braid_provider_payloads_total` during a turn. Metrics are not sampled. + +Only host loopback ports 14318 (ingest), 18888 (Collector internal metrics), +and 3300 (Grafana UI) are exposed; backend ports stay on the private Compose +network. **Do not expose these ports through tunnels or bind to public IPs.** +Local users/Docker administrators can read evidence; this template has no +multi-user security boundary. The images and writable container layers are +for a short, supervised local check, not a retention-managed production store. +Loki has a 24h retention policy (asynchronous deletion), plus explicit 64MB +structured-metadata and 16MB body limits with truncation disabled. Oversized +records are rejected, not partially retained; monitor rejected records. There +are no host data mounts or configured persistent volumes. Stop and destroy +all evidence after the window: + +```sh +docker compose -p braid-observability -f deploy/compose.observability.yaml down -v +``` + +A mere `stop` retains sensitive writable layers. For durable deployment, use an +operator-controlled LGTM-compatible OTLP backend with explicit authenticated +access, retention/deletion, storage capacity, backup policy and TLS for any +non-loopback hop; change `otlphttp/lgtm.endpoint` accordingly. Logs must accept +complete large attributes without truncation: validate by reading a long tool +result back before trusting a backend's limits. Remote Docker contexts require +host-local files and deliberate port access; do not mistake their daemon's +loopback for the CLI machine's loopback. + +### Managed single-host dogfood backend + +The disposable template above must **not** receive real sensitive evidence. +For a controlled dogfood window, use the small +`deploy/compose.observability.dogfood.yaml` override. This is a Braid-owned, +retained resource, not task temporary storage. It is not production multi-tenant +security: host users with access to the private directory and Docker admins can +read all evidence. Only Grafana queries are authenticated; ingest and Collector +metrics remain host-loopback-only. Keep backend ports private, never publish a +public tunnel; remote UI access may use an operator-only SSH loopback forward. + +Install the exact committed templates into a private managed directory, e.g. +`~/.braid-inkcre/observability/dogfood2` (not another project's stack/volume): + +```sh +umask 077 +managed="$HOME/.braid-inkcre/observability/dogfood2" +mkdir -p "$managed" +chmod 700 "$managed" +cp deploy/compose.observability*.yaml deploy/otel-collector.example.yaml \ + deploy/loki.observability.yaml deploy/start-dogfood-lgtm.sh "$managed/" +cd "$managed" +# Only the managed copy changes; full-field/reject-not-truncate limits stay intact. +sed 's/retention_period: 24h/retention_period: 168h/' loki.observability.yaml > loki.tmp +mv loki.tmp loki.observability.yaml +# Generate once, never print or commit. Grafana reads via __FILE, not environment value. +test -e grafana-admin-password || openssl rand -hex 32 > grafana-admin-password +chmod 600 grafana-admin-password +# The Collector runs as a non-root container UID; bind-mounted config must be readable. +# The enclosing managed directory remains 0700; these templates contain no secrets. +chmod 644 otel-collector.example.yaml loki.observability.yaml start-dogfood-lgtm.sh +# Use this same project + both files for every lifecycle command. +docker compose -p braid-dogfood2 -f compose.observability.yaml \ + -f compose.observability.dogfood.yaml config --quiet +docker compose -p braid-dogfood2 -f compose.observability.yaml \ + -f compose.observability.dogfood.yaml up -d +``` + +The override disables anonymous access and signup, mounts the mode-0600 password +as a file secret, sets `unless-stopped`, and persists `/data` in the dedicated +`braid-dogfood2_data` volume. Local Compose secrets are file mounts, not encrypted +secret storage. Before routing real evidence, verify unauthenticated Grafana +`/api/datasources` returns **401**, authenticated queries work, mounts and file +modes are correct, and restart/recreate retains a synthetic probe. Grafana login +is `admin`; obtain the password directly from the private password file, never +paste it into issue comments, command output, or model context. Password changes +after initialization require Grafana's admin rotation procedure; replacing the +bootstrap file alone does not rotate the database password. + +Default managed retention is **7 days**: installed Loki copy uses `168h`, the +pinned-image startup wrapper sets Tempo block retention to `168h` and Prometheus +TSDB retention to `7d`. Deletion is asynchronous (not a hard erasure deadline), +and WAL/head data may outlive the nominal query window. Grafana configuration +persists until explicit destruction. Verify actual config/flags after upgrades; +the wrapper is tied to LGTM 0.11.0. No second Collector sampling or debug exporter. +The original disposable template remains 24h Loki / ephemeral layers. + +During dogfood, check daily and after failures: host `df -h`, volume `du`, container +restart/state and bounded logs, Collector receiver refusals/export failures, Loki +rejections and actual Loki/Tempo/Prometheus query results. Investigate any nonzero +failures or missing probe; stop/shorten the window before disk exhaustion (reserve +at least 20% free). Restart policy is not a per-component watchdog: LGTM may stay +running after an internal process dies. Check backend readiness and queries, not +container state alone. No automatic alerting or backup is supplied by this small +single-host stack. The operator owns these checks. Backups contain raw secrets and +transcripts: keep access as restrictive as live storage, encrypt off-host copies, +record their own expiry, and authorize restoration/destruction. For a consistent +volume backup stop the stack first; never treat a live filesystem copy as one. + +`stop` preserves evidence for the next window. For authorized final destruction: + +```sh +cd "$HOME/.braid-inkcre/observability/dogfood2" +docker compose -p braid-dogfood2 -f compose.observability.yaml \ + -f compose.observability.dogfood.yaml down -v +# After separately handling authorized backups, delete the private managed files. +rm -f grafana-admin-password +``` + +Destroying this volume does not erase separately saved backups or host snapshots. +Do not remove existing Velune or other Braid Collector resources. Disposable +verification projects must separately run their original `down -v` at task close. ## Startup and Supervision -Braid validates the configuration and database schema before acquiring the -runtime owner lease. It recovers pending writes and checks the GitHub App -installation before starting loopback ingress and health. Supervised workers -handle scheduling, GitHub writes and reconciliation, and provider session -recovery. `serve --transport-only` skips the provider workers. +Startup is ordered: -With `--tunnel`, Braid verifies the signed public probe before updating the -App webhook and marking startup ready. Provider availability is reported -through health as the configured adapters connect. +1. parse/validate config and secrets; +2. acquire process/runtime owner lease; +3. verify/apply permitted DB migrations; +4. probe installed Codex version/schema and GitHub App installation; +5. start OTLP exporters and loopback health/ingress; +6. start Codex adapter and reconcile persisted sessions/turns/outbox; +7. start canonical GitHub reconciliation; +8. optionally start Wrangler, verify a signed public ping through the returned + URL, then update the GitHub App webhook; +9. mark repository ready for assignment/turn claims. The provider adapter reconnects and resumes compatible sessions where the provider contract makes that safe. Any other supervised worker exit makes @@ -132,12 +330,32 @@ SQLite. An active turn without provider terminal evidence remains `unknown` on the next compatible resume; Braid neither starts a parallel turn nor calls it a success or failure. -Quick Tunnel URLs are temporary. A graceful stop restores the prior App webhook -URL. If the supervised Wrangler child exits unexpectedly, Braid immediately -marks tunnel health unavailable and attempts the same restoration while the -local runtime and reconciliation remain available. A failed repair stays -explicit in health and requires operator action. GitHub does not automatically -redeliver failed webhooks; reconciliation is the recovery path. +Quick Tunnel URLs are temporary. A dedicated supervisor owns the child, public +verification and App URL synchronization independently of Agent execution. +The first public registration also runs under this supervisor. A failed candidate +leaves connectivity degraded while local ingress and reconciliation continue. +Child exit or an explicit `Tunnel not found` marks connectivity unavailable and starts +bounded, backed-off candidate rebuilding without restarting `serve` or its Agent +sessions. Every 60 seconds it verifies a signed public request receives ingress +202 and that the App still names that URL. A failed check reports degraded +immediately; three consecutive public failures replace the candidate. URL drift +retries synchronization of the live candidate rather than creating a new Agent +session. Failed App synchronization remains `sync_pending` and retries with a +10–120-second backoff. On Unix, each candidate starts in its own owned process +group, including Wrangler's Node wrappers and cloudflared. Stop and failed +registration close that group; cancellation retains a last-resort group signal. +An unconfirmed stop reports `stop_unconfirmed` and stops creating candidates +until operator recovery. It does not restart Agent execution to hide the fault. + +`/healthz` returns 503 while a requested Tunnel is not connected. Its +`webhook_sync`, `tunnel_verified_at` and `tunnel_error` distinguish the last +confirmed URL from a pending or failed repair; systemd active is not webhook +readiness. `doctor` primarily checks installation preconditions and cannot +substitute for these live observations. On graceful stop, Braid restores the +prior App webhook only if the current URL still belongs to its own candidate. +GitHub does not automatically redeliver failed deliveries: canonical +reconciliation recovers current-state changes, while `github redeliver` remains +the explicit route for recovering a particular delivery. On networks that block outbound QUIC, the Quick Tunnel supervisor explicitly uses Cloudflare's TCP HTTP/2 transport. Readiness requires both cloudflared's registered-connection signal and a signed request that traverses the public URL @@ -152,6 +370,66 @@ and stable secret, then select the events declared in the GitHub boundary contract. Once that hook exists, `serve --tunnel` reads its prior URL, patches the verified temporary URL, and restores the prior URL on graceful shutdown. +### 升级现有实现请求与原生材料 + +Schema 12 会把“已固定 PR,但 activation receipt 缺失”的旧错误 applied ensure 重新 +交给原 outbox。迁移本身不启动 Agent;服务恢复后,执行 owner 重验当前精确 PR、 +源 Issue 的 OPEN 状态、canonical 关联、Profile 与生命周期,再补交原授权。已有 +blocked/sleeping/retired/finalizing 历史不会被 ensure 自动解阻或换代。升级前应检查 +这些待恢复请求,尤其旧版本已创建却从未交接的 PR;不要把它误解为按任意关联自动 +授权新角色,也不要把 applied 当成模型已执行。 + +Braid 二进制升级不会替换配置引用的 immutable Pi 安装。新版本源码中的环境修复 +只有在新材料实际被引用后才生效;禁止原地改动 manifest 已锁定的安装。保留旧材料 +时,可由服务显式设置正确的 `GH_CONFIG_DIR` 作为过渡,路径不能由 Agent 猜测。 +材料 identity 检查和 `pi --version` 不证明 execution-local 环境下的默认 gh/Git +credential helper 可用;安装验收要在那个环境中验证,仅报告结果,绝不输出 token +或 credential 的值。 + +切换服务配置前,用候选 binary 对候选配置执行 `braid doctor --config PATH`。 +只读 Session compatibility 检查将当前有效材料与最新既有 generation 比较,并对 +可静态重建的 GitHub 工作项校验指令。Built-in 按已显式选择的 Profile 比较材料; +有限 run 的动态协调指令仍由运行时校验,预检不猜测它。不更改 assignment、Agent、 +Session 或分支。材料/指令不匹配会明确失败;材料回退后 +仍 blocked 或执行 unknown 也不会被当成已恢复。先保持兼容配置,或明确用 +`assignment reactivate` 创建新 generation。恢复完全相同 Profile 只是复用旧 generation +的必要条件,不是 owned execution 已停止的证明;当前不提供把旧 blocked 记录自动 +翻回 active 的通用入口,不把现场特定的 SQL 逆向操作当作受支持恢复流程。 + +Schema 13 只修复 Operational Status 的公开投影。已有 generation 的正常运行证据 +可在服务恢复、outbox 下一次领取时,把旧故障 comment 更新为已恢复或由新代接替, +无需再次激活或调用模型;原 blocked 记录不会改变。更新包含最后确认时间,不能 +当作当前凭据仍有效或工作已验收的证明。若旧评论创建尚未确认,执行器先对账原 +请求再更新,避免重复 comment。OAuth 源文件生命周期不在这次迁移范围内。 + +Schema 14 将事件与批次的唯一关系限定在单个批次内。结果 unknown 的轮次重放时, +新批次可保留原 Event References 与 trusted mention 身份,旧轮次的输入历史不变。 +迁移不把 unknown 当作已停止;替代执行仍须经过旧执行停止与 Context replacement +屏障。 + +Schema 15 单独保存 adapter 已确认的原生停止依据,覆盖重启后的 Context 替换 +和重开。迁移为旧会话保留空的停止记录,避免从旧生命周期推断执行已停。升级 +前停止服务并备份;旧 binary 不能打开 schema 15 账本。 + +Schema 16 在轮次认领时保存内建事件 cursor,记下已发起的 writer grant 申请和 +正在确认的撤权。升级时一并更换内建 Platform 与 Harness 二进制。新平台的 grant +签发要求 Harness 提供认领时的 cursor。历史轮次保留空 cursor。 + +Harness schema 17 与 Platform schema 4 引入执行代次。先停止旧 Harness,再升级 +Platform 以禁用缺少执行代次的旧 grant 并保留原始回执,随后升级 Harness。升级只 +改变平台授予的写入资格。历史会话仍按原有原生停止证据判定。新 Harness 可继续 +接纳事件,平台支持执行封禁并确认既有代次后才启动 Provider。 + +Schema 18 将已知 GitHub Operational Status 评论 ID 迁入 Context 的角色账本, +保留可独立核对的旧待确认请求及多候选歧义。Schema 19 将已接纳 PR 交接的来源、 +目标代次和下一轮约束迁入输入账本。旧交接证据缺损时,在发送 Provider 前单独 +退休相应输入。Schema 20 保留旧 eyes 的精确 GitHub 目标。新的反馈由输入和轮次 +账本持有,发布器领取后才投影到 outbox。迁移保留旧发布尝试与回执。 +Schema 21 在首次完整对账时建立标题和正文各自的基线。缺少可证实作者的历史 +变更按外部变化处理。 +Schema 22 在输入和执行账本持久记录待公开的 Operational Status,发布器恢复后 +继续投影,保留原有评论身份和历史回执。 + ## Health and Status Loopback `/healthz` and `braid status` expose bounded, non-semantic state: @@ -164,6 +442,21 @@ Loopback `/healthz` and `braid status` expose bounded, non-semantic state: - oldest pending/uncertain write intent; - OTel exporter and sampling mode. +`runnable_batches` remains the compatible raw batch-lifecycle count, not a claim +or execution promise. `durable_eligible_batches` and each batch's `scheduler` +projection use the same assignment/agent/session conditions as durable claim: +active + idle agent, or finalizing + finalizing agent, with an idle provider +session. Reasons distinguish non-runnable, no active/finalizing assignment, +no matching agent and no idle session. Physical provider availability is explicitly +`unknown_not_in_database`; claim additionally filters the worker's available +physical sessions and requested kind/Profile. Closed/merged alone is not an +exclusion: finalization can remain eligible. Diagnostics never delete/consume +residual batches or change Group lifecycle. Agent groups mark `current_generation` +by the highest durable assignment generation for that Work Item; historical blocked +records are not current-generation failures. Both JSON and text expose this split. A deferred complete-input read also keeps +its bounded `input_error` on the batch, so a runnable lifecycle cannot disguise +repeated Context failures. Native execution has not started for that input. + Health never reports task acceptance, design readiness, or implementation success. Operational Status Comments are the GitHub-visible projection for specific blocked Work Items. @@ -186,3 +479,101 @@ Then drive only the real campaign in [`../10-prd/acceptance.md`](../10-prd/acceptance.md). Source-tree execution, private DB edits, fake events, or a manually signed local request cannot accept the release. + +## 内建平台与 Harness 接入 + +内建平台使用独立声明、schema 与数据库,作为 Harness 的上游与 GitHub 并列。 +`braid platform init/serve/import` 管理平台;`braid init` 只声明 Harness 执行环境 +与 `[builtin]` repository/endpoint,不创建 GitHub App 或保存 API key 值。 +平台 source 与默认分支独立绑定,不能通过修改 endpoint 静默切换空间身份。 + +Harness 配置 schema 3 选择 `[github]` 或 `[builtin]`。原 GitHub schema 2 声明 +继续有效,旧 `[local]` 明确拒绝,并给出显式平台导入指引。导入前停止旧进程 +和写入入口,核实在途意图;保留原数据库、对象身份、事件及对象回执。Harness +数据库迁移至 schema 6,平台此后使用自己的 schema,不读取执行表。迁移及 +启动命令见[内建平台指南](../user-manual/local.md)。 + +平台当前 schema 5 持有自己的嵌入迁移名称与 SHA-256 校验。已有平台在启动时 +先备份再向前升级,保留空间身份、对象和回执。 +未知版本或迁移校验不一致明确拒绝。历史候选与合并提交保留平台专属 Git 引用, +避免工作分支移动或清理后丢失已接受的提交。已注册平台在 Git 工作区离线时仍可 +提供数据库对象、事件和范围查询。创建候选、Git diff、合并和判定最终交付时会 +重新检查相应 Git 数据。首次注册仍验证绑定工作区和默认分支。 + +两个上游经过同一 Harness 运行入口、lease、调度和 Group/provider 停止合同。 +内建 adapter 使用 HTTP 平台接口,事件 cursor 和 grant 能力保留在 Harness +ledger;平台不为每个消费者修改事件。`--transport-only` 接入对象事件和队列, +不启动原生模型会话。GitHub 专属命令在内建上游明确拒绝。 + +Agent 子进程取得 `BRAID_CONFIG` 与 `BRAID_AGENT`,对象 gateway 通过专属 cwd、 +当前 assignment/session/turn 按需使用或申请有效 grant。普通 prompt 发送无需 +等待签发。平台签发和提交事务核验执行代次及当前指派和范围的权威事件版本。 +同名重新指派、范围登记、关闭和重开都使旧 grant 失效。 +平台封禁或原生停止无法确认时阻断执行替换。同 +账户进程不是安全沙箱的隔离对手。平台对象、provider history 与 Git 资料保留 +各自身份和数据库,停止 Harness 不删除平台。 + +## Braid Collector 与 Console + +`braid console` 提供 loopback OTLP HTTP/protobuf、独立原始证据库和内嵌 Web。 +`--config` 可连接任一上游的 Harness;`--platform-config` 可便捷托管独立平台, +也可只配置平台而不配置 Harness。对象操作经过固定平台 API,执行 snapshot +只读 Harness ledger,runtime manager 持有真实任务与启停回执。Console 不走 +CLI 子进程,也不由 OTLP 重建权威。停止 Harness 后平台和 Collector 继续在线。 +使用方法和未确认停止的处置见[Console 指南](../user-manual/console.md)。 + +平台命令回执属于平台数据库,启停回执属于 Harness。普通对象变更、事件和 +回执原子提交,Git 候选保留自己的意图与 ref CAS。监督器等待所有 Group/provider +停止结果,任何未确认停止进入 blocked 并禁止替代启动。Console 可在同进程 +装配三项职责,但不因此合并权威,亦不提供进程级故障隔离。 + +真实指标使用低基数标签:runtime 观察代次开始/结束次数、provider 生命周期事件计数、接纳到 +终态的单调时钟观察时长,以及 provider payload 的采样和关联覆盖计数。时长是 +观察区间,Unknown 不是停止证明;没有原生 usage 事实时不推测 token 或费用。 + +OTLP 信号接口的失败响应按[协议规范](https://opentelemetry.io/docs/specs/otlp/#failures) +使用 protobuf Status;正常批次因存储不可用不能接受时返回 503,让 exporter 可以 +重试。成功响应只表示持久接收,不承诺 Exactly Once;Web 查询和控制错误另用 +JSON,避免浏览器把诊断响应当作业务回执。 + +## GitHub GraphQL quota recovery + +正常预算下,OPEN 或仍有 materializing/active/finalizing Assignment 的 Work Item +完整巡检成功后默认 60 秒再次到期;其他已关闭/合并历史项为 30 分钟。 +`scheduler.reconciliation_seconds` 控制 hot 成功间隔,不是 worker tick;本地 +到期检查每 `min(reconciliation_seconds, 5)` 秒执行,另有遍历、网络与预算等待。 +失败项至少间隔一个 hot 周期再试;已知 installation 冷却期间不会反复联网, +巡检只在进入降级状态时告警。 + +升级需应用 schema 8 迁移,新增独立的完整成功/尝试时钟;旧记录起初均到期, +但仍受 installation 准入限制。重启应保留 runtime 数据库,避免丢失成功事实。 +旧二进制不能直接打开升级后的数据库;回滚遵守上文 Database Lifecycle。 + +普通成功预算事件已降为 DEBUG。以下指标/归因日志的 coverage 仅为 Braid GraphQL +transport(包括 canonical Context 完整遍历),不是所有 GitHub 调用。REST(含 +`write_rest`)及 App/installation-token 请求的请求数、时长和成本仍为 unknown。 +按 `braid.github.requests`(GraphQL HTTP请求,不是points)与 +`braid.github.request.duration` 聚合 operation/class/resource/outcome/cost_known, +其中 metric 的 resource 固定为 `graphql`; +`braid.github.graphql.points` 只统计实际返回 `rateLimit.cost`,不能用 unknown 样本 +推导总点数。指标不带 repository/installation/object/session 标签;DEBUG/span 以 +repository/work item、installation、request ID、status/latency、used/remaining/reset +归因,WARN 保留准入/限流/退避失败。used delta 在同一resource/reset窗口内才可比, +仍可能包含别的调用者。字段缺失明确 unknown,不能冒称 querycost。body/token/vars +不进入这些普通日志;完整采样证据的受控路由不变。 + +本地 mock GraphQL HTTP 单页、无项目/关联/线程/drift 的完整读取账单 Issue13→5、PR10→5; +关联Issue、线程评论、项目字段及分页另外计费。该下降不证明线上 points 同比例下降。 +正常预算窗口需在真实backend对操作指标与限额事件联合观察,再决定后续优化。 + +后台在剩余点数不大于 100 时让出余量;主限额耗尽等 reset,次级限流遵守 +Retry-After,缺提示的限流或网络故障有界退避,到期重新探测。不要反复重启绕过 +冷却:预算只在进程内共享,重启后首次响应前未知,而 GitHub 的安装额度不会重置。 +独立 CLI、其他进程和 REST/App token 操作不受此 GraphQL gate 协调。若活跃集合 +本身超预算,应减少消耗或调整目标周期,退避不能创造额外吞吐。 + +**自动恢复范围有限。**巡检和仍待处理的请求可在冷却后继续;首次 setup/serve 的 +身份读取失败发生在 worker 启动前,需要额度恢复后重试启动。已因 Context 物化 +失败进入 `blocked` 的 Issue 激活或 Context replacement 不会被一次成功探测自动 +解除;先排除权限、配置和外部故障,再使用既有 operator reactivation 路径。 +不要把 API 配额恢复等同于所有 Agent 业务自动继续。 diff --git a/docs/assets/README.md b/docs/assets/README.md new file mode 100644 index 00000000..7d035630 --- /dev/null +++ b/docs/assets/README.md @@ -0,0 +1,19 @@ +# Braid 品牌素材 + +[`logo/`](logo/) 是仓库内 Logo 的唯一素材源,完整保留 2026-10-19 交付包的目录和文件字节。包内的 [`README.md`](logo/README.md) 记录设计与制作说明,[`manifest.json`](logo/manifest.json) 以相对路径、字节数和 SHA-256 列出其余 130 个文件;校验清单本身不列入清单。 + +素材共有八款:彩色图形配透明、白色、黑色、深蓝圆角徽章背景,白色图形配透明或黑色背景,黑色图形配透明或白色背景。每款提供 16、20、24、32、48、64、128、256、512、1024 px PNG。 + +大尺寸使用 `logo/svg/standard/`。16–32 px 彩色图标使用 `logo/svg/small-optical-color/`;单色图标使用 `logo/svg/optical//` 中对应 16–128 px 的版本,保留小尺寸下的开口与编织轮廓。PNG 已按这些规则生成。SVG 不依赖字体、嵌入位图或外部资源;彩色版使用渐变、滤镜和裁剪,单色版使用路径和透明蒙版。 + +| 使用位置 | 直接使用的交付素材 | +| --- | --- | +| 根目录 `README.md`,显示为 96 × 96 px | `logo/png/braid-color-on-badge/braid-color-on-badge-128.png` | +| `src/setup/logo.rs`,合成 GitHub App 头像 | `logo/png/braid-color-on-transparent/braid-color-on-transparent-512.png` | +| Web Console 品牌图标 `/braid-logo.svg` | `logo/svg/small-optical-color/braid-color-on-transparent.svg` | +| Web Console favicon `/favicon.svg` | `logo/svg/small-optical-color/braid-color-on-badge.svg` | +| Web Console 备用 favicon `/favicon.png` | `logo/png/braid-color-on-badge/braid-color-on-badge-32.png` | + +[`preview.png`](logo/preview.png) 展示全部款式,[`actual-size-preview.png`](logo/actual-size-preview.png) 展示单色小图的实际像素尺寸。`logo/source/` 保留原始高清参考图、已批准的单色轮廓和彩色版基线哈希;彩色 SVG 是冻结的制作输入。已有成品可直接使用,构建 Braid 无需重建素材。 + +如需重建,在 `logo/` 下依次运行 `python3 build_pack.py` 和 `python3 qa.py`。依赖 Python 3、Pillow、NumPy、SciPy 与 Inkscape CLI;预览生成还需要脚本指定的 `/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf`,其他系统应先准备该字体路径或明确调整制作脚本。`qa.py` 会重新写入 `QA.json` 和 `manifest.json`,重建后须检查差异再接受新成品。 diff --git a/docs/assets/braid-logo-128.png b/docs/assets/braid-logo-128.png deleted file mode 100644 index 833d073d..00000000 Binary files a/docs/assets/braid-logo-128.png and /dev/null differ diff --git a/docs/assets/braid-logo-512.png b/docs/assets/braid-logo-512.png deleted file mode 100644 index 7fcfda31..00000000 Binary files a/docs/assets/braid-logo-512.png and /dev/null differ diff --git a/docs/assets/braid-logo-transparent.png b/docs/assets/braid-logo-transparent.png deleted file mode 100644 index fb9cbb25..00000000 Binary files a/docs/assets/braid-logo-transparent.png and /dev/null differ diff --git a/docs/assets/logo/QA.json b/docs/assets/logo/QA.json new file mode 100644 index 00000000..3a49b53e --- /dev/null +++ b/docs/assets/logo/QA.json @@ -0,0 +1,130 @@ +{ + "color_v2_byte_identical_files": 48, + "color_v2_unchanged": true, + "png_count": 80, + "svg_count": 40, + "monochrome_checks": [ + { + "size": 16, + "alpha_difference_max": 0, + "solid_complement_error_max": 0, + "alpha_vs_solid_error_max": 0, + "negative_regions_4_connected": 3, + "negative_region_areas": [ + 181, + 3, + 7 + ] + }, + { + "size": 20, + "alpha_difference_max": 0, + "solid_complement_error_max": 0, + "alpha_vs_solid_error_max": 0, + "negative_regions_4_connected": 3, + "negative_region_areas": [ + 278, + 5, + 13 + ] + }, + { + "size": 24, + "alpha_difference_max": 0, + "solid_complement_error_max": 0, + "alpha_vs_solid_error_max": 0, + "negative_regions_4_connected": 3, + "negative_region_areas": [ + 390, + 10, + 17 + ] + }, + { + "size": 32, + "alpha_difference_max": 0, + "solid_complement_error_max": 0, + "alpha_vs_solid_error_max": 0, + "negative_regions_4_connected": 3, + "negative_region_areas": [ + 679, + 17, + 29 + ] + }, + { + "size": 48, + "alpha_difference_max": 0, + "solid_complement_error_max": 0, + "alpha_vs_solid_error_max": 0, + "negative_regions_4_connected": 3, + "negative_region_areas": [ + 1622, + 30, + 60 + ] + }, + { + "size": 64, + "alpha_difference_max": 0, + "solid_complement_error_max": 0, + "alpha_vs_solid_error_max": 0, + "negative_regions_4_connected": 3, + "negative_region_areas": [ + 2869, + 51, + 106 + ] + }, + { + "size": 128, + "alpha_difference_max": 0, + "solid_complement_error_max": 0, + "alpha_vs_solid_error_max": 0, + "negative_regions_4_connected": 3, + "negative_region_areas": [ + 11351, + 211, + 427 + ] + }, + { + "size": 256, + "alpha_difference_max": 0, + "solid_complement_error_max": 0, + "alpha_vs_solid_error_max": 0, + "negative_regions_4_connected": 3, + "negative_region_areas": [ + 45353, + 852, + 1701 + ] + }, + { + "size": 512, + "alpha_difference_max": 0, + "solid_complement_error_max": 0, + "alpha_vs_solid_error_max": 0, + "negative_regions_4_connected": 3, + "negative_region_areas": [ + 181241, + 3403, + 6813 + ] + }, + { + "size": 1024, + "alpha_difference_max": 0, + "solid_complement_error_max": 0, + "alpha_vs_solid_error_max": 0, + "negative_regions_4_connected": 3, + "negative_region_areas": [ + 724952, + 13610, + 27300 + ] + } + ], + "svg_no_images_text_external_references": true, + "note": "Negative-region check uses threshold alpha 128 and 4-neighbour connectivity; standard has two enclosed counters plus exterior-connected lower openings." +} \ No newline at end of file diff --git a/docs/assets/logo/README.md b/docs/assets/logo/README.md new file mode 100644 index 00000000..359eff80 --- /dev/null +++ b/docs/assets/logo/README.md @@ -0,0 +1,26 @@ +# Braid logo pack · 2026-10-19 + +## Approved design +The full-color logo retains the previously reviewed HD-PNG-based vector reconstruction, including editable colored ribbons, gradients and local overlap shading. It is a reconstruction, not the original authoring file; fine grain is omitted. Its SVGs and PNGs are unchanged from the color v2 pack. + +The monochrome logo is the user's approved same-form interpretation: original three-ribbon identity, a widened lower-left opening connecting to the right counter, and a naturally curved lower-right opening reaching the exterior. The approved main outline, lower-left opening and final tangent-matched right opening are preserved in `source/approved-monochrome.svg`. + +## Included variants and sizes +Eight variants: color on transparent, white, black and original-style navy rounded badge; white on transparent or black; black on transparent or white. + +PNG sizes: 16, 20, 24, 32, 48, 64, 128, 256, 512 and 1024 px. PNG filenames identify the actual size. + +- `svg/standard`: four color and four approved monochrome masters. +- `svg/small-optical-color`: unchanged color v2 small masters, used for 16–32 px. +- `svg/optical/`: monochrome masters tuned for each size through 128 px. Both approved openings are widened with rounded mask expansion to survive rasterization. Through 32 px the mark is enlarged 8% around its center. These are optical adaptations of the approved form, not alternative logos. +- `png/`: ready-to-use images. +- `preview.png`: all variants, with small sizes enlarged for inspection. +- `actual-size-preview.png`: monochrome 16–128 px at native pixels. +- `source/original-hd.png`: unchanged original raster reference. + +Use the matching optical SVG for small UI icons; use the standard master for large artwork. At 16–24 px, fine curves inevitably become antialiased pixels; the optical versions preserve the broad woven form and open separations, not every large-size detail. The overlap hierarchy is clearer at 32 px and above. Transparent variants use real alpha, including the open ribbon boundaries. Backgrounds are independent SVG rectangles. No fonts, embedded bitmaps or external resources are required by the SVG logos. Color SVGs use gradients, filters and clipping; monochrome SVGs use editable paths and alpha masks. Use a full SVG renderer such as Inkscape. + +## Rebuild and checks +Requires Python 3, Pillow, NumPy, SciPy and Inkscape CLI. Run `python build_pack.py`, then `python qa.py`. The color SVGs are frozen inputs; all other inputs are under `source/`. Rebuilding is offline and does not access other project directories. Preview labels use an available local DejaVu font; the logo assets have no font dependencies. + +`QA.json` records image dimensions, monochrome alpha/complement checks, small-size region checks and SVG resource inspection. `manifest.json` lists deliverable hashes. No upstream repository was modified. Earlier exploratory candidates are not included. diff --git a/docs/assets/logo/actual-size-preview.png b/docs/assets/logo/actual-size-preview.png new file mode 100644 index 00000000..4285e5f3 Binary files /dev/null and b/docs/assets/logo/actual-size-preview.png differ diff --git a/docs/assets/logo/build_pack.py b/docs/assets/logo/build_pack.py new file mode 100644 index 00000000..3b6f177f --- /dev/null +++ b/docs/assets/logo/build_pack.py @@ -0,0 +1,39 @@ +from pathlib import Path +import xml.etree.ElementTree as E,subprocess,copy,json,hashlib +from PIL import Image,ImageDraw,ImageFont +P=Path(__file__).parent;N='{http://www.w3.org/2000/svg}';E.register_namespace('',N[1:-1]);SIZES=[16,20,24,32,48,64,128,256,512,1024];VARIANTS=[('color','transparent'),('color','white'),('color','black'),('color','badge'),('white','transparent'),('white','black'),('black','transparent'),('black','white')] +def mono(tone,bg,n=None): + r=E.parse(P/'source/approved-monochrome.svg').getroot();r.set('width','1254');r.set('height','1254');r.find(N+'rect').set('fill','none' if bg=='transparent' else bg);p=r.find(N+'path');p.set('fill',tone);p.set('id','approved-monochrome-silhouette') + if n: + stroke=max(0,1.3*1254/n-10) + for cut in r.find(N+'defs').find(N+'mask').findall(N+'path'): + cut.set('stroke','black');cut.set('stroke-width',f'{stroke:.3f}');cut.set('stroke-linejoin','round') + if n<=32: + r.remove(p);g=E.SubElement(r,N+'g',{'transform':'translate(627 627) scale(1.08) translate(-627 -627)','id':'small-size-optical-scale'});g.append(p) + title=E.SubElement(r,N+'title');title.text=f'Braid {tone} on {bg} / '+(f'{n}px optical' if n else 'approved standard') + return E.tostring(r,encoding='unicode') +for tone,bg in VARIANTS: + name=f'braid-{tone}-on-{bg}' + if tone!='color': + f=P/'svg/standard'/(name+'.svg');f.parent.mkdir(parents=True,exist_ok=True);f.write_text(mono(tone,bg)) + for n in SIZES: + if n<=128: + f=P/'svg/optical'/str(n)/(name+'.svg');f.parent.mkdir(parents=True,exist_ok=True);f.write_text(mono(tone,bg,n)) + for n in SIZES: + if tone=='color':src=P/'svg'/('small-optical-color' if n<=32 else 'standard')/(name+'.svg') + else:src=P/'svg/optical'/str(n)/(name+'.svg') if n<=128 else P/'svg/standard'/(name+'.svg') + out=P/'png'/name/(name+f'-{n}.png');out.parent.mkdir(parents=True,exist_ok=True) + subprocess.run(['inkscape',str(src),'--export-filename='+str(out),'--export-width='+str(n),'--export-height='+str(n)],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,check=True) +font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf',17) +s=Image.new('RGB',(1360,1250),'#e7e9ee');d=ImageDraw.Draw(s) +for row,(tone,bg) in enumerate(VARIANTS): + name=f'braid-{tone}-on-{bg}';y=10+row*154;d.text((12,y+7),f'{tone} / {bg}',font=font,fill='black') + for col,n in enumerate([16,24,32,64,128,256]): + x=245+col*180;tile=Image.new('RGBA',(160,120),'#7d8290' if bg=='transparent' else bg if bg!='badge' else '#bec2cb');im=Image.open(P/'png'/name/(name+f'-{n}.png')).convert('RGBA');im=im.resize((112,112),Image.Resampling.NEAREST if n<=32 else Image.Resampling.LANCZOS);tile.alpha_composite(im,(24,4));s.paste(tile.convert('RGB'),(x,y));d.text((x,y+124),f'{n}px'+(' enlarged' if n<=32 else ''),font=font,fill='black') +s.save(P/'preview.png') +s=Image.new('RGB',(900,410),'#e7e9ee');d=ImageDraw.Draw(s) +for row,(tone,bg) in enumerate([('black','white'),('white','black')]): + d.text((10,10+row*195),f'{tone} / {bg} - actual pixels',font=font,fill='black') + for i,n in enumerate([16,20,24,32,48,64,128]): + im=Image.open(P/'png'/f'braid-{tone}-on-{bg}'/f'braid-{tone}-on-{bg}-{n}.png').convert('RGBA');tile=Image.new('RGBA',(115,145),bg);tile.alpha_composite(im,((115-n)//2,(145-n)//2));x=10+i*125;y=40+row*195;s.paste(tile.convert('RGB'),(x,y));d.text((x+10,y+150),str(n),font=font,fill='black') +s.save(P/'actual-size-preview.png') diff --git a/docs/assets/logo/independent-review.json b/docs/assets/logo/independent-review.json new file mode 100644 index 00000000..c432f3ae --- /dev/null +++ b/docs/assets/logo/independent-review.json @@ -0,0 +1,13 @@ +{ + "date": "2026-10-19", + "result": "passed", + "checks": { + "png_count": 80, + "svg_count": 40, + "all_40_color_png_byte_identical_to_v2": true, + "monochrome_alpha_and_black_white_complement_max_error": 0, + "all_sizes_have_two_enclosed_counters_and_open_lower_separations": true, + "approved_preview_panel_vs_standard_render_520px_max_pixel_difference": 0, + "actual_size_16_to_64_visual_review": "Form and open separations readable; fine-detail limits acknowledged." + } +} \ No newline at end of file diff --git a/docs/assets/logo/manifest.json b/docs/assets/logo/manifest.json new file mode 100644 index 00000000..55531c88 --- /dev/null +++ b/docs/assets/logo/manifest.json @@ -0,0 +1,652 @@ +[ + { + "path": "QA.json", + "bytes": 2963, + "sha256": "9b6ce8b8fe55ea0c7bfb5388c713e69e78db03f614ce35867a3d05f43382b8eb" + }, + { + "path": "README.md", + "bytes": 2977, + "sha256": "8ddea8aa448f161180774503a54db9336f2c6bb5922116890fe1d0ec9b8d5fbf" + }, + { + "path": "actual-size-preview.png", + "bytes": 35308, + "sha256": "e5bcf2f6f8bb71fdf38c0278ad94d91c3787a65a616b09e25fc9c948501062f4" + }, + { + "path": "build_pack.py", + "bytes": 3398, + "sha256": "9345d72285a6f2c7a064e4ce9ad5000557e79728ce9161ff8e5f556e8eae4ab6" + }, + { + "path": "independent-review.json", + "bytes": 493, + "sha256": "11aa6c7a72df239e758f5136a591d4f5eb14ffb119f8f333d4fb55cae7a0d82c" + }, + { + "path": "png/braid-black-on-transparent/braid-black-on-transparent-1024.png", + "bytes": 37336, + "sha256": "96c6d0c894611e2e11dff5f851eb9f9ed83075d2d8acafd909f57369c27e3693" + }, + { + "path": "png/braid-black-on-transparent/braid-black-on-transparent-128.png", + "bytes": 3532, + "sha256": "21cb06dc6fed9fc76d97ed6aa37d26dd02b8bc7b2a0bb0878736937196502d74" + }, + { + "path": "png/braid-black-on-transparent/braid-black-on-transparent-16.png", + "bytes": 433, + "sha256": "42a4f8de091c444255a96478aed324dc3e0a5869f7bb53e1fcf55721e2f7a3f8" + }, + { + "path": "png/braid-black-on-transparent/braid-black-on-transparent-20.png", + "bytes": 527, + "sha256": "8e206c387c978967a5f8a00910cb6394f59a5fa68bb3664edf6d2235d67befd3" + }, + { + "path": "png/braid-black-on-transparent/braid-black-on-transparent-24.png", + "bytes": 606, + "sha256": "28d7938611af53340b97474291c8f7951d162bba54085dcd5a4f7c3861d368db" + }, + { + "path": "png/braid-black-on-transparent/braid-black-on-transparent-256.png", + "bytes": 7737, + "sha256": "6871be08c1afcb230d56154f27f70cdb0dde9880ae0ae73f289ad1b0db22ff00" + }, + { + "path": "png/braid-black-on-transparent/braid-black-on-transparent-32.png", + "bytes": 826, + "sha256": "401edf5226d89974e641d3bbd57be48eddbe248d390c0874f2a9d584ecd2ea5a" + }, + { + "path": "png/braid-black-on-transparent/braid-black-on-transparent-48.png", + "bytes": 1137, + "sha256": "581007a4d2c793f2258b884b31cbbf07b2764ca1fc789f15bddb19b4555a832c" + }, + { + "path": "png/braid-black-on-transparent/braid-black-on-transparent-512.png", + "bytes": 16936, + "sha256": "d9d94168160b2ea62b52d0439e7d4e7658efa37463e2ee795ff3fd960b87c84d" + }, + { + "path": "png/braid-black-on-transparent/braid-black-on-transparent-64.png", + "bytes": 1604, + "sha256": "47d156742f05b77bb65e621856050302dde9035ebbacc337921e1813a1da6865" + }, + { + "path": "png/braid-black-on-white/braid-black-on-white-1024.png", + "bytes": 49780, + "sha256": "c7bc5432a89397ddefacaba27b86f0fa95e08a6ebb6098bfaf0dd0790f4ca1ca" + }, + { + "path": "png/braid-black-on-white/braid-black-on-white-128.png", + "bytes": 4575, + "sha256": "893da788dc4bda4f3d4bbfa008a110793faca50d4c35d02e4513476e0b5ae9a7" + }, + { + "path": "png/braid-black-on-white/braid-black-on-white-16.png", + "bytes": 586, + "sha256": "15259102343fb12d2176b5447895f32ffd0aaca9f300f4b613dd310e8050bca4" + }, + { + "path": "png/braid-black-on-white/braid-black-on-white-20.png", + "bytes": 722, + "sha256": "6567ecf9d1819755c1fcd2112b76252b65b214ed63611b8198f1815a74dc6674" + }, + { + "path": "png/braid-black-on-white/braid-black-on-white-24.png", + "bytes": 852, + "sha256": "98c2194609fbcfc3626470eada4208a03c8c38ca09171ce5016648ec9edee63a" + }, + { + "path": "png/braid-black-on-white/braid-black-on-white-256.png", + "bytes": 10188, + "sha256": "307dbcf5f471838e106cc3e4fbb96ba1c4c93bf43f8d73246456459dfcc1d82b" + }, + { + "path": "png/braid-black-on-white/braid-black-on-white-32.png", + "bytes": 1151, + "sha256": "3ef78e9674a4bda3d7787d046010e6a3aa873376dc4735205e2a0d9d254943cf" + }, + { + "path": "png/braid-black-on-white/braid-black-on-white-48.png", + "bytes": 1581, + "sha256": "3db2185e21fc6d616328962615f938b13f1fe9d051ce64c92d2b98b38bbac119" + }, + { + "path": "png/braid-black-on-white/braid-black-on-white-512.png", + "bytes": 22408, + "sha256": "d5a39dca9551f18c5ef39f6f343421ea1b3aeec03f1ce6b3b9889be846953abc" + }, + { + "path": "png/braid-black-on-white/braid-black-on-white-64.png", + "bytes": 2221, + "sha256": "63235dfae19fd09eaad2dacd0cd5411a4649607b302b288edc5c21e8e47945da" + }, + { + "path": "png/braid-color-on-badge/braid-color-on-badge-1024.png", + "bytes": 98226, + "sha256": "d9646977744bd13fcb2f4d183ec08ddebd3092b922ce2dfb57853348c1abf3f8" + }, + { + "path": "png/braid-color-on-badge/braid-color-on-badge-128.png", + "bytes": 7561, + "sha256": "af6d9c76b2c00ce7f4bdc0d975b6bfa2cbe36bc43ac9f949404ac29b5b993a28" + }, + { + "path": "png/braid-color-on-badge/braid-color-on-badge-16.png", + "bytes": 745, + "sha256": "a8f7f5c9bcc247df57ff63017292cdaea9d65c9115e26084108e23c975d613f0" + }, + { + "path": "png/braid-color-on-badge/braid-color-on-badge-20.png", + "bytes": 987, + "sha256": "13be3ba4c659419bf7b24c1561f53f16e2accb6fce3ba1b969f9eccc59e0eabc" + }, + { + "path": "png/braid-color-on-badge/braid-color-on-badge-24.png", + "bytes": 1217, + "sha256": "792e700358adbb34f75c72ff71c573b00d86d41e631f6a31fcbe88f95737c52d" + }, + { + "path": "png/braid-color-on-badge/braid-color-on-badge-256.png", + "bytes": 17575, + "sha256": "521712a5b1afac415e1e41b2b8f467df596cfe3d01fba7c3c2ff275a115c229d" + }, + { + "path": "png/braid-color-on-badge/braid-color-on-badge-32.png", + "bytes": 1705, + "sha256": "21ae32139d9bad085f1de78b655f5c0b639d69f5bfdc6deb85eb528c3f01f136" + }, + { + "path": "png/braid-color-on-badge/braid-color-on-badge-48.png", + "bytes": 2414, + "sha256": "09858e9ef8ea5c9243278faa8cfa10a76f143bcc5d5d0e90bcb9676bd0d0ca80" + }, + { + "path": "png/braid-color-on-badge/braid-color-on-badge-512.png", + "bytes": 41094, + "sha256": "82d5510e5142ec1c70ae0f50f809b71a78b9803952df0338523ad86b87c04524" + }, + { + "path": "png/braid-color-on-badge/braid-color-on-badge-64.png", + "bytes": 3409, + "sha256": "d7378eeebd392e5a128d4843c66245de7855fc3cbb048dc775ec7be0725d6576" + }, + { + "path": "png/braid-color-on-black/braid-color-on-black-1024.png", + "bytes": 89804, + "sha256": "1e7685263bf116332b6146125faff3adfd6b9db940edb63ecdfd8abc3f351917" + }, + { + "path": "png/braid-color-on-black/braid-color-on-black-128.png", + "bytes": 6760, + "sha256": "3698c55402a45e250d60c13ddac05c6b40d88958589ce3d42a0311130cb3cea8" + }, + { + "path": "png/braid-color-on-black/braid-color-on-black-16.png", + "bytes": 694, + "sha256": "fec088b2c2ed97c2de8aa499264a346ffe5527ae8fd686e3773f182f8f2c8c4b" + }, + { + "path": "png/braid-color-on-black/braid-color-on-black-20.png", + "bytes": 889, + "sha256": "485e9d0e89fa897d8ecfc959b0dd35dd8bc947f2a642282f315299d6673005c8" + }, + { + "path": "png/braid-color-on-black/braid-color-on-black-24.png", + "bytes": 1094, + "sha256": "9697c798080c8c59e76dc026549d9aad06bafc7ac445d9167a09622cf651e5e2" + }, + { + "path": "png/braid-color-on-black/braid-color-on-black-256.png", + "bytes": 15741, + "sha256": "c4dfc44d242efaf93c297bed4f3ae80727fc73a65d8e05bde5ba19da37681973" + }, + { + "path": "png/braid-color-on-black/braid-color-on-black-32.png", + "bytes": 1529, + "sha256": "d23481bddbc66c8319b82ee603eb06179357e559cf8e5d7895124d5e2bcc3bb0" + }, + { + "path": "png/braid-color-on-black/braid-color-on-black-48.png", + "bytes": 2136, + "sha256": "84caf1de70c6720d337a6bfe18b6e870ebc746598d5e04033df00d18234ea496" + }, + { + "path": "png/braid-color-on-black/braid-color-on-black-512.png", + "bytes": 37326, + "sha256": "a114b8f0856851c35c64939c14b3e9f588c5601d8dd064bd816383f2d4c4ad9f" + }, + { + "path": "png/braid-color-on-black/braid-color-on-black-64.png", + "bytes": 3036, + "sha256": "a4265b4ba9f99c55c620b6720d712f4e4843aa117c8f01a4d1020e5e73b1c1d4" + }, + { + "path": "png/braid-color-on-transparent/braid-color-on-transparent-1024.png", + "bytes": 86581, + "sha256": "3e02235271ab44163517d27e54a0101e2bbcac58705b8879fff635ab038c6b28" + }, + { + "path": "png/braid-color-on-transparent/braid-color-on-transparent-128.png", + "bytes": 6678, + "sha256": "9b59d1c8103d2f29816f45654a631e317818e8a2df5c1886700db4b6d74323d0" + }, + { + "path": "png/braid-color-on-transparent/braid-color-on-transparent-16.png", + "bytes": 671, + "sha256": "0af9654e1e515bd37614868d74b12e09f6df6513fd68734f413706a5b415813f" + }, + { + "path": "png/braid-color-on-transparent/braid-color-on-transparent-20.png", + "bytes": 855, + "sha256": "c90ac6dad0c0c9113d2a2084aee0cb949cb9ead1a3093f4d77153bc467df488c" + }, + { + "path": "png/braid-color-on-transparent/braid-color-on-transparent-24.png", + "bytes": 1052, + "sha256": "8dc42b1ece609ce7cbe1dff4eb7fd6a328fffd2a531c92f95c7be77ef70ea4d0" + }, + { + "path": "png/braid-color-on-transparent/braid-color-on-transparent-256.png", + "bytes": 15378, + "sha256": "0c33f618461128993fdd5ea0816045a871dac6732d0df72371c9da80629700e6" + }, + { + "path": "png/braid-color-on-transparent/braid-color-on-transparent-32.png", + "bytes": 1459, + "sha256": "4880253e54b88d8d21d99714ee9c7aa2d6b7f4a481e4c40f5619c7cd2ece66e0" + }, + { + "path": "png/braid-color-on-transparent/braid-color-on-transparent-48.png", + "bytes": 2078, + "sha256": "47ee3eb89902b3d77f964128ee52f0800da05c3b4590c4f92856e8d5daad2c50" + }, + { + "path": "png/braid-color-on-transparent/braid-color-on-transparent-512.png", + "bytes": 36218, + "sha256": "c2089878bcc24a1165f09881e6e8c4102e319a83e9fc30807c5faf0f596b4fdc" + }, + { + "path": "png/braid-color-on-transparent/braid-color-on-transparent-64.png", + "bytes": 2958, + "sha256": "1675060f4d6c1b93e42986cdf9140f8438942a69edc8a09df4b7c2ce1de304e5" + }, + { + "path": "png/braid-color-on-white/braid-color-on-white-1024.png", + "bytes": 83820, + "sha256": "75a64a518a8cd04193f3fc51c63abbc38d00d19a12186fde40a00508eefb11b4" + }, + { + "path": "png/braid-color-on-white/braid-color-on-white-128.png", + "bytes": 6181, + "sha256": "223872f689be16c03700389fb2101f731ee0bdf4b9b3b3ee95ca6b9f967689d1" + }, + { + "path": "png/braid-color-on-white/braid-color-on-white-16.png", + "bytes": 632, + "sha256": "ef728196b3b95b3b3ac242ace2aa14b01696799ae3a02c9494293427cd626ecf" + }, + { + "path": "png/braid-color-on-white/braid-color-on-white-20.png", + "bytes": 809, + "sha256": "a3af910b6497db25abe819dfd879292981ee0b33ada28a4b3e912015ff5afb1a" + }, + { + "path": "png/braid-color-on-white/braid-color-on-white-24.png", + "bytes": 994, + "sha256": "cc454d31cd3f84b33562cbbd6bb41650c92f0694e5f09e0213b276ff9b3376f3" + }, + { + "path": "png/braid-color-on-white/braid-color-on-white-256.png", + "bytes": 14435, + "sha256": "4658119abab046ff5f5721b8b380c75fab16b4d8ed3e7ba107df8232d92bb069" + }, + { + "path": "png/braid-color-on-white/braid-color-on-white-32.png", + "bytes": 1402, + "sha256": "a7d7fce1bcc0e9e0cf423b58925d5b7436eed34175bd61505be8c12e46534a44" + }, + { + "path": "png/braid-color-on-white/braid-color-on-white-48.png", + "bytes": 1976, + "sha256": "dc66504675b47b14966f7d6c7160c25de35618b42099b46233e0277b6797d848" + }, + { + "path": "png/braid-color-on-white/braid-color-on-white-512.png", + "bytes": 34552, + "sha256": "bffd6b511c20d13a25d2d380e34692d212a12a5c48383535d095a329e0be1396" + }, + { + "path": "png/braid-color-on-white/braid-color-on-white-64.png", + "bytes": 2731, + "sha256": "12b71d020cc82e4aaeb4da712ca8eabf225ef393f70b1fdd660faf169b760871" + }, + { + "path": "png/braid-white-on-black/braid-white-on-black-1024.png", + "bytes": 49945, + "sha256": "ee5dd59412cb282f80ec99b3b84a643f7657089931648552f70eaceae9279168" + }, + { + "path": "png/braid-white-on-black/braid-white-on-black-128.png", + "bytes": 4381, + "sha256": "8faece00526fd8dfde96e70c801d2daed84926d05ad4fdcfec08a6b860252051" + }, + { + "path": "png/braid-white-on-black/braid-white-on-black-16.png", + "bytes": 584, + "sha256": "faf3e138a49b0e45519bc2fde34ead01fe7e27e438609e2c83e8031b88e56242" + }, + { + "path": "png/braid-white-on-black/braid-white-on-black-20.png", + "bytes": 710, + "sha256": "3e3700ca6049a3d7b173811aa02e22e12941e33b5678a22e0603ba4dd24e9bd2" + }, + { + "path": "png/braid-white-on-black/braid-white-on-black-24.png", + "bytes": 846, + "sha256": "ee29215f63579c9ed9dc2ca5aee122a79820fe60aa0ec0924f56cc4cd4bf3871" + }, + { + "path": "png/braid-white-on-black/braid-white-on-black-256.png", + "bytes": 9832, + "sha256": "75ecfbb16b261014b77ed259e4a63eac8c9e52a7ee56a1139997696265348588" + }, + { + "path": "png/braid-white-on-black/braid-white-on-black-32.png", + "bytes": 1144, + "sha256": "48ad338b8671b8ee64c3e27e76bdc448023afcd73338da0c962c8552b71bfedf" + }, + { + "path": "png/braid-white-on-black/braid-white-on-black-48.png", + "bytes": 1574, + "sha256": "e0c63bff6b94418c82ee1debf4637f9273e1c1b809e6193f5636c062c717606a" + }, + { + "path": "png/braid-white-on-black/braid-white-on-black-512.png", + "bytes": 22355, + "sha256": "428447dfdc1abb4929764a1f751eae081c7029135d5994a0cd2032c3a031bd88" + }, + { + "path": "png/braid-white-on-black/braid-white-on-black-64.png", + "bytes": 2178, + "sha256": "8952f6f5cd3572272cf8c5dbfe15d6dd8ecfb5f738315d99a5d8dfa9cc0c06e2" + }, + { + "path": "png/braid-white-on-transparent/braid-white-on-transparent-1024.png", + "bytes": 34021, + "sha256": "d8f91112ec7707cc5b5831eb8091a52ffa9cdd7260a1ab8c53eef025aa05f31a" + }, + { + "path": "png/braid-white-on-transparent/braid-white-on-transparent-128.png", + "bytes": 3518, + "sha256": "cd6147316fb7b99922e139e58fab404419d4407159d0db8250ab1dad938c7dca" + }, + { + "path": "png/braid-white-on-transparent/braid-white-on-transparent-16.png", + "bytes": 434, + "sha256": "cf4b85e2295b713c47a1b763fe468367dca6dd91ce2ea8e63c73bbc88b183504" + }, + { + "path": "png/braid-white-on-transparent/braid-white-on-transparent-20.png", + "bytes": 531, + "sha256": "2076f57a0a54a807c55877ab38d3be8d95a45180e20326139d71fc6c05eeb9ad" + }, + { + "path": "png/braid-white-on-transparent/braid-white-on-transparent-24.png", + "bytes": 629, + "sha256": "4c328e56f8ba5055dc1bef67938619529c7d0fee536b9d0acdd899a96bfb3277" + }, + { + "path": "png/braid-white-on-transparent/braid-white-on-transparent-256.png", + "bytes": 7259, + "sha256": "68d8f2b6b0c8a286e07f9f2f0d379cf9db40e1d3ccd57f85d0cd7b7a5b5c29a8" + }, + { + "path": "png/braid-white-on-transparent/braid-white-on-transparent-32.png", + "bytes": 839, + "sha256": "bcfc6a532b5e3eda8cad7e85d22b9178e992f9bab8a71bd908649d328a7bb044" + }, + { + "path": "png/braid-white-on-transparent/braid-white-on-transparent-48.png", + "bytes": 1231, + "sha256": "2f3d7859ca91ef1a3b8e780fa12e0f65c407f41c4ca8d3dc515339b239c54757" + }, + { + "path": "png/braid-white-on-transparent/braid-white-on-transparent-512.png", + "bytes": 15598, + "sha256": "8125459292efadce7079a995bbdd93c931a3e41be156ec8d4ce979b1cd67d851" + }, + { + "path": "png/braid-white-on-transparent/braid-white-on-transparent-64.png", + "bytes": 1672, + "sha256": "74f54e1a74b1c2ea6f33b91663c4ac57e105c4659950dfecfe0756c9caf6fa6d" + }, + { + "path": "preview.png", + "bytes": 270750, + "sha256": "44b4d13409bde52c478a5f90d15a905228ae2c3bbdefb75f42cec81fbf0d800a" + }, + { + "path": "qa.py", + "bytes": 2498, + "sha256": "d4b9b3e13203591e299739ffaee48a48581839c2c9ea014a1c9cad7392cb2bb9" + }, + { + "path": "source/approved-monochrome.svg", + "bytes": 1296, + "sha256": "fba1bc550d2b64b96bc52a926e54553713341391aa6d48cf8af9c85fd7047eae" + }, + { + "path": "source/color-v2-hashes.json", + "bytes": 6126, + "sha256": "02e1cb5e0c1764145330338324741074c01fbc3aeeeda25c4ef464a6ada1270a" + }, + { + "path": "source/original-hd.png", + "bytes": 998750, + "sha256": "3b5dd92845f1d039375581c7010c65bc52084387d0a0a76bbfdee9805eeaf885" + }, + { + "path": "svg/optical/128/braid-black-on-transparent.svg", + "bytes": 1539, + "sha256": "05309dc06ab4e6d5f4c7a451aba2045d4d6c78a5dc12fa73b8e55ee39c88dbec" + }, + { + "path": "svg/optical/128/braid-black-on-white.svg", + "bytes": 1534, + "sha256": "a3094a9b43d9b6bdebffb780dfdb880403d769dfd28ba9c419a61a89fdfb1028" + }, + { + "path": "svg/optical/128/braid-white-on-black.svg", + "bytes": 1534, + "sha256": "1ddcf1d1da70196e6a166e5e42d3498e42e7e484da0e353de842e3a3d806a6ba" + }, + { + "path": "svg/optical/128/braid-white-on-transparent.svg", + "bytes": 1539, + "sha256": "d7efde2af31692a7e93febf008ada2971d802686587f44f98a4fd831ba3e1dc7" + }, + { + "path": "svg/optical/16/braid-black-on-transparent.svg", + "bytes": 1641, + "sha256": "25f47ee99fec3be95676468757e2e7a0a1d9ec7e1c319154a4d0779e0f7bfc49" + }, + { + "path": "svg/optical/16/braid-black-on-white.svg", + "bytes": 1636, + "sha256": "a71077ff6d0e428d96bdf02c8210e70342b3261bd2a4d0d41b6662ae4cc349dd" + }, + { + "path": "svg/optical/16/braid-white-on-black.svg", + "bytes": 1636, + "sha256": "2d9084f9d40596476feb270eaf0da0000c39a2b06bdbefd136f2e24a2032c1a0" + }, + { + "path": "svg/optical/16/braid-white-on-transparent.svg", + "bytes": 1641, + "sha256": "738b65e0918804c59cf6791f3d4fedc9d666fe2878b35a49d6054722da0aac14" + }, + { + "path": "svg/optical/20/braid-black-on-transparent.svg", + "bytes": 1641, + "sha256": "d10f622d46d0efd82fe646555415b92382e1446841c8a0af1ad4a6f51c3e85af" + }, + { + "path": "svg/optical/20/braid-black-on-white.svg", + "bytes": 1636, + "sha256": "a9d43ece46ea91b025505430be5dd6b2ebfedc9545d1566ce1364d1691c79d47" + }, + { + "path": "svg/optical/20/braid-white-on-black.svg", + "bytes": 1636, + "sha256": "af1fdf88a37d8a460406183b077d948dce940aeeabfe19d6c6c7ebbd2773b44b" + }, + { + "path": "svg/optical/20/braid-white-on-transparent.svg", + "bytes": 1641, + "sha256": "5772726a4f81ac52160c82a609c04bb08e69c8f0456949d204b397e69cffcdba" + }, + { + "path": "svg/optical/24/braid-black-on-transparent.svg", + "bytes": 1641, + "sha256": "25ae0c7c66aee30bc477cf517e54ae54e3082e0dea845b045436170eee3a3264" + }, + { + "path": "svg/optical/24/braid-black-on-white.svg", + "bytes": 1636, + "sha256": "8c54254a155c98cc75905fcf72c7d259fa80d59748b5b8cdc310d7121c742e57" + }, + { + "path": "svg/optical/24/braid-white-on-black.svg", + "bytes": 1636, + "sha256": "9c731be70a70f14d5fa0e2965416be1acef74c41fcde79207f89c52f2d192931" + }, + { + "path": "svg/optical/24/braid-white-on-transparent.svg", + "bytes": 1641, + "sha256": "63db0994f4930cd93aa4718015041671d8fac54b5f8dec7586be8bede8f34cf1" + }, + { + "path": "svg/optical/32/braid-black-on-transparent.svg", + "bytes": 1641, + "sha256": "7f2b8f6af8816d8263640657490d98c4047014928b4819611608fe2d36b6d36e" + }, + { + "path": "svg/optical/32/braid-black-on-white.svg", + "bytes": 1636, + "sha256": "d4b02dd7bc25442d55767d190dd2f4a81274bd031eccfd4829ba6c6e0d2aa5bb" + }, + { + "path": "svg/optical/32/braid-white-on-black.svg", + "bytes": 1636, + "sha256": "3433dfe1b9ec5c26a7cd7852049258b2cd6f99446345aa3878a73380358ad494" + }, + { + "path": "svg/optical/32/braid-white-on-transparent.svg", + "bytes": 1641, + "sha256": "854372571049fa862d8b7a68804333ce3c71e7006ca8db3f6e46eec4cda60a93" + }, + { + "path": "svg/optical/48/braid-black-on-transparent.svg", + "bytes": 1540, + "sha256": "3eeace77b0c4bcaac0902d81b636b07c9b8a161ce541f4d8e976413bf96a198b" + }, + { + "path": "svg/optical/48/braid-black-on-white.svg", + "bytes": 1535, + "sha256": "5486589e2efbd312c0925b01e41b82bf6d95a0b380b6eca66e8622c07dd68938" + }, + { + "path": "svg/optical/48/braid-white-on-black.svg", + "bytes": 1535, + "sha256": "ae8e446f1fdecbae05c702b195ef7b2ffe817436675850d22182dcb826aeb400" + }, + { + "path": "svg/optical/48/braid-white-on-transparent.svg", + "bytes": 1540, + "sha256": "a834c93dd4349ed18f7dff4e7feca1a9b4bcd4572521c359dcb878e35bbfc824" + }, + { + "path": "svg/optical/64/braid-black-on-transparent.svg", + "bytes": 1540, + "sha256": "74a6e7f5fa744266ab09267601609abab9ae2b809398a053021127b8bd3221eb" + }, + { + "path": "svg/optical/64/braid-black-on-white.svg", + "bytes": 1535, + "sha256": "01adb5c036f209153d575935d524721f22f006d3279ad441f40368551756cc7c" + }, + { + "path": "svg/optical/64/braid-white-on-black.svg", + "bytes": 1535, + "sha256": "bc4a20a76d2c8a46aca422dda622507554b127e73edf758b40defa04c8285148" + }, + { + "path": "svg/optical/64/braid-white-on-transparent.svg", + "bytes": 1540, + "sha256": "bf6fdc2340885c008b212cee445887c1f7bfcb63d9ed8f9f125894cac48984f9" + }, + { + "path": "svg/small-optical-color/braid-color-on-badge.svg", + "bytes": 5718, + "sha256": "ff1cefae1e9c61ee7fbdc6b839978fafaedeeb7b81d23f8c74400dd8e8d66195" + }, + { + "path": "svg/small-optical-color/braid-color-on-black.svg", + "bytes": 5714, + "sha256": "5941928507ffed66985ecafc0b2856eb93b08356ee366d239213aa033ee53b19" + }, + { + "path": "svg/small-optical-color/braid-color-on-transparent.svg", + "bytes": 5665, + "sha256": "525ac3ab514b3e4412a7659f4c93efc4a2831c1221ea9cd148547d3402ec502b" + }, + { + "path": "svg/small-optical-color/braid-color-on-white.svg", + "bytes": 5714, + "sha256": "ef0014b04086b01be892d4defe733aac529b15d6dc66936505545fe91ce28024" + }, + { + "path": "svg/standard/braid-black-on-transparent.svg", + "bytes": 1423, + "sha256": "a8d188708010d935bf2cea690229cd823d5b23cba654211cbcdcc1f735953697" + }, + { + "path": "svg/standard/braid-black-on-white.svg", + "bytes": 1418, + "sha256": "d86847d26ea10ce0b3e09159f8f2af8c0d6d9fe0166ed88ce6c18ebf2f255eb1" + }, + { + "path": "svg/standard/braid-color-on-badge.svg", + "bytes": 5944, + "sha256": "359e13c2f2fef532cc81166dad7688f3b4d0e44fcc6fe3fcd88377ffc7ccf839" + }, + { + "path": "svg/standard/braid-color-on-black.svg", + "bytes": 5940, + "sha256": "ca6aa4f0e05fa1e254d244954b50d25664115c9797eec0fe745a321aedaf35ed" + }, + { + "path": "svg/standard/braid-color-on-transparent.svg", + "bytes": 5891, + "sha256": "350631de9f7ed979804e8fe88ba6f9beef3d8d48c0b843082c3cf07a937828f3" + }, + { + "path": "svg/standard/braid-color-on-white.svg", + "bytes": 5940, + "sha256": "1feb017e13ff124ac8897e6f5546cf39ebb344254aedff8bc067bc2b3523471a" + }, + { + "path": "svg/standard/braid-white-on-black.svg", + "bytes": 1418, + "sha256": "7c1843b2d373f5bab365589157211d17ed060960923b7f3fce3c0f04504842ea" + }, + { + "path": "svg/standard/braid-white-on-transparent.svg", + "bytes": 1423, + "sha256": "5a07d8fcd53fb0939eee4c19cd02122f0a9f0b8352b2f06814e733175b8b43ec" + } +] \ No newline at end of file diff --git a/docs/assets/logo/png/braid-black-on-transparent/braid-black-on-transparent-1024.png b/docs/assets/logo/png/braid-black-on-transparent/braid-black-on-transparent-1024.png new file mode 100644 index 00000000..fee2734c Binary files /dev/null and b/docs/assets/logo/png/braid-black-on-transparent/braid-black-on-transparent-1024.png differ diff --git a/docs/assets/logo/png/braid-black-on-transparent/braid-black-on-transparent-128.png b/docs/assets/logo/png/braid-black-on-transparent/braid-black-on-transparent-128.png new file mode 100644 index 00000000..831171e7 Binary files /dev/null and b/docs/assets/logo/png/braid-black-on-transparent/braid-black-on-transparent-128.png differ diff --git a/docs/assets/logo/png/braid-black-on-transparent/braid-black-on-transparent-16.png b/docs/assets/logo/png/braid-black-on-transparent/braid-black-on-transparent-16.png new file mode 100644 index 00000000..a0435ae1 Binary files /dev/null and b/docs/assets/logo/png/braid-black-on-transparent/braid-black-on-transparent-16.png differ diff --git a/docs/assets/logo/png/braid-black-on-transparent/braid-black-on-transparent-20.png b/docs/assets/logo/png/braid-black-on-transparent/braid-black-on-transparent-20.png new file mode 100644 index 00000000..275c73d7 Binary files /dev/null and b/docs/assets/logo/png/braid-black-on-transparent/braid-black-on-transparent-20.png differ diff --git a/docs/assets/logo/png/braid-black-on-transparent/braid-black-on-transparent-24.png b/docs/assets/logo/png/braid-black-on-transparent/braid-black-on-transparent-24.png new file mode 100644 index 00000000..9059718d Binary files /dev/null and b/docs/assets/logo/png/braid-black-on-transparent/braid-black-on-transparent-24.png differ diff --git a/docs/assets/logo/png/braid-black-on-transparent/braid-black-on-transparent-256.png b/docs/assets/logo/png/braid-black-on-transparent/braid-black-on-transparent-256.png new file mode 100644 index 00000000..13b5bb4f Binary files /dev/null and b/docs/assets/logo/png/braid-black-on-transparent/braid-black-on-transparent-256.png differ diff --git a/docs/assets/logo/png/braid-black-on-transparent/braid-black-on-transparent-32.png b/docs/assets/logo/png/braid-black-on-transparent/braid-black-on-transparent-32.png new file mode 100644 index 00000000..f2da583f Binary files /dev/null and b/docs/assets/logo/png/braid-black-on-transparent/braid-black-on-transparent-32.png differ diff --git a/docs/assets/logo/png/braid-black-on-transparent/braid-black-on-transparent-48.png b/docs/assets/logo/png/braid-black-on-transparent/braid-black-on-transparent-48.png new file mode 100644 index 00000000..329e1fe2 Binary files /dev/null and b/docs/assets/logo/png/braid-black-on-transparent/braid-black-on-transparent-48.png differ diff --git a/docs/assets/logo/png/braid-black-on-transparent/braid-black-on-transparent-512.png b/docs/assets/logo/png/braid-black-on-transparent/braid-black-on-transparent-512.png new file mode 100644 index 00000000..8bf17412 Binary files /dev/null and b/docs/assets/logo/png/braid-black-on-transparent/braid-black-on-transparent-512.png differ diff --git a/docs/assets/logo/png/braid-black-on-transparent/braid-black-on-transparent-64.png b/docs/assets/logo/png/braid-black-on-transparent/braid-black-on-transparent-64.png new file mode 100644 index 00000000..74a97fdd Binary files /dev/null and b/docs/assets/logo/png/braid-black-on-transparent/braid-black-on-transparent-64.png differ diff --git a/docs/assets/logo/png/braid-black-on-white/braid-black-on-white-1024.png b/docs/assets/logo/png/braid-black-on-white/braid-black-on-white-1024.png new file mode 100644 index 00000000..91d76771 Binary files /dev/null and b/docs/assets/logo/png/braid-black-on-white/braid-black-on-white-1024.png differ diff --git a/docs/assets/logo/png/braid-black-on-white/braid-black-on-white-128.png b/docs/assets/logo/png/braid-black-on-white/braid-black-on-white-128.png new file mode 100644 index 00000000..5bbbd585 Binary files /dev/null and b/docs/assets/logo/png/braid-black-on-white/braid-black-on-white-128.png differ diff --git a/docs/assets/logo/png/braid-black-on-white/braid-black-on-white-16.png b/docs/assets/logo/png/braid-black-on-white/braid-black-on-white-16.png new file mode 100644 index 00000000..a1714c77 Binary files /dev/null and b/docs/assets/logo/png/braid-black-on-white/braid-black-on-white-16.png differ diff --git a/docs/assets/logo/png/braid-black-on-white/braid-black-on-white-20.png b/docs/assets/logo/png/braid-black-on-white/braid-black-on-white-20.png new file mode 100644 index 00000000..7a2a70fd Binary files /dev/null and b/docs/assets/logo/png/braid-black-on-white/braid-black-on-white-20.png differ diff --git a/docs/assets/logo/png/braid-black-on-white/braid-black-on-white-24.png b/docs/assets/logo/png/braid-black-on-white/braid-black-on-white-24.png new file mode 100644 index 00000000..1e69dc4c Binary files /dev/null and b/docs/assets/logo/png/braid-black-on-white/braid-black-on-white-24.png differ diff --git a/docs/assets/logo/png/braid-black-on-white/braid-black-on-white-256.png b/docs/assets/logo/png/braid-black-on-white/braid-black-on-white-256.png new file mode 100644 index 00000000..51c56f3a Binary files /dev/null and b/docs/assets/logo/png/braid-black-on-white/braid-black-on-white-256.png differ diff --git a/docs/assets/logo/png/braid-black-on-white/braid-black-on-white-32.png b/docs/assets/logo/png/braid-black-on-white/braid-black-on-white-32.png new file mode 100644 index 00000000..f3243541 Binary files /dev/null and b/docs/assets/logo/png/braid-black-on-white/braid-black-on-white-32.png differ diff --git a/docs/assets/logo/png/braid-black-on-white/braid-black-on-white-48.png b/docs/assets/logo/png/braid-black-on-white/braid-black-on-white-48.png new file mode 100644 index 00000000..54675f65 Binary files /dev/null and b/docs/assets/logo/png/braid-black-on-white/braid-black-on-white-48.png differ diff --git a/docs/assets/logo/png/braid-black-on-white/braid-black-on-white-512.png b/docs/assets/logo/png/braid-black-on-white/braid-black-on-white-512.png new file mode 100644 index 00000000..724ff1aa Binary files /dev/null and b/docs/assets/logo/png/braid-black-on-white/braid-black-on-white-512.png differ diff --git a/docs/assets/logo/png/braid-black-on-white/braid-black-on-white-64.png b/docs/assets/logo/png/braid-black-on-white/braid-black-on-white-64.png new file mode 100644 index 00000000..16a3828e Binary files /dev/null and b/docs/assets/logo/png/braid-black-on-white/braid-black-on-white-64.png differ diff --git a/docs/assets/logo/png/braid-color-on-badge/braid-color-on-badge-1024.png b/docs/assets/logo/png/braid-color-on-badge/braid-color-on-badge-1024.png new file mode 100644 index 00000000..ad560abf Binary files /dev/null and b/docs/assets/logo/png/braid-color-on-badge/braid-color-on-badge-1024.png differ diff --git a/docs/assets/logo/png/braid-color-on-badge/braid-color-on-badge-128.png b/docs/assets/logo/png/braid-color-on-badge/braid-color-on-badge-128.png new file mode 100644 index 00000000..e4d74c3e Binary files /dev/null and b/docs/assets/logo/png/braid-color-on-badge/braid-color-on-badge-128.png differ diff --git a/docs/assets/logo/png/braid-color-on-badge/braid-color-on-badge-16.png b/docs/assets/logo/png/braid-color-on-badge/braid-color-on-badge-16.png new file mode 100644 index 00000000..724ded85 Binary files /dev/null and b/docs/assets/logo/png/braid-color-on-badge/braid-color-on-badge-16.png differ diff --git a/docs/assets/logo/png/braid-color-on-badge/braid-color-on-badge-20.png b/docs/assets/logo/png/braid-color-on-badge/braid-color-on-badge-20.png new file mode 100644 index 00000000..770e5e99 Binary files /dev/null and b/docs/assets/logo/png/braid-color-on-badge/braid-color-on-badge-20.png differ diff --git a/docs/assets/logo/png/braid-color-on-badge/braid-color-on-badge-24.png b/docs/assets/logo/png/braid-color-on-badge/braid-color-on-badge-24.png new file mode 100644 index 00000000..053eb03f Binary files /dev/null and b/docs/assets/logo/png/braid-color-on-badge/braid-color-on-badge-24.png differ diff --git a/docs/assets/logo/png/braid-color-on-badge/braid-color-on-badge-256.png b/docs/assets/logo/png/braid-color-on-badge/braid-color-on-badge-256.png new file mode 100644 index 00000000..890f3aba Binary files /dev/null and b/docs/assets/logo/png/braid-color-on-badge/braid-color-on-badge-256.png differ diff --git a/docs/assets/logo/png/braid-color-on-badge/braid-color-on-badge-32.png b/docs/assets/logo/png/braid-color-on-badge/braid-color-on-badge-32.png new file mode 100644 index 00000000..bcd06479 Binary files /dev/null and b/docs/assets/logo/png/braid-color-on-badge/braid-color-on-badge-32.png differ diff --git a/docs/assets/logo/png/braid-color-on-badge/braid-color-on-badge-48.png b/docs/assets/logo/png/braid-color-on-badge/braid-color-on-badge-48.png new file mode 100644 index 00000000..b6915e1c Binary files /dev/null and b/docs/assets/logo/png/braid-color-on-badge/braid-color-on-badge-48.png differ diff --git a/docs/assets/logo/png/braid-color-on-badge/braid-color-on-badge-512.png b/docs/assets/logo/png/braid-color-on-badge/braid-color-on-badge-512.png new file mode 100644 index 00000000..e537d9be Binary files /dev/null and b/docs/assets/logo/png/braid-color-on-badge/braid-color-on-badge-512.png differ diff --git a/docs/assets/logo/png/braid-color-on-badge/braid-color-on-badge-64.png b/docs/assets/logo/png/braid-color-on-badge/braid-color-on-badge-64.png new file mode 100644 index 00000000..ab55852c Binary files /dev/null and b/docs/assets/logo/png/braid-color-on-badge/braid-color-on-badge-64.png differ diff --git a/docs/assets/logo/png/braid-color-on-black/braid-color-on-black-1024.png b/docs/assets/logo/png/braid-color-on-black/braid-color-on-black-1024.png new file mode 100644 index 00000000..86674e4c Binary files /dev/null and b/docs/assets/logo/png/braid-color-on-black/braid-color-on-black-1024.png differ diff --git a/docs/assets/logo/png/braid-color-on-black/braid-color-on-black-128.png b/docs/assets/logo/png/braid-color-on-black/braid-color-on-black-128.png new file mode 100644 index 00000000..04f4d731 Binary files /dev/null and b/docs/assets/logo/png/braid-color-on-black/braid-color-on-black-128.png differ diff --git a/docs/assets/logo/png/braid-color-on-black/braid-color-on-black-16.png b/docs/assets/logo/png/braid-color-on-black/braid-color-on-black-16.png new file mode 100644 index 00000000..a0f49e20 Binary files /dev/null and b/docs/assets/logo/png/braid-color-on-black/braid-color-on-black-16.png differ diff --git a/docs/assets/logo/png/braid-color-on-black/braid-color-on-black-20.png b/docs/assets/logo/png/braid-color-on-black/braid-color-on-black-20.png new file mode 100644 index 00000000..d6bba20f Binary files /dev/null and b/docs/assets/logo/png/braid-color-on-black/braid-color-on-black-20.png differ diff --git a/docs/assets/logo/png/braid-color-on-black/braid-color-on-black-24.png b/docs/assets/logo/png/braid-color-on-black/braid-color-on-black-24.png new file mode 100644 index 00000000..e827d06c Binary files /dev/null and b/docs/assets/logo/png/braid-color-on-black/braid-color-on-black-24.png differ diff --git a/docs/assets/logo/png/braid-color-on-black/braid-color-on-black-256.png b/docs/assets/logo/png/braid-color-on-black/braid-color-on-black-256.png new file mode 100644 index 00000000..7f635c84 Binary files /dev/null and b/docs/assets/logo/png/braid-color-on-black/braid-color-on-black-256.png differ diff --git a/docs/assets/logo/png/braid-color-on-black/braid-color-on-black-32.png b/docs/assets/logo/png/braid-color-on-black/braid-color-on-black-32.png new file mode 100644 index 00000000..6a8563a2 Binary files /dev/null and b/docs/assets/logo/png/braid-color-on-black/braid-color-on-black-32.png differ diff --git a/docs/assets/logo/png/braid-color-on-black/braid-color-on-black-48.png b/docs/assets/logo/png/braid-color-on-black/braid-color-on-black-48.png new file mode 100644 index 00000000..bb5c86d9 Binary files /dev/null and b/docs/assets/logo/png/braid-color-on-black/braid-color-on-black-48.png differ diff --git a/docs/assets/logo/png/braid-color-on-black/braid-color-on-black-512.png b/docs/assets/logo/png/braid-color-on-black/braid-color-on-black-512.png new file mode 100644 index 00000000..62b5ee98 Binary files /dev/null and b/docs/assets/logo/png/braid-color-on-black/braid-color-on-black-512.png differ diff --git a/docs/assets/logo/png/braid-color-on-black/braid-color-on-black-64.png b/docs/assets/logo/png/braid-color-on-black/braid-color-on-black-64.png new file mode 100644 index 00000000..da76a444 Binary files /dev/null and b/docs/assets/logo/png/braid-color-on-black/braid-color-on-black-64.png differ diff --git a/docs/assets/logo/png/braid-color-on-transparent/braid-color-on-transparent-1024.png b/docs/assets/logo/png/braid-color-on-transparent/braid-color-on-transparent-1024.png new file mode 100644 index 00000000..781117b8 Binary files /dev/null and b/docs/assets/logo/png/braid-color-on-transparent/braid-color-on-transparent-1024.png differ diff --git a/docs/assets/logo/png/braid-color-on-transparent/braid-color-on-transparent-128.png b/docs/assets/logo/png/braid-color-on-transparent/braid-color-on-transparent-128.png new file mode 100644 index 00000000..f84eed26 Binary files /dev/null and b/docs/assets/logo/png/braid-color-on-transparent/braid-color-on-transparent-128.png differ diff --git a/docs/assets/logo/png/braid-color-on-transparent/braid-color-on-transparent-16.png b/docs/assets/logo/png/braid-color-on-transparent/braid-color-on-transparent-16.png new file mode 100644 index 00000000..c0ca865a Binary files /dev/null and b/docs/assets/logo/png/braid-color-on-transparent/braid-color-on-transparent-16.png differ diff --git a/docs/assets/logo/png/braid-color-on-transparent/braid-color-on-transparent-20.png b/docs/assets/logo/png/braid-color-on-transparent/braid-color-on-transparent-20.png new file mode 100644 index 00000000..a8201ca8 Binary files /dev/null and b/docs/assets/logo/png/braid-color-on-transparent/braid-color-on-transparent-20.png differ diff --git a/docs/assets/logo/png/braid-color-on-transparent/braid-color-on-transparent-24.png b/docs/assets/logo/png/braid-color-on-transparent/braid-color-on-transparent-24.png new file mode 100644 index 00000000..8883d989 Binary files /dev/null and b/docs/assets/logo/png/braid-color-on-transparent/braid-color-on-transparent-24.png differ diff --git a/docs/assets/logo/png/braid-color-on-transparent/braid-color-on-transparent-256.png b/docs/assets/logo/png/braid-color-on-transparent/braid-color-on-transparent-256.png new file mode 100644 index 00000000..a5a27362 Binary files /dev/null and b/docs/assets/logo/png/braid-color-on-transparent/braid-color-on-transparent-256.png differ diff --git a/docs/assets/logo/png/braid-color-on-transparent/braid-color-on-transparent-32.png b/docs/assets/logo/png/braid-color-on-transparent/braid-color-on-transparent-32.png new file mode 100644 index 00000000..f805841e Binary files /dev/null and b/docs/assets/logo/png/braid-color-on-transparent/braid-color-on-transparent-32.png differ diff --git a/docs/assets/logo/png/braid-color-on-transparent/braid-color-on-transparent-48.png b/docs/assets/logo/png/braid-color-on-transparent/braid-color-on-transparent-48.png new file mode 100644 index 00000000..69788540 Binary files /dev/null and b/docs/assets/logo/png/braid-color-on-transparent/braid-color-on-transparent-48.png differ diff --git a/docs/assets/logo/png/braid-color-on-transparent/braid-color-on-transparent-512.png b/docs/assets/logo/png/braid-color-on-transparent/braid-color-on-transparent-512.png new file mode 100644 index 00000000..3381ef03 Binary files /dev/null and b/docs/assets/logo/png/braid-color-on-transparent/braid-color-on-transparent-512.png differ diff --git a/docs/assets/logo/png/braid-color-on-transparent/braid-color-on-transparent-64.png b/docs/assets/logo/png/braid-color-on-transparent/braid-color-on-transparent-64.png new file mode 100644 index 00000000..55a43d22 Binary files /dev/null and b/docs/assets/logo/png/braid-color-on-transparent/braid-color-on-transparent-64.png differ diff --git a/docs/assets/logo/png/braid-color-on-white/braid-color-on-white-1024.png b/docs/assets/logo/png/braid-color-on-white/braid-color-on-white-1024.png new file mode 100644 index 00000000..fda95c2f Binary files /dev/null and b/docs/assets/logo/png/braid-color-on-white/braid-color-on-white-1024.png differ diff --git a/docs/assets/logo/png/braid-color-on-white/braid-color-on-white-128.png b/docs/assets/logo/png/braid-color-on-white/braid-color-on-white-128.png new file mode 100644 index 00000000..5e96c062 Binary files /dev/null and b/docs/assets/logo/png/braid-color-on-white/braid-color-on-white-128.png differ diff --git a/docs/assets/logo/png/braid-color-on-white/braid-color-on-white-16.png b/docs/assets/logo/png/braid-color-on-white/braid-color-on-white-16.png new file mode 100644 index 00000000..916f64c7 Binary files /dev/null and b/docs/assets/logo/png/braid-color-on-white/braid-color-on-white-16.png differ diff --git a/docs/assets/logo/png/braid-color-on-white/braid-color-on-white-20.png b/docs/assets/logo/png/braid-color-on-white/braid-color-on-white-20.png new file mode 100644 index 00000000..497c0686 Binary files /dev/null and b/docs/assets/logo/png/braid-color-on-white/braid-color-on-white-20.png differ diff --git a/docs/assets/logo/png/braid-color-on-white/braid-color-on-white-24.png b/docs/assets/logo/png/braid-color-on-white/braid-color-on-white-24.png new file mode 100644 index 00000000..8915dcc8 Binary files /dev/null and b/docs/assets/logo/png/braid-color-on-white/braid-color-on-white-24.png differ diff --git a/docs/assets/logo/png/braid-color-on-white/braid-color-on-white-256.png b/docs/assets/logo/png/braid-color-on-white/braid-color-on-white-256.png new file mode 100644 index 00000000..9849703a Binary files /dev/null and b/docs/assets/logo/png/braid-color-on-white/braid-color-on-white-256.png differ diff --git a/docs/assets/logo/png/braid-color-on-white/braid-color-on-white-32.png b/docs/assets/logo/png/braid-color-on-white/braid-color-on-white-32.png new file mode 100644 index 00000000..e3c991d9 Binary files /dev/null and b/docs/assets/logo/png/braid-color-on-white/braid-color-on-white-32.png differ diff --git a/docs/assets/logo/png/braid-color-on-white/braid-color-on-white-48.png b/docs/assets/logo/png/braid-color-on-white/braid-color-on-white-48.png new file mode 100644 index 00000000..26457f82 Binary files /dev/null and b/docs/assets/logo/png/braid-color-on-white/braid-color-on-white-48.png differ diff --git a/docs/assets/logo/png/braid-color-on-white/braid-color-on-white-512.png b/docs/assets/logo/png/braid-color-on-white/braid-color-on-white-512.png new file mode 100644 index 00000000..9c03a94a Binary files /dev/null and b/docs/assets/logo/png/braid-color-on-white/braid-color-on-white-512.png differ diff --git a/docs/assets/logo/png/braid-color-on-white/braid-color-on-white-64.png b/docs/assets/logo/png/braid-color-on-white/braid-color-on-white-64.png new file mode 100644 index 00000000..1602eaee Binary files /dev/null and b/docs/assets/logo/png/braid-color-on-white/braid-color-on-white-64.png differ diff --git a/docs/assets/logo/png/braid-white-on-black/braid-white-on-black-1024.png b/docs/assets/logo/png/braid-white-on-black/braid-white-on-black-1024.png new file mode 100644 index 00000000..4a837271 Binary files /dev/null and b/docs/assets/logo/png/braid-white-on-black/braid-white-on-black-1024.png differ diff --git a/docs/assets/logo/png/braid-white-on-black/braid-white-on-black-128.png b/docs/assets/logo/png/braid-white-on-black/braid-white-on-black-128.png new file mode 100644 index 00000000..0316944c Binary files /dev/null and b/docs/assets/logo/png/braid-white-on-black/braid-white-on-black-128.png differ diff --git a/docs/assets/logo/png/braid-white-on-black/braid-white-on-black-16.png b/docs/assets/logo/png/braid-white-on-black/braid-white-on-black-16.png new file mode 100644 index 00000000..f2e18140 Binary files /dev/null and b/docs/assets/logo/png/braid-white-on-black/braid-white-on-black-16.png differ diff --git a/docs/assets/logo/png/braid-white-on-black/braid-white-on-black-20.png b/docs/assets/logo/png/braid-white-on-black/braid-white-on-black-20.png new file mode 100644 index 00000000..54579339 Binary files /dev/null and b/docs/assets/logo/png/braid-white-on-black/braid-white-on-black-20.png differ diff --git a/docs/assets/logo/png/braid-white-on-black/braid-white-on-black-24.png b/docs/assets/logo/png/braid-white-on-black/braid-white-on-black-24.png new file mode 100644 index 00000000..7549e694 Binary files /dev/null and b/docs/assets/logo/png/braid-white-on-black/braid-white-on-black-24.png differ diff --git a/docs/assets/logo/png/braid-white-on-black/braid-white-on-black-256.png b/docs/assets/logo/png/braid-white-on-black/braid-white-on-black-256.png new file mode 100644 index 00000000..2d499b36 Binary files /dev/null and b/docs/assets/logo/png/braid-white-on-black/braid-white-on-black-256.png differ diff --git a/docs/assets/logo/png/braid-white-on-black/braid-white-on-black-32.png b/docs/assets/logo/png/braid-white-on-black/braid-white-on-black-32.png new file mode 100644 index 00000000..5285e334 Binary files /dev/null and b/docs/assets/logo/png/braid-white-on-black/braid-white-on-black-32.png differ diff --git a/docs/assets/logo/png/braid-white-on-black/braid-white-on-black-48.png b/docs/assets/logo/png/braid-white-on-black/braid-white-on-black-48.png new file mode 100644 index 00000000..0f68ac5a Binary files /dev/null and b/docs/assets/logo/png/braid-white-on-black/braid-white-on-black-48.png differ diff --git a/docs/assets/logo/png/braid-white-on-black/braid-white-on-black-512.png b/docs/assets/logo/png/braid-white-on-black/braid-white-on-black-512.png new file mode 100644 index 00000000..06ad6fa8 Binary files /dev/null and b/docs/assets/logo/png/braid-white-on-black/braid-white-on-black-512.png differ diff --git a/docs/assets/logo/png/braid-white-on-black/braid-white-on-black-64.png b/docs/assets/logo/png/braid-white-on-black/braid-white-on-black-64.png new file mode 100644 index 00000000..f3e8280b Binary files /dev/null and b/docs/assets/logo/png/braid-white-on-black/braid-white-on-black-64.png differ diff --git a/docs/assets/logo/png/braid-white-on-transparent/braid-white-on-transparent-1024.png b/docs/assets/logo/png/braid-white-on-transparent/braid-white-on-transparent-1024.png new file mode 100644 index 00000000..1c3757cb Binary files /dev/null and b/docs/assets/logo/png/braid-white-on-transparent/braid-white-on-transparent-1024.png differ diff --git a/docs/assets/logo/png/braid-white-on-transparent/braid-white-on-transparent-128.png b/docs/assets/logo/png/braid-white-on-transparent/braid-white-on-transparent-128.png new file mode 100644 index 00000000..56b51e53 Binary files /dev/null and b/docs/assets/logo/png/braid-white-on-transparent/braid-white-on-transparent-128.png differ diff --git a/docs/assets/logo/png/braid-white-on-transparent/braid-white-on-transparent-16.png b/docs/assets/logo/png/braid-white-on-transparent/braid-white-on-transparent-16.png new file mode 100644 index 00000000..3a3f342d Binary files /dev/null and b/docs/assets/logo/png/braid-white-on-transparent/braid-white-on-transparent-16.png differ diff --git a/docs/assets/logo/png/braid-white-on-transparent/braid-white-on-transparent-20.png b/docs/assets/logo/png/braid-white-on-transparent/braid-white-on-transparent-20.png new file mode 100644 index 00000000..c6028688 Binary files /dev/null and b/docs/assets/logo/png/braid-white-on-transparent/braid-white-on-transparent-20.png differ diff --git a/docs/assets/logo/png/braid-white-on-transparent/braid-white-on-transparent-24.png b/docs/assets/logo/png/braid-white-on-transparent/braid-white-on-transparent-24.png new file mode 100644 index 00000000..23c5d852 Binary files /dev/null and b/docs/assets/logo/png/braid-white-on-transparent/braid-white-on-transparent-24.png differ diff --git a/docs/assets/logo/png/braid-white-on-transparent/braid-white-on-transparent-256.png b/docs/assets/logo/png/braid-white-on-transparent/braid-white-on-transparent-256.png new file mode 100644 index 00000000..7cf7ebd4 Binary files /dev/null and b/docs/assets/logo/png/braid-white-on-transparent/braid-white-on-transparent-256.png differ diff --git a/docs/assets/logo/png/braid-white-on-transparent/braid-white-on-transparent-32.png b/docs/assets/logo/png/braid-white-on-transparent/braid-white-on-transparent-32.png new file mode 100644 index 00000000..f50a8444 Binary files /dev/null and b/docs/assets/logo/png/braid-white-on-transparent/braid-white-on-transparent-32.png differ diff --git a/docs/assets/logo/png/braid-white-on-transparent/braid-white-on-transparent-48.png b/docs/assets/logo/png/braid-white-on-transparent/braid-white-on-transparent-48.png new file mode 100644 index 00000000..74281b92 Binary files /dev/null and b/docs/assets/logo/png/braid-white-on-transparent/braid-white-on-transparent-48.png differ diff --git a/docs/assets/logo/png/braid-white-on-transparent/braid-white-on-transparent-512.png b/docs/assets/logo/png/braid-white-on-transparent/braid-white-on-transparent-512.png new file mode 100644 index 00000000..943f20d7 Binary files /dev/null and b/docs/assets/logo/png/braid-white-on-transparent/braid-white-on-transparent-512.png differ diff --git a/docs/assets/logo/png/braid-white-on-transparent/braid-white-on-transparent-64.png b/docs/assets/logo/png/braid-white-on-transparent/braid-white-on-transparent-64.png new file mode 100644 index 00000000..ae5e16ec Binary files /dev/null and b/docs/assets/logo/png/braid-white-on-transparent/braid-white-on-transparent-64.png differ diff --git a/docs/assets/logo/preview.png b/docs/assets/logo/preview.png new file mode 100644 index 00000000..3a463e6b Binary files /dev/null and b/docs/assets/logo/preview.png differ diff --git a/docs/assets/logo/qa.py b/docs/assets/logo/qa.py new file mode 100644 index 00000000..a80c513d --- /dev/null +++ b/docs/assets/logo/qa.py @@ -0,0 +1,32 @@ +from pathlib import Path +import json,hashlib,xml.etree.ElementTree as E +from PIL import Image +import numpy as np +from scipy.ndimage import label +P=Path(__file__).parent;S=[16,20,24,32,48,64,128,256,512,1024];results=[] +def img(t,b,n):return np.array(Image.open(P/'png'/f'braid-{t}-on-{b}'/f'braid-{t}-on-{b}-{n}.png').convert('RGBA')) +for n in S: + bt=img('black','transparent',n);wt=img('white','transparent',n);bw=img('black','white',n);wb=img('white','black',n) + negative=bt[:,:,3]<128;l,c=label(negative);sizes=np.bincount(l.ravel())[1:].tolist() + results.append({'size':n,'alpha_difference_max':int(np.abs(bt[:,:,3].astype(int)-wt[:,:,3].astype(int)).max()),'solid_complement_error_max':int(np.abs(bw[:,:,:3].astype(int)+wb[:,:,:3].astype(int)-255).max()),'alpha_vs_solid_error_max':int(np.abs(bt[:,:,3].astype(int)-wb[:,:,0].astype(int)).max()),'negative_regions_4_connected':c,'negative_region_areas':sizes}) +imgs=[] +for p in (P/'png').rglob('*.png'): + im=Image.open(p);n=int(p.stem.rsplit('-',1)[1]);assert im.size==(n,n);imgs.append(str(p.relative_to(P))) +svg=[] +for p in (P/'svg').rglob('*.svg'): + root=E.parse(p).getroot();bad=[] + for e in root.iter(): + if e.tag.split('}')[-1] in ['image','text']:bad.append(e.tag) + for k,v in e.attrib.items(): + if k.endswith('href') and not v.startswith('#'):bad.append(v) + assert not bad,(p,bad);svg.append(str(p.relative_to(P))) +assert len(imgs)==80 and len(svg)==40 +assert all(q['alpha_difference_max']==0 and q['solid_complement_error_max']==0 and q['alpha_vs_solid_error_max']==0 and q['negative_regions_4_connected']==3 for q in results) +baseline=json.loads((P/'source/color-v2-hashes.json').read_text());unchanged=all(hashlib.sha256((P/k).read_bytes()).hexdigest()==v for k,v in baseline.items());assert unchanged +report={'color_v2_byte_identical_files':len(baseline),'color_v2_unchanged':unchanged,'png_count':len(imgs),'svg_count':len(svg),'monochrome_checks':results,'svg_no_images_text_external_references':True,'note':'Negative-region check uses threshold alpha 128 and 4-neighbour connectivity; standard has two enclosed counters plus exterior-connected lower openings.'} +(P/'QA.json').write_text(json.dumps(report,indent=2)) +manifest=[] +for p in sorted(P.rglob('*')): + if p.is_file() and p.name!='manifest.json':manifest.append({'path':str(p.relative_to(P)),'bytes':p.stat().st_size,'sha256':hashlib.sha256(p.read_bytes()).hexdigest()}) +(P/'manifest.json').write_text(json.dumps(manifest,indent=2)) +print(json.dumps(report,indent=2)) diff --git a/docs/assets/logo/source/approved-monochrome.svg b/docs/assets/logo/source/approved-monochrome.svg new file mode 100644 index 00000000..e4daa49f --- /dev/null +++ b/docs/assets/logo/source/approved-monochrome.svg @@ -0,0 +1 @@ + diff --git a/docs/assets/logo/source/color-v2-hashes.json b/docs/assets/logo/source/color-v2-hashes.json new file mode 100644 index 00000000..d607b8d9 --- /dev/null +++ b/docs/assets/logo/source/color-v2-hashes.json @@ -0,0 +1,50 @@ +{ + "png/braid-color-on-black/braid-color-on-black-24.png": "9697c798080c8c59e76dc026549d9aad06bafc7ac445d9167a09622cf651e5e2", + "png/braid-color-on-black/braid-color-on-black-1024.png": "1e7685263bf116332b6146125faff3adfd6b9db940edb63ecdfd8abc3f351917", + "png/braid-color-on-black/braid-color-on-black-512.png": "a114b8f0856851c35c64939c14b3e9f588c5601d8dd064bd816383f2d4c4ad9f", + "png/braid-color-on-black/braid-color-on-black-128.png": "3698c55402a45e250d60c13ddac05c6b40d88958589ce3d42a0311130cb3cea8", + "png/braid-color-on-black/braid-color-on-black-16.png": "fec088b2c2ed97c2de8aa499264a346ffe5527ae8fd686e3773f182f8f2c8c4b", + "png/braid-color-on-black/braid-color-on-black-256.png": "c4dfc44d242efaf93c297bed4f3ae80727fc73a65d8e05bde5ba19da37681973", + "png/braid-color-on-black/braid-color-on-black-32.png": "d23481bddbc66c8319b82ee603eb06179357e559cf8e5d7895124d5e2bcc3bb0", + "png/braid-color-on-black/braid-color-on-black-64.png": "a4265b4ba9f99c55c620b6720d712f4e4843aa117c8f01a4d1020e5e73b1c1d4", + "png/braid-color-on-black/braid-color-on-black-48.png": "84caf1de70c6720d337a6bfe18b6e870ebc746598d5e04033df00d18234ea496", + "png/braid-color-on-black/braid-color-on-black-20.png": "485e9d0e89fa897d8ecfc959b0dd35dd8bc947f2a642282f315299d6673005c8", + "png/braid-color-on-white/braid-color-on-white-128.png": "223872f689be16c03700389fb2101f731ee0bdf4b9b3b3ee95ca6b9f967689d1", + "png/braid-color-on-white/braid-color-on-white-1024.png": "75a64a518a8cd04193f3fc51c63abbc38d00d19a12186fde40a00508eefb11b4", + "png/braid-color-on-white/braid-color-on-white-256.png": "4658119abab046ff5f5721b8b380c75fab16b4d8ed3e7ba107df8232d92bb069", + "png/braid-color-on-white/braid-color-on-white-32.png": "a7d7fce1bcc0e9e0cf423b58925d5b7436eed34175bd61505be8c12e46534a44", + "png/braid-color-on-white/braid-color-on-white-16.png": "ef728196b3b95b3b3ac242ace2aa14b01696799ae3a02c9494293427cd626ecf", + "png/braid-color-on-white/braid-color-on-white-512.png": "bffd6b511c20d13a25d2d380e34692d212a12a5c48383535d095a329e0be1396", + "png/braid-color-on-white/braid-color-on-white-24.png": "cc454d31cd3f84b33562cbbd6bb41650c92f0694e5f09e0213b276ff9b3376f3", + "png/braid-color-on-white/braid-color-on-white-20.png": "a3af910b6497db25abe819dfd879292981ee0b33ada28a4b3e912015ff5afb1a", + "png/braid-color-on-white/braid-color-on-white-64.png": "12b71d020cc82e4aaeb4da712ca8eabf225ef393f70b1fdd660faf169b760871", + "png/braid-color-on-white/braid-color-on-white-48.png": "dc66504675b47b14966f7d6c7160c25de35618b42099b46233e0277b6797d848", + "png/braid-color-on-badge/braid-color-on-badge-64.png": "d7378eeebd392e5a128d4843c66245de7855fc3cbb048dc775ec7be0725d6576", + "png/braid-color-on-badge/braid-color-on-badge-256.png": "521712a5b1afac415e1e41b2b8f467df596cfe3d01fba7c3c2ff275a115c229d", + "png/braid-color-on-badge/braid-color-on-badge-48.png": "09858e9ef8ea5c9243278faa8cfa10a76f143bcc5d5d0e90bcb9676bd0d0ca80", + "png/braid-color-on-badge/braid-color-on-badge-16.png": "a8f7f5c9bcc247df57ff63017292cdaea9d65c9115e26084108e23c975d613f0", + "png/braid-color-on-badge/braid-color-on-badge-512.png": "82d5510e5142ec1c70ae0f50f809b71a78b9803952df0338523ad86b87c04524", + "png/braid-color-on-badge/braid-color-on-badge-20.png": "13be3ba4c659419bf7b24c1561f53f16e2accb6fce3ba1b969f9eccc59e0eabc", + "png/braid-color-on-badge/braid-color-on-badge-1024.png": "d9646977744bd13fcb2f4d183ec08ddebd3092b922ce2dfb57853348c1abf3f8", + "png/braid-color-on-badge/braid-color-on-badge-128.png": "af6d9c76b2c00ce7f4bdc0d975b6bfa2cbe36bc43ac9f949404ac29b5b993a28", + "png/braid-color-on-badge/braid-color-on-badge-32.png": "21ae32139d9bad085f1de78b655f5c0b639d69f5bfdc6deb85eb528c3f01f136", + "png/braid-color-on-badge/braid-color-on-badge-24.png": "792e700358adbb34f75c72ff71c573b00d86d41e631f6a31fcbe88f95737c52d", + "png/braid-color-on-transparent/braid-color-on-transparent-1024.png": "3e02235271ab44163517d27e54a0101e2bbcac58705b8879fff635ab038c6b28", + "png/braid-color-on-transparent/braid-color-on-transparent-512.png": "c2089878bcc24a1165f09881e6e8c4102e319a83e9fc30807c5faf0f596b4fdc", + "png/braid-color-on-transparent/braid-color-on-transparent-32.png": "4880253e54b88d8d21d99714ee9c7aa2d6b7f4a481e4c40f5619c7cd2ece66e0", + "png/braid-color-on-transparent/braid-color-on-transparent-20.png": "c90ac6dad0c0c9113d2a2084aee0cb949cb9ead1a3093f4d77153bc467df488c", + "png/braid-color-on-transparent/braid-color-on-transparent-48.png": "47ee3eb89902b3d77f964128ee52f0800da05c3b4590c4f92856e8d5daad2c50", + "png/braid-color-on-transparent/braid-color-on-transparent-16.png": "0af9654e1e515bd37614868d74b12e09f6df6513fd68734f413706a5b415813f", + "png/braid-color-on-transparent/braid-color-on-transparent-128.png": "9b59d1c8103d2f29816f45654a631e317818e8a2df5c1886700db4b6d74323d0", + "png/braid-color-on-transparent/braid-color-on-transparent-256.png": "0c33f618461128993fdd5ea0816045a871dac6732d0df72371c9da80629700e6", + "png/braid-color-on-transparent/braid-color-on-transparent-64.png": "1675060f4d6c1b93e42986cdf9140f8438942a69edc8a09df4b7c2ce1de304e5", + "png/braid-color-on-transparent/braid-color-on-transparent-24.png": "8dc42b1ece609ce7cbe1dff4eb7fd6a328fffd2a531c92f95c7be77ef70ea4d0", + "svg/standard/braid-color-on-black.svg": "ca6aa4f0e05fa1e254d244954b50d25664115c9797eec0fe745a321aedaf35ed", + "svg/standard/braid-color-on-transparent.svg": "350631de9f7ed979804e8fe88ba6f9beef3d8d48c0b843082c3cf07a937828f3", + "svg/standard/braid-color-on-badge.svg": "359e13c2f2fef532cc81166dad7688f3b4d0e44fcc6fe3fcd88377ffc7ccf839", + "svg/standard/braid-color-on-white.svg": "1feb017e13ff124ac8897e6f5546cf39ebb344254aedff8bc067bc2b3523471a", + "svg/small-optical-color/braid-color-on-black.svg": "5941928507ffed66985ecafc0b2856eb93b08356ee366d239213aa033ee53b19", + "svg/small-optical-color/braid-color-on-transparent.svg": "525ac3ab514b3e4412a7659f4c93efc4a2831c1221ea9cd148547d3402ec502b", + "svg/small-optical-color/braid-color-on-badge.svg": "ff1cefae1e9c61ee7fbdc6b839978fafaedeeb7b81d23f8c74400dd8e8d66195", + "svg/small-optical-color/braid-color-on-white.svg": "ef0014b04086b01be892d4defe733aac529b15d6dc66936505545fe91ce28024" +} \ No newline at end of file diff --git a/docs/assets/braid-logo.png b/docs/assets/logo/source/original-hd.png similarity index 100% rename from docs/assets/braid-logo.png rename to docs/assets/logo/source/original-hd.png diff --git a/docs/assets/logo/svg/optical/128/braid-black-on-transparent.svg b/docs/assets/logo/svg/optical/128/braid-black-on-transparent.svg new file mode 100644 index 00000000..d475f547 --- /dev/null +++ b/docs/assets/logo/svg/optical/128/braid-black-on-transparent.svg @@ -0,0 +1 @@ +Braid black on transparent / 128px optical \ No newline at end of file diff --git a/docs/assets/logo/svg/optical/128/braid-black-on-white.svg b/docs/assets/logo/svg/optical/128/braid-black-on-white.svg new file mode 100644 index 00000000..a4550336 --- /dev/null +++ b/docs/assets/logo/svg/optical/128/braid-black-on-white.svg @@ -0,0 +1 @@ +Braid black on white / 128px optical \ No newline at end of file diff --git a/docs/assets/logo/svg/optical/128/braid-white-on-black.svg b/docs/assets/logo/svg/optical/128/braid-white-on-black.svg new file mode 100644 index 00000000..805e6e26 --- /dev/null +++ b/docs/assets/logo/svg/optical/128/braid-white-on-black.svg @@ -0,0 +1 @@ +Braid white on black / 128px optical \ No newline at end of file diff --git a/docs/assets/logo/svg/optical/128/braid-white-on-transparent.svg b/docs/assets/logo/svg/optical/128/braid-white-on-transparent.svg new file mode 100644 index 00000000..ea964946 --- /dev/null +++ b/docs/assets/logo/svg/optical/128/braid-white-on-transparent.svg @@ -0,0 +1 @@ +Braid white on transparent / 128px optical \ No newline at end of file diff --git a/docs/assets/logo/svg/optical/16/braid-black-on-transparent.svg b/docs/assets/logo/svg/optical/16/braid-black-on-transparent.svg new file mode 100644 index 00000000..ca98f920 --- /dev/null +++ b/docs/assets/logo/svg/optical/16/braid-black-on-transparent.svg @@ -0,0 +1 @@ +Braid black on transparent / 16px optical \ No newline at end of file diff --git a/docs/assets/logo/svg/optical/16/braid-black-on-white.svg b/docs/assets/logo/svg/optical/16/braid-black-on-white.svg new file mode 100644 index 00000000..9d5a4a32 --- /dev/null +++ b/docs/assets/logo/svg/optical/16/braid-black-on-white.svg @@ -0,0 +1 @@ +Braid black on white / 16px optical \ No newline at end of file diff --git a/docs/assets/logo/svg/optical/16/braid-white-on-black.svg b/docs/assets/logo/svg/optical/16/braid-white-on-black.svg new file mode 100644 index 00000000..e4d036fd --- /dev/null +++ b/docs/assets/logo/svg/optical/16/braid-white-on-black.svg @@ -0,0 +1 @@ +Braid white on black / 16px optical \ No newline at end of file diff --git a/docs/assets/logo/svg/optical/16/braid-white-on-transparent.svg b/docs/assets/logo/svg/optical/16/braid-white-on-transparent.svg new file mode 100644 index 00000000..3cf27124 --- /dev/null +++ b/docs/assets/logo/svg/optical/16/braid-white-on-transparent.svg @@ -0,0 +1 @@ +Braid white on transparent / 16px optical \ No newline at end of file diff --git a/docs/assets/logo/svg/optical/20/braid-black-on-transparent.svg b/docs/assets/logo/svg/optical/20/braid-black-on-transparent.svg new file mode 100644 index 00000000..f4c07053 --- /dev/null +++ b/docs/assets/logo/svg/optical/20/braid-black-on-transparent.svg @@ -0,0 +1 @@ +Braid black on transparent / 20px optical \ No newline at end of file diff --git a/docs/assets/logo/svg/optical/20/braid-black-on-white.svg b/docs/assets/logo/svg/optical/20/braid-black-on-white.svg new file mode 100644 index 00000000..2d7fb4b2 --- /dev/null +++ b/docs/assets/logo/svg/optical/20/braid-black-on-white.svg @@ -0,0 +1 @@ +Braid black on white / 20px optical \ No newline at end of file diff --git a/docs/assets/logo/svg/optical/20/braid-white-on-black.svg b/docs/assets/logo/svg/optical/20/braid-white-on-black.svg new file mode 100644 index 00000000..f3d7ca7d --- /dev/null +++ b/docs/assets/logo/svg/optical/20/braid-white-on-black.svg @@ -0,0 +1 @@ +Braid white on black / 20px optical \ No newline at end of file diff --git a/docs/assets/logo/svg/optical/20/braid-white-on-transparent.svg b/docs/assets/logo/svg/optical/20/braid-white-on-transparent.svg new file mode 100644 index 00000000..4033e1f2 --- /dev/null +++ b/docs/assets/logo/svg/optical/20/braid-white-on-transparent.svg @@ -0,0 +1 @@ +Braid white on transparent / 20px optical \ No newline at end of file diff --git a/docs/assets/logo/svg/optical/24/braid-black-on-transparent.svg b/docs/assets/logo/svg/optical/24/braid-black-on-transparent.svg new file mode 100644 index 00000000..e628bdcd --- /dev/null +++ b/docs/assets/logo/svg/optical/24/braid-black-on-transparent.svg @@ -0,0 +1 @@ +Braid black on transparent / 24px optical \ No newline at end of file diff --git a/docs/assets/logo/svg/optical/24/braid-black-on-white.svg b/docs/assets/logo/svg/optical/24/braid-black-on-white.svg new file mode 100644 index 00000000..9a335854 --- /dev/null +++ b/docs/assets/logo/svg/optical/24/braid-black-on-white.svg @@ -0,0 +1 @@ +Braid black on white / 24px optical \ No newline at end of file diff --git a/docs/assets/logo/svg/optical/24/braid-white-on-black.svg b/docs/assets/logo/svg/optical/24/braid-white-on-black.svg new file mode 100644 index 00000000..a2e5ee52 --- /dev/null +++ b/docs/assets/logo/svg/optical/24/braid-white-on-black.svg @@ -0,0 +1 @@ +Braid white on black / 24px optical \ No newline at end of file diff --git a/docs/assets/logo/svg/optical/24/braid-white-on-transparent.svg b/docs/assets/logo/svg/optical/24/braid-white-on-transparent.svg new file mode 100644 index 00000000..0e3c0932 --- /dev/null +++ b/docs/assets/logo/svg/optical/24/braid-white-on-transparent.svg @@ -0,0 +1 @@ +Braid white on transparent / 24px optical \ No newline at end of file diff --git a/docs/assets/logo/svg/optical/32/braid-black-on-transparent.svg b/docs/assets/logo/svg/optical/32/braid-black-on-transparent.svg new file mode 100644 index 00000000..0b77a219 --- /dev/null +++ b/docs/assets/logo/svg/optical/32/braid-black-on-transparent.svg @@ -0,0 +1 @@ +Braid black on transparent / 32px optical \ No newline at end of file diff --git a/docs/assets/logo/svg/optical/32/braid-black-on-white.svg b/docs/assets/logo/svg/optical/32/braid-black-on-white.svg new file mode 100644 index 00000000..51bab1e0 --- /dev/null +++ b/docs/assets/logo/svg/optical/32/braid-black-on-white.svg @@ -0,0 +1 @@ +Braid black on white / 32px optical \ No newline at end of file diff --git a/docs/assets/logo/svg/optical/32/braid-white-on-black.svg b/docs/assets/logo/svg/optical/32/braid-white-on-black.svg new file mode 100644 index 00000000..7013b3f4 --- /dev/null +++ b/docs/assets/logo/svg/optical/32/braid-white-on-black.svg @@ -0,0 +1 @@ +Braid white on black / 32px optical \ No newline at end of file diff --git a/docs/assets/logo/svg/optical/32/braid-white-on-transparent.svg b/docs/assets/logo/svg/optical/32/braid-white-on-transparent.svg new file mode 100644 index 00000000..dc314724 --- /dev/null +++ b/docs/assets/logo/svg/optical/32/braid-white-on-transparent.svg @@ -0,0 +1 @@ +Braid white on transparent / 32px optical \ No newline at end of file diff --git a/docs/assets/logo/svg/optical/48/braid-black-on-transparent.svg b/docs/assets/logo/svg/optical/48/braid-black-on-transparent.svg new file mode 100644 index 00000000..58772a91 --- /dev/null +++ b/docs/assets/logo/svg/optical/48/braid-black-on-transparent.svg @@ -0,0 +1 @@ +Braid black on transparent / 48px optical \ No newline at end of file diff --git a/docs/assets/logo/svg/optical/48/braid-black-on-white.svg b/docs/assets/logo/svg/optical/48/braid-black-on-white.svg new file mode 100644 index 00000000..c64ca7a5 --- /dev/null +++ b/docs/assets/logo/svg/optical/48/braid-black-on-white.svg @@ -0,0 +1 @@ +Braid black on white / 48px optical \ No newline at end of file diff --git a/docs/assets/logo/svg/optical/48/braid-white-on-black.svg b/docs/assets/logo/svg/optical/48/braid-white-on-black.svg new file mode 100644 index 00000000..a150a26b --- /dev/null +++ b/docs/assets/logo/svg/optical/48/braid-white-on-black.svg @@ -0,0 +1 @@ +Braid white on black / 48px optical \ No newline at end of file diff --git a/docs/assets/logo/svg/optical/48/braid-white-on-transparent.svg b/docs/assets/logo/svg/optical/48/braid-white-on-transparent.svg new file mode 100644 index 00000000..b01239b4 --- /dev/null +++ b/docs/assets/logo/svg/optical/48/braid-white-on-transparent.svg @@ -0,0 +1 @@ +Braid white on transparent / 48px optical \ No newline at end of file diff --git a/docs/assets/logo/svg/optical/64/braid-black-on-transparent.svg b/docs/assets/logo/svg/optical/64/braid-black-on-transparent.svg new file mode 100644 index 00000000..3cbd6357 --- /dev/null +++ b/docs/assets/logo/svg/optical/64/braid-black-on-transparent.svg @@ -0,0 +1 @@ +Braid black on transparent / 64px optical \ No newline at end of file diff --git a/docs/assets/logo/svg/optical/64/braid-black-on-white.svg b/docs/assets/logo/svg/optical/64/braid-black-on-white.svg new file mode 100644 index 00000000..2f57a7c2 --- /dev/null +++ b/docs/assets/logo/svg/optical/64/braid-black-on-white.svg @@ -0,0 +1 @@ +Braid black on white / 64px optical \ No newline at end of file diff --git a/docs/assets/logo/svg/optical/64/braid-white-on-black.svg b/docs/assets/logo/svg/optical/64/braid-white-on-black.svg new file mode 100644 index 00000000..4167c8aa --- /dev/null +++ b/docs/assets/logo/svg/optical/64/braid-white-on-black.svg @@ -0,0 +1 @@ +Braid white on black / 64px optical \ No newline at end of file diff --git a/docs/assets/logo/svg/optical/64/braid-white-on-transparent.svg b/docs/assets/logo/svg/optical/64/braid-white-on-transparent.svg new file mode 100644 index 00000000..2474e2a2 --- /dev/null +++ b/docs/assets/logo/svg/optical/64/braid-white-on-transparent.svg @@ -0,0 +1 @@ +Braid white on transparent / 64px optical \ No newline at end of file diff --git a/docs/assets/logo/svg/small-optical-color/braid-color-on-badge.svg b/docs/assets/logo/svg/small-optical-color/braid-color-on-badge.svg new file mode 100644 index 00000000..f601455b --- /dev/null +++ b/docs/assets/logo/svg/small-optical-color/braid-color-on-badge.svg @@ -0,0 +1,6 @@ +Braid color / badge / small optical + + + + + \ No newline at end of file diff --git a/docs/assets/logo/svg/small-optical-color/braid-color-on-black.svg b/docs/assets/logo/svg/small-optical-color/braid-color-on-black.svg new file mode 100644 index 00000000..c8312413 --- /dev/null +++ b/docs/assets/logo/svg/small-optical-color/braid-color-on-black.svg @@ -0,0 +1,6 @@ +Braid color / black / small optical + + + + + \ No newline at end of file diff --git a/docs/assets/logo/svg/small-optical-color/braid-color-on-transparent.svg b/docs/assets/logo/svg/small-optical-color/braid-color-on-transparent.svg new file mode 100644 index 00000000..75bb06f3 --- /dev/null +++ b/docs/assets/logo/svg/small-optical-color/braid-color-on-transparent.svg @@ -0,0 +1,6 @@ +Braid color / transparent / small optical + + + + + \ No newline at end of file diff --git a/docs/assets/logo/svg/small-optical-color/braid-color-on-white.svg b/docs/assets/logo/svg/small-optical-color/braid-color-on-white.svg new file mode 100644 index 00000000..83c14840 --- /dev/null +++ b/docs/assets/logo/svg/small-optical-color/braid-color-on-white.svg @@ -0,0 +1,6 @@ +Braid color / white / small optical + + + + + \ No newline at end of file diff --git a/docs/assets/logo/svg/standard/braid-black-on-transparent.svg b/docs/assets/logo/svg/standard/braid-black-on-transparent.svg new file mode 100644 index 00000000..1cdcbc5e --- /dev/null +++ b/docs/assets/logo/svg/standard/braid-black-on-transparent.svg @@ -0,0 +1 @@ +Braid black on transparent / approved standard \ No newline at end of file diff --git a/docs/assets/logo/svg/standard/braid-black-on-white.svg b/docs/assets/logo/svg/standard/braid-black-on-white.svg new file mode 100644 index 00000000..e973a7a4 --- /dev/null +++ b/docs/assets/logo/svg/standard/braid-black-on-white.svg @@ -0,0 +1 @@ +Braid black on white / approved standard \ No newline at end of file diff --git a/docs/assets/logo/svg/standard/braid-color-on-badge.svg b/docs/assets/logo/svg/standard/braid-color-on-badge.svg new file mode 100644 index 00000000..3528f76d --- /dev/null +++ b/docs/assets/logo/svg/standard/braid-color-on-badge.svg @@ -0,0 +1,6 @@ +Braid color / badge / standard + + + + + \ No newline at end of file diff --git a/docs/assets/logo/svg/standard/braid-color-on-black.svg b/docs/assets/logo/svg/standard/braid-color-on-black.svg new file mode 100644 index 00000000..a48159e1 --- /dev/null +++ b/docs/assets/logo/svg/standard/braid-color-on-black.svg @@ -0,0 +1,6 @@ +Braid color / black / standard + + + + + \ No newline at end of file diff --git a/docs/assets/logo/svg/standard/braid-color-on-transparent.svg b/docs/assets/logo/svg/standard/braid-color-on-transparent.svg new file mode 100644 index 00000000..c04912d7 --- /dev/null +++ b/docs/assets/logo/svg/standard/braid-color-on-transparent.svg @@ -0,0 +1,6 @@ +Braid color / transparent / standard + + + + + \ No newline at end of file diff --git a/docs/assets/logo/svg/standard/braid-color-on-white.svg b/docs/assets/logo/svg/standard/braid-color-on-white.svg new file mode 100644 index 00000000..592202e9 --- /dev/null +++ b/docs/assets/logo/svg/standard/braid-color-on-white.svg @@ -0,0 +1,6 @@ +Braid color / white / standard + + + + + \ No newline at end of file diff --git a/docs/assets/logo/svg/standard/braid-white-on-black.svg b/docs/assets/logo/svg/standard/braid-white-on-black.svg new file mode 100644 index 00000000..1f23e24d --- /dev/null +++ b/docs/assets/logo/svg/standard/braid-white-on-black.svg @@ -0,0 +1 @@ +Braid white on black / approved standard \ No newline at end of file diff --git a/docs/assets/logo/svg/standard/braid-white-on-transparent.svg b/docs/assets/logo/svg/standard/braid-white-on-transparent.svg new file mode 100644 index 00000000..db5ef151 --- /dev/null +++ b/docs/assets/logo/svg/standard/braid-white-on-transparent.svg @@ -0,0 +1 @@ +Braid white on transparent / approved standard \ No newline at end of file diff --git a/docs/user-manual/console.md b/docs/user-manual/console.md new file mode 100644 index 00000000..3fbbf52c --- /dev/null +++ b/docs/user-manual/console.md @@ -0,0 +1,106 @@ +# Braid Web Console + +Console 与 Braid 一起交付,不需要 Python、Node 或前端构建环境。它接收 OTLP +HTTP/protobuf,保存原始批次和解码记录,并在浏览器中展示 traces、logs、metrics +和 provider 证据。Console 属于整个 Braid,接入平台对象 API 与统一 Harness 控制, +不属于内建平台的专属运行模式。 +HTTP 后端调用 Braid 的应用模块,不执行 Braid CLI 子进程。 + +先按[内建平台指南](local.md)分别声明平台与 Harness,再由 Console 便捷装配: + +```shell +braid migrate apply --config /absolute/space/config.toml +braid console --platform-config /absolute/platform.toml --config /absolute/space/config.toml \ + --database /absolute/space/observations.sqlite3 --listen 127.0.0.1:4318 +``` + +遥测数据库必须与 runtime 数据库分开。Console 仅监听 loopback;浏览器打开输出 +的地址。平台库、Harness 库、遥测库必须各自独立。Mac 本项目的配置、数据库 +和临时数据都应位于 WorkSSD。`--config` 可为 GitHub 或内建上游;只有 +`--platform-config` 时也可管理对象。两者均省略时只提供 Collector 和观测阅读。 +已经独立启动平台时,不再提供 `--platform-config`,Console 按 Harness 的 +`builtin.endpoint` 接入其 API。 + +Console 启动后 runtime 尚未启动。页面中的“启动”操作携带当前 generation; +“仅传输”处理本地对象和队列,不启动模型。普通启动会使用配置中的真实 provider, +需要对应凭据和运行授权。托管 runtime 在内存中使用本 Console 地址作为 OTLP +endpoint,不改磁盘配置。停止 runtime 后页面、Collector 和对象操作仍可使用, +停服期间平台继续接受对象操作,稳定事件等待 Harness 从自己的 cursor 接续。 +平台服务是否可用、Harness 是否执行与最后观测时间分别展示;启动平台不启动 Agent。 + +观测数据库打开失败时,平台和 Harness 控制仍可使用。OTLP 和证据读取返回 +503,概览显示采集错误。修复存储后重启 Console 以恢复采集。 + +## 阅读证据与当前状态 + +概览将 Collector 收到的数据、新鲜度和 runtime 权威状态分别展示。trace 时间轴 +可以查看 Span、事件和缺失父节点;日志和 provider 原始事件可按 instance、session、 +turn 或 trace 阅读;metrics 保留实际数据点和分布。原始批次可下载,接收时间与 +事件发生时间各自保留。采样、未关联记录和接收错误会造成缺口;没有新数据不能 +证明 Agent 空闲,模型 token 增长也不能证明任务进展。 + +Collector 接收 `/v1/traces`、`/v1/logs`、`/v1/metrics` 的 +`application/x-protobuf`,支持 identity 和 gzip 编码。原始请求与解码记录原子保存 +后才返回成功。分页查询使用稳定递增记录游标;重发批次保留接收事实与重复标记, +不能把 metric 的累计数据点相加成额外消耗。HTTP 错误保留具体状态和原因。 + +完整 provider 证据仍服从 runtime 的采样设置。它通过明确 session 与 turn 身份 +关联,不从正文或相近时间猜归属。未关联的连接输出保留为连接级证据。SQLite 与 +provider 决定当前对象和执行事实,OTLP 只提供观测历史,不承担可靠命令投递。 + +## 操作与回执 + +内建平台对象页可创建 Issue/PR、编辑正文、评论及回复、指派或解除、关闭或重开、 +关联 PR、发布候选和合并。修改携带开始编辑时的 revision;冲突保留草稿,用户 +查看最新正文后再决定是否重新提交。发布可以明确选择配置 source 的当前已提交 checkout,或该 PR 当前责任登记的 +worktree。Harness 核验责任后交接固定提交 OID,平台在绑定 Git 对象库中核验并 +保留候选;浏览器不能提交任意路径。Git 合并沿用平台对象的持久意图和 base 引用检查, +不是 Git 与 SQLite 的跨系统原子事务。 + +Diff 显示生成该内容时的对象编号、revision 及固定 head/base OID。它与详情页 +版本不一致时,页面提示详情已过期并提供刷新;该快照不会自动改变合并使用的 +revision 前提,采纳前应重新核对当前候选。 + +每次命令带 request ID。同一个 ID 不可换成另一份命令,响应丢失后查询原回执, +不自动重新执行修改。对象回执表示对象与事件已接受,不能证明 Agent 已阅读或 +业务完成。runtime 启停回执也只表示请求接受;只有监督器收到全部 worker 的 +真实停止结果才展示“已停止”。停止失败展示具体错误并禁止替代启动。 + +若 Console 异常退出而没有保存停止确认,下次使用同一实例会展示阻塞状态, +不会把旧执行当作已经结束。需要核对并处置该实例原生执行后再恢复;当前版本不 +提供网页“强制清除”来绕过停止证明。Console 可与托管平台和 Harness 处于同一进程,尚不提供 +进程级故障隔离、暂停/恢复、远程访问、多人权限或外部 GitHub 对象修改入口。GitHub 接入拥有同一 Harness 启停入口, +对象编辑仍使用该上游已有操作方式;不能用内建平台 UI 向 GitHub 伪装对象写入。 +外部隧道接入 managed GitHub ingress 时,App webhook URL 必须包含 `/webhook` +路由;仅公网 host 根路径不会接收对象事件。以 GitHub 的实际 delivery 响应 +确认投递,不把隧道存活或另一路径的签名请求当作当前 App URL 已生效。 + +## 数据边界 + +遥测可能包含完整正文、工具输出、路径和配置所允许的敏感诊断。采样控制容量, +不是保密措施;Collector 数据及原始批次只应交给该实例授权操作者。Console 没有 +自动删除历史数据,需由操作者停止服务后管理数据库备份与保留范围。 + +采样命中的完整 provider/GitHub/credential evidence 只通过专用 target 进入 OTLP +logs,不写普通 stderr/journal,也不复制为 trace event。普通日志保留生命周期与 +关联信息,payload 覆盖用指标计数,不逐 chunk 输出摘要。配置外部 LGTM、按 +trace/session 回读、探针结果边界和销毁临时后端的方法见 +[部署观测指南](../40-deployment/README.md#opentelemetry)。Console Collector +和外部 LGTM 是可选接收端,不要把端口可达或 SDK export success 当作持续存储证明。 + +页面以文本呈现不可信内容,不执行记录中的 HTML。HTTP 接口校验 loopback Host +和写操作 Origin,浏览器不能提供任意 shell 命令、PID 或文件根目录。这些措施 +防止网页误驱动本机接口,不把拥有本机账户权限的进程视为隔离的对手。 + +## 选择常驻服务或 root 运行 + +配置 built-in 上游后,运行方式可以选择常驻 `serve` 或有限 `run`。run 输入为已有 +root 编号或 description(二者择一),并声明 run ID、交付 ref 和最大并发 Braid 轮次。 +首版 GitHub 上游仍使用 serve;run 不能与“仅传输”同时启用。 + +`POST /api/runtime/commands` 保持原 request_id、operation、expected_generation 合同, +启动 run 时附 `run_request`,其字段为 runId、rootIssue 或 description、deliveryRef 和 +maxConcurrency。状态与回执分别展示 run 结果和 stop_confirmed;确认停止后的 blocked/failed +结果可以由明确新启动接续,不确定停止仍禁止覆盖。run 的确定交付 commit 不等于应用验收通过。 +`/api/harness/snapshot` 阅读当前 run 的真实 ledger,平台对象和 OTLP 保持各自权威。 +完整输入、配置冻结、交付和接续方法见[自主运行指南](run.md)。 diff --git a/docs/user-manual/local.md b/docs/user-manual/local.md new file mode 100644 index 00000000..6a907a58 --- /dev/null +++ b/docs/user-manual/local.md @@ -0,0 +1,98 @@ +# 内建协作平台 + +GitHub 与内建协作平台是 Braid Harness 的两种上游。内建平台独立持有仓库、 +Issue、PR、正文、评论、指派、事件和候选合并记录,不依赖 Harness 的 Profile、 +会话或执行数据库。停止 Harness 不停止平台,也不删除协作内容。Web Console +属于整个 Braid,可同时阅读平台、Harness 和 OTLP 观测。 + +## 声明平台与 Harness + +先准备有命名分支的真实 Git checkout。平台有自己的配置与数据库,不需要安装 +Agent CLI 或提供模型凭据: + +```shell +braid platform init --source /absolute/path/to/repository --config /absolute/path/to/platform.toml --name demo +braid platform serve --config /absolute/path/to/platform.toml +``` + +平台声明固定 repository、source、默认分支、数据库与 loopback listen 地址。 +默认分支不会随 source 当前检出的分支改变。平台对象只能访问已绑定的 Git +对象库,HTTP 调用不能提交任意文件路径。 + +Harness 单独声明上游与执行环境。准备实际安装的 Pi 或 Codex,并明确模型。 +Pi 还要显式声明 LLM provider id 与凭据 kind:`api_key` 引用 `provider_api_key = "..."` +的 secret 文件(`0600`),`oauth` 引用 token set 文件,keyless 用 `none`。Codex +使用自己的 provider home,不接受这些 LLM 参数。初始化不复制 key 值,也不在 +配置中声明环境变量: + +```shell +braid init --source /absolute/path/to/repository --config /absolute/path/to/harness/config.toml --name demo --endpoint http://127.0.0.1:18082 --adapter pi --executable /absolute/path/to/pi --model --llm-provider --llm-base-url https://llm.example.invalid/v1 --llm-credential-kind api_key --llm-credential-file /absolute/path/to/user/secrets/.toml +braid config check --config /absolute/path/to/harness/config.toml +braid migrate apply --config /absolute/path/to/harness/config.toml +braid serve --config /absolute/path/to/harness/config.toml +``` + +Harness 的 `[builtin]` 只选择平台 repository 与 endpoint,与 `[github]` 互斥。 +Profile 的 workspace 是执行源,与平台声明分别维护;首版候选交接要求两者 +能访问同一个 Git 对象库,不承诺远程 clone/push 托管。平台不读取 Harness +数据库;Harness 通过 HTTP 获取当前对象和稳定事件,在自己的 ledger 保留 +消费游标与去重记录。更换执行实例不会消耗或删除平台事件。 + +## 工作项与候选 + +通过[Web Console](console.md)可以不启动 Harness 就创建和讨论工作项。指派的 +actor 是平台事实;Harness 将它映射为当前支持的 Profile。只有实际开始执行 +并取得写入授权后,Agent 才能发布内容。对象正文是当前工作依据,评论是讨论 +数据,不能获得系统指令权限。 + +`braid object --config ` 是 Harness 的对象接入入口,使用平台 API, +不直接修改平台数据库。只读 list/show/context/diff 及对象命令 receipt 使用同一 +平台的公开读取路径,仍核对配置中的 repository、nodeId 与持久 spaceId,不要求 +写 grant;关闭后的收口也可以读取 Context。Agent 写入时,Harness 核对专属 cwd、 +当前 assignment、session 与 turn,并使用已授予的 writer grant;平台提交事务核对 +授权版本、对象 revision 与 request ID。撤销授权先于替换执行,过期请求明确 +拒绝。此合同防止正常执行串写,不是恶意本机账户的安全沙箱。 + +失去响应时,先用 `braid object --config receipt ` 查询 +原回执,不生成新请求。需要重复提交时保留原 `--request-id`、命令内容和 +`--expected-revision`;不能重新读取当前 revision 后把不同前提当成同一请求。 +关闭后的执行收口先确认撤权,清理执行不重新获得正文发布权限。 + +PR 保存固定的 base/head 提交;发布候选交接完整 commit OID,不重新解析可变 +工作分支。平台在自己的 Git 对象库核验并保留候选引用。新实施工作树从已发布 +候选接续。合并是显式的候选采纳动作,不自动验收或关闭关联 Issue;拒绝冲突、 +base 移动及不安全的检出状态。合并前将 source 和其它 worktree 切离目标 base。 + +Git 引用与 SQLite 不是同一事务。平台在移动 Git 引用前,将请求 ID 与合并意图的 +精确 commit 一起持久保存;合并完成的对象状态、事件和成功回执在同一数据库事务中 +提交。若 Git 引用已更新而最终记录失败,保留原请求重试;只有当前目标引用仍指向 +该请求绑定的 commit 时,平台才补齐记录。此确认可以在原 writer 已撤权后完成, +不会重新移动 Git 引用或授予写权限。未被采用的合并不会借重试绕过撤权。 +候选发布的对象更新、事件和成功回执也一起提交,回执保存失败不会留下已发布状态。 + +旧版本遗留、未绑定精确 commit 的 prepared 回执,以及目标引用已经继续前移的 +未完成合并,不能自动判定归属。保留数据库、Git 引用和原请求现场,核实后再处理; +不要改写 request ID 或预期 revision 来冒充原请求恢复。 + +## 从旧 Local 实例迁移 + +旧 `[local]` 将平台和 Harness 数据混在一起,新 binary 明确拒绝继续使用。 +停止旧 daemon 和对象写入入口,保留现场并核实 prepared/unknown 写入、合并意图 +及原生执行停止结果。声明独立平台后显式导入旧 runtime 数据库: + +```shell +braid platform import --config /absolute/path/to/platform.toml --from-runtime-db /absolute/path/to/old/state/braid.sqlite3 +``` + +导入保留原数据库及对象编号、local:*身份、事件、正文、评论、关联、候选与 +对象命令回执。执行会话和运行回执留在 Harness;旧会话不自动取得新写授权。 +将 Harness 配置改为 `[builtin]`,保留原 Profile workspace 和 runtime 路径, +应用 Harness 迁移后再接入平台。新入口重新投递稳定事件,已有 delivery 去重, +不以旧 consumed_at 最大值跳过未消费事件。不可继续用旧 binary 写原库,否则 +会形成两份对象权威。 + +没有模型调用时,`serve --transport-only` 可实际核对上游接入、事件和队列, +不能证明 Agent 已完成产品工作。当前不提供 GitHub API 全兼容、双向同步、 +远程多人权限系统或完整跨进程崩溃恢复。 + +平台也可为[自主 run](run.md)提供 root、父子 Issue 和关联 PR。run 是 Harness 的运行方式;不启动 run 仍可完整使用平台对象与常驻 serve。 diff --git a/docs/user-manual/profiles.md b/docs/user-manual/profiles.md new file mode 100644 index 00000000..d573258f --- /dev/null +++ b/docs/user-manual/profiles.md @@ -0,0 +1,130 @@ +# Agent Profile 与原生材料 + +Profile 定义根 Agent 的 adapter、model、可选 reasoning、指令及支持的材料选择; +只有 Pi Profile 额外引用 `llm_providers` 中的 provider。Codex 通过自己的 +provider home 认证,Profile 不声明 LLM provider 或 API key 文件。GitHub +多 repository instance 中,每个 Profile 还必须声明自己的 `repository` 和 +显式 `workspace`;Profile id 在 instance 内唯一,不能用同一 id 隐含不同仓库 +的指令。Repository 只限定调度、工作区、恢复和写入边界,不共享 Context。 +Runtime 定义 +可执行入口、adapter 版本及锁定插件安装。Factory 的 preset、variant +和实验配方由消费方装配,不导入 Braid 的配置目录。Pi 原生 subagent 角色是根 +Agent 的局部执行能力,不是可独立指派的 Braid Profile。 + +`user_instructions` 保持现有配置字段。消费方可以从独立的 `instructions.md` +装配它,但不能将 SKILL.md 或 references 正文混入这些角色指令;Braid 不接管 +Factory 的模板生成流程,也不默认要求其 SVC 技能、分支流程或原生角色配方。 + +当前执行器使用第一个带 `issue` tag 的 Profile 和 `profile_selection.default_pr_profile` +指定的 PR Profile。配置中存在其它 Profile 不表示有对应 driver;不要将 catalog +可查看解释为任意 Profile 可执行。 + +## 选择 Pi 材料 + +在已有 `[[profiles]]` 中可以配置以下可选字段;相对路径按 Harness 配置文件所在 +目录解析。`skills` 的每项是一个技能目录、直接的 `SKILL.md`,或直接子目录各自 +包含 `SKILL.md` 的技能 catalog;catalog 按稳定目录名展开,不递归寻找更深层的 +技能集合。其它 adapter 没有此材料消费接口,非空配置会明确拒绝。 + +```toml +skills = ["materials/skills/example"] +native_template = "materials/pi-issue" +``` + +技能独立保存,包含按需读取的 references 和工具资源。Pi 使用显式技能发现入口, +提示词只包含名称、description 和路径;Braid 不把 SKILL.md 或 reference 正文拼入 +system、profile 或任务输入。已选锁定插件附带的技能仍由安装 manifest 决定; +项目或用户目录中未选择的技能不自动加入。仓库的 [braid-collaboration](../../skills/README.md) +是可选方法材料,Braid 不自动安装或启用它。 + +Pi 模板是材料源,允许 `settings.json` 和 `agents/*.md`,不携带 auth、原生会话、 +缓存或临时文件。未指定模板时,已有 `RuntimeEntry.home` 的受支持语义文件作为 +只读来源,不能将整个 home 当作模板复制。没有这两种来源时使用空模板。每个执行 +工作树持有独立、持久的 Braid 原生材料目录,避免 Issue 与 PR 改写共享 home; +恢复不会用当前模板覆盖旧材料。 + +`models.json` 不再是材料输入:Pi adapter 从 `llm_providers` 声明派生它。每个被 +Pi Profile 引用的条目需要 `base_url`、可选 `api`,以及至少包含 Profile `model` +的 `[[llm_providers.models]]` 声明(`id`、`name`、`reasoning`、`input`、 +`context_window`、`max_tokens`、`thinking_level_map`、`compat` 均按声明渲染)。渲染出的 +`apiKey` 只在 `credential.kind = "api_key"` 时出现并引用 Braid 管理的 +`$BRAID_PROVIDER_API_KEY`;模板或 runtime home 中出现 `models.json` 会被明确拒绝并 +指向这份声明。根模型及推理仍由 Profile 决定,不是第二套根模型选择;凭据由 +`llm_providers` 条目的 `credential` 声明。`settings.json` 只支持有实际消费者的设置,不能另行选择根模型、 +凭据、扩展、技能或动态安装 package。扩展由 `RuntimeEntry.native_runtime` 的锁定 +manifest 提供。原生子角色的职责、模型、工具与继承范围由受支持的角色材料及 +Pi 插件决定;Braid 不把这些角色提升为 Issue/PR 负责人,也不承诺仓库代码的 +安全沙箱。 + +## Provider credential + +每个 `llm_providers` 条目必须显式声明凭据,三种 kind 覆盖全部情况: + +```toml +[[llm_providers]] +id = "example-llm" +credential = { kind = "api_key", file = "/absolute/path/to/secrets/example-llm.toml" } +# 或:credential = { kind = "oauth", file = "/absolute/path/to/secrets/kimi.toml" } +# 或:credential = { kind = "none" }(显式 keyless,不引用任何文件) +``` + +凭据文件是 Braid 自己的 schema,不是 runtime 的文件格式。`api_key` 文件仍是 +`provider_api_key = "..."`;`oauth` 文件是 token set: + +```toml +access = "..." +refresh = "..." +expires = 4102444800000 # epoch 毫秒 +account = "..." # 可选,仅诊断展示 +``` + +Pi adapter 是唯一位于 runtime 格式边界内的层:`api_key` 凭据被读取后以 +`BRAID_PROVIDER_API_KEY` 注入对应 Pi 子进程(`models.json.apiKey` 固定引用该 +名称,且仅在 kind 为 `api_key` 时允许);`oauth` token set 被渲染为 session home +的 `auth.json`,`none` 不注入任何东西。凭据是静态秘密,Braid 从不修改凭据文件; +过期或轮换由显式替换触发,内容 hash 变化会改变 Profile 有效版本并让旧 session +明确 blocked。kind 与内容摘要可见于 `braid profile inspect`,凭据值永不展示。 + +既有 Pi `auth.json` 不要手工复制到任何 runtime home——材料快照从不携带它。 +用一次性显式 import 转换进 Braid secrets: + +```sh +braid provider import-auth --from /path/to/auth.json +``` + +服务 URL 不携带 userinfo 凭据。Header +保留 Pi 的原生解析能力,识别为认证用途的 header 必须引用同一固定名称,普通协议 +header 可以声明非秘密值;配置者不得借其它 +字段写入凭据。本材料合同支持 `$ENV_NAME`、`${ENV_NAME}` 及常见 `Bearer` 引用; +未知环境引用、其它混合模板和 `!command` 明确拒绝,后者会额外执行未受控 shell。 +正常版本或部署 query 保留,明确的凭据 query 不允许。模板中的非空原生角色 +extensions 会明确拒绝,不能绕开锁定安装。 +要消费 `agents/*.md` 或 `subagents` 设置,受控 Pi 安装须显式选择 `subagents` 插件; +模板不负责安装或启用它。外部基础 Pi 的扩展发现关闭,不提供这项原生角色能力。 +角色 `skillPath: "@SKILLS@"` 指向本次 Profile 技能快照的 catalog,按技能名称 +选择的条目须在 `skills` 声明中,不能引用未冻结的外部材料。 + +## 查看实际选择与恢复身份 + +```sh +braid profile inspect --config /absolute/path/to/config.toml PROFILE_ID +braid profile inspect --config /absolute/path/to/config.toml PROFILE_ID --json +``` + +查看结果保留 Profile 声明,并提供有效版本、摘要和选择的材料身份。它不显示 +原生文件正文或凭据值,也不证明已发起模型推理。实际启动记录用于核对对应会话 +消费的材料;原生子角色是否执行仍需其实际启动、结果和模型记录。 + +有效 Profile 身份包含声明、adapter 合同、锁定安装 manifest、所选技能与模板 +内容及非秘密服务路由。临时 execution、工作树和派生 home 路径及凭据值不作为 +语义材料身份。材料变化会改变有效版本;恢复旧版本会明确 blocked,不静默在 +新材料下续用旧历史。应先完成旧执行停止,再按现有公开重新指派或新运行流程 +消费新配置,不能修改 ledger 或旧 home 标记制造兼容。 + +Pi 自己保存的根模型偏好不成为第二权威:Profile 显式指定的 model 及根 +provider 覆盖对应偏好;reasoning 只在声明时覆盖。快照设置按 JSON 语义核对,避免仅格式变化阻断恢复; +其它行为键、角色与技能内容变化仍拒绝复用。原生运行状态不作为声明材料复制。 + +这次身份合同补全后,旧版仅按 Profile JSON 生成的版本也可能不兼容;保留旧 +运行、原生记录与材料,不将新配置启动称为原生历史接续。配置查看、编译与 +无推理装载只证明各自边界,不代替真实模型协作和产品验收。 diff --git a/docs/user-manual/run.md b/docs/user-manual/run.md new file mode 100644 index 00000000..f3a1b66a --- /dev/null +++ b/docs/user-manual/run.md @@ -0,0 +1,44 @@ +# 从 root 任务自主推进 + +`braid run` 在内建协作平台上执行一次以 root Issue 为范围的工作。平台是独立的 minimal GitHub;`serve` 持续响应协作事件,`run` 让 root Agent 组织拆分、分派和成果整合,并保存可判断的运行结果。Web Console 属于整个 Braid,两个入口使用同一套调度和原生执行。 + +先按[内建平台指南](local.md)配置真实 Git checkout、独立平台与 Harness。平台须已运行,Harness 配置须包含实际 provider、模型和角色。业务输入可以只有一个 description 文件,但这不替代仓库配置、模型凭据或运行授权。首版 `run` 接入 built-in,不接入外部 GitHub。 + +```shell +braid run --config /absolute/path/to/harness/config.toml --run-id feature-a \ + --description-file /absolute/path/to/requirements.md \ + --delivery-ref refs/heads/run/feature-a --max-concurrency 2 +``` + +现有 root 必须是没有父 Issue 的顶层任务;已作为其它任务子项的 Issue 不能直接注册为 run root。已有 root 则把 `--description-file` 换成 `--root-issue 42`,二者不可同时提供。description 创建的 root 通过固定请求 ID 去重;`run-id` 绑定输入、交付 ref、并发和执行相关的解析配置。同一个 ID 接续可以调整遥测采样或输出端点,仍使用原需求和执行配方。完成后再次调用只回读既有完成结果,不重新生成。未确认旧执行停止时禁止替代启动。 + +每次 run 有独立 Harness ledger、工作树和冻结配置,存于原 `runtime.root/runs//`。平台仍保存唯一的 Issue/PR 工作图;run 不接管 `serve` 的旧指派和无关对象。description 或现有 root、子项和关联 PR 通过公开平台 API 读取和修改,不直接操作平台数据库。配置和原生历史仍包含实例允许保存的材料,应按该实例的授权范围保留。 + +## 协作和交付 + +root 使用专属协调职责,Agent 自行决定拆分方式、依赖顺序和何时指派。Harness 不按需求编号拆工作。子 Issue 正文应保留必要需求、共享决定、依赖和交付 ref;root 等待成员时应结束当前轮次以让出 Issue 组的执行机会。PR Agent 实现并发布真实 Git 候选;业务技能和固定交付步骤由调用方配置,不自动植入 Factory 的 Web 应用、基础 PR 或最终整合 PR 配方。 + +子 Issue 用 `braid object issue --title ... --body-file ... --parent <父Issue>` 创建。创建和父子关系在同一平台事务提交,不提供事后随意重绑入口。创建未指派对象不启动成员。平台将子项生命周期、候选发布、讨论和设计变化送回祖先;讨论及设计通知仅包含对象和变化类型,正文仍按需读取。root 根据当前对象事实采用成果,不依赖模型会话记忆推断交接完成。 + +run 的交付 ref 必须明确写为 `refs/heads/...`。平台冻结 root、run ID、Harness client 与该 ref 的关系,Agent 不能修改这项运行授权,范围内 PR 的 base 和合并目标由平台校验。若交付分支尚不存在,平台在处理首个范围内 PR 的候选时,从当前默认分支创建它。已有交付分支保持原位。建议每 run 使用独立交付分支。合并仍检查确切候选、base 是否移动以及分支检出状态。 + +root writer 只能协调自己的后代 Issue 和关联 PR;子项不获得任意仓库管理身份。注册 root 关闭时整个范围 writer 立即失效,子项不能在收尾期间继续发布。普通 `serve` 的关联 Issue 关闭规则不因此改变。root 应在范围义务收敛后最后关闭;提前关闭不作为成功,需由操作者明确重开才能继续。 + +`--max-concurrency` 限制同时在途的 Braid 轮次,root 也计入,默认 2。它不限制空闲 Pi 会话、Pi 内部 subagents 或 background 服务的数量;当前 Issue/PR 两组执行还限制各自组内同时在途轮次。保留物理会话可能增加内存占用,不能把这个参数当作总进程或宿主内存上限。当前不自动驱逐健康空闲会话来释放容量。 + +## 结果和停止 + +运行输出结构化结果,保留 run ID、root、状态、交付 commit、具体原因与停止确认。状态含义如下: + +| 状态 | 含义 | +| --- | --- | +| `completed` | root 声明完成,范围义务收敛,确定交付 commit 对应已发布或合并的范围候选,未决写入及执行收尾满足合同。 | +| `blocked` | 明确前提或义务未满足,例如 root 提前关闭、合并冲突或执行无法恢复;保留具体原因。 | +| `failed` | 运行发生具体设施错误。 | +| `stopped` | 收到主动停止,不等于需求完成。 | + +root 开放且暂时没有可执行工作时继续等待,不因安静自动成功或失败。CLI 仅 completed 正常成功退出;其余状态保留结果并以非零结束。业务满足需求仍须对应用实际验收;completed 只说明团队交付声明与运行闭环已完成。 + +终态与 `stopConfirmed` 分别读取。实际原生停止不确定时不允许新运行覆盖。CLI 使用正常终止信号请求停止;Console 的停止按钮调用同一监督器。关闭 Harness 后平台对象和观测历史保留,不自动删除应用、候选或原生证据。异常退出不能推断为安全接续;核对原件并处理旧执行所有权后才继续。 + +Console 的运行方式选择 `run` 后可输入 description 或 root 编号、run ID、独立交付 ref 和并发轮次。“填入最近运行参数”只预填原始输入,不自动启动;从 description 创建的 run 接续仍保留原 description,不能借同一 ID 换为生成后的 root 编号。控制经同一个内进程应用接口,不启动 CLI 子进程;Harness snapshot 指向当前 run ledger,OTLP 只提供观测,不决定完成。更多命令回执和停止边界见[Console 指南](console.md)。 diff --git a/docs/user-manual/setup.md b/docs/user-manual/setup.md index 419d489d..00766151 100644 --- a/docs/user-manual/setup.md +++ b/docs/user-manual/setup.md @@ -17,17 +17,76 @@ braid --version - [`gh`](https://cli.github.com/) installed and authenticated with an account that can create GitHub Apps for the target owner (user or organization). - A repository where you will install the App. -- The selected runtime executable, [Pi](https://pi.dev/) or - [Codex](https://github.com/openai/codex). -- For the Pi provider: a DeepSeek API key exported as `DEEPSEEK_API_KEY` (or - the environment variable configured with `--api-key-environment`) *only at - setup time). An existing user-level provider secret also works. +- For the Pi adapter: an explicitly selected LLM provider, model, and + credential (`api_key`, `oauth`, or `none`) described below. Codex uses its + own provider home instead. + +## Pi 原生插件 + +需要 subagents 或 background 时,先按 [原生材料说明](../../native/pi/README.md) +安装锁定材料,再给 setup 指定 `--runtime-executable /pi`。 +Setup 识别相邻 `runtime-manifest.json`;既有配置可将 `[[runtimes]]` 的 +`executable` 与 `native_runtime` 指向同一安装。外部 Pi 仍可基础接入,但不会自动 +加载宿主扩展。材料验证失败须修复明确的文件或配置漂移,不能静默改走全局 Pi。 + +## Provider credential + +Every Pi setup declares an explicit credential kind for its LLM provider: +`api_key`, `oauth`, or `none`. Braid does not derive a default provider, model, +authentication method, or file name from the adapter. Credential files live in +Braid's own schema under `~/.braid/secrets/.toml` (mode `0600`); +never put them in `config.toml` or a shell environment variable: + +```shell +install -d -m 700 ~/.braid/secrets +${EDITOR:-vi} ~/.braid/secrets/.toml +chmod 600 ~/.braid/secrets/.toml +``` + +An `api_key` file contains `provider_api_key = "..."`. An `oauth` file is a +token set (`access`, `refresh`, `expires` in epoch milliseconds, optional +`account`). A `none` route references no file. The Pi adapter converts these +Braid-schema files at session materialization: `api_key` is injected as +`BRAID_PROVIDER_API_KEY` for the matching `models.json.apiKey` reference, +`oauth` is rendered into the session home's `auth.json`, `none` injects +nothing. Credentials are static secrets; replace the file to rotate. + +To migrate an existing Pi `auth.json`, run the one-shot converter instead of +copying it anywhere: + +```shell +braid provider import-auth --from /path/to/auth.json +``` + +The converter honors `BRAID_USER_HOME` (or `--user-home`) and prints the exact +file it wrote. Run it in the same environment as the instance it serves; the +printed path is the one to reference in `credential.file`. + +To migrate an existing configuration, remove `api_key_environment` and +`api_key_file`, add an explicit `credential = { kind, file }` entry, and store +the key in that file. Braid does not import legacy environment variables +automatically. ## Bootstrap +Pi requires an explicit model route, provider endpoint, and credential kind: + +```shell +braid setup owner/repository --instance --adapter pi --model \ + --llm-provider --llm-base-url https://api.example.invalid/v1 \ + --llm-credential-kind api_key --llm-credential-file ~/.braid/secrets/.toml +``` + +OAuth routes pass `--llm-credential-kind oauth` with the token-set file; a +keyless route passes `--llm-credential-kind none` and no file. The setup writes +`base_url` plus a single declared model; enrich `[[llm_providers.models]]` in +the generated config when you need capability metadata — the Pi adapter derives +`models.json` from it and rejects template copies. + +Codex uses its own authenticated home and no LLM provider arguments: + ```shell -export DEEPSEEK_API_KEY=... -braid setup owner/repository --instance +braid setup owner/repository --instance --adapter codex --model ``` `--instance` defaults to the repository owner. It is the local name for the @@ -36,50 +95,56 @@ and the `service.instance.id` telemetry attribute. Options: -- `--provider pi|codex` — defaults to `pi`. -- `--model ` — defaults to `deepseek-chat`. -- `--api-key-environment ` — env var to read the provider API key from - during setup; defaults to `DEEPSEEK_API_KEY`. The key is then persisted into - the user-level secrets file, so the env var is only needed at setup time. +- `--adapter pi|codex` — selects the Agent runtime adapter; it does not imply + an LLM provider. +- `--model ` — model requested from the selected runtime. +- `--reasoning ` — optional runtime reasoning/thinking level; Braid + does not choose one by default. +- Pi only: `--llm-provider ` declares the LLM route, + `--llm-base-url ` its endpoint (rendered into the derived `models.json`), + and `--llm-credential-kind api_key|oauth|none` plus + `--llm-credential-file ` (unless `none`) declare its credential. - `--user-home ` — defaults to `~/.braid` (or `BRAID_USER_HOME`). - `--instance ` — defaults to the repository owner. -- `--runtime-executable ` — use an explicit Pi or Codex executable - instead of automatic discovery. +- `--runtime-executable ` — use an explicit runtime executable instead + of automatic discovery. `braid setup` performs these steps: 1. Verifies `gh auth` and reads the acting GitHub login. 2. Resolves the Braid user home (`~/.braid` by default) and instance key (owner by default). -3. Generates a random webhook secret. -4. Builds a GitHub App Manifest with the permissions Braid needs +3. Checks the required tools, runtime executable, and generated configuration + before creating a GitHub App. +4. For Pi, validates the explicit credential file when the selected route + declares `api_key` or `oauth`. +5. Builds a GitHub App Manifest with the permissions Braid needs (`contents:write`, `issues:write`, `pull_requests:write`, `metadata:read`). -5. Starts a temporary local HTTP callback server. -6. Opens a browser to `github.com/settings/apps/new` (or the organization +6. Starts a temporary local HTTP callback server. +7. Opens a browser to `github.com/settings/apps/new` (or the organization variant) with the manifest pre-filled. -7. Captures the browser redirect and exchanges the code for the App's - private key, slug, and ID. -8. Verifies the selected runtime and resolves provider credentials from the - existing provider secret or the configured environment variable. +8. Captures the browser redirect and exchanges the code for the App's + private key, slug, ID, and webhook secret. Braid preserves the returned secret + so local signature verification matches the App configuration. 9. Writes files under `~/.braid`: - `registry.toml` — the instance registry (SSoT for `BRAID_INSTANCE` resolution). - - `instances//config.toml` (schema version 2) + - `instances//config.toml` (schema version 3) - `instances//github-app.pem` (mode `0600`) - `instances//secrets.toml` (mode `0600`) — webhook secret only - - `secrets/.toml` (mode `0600`) — provider API key, shared - across instances for the same provider - `instances//state/` directory for the SQLite database, backups, and worktrees. -Using per-instance secrets and a shared user-level provider key means multiple -Braid instances can run on the same machine without colliding on a single -environment variable. `BRAID_WEBHOOK_SECRET` is no longer required. +Using per-instance webhook secrets and explicit provider key files means +multiple Braid instances can run on the same machine without putting provider +credentials in their shell environments. Instances may share one provider key +file only when you intentionally reference the same file. +`BRAID_WEBHOOK_SECRET` is no longer required. After setup: 1. Install the App on your repository by visiting the printed install URL. -2. Initialize the instance database and run diagnostics. +2. Apply the initial database migrations, then run diagnostics: ```shell braid migrate apply --instance @@ -100,10 +165,10 @@ The tunnel receives GitHub webhooks and routes them to Braid's local ingress. ## Activating Braid on an Issue Braid activates through a **trusted `@braid` mention**: a visible `@braid` in -an issue comment from a repository MAINTAIN/ADMIN actor bypasses the Quiet -Window and event threshold. Braid acknowledges durable receipt with `eyes`. -See the [scheduling contract](../10-prd/scheduling.md) for provider acceptance -and terminal reactions. +an issue comment from a repository MAINTAIN/ADMIN actor wakes the Issue Agent +without waiting for the Quiet Window. Braid acknowledges the mention with an `eyes` +reaction. See the [scheduling contract](../10-prd/scheduling.md) for provider +acceptance and terminal reactions. Native Issue assignment is a GitHub-side *Agent App* provisioning (the same capability that makes Copilot assignable), not a permission an ordinary @@ -133,26 +198,78 @@ authenticate it before serving: CODEX_HOME=~/.braid/instances//provider/codex codex login ``` -`braid doctor` reports this as the "Codex credentials" check. The Pi provider -needs no home bootstrap: it authenticates with the API key persisted at setup. +`braid doctor` reports this as the "Codex credentials" check. Pi needs no +provider-home bootstrap: it authenticates with the explicit credential +declared by its provider entry (`api_key` or `oauth` file, or `none`). + +## Multiple repositories in one instance + +A setup-generated instance starts with one repository. One GitHub App and one +Braid instance may serve additional explicitly configured repositories when the +operational profile is intentionally shared, but Profiles, workspaces, Events, +worktrees, and writes remain repository-scoped. Braid does not build a shared +cross-repository Context or work graph. + +Add repository names under `additional_repositories`, then bind every GitHub +Profile to a repository and give it an explicit source checkout: + +```toml +[github] +repository = "owner/first" +additional_repositories = [{ name = "owner/second" }] +# ... App credentials and webhook settings + +[[profiles]] +id = "issue-first" +repository = "owner/first" +workspace = "/absolute/path/to/first-source" +# ... + +[[profiles]] +id = "issue-second" +repository = "owner/second" +workspace = "/absolute/path/to/second-source" +# ... +``` + +Profile ids remain unique within the instance. Install the same GitHub App on +every configured repository. Webhooks from other installed but unconfigured +repositories are rejected before scheduling. `braid gh pr ensure` requires +`--repository` in a multi-repository instance; generation-scoped worktrees are +kept under a repository-prefixed path. This release keeps the existing MVP +constraint that all Profiles use the same runtime adapter type; it does not yet +mix Codex and Pi repositories in one instance. ## Headless / manual App creation If you cannot or do not want to open a browser from the terminal, run: ```shell -braid setup owner/repository --no-browser +braid setup owner/repository --adapter pi --no-browser +``` + +Braid writes a pending setup draft under `~/.braid/setup-drafts/`, prints the +manifest form, and shows how to finish later. Open the HTML form from any +browser. GitHub redirects to the local callback URL; on a headless host that +page is expected to fail. Copy the complete URL, then run the same setup +options again with `--callback-url` instead of `--no-browser`: + +```shell +braid setup owner/repository --adapter pi --model --llm-provider \ + --callback-url '' ``` -This prints: +The callback state must match the pending draft, so a stale or cross-instance +redirect is rejected before the App manifest is converted. The completion path +requires no browser on the setup host. It prints: - A generated auto-submitting HTML form file; open it in any browser to POST the manifest to GitHub. - A `curl` command that performs the same POST. - The full manifest JSON for copy-paste creation. - The install URL for the repository. -- Instructions on how to persist the PEM, secrets file, and config so Braid - can run. +- Instructions for completing the instance with `--callback-url`, or for manual + recovery by writing the PEM, secrets file, and config yourself. GitHub expects the manifest as a `POST` form field named `manifest`; a plain query parameter will not pre-fill the form. The generated HTML file handles this @@ -165,4 +282,5 @@ automatically. - The generated App logo is saved as `~/.braid/instances//braid-of--logo.png`. - Secrets are split: the webhook secret lives in the instance - `secrets.toml`; the provider API key lives in `~/.braid/secrets/.toml`. Both are mode `0600`. + `secrets.toml`; any Pi provider credential lives in the explicit file + referenced by `llm_providers[].credential`. Both files should be mode `0600`. diff --git a/docs/user-manual/tunnel.md b/docs/user-manual/tunnel.md index e3324b56..53fb499a 100644 --- a/docs/user-manual/tunnel.md +++ b/docs/user-manual/tunnel.md @@ -25,9 +25,11 @@ Braid performs these steps automatically: 4. Appends `/webhook` to form the public webhook endpoint. 5. Sends a signed `ping` through that endpoint to verify it reaches Braid's ingress and passes signature verification. -6. Once reachable, updates the GitHub App's webhook URL to the public endpoint. -7. Runs the runtime normally. -8. On clean shutdown, restores the GitHub App's previous webhook URL. +6. Once reachable, updates the GitHub App's webhook URL to the public endpoint + and confirms it by reading the App configuration. +7. Local runtime and reconciliation can operate while the public endpoint recovers. +8. On clean shutdown, attempts to restore the previous webhook URL if the App + still points to this supervisor's published endpoint. ## No Cloudflare account required @@ -58,9 +60,7 @@ maps instance keys to their home directories, so `--instance` (or ## Troubleshooting -- Braid tries at most five tunnel candidates. Each candidate has up to 45 - seconds to publish its URL and register the connection. Braid then allows - time for DNS propagation before probing the public endpoint. If all - candidates fail, Braid reports the last error. +- If a tunnel candidate fails, Braid reports degraded public connectivity and + retries with backoff. Inspect the tunnel error in health or the supervisor logs. - `braid tunnel probe --instance --url ` can verify a specific URL manually, but normal `serve --tunnel` does this automatically. diff --git a/migrations/0003_turn_errors.sql b/migrations/0003_turn_errors.sql new file mode 100644 index 00000000..9bc5d2ed --- /dev/null +++ b/migrations/0003_turn_errors.sql @@ -0,0 +1,2 @@ +-- Preserve complete operational failure evidence before publishing a bounded summary. +ALTER TABLE turns ADD COLUMN error TEXT; diff --git a/migrations/0004_local_collaboration.sql b/migrations/0004_local_collaboration.sql new file mode 100644 index 00000000..cd675958 --- /dev/null +++ b/migrations/0004_local_collaboration.sql @@ -0,0 +1,76 @@ +CREATE TABLE local_items ( + number INTEGER PRIMARY KEY AUTOINCREMENT, + repository TEXT NOT NULL, + kind TEXT NOT NULL CHECK(kind IN ('issue','pr')), + title TEXT NOT NULL, + body TEXT NOT NULL, + author TEXT NOT NULL, + state TEXT NOT NULL DEFAULT 'open' CHECK(state IN ('open','closed')), + desired_profile TEXT, + head_ref TEXT, + base_ref TEXT, + head_commit TEXT, + base_commit TEXT, + revision INTEGER NOT NULL DEFAULT 1 CHECK(revision > 0), + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + CHECK((kind='issue' AND head_ref IS NULL AND base_ref IS NULL AND head_commit IS NULL AND base_commit IS NULL) + OR (kind='pr' AND head_ref IS NOT NULL AND base_ref IS NOT NULL AND head_commit IS NOT NULL AND base_commit IS NOT NULL)) +) STRICT; +CREATE INDEX local_items_repository ON local_items(repository,number); +CREATE TABLE local_comments ( + comment_id INTEGER PRIMARY KEY AUTOINCREMENT, + item_number INTEGER NOT NULL REFERENCES local_items(number), + author TEXT NOT NULL, + body TEXT NOT NULL, + created_at TEXT NOT NULL +) STRICT; +CREATE TABLE local_links ( + issue_number INTEGER NOT NULL REFERENCES local_items(number), + pr_number INTEGER NOT NULL REFERENCES local_items(number), + PRIMARY KEY(issue_number,pr_number) +) STRICT; +-- Replay uses the stable event ID as the existing ingress delivery GUID. +CREATE TABLE local_events ( + event_id INTEGER PRIMARY KEY AUTOINCREMENT, + item_number INTEGER NOT NULL REFERENCES local_items(number), + kind TEXT NOT NULL, + detail TEXT, + actor TEXT NOT NULL, + body TEXT, + revision INTEGER NOT NULL, + item_state TEXT NOT NULL, + created_at TEXT NOT NULL, + consumed_at TEXT +) STRICT; +CREATE INDEX local_events_pending ON local_events(event_id) WHERE consumed_at IS NULL; +CREATE TABLE local_space ( + singleton INTEGER PRIMARY KEY CHECK(singleton=1), + repository TEXT NOT NULL, + source TEXT +) STRICT; +ALTER TABLE local_comments ADD COLUMN operational INTEGER NOT NULL DEFAULT 0 CHECK(operational IN (0,1)); +ALTER TABLE local_events ADD COLUMN origin TEXT NOT NULL DEFAULT 'human'; +CREATE TABLE local_reactions ( + reaction_id INTEGER PRIMARY KEY AUTOINCREMENT, + comment_id INTEGER NOT NULL REFERENCES local_comments(comment_id), + content TEXT NOT NULL, + UNIQUE(comment_id,content) +) STRICT; +CREATE TABLE local_write_receipts ( + intent_id TEXT PRIMARY KEY, + database_id TEXT, + node_id TEXT +) STRICT; +CREATE TABLE local_merges ( + pr_number INTEGER PRIMARY KEY REFERENCES local_items(number), + expected_base TEXT NOT NULL, + expected_head TEXT NOT NULL, + merge_commit TEXT, + lifecycle TEXT NOT NULL CHECK(lifecycle IN ('prepared','applied','conflict','failed')), + error TEXT, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL +) STRICT; +ALTER TABLE local_items ADD COLUMN published INTEGER NOT NULL DEFAULT 0 CHECK(published IN (0,1)); +ALTER TABLE local_comments ADD COLUMN reply_to INTEGER REFERENCES local_comments(comment_id); diff --git a/migrations/0005_control_receipts.sql b/migrations/0005_control_receipts.sql new file mode 100644 index 00000000..b9c3d358 --- /dev/null +++ b/migrations/0005_control_receipts.sql @@ -0,0 +1,12 @@ +CREATE TABLE control_receipts ( + scope TEXT NOT NULL, + request_id TEXT NOT NULL, + payload_sha256 TEXT NOT NULL CHECK(length(payload_sha256)=64), + request_json TEXT NOT NULL, + state TEXT NOT NULL CHECK(state IN ('prepared','applied','rejected','blocked')), + response_json TEXT, + error TEXT, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + PRIMARY KEY(scope,request_id) +) STRICT; diff --git a/migrations/0006_builtin_harness.sql b/migrations/0006_builtin_harness.sql new file mode 100644 index 00000000..8160a35d --- /dev/null +++ b/migrations/0006_builtin_harness.sql @@ -0,0 +1,17 @@ +CREATE TABLE builtin_upstream ( + singleton INTEGER PRIMARY KEY CHECK(singleton=1), + space_id TEXT NOT NULL, + repository TEXT NOT NULL, + client_id TEXT NOT NULL, + cursor INTEGER NOT NULL DEFAULT 0 CHECK(cursor>=0) +); +CREATE TABLE builtin_writer_grants ( + session_id TEXT PRIMARY KEY, + item_number INTEGER NOT NULL, + actor TEXT NOT NULL, + request_id TEXT NOT NULL, + epoch INTEGER NOT NULL, + grant_id TEXT, + token TEXT, + lifecycle TEXT NOT NULL CHECK(lifecycle IN ('pending','active','revoked')) +); diff --git a/migrations/0007_harness_runs.sql b/migrations/0007_harness_runs.sql new file mode 100644 index 00000000..09535e92 --- /dev/null +++ b/migrations/0007_harness_runs.sql @@ -0,0 +1,5 @@ +CREATE TABLE harness_runs ( + run_id TEXT PRIMARY KEY NOT NULL, + request_json TEXT NOT NULL, + result_json TEXT NOT NULL +); diff --git a/migrations/0008_reconciliation_clock.sql b/migrations/0008_reconciliation_clock.sql new file mode 100644 index 00000000..5b3a24b4 --- /dev/null +++ b/migrations/0008_reconciliation_clock.sql @@ -0,0 +1,3 @@ +-- Full traversal success is independent of ordinary webhook/context observations. +ALTER TABLE work_items ADD COLUMN reconciled_at INTEGER; +ALTER TABLE work_items ADD COLUMN reconcile_attempted_at INTEGER; diff --git a/migrations/0009_durable_publication.sql b/migrations/0009_durable_publication.sql new file mode 100644 index 00000000..67f32e17 --- /dev/null +++ b/migrations/0009_durable_publication.sql @@ -0,0 +1,16 @@ +ALTER TABLE write_intents ADD COLUMN public_request_id TEXT; +ALTER TABLE write_intents ADD COLUMN source_binding TEXT; +UPDATE write_intents SET public_request_id='request-' || lower(hex(randomblob(16))) +WHERE request_key IS NOT NULL; +CREATE UNIQUE INDEX write_intents_public_request ON write_intents(public_request_id); +ALTER TABLE github_write_outbox ADD COLUMN claim_owner TEXT; +ALTER TABLE github_write_outbox ADD COLUMN claim_generation INTEGER; +-- Legacy CLI obligations join the same executor. Sending may already have mutated. +INSERT INTO github_write_outbox(intent_id,repository,target_kind,target_database_id, + operation,content,request_digest,remote_database_id,lifecycle,attempts,next_attempt_at, + last_error,created_at,updated_at) +SELECT intent_id,repository,'agent',target,'agent_write',payload, + lower(hex(randomblob(32))),remote_database_id, + CASE WHEN lifecycle='sending' THEN 'uncertain' ELSE lifecycle END, + attempts,updated_at,last_error,created_at,updated_at FROM write_intents +WHERE request_key IS NOT NULL AND lifecycle IN ('pending','sending','uncertain'); diff --git a/migrations/0010_pr_handoff.sql b/migrations/0010_pr_handoff.sql new file mode 100644 index 00000000..1307e507 --- /dev/null +++ b/migrations/0010_pr_handoff.sql @@ -0,0 +1,6 @@ +-- First acceptance freezes the existing target generation, never an activation. +CREATE TABLE pr_handoffs ( + intent_id TEXT PRIMARY KEY REFERENCES write_intents(intent_id), + target_assignment_id TEXT NOT NULL REFERENCES assignments(assignment_id), + event_id TEXT UNIQUE REFERENCES events(event_id) +) STRICT; diff --git a/migrations/0011_collaboration_inputs.sql b/migrations/0011_collaboration_inputs.sql new file mode 100644 index 00000000..58a0eae5 --- /dev/null +++ b/migrations/0011_collaboration_inputs.sql @@ -0,0 +1,58 @@ +-- A projection read is not an acknowledgement of responsibility input. +-- Only a complete observation and its classified events advance this frontier. +CREATE TABLE processed_objects ( + work_item_node_id TEXT NOT NULL REFERENCES work_items(node_id), + node_id TEXT NOT NULL, + database_id TEXT, + object_kind TEXT NOT NULL, + version TEXT NOT NULL, + digest TEXT NOT NULL CHECK (length(digest)=64), + lifecycle TEXT NOT NULL, + author_node_id TEXT, + author_login TEXT, + metadata_digest TEXT CHECK(metadata_digest IS NULL OR length(metadata_digest)=64), + PRIMARY KEY(work_item_node_id,node_id) +) STRICT; + +-- Establish a new observation epoch from retained current state. This does not +-- claim that historically missing inputs have been executed; old gaps require +-- explicit operator recovery, never automatic activation of a real task. +INSERT INTO processed_objects +SELECT c.work_item_node_id,c.node_id,c.database_id,c.object_kind,c.version,c.digest, + CASE WHEN c.object_kind IN ('issue','pr') THEN lower(w.state) ELSE c.lifecycle END, + c.author_node_id,c.author_login,NULL FROM canonical_objects c JOIN work_items w ON w.node_id=c.work_item_node_id; + +-- Invalidation and an obligation to consider a change are orthogonal. +ALTER TABLE events ADD COLUMN requires_attention INTEGER NOT NULL DEFAULT 0 + CHECK (requires_attention IN (0,1)); +UPDATE events SET requires_attention=1 +WHERE kind IN ('wake','mention','assign'); + +CREATE INDEX events_object_version ON events(object_node_id,object_version) + WHERE object_version IS NOT NULL; + +-- A second transport observation can reuse a real existing event. Keep the +-- binding explicit instead of silently succeeding after INSERT OR IGNORE. +ALTER TABLE deliveries ADD COLUMN effect_event_id TEXT REFERENCES events(event_id); +UPDATE deliveries SET effect_event_id=(SELECT e.event_id FROM events e + WHERE e.delivery_guid=deliveries.delivery_guid ORDER BY e.rowid LIMIT 1); + +ALTER TABLE wake_batches ADD COLUMN input_error TEXT; + +ALTER TABLE implementation_requests ADD COLUMN activation_event_id TEXT REFERENCES events(event_id); +UPDATE implementation_requests SET activation_event_id=( + SELECT e.event_id FROM events e JOIN deliveries d ON d.delivery_guid=e.delivery_guid + WHERE e.work_item_node_id=implementation_requests.pull_request_node_id + AND e.kind='assign' AND e.detail='pr_ensure' + AND d.delivery_guid='braid-pr-ensure-' || implementation_requests.repository || '-' || implementation_requests.comment_database_id +); + +-- Exact version/content evidence of an Agent edit. The original author or a +-- human-visible attribution block cannot prove who made a later revision. +CREATE TABLE publication_versions ( + node_id TEXT NOT NULL, + version TEXT NOT NULL, + digest TEXT NOT NULL CHECK (length(digest)=64), + intent_id TEXT NOT NULL REFERENCES write_intents(intent_id), + PRIMARY KEY(node_id,version,digest) +) STRICT; diff --git a/migrations/0012_implementation_delivery.sql b/migrations/0012_implementation_delivery.sql new file mode 100644 index 00000000..b4549ec3 --- /dev/null +++ b/migrations/0012_implementation_delivery.sql @@ -0,0 +1,34 @@ +-- A later comment may refer to a published managed implementation without +-- creating another PR. The original immutable request remains its identity. +ALTER TABLE implementation_requests ADD COLUMN root_intent_id TEXT + REFERENCES implementation_requests(intent_id); +CREATE INDEX implementation_requests_managed_head +ON implementation_requests(repository,head_ref,issue_node_id,base_ref,pr_profile_id); + +-- Legacy false success is an unfinished, already-authorized delivery obligation. +-- Reuse the one outbox; execution revalidates the exact published PR/association +-- and refuses to replace any blocked/sleeping/retired assignment generation. +UPDATE write_intents SET lifecycle='pending',updated_at=strftime('%Y-%m-%dT%H:%M:%fZ','now'), + last_error='published implementation still owes activation delivery' +WHERE operation='pr_ensure' AND lifecycle='applied' AND intent_id IN ( + SELECT intent_id FROM implementation_requests + WHERE activation_event_id IS NULL AND stage='activation_pending' + AND pull_request_node_id IS NOT NULL AND pull_request_number IS NOT NULL +); +INSERT OR IGNORE INTO github_write_outbox(intent_id,repository,target_kind,target_database_id, + operation,content,request_digest,lifecycle,next_attempt_at,created_at,updated_at) +SELECT intent_id,repository,'agent',target,'agent_write',payload,lower(hex(randomblob(32))), + 'pending',updated_at,created_at,updated_at FROM write_intents +WHERE operation='pr_ensure' AND lifecycle='pending' AND intent_id IN ( + SELECT intent_id FROM implementation_requests WHERE activation_event_id IS NULL + AND stage='activation_pending' AND pull_request_node_id IS NOT NULL +); +UPDATE github_write_outbox SET lifecycle='pending', + next_attempt_at=strftime('%Y-%m-%dT%H:%M:%fZ','now'), + updated_at=strftime('%Y-%m-%dT%H:%M:%fZ','now'), + last_error='published implementation still owes activation delivery' +WHERE lifecycle='applied' AND intent_id IN ( + SELECT w.intent_id FROM write_intents w JOIN implementation_requests i ON i.intent_id=w.intent_id + WHERE w.operation='pr_ensure' AND w.lifecycle='pending' AND i.activation_event_id IS NULL + AND i.stage='activation_pending' AND i.pull_request_node_id IS NOT NULL AND i.pull_request_number IS NOT NULL +); diff --git a/migrations/0013_operational_status_convergence.sql b/migrations/0013_operational_status_convergence.sql new file mode 100644 index 00000000..903e1a1f --- /dev/null +++ b/migrations/0013_operational_status_convergence.sql @@ -0,0 +1,20 @@ +-- Status remains one stable comment per work item/Profile/generation. +-- The outbox mapping survives replacement of a desired publication while an +-- older create is in flight, so its remote identity is never orphaned. +ALTER TABLE status_comments ADD COLUMN projection_kind TEXT NOT NULL DEFAULT 'failure' + CHECK (projection_kind IN ('failure','recovered','superseded')); +ALTER TABLE status_comments ADD COLUMN failure_body TEXT; +ALTER TABLE status_comments ADD COLUMN failure_recorded_at TEXT; +ALTER TABLE status_comments ADD COLUMN successor_generation INTEGER; +UPDATE status_comments SET + failure_body=(SELECT content FROM github_write_outbox o WHERE o.intent_id=status_comments.write_intent_id), + failure_recorded_at=COALESCE((SELECT created_at FROM github_write_outbox o WHERE o.intent_id=status_comments.write_intent_id),updated_at); +ALTER TABLE github_write_outbox ADD COLUMN status_work_item_node_id TEXT; +ALTER TABLE github_write_outbox ADD COLUMN status_profile_id TEXT; +ALTER TABLE github_write_outbox ADD COLUMN status_generation INTEGER; +UPDATE github_write_outbox SET + status_work_item_node_id=(SELECT work_item_node_id FROM status_comments s WHERE s.write_intent_id=github_write_outbox.intent_id), + status_profile_id=(SELECT profile_id FROM status_comments s WHERE s.write_intent_id=github_write_outbox.intent_id), + status_generation=(SELECT assignment_generation FROM status_comments s WHERE s.write_intent_id=github_write_outbox.intent_id) +WHERE EXISTS(SELECT 1 FROM status_comments s WHERE s.write_intent_id=github_write_outbox.intent_id); +CREATE INDEX outbox_status_publications ON github_write_outbox(status_work_item_node_id,status_profile_id,status_generation,lifecycle); diff --git a/migrations/0014_replay_batch_membership.sql b/migrations/0014_replay_batch_membership.sql new file mode 100644 index 00000000..91553dc2 --- /dev/null +++ b/migrations/0014_replay_batch_membership.sql @@ -0,0 +1,14 @@ +-- An uncertain turn retains its original input evidence while a later batch +-- re-delivers those same events after the old execution is confirmed stopped. +CREATE TABLE wake_batch_events_v14 ( + batch_id TEXT NOT NULL REFERENCES wake_batches(batch_id), + event_id TEXT NOT NULL REFERENCES events(event_id), + ordinal INTEGER NOT NULL CHECK (ordinal >= 0), + PRIMARY KEY (batch_id, ordinal), + UNIQUE (batch_id, event_id) +) STRICT; +INSERT INTO wake_batch_events_v14(batch_id,event_id,ordinal) +SELECT batch_id,event_id,ordinal FROM wake_batch_events; +DROP TABLE wake_batch_events; +ALTER TABLE wake_batch_events_v14 RENAME TO wake_batch_events; +CREATE INDEX wake_batch_events_event ON wake_batch_events(event_id); diff --git a/migrations/0015_provider_stop_evidence.sql b/migrations/0015_provider_stop_evidence.sql new file mode 100644 index 00000000..79f90ac8 --- /dev/null +++ b/migrations/0015_provider_stop_evidence.sql @@ -0,0 +1,3 @@ +-- Only a confirmed native close may record a stop. Inherited session state +-- does not prove execution stopped, including idle and reset_pending. +ALTER TABLE provider_sessions ADD COLUMN execution_stopped_at TEXT; diff --git a/migrations/0016_builtin_writer_admission.sql b/migrations/0016_builtin_writer_admission.sql new file mode 100644 index 00000000..ac2110fe --- /dev/null +++ b/migrations/0016_builtin_writer_admission.sql @@ -0,0 +1,5 @@ +-- A native turn can run before a writer grant is requested. +-- Legacy turns have no recorded authority snapshot and cannot mint a new grant. +ALTER TABLE turns ADD COLUMN builtin_writer_cursor INTEGER CHECK (builtin_writer_cursor >= 0); +ALTER TABLE builtin_writer_grants ADD COLUMN authority_cursor INTEGER CHECK (authority_cursor >= 0); +ALTER TABLE builtin_writer_grants ADD COLUMN revoking INTEGER NOT NULL DEFAULT 0 CHECK (revoking IN (0, 1)); diff --git a/migrations/0017_builtin_execution_fences.sql b/migrations/0017_builtin_execution_fences.sql new file mode 100644 index 00000000..2c266fb3 --- /dev/null +++ b/migrations/0017_builtin_execution_fences.sql @@ -0,0 +1,8 @@ +ALTER TABLE provider_sessions ADD COLUMN builtin_execution_id TEXT; +ALTER TABLE provider_sessions ADD COLUMN builtin_execution_owner TEXT; +ALTER TABLE provider_sessions ADD COLUMN builtin_execution_state TEXT NOT NULL DEFAULT 'open' + CHECK (builtin_execution_state IN ('open','fencing','fenced')); +CREATE UNIQUE INDEX provider_builtin_execution ON provider_sessions(builtin_execution_id) + WHERE builtin_execution_id IS NOT NULL; +ALTER TABLE turns ADD COLUMN builtin_execution_id TEXT; +ALTER TABLE builtin_writer_grants ADD COLUMN execution_id TEXT; diff --git a/migrations/0018_operational_comment_roles.sql b/migrations/0018_operational_comment_roles.sql new file mode 100644 index 00000000..38271709 --- /dev/null +++ b/migrations/0018_operational_comment_roles.sql @@ -0,0 +1,53 @@ +CREATE TABLE operational_comment_roles ( + role_id TEXT PRIMARY KEY CHECK (length(role_id) = 32), + work_item_node_id TEXT NOT NULL REFERENCES work_items(node_id), + profile_id TEXT NOT NULL, + assignment_generation INTEGER NOT NULL CHECK (assignment_generation > 0), + comment_node_id TEXT UNIQUE, + ambiguous INTEGER NOT NULL DEFAULT 0 CHECK (ambiguous IN (0, 1)), + UNIQUE (work_item_node_id, profile_id, assignment_generation) +) STRICT; + +CREATE TABLE operational_comment_role_bodies ( + role_id TEXT NOT NULL REFERENCES operational_comment_roles(role_id), + body_digest TEXT NOT NULL CHECK (length(body_digest) = 64), + PRIMARY KEY (role_id, body_digest) +) STRICT; + +CREATE TABLE legacy_operational_comment_bodies ( + role_id TEXT NOT NULL REFERENCES operational_comment_roles(role_id), + body TEXT NOT NULL, + not_before TEXT NOT NULL, + PRIMARY KEY (role_id, body, not_before) +) STRICT; + +-- Preserve exact historical identities and recorded multiple-match uncertainty. +INSERT INTO operational_comment_roles + (role_id, work_item_node_id, profile_id, assignment_generation, comment_node_id, ambiguous) +SELECT lower(hex(randomblob(16))), s.work_item_node_id, s.profile_id, s.assignment_generation, + s.remote_comment_node_id, s.remote_comment_node_id IS NULL AND EXISTS ( + SELECT 1 FROM github_write_outbox o + WHERE o.status_work_item_node_id=s.work_item_node_id + AND o.status_profile_id=s.profile_id AND o.status_generation=s.assignment_generation + AND o.operation='comment_create' AND o.lifecycle='ambiguous') +FROM status_comments s; + +-- A pending request with zero attempts has never crossed the network boundary. +UPDATE github_write_outbox AS o +SET content=o.content || char(10,10) || '' +WHERE o.status_work_item_node_id IS NOT NULL + AND o.operation IN ('comment_create','comment_update') + AND o.lifecycle='pending' AND o.attempts=0; + +-- Save the recovery evidence independently of future publisher activity. +INSERT OR IGNORE INTO legacy_operational_comment_bodies (role_id, body, not_before) +SELECT r.role_id, o.content, o.created_at +FROM github_write_outbox o JOIN operational_comment_roles r + ON r.work_item_node_id=o.status_work_item_node_id + AND r.profile_id=o.status_profile_id AND r.assignment_generation=o.status_generation +WHERE r.comment_node_id IS NULL AND r.ambiguous=0 + AND o.operation='comment_create' AND o.lifecycle IN ('pending','sending','uncertain','applied'); diff --git a/migrations/0019_handoff_inputs.sql b/migrations/0019_handoff_inputs.sql new file mode 100644 index 00000000..4a470833 --- /dev/null +++ b/migrations/0019_handoff_inputs.sql @@ -0,0 +1,41 @@ +-- The accepted input carries all facts needed by the scheduler and Context. +ALTER TABLE events ADD COLUMN next_turn_only INTEGER NOT NULL DEFAULT 0 + CHECK (next_turn_only IN (0,1)); +UPDATE events SET next_turn_only=1 WHERE kind='wake' AND detail='pr_handoff'; + +CREATE TABLE handoff_inputs ( + event_id TEXT PRIMARY KEY REFERENCES events(event_id), + source_repository TEXT NOT NULL CHECK (length(source_repository)>0), + source_number INTEGER NOT NULL CHECK (source_number>0), + target_assignment_id TEXT NOT NULL REFERENCES assignments(assignment_id), + target_generation INTEGER NOT NULL CHECK (target_generation>0) +) STRICT; + +-- An old Wake without recoverable evidence remains next-turn-only and is +-- retired by the input consumer before any provider delivery. +INSERT INTO handoff_inputs +SELECT e.event_id,w.repository,source_item.number,target.assignment_id,target.generation +FROM events e +JOIN pr_handoffs h ON h.event_id=e.event_id +JOIN write_intents w ON w.intent_id=h.intent_id AND w.operation='pr_handoff' +JOIN assignments target + ON target.assignment_id=h.target_assignment_id AND target.work_item_node_id=e.work_item_node_id +JOIN work_items target_item ON target_item.node_id=target.work_item_node_id AND target_item.kind='pr' +JOIN assignments source ON source.assignment_id=CASE WHEN json_valid(w.source_binding) + THEN json_extract(w.source_binding,'$.assignment_id') END +JOIN work_items source_item ON source_item.node_id=source.work_item_node_id + AND source_item.kind='issue' AND source_item.repository_node_id=target_item.repository_node_id +WHERE e.next_turn_only=1 AND length(w.repository)>0; + +-- Before delivery the request owns the reserved target. After delivery the +-- receipt retains a reference to the accepted event. +CREATE TABLE pr_handoffs_v19 ( + intent_id TEXT PRIMARY KEY REFERENCES write_intents(intent_id), + target_assignment_id TEXT REFERENCES assignments(assignment_id), + event_id TEXT UNIQUE REFERENCES events(event_id), + CHECK ((target_assignment_id IS NULL) <> (event_id IS NULL)) +) STRICT; +INSERT INTO pr_handoffs_v19 +SELECT intent_id,CASE WHEN event_id IS NULL THEN target_assignment_id END,event_id FROM pr_handoffs; +DROP TABLE pr_handoffs; +ALTER TABLE pr_handoffs_v19 RENAME TO pr_handoffs; diff --git a/migrations/0020_github_reaction_feedback.sql b/migrations/0020_github_reaction_feedback.sql new file mode 100644 index 00000000..35b545e2 --- /dev/null +++ b/migrations/0020_github_reaction_feedback.sql @@ -0,0 +1,29 @@ +CREATE TABLE github_reaction_feedback ( + sequence INTEGER PRIMARY KEY, + event_id TEXT UNIQUE REFERENCES events(event_id), + turn_id TEXT REFERENCES turns(turn_id), + repository TEXT NOT NULL, + target_kind TEXT NOT NULL, + target_database_id TEXT NOT NULL, + content TEXT NOT NULL CHECK (content IN ('eyes','rocket','+1','confused','clear_rocket')), + created_at TEXT NOT NULL, + projected INTEGER NOT NULL DEFAULT 0 CHECK (projected IN (0,1)), + publication_intent_id TEXT UNIQUE, + UNIQUE (turn_id, content), + CHECK ((event_id IS NOT NULL AND turn_id IS NULL AND content='eyes') + OR (event_id IS NULL AND turn_id IS NOT NULL AND content!='eyes')) +) STRICT; + +CREATE INDEX github_reaction_feedback_unprojected ON github_reaction_feedback(sequence) +WHERE projected=0; + +CREATE INDEX github_reaction_feedback_clear ON github_reaction_feedback +(repository, target_kind, target_database_id, sequence) +WHERE content IN ('clear_rocket','+1','confused'); + +-- Existing writes keep their attempts and receipts. Copy their accepted event targets. +INSERT INTO github_reaction_feedback + (event_id,repository,target_kind,target_database_id,content,created_at,projected,publication_intent_id) +SELECT event_id,repository,target_kind,target_database_id,content,created_at,1,intent_id +FROM github_write_outbox +WHERE event_id IS NOT NULL AND operation='reaction_add' AND content='eyes'; diff --git a/migrations/0021_observed_root_fields.sql b/migrations/0021_observed_root_fields.sql new file mode 100644 index 00000000..54a5263f --- /dev/null +++ b/migrations/0021_observed_root_fields.sql @@ -0,0 +1,6 @@ +-- A complete canonical observation owns the title/body comparison frontier. +-- Legacy rows carry only the combined projection. The next complete snapshot +-- establishes the field baseline without inferring authorship from receipts. +ALTER TABLE processed_objects ADD COLUMN title_digest TEXT CHECK (length(title_digest)=64); +ALTER TABLE processed_objects ADD COLUMN body_digest TEXT CHECK (length(body_digest)=64); +ALTER TABLE processed_objects ADD COLUMN title_event_id TEXT; diff --git a/migrations/0022_operational_status_facts.sql b/migrations/0022_operational_status_facts.sql new file mode 100644 index 00000000..a01173dd --- /dev/null +++ b/migrations/0022_operational_status_facts.sql @@ -0,0 +1,5 @@ +CREATE TABLE operational_status_facts ( + assignment_id TEXT PRIMARY KEY REFERENCES assignments(assignment_id), + body TEXT NOT NULL, + observed_at TEXT NOT NULL +) STRICT; diff --git a/native/pi/README.md b/native/pi/README.md new file mode 100644 index 00000000..fb7d12ad --- /dev/null +++ b/native/pi/README.md @@ -0,0 +1,83 @@ +# Braid 的 Pi 原生材料 + +本目录提供独立 Braid 的锁定 Pi 1.1.0 材料。插件按安装时的明确选择安装和启用, +不读取系统全局 Pi 扩展;CLI 和 RPC 使用同一入口。共同生命周期与停止合同归 +[provider 技术说明](../../docs/20-product-tdd/app-server.md)。 + +`pi.mjs` 准备隔离环境与显式材料;`sdk-host.mjs` 使用 Pi 根包公开导出的 SDK +构造会话、资源和工具,复用公开的 RPC/print 实现;`rpc-adapter.mjs` 增加 Braid +停止、服务交接和实际运行身份。Braid 不再修改 Pi CLI/RPC bundle、会话生命周期、 +资源加载器和 Bash 实现来注入这些策略。 +受管入口支持 Braid 使用的 RPC,以及子 Agent 使用的 JSON/text print、文本任务 +文件和图片附件。它不是完整交互式 Pi CLI;未实现的原生 CLI 选项明确报错, +不能忽略选项后开始另一种模型操作。 + +在有 Node、npm、curl 与 tar 的开发宿主安装到新的绝对目录。不要覆盖正在使用的安装, +保留旧版本和执行回执。Mac 本项目的目录必须位于 WorkSSD。 + +```sh +node native/pi/install.mjs /Volumes/WorkSSD/Development/braid-runtime/pi-1.1.0 \ + --plugins subagents,background +/Volumes/WorkSSD/Development/braid-runtime/pi-1.1.0/pi --version +``` + +安装使用同一份锁定依赖图,以 npm workspace 选择基础 SDK 和指定插件, +仅应用基础补丁与所选插件补丁。未选择的插件不安装、不修改;插件之间不隐含绑定, +例如 background 可单独选择。安装下载 Node 官方 24.15.0 对应平台发行包, +核对内置 archive SHA-256 后交付独立的 `bin/node`、许可证、`pi` 入口和 +`runtime-manifest.json`。支持 macOS/Linux 的 arm64 与 x64;manifest 保留发行身份 +和实际文件哈希。安装器不复制可能依赖 Homebrew 动态库的宿主 Node。 +安装目录中的缓存和临时目录也位于该目录;安装时会实际启动交付的 Node, +Pi 的实际能力仍须通过 doctor 与运行核实。 +可选插件名称为 subagents、background、context7、fff、mcporter;默认不启用插件。 +FFF 使用平台原生依赖,安装失败应保留原始错误,不降级为不可用的工具。 + +基础发行保留两类小范围上游补丁:`compaction.thresholdTokens` 提供提前压缩触发点, +计算为它与真实模型容量减 reserve 的较小值,不伪造模型容量或改变总结预算; +pi-ai 的连接重置错误分类保留已观察到的 `connection reset by peer` 重试行为。 +对应的公开设置或错误分类被上游提供并取得实际反馈后,再退役这些补丁。 +subagents、background、Context7 和 MCPorter 的局部补丁仅随相应插件安装, +仍包含尚无公开接线点的插件内部修复及 owned process/service 登记。 +它们不是无补丁上游发行,不应删掉停止或交接能力来换取零补丁。 + +对全新安装仅选择 `background` 后,可直接验证交付的 Node、Pi SDK 与扩展、工具环境和停止回执。 +下面的验收使用临时 HOME、离线模型描述和本地 Bash,不需要模型账号。它也会检查新建 +session 文件和结束 RPC 输入后的进程退出。Rust 工厂用例在绑定失败时核对执行目录的离线停止回执。 +另一个用例通过 SDK 调用所选插件的 Bash 工具,检查命令退出 0 时仍能报告归属未确认。 + +```sh +node native/pi/install.mjs "$PWD/runtime/pi-background" --plugins background +export BRAID_TEST_PI_INSTALL="$PWD/runtime/pi-background" +"$BRAID_TEST_PI_INSTALL/bin/node" --test native/pi/acceptance/installed-runtime.test.mjs +PI_OFFLINE=1 agent-build cargo test --locked --bin braid failed_home_binding_stops_the_installed_execution_before_returning -- --ignored +``` + +锁定的 pi-subagents 0.56.0 对自定义角色 frontmatter 使用字符串列表解析, +`fallbackModels: []` 和 `fallbackModels: false` 都会成为模型名称,不能用于禁用回退。 +只有主模型时省略该字段;需要限制模型范围时配置插件的 modelScope,并通过实际 +角色读取核对候选,随后从根与子会话的调用记录确认真正使用的模型。 + +将实例的 `[[runtimes]]` 中 `executable` 设为安装的 `pi`, +`native_runtime` 设为同目录的 `runtime-manifest.json`。`braid setup` 对明确指定 +的原生入口识别相邻 manifest;`braid doctor` 核对材料身份,实际会话启动再核对 +运行能力。缺失或漂移不能通过系统全局 Pi 回退隐藏。 + +受控 Bash 工具与 background 插件使用非登录 shell,并从原生入口移除 `BASH_ENV` 和 `ENV`。 +工具消费实例提供的 PATH、HOME、临时及缓存目录,不依赖宿主登录 profile 注入 alias、函数或路径; +所需工具须在运行配方中明确准备。模型显式执行的命令仍保持原意,包括主动调用登录 shell 或 source 脚本。 + +选择 MCPorter 时,执行目录的 Unix socket 路径必须满足系统长度限制。路径过长时 +明确设置 `BRAID_NATIVE_SOCKET_ROOT` 为同文件系统上足够短的私有绝对目录, +例如 WorkSSD 上的短目录;不能默认改写到 `/tmp`。未选择 MCPorter 时不要求此项。 + +Braid 为每个物理执行分配独立目录;关闭后的记录仍保留。人工处置遗留执行前, +先确认对应的安装、execution ID 和目录,再用该安装的固定 Node 调用: + +```sh +/bin/node /managed.mjs cleanup \ + --execution-dir --execution-id +``` + +回执中的 unknown 表示不能证明归属或停止;父进程退出不能替代后代清理证明。 +操作不能撤销已经发出的网络请求,也不是同账户进程的安全沙箱。较晚 cleanup 成功只证明 +回执时点的执行收口,不能改写此前 deadline 内停止未知的运行结果。 diff --git a/native/pi/acceptance/installed-runtime.test.mjs b/native/pi/acceptance/installed-runtime.test.mjs new file mode 100644 index 00000000..581b8092 --- /dev/null +++ b/native/pi/acceptance/installed-runtime.test.mjs @@ -0,0 +1,116 @@ +import assert from 'node:assert/strict'; +import { execFileSync, spawn } from 'node:child_process'; +import { randomUUID } from 'node:crypto'; +import { once } from 'node:events'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import readline from 'node:readline'; +import test from 'node:test'; +import { pathToFileURL } from 'node:url'; + +// Install once with --plugins background, then run against that candidate. +// This is a distribution test; the regular source tests need no npm install. +test('installed background-only Pi opens a fresh session, serves tools and closes the execution', async t => { + const candidate = process.env.BRAID_TEST_PI_INSTALL; + assert.ok(candidate && path.isAbsolute(candidate), 'set BRAID_TEST_PI_INSTALL to an absolute background-only installation'); + const install = fs.realpathSync(candidate); + const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'braid-pi-smoke-'))); + t.after(() => fs.rmSync(root, { recursive: true, force: true })); + const agentDir = path.join(root, 'pi-home'); + fs.mkdirSync(agentDir); + fs.writeFileSync(path.join(agentDir, 'models.json'), JSON.stringify({ + providers: { fixture: { baseUrl: 'http://127.0.0.1:1/v1', api: 'openai-completions', models: [{ id: 'offline' }] } }, + })); + const id = randomUUID(); + const start = randomUUID(); + const directory = path.join(root, 'execution'); + const session = path.join(root, 'fresh.jsonl'); + const env = { + PATH: '/usr/bin:/bin', HOME: root, PI_OFFLINE: '1', PI_CODING_AGENT_DIR: agentDir, + XDG_CONFIG_HOME: path.join(root, 'operator-config'), + BRAID_NATIVE_EXECUTION_DIR: directory, BRAID_NATIVE_EXECUTION_ID: id, BRAID_NATIVE_LAUNCH_START_ID: start, + }; + const pi = path.join(install, 'pi'); + const node = path.join(install, 'bin/node'); + const packageConfig = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')); + const expectedVersion = packageConfig.dependencies['@earendil-works/pi-coding-agent']; + assert.equal(execFileSync(pi, ['--version'], { cwd: root, env, encoding: 'utf8', timeout: 30000 }).trim(), expectedVersion); + const child = spawn(node, [ + path.join(install, 'process-owner.mjs'), 'launch', '--start-id', start, '--kind', 'root', '--', + pi, '--mode', 'rpc', '--session', session, '--provider', 'fixture', '--model', 'offline', + ], { cwd: root, env, detached: true, timeout: 30000 }); + const closed = once(child, 'close'); + let stderr = ''; + child.stderr.setEncoding('utf8').on('data', text => { stderr += text; }); + const responses = readline.createInterface({ input: child.stdout })[Symbol.asyncIterator](); + const request = async (type, fields = {}) => { + child.stdin.write(JSON.stringify({ id: type, type, ...fields }) + '\n'); + for (;;) { + const line = await responses.next(); + assert.equal(line.done, false, `Pi exited before ${type}: ${stderr}`); + const reply = JSON.parse(line.value); + if (reply.type !== 'response') continue; + assert.equal(reply.id, type); + assert.equal(reply.command, type); + assert.equal(reply.success, true, JSON.stringify(reply)); + return reply.data; + } + }; + try { + const state = await request('get_state'); + assert.equal(state.sessionFile, session); + assert.equal(state.model.provider, 'fixture'); + assert.equal(state.model.id, 'offline'); + assert.equal(state.managed_state.status, 'quiescent'); + assert.deepEqual(state.braid_native_runtime.extensions, [ + path.join(install, 'node_modules/pi-background-bash/extensions/background-bash.ts'), + ]); + const bash = await request('bash', { command: 'printf "%s\n%s" "$GH_CONFIG_DIR" "$XDG_CONFIG_HOME"', excludeFromContext: true }); + assert.equal(bash.exitCode, 0, JSON.stringify(bash)); + assert.equal(bash.output, [path.join(root, 'operator-config/gh'), path.join(directory, 'config')].join('\n')); + const handoff = await request('yield_stoppable_services'); + assert.equal(handoff.managed_state.status, 'quiescent'); + assert.equal(handoff.managed_state.execution_id, id); + const receipt = await request('stop_owned_execution'); + assert.equal(receipt.status, 'stopped', JSON.stringify(receipt)); + assert.equal(receipt.execution_id, id); + assert.equal(receipt.scope, 'root-descendants'); + } finally { + child.stdin.end(); + const [code, signal] = await closed; + assert.equal(signal, null, stderr); + assert.equal(code, 0, stderr); + } +}); + +test('installed background bash reports an unverified stop even when the command exits zero', async t => { + const install = fs.realpathSync(process.env.BRAID_TEST_PI_INSTALL); + const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'braid-pi-tool-'))); + t.after(() => fs.rmSync(root, { recursive: true, force: true })); + const directory = path.join(root, 'execution'); + const id = randomUUID(); + t.mock.property(process, 'env', { + HOME: root, PATH: '/usr/bin:/bin', PI_OFFLINE: '1', + BRAID_NATIVE_EXECUTION_ID: id, BRAID_NATIVE_EXECUTION_DIR: directory, + }); + await import(pathToFileURL(path.join(install, 'managed.mjs'))); + const sdk = await import(pathToFileURL(path.join(install, 'node_modules/@earendil-works/pi-coding-agent/dist/index.js'))); + const plugin = path.join(install, 'node_modules/pi-background-bash/extensions/background-bash.ts'); + const { extensions, errors } = await sdk.discoverAndLoadExtensions([plugin], root, root); + assert.deepEqual(errors, []); + const bash = extensions.find(extension => extension.tools.has('bash')).tools.get('bash').definition; + const invoke = () => bash.execute('foreground', { command: 'printf completed' }, undefined, undefined, { cwd: root }); + const result = await invoke(); + assert.deepEqual(result.content, [{ type: 'text', text: 'completed' }]); + + // A damaged registration prevents proving scope even after this new command exits. + fs.writeFileSync(path.join(directory, 'processes/damaged.json'), '{}'); + await assert.rejects(invoke, /Managed bash cleanup is unknown: Invalid native ownership record: damaged\.json/); + const terminal = fs.readdirSync(path.join(directory, 'terminals')) + .map(file => JSON.parse(fs.readFileSync(path.join(directory, 'terminals', file), 'utf8'))) + .find(record => record.terminal.status === 'unknown'); + assert.equal(terminal.execution_id, id); + assert.equal(terminal.close.exit_code, 0); + assert.match(terminal.terminal.reason, /Invalid native ownership record: damaged\.json/); +}); diff --git a/native/pi/install.mjs b/native/pi/install.mjs new file mode 100644 index 00000000..4d209f6f --- /dev/null +++ b/native/pi/install.mjs @@ -0,0 +1,117 @@ +#!/usr/bin/env node +import fs from 'node:fs'; +import path from 'node:path'; +import crypto from 'node:crypto'; +import { execFileSync } from 'node:child_process'; +import { fileURLToPath } from 'node:url'; + +const nodeVersion = '24.15.0'; +const nodeDistributions = { + 'darwin-arm64': ['tar.gz', '372331b969779ab5d15b949884fc6eaf88d5afe87bde8ba881d6400b9100ffc4'], + 'darwin-x64': ['tar.gz', 'ffd5ee293467927f3ee731a553eb88fd1f48cf74eebc2d74a6babe4af228673b'], + 'linux-arm64': ['tar.xz', 'f3d5a797b5d210ce8e2cb265544c8e482eaedcb8aa409a8b46da7e8595d0dda0'], + 'linux-x64': ['tar.xz', '472655581fb851559730c48763e0c9d3bc25975c59d518003fc0849d3e4ba0f6'], +}; +const nodePlatform = `${process.platform}-${process.arch}`; +const nodeDistribution = nodeDistributions[nodePlatform]; +if (!nodeDistribution) throw new Error(`No locked Node distribution for ${nodePlatform}.`); + +const source = path.dirname(fileURLToPath(import.meta.url)); +const args = process.argv.slice(2); +const destination = args.shift(); +if (!destination || (args.length && (args.length !== 2 || args[0] !== '--plugins'))) { + throw new Error('Usage: node install.mjs ABSOLUTE_INSTALL_DIRECTORY [--plugins subagents,background,context7,fff,mcporter]'); +} +if (!path.isAbsolute(destination)) throw new Error('Install directory must be absolute.'); +const selected = args.length ? args[1].split(',').filter(Boolean) : []; +const catalog = { + subagents: { extension_paths: ['node_modules/pi-subagents/index.ts'], skill_paths: ['node_modules/pi-subagents/skills'] }, + background: { extension_paths: ['node_modules/pi-background-bash/extensions/background-bash.ts'], skill_paths: ['node_modules/pi-background-bash/skills'] }, + context7: { extension_paths: ['node_modules/@upstash/context7-pi/extensions/context7.ts'], skill_paths: ['node_modules/@upstash/context7-pi/skills'] }, + fff: { extension_paths: ['node_modules/@ff-labs/pi-fff/src/index.ts'], skill_paths: [] }, + mcporter: { extension_paths: [], skill_paths: [], executable_paths: ['node_modules/mcporter/dist/cli.js'] }, +}; +if (new Set(selected).size !== selected.length || selected.some(name => !Object.hasOwn(catalog, name))) throw new Error('Unknown or duplicate plugin selection.'); +if (fs.existsSync(destination) && fs.readdirSync(destination).length) throw new Error('Install directory must be empty; retain the previous runtime and install a new immutable candidate.'); +fs.mkdirSync(destination, { recursive: true }); +for (const name of ['.cache', '.tmp', '.install-home']) fs.mkdirSync(path.join(destination, name), { recursive: true }); +const env = { ...process.env, HOME: path.join(destination, '.install-home'), TMPDIR: path.join(destination, '.tmp'), npm_config_cache: path.join(destination, '.cache') }; +const runtimeFiles = ['package.json', 'package-lock.json', 'pi', ...fs.readdirSync(source).filter(name => name.endsWith('.mjs') && name !== 'install.mjs')]; +for (const name of runtimeFiles) fs.copyFileSync(path.join(source, name), path.join(destination, name)); +for (const name of Object.keys(catalog)) { + const directory = path.join(destination, 'plugins', name); + fs.mkdirSync(directory, { recursive: true }); + fs.copyFileSync(path.join(source, 'plugins', name, 'package.json'), path.join(directory, 'package.json')); +} +fs.chmodSync(path.join(destination, 'pi'), 0o755); +fs.mkdirSync(path.join(destination, 'bin')); +const sha = filename => crypto.createHash('sha256').update(fs.readFileSync(filename)).digest('hex'); +// Host Node may link Homebrew libraries; deliver the official standalone binary instead. +const nodeDirectory = `node-v${nodeVersion}-${nodePlatform}`; +const nodeArchive = `${nodeDirectory}.${nodeDistribution[0]}`; +const nodeUrl = `https://nodejs.org/dist/v${nodeVersion}/${nodeArchive}`; +const archivePath = path.join(destination, '.cache', nodeArchive); +execFileSync('curl', ['--fail', '--location', '--silent', '--show-error', '--connect-timeout', '30', '--max-time', '300', '--output', archivePath, nodeUrl], { env, stdio: 'inherit' }); +if (sha(archivePath) !== nodeDistribution[1]) throw new Error(`Node distribution SHA256 mismatch: ${nodeArchive}.`); +execFileSync('tar', ['-xf', archivePath, '-C', path.join(destination, '.tmp'), `${nodeDirectory}/bin/node`, `${nodeDirectory}/LICENSE`], { env, stdio: 'inherit' }); +fs.copyFileSync(path.join(destination, '.tmp', nodeDirectory, 'bin/node'), path.join(destination, 'bin/node')); +fs.copyFileSync(path.join(destination, '.tmp', nodeDirectory, 'LICENSE'), path.join(destination, 'bin/node-LICENSE')); +fs.chmodSync(path.join(destination, 'bin/node'), 0o755); +const installedNodeVersion = execFileSync(path.join(destination, 'bin/node'), ['--version'], { env, encoding: 'utf8' }).trim(); +if (installedNodeVersion !== `v${nodeVersion}`) throw new Error(`Installed Node did not report v${nodeVersion}: ${installedNodeVersion}.`); +const workspaceArgs = selected.length + ? ['--include-workspace-root', ...selected.map(name => `--workspace=plugins/${name}`)] + : ['--workspaces=false']; +execFileSync('npm', ['ci', '--ignore-scripts', '--no-audit', '--no-fund', ...workspaceArgs], { cwd: destination, env, stdio: 'inherit' }); +// Workspace wrappers select dependencies at installation; they are not runtime packages. +for (const name of Object.keys(catalog)) { + const link = path.join(destination, 'node_modules', '@braid', `pi-runtime-${name}`); + if (fs.existsSync(link)) fs.unlinkSync(link); +} +const patches = JSON.parse(fs.readFileSync(path.join(source, 'patches.json'), 'utf8')) + .filter(item => !item.plugin || selected.includes(item.plugin)); +for (const item of patches) { + execFileSync('patch', ['--batch', '--fuzz=0', '-p1', '-d', path.join(destination, 'node_modules', item.package), '-i', path.join(source, item.path)], { env, stdio: 'inherit' }); +} +const files = {}; +function record(directory, relative = '') { + for (const name of fs.readdirSync(directory).sort()) { + const filename = path.join(directory, name); + const entry = path.join(relative, name); + const stat = fs.lstatSync(filename); + if (stat.isDirectory()) record(filename, entry); + else if (stat.isSymbolicLink()) { + const canonical = fs.realpathSync(filename); + const within = path.relative(fs.realpathSync(destination), canonical); + if (within === '..' || within.startsWith(`..${path.sep}`) || path.isAbsolute(within)) throw new Error(`Runtime symlink leaves installation: ${entry}`); + if (!fs.statSync(canonical).isFile()) throw new Error(`Runtime directory symlink is unsupported: ${entry}`); + files[entry] = sha(canonical); + } + else if (stat.isFile()) files[entry] = sha(filename); + } +} +record(path.join(destination, 'node_modules'), 'node_modules'); +record(path.join(destination, 'bin'), 'bin'); +for (const name of runtimeFiles) files[name] = sha(path.join(destination, name)); +record(path.join(destination, 'plugins'), 'plugins'); +const member = relative => ({ path: relative, sha256: files[relative] }); +const manifest = { + schema_version: 1, + pi_version: JSON.parse(fs.readFileSync(path.join(destination, 'node_modules/@earendil-works/pi-coding-agent/package.json'))).version, + capabilities: ['retry_intent', 'settle_extensions', 'owned_inference', 'managed_execution', 'owned_stop'], + entrypoint: member('pi'), + managed_module: member('managed.mjs'), + process_owner: member('process-owner.mjs'), + node: member('bin/node'), + node_distribution: { version: nodeVersion, platform: process.platform, arch: process.arch, url: nodeUrl, archive_sha256: nodeDistribution[1] }, + plugins: selected.map(name => ({ name, executable_paths: [], ...catalog[name] })), + npm_lock_sha256: files['package-lock.json'], + packages: Object.fromEntries([ + ...Object.keys(JSON.parse(fs.readFileSync(path.join(source, 'package.json'))).dependencies), + ...selected.flatMap(name => Object.keys(JSON.parse(fs.readFileSync(path.join(source, 'plugins', name, 'package.json'))).dependencies)), + ].map(name => [name, JSON.parse(fs.readFileSync(path.join(destination, 'node_modules', name, 'package.json'))).version])), + patches: patches.map(({ package: name, path: relative }) => ({ package: name, path: relative, sha256: sha(path.join(source, relative)) })), + files, +}; +fs.writeFileSync(path.join(destination, 'runtime-manifest.json'), `${JSON.stringify(manifest, null, 2)}\n`, { flag: 'wx' }); +console.log(JSON.stringify({ manifest: path.join(destination, 'runtime-manifest.json'), entrypoint: path.join(destination, 'pi'), plugins: selected, files: Object.keys(files).length })); diff --git a/native/pi/managed.mjs b/native/pi/managed.mjs new file mode 100644 index 00000000..c2a56ba1 --- /dev/null +++ b/native/pi/managed.mjs @@ -0,0 +1,335 @@ +import { spawn } from "node:child_process"; +import { createHash, randomUUID } from "node:crypto"; +import * as fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { bootIdentity, processIdentity, processMarkers, processSnapshot, withAdmission, writeJson } from "./process-owner.mjs"; +const providers = globalThis[Symbol.for("braid.native-managed-providers.v1")] ??= new Map(); +// MCPorter services share only this execution's namespace, never the user daemon. +if (process.env.BRAID_NATIVE_MCPORTER_ENABLED === "1" && process.env.BRAID_NATIVE_EXECUTION_DIR && process.env.BRAID_NATIVE_EXECUTION_ID) { + const directory = path.resolve(process.env.BRAID_NATIVE_EXECUTION_DIR, "mcporter"); + let namespace = directory; + const limit = process.platform === "darwin" ? 104 : 108; + if (Buffer.byteLength(path.join(directory, "daemon/user.sock")) >= limit) { + const root = process.env.BRAID_NATIVE_SOCKET_ROOT; + if (!root || !path.isAbsolute(root)) throw new Error(`Execution MCPorter Unix socket exceeds ${limit - 1} bytes; configure an absolute shorter BRAID_NATIVE_SOCKET_ROOT.`); + fs.mkdirSync(root, { recursive: true, mode: 0o700 }); + const info = fs.lstatSync(root); + if (!info.isDirectory() || info.isSymbolicLink() || info.uid !== process.getuid() || (info.mode & 0o777) !== 0o700) throw new Error("Native socket root must be a private owned directory."); + fs.mkdirSync(directory, { recursive: true, mode: 0o700 }); + if (fs.statSync(root).dev !== fs.statSync(directory).dev) throw new Error("Native socket alias must remain on the execution filesystem."); + namespace = path.join(root, createHash("sha256").update(directory).update("\0").update(process.env.BRAID_NATIVE_EXECUTION_ID).digest("hex").slice(0, 24)); + if (Buffer.byteLength(path.join(namespace, "daemon/user.sock")) >= limit) throw new Error("Native socket root is still too long."); + try { fs.symlinkSync(directory, namespace); } + catch (error) { if (error.code !== "EEXIST" || !fs.lstatSync(namespace).isSymbolicLink() || fs.readlinkSync(namespace) !== directory) throw error; } + } + process.env.MCPORTER_DAEMON_DIR = namespace; +} +const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); +const diagnostic = (error) => error instanceof Error ? error.message : String(error); +const readJson = (file) => JSON.parse(fs.readFileSync(file, "utf8")); + +/** The detached launcher registers ownership before starting the payload. */ +export function spawnManaged(command, args, options = {}, metadata = {}) { + const env = options.env ?? process.env; + if (!env.BRAID_NATIVE_EXECUTION_DIR || !env.BRAID_NATIVE_EXECUTION_ID) throw new Error("Native execution identity is unavailable."); + const startId = randomUUID(); + const launchArgs = [fileURLToPath(new URL("./process-owner.mjs", import.meta.url)), "launch", "--start-id", startId, "--kind", metadata.kind ?? "tool"]; + if (metadata.manifest) launchArgs.push("--manifest", metadata.manifest); + if (metadata.service) launchArgs.push("--service"); + launchArgs.push("--", command, ...args); + const child = spawn(process.execPath, launchArgs, { ...options, detached: true, env: { ...env, BRAID_NATIVE_LAUNCH_START_ID: startId } }); + child.managedStartId = startId; + child.managedResourceDirectory = env.BRAID_NATIVE_EXECUTION_DIR; + child.managedStartReceipt = path.join(env.BRAID_NATIVE_EXECUTION_DIR, "starts", `${startId}.json`); + child.managedClose = new Promise(resolve => { + child.once("error", error => resolve({ error: diagnostic(error) })); + child.once("close", (code, signal) => resolve({ code, signal })); + }); + return child; +} + +/** Wait without blocking the Pi event loop; callers attach stdout/error/close first. */ +export async function waitManagedStartup(child, timeoutMs = 30_000) { + if (!child?.managedStartReceipt) return { status: "started", unmanaged: true }; + child.managedStartup ??= (async () => { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + try { + const start = readJson(child.managedStartReceipt); + if (start.status !== "started") throw new Error(`Managed process did not start: ${JSON.stringify(start)}`); + child.managedProcessRecord = start.process_record; + return start; + } catch (error) { if (error.code !== "ENOENT") throw error; } + if ((child.exitCode !== null && child.exitCode !== undefined) || + (child.signalCode !== null && child.signalCode !== undefined)) { + throw new Error(`Managed launcher exited before publishing a start receipt: ${child.managedStartReceipt}.`); + } + await pause(10); + } + const recordPath = path.join(child.managedResourceDirectory, "processes", `${child.managedStartId}.json`); + let cleanup; + await withAdmission(child.managedResourceDirectory, () => writeJson(path.join(child.managedResourceDirectory, "fences", `${child.managedStartId}.json`), { start_id: child.managedStartId })); + if (fs.existsSync(recordPath)) { + child.managedProcessRecord = recordPath; + const record = readJson(recordPath); + await withAdmission(child.managedResourceDirectory, () => writeJson(path.join(child.managedResourceDirectory, "fences", `${record.start_id}.json`), { execution_id: record.execution_id, start_id: record.start_id })); + try { await stopRecords([record], record.execution_id, process.pid, false, child.managedResourceDirectory); cleanup = "owned subtree stopped"; } + catch (error) { cleanup = `owned subtree unknown: ${diagnostic(error)}`; } + } else { child.kill("SIGKILL"); cleanup = "launcher killed before registration; no subtree proof"; } + throw new Error(`Managed launcher did not publish a start receipt: ${child.managedStartReceipt}; ${cleanup}.`); + })(); + return child.managedStartup; +} + +export function registerManagedProvider(name, snapshot, stopServices) { + const provider = { snapshot, stopServices }; + providers.set(name, provider); + return () => { if (providers.get(name) === provider) providers.delete(name); }; +} + +function execution(env = process.env) { + const directory = env.BRAID_NATIVE_EXECUTION_DIR; + const id = env.BRAID_NATIVE_EXECUTION_ID; + if (!directory || !id) throw new Error("Native execution identity is unavailable."); + return { directory, id }; +} + +function records(directory, id) { + const entries = fs.readdirSync(path.join(directory, "processes")); + return entries.filter((name) => name.endsWith(".json")).map((name) => { + const record = readJson(path.join(directory, "processes", name)); + if (record.schema_version !== 1 || record.execution_id !== id || !Number.isInteger(record.pid) || !Number.isInteger(record.pgid) || !record.starttime || !record.boot_id || !record.start_id) { + throw new Error(`Invalid native ownership record: ${name}.`); + } + return { ...record, ownership_path: path.join(directory, "processes", name) }; + }); +} + +function ownedProcesses(ownership, id, skipPid, allExecution = false) { + const bootId = bootIdentity(); + if (ownership.some(record => record.boot_id !== bootId)) throw new Error("Native ownership belongs to another boot identity."); + const all = processSnapshot(); + const ownGroups = new Set(); + for (const record of ownership) { + const leader = all.find((item) => item.pid === record.pid); + if (leader && leader.starttime !== record.starttime) { + let previous; + try { previous = readJson(path.join(path.dirname(path.dirname(record.ownership_path)), "terminals", `${record.start_id}.json`)); } + catch (error) { if (error.code !== "ENOENT") throw error; } + if (previous?.start_id === record.start_id && previous.execution_id === id && previous.terminal?.status === "stopped") continue; + throw new Error(`Native PID identity conflict for ${record.start_id}.`); + } + if (leader?.starttime === record.starttime && leader.pgid === record.pgid) { + // macOS birth time has seconds precision; inherited random markers disambiguate reuse. + if (process.platform === "darwin" && (leader.owner !== id || leader.startId !== record.start_id)) throw new Error(`Unverified native owner marker for ${record.start_id}.`); + ownGroups.add(record.pgid); + } + else if (leader && leader.owner === id) throw new Error(`Native PID identity conflict for ${record.start_id}.`); + else { + const payload = record.payload_identity && all.find(item => item.pid === record.payload_identity.pid); + if (payload && payload.starttime === record.payload_identity.starttime && payload.pgid === record.pgid) { + ownGroups.add(record.pgid); + continue; + } + const members = all.filter((item) => item.pgid === record.pgid); + if (members.length && !members.every((item) => item.owner === id)) throw new Error(`Unverified surviving process group ${record.pgid}.`); + if (members.length) ownGroups.add(record.pgid); + } + } + const startIds = new Set(ownership.map((record) => record.start_id)); + const skipped = new Set(Array.isArray(skipPid) ? skipPid : [skipPid]); + return all.filter((item) => !skipped.has(item.pid) && (ownGroups.has(item.pgid) || (item.owner === id && (allExecution || startIds.has(item.startId))))); +} + +function ownedDescendants(ownership, startId) { + const selected = new Set([startId]); + for (let previous = -1; previous !== selected.size;) { + previous = selected.size; + for (const record of ownership) if (selected.has(record.parent_start_id)) selected.add(record.start_id); + } + return ownership.filter((record) => selected.has(record.start_id)); +} + +function signalExact(identity, signal) { + const current = processIdentity(identity.pid); + if (!current || /^[ZX]/.test(current.state)) return; + if (current.starttime !== identity.starttime) throw new Error(`PID ${identity.pid} changed birth identity before ${signal}.`); + if (process.platform === "darwin") { + let markers; + try { markers = processMarkers(identity.pid); } + catch (error) { + const after = processIdentity(identity.pid); + if (!after || /^[ZX]/.test(after.state)) return; + throw error; + } + const after = processIdentity(identity.pid); + // Exit can remove environment markers while ps reads them; verify disappearance. + if (!after || /^[ZX]/.test(after.state)) return; + if (after.starttime !== identity.starttime) throw new Error(`PID ${identity.pid} changed birth identity before ${signal}.`); + if (markers.owner !== identity.owner || markers.startId !== identity.startId) throw new Error(`PID ${identity.pid} changed ownership markers before ${signal}.`); + } + try { process.kill(identity.pid, signal); } + catch (error) { if (error.code !== "ESRCH") throw error; } +} + +async function stopRecords(ownership, id, skipPid, allExecution = false, directory = execution().directory) { + const roots = ownership.map((record) => record.start_id); + const collect = () => { + const current = records(directory, id); + const selected = allExecution ? current : [...new Map(roots.flatMap((root) => ownedDescendants(current, root)).map((record) => [record.start_id, record])).values()]; + return ownedProcesses(selected, id, skipPid, allExecution); + }; + let active = collect(); + for (const item of active) signalExact(item, "SIGTERM"); + const deadline = Date.now() + 3000; + while (active.length && Date.now() < deadline) { await pause(25); active = collect(); } + for (const item of active) signalExact(item, "SIGKILL"); + const killDeadline = Date.now() + 1000; + while (active.length && Date.now() < killDeadline) { await pause(25); active = collect(); } + if (active.length) throw new Error(`Owned execution remains active: ${active.map((item) => item.pid).join(", ")}.`); + // Admission has been fenced; repeat the observation after signals settle. + await pause(25); + if (collect().length) throw new Error("Owned execution became active during stop verification."); +} + +export function managedState(session = {}) { + try { + const { directory, id } = execution(); + if (fs.existsSync(path.join(directory, "stopping.json"))) return { status: "unknown", reason: "execution_stopping", execution_id: id }; + const ownership = records(directory, id); + if (session.isStreaming || session.isCompacting || session.pendingMessageCount > 0) return { status: "busy", reason: "native_turn_or_messages", execution_id: id }; + if (ownedProcesses(ownership, id, [process.pid, ownership.find(record => record.start_id === process.env.BRAID_NATIVE_START_ID)?.pid], true).length) return { status: "busy", reason: "owned_process_active", execution_id: id }; + for (const [name, provider] of providers) { + const state = provider.snapshot(); + if (state.status !== "quiescent") return { status: state.status, reason: `${name}: ${state.reason ?? state.status}`.slice(0, 512), execution_id: id }; + } + return { status: "quiescent", execution_id: id }; + } catch (error) { return { status: "unknown", reason: diagnostic(error).slice(0, 512), execution_id: process.env.BRAID_NATIVE_EXECUTION_ID ?? "unavailable" }; } +} + +/** Yield only declared services after finite/native obligations are empty. */ +export async function yieldStoppableServices(session = {}) { + try { + const { directory, id } = execution(); + if (session.isStreaming || session.isCompacting || session.pendingMessageCount > 0) return managedState(session); + if (fs.existsSync(path.join(directory, "stopping.json"))) return managedState(session); + const serviceProviders = []; + for (const [name, provider] of providers) { + const state = provider.snapshot(); + if (state.status === "quiescent") continue; + if (!state.services_only || typeof provider.stopServices !== "function") { + return { status: state.status, reason: `${name}: ${state.reason ?? state.status}`, execution_id: id }; + } + serviceProviders.push(provider); + } + const ownership = records(directory, id); + const serviceRoots = ownership.filter((record) => record.service === true); + const serviceRecords = [...new Map(serviceRoots.flatMap((root) => ownedDescendants(ownership, root.start_id)).map((record) => [record.start_id, record])).values()]; + const covered = new Set(ownedProcesses(serviceRecords, id, process.pid).map((item) => item.pid)); + const active = ownedProcesses(ownership, id, [process.pid, ownership.find(record => record.start_id === process.env.BRAID_NATIVE_START_ID)?.pid], true); + if (active.some((item) => !covered.has(item.pid))) return { status: "busy", reason: "finite_or_unclassified_owned_process", execution_id: id }; + await withAdmission(directory, () => { for (const root of serviceRoots) writeJson(path.join(directory, "fences", `${root.start_id}.json`), { start_id: root.start_id, execution_id: id }); }); + for (const provider of serviceProviders) await provider.stopServices(); + await stopRecords(serviceRoots, id, process.pid, false, directory); + const verifiedAt = Date.now(); + for (const record of serviceRecords) { + const terminalPath = path.join(directory, "terminals", `${record.start_id}.json`); + let previous; + try { previous = readJson(terminalPath); } catch (error) { if (error.code !== "ENOENT") throw error; } + writeJson(terminalPath, { + start_id: record.start_id, execution_id: id, + close: previous?.close ?? { observation: "owned_service_handoff", observed_at: verifiedAt }, + terminal: { status: "stopped", verified_at: verifiedAt }, + }); + } + const state = managedState(session); + writeJson(path.join(directory, "service-handoff.json"), { ...state, service_start_ids: serviceRoots.map((record) => record.start_id), verified_at: verifiedAt }); + return state; + } catch (error) { return { status: "unknown", reason: diagnostic(error).slice(0, 1024), execution_id: process.env.BRAID_NATIVE_EXECUTION_ID ?? "unavailable" }; } +} + +export async function cleanupOwnedExecution(options = {}) { + let receiptPath; + try { + const { directory, id } = options.directory ? { directory: options.directory, id: options.id } : execution(); + if (!id) throw new Error("Native cleanup requires an execution identity."); + const self = options.skipSelf ? records(directory, id).find((record) => record.start_id === process.env.BRAID_NATIVE_START_ID) : undefined; + if (options.skipSelf && !self) throw new Error("Native root ownership identity is unavailable."); + if (self?.parent_start_id) throw new Error("Nested native RPC cleanup requires its own subtree fence; execution cleanup belongs to the root owner."); + await withAdmission(directory, () => writeJson(path.join(directory, "stopping.json"), { execution_id: id, requested_at: Date.now() })); + receiptPath = path.join(directory, options.skipSelf ? "children-stop.json" : "execution-stop.json"); + const ownership = records(directory, id); + await stopRecords(ownership, id, options.skipSelf ? [process.pid, self?.pid] : process.pid, true, directory); + const result = { status: "stopped", execution_id: id, scope: options.skipSelf ? "root-descendants" : "execution", verified_at: Date.now(), coverage: "registered-process-groups-and-inherited-execution-markers", receipt_path: receiptPath }; + writeJson(receiptPath, result); + return result; + } catch (error) { + const result = { status: "unknown", reason: diagnostic(error).slice(0, 1024), ...(receiptPath ? { receipt_path: receiptPath } : {}) }; + if (receiptPath) writeJson(receiptPath, result); + return result; + } +} + +/** Raw close observations are separate from the proof that the owned group stopped. */ +export async function finishManagedProcess(child, close) { + if (!child.managedProcessRecord && child.managedStartReceipt) { + try { await waitManagedStartup(child); } + catch (error) { return { status: "unknown", reason: diagnostic(error) }; } + } + if (!child.managedProcessRecord) return undefined; + const record = readJson(child.managedProcessRecord); + const { directory, id } = execution(); + let terminal; + try { await withAdmission(directory, () => writeJson(path.join(directory, "fences", `${record.start_id}.json`), { start_id: record.start_id, execution_id: id })); await stopRecords(ownedDescendants(records(directory, id), record.start_id), id, process.pid); terminal = { status: "stopped", verified_at: Date.now() }; } + catch (error) { terminal = { status: "unknown", reason: diagnostic(error) }; } + const terminalPath = path.join(directory, "terminals", `${record.start_id}.json`); + let previous; + try { previous = readJson(terminalPath); } catch (error) { if (error.code !== "ENOENT") throw error; } + writeJson(terminalPath, { start_id: record.start_id, execution_id: id, close: close.observation ? previous?.close ?? close : close, terminal }); + return terminal; +} + +export function createManagedProcessTreeController(child) { + if (!child.managedProcessRecord) return undefined; + let terminal; + const terminate = () => terminal ??= (async () => { + const result = await finishManagedProcess(child, { observation: "cleanup_requested", observed_at: Date.now() }); + return result?.status === "stopped" + ? { state: "observed", mechanism: "posix-process-group", processGroupId: child.pid, verifiedAt: Date.now() } + : { state: "unknown", reason: "verification-failed", diagnostic: result?.reason ?? "Managed process record unavailable." }; + })(); + return { terminate, finishAfterWriterClose: terminate }; +} + +export function publishChildStartup(manifestDirectory, status, reason) { + if (!process.env.BRAID_NATIVE_EXECUTION_DIR || !manifestDirectory) return; + writeJson(path.join(manifestDirectory, "native-child-startup.json"), { status, reason, execution_id: process.env.BRAID_NATIVE_EXECUTION_ID, observed_at: Date.now() }); +} + +export async function waitChildStartup(manifestDirectory, timeoutMs) { + const file = path.join(manifestDirectory, "native-child-startup.json"); + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + try { + const receipt = readJson(file); + if (receipt.execution_id !== process.env.BRAID_NATIVE_EXECUTION_ID) throw new Error("Child startup execution identity mismatch."); + return receipt; + } + catch (error) { if (error.code !== "ENOENT") throw error; } + await pause(10); + } + throw new Error(`Async child did not confirm physical startup within ${timeoutMs}ms: ${file}.`); +} + +// Process management is installed by this module; it does not alter model prompts. +export default function managedProcessExtension() {} + +globalThis[Symbol.for("braid.native-runtime.v1")] = { spawnManaged, waitManagedStartup, finishManagedProcess, createManagedProcessTreeController, registerManagedProvider, publishChildStartup, waitChildStartup }; + +if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + const args = process.argv.slice(2); + const argument = (name) => args[args.indexOf(name) + 1]; + if (args[0] !== "cleanup" || !args.includes("--execution-dir") || !args.includes("--execution-id")) throw new Error("Usage: native-managed.mjs cleanup --execution-dir DIR --execution-id ID"); + console.log(JSON.stringify(await cleanupOwnedExecution({ directory: argument("--execution-dir"), id: argument("--execution-id") }))); +} diff --git a/native/pi/package-lock.json b/native/pi/package-lock.json new file mode 100644 index 00000000..471bf589 --- /dev/null +++ b/native/pi/package-lock.json @@ -0,0 +1,3266 @@ +{ + "name": "braid-pi-runtime", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "braid-pi-runtime", + "version": "1.0.0", + "workspaces": [ + "plugins/*" + ], + "dependencies": { + "@earendil-works/pi-coding-agent": "1.1.0" + } + }, + "node_modules/@anthropic-ai/sdk": { + "version": "0.129.0", + "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.129.0.tgz", + "integrity": "sha512-MH7LB20kNpGLUpPTe2OG5XvL/KhX8HUO9XyBaFjgFk6TLS4Xjt0VPIuMKywe7POKKPslX+QxSlVok9e+8kG5Nw==", + "license": "MIT", + "dependencies": { + "json-schema-to-ts": "^3.1.1", + "standardwebhooks": "^1.0.0" + }, + "bin": { + "anthropic-ai-sdk": "bin/cli" + }, + "peerDependencies": { + "zod": "^3.25.0 || ^4.0.0" + }, + "peerDependenciesMeta": { + "zod": { + "optional": true + } + } + }, + "node_modules/@aws-sdk/client-bedrock-runtime": { + "version": "3.1127.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-bedrock-runtime/-/client-bedrock-runtime-3.1127.0.tgz", + "integrity": "sha512-IDl/lrPb90aH+pZFHGNDmgH9nAUQj5PlZH1sJ3w7RikctyjHSnY3oNjZhrLoaBoQn/rNK0zsP6OHEqEhj2tdLA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.977.9", + "@aws-sdk/credential-provider-node": "^3.972.82", + "@aws-sdk/eventstream-handler-node": "^3.972.34", + "@aws-sdk/middleware-eventstream": "^3.972.29", + "@aws-sdk/middleware-websocket": "^3.972.52", + "@aws-sdk/token-providers": "3.1127.0", + "@aws-sdk/types": "^3.974.5", + "@smithy/core": "^3.33.3", + "@smithy/fetch-http-handler": "^5.7.2", + "@smithy/node-http-handler": "^4.11.3", + "@smithy/types": "^4.17.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/core": { + "version": "3.978.2", + "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.978.2.tgz", + "integrity": "sha512-ViOBLuGSSyPAmkKGJ6KJXtVN7MOEp3rnI7uH+kWxnHccvo8C9cvunEAnN5/oaZH1laQfsTBw7IOnmNkWlFZl2A==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "^3.974.6", + "@aws-sdk/xml-builder": "^3.972.41", + "@aws/lambda-invoke-store": "^0.3.0", + "@smithy/core": "^3.35.2", + "@smithy/signature-v4": "^5.7.4", + "@smithy/types": "^4.19.0", + "bowser": "^2.11.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-env": { + "version": "3.972.73", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.972.73.tgz", + "integrity": "sha512-PxlFZiF5IPUsPnuVSqjM9jlmRwZhL0xx40ccWfZiLQS8TRnHQpegpK1uAidatWuEqbJtbbY97A2Sezikz2AMUw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.978.2", + "@aws-sdk/types": "^3.974.6", + "@smithy/core": "^3.35.2", + "@smithy/types": "^4.19.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-http": { + "version": "3.972.75", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.972.75.tgz", + "integrity": "sha512-Q/uIDy8eAVN7JgSKDg16F/f+hmNJj/ZyLJN8AkW2ofVdDgJVh8fO/A26iZ7YsvM2/k76hsf/u2lLAtyXsK8Ziw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.978.2", + "@aws-sdk/types": "^3.974.6", + "@smithy/core": "^3.35.2", + "@smithy/fetch-http-handler": "^5.8.0", + "@smithy/node-http-handler": "^4.12.1", + "@smithy/types": "^4.19.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-ini": { + "version": "3.973.18", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.973.18.tgz", + "integrity": "sha512-KoyjZ9vdjuxEQ8obAH06xKP8H0WKqGhwUZLMqAOiS7G0xgUAht4X8f0ASLC/vhNLCWGblZOD3VQHWyTROGJHLg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.978.2", + "@aws-sdk/credential-provider-env": "^3.972.73", + "@aws-sdk/credential-provider-http": "^3.972.75", + "@aws-sdk/credential-provider-login": "^3.972.80", + "@aws-sdk/credential-provider-process": "^3.972.73", + "@aws-sdk/credential-provider-sso": "^3.973.17", + "@aws-sdk/credential-provider-web-identity": "^3.972.79", + "@aws-sdk/nested-clients": "^3.997.47", + "@aws-sdk/types": "^3.974.6", + "@smithy/core": "^3.35.2", + "@smithy/credential-provider-imds": "^4.5.2", + "@smithy/types": "^4.19.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-login": { + "version": "3.972.80", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-login/-/credential-provider-login-3.972.80.tgz", + "integrity": "sha512-xF9A0gaO7k+1dYPFoo69OQatA9Ov0QuDZfqE8H0FLyIoOph+mlEC+I1Qo9UULupGuDfSYh+kVpfcDSxSYf/2fg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.978.2", + "@aws-sdk/nested-clients": "^3.997.47", + "@aws-sdk/types": "^3.974.6", + "@smithy/core": "^3.35.2", + "@smithy/types": "^4.19.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-node": { + "version": "3.972.85", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.972.85.tgz", + "integrity": "sha512-CrFcML/xImiSlquH4W3V6Npz3aSkPXHDVciAU1JOBN0vqjmkcz9H9up2sCHQqN76J/WrT+TJ580L8h2joksQrg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/credential-provider-env": "^3.972.73", + "@aws-sdk/credential-provider-http": "^3.972.75", + "@aws-sdk/credential-provider-ini": "^3.973.18", + "@aws-sdk/credential-provider-process": "^3.972.73", + "@aws-sdk/credential-provider-sso": "^3.973.17", + "@aws-sdk/credential-provider-web-identity": "^3.972.79", + "@aws-sdk/types": "^3.974.6", + "@smithy/core": "^3.35.2", + "@smithy/credential-provider-imds": "^4.5.2", + "@smithy/types": "^4.19.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-process": { + "version": "3.972.73", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.972.73.tgz", + "integrity": "sha512-tyNnT4aVuOEXmKKKZPExBi828vRd9heshobBsKF0bov5EORHSJc1AGsHOMRP57sDt+dIuVASUOywaixiX26t4g==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.978.2", + "@aws-sdk/types": "^3.974.6", + "@smithy/core": "^3.35.2", + "@smithy/types": "^4.19.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-sso": { + "version": "3.973.17", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.973.17.tgz", + "integrity": "sha512-gxKTWaUk2gSbBOH4m3NPRfEKcGXeDAOgHr7nNG5JktR1xZLo0R+DpMjbcleoHbB0uJREOG7hjIRE635IuBWsRQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.978.2", + "@aws-sdk/nested-clients": "^3.997.47", + "@aws-sdk/token-providers": "3.1149.0", + "@aws-sdk/types": "^3.974.6", + "@smithy/core": "^3.35.2", + "@smithy/types": "^4.19.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers": { + "version": "3.1149.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.1149.0.tgz", + "integrity": "sha512-CAwYyA8eVk1w6h8YgLvkjIOakWPwURaUFrP7BRVgkxTFUM+O87thyKsGKJ6rVPbP8eoEV10cBWQ5YfaYl3qSVQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.978.2", + "@aws-sdk/nested-clients": "^3.997.47", + "@aws-sdk/types": "^3.974.6", + "@smithy/core": "^3.35.2", + "@smithy/types": "^4.19.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-web-identity": { + "version": "3.972.79", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.972.79.tgz", + "integrity": "sha512-/jn0Gs/qm6fs6nTIA5yncHayybz42SATZ3rNxCEBYPJ9v69PLrDRgk07E9xTT2gpRcNmDXXbi27ZbuU06N0Z6Q==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.978.2", + "@aws-sdk/nested-clients": "^3.997.47", + "@aws-sdk/types": "^3.974.6", + "@smithy/core": "^3.35.2", + "@smithy/types": "^4.19.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/eventstream-handler-node": { + "version": "3.972.36", + "resolved": "https://registry.npmjs.org/@aws-sdk/eventstream-handler-node/-/eventstream-handler-node-3.972.36.tgz", + "integrity": "sha512-HFaKXA6ugPVvpR7W/3UT3hylWIPndqGMwduwNVrmGsRT5+OESHN8/ven4eeofraQF5Kxp8A8QgGVrv7iQsTRKQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "^3.974.6", + "@smithy/core": "^3.35.2", + "@smithy/types": "^4.19.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/middleware-eventstream": { + "version": "3.972.31", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-eventstream/-/middleware-eventstream-3.972.31.tgz", + "integrity": "sha512-4yvdTVwPGKCnrwuwlYEmwLqQXKwk0unx3f/FvBi4FA9ruK/WGoPJyqfK7hOYurheIyQL44FR0ovgOHqvkfdpAQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "^3.974.6", + "@smithy/core": "^3.35.2", + "@smithy/types": "^4.19.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/middleware-websocket": { + "version": "3.972.55", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-websocket/-/middleware-websocket-3.972.55.tgz", + "integrity": "sha512-dHlEl3sCn1Cu+qddPoz5RxjgGCXEzs/pbrh/rDRaOeb/Tz//FF59hacDvy7kvUn19mkm2nQRjhpzBnX+Ye37Qw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.978.2", + "@aws-sdk/types": "^3.974.6", + "@smithy/core": "^3.35.2", + "@smithy/fetch-http-handler": "^5.8.0", + "@smithy/signature-v4": "^5.7.4", + "@smithy/types": "^4.19.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">= 14.0.0" + } + }, + "node_modules/@aws-sdk/nested-clients": { + "version": "3.997.47", + "resolved": "https://registry.npmjs.org/@aws-sdk/nested-clients/-/nested-clients-3.997.47.tgz", + "integrity": "sha512-bovCKvDsLocNTzaj6VrrMVJ2BGROqO0JlwcGseO67a+I9Bo+08nUJhSQfZUIx4+A4a7I4101GEJd/AYm7dQ68w==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.978.2", + "@aws-sdk/signature-v4-multi-region": "^3.996.48", + "@aws-sdk/types": "^3.974.6", + "@smithy/core": "^3.35.2", + "@smithy/fetch-http-handler": "^5.8.0", + "@smithy/node-http-handler": "^4.12.1", + "@smithy/types": "^4.19.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/signature-v4-multi-region": { + "version": "3.996.48", + "resolved": "https://registry.npmjs.org/@aws-sdk/signature-v4-multi-region/-/signature-v4-multi-region-3.996.48.tgz", + "integrity": "sha512-cFDXfEbXaGwbnpvR/DyqfxfjxpjXVRVthQLgkwvcfDS5u3+8G9WSj1X1Ag/pTRg/QOeOno1Tq3ycEdrKsCUcOA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "^3.974.6", + "@smithy/signature-v4": "^5.7.4", + "@smithy/types": "^4.19.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/token-providers": { + "version": "3.1127.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.1127.0.tgz", + "integrity": "sha512-Dv2TMWBshJ+tF6ahs2Sy5bh4Iabsd4GAQqVvE9XZmYmnoaVbpS2QKIKE/HRacc7bTtbjEEvP+laGzHvHlf1CiQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.977.9", + "@aws-sdk/nested-clients": "^3.997.44", + "@aws-sdk/types": "^3.974.5", + "@smithy/core": "^3.33.3", + "@smithy/types": "^4.17.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/types": { + "version": "3.974.6", + "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.974.6.tgz", + "integrity": "sha512-v/clNZzZnDxGyvpHMOGpJKVXFAExJzUNAAjaWGdcx8QAcXLGwTaOkw33p5SHAi0YAioK32xB3hWwOekRVfmfKg==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.19.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/xml-builder": { + "version": "3.972.41", + "resolved": "https://registry.npmjs.org/@aws-sdk/xml-builder/-/xml-builder-3.972.41.tgz", + "integrity": "sha512-ctjVSyCMegrWfXlx6VqzSBFI6UqmQ5ZlnfMhdLIiWmhoH8UAQxSCP5N3OpG7X3k4LnS7ou74C4mt20+bfTW2aQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.19.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws/lambda-invoke-store": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@aws/lambda-invoke-store/-/lambda-invoke-store-0.3.0.tgz", + "integrity": "sha512-sl4Bm6yiMNYrZKkqqDFWN0UfnWhlS8ivKxrYl+6t0gCLrqr8y3B2IqZZbFRkfaVVp7C/baApyh71P+LeE1A2sQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@babel/runtime": { + "version": "7.29.10", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.10.tgz", + "integrity": "sha512-NpugTzbKgGrNe45Ui32cN8vCFFMxVtP/9rtfwv0nP5FRDAjvYBxJcLVpYA9mr1jxP6cnIT7x9LUzuDTbWYYNRA==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@braid/pi-runtime-background": { + "resolved": "plugins/background", + "link": true + }, + "node_modules/@braid/pi-runtime-context7": { + "resolved": "plugins/context7", + "link": true + }, + "node_modules/@braid/pi-runtime-fff": { + "resolved": "plugins/fff", + "link": true + }, + "node_modules/@braid/pi-runtime-mcporter": { + "resolved": "plugins/mcporter", + "link": true + }, + "node_modules/@braid/pi-runtime-subagents": { + "resolved": "plugins/subagents", + "link": true + }, + "node_modules/@earendil-works/chord": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@earendil-works/chord/-/chord-1.1.0.tgz", + "integrity": "sha512-gsHzKfyQ3t0ZIQ3cLBjJ5Vqy1TYnFyruHIV3g3BwmulCDYe5BW4yT9vaJk9QzN6YANILIO75uzuq+Gdxtzz1og==", + "license": "MIT", + "dependencies": { + "esbuild": "0.28.2" + }, + "engines": { + "node": ">=22.19.0" + } + }, + "node_modules/@earendil-works/pi-agent-core": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@earendil-works/pi-agent-core/-/pi-agent-core-1.1.0.tgz", + "integrity": "sha512-aX1KZomNCPmwYnXa3OivF3VYLJ+WPUkIJlEIZTgwdOZdY/+oToWTQ334WYpQeOz9POpiYFNMJLPwIhXQ4e48kg==", + "license": "MIT", + "dependencies": { + "@earendil-works/pi-ai": "^1.1.0", + "typebox": "1.3.27" + }, + "engines": { + "node": ">=22.19.0" + } + }, + "node_modules/@earendil-works/pi-agent-core/node_modules/typebox": { + "version": "1.3.27", + "resolved": "https://registry.npmjs.org/typebox/-/typebox-1.3.27.tgz", + "integrity": "sha512-zu+jc1pcy4UiNThxikUr36f0Rybk9PEeCg/NE6adeWr/SKsdNO4EzZHYRDlv2YCVAfj3Odq3dESSo/jNyoBXzA==", + "license": "MIT" + }, + "node_modules/@earendil-works/pi-ai": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@earendil-works/pi-ai/-/pi-ai-1.1.0.tgz", + "integrity": "sha512-1T7LAkc/5Bvc0v6w4vAGVdCrli0o/E0pEmYKTnixu95vSFArBjvbhS/G4ZwI0RUePgf0Imcu0VyqlM4EcXxqfw==", + "license": "MIT", + "dependencies": { + "@anthropic-ai/sdk": "0.129.0", + "@aws-sdk/client-bedrock-runtime": "3.1127.0", + "@earendil-works/pi-telemetry": "^1.1.0", + "@google/genai": "2.21.0", + "@smithy/node-http-handler": "4.12.1", + "http-proxy-agent": "9.1.0", + "https-proxy-agent": "9.1.0", + "openai": "7.19.0", + "partial-json": "0.1.7", + "typebox": "1.3.27" + }, + "bin": { + "pi-ai": "dist/cli.js" + }, + "engines": { + "node": ">=22.19.0" + } + }, + "node_modules/@earendil-works/pi-ai/node_modules/typebox": { + "version": "1.3.27", + "resolved": "https://registry.npmjs.org/typebox/-/typebox-1.3.27.tgz", + "integrity": "sha512-zu+jc1pcy4UiNThxikUr36f0Rybk9PEeCg/NE6adeWr/SKsdNO4EzZHYRDlv2YCVAfj3Odq3dESSo/jNyoBXzA==", + "license": "MIT" + }, + "node_modules/@earendil-works/pi-codemode": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@earendil-works/pi-codemode/-/pi-codemode-1.1.0.tgz", + "integrity": "sha512-8Asc2AzhoNaXS1snmRFa96OhcWIlFM5k1Kuiz6p2DvIYgi5QHQccRAmDVY9oO92TzWrizpvQpconZGQ7JhlI7Q==", + "license": "MIT", + "dependencies": { + "quickjs-wasi": "3.6.2" + }, + "engines": { + "node": ">=22.19.0" + } + }, + "node_modules/@earendil-works/pi-coding-agent": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@earendil-works/pi-coding-agent/-/pi-coding-agent-1.1.0.tgz", + "integrity": "sha512-SeEi/4hdcHNgA9UWlefZl7ZZpm3dzi2OoxNjDHsBJ9o298LNOtbL4DGKgitlEj6uCTccvtw6f2hlCkTPVJ2RXg==", + "license": "MIT", + "dependencies": { + "@earendil-works/chord": "^1.1.0", + "@earendil-works/pi-agent-core": "^1.1.0", + "@earendil-works/pi-ai": "^1.1.0", + "@earendil-works/pi-codemode": "^1.1.0", + "@earendil-works/pi-mcp": "^1.1.0", + "@earendil-works/pi-tui": "^1.1.0", + "@silvia-odwyer/photon-node": "0.3.4", + "brace-expansion": "5.0.12", + "chalk": "6.0.0", + "cross-spawn": "7.0.6", + "diff": "8.0.4", + "grok-mermaid": "0.2.3", + "highlight.js": "10.7.3", + "hosted-git-info": "9.0.3", + "ignore": "7.0.8", + "jiti": "2.7.0", + "minimatch": "10.2.6", + "proper-lockfile": "4.1.2", + "quickjs-wasi": "3.6.2", + "semver": "7.8.5", + "typebox": "1.3.27", + "undici": "8.10.2", + "yaml": "2.9.0" + }, + "bin": { + "pi": "dist/bundle/cli.js" + }, + "engines": { + "node": ">=22.19.0" + } + }, + "node_modules/@earendil-works/pi-coding-agent/node_modules/typebox": { + "version": "1.3.27", + "resolved": "https://registry.npmjs.org/typebox/-/typebox-1.3.27.tgz", + "integrity": "sha512-zu+jc1pcy4UiNThxikUr36f0Rybk9PEeCg/NE6adeWr/SKsdNO4EzZHYRDlv2YCVAfj3Odq3dESSo/jNyoBXzA==", + "license": "MIT" + }, + "node_modules/@earendil-works/pi-mcp": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@earendil-works/pi-mcp/-/pi-mcp-1.1.0.tgz", + "integrity": "sha512-xGKwvu3SvVTeoIx8Z7UGoJprB4VK20wKORMhufcWGx61fIauhu3J+UqfB5eeoF1oE/geYBA598K6nh1SdABQkg==", + "license": "MIT", + "dependencies": { + "cross-spawn": "7.0.6" + }, + "engines": { + "node": ">=22.19.0" + } + }, + "node_modules/@earendil-works/pi-telemetry": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@earendil-works/pi-telemetry/-/pi-telemetry-1.1.0.tgz", + "integrity": "sha512-8gAK05/2pPozZZz6hCLOi8x2vsqzvsmO9gG92kbvuvTPm0qMHaFlaXX98ndXsrOi5pmzha7vNLguuG4+0Rgxjw==", + "license": "MIT", + "engines": { + "node": ">=22.19.0" + } + }, + "node_modules/@earendil-works/pi-tui": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@earendil-works/pi-tui/-/pi-tui-1.1.0.tgz", + "integrity": "sha512-v7wkS0y2ErZvZkSfemqd9RrBZJ5x6p8Ujsv7NdJj01IXJyFM0kNL6rMdcKcvTe7EVTd6ugvDB9VPZSoaBF9QxQ==", + "license": "MIT", + "dependencies": { + "get-east-asian-width": "1.6.0", + "marked": "18.0.11" + }, + "engines": { + "node": ">=22.19.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", + "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==", + "cpu": [ + "ppc64" + ], + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz", + "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz", + "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz", + "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz", + "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz", + "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz", + "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz", + "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz", + "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz", + "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz", + "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==", + "cpu": [ + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz", + "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==", + "cpu": [ + "loong64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz", + "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==", + "cpu": [ + "mips64el" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz", + "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==", + "cpu": [ + "ppc64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz", + "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==", + "cpu": [ + "riscv64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz", + "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==", + "cpu": [ + "s390x" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz", + "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz", + "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz", + "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz", + "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz", + "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz", + "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz", + "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz", + "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz", + "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==", + "cpu": [ + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz", + "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@ff-labs/fff-bin-android-arm64": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@ff-labs/fff-bin-android-arm64/-/fff-bin-android-arm64-0.11.0.tgz", + "integrity": "sha512-7CmURAtJg1xCETKE8d46CUpeql9tpdsdbyoNCrNRkH+t608jMy+mLQxmyw7cBDOI0ljg5BaffxGZfOS2E6kasA==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@ff-labs/fff-bin-darwin-arm64": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@ff-labs/fff-bin-darwin-arm64/-/fff-bin-darwin-arm64-0.11.0.tgz", + "integrity": "sha512-C2VLBldxqNhTMtp1/NXULdEWpqfUKugP9E8BOMUDPw5qZH/YGC0tZQmeOlQUYOSScFQOiXZLJGXJMp3Uk+FGxg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@ff-labs/fff-bin-darwin-x64": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@ff-labs/fff-bin-darwin-x64/-/fff-bin-darwin-x64-0.11.0.tgz", + "integrity": "sha512-DOnG46YoSOR8SxNVMMe+xhPS2JjFUigMS2r0M4oCGfHDaWVY2mnYK/g1YxrAeJS3cRGO5N8Aj4RP1zq5Z2f6jQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@ff-labs/fff-bin-linux-arm64-gnu": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@ff-labs/fff-bin-linux-arm64-gnu/-/fff-bin-linux-arm64-gnu-0.11.0.tgz", + "integrity": "sha512-wOTyNzovqN1+Kg3kPqfKqZ2+A262Um4bHrEIeAwKU9R7YoyMXI9oo6DTbEl2ullF3G01FaBt/PPHOZYi1q8ubw==", + "cpu": [ + "arm64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@ff-labs/fff-bin-linux-arm64-musl": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@ff-labs/fff-bin-linux-arm64-musl/-/fff-bin-linux-arm64-musl-0.11.0.tgz", + "integrity": "sha512-dtVOgT/mKN4VTqOh4i3AWjc3Kd9uDX9xz9YsiPs33lNXpEi/x68qynuaqb7JM7x/eD/nYrsJRsb5ivtH1D6nrQ==", + "cpu": [ + "arm64" + ], + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@ff-labs/fff-bin-linux-x64-gnu": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@ff-labs/fff-bin-linux-x64-gnu/-/fff-bin-linux-x64-gnu-0.11.0.tgz", + "integrity": "sha512-MJ1AJz9c5kxdTiIhmlEwA+hw57vBDoa+VQSr4F+1inaEiFDtem7EnXE1P8Bdhf4okGM557mCXgRrvCt4kM5pSg==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@ff-labs/fff-bin-linux-x64-musl": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@ff-labs/fff-bin-linux-x64-musl/-/fff-bin-linux-x64-musl-0.11.0.tgz", + "integrity": "sha512-UjqEBtZphjH6MTK18kTlA+5ccUAu3PBATerAKh9otEWbLCwqpFV0ke8LON2+UavaO5+VhBUCk7Zi97AOQhn/9Q==", + "cpu": [ + "x64" + ], + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@ff-labs/fff-bin-win32-arm64": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@ff-labs/fff-bin-win32-arm64/-/fff-bin-win32-arm64-0.11.0.tgz", + "integrity": "sha512-IF54PgYYi+AsCGseNG5kYpMqkwTmp/9bB8zvndp6tXZp4xLQ4G6x/NgHgM4vyK85Sv3FWr6Sf4OZQhP4mSSipA==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@ff-labs/fff-bin-win32-x64": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@ff-labs/fff-bin-win32-x64/-/fff-bin-win32-x64-0.11.0.tgz", + "integrity": "sha512-NFnFcueeRZ+QHvBg/k3KhduH20zFRCGqPHqjslk/3H0CHOMyP5AMTbscNwn5TZUhMutIRCfFzVI7mm+oU8jvCQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@ff-labs/fff-bun": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@ff-labs/fff-bun/-/fff-bun-0.11.0.tgz", + "integrity": "sha512-IWN7pKGcYYX/g0KxZkPp2fuLrLydbKstnFswb1RfRxr0lXaw7WBchefMKUFvpfbxCWOAi3sUXHIlbfDA/Vpo4Q==", + "cpu": [ + "x64", + "arm64" + ], + "license": "MIT", + "os": [ + "darwin", + "linux", + "win32", + "android" + ], + "engines": { + "bun": ">=1.0.0" + }, + "optionalDependencies": { + "@ff-labs/fff-bin-android-arm64": "0.11.0", + "@ff-labs/fff-bin-darwin-arm64": "0.11.0", + "@ff-labs/fff-bin-darwin-x64": "0.11.0", + "@ff-labs/fff-bin-linux-arm64-gnu": "0.11.0", + "@ff-labs/fff-bin-linux-arm64-musl": "0.11.0", + "@ff-labs/fff-bin-linux-x64-gnu": "0.11.0", + "@ff-labs/fff-bin-linux-x64-musl": "0.11.0", + "@ff-labs/fff-bin-win32-arm64": "0.11.0", + "@ff-labs/fff-bin-win32-x64": "0.11.0" + } + }, + "node_modules/@ff-labs/fff-node": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@ff-labs/fff-node/-/fff-node-0.11.0.tgz", + "integrity": "sha512-/7fX4kgy28pFZghxuXCAcIPQKb2+VqVirpFcDqMKgrFLTz56tVzHjOkFSdKGq7fa6wRb6eS5Dg9SaX1qyCcKxQ==", + "cpu": [ + "x64", + "arm64" + ], + "license": "MIT", + "os": [ + "darwin", + "linux", + "win32", + "android" + ], + "dependencies": { + "ffi-rs": "^1.0.0" + }, + "engines": { + "node": ">=18.0.0" + }, + "optionalDependencies": { + "@ff-labs/fff-bin-android-arm64": "0.11.0", + "@ff-labs/fff-bin-darwin-arm64": "0.11.0", + "@ff-labs/fff-bin-darwin-x64": "0.11.0", + "@ff-labs/fff-bin-linux-arm64-gnu": "0.11.0", + "@ff-labs/fff-bin-linux-arm64-musl": "0.11.0", + "@ff-labs/fff-bin-linux-x64-gnu": "0.11.0", + "@ff-labs/fff-bin-linux-x64-musl": "0.11.0", + "@ff-labs/fff-bin-win32-arm64": "0.11.0", + "@ff-labs/fff-bin-win32-x64": "0.11.0" + } + }, + "node_modules/@ff-labs/pi-fff": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@ff-labs/pi-fff/-/pi-fff-0.11.0.tgz", + "integrity": "sha512-RNYBSnmRaGxYF9/R5KO4Uq0q1Prtbe6CmltK7i3efD0+JEwR2h69sL+p6UIXNDrVANSXEWM8ehagQefbskoGwg==", + "license": "MIT", + "dependencies": { + "@ff-labs/fff-bun": "0.11.0", + "@ff-labs/fff-node": "0.11.0" + }, + "peerDependencies": { + "@earendil-works/pi-coding-agent": "*", + "@earendil-works/pi-tui": "*", + "@sinclair/typebox": "*" + } + }, + "node_modules/@google/genai": { + "version": "2.21.0", + "resolved": "https://registry.npmjs.org/@google/genai/-/genai-2.21.0.tgz", + "integrity": "sha512-+PDtco2/Z0ONdzCGekCoCT+O1VJS9xJQNN4XzQpXG/t3El/SWWMkCWlFRO1KmivOHPa4Q0VjUYu1HBKCZ/v33Q==", + "hasInstallScript": true, + "license": "Apache-2.0", + "dependencies": { + "google-auth-library": "^10.3.0", + "p-retry": "^4.6.2", + "protobufjs": "^7.5.4", + "ws": "^8.18.0" + }, + "engines": { + "node": ">=20.0.0" + }, + "peerDependencies": { + "@modelcontextprotocol/sdk": "^1.25.2" + }, + "peerDependenciesMeta": { + "@modelcontextprotocol/sdk": { + "optional": true + } + } + }, + "node_modules/@iarna/toml": { + "version": "2.2.5", + "resolved": "https://registry.npmjs.org/@iarna/toml/-/toml-2.2.5.tgz", + "integrity": "sha512-trnsAYxU3xnS1gPHPyU961coFyLkh4gAD/0zQ5mymY4yOZ+CYvsPqUbOFSw0aDM4y0tV7tiFxL/1XfXPNC6IPg==", + "license": "ISC" + }, + "node_modules/@modelcontextprotocol/client": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/client/-/client-2.3.1.tgz", + "integrity": "sha512-mIGZXpHsjnZ6lD+gD/WCMpR5k8yVQQ8nNFH1N0Srf7AvnwTUMYD6pvTY8ng2+He5FfV7YMZLmrjL7cLa/cc3dQ==", + "license": "Apache-2.0", + "dependencies": { + "@modelcontextprotocol/core": "2.3.1", + "cross-spawn": "^7.0.5", + "eventsource": "^3.0.2", + "eventsource-parser": "^3.0.8", + "jose": "^6.1.3", + "pkce-challenge": "^5.0.0", + "zod": "^4.2.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@modelcontextprotocol/core": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/core/-/core-2.3.1.tgz", + "integrity": "sha512-laVmIhPGpWi7rG9q+0UigblRN0Hws/Yjlb6qLFtVqryXVLkc4h+yN8z731POD2LnAGQlFe7/tXhUm7Bi0YB91g==", + "license": "Apache-2.0", + "dependencies": { + "zod": "^4.2.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@modelcontextprotocol/server": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/server/-/server-2.3.1.tgz", + "integrity": "sha512-e59MfWuSssj6DoQ96JCTqdW1AXT5/XtnTl0WWd6MU1Ka434fFUGGosCLJbGNySDhHGvxQWoRWK137FXYFkYNWw==", + "license": "Apache-2.0", + "dependencies": { + "@modelcontextprotocol/core": "2.3.1", + "zod": "^4.2.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@oxc-project/types": { + "version": "0.150.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.150.0.tgz", + "integrity": "sha512-rDS5/31E9HfPl/CIzGrn0DOlvBbXFseQ5URJ9sYMfstbKLD/c6Gm9vmRzRGDdAXyOIL4zmO37lc9RIwYqVruZw==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/oxc-project" + } + }, + "node_modules/@protobufjs/aspromise": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz", + "integrity": "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/base64": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz", + "integrity": "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/codegen": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@protobufjs/codegen/-/codegen-2.0.5.tgz", + "integrity": "sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/eventemitter": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.1.tgz", + "integrity": "sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/fetch": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.1.tgz", + "integrity": "sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw==", + "license": "BSD-3-Clause", + "dependencies": { + "@protobufjs/aspromise": "^1.1.1" + } + }, + "node_modules/@protobufjs/float": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@protobufjs/float/-/float-1.0.2.tgz", + "integrity": "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/path": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz", + "integrity": "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/pool": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/pool/-/pool-1.1.0.tgz", + "integrity": "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/utf8": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.2.tgz", + "integrity": "sha512-b1UQwcEZ4yCnMCD8DAL1VlbvBJE9/IX4FTIp7BG1xYpf29SLazLSrqUkj4w7Y5y7cCVP6E5tcqqcI0xemPkHug==", + "license": "BSD-3-Clause" + }, + "node_modules/@rolldown/binding-android-arm-eabi": { + "version": "1.2.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.9.tgz", + "integrity": "sha512-tNISae1QEf/vkb3xkRcjV5SEdzPE97We5IVaa2Z8jSszQPZ8U60B/YCYpw4QI7VidYsBtKavczXf+DyDs9WGxw==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.2.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.9.tgz", + "integrity": "sha512-YC8YsI30o606GTZi0VyzYlsDKFP8W61i/QzayHDkLbNEz/IShqAmTa+hsJRj13xTHA0H+6fk4b2UmGn+Q/cMlg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-arm64": { + "version": "1.2.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.9.tgz", + "integrity": "sha512-IwhlH3qK5urrY8hZiEgGkHKEFN901p/p2bjxCxJlr4GyNnF7wYpUvK+Y43uaRYuC4hpfjzbR3SJC3arX1jGvmw==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-x64": { + "version": "1.2.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.9.tgz", + "integrity": "sha512-XxpJfVzFh+jilRxIXUqcfYAYcunIc/XEzIizsOL1fcJee5Sf7H3mH8WlLmfHfluz5amqR88QQo9izKtmMlavAw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-freebsd-x64": { + "version": "1.2.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.9.tgz", + "integrity": "sha512-kSfvhmgeWyfkbT3p/1s5vSgboogoah2zkm9fX2zjg2hHxSV7T4KhMWRUUaRk4OXNqoD3QAUeRqLcs1aZOK4U1g==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm-gnueabihf": { + "version": "1.2.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.9.tgz", + "integrity": "sha512-1RVzG17pxqbTfYLC352JlLt6kKLG+6Hr30n8DlIJqsnV5luUDd2Qdx9Ayw1Cabfyb1K9k0jXEZ7evxkRoT+uiw==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-gnu": { + "version": "1.2.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.9.tgz", + "integrity": "sha512-BXqPvZ2drqVD+/Z8UpKwcs4Mp7grM+eGFku4CAEKrEtcbAsUpzREphK1sogCRZGreVPiMkiiBtw0n3TPteuqvw==", + "cpu": [ + "arm64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-musl": { + "version": "1.2.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.9.tgz", + "integrity": "sha512-11vWvo8YDwLzukt27J3aYDWU+gg2P7J+ZOmiJ0hkF5BXZDW7pVya7r40MXDy6ya0i9KamoENSVKIugvJNgFXIA==", + "cpu": [ + "arm64" + ], + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.2.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.9.tgz", + "integrity": "sha512-a1tijMkdwsIARtc0F39ApURROkf3NwqinI6TOiSSWCTR7dT96dffNvMUtDHnq64wKNTIZOIlzKrFvvFUznJiyw==", + "cpu": [ + "ppc64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.2.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.9.tgz", + "integrity": "sha512-x6SQNdAvv4c3hWqTMaWuawzMX9myaCs/yEmlGsxJzkdClnHW7FbrjQuSiRDhuSYzEYoEMhsaJy9qHG/XNemJPQ==", + "cpu": [ + "s390x" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.2.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.9.tgz", + "integrity": "sha512-9s0AZ8BFK5/n7B/TBoa2yJE3gI3KURrbXcPBlsAsvjU4VeJKgE90y1YtNxyEUIcHPQkg6/yfF3qihUrcM/Kf0Q==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.2.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.9.tgz", + "integrity": "sha512-P7VWAmV+WdJluH7ovnRGoiv2i8To7GAZ+kGzfGup635cyL7SyYl3lSUaA3Gp5THf0n/Co5EyEqb2zbqq+nMOHQ==", + "cpu": [ + "x64" + ], + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.2.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.9.tgz", + "integrity": "sha512-1qixtsE4BK8h+yS3BfmZ09UhA7O/N4IACva6YBr7EBvCJraByTuRcgOTaiA62Tm0vey3UcKXLOaoGHtYmNGEVg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.2.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.9.tgz", + "integrity": "sha512-ok8IQjcEPs1AKZfuEUznVBrJw+gK4soq+bx8b1X2XoMqVClarc1q5JDmVtWXY1xfr6ZuHTAsPXHTgTrqKTZeww==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.2.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.9.tgz", + "integrity": "sha512-Ip2mXoU0hM0boq3Rf+ekuT653OROSo6aSYcPT1VHE4q52KvyxgFkQgrgb/IEsxOuvQ2fZZbs8khJAyCEPM24/g==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", + "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", + "license": "MIT" + }, + "node_modules/@silvia-odwyer/photon-node": { + "version": "0.3.4", + "resolved": "https://registry.npmjs.org/@silvia-odwyer/photon-node/-/photon-node-0.3.4.tgz", + "integrity": "sha512-bnly4BKB3KDTFxrUIcgCLbaeVVS8lrAkri1pEzskpmxu9MdfGQTy8b8EgcD83ywD3RPMsIulY8xJH5Awa+t9fA==", + "license": "Apache-2.0" + }, + "node_modules/@sinclair/typebox": { + "version": "0.34.52", + "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.34.52.tgz", + "integrity": "sha512-XiMQh7qqVlxZzcVD+kkGMNGMzcTrDMLWI7S4x7z1MkCkbDPrekpZXEUK0eZqZFMuHQg2a2DZOcDIh9o5v3Gonw==", + "license": "MIT", + "peer": true + }, + "node_modules/@smithy/core": { + "version": "3.35.2", + "resolved": "https://registry.npmjs.org/@smithy/core/-/core-3.35.2.tgz", + "integrity": "sha512-ejTukBuP/Pg3t9N8Ux+0zKsXeHWm7p6W3HbXFOyltKasSxZwCFmvTut7kBdZSCF3m9y1bXXyVu6p2xuMFcsTyQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.19.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/credential-provider-imds": { + "version": "4.5.2", + "resolved": "https://registry.npmjs.org/@smithy/credential-provider-imds/-/credential-provider-imds-4.5.2.tgz", + "integrity": "sha512-A9uSdn72ozbRUSit0eib0TW7nXuNPlaeM0zcGkJ+nE6tFcSDbnmtwoxbTCFBukVQcszDAyvsd7+rTduPTXpygg==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/core": "^3.33.2", + "@smithy/types": "^4.17.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/fetch-http-handler": { + "version": "5.8.0", + "resolved": "https://registry.npmjs.org/@smithy/fetch-http-handler/-/fetch-http-handler-5.8.0.tgz", + "integrity": "sha512-ycSJu3tFAQ4v04CBB0agqFMVsSQ1iG3yw+SpgxRqKfaURpQD4CZ8Wn0zPMmSnOuTpTh65Vz+EA0rMrw089wvkA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/core": "^3.33.3", + "@smithy/types": "^4.18.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/node-http-handler": { + "version": "4.12.1", + "resolved": "https://registry.npmjs.org/@smithy/node-http-handler/-/node-http-handler-4.12.1.tgz", + "integrity": "sha512-ThMkboGeONWXAelq9FvGsuJC4rOi+qyC4/zhUF58xYpxUg5sQKx2VXZYJmtNjr4dSuBJ1HeJXETQILCz3wOHvw==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/core": "^3.33.3", + "@smithy/types": "^4.18.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/signature-v4": { + "version": "5.7.4", + "resolved": "https://registry.npmjs.org/@smithy/signature-v4/-/signature-v4-5.7.4.tgz", + "integrity": "sha512-tHy0K0VtqNd5Y7Y41h0a0Lhh0L1GzC08dTWg0F7vRJWFtTENg7IZikf3wQkanYIRdb7ngoIPMTmqgUi401fEeQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/core": "^3.35.0", + "@smithy/types": "^4.19.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/types": { + "version": "4.19.0", + "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.19.0.tgz", + "integrity": "sha512-r7jh49VJxGerfAcTQA6gXcKc+98zOp/tqRwzYjgOE+iSQsP6cEU1hq2QzbuipmP68QtYdY9wKEhiCQZIzHgZ4Q==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@stablelib/base64": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@stablelib/base64/-/base64-1.0.1.tgz", + "integrity": "sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==", + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "26.6.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.5.tgz", + "integrity": "sha512-uMzsv9stDdofIZBx4UGh4Z9ZgXnGC9seRDscilBcTHAeOFk67MZg/k9bWVfO+bk4qZmG+l52hRnLwUiH2LnJTg==", + "license": "MIT", + "dependencies": { + "undici-types": "~8.9.0" + } + }, + "node_modules/@types/retry": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/@types/retry/-/retry-0.12.0.tgz", + "integrity": "sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA==", + "license": "MIT" + }, + "node_modules/@upstash/context7-pi": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/@upstash/context7-pi/-/context7-pi-0.1.2.tgz", + "integrity": "sha512-uxYqDF/A32nuKJBeUCWuBQqLmRJJ3eUI6zsM7TPEds7KUK/a/PdicEZRC2ja/b1Zl1uhjbyLWmQynQC4cID+Zg==", + "license": "MIT", + "peerDependencies": { + "@earendil-works/pi-coding-agent": "*", + "typebox": "*" + } + }, + "node_modules/@yuuang/ffi-rs-android-arm64": { + "version": "1.3.7", + "resolved": "https://registry.npmjs.org/@yuuang/ffi-rs-android-arm64/-/ffi-rs-android-arm64-1.3.7.tgz", + "integrity": "sha512-t6Wx3Xll6c07Nuk0k3xnZsxKFxlshm92i0U/BiTHc6kQbvu+fMJF+gKsj4yEj886jH51CM3EqZT9Xdhq9CdUVw==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12" + } + }, + "node_modules/@yuuang/ffi-rs-darwin-arm64": { + "version": "1.3.7", + "resolved": "https://registry.npmjs.org/@yuuang/ffi-rs-darwin-arm64/-/ffi-rs-darwin-arm64-1.3.7.tgz", + "integrity": "sha512-OueBlUFBT9IwD9pQnoYs0UszRBEySskfrEPXXfvKfGjL/DXnfn6kUheQ3oIP6sSmshVGNQUwrTCPo6feAa4QjA==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12" + } + }, + "node_modules/@yuuang/ffi-rs-darwin-x64": { + "version": "1.3.7", + "resolved": "https://registry.npmjs.org/@yuuang/ffi-rs-darwin-x64/-/ffi-rs-darwin-x64-1.3.7.tgz", + "integrity": "sha512-x4mxXOKwSgwYx6OBAKrW+Ocp8um2KoPpUwaD0Z2tmR6EekoRvFGN7s/eEK1avqCxcsLN7/MzGOnCCFyGpOVfPA==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12" + } + }, + "node_modules/@yuuang/ffi-rs-linux-arm-gnueabihf": { + "version": "1.3.7", + "resolved": "https://registry.npmjs.org/@yuuang/ffi-rs-linux-arm-gnueabihf/-/ffi-rs-linux-arm-gnueabihf-1.3.7.tgz", + "integrity": "sha512-9r//Z022QYVoIAY458Dpk8HWkisk/y4NJC3d52RlkdsLD+9p0zn0cKKSoMF/xUsOWDFSmOf+cwU/Xadi/wxFMQ==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12" + } + }, + "node_modules/@yuuang/ffi-rs-linux-arm64-gnu": { + "version": "1.3.7", + "resolved": "https://registry.npmjs.org/@yuuang/ffi-rs-linux-arm64-gnu/-/ffi-rs-linux-arm64-gnu-1.3.7.tgz", + "integrity": "sha512-nrW4MlFlyQInfxTsI5wtcIpbV4KlHLWo2BCk4CHIETlUT+PUspNFqDg+Byy7My3hpCZlXp0WsMVP/3N0LlybNw==", + "cpu": [ + "arm64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12" + } + }, + "node_modules/@yuuang/ffi-rs-linux-arm64-musl": { + "version": "1.3.7", + "resolved": "https://registry.npmjs.org/@yuuang/ffi-rs-linux-arm64-musl/-/ffi-rs-linux-arm64-musl-1.3.7.tgz", + "integrity": "sha512-eLLx4P8DzNnuPif19nAvKPaf88lSf6KFbDetH3nAIRZvI495h0jigN835Ayr7uAADssohGfO9MPMH33DXmFErA==", + "cpu": [ + "arm64" + ], + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12" + } + }, + "node_modules/@yuuang/ffi-rs-linux-x64-gnu": { + "version": "1.3.7", + "resolved": "https://registry.npmjs.org/@yuuang/ffi-rs-linux-x64-gnu/-/ffi-rs-linux-x64-gnu-1.3.7.tgz", + "integrity": "sha512-upEz1Q98T51x2In872fsjgHCJbE3e8r9JxhJD+5NvSMk6BpieYWRodTbsMxV6oKWmfl12loKwF2j4OBSWKl0lA==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12" + } + }, + "node_modules/@yuuang/ffi-rs-linux-x64-musl": { + "version": "1.3.7", + "resolved": "https://registry.npmjs.org/@yuuang/ffi-rs-linux-x64-musl/-/ffi-rs-linux-x64-musl-1.3.7.tgz", + "integrity": "sha512-YOcOkIwVvIhpwuGJ428h15vpE0KnT3teFG0g2J31FrBxrVh9IH4HeTGXjelI3l9SI5gyiZDnD4PQnQ1U6oqTcA==", + "cpu": [ + "x64" + ], + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12" + } + }, + "node_modules/@yuuang/ffi-rs-win32-arm64-msvc": { + "version": "1.3.7", + "resolved": "https://registry.npmjs.org/@yuuang/ffi-rs-win32-arm64-msvc/-/ffi-rs-win32-arm64-msvc-1.3.7.tgz", + "integrity": "sha512-ZfYzLV1w7Mhzh9XRScEMpw9oazIEiwO+0+TYHHRL882d5oD0Q99YikmRhdifsoHCCQefKmWF/4BXCeFkzg8NFA==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12" + } + }, + "node_modules/@yuuang/ffi-rs-win32-ia32-msvc": { + "version": "1.3.7", + "resolved": "https://registry.npmjs.org/@yuuang/ffi-rs-win32-ia32-msvc/-/ffi-rs-win32-ia32-msvc-1.3.7.tgz", + "integrity": "sha512-ifYz+f+giKpT39lKWDru+om6QnA9J7J953ns60xHgB46ESZvPd/Y2W5+PesRNC9U+vnFEiLZ9CNC+R3fBWC1pg==", + "cpu": [ + "x64", + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12" + } + }, + "node_modules/@yuuang/ffi-rs-win32-x64-msvc": { + "version": "1.3.7", + "resolved": "https://registry.npmjs.org/@yuuang/ffi-rs-win32-x64-msvc/-/ffi-rs-win32-x64-msvc-1.3.7.tgz", + "integrity": "sha512-H3s4wOLtZtKtmuPjUNE+bhnSKxxpXcuxG70jRC8dUMHqIm5iCvdoZ4XYDeq7/uUYlySerXFmRL4dAVCX/TUNTg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12" + } + }, + "node_modules/acorn": { + "version": "8.19.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.19.0.tgz", + "integrity": "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw==", + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/agent-base": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-9.0.0.tgz", + "integrity": "sha512-TQf59BsZnytt8GdJKLPfUZ54g/iaUL2OWDSFCCvMOhsHduDQxO8xC4PNeyIkVcA5KwL2phPSv0douC0fgWzmnA==", + "license": "MIT", + "engines": { + "node": ">= 20" + } + }, + "node_modules/ansi-regex": { + "version": "6.4.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.4.0.tgz", + "integrity": "sha512-KzTVk2tCWAHtYrvvvaP8bJKJq2pVinhLcGEQdtLIYPbmNGNyYe8QwNaTUYQp2J7/vIsUKt5QCqAfUkYyG9DkOw==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/bignumber.js": { + "version": "9.3.1", + "resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.3.1.tgz", + "integrity": "sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ==", + "license": "MIT", + "engines": { + "node": "*" + } + }, + "node_modules/bowser": { + "version": "2.14.1", + "resolved": "https://registry.npmjs.org/bowser/-/bowser-2.14.1.tgz", + "integrity": "sha512-tzPjzCxygAKWFOJP011oxFHs57HzIhOEracIgAePE4pqB3LikALKnSzUyU4MGs9/iCEUuHlAJTjTc5M+u7YEGg==", + "license": "MIT" + }, + "node_modules/brace-expansion": { + "version": "5.0.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", + "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/buffer-equal-constant-time": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", + "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==", + "license": "BSD-3-Clause" + }, + "node_modules/chalk": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-6.0.0.tgz", + "integrity": "sha512-2uNTXIuTTxk7ciZgAU1BQcgnchcG0xXnrs6jzkQfj9SsRa9M2s5zE8WT96hS6KmG4MzWHSrvH43DF1m4XRkrFg==", + "license": "MIT", + "engines": { + "node": ">=22" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/cli-cursor": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-5.0.0.tgz", + "integrity": "sha512-aCj4O5wKyszjMmDT4tZj93kxyydN/K5zPWSCe6/0AV/AA1pqe5ZBIw0a2ZfPQV7lL5/yb5HsUreJ6UFAF1tEQw==", + "license": "MIT", + "dependencies": { + "restore-cursor": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cli-spinners": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/cli-spinners/-/cli-spinners-3.4.0.tgz", + "integrity": "sha512-bXfOC4QcT1tKXGorxL3wbJm6XJPDqEnij2gQ2m7ESQuE+/z9YFIWnl/5RpTiKWbMq3EVKR4fRLJGn6DVfu0mpw==", + "license": "MIT", + "engines": { + "node": ">=18.20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/commander": { + "version": "15.0.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-15.0.0.tgz", + "integrity": "sha512-z67u4ZhzCL/Tydu1lJARtEZYWbWaN7oYLHbsuzocr6y4N6WZAagG3RQ4FW61V1/0+jImpj293XfrcYnd1qxtPg==", + "license": "MIT", + "engines": { + "node": ">=22.12.0" + } + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/data-uri-to-buffer": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz", + "integrity": "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==", + "license": "MIT", + "engines": { + "node": ">= 12" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/diff": { + "version": "8.0.4", + "resolved": "https://registry.npmjs.org/diff/-/diff-8.0.4.tgz", + "integrity": "sha512-DPi0FmjiSU5EvQV0++GFDOJ9ASQUVFh5kD+OzOnYdi7n3Wpm9hWWGfB/O2blfHcMVTL5WkQXSnRiK9makhrcnw==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.3.1" + } + }, + "node_modules/ecdsa-sig-formatter": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", + "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", + "license": "Apache-2.0", + "dependencies": { + "safe-buffer": "^5.0.1" + } + }, + "node_modules/es-toolkit": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.52.0.tgz", + "integrity": "sha512-XTNEJQh1tY1ZJVcf6ayP/2n4ZPyaHlW2FWs7xvw5ddPuhUVjLD3olQVQS7kf58JbAB48iL0uL/jerTrjtV3lDA==", + "license": "MIT", + "workspaces": [ + "docs", + "benchmarks", + "tests/types", + "tests/browser-compat" + ] + }, + "node_modules/esbuild": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", + "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==", + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.2", + "@esbuild/android-arm": "0.28.2", + "@esbuild/android-arm64": "0.28.2", + "@esbuild/android-x64": "0.28.2", + "@esbuild/darwin-arm64": "0.28.2", + "@esbuild/darwin-x64": "0.28.2", + "@esbuild/freebsd-arm64": "0.28.2", + "@esbuild/freebsd-x64": "0.28.2", + "@esbuild/linux-arm": "0.28.2", + "@esbuild/linux-arm64": "0.28.2", + "@esbuild/linux-ia32": "0.28.2", + "@esbuild/linux-loong64": "0.28.2", + "@esbuild/linux-mips64el": "0.28.2", + "@esbuild/linux-ppc64": "0.28.2", + "@esbuild/linux-riscv64": "0.28.2", + "@esbuild/linux-s390x": "0.28.2", + "@esbuild/linux-x64": "0.28.2", + "@esbuild/netbsd-arm64": "0.28.2", + "@esbuild/netbsd-x64": "0.28.2", + "@esbuild/openbsd-arm64": "0.28.2", + "@esbuild/openbsd-x64": "0.28.2", + "@esbuild/openharmony-arm64": "0.28.2", + "@esbuild/sunos-x64": "0.28.2", + "@esbuild/win32-arm64": "0.28.2", + "@esbuild/win32-ia32": "0.28.2", + "@esbuild/win32-x64": "0.28.2" + } + }, + "node_modules/eventsource": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz", + "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==", + "license": "MIT", + "dependencies": { + "eventsource-parser": "^3.0.1" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/eventsource-parser": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.1.1.tgz", + "integrity": "sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/extend": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", + "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", + "license": "MIT" + }, + "node_modules/fast-sha256": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/fast-sha256/-/fast-sha256-1.3.0.tgz", + "integrity": "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==", + "license": "Unlicense" + }, + "node_modules/fetch-blob": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz", + "integrity": "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "paypal", + "url": "https://paypal.me/jimmywarting" + } + ], + "license": "MIT", + "dependencies": { + "node-domexception": "^1.0.0", + "web-streams-polyfill": "^3.0.3" + }, + "engines": { + "node": "^12.20 || >= 14.13" + } + }, + "node_modules/ffi-rs": { + "version": "1.3.7", + "resolved": "https://registry.npmjs.org/ffi-rs/-/ffi-rs-1.3.7.tgz", + "integrity": "sha512-5MMZQS2t/6f/ec3sx0f51gBcKGZPGfolPAW04lvLOSYnr7gmOKs8YzH1Rh+34WGO+VtcgcTuxaUUoJLcR4Tirg==", + "license": "MIT", + "optionalDependencies": { + "@yuuang/ffi-rs-android-arm64": "1.3.7", + "@yuuang/ffi-rs-darwin-arm64": "1.3.7", + "@yuuang/ffi-rs-darwin-x64": "1.3.7", + "@yuuang/ffi-rs-linux-arm-gnueabihf": "1.3.7", + "@yuuang/ffi-rs-linux-arm64-gnu": "1.3.7", + "@yuuang/ffi-rs-linux-arm64-musl": "1.3.7", + "@yuuang/ffi-rs-linux-x64-gnu": "1.3.7", + "@yuuang/ffi-rs-linux-x64-musl": "1.3.7", + "@yuuang/ffi-rs-win32-arm64-msvc": "1.3.7", + "@yuuang/ffi-rs-win32-ia32-msvc": "1.3.7", + "@yuuang/ffi-rs-win32-x64-msvc": "1.3.7" + } + }, + "node_modules/formdata-polyfill": { + "version": "4.0.10", + "resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz", + "integrity": "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==", + "license": "MIT", + "dependencies": { + "fetch-blob": "^3.1.2" + }, + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/gaxios": { + "version": "7.3.1", + "resolved": "https://registry.npmjs.org/gaxios/-/gaxios-7.3.1.tgz", + "integrity": "sha512-kB3rzJV7d9juLZh8/56QTXCwQfxyhdOMdyYk1HdQKFtF8TJTDTZQJtixWIwXdE9Jji91mC41DUNpjleo4L4eAQ==", + "license": "Apache-2.0", + "dependencies": { + "extend": "^3.0.2", + "https-proxy-agent": "^7.0.1", + "node-fetch": "^3.3.2" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/gaxios/node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/gaxios/node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/gcp-metadata": { + "version": "8.1.2", + "resolved": "https://registry.npmjs.org/gcp-metadata/-/gcp-metadata-8.1.2.tgz", + "integrity": "sha512-zV/5HKTfCeKWnxG0Dmrw51hEWFGfcF2xiXqcA3+J90WDuP0SvoiSO5ORvcBsifmx/FoIjgQN3oNOGaQ5PhLFkg==", + "license": "Apache-2.0", + "dependencies": { + "gaxios": "^7.0.0", + "google-logging-utils": "^1.0.0", + "json-bigint": "^1.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/get-east-asian-width": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.6.0.tgz", + "integrity": "sha512-QRbvDIbx6YklUe6RxeTeleMR0yv3cYH6PsPZHcnVn7xv7zO1BHN8r0XETu8n6Ye3Q+ahtSarc3WgtNWmehIBfA==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/google-auth-library": { + "version": "10.9.1", + "resolved": "https://registry.npmjs.org/google-auth-library/-/google-auth-library-10.9.1.tgz", + "integrity": "sha512-i1ydyHrqcIxXkWh/uBmVkzCvIuq5yiK2ATndIe5XxKholrG/MTYP9xGYka4sQhrbIAgGjL2B6NOE7rFaiF3fXw==", + "license": "Apache-2.0", + "dependencies": { + "base64-js": "^1.3.0", + "ecdsa-sig-formatter": "^1.0.11", + "gaxios": "^7.1.4", + "gcp-metadata": "8.1.2", + "google-logging-utils": "1.1.3", + "jws": "^4.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/google-logging-utils": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/google-logging-utils/-/google-logging-utils-1.1.3.tgz", + "integrity": "sha512-eAmLkjDjAFCVXg7A1unxHsLf961m6y17QFqXqAXGj/gVkKFrEICfStRfwUlGNfeCEjNRa32JEWOUTlYXPyyKvA==", + "license": "Apache-2.0", + "engines": { + "node": ">=14" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", + "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", + "license": "ISC" + }, + "node_modules/grok-mermaid": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/grok-mermaid/-/grok-mermaid-0.2.3.tgz", + "integrity": "sha512-/4KopAbsjvuRP9MdPtlDjOHUmUVEohOX73JNcsWpzAtFxh+bq5+Dhb6gzvRieLDwIPQIR3/vy8V1NNTuz4Zsmg==", + "license": "Apache-2.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/highlight.js": { + "version": "10.7.3", + "resolved": "https://registry.npmjs.org/highlight.js/-/highlight.js-10.7.3.tgz", + "integrity": "sha512-tzcUFauisWKNHaRkN4Wjl/ZA07gENAjFl3J/c480dprkGTg5EQstgaNFqBfUqCq54kZRIEcreTsAgF/m2quD7A==", + "license": "BSD-3-Clause", + "engines": { + "node": "*" + } + }, + "node_modules/hosted-git-info": { + "version": "9.0.3", + "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-9.0.3.tgz", + "integrity": "sha512-Hc+ghLoSt6QaYZUv0WBiIvmMDZuZZ7oaDvdH8MbfOO4lOsxdXLEvuC6ePoGs9H1X9oCLyq6+NVN0MKqD+ydxyg==", + "license": "ISC", + "dependencies": { + "lru-cache": "^11.1.0" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/http-proxy-agent": { + "version": "9.1.0", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-9.1.0.tgz", + "integrity": "sha512-2NxoveTT58mjYT4n3RPTEfCZGLMbidoO8XEieXfpSYxu+PQJ1qpx4ypwH6N+uF9twBPIvRRgvkvW5HUTYWENig==", + "license": "MIT", + "dependencies": { + "agent-base": "9.0.0", + "debug": "^4.3.4", + "proxy-agent-negotiate": "1.1.0" + }, + "engines": { + "node": ">= 20" + } + }, + "node_modules/https-proxy-agent": { + "version": "9.1.0", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-9.1.0.tgz", + "integrity": "sha512-ag87y7cJJ9/3+GxFr8Oy4O5faDsGRGnBGsJj/YjOSsSx/5eadKLYTMPlzuR6obgoCDDm0abAAZitXXQkMOPSpA==", + "license": "MIT", + "dependencies": { + "agent-base": "9.0.0", + "debug": "^4.3.4", + "proxy-agent-negotiate": "1.1.0" + }, + "engines": { + "node": ">= 20" + } + }, + "node_modules/ignore": { + "version": "7.0.8", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.8.tgz", + "integrity": "sha512-YYNsSlXBjMk92SKnkwvB5LOVSa6OznlFUGcsvrFgNJbJCd0M1XKeFVRc8ZByeCqz32FivYNHJVooLmdqrmvp/Q==", + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/is-interactive": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-interactive/-/is-interactive-2.0.0.tgz", + "integrity": "sha512-qP1vozQRI+BMOPcjFzrjXuQvdak2pHNUMZoeG2eRbiSqyvbEf/wQtEOTOX1guk6E3t36RkaqiSt8A/6YElNxLQ==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-unicode-supported": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-2.1.0.tgz", + "integrity": "sha512-mE00Gnza5EEB3Ds0HfMyllZzbBrmLOX3vfWoj9A9PEnTfratQ/BcaJOuMhnkhjXvb2+FkY3VuHqtAGpTPmglFQ==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "license": "ISC" + }, + "node_modules/jiti": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz", + "integrity": "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==", + "license": "MIT", + "bin": { + "jiti": "lib/jiti-cli.mjs" + } + }, + "node_modules/jose": { + "version": "6.2.12", + "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.12.tgz", + "integrity": "sha512-9NiFmJEex0sy2Dk58j2UGBSHgUs2ypF9eZSu4L6vjOX3Dp96Sw1F3uL+H+D1sx02jZZdzUT0HgvCy59CuvXcWw==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, + "node_modules/json-bigint": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-bigint/-/json-bigint-1.0.0.tgz", + "integrity": "sha512-SiPv/8VpZuWbvLSMtTDU8hEfrZWg/mH/nV/b4o0CYbSxu1UIQPLdwKOCIyLQX+VIPO5vrLX3i8qtqFyhdPSUSQ==", + "license": "MIT", + "dependencies": { + "bignumber.js": "^9.0.0" + } + }, + "node_modules/json-schema-to-ts": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/json-schema-to-ts/-/json-schema-to-ts-3.1.1.tgz", + "integrity": "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.18.3", + "ts-algebra": "^2.0.0" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/jsonc-parser": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/jsonc-parser/-/jsonc-parser-3.3.1.tgz", + "integrity": "sha512-HUgH65KyejrUFPvHFPbqOY0rsFip3Bo5wb4ngvdi1EpCYWUQDC5V+Y7mZws+DLkr4M//zQJoanu1SP+87Dv1oQ==", + "license": "MIT" + }, + "node_modules/jwa": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz", + "integrity": "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==", + "license": "MIT", + "dependencies": { + "buffer-equal-constant-time": "^1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/jws": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/jws/-/jws-4.0.1.tgz", + "integrity": "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==", + "license": "MIT", + "dependencies": { + "jwa": "^2.0.1", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/log-symbols": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-7.0.1.tgz", + "integrity": "sha512-ja1E3yCr9i/0hmBVaM0bfwDjnGy8I/s6PP4DFp+yP+a+mrHO4Rm7DtmnqROTUkHIkqffC84YY7AeqX6oFk0WFg==", + "license": "MIT", + "dependencies": { + "is-unicode-supported": "^2.0.0", + "yoctocolors": "^2.1.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/long": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz", + "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==", + "license": "Apache-2.0" + }, + "node_modules/lru-cache": { + "version": "11.5.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", + "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/marked": { + "version": "18.0.11", + "resolved": "https://registry.npmjs.org/marked/-/marked-18.0.11.tgz", + "integrity": "sha512-HnslJfsZkRPBDJRHvVtAaWlZHEpSu7u8LgQuJCELjRKuWR+hpq4A7sLq3p8HaI9ypVoXDXxV34CsQJEe1+J5Aw==", + "license": "MIT", + "bin": { + "marked": "bin/marked.js" + }, + "engines": { + "node": ">= 20" + } + }, + "node_modules/mcporter": { + "version": "0.14.0", + "resolved": "https://registry.npmjs.org/mcporter/-/mcporter-0.14.0.tgz", + "integrity": "sha512-R60nKyUcW65WawhVjoESC0HeNibsf+1iqpX0wHPX9P60AFX/DYCBlhS7pDYcuWzeGYqYfZG2Xf5jWWkM74d/+A==", + "license": "MIT", + "dependencies": { + "@iarna/toml": "^2.2.5", + "@modelcontextprotocol/client": "^2.0.0", + "@modelcontextprotocol/server": "^2.0.0", + "acorn": "^8.18.0", + "commander": "^15.0.0", + "es-toolkit": "^1.52.0", + "jsonc-parser": "^3.3.1", + "ora": "^9.4.1", + "rolldown": "1.2.9", + "zod": "^4.6.5" + }, + "bin": { + "mcporter": "dist/cli.js" + }, + "engines": { + "node": ">=24" + } + }, + "node_modules/mimic-function": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/mimic-function/-/mimic-function-5.0.1.tgz", + "integrity": "sha512-VP79XUPxV2CigYP3jWwAUFSku2aKqBH7uTAapFWCBqutsbmDo96KY5o8uh6U+/YSIn5OxJnXp73beVkpqMIGhA==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/minimatch": { + "version": "10.2.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", + "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.8" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/node-domexception": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz", + "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==", + "deprecated": "Use your platform's native DOMException instead", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "github", + "url": "https://paypal.me/jimmywarting" + } + ], + "license": "MIT", + "engines": { + "node": ">=10.5.0" + } + }, + "node_modules/node-fetch": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-3.3.2.tgz", + "integrity": "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==", + "license": "MIT", + "dependencies": { + "data-uri-to-buffer": "^4.0.0", + "fetch-blob": "^3.1.4", + "formdata-polyfill": "^4.0.10" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/node-fetch" + } + }, + "node_modules/onetime": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-7.0.0.tgz", + "integrity": "sha512-VXJjc87FScF88uafS3JllDgvAm+c/Slfz06lorj2uAY34rlUu0Nt+v8wreiImcrgAjjIHp1rXpTDlLOGw29WwQ==", + "license": "MIT", + "dependencies": { + "mimic-function": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/openai": { + "version": "7.19.0", + "resolved": "https://registry.npmjs.org/openai/-/openai-7.19.0.tgz", + "integrity": "sha512-MX2s3u2L5racTO0CC/SWpCOasJQBCJrqLKXK+l82cAhdeF8mPMBEe/gxMm0ZFa2xpKpOFLRjxv5afYEZbBXmbQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=22.0.0" + }, + "peerDependencies": { + "@aws-sdk/credential-provider-node": ">=3.972.0 <4", + "@smithy/hash-node": ">=4.3.0 <5", + "@smithy/signature-v4": ">=5.4.0 <6", + "undici": ">=5 <9", + "ws": "^8.21.0", + "zod": "^3.25 || ^4.0" + }, + "peerDependenciesMeta": { + "@aws-sdk/credential-provider-node": { + "optional": true + }, + "@smithy/hash-node": { + "optional": true + }, + "@smithy/signature-v4": { + "optional": true + }, + "undici": { + "optional": true + }, + "ws": { + "optional": true + }, + "zod": { + "optional": true + } + } + }, + "node_modules/ora": { + "version": "9.4.1", + "resolved": "https://registry.npmjs.org/ora/-/ora-9.4.1.tgz", + "integrity": "sha512-6VlU9MLXbjVQD04AZCMX28hVtA5bUoadvUqO76MUCVA0ilwJbMiHsITRPfyVm6p/BC0Av/BXMujx39WCe1LEqw==", + "license": "MIT", + "dependencies": { + "chalk": "^5.6.2", + "cli-cursor": "^5.0.0", + "cli-spinners": "^3.2.0", + "is-interactive": "^2.0.0", + "is-unicode-supported": "^2.1.0", + "log-symbols": "^7.0.1", + "stdin-discarder": "^0.3.2", + "string-width": "^8.1.0" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ora/node_modules/chalk": { + "version": "5.6.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz", + "integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==", + "license": "MIT", + "engines": { + "node": "^12.17.0 || ^14.13 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/p-retry": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/p-retry/-/p-retry-4.6.2.tgz", + "integrity": "sha512-312Id396EbJdvRONlngUx0NydfrIQ5lsYu0znKVUzVvArzEIt08V1qhtyESbGVd1FGX7UKtiFp5uwKZdM8wIuQ==", + "license": "MIT", + "dependencies": { + "@types/retry": "0.12.0", + "retry": "^0.13.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/partial-json": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/partial-json/-/partial-json-0.1.7.tgz", + "integrity": "sha512-Njv/59hHaokb/hRUjce3Hdv12wd60MtM9Z5Olmn+nehe0QDAsRtRbJPvJ0Z91TusF0SuZRIvnM+S4l6EIP8leA==", + "license": "MIT" + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/pi-background-bash": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/pi-background-bash/-/pi-background-bash-1.0.5.tgz", + "integrity": "sha512-n1v0lSiXaP8MRHRaXQYA/5zNzr3wfbtMZ+Kc240mzsJprbzpI19MZVAVZsUcMprk2RE8X6MVxUARRHSuenCBvA==", + "license": "MIT", + "dependencies": { + "pi-lane": "https://codeload.github.com/sshkeda/pi-lane/tar.gz/929a74b", + "pi-pending": "https://codeload.github.com/sshkeda/pi-pending/tar.gz/v0.1.5" + }, + "bin": { + "pbb": "bin/pbb.js" + }, + "peerDependencies": { + "@earendil-works/pi-agent-core": "*", + "@earendil-works/pi-coding-agent": "*", + "@earendil-works/pi-tui": "*", + "typebox": "*" + } + }, + "node_modules/pi-lane": { + "version": "0.1.0", + "resolved": "https://codeload.github.com/sshkeda/pi-lane/tar.gz/929a74b", + "integrity": "sha512-kK1ip3DQQjoz81KKO5zXpFq48mVpPydPomGLupBAQNPO5o2JE7NtSS7aYfX8f9PpCKPWmaD3vUAARQryg/sTQg==", + "license": "MIT", + "bin": { + "pil": "bin/pil.js" + }, + "peerDependencies": { + "@earendil-works/pi-coding-agent": "*" + } + }, + "node_modules/pi-pending": { + "version": "0.1.5", + "resolved": "https://codeload.github.com/sshkeda/pi-pending/tar.gz/v0.1.5", + "integrity": "sha512-W55GnQerJVrdrMJa+14EZICcXJXP6RP0oIjRc6taSuE+fd+7hcWV3dT9w6jNE9yy8JwVYC7Rs1e3g0os1Mdugw==", + "license": "MIT", + "peerDependencies": { + "@earendil-works/pi-coding-agent": "*", + "@earendil-works/pi-tui": "*" + } + }, + "node_modules/pi-subagents": { + "version": "0.56.0", + "resolved": "https://registry.npmjs.org/pi-subagents/-/pi-subagents-0.56.0.tgz", + "integrity": "sha512-XBmKqvrj4mCVQ6/uXiPqCmzHxGfBB+jjwmfNR3El+IfhnaJwZ+W6evXYRI3lQEXe6Nf56xfzUXQExIzE8cT5BQ==", + "license": "MIT", + "dependencies": { + "acorn": "8.18.0", + "jiti": "2.7.0", + "typebox": "1.1.38", + "yaml": "2.8.3" + }, + "bin": { + "pi-subagents": "install.mjs" + }, + "peerDependencies": { + "@earendil-works/pi-agent-core": "*", + "@earendil-works/pi-ai": ">=0.80.0", + "@earendil-works/pi-coding-agent": "*", + "@earendil-works/pi-tui": "*" + }, + "peerDependenciesMeta": { + "@earendil-works/pi-agent-core": { + "optional": true + }, + "@earendil-works/pi-ai": { + "optional": true + }, + "@earendil-works/pi-coding-agent": { + "optional": true + }, + "@earendil-works/pi-tui": { + "optional": true + } + } + }, + "node_modules/pi-subagents/node_modules/acorn": { + "version": "8.18.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.18.0.tgz", + "integrity": "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==", + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/pi-subagents/node_modules/typebox": { + "version": "1.1.38", + "resolved": "https://registry.npmjs.org/typebox/-/typebox-1.1.38.tgz", + "integrity": "sha512-pZ0aQPmMmXoUvSbeuWf/Hzsc+avNw/Zd6VeE8CFgkVGWyuHPJvqeJJDeJqLve+K70LvjYIoleGcoJHPT17cWoA==", + "license": "MIT" + }, + "node_modules/pi-subagents/node_modules/yaml": { + "version": "2.8.3", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.8.3.tgz", + "integrity": "sha512-AvbaCLOO2Otw/lW5bmh9d/WEdcDFdQp2Z2ZUH3pX9U2ihyUY0nvLv7J6TrWowklRGPYbB/IuIMfYgxaCPg5Bpg==", + "license": "ISC", + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14.6" + }, + "funding": { + "url": "https://github.com/sponsors/eemeli" + } + }, + "node_modules/pkce-challenge": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz", + "integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==", + "license": "MIT", + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/proper-lockfile": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/proper-lockfile/-/proper-lockfile-4.1.2.tgz", + "integrity": "sha512-TjNPblN4BwAWMXU8s9AEz4JmQxnD1NNL7bNOY/AKUzyamc379FWASUhc/K1pL2noVb+XmZKLL68cjzLsiOAMaA==", + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.4", + "retry": "^0.12.0", + "signal-exit": "^3.0.2" + } + }, + "node_modules/proper-lockfile/node_modules/retry": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/retry/-/retry-0.12.0.tgz", + "integrity": "sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow==", + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/protobufjs": { + "version": "7.6.6", + "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.6.6.tgz", + "integrity": "sha512-dYDWdjSl5RNb7SgPxGQcRU+GtvP7s2fpkrY0r432PcOIaZ0/rBcxEZnQN67iJhFuQiVw754JDoPruPCNdGsbjg==", + "hasInstallScript": true, + "license": "BSD-3-Clause", + "dependencies": { + "@protobufjs/aspromise": "^1.1.2", + "@protobufjs/base64": "^1.1.2", + "@protobufjs/codegen": "^2.0.5", + "@protobufjs/eventemitter": "^1.1.1", + "@protobufjs/fetch": "^1.1.1", + "@protobufjs/float": "^1.0.2", + "@protobufjs/path": "^1.1.2", + "@protobufjs/pool": "^1.1.0", + "@protobufjs/utf8": "^1.1.1", + "@types/node": ">=13.7.0", + "long": "^5.3.2" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/proxy-agent-negotiate": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/proxy-agent-negotiate/-/proxy-agent-negotiate-1.1.0.tgz", + "integrity": "sha512-N8IBcM3UgCVzz2L2Lqv8DVntDnnC8/hiV4nEDUPkqq72TPUgYWjQc+bdZlBPZK9LzPAvOY//gAt0S0DApoOXWQ==", + "license": "MIT", + "engines": { + "node": ">= 20" + }, + "peerDependencies": { + "kerberos": "^2.0.0" + }, + "peerDependenciesMeta": { + "kerberos": { + "optional": true + } + } + }, + "node_modules/quickjs-wasi": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/quickjs-wasi/-/quickjs-wasi-3.6.2.tgz", + "integrity": "sha512-FCqGtGOrMgzUiIrMNMA2YnsOxCNwo31dzqXvclXUC6xeT35NJLKXQJsvbeCTjvoFAwZgEAPg8U6+KAPDGXn8Mg==", + "license": "MIT" + }, + "node_modules/restore-cursor": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-5.1.0.tgz", + "integrity": "sha512-oMA2dcrw6u0YfxJQXm342bFKX/E4sG9rbTzO9ptUcR/e8A33cHuvStiYOwH7fszkZlZ1z/ta9AAoPk2F4qIOHA==", + "license": "MIT", + "dependencies": { + "onetime": "^7.0.0", + "signal-exit": "^4.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/restore-cursor/node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/retry": { + "version": "0.13.1", + "resolved": "https://registry.npmjs.org/retry/-/retry-0.13.1.tgz", + "integrity": "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==", + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/rolldown": { + "version": "1.2.9", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.9.tgz", + "integrity": "sha512-hx/Pv0N1haXRb11qkfnK5MXB/iqr7i0yjWQqmO9uHqZpBgQSqzc8UsSnEpalsh+j1I8qQ2CkXAkJC8Br3dKSlg==", + "license": "MIT", + "dependencies": { + "@oxc-project/types": "=0.150.0", + "@rolldown/pluginutils": "^1.0.0" + }, + "bin": { + "rolldown": "bin/cli.mjs" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@rolldown/binding-android-arm-eabi": "1.2.9", + "@rolldown/binding-android-arm64": "1.2.9", + "@rolldown/binding-darwin-arm64": "1.2.9", + "@rolldown/binding-darwin-x64": "1.2.9", + "@rolldown/binding-freebsd-x64": "1.2.9", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.9", + "@rolldown/binding-linux-arm64-gnu": "1.2.9", + "@rolldown/binding-linux-arm64-musl": "1.2.9", + "@rolldown/binding-linux-ppc64-gnu": "1.2.9", + "@rolldown/binding-linux-s390x-gnu": "1.2.9", + "@rolldown/binding-linux-x64-gnu": "1.2.9", + "@rolldown/binding-linux-x64-musl": "1.2.9", + "@rolldown/binding-openharmony-arm64": "1.2.9", + "@rolldown/binding-win32-arm64-msvc": "1.2.9", + "@rolldown/binding-win32-x64-msvc": "1.2.9" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/semver": { + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "license": "ISC" + }, + "node_modules/standardwebhooks": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/standardwebhooks/-/standardwebhooks-1.1.1.tgz", + "integrity": "sha512-bCbX9ZEyFkWPsRz7Bl3NuQUJohmwGSev/yhr7vhaGPlc4AfIrspIRa6cPTBuI1ItmrTDJ4d/S2hCsfe4+vQGnQ==", + "license": "MIT", + "dependencies": { + "@stablelib/base64": "^1.0.0", + "fast-sha256": "^1.3.0" + } + }, + "node_modules/stdin-discarder": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/stdin-discarder/-/stdin-discarder-0.3.2.tgz", + "integrity": "sha512-eCPu1qRxPVkl5605OTWF8Wz40b4Mf45NY5LQmVPQ599knfs5QhASUm9GbJ5BDMDOXgrnh0wyEdvzmL//YMlw0A==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/string-width": { + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-8.3.0.tgz", + "integrity": "sha512-ZbmZM0JCihQN91dWnxoipT2KOEyHqEyfRXUyjuRhW8b/xnqPDoq4gWEVApTVa9db2wN8mmoikgFBbjh71+cGeQ==", + "license": "MIT", + "dependencies": { + "get-east-asian-width": "^1.5.0", + "strip-ansi": "^7.1.2" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/strip-ansi": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz", + "integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.2.2" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/ts-algebra": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ts-algebra/-/ts-algebra-2.0.0.tgz", + "integrity": "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==", + "license": "MIT" + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "license": "0BSD" + }, + "node_modules/typebox": { + "version": "1.3.36", + "resolved": "https://registry.npmjs.org/typebox/-/typebox-1.3.36.tgz", + "integrity": "sha512-bu2Ec2Ti9B4IFSFj1FcZbtLNB/W7igQwxocMGJLAG2NTv1nI+ImtIA34YgHW4CVyGVlJqNXR1GJyLmdWgV3DuA==", + "license": "MIT", + "peer": true + }, + "node_modules/undici": { + "version": "8.10.2", + "resolved": "https://registry.npmjs.org/undici/-/undici-8.10.2.tgz", + "integrity": "sha512-/y4/bH9YNU5hi9NIrpOuvGXFcxrj3CMrV+/AYpowAYTpHn8gX/XPFjNy766FPoYY0miQhdW977JFWKGNhBdwyQ==", + "license": "MIT", + "engines": { + "node": ">=22.19.0" + } + }, + "node_modules/undici-types": { + "version": "8.9.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz", + "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==", + "license": "MIT" + }, + "node_modules/web-streams-polyfill": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz", + "integrity": "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==", + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/ws": { + "version": "8.22.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz", + "integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/yaml": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.0.tgz", + "integrity": "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==", + "license": "ISC", + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14.6" + }, + "funding": { + "url": "https://github.com/sponsors/eemeli" + } + }, + "node_modules/yoctocolors": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/yoctocolors/-/yoctocolors-2.2.0.tgz", + "integrity": "sha512-xYqdZFUK/VYazNl/oCDYN+3WloWQwMfZxBoiNt6qNyk+xfOdi598muWE42rNZFp1kNOiqW936q5RhUdnpqElSg==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/zod": { + "version": "4.6.5", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.5.tgz", + "integrity": "sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, + "plugins/background": { + "name": "@braid/pi-runtime-background", + "version": "1.0.0", + "dependencies": { + "pi-background-bash": "1.0.5" + } + }, + "plugins/context7": { + "name": "@braid/pi-runtime-context7", + "version": "1.0.0", + "dependencies": { + "@upstash/context7-pi": "0.1.2" + } + }, + "plugins/fff": { + "name": "@braid/pi-runtime-fff", + "version": "1.0.0", + "dependencies": { + "@ff-labs/pi-fff": "0.11.0" + } + }, + "plugins/mcporter": { + "name": "@braid/pi-runtime-mcporter", + "version": "1.0.0", + "dependencies": { + "mcporter": "0.14.0" + } + }, + "plugins/subagents": { + "name": "@braid/pi-runtime-subagents", + "version": "1.0.0", + "dependencies": { + "pi-subagents": "0.56.0" + } + } + } +} diff --git a/native/pi/package.json b/native/pi/package.json new file mode 100644 index 00000000..d52648b1 --- /dev/null +++ b/native/pi/package.json @@ -0,0 +1,12 @@ +{ + "name": "braid-pi-runtime", + "version": "1.0.0", + "private": true, + "type": "module", + "dependencies": { + "@earendil-works/pi-coding-agent": "1.1.0" + }, + "workspaces": [ + "plugins/*" + ] +} diff --git a/native/pi/patches.json b/native/pi/patches.json new file mode 100644 index 00000000..8b1ddd61 --- /dev/null +++ b/native/pi/patches.json @@ -0,0 +1,70 @@ +[ + { + "package": "@earendil-works/pi-coding-agent", + "path": "patches/pi-1.1.0-compaction-threshold.patch", + "targets": [ + "dist/core/compaction/compaction.js", + "dist/core/compaction/compaction.d.ts", + "dist/core/settings-manager.js", + "dist/core/settings-manager.d.ts" + ] + }, + { + "package": "@earendil-works/pi-ai", + "path": "patches/pi-ai-1.1.0-connection-reset.patch", + "targets": [ + "dist/utils/retry.js" + ] + }, + { + "package": "pi-subagents", + "path": "patches/pi-subagents-0.56.0-braid.patch", + "targets": [ + "src/extension/index.ts", + "src/runs/background/async-execution.ts", + "src/runs/background/notify.ts", + "src/runs/background/result-watcher.ts", + "src/runs/background/stale-run-reconciler.ts", + "src/runs/background/subagent-runner.ts", + "src/runs/background/subagent-wait.ts", + "src/runs/foreground/execution.ts", + "src/runs/foreground/subagent-executor.ts", + "src/runs/shared/model-exclusions.ts", + "src/runs/shared/model-fallback.ts", + "src/runs/shared/pi-args.ts", + "src/runs/shared/session-lease.ts", + "src/shared/types.ts", + "src/shared/utils.ts", + "src/runs/shared/external-job-bridge.ts", + "src/runs/background/async-retention.ts", + "src/missions/workflow-state.ts" + ], + "plugin": "subagents" + }, + { + "package": "pi-background-bash", + "path": "patches/pi-background-bash-1.0.5-braid.patch", + "targets": [ + "bin/pbb.js", + "extensions/background-bash.ts", + "skills/pbb/SKILL.md" + ], + "plugin": "background" + }, + { + "package": "@upstash/context7-pi", + "path": "patches/context7-pi-0.1.2-errors.patch", + "targets": [ + "lib/api.ts" + ], + "plugin": "context7" + }, + { + "package": "mcporter", + "path": "patches/mcporter-0.14.0-owned-service.patch", + "targets": [ + "dist/daemon/launch.js" + ], + "plugin": "mcporter" + } +] diff --git a/native/pi/patches/context7-pi-0.1.2-errors.patch b/native/pi/patches/context7-pi-0.1.2-errors.patch new file mode 100644 index 00000000..ae85c3be --- /dev/null +++ b/native/pi/patches/context7-pi-0.1.2-errors.patch @@ -0,0 +1,36 @@ +--- a/lib/api.ts ++++ b/lib/api.ts +@@ -13,26 +13,13 @@ + } + + async function parseErrorResponse(response: Response): Promise { +- try { +- const json = (await response.json()) as { message?: string }; +- if (json.message) return json.message; +- } catch { +- // JSON parsing failed, fall through to status-based message +- } +- +- const hasKey = Boolean(process.env.CONTEXT7_API_KEY); +- if (response.status === 429) { +- return hasKey +- ? "Rate limited or quota exceeded. Upgrade your plan at https://context7.com/plans for higher limits." +- : "Rate limited or quota exceeded. Create a free API key at https://context7.com/dashboard for higher limits."; +- } +- if (response.status === 404) { +- return "The library you are trying to access does not exist. Please try with a different library ID."; +- } +- if (response.status === 401) { +- return "Invalid API key. Please check your API key. API keys should start with 'ctx7sk' prefix."; +- } +- return `Request failed with status ${response.status}. Please try again later.`; ++ let body = await response.text(); ++ const apiKey = process.env.CONTEXT7_API_KEY; ++ if (apiKey) body = body.split(apiKey).join("[REDACTED]"); ++ const limit = 8000; ++ const truncated = body.length > limit ? `\n[Response truncated: ${body.length} characters, showing ${limit}]` : ""; ++ const requestId = response.headers.get("x-request-id"); ++ return `HTTP ${response.status} ${response.statusText}${requestId ? `; request ID: ${requestId}` : ""}\n${body.slice(0, limit) || "(empty response)"}${truncated}`; + } + + export async function searchLibraries(query: string, libraryName: string): Promise { diff --git a/native/pi/patches/mcporter-0.14.0-owned-service.patch b/native/pi/patches/mcporter-0.14.0-owned-service.patch new file mode 100644 index 00000000..bdc02524 --- /dev/null +++ b/native/pi/patches/mcporter-0.14.0-owned-service.patch @@ -0,0 +1,24 @@ +--- a/dist/daemon/launch.js ++++ b/dist/daemon/launch.js +@@ -4,16 +4,18 @@ + import { fileURLToPath } from 'node:url'; + export async function launchDaemonDetached(options, launch = spawn) { + const invocation = buildDaemonLaunchInvocation(options); ++ const managed = process.env.BRAID_NATIVE_RUNTIME_MODULE ? await import(process.env.BRAID_NATIVE_RUNTIME_MODULE) : undefined; + try { + await new Promise((resolve, reject) => { +- const child = launch(invocation.command, invocation.args, { ++ const child = (managed?.spawnManaged ?? launch)(invocation.command, invocation.args, { + detached: true, + stdio: 'ignore', + env: invocation.env, +- }); ++ }, { kind: 'mcp-daemon', service: true }); + // Keep handling late errors after spawn; readiness is checked by the caller. + child.on('error', reject); +- child.once('spawn', resolve); ++ if (managed) managed.waitManagedStartup(child).then(resolve, reject); ++ else child.once('spawn', resolve); + child.unref(); + }); + } diff --git a/native/pi/patches/pi-1.1.0-compaction-threshold.patch b/native/pi/patches/pi-1.1.0-compaction-threshold.patch new file mode 100644 index 00000000..a857a1e8 --- /dev/null +++ b/native/pi/patches/pi-1.1.0-compaction-threshold.patch @@ -0,0 +1,60 @@ +--- a/dist/core/compaction/compaction.js ++++ b/dist/core/compaction/compaction.js +@@ -173,7 +173,8 @@ + export function shouldCompact(contextTokens, contextWindow, settings) { + if (!settings.enabled) + return false; +- return contextTokens > contextWindow - settings.reserveTokens; ++ const capacityThreshold = Math.max(0, contextWindow - settings.reserveTokens); ++ return contextTokens > Math.min(settings.thresholdTokens ?? Infinity, capacityThreshold); + } + // ============================================================================ + // Cut point detection +--- a/dist/core/compaction/compaction.d.ts ++++ b/dist/core/compaction/compaction.d.ts +@@ -29,6 +29,8 @@ + enabled: boolean; + reserveTokens: number; + keepRecentTokens: number; ++ /** Operational trigger; does not change model capacity or summary reserve. */ ++ thresholdTokens?: number; + } + export declare const DEFAULT_COMPACTION_SETTINGS: CompactionSettings; + /** +--- a/dist/core/settings-manager.js ++++ b/dist/core/settings-manager.js +@@ -654,10 +654,15 @@ + } + /** Resolve each token setting through model override, ordinary setting, then built-in default. */ + getCompactionSettings(model) { ++ const thresholdTokens = this.settings.compaction?.thresholdTokens; ++ if (thresholdTokens !== undefined && (!Number.isSafeInteger(thresholdTokens) || thresholdTokens <= 0)) { ++ throw new Error("compaction.thresholdTokens must be a positive safe integer"); ++ } + return { + enabled: this.getCompactionEnabled(), + reserveTokens: this.getCompactionReserveTokens(model), + keepRecentTokens: this.getCompactionKeepRecentTokens(model), ++ thresholdTokens, + }; + } + getBranchSummarySettings() { +--- a/dist/core/settings-manager.d.ts ++++ b/dist/core/settings-manager.d.ts +@@ -6,6 +6,8 @@ + keepRecentTokens?: number; + } + export interface CompactionSettings { ++ /** Operational trigger; does not change model capacity or summary reserve. */ ++ thresholdTokens?: number; + enabled?: boolean; + reserveTokens?: number; + keepRecentTokens?: number; +@@ -269,6 +271,7 @@ + getCompactionKeepRecentTokens(model?: Pick, "provider" | "id">): number; + /** Resolve each token setting through model override, ordinary setting, then built-in default. */ + getCompactionSettings(model?: Pick, "provider" | "id">): { ++ thresholdTokens: number | undefined; + enabled: boolean; + reserveTokens: number; + keepRecentTokens: number; diff --git a/native/pi/patches/pi-ai-1.1.0-connection-reset.patch b/native/pi/patches/pi-ai-1.1.0-connection-reset.patch new file mode 100644 index 00000000..5dd879b4 --- /dev/null +++ b/native/pi/patches/pi-ai-1.1.0-connection-reset.patch @@ -0,0 +1,10 @@ +--- a/dist/utils/retry.js ++++ b/dist/utils/retry.js +@@ -50,6 +50,7 @@ + "connection.?error", + "connection.?refused", + "connection.?lost", ++ "connection reset by peer", + "other side closed", + "fetch failed", + "getaddrinfo", 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 new file mode 100644 index 00000000..d5498a7a --- /dev/null +++ b/native/pi/patches/pi-background-bash-1.0.5-braid.patch @@ -0,0 +1,722 @@ +--- a/bin/pbb.js ++++ b/bin/pbb.js +@@ -109,7 +109,7 @@ + } + } + +-let pilInstancesCache; ++const pilInstancesCache = new Map(); + + function failPil(id, message, error) { + const detail = error instanceof Error ? error.message : String(error || ""); +@@ -130,7 +130,7 @@ + } + + function readPilInstances(id) { +- if (pilInstancesCache !== undefined) return pilInstancesCache; ++ if (pilInstancesCache.has(id.sessionKey)) return pilInstancesCache.get(id.sessionKey); + const pil = pilCommand(id); + try { + const raw = execFileSync(pil.file, [...pil.args, "instances", "--json"], { +@@ -146,26 +146,41 @@ + PI_LANE_CURRENT_LANE: id.lane, + }, + }); +- pilInstancesCache = JSON.parse(raw).instances || []; ++ pilInstancesCache.set(id.sessionKey, JSON.parse(raw).instances || []); + } catch (error) { + failPil(id, "tracked pi-lane pil command failed", error); + } +- return pilInstancesCache; ++ return pilInstancesCache.get(id.sessionKey); + } + + function ownerInfo(id, job) { + const state = readPilInstances(id).find((item) => item.instanceId === job.instanceId); ++ // PBB also runs without a pi-lane extension; its own identity records the owner PID. ++ const ownerPid = readJson(join(instanceDir(id, job.instanceId), "identity.json"))?.pid; ++ let ownerLive = Boolean(state?.live); ++ if (!state && Number.isInteger(ownerPid) && ownerPid > 0) { ++ try { process.kill(ownerPid, 0); ownerLive = true; } ++ catch (error) { ++ if (error.code === "EPERM") ownerLive = true; ++ else if (error.code !== "ESRCH") throw error; ++ } ++ } + return { +- ownerStatus: state?.status || "unknown", ++ ownerStatus: state?.status || (ownerLive ? "running" : "unknown"), + ownerLastSeenAt: state?.lastSeenAt || "", + ownerLastSeenAgeMs: state?.lastSeenAgeMs, +- ownerLive: Boolean(state?.live), +- ownerStale: !state?.live, ++ ownerLive, ++ ownerStale: !ownerLive, + }; + } + + function enrichJob(id, job, path) { +- return { ...job, ...ownerInfo(id, job), _path: path }; ++ const owner = ownerInfo(id, job); ++ const missingCompletion = owner.ownerStale && ["running", "kill_requested"].includes(job.status); ++ return { ...job, ...owner, ...(missingCompletion ? { ++ recordedStatus: job.status, status: "unknown", outcome: "unknown", exitCode: null, ++ reason: "owner_unavailable_without_completion", ++ } : {}), _path: path }; + } + + function listInstanceIds(id, scope, explicitInstance) { +@@ -191,8 +206,27 @@ + return jobs.sort((a, b) => String(a.startedAt ?? "").localeCompare(String(b.startedAt ?? "")) || String(a.jobId).localeCompare(String(b.jobId))); + } + +-function findJob(id, jobId, opts) { +- const jobs = readJobs(id, opts).filter((job) => job.jobId === jobId || job.globalJobId === jobId); ++function findJob(id, jobId, opts, acrossSessions = false) { ++ let jobs; ++ if (acrossSessions && opts.scope === "global") { ++ // Global IDs are read across retained sessions; short IDs keep their existing scope. ++ const [instance, localJob, extra] = jobId.split(":"); ++ jobs = []; ++ const sessions = join(id.root, "sessions"); ++ if (!extra && /^bg[0-9]+$/.test(localJob || "") && existsSync(sessions)) { ++ for (const entry of readdirSync(sessions, { withFileTypes: true })) { ++ if (!entry.isDirectory()) continue; ++ const source = { ...id, sessionKey: entry.name }; ++ // Match a directory entry before using the caller's instance in a path. ++ if (!listInstanceIds(source, "session").includes(instance)) continue; ++ const path = join(jobsDir(source, instance), `${localJob}.json`); ++ const job = readJson(path); ++ if (job?.globalJobId === jobId) jobs.push(enrichJob({ ...source, ...job, root: id.root }, job, path)); ++ } ++ } ++ } else { ++ jobs = readJobs(id, opts).filter((job) => job.jobId === jobId || job.globalJobId === jobId); ++ } + if (jobs.length === 0) return { error: "missing", jobs }; + if (jobs.length > 1) return { error: "ambiguous", jobs }; + return { job: jobs[0], jobs }; +@@ -275,8 +309,8 @@ + + function printStatus(id, jobId, opts) { + if (!jobId) return printList(id, opts); +- const scope = opts.scope || (opts.instance ? "session" : "current-instance"); +- const result = findJob(id, jobId, { scope, instance: opts.instance }); ++ const scope = jobId?.includes(":") ? "global" : opts.scope || (opts.instance ? "session" : "current-instance"); ++ const result = findJob(id, jobId, { scope, instance: opts.instance }, true); + if (result.error === "missing") { + console.error(context("pbb.error", { session_key: id.sessionKey, instance_id: id.instanceId, scope, job_id: jobId, error: "unknown_job" }, `unknown job ${jobId}`)); + process.exit(2); +@@ -300,8 +334,8 @@ + } + + function printTail(id, jobId, opts) { +- const scope = opts.scope || (opts.instance ? "session" : "current-instance"); +- const result = findJob(id, jobId, { scope, instance: opts.instance }); ++ const scope = jobId?.includes(":") ? "global" : opts.scope || (opts.instance ? "session" : "current-instance"); ++ const result = findJob(id, jobId, { scope, instance: opts.instance }, true); + if (!result.job) { + console.error(context("pbb.error", { session_key: id.sessionKey, instance_id: id.instanceId, scope, job_id: jobId, error: result.error === "ambiguous" ? "ambiguous_job" : "unknown_job" }, `${result.error === "ambiguous" ? "ambiguous" : "unknown"} job ${jobId}`)); + process.exit(result.error === "ambiguous" ? 3 : 2); +@@ -334,14 +368,14 @@ + } + + function printKill(id, jobId, opts) { +- const scope = opts.scope || (opts.instance ? "session" : "current-instance"); +- const result = findJob(id, jobId, { scope, instance: opts.instance }); ++ const scope = jobId?.includes(":") ? "global" : opts.scope || (opts.instance ? "session" : "current-instance"); ++ const result = findJob(id, jobId, { scope, instance: opts.instance }, true); + if (!result.job) { + console.error(context("pbb.error", { session_key: id.sessionKey, instance_id: id.instanceId, scope, job_id: jobId, error: result.error === "ambiguous" ? "ambiguous_job" : "unknown_job" }, `${result.error === "ambiguous" ? "ambiguous" : "unknown"} job ${jobId}`)); + process.exit(result.error === "ambiguous" ? 3 : 2); + } + const job = result.job; +- if (!["running", "kill_requested"].includes(job.status)) { ++ if (!["running", "kill_requested"].includes(job.recordedStatus ?? job.status)) { + console.log(context("pbb.kill", { session_id: id.sessionId, session_key: id.sessionKey, instance_id: id.instanceId, lane: id.lane, scope, job_id: job.jobId, owner_instance_id: job.instanceId, status: job.status, requested: false }, `${job.jobId} is not running; no kill requested`)); + return; + } +@@ -378,7 +412,7 @@ + const id = identity(); + + if (["help", "--help", "-h"].includes(command)) { +- console.log(`pbb - Pi background bash inspector\n\nCommands:\n pbb self [--json]\n pbb list [--scope current-instance|session] [--instance ID] [--json]\n pbb instances [--json]\n pbb status [JOB] [--json]\n pbb tail JOB [-n LINES] [--full] [--json]\n pbb kill JOB [--stale] [--signal TERM]\n\nDefaults to the current pi-lane instance using PI_LANE_* env vars.`); ++ console.log(`pbb - Pi background bash inspector\n\nCommands:\n pbb self [--json]\n pbb list [--scope current-instance|session] [--instance ID] [--json]\n pbb instances [--json]\n pbb status [JOB] [--json]\n pbb tail JOB [-n LINES] [--full] [--json]\n pbb kill JOB [--stale] [--signal TERM]\n\nDefaults to the current pi-lane instance using PI_LANE_* env vars. An empty list covers only that scope.\nUse pbb status/tail/kill INSTANCE:bgNNN to read or stop a retained result across sessions. Missing completion from an unavailable owner is unknown, not a confirmed cancellation.`); + process.exit(0); + } + +--- a/extensions/background-bash.ts ++++ b/extensions/background-bash.ts +@@ -1,6 +1,6 @@ + import { spawn, type ChildProcess } from "node:child_process"; + import { createHash, randomUUID } from "node:crypto"; +-import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs"; ++import { appendFileSync, existsSync, mkdirSync, readFileSync, openSync, readSync, closeSync, fstatSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs"; + import { homedir } from "node:os"; + import { dirname, join } from "node:path"; + import type { AgentMessage, AgentToolResult } from "@earendil-works/pi-agent-core"; +@@ -20,6 +20,7 @@ + type Outcome = "running" | "exit" | "timeout" | "abort" | "error"; + + type BackgroundBashDetails = BashToolDetails & { ++ handle?: string; + jobId: string; + command: string; + outcome: Outcome; +@@ -41,6 +42,7 @@ + command: string; + timeout?: number; + background?: boolean; ++ service?: boolean; + }; + + type CompletedBashRun = +@@ -59,6 +61,7 @@ + details: BashToolDetails | undefined; + outcome: Outcome; + exitCode: number | null; ++ signal?: NodeJS.Signals; + }; + + type PbbIdentity = { +@@ -85,6 +88,11 @@ + id: string; + command: string; + toolCallId: string; ++ ownerSessionId?: string; ++ service?: boolean; ++ capacityHandoff?: boolean; ++ completion?: Promise; ++ startError?: string; + abortController: AbortController; + startedAt: number; + cwd?: string; +@@ -107,6 +115,7 @@ + command: Type.String({ description: "Bash command to execute" }), + timeout: Type.Optional(Type.Number({ description: "Timeout in seconds (optional, no default timeout)" })), + background: Type.Optional(Type.Boolean({ description: "Run immediately in the background and return a job id" })), ++ service: Type.Optional(Type.Boolean({ description: "Run as a long-lived background service that does not delay session completion; default false" })), + }); + + const JOB_ID_PREFIX = "bg"; +@@ -214,6 +223,12 @@ + laneRoot: process.env.PI_LANE_ROOT, + root: process.env.PBB_ROOT || join(homedir(), ".pi", "pbb"), + }; ++} ++ ++function currentPiSessionId(ctx: { sessionManager: { getSessionFile(): string | null | undefined; getSessionId(): string | null | undefined } }): string { ++ const sessionId = ctx.sessionManager.getSessionFile() ?? ctx.sessionManager.getSessionId(); ++ if (!sessionId) throw new Error("Cannot track background bash job without a Pi session identity."); ++ return sessionId; + } + + function asRecord(value: unknown): Record | undefined { +@@ -427,6 +442,7 @@ + lane: job.pbb.lane, + jobId: job.id, + globalJobId: `${job.pbb.instanceId}:${job.id}`, ++ handle: `pbb:${job.pbb.instanceId}:${job.id}`, + ...data, + })}\n`); + return eventId; +@@ -440,6 +456,7 @@ + schemaVersion: 1, + jobId: job.id, + globalJobId: `${job.pbb.instanceId}:${job.id}`, ++ handle: `pbb:${job.pbb.instanceId}:${job.id}`, + command: job.command, + toolCallId: job.toolCallId, + cwd: patch.cwd ?? job.cwd, +@@ -503,6 +520,7 @@ + status: completed.outcome === "exit" ? "exited" : completed.outcome, + outcome: completed.outcome, + exitCode: completed.exitCode, ++ signal: completed.status === "error" ? completed.signal : undefined, + completedAt: new Date().toISOString(), + durationMs, + lastEventId: job.lastEventId, +@@ -571,15 +589,29 @@ + resolve(completed); + }; + +- const child = spawn("bash", ["-lc", params.command], { ++ const managedRuntime = (globalThis as any)[Symbol.for("braid.native-runtime.v1")]; ++ let child: ChildProcess; ++ let managedStartup: Promise | undefined; ++ try { ++ child = (managedRuntime?.spawnManaged ?? spawn)("bash", ["-c", params.command], { + cwd, + env: process.env, + detached: true, + stdio: ["ignore", "pipe", "pipe"], +- }); ++ }, { kind: "tool", service: job.service, manifest: job.pbb ? join(pbbJobsDir(job.pbb), `${job.id}.json`) : undefined }); ++ managedStartup = managedRuntime?.waitManagedStartup(child); ++ } catch (error) { ++ job.startError = error instanceof Error ? error.message : String(error); ++ finish({ status: "error", error, body: job.startError, details: undefined, outcome: "error", exitCode: null }); ++ return; ++ } + job.child = child; + job.pid = child.pid; + job.pgid = child.pid; ++ managedStartup?.catch((error) => { ++ job.startError = error instanceof Error ? error.message : String(error); ++ finish({ status: "error", error, body: job.startError, details: undefined, outcome: "error", exitCode: 75 }); ++ }); + writePbbJob(job, { pid: child.pid, pgid: child.pid, runner: "pbb" }); + + const append = (chunk: Buffer) => { +@@ -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) => { ++ 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 }); ++ finish({ status: "error", error: new Error(body), body, details: undefined, outcome: "timeout", exitCode: code, signal: signalName ?? undefined }); + return; + } + if (aborted || signalName) { + const body = completionBody(output, "Command aborted"); +- finish({ status: "error", error: new Error(body), body, details: undefined, outcome: "abort", exitCode: null }); ++ finish({ status: "error", error: new Error(body), body, details: undefined, outcome: "abort", exitCode: code, signal: signalName ?? undefined }); + return; + } + if (code === 0) { +@@ -682,7 +727,7 @@ + } + + function writeForegroundFullOutput(body: string): string { +- const dir = join(homedir(), ".pi", "pbb", "truncated"); ++ const dir = join(process.env.PBB_ROOT || join(homedir(), ".pi", "pbb"), "truncated"); + mkdirSync(dir, { recursive: true }); + const path = join(dir, `${new Date().toISOString().replace(/[:.]/g, "-")}-${randomUUID().slice(0, 8)}.log`); + writeFileSync(path, body); +@@ -743,7 +788,7 @@ + + const pendingBackgroundResultFollowUps: PendingBackgroundResultFollowUp[] = []; + +-function deliverBackgroundResultFollowUp(pi: ExtensionAPI, item: PendingBackgroundResultFollowUp): void { ++function deliverBackgroundResultFollowUp(pi: ExtensionAPI, item: PendingBackgroundResultFollowUp, triggerTurn = true): void { + if (shuttingDown) return; + repairDetachedBackgroundToolResults(item.job.repairContext, item.job.toolCallId, { rewriteFile: item.job.repairContext?.isIdle?.() === true }); + pi.sendMessage( +@@ -753,14 +798,25 @@ + display: true, + details: item.details, + }, +- { deliverAs: "followUp", triggerTurn: true }, ++ { deliverAs: "followUp", triggerTurn: triggerTurn && !item.job.service }, + ); + } + +-function flushPendingBackgroundResultFollowUps(pi: ExtensionAPI): void { ++function flushPendingBackgroundResultFollowUps(pi: ExtensionAPI, triggerTurn = true): void { + if (shuttingDown || pendingBackgroundResultFollowUps.length === 0) return; + const items = pendingBackgroundResultFollowUps.splice(0); +- for (const item of items) deliverBackgroundResultFollowUp(pi, item); ++ if (items.length === 1) { ++ deliverBackgroundResultFollowUp(pi, items[0], triggerTurn); ++ return; ++ } ++ // Completions queued during one inference are one observation batch, not ++ // separate user requests. Keep every result, but wake Pi only once. ++ for (const item of items) { ++ repairDetachedBackgroundToolResults(item.job.repairContext, item.job.toolCallId, { rewriteFile: item.job.repairContext?.isIdle?.() === true }); ++ } ++ pi.sendMessage({ customType: CUSTOM_TYPE, content: items.map((item) => item.content).join("\n\n"), display: true, ++ details: { jobs: items.map((item) => item.details) } }, ++ { deliverAs: "followUp", triggerTurn: triggerTurn && items.some((item) => !item.job.service) }); + } + + function sendBackgroundResultFollowUp(pi: ExtensionAPI, job: ActiveJob, content: string, details: BackgroundBashDetails): void { +@@ -783,12 +839,11 @@ + } + + function deliverBackgroundResult(pi: ExtensionAPI, job: ActiveJob, completed: CompletedBashRun, cwd: string) { ++ const durationMs = Date.now() - job.startedAt; ++ recordPbbJobCompleted(job, completed, cwd, durationMs); + activeJobs.delete(job.id); + pendingJobs.finish(job.id); +- if (shuttingDown) return; +- +- const durationMs = Date.now() - job.startedAt; +- recordPbbJobCompleted(job, completed, cwd, durationMs); ++ if (shuttingDown || job.capacityHandoff) return; + const body = truncateBackgroundBody(job, completed.body); + const content = buildXmlResult(job, completed.outcome, completed.exitCode, durationMs, body); + const details: BackgroundBashDetails = { +@@ -809,6 +864,7 @@ + instanceId: job.pbb.instanceId, + lane: job.pbb.lane, + globalJobId: `${job.pbb.instanceId}:${job.id}`, ++ handle: `pbb:${job.pbb.instanceId}:${job.id}`, + pbbCursor: job.lastEventId, + } + : {}), +@@ -884,6 +940,7 @@ + instanceId: job.pbb.instanceId, + lane: job.pbb.lane, + globalJobId: `${job.pbb.instanceId}:${job.id}`, ++ handle: `pbb:${job.pbb.instanceId}:${job.id}`, + pbbCursor: job.lastEventId, + } + : {}), +@@ -898,8 +955,6 @@ + job.abortController.abort(); + if (job.runner === "pbb") killProcessGroup(job.pgid ?? job.pid, "SIGTERM"); + } +- activeJobs.clear(); +- pendingJobs.clear(); + } + + function installProcessHooks() { +@@ -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. +- process.once("exit", abortAllJobs); ++ process.once("exit", () => { ++ // The event loop cannot observe child exits here. Never claim cancellation. ++ for (const job of activeJobs.values()) { ++ try { ++ writePbbJob(job, { status: "unknown", outcome: "unknown", reason: "owner_exited_before_completion" }); ++ } catch (error) { ++ console.error(`Could not record unknown outcome for ${job.id}:`, error); ++ } ++ } ++ abortAllJobs(); ++ }); + } + + function restoreJobCounterFromSession(ctx: { sessionManager?: { getEntries?: () => unknown[] } }) { +@@ -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; +- const candidates = [details?.jobId, content?.match(/]*\bid="(bg\d{3,})"/)?.[1]]; ++ const batch = Array.isArray(details?.jobs) ? details.jobs as Record[] : []; ++ const candidates = [details?.jobId, ...batch.map((job) => job.jobId), content?.match(/]*\bid="(bg\d{3,})"/)?.[1]]; + for (const candidate of candidates) { + const n = parseJobNumber(candidate); + if (n !== undefined) max = Math.max(max, n); +@@ -926,8 +992,40 @@ + nextJobNumber = Math.max(nextJobNumber, max + 1); + } + +-export default function backgroundBashExtension(pi: ExtensionAPI) { ++function pendingCompletionJobs(): ActiveJob[] { ++ return [...activeJobs.values()].filter((job) => job.ownerSessionId && !job.service); ++} ++ ++export default async function backgroundBashExtension(pi: ExtensionAPI) { + installProcessHooks(); ++ const managedRuntime = (globalThis as any)[Symbol.for("braid.native-runtime.v1")]; ++ const unregisterManaged = managedRuntime?.registerManagedProvider("pi-background-bash", () => { ++ const finite = [...activeJobs.values()].some((job) => !job.service); ++ const pending = pendingBackgroundResultFollowUps.length > 0; ++ return { ++ status: activeJobs.size || pending ? "busy" : "quiescent", ++ services_only: activeJobs.size > 0 && !finite && !pending, ++ reason: finite ? "finite_job_active" : pending ? "result_not_consumed" : "services_only", ++ }; ++ }, async () => { ++ const jobs = [...activeJobs.values()]; ++ if (pendingBackgroundResultFollowUps.length || jobs.some((job) => !job.service || !job.child?.managedProcessRecord || !job.completion)) { ++ throw new Error("Service handoff requires only registered service jobs with no pending result."); ++ } ++ for (const job of jobs) job.capacityHandoff = true; ++ for (const job of jobs) { ++ const stop = await managedRuntime.finishManagedProcess(job.child, { observation: "capacity_service_handoff", observed_at: Date.now() }); ++ if (stop?.status !== "stopped") throw new Error(`Service ${job.id} stop proof failed: ${stop?.reason ?? "unknown"}`); ++ await job.completion; ++ } ++ }); ++ // PBB drains its own finite jobs; the cross-plugin API is only needed when subagents is selected. ++ const unregisterBackgroundWork = process.env.BRAID_NATIVE_SUBAGENTS_ENABLED === "1" ++ ? (await import("pi-subagents/background-work")).registerBackgroundWorkProvider({ ++ name: "pi-background-bash", ++ listActiveWork: () => pendingCompletionJobs().map((job) => ({ id: job.id, sessionId: job.ownerSessionId! })), ++ }) ++ : undefined; + + pi.registerMessageRenderer(CUSTOM_TYPE, (message, options, theme) => { + const details = message.details; +@@ -949,16 +1047,41 @@ + }); + + pi.on("session_shutdown", async () => { ++ const jobs = [...activeJobs.values()]; + abortAllJobs(); ++ const outcomes = await Promise.allSettled(jobs.map((job) => job.completion ?? ++ Promise.reject(new Error(`Background bash job ${job.id} has no completion promise.`)))); ++ unregisterBackgroundWork?.(); ++ unregisterManaged?.(); ++ // Completion callbacks have persisted their results before notifications are discarded. + pendingBackgroundResultFollowUps.length = 0; + pendingJobs.detach(); +- }); +- +- pi.on("agent_end", async () => { +- // Treat agent_end as the event-driven idle boundary, but defer one macrotask +- // so Pi can finish unwinding the just-ended turn before the follow-up starts. +- const handle = setImmediate(() => flushPendingBackgroundResultFollowUps(pi)); +- handle.unref?.(); ++ for (const outcome of outcomes) if (outcome.status === "rejected") throw outcome.reason; ++ }); ++ ++ const retainTerminalBackground = (outcome: "error" | "aborted") => { ++ // Preserve results without scheduling inference or changing active job ownership. ++ flushPendingBackgroundResultFollowUps(pi, false); ++ pi.sendMessage({ customType: "background-bash-terminal-work", content: "Inference did not complete; active bash jobs remain available for recovery.", display: false, ++ details: { outcome, jobs: [...activeJobs.values()].map((job) => ({ id: job.id, sessionId: job.ownerSessionId, service: job.service === true })) } }, { triggerTurn: false }); ++ }; ++ pi.on("agent_before_settle", async (event, ctx) => { ++ if (event.outcome !== "completed") { ++ retainTerminalBackground(event.outcome); ++ return; ++ } ++ // Child Pi sessions may load PBB without pi-subagents. Await their own ++ // finite jobs before non-interactive shutdown can abort them; RPC has a UI proxy. ++ if (ctx.mode !== "tui") await Promise.all(pendingCompletionJobs().map((job) => { ++ if (!job.completion) throw new Error(`Background bash job ${job.id} has no completion promise.`); ++ return job.completion; ++ })); ++ // Queue completions in Pi's native follow-up loop before agent_settled. ++ flushPendingBackgroundResultFollowUps(pi); ++ }); ++ ++ pi.on("agent_settled", (event) => { ++ if (event.aborted) retainTerminalBackground("aborted"); + }); + + pi.on("context", (event) => { +@@ -966,19 +1089,84 @@ + if (messages) return { messages }; + }); + ++ ++ pi.registerTool({ ++ name: "background_job", ++ label: "Background job", ++ description: "Read or wait for a specific Bash job by copying the actual Handle printed in the Bash startup response (never construct an instance placeholder). Terminal results remain available while the Agent is busy; do not use subagent_wait or pgrep for Bash jobs. result is immediate; wait has a bounded timeout; stop requests owned process-group shutdown and confirms it. Persistent servers must be launched with bash service:true. This reports the shell exit code, so preserve a suite's original exit code before formatting logs.", ++ parameters: Type.Object({ ++ operation: Type.Union([Type.Literal("result"), Type.Literal("wait"), Type.Literal("stop")]), ++ handle: Type.String({ description: "Copy the actual Handle printed in the Bash result; a legacy bgNNN is resolved only in this current owner" }), ++ timeoutSeconds: Type.Optional(Type.Number({ minimum: 0, maximum: 300 })), ++ }), ++ async execute(_toolCallId, params, signal, _onUpdate, ctx) { ++ const reply = (details: Record, isError = false) => { if (isError) throw new Error(JSON.stringify(details)); return { content: [{ type: "text" as const, text: JSON.stringify(details) }], details }; }; ++ try { ++ const identity = pbbIdentity(ctx); ++ if (!identity) throw new Error("OWNER_UNAVAILABLE: persistent PBB identity is required"); ++ const candidates = () => { ++ const jobs = pbbJobsDir(identity); ++ return existsSync(jobs) ? readdirSync(jobs).filter(name => /^bg[0-9]+\.json$/.test(name)).map(name => `pbb:${identity.instanceId}:${name.slice(0, -5)}`) : []; ++ }; ++ // Local IDs are meaningful only in this process owner, never a search ++ // across old instances where the same bg number may name other work. ++ const requested = /^bg[0-9]+$/.test(params.handle) ? `pbb:${identity.instanceId}:${params.handle}` : params.handle; ++ const match = /^pbb:([A-Za-z0-9_.-]+):(bg[0-9]+)$/.exec(requested); ++ if (!match) throw new Error(`WRONG_HANDLE: copy the actual Handle printed by bash; current-owner handles: ${candidates().join(", ") || "none"}`); ++ const [, instance, local] = match; ++ const path = join(pbbSessionDir(identity), "instances", instance, "jobs", `${local}.json`); ++ const read = () => { ++ if (!existsSync(path)) throw new Error(`UNKNOWN_JOB: no retained result for this session and handle; current-owner handles: ${candidates().join(", ") || "none"}`); ++ const record = JSON.parse(readFileSync(path, "utf8")); ++ if (record.sessionKey !== identity.sessionKey || record.instanceId !== instance || record.jobId !== local) throw new Error("OWNER_MISMATCH: invalid retained job identity"); ++ return record; ++ }; ++ let record = read(); ++ const started = Date.now(); ++ const deadline = started + (params.timeoutSeconds ?? 30) * 1000; ++ const groupAlive = () => { ++ if (!Number.isInteger(record.pgid) || record.pgid <= 0) throw new Error("PROCESS_IDENTITY_MISSING: cannot confirm service shutdown"); ++ try { process.kill(-record.pgid, 0); return true; } ++ catch (error) { if ((error as NodeJS.ErrnoException).code === "ESRCH") return false; throw error; } ++ }; ++ if (params.operation === "stop") { ++ const job = activeJobs.get(local!); ++ if (instance !== identity.instanceId || !job || job.pbb?.instanceId !== instance || job.ownerSessionId !== currentPiSessionId(ctx)) throw new Error("OWNER_UNAVAILABLE: stop requires this live owner; use explicit pbb stale control for old owners"); ++ job.abortController.abort(); ++ } ++ while (params.operation !== "result") { ++ if (signal?.aborted) throw new Error("ABORTED: query cancelled; job state is retained"); ++ record = read(); ++ const terminal = !["running", "kill_requested"].includes(record.status); ++ if (params.operation === "stop" && Date.now() - started >= 500 && groupAlive()) killProcessGroup(record.pgid, "SIGKILL"); ++ if (terminal && (params.operation !== "stop" || !groupAlive())) break; ++ if (Date.now() >= deadline) return reply({ handle: requested, status: "wait_timeout", job: record, stopped: false }, true); ++ await new Promise((resolve, reject) => { ++ const done = () => { signal?.removeEventListener("abort", abort); resolve(); }; ++ const timer = setTimeout(done, 100); ++ const abort = () => { clearTimeout(timer); signal?.removeEventListener("abort", abort); reject(new Error("ABORTED: query cancelled; job state is retained")); }; ++ signal?.addEventListener("abort", abort, { once: true }); ++ }); ++ } ++ const logPath = join(pbbSessionDir(identity), "instances", instance, "logs", `${local}.log`); ++ let body = "", bytes = 0; ++ if (existsSync(logPath)) { ++ const fd = openSync(logPath, "r"); ++ try { bytes = fstatSync(fd).size; const buffer = Buffer.alloc(Math.min(bytes, MAX_RESULT_BYTES)); readSync(fd, buffer, 0, buffer.length, Math.max(0, bytes - buffer.length)); body = buffer.toString("utf8"); } ++ finally { closeSync(fd); } ++ } ++ return reply({ handle: requested, job: record, body: body.slice(-MAX_RESULT_BYTES), logPath, truncated: bytes > MAX_RESULT_BYTES, ...(params.operation === "stop" ? { stopped: true } : {}) }, record.outcome === "error" || record.status === "unknown"); ++ } catch (error) { return reply({ handle: params.handle, error: error instanceof Error ? error.message : String(error) }, true); } ++ }, ++ }); ++ + pi.registerTool({ + name: "bash", + label: "bash", +- description: `Execute a bash command in the current working directory. Returns stdout and stderr. Verbose background results are truncated with the full output available through pbb tail. Set background: true to run immediately in the background and get a job id. Otherwise, if the command is still running after the configured auto-background threshold (${formatThreshold(DEFAULT_AUTO_BACKGROUND_AFTER_SECONDS)} by default), it is automatically moved to the background; a message is injected when it finishes. Optionally provide a timeout in seconds.`, +- promptSnippet: `Execute bash commands (ls, grep, find, etc.); timeout is in seconds. Set background: true for long-running non-interactive commands. Commands still running after the configured auto-background threshold (${formatThreshold(DEFAULT_AUTO_BACKGROUND_AFTER_SECONDS)} by default) automatically move to background and wake you with a pi-background-bash result when finished.`, +- promptGuidelines: [ +- "Use bash with background: true for long-running non-interactive commands such as builds, full test suites, dev servers, watchers, deploys, downloads, or commands you do not need before the next step.", +- `Use bash normally for shell commands; Pi automatically moves bash commands that run longer than the configured auto-background threshold (${formatThreshold(DEFAULT_AUTO_BACKGROUND_AFTER_SECONDS)} by default) to the background.`, +- "When bash reports that a command started or moved to background, do not retry it just to wait; continue independent work or tell the user the job is running.", +- "Use the pbb CLI (`pbb list`, `pbb status `, `pbb tail `) only when you need progress before the completion follow-up arrives, need full truncated logs, or need to manage a job; pbb defaults to the current pi-lane runtime instance when available.", +- "When a message appears, treat it like the final result of the original bash command.", +- "Do not use bash for interactive commands that require stdin unless the user explicitly asks for that behavior.", +- ], ++ description: `Execute a bash command in the current working directory. Returns stdout and stderr. Optionally provide a timeout in seconds. Set background:true to run a long non-interactive command immediately in the background and get a job id and pbb handle for background_job; otherwise commands still running after the configured threshold (${formatThreshold(DEFAULT_AUTO_BACKGROUND_AFTER_SECONDS)} by default) automatically move to background. Set service:true for a persistent server or watcher; it starts in the background and does not delay session completion. ++A message carries the final result of the original command. Obtain that result and exit code before reporting completion. Do not retry a background command merely to wait. Verbose results are truncated; use pbb tail for full logs. Use pbb list/status/tail only for early progress, full logs, or job management; pbb defaults to the current pi-lane runtime instance, so an empty current list does not describe old jobs. After session replacement, read retained results with pbb status/tail and the returned globalJobId. ++Do not use bash for interactive commands requiring stdin unless the user explicitly asks.`, ++ promptSnippet: "Execute shell commands and manage background jobs.", + parameters: schema, + async execute(toolCallId, params, signal, onUpdate, ctx): Promise> { + const autoAfterSeconds = getAutoBackgroundAfterSeconds(ctx.cwd); +@@ -987,7 +1175,7 @@ + throw new Error("Command aborted"); + } + +- if (params.background) { ++ if (params.background || params.service) { + 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 +1184,8 @@ + id: formatJobId(nextJobNumber++), + command: params.command, + toolCallId, ++ ownerSessionId: currentPiSessionId(ctx), ++ service: params.service === true, + abortController: new AbortController(), + startedAt: Date.now(), + cwd: ctx.cwd, +@@ -1009,20 +1199,32 @@ + id: job.id, + text: job.command, + startedAt: job.startedAt, +- details: { toolCallId: job.toolCallId }, ++ details: { toolCallId: job.toolCallId, ownerSessionId: job.ownerSessionId, service: job.service }, + }); + + const completedPromise = runPbbBash(job, ctx.cwd, params); ++ const managedRuntime = (globalThis as any)[Symbol.for("braid.native-runtime.v1")]; ++ if (job.child && managedRuntime) await managedRuntime.waitManagedStartup(job.child); ++ if (job.startError) { ++ const completed = await completedPromise; ++ recordPbbJobCompleted(job, completed, ctx.cwd, Date.now() - job.startedAt); ++ activeJobs.delete(job.id); ++ pendingJobs.finish(job.id); ++ throw new Error(job.startError); ++ } + // Capture cwd eagerly: the completion callback may fire after session + // teardown (headless one-shot exit), when ctx.cwd access throws. + const jobCwd = ctx.cwd; +- void completedPromise.then((completed) => { ++ job.completion = completedPromise.then((completed) => { + deliverBackgroundResult(pi, job, completed, jobCwd); ++ return completed; + }); + scheduleDetachedBackgroundToolResultRepair(ctx, toolCallId); + + return { +- content: [{ type: "text", text: `Bash job ${job.id} started in background. A follow-up result will arrive when it finishes; continue independent work. Use pbb only if you need progress before completion.` }], ++ content: [{ type: "text", text: params.service ++ ? `Bash service ${job.id} started in background. Handle: ${job.pbb ? `pbb:${job.pbb.instanceId}:${job.id}` : "unavailable (no persistent owner identity)"}. Use background_job with this actual handle. It stays active until stopped or session shutdown; continue independent work.` ++ : `Bash job ${job.id} started in background. Handle: ${job.pbb ? `pbb:${job.pbb.instanceId}:${job.id}` : "unavailable (no persistent owner identity)"}. Use background_job with this actual handle. A follow-up result will arrive when it finishes; continue independent work. Use pbb only if you need progress before completion.` }], + details: runningJobDetails(job, ctx.cwd), + }; + } +@@ -1041,7 +1243,8 @@ + if (signal?.aborted) forwardAbort(); + else signal?.addEventListener("abort", forwardAbort, { once: true }); + try { +- const completed = await runPbbBash(job, ctx.cwd, params, onUpdate); ++ job.completion = runPbbBash(job, ctx.cwd, params, onUpdate); ++ const completed = await job.completion; + if (completed.status === "success") return truncateForegroundResult(job, completed); + rethrowBashError(completed, job); + } finally { +@@ -1078,6 +1281,7 @@ + latestBody = getText(update); + if (!backgrounded) onUpdate?.(update); + }); ++ job.completion = completedPromise; + + const winner = await Promise.race([completedPromise, waitForBackgroundThreshold(autoAfterSeconds)]); + if (winner !== "background") { +@@ -1093,6 +1297,8 @@ + job.id = formatJobId(nextJobNumber++); + job.cwd = ctx.cwd; + job.pbb = pbbIdentity(ctx); ++ job.ownerSessionId = currentPiSessionId(ctx); ++ job.service = params.service === true; + activeJobs.set(job.id, job); + recordPbbJobStarted(job, ctx.cwd); + appendPbbLogDelta(job, latestBody); +@@ -1100,19 +1306,20 @@ + id: job.id, + text: job.command, + startedAt: job.startedAt, +- details: { toolCallId: job.toolCallId }, ++ details: { toolCallId: job.toolCallId, ownerSessionId: job.ownerSessionId, service: job.service }, + }); + + // Capture cwd eagerly: the completion callback may fire after session + // teardown (headless one-shot exit), when ctx.cwd access throws. + const jobCwd = ctx.cwd; +- void completedPromise.then((completed) => { ++ job.completion = completedPromise.then((completed) => { + deliverBackgroundResult(pi, job, completed, jobCwd); ++ return completed; + }); + scheduleDetachedBackgroundToolResultRepair(ctx, toolCallId); + + return { +- content: [{ type: "text", text: `Bash job ${job.id} moved to background after ${formatThreshold(autoAfterSeconds)}. A follow-up result will arrive when it finishes; continue independent work. Use pbb only if you need progress before completion.` }], ++ content: [{ type: "text", text: `Bash job ${job.id} moved to background after ${formatThreshold(autoAfterSeconds)}. Handle: ${job.pbb ? `pbb:${job.pbb.instanceId}:${job.id}` : "unavailable (no persistent owner identity)"}. Use background_job with this actual handle. A follow-up result will arrive when it finishes; continue independent work. Use pbb only if you need progress before completion.` }], + details: runningJobDetails(job, ctx.cwd), + }; + }, +--- a/skills/pbb/SKILL.md ++++ b/skills/pbb/SKILL.md +@@ -55,3 +55,9 @@ + - If a job is ambiguous or belongs to another instance, ask before operating on it. + - `pbb kill` is intentionally conservative; same-instance live-runtime control is safest. + - Treat `owner=stale` as a warning that the owning Pi runtime may not honor mailbox requests. ++ ++## Native job results and control ++ ++Copy the actual Handle printed by Bash. Never construct an owner or instance placeholder; a legacy bg id is resolved only by the current owner. Use `background_job` with `operation: result`, `wait`, or `stop` and this exact handle. result reads retained terminal status and bounded output immediately; wait blocks only on this job for a bounded duration; stop requests this live owner to stop its process group and confirms disappearance. Errors are native tool failures with the concrete reason; timeout is not completion, and unknown/stale owner is not a safe automatic kill target. Repeated result reads retain the same job identity and log path. Do not pass Bash handles to subagent_wait or wait on all jobs merely for one suite. Declare persistent servers with `service:true`. ++ ++Preserve the original check exit status before summarizing output. PBB records the shell exit code and does not infer application assertions from grep/tail. Automatic completion notifications retain their existing lifecycle; direct result retrieval does not trigger a new Agent turn. diff --git a/native/pi/patches/pi-subagents-0.56.0-braid.patch b/native/pi/patches/pi-subagents-0.56.0-braid.patch new file mode 100644 index 00000000..28ca1da6 --- /dev/null +++ b/native/pi/patches/pi-subagents-0.56.0-braid.patch @@ -0,0 +1,943 @@ +--- a/src/extension/index.ts ++++ b/src/extension/index.ts +@@ -12,6 +12,7 @@ + * { "asyncByDefault": true, "defaultSubagentContext": "fork", "forceTopLevelAsync": true, "maxSubagentDepth": 1, "intercomBridge": { "mode": "always", "instructionFile": "./intercom-bridge.md" }, "worktreeSetupHook": "./scripts/setup-worktree.mjs" } + */ + ++import { snapshotBackgroundWork } from "../api/background-work.ts"; + import { randomUUID } from "node:crypto"; + import * as fs from "node:fs"; + import * as os from "node:os"; +@@ -54,7 +55,7 @@ + import registerSubagentNotify, { parseSubagentNotifyContent, type SubagentNotifyDetails } from "../runs/background/notify.ts"; + import { formatSteeringNotice, handleSubagentSteeringNotice, SUBAGENT_STEERING_MESSAGE_TYPE, type SubagentSteeringMessageDetails } from "./steering-notices.ts"; + import { SUBAGENT_CHILD_ENV, SUBAGENT_PARENT_SESSION_ENV } from "../runs/shared/pi-args.ts"; +-import { resolveCurrentSubagentCapabilityCeiling } from "../runs/shared/capability-ceiling.ts"; ++import { isAgentAllowedByCapabilityCeiling, resolveCurrentSubagentCapabilityCeiling } from "../runs/shared/capability-ceiling.ts"; + import { formatDuration, shortenPath } from "../shared/formatters.ts"; + import { loadConfig, resolveAsyncByDefault, resolveScheduledStoreRoot } from "./config.ts"; + import { buildSubagentToolDescription, buildSubagentToolPromptMetadata } from "./tool-description.ts"; +@@ -510,6 +511,18 @@ + agents: merged.agents.map((agent) => agent.maxThinking === discovered.maxThinking ? agent : { ...agent, maxThinking: discovered.maxThinking }), + }; + }; ++ // Project only discovery metadata; role and skill bodies remain independent files. ++ if (process.env.BRAID_SUBAGENT_CATALOG === "1") { ++ pi.on("before_agent_start", (event, ctx) => { ++ const ceiling = resolveCurrentSubagentCapabilityCeiling(resolveCurrentSessionId(ctx.sessionManager)); ++ const agents = discoverAgentsForRuntime(ctx.cwd, "both").agents ++ .filter((agent) => !agent.disabled && isAgentAllowedByCapabilityCeiling(agent.name, ceiling)) ++ .sort((a, b) => a.name.localeCompare(b.name)); ++ if (!agents.length) return; ++ const catalog = agents.map((agent) => `- ${agent.name}: ${agent.description.replace(/\s+/g, " ").trim()}`).join("\n"); ++ return { systemPrompt: `${event.systemPrompt}\n\nAvailable native sub-agent roles:\n${catalog}` }; ++ }); ++ } + const { ensurePoller, refreshWidget, handleStarted, handleComplete, resetJobs, restoreActiveJobs, dispose: disposeAsyncJobTracker } = createAsyncJobTracker(pi, state, DIRS.async, { + widgetEnabled: asyncWidgetEnabled, + onJobTerminal: () => refreshResultDelivery(), +@@ -530,6 +543,11 @@ + ); + const { startResultWatcher, primeExistingResults, stopResultWatcher } = resultWatcher; + refreshResultDelivery = resultWatcher.refreshResultDelivery; ++ const managedRuntime = (globalThis as any)[Symbol.for("braid.native-runtime.v1")]; ++ const unregisterManaged = managedRuntime?.registerManagedProvider("pi-subagents", () => ({ ++ status: resultWatcher.hasUnconsumedCurrentSessionResults() ? "busy" : "quiescent", ++ reason: "result_not_consumed", ++ })); + const asyncRetentionAbort = new AbortController(); + const asyncRetentionTimer = setTimeout(async () => { + try { +@@ -717,8 +735,37 @@ + + registerWaitTool(pi, state, waitToolConfig.enabled, waitSubscriptionManager); + +- pi.on("agent_end", async (_event, ctx) => { +- if (!ctx.hasUI) await drainOutstandingWork({ state, events: pi.events }); ++ const retainTerminalBackground = (outcome: "error" | "aborted") => { ++ pi.sendMessage({ customType: "subagent-terminal-background", content: "Inference did not complete; background work and saved results remain available for recovery.", display: false, ++ details: { outcome, sessionId: state.currentSessionId, active: snapshotBackgroundWork(state.currentSessionId ?? "", Date.now()).items, ++ retained: state.currentSessionId ? listRetainedChildren(DIRS.async, state.currentSessionId) : [] } }, { triggerTurn: false }); ++ }; ++ // Pi's public boundary runs after automatic retry and compaction, before final settlement. ++ pi.on("agent_before_settle", async (event, ctx) => { ++ if (event.outcome !== "completed") { ++ retainTerminalBackground(event.outcome); ++ return; ++ } ++ if (ctx.mode !== "tui") { ++ completionNotifier.beginDrain(); ++ try { ++ let drainError: unknown; ++ try { ++ await drainOutstandingWork({ state, events: pi.events }); ++ } catch (error) { ++ drainError = error; ++ } ++ try { ++ await resultWatcher.drainCurrentSessionResults(); ++ } catch (resultError) { ++ if (drainError) throw new Error(`Background drain failed: ${String(drainError)}; result delivery failed: ${String(resultError)}`); ++ throw resultError; ++ } ++ if (drainError) throw drainError; ++ } finally { ++ completionNotifier.endDrain(); ++ } ++ } + const ownerSessionId = state.currentSessionId; + if (!ownerSessionId) return; + goalTurnId += 1; +@@ -736,6 +783,10 @@ + } catch (error) { + console.error("Failed to evaluate goal missions:", error); + } ++ }); ++ ++ pi.on("agent_settled", (event) => { ++ if (event.aborted) retainTerminalBackground("aborted"); + }); + + registerSlashCommands(pi, state, { +@@ -1031,6 +1082,7 @@ + }); + + pi.on("session_shutdown", async () => { ++ unregisterManaged?.(); + runtimeEntry.cleanup(); + await herdrStatusBridge.flush(); + }); +--- a/src/runs/background/async-execution.ts ++++ b/src/runs/background/async-execution.ts +@@ -493,7 +493,7 @@ + startupDidNotProceed?: boolean; + } + +-function spawnRunner(cfg: object, suffix: string, cwd: string, onProcessTerminal?: (proof: unknown) => void): SpawnRunnerResult { ++async function spawnRunner(cfg: object, suffix: string, cwd: string, onProcessTerminal?: (proof: unknown) => void): Promise { + if (!jitiCliPath) { + return { error: "upstream jiti for TypeScript execution could not be found; ensure package dependencies are installed" }; + } +@@ -537,7 +537,9 @@ + stdoutFd = fs.openSync(logPaths.stdoutPath, "a"); + stderrFd = fs.openSync(logPaths.stderrPath, "a"); + } +- const proc = spawn(nodeCommand, [jitiCliPath, runner, cfgPath], { ++ const managedRuntime = (globalThis as any)[Symbol.for("braid.native-runtime.v1")]; ++ if (managedRuntime && launchAsyncDir) fs.rmSync(path.join(launchAsyncDir, "native-child-startup.json"), { force: true }); ++ const proc = (managedRuntime?.spawnManaged ?? spawn)(nodeCommand, [jitiCliPath, runner, cfgPath], { + cwd, + detached: true, + stdio: ["ignore", stdoutFd ?? "ignore", stderrFd ?? "ignore"], +@@ -546,13 +548,15 @@ + ...omitExtensionBindingsEnv(process.env), + ...(piPackageRoot ? { [PI_CODING_AGENT_PACKAGE_ROOT_ENV]: piPackageRoot } : {}), + }, +- }); ++ }, { kind: "native", manifest: launchAsyncDir ? path.join(launchAsyncDir, "status.json") : undefined }); + closeFd(stdoutFd); + closeFd(stderrFd); + proc.on("error", (error) => { + console.error(`[pi-subagents] async spawn failed: ${error.message}`); + }); +- proc.once("close", (exitCode, signal) => { ++ const managedStartup = managedRuntime?.waitManagedStartup(proc); ++ proc.once("close", async (exitCode, signal) => { ++ await managedRuntime?.finishManagedProcess(proc, { exit_code: exitCode, signal, observed_at: Date.now() }); + const launch = launchConfig as { asyncDir?: unknown; id?: unknown; nestedRoute?: NestedRouteInfo; nestedSelf?: { parentRunId: string; parentStepIndex?: number; depth: number; path?: Array<{ runId: string; stepIndex?: number; agent?: string }> } }; + const asyncDir = launch.asyncDir; + const runId = launch.id; +@@ -600,7 +604,8 @@ + console.error("Failed to emit final nested process-terminal status:", error); + } + } +- onProcessTerminal?.(persisted); ++ try { onProcessTerminal?.(persisted); } ++ catch (error) { console.error("Native process terminal proof was persisted but its owning extension context could not receive it:", error); } + }); + if (typeof proc.pid !== "number") { + return { error: `async runner did not produce a pid for cwd: ${cwd}` }; +@@ -642,6 +647,27 @@ + fs.rmSync(startupPath, { force: true }); + } catch { + // Proceed is the commit point; handshake cleanup cannot turn a running revival into a start error. ++ } ++ } ++ if (managedRuntime) { ++ try { ++ await managedStartup; ++ if (launchAsyncDir) { ++ const startup = await managedRuntime.waitChildStartup(launchAsyncDir, RUNNER_STARTUP_TIMEOUT_MS); ++ if (startup.status !== "started") throw new Error(startup.reason || "Async child was not physically started."); ++ } ++ } catch (error) { ++ const message = `native_start_failed: ${error instanceof Error ? error.message : String(error)}`; ++ const terminal = await managedRuntime.finishManagedProcess(proc, { observation: "async_child_start_failed", observed_at: Date.now() }); ++ if (launchAsyncDir) { ++ try { ++ const statusPath = path.join(launchAsyncDir, "status.json"); ++ const status = JSON.parse(fs.readFileSync(statusPath, "utf-8")); ++ writePrivateAtomicJson(statusPath, { ...status, state: "failed", lastUpdate: Date.now(), error: message }); ++ } catch (persistError) { console.error("Failed to persist native async startup error:", persistError); } ++ } ++ // Proceed may already have happened; a stop proof does not undo preparation or detached child effects. ++ return { pid: proc.pid, runnerProcessInstanceId, error: message, terminationObserved: terminal?.status === "stopped", startupDidNotProceed: false }; + } + } + return { pid: proc.pid, runnerProcessInstanceId }; +@@ -1080,10 +1106,10 @@ + /** + * Execute a chain asynchronously + */ +-export function executeAsyncChain( ++export async function executeAsyncChain( + id: string, + params: AsyncChainParams, +-): AsyncExecutionResult { ++): Promise { + const { + chain, + agents, +@@ -1194,7 +1220,7 @@ + + let spawnResult: SpawnRunnerResult = {}; + try { +- spawnResult = spawnRunner( ++ spawnResult = await spawnRunner( + { + id, + steps, +@@ -1379,10 +1405,10 @@ + return path.join(asyncDir, "workflow-result.json"); + } + +-export function executeAsyncSingle( ++export async function executeAsyncSingle( + id: string, + params: AsyncSingleParams, +-): AsyncExecutionResult { ++): Promise { + const { + agent, + agentConfig, +@@ -1679,7 +1705,7 @@ + } + let spawnResult: SpawnRunnerResult = {}; + try { +- spawnResult = spawnRunner( ++ spawnResult = await spawnRunner( + { + id, + steps: [ +--- a/src/runs/background/notify.ts ++++ b/src/runs/background/notify.ts +@@ -95,6 +95,8 @@ + + export interface CompletionNotifier { + deliver(result: CompletionNotification): Promise; ++ beginDrain(): void; ++ endDrain(): void; + dispose(): void; + } + +@@ -335,6 +337,7 @@ + const batchConfig = resolveCompletionBatchConfig(options.batchConfig); + const batchers = new Map>(); + let disposed = false; ++ let draining = false; + + const settle = (items: PendingCompletion[], accepted: boolean) => { + for (const item of items) { +@@ -379,7 +382,7 @@ + triggerTurn: result.triggerTurn !== false, + resolve, + }; +- if (details.source === "foreground") { ++ if (draining || details.source === "foreground") { + emit([item]); + return completion; + } +@@ -402,6 +405,11 @@ + + return { + deliver, ++ beginDrain() { ++ draining = true; ++ for (const batcher of batchers.values()) batcher.flush(); ++ }, ++ endDrain() { draining = false; }, + dispose() { + if (disposed) return; + disposed = true; +--- a/src/runs/background/result-watcher.ts ++++ b/src/runs/background/result-watcher.ts +@@ -199,6 +199,8 @@ + primeExistingResults: (options?: { triggerTurn?: boolean }) => void; + refreshResultDelivery: () => void; + stopResultWatcher: () => void; ++ drainCurrentSessionResults: () => Promise; ++ hasUnconsumedCurrentSessionResults: () => boolean; + } { + const fsApi = deps.fs ?? fs; + const timers = deps.timers ?? { setTimeout, clearTimeout, setInterval, clearInterval }; +@@ -206,7 +208,8 @@ + const parseResult = deps.parseResult ?? ((raw: string) => JSON.parse(raw) as ResultFileData); + const deliverIntercomResults = deps.deliverIntercomResults !== false; + const pendingTriggerTurn = new Map(); +- const processing = new Set(); ++ const processing = new Map>(); ++ const acceptedResults = new Map(); + const identityCache = new Map(); + let deliveryActive = true; + let deliveryEpoch = 0; +@@ -314,6 +317,7 @@ + try { + if (publicResultFileExists(file)) fsApi.unlinkSync(publicResultPath(file)); + identityCache.delete(file); ++ acceptedResults.delete(file); + removeResultIndex(resultsDir, sessionId, runId, toolCallId); + return true; + } catch (error) { +@@ -324,8 +328,7 @@ + return true; + } + }; +- const handleResult = async (file: string, triggerTurn: boolean) => { +- if (processing.has(file)) return; ++ const processResult = async (file: string, triggerTurn: boolean) => { + let observed: ReadonlySet | undefined; + try { + if (!shouldProcessResult(file)) { +@@ -339,7 +342,6 @@ + scheduleResult(file, triggerTurn, RETRY_DELAY_MS); + return; + } +- processing.add(file); + let rereadReplacedPayload = false; + let resultPath = publicResultPath(file); + const readPublicResultIdentity = (): PublicResultIdentity | undefined => { +@@ -547,6 +549,10 @@ + scheduleResult(file, triggerTurn, RETRY_DELAY_MS); + return; + } ++ acceptedResults.set(file, { ++ state: typeof data.state === "string" ? data.state : undefined, ++ timestamp: typeof data.timestamp === "number" ? data.timestamp : undefined, ++ }); + if (markReplacedPayload()) return; + try { + data = markDeliveredNotification(publicResultPath(file), data, runId, Date.now()); +@@ -592,9 +598,17 @@ + scheduleResult(file, triggerTurn, RETRY_DELAY_MS); + } else if (!isNotFound(error)) console.error(`Failed to process subagent result file '${resultPath}':`, error); + } finally { +- processing.delete(file); + if (rereadReplacedPayload) scheduleResult(file, triggerTurn); + } ++ }; ++ ++ const handleResult = (file: string, triggerTurn: boolean): Promise => { ++ const active = processing.get(file); ++ if (active) return active; ++ const task = processResult(file, triggerTurn); ++ processing.set(file, task); ++ void task.then(() => processing.delete(file), () => processing.delete(file)); ++ return task; + }; + + state.resultFileCoalescer = createFileCoalescer((file) => { +@@ -642,6 +656,38 @@ + } catch (error) { + if (!isNotFound(error)) console.error(`Failed to scan subagent result index in '${resultsDir}':`, error); + } ++ }; ++ ++ const currentResults = () => { ++ const sessionId = state.currentSessionId; ++ if (!sessionId) throw new Error("Cannot inspect subagent results without a Pi session identity."); ++ return resultCandidateFilesForSession(resultsDir, sessionId).filter((file) => { ++ const identity = inspectResult(file)?.identity; ++ if (identity?.sessionId && (identity.sessionId !== sessionId || identity.completionOwnerId !== state.completionOwnerId)) return false; ++ try { ++ const payload = resultPayloadPath(file); ++ if (payload) { ++ const current = JSON.parse(fsApi.readFileSync(payload, "utf-8")) as ResultFileData; ++ if (hasDeliveredNotification(current)) return false; ++ const accepted = acceptedResults.get(file); ++ if (accepted && (accepted.state !== undefined || accepted.timestamp !== undefined) ++ && accepted.state === current.state && accepted.timestamp === current.timestamp) return false; ++ } ++ } catch { /* Treat unreadable results as undelivered. */ } ++ return true; ++ }); ++ }; ++ const hasUnconsumedCurrentSessionResults = () => processing.size > 0 || currentResults().length > 0; ++ const drainCurrentSessionResults = async () => { ++ const sessionId = state.currentSessionId; ++ const files = currentResults(); ++ for (const file of files) { ++ state.resultFileCoalescer.flush(file); ++ await handleResult(file, true); ++ } ++ await Promise.all(files.map((file) => processing.get(file)).filter((task): task is Promise => task !== undefined)); ++ const remaining = currentResults(); ++ if (remaining.length) throw new Error(`Subagent results were not accepted for session '${sessionId}': ${remaining.join(", ")}`); + }; + + const clearResultScan = () => { +@@ -762,8 +808,9 @@ + state.resultFileCoalescer.clear(); + pendingTriggerTurn.clear(); + processing.clear(); ++ acceptedResults.clear(); + identityCache.clear(); + }; + +- return { startResultWatcher, primeExistingResults, stopResultWatcher, refreshResultDelivery: () => { primeExistingResults(); startDemandPolling(); } }; +-} ++ return { startResultWatcher, primeExistingResults, stopResultWatcher, drainCurrentSessionResults, hasUnconsumedCurrentSessionResults, refreshResultDelivery: () => { primeExistingResults(); startDemandPolling(); } }; ++} +--- a/src/runs/background/stale-run-reconciler.ts ++++ b/src/runs/background/stale-run-reconciler.ts +@@ -1,3 +1,5 @@ ++import { getProcessStartIdentity } from "../shared/session-lease.ts"; ++import { currentCompletionOwnerId } from "../../shared/completion-owner.ts"; + import * as fs from "node:fs"; + import * as path from "node:path"; + import { writeAtomicJson } from "../../shared/atomic-json.ts"; +@@ -275,6 +277,13 @@ + + function writeFailedRepair(asyncDir: string, status: AsyncStatus, resultPath: string, now: number, reason?: string): ReconcileAsyncRunResult { + const repair = buildFailedRepair(status, asyncDir, now, reason); ++ if (reason?.startsWith("INTERRUPTED_")) { ++ repair.result.interrupted = true; ++ delete repair.result.exitCode; ++ for (const step of repair.status.steps ?? []) { ++ if (step.error?.includes("INTERRUPTED_")) delete step.exitCode; ++ } ++ } + if (repair.result.sessionId) writeAsyncResultFile(resultPath, repair.result); + writeAtomicJson(path.join(asyncDir, "status.json"), repair.status); + updateActiveRunIndex(asyncDir, repair.status.state, repair.status.toolCallId); +@@ -391,6 +400,19 @@ + } + } + ++ // A workflow continuation lives in its owning Pi process, not in status.json. ++ // A detached runner may survive parent restoration; verify its OS birth ++ // identity independently rather than using the parent's completion token. ++ const actualBirth = getProcessStartIdentity(effectiveStatus.pid); ++ const workflowHere = effectiveStatus.mode === "workflow" && effectiveStatus.pid === process.pid; ++ const lostWorkflow = workflowHere && effectiveStatus.completionOwnerId !== currentCompletionOwnerId(); ++ const unknownBirth = !effectiveStatus.processStartIdentity || !actualBirth; ++ const changedBirth = !unknownBirth && effectiveStatus.processStartIdentity !== actualBirth; ++ if (lostWorkflow || changedBirth || (unknownBirth && !workflowHere)) { ++ const reason = lostWorkflow ? "INTERRUPTED_OWNER_REPLACED" : changedBirth ? "INTERRUPTED_PROCESS_REPLACED" : "INTERRUPTED_OWNERSHIP_UNVERIFIED"; ++ return writeFailedRepair(asyncDir, effectiveStatus, resultPath, now, ++ `${reason}: retained task metadata cannot restore execution ownership. Existing results and artifacts remain available; no process was killed and no process exit code was observed.`); ++ } + const liveness = checkPidLiveness(effectiveStatus.pid, options.kill); + if (liveness !== "dead") { + const staleAfterMs = options.staleAlivePidMs ?? 24 * 60 * 60 * 1000; +--- a/src/runs/background/subagent-runner.ts ++++ b/src/runs/background/subagent-runner.ts +@@ -88,6 +88,7 @@ + import { claimRunFanoutBatch, getRunFanoutBudgetSnapshot } from "../shared/run-fanout-budget.ts"; + import { nestedSummaryFromAsyncStatus, projectNestedEvents, resolveNestedAsyncDir, writeNestedEvent } from "../shared/nested-events.ts"; + import { formatModelAttemptNote, formatSubagentModelVerificationError, isContextOverflow, isRetryableModelFailure, recordRetryableModelFailure } from "../shared/model-fallback.ts"; ++import { describeModelExclusion } from "../shared/model-exclusions.ts"; + import { + SUBAGENT_STARTUP_RETRY_DELAYS_MS, + formatSubagentExtensionConflictError, +@@ -142,7 +143,7 @@ + import { formatParallelHandoffError, formatParallelHandoffReference, parallelHandoffPath, writeParallelHandoffGroup, writePendingParallelHandoff } from "../shared/parallel-handoff.ts"; + import { resolveWatchdogConfig } from "../../watchdog/settings.ts"; + import { createBoundedByteTail, createBoundedLineReader, formatProtocolOutputLimit, MAX_CHILD_STDERR_BYTES, PI_AGGREGATE_EVENT_PROJECTOR, projectChildLifecycle, type ChildLifecycleAction, type ProtocolOutputLimit } from "../shared/child-protocol.ts"; +-import { acquireSessionLease, type SessionLeaseRequest } from "../shared/session-lease.ts"; ++import { getProcessStartIdentity, acquireSessionLease, type SessionLeaseRequest } from "../shared/session-lease.ts"; + import { buildExternalCliPrompt, runExternalCli } from "../shared/external-cli-runner.ts"; + import { runExternalJob } from "../shared/external-job-runner.ts"; + import { createOrcaProgressTab, type OrcaProgressTab } from "../shared/orca-progress-tabs.ts"; +@@ -582,13 +583,34 @@ + ...(piPackageRoot ? { piPackageRoot } : {}), + ...(piArgv1 ? { argv1: piArgv1 } : {}), + }); +- const child = spawn(spawnSpec.command, spawnSpec.args, { ++ const managedRuntime = (globalThis as any)[Symbol.for("braid.native-runtime.v1")]; ++ let child: ReturnType; ++ let nativeStartupError: string | undefined; ++ try { ++ child = (managedRuntime?.spawnManaged ?? spawn)(spawnSpec.command, spawnSpec.args, { + cwd, + stdio: ["ignore", "pipe", "pipe"], + env: spawnEnv, + windowsHide: true, + detached: process.platform !== "win32", ++ }, { kind: "native", manifest: outputFile }); ++ void managedRuntime?.waitManagedStartup(child).then((startup: { payload_pid?: number }) => { ++ if (!Number.isInteger(startup.payload_pid)) throw new Error("Managed native Pi start receipt has no payload PID."); ++ onWriterProcess?.({ state: "running", pid: startup.payload_pid! }); ++ managedRuntime.publishChildStartup(path.dirname(outputFile), "started"); ++ }).catch((error) => { ++ nativeStartupError = `native_start_failed: ${error instanceof Error ? error.message : String(error)}`; ++ managedRuntime.publishChildStartup(path.dirname(outputFile), "failed", nativeStartupError); ++ try { child.kill("SIGTERM"); } catch {} + }); ++ } catch (error) { ++ const message = `native_start_failed: ${error instanceof Error ? error.message : String(error)}`; ++ managedRuntime?.publishChildStartup(path.dirname(outputFile), "failed", message); ++ outputStream.end(); ++ onWriterProcess?.({ state: "none" }); ++ resolve({ stderr: message, exitCode: 75, messages: [], usage: emptyUsage(), toolCount: 0, durationMs: Date.now() - startedAt, error: message, finalOutput: message, outputState: "absent", processInstanceId, processTree: { state: "unknown", reason: "verification-failed", diagnostic: message } }); ++ return; ++ } + let processTreeController: OwnedProcessTreeController | undefined; + const stderrTail = createBoundedByteTail(); + const rawStdoutTail = createBoundedByteTail(); +@@ -597,9 +619,9 @@ + let model: string | undefined; + let writerRegistrationError: string | undefined; + if (typeof child.pid === "number") { +- processTreeController = createOwnedProcessTreeController(child.pid); ++ processTreeController = managedRuntime?.createManagedProcessTreeController(child) ?? createOwnedProcessTreeController(child.pid); + try { +- onWriterProcess?.({ state: "running", pid: child.pid }); ++ if (!managedRuntime) onWriterProcess?.({ state: "running", pid: child.pid }); + } catch (writerError) { + writerRegistrationError = `Failed to record revived Pi writer ownership: ${writerError instanceof Error ? writerError.message : String(writerError)}`; + trySignalChild(child, "SIGKILL"); +@@ -987,6 +1009,7 @@ + clearDrainTimers(); + }); + child.on("close", async (exitCode, signal) => { ++ await managedRuntime?.finishManagedProcess(child, { exit_code: exitCode, signal, observed_at: Date.now() }); + settled = true; + const processCloseObservedAt = Date.now(); + const processTree = processTreeController +@@ -1008,7 +1031,7 @@ + outputStream.end(); + const stderr = stderrTail.text(); + const finalOutput = getFinalOutput(messages) || rawStdoutTail.text().trim(); +- const finalError = error ?? assistantError; ++ const finalError = nativeStartupError ?? error ?? assistantError; + const forcedDrainAfterFinalSuccess = Boolean(forcedTerminationSignal || signal) && (cleanTerminalAssistantStopReceived || agentSettledReceived) && !finalError; + const signalError = isUnexplainedProcessSignal({ + processSignal: signal, +@@ -1508,6 +1531,14 @@ + }); + } + ++ if (step.modelCandidates !== undefined && step.modelCandidates.length === 0) { ++ const diagnostic = step.model ? describeModelExclusion(step.model) : undefined; ++ const error = diagnostic ++ ? `No launchable subagent model candidates; refusing ambient provider fallback. ${diagnostic}` ++ : "No launchable subagent model candidates; refusing ambient provider fallback."; ++ return omitUndefinedProperties({ agent: step.agent, context: step.context, output: error, error, success: false, exitCode: 1 }); ++ } ++ + const candidates = step.modelCandidates !== undefined + ? step.modelCandidates.length > 0 ? step.modelCandidates : [undefined] + : step.model +@@ -1808,7 +1839,8 @@ + turnBudgetExceeded: run.turnBudgetExceeded, + })) ? formatProcessSignalError(run.processSignal!) : undefined; + const error = formatSubagentExtensionConflictError( +- toolAvailabilityError ++ (run.error?.startsWith("native_start_failed:") ? run.error : undefined) ++ ?? toolAvailabilityError + ?? completionGuardError + ?? structuredError + ?? emptyOutputError +@@ -1840,7 +1872,7 @@ + toolBudget = toolBudgetState(step.toolBudget, toolMessages.length, blockedMessage ? (blockedMessage as { toolName?: string }).toolName : undefined); + } + finalResult = { ...run, exitCode: effectiveExitCode, model: candidate ?? run.model, error, structuredOutput, runtimeAcknowledgedExtensions, ...(step.agentContract ? { agentContract: step.agentContract } : {}), ...(fileMutationEffect ? { effects: { fileMutation: fileMutationEffect } } : {}) } as RunPiStreamingResult & { structuredOutput?: unknown; agentContract?: import("../../shared/types.ts").AgentContract; effects?: import("../../shared/types.ts").EffectsProjection }; +- if (run.turnBudgetExceeded) break modelAttemptsLoop; ++ if (run.turnBudgetExceeded || run.error?.startsWith("native_start_failed:")) break modelAttemptsLoop; + if (run.stopped || run.timedOut || ctx.timeoutSignal?.aborted || ctx.stopSignal?.aborted || ctx.skipAcceptance?.()) break modelAttemptsLoop; + if (attempt.success || completionGuardTriggered) break modelAttemptsLoop; + +@@ -2504,6 +2536,7 @@ + ...(config.toolBudget ? { toolBudget: initialToolBudgetState(config.toolBudget) } : {}), + ...(config.usageBudget ? { usageBudget: usageBudgetState(config.usageBudget, undefined) } : {}), + pid: process.pid, ++ processStartIdentity: getProcessStartIdentity(process.pid), + cwd, + currentStep: 0, + chainStepCount: steps.length, +@@ -3754,6 +3787,7 @@ + mode: statusPayload.mode, + cwd, + pid: process.pid, ++ processStartIdentity: getProcessStartIdentity(process.pid), + }), + ); + +@@ -3788,6 +3822,12 @@ + const thinkingOverride = step.thinkingOverrides?.[itemIndex]; + const model = thinkingOverride ? applyThinkingSuffix(step.parallel.model, thinkingOverride, true) : step.parallel.model; + const configThinking = thinkingOverride ? thinkingOverride : step.parallel.thinking; ++ if (step.parallel.modelCandidates !== undefined && step.parallel.modelCandidates.length === 0) { ++ const diagnostic = step.parallel.model ? describeModelExclusion(step.parallel.model) : undefined; ++ throw new Error(diagnostic ++ ? `No launchable subagent model candidates; refusing ambient provider fallback. ${diagnostic}` ++ : "No launchable subagent model candidates; refusing ambient provider fallback."); ++ } + const candidates = step.parallel.modelCandidates !== undefined + ? step.parallel.modelCandidates.length > 0 + ? step.parallel.modelCandidates.map((candidate) => thinkingOverride ? applyThinkingSuffix(candidate, thinkingOverride, true) ?? candidate : candidate) +@@ -5369,6 +5409,7 @@ + } + + async function runConfiguredSubagent(config: SubagentRunConfig): Promise { ++ const managedRuntime = process.env.BRAID_NATIVE_RUNTIME_MODULE ? await import(process.env.BRAID_NATIVE_RUNTIME_MODULE) : undefined; + let lease: ReturnType | undefined; + let startupCommitted = config.revivalLease === undefined; + const startupPath = path.join(config.asyncDir, "runner-startup.json"); +@@ -5400,6 +5441,10 @@ + } + } + await runSubagent(config, lease ? (writer) => lease!.updateWriter(writer) : undefined); ++ if (managedRuntime && !fs.existsSync(path.join(config.asyncDir, "native-child-startup.json"))) { ++ const status = JSON.parse(fs.readFileSync(path.join(config.asyncDir, "status.json"), "utf8")); ++ managedRuntime.publishChildStartup(config.asyncDir, "failed", status.error ?? status.steps?.find((step: any) => step.error)?.error ?? "No native Pi child was started; the retained status records the completed preparation or failure."); ++ } + } catch (error) { + if (config.revivalLease && !startupCommitted) { + try { +@@ -5408,6 +5453,7 @@ + // The parent will time out and terminate this runner if the handshake cannot be written. + } + } ++ managedRuntime?.publishChildStartup(config.asyncDir, "failed", error instanceof Error ? error.message : String(error)); + throw error; + } finally { + process.off("exit", releaseOnExit); +--- a/src/runs/background/subagent-wait.ts ++++ b/src/runs/background/subagent-wait.ts +@@ -550,9 +550,19 @@ + + let providerActive = providerSnapshot.items; + if (active.length === 0 && providerActive.length === 0) { ++ if (params.id) { ++ const retained = listAsyncRuns(deps.asyncDirRoot ?? DIRS.async, { ++ sessionId: deps.state.currentSessionId ?? undefined, resultsDir: deps.resultsDir ?? DIRS.results, ++ includeNested: false, runId: params.id, ++ }).filter(run => matchesId(run, params.id!)); ++ if (retained.length === 1 && !ACTIVE_STATES.includes(retained[0]!.state)) { ++ const run = retained[0]!; ++ return result(`Subagent ${run.id} is already ${run.state}; no live task will be waited for. ${formatAsyncRunList(retained)} Inspect its retained result and artifacts before deciding whether to start a new task.`, run.state === "failed"); ++ } ++ } + return result(params.id +- ? `No active run matched "${params.id}". Nothing to wait for.` +- : "No active async runs or registered provider work in this session. Nothing to wait for."); ++ ? `UNKNOWN_SUBAGENT: no active subagent matched "${params.id}". Bash pbb handles belong to background_job; use result or wait there.` ++ : "No active async runs or registered provider work in this session. Nothing to wait for.", Boolean(params.id)); + } + const waitParams = params.id ? { ...params, id: active[0]!.id } : params; + const initialAsyncIds = new Set(active.map((run) => run.id)); +--- a/src/runs/foreground/execution.ts ++++ b/src/runs/foreground/execution.ts +@@ -541,15 +541,31 @@ + + const exitCode = await new Promise((resolve) => { + const spawnSpec = getPiSpawnCommand(args); +- const proc = spawn(spawnSpec.command, spawnSpec.args, { ++ const managedRuntime = (globalThis as any)[Symbol.for("braid.native-runtime.v1")]; ++ let proc: ReturnType; ++ try { ++ proc = (managedRuntime?.spawnManaged ?? spawn)(spawnSpec.command, spawnSpec.args, { + cwd: options.cwd ?? runtimeCwd, + env: spawnEnv, + stdio: ["ignore", "pipe", "pipe"], + windowsHide: true, +- }); ++ }, { kind: "native", manifest: shared.jsonlPath }); ++ } catch (error) { ++ result.error = `native_start_failed: ${error instanceof Error ? error.message : String(error)}`; ++ result.finalOutput = result.error; ++ cleanupTempDir(tempDir); ++ resolve(75); ++ return; ++ } + const jsonlWriter = createJsonlWriter(shared.jsonlPath, proc.stdout); + let processClosed = false; + let lifecycleFinished = false; ++ const startup = managedRuntime?.waitManagedStartup(proc); ++ startup?.catch((error) => { ++ result.error = `native_start_failed: ${error instanceof Error ? error.message : String(error)}`; ++ result.finalOutput = result.error; ++ try { proc.kill("SIGTERM"); } catch {} ++ }); + let detached = false; + let intercomStarted = false; + let assistantError: string | undefined; +@@ -1310,7 +1326,8 @@ + childExited = true; + clearFinalDrainTimers(); + }); +- proc.on("close", (code, signal) => { ++ proc.on("close", async (code, signal) => { ++ await managedRuntime?.finishManagedProcess(proc, { exit_code: code, signal, observed_at: Date.now() }); + if (lifecycleFinished) return; + processClosed = true; + clearFinalDrainTimers(); +@@ -1361,7 +1378,7 @@ + stdoutReader.end(); + stderrReader.end(); + if (!result.error) { +- result.error = error instanceof Error ? error.message : String(error); ++ result.error = `native_start_failed: ${error instanceof Error ? error.message : String(error)}`; + } + finish(1); + }); +@@ -1917,7 +1934,7 @@ + // Preserve the legacy intercom handoff contract: once this logical run has + // been handed to a supervisor, terminating that attempt must not launch a + // startup retry or model fallback. Explicit user detach retains fallback. +- if (intercomDetached || result.timedOut || result.turnBudgetExceeded) break modelAttemptsLoop; ++ if (intercomDetached || result.timedOut || result.turnBudgetExceeded || result.error?.startsWith("native_start_failed:")) break modelAttemptsLoop; + if (attemptSucceeded) break modelAttemptsLoop; + + const startupFailure = isRetryableSubagentStartupFailure({ +--- a/src/runs/foreground/subagent-executor.ts ++++ b/src/runs/foreground/subagent-executor.ts +@@ -1,3 +1,4 @@ ++import { getProcessStartIdentity } from "../shared/session-lease.ts"; + import { randomUUID } from "node:crypto"; + import * as fs from "node:fs"; + import * as path from "node:path"; +@@ -1585,7 +1586,7 @@ + ...input.baseAgentConfig, + runner: { type: "external-job", provider: runner.provider, options: runner.options }, + }; +- const result = executeAsyncSingle(runId, compactOptional[1]>({ ++ const result = await executeAsyncSingle(runId, compactOptional[1]>({ + agent: input.target.agent, + task: input.followUp, + goal: input.followUp, +@@ -1820,7 +1821,7 @@ + const chain = wrapChainTasksForFork(attachChain, contextPolicy); + const normalized = normalizeSkillInput(input.params.skill); + const parentModel = input.parentModel; +- const result = executeAsyncChain(runId, compactOptional[1]>({ ++ const result = await executeAsyncChain(runId, compactOptional[1]>({ + chain, + task: workflowTask, + goal, +@@ -1924,7 +1925,7 @@ + const availableModels = input.ctx.modelRegistry.getAvailable().map(toModelInfo); + const parentModel = input.parentModel; + const revivalAsyncDir = path.join(DIRS.async, runId); +- const result = executeAsyncSingle(runId, compactOptional[1]>({ ++ const result = await executeAsyncSingle(runId, compactOptional[1]>({ + agent: target.agent, + task: buildRevivedAsyncTask(target as Parameters[0], effectiveFollowUp), + goal: effectiveFollowUp, +@@ -3157,7 +3158,7 @@ + ? params.model ?? (externalRunnerWithoutExplicitModel ? undefined : a.model) + : resolveEffectiveSubagentModel(params.model as string | undefined, a.model, parentModel, availableModels, a.modelProvider ?? currentProvider, modelScopes.length === 0 ? {} : { scope: modelScopes }); + const modelOverrideFromParent = inheritsParentModel(params.model as string | undefined, a.model, parentModel); +- const asyncResult = executeAsyncSingle(id, compactOptional[1]>({ ++ const asyncResult = await executeAsyncSingle(id, compactOptional[1]>({ + agent: params.agent!, + task: shouldForkAgent(contextPolicy, params.agent!) ? wrapForkTask(params.task ?? "") : (params.task ?? ""), + goal: params.task ?? "", +@@ -4429,6 +4430,7 @@ + ...(workflowSessionRoot ? { sessionRoot: workflowSessionRoot } : {}), + ...(requestParams.scheduleOrigin ? { scheduleOrigin: requestParams.scheduleOrigin } : {}), + pid: process.pid, ++ processStartIdentity: getProcessStartIdentity(process.pid), + steps: [], + workflow: { trace: [], emits: [], console: [] }, + runFanoutBudget: getRunFanoutBudgetSnapshot(workflowFanoutBudget), +--- a/src/runs/shared/model-exclusions.ts ++++ b/src/runs/shared/model-exclusions.ts +@@ -176,6 +176,31 @@ + } + + /** ++ * Return the active exclusion that blocks a full provider/model id. ++ * Callers use this only for diagnostics; it never clears or bypasses an exclusion. ++ */ ++export function findModelExclusion(fullId: string, opts?: { now?: number }): ModelExclusion | undefined { ++ ensureLoaded(); ++ const timestamp = opts?.now ?? Date.now(); ++ const { provider, modelId } = parseModelKey(fullId); ++ return exclusions.find((entry) => entryMatches(entry, modelId, provider, timestamp)); ++} ++ ++function diagnosticReason(reason: string | undefined): string { ++ if (!reason) return "provider runtime failure"; ++ if (/429|rate.?limit|quota|credit|balance/i.test(reason)) return "provider rate/quota failure"; ++ if (/401|auth|api.?key|unauthori[sz]ed/i.test(reason)) return "provider authentication failure"; ++ return "provider runtime failure"; ++} ++ ++/** Format an active exclusion without exposing stored provider error text. */ ++export function describeModelExclusion(fullId: string, opts?: { now?: number }): string | undefined { ++ const entry = findModelExclusion(fullId, opts); ++ if (!entry) return undefined; ++ return `model '${fullId}' is excluded until ${new Date(entry.expiresAt).toISOString()} (${diagnosticReason(entry.reason)}).`; ++} ++ ++/** + * Number of live (non-expired) exclusions. + */ + export function getExcludedCount(): number { +--- a/src/runs/shared/model-fallback.ts ++++ b/src/runs/shared/model-fallback.ts +@@ -1,6 +1,6 @@ + import { splitKnownThinkingSuffix, type ModelInfo as AvailableModelInfo } from "../../shared/model-info.ts"; + import type { Usage } from "../../shared/types.ts"; +-import { filterFallbackCandidates, parseModelKey, recordModelFailure } from "./model-exclusions.ts"; ++import { describeModelExclusion, filterFallbackCandidates, parseModelKey, recordModelFailure } from "./model-exclusions.ts"; + import { checkModelScope, type ModelScopeCheckRule, type ModelScopeViolation, type ModelSource } from "./model-scope.ts"; + + export type { AvailableModelInfo }; +@@ -394,7 +394,15 @@ + seen.add(normalized); + candidates.push(normalized); + } +- return filterFallbackCandidates(candidates); ++ const filtered = filterFallbackCandidates(candidates); ++ if (candidates.length > 0 && filtered.length === 0) { ++ const details = candidates ++ .map((candidate) => describeModelExclusion(candidate)) ++ .filter((detail): detail is string => detail !== undefined) ++ .join(" "); ++ throw new Error(`All requested subagent model candidates are temporarily excluded; refusing ambient provider fallback. ${details}`.trim()); ++ } ++ return filtered; + } + + const RETRYABLE_MODEL_FAILURE_PATTERNS = [ +--- a/src/runs/shared/pi-args.ts ++++ b/src/runs/shared/pi-args.ts +@@ -453,7 +453,9 @@ + ? ["read", ...requestedBuiltinTools] + : requestedBuiltinTools + ).filter((tool) => !allowedToolSet || allowedToolSet.has(tool)); +- const fanoutAuthorized = declaredBuiltinTools.includes("subagent"); ++ const fanoutAuthorized = ++ declaredBuiltinTools.includes("subagent") || ++ (input.tools === undefined && allowedToolSet === undefined); + const toolExtensionPaths: string[] = capabilityCeiling?.denyExtensions + ? [] + : (input.tools ?? []).filter( +--- a/src/runs/shared/session-lease.ts ++++ b/src/runs/shared/session-lease.ts +@@ -1,4 +1,5 @@ + import { createHash, randomUUID } from "node:crypto"; ++import { execFileSync } from "node:child_process"; + import * as fs from "node:fs"; + import * as os from "node:os"; + import * as path from "node:path"; +@@ -65,7 +66,7 @@ + } + } + +-function getProcessStartIdentity(pid: number): string | undefined { ++export function getProcessStartIdentity(pid: number): string | undefined { + if (process.platform === "linux") { + try { + const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf-8"); +@@ -77,6 +78,12 @@ + } catch { + return undefined; + } ++ } ++ if (process.platform === "darwin") { ++ try { ++ const birth = execFileSync("/bin/ps", ["-p", String(pid), "-o", "lstart="], { encoding: "utf-8", timeout: 2000 }).trim(); ++ return birth ? `darwin:${birth}` : undefined; ++ } catch { return undefined; } + } + return undefined; + } +--- a/src/shared/types.ts ++++ b/src/shared/types.ts +@@ -1450,6 +1450,8 @@ + runId: string; + /** Parent Pi process/window that owns local completion delivery. */ + completionOwnerId?: string; ++ /** OS process birth identity, never PID liveness alone. */ ++ processStartIdentity?: string; + /** Host tool-call id retained when it differs from the internal run id. */ + toolCallId?: string; + sessionId?: string; +--- a/src/shared/utils.ts ++++ b/src/shared/utils.ts +@@ -307,6 +307,10 @@ + * Get the final text output from a list of messages + */ + export function getFinalOutput(messages: Message[]): string { ++ const lastAssistant = messages.findLast((message) => message.role === "assistant"); ++ if (lastAssistant?.role === "assistant" && lastAssistant.stopReason === "length") { ++ return `[结果不完整:stopReason=length,回答因长度限制截断。保留以下部分内容;按需仅补缺失部分,不必重做已完成工作。]\n\n${extractTextFromContent(lastAssistant.content)}`; ++ } + const validTextParts: string[] = []; + for (let i = messages.length - 1; i >= 0; i--) { + const msg = messages[i]; +@@ -509,6 +513,15 @@ + * Detect errors in subagent execution from messages (only errors with no subsequent success) + */ + export function detectSubagentError(messages: Message[]): ErrorInfo { ++ const lastAssistant = messages.findLast((message) => message.role === "assistant"); ++ if (lastAssistant?.role === "assistant" && lastAssistant.stopReason === "length") { ++ return { ++ hasError: true, ++ exitCode: 1, ++ errorType: "response", ++ details: "stopReason=length:回答因长度限制截断,已有部分内容已保留;是否补齐缺失内容由调用者决定。", ++ }; ++ } + let lastAssistantTextIndex = -1; + for (let i = messages.length - 1; i >= 0; i--) { + const msg = messages[i]; +--- a/src/runs/shared/external-job-bridge.ts ++++ b/src/runs/shared/external-job-bridge.ts +@@ -1,3 +1,4 @@ ++import { getProcessStartIdentity as sharedProcessStartIdentity } from "./session-lease.ts"; + import { randomUUID } from "node:crypto"; + import * as fs from "node:fs"; + import * as os from "node:os"; +@@ -127,6 +128,7 @@ + } + + function processStartIdentity(pid: number): string | undefined { ++ if (process.platform === "darwin") return sharedProcessStartIdentity(pid); + if (process.platform === "linux") { + try { + const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf-8"); +--- a/src/runs/background/async-retention.ts ++++ b/src/runs/background/async-retention.ts +@@ -1,3 +1,4 @@ ++import { getProcessStartIdentity as sharedProcessStartIdentity } from "../shared/session-lease.ts"; + import { spawnSync } from "node:child_process"; + import * as fs from "node:fs"; + import * as os from "node:os"; +@@ -318,6 +319,7 @@ + } + + function processStartIdentity(pid: number): string | undefined { ++ if (process.platform === "darwin") return sharedProcessStartIdentity(pid); + if (process.platform === "linux") { + try { + const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf-8"); +--- a/src/missions/workflow-state.ts ++++ b/src/missions/workflow-state.ts +@@ -1,3 +1,4 @@ ++import { getProcessStartIdentity } from "../runs/shared/session-lease.ts"; + import { execFileSync } from "node:child_process"; + import { randomUUID } from "node:crypto"; + import * as fs from "node:fs"; +@@ -67,6 +68,7 @@ + } + + function processStartKey(pid: number): string | undefined { ++ if (process.platform === "darwin") return getProcessStartIdentity(pid); + if (process.platform === "linux") return linuxProcessStartKey(pid) ?? psProcessStartKey(pid); + if (process.platform === "win32") return windowsProcessStartKey(pid); + return undefined; diff --git a/native/pi/pi b/native/pi/pi new file mode 100755 index 00000000..2a963504 --- /dev/null +++ b/native/pi/pi @@ -0,0 +1,2 @@ +#!/bin/sh +exec "$(dirname "$0")/bin/node" "$(dirname "$0")/pi.mjs" "$@" diff --git a/native/pi/pi.mjs b/native/pi/pi.mjs new file mode 100644 index 00000000..8fdaf5ba --- /dev/null +++ b/native/pi/pi.mjs @@ -0,0 +1,47 @@ +#!/usr/bin/env node +import fs from 'node:fs'; +import path from 'node:path'; +import os from 'node:os'; +import { preserveToolConfig } from './tool-environment.mjs'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +const directory = path.dirname(fileURLToPath(import.meta.url)); +const args = process.argv.slice(2); +const informational = args.includes('--version') || args.includes('-v') || args.includes('--help') || args.includes('-h'); +if (informational) { + const pi = await import('@earendil-works/pi-coding-agent'); + if (args.includes('--version') || args.includes('-v')) process.stdout.write(`${pi.VERSION}\n`); + else process.stdout.write(`Pi coding agent\n\nUsage: pi [options] [messages...]\n\n --mode Select output mode\n -p, --print Run one non-interactive prompt\n -c, --continue Continue the most recent session\n -r, --resume Resume the most recent session\n --session Open a saved session\n --session-dir Set session storage\n --model Select a model\n --provider Select a provider\n --thinking Set reasoning level\n -e, --extension Load an extension\n --skill Load a skill\n --no-extensions Disable extension discovery\n --no-skills Disable skill discovery\n -h, --help Show this help\n -v, --version Show the Pi version\n`); +} else { + // Native tools consume the configured environment, not ambient shell startup files. + delete process.env.BASH_ENV; + delete process.env.ENV; + const manifest = JSON.parse(fs.readFileSync(path.join(directory, 'runtime-manifest.json'), 'utf8')); + for (const name of ['BRAID_NATIVE_EXECUTION_DIR', 'BRAID_NATIVE_EXECUTION_ID', 'BRAID_NATIVE_START_ID']) { + if (!process.env[name]) throw new Error(`${name} is required: launch this Pi runtime through Braid's native execution owner.`); + } + const nativeHome = process.env.PI_CODING_AGENT_DIR; + if (!nativeHome || !path.isAbsolute(nativeHome)) throw new Error('PI_CODING_AGENT_DIR must be an absolute, persistent Braid native home.'); + preserveToolConfig(process.env, os.homedir()); + for (const [name, relative] of Object.entries({ TMPDIR: 'tmp', XDG_CACHE_HOME: 'cache', XDG_DATA_HOME: 'data', XDG_CONFIG_HOME: 'config' })) { + const value = path.join(process.env.BRAID_NATIVE_EXECUTION_DIR, relative); + fs.mkdirSync(value, { recursive: true, mode: 0o700 }); + process.env[name] = value; + } + process.env.PBB_ROOT = path.join(nativeHome, 'pbb'); + process.env.PI_LANE_ROOT = path.join(nativeHome, 'pi-lane'); + process.env.BRAID_AGENT_RUNTIME = '1'; + process.env.BRAID_NATIVE_RUNTIME_MODULE = pathToFileURL(path.join(directory, manifest.managed_module.path)).href; + process.env.PI_SUBAGENT_PI_BINARY = path.join(directory, 'pi'); + process.env.PI_CODING_AGENT_PACKAGE_ROOT = path.join(directory, 'node_modules/@earendil-works/pi-coding-agent'); + process.env.PATH = `${path.join(directory, 'bin')}${path.delimiter}${path.join(directory, 'node_modules/.bin')}${path.delimiter}${process.env.PATH ?? ''}`; + process.env.BRAID_SUBAGENT_CATALOG = manifest.plugins.some(plugin => plugin.name === 'subagents') ? '1' : '0'; + process.env.BRAID_NATIVE_SUBAGENTS_ENABLED = manifest.plugins.some(plugin => plugin.name === 'subagents') ? '1' : '0'; + process.env.BRAID_NATIVE_MCPORTER_ENABLED = manifest.plugins.some(plugin => plugin.name === 'mcporter') ? '1' : '0'; + await import(process.env.BRAID_NATIVE_RUNTIME_MODULE); + const selected = manifest.plugins.flatMap(plugin => plugin.extension_paths.flatMap(relative => ['-e', path.join(directory, relative)])); + const skills = manifest.plugins.flatMap(plugin => plugin.skill_paths.flatMap(relative => ['--skill', path.join(directory, relative)])); + process.argv.splice(2, 0, '--no-extensions', ...selected, ...skills); + const sdk = await import('./sdk-host.mjs'); + await sdk.main(); +} diff --git a/native/pi/plugins/background/package.json b/native/pi/plugins/background/package.json new file mode 100644 index 00000000..835af1c5 --- /dev/null +++ b/native/pi/plugins/background/package.json @@ -0,0 +1,8 @@ +{ + "name": "@braid/pi-runtime-background", + "version": "1.0.0", + "private": true, + "dependencies": { + "pi-background-bash": "1.0.5" + } +} diff --git a/native/pi/plugins/context7/package.json b/native/pi/plugins/context7/package.json new file mode 100644 index 00000000..5157b0af --- /dev/null +++ b/native/pi/plugins/context7/package.json @@ -0,0 +1,8 @@ +{ + "name": "@braid/pi-runtime-context7", + "version": "1.0.0", + "private": true, + "dependencies": { + "@upstash/context7-pi": "0.1.2" + } +} diff --git a/native/pi/plugins/fff/package.json b/native/pi/plugins/fff/package.json new file mode 100644 index 00000000..eb21c744 --- /dev/null +++ b/native/pi/plugins/fff/package.json @@ -0,0 +1,8 @@ +{ + "name": "@braid/pi-runtime-fff", + "version": "1.0.0", + "private": true, + "dependencies": { + "@ff-labs/pi-fff": "0.11.0" + } +} diff --git a/native/pi/plugins/mcporter/package.json b/native/pi/plugins/mcporter/package.json new file mode 100644 index 00000000..2564f99b --- /dev/null +++ b/native/pi/plugins/mcporter/package.json @@ -0,0 +1,8 @@ +{ + "name": "@braid/pi-runtime-mcporter", + "version": "1.0.0", + "private": true, + "dependencies": { + "mcporter": "0.14.0" + } +} diff --git a/native/pi/plugins/subagents/package.json b/native/pi/plugins/subagents/package.json new file mode 100644 index 00000000..e6a03f2f --- /dev/null +++ b/native/pi/plugins/subagents/package.json @@ -0,0 +1,8 @@ +{ + "name": "@braid/pi-runtime-subagents", + "version": "1.0.0", + "private": true, + "dependencies": { + "pi-subagents": "0.56.0" + } +} diff --git a/native/pi/process-owner.mjs b/native/pi/process-owner.mjs new file mode 100644 index 00000000..006fad1f --- /dev/null +++ b/native/pi/process-owner.mjs @@ -0,0 +1,161 @@ +import { spawn, spawnSync } from 'node:child_process'; +import * as fs from 'node:fs'; +import path from 'node:path'; +import { randomUUID } from 'node:crypto'; +import { fileURLToPath } from 'node:url'; +export const pause = ms => new Promise(resolve => setTimeout(resolve, ms)); +export function writeJson(file, value) { + fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 }); + const temporary = `${file}.${process.pid}.${randomUUID()}.tmp`; + fs.writeFileSync(temporary, `${JSON.stringify(value)}\n`, { mode: 0o600 }); + fs.renameSync(temporary, file); +} +function inspectionEnv() { + const { BRAID_NATIVE_EXECUTION_ID: _execution, BRAID_NATIVE_START_ID: _start, BRAID_NATIVE_LAUNCH_START_ID: _launch, ...env } = process.env; + return { ...env, LC_ALL: 'C' }; +} +function command(args) { + const result = spawnSync(args[0], args.slice(1), { encoding: 'utf8', maxBuffer: 32 * 1024 * 1024, env: inspectionEnv() }); + if (result.error || result.status !== 0) throw result.error ?? new Error(`${args[0]}: ${result.stderr.trim()}`); + return result.stdout; +} +export function bootIdentity() { + if (process.platform === 'linux') return fs.readFileSync('/proc/sys/kernel/random/boot_id', 'utf8').trim(); + if (process.platform === 'darwin') { + const identity = command(['/usr/sbin/sysctl', '-n', 'kern.bootsessionuuid']).trim(); + if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(identity)) throw new Error('macOS boot session identity is unavailable.'); + return identity.toLowerCase(); + } + throw new Error(`Native ownership is unsupported on ${process.platform}.`); +} +export function processIdentity(pid) { + if (process.platform === 'linux') { + try { + const raw = fs.readFileSync(`/proc/${pid}/stat`, 'utf8'); + const fields = raw.slice(raw.lastIndexOf(')') + 2).split(' '); + return { pid, ppid: Number(fields[1]), pgid: Number(fields[2]), starttime: fields[19], state: fields[0] }; + } catch (error) { if (['ENOENT', 'ESRCH'].includes(error.code)) return undefined; throw error; } + } + const result = spawnSync('/bin/ps', ['-p', String(pid), '-o', 'pid=,ppid=,pgid=,lstart=,state='], { encoding: 'utf8', env: inspectionEnv() }); + if (result.error) throw result.error; + if (result.status === 1 && !result.stdout.trim()) return undefined; + if (result.status !== 0) throw new Error(`ps identity failed: ${result.stderr.trim()}`); + const row = result.stdout.trim().match(/^(\d+)\s+(\d+)\s+(\d+)\s+(.+?)\s+(\S+)$/); + if (!row) throw new Error(`Cannot parse process identity for ${pid}.`); + return { pid: Number(row[1]), ppid: Number(row[2]), pgid: Number(row[3]), starttime: row[4], state: row[5] }; +} +export function processMarkers(pid) { + let raw; + if (process.platform === 'linux') raw = fs.readFileSync(`/proc/${pid}/environ`, 'utf8').replaceAll('\0', ' '); + else raw = command(['/bin/ps', 'eww', '-p', String(pid), '-o', 'command=']); + // Only these random ownership markers leave the environment inspection. + return { owner: raw.match(/(?:^|\s)BRAID_NATIVE_EXECUTION_ID=([^\s]+)/)?.[1], startId: raw.match(/(?:^|\s)BRAID_NATIVE_LAUNCH_START_ID=([^\s]+)/)?.[1] ?? raw.match(/(?:^|\s)BRAID_NATIVE_START_ID=([^\s]+)/)?.[1] }; +} +export function processSnapshot() { + if (process.platform === 'darwin') { + const snapshot = spawnSync('/bin/ps', ['eww', '-axo', 'pid=,ppid=,pgid=,lstart=,state=,command='], { encoding: 'utf8', maxBuffer: 32 * 1024 * 1024, env: inspectionEnv() }); + if (snapshot.error || snapshot.status !== 0) throw snapshot.error ?? new Error(`ps snapshot: ${snapshot.stderr.trim()}`); + return snapshot.stdout.split('\n').filter(Boolean).flatMap(raw => { + const row = raw.trim().match(/^(\d+)\s+(\d+)\s+(\d+)\s+(.+?\d{4})\s+(\S+)\s+(.*)$/); + if (!row) throw new Error('Cannot parse macOS process ownership snapshot.'); + if (/^[ZX]/.test(row[5]) || Number(row[1]) === snapshot.pid) return []; + const command = row[6]; + return [{ pid: Number(row[1]), ppid: Number(row[2]), pgid: Number(row[3]), starttime: row[4], state: row[5], owner: command.match(/(?:^|\s)BRAID_NATIVE_EXECUTION_ID=([^\s]+)/)?.[1], startId: command.match(/(?:^|\s)BRAID_NATIVE_LAUNCH_START_ID=([^\s]+)/)?.[1] ?? command.match(/(?:^|\s)BRAID_NATIVE_START_ID=([^\s]+)/)?.[1] }]; + }); + } + const ids = process.platform === 'linux' ? fs.readdirSync('/proc').filter(name => /^\d+$/.test(name)).map(Number) : command(['/bin/ps', '-axo', 'pid=']).trim().split(/\s+/).map(Number); + const result = []; + for (const pid of ids) { + const identity = processIdentity(pid); + if (!identity || /^[ZX]/.test(identity.state)) continue; + let ownership = {}; + try { ownership = processMarkers(pid); } + catch (error) { + if (!processIdentity(pid)) continue; + ownership = { marker_error: error.message }; + } + // Recheck birth after reading markers; a reused PID is never associated. + const after = processIdentity(pid); + if (after && after.starttime === identity.starttime) result.push({ ...identity, ...ownership }); + } + return result; +} +export async function withAdmission(directory, operation) { + fs.mkdirSync(directory, { recursive: true, mode: 0o700 }); + const lock = path.join(directory, 'admission.lock'); + const deadline = Date.now() + 10000; + for (;;) { + try { fs.mkdirSync(lock, { mode: 0o700 }); break; } + catch (error) { if (error.code !== 'EEXIST') throw error; if (Date.now() >= deadline) throw new Error('Native admission lock unavailable; refusing stale lock takeover.'); await pause(10); } + } + try { return await operation(); } finally { fs.rmdirSync(lock); } +} +async function launch(args) { + const divider = args.indexOf('--'); + if (divider < 0 || !args[divider + 1]) throw new Error('launch requires -- COMMAND ARGS'); + const value = name => args[args.indexOf(name) + 1]; + const directory = process.env.BRAID_NATIVE_EXECUTION_DIR; + const id = process.env.BRAID_NATIVE_EXECUTION_ID; + const startId = value('--start-id'); + if (!directory || !id || !startId || !/^[a-zA-Z0-9-]+$/.test(startId)) throw new Error('Native launch identity unavailable.'); + const receipt = path.join(directory, 'starts', `${startId}.json`); + let child; + let closed; + await withAdmission(directory, async () => { + let parent = process.env.BRAID_NATIVE_START_ID; + let fenced = fs.existsSync(path.join(directory, 'stopping.json')) || fs.existsSync(path.join(directory, 'fences', `${startId}.json`)); + const visited = new Set(); + while (parent && !fenced) { + if (visited.has(parent)) throw new Error('Native ownership parent cycle.'); + visited.add(parent); + fenced = fs.existsSync(path.join(directory, 'fences', `${parent}.json`)); + const parentRecord = JSON.parse(fs.readFileSync(path.join(directory, 'processes', `${parent}.json`), 'utf8')); + if (parentRecord.execution_id !== id) throw new Error('Native parent execution identity mismatch.'); + parent = parentRecord.parent_start_id; + } + if (fenced) { + writeJson(receipt, { status: 'start_rejected', reason: 'execution_stopping', execution_id: id, start_id: startId }); + throw new Error('Execution admission fenced.'); + } + const identity = processIdentity(process.pid); + if (!identity || identity.pgid !== process.pid) throw new Error('Native launcher requires its own detached process group.'); + const recordPath = path.join(directory, 'processes', `${startId}.json`); + if (fs.existsSync(recordPath) || fs.existsSync(receipt)) throw new Error('Native start identity cannot be reused.'); + const record = { schema_version: 1, execution_id: id, start_id: startId, parent_start_id: process.env.BRAID_NATIVE_START_ID ?? null, boot_id: bootIdentity(), kind: args.includes('--kind') ? value('--kind') : 'tool', service: args.includes('--service'), ...identity, created_at: Date.now() }; + if (args.includes('--manifest')) record.manifest_path = value('--manifest'); + writeJson(recordPath, record); + const { BRAID_NATIVE_LAUNCH_START_ID: _launcherMarker, ...payloadEnv } = process.env; + child = spawn(args[divider + 1], args.slice(divider + 2), { stdio: 'inherit', env: { ...payloadEnv, BRAID_NATIVE_START_ID: startId } }); + // Retain close before any asynchronous startup observation, including tiny commands. + closed = new Promise(resolve => { child.once('error', error => resolve({ error: error.message })); child.once('close', (code, signal) => resolve({ code, signal })); }); + await new Promise((resolve, reject) => { child.once('spawn', resolve); child.once('error', reject); }); + const payloadIdentity = processIdentity(child.pid); + if (payloadIdentity) { + if (payloadIdentity.pgid !== record.pgid) throw new Error('Payload escaped its registered process group during startup.'); + record.payload_identity = payloadIdentity; + writeJson(recordPath, record); + } + writeJson(receipt, { status: 'started', execution_id: id, start_id: startId, process_record: recordPath, pid: process.pid, payload_pid: child.pid, observed_at: Date.now() }); + }); + for (const signal of ['SIGTERM', 'SIGINT']) process.on(signal, () => { try { child.kill(signal); } catch {} }); + const close = await closed; + writeJson(path.join(directory, 'closes', `${startId}.json`), { execution_id: id, start_id: startId, ...close, observed_at: Date.now() }); + if (close.error) { console.error(close.error); process.exitCode = 126; } + else if (close.signal) { + process.removeAllListeners(close.signal); + process.kill(process.pid, close.signal); + } else process.exitCode = close.code ?? 128; +} +if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + if (process.argv[2] !== 'launch') throw new Error('Usage: process-owner.mjs launch --start-id ID -- COMMAND ARGS'); + try { await launch(process.argv.slice(3)); } catch (error) { + const args = process.argv.slice(3); + const startId = args[args.indexOf('--start-id') + 1]; + const directory = process.env.BRAID_NATIVE_EXECUTION_DIR; + if (directory && /^[a-zA-Z0-9-]+$/.test(startId ?? '')) { + const receipt = path.join(directory, 'starts', `${startId}.json`); + if (!fs.existsSync(receipt)) writeJson(receipt, { status: 'start_failed', execution_id: process.env.BRAID_NATIVE_EXECUTION_ID, start_id: startId, reason: error.message, observed_at: Date.now() }); + } + console.error(error.message); process.exitCode = 75; + } +} diff --git a/native/pi/rpc-adapter.mjs b/native/pi/rpc-adapter.mjs new file mode 100644 index 00000000..579816dd --- /dev/null +++ b/native/pi/rpc-adapter.mjs @@ -0,0 +1,100 @@ +import { PassThrough } from 'node:stream'; +import readline from 'node:readline'; + +const BRAID_CAPABILITIES = ['retry_intent', 'settle_extensions', 'owned_inference', 'managed_execution', 'owned_stop']; +const success = (id, command, data) => ({ id, type: 'response', command, success: true, data }); + +function runtimeState(runtime, policy, managedRuntime, piVersion) { + const session = runtime.session; + const deferred = policy.sessionState.pendingInputs; + const managed = policy.sessionState.queueFailure + ? { status: 'unknown', reason: `deferred_input_preservation_failed: ${policy.sessionState.queueFailure}`, execution_id: process.env.BRAID_NATIVE_EXECUTION_ID } + : policy.sessionState.hookErrors.length + ? { status: 'unknown', reason: 'extension_hook_failure_stop', execution_id: process.env.BRAID_NATIVE_EXECUTION_ID } + : deferred.length + ? { status: 'busy', reason: 'deferred_native_inputs', execution_id: process.env.BRAID_NATIVE_EXECUTION_ID } + : managedRuntime.managedState(session); + const extensions = runtime.services.resourceLoader.getExtensions(); + return { + managed_state: managed, + braid_native_runtime: { + schema_version: 1, + pi_version: piVersion, + capabilities: BRAID_CAPABILITIES, + execution_id: process.env.BRAID_NATIVE_EXECUTION_ID, + extensions: extensions.extensions.map(extension => extension.path), + extension_errors: extensions.errors, + hook_failure_stop_requested: policy.sessionState.hookErrors.length > 0, + hook_errors: policy.sessionState.hookErrors.map(({ extensionPath, event, error }) => ({ extension_path: extensionPath, event, error })), + ...(policy.sessionState.abortError ? { hook_failure_stop_error: policy.sessionState.abortError } : {}), + deferred_inputs: deferred.map(({ id, steering, followUp, error }) => ({ + id, + steering_count: steering.length, + follow_up_count: followUp.length, + error, + })), + ...(policy.sessionState.queueFailure ? { deferred_input_error: policy.sessionState.queueFailure } : {}), + }, + }; +} + +function decorateStateResponse(line, runtime, policy, managedRuntime, piVersion) { + if (!line.endsWith('\n')) return line; + const payload = line.slice(0, -1); + let value; + try { value = JSON.parse(payload); } catch { return line; } + if (value?.type === 'response' && value.command === 'get_state' && value.success && value.data) { + Object.assign(value.data, runtimeState(runtime, policy, managedRuntime, piVersion)); + return `${JSON.stringify(value)}\n`; + } + return line; +} + +export async function runBraidRpcMode(runtime, policy, managedRuntime, piVersion, runRpcMode) { + const originalInput = process.stdin; + const rpcInput = new PassThrough(); + Object.defineProperty(process, 'stdin', { configurable: true, value: rpcInput }); + + const originalWrite = process.stdout.write.bind(process.stdout); + process.stdout.write = function writeWithBraidState(chunk, encodingOrCallback, callback) { + const encoding = typeof encodingOrCallback === 'string' ? encodingOrCallback : undefined; + const done = typeof encodingOrCallback === 'function' ? encodingOrCallback : callback; + const text = Buffer.isBuffer(chunk) ? chunk.toString(encoding) : String(chunk); + return originalWrite(decorateStateResponse(text, runtime, policy, managedRuntime, piVersion), done); + }; + + const response = (value) => originalWrite(`${JSON.stringify(value)}\n`); + const input = readline.createInterface({ input: originalInput, crlfDelay: Infinity }); + let chain = Promise.resolve(); + input.on('line', line => { + chain = chain.then(async () => { + let command; + try { + try { command = JSON.parse(line); } catch { rpcInput.write(`${line}\n`); return; } + if (command?.type === 'stop_owned_execution') { + response(success(command.id, command.type, await managedRuntime.cleanupOwnedExecution({ skipSelf: true }))); + return; + } + if (command?.type === 'yield_stoppable_services') { + const managedState = policy.sessionState.queueFailure + ? { status: 'unknown', reason: `deferred_input_preservation_failed: ${policy.sessionState.queueFailure}`, execution_id: process.env.BRAID_NATIVE_EXECUTION_ID } + : policy.sessionState.hookErrors.length + ? { status: 'unknown', reason: 'extension_hook_failure_stop', execution_id: process.env.BRAID_NATIVE_EXECUTION_ID } + : policy.sessionState.pendingInputs.length + ? { status: 'busy', reason: 'deferred_native_inputs', execution_id: process.env.BRAID_NATIVE_EXECUTION_ID } + : await managedRuntime.yieldStoppableServices(runtime.session); + response(success(command.id, command.type, { managed_state: managedState })); + return; + } + if (['prompt', 'steer', 'follow_up'].includes(command?.type)) await policy.restorePendingInputs(); + rpcInput.write(`${line}\n`); + } catch (error) { + response({ id: command?.id, type: 'response', command: command?.type ?? 'braid_adapter', success: false, error: error instanceof Error ? error.message : String(error) }); + } + }); + }); + input.on('close', () => { void chain.finally(() => rpcInput.end()); }); + input.on('error', error => { process.stderr.write(`Braid Pi RPC input failed: ${error.message}\n`); rpcInput.destroy(error); }); + + return runRpcMode(runtime); +} diff --git a/native/pi/sdk-host.mjs b/native/pi/sdk-host.mjs new file mode 100644 index 00000000..6f99c3c8 --- /dev/null +++ b/native/pi/sdk-host.mjs @@ -0,0 +1,373 @@ +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { + createAgentSessionFromServices, + createAgentSessionRuntime, + createAgentSessionServices, + createBashToolDefinition, + getShellConfig, + ModelRuntime, + parseArgs, + resolveCliModel, + runPrintMode, + runRpcMode, + SessionManager, + SettingsManager, + VERSION, + detectSupportedImageMimeTypeFromFile, +} from '@earendil-works/pi-coding-agent'; +import { runBraidRpcMode } from './rpc-adapter.mjs'; + +const managedRuntime = await import(process.env.BRAID_NATIVE_RUNTIME_MODULE); + +function absolutePath(value, cwd) { + const expanded = value.startsWith('~/') ? path.join(os.homedir(), value.slice(2)) : value; + return path.resolve(cwd, expanded); +} + +function assertSupportedCliOptions(args) { + const unsupported = [ + [args.models !== undefined, '--models'], + [args.listModels !== undefined, '--list-models'], + [args.export !== undefined, '--export'], + [args.offline, '--offline'], + [args.name !== undefined, '--name'], + [args.promptTemplates?.length, '--prompt-template'], + [args.themes?.length, '--theme'], + [args.useTheme !== undefined, '--use-theme'], + [args.verbose, '--verbose'], + [args.tuiMode !== undefined, '--tui-mode'], + ].filter(([used]) => used); + if (unsupported.length) throw new Error(`Unsupported Pi CLI option(s): ${unsupported.map(([, name]) => name).join(', ')}`); +} + +async function readPipedStdin() { + if (process.stdin.isTTY) return undefined; + process.stdin.setEncoding('utf8'); + let content = ''; + for await (const chunk of process.stdin) content += chunk; + return content.trim() || undefined; +} + +async function processFileArguments(fileArgs, cwd) { + let text = ''; + const images = []; + for (const fileArg of fileArgs) { + const filename = absolutePath(fileArg, cwd); + let stat; + try { stat = await fs.promises.stat(filename); } + catch (error) { throw new Error(`File not found: ${filename}: ${error instanceof Error ? error.message : String(error)}`); } + if (stat.size === 0) continue; + const mimeType = await detectSupportedImageMimeTypeFromFile(filename); + if (mimeType) { + const data = await fs.promises.readFile(filename); + images.push({ type: 'image', mimeType, data: data.toString('base64') }); + text += `\n`; + continue; + } + try { + const content = (await fs.promises.readFile(filename, 'utf8')).replace(/^\uFEFF/, ''); + text += `\n${content}\n\n`; + } catch (error) { + throw new Error(`Could not read file ${filename}: ${error instanceof Error ? error.message : String(error)}`); + } + } + return { text, images }; +} + +async function prepareInitialMessage(args, cwd, stdinContent) { + const fileContent = args.fileArgs.length ? await processFileArguments(args.fileArgs, cwd) : { text: '', images: [] }; + const parts = []; + if (stdinContent !== undefined) parts.push(stdinContent); + if (fileContent.text) parts.push(fileContent.text); + if (args.messages.length) parts.push(args.messages.shift()); + return { + initialMessage: parts.length ? parts.join('') : undefined, + initialImages: fileContent.images.length ? fileContent.images : undefined, + }; +} + +async function sessionManagerFor(parsed, cwd, settingsManager) { + const sessionDir = parsed.sessionDir ? absolutePath(parsed.sessionDir, cwd) : settingsManager.getSessionDir(); + if (parsed.noSession || parsed.help) return SessionManager.inMemory(cwd, parsed.sessionId ? { id: parsed.sessionId } : undefined); + // Path-vs-id resolution mirrors the upstream CLI's resolveSessionPath: + // arguments containing a separator or ending in .jsonl are session file + // paths even when they do not exist yet (fresh subagents pass a lazily + // created path); bare id/prefix arguments resolve through the session index. + const looksLikePath = value => + value.includes('/') || value.includes('\\') || value.endsWith('.jsonl'); + if (parsed.fork) { + const source = looksLikePath(parsed.fork) + ? absolutePath(parsed.fork, cwd) + : (await SessionManager.listAll(sessionDir)).find(item => item.id.startsWith(parsed.fork))?.path; + if (!source) throw new Error(`No session found matching '${parsed.fork}'.`); + return SessionManager.forkFrom(source, cwd, sessionDir, parsed.sessionId ? { id: parsed.sessionId } : undefined); + } + if (parsed.session) { + if (looksLikePath(parsed.session)) { + return SessionManager.open(absolutePath(parsed.session, cwd), sessionDir, cwd); + } + const matches = (await SessionManager.listAll(sessionDir)).filter(item => item.id.startsWith(parsed.session)); + if (matches.length !== 1) throw new Error(matches.length ? `Session '${parsed.session}' is ambiguous.` : `No session found matching '${parsed.session}'.`); + return SessionManager.open(matches[0].path, sessionDir); + } + if (parsed.resume || parsed.continue) return SessionManager.continueRecent(cwd, sessionDir); + if (parsed.sessionId) { + const match = SessionManager.findById(cwd, parsed.sessionId, sessionDir); + return match ? SessionManager.open(match, sessionDir) : SessionManager.create(cwd, sessionDir, { id: parsed.sessionId }); + } + return SessionManager.create(cwd, sessionDir); +} + +function isWithin(parent, candidate) { + const relative = path.relative(path.resolve(parent), path.resolve(candidate)); + return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative)); +} + +function managedBashOperations(shellPath) { + return { + exec: async (command, cwd, { onData, signal, timeout, env }) => { + if (signal?.aborted) throw new Error('aborted'); + const config = getShellConfig(shellPath); + await fs.promises.access(cwd); + const stdinCommand = config.commandTransport === 'stdin'; + const child = managedRuntime.spawnManaged(config.shell, stdinCommand ? config.args : [...config.args, command], { + cwd, + env: env ?? process.env, + detached: true, + stdio: [stdinCommand ? 'pipe' : 'ignore', 'pipe', 'pipe'], + windowsHide: true, + }, { kind: 'pi-bash' }); + let timeoutId; + child.stdout?.on('data', onData); + child.stderr?.on('data', onData); + child.stdin?.on('error', () => {}); + if (stdinCommand) child.stdin?.end(command); + let resolveStop; + const stopRequested = new Promise(resolve => { resolveStop = resolve; }); + const terminate = reason => resolveStop(reason); + const onAbort = () => terminate('aborted'); + signal?.addEventListener('abort', onAbort, { once: true }); + if (timeout !== undefined) timeoutId = setTimeout(() => terminate(`timeout:${timeout}`), timeout * 1000); + try { + await managedRuntime.waitManagedStartup(child); + const result = await Promise.race([child.managedClose.then(close => ({ close })), stopRequested.then(reason => ({ reason }))]); + if ('reason' in result) { + const terminal = await managedRuntime.finishManagedProcess(child, { observation: 'cancelled_or_timed_out', observed_at: Date.now() }); + if (terminal?.status !== 'stopped') throw new Error(`Managed bash stop is unknown: ${terminal?.reason ?? 'missing terminal receipt'}`); + await child.managedClose; + throw new Error(result.reason); + } + const closed = result.close; + const terminal = await managedRuntime.finishManagedProcess(child, { ...closed, observed_at: Date.now() }); + if (terminal?.status === 'unknown') throw new Error(`Managed bash cleanup is unknown: ${terminal.reason}`); + return { exitCode: closed.code ?? 1 }; + } finally { + if (timeoutId) clearTimeout(timeoutId); + signal?.removeEventListener('abort', onAbort); + } + }, + }; +} + +function deferredInputs(session) { + const latest = new Map(); + for (const entry of session.sessionManager.getBranch()) { + if (entry.type !== 'custom' || entry.customType !== 'braid.pending-native-inputs') continue; + const data = entry.data; + if (data?.id && data.state === 'pending') latest.set(data.id, data); + else if (data?.id && data.state === 'restored') latest.delete(data.id); + else if (data?.id && data.state === 'superseded') latest.delete(data.id); + } + return [...latest.values()]; +} + +function installSessionPolicy(session, terminalHookErrors) { + const native = { pendingInputs: deferredInputs(session), queueFailure: undefined, hookErrors: terminalHookErrors, unsubscribe: undefined, unsubscribeExtensionError: undefined, abortError: undefined }; + const sendCustomMessage = session.sendCustomMessage.bind(session); + const executeBash = session.executeBash.bind(session); + const bashOperations = managedBashOperations(session.settingsManager.getShellPath()); + session.sendCustomMessage = (message, options = {}) => sendCustomMessage(message, { ...options, triggerTurn: false }); + session.executeBash = (command, onChunk, options) => executeBash( + command, + onChunk, + options?.operations === undefined ? { ...options, operations: bashOperations } : options, + ); + const deferQueuedInputs = reason => { + const requested = { steering: [...session.getSteeringMessages()], followUp: [...session.getFollowUpMessages()] }; + if (!requested.steering.length && !requested.followUp.length) return; + const id = `${Date.now()}-${Math.random().toString(36).slice(2)}`; + const record = { id, state: 'pending', ...requested, error: reason }; + let persisted = false; + try { + session.sessionManager.appendCustomEntry('braid.pending-native-inputs', record); + persisted = true; + } catch (error) { + native.queueFailure = `cannot persist queued input before deferring: ${error instanceof Error ? error.message : String(error)}`; + } + let cleared; + try { cleared = session.clearQueue(); } + catch (error) { + native.queueFailure = `cannot clear queued input after terminal failure: ${error instanceof Error ? error.message : String(error)}`; + native.pendingInputs = deferredInputs(session); + return; + } + if (JSON.stringify(cleared) !== JSON.stringify(requested)) { + if (persisted) { + try { session.sessionManager.appendCustomEntry('braid.pending-native-inputs', { id, state: 'superseded' }); } + catch (error) { native.queueFailure = `cannot supersede stale queued input record: ${error instanceof Error ? error.message : String(error)}`; } + } + if (cleared.steering.length || cleared.followUp.length) { + const corrected = { ...cleared, error: reason, id: `${id}-corrected`, state: 'pending' }; + native.pendingInputs.push(corrected); + try { session.sessionManager.appendCustomEntry('braid.pending-native-inputs', corrected); } + catch (error) { native.queueFailure = `cannot persist cleared Pi input: ${error instanceof Error ? error.message : String(error)}`; } + } + } else { + native.pendingInputs.push(record); + if (!persisted) { + try { session.sessionManager.appendCustomEntry('braid.pending-native-inputs', record); } + catch (error) { native.queueFailure = `cannot persist cleared Pi input: ${error instanceof Error ? error.message : String(error)}`; } + } + } + }; + native.unsubscribeExtensionError = session.extensionRunner.onError(error => { + if (!['agent_end', 'agent_before_settle', 'agent_settled'].includes(error.event)) return; + native.hookErrors.push(error); + const reason = `Pi extension hook ${error.event} failed (${error.extensionPath}): ${error.error}`; + try { deferQueuedInputs(reason); } + catch (failure) { native.queueFailure = `cannot preserve queued input after extension hook failure: ${failure instanceof Error ? failure.message : String(failure)}`; } + if (native.hookErrors.length === 1) { + void session.abort().catch(failure => { + native.abortError = failure instanceof Error ? failure.message : String(failure); + }); + } + }); + native.unsubscribe = session.subscribe(event => { + if (event.type !== 'agent_end' || event.willRetry) return; + const finalMessage = [...event.messages].reverse().find(message => message.role === 'assistant'); + if (finalMessage?.stopReason !== 'error') return; + deferQueuedInputs(finalMessage.errorMessage ?? 'Agent turn failed.'); + }); + return native; +} + +function installRuntimePolicy(runtime) { + const terminalHookErrors = []; + let state = installSessionPolicy(runtime.session, terminalHookErrors); + const setRebindSession = runtime.setRebindSession.bind(runtime); + runtime.setRebindSession = callback => setRebindSession(async (...args) => { + await callback?.(...args); + state.unsubscribe?.(); + state.unsubscribeExtensionError?.(); + state = installSessionPolicy(runtime.session, terminalHookErrors); + }); + return { + get sessionState() { return state; }, + async restorePendingInputs() { + if (terminalHookErrors.length) throw new Error(`Native runtime stopped after Pi extension hook failure: ${terminalHookErrors.map(error => `${error.extensionPath} ${error.event}: ${error.error}`).join('; ')}`); + if (state.queueFailure) throw new Error(`Deferred Pi input preservation failed: ${state.queueFailure}`); + if (!state.pendingInputs.length) return; + const restoring = state.pendingInputs; + try { + for (const record of restoring) { + for (const message of record.steering) await runtime.session.steer(message, undefined, { source: 'extension' }); + for (const message of record.followUp) await runtime.session.followUp(message, undefined, { source: 'extension' }); + } + } catch (error) { + runtime.session.clearQueue(); + throw error; + } + for (const record of restoring) { + runtime.session.sessionManager.appendCustomEntry('braid.pending-native-inputs', { id: record.id, state: 'restored' }); + } + state.pendingInputs = []; + state.queueFailure = undefined; + }, + }; +} + +async function buildRuntime(parsed) { + const cwd = process.cwd(); + const agentDir = process.env.PI_CODING_AGENT_DIR; + const startupSettings = SettingsManager.create(cwd, agentDir); + const sessionManager = await sessionManagerFor(parsed, cwd, startupSettings); + const modelRuntime = await ModelRuntime.create({ + authPath: path.join(agentDir, 'auth.json'), + modelsPath: path.join(agentDir, 'models.json'), + refreshOnCreate: false, + }); + const resolved = parsed.model ? resolveCliModel({ cliProvider: parsed.provider, cliModel: parsed.model, cliThinking: parsed.thinking, modelRuntime }) : undefined; + if (resolved?.error) throw new Error(resolved.error); + const defaultProvider = startupSettings.getDefaultProvider(); + const defaultModel = startupSettings.getDefaultModel(); + const model = resolved?.model ?? (defaultProvider && defaultModel ? modelRuntime.getModel(defaultProvider, defaultModel) : undefined) ?? modelRuntime.getModels()[0]; + if (!model) throw new Error('No model is available in this Braid native home.'); + if (parsed.apiKey) await modelRuntime.setRuntimeApiKey(model.provider, parsed.apiKey); + const thinkingLevel = parsed.thinking ?? resolved?.thinkingLevel ?? startupSettings.getDefaultThinkingLevel() ?? 'medium'; + const extensionPaths = (parsed.extensions ?? []).map(item => absolutePath(item, cwd)); + const skillPaths = (parsed.skills ?? []).map(item => absolutePath(item, cwd)); + const createRuntime = async ({ cwd: sessionCwd, agentDir: runtimeAgentDir, sessionManager: targetSessionManager, sessionStartEvent }) => { + const settingsManager = SettingsManager.create(sessionCwd, runtimeAgentDir); + const services = await createAgentSessionServices({ + cwd: sessionCwd, + agentDir: runtimeAgentDir, + settingsManager, + modelRuntime, + extensionFlagValues: parsed.unknownFlags, + resourceLoaderOptions: { + additionalExtensionPaths: extensionPaths, + additionalSkillPaths: skillPaths, + noExtensions: parsed.noExtensions, + noSkills: parsed.noSkills, + disabledBuiltinExtensions: parsed.noMcp ? ['mcp'] : undefined, + noPromptTemplates: parsed.noPromptTemplates, + noThemes: parsed.noThemes, + noContextFiles: parsed.noContextFiles, + agentsFilesOverride: base => ({ + agentsFiles: base.agentsFiles.filter(item => isWithin(sessionCwd, item.path) || isWithin(runtimeAgentDir, item.path)), + }), + systemPrompt: parsed.systemPrompt, + appendSystemPrompt: parsed.appendSystemPrompt, + }, + }); + const selectedModel = parsed.model + ? resolveCliModel({ cliProvider: parsed.provider, cliModel: parsed.model, cliThinking: parsed.thinking, modelRuntime: services.modelRuntime }).model + : model; + const created = await createAgentSessionFromServices({ + services, + sessionManager: targetSessionManager, + sessionStartEvent, + model: selectedModel, + thinkingLevel, + tools: parsed.tools, + excludeTools: parsed.excludeTools, + noTools: parsed.noTools ? 'all' : parsed.noBuiltinTools ? 'builtin' : undefined, + customTools: [createBashToolDefinition(sessionCwd, { + operations: managedBashOperations(settingsManager.getShellPath()), + shellPath: settingsManager.getShellPath(), + commandPrefix: settingsManager.getShellCommandPrefix(), + })], + }); + return { ...created, services }; + }; + return createAgentSessionRuntime(createRuntime, { cwd: sessionManager.getCwd(), agentDir, sessionManager }); +} + +export async function main(argv = process.argv.slice(2)) { + const args = parseArgs(argv); + if (args.diagnostics.some(item => item.type === 'error')) throw new Error(args.diagnostics.filter(item => item.type === 'error').map(item => item.message).join('\n')); + if (args.version) { process.stdout.write(`${VERSION}\n`); return; } + if (args.help) return; + assertSupportedCliOptions(args); + if (args.mode === 'rpc' && args.fileArgs.length) throw new Error('@file arguments are not supported in RPC mode.'); + const runtime = await buildRuntime(args); + const policy = installRuntimePolicy(runtime); + if (args.mode === 'rpc') return runBraidRpcMode(runtime, policy, managedRuntime, VERSION, runRpcMode); + const stdinContent = await readPipedStdin(); + const { initialMessage, initialImages } = await prepareInitialMessage(args, process.cwd(), stdinContent); + const exitCode = await runPrintMode(runtime, { mode: args.mode === 'json' ? 'json' : 'text', initialMessage, initialImages, messages: args.messages }); + if (exitCode !== 0) process.exitCode = exitCode; + else if (policy.sessionState.hookErrors.length) process.exitCode = 1; +} diff --git a/native/pi/tests/managed-process.test.mjs b/native/pi/tests/managed-process.test.mjs new file mode 100644 index 00000000..a47afa6b --- /dev/null +++ b/native/pi/tests/managed-process.test.mjs @@ -0,0 +1,134 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { randomUUID } from 'node:crypto'; +import { once } from 'node:events'; +import { spawnSync } from 'node:child_process'; +import { processIdentity, processMarkers } from '../process-owner.mjs'; + +// A test launched by Braid may inherit its operator's execution markers. Do +// not let module initialization allocate a socket alias in that execution. +const inheritedMcporter = process.env.BRAID_NATIVE_MCPORTER_ENABLED; +delete process.env.BRAID_NATIVE_MCPORTER_ENABLED; +let managed; +try { managed = await import('../managed.mjs'); } +finally { + if (inheritedMcporter !== undefined) process.env.BRAID_NATIVE_MCPORTER_ENABLED = inheritedMcporter; +} +const { spawnManaged, waitManagedStartup, finishManagedProcess, cleanupOwnedExecution } = managed; + +function execution(t) { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'braid-managed-')); + const id = randomUUID(); + const keys = ['BRAID_NATIVE_EXECUTION_DIR', 'BRAID_NATIVE_EXECUTION_ID', 'BRAID_NATIVE_START_ID', 'BRAID_NATIVE_LAUNCH_START_ID']; + const original = Object.fromEntries(keys.map(key => [key, process.env[key]])); + process.env.BRAID_NATIVE_EXECUTION_DIR = directory; + process.env.BRAID_NATIVE_EXECUTION_ID = id; + delete process.env.BRAID_NATIVE_START_ID; + delete process.env.BRAID_NATIVE_LAUNCH_START_ID; + const children = []; + const owned = []; + const track = pid => { + const identity = processIdentity(pid); + if (identity) owned.push(identity); + }; + t.after(async () => { + try { + const receipt = await cleanupOwnedExecution({ directory, id }); + // Test teardown must also recover a broken cleanup implementation. + // Identity helpers are used only for emergency cleanup, never as the + // oracle that decides whether the production stop was correct. + for (const identity of owned) { + const current = processIdentity(identity.pid); + if (current?.starttime === identity.starttime && !/^[ZX]/.test(current.state)) { + if (processMarkers(identity.pid).owner !== id) continue; + try { process.kill(identity.pid, 'SIGKILL'); } + catch (error) { if (error.code !== 'ESRCH') throw error; } + } + } + await Promise.all(children.map(child => child.managedClose)); + assert.equal(receipt.status, 'stopped', JSON.stringify(receipt)); + } finally { + for (const key of keys) { + if (original[key] === undefined) delete process.env[key]; + else process.env[key] = original[key]; + } + fs.rmSync(directory, { recursive: true, force: true }); + } + }); + return { + directory, id, track, + spawn(code) { + const child = spawnManaged(process.execPath, ['-e', code], { stdio: ['ignore', 'pipe', 'ignore'] }); + children.push(child); + if (child.pid) track(child.pid); + return child; + }, + }; +} + +function isExecuting(pid) { + // Independent OS observation: do not reuse managed.mjs's process selector + // as the expected value for its own stop decision. Zombies cannot execute. + const observed = spawnSync('/bin/ps', ['-p', String(pid), '-o', 'stat='], { encoding: 'utf8' }); + assert.equal(observed.error, undefined); + assert.ok(observed.status === 0 || observed.status === 1, observed.stderr); + const state = observed.stdout.trim(); + return Boolean(state) && !/^[ZX]/.test(state); +} + +test('owned stop reaches a real grandchild and fences later launches', { timeout: 20000 }, async t => { + const fixture = execution(t); + const child = fixture.spawn(` + const { spawn } = require('node:child_process'); + const leaf = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { stdio: 'ignore' }); + process.stdout.write(String(leaf.pid) + '\\n'); + setInterval(() => {}, 1000); + `); + const output = once(child.stdout, 'data', { signal: AbortSignal.timeout(5000) }); + const started = await waitManagedStartup(child, 5000); + const leaf = Number(String((await output)[0]).trim()); + assert.ok(Number.isInteger(leaf) && leaf > 1); + fixture.track(started.payload_pid); + fixture.track(leaf); + assert.equal(isExecuting(leaf), true); + const terminal = await finishManagedProcess(child, { observation: 'test_stop', observed_at: Date.now() }); + assert.equal(terminal.status, 'stopped', JSON.stringify(terminal)); + assert.equal(isExecuting(started.payload_pid), false); + assert.equal(isExecuting(leaf), false); + await child.managedClose; + const persisted = JSON.parse(fs.readFileSync(path.join(fixture.directory, 'terminals', `${started.start_id}.json`), 'utf8')); + assert.equal(persisted.execution_id, fixture.id); + assert.equal(persisted.terminal.status, 'stopped'); + + const stopped = await cleanupOwnedExecution({ directory: fixture.directory, id: fixture.id }); + assert.equal(stopped.status, 'stopped', JSON.stringify(stopped)); + const marker = path.join(fixture.directory, 'should-not-launch'); + const rejected = fixture.spawn(`require('node:fs').writeFileSync(${JSON.stringify(marker)}, 'ran')`); + await assert.rejects(waitManagedStartup(rejected, 5000), /start_rejected.*execution_stopping/); + await rejected.managedClose; + assert.equal(fs.existsSync(marker), false); +}); + +test('ambiguous persisted ownership reports unknown without killing the payload', { timeout: 20000 }, async t => { + const fixture = execution(t); + const child = fixture.spawn('setInterval(() => {}, 1000)'); + const started = await waitManagedStartup(child, 5000); + fixture.track(started.payload_pid); + const original = fs.readFileSync(started.process_record, 'utf8'); + const record = JSON.parse(original); + fs.writeFileSync(started.process_record, JSON.stringify({ ...record, boot_id: 'different-boot' })); + try { + const result = await cleanupOwnedExecution({ directory: fixture.directory, id: fixture.id }); + assert.equal(result.status, 'unknown'); + assert.match(result.reason, /another boot identity/); + assert.equal(isExecuting(started.payload_pid), true); + const persisted = JSON.parse(fs.readFileSync(path.join(fixture.directory, 'execution-stop.json'), 'utf8')); + assert.equal(persisted.status, 'unknown'); + } finally { + // Restore the actual launcher's identity before teardown performs real stop. + fs.writeFileSync(started.process_record, original); + } +}); diff --git a/native/pi/tests/tool-environment.test.mjs b/native/pi/tests/tool-environment.test.mjs new file mode 100644 index 00000000..a71bd240 --- /dev/null +++ b/native/pi/tests/tool-environment.test.mjs @@ -0,0 +1,13 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +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'], + ['absent GH and XDG use the caller home', {}, '/operator/home/.config/gh'], +]) { + test(name, () => { + preserveToolConfig(environment, '/operator/home'); + assert.equal(environment.GH_CONFIG_DIR, expected); + }); +} diff --git a/native/pi/tool-environment.mjs b/native/pi/tool-environment.mjs new file mode 100644 index 00000000..79f70cab --- /dev/null +++ b/native/pi/tool-environment.mjs @@ -0,0 +1,11 @@ +import path from 'node:path'; + +// Execution-local XDG state must not silently change ordinary gh's credential +// lookup (including git's `gh auth git-credential` helper). Preserve the caller's +// normal path, never copy or expose credential values. Supported hosts are Unix. +export function preserveToolConfig(environment, home) { + if (!environment.GH_CONFIG_DIR) { + const config = environment.XDG_CONFIG_HOME || path.join(home, '.config'); + environment.GH_CONFIG_DIR = path.join(config, 'gh'); + } +} diff --git a/scripts/package.sh b/scripts/package.sh index d87241fc..1f5cbcdc 100755 --- a/scripts/package.sh +++ b/scripts/package.sh @@ -2,14 +2,19 @@ set -eu repository_root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) -target=${BRAID_BUILD_TARGET:-aarch64-apple-darwin} +target=${BRAID_BUILD_TARGET:-$(rustc -vV | sed -n 's/^host: //p')} output_root=${BRAID_DIST_DIR:-"$repository_root/dist"} cd "$repository_root" cargo build --release --locked --target "$target" -binary="$repository_root/target/$target/release/braid" +target_directory=${CARGO_TARGET_DIR:-"$repository_root/target"} +binary="$target_directory/$target/release/braid" version=$("$binary" --version | awk '{print $2}') +if [ -n "${BRAID_RELEASE_TAG:-}" ] && [ "$BRAID_RELEASE_TAG" != "v$version" ]; then + printf 'Release tag %s does not match binary version v%s\n' "$BRAID_RELEASE_TAG" "$version" >&2 + exit 1 +fi artifact="braid-v${version}-${target}" archive="$output_root/$artifact.tar.gz" mkdir -p "$output_root" diff --git a/scripts/tests/00_clean_install.sh b/scripts/tests/00_clean_install.sh deleted file mode 100755 index 542d9c9d..00000000 --- a/scripts/tests/00_clean_install.sh +++ /dev/null @@ -1,243 +0,0 @@ -#!/bin/sh -set -eu - -repository_root=$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd) -temporary_root=$(mktemp -d "${TMPDIR:-/tmp}/braid-clean-install.XXXXXX") -python3_executable=$(command -v python3 || true) -trap 'rm -rf "$temporary_root"' EXIT HUP INT TERM - -archive=${1:-} -if [ -z "$archive" ]; then - archive=$(BRAID_DIST_DIR="$temporary_root/dist" "$repository_root/scripts/package.sh") -fi -case "$archive" in - /*) ;; - *) archive="$repository_root/$archive" ;; -esac -(cd "$(dirname "$archive")" && /usr/bin/shasum -a 256 -c "$(basename "$archive").sha256") - -install_root="$temporary_root/install" -mkdir -p "$install_root" -tar -C "$install_root" -xzf "$archive" -package_root=$(find "$install_root" -mindepth 1 -maxdepth 1 -type d -name 'braid-*' | head -1) -braid="$package_root/bin/braid" -runtime="$temporary_root/runtime" -mkdir -p "$runtime/state/backups" "$runtime/provider" "$runtime/workspace" -private_key="$runtime/github-app.pem" -secrets_file="$runtime/secrets.toml" -printf '%s\n' 'diagnostic placeholder for the intentionally unready instance' > "$private_key" -touch "$secrets_file" - -write_config() { - config_path=$1 - database_path=$2 - sample_ratio=$3 - port=$4 - cat > "$config_path" < "$temporary_root/setup-removed-argument.out" 2>&1; then - echo "setup accepted a removed option" >&2 - exit 1 -fi -/usr/bin/grep -q 'unexpected argument.*--runtime-api-url' "$temporary_root/setup-removed-argument.out" -run_clean "$braid" config check --config "$config" -run_clean "$braid" migrate plan --config "$config" -run_clean "$braid" migrate apply --config "$config" -test "$(find "$runtime/state/backups" -type f -name '*.sqlite3' | wc -l | tr -d ' ')" = "1" -run_clean "$braid" profile inspect --config "$config" --profile pr-codex -run_clean "$braid" status --config "$config" - -if run_clean "$braid" doctor --config "$config" --json > "$temporary_root/doctor.json" 2>&1; then - echo "doctor unexpectedly accepted unavailable diagnostic dependencies" >&2 - exit 1 -fi -/usr/bin/grep -q '"ready": false' "$temporary_root/doctor.json" -/usr/bin/grep -q 'Codex app-server' "$temporary_root/doctor.json" - -schema=$(run_clean "$braid" status --config "$config" --json | /usr/bin/sed -n 's/.*"config_schema": \([0-9][0-9]*\).*/\1/p') -test "$schema" = "2" - -# v1 fixture: intentionally a v1 DB that must remain compatible after migration -v1="$runtime/state/v1.sqlite3" -/usr/bin/sqlite3 "$v1" < "$repository_root/migrations/0001_initial.sql" -v1_checksum=$(/usr/bin/shasum -a 256 "$repository_root/migrations/0001_initial.sql" | /usr/bin/awk '{print $1}') -/usr/bin/sqlite3 "$v1" "INSERT INTO schema_migrations VALUES (1,'initial','$v1_checksum','fixture');" -/usr/bin/sqlite3 "$v1" " -INSERT INTO repositories(node_id,name_with_owner,observed_at) -VALUES ('REPOSITORY_NODE','xiaoland/braid','fixture'); -INSERT INTO work_items(node_id,repository_node_id,kind,number,state,observed_at) -VALUES ('ISSUE_NODE','REPOSITORY_NODE','issue',9001,'OPEN','fixture'), - ('PR_NODE','REPOSITORY_NODE','pr',9002,'OPEN','fixture'); -INSERT INTO associations(issue_node_id,pr_node_id,source,observed_version,active) -VALUES ('ISSUE_NODE','PR_NODE','native','fixture',1); -INSERT INTO canonical_objects( - node_id,work_item_node_id,object_kind,version,digest,lifecycle,observed_at -) VALUES ( - 'COMMENT_NODE','ISSUE_NODE','issue_comment','fixture', - '0000000000000000000000000000000000000000000000000000000000000000', - 'active','fixture' -);" -v1_config="$temporary_root/v1.toml" -write_config "$v1_config" "$v1" 1.0 43189 -backup_count_before=$(find "$runtime/state/backups" -type f -name '*.sqlite3' | wc -l | tr -d ' ') -run_clean "$braid" migrate apply --config "$v1_config" -backup_count_after=$(find "$runtime/state/backups" -type f -name '*.sqlite3' | wc -l | tr -d ' ') -# Applying v2 on the v1 fixture is a real upgrade and must take exactly one -# pre-migration backup; re-applying is a no-op and must not add another. -test "$backup_count_after" = "$((backup_count_before + 1))" -run_clean "$braid" migrate apply --config "$v1_config" -backup_count_final=$(find "$runtime/state/backups" -type f -name '*.sqlite3' | wc -l | tr -d ' ') -test "$backup_count_final" = "$backup_count_after" -test "$(/usr/bin/sqlite3 "$v1" 'SELECT MAX(version) FROM schema_migrations;')" = "2" -/usr/bin/sqlite3 "$v1" \ - "SELECT 1 FROM associations WHERE issue_node_id='ISSUE_NODE' AND pr_node_id='PR_NODE' AND active=1;" \ - | /usr/bin/grep -q '^1$' -/usr/bin/sqlite3 "$v1" \ - "SELECT 1 FROM canonical_objects WHERE node_id='COMMENT_NODE' AND lifecycle='active';" \ - | /usr/bin/grep -q '^1$' -/usr/bin/sqlite3 "$v1" 'SELECT kind, detail FROM events LIMIT 0;' - -newer="$runtime/state/newer.sqlite3" -/usr/bin/sqlite3 "$newer" 'CREATE TABLE schema_migrations(version INTEGER PRIMARY KEY, name TEXT NOT NULL, checksum TEXT NOT NULL, applied_at TEXT NOT NULL); INSERT INTO schema_migrations VALUES (3,"future","0000000000000000000000000000000000000000000000000000000000000000","future");' -newer_config="$temporary_root/newer.toml" -write_config "$newer_config" "$newer" 1.0 43189 -if run_clean "$braid" migrate plan --config "$newer_config" > "$temporary_root/newer.out" 2>&1; then - echo "schema-newer fixture was accepted unexpectedly" >&2 - exit 1 -fi -/usr/bin/grep -q 'schema 3 is newer' "$temporary_root/newer.out" - -foreign="$runtime/state/foreign.sqlite3" -/usr/bin/sqlite3 "$foreign" 'CREATE TABLE prototype_state(id INTEGER PRIMARY KEY);' -foreign_config="$temporary_root/foreign.toml" -write_config "$foreign_config" "$foreign" 1.0 43189 -if run_clean "$braid" migrate plan --config "$foreign_config" > "$temporary_root/foreign.out" 2>&1; then - echo "foreign database fixture was accepted unexpectedly" >&2 - exit 1 -fi -/usr/bin/grep -q 'not an empty or Braid Rust database' "$temporary_root/foreign.out" - -if [ -n "$python3_executable" ] && [ -x "$python3_executable" ]; then - capture_one="$temporary_root/otel-one.bin" - "$python3_executable" "$repository_root/scripts/tests/otel_receiver.py" --port 43189 --minimum-requests 3 --output "$capture_one" & - receiver=$! - sleep 1 - run_clean "$braid" telemetry probe --config "$config" --marker BRAID_OTEL_FULL_PAYLOAD_PROBE - wait "$receiver" - /usr/bin/grep -a -q 'BRAID_OTEL_FULL_PAYLOAD_PROBE' "$capture_one" - /usr/bin/grep -a -q 'PATH /v1/traces' "$capture_one" - - capture_zero="$temporary_root/otel-zero.bin" - write_config "$config" "$database" 0.0 43189 - "$python3_executable" "$repository_root/scripts/tests/otel_receiver.py" --port 43189 --minimum-requests 1 --output "$capture_zero" & - receiver=$! - sleep 1 - run_clean "$braid" telemetry probe --config "$config" --marker BRAID_OTEL_MUST_NOT_EXPORT - wait "$receiver" - if /usr/bin/grep -a -q 'PATH /v1/traces' "$capture_zero"; then - echo "ratio 0 exported an orphan trace" >&2 - exit 1 - fi -else - echo "UNAVAILABLE: python3 is required only for the local OTLP capture helper" >&2 - exit 1 -fi - -echo "clean-install diagnostics passed" diff --git a/scripts/tests/05_instances.sh b/scripts/tests/05_instances.sh deleted file mode 100755 index 6c8edc00..00000000 --- a/scripts/tests/05_instances.sh +++ /dev/null @@ -1,162 +0,0 @@ -#!/bin/sh -set -eu - -repository_root=$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd) -temporary_root=$(mktemp -d "${TMPDIR:-/tmp}/braid-instances.XXXXXX") -trap 'rm -rf "$temporary_root"' EXIT HUP INT TERM - -archive=${1:-} -if [ -z "$archive" ]; then - archive=$(BRAID_DIST_DIR="$temporary_root/dist" "$repository_root/scripts/package.sh") -fi -case "$archive" in - /*) ;; - *) archive="$repository_root/$archive" ;; -esac - -install_root="$temporary_root/install" -mkdir -p "$install_root" -tar -C "$install_root" -xzf "$archive" -package_root=$(find "$install_root" -mindepth 1 -maxdepth 1 -type d -name 'braid-*' | head -1) -braid="$package_root/bin/braid" - -user_home="$temporary_root/home/.braid" -mkdir -p "$user_home/instances/first/state" \ - "$user_home/instances/second/state" \ - "$user_home/secrets" - -printf '%s\n' 'provider_api_key = "fake-deepseek"' > "$user_home/secrets/deepseek.toml" -printf '%s\n' 'provider_api_key = "fake-openai"' > "$user_home/secrets/openai.toml" - -cat > "$user_home/instances/first/github-app.pem" < "$user_home/instances/$key/config.toml" < "$user_home/registry.toml" < "$temporary_root/first.out" - -# Explicit instance selection. -run "$braid" config check --instance second > "$temporary_root/second.out" - -# Env-based instance selection. -run env BRAID_INSTANCE=second "$braid" config check > "$temporary_root/second-env.out" - -# BRAID_INSTANCE_HOME override. -run env BRAID_INSTANCE_HOME="$user_home/instances/second" "$braid" config check > "$temporary_root/second-home.out" - -# --config bypasses registry. -run "$braid" config check --config "$user_home/instances/first/config.toml" > "$temporary_root/first-bypass.out" - -# Doctor detects the overlapping ingress/health ports across instances. -if run "$braid" doctor --json > "$temporary_root/doctor.json" 2>&1; then - echo "doctor unexpectedly accepted overlapping ports" >&2 - exit 1 -fi -/usr/bin/grep -qE 'duplicate|collision' "$temporary_root/doctor.json" || { - echo "--- doctor.json ---" >&2 - cat "$temporary_root/doctor.json" >&2 - echo "doctor did not report port conflict" >&2 - exit 1 -} - -echo "OK: instance resolution and registry port cross-check" diff --git a/scripts/tests/10_context_projection.sh b/scripts/tests/10_context_projection.sh deleted file mode 100755 index d1845372..00000000 --- a/scripts/tests/10_context_projection.sh +++ /dev/null @@ -1,95 +0,0 @@ -#!/bin/sh -set -eu - -repository_root=$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd) -temporary_root=$(mktemp -d "${TMPDIR:-/tmp}/braid-context-projection.XXXXXX") -trap 'rm -rf "$temporary_root"' EXIT HUP INT TERM - -if [ "$#" -lt 3 ]; then - echo "UNAVAILABLE: usage: $0 ABSOLUTE_CONFIG OWNER/REPO#ISSUE OWNER/REPO#PR [ARCHIVE]" >&2 - exit 2 -fi - -for required in \ - BRAID_EXPECT_VISIBLE_TEXT \ - BRAID_EXPECT_FILTERED_TEXT \ - BRAID_EXPECT_FOLDED_REFERENCE \ - BRAID_EXPECT_DELETED_REFERENCE \ - BRAID_EXPECT_PAGINATED_REFERENCE \ - BRAID_EXPECT_METADATA_LINE \ - BRAID_EXPECT_ISSUE_PR_COUNT \ - BRAID_EXPECT_CLOSED_ISSUE_REFERENCE \ - BRAID_EXPECT_CLOSED_ISSUE_FILTERED_TEXT \ - BRAID_EXPECT_PR_ISSUE_COUNT -do - eval "value=\${$required:-}" - if [ -z "$value" ]; then - echo "UNAVAILABLE: $required must describe the controlled real fixture" >&2 - exit 2 - fi -done - -config=$1 -issue=$2 -pull_request=$3 -archive=${4:-} -if [ -z "$archive" ]; then - archive=$(BRAID_DIST_DIR="$temporary_root/dist" "$repository_root/scripts/package.sh") -fi -case "$archive" in - /*) ;; - *) archive="$repository_root/$archive" ;; -esac - -install_root="$temporary_root/install" -mkdir -p "$install_root" -tar -C "$install_root" -xzf "$archive" -package_root=$(find "$install_root" -mindepth 1 -maxdepth 1 -type d -name 'braid-*' | head -1) -braid="$package_root/bin/braid" - -"$braid" migrate apply --config "$config" -repository=${issue%#*} -"$braid" github probe --config "$config" --repository "$repository" --json > "$temporary_root/github.json" - -"$braid" context issue "$issue" --config "$config" --page-size 1 > "$temporary_root/issue-a.md" -"$braid" context issue "$issue" --config "$config" --page-size 1 > "$temporary_root/issue-b.md" -cmp "$temporary_root/issue-a.md" "$temporary_root/issue-b.md" - -"$braid" context pr "$pull_request" --config "$config" --page-size 1 > "$temporary_root/pr-a.md" -"$braid" context pr "$pull_request" --config "$config" --page-size 1 > "$temporary_root/pr-b.md" -cmp "$temporary_root/pr-a.md" "$temporary_root/pr-b.md" - -"$braid" context issue "$issue" --config "$config" --page-size 1 --json > "$temporary_root/issue.json" -jq -e '.bytes > 0 and (.pressure == "normal" or .pressure == "soft") and (has("revision") | not)' \ - "$temporary_root/issue.json" >/dev/null - -grep -F -q "$BRAID_EXPECT_VISIBLE_TEXT" "$temporary_root/issue-a.md" -if grep -F -q "$BRAID_EXPECT_FILTERED_TEXT" "$temporary_root/issue-a.md"; then - echo "HTML-comment content leaked into Issue Context" >&2 - exit 1 -fi -grep -F -q "$BRAID_EXPECT_FOLDED_REFERENCE" "$temporary_root/issue-a.md" -grep -F -q "$BRAID_EXPECT_DELETED_REFERENCE" "$temporary_root/issue-a.md" -grep -F -q "$BRAID_EXPECT_PAGINATED_REFERENCE" "$temporary_root/issue-a.md" -grep -F -q "$BRAID_EXPECT_METADATA_LINE" "$temporary_root/issue-a.md" - -issue_pr_count=$(grep -o 'GitHub PR:' "$temporary_root/issue-a.md" | wc -l | tr -d ' ') -test "$issue_pr_count" = "$BRAID_EXPECT_ISSUE_PR_COUNT" - -issue_count=$(grep -c '^# GitHub Issue: ' "$temporary_root/pr-a.md") -test "$issue_count" = "$BRAID_EXPECT_PR_ISSUE_COUNT" -grep -F -q "$BRAID_EXPECT_CLOSED_ISSUE_REFERENCE" "$temporary_root/pr-a.md" -if grep -F -q "$BRAID_EXPECT_CLOSED_ISSUE_FILTERED_TEXT" "$temporary_root/pr-a.md"; then - echo "closed Issue body leaked into PR Context" >&2 - exit 1 -fi - -tiny_config="$temporary_root/tiny.toml" -sed 's/^github_context_hard_bytes = .*/github_context_hard_bytes = 1/' "$config" > "$tiny_config" -if "$braid" context issue "$issue" --config "$tiny_config" --page-size 1 > "$temporary_root/tiny.out" 2>&1; then - echo "hard Context budget unexpectedly emitted a partial Context" >&2 - exit 1 -fi -grep -q 'above the Profile hard limit' "$temporary_root/tiny.out" - -echo "real Context projection diagnostics passed" diff --git a/scripts/tests/20_ingress_scheduler.sh b/scripts/tests/20_ingress_scheduler.sh deleted file mode 100755 index ffe031c8..00000000 --- a/scripts/tests/20_ingress_scheduler.sh +++ /dev/null @@ -1,361 +0,0 @@ -#!/bin/bash -set -euo pipefail - -readonly script_name="$(basename "$0")" -readonly config_path="${BRAID_CONFIG:-}" -readonly binary="${BRAID_BIN:-$(command -v braid || true)}" -readonly keep_fixtures="${BRAID_TEST_KEEP_FIXTURES:-0}" -readonly webhook_mode="${BRAID_TEST_WEBHOOK_MODE:-app}" -readonly repository_webhook_url="${BRAID_TEST_PUBLIC_WEBHOOK_URL:-}" -readonly ingress_address="${BRAID_TEST_INGRESS:-127.0.0.1:18080}" -readonly health_address="${BRAID_TEST_HEALTH:-127.0.0.1:18081}" -readonly health_url="http://$health_address/healthz" - -runtime_pid="" -temporary_root="" -fixture_issues=() -prior_webhook_url="" -repository_hook_id="" - -fail() { - printf '%s: FAIL: %s\n' "$script_name" "$*" >&2 - exit 1 -} - -note() { - printf '%s: %s\n' "$script_name" "$*" -} - -require_command() { - command -v "$1" >/dev/null 2>&1 || fail "required command is unavailable: $1" -} - -stop_runtime() { - if [[ -n "$runtime_pid" ]] && kill -0 "$runtime_pid" 2>/dev/null; then - kill -INT "$runtime_pid" - wait "$runtime_pid" || true - fi - runtime_pid="" -} - -cleanup() { - local status=$? - stop_runtime - if [[ -n "$repository_hook_id" ]]; then - gh api --method DELETE "repos/$repository/hooks/$repository_hook_id" >/dev/null 2>&1 || true - fi - if [[ "$keep_fixtures" != "1" ]]; then - for issue in "${fixture_issues[@]:-}"; do - gh issue close "$issue" --repo "$repository" --comment "Braid Slice 2 black-box fixture closed." >/dev/null 2>&1 || true - done - fi - if [[ -n "$temporary_root" && -d "$temporary_root" ]]; then - rm -rf "$temporary_root" - fi - if [[ $status -ne 0 ]]; then - printf '%s: runtime log follows\n' "$script_name" >&2 - [[ -f "${runtime_log:-}" ]] && tail -200 "$runtime_log" >&2 || true - fi - exit "$status" -} -trap cleanup EXIT INT TERM - -[[ -n "$binary" && -x "$binary" ]] || fail "set BRAID_BIN to the packaged braid binary" -[[ -n "$config_path" && "$config_path" = /* && -f "$config_path" ]] || \ - fail "set BRAID_CONFIG to an absolute acceptance configuration path" -[[ -n "${BRAID_WEBHOOK_SECRET:-}" ]] || \ - fail "BRAID_WEBHOOK_SECRET must match the dedicated GitHub App webhook secret" -[[ "$webhook_mode" == "app" || "$webhook_mode" == "repository" ]] || \ - fail "BRAID_TEST_WEBHOOK_MODE must be app or repository" -if [[ "$webhook_mode" == "repository" ]]; then - [[ "$repository_webhook_url" == https://*/webhook ]] || \ - fail "repository mode requires BRAID_TEST_PUBLIC_WEBHOOK_URL=https:///webhook" -fi - -for command in curl gh jq sed mktemp; do - require_command "$command" -done - -gh auth status >/dev/null 2>&1 || fail "gh must be authenticated as the Human fixture actor" -repository="$($binary config check --config "$config_path" --json | jq -er '.repository')" -app_actor="$($binary github probe --config "$config_path" --repository "$repository" --json | jq -er '.actor_login')" -if [[ "$webhook_mode" == "app" ]]; then - prior_webhook_url="$($binary github webhook --config "$config_path" --json | jq -er '.url')" -fi - -temporary_root="$(mktemp -d "${TMPDIR:-/tmp}/braid-slice2.XXXXXX")" -readonly runtime_root="$temporary_root/runtime" -readonly runtime_log="$temporary_root/runtime.log" -readonly test_config="$temporary_root/braid.toml" -mkdir -p "$runtime_root/state/backups" - -awk \ - -v root="$runtime_root" \ - -v database="$runtime_root/state/braid.sqlite3" \ - -v backups="$runtime_root/state/backups" \ - -v ingress="$ingress_address" \ - -v health="$health_address" ' - /^\[runtime\]$/ { in_runtime=1; print; next } - /^\[server\]$/ { in_runtime=0; in_server=1; print; next } - /^\[/ && $0 != "[runtime]" && $0 != "[server]" { in_runtime=0; in_server=0 } - in_runtime && /^root = / { printf "root = \"%s\"\n", root; next } - in_runtime && /^database = / { printf "database = \"%s\"\n", database; next } - in_runtime && /^backups = / { printf "backups = \"%s\"\n", backups; next } - in_runtime && /^auto_migrate = / { print "auto_migrate = false"; next } - in_server && /^ingress = / { printf "ingress = \"%s\"\n", ingress; next } - in_server && /^health = / { printf "health = \"%s\"\n", health; next } - { print } -' "$config_path" > "$test_config" - -$binary migrate apply --config "$test_config" >/dev/null - -status_json() { - "$binary" status --config "$test_config" --json -} - -batch_json() { - local issue_number=$1 - status_json | jq -ec --argjson number "$issue_number" \ - '.transport.batches[] | select(.work_item_kind == "issue" and .work_item_number == $number)' -} - -wait_for_health() { - local attempt expected_tunnel - for attempt in $(seq 1 "${BRAID_TEST_WAIT_SECONDS:-120}"); do - expected_tunnel="connected" - [[ "$webhook_mode" == "repository" ]] && expected_tunnel="disabled" - if curl -fsS "$health_url" 2>/dev/null | \ - jq -e --arg tunnel "$expected_tunnel" '.ready == true and .tunnel == $tunnel' >/dev/null; then - return 0 - fi - if ! kill -0 "$runtime_pid" 2>/dev/null; then - fail "runtime exited before becoming ready" - fi - sleep 1 - done - fail "runtime did not become ready within ${BRAID_TEST_WAIT_SECONDS:-120} seconds" -} - -start_runtime() { - : > "$runtime_log" - if [[ "$webhook_mode" == "app" ]]; then - BRAID_WEBHOOK_SECRET="$BRAID_WEBHOOK_SECRET" "$binary" serve \ - --config "$test_config" --tunnel --transport-only >"$runtime_log" 2>&1 & - else - BRAID_WEBHOOK_SECRET="$BRAID_WEBHOOK_SECRET" "$binary" serve \ - --config "$test_config" --transport-only >"$runtime_log" 2>&1 & - fi - runtime_pid=$! - wait_for_health - if [[ "$webhook_mode" == "app" ]]; then - local runtime_url app_url - runtime_url="$(curl -fsS "$health_url" | jq -er '.webhook_url')" - app_url="$($binary github webhook --config "$test_config" --json | jq -er '.url')" - [[ "$runtime_url" == "$app_url" ]] || fail "runtime and GitHub App webhook URLs diverged" - elif [[ -z "$repository_hook_id" ]]; then - repository_hook_id="$(jq -cn \ - --arg url "$repository_webhook_url" \ - '{name:"web",active:true,events:["issues","issue_comment","pull_request","pull_request_review","pull_request_review_comment"],config:{url:$url,content_type:"json",insecure_ssl:"0",secret:env.BRAID_WEBHOOK_SECRET}}' | \ - gh api --method POST "repos/$repository/hooks" --input - --jq '.id')" - [[ -n "$repository_hook_id" ]] || fail "GitHub did not create the temporary repository webhook" - fi -} - -wait_for_restoration() { - [[ "$webhook_mode" == "repository" ]] && return 0 - local attempt current - for attempt in $(seq 1 30); do - current="$($binary github webhook --config "$test_config" --json | jq -er '.url')" - [[ "$current" == "$prior_webhook_url" ]] && return 0 - sleep 1 - done - fail "graceful shutdown did not restore the prior GitHub App webhook URL" -} - -new_issue() { - local purpose=$1 number - number="$(gh api --method POST "repos/$repository/issues" \ - -f title="Braid Slice 2: $purpose $(date -u +%Y%m%dT%H%M%SZ)" \ - -f body="Disposable real-object fixture for the Braid Slice 2 ingress/scheduler gate." \ - --jq '.number')" - printf '%s' "$number" -} - -new_comment() { - local issue_number=$1 body=$2 - gh api --method POST "repos/$repository/issues/$issue_number/comments" \ - -f body="$body" --jq '.id' -} - -edit_comment() { - local comment_id=$1 body=$2 - gh api --method PATCH "repos/$repository/issues/comments/$comment_id" \ - -f body="$body" >/dev/null -} - -has_eyes() { - local comment_id=$1 - gh api "repos/$repository/issues/comments/$comment_id/reactions" \ - -H "Accept: application/vnd.github+json" \ - --jq ".[] | select(.content == \"eyes\" and .user.login == \"$app_actor\") | .id" | \ - grep -q . -} - -wait_for_eyes() { - local comment_id=$1 attempt - for attempt in $(seq 1 45); do - has_eyes "$comment_id" && return 0 - sleep 1 - done - fail "Braid App did not add eyes to comment $comment_id" -} - -wait_for_batch() { - local issue_number=$1 predicate=$2 attempt payload - for attempt in $(seq 1 60); do - payload="$(batch_json "$issue_number" 2>/dev/null || true)" - if [[ -n "$payload" ]] && jq -e "$predicate" >/dev/null <<<"$payload"; then - printf '%s' "$payload" - return 0 - fi - sleep 1 - done - fail "batch for Issue #$issue_number did not satisfy: $predicate" -} - -latest_delivery_id() { - local after_id=$1 event=$2 action=$3 attempt id deliveries - for attempt in $(seq 1 45); do - if [[ "$webhook_mode" == "app" ]]; then - deliveries="$($binary github deliveries --config "$test_config" --json)" - else - deliveries="$(gh api "repos/$repository/hooks/$repository_hook_id/deliveries?per_page=100")" - fi - id="$(jq -r --argjson after "$after_id" --arg event "$event" --arg action "$action" \ - '[.[] | select(.id > $after and .event == $event and .action == $action)] | max_by(.id) | .id // empty' \ - <<<"$deliveries")" - [[ -n "$id" ]] && { printf '%s' "$id"; return 0; } - sleep 1 - done - fail "GitHub delivery $event/$action did not appear" -} - -note "starting real Quick Tunnel and GitHub transport ($webhook_mode webhook mode)" -start_runtime - -note "proving durable ingest, eyes, redelivery dedupe, and quiet-window reset" -basic_issue="$(new_issue "durable ingress")" -fixture_issues+=("$basic_issue") -if [[ "$webhook_mode" == "app" ]]; then - before_delivery="$($binary github deliveries --config "$test_config" --json | jq '[.[].id] | max // 0')" -else - before_delivery="$(gh api "repos/$repository/hooks/$repository_hook_id/deliveries?per_page=100" --jq '[.[].id] | max // 0')" -fi -first_comment="$(new_comment "$basic_issue" "first ordinary event")" -wait_for_eyes "$first_comment" -created_delivery="$(latest_delivery_id "$before_delivery" issue_comment created)" -first_batch="$(wait_for_batch "$basic_issue" '.lifecycle == "pending" and .event_count == 1 and .urgent == false')" -first_deadline="$(jq -r .quiet_deadline <<<"$first_batch")" -sleep 10 -second_comment="$(new_comment "$basic_issue" "second ordinary event resets debounce")" -wait_for_eyes "$second_comment" -second_batch="$(wait_for_batch "$basic_issue" '.lifecycle == "pending" and .event_count >= 2')" -second_deadline="$(jq -r .quiet_deadline <<<"$second_batch")" -[[ "$second_deadline" > "$first_deadline" ]] || fail "quiet deadline did not move forward" - -if [[ "$webhook_mode" == "app" ]]; then - $binary github redeliver "$created_delivery" --config "$test_config" >/dev/null -else - gh api --method POST "repos/$repository/hooks/$repository_hook_id/deliveries/$created_delivery/attempts" >/dev/null -fi -for _ in $(seq 1 30); do - duplicates="$(status_json | jq -r '.transport.duplicate_deliveries')" - [[ "$duplicates" -ge 1 ]] && break - sleep 1 -done -[[ "${duplicates:-0}" -ge 1 ]] || fail "redelivered GUID was not deduplicated" -after_redelivery="$(batch_json "$basic_issue")" -[[ "$(jq -r .event_count <<<"$after_redelivery")" == "$(jq -r .event_count <<<"$second_batch")" ]] || \ - fail "redelivery changed the logical batch" -sleep 22 -[[ "$(batch_json "$basic_issue" | jq -r .lifecycle)" == "pending" ]] || \ - fail "batch released before 30 seconds from the second event" -wait_for_batch "$basic_issue" '.lifecycle == "runnable"' >/dev/null - -note "proving the eight-event release threshold" -threshold_issue="$(new_issue "event threshold")" -fixture_issues+=("$threshold_issue") -for index in $(seq 1 8); do - new_comment "$threshold_issue" "threshold event $index" >/dev/null -done -threshold_batch="$(wait_for_batch "$threshold_issue" '.lifecycle == "runnable" and .event_count >= 8')" -[[ "$(jq -r .urgent <<<"$threshold_batch")" == "false" ]] || fail "threshold batch was incorrectly urgent" - -note "proving visible trusted mention grammar" -grammar_issue="$(new_issue "mention grammar")" -fixture_issues+=("$grammar_issue") -new_comment "$grammar_issue" '> @braid quoted text must not be urgent' >/dev/null -new_comment "$grammar_issue" '`@braid` inline code must not be urgent' >/dev/null -new_comment "$grammar_issue" '' >/dev/null -grammar_batch="$(wait_for_batch "$grammar_issue" '.event_count >= 3')" -[[ "$(jq -r .urgent <<<"$grammar_batch")" == "false" ]] || fail "hidden/code/quoted mention became urgent" - -urgent_issue="$(new_issue "trusted mention")" -fixture_issues+=("$urgent_issue") -urgent_comment="$(new_comment "$urgent_issue" '@braid please inspect this fixture')" -wait_for_eyes "$urgent_comment" -wait_for_batch "$urgent_issue" '.lifecycle == "runnable" and .urgent == true' >/dev/null - -note "proving pending-batch restart and reconciliation across tunnel loss" -restart_issue="$(new_issue "restart and reconciliation")" -fixture_issues+=("$restart_issue") -restart_comment="$(new_comment "$restart_issue" 'pending before restart')" -wait_for_eyes "$restart_comment" -wait_for_batch "$restart_issue" '.lifecycle == "pending" and .event_count == 1' >/dev/null -stop_runtime -wait_for_restoration - -if [[ "$webhook_mode" == "app" ]]; then - before_lost_delivery="$($binary github deliveries --config "$test_config" --json | jq '[.[].id] | max // 0')" -else - before_lost_delivery="$(gh api "repos/$repository/hooks/$repository_hook_id/deliveries?per_page=100" --jq '[.[].id] | max // 0')" -fi -lost_comment="$(new_comment "$restart_issue" 'created while the local tunnel is unavailable')" -lost_delivery="$(latest_delivery_id "$before_lost_delivery" issue_comment created)" - -start_runtime -wait_for_eyes "$lost_comment" -wait_for_batch "$restart_issue" '.event_count >= 2' >/dev/null -edit_comment "$lost_comment" 'newer canonical body after runtime recovery' -sleep 3 -count_before_old="$(batch_json "$restart_issue" | jq -r .event_count)" -if [[ "$webhook_mode" == "app" ]]; then - $binary github redeliver "$lost_delivery" --config "$test_config" >/dev/null -else - gh api --method POST "repos/$repository/hooks/$repository_hook_id/deliveries/$lost_delivery/attempts" >/dev/null -fi -sleep 5 -count_after_old="$(batch_json "$restart_issue" | jq -r .event_count)" -[[ "$count_after_old" == "$count_before_old" ]] || \ - fail "an older delivery regressed or duplicated the canonical batch" - -stop_runtime -wait_for_restoration - -jq -n \ - --arg repository "$repository" \ - --arg app_actor "$app_actor" \ - --arg webhook_mode "$webhook_mode" \ - --argjson durable_issue "$basic_issue" \ - --argjson threshold_issue "$threshold_issue" \ - --argjson grammar_issue "$grammar_issue" \ - --argjson urgent_issue "$urgent_issue" \ - --argjson restart_issue "$restart_issue" \ - '{ - verdict:"PASS", - boundary:"real GitHub webhook -> Quick Tunnel -> packaged Braid -> Braid App reactions/status", - webhook_mode:$webhook_mode, - repository:$repository, - app_actor:$app_actor, - fixtures:[$durable_issue,$threshold_issue,$grammar_issue,$urgent_issue,$restart_issue] - }' diff --git a/scripts/tests/30_issue_agent.sh b/scripts/tests/30_issue_agent.sh deleted file mode 100755 index 57c75f3f..00000000 --- a/scripts/tests/30_issue_agent.sh +++ /dev/null @@ -1,498 +0,0 @@ -#!/bin/bash -set -euo pipefail - -readonly script_name="$(basename "$0")" -readonly config_path="${BRAID_CONFIG:-}" -readonly binary="${BRAID_BIN:-$(command -v braid || true)}" -readonly ingress_address="${BRAID_TEST_INGRESS:-127.0.0.1:18080}" -readonly health_address="${BRAID_TEST_HEALTH:-127.0.0.1:18081}" -readonly health_url="http://$health_address/healthz" -readonly evidence_root="${BRAID_TEST_EVIDENCE_DIR:-$(mktemp -d "${TMPDIR:-/tmp}/braid-slice3-evidence.XXXXXX")}" -readonly keep_fixture="${BRAID_TEST_KEEP_FIXTURES:-0}" - -runtime_pid="" -tunnel_pid="" -repository_hook_id="" -fixture_issue="" -failure_issue="" -temporary_root="" -runtime_log="" -tunnel_log="" - -fail() { - printf '%s: FAIL: %s\n' "$script_name" "$*" >&2 - exit 1 -} - -note() { - printf '%s: %s\n' "$script_name" "$*" -} - -require_command() { - command -v "$1" >/dev/null 2>&1 || fail "required command is unavailable: $1" -} - -stop_process() { - local pid=$1 - [[ -n "$pid" ]] || return 0 - kill -0 "$pid" 2>/dev/null || return 0 - kill -INT "$pid" 2>/dev/null || true - for _ in $(seq 1 10); do - kill -0 "$pid" 2>/dev/null || { wait "$pid" 2>/dev/null || true; return 0; } - sleep 1 - done - kill -TERM "$pid" 2>/dev/null || true - for _ in $(seq 1 5); do - kill -0 "$pid" 2>/dev/null || { wait "$pid" 2>/dev/null || true; return 0; } - sleep 1 - done - kill -KILL "$pid" 2>/dev/null || true - wait "$pid" 2>/dev/null || true -} - -cleanup() { - local exit_status=$? - stop_process "$runtime_pid" - stop_process "$tunnel_pid" - if [[ -n "$repository_hook_id" ]]; then - gh api --method DELETE "repos/$repository/hooks/$repository_hook_id" >/dev/null 2>&1 || true - fi - if [[ -n "$fixture_issue" && "$keep_fixture" != "1" ]]; then - gh issue close "$fixture_issue" --repo "$repository" \ - --comment "Braid Slice 3 black-box fixture closed." >/dev/null 2>&1 || true - fi - if [[ -n "$failure_issue" && "$keep_fixture" != "1" ]]; then - gh issue close "$failure_issue" --repo "$repository" \ - --comment "Braid Slice 3 failure fixture closed." >/dev/null 2>&1 || true - fi - if [[ $exit_status -ne 0 ]]; then - printf '%s: runtime log follows\n' "$script_name" >&2 - [[ -f "$runtime_log" ]] && tail -200 "$runtime_log" >&2 || true - printf '%s: tunnel log follows\n' "$script_name" >&2 - [[ -f "$tunnel_log" ]] && tail -100 "$tunnel_log" >&2 || true - fi - if [[ -n "$temporary_root" && -d "$temporary_root" ]]; then - mkdir -p "$evidence_root" - cp "$temporary_root"/*.log "$evidence_root/" 2>/dev/null || true - if [[ -f "$temporary_root/braid.toml" ]]; then - "$binary" status --config "$temporary_root/braid.toml" --json > "$evidence_root/status.json" 2>/dev/null || true - fi - if [[ -f "$temporary_root/failure.toml" ]]; then - "$binary" status --config "$temporary_root/failure.toml" --json > "$evidence_root/failure-status.json" 2>/dev/null || true - fi - for issue in "$fixture_issue" "$failure_issue"; do - [[ -n "$issue" ]] || continue - gh api "repos/$repository/issues/$issue/comments" > "$evidence_root/issue-$issue-comments.json" 2>/dev/null || true - done - rm -rf "$temporary_root" - fi - printf '%s: evidence: %s (exit=%s)\n' "$script_name" "$evidence_root" "$exit_status" - exit "$exit_status" -} -trap cleanup EXIT -trap 'exit 130' INT -trap 'exit 143' TERM - -[[ -n "$binary" && -x "$binary" ]] || fail "set BRAID_BIN to the packaged braid binary" -[[ -n "$config_path" && "$config_path" = /* && -f "$config_path" ]] || \ - fail "set BRAID_CONFIG to an absolute acceptance configuration path" -[[ -n "${BRAID_WEBHOOK_SECRET:-}" ]] || \ - fail "BRAID_WEBHOOK_SECRET must match the dedicated acceptance webhook secret" -for command in curl gh grep jq mktemp pgrep sed shasum; do - require_command "$command" -done -gh auth status >/dev/null 2>&1 || fail "gh must expose the configured Coding Agent identity" - -repository="$($binary config check --config "$config_path" --json | jq -er '.repository')" -app_actor="$($binary github probe --config "$config_path" --repository "$repository" --json | jq -er '.actor_login')" -agent_actor="$(gh api user --jq '.login')" -wrangler="${BRAID_TEST_WRANGLER:-$(command -v wrangler || true)}" -public_url="${BRAID_TEST_PUBLIC_WEBHOOK_URL:-}" -public_url="${public_url%/webhook}" -if [[ -z "$public_url" ]]; then - [[ -n "$wrangler" && -x "$wrangler" ]] || fail "set BRAID_TEST_WRANGLER to Wrangler" -fi -candidate_version="$($binary --version)" -candidate_sha256="$(shasum -a 256 "$binary" | sed 's/ .*//')" -note "candidate $candidate_version sha256=$candidate_sha256" - -mkdir -p "$evidence_root" -temporary_root="$(mktemp -d "${TMPDIR:-/tmp}/braid-slice3.XXXXXX")" -runtime_log="$temporary_root/runtime.log" -tunnel_log="$temporary_root/tunnel.log" -readonly runtime_root="$temporary_root/runtime" -readonly test_config="$temporary_root/braid.toml" -mkdir -p "$runtime_root/state/backups" - -awk \ - -v root="$runtime_root" \ - -v database="$runtime_root/state/braid.sqlite3" \ - -v backups="$runtime_root/state/backups" \ - -v ingress="$ingress_address" \ - -v health="$health_address" ' - /^\[runtime\]$/ { section="runtime"; print; next } - /^\[server\]$/ { section="server"; print; next } - /^\[/ && $0 != "[runtime]" && $0 != "[server]" { section="other" } - section == "runtime" && /^root = / { printf "root = \"%s\"\n", root; next } - section == "runtime" && /^database = / { printf "database = \"%s\"\n", database; next } - section == "runtime" && /^backups = / { printf "backups = \"%s\"\n", backups; next } - section == "runtime" && /^auto_migrate = / { print "auto_migrate = false"; next } - section == "server" && /^ingress = / { printf "ingress = \"%s\"\n", ingress; next } - section == "server" && /^health = / { printf "health = \"%s\"\n", health; next } - { print } -' "$config_path" > "$test_config" - -$binary migrate apply --config "$test_config" >/dev/null -$binary status --config "$test_config" --json | \ - jq -e '.database.schema_version == 2 and .database.supported_schema == 2' >/dev/null || \ - fail "candidate does not expose the expected current schema 2" - -public_url="${BRAID_TEST_PUBLIC_WEBHOOK_URL:-}" -public_url="${public_url%/webhook}" -if [[ -n "$public_url" ]]; then - note "using external public webhook URL" - tunnel_pid="" -else - note "starting a free HTTP/2 Quick Tunnel" - TUNNEL_TRANSPORT_PROTOCOL=http2 "$wrangler" tunnel quick-start \ - "http://$ingress_address" --log-level info >"$tunnel_log" 2>&1 & - tunnel_pid=$! - public_url="" - for _ in $(seq 1 60); do - public_url="$(grep -Eo 'https://[a-z0-9-]+\.(trycloudflare\.com|loca\.lt)' "$tunnel_log" | head -1 || true)" - grep -q 'Registered tunnel connection' "$tunnel_log" 2>/dev/null && \ - [[ -n "$public_url" ]] && break - kill -0 "$tunnel_pid" 2>/dev/null || fail "Quick Tunnel exited during startup" - sleep 1 - done - [[ -n "$public_url" ]] || fail "Quick Tunnel did not publish a URL" -fi - -note "starting packaged Braid with the real Codex app-server" -BRAID_CONFIG="$test_config" PATH="$(dirname "$binary"):$PATH" BRAID_WEBHOOK_SECRET="$BRAID_WEBHOOK_SECRET" "$binary" serve \ - --config "$test_config" >"$runtime_log" 2>&1 & -runtime_pid=$! -for _ in $(seq 1 "${BRAID_TEST_WAIT_SECONDS:-120}"); do - if curl -fsS "$health_url" 2>/dev/null | \ - jq -e '.ready == true and .provider == "connected"' >/dev/null; then - break - fi - kill -0 "$runtime_pid" 2>/dev/null || fail "Braid exited during startup" - sleep 1 -done -curl -fsS "$health_url" | jq -e '.ready == true and .provider == "connected"' >/dev/null || \ - fail "Braid did not become provider-ready" - -note "verifying the public signed webhook path before creating fixtures" -public_probe_ready=0 -# Give fresh Quick Tunnel DNS time to publish before priming resolver caches. -sleep 20 -for _ in $(seq 1 3); do - if "$binary" tunnel probe --config "$test_config" --url "$public_url/webhook" >> "$temporary_root/public-probe.log" 2>&1; then - public_probe_ready=1 - break - fi - sleep 5 -done -[[ "$public_probe_ready" -eq 1 ]] || fail "public signed webhook probe failed" - -repository_hook_id="$(jq -nc \ - --arg url "$public_url/webhook" \ - '{name:"web",active:true,events:["issues","issue_comment"],config:{url:$url,content_type:"json",insecure_ssl:"0",secret:env.BRAID_WEBHOOK_SECRET}}' | \ - gh api --method POST "repos/$repository/hooks" --input - --jq '.id')" -[[ -n "$repository_hook_id" ]] || fail "GitHub did not create the temporary repository webhook" - -note "activating a dormant Issue through the trusted-mention fallback" -fixture_issue="$(gh api --method POST "repos/$repository/issues" \ - -f title="Braid Slice 3: Issue Agent $(date -u +%Y%m%dT%H%M%SZ)" \ - -f body='Disposable real-object fixture for the Braid Issue Agent gate.' --jq '.number')" -mention_comment="$(gh api --method POST "repos/$repository/issues/$fixture_issue/comments" \ - -f body='@braid Acceptance request: read this Issue, wait at least 8 seconds with a shell command, then publish exactly one concise comment saying the real Issue Agent turn completed. Begin with the required Braid Agent attribution quote.' --jq '.id')" - -has_reaction() { - local comment_id=$1 - local content=$2 - gh api "repos/$repository/issues/comments/$comment_id/reactions" \ - --jq ".[] | select(.content == \"$content\" and .user.login == \"$app_actor\") | .id" | \ - grep -q . -} - -agent_marker_count() { - local issue=$1 - local marker=$2 - gh api "repos/$repository/issues/$issue/comments" | jq --arg actor "$app_actor" --arg marker "$marker" \ - '[.[] | select(.user.login == $actor and (.body | startswith("> **Braid Agent")) and (.body | contains($marker)))] | length' -} - -for _ in $(seq 1 90); do - has_reaction "$mention_comment" eyes && has_reaction "$mention_comment" rocket && break - sleep 1 -done -has_reaction "$mention_comment" eyes || fail "Braid did not acknowledge the mention with eyes" -has_reaction "$mention_comment" rocket || fail "Braid did not expose the accepted active turn with rocket" - -note "steering the same active turn with an edited trusted mention" -gh api --method PATCH "repos/$repository/issues/comments/$mention_comment" \ - -f body='@braid Acceptance update: keep the same concise completion comment; this edit must steer the active turn rather than start a parallel turn.' >/dev/null - -for _ in $(seq 1 180); do - agent_comments="$(gh api "repos/$repository/issues/$fixture_issue/comments" 2>/dev/null | \ - jq --arg actor "$app_actor" \ - '[.[] | select(.user.login == $actor and (.body | startswith("> **Braid Agent")))] | length' || true)" - if has_reaction "$mention_comment" +1 && [[ "${agent_comments:-0}" -eq 1 ]]; then - break - fi - sleep 2 -done -has_reaction "$mention_comment" +1 || fail "Braid did not expose normal terminal with +1" -[[ "${agent_comments:-0}" -eq 1 ]] || fail "Agent did not publish exactly one attributed comment" - -for _ in $(seq 1 30); do - has_reaction "$mention_comment" rocket || break - sleep 1 -done -has_reaction "$mention_comment" rocket && fail "terminal reaction state retained stale rocket" - -sleep 3 -status_payload="$($binary status --config "$test_config" --json)" -jq -e --argjson number "$fixture_issue" ' - [.transport.agent_groups[] | - select(.work_item_kind == "issue" and .work_item_number == $number and - .assignment_lifecycle == "active" and .session_lifecycle == "idle" and - .active_turn_id == null)] | length == 1 -' >/dev/null <<<"$status_payload" || fail "Issue Agent did not converge to one idle session" -app_comments="$(gh api "repos/$repository/issues/$fixture_issue/comments" | \ - jq --arg actor "$app_actor" '[.[] | select(.user.login == $actor)] | length')" -[[ "$app_comments" -eq 1 ]] || fail "Braid did not publish exactly one App-authored comment" - -note "proving one ordinary comment waits for the complete quiet window" -ordinary_marker="BRAID_ORDINARY_COMPLETE_$(date -u +%s)" -ordinary_started="$(date +%s)" -ordinary_comment="$(gh api --method POST "repos/$repository/issues/$fixture_issue/comments" \ - -f body="Ordinary event: after Braid releases this batch, publish one concise attributed comment containing $ordinary_marker. Do not mention the configured handle." --jq '.id')" -for _ in $(seq 1 30); do - has_reaction "$ordinary_comment" eyes && break - sleep 1 -done -has_reaction "$ordinary_comment" eyes || fail "ordinary comment did not receive eyes" -while [[ "$(($(date +%s) - ordinary_started))" -lt 30 ]]; do - [[ "$(agent_marker_count "$fixture_issue" "$ordinary_marker")" -eq 0 ]] || \ - fail "ordinary turn produced Agent output before the 30-second quiet window" - sleep 2 -done -for _ in $(seq 1 60); do - [[ "$(agent_marker_count "$fixture_issue" "$ordinary_marker")" -eq 1 ]] && break - sleep 2 -done -[[ "$(agent_marker_count "$fixture_issue" "$ordinary_marker")" -eq 1 ]] || \ - fail "ordinary debounced turn did not publish exactly one Agent marker" -for reaction in rocket +1 confused; do - has_reaction "$ordinary_comment" "$reaction" && \ - fail "ordinary turn exposed request-like $reaction reaction" -done - -note "proving eight ordinary events release one count-threshold turn" -count_marker="BRAID_COUNT_COMPLETE_$(date -u +%s)" -count_comments=() -for index in $(seq 1 7); do - count_comments+=("$(gh api --method POST "repos/$repository/issues/$fixture_issue/comments" \ - -f body="Count-threshold event $index of 8. Do not publish yet and do not mention the configured handle." --jq '.id')") - sleep 1 -done -count_comments+=("$(gh api --method POST "repos/$repository/issues/$fixture_issue/comments" \ - -f body="Count-threshold event 8 of 8: run a shell sleep for 8 seconds, then publish one concise attributed comment containing $count_marker. Do not mention the configured handle." --jq '.id')") -count_durable=0 -for _ in $(seq 1 90); do - count_durable=1 - for comment_id in "${count_comments[@]}"; do - if ! has_reaction "$comment_id" eyes; then - count_durable=0 - break - fi - done - [[ "$count_durable" -eq 1 ]] && break - sleep 1 -done -[[ "$count_durable" -eq 1 ]] || fail "GitHub did not deliver all eight events into Braid" -count_started="$(date +%s)" -count_running=0 -for _ in $(seq 1 15); do - if [[ "$(agent_marker_count "$fixture_issue" "$count_marker")" -eq 1 ]]; then - count_running=1 - break - fi - status_payload="$($binary status --config "$test_config" --json)" - if jq -e --argjson number "$fixture_issue" ' - any(.transport.agent_groups[]; - .work_item_kind == "issue" and .work_item_number == $number and - .session_lifecycle == "running" and .turn_lifecycle == "running") - ' >/dev/null <<<"$status_payload"; then - count_running=1 - break - fi - sleep 1 -done -[[ "$count_running" -eq 1 ]] || \ - fail "eight-event batch was not accepted within 15 seconds of durable receipt" -for _ in $(seq 1 60); do - [[ "$(agent_marker_count "$fixture_issue" "$count_marker")" -eq 1 ]] && break - sleep 2 -done -[[ "$(agent_marker_count "$fixture_issue" "$count_marker")" -eq 1 ]] || \ - fail "count-threshold turn did not publish exactly one Agent marker" -for comment_id in "${count_comments[@]}"; do - has_reaction "$comment_id" eyes || fail "count-threshold comment did not receive eyes" - for reaction in rocket +1 confused; do - has_reaction "$comment_id" "$reaction" && \ - fail "count-threshold turn exposed request-like $reaction reaction" - done -done -[[ "$(($(date +%s) - count_started))" -lt 90 ]] || \ - fail "count-threshold turn did not converge in the bounded window" - -note "proving provider disconnect remains unknown and publishes Operational Status" -unknown_comment="$(gh api --method POST "repos/$repository/issues/$fixture_issue/comments" \ - -f body='@braid Unknown-outcome fixture: run a shell sleep for 60 seconds before any other action; do not publish a comment before the sleep finishes.' --jq '.id')" -for _ in $(seq 1 90); do - has_reaction "$unknown_comment" eyes && has_reaction "$unknown_comment" rocket && break - sleep 1 -done -printf '%s\n' "$status_payload" > "$evidence_root/unknown-status.json" -has_reaction "$unknown_comment" rocket || fail "unknown-outcome turn was not accepted" -unknown_session="$($binary status --config "$test_config" --json | jq -er --argjson number "$fixture_issue" '.transport.agent_groups[] | select(.work_item_number == $number and .turn_lifecycle == "running") | .provider_session_id')" -provider_pid="$(pgrep -P "$runtime_pid" -f 'codex.*app-server' | head -1 || true)" -if [[ -z "$provider_pid" ]]; then - provider_pid="$(pgrep -P "$runtime_pid" | head -1 || true)" -fi -[[ -n "$provider_pid" ]] || fail "cannot locate the real provider child process" -pkill -9 -P "$provider_pid" >/dev/null 2>&1 || true -kill -KILL "$provider_pid" -for _ in $(seq 1 60); do - status_payload="$($binary status --config "$test_config" --json)" - if jq -e --argjson number "$fixture_issue" ' - any(.transport.agent_groups[]; - .work_item_kind == "issue" and .work_item_number == $number and - .turn_lifecycle == "unknown") - ' >/dev/null <<<"$status_payload"; then - break - fi - sleep 1 -done -jq -e --argjson number "$fixture_issue" ' - any(.transport.agent_groups[]; - .work_item_kind == "issue" and .work_item_number == $number and - .turn_lifecycle == "unknown") -' >/dev/null <<<"$status_payload" || fail "disconnect did not preserve an unknown turn" -printf '%s\n' "$status_payload" > "$evidence_root/unknown-status.json" -has_reaction "$unknown_comment" rocket || fail "unknown turn did not retain rocket" -has_reaction "$unknown_comment" +1 && fail "unknown turn was reported successful" -has_reaction "$unknown_comment" confused && fail "unknown turn was reported failed" -for _ in $(seq 1 60); do - operational_comments="$(gh api "repos/$repository/issues/$fixture_issue/comments" | \ - jq --arg actor "$app_actor" '[.[] | select(.user.login == $actor and (.body | startswith("> **Braid Operational Status")) and (.body | contains("Provider outcome unknown")))] | length')" - [[ "$operational_comments" -eq 1 ]] && break - sleep 1 -done -[[ "${operational_comments:-0}" -eq 1 ]] || fail "provider unknown did not publish one Operational Status comment" -for _ in $(seq 1 60); do - status_payload="$($binary status --config "$test_config" --json)" - if jq -e --argjson number "$fixture_issue" --arg old "$unknown_session" ' - any(.transport.agent_groups[]; .work_item_number == $number and - .provider_session_id != $old and .turn_lifecycle == "running") - ' >/dev/null <<<"$status_payload"; then break; fi - sleep 1 -done -jq -e --argjson number "$fixture_issue" --arg old "$unknown_session" ' - any(.transport.agent_groups[]; .work_item_number == $number and - .provider_session_id != $old and .turn_lifecycle == "running") -' >/dev/null <<<"$status_payload" || fail "fenced input did not resume in a replacement session" -printf '%s\n' "$status_payload" > "$evidence_root/recovery-status.json" -curl -fsS "$health_url" > "$evidence_root/recovery-health.json" -jq -e '.provider == "connected"' "$evidence_root/recovery-health.json" >/dev/null || fail "provider health did not recover" - - -stop_process "$runtime_pid" -runtime_pid="" - -note "proving a real accepted Codex turn can terminate failed and converge to confused" -readonly failure_root="$temporary_root/failure-runtime" -readonly failure_config="$temporary_root/failure.toml" -mkdir -p "$failure_root/state/backups" -awk \ - -v root="$failure_root" \ - -v database="$failure_root/state/braid.sqlite3" ' - /^\[runtime\]$/ { section="runtime"; print; next } - /^\[\[profiles\]\]$/ { profile += 1; section="profile"; print; next } - /^\[/ && $0 != "[runtime]" && $0 != "[[profiles]]" { section="other" } - section == "runtime" && /^root = / { printf "root = \"%s\"\n", root; next } - section == "runtime" && /^database = / { printf "database = \"%s\"\n", database; next } - section == "runtime" && /^backups = / { printf "backups = \"%s/state/backups\"\n", root; next } - profile == 1 && /^model = / { print "model = \"braid-intentionally-invalid-model\""; next } - { print } -' "$test_config" > "$failure_config" -$binary migrate apply --config "$failure_config" >/dev/null -runtime_log="$temporary_root/failure-runtime.log" -BRAID_CONFIG="$failure_config" PATH="$(dirname "$binary"):$PATH" BRAID_WEBHOOK_SECRET="$BRAID_WEBHOOK_SECRET" "$binary" serve \ - --config "$failure_config" >"$runtime_log" 2>&1 & -runtime_pid=$! -for _ in $(seq 1 "${BRAID_TEST_WAIT_SECONDS:-120}"); do - if curl -fsS "$health_url" 2>/dev/null | \ - jq -e '.ready == true and .provider == "connected"' >/dev/null; then - break - fi - kill -0 "$runtime_pid" 2>/dev/null || fail "failure-fixture Braid exited during startup" - sleep 1 -done -failure_issue="$(gh api --method POST "repos/$repository/issues" \ - -f title="Braid Slice 3: failed terminal $(date -u +%Y%m%dT%H%M%SZ)" \ - -f body='Disposable real-provider failed-terminal fixture.' --jq '.number')" -failure_comment="$(gh api --method POST "repos/$repository/issues/$failure_issue/comments" \ - -f body='@braid Start the controlled real-provider failure turn.' --jq '.id')" -rocket_observed=0 -# Invalid-model failures can settle in under two seconds. Sample both states -# from one response, without the blind interval between two separate requests. -for _ in $(seq 1 180); do - reactions="$(gh api "repos/$repository/issues/comments/$failure_comment/reactions")" - printf '%s\n' "$reactions" | jq -c . >> "$evidence_root/failure-reactions.ndjson" - jq -e --arg actor "$app_actor" 'any(.[]; .user.login == $actor and .content == "rocket")' >/dev/null <<<"$reactions" && rocket_observed=1 - if jq -e --arg actor "$app_actor" 'any(.[]; .user.login == $actor and .content == "confused")' >/dev/null <<<"$reactions"; then break; fi - sleep 0.1 -done -[[ "$rocket_observed" -eq 1 ]] || fail "failed-terminal turn never exposed accepted rocket" -has_reaction "$failure_comment" confused || fail "real failed terminal did not converge to confused" -for _ in $(seq 1 30); do - has_reaction "$failure_comment" rocket || break - sleep 1 -done -has_reaction "$failure_comment" rocket && fail "failed terminal retained stale rocket" -failure_agent_comments="$(gh api "repos/$repository/issues/$failure_issue/comments" | \ - jq --arg actor "$app_actor" '[.[] | select(.user.login == $actor and (.body | startswith("> **Braid Agent")))] | length')" -[[ "$failure_agent_comments" -eq 0 ]] || fail "failed provider turn fabricated an Agent comment" - -stop_process "$runtime_pid" -runtime_pid="" -stop_process "$tunnel_pid" -tunnel_pid="" - -jq -n \ - --arg repository "$repository" \ - --arg app_actor "$app_actor" \ - --arg agent_actor "$agent_actor" \ - --arg candidate "$candidate_version" \ - --arg candidate_sha256 "$candidate_sha256" \ - --arg activation "trusted @braid fallback (ordinary GitHub App is not assignable)" \ - --argjson issue "$fixture_issue" \ - --argjson failure_issue "$failure_issue" \ - '{ - verdict:"PASS", - boundary:"real GitHub -> HTTP/2 Quick Tunnel -> packaged Braid -> real Codex app-server -> Agent gh comment", - repository:$repository, - activation:$activation, - candidate:$candidate, - candidate_sha256:$candidate_sha256, - app_actor:$app_actor, - agent_actor:$agent_actor, - fixture_issue:$issue, - failed_terminal_issue:$failure_issue, - journeys:["trusted-mention-steer","ordinary-debounce","eight-event-threshold","provider-disconnect-unknown","real-provider-failed-terminal"] - }' | tee "$evidence_root/result.json" diff --git a/scripts/tests/40_context_lifecycle.sh b/scripts/tests/40_context_lifecycle.sh deleted file mode 100755 index dcc787c9..00000000 --- a/scripts/tests/40_context_lifecycle.sh +++ /dev/null @@ -1,808 +0,0 @@ -#!/bin/bash -set -euo pipefail - -readonly script_name="$(basename "$0")" -readonly config_path="${BRAID_CONFIG:-}" -readonly binary="${BRAID_BIN:-$(command -v braid || true)}" -readonly ingress_address="${BRAID_TEST_INGRESS:-127.0.0.1:18080}" -readonly health_address="${BRAID_TEST_HEALTH:-127.0.0.1:18081}" -readonly health_url="http://$health_address/healthz" -readonly keep_fixture="${BRAID_TEST_KEEP_FIXTURES:-0}" - -runtime_pid="" -tunnel_pid="" -repository_hook_id="" -fixture_issue="" -soft_issue="" -hard_issue="" -temporary_root="" -runtime_log="" -tunnel_log="" - -fail() { - printf '%s: FAIL: %s\n' "$script_name" "$*" >&2 - exit 1 -} - -note() { - printf '%s: %s\n' "$script_name" "$*" -} - -stop_process() { - local pid=$1 - [[ -n "$pid" ]] || return 0 - kill -0 "$pid" 2>/dev/null || return 0 - kill -INT "$pid" 2>/dev/null || true - for _ in $(seq 1 10); do - kill -0 "$pid" 2>/dev/null || { wait "$pid" 2>/dev/null || true; return 0; } - sleep 1 - done - kill -TERM "$pid" 2>/dev/null || true - sleep 2 - kill -KILL "$pid" 2>/dev/null || true - wait "$pid" 2>/dev/null || true -} - -cleanup() { - local exit_status=$? - stop_process "$runtime_pid" - stop_process "$tunnel_pid" - if [[ -n "$repository_hook_id" ]]; then - gh api --method DELETE "repos/$repository/hooks/$repository_hook_id" >/dev/null 2>&1 || true - fi - if [[ "$keep_fixture" != "1" ]]; then - for issue in "$fixture_issue" "$soft_issue" "$hard_issue"; do - [[ -n "$issue" ]] || continue - gh issue close "$issue" --repo "$repository" \ - --comment "Braid Slice 4 black-box fixture closed." >/dev/null 2>&1 || true - done - fi - if [[ $exit_status -ne 0 ]]; then - printf '%s: runtime log follows\n' "$script_name" >&2 - [[ -f "$runtime_log" ]] && tail -240 "$runtime_log" >&2 || true - printf '%s: tunnel log follows\n' "$script_name" >&2 - [[ -f "$tunnel_log" ]] && tail -100 "$tunnel_log" >&2 || true - fi - if [[ -n "$temporary_root" && -d "$temporary_root" ]]; then - rm -rf "$temporary_root" - fi - exit "$exit_status" -} -trap cleanup EXIT INT TERM - -[[ -n "$binary" && -x "$binary" ]] || fail "set BRAID_BIN to the packaged braid binary" -[[ -n "$config_path" && "$config_path" = /* && -f "$config_path" ]] || \ - fail "set BRAID_CONFIG to an absolute acceptance configuration path" -[[ -n "${BRAID_WEBHOOK_SECRET:-}" ]] || \ - fail "BRAID_WEBHOOK_SECRET must match the temporary repository webhook secret" -for command in awk curl gh grep head jq mktemp ps sed shasum tr; do - command -v "$command" >/dev/null 2>&1 || fail "required command is unavailable: $command" -done -gh auth status >/dev/null 2>&1 || fail "gh must expose the controlled Human/Agent identity" - -repository="$($binary config check --config "$config_path" --json | jq -er '.repository')" -app_actor="$($binary github probe --config "$config_path" --repository "$repository" --json | jq -er '.actor_login')" -wrangler="${BRAID_TEST_WRANGLER:-$(command -v wrangler || true)}" -tunnel_url="${BRAID_TEST_PUBLIC_WEBHOOK_URL:-}" -tunnel_url="${tunnel_url%/webhook}" -if [[ -z "$tunnel_url" ]]; then - [[ -n "$wrangler" && -x "$wrangler" ]] || fail "set BRAID_TEST_WRANGLER to Wrangler" -fi -candidate_version="$($binary --version)" -candidate_sha256="$(shasum -a 256 "$binary" | sed 's/ .*//')" -note "candidate $candidate_version sha256=$candidate_sha256" - -temporary_root="$(mktemp -d "${TMPDIR:-/tmp}/braid-slice4.XXXXXX")" -runtime_log="$temporary_root/runtime.log" -tunnel_log="$temporary_root/tunnel.log" -readonly runtime_root="$temporary_root/runtime" -readonly test_config="$temporary_root/braid.toml" -mkdir -p "$runtime_root/state/backups" - -# The controlled Human and Agent share one gh login in this PoC. Removing the -# optional stable actor declaration lets quote-block attribution identify Agent -# comments while plain Human edits remain external invalidations. -awk \ - -v root="$runtime_root" \ - -v database="$runtime_root/state/braid.sqlite3" \ - -v backups="$runtime_root/state/backups" \ - -v ingress="$ingress_address" \ - -v health="$health_address" ' - /^github_actor_node_id = / { next } - /^\[runtime\]$/ { section="runtime"; print; next } - /^\[server\]$/ { section="server"; print; next } - /^\[/ && $0 != "[runtime]" && $0 != "[server]" { section="other" } - section == "runtime" && /^root = / { printf "root = \"%s\"\n", root; next } - section == "runtime" && /^database = / { printf "database = \"%s\"\n", database; next } - section == "runtime" && /^backups = / { printf "backups = \"%s\"\n", backups; next } - section == "runtime" && /^auto_migrate = / { print "auto_migrate = false"; next } - section == "server" && /^ingress = / { printf "ingress = \"%s\"\n", ingress; next } - section == "server" && /^health = / { printf "health = \"%s\"\n", health; next } - { print } -' "$config_path" > "$test_config" - -$binary migrate apply --config "$test_config" >/dev/null -$binary status --config "$test_config" --json | \ - jq -e '.database.schema_version == 2 and .database.supported_schema == 2' >/dev/null || \ - fail "candidate does not expose the expected current schema 1" - -if [[ -n "$tunnel_url" ]]; then - note "using external public webhook URL" - tunnel_pid="" -else - note "starting a free HTTP/2 Quick Tunnel" - TUNNEL_TRANSPORT_PROTOCOL=http2 "$wrangler" tunnel quick-start \ - "http://$ingress_address" >"$tunnel_log" 2>&1 & - tunnel_pid=$! - tunnel_url="" - for _ in $(seq 1 90); do - tunnel_url="$(grep -Eo 'https://[a-z0-9-]+\.(trycloudflare\.com|loca\.lt)' "$tunnel_log" | tail -1 || true)" - [[ -n "$tunnel_url" ]] && break - kill -0 "$tunnel_pid" 2>/dev/null || fail "Quick Tunnel exited before publishing a URL" - sleep 1 - done - [[ -n "${tunnel_url:-}" ]] || fail "Quick Tunnel did not publish a URL" -fi - -BRAID_WEBHOOK_SECRET="$BRAID_WEBHOOK_SECRET" "$binary" serve \ - --config "$test_config" >"$runtime_log" 2>&1 & -runtime_pid=$! -for _ in $(seq 1 "${BRAID_TEST_WAIT_SECONDS:-120}"); do - if curl -fsS "$health_url" 2>/dev/null | \ - jq -e '.ready == true and .provider == "connected"' >/dev/null; then - break - fi - kill -0 "$runtime_pid" 2>/dev/null || fail "Braid exited during startup" - sleep 1 -done -curl -fsS "$health_url" | jq -e '.ready == true and .provider == "connected"' >/dev/null || \ - fail "Braid did not become ready" - -note "verifying the public signed webhook boundary before creating GitHub fixtures" -public_probe_ready=0 -for _ in $(seq 1 3); do - if BRAID_WEBHOOK_SECRET="$BRAID_WEBHOOK_SECRET" "$binary" tunnel probe \ - --config "$test_config" --url "$tunnel_url/webhook" >/dev/null 2>&1; then - public_probe_ready=1 - break - fi - sleep 5 -done -[[ "$public_probe_ready" -eq 1 ]] || fail "public signed webhook probe failed" - -readonly baseline_marker="BRAID_RESET_BASELINE_$(date -u +%s)" -readonly idle_marker="BRAID_IDLE_CONTEXT_$(date -u +%s)" -readonly active_marker="BRAID_ACTIVE_CONTEXT_$(date -u +%s)" -readonly restored_marker="BRAID_RESTORED_COMMENT_$(date -u +%s)" -readonly deleted_marker="BRAID_DELETED_COMMENT_$(date -u +%s)" -readonly preclose_marker="BRAID_PRECLOSE_REVIEW_$(date -u +%s)" -readonly reopened_marker="BRAID_REOPENED_CONTEXT_$(date -u +%s)" -readonly resumed_marker="BRAID_PROVIDER_RESUMED_$(date -u +%s)" -fixture_issue="$(gh api --method POST "repos/$repository/issues" \ - -f title="Braid Slice 4: Context lifecycle $(date -u +%Y%m%dT%H%M%SZ)" \ - -f body="Baseline design: $baseline_marker" --jq '.number')" -restored_comment_json="$(gh api --method POST "repos/$repository/issues/$fixture_issue/comments" \ - -f body="Lifecycle fixture $restored_marker. Only when Braid reports that this comment was unminimized, publish one concise attributed comment containing $restored_marker.")" -restored_comment_node_id="$(jq -er '.node_id' <<<"$restored_comment_json")" -deleted_comment_json="$(gh api --method POST "repos/$repository/issues/$fixture_issue/comments" \ - -f body="Lifecycle deletion fixture: $deleted_marker")" -deleted_comment_id="$(jq -er '.id' <<<"$deleted_comment_json")" - -# Register transport only after the baseline lifecycle comments exist. They -# enter the initial canonical Context without manufacturing pre-activation -# Wake batches. -repository_hook_id="$(gh api --method POST "repos/$repository/hooks" \ - -f name=web \ - -F active=true \ - -f 'events[]=issues' \ - -f 'events[]=issue_comment' \ - -f "config[url]=$tunnel_url/webhook" \ - -f 'config[content_type]=json' \ - -f "config[secret]=$BRAID_WEBHOOK_SECRET" \ - --jq '.id')" - -has_reaction() { - local comment_id=$1 - local content=$2 - gh api "repos/$repository/issues/comments/$comment_id/reactions" \ - --jq ".[] | select(.content == \"$content\" and .user.login == \"$app_actor\") | .id" | \ - grep -q . -} - -agent_marker_count() { - local marker=$1 - local issue=${2:-$fixture_issue} - gh api "repos/$repository/issues/$issue/comments" | \ - jq --arg actor "$app_actor" --arg marker "$marker" \ - '[.[] | select(.user.login == $actor and (.body | startswith("> **Braid Agent")) and (.body | contains($marker)))] | length' -} - -operational_status_count() { - local issue=$1 - local phrase=$2 - gh api "repos/$repository/issues/$issue/comments" | \ - jq --arg actor "$app_actor" --arg phrase "$phrase" \ - '[.[] | select(.user.login == $actor and (.body | contains($phrase)))] | length' -} - -write_pressure_config() { - local destination=$1 - local root=$2 - local soft_ratio=$3 - local hard_bytes=$4 - mkdir -p "$root/state/backups" - awk \ - -v root="$root" \ - -v database="$root/state/braid.sqlite3" \ - -v backups="$root/state/backups" \ - -v soft_ratio="$soft_ratio" \ - -v hard_bytes="$hard_bytes" ' - /^\[runtime\]$/ { section="runtime"; print; next } - /^\[/ && $0 != "[runtime]" { section="other" } - section == "runtime" && /^root = / { printf "root = \"%s\"\n", root; next } - section == "runtime" && /^database = / { printf "database = \"%s\"\n", database; next } - section == "runtime" && /^backups = / { printf "backups = \"%s\"\n", backups; next } - /^github_context_soft_ratio = / { printf "github_context_soft_ratio = %s\n", soft_ratio; next } - /^github_context_hard_bytes = / { printf "github_context_hard_bytes = %s\n", hard_bytes; next } - { print } - ' "$test_config" > "$destination" -} - -start_candidate_runtime() { - local config=$1 - BRAID_WEBHOOK_SECRET="$BRAID_WEBHOOK_SECRET" "$binary" serve \ - --config "$config" >>"$runtime_log" 2>&1 & - runtime_pid=$! - for _ in $(seq 1 "${BRAID_TEST_WAIT_SECONDS:-120}"); do - if curl -fsS "$health_url" 2>/dev/null | \ - jq -e '.ready == true and .provider == "connected"' >/dev/null; then - return 0 - fi - kill -0 "$runtime_pid" 2>/dev/null || fail "Braid exited during startup" - sleep 1 - done - fail "Braid did not become ready" -} - -note "activating one baseline Issue Agent session" -activation_comment="$(gh api --method POST "repos/$repository/issues/$fixture_issue/comments" \ - -f body="@braid Read the current Issue design and publish one concise attributed comment containing $baseline_marker." --jq '.id')" -for _ in $(seq 1 180); do - has_reaction "$activation_comment" +1 && \ - [[ "$(agent_marker_count "$baseline_marker")" -eq 1 ]] && break - sleep 2 -done -has_reaction "$activation_comment" +1 || fail "baseline activation did not complete" -# GitHub's comments-list read can briefly lag the reactions read right after -# a turn terminal; give the final marker assertion a short settle window. -for _ in $(seq 1 15); do - [[ "$(agent_marker_count "$baseline_marker")" -eq 1 ]] && break - sleep 2 -done -[[ "$(agent_marker_count "$baseline_marker")" -eq 1 ]] || fail "baseline Agent marker is absent" - -for _ in $(seq 1 90); do - status_payload="$($binary status --config "$test_config" --json)" - if jq -e --argjson number "$fixture_issue" ' - any(.transport.agent_groups[]; - .work_item_kind == "issue" and .work_item_number == $number and - .session_lifecycle == "idle" and .active_turn_id == null) - ' >/dev/null <<<"$status_payload"; then - break - fi - sleep 1 -done -jq -e --argjson number "$fixture_issue" ' - any(.transport.agent_groups[]; - .work_item_kind == "issue" and .work_item_number == $number and - .session_lifecycle == "idle" and .active_turn_id == null) -' >/dev/null <<<"$status_payload" || fail "baseline turn did not converge to idle" -baseline_session="$(jq -er --argjson number "$fixture_issue" ' - [.transport.agent_groups[] | select( - .work_item_kind == "issue" and .work_item_number == $number and - .session_lifecycle == "idle")][0].provider_session_id -' <<<"$status_payload")" -baseline_agent_comments="$(gh api "repos/$repository/issues/$fixture_issue/comments" | \ - jq --arg actor "$app_actor" '[.[] | select(.user.login == $actor and (.body | startswith("> **Braid Agent")))] | length')" - -note "editing idle Issue Context: replace session without starting a turn" -gh issue edit "$fixture_issue" --repo "$repository" --body "Idle replacement design: $idle_marker" >/dev/null -for _ in $(seq 1 "${BRAID_TEST_WAIT_SECONDS:-120}"); do - status_payload="$($binary status --config "$test_config" --json)" - if jq -e --argjson number "$fixture_issue" ' - any(.transport.context_resets[]; - .work_item_number == $number and .lifecycle == "applied" and - .continuation == false and .context_revision_before != .context_revision_after) - ' >/dev/null <<<"$status_payload"; then - break - fi - sleep 1 -done -jq -e --argjson number "$fixture_issue" ' - any(.transport.context_resets[]; - .work_item_number == $number and .lifecycle == "applied" and - .continuation == false and .context_revision_before != .context_revision_after) -' >/dev/null <<<"$status_payload" || fail "idle Hard Invalidation did not apply" -idle_session="$(jq -er --argjson number "$fixture_issue" ' - [.transport.agent_groups[] | select( - .work_item_kind == "issue" and .work_item_number == $number and - .session_lifecycle == "idle")][-1].provider_session_id -' <<<"$status_payload")" -[[ "$idle_session" != "$baseline_session" ]] || fail "idle invalidation reused the stale provider session" -sleep 5 -current_agent_comments="$(gh api "repos/$repository/issues/$fixture_issue/comments" | \ - jq --arg actor "$app_actor" '[.[] | select(.user.login == $actor and (.body | startswith("> **Braid Agent")))] | length')" -[[ "$current_agent_comments" -eq "$baseline_agent_comments" ]] || \ - fail "idle invalidation fabricated a turn" - -note "editing Issue Context during a turn: fence, interrupt, replace, continue" -active_comment="$(gh api --method POST "repos/$repository/issues/$fixture_issue/comments" \ - -f body="@braid Please review whether the current Issue description is internally coherent and publish one concise attributed assessment that names its current BRAID_* design marker." --jq '.id')" -for _ in $(seq 1 90); do - has_reaction "$active_comment" rocket && break - sleep 1 -done -has_reaction "$active_comment" rocket || fail "active invalidation fixture was not accepted" -gh issue edit "$fixture_issue" --repo "$repository" --body "Active replacement design: $active_marker" >/dev/null - -for _ in $(seq 1 240); do - status_payload="$($binary status --config "$test_config" --json)" - active_reset_count="$(jq --argjson number "$fixture_issue" \ - '[.transport.context_resets[] | select(.work_item_number == $number and .lifecycle == "applied" and .continuation == true)] | length' \ - <<<"$status_payload")" - if [[ "$active_reset_count" -eq 1 ]] && [[ "$(agent_marker_count "$active_marker")" -eq 1 ]]; then - break - fi - sleep 2 -done -[[ "${active_reset_count:-0}" -eq 1 ]] || fail "active Hard Invalidation did not apply exactly once" -[[ "$(agent_marker_count "$active_marker")" -eq 1 ]] || \ - fail "continuation did not use the replacement Context" -for _ in $(seq 1 30); do - has_reaction "$active_comment" rocket || break - sleep 1 -done -has_reaction "$active_comment" rocket && fail "superseded turn retained rocket" -has_reaction "$active_comment" +1 && fail "superseded turn was reported successful" -has_reaction "$active_comment" confused && fail "superseded turn was reported failed" - -for _ in $(seq 1 90); do - status_payload="$($binary status --config "$test_config" --json)" - if jq -e --argjson number "$fixture_issue" ' - any(.transport.agent_groups[]; - .work_item_kind == "issue" and .work_item_number == $number and - .session_lifecycle == "idle" and .active_turn_id == null) - ' >/dev/null <<<"$status_payload"; then - break - fi - sleep 1 -done -jq -e --argjson number "$fixture_issue" ' - any(.transport.agent_groups[]; - .work_item_kind == "issue" and .work_item_number == $number and - .session_lifecycle == "idle" and .active_turn_id == null) -' >/dev/null <<<"$status_payload" || fail "replacement continuation did not converge to idle" - -active_session="$(jq -er --argjson number "$fixture_issue" ' - [.transport.agent_groups[] | select( - .work_item_kind == "issue" and .work_item_number == $number and - .session_lifecycle == "idle")][-1].provider_session_id -' <<<"$status_payload")" -[[ "$active_session" != "$idle_session" ]] || fail "active invalidation reused the stale session" -distinct_sessions="$(jq --argjson number "$fixture_issue" ' - [.transport.agent_groups[] | select(.work_item_number == $number) | .provider_session_id] | - unique | length -' <<<"$status_payload")" -[[ "$distinct_sessions" -eq 3 ]] || fail "expected exactly three physical sessions, got $distinct_sessions" - -note "minimizing a visible comment: reconcile, replace idle Context, start no turn" -comments_before_minimize="$(gh api "repos/$repository/issues/$fixture_issue/comments" | \ - jq --arg actor "$app_actor" '[.[] | select(.user.login == $actor and (.body | startswith("> **Braid Agent")))] | length')" -gh api graphql \ - -f query='mutation($id:ID!){minimizeComment(input:{subjectId:$id,classifier:OUTDATED}){minimizedComment{isMinimized minimizedReason}}}' \ - -f id="$restored_comment_node_id" | jq -e '.data.minimizeComment.minimizedComment.isMinimized == true' >/dev/null -for _ in $(seq 1 180); do - status_payload="$($binary status --config "$test_config" --json)" - if jq -e --argjson number "$fixture_issue" --arg old "$active_session" ' - any(.transport.context_resets[]; - .work_item_number == $number and .old_provider_session_id == $old and - .lifecycle == "applied" and .continuation == false and - .context_revision_before != .context_revision_after) - ' >/dev/null <<<"$status_payload"; then - break - fi - sleep 1 -done -jq -e --argjson number "$fixture_issue" --arg old "$active_session" ' - any(.transport.context_resets[]; - .work_item_number == $number and .old_provider_session_id == $old and - .lifecycle == "applied" and .continuation == false and - .context_revision_before != .context_revision_after) -' >/dev/null <<<"$status_payload" || fail "minimized comment did not replace idle Context" -minimized_session="$(jq -er --argjson number "$fixture_issue" ' - [.transport.agent_groups[] | select( - .work_item_kind == "issue" and .work_item_number == $number and - .session_lifecycle == "idle")][-1].provider_session_id -' <<<"$status_payload")" -[[ "$minimized_session" != "$active_session" ]] || fail "minimized comment reused stale Context" -minimized_context="$($binary context issue "$repository#$fixture_issue" --config "$test_config")" -grep -q 'State: minimized (outdated)' <<<"$minimized_context" || \ - fail "minimized comment metadata is absent from current Context" -grep -q "$restored_marker" <<<"$minimized_context" && \ - fail "minimized comment body remained in current Context" -sleep 5 -comments_after_minimize="$(gh api "repos/$repository/issues/$fixture_issue/comments" | \ - jq --arg actor "$app_actor" '[.[] | select(.user.login == $actor and (.body | startswith("> **Braid Agent")))] | length')" -[[ "$comments_after_minimize" -eq "$comments_before_minimize" ]] || \ - fail "minimize Hard Invalidation fabricated a turn" - -note "unminimizing the comment: restore body and release one ordinary Wake" -gh api graphql \ - -f query='mutation($id:ID!){unminimizeComment(input:{subjectId:$id}){unminimizedComment{isMinimized}}}' \ - -f id="$restored_comment_node_id" | jq -e '.data.unminimizeComment.unminimizedComment.isMinimized == false' >/dev/null -for _ in $(seq 1 240); do - status_payload="$($binary status --config "$test_config" --json)" - if [[ "$(agent_marker_count "$restored_marker")" -eq 1 ]] && \ - jq -e --argjson number "$fixture_issue" ' - any(.transport.agent_groups[]; - .work_item_number == $number and .session_lifecycle == "idle" and - .active_turn_id == null) - ' >/dev/null <<<"$status_payload"; then - break - fi - sleep 1 -done -[[ "$(agent_marker_count "$restored_marker")" -eq 1 ]] || \ - fail "unminimize Wake did not expose the restored comment body to the Agent" -restored_session="$(jq -er --argjson number "$fixture_issue" ' - [.transport.agent_groups[] | select( - .work_item_kind == "issue" and .work_item_number == $number and - .session_lifecycle == "idle")][-1].provider_session_id -' <<<"$status_payload")" -[[ "$restored_session" == "$minimized_session" ]] || \ - fail "unminimize Wake unexpectedly replaced the valid provider session" -restored_context="$($binary context issue "$repository#$fixture_issue" --config "$test_config")" -grep -q "$restored_marker" <<<"$restored_context" || \ - fail "unminimized body is absent from current Context" - -note "deleting another visible comment: retain tombstone, replace idle Context" -comments_before_delete="$(gh api "repos/$repository/issues/$fixture_issue/comments" | \ - jq --arg actor "$app_actor" '[.[] | select(.user.login == $actor and (.body | startswith("> **Braid Agent")))] | length')" -gh api --method DELETE "repos/$repository/issues/comments/$deleted_comment_id" >/dev/null -for _ in $(seq 1 150); do - status_payload="$($binary status --config "$test_config" --json)" - if jq -e --argjson number "$fixture_issue" --arg old "$restored_session" ' - any(.transport.context_resets[]; - .work_item_number == $number and .old_provider_session_id == $old and - .lifecycle == "applied" and .continuation == false and - .context_revision_before != .context_revision_after) - ' >/dev/null <<<"$status_payload"; then - break - fi - sleep 1 -done -jq -e --argjson number "$fixture_issue" --arg old "$restored_session" ' - any(.transport.context_resets[]; - .work_item_number == $number and .old_provider_session_id == $old and - .lifecycle == "applied" and .continuation == false and - .context_revision_before != .context_revision_after) -' >/dev/null <<<"$status_payload" || fail "deleted comment did not replace idle Context" -deleted_session="$(jq -er --argjson number "$fixture_issue" ' - [.transport.agent_groups[] | select( - .work_item_kind == "issue" and .work_item_number == $number and - .session_lifecycle == "idle")][-1].provider_session_id -' <<<"$status_payload")" -[[ "$deleted_session" != "$restored_session" ]] || fail "deleted comment reused stale Context" -deleted_context="$($binary context issue "$repository#$fixture_issue" --config "$test_config")" -grep -q 'State: deleted' <<<"$deleted_context" || \ - fail "deleted comment tombstone is absent from current Context" -grep -q "$deleted_marker" <<<"$deleted_context" && \ - fail "deleted comment body remained in current Context" -sleep 5 -comments_after_delete="$(gh api "repos/$repository/issues/$fixture_issue/comments" | \ - jq --arg actor "$app_actor" '[.[] | select(.user.login == $actor and (.body | startswith("> **Braid Agent")))] | length')" -[[ "$comments_after_delete" -eq "$comments_before_delete" ]] || \ - fail "delete Hard Invalidation fabricated a turn" - -distinct_sessions="$(jq --argjson number "$fixture_issue" ' - [.transport.agent_groups[] | select(.work_item_number == $number) | .provider_session_id] | - unique | length -' <<<"$status_payload")" -[[ "$distinct_sessions" -eq 5 ]] || fail "expected five physical sessions, got $distinct_sessions" - -note "closing during an active turn: finish current turn, run one finalization, then sleep" -preclose_comment="$(gh api --method POST "repos/$repository/issues/$fixture_issue/comments" \ - -f body="@braid Conduct a careful final design audit before closure and publish one concise attributed comment containing $preclose_marker." --jq '.id')" -for _ in $(seq 1 90); do - status_payload="$($binary status --config "$test_config" --json)" - if has_reaction "$preclose_comment" rocket && \ - jq -e --argjson number "$fixture_issue" ' - any(.transport.agent_groups[]; - .work_item_number == $number and .session_lifecycle == "running" and - .active_turn_id != null) - ' >/dev/null <<<"$status_payload"; then - break - fi - sleep 1 -done -has_reaction "$preclose_comment" rocket || fail "pre-close turn was not accepted" -jq -e --argjson number "$fixture_issue" ' - any(.transport.agent_groups[]; - .work_item_number == $number and .session_lifecycle == "running" and - .active_turn_id != null) -' >/dev/null <<<"$status_payload" || fail "Issue was not active before close" -gh issue close "$fixture_issue" --repo "$repository" >/dev/null - -for _ in $(seq 1 240); do - status_payload="$($binary status --config "$test_config" --json)" - if jq -e --argjson number "$fixture_issue" ' - any(.transport.agent_groups[]; - .work_item_number == $number and .assignment_lifecycle == "sleeping" and - .session_lifecycle == "sleeping" and .active_turn_id == null and - .finalization_turns == 1 and .last_finalization_lifecycle == "completed") - ' >/dev/null <<<"$status_payload"; then - break - fi - sleep 2 -done -jq -e --argjson number "$fixture_issue" ' - any(.transport.agent_groups[]; - .work_item_number == $number and .assignment_lifecycle == "sleeping" and - .session_lifecycle == "sleeping" and .active_turn_id == null and - .finalization_turns == 1 and .last_finalization_lifecycle == "completed") -' >/dev/null <<<"$status_payload" || fail "close did not converge through one finalization to sleeping" -has_reaction "$preclose_comment" +1 || fail "close interrupted the already-running turn" -has_reaction "$preclose_comment" confused && fail "close reported the already-running turn failed" -[[ "$(agent_marker_count "$preclose_marker")" -eq 1 ]] || \ - fail "pre-close turn did not publish its expected assessment" - -note "adding work while closed: retain it in GitHub Context without granting another turn" -closed_comment="$(gh api --method POST "repos/$repository/issues/$fixture_issue/comments" \ - -f body="When this Issue reopens, read the complete current Context and publish one concise attributed comment containing $reopened_marker." --jq '.id')" -for _ in $(seq 1 90); do - has_reaction "$closed_comment" eyes && break - sleep 1 -done -has_reaction "$closed_comment" eyes || fail "closed-Issue comment was not durably acknowledged" -sleep 35 -status_payload="$($binary status --config "$test_config" --json)" -jq -e --argjson number "$fixture_issue" ' - any(.transport.agent_groups[]; - .work_item_number == $number and .assignment_lifecycle == "sleeping" and - .finalization_turns == 1) -' >/dev/null <<<"$status_payload" || fail "closed-Issue activity woke the sleeping Agent Group" -[[ "$(agent_marker_count "$reopened_marker")" -eq 0 ]] || \ - fail "closed-Issue activity started a second turn" - -note "reopening: rebuild current Context in a fresh session and release one debounced Wake" -gh issue reopen "$fixture_issue" --repo "$repository" >/dev/null -for _ in $(seq 1 300); do - status_payload="$($binary status --config "$test_config" --json)" - if [[ "$(agent_marker_count "$reopened_marker")" -eq 1 ]] && \ - jq -e --argjson number "$fixture_issue" ' - any(.transport.agent_groups[]; - .work_item_number == $number and .assignment_lifecycle == "active" and - .session_lifecycle == "idle" and .active_turn_id == null and - .finalization_turns == 1) - ' >/dev/null <<<"$status_payload"; then - break - fi - sleep 1 -done -[[ "$(agent_marker_count "$reopened_marker")" -eq 1 ]] || \ - fail "reopen Wake did not use the current GitHub Context" -reopened_session="$(jq -er --argjson number "$fixture_issue" ' - [.transport.agent_groups[] | select( - .work_item_kind == "issue" and .work_item_number == $number and - .session_lifecycle == "idle")][-1].provider_session_id -' <<<"$status_payload")" -[[ "$reopened_session" != "$deleted_session" ]] || fail "reopen reused the sleeping provider session" -distinct_sessions="$(jq --argjson number "$fixture_issue" ' - [.transport.agent_groups[] | select(.work_item_number == $number) | .provider_session_id] | - unique | length -' <<<"$status_payload")" -[[ "$distinct_sessions" -eq 6 ]] || fail "expected six physical sessions after reopen, got $distinct_sessions" - -note "terminating the idle app-server: reconnect and resume the same provider thread" -provider_child_pid="" -for _ in $(seq 1 30); do - provider_child_pid="$(ps -axo pid=,ppid=,command= | awk -v parent="$runtime_pid" ' - # consume all of ps output; an early exit SIGPIPEs ps under pipefail - $2 == parent && index($0, "app-server") && !found { print $1; found = 1 } - ')" - [[ -n "$provider_child_pid" ]] && break - sleep 1 -done -[[ -n "$provider_child_pid" ]] || fail "could not identify the app-server child process" -kill -TERM "$provider_child_pid" -for _ in $(seq 1 "${BRAID_TEST_WAIT_SECONDS:-120}"); do - status_payload="$($binary status --config "$test_config" --json)" - if curl -fsS "$health_url" 2>/dev/null | jq -e '.provider == "connected"' >/dev/null && \ - jq -e --argjson number "$fixture_issue" --arg session "$reopened_session" ' - any(.transport.agent_groups[]; - .work_item_number == $number and .provider_session_id == $session and - .session_lifecycle == "idle" and .provider_resume_count >= 1 and - .last_provider_resume != null) - ' >/dev/null <<<"$status_payload"; then - break - fi - kill -0 "$runtime_pid" 2>/dev/null || fail "Braid exited while reconnecting app-server" - sleep 1 -done -jq -e --argjson number "$fixture_issue" --arg session "$reopened_session" ' - any(.transport.agent_groups[]; - .work_item_number == $number and .provider_session_id == $session and - .session_lifecycle == "idle" and .provider_resume_count >= 1 and - .last_provider_resume != null) -' >/dev/null <<<"$status_payload" || fail "provider thread did not resume in place" - -resume_comment="$(gh api --method POST "repos/$repository/issues/$fixture_issue/comments" \ - -f body="After the debounce window, publish one concise attributed comment containing $resumed_marker." --jq '.id')" -for _ in $(seq 1 240); do - status_payload="$($binary status --config "$test_config" --json)" - if [[ "$(agent_marker_count "$resumed_marker")" -eq 1 ]] && \ - jq -e --argjson number "$fixture_issue" --arg session "$reopened_session" ' - any(.transport.agent_groups[]; - .work_item_number == $number and .provider_session_id == $session and - .session_lifecycle == "idle" and .active_turn_id == null) - ' >/dev/null <<<"$status_payload"; then - break - fi - sleep 1 -done -has_reaction "$resume_comment" eyes || fail "post-resume Wake was not durably acknowledged" -has_reaction "$resume_comment" rocket && fail "ordinary post-resume Wake received request-style reaction" -[[ "$(agent_marker_count "$resumed_marker")" -eq 1 ]] || \ - fail "resumed provider thread did not handle the next debounced Wake" -jq -e --argjson number "$fixture_issue" --arg session "$reopened_session" ' - any(.transport.agent_groups[]; - .work_item_number == $number and .provider_session_id == $session and - .session_lifecycle == "idle" and .active_turn_id == null) -' >/dev/null <<<"$status_payload" || fail "post-resume turn changed the physical provider session" - -app_comments="$(gh api "repos/$repository/issues/$fixture_issue/comments" | \ - jq --arg actor "$app_actor" '[.[] | select(.user.login == $actor - and ((.body | startswith("> **Braid Agent")) | not) - and ((.body | startswith("> **Braid Operational Status")) | not))] | length')" -[[ "$app_comments" -eq 0 ]] || fail "Braid published turn activity during Context replacement" - -stop_process "$runtime_pid" -runtime_pid="" - -note "activating a soft-pressure Context: publish status but supply the complete Context" -readonly soft_root="$temporary_root/soft-runtime" -readonly soft_config="$temporary_root/soft-braid.toml" -write_pressure_config "$soft_config" "$soft_root" 0.10 20000 -$binary migrate apply --config "$soft_config" >/dev/null -start_candidate_runtime "$soft_config" -soft_payload="$(head -c 4096 /dev/zero | tr '\0' S)" -soft_marker="BRAID_SOFT_CONTEXT_$(date -u +%s)" -soft_issue="$(gh api --method POST "repos/$repository/issues" \ - -f title="Braid Slice 4: soft Context pressure" \ - -f body="Soft-pressure design fixture. $soft_payload" --jq '.number')" -soft_activation="$(gh api --method POST "repos/$repository/issues/$soft_issue/comments" \ - -f body="@braid Publish one concise attributed comment containing $soft_marker." --jq '.id')" -for _ in $(seq 1 300); do - soft_status="$($binary status --config "$soft_config" --json)" - if [[ "$(agent_marker_count "$soft_marker" "$soft_issue")" -eq 1 ]] && \ - [[ "$(operational_status_count "$soft_issue" "near the Profile limit")" -eq 1 ]] && \ - jq -e --argjson number "$soft_issue" ' - any(.transport.agent_groups[]; - .work_item_number == $number and .assignment_lifecycle == "active" and - .session_lifecycle == "idle" and .active_turn_id == null and - .context_pressure == "soft" and .context_bytes > 0) - ' >/dev/null <<<"$soft_status"; then - break - fi - sleep 1 -done -has_reaction "$soft_activation" +1 || fail "soft-pressure turn did not complete" -[[ "$(agent_marker_count "$soft_marker" "$soft_issue")" -eq 1 ]] || \ - fail "soft-pressure Agent did not receive the complete Context" -[[ "$(operational_status_count "$soft_issue" "near the Profile limit")" -eq 1 ]] || \ - fail "soft pressure did not converge to one Operational Status Comment" -soft_context_bytes="$(jq -er --argjson number "$soft_issue" ' - [.transport.agent_groups[] | select( - .work_item_number == $number and .context_pressure == "soft")][0].context_bytes -' <<<"$soft_status")" -[[ "$soft_context_bytes" -lt 20000 ]] || fail "soft fixture crossed the hard limit" - -stop_process "$runtime_pid" -runtime_pid="" - -note "activating a hard-pressure Context: block without truncation or a provider session" -readonly hard_root="$temporary_root/hard-runtime" -readonly hard_config="$temporary_root/hard-braid.toml" -write_pressure_config "$hard_config" "$hard_root" 0.80 512 -$binary migrate apply --config "$hard_config" >/dev/null -start_candidate_runtime "$hard_config" -hard_payload="$(head -c 2048 /dev/zero | tr '\0' H)" -hard_marker="BRAID_HARD_CONTEXT_$(date -u +%s)" -hard_issue="$(gh api --method POST "repos/$repository/issues" \ - -f title="Braid Slice 4: hard Context pressure" \ - -f body="Hard-pressure design fixture. $hard_payload" --jq '.number')" -hard_activation="$(gh api --method POST "repos/$repository/issues/$hard_issue/comments" \ - -f body="@braid Do not truncate this Context. If accepted, publish $hard_marker." --jq '.id')" -for _ in $(seq 1 180); do - hard_status="$($binary status --config "$hard_config" --json)" - if has_reaction "$hard_activation" eyes && \ - [[ "$(operational_status_count "$hard_issue" "Context is too large")" -eq 1 ]] && \ - jq -e --argjson number "$hard_issue" ' - any(.transport.agent_groups[]; - .work_item_number == $number and .assignment_lifecycle == "blocked" and - .provider_session_id == null and .session_lifecycle == null and - .context_pressure == "hard" and .context_bytes > 512) - ' >/dev/null <<<"$hard_status"; then - break - fi - sleep 1 -done -has_reaction "$hard_activation" eyes || fail "hard-pressure event was not durably acknowledged" -has_reaction "$hard_activation" rocket && fail "hard-pressure event started a provider turn" -has_reaction "$hard_activation" +1 && fail "hard-pressure event was reported successful" -has_reaction "$hard_activation" confused && fail "hard-pressure event was reported as Agent failure" -[[ "$(agent_marker_count "$hard_marker" "$hard_issue")" -eq 0 ]] || \ - fail "hard-pressure Context reached an Agent" -[[ "$(operational_status_count "$hard_issue" "Context is too large")" -eq 1 ]] || \ - fail "hard pressure did not converge to one Operational Status Comment" -jq -e --argjson number "$hard_issue" ' - any(.transport.agent_groups[]; - .work_item_number == $number and .assignment_lifecycle == "blocked" and - .provider_session_id == null and .context_pressure == "hard" and - .context_bytes > 512) -' >/dev/null <<<"$hard_status" || fail "hard pressure did not remain observable and blocked" - -stop_process "$runtime_pid" -runtime_pid="" -stop_process "$tunnel_pid" -tunnel_pid="" -gh api --method DELETE "repos/$repository/hooks/$repository_hook_id" >/dev/null -repository_hook_id="" - -jq -n \ - --arg repository "$repository" \ - --arg candidate "$candidate_version" \ - --arg candidate_sha256 "$candidate_sha256" \ - --arg baseline_session "$baseline_session" \ - --arg idle_session "$idle_session" \ - --arg active_session "$active_session" \ - --arg minimized_session "$minimized_session" \ - --arg deleted_session "$deleted_session" \ - --arg reopened_session "$reopened_session" \ - --argjson issue "$fixture_issue" \ - --argjson soft_issue "$soft_issue" \ - --argjson hard_issue "$hard_issue" \ - --argjson soft_context_bytes "$soft_context_bytes" \ - '{ - verdict:"PASS", - boundary:"real GitHub -> HTTP/2 Quick Tunnel -> packaged Braid -> real Codex app-server", - repository:$repository, - candidate:$candidate, - candidate_sha256:$candidate_sha256, - fixture_issue:$issue, - pressure_fixtures:{soft_issue:$soft_issue,hard_issue:$hard_issue,soft_context_bytes:$soft_context_bytes}, - sessions:{ - baseline:$baseline_session, - idle_replacement:$idle_session, - active_replacement:$active_session, - minimized_replacement:$minimized_session, - deleted_replacement:$deleted_session, - reopened:$reopened_session - }, - journeys:[ - "idle-hard-invalidation", - "active-hard-invalidation", - "stale-turn-reaction-fence", - "continuation-current-context", - "minimize-reconciliation-reset", - "unminimize-wake", - "delete-tombstone-reset", - "active-close-finalization-sleep", - "closed-activity-no-wake", - "reopen-fresh-context-debounced-wake", - "provider-reconnect-same-thread", - "post-resume-debounced-wake", - "soft-pressure-complete-context", - "hard-pressure-block-no-truncation" - ] - }' diff --git a/scripts/tests/50_issue_to_pr.sh b/scripts/tests/50_issue_to_pr.sh deleted file mode 100755 index 58d901e4..00000000 --- a/scripts/tests/50_issue_to_pr.sh +++ /dev/null @@ -1,757 +0,0 @@ -#!/bin/sh -set -eu - -fail() { - echo "FAIL: $*" >&2 - exit 1 -} - -require_comment_result() { - result=$1 - if ! printf '%s' "$result" | jq -e \ - '.state == "applied" and (.comment | type == "string") and - (.comment | contains("#issuecomment-"))' >/dev/null; then - printf 'Unexpected braid gh comment result:\n%s\n' "$result" >&2 - fail "comment result omitted its semantic GitHub comment reference" - fi -} - -source_config=${BRAID_CONFIG:?BRAID_CONFIG must point to the real acceptance config} -braid=${BRAID_BIN:-braid} -repository=${BRAID_TEST_REPOSITORY:-xiaoland/braid} -issue_profile=${BRAID_TEST_ISSUE_PROFILE:-issue-codex} -keep=${BRAID_TEST_KEEP_FIXTURES:-0} -ingress_address=${BRAID_TEST_INGRESS:-127.0.0.1:18090} -health_address=${BRAID_TEST_HEALTH:-127.0.0.1:18091} -health_url="http://$health_address/healthz" -stamp=$(date -u +%Y%m%dT%H%M%SZ) -issue_number= -restart_issue_number= -pull_number= -head_ref= -merge_base_ref= -runtime_pid= -tunnel_pid= -repository_hook_id= -worktree_path= -temporary_root=$(mktemp -d "${TMPDIR:-/tmp}/braid-slice5.XXXXXX") -runtime_root="$temporary_root/runtime" -source_checkout="$temporary_root/source" -config="$temporary_root/braid.toml" -runtime_log="$temporary_root/runtime.log" -tunnel_log="$temporary_root/tunnel.log" - -latest_pr_group() { - "$braid" status --config "$config" --json | jq -c \ - --argjson number "$pull_number" --arg profile "$pr_profile" \ - '[.transport.agent_groups[]? | select( - .work_item_kind == "pr" and .work_item_number == $number and - .profile_id == $profile)][-1] // empty' -} - -latest_issue_group() { - "$braid" status --config "$config" --json | jq -c \ - --argjson number "$restart_issue_number" --arg profile "$issue_profile" \ - '[.transport.agent_groups[]? | select( - .work_item_kind == "issue" and .work_item_number == $number and - .profile_id == $profile)][-1] // empty' -} - -duplicate_agent_attribution_count() { - gh api "repos/$repository/issues/$pull_number/comments" --paginate | jq \ - --arg prefix "$agent_prefix" \ - '[.[] | select(.body | startswith($prefix + "\n\n" + $prefix))] | length' -} - -review_reaction_exists() { - comment_id=$1 - content=$2 - gh api "repos/$repository/pulls/comments/$comment_id/reactions" \ - --jq "any(.content == \"$content\" and .user.login == \"$app_actor\")" \ - 2>/dev/null | grep -q true -} - -issue_reaction_exists() { - comment_id=$1 - content=$2 - gh api "repos/$repository/issues/comments/$comment_id/reactions" \ - --jq "any(.content == \"$content\" and .user.login == \"$app_actor\")" \ - 2>/dev/null | grep -q true -} - -stop_process() { - pid=$1 - [ -n "$pid" ] || return 0 - kill -0 "$pid" 2>/dev/null || return 0 - kill -INT "$pid" 2>/dev/null || true - for _ in $(seq 1 15); do - kill -0 "$pid" 2>/dev/null || { - wait "$pid" 2>/dev/null || true - return 0 - } - sleep 1 - done - kill -TERM "$pid" 2>/dev/null || true - wait "$pid" 2>/dev/null || true -} - -cleanup() { - status=$? - trap - EXIT HUP INT TERM - stop_process "$runtime_pid" - stop_process "$tunnel_pid" - if [ -n "$repository_hook_id" ]; then - gh api --method DELETE "repos/$repository/hooks/$repository_hook_id" >/dev/null 2>&1 || true - fi - if [ "$keep" = "1" ]; then - echo "keeping Slice 5 fixtures: issue=${issue_number:-none} pr=${pull_number:-none}" >&2 - return - fi - if [ -n "$pull_number" ]; then - gh pr close "$pull_number" --repo "$repository" >/dev/null 2>&1 || true - fi - if [ -n "$head_ref" ]; then - gh api --method DELETE "repos/$repository/git/refs/heads/$head_ref" >/dev/null 2>&1 || true - fi - if [ -n "$merge_base_ref" ]; then - gh api --method DELETE "repos/$repository/git/refs/heads/$merge_base_ref" >/dev/null 2>&1 || true - fi - if [ -n "$issue_number" ]; then - gh issue close "$issue_number" --repo "$repository" --reason "not planned" >/dev/null 2>&1 || true - fi - if [ -n "$restart_issue_number" ]; then - gh issue close "$restart_issue_number" --repo "$repository" --reason "not planned" >/dev/null 2>&1 || true - fi - if [ "$status" -ne 0 ]; then - echo "Slice 5 runtime log follows" >&2 - [ -f "$runtime_log" ] && tail -200 "$runtime_log" >&2 || true - echo "Slice 5 tunnel log follows" >&2 - [ -f "$tunnel_log" ] && tail -100 "$tunnel_log" >&2 || true - fi - rm -rf "$temporary_root" -} -trap cleanup EXIT HUP INT TERM - -command -v "$braid" >/dev/null 2>&1 || [ -x "$braid" ] || fail "Braid binary is unavailable" -command -v gh >/dev/null 2>&1 || fail "gh is unavailable" -command -v jq >/dev/null 2>&1 || fail "jq is unavailable" -command -v curl >/dev/null 2>&1 || fail "curl is unavailable" -command -v git >/dev/null 2>&1 || fail "git is unavailable" -wrangler=${BRAID_TEST_WRANGLER:-$(command -v wrangler || true)} -tunnel_url=${BRAID_TEST_PUBLIC_WEBHOOK_URL:-} -tunnel_url=${tunnel_url%/webhook} -if [ -z "$tunnel_url" ]; then - [ -n "$wrangler" ] && [ -x "$wrangler" ] || fail "set BRAID_TEST_WRANGLER to Wrangler" -fi -[ -n "${BRAID_WEBHOOK_SECRET:-}" ] || fail "BRAID_WEBHOOK_SECRET is required by the runtime" -[ "$source_config" = "${source_config#/}" ] && fail "BRAID_CONFIG must be absolute" -[ -f "$source_config" ] || fail "BRAID_CONFIG does not exist" -braid_path=$(command -v "$braid" 2>/dev/null || printf '%s' "$braid") - -pr_profile=$("$braid" config check --config "$source_config" --json | jq -er .default_pr_profile) -mkdir -p "$runtime_root/state/backups" -runtime_root_real=$(cd "$runtime_root" && pwd -P) -gh repo clone "$repository" "$source_checkout" -- --quiet -awk \ - -v root="$runtime_root" \ - -v database="$runtime_root/state/braid.sqlite3" \ - -v backups="$runtime_root/state/backups" \ - -v ingress="$ingress_address" \ - -v health="$health_address" \ - -v pr_profile="$pr_profile" \ - -v source="$source_checkout" ' - /^github_actor_node_id = / { next } - /^\[runtime\]$/ { section="runtime"; print; next } - /^\[server\]$/ { section="server"; print; next } - /^\[scheduler\]$/ { section="scheduler"; print; next } - /^\[\[profiles\]\]$/ { section="profile"; profile=""; print; next } - /^\[/ && $0 != "[runtime]" && $0 != "[server]" && $0 != "[scheduler]" && $0 != "[[profiles]]" { section="other" } - section == "runtime" && /^root = / { printf "root = \"%s\"\n", root; next } - section == "runtime" && /^database = / { printf "database = \"%s\"\n", database; next } - section == "runtime" && /^backups = / { printf "backups = \"%s\"\n", backups; next } - section == "runtime" && /^auto_migrate = / { print "auto_migrate = false"; next } - section == "server" && /^ingress = / { printf "ingress = \"%s\"\n", ingress; next } - section == "server" && /^health = / { printf "health = \"%s\"\n", health; next } - section == "scheduler" && /^quiet_seconds = / { print "quiet_seconds = 5"; next } - section == "scheduler" && /^reconciliation_seconds = / { print "reconciliation_seconds = 60"; next } - section == "profile" && /^id = / { - profile=$0 - gsub(/^id = \"|\"$/, "", profile) - print - next - } - section == "profile" && profile == pr_profile && /^workspace = / { - printf "workspace = \"%s\"\n", source - next - } - { print } -' "$source_config" > "$config" - -"$braid" migrate apply --config "$config" >/dev/null -identity=$("$braid" github probe --config "$config" --repository "$repository" --json) -app_actor=$(printf '%s' "$identity" | jq -er .actor_login) -jq -e '.permissions.issues == "write" and .permissions.pull_requests == "write" and .permissions.contents == "write"' \ - >/dev/null <"$runtime_log" 2>&1 & - runtime_pid=$! - for _ in $(seq 1 "${BRAID_TEST_WAIT_SECONDS:-120}"); do - if curl -fsS "$health_url" 2>/dev/null | \ - jq -e '.ready == true and .provider == "connected"' >/dev/null; then - return 0 - fi - kill -0 "$runtime_pid" 2>/dev/null || fail "Braid exited during PR Agent startup" - sleep 1 - done - fail "Braid did not become provider-ready" -} - -if [ -n "$tunnel_url" ]; then - echo "Using external public webhook URL" - tunnel_pid="" -else - TUNNEL_TRANSPORT_PROTOCOL=http2 "$wrangler" tunnel quick-start \ - "http://$ingress_address" >"$tunnel_log" 2>&1 & - tunnel_pid=$! - tunnel_url="" - for _ in $(seq 1 90); do - tunnel_url=$(grep -Eo 'https://[a-z0-9-]+\.(trycloudflare\.com|loca\.lt)' "$tunnel_log" | tail -1 || true) - [ -n "$tunnel_url" ] && break - kill -0 "$tunnel_pid" 2>/dev/null || fail "Quick Tunnel exited before publishing a URL" - sleep 1 - done - [ -n "${tunnel_url:-}" ] || fail "Quick Tunnel did not publish a URL" -fi - -start_runtime - -public_probe_ready=0 -for _ in $(seq 1 18); do - if BRAID_WEBHOOK_SECRET="$BRAID_WEBHOOK_SECRET" "$braid" tunnel probe \ - --config "$config" --url "$tunnel_url/webhook" >/dev/null 2>&1; then - public_probe_ready=1 - break - fi - sleep 5 -done -[ "$public_probe_ready" -eq 1 ] || fail "public signed webhook probe failed" - -repository_hook_id=$(gh api --method POST "repos/$repository/hooks" \ - -f name=web \ - -F active=true \ - -f 'events[]=issues' \ - -f 'events[]=issue_comment' \ - -f 'events[]=pull_request' \ - -f 'events[]=pull_request_review' \ - -f 'events[]=pull_request_review_comment' \ - -f 'events[]=pull_request_review_thread' \ - -f "config[url]=$tunnel_url/webhook" \ - -f 'config[content_type]=json' \ - -f "config[secret]=$BRAID_WEBHOOK_SECRET" \ - --jq .id) - -fixture_path="acceptance/slice5-$stamp.md" -fixture_marker="Braid Slice 5 PR Agent $stamp" - -issue_url=$(gh issue create \ - --repo "$repository" \ - --title "Braid Slice 5 write receipt $stamp" \ - --body "Disposable real-object fixture. Implement by creating \`$fixture_path\` containing exactly \`$fixture_marker\`, then commit, push the PR branch, verify the diff, and publish one concise PR comment.") -issue_number=${issue_url##*/} - -comment_json=$("$braid" gh comment create "$repository#$issue_number" \ - --config "$config" \ - --profile "$issue_profile" \ - --request-id "slice5-$stamp-implementation-request" \ - --body "Implementation Request: implement the exact bounded file change in this Issue description, verify it, push it, and report concisely on the Draft PR." \ - --json) -require_comment_result "$comment_json" -comment_id=$(printf '%s' "$comment_json" | jq -r '.comment | split("#issuecomment-")[1]') -profile_display=$("$braid" profile inspect --config "$config" --profile "$issue_profile" --json | jq -r .display_name) -[ -n "$comment_id" ] && [ "$comment_id" != null ] || fail "comment result omitted its GitHub comment reference" -body=$(gh api "repos/$repository/issues/comments/$comment_id" --jq .body) -first=$(printf '%s\n' "$body" | sed -n '1p') -second=$(printf '%s\n' "$body" | sed -n '2p') -[ "$first" = "> **Braid Agent · $profile_display**" ] || fail "Braid attribution display name drifted" -[ "$second" = '> Issue Agent' ] || fail "Braid attribution role drifted" -comment_retry_json=$("$braid" gh comment create "$repository#$issue_number" \ - --config "$config" \ - --profile "$issue_profile" \ - --request-id "slice5-$stamp-implementation-request" \ - --body "Implementation Request: implement the exact bounded file change in this Issue description, verify it, push it, and report concisely on the Draft PR." \ - --json) -require_comment_result "$comment_retry_json" -retry_comment_id=$(printf '%s' "$comment_retry_json" | jq -r '.comment | split("#issuecomment-")[1]') -[ "$retry_comment_id" = "$comment_id" ] || fail "idempotent comment retry created a different comment" -printf '%s' "$comment_retry_json" | jq -e \ - '(has("intent_id") | not) and (has("request_digest") | not) and (has("remote_node_id") | not) and (has("write") | not)' \ - >/dev/null || fail "comment result leaked internal identifiers" - -head_ref="braid/implementation-request-$comment_id" -"$braid" gh pr ensure --comment "$comment_id" --config "$config" --json \ - >"$temporary_root/ensure-a.json" 2>"$temporary_root/ensure-a.err" & -first_pid=$! -"$braid" gh pr ensure --comment "$comment_id" --config "$config" --json \ - >"$temporary_root/ensure-b.json" 2>"$temporary_root/ensure-b.err" & -second_pid=$! -wait "$first_pid" || { - cat "$temporary_root/ensure-a.err" >&2 - fail "first concurrent pr ensure failed" -} -wait "$second_pid" || { - cat "$temporary_root/ensure-b.err" >&2 - fail "second concurrent pr ensure failed" -} - -first_pr=$(jq -r '.pull_request | split("#")[1]' "$temporary_root/ensure-a.json") -second_pr=$(jq -r '.pull_request | split("#")[1]' "$temporary_root/ensure-b.json") -[ "$first_pr" = "$second_pr" ] || fail "concurrent pr ensure calls returned different PRs" -pull_number=$first_pr -[ "$pull_number" != null ] || fail "pr ensure result omitted its GitHub PR reference" -jq -e \ - '(has("write") | not) and (has("intent_id") | not) and (has("request_digest") | not) and (has("pull_request_node_id") | not)' \ - "$temporary_root/ensure-a.json" >/dev/null || fail "PR result leaked internal identifiers" - -pr=$(gh pr view "$pull_number" --repo "$repository" --json isDraft,state,headRefName,baseRefName,url) -printf '%s' "$pr" | jq -e \ - --arg head "$head_ref" '.isDraft == true and .state == "OPEN" and .headRefName == $head' \ - >/dev/null || fail "ensured PR is not the expected open Draft/head" -count=$(gh pr list --repo "$repository" --state open --head "$head_ref" --json number --jq length) -[ "$count" = "1" ] || fail "expected exactly one open PR for deterministic head; found $count" - -associated=$(gh api graphql \ - -f query='query($owner:String!,$name:String!,$number:Int!){repository(owner:$owner,name:$name){pullRequest(number:$number){closingIssuesReferences(first:100){nodes{number repository{nameWithOwner}}}}}}' \ - -f owner="${repository%%/*}" \ - -f name="${repository#*/}" \ - -F number="$pull_number" \ - --jq ".data.repository.pullRequest.closingIssuesReferences.nodes | any(.number == $issue_number and .repository.nameWithOwner == \"$repository\")") -[ "$associated" = true ] || fail "PR lacks the native association to the Implementation Request Issue" - -head_sha=$(gh api "repos/$repository/git/ref/heads/$head_ref" --jq .object.sha) -commit=$(gh api "repos/$repository/git/commits/$head_sha") -parent_sha=$(printf '%s' "$commit" | jq -r '.parents[0].sha') -tree_sha=$(printf '%s' "$commit" | jq -r '.tree.sha') -parent_tree=$(gh api "repos/$repository/git/commits/$parent_sha" --jq .tree.sha) -[ "$tree_sha" = "$parent_tree" ] || fail "bootstrap commit changed the repository tree" -printf '%s' "$commit" | jq -e --arg id "$comment_id" \ - '.message == ("chore(braid): initialize implementation request " + $id)' \ - >/dev/null || fail "bootstrap commit message omitted the Implementation Request" - -for _ in $(seq 1 240); do - group=$("$braid" status --config "$config" --json | jq -c \ - --argjson number "$pull_number" --arg profile "$pr_profile" \ - '.transport.agent_groups[]? | select(.work_item_kind == "pr" and .work_item_number == $number and .profile_id == $profile)' | tail -1) - if [ -n "$group" ] && printf '%s' "$group" | jq -e \ - '.assignment_lifecycle == "active" and .provider_session_id != null and .worktree_lifecycle == "active" and .worktree_path != null' >/dev/null; then - worktree_path=$(printf '%s' "$group" | jq -r .worktree_path) - break - fi - kill -0 "$runtime_pid" 2>/dev/null || fail "Braid exited before PR Agent materialization" - sleep 1 -done -[ -n "$worktree_path" ] || fail "PR Agent/worktree did not materialize" -case "$worktree_path" in - "$runtime_root_real"/worktrees/*) ;; - *) fail "PR Agent worktree escaped the isolated runtime root" ;; -esac -[ -d "$worktree_path" ] || fail "recorded PR Agent worktree does not exist" - -for _ in $(seq 1 600); do - if gh api "repos/$repository/contents/$fixture_path?ref=$head_ref" \ - --jq .content >"$temporary_root/content.b64" 2>/dev/null; then - tr -d '\n' <"$temporary_root/content.b64" | base64 --decode >"$temporary_root/content.txt" - [ "$(cat "$temporary_root/content.txt")" = "$fixture_marker" ] && break - fi - kill -0 "$runtime_pid" 2>/dev/null || fail "Braid exited before the implementation diff" - sleep 1 -done -[ -f "$temporary_root/content.txt" ] && \ - [ "$(cat "$temporary_root/content.txt")" = "$fixture_marker" ] || \ - fail "PR Agent did not push the exact requested file" - -for _ in $(seq 1 60); do - files=$(gh api "repos/$repository/pulls/$pull_number/files" --jq 'map(.filename)') - if printf '%s' "$files" | jq -e --arg path "$fixture_path" \ - 'length == 1 and .[0] == $path' >/dev/null; then - break - fi - sleep 1 -done -printf '%s' "$files" | jq -e --arg path "$fixture_path" \ - 'length == 1 and .[0] == $path' >/dev/null || fail "PR diff escaped the bounded fixture file" -pr_display=$("$braid" profile inspect --config "$config" --profile "$pr_profile" --json | jq -r .display_name) -agent_prefix=$(printf '> **Braid Agent · %s**\n> PR Implementation Agent' "$pr_display") -gh api "repos/$repository/issues/$pull_number/comments" --paginate --jq '.[].body' | \ - grep -q '# Braid Event References' && fail "Braid mirrored internal Event References to GitHub" - -initial_group=$(latest_pr_group) -initial_session=$(printf '%s' "$initial_group" | jq -er .provider_session_id) -initial_worktree=$(printf '%s' "$initial_group" | jq -er .worktree_path) - -review_hidden_marker="BRAID_SLICE5_FOLDED_REVIEW_$stamp" -head_sha=$(gh pr view "$pull_number" --repo "$repository" --json headRefOid --jq .headRefOid) -review_comment=$(gh api --method POST "repos/$repository/pulls/$pull_number/comments" \ - -f body="Review acceptance $review_hidden_marker: inspect this thread and decide whether any response is useful. Do not modify the implementation." \ - -f commit_id="$head_sha" \ - -f path="$fixture_path" \ - -F line=1 \ - -f side=RIGHT) -review_comment_id=$(printf '%s' "$review_comment" | jq -er .id) -review_comment_node_id=$(printf '%s' "$review_comment" | jq -er .node_id) -review_baseline_turns=$(latest_pr_group | jq -er .turn_count) - -for _ in $(seq 1 240); do - review_turns=$(latest_pr_group | jq -er .turn_count) - if review_reaction_exists "$review_comment_id" eyes && \ - [ "$review_turns" -gt "$review_baseline_turns" ]; then - break - fi - kill -0 "$runtime_pid" 2>/dev/null || fail "Braid exited while handling PR review feedback" - sleep 1 -done -review_reaction_exists "$review_comment_id" eyes || fail "PR review comment was not durably acknowledged" -[ "$review_turns" -gt "$review_baseline_turns" ] || \ - fail "PR review comment did not Wake the PR Agent" -review_group=$(latest_pr_group) -review_pre_reset_session=$(printf '%s' "$review_group" | jq -er .provider_session_id) - -review_thread_id=$(gh api graphql \ - -f query='query($owner:String!,$name:String!,$number:Int!){repository(owner:$owner,name:$name){pullRequest(number:$number){reviewThreads(first:100){nodes{id isResolved comments(first:100){nodes{id}}}}}}}' \ - -f owner="${repository%%/*}" \ - -f name="${repository#*/}" \ - -F number="$pull_number" \ - --jq ".data.repository.pullRequest.reviewThreads.nodes[] | select(any(.comments.nodes[]; .id == \"$review_comment_node_id\")) | .id") -[ -n "$review_thread_id" ] || fail "could not resolve the created review comment to a review thread" - -gh api graphql \ - -f query='mutation($thread:ID!){resolveReviewThread(input:{threadId:$thread}){thread{id isResolved}}}' \ - -f thread="$review_thread_id" | \ - jq -e '.data.resolveReviewThread.thread.isResolved == true' >/dev/null || \ - fail "GitHub did not resolve the review thread" - -review_reset_session= -stable_review_session= -stable_review_observations=0 -for _ in $(seq 1 300); do - review_group=$(latest_pr_group) - if printf '%s' "$review_group" | jq -e \ - --arg old "$review_pre_reset_session" ' - .provider_session_id != $old and .session_lifecycle == "idle" and - .active_turn_id == null' >/dev/null; then - candidate_session=$(printf '%s' "$review_group" | jq -er .provider_session_id) - if [ "$candidate_session" = "$stable_review_session" ]; then - stable_review_observations=$((stable_review_observations + 1)) - else - stable_review_session=$candidate_session - stable_review_observations=1 - fi - if [ "$stable_review_observations" -ge 5 ]; then - review_reset_session=$candidate_session - break - fi - else - stable_review_session= - stable_review_observations=0 - fi - kill -0 "$runtime_pid" 2>/dev/null || fail "Braid exited before review replacement converged" - sleep 1 -done -[ -n "$review_reset_session" ] || fail "resolved review thread did not converge to current PR Context" -[ "$(printf '%s' "$review_group" | jq -r .worktree_path)" = "$initial_worktree" ] || \ - fail "review Context replacement changed the dedicated worktree" -"$braid" context pr "$repository#$pull_number" --config "$config" >"$temporary_root/review-context.md" -grep -q "Review thread at $fixture_path:1" "$temporary_root/review-context.md" || \ - fail "resolved review thread location is absent from current PR Context" -grep -q 'State: resolved' "$temporary_root/review-context.md" || \ - fail "review thread did not render its resolved lifecycle" -grep -q "$review_hidden_marker" "$temporary_root/review-context.md" && \ - fail "resolved review-thread body remained in current PR Context" - -cross_marker="BRAID_SLICE5_DESIGN_$stamp" -active_marker="BRAID_SLICE5_ACTIVE_$stamp" -active_comment=$(gh api --method POST "repos/$repository/issues/$pull_number/comments" \ - -f body="@braid Acceptance: first run \`sleep 30\` in the dedicated worktree so this turn remains active, then publish one concise attributed PR comment containing $active_marker." --jq .id) - -active_session= -for _ in $(seq 1 "${BRAID_TEST_WAIT_SECONDS:-120}"); do - active_group=$(latest_pr_group) - if [ -n "$active_group" ] && printf '%s' "$active_group" | \ - jq -e '.session_lifecycle == "running" and .active_turn_id != null' >/dev/null; then - active_session=$(printf '%s' "$active_group" | jq -er .provider_session_id) - break - fi - kill -0 "$runtime_pid" 2>/dev/null || fail "Braid exited before the active PR turn" - sleep 1 -done -[ -n "$active_session" ] || fail "trusted PR mention did not start an observable active turn" - -updated_issue_body="Disposable real-object fixture. The implementation remains the exact file requested below. Current accepted design marker: $cross_marker. Implement by creating \`$fixture_path\` containing exactly \`$fixture_marker\`, then commit, push the PR branch, verify the diff, and publish concise PR comments." -gh issue edit "$issue_number" --repo "$repository" --body "$updated_issue_body" >/dev/null -edit_epoch=$(date +%s) -sleep 3 -status_payload=$("$braid" status --config "$config" --json) -early_cross_reset=$(printf '%s' "$status_payload" | jq \ - --argjson number "$pull_number" --arg old "$active_session" ' - [.transport.context_resets[]? | select( - .work_item_kind == "pr" and .work_item_number == $number and - .old_provider_session_id == $old and .lifecycle == "applied")] | length') -[ "$early_cross_reset" -eq 0 ] || fail "Associated-Issue invalidation bypassed the configured debounce window" - -cross_reset_session= -cross_reset_continuation= -for _ in $(seq 1 240); do - status_payload=$("$braid" status --config "$config" --json) - cross_reset=$(printf '%s' "$status_payload" | jq -c \ - --argjson number "$pull_number" --arg old "$active_session" ' - [.transport.context_resets[]? | select( - .work_item_kind == "pr" and .work_item_number == $number and - .old_provider_session_id == $old and .lifecycle == "applied")][-1] // empty') - if [ -n "$cross_reset" ]; then - cross_reset_session=$(printf '%s' "$cross_reset" | jq -er .new_provider_session_id) - cross_reset_continuation=$(printf '%s' "$cross_reset" | jq -er .continuation) - break - fi - kill -0 "$runtime_pid" 2>/dev/null || fail "Braid exited during cross-surface Context replacement" - sleep 1 -done -[ -n "$cross_reset_session" ] || fail "Associated-Issue description edit did not replace PR Context" -[ "$cross_reset_continuation" = true ] || fail "active cross-surface invalidation did not schedule one continuation" -elapsed=$(( $(date +%s) - edit_epoch )) -[ "$elapsed" -ge 5 ] || fail "cross-surface invalidation completed before the debounce window" - -for _ in $(seq 1 300); do - cross_group=$(latest_pr_group) - if [ -n "$cross_group" ] && printf '%s' "$cross_group" | jq -e \ - --arg session "$cross_reset_session" ' - .provider_session_id == $session and .session_lifecycle == "idle" and - .active_turn_id == null' >/dev/null; then - break - fi - kill -0 "$runtime_pid" 2>/dev/null || fail "Braid exited before the replacement PR turn converged" - sleep 1 -done -if [ "$(printf '%s' "$cross_group" | jq -r .provider_session_id)" != "$cross_reset_session" ]; then - echo "expected cross-surface session: $cross_reset_session" >&2 - printf '%s' "$status_payload" | jq \ - --argjson number "$pull_number" --arg profile "$pr_profile" \ - '{groups:[.transport.agent_groups[]? | select( - .work_item_kind == "pr" and .work_item_number == $number and - .profile_id == $profile)], resets:[.transport.context_resets[]? | select( - .work_item_kind == "pr" and .work_item_number == $number and - .profile_id == $profile)]}' >&2 - fail "PR Agent did not adopt the cross-surface replacement session" -fi -[ "$(printf '%s' "$cross_group" | jq -r .worktree_path)" = "$initial_worktree" ] || \ - fail "cross-surface Context replacement changed the dedicated worktree" -"$braid" context pr "$repository#$pull_number" --config "$config" >"$temporary_root/cross-context.md" -grep -q "$cross_marker" "$temporary_root/cross-context.md" || \ - fail "replacement PR Context omitted the edited Associated-Issue description" - -active_reactions=$(gh api "repos/$repository/issues/comments/$active_comment/reactions" --jq 'map(.content)') -printf '%s' "$active_reactions" | jq -e 'all(.[]; . != "rocket" and . != "+1" and . != "confused")' \ - >/dev/null || fail "superseded trusted turn retained a terminal lifecycle reaction" -gh api "repos/$repository/issues/$pull_number/comments" --paginate --jq '.[].body' | \ - grep -q '# Braid Event References' && fail "Braid mirrored Event References after replacement" -[ "$(duplicate_agent_attribution_count)" -eq 0 ] || \ - fail "an Agent comment contains duplicate generated attribution" - -direct_external_marker="BRAID_SLICE5_DIRECT_EXTERNAL_$stamp" -direct_baseline_turns=$(latest_pr_group | jq -er .turn_count) -direct_external_comment=$(gh api --method POST "repos/$repository/issues/$pull_number/comments" \ - -f body="Direct gh acceptance $direct_external_marker: inspect this external comment and decide whether any response is useful. Do not modify the implementation." \ - --jq .id) -for _ in $(seq 1 240); do - direct_group=$(latest_pr_group) - direct_turns=$(printf '%s' "$direct_group" | jq -er .turn_count) - if issue_reaction_exists "$direct_external_comment" eyes && \ - [ "$direct_turns" -gt "$direct_baseline_turns" ]; then - break - fi - kill -0 "$runtime_pid" 2>/dev/null || fail "Braid exited during unconfigured direct-gh origin" - sleep 1 -done -issue_reaction_exists "$direct_external_comment" eyes || \ - fail "unconfigured direct gh comment was not treated as external" -[ "$direct_turns" -gt "$direct_baseline_turns" ] || \ - fail "unconfigured direct gh comment did not create a turn" - -preclose_group=$(latest_pr_group) -preclose_session=$(printf '%s' "$preclose_group" | jq -er .provider_session_id) -preclose_turns=$(printf '%s' "$preclose_group" | jq -er .turn_count) -gh pr close "$pull_number" --repo "$repository" >/dev/null -for _ in $(seq 1 300); do - closed_group=$(latest_pr_group) - if printf '%s' "$closed_group" | jq -e \ - '.assignment_lifecycle == "sleeping" and .session_lifecycle == "sleeping" and - .worktree_lifecycle == "sleeping" and .finalization_turns == 1 and - .last_finalization_lifecycle == "completed"' >/dev/null; then - break - fi - kill -0 "$runtime_pid" 2>/dev/null || fail "Braid exited during PR close finalization" - sleep 1 -done -printf '%s' "$closed_group" | jq -e \ - '.assignment_lifecycle == "sleeping" and .finalization_turns == 1' >/dev/null || \ - fail "closed PR did not converge through exactly one Finalization Turn" -[ "$(printf '%s' "$closed_group" | jq -er .turn_count)" -eq $((preclose_turns + 1)) ] || \ - fail "PR close produced an unexpected number of turns" - -closed_comment=$(gh api --method POST "repos/$repository/issues/$pull_number/comments" \ - -f body="Closed PR sleep acceptance: acknowledge this comment but do not start another turn." \ - --jq .id) -for _ in $(seq 1 30); do - issue_reaction_exists "$closed_comment" eyes && break - sleep 1 -done -issue_reaction_exists "$closed_comment" eyes || fail "closed PR comment was not durably seen" -sleep 8 -closed_after=$(latest_pr_group) -[ "$(printf '%s' "$closed_after" | jq -er .turn_count)" -eq $((preclose_turns + 1)) ] || \ - fail "closed PR event granted a second Finalization Turn" - -gh pr reopen "$pull_number" --repo "$repository" >/dev/null -for _ in $(seq 1 300); do - reopened_group=$(latest_pr_group) - if printf '%s' "$reopened_group" | jq -e \ - --arg old "$preclose_session" --argjson minimum $((preclose_turns + 2)) ' - .assignment_lifecycle == "active" and .session_lifecycle == "idle" and - .worktree_lifecycle == "active" and .provider_session_id != $old and - .turn_count >= $minimum and .active_turn_id == null' >/dev/null; then - break - fi - kill -0 "$runtime_pid" 2>/dev/null || fail "Braid exited during PR reopen" - sleep 1 -done -printf '%s' "$reopened_group" | jq -e \ - '.assignment_lifecycle == "active" and .worktree_lifecycle == "active"' >/dev/null || \ - fail "reopened PR did not restore its Agent Group/worktree" -[ "$(printf '%s' "$reopened_group" | jq -er .worktree_path)" = "$initial_worktree" ] || \ - fail "PR reopen replaced the dedicated worktree" - -reopened_session=$(printf '%s' "$reopened_group" | jq -er .provider_session_id) -reopened_resume_count=$(printf '%s' "$reopened_group" | jq -er .provider_resume_count) -stop_process "$runtime_pid" -runtime_pid= -start_runtime -for _ in $(seq 1 180); do - resumed_group=$(latest_pr_group) - if printf '%s' "$resumed_group" | jq -e \ - --arg session "$reopened_session" \ - --arg worktree "$initial_worktree" \ - --argjson resumes $((reopened_resume_count + 1)) ' - .assignment_lifecycle == "active" and .session_lifecycle == "idle" and - .provider_session_id == $session and .worktree_path == $worktree and - .worktree_lifecycle == "active" and .provider_resume_count >= $resumes' \ - >/dev/null; then - break - fi - kill -0 "$runtime_pid" 2>/dev/null || fail "Braid exited while resuming the reopened PR Agent" - sleep 1 -done -printf '%s' "$resumed_group" | jq -e \ - --arg session "$reopened_session" --arg worktree "$initial_worktree" ' - .provider_session_id == $session and .worktree_path == $worktree and - .session_lifecycle == "idle"' >/dev/null || \ - fail "Braid restart did not resume the same PR provider session and worktree" - -merge_base_ref="acceptance/slice5-base-$stamp" -gh api --method POST "repos/$repository/git/refs" \ - -f ref="refs/heads/$merge_base_ref" -f sha="$parent_sha" >/dev/null -gh pr edit "$pull_number" --repo "$repository" --base "$merge_base_ref" >/dev/null -for _ in $(seq 1 240); do - before_merge_group=$(latest_pr_group) - if printf '%s' "$before_merge_group" | jq -e \ - '.assignment_lifecycle == "active" and .session_lifecycle == "idle" and - .active_turn_id == null' >/dev/null; then - break - fi - kill -0 "$runtime_pid" 2>/dev/null || fail "Braid exited while changing the disposable merge base" - sleep 1 -done -premerge_turns=$(printf '%s' "$before_merge_group" | jq -er .turn_count) -gh pr ready "$pull_number" --repo "$repository" >/dev/null -gh pr merge "$pull_number" --repo "$repository" --merge --delete-branch=false >/dev/null -for _ in $(seq 1 300); do - merged_group=$(latest_pr_group) - if printf '%s' "$merged_group" | jq -e \ - --argjson minimum $((premerge_turns + 1)) ' - .assignment_lifecycle == "retired" and .session_lifecycle == "retired" and - .worktree_lifecycle == "retired" and .finalization_turns == 2 and - .last_finalization_lifecycle == "completed" and .turn_count == $minimum' >/dev/null; then - break - fi - kill -0 "$runtime_pid" 2>/dev/null || fail "Braid exited during merged PR finalization" - sleep 1 -done -printf '%s' "$merged_group" | jq -e \ - '.assignment_lifecycle == "retired" and .finalization_turns == 2' >/dev/null || \ - fail "merged PR did not retire after exactly one final Finalization Turn" -gh pr view "$pull_number" --repo "$repository" --json state,mergedAt,baseRefName | jq -e \ - --arg base "$merge_base_ref" '.state == "MERGED" and .mergedAt != null and .baseRefName == $base' \ - >/dev/null || fail "PR was not merged only into the disposable base" - -restart_issue_url=$(gh issue create \ - --repo "$repository" \ - --title "Braid Slice 6 active restart $stamp" \ - --body "Disposable active-turn restart fixture. Inspect the repository documentation carefully before responding; make no repository changes.") -restart_issue_number=${restart_issue_url##*/} -restart_comment=$(gh api --method POST "repos/$repository/issues/$restart_issue_number/comments" \ - -f body="@braid Inspect the repository documentation carefully before responding. Keep this turn read-only and report concisely." \ - --jq .id) -for _ in $(seq 1 "${BRAID_TEST_WAIT_SECONDS:-120}"); do - active_restart_group=$(latest_issue_group) - if printf '%s' "$active_restart_group" | jq -e \ - '.assignment_lifecycle == "active" and .session_lifecycle == "running" and - .active_turn_id != null and .turn_lifecycle == "running"' >/dev/null; then - break - fi - kill -0 "$runtime_pid" 2>/dev/null || fail "Braid exited before the restart fixture became active" - sleep 1 -done -printf '%s' "$active_restart_group" | jq -e '.active_turn_id != null' >/dev/null || \ - fail "trusted mention did not create an active Issue turn for restart" -restart_session=$(printf '%s' "$active_restart_group" | jq -er .provider_session_id) -restart_turns=$(printf '%s' "$active_restart_group" | jq -er .turn_count) -issue_reaction_exists "$restart_comment" rocket || \ - fail "active restart fixture did not expose the trusted-mention rocket" -stop_process "$runtime_pid" -runtime_pid= -start_runtime -for _ in $(seq 1 "${BRAID_TEST_WAIT_SECONDS:-120}"); do - unknown_group=$(latest_issue_group) - unknown_status_count=$(gh api "repos/$repository/issues/$restart_issue_number/comments" --paginate | jq \ - --arg app "$app_actor" \ - '[.[] | select(.user.login == $app and (.body | contains("Provider outcome unknown")))] | length') - if printf '%s' "$unknown_group" | jq -e \ - --arg session "$restart_session" --argjson turns "$restart_turns" ' - .provider_session_id == $session and .session_lifecycle == "unknown" and - .turn_lifecycle == "unknown" and - .turn_count == $turns and .provider_resume_count >= 1' >/dev/null && \ - [ "$unknown_status_count" -eq 1 ]; then - break - fi - kill -0 "$runtime_pid" 2>/dev/null || fail "Braid exited while converging an unknown active turn" - sleep 1 -done -printf '%s' "$unknown_group" | jq -e \ - --arg session "$restart_session" --argjson turns "$restart_turns" ' - .provider_session_id == $session and .session_lifecycle == "unknown" and - .turn_lifecycle == "unknown" and .turn_count == $turns' >/dev/null || \ - fail "active-turn restart did not preserve one neutral unknown turn on the same provider session" -[ "$unknown_status_count" -eq 1 ] || fail "active-turn restart did not converge one Operational Status Comment" -issue_reaction_exists "$restart_comment" rocket || \ - fail "unknown active-turn restart incorrectly claimed a terminal reaction" - -echo "PASS: Slice 5 Issue-to-PR, direct origin, review/reset, and PR lifecycle" -echo "candidate=$($braid --version)" -echo "repository=$repository issue=$issue_number pr=$pull_number comment=$comment_id" -echo "profile=$pr_profile diff=$fixture_path worktree=preserved" -echo "scope=semantic comment result, concurrent idempotency, bootstrap, Draft/native association, PR Profile/session/worktree, exact diff, review wake, review-thread invalidation, debounced Associated-Issue active invalidation, unconfigured direct gh origin, close/sleep/reopen, idle PR session/worktree restart, merge/retire, active Issue turn restart to one neutral unknown" -echo "UNPROVEN: configured stable direct-gh actor, full Slice 5 campaign matrix, and native App assignment capability" diff --git a/scripts/tests/60_operations.sh b/scripts/tests/60_operations.sh deleted file mode 100755 index e02cf495..00000000 --- a/scripts/tests/60_operations.sh +++ /dev/null @@ -1,232 +0,0 @@ -#!/bin/sh -set -eu - -fail() { - echo "FAIL: $*" >&2 - exit 1 -} - -source_config=${BRAID_CONFIG:?BRAID_CONFIG must point to the real acceptance config} -webhook_secret=${BRAID_WEBHOOK_SECRET:?BRAID_WEBHOOK_SECRET must match the dedicated App} -braid=${BRAID_BIN:-braid} -previous_braid=${BRAID_PREVIOUS_BIN:-} -repository_root=$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd) -temporary_root=$(mktemp -d "${TMPDIR:-/tmp}/braid-slice6.XXXXXX") -runtime_root="$temporary_root/runtime" -config="$temporary_root/braid.toml" -runtime_log="$temporary_root/runtime.log" -ingress_address=${BRAID_TEST_INGRESS:-127.0.0.1:18100} -health_address=${BRAID_TEST_HEALTH:-127.0.0.1:18101} -health_url="http://$health_address/healthz" -runtime_pid= -receiver_pid= -tunnel_runtime_log= -tunnel_scope=verified - -stop_process() { - pid=$1 - signal=${2:-TERM} - [ -n "$pid" ] || return 0 - kill -0 "$pid" 2>/dev/null || return 0 - kill -"$signal" "$pid" 2>/dev/null || true - for _ in $(seq 1 20); do - kill -0 "$pid" 2>/dev/null || { - wait "$pid" 2>/dev/null || true - return 0 - } - sleep 1 - done - kill -KILL "$pid" 2>/dev/null || true - wait "$pid" 2>/dev/null || true -} - -cleanup() { - status=$? - trap - EXIT HUP INT TERM - stop_process "$runtime_pid" - stop_process "$receiver_pid" - if [ "$status" -ne 0 ] && [ -f "$runtime_log" ]; then - echo "Slice 6 runtime log follows" >&2 - tail -200 "$runtime_log" >&2 - fi - if [ "$status" -ne 0 ] && [ -n "$tunnel_runtime_log" ] && [ -f "$tunnel_runtime_log" ]; then - echo "Slice 6 tunnel runtime log follows" >&2 - tail -200 "$tunnel_runtime_log" >&2 - fi - rm -rf "$temporary_root" -} -trap cleanup EXIT HUP INT TERM - -command -v "$braid" >/dev/null 2>&1 || [ -x "$braid" ] || fail "Braid binary is unavailable" -command -v curl >/dev/null 2>&1 || fail "curl is unavailable" -command -v jq >/dev/null 2>&1 || fail "jq is unavailable" -command -v python3 >/dev/null 2>&1 || fail "python3 is required for the OTLP black-box helper" -[ -f "$source_config" ] || fail "acceptance config does not exist" -mkdir -p "$runtime_root/state/backups" - -awk \ - -v root="$runtime_root" \ - -v database="$runtime_root/state/braid.sqlite3" \ - -v backups="$runtime_root/state/backups" \ - -v ingress="$ingress_address" \ - -v health="$health_address" ' - /^\[runtime\]$/ { section="runtime"; print; next } - /^\[server\]$/ { section="server"; print; next } - /^\[telemetry\]$/ { section="telemetry"; print; next } - /^\[/ && $0 != "[runtime]" && $0 != "[server]" && $0 != "[telemetry]" { section="other" } - section == "runtime" && /^root = / { printf "root = \"%s\"\n", root; next } - section == "runtime" && /^database = / { printf "database = \"%s\"\n", database; next } - section == "runtime" && /^backups = / { printf "backups = \"%s\"\n", backups; next } - section == "runtime" && /^auto_migrate = / { print "auto_migrate = false"; next } - section == "server" && /^ingress = / { printf "ingress = \"%s\"\n", ingress; next } - section == "server" && /^health = / { printf "health = \"%s\"\n", health; next } - section == "telemetry" && /^endpoint = / { print "endpoint = \"http://127.0.0.1:43219\""; next } - section == "telemetry" && /^sample_ratio = / { print "sample_ratio = 0.10"; next } - section == "telemetry" && /^incident_mode = / { print "incident_mode = false"; next } - { print } -' "$source_config" > "$config" - -"$braid" migrate apply --config "$config" >/dev/null -archive=$(BRAID_DIST_DIR="$temporary_root/dist" "$repository_root/scripts/package.sh") -"$repository_root/scripts/tests/00_clean_install.sh" "$archive" - -if [ -z "$previous_braid" ] || [ ! -x "$previous_braid" ]; then - fail "BRAID_PREVIOUS_BIN must name the declared schema-compatible rollback binary" -fi -"$previous_braid" status --config "$config" --json | \ - jq -e '.database.schema_version == .database.supported_schema' >/dev/null || \ - fail "the declared rollback binary cannot read the migrated database" - -start_transport() { - BRAID_WEBHOOK_SECRET="$webhook_secret" "$braid" serve --config "$config" --transport-only \ - >"$runtime_log" 2>&1 & - runtime_pid=$! - for _ in $(seq 1 90); do - if curl -fsS "$health_url" 2>/dev/null | jq -e '.ready == true' >/dev/null; then - return 0 - fi - kill -0 "$runtime_pid" 2>/dev/null || fail "transport runtime exited before readiness" - sleep 1 - done - fail "transport runtime did not become ready" -} - -start_transport -stop_process "$runtime_pid" TERM -runtime_pid= -"$braid" status --config "$config" --json | jq -e '.transport.owner == null' >/dev/null || \ - fail "SIGTERM did not release the runtime owner lease" - -start_transport -killed_pid=$runtime_pid -kill -KILL "$killed_pid" -wait "$killed_pid" 2>/dev/null || true -runtime_pid= -if BRAID_WEBHOOK_SECRET="$webhook_secret" "$braid" serve --config "$config" --transport-only \ - >"$temporary_root/fenced-restart.log" 2>&1; then - fail "forced shutdown allowed a second owner before lease expiry" -fi -grep -q 'another Braid runtime owns' "$temporary_root/fenced-restart.log" || \ - fail "forced restart did not expose owner fencing" -sleep 31 -start_transport -stop_process "$runtime_pid" TERM -runtime_pid= - -if [ "${BRAID_TEST_SKIP_TUNNEL:-0}" != "1" ]; then - tunnel_runtime_log="$temporary_root/tunnel-runtime.log" - BRAID_WEBHOOK_SECRET="$webhook_secret" "$braid" serve --config "$config" \ - --transport-only --tunnel >"$tunnel_runtime_log" 2>&1 & - runtime_pid=$! - public_webhook= - for _ in $(seq 1 900); do - health=$(curl -fsS "$health_url" 2>/dev/null || true) - if printf '%s' "$health" | jq -e \ - '.ready == true and .tunnel == "connected" and .webhook_url != null' >/dev/null 2>&1; then - public_webhook=$(printf '%s' "$health" | jq -er .webhook_url) - break - fi - kill -0 "$runtime_pid" 2>/dev/null || fail "tunnel runtime exited before readiness" - sleep 1 - done - [ -n "$public_webhook" ] || fail "Braid did not establish a verified internal Quick Tunnel" - tunnel_child=$(pgrep -P "$runtime_pid" | head -1 || true) - [ -n "$tunnel_child" ] || fail "Braid Quick Tunnel child was not observable" - kill -TERM "$tunnel_child" - for _ in $(seq 1 60); do - health=$(curl -fsS "$health_url" 2>/dev/null || true) - if printf '%s' "$health" | jq -e \ - --arg public "$public_webhook" ' - .ready == true and .tunnel == "unavailable" and - .webhook_url != $public and - (.last_error | contains("prior App webhook was restored"))' >/dev/null 2>&1; then - break - fi - kill -0 "$runtime_pid" 2>/dev/null || fail "runtime exited with its Quick Tunnel" - sleep 1 - done - printf '%s' "$health" | jq -e \ - '.ready == true and .tunnel == "unavailable" and - (.last_error | contains("prior App webhook was restored"))' >/dev/null || \ - fail "Quick Tunnel death did not repair the App webhook and preserve runtime health" - stop_process "$runtime_pid" TERM - runtime_pid= -else - tunnel_scope=unavailable -fi - -sample_config="$temporary_root/sample.toml" -cp "$config" "$sample_config" -capture="$temporary_root/otel-sample.bin" -python3 "$repository_root/scripts/tests/otel_receiver.py" \ - --port 43219 --minimum-requests 3 --idle-seconds 2 --deadline-seconds 180 \ - --output "$capture" & -receiver_pid=$! -sleep 1 -sampled=0 -probes=0 -for index in $(seq 1 "${BRAID_TEST_WAIT_SECONDS:-120}"); do - result=$("$braid" telemetry probe --config "$sample_config" \ - --marker "BRAID_SLICE6_SAMPLE_$index" --json) - probes=$index - printf '%s' "$result" | jq -e '.sampled == .payload_emitted' >/dev/null || \ - fail "trace sampling orphaned a payload child" - if printf '%s' "$result" | jq -e '.sampled == true' >/dev/null; then - sampled=$((sampled + 1)) - fi - if [ "$probes" -ge 30 ] && [ "$sampled" -gt 0 ] && [ "$sampled" -lt "$probes" ]; then - break - fi -done -wait "$receiver_pid" -receiver_pid= -[ "$sampled" -gt 0 ] && [ "$sampled" -lt "$probes" ] || \ - fail "10% sampling did not retain a bounded subset ($sampled/$probes)" -grep -a -q 'PATH /v1/traces' "$capture" || fail "sampled traces did not reach OTLP" - -incident_config="$temporary_root/incident.toml" -awk ' - /^incident_mode = / { print "incident_mode = true"; next } - /^endpoint = / { print "endpoint = \"http://127.0.0.1:43220\""; next } - { print } -' "$sample_config" > "$incident_config" -incident_capture="$temporary_root/otel-incident.bin" -python3 "$repository_root/scripts/tests/otel_receiver.py" \ - --port 43220 --minimum-requests 3 --deadline-seconds 30 --output "$incident_capture" & -receiver_pid=$! -sleep 1 -incident=$("$braid" telemetry probe --config "$incident_config" \ - --marker BRAID_SLICE6_INCIDENT --json) -printf '%s' "$incident" | jq -e \ - '.sampled == true and .payload_emitted == true and - .exporter.configured_sample_ratio == 0.1 and - .exporter.effective_sample_ratio == 1.0 and .exporter.incident_mode == true' \ - >/dev/null || fail "incident mode did not force complete sampling" -wait "$receiver_pid" -receiver_pid= -grep -a -q 'BRAID_SLICE6_INCIDENT' "$incident_capture" || \ - fail "incident payload evidence did not reach OTLP" - -echo "PASS: Slice 6 packaging, migration/rollback, owner fencing, SIGTERM, and OTel convergence" -echo "candidate=$($braid --version) sampled=$sampled/$probes tunnel=$tunnel_scope" -echo "UNPROVEN HERE: active-turn restart and uncertain remote write; active restart is covered by the real Slice 5/6 campaign" diff --git a/scripts/tests/README.md b/scripts/tests/README.md deleted file mode 100644 index ec572916..00000000 --- a/scripts/tests/README.md +++ /dev/null @@ -1,198 +0,0 @@ -# Acceptance Helpers - -This directory contains operator scripts that exercise public boundaries while -the real Braid workflow is being stabilized. A helper may invoke the installed -`braid` binary, GitHub/`gh`, Git/Codex/Wrangler, loopback health, OTLP, and -process controls. It must not import Braid internals, inject SQLite rows/events, -or replace GitHub/provider with fakes and then claim product acceptance. - -Scripts should capture bounded machine-readable evidence and leave Human -verdicts explicit. Running a helper is not acceptance: every release candidate -must satisfy [`docs/10-prd/acceptance.md`](../../docs/10-prd/acceptance.md) -through real GitHub Work Items and a clean packaged installation. - -`00_clean_install.sh` is the packaged binary check run by CI. It exercises the -public CLI with a clean environment, checks database creation, upgrades schema -1 to schema 2 while retaining existing data, confirms a no-op reapply, and -checks refusal of newer and foreign databases. The adjacent loopback OTLP -capture helper checks trace sampling. SQLite access constructs and inspects -migration fixtures. - -`05_instances.sh` is the multi-instance layout gate. It builds on the packaged -binary, constructs a temporary `BRAID_USER_HOME` with two registered -instances, and exercises `--config`/`--instance`/`BRAID_INSTANCE`/ -`BRAID_INSTANCE_HOME` resolution plus the registry-based default instance. It -also proves `braid doctor` rejects overlapping ingress/health ports across -registered instances without needing a real GitHub App. - -`10_context_projection.sh` is the Slice 1 real-object gate. It requires an -absolute App-backed config, a controlled Issue and PR, plus explicit fixture -expectations for visible/filtered/folded/deleted/paginated evidence and the -number of directly Associated Issues/PRs. It lowers the public diagnostic -GraphQL page size to one, proving the real page walkers without manufacturing -hundreds of comments, and checks that a closed Associated Issue contributes no -body. Missing fixture inputs return -`UNAVAILABLE` rather than substituting a user token, mock server, or synthetic -snapshot. The helper drives only packaged `braid` commands and compares the -emitted bytes. - -`20_ingress_scheduler.sh` is the Slice 2 transport gate. It requires the -dedicated GitHub App to subscribe to Braid's declared Issue and PR event set, -an acceptance config, an App-matching `BRAID_WEBHOOK_SECRET`, authenticated -Human `gh`, and the packaged candidate binary. It creates disposable real -Issues, lets Braid own a Quick Tunnel only while the helper runs, and proves -durable webhook admission, App-owned `eyes`, delivery rededuplication, -older-after-newer non-regression, the 30-second debounce window, the -eight-event release threshold, trusted visible `@braid`, canonical -reconciliation during tunnel loss, pending-batch restart, and graceful webhook -URL restoration. It observes only public CLI/health/GitHub surfaces and never -starts a provider turn. - -The default `BRAID_TEST_WEBHOOK_MODE=app` also proves App webhook handoff and -restoration. When GitHub has no App webhook object yet and its settings UI -cannot bootstrap one, the bounded `repository` mode can prove the transport -behavior without recreating the App. Start a Quick Tunnel to an unused local -ingress, then provide its `/webhook` URL through -`BRAID_TEST_PUBLIC_WEBHOOK_URL`; the helper creates and deletes one temporary -repository webhook and accepts optional `BRAID_TEST_INGRESS` and -`BRAID_TEST_HEALTH` loopback addresses. This mode does not prove App event -subscriptions or App webhook handoff/restoration, and its JSON verdict says so. - -`30_issue_agent.sh` is the Slice 3 provider gate. It records the candidate -version/SHA-256 and starts that exact packaged -Braid binary against the real pinned Codex app-server, creates one temporary -repository webhook and disposable Issue, and uses the ordinary-App fallback: -the first trusted `@braid` activates the dormant Issue and starts the turn. It -then proves: - -- one expected-turn edit steer and `eyes`/`rocket` to `eyes`/`+1` convergence; -- one ordinary turn only after the complete 30-second debounce window, with no - request-style reactions; -- eight durably received events releasing one threshold turn, also without - request-style reactions; -- real app-server process loss preserving an unknown turn and `rocket` while - publishing one App-authored Operational Status Comment;随后验证替换会话重新接收 fenced 输入,历史 Unknown 仍可通过 status 查询; -- a separate accepted turn using an intentionally unsupported model receiving - a real Codex `turn.failed`, converging from observed `rocket` to `confused`; -- Agent-authored attributed comments, one initial session per fixture, and zero Braid - turn-mirror comments;Unknown 恢复会产生替换会话,原 turn 的历史记录保留。 - -The count timing begins only after all eight `eyes` acknowledgements prove -durable Braid receipt; GitHub webhook delivery latency is not mislabeled as -scheduler latency. The helper deletes its temporary webhook and closes both -Issues unless -`BRAID_TEST_KEEP_FIXTURES=1`。`BRAID_TEST_EVIDENCE_DIR` 可指定证据目录;未指定时创建独立临时目录,保留日志、状态快照、GitHub 评论与结果 JSON。 - -Run it with a real authenticated Agent `gh` identity and an acceptance config -whose Codex home already has provider authentication: - -```shell -BRAID_CONFIG=/absolute/path/to/braid.toml \ -BRAID_BIN=/absolute/path/to/braid \ -BRAID_TEST_WRANGLER=/absolute/path/to/wrangler \ -BRAID_WEBHOOK_SECRET='acceptance-secret' \ -scripts/tests/30_issue_agent.sh -``` - -This gate does not prove native Agent App assignment, App-webhook bootstrap, -Context invalidation/replacement, restart/resume, PR Agents, or the full release -campaign. - -`40_context_lifecycle.sh` is the Slice 4 lifecycle gate at the public boundary. - -It requires the current schema and a real App/Codex/Quick Tunnel fixture. A -plain external Issue-description edit while the Agent is idle must create a new -physical provider session without starting a turn. The same edit during an -accepted turn must fence and interrupt that turn, remove its `rocket` without -claiming success/failure, inject the complete current Issue Context into a third -session, and run one continuation that demonstrates the edited description was -seen. The helper then folds a visible comment and proves reconciliation replaces -the idle session while retaining only folded metadata; restores it and proves -one ordinary Wake uses the same valid session and sees the restored body; then -deletes another comment and proves a body-less tombstone plus a fifth physical -session. The fixture uses a real design-review message to create the active turn, -not a shell/sleep command. The helper observes only GitHub, loopback health, -`braid context`, and `braid status`; the status command exposes durable -reset/session/revision evidence rather than requiring SQLite inspection. - -The same fixture now closes the Issue only after public status proves a turn -is running. That turn reaches its ordinary terminal without interruption; one -and only one Finalization Turn follows, then the Agent Group and provider -session become `sleeping`. A comment created while closed receives durable -`eyes` but grants no second turn. Reopen creates a fresh physical session from -the complete current GitHub Context and releases exactly one ordinary Wake -after the normal debounce window. Public status exposes the bounded -finalization count and terminal lifecycle so the helper never reads SQLite. - -The helper also terminates the idle app-server child and requires Braid to -reconnect, resume the exact same provider thread, expose the resume through -public status, and process the next ordinary Wake after the debounce window. -Two additional fresh-runtime fixtures exercise the Profile pressure policy: -soft pressure publishes one Operational Status Comment but supplies the full -Context and completes a turn; hard pressure publishes one status, starts no -provider session or turn, and never truncates or summarizes the Context. - -This Slice 4 helper does not yet claim native unassignment, active-turn -app-server loss, Context-unavailable recovery, or PR Agent coverage. - -`50_issue_to_pr.sh` is the growing Slice 5 public gate without claiming the full -Issue-to-implementation journey. It creates a disposable real Issue, publishes -one App-authored attributed Implementation Request through `braid gh`, verifies -its durable receipt, and invokes `braid gh pr ensure` twice concurrently. It -requires one deterministic branch, one same-tree bootstrap commit, one Draft PR, -one native Issue association, one PR Profile/session, and one generation-scoped -worktree provisioned from a fresh source clone. The real Codex Implementation -Agent must then push one exact requested file and publish one concise attributed -PR comment. It then uses a real inline review comment and review-thread -resolution to prove PR Event References plus an idle PR Context replacement, -starts a second real PR turn, and edits the directly Associated Issue -description to prove debounced active-turn fencing, one continuation, and -preservation of the same dedicated worktree. A temporary free Quick Tunnel and -repository webhook provide the low-latency ingress; reconciliation remains the -60-second repair path. The PR must contain no Braid turn mirror. Cleanup deletes -the webhook, closes the PR and Issue, deletes the fixture branch, and removes -the isolated runtime/source. -Set `BRAID_TEST_KEEP_FIXTURES=1` to retain evidence intentionally. - -The helper requires the installed Braid App to expose `Issues: write`, `Pull -requests: write`, and `Contents: write` and a schema-current config/private key: - -```shell -BRAID_CONFIG=/absolute/path/to/braid.toml \ -BRAID_BIN=/absolute/path/to/braid \ -BRAID_TEST_WRANGLER=/absolute/path/to/wrangler \ -BRAID_WEBHOOK_SECRET='temporary-repository-hook-secret' \ -scripts/tests/50_issue_to_pr.sh -``` - -Its PASS is deliberately bounded. The expanded campaign covers external -direct-`gh` origin, one close/sleep/reopen cycle, merge retirement, compatible -idle PR provider/worktree resume, and a separate active Issue turn that becomes -one neutral `unknown` after Braid restart. A Profile configured from the start -with a distinct stable Agent GitHub identity and native App assignment remain -separate capability gaps; changing Profile identity under a running assignment -correctly fails compatibility instead of silently rebinding it. - -`60_operations.sh` is the Slice 6 distribution and operations gate. It requires -the real acceptance config, matching App webhook secret, current candidate, and -a declared schema-compatible prior binary. Through public CLI/process/health -boundaries it packages and clean-installs the candidate, verifies upgrade and -compatible rollback, exercises graceful SIGTERM, forced-exit owner fencing and -post-expiry recovery, kills the runtime-owned Quick Tunnel and requires -automatic App webhook repair, and measures trace-consistent 10% sampling plus -incident-mode 100% sampling against a bounded OTLP receiver. Active-turn -unknown is deliberately composed with the real Slice 5/6 campaign rather than -manufactured in the local operations helper. - -If the account-less Cloudflare service is externally unavailable, setting -`BRAID_TEST_SKIP_TUNNEL=1` runs the remaining independent operations journeys -and reports `tunnel=unavailable`; that result does not accept the tunnel -child-death/App-webhook-repair journey. A later unskipped run is still required. - -```shell -BRAID_CONFIG=/absolute/path/to/braid.toml \ -BRAID_BIN=/absolute/path/to/current/braid \ -BRAID_PREVIOUS_BIN=/absolute/path/to/schema-compatible/braid \ -BRAID_WEBHOOK_SECRET='dedicated-app-secret' \ -scripts/tests/60_operations.sh -``` diff --git a/scripts/tests/otel_receiver.py b/scripts/tests/otel_receiver.py deleted file mode 100755 index 1ec2a3c4..00000000 --- a/scripts/tests/otel_receiver.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python3 -"""Capture a bounded number of OTLP/HTTP requests for the public CLI helper.""" - -from __future__ import annotations - -import argparse -from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer -from pathlib import Path -import time - - -class CaptureHandler(BaseHTTPRequestHandler): - output: Path - requests: int = 0 - last_request: float = 0.0 - - def do_POST(self) -> None: # noqa: N802 - HTTP handler contract - length = int(self.headers.get("Content-Length", "0")) - body = self.rfile.read(length) - with self.output.open("ab") as stream: - stream.write(f"PATH {self.path}\n".encode()) - stream.write(body) - stream.write(b"\nEND\n") - type(self).requests += 1 - type(self).last_request = time.monotonic() - self.send_response(200) - self.send_header("Content-Type", "application/x-protobuf") - self.send_header("Content-Length", "0") - self.end_headers() - - def log_message(self, _format: str, *_arguments: object) -> None: - return - - -def main() -> None: - parser = argparse.ArgumentParser() - parser.add_argument("--port", type=int, required=True) - parser.add_argument("--minimum-requests", type=int, required=True) - parser.add_argument("--idle-seconds", type=float, default=1.0) - parser.add_argument("--deadline-seconds", type=float, default=15.0) - parser.add_argument("--output", type=Path, required=True) - arguments = parser.parse_args() - CaptureHandler.output = arguments.output - server = ThreadingHTTPServer(("127.0.0.1", arguments.port), CaptureHandler) - server.timeout = 0.1 - deadline = time.monotonic() + arguments.deadline_seconds - while time.monotonic() < deadline: - server.handle_request() - if ( - CaptureHandler.requests >= arguments.minimum_requests - and time.monotonic() - CaptureHandler.last_request >= arguments.idle_seconds - ): - return - raise SystemExit("timed out waiting for OTLP requests") - - -if __name__ == "__main__": - main() diff --git a/scripts/verify-package.sh b/scripts/verify-package.sh new file mode 100755 index 00000000..9e457160 --- /dev/null +++ b/scripts/verify-package.sh @@ -0,0 +1,47 @@ +#!/bin/sh +# Check a native release archive as its consumer, away from the checkout. +set -eu + +if [ "$#" -ne 3 ]; then + echo 'Usage: verify-package.sh DIST_DIRECTORY RELEASE_TAG RUST_TARGET' >&2 + exit 2 +fi +dist=$(CDPATH= cd -- "$1" && pwd) +artifact="braid-$2-$3" +archive="$artifact.tar.gz" +cd "$dist" +if ! verified=$(shasum -a 256 -c "$archive.sha256"); then + printf 'SHA-256 verification failed for %s: %s\n' "$archive" "$verified" >&2 + exit 1 +fi +if [ "$verified" != "$archive: OK" ]; then + printf 'Checksum must identify %s (got %s)\n' "$archive" "$verified" >&2 + exit 1 +fi +install_root=$(mktemp -d) +trap 'rm -rf "$install_root"' EXIT +tar -xzf "$archive" -C "$install_root" +cd "$install_root/$artifact" +for entry in LICENSE README.md CHANGELOG.md deploy/otel-collector.example.yaml; do + if [ ! -s "$entry" ]; then + printf 'Required release file is missing or empty: %s\n' "$entry" >&2 + exit 1 + fi +done +# The packaged executable must run without a checkout, Rust toolchain or user config. +braid() { env -i HOME="$install_root" PATH=/usr/bin:/bin ./bin/braid "$@"; } +version=$(braid --version) +if [ "$version" != "braid ${2#v}" ]; then + printf 'Expected braid %s, installed binary reported %s\n' "${2#v}" "$version" >&2 + exit 1 +fi +config="$PWD/config.example.toml" +braid config check --config "$config" +applied=$(braid migrate apply --config "$config") +printf '%s\n' "$applied" +if ! printf '%s\n' "$applied" | grep -Eq '^schema: 0 -> [1-9][0-9]*$'; then + echo 'Clean installation must migrate a fresh database from schema 0' >&2 + exit 1 +fi +plan=$(braid migrate plan --config "$config") +printf '%s\n' "$plan" | grep -Fx 'pending: none' diff --git a/skills/README.md b/skills/README.md new file mode 100644 index 00000000..1811678f --- /dev/null +++ b/skills/README.md @@ -0,0 +1,9 @@ +# 独立 Agent Skills + +本目录保存可由 Agent 按需读取的独立方法材料。它们与 Braid 软件分开消费,不自动安装、加载、编译嵌入或加入默认 Profile,也不将 SKILL.md 及 references 正文内联到提示词。使用者将所需技能目录交给自己的 Agent Skills 发现机制;入口只保留名称、description 和路径,相关 reference 在需要时读取。 + +| 名称 | 用途 | 入口 | +| --- | --- | --- | +| braid-collaboration | 组织成果责任、接手剩余义务、判断变化影响、核对成员执行及采用与完成。 | [SKILL.md](braid-collaboration/SKILL.md) | + +`braid-collaboration` 反哺自 Factory26 的 `materials/skills/braid-collaboration/`(来源提交 `f3963f89e6f0250ea78a2702ebe2a6fcc5d46ba8`),保留四份专题材料,并按独立 Braid 的 GitHub/内建上游、serve/run 及现有 Console 接口调整操作部分。技能本身不授予模型运行或对象修改权限,不要求安装其它 SVC 技能;可选互补方法通过当前环境的实际技能清单发现。软件操作合同仍由 Braid 对应版本的项目文档持有,不由技能创建新接口;复制 `braid-collaboration/` 目录即可保留技能及其全部方法 references,无需复制软件源码。 diff --git a/skills/braid-collaboration/SKILL.md b/skills/braid-collaboration/SKILL.md new file mode 100644 index 00000000..f8e43833 --- /dev/null +++ b/skills/braid-collaboration/SKILL.md @@ -0,0 +1,48 @@ +--- +name: braid-collaboration +description: 理解 Braid 协作中的成果、责任、采用与完成;用于组织工作、接手剩余义务、判断共同约定变化,检查成员实际执行与进展,以及审阅采用候选和结束工作。 +--- + +# Braid 协作 + +协作的目的,是让不同工作共同兑现产品承诺,同时使每位成员能够专心处理自己承担的结果。Braid 的工作项、讨论、指派与代码关联让事实可定位;成果是否可用、谁仍欠什么、哪些依据支持完成,是不同的判断。 + +## 适用边界与操作入口 + +本技能是可独立采用的协作方法,不依赖 Braid 安装,也不由 Braid 软件自动安装、加载或编译嵌入。使用者通过自己的 Agent Skills 发现入口按需读取本文件及相关 reference;不要将技能正文内联进 system、profile、role 或 task prompt。 + +Braid 软件接入 GitHub 与内建协作平台这两个同等角色的上游。`serve` 持续响应协作事件;`run` 在内建平台上让 root Agent 组织一次有限范围工作。内建平台不是运行模式,Web Console 属于整个 Braid。两种入口都需要按成果安置责任、采用真实候选及核对剩余义务;`run` 的 completed 不替代产品验收。 + +方法不授予创建、指派、修改、合并、关闭或调用模型的权限。按当前实例授权及实际接口操作:外部 GitHub 使用其原生入口与现有 `braid gh` 能力;内建使用 `braid object`。执行前按需查询当前 `braid --help` 和子命令 help。持有 Braid 源码时,可在仓库内读取 `docs/user-manual/local.md`、`docs/user-manual/run.md` 与 `docs/user-manual/console.md`,核对命令、配置及停止合同;未持有源码时,以实际安装版本的 help 和官方 `xiaoland/braid` 仓库中对应版本的文档为准。这些软件操作材料不是技能包的必需依赖,将本目录复制到其它 Agent Skills 环境仍可使用包内方法与 references。不要把其它 Harness 中同名工具或旧 CLI 能力当作本项目已有接口。 + +## 成果决定责任的边界 + +一个成果的意义取决于消费者用它完成什么。接口、调查或局部实现都可以成为有效交付;若用户结果跨越几个入口或共享状态,完整结果仍需要汇总责任。实现分工与整体责任可以不同:同一人实现各层,也可能遗漏真实调用;多个人分工,也可以兑现同一完整承诺。 + +Issue 组织一项结果的需求解释、方案、验收与剩余义务,PR 交付关联 Issue 可采用的实现候选。一个 Issue 可以组织多个 PR,一个 PR 也可以关联多个 Issue;关联本身不代替各项结果的责任。拆分结果责任与安排实施顺序是不同决定:共同基础先交付、业务 PR 顺序推进,不改变各业务 Issue 的结果责任。把能力分配给负责人、组织关联实现 PR、或调整共同前提时,读 [组织工作](references/organizing-work.md)。 + +## 生产、接手与兑现是不同事实 + +发布使成果可取得,采用使它进入消费者的工作,兑现意味着适用结果支持原承诺。文件存在、代码合并或消息送达分别只证明这些动作本身。消费者可发现的共同定义、任务材料与成果身份,使下一步有可靠依据;私有笔记即使正确,也未必可供接续。 + +接手安置了剩余义务的责任,没有解除其结果要求。延期的完整消费者结果仍包括原要求中的前态、动作和成功或失败后的状态;一个接口名或局部异常分支可能只表达其中一部分。实际后续工作能够支持承接成立,额外回执并不自然增加依据。成果取得、义务承接和变化影响的区别见 [交接与变化](references/handoffs-and-changes.md)。 + +## 共同约定与接受结论各有依据 + +原要求界定产品承诺,共同文档保存当前解释与实现合同。新默认行为或例外是否成立,取决于它与原承诺及适用条件的关系;文档发布本身没有改变目标的权限。明确冲突意味着约定或候选需要纠正,真正歧义与目标变化则涉及有权者的决定,普通实现选择仍由实施者判断。 + +行为声明的依据连接原承诺、判据、实际条件与候选结果。局部检查可以真实通过,却未覆盖用户入口所需的调用条件、连续操作或失败后状态。接受这样的局部成果与保留整体义务可以同时成立;变化后的旧证据是否有效,取决于受影响行为和观察条件,而非只有提交号。相关判断见 [接受与关闭](references/accepting-and-closing.md),证据设计与解释可与 `svc-verification` 配合;发现方式见下文。 + +## 整理支持判断,也有自己的边界 + +Issue description 提供当前目标、采用的决定和开放义务,PR description 提供候选及其支撑范围;项目文档持有共同知识,packet 持有当前推理与接续状态。它们各有消费者与变化原因,重复维护同一动态答案会产生分歧。知识归属、任务维护及原生局部委派可分别参考环境提供的互补技能,不是使用本技能的前提。 + +已有上下文是否足够,取决于当前决定的具体未知。对象投影可以支持直接继续工作;折叠细节、新回复、责任冲突或候选身份缺口可能需要额外材料。例行整理可以由具有相应能力的整理者承担,它组织已成立事实和仍欠义务;事实正确性、需求解释与成果验收仍属于拥有相应判断责任和信息的人。更新的快照说明对象较新,不说明其中每项主张已被证实。 + +工作项状态、执行状态与产品进展各有依据。没有新评论或提交,不排除成员仍在处理未发布成果;执行中也不证明方向正确。需要判断其它成员(包括 reviewer)是否在推进、等待或失败时,先读 [执行与进展核查](references/organizing-work.md#核对成员实际执行与进展),取得相应执行事实与产物证据。 + +讨论整理、局部合并、局部工作结束与整体完成分别改变不同事实。没有新的事实或行动价值时,维护可以停止;仍有效的义务不会因此消失。[编辑器与导入器的例子](references/worked-example.md)展示这些区别如何改变采用与结束结论。 + +## 可选互补技能 + +使用环境可能另外提供 `svc-verification`(证据与反馈)、`svc-documentation` 或 `svc-specs`(知识归属)、`svc-task-packet`(接续材料)、`svc-sub-agents` 或 `svc-agent-collaboration`(原生委派)。这些名称来自技能来源或不同环境,不保证均已安装,也不保证接口相同。需要时从当前 Agent Skills 清单按名称、description 与实际路径发现,再读取相应 SKILL.md;本目录不携带这些技能,不要求相邻目录,也不复制其正文。未提供时直接使用本技能已经说明的成果、责任、原始证据与剩余义务原则,并遵守当前项目维护规则。 diff --git a/skills/braid-collaboration/references/accepting-and-closing.md b/skills/braid-collaboration/references/accepting-and-closing.md new file mode 100644 index 00000000..f9098ddc --- /dev/null +++ b/skills/braid-collaboration/references/accepting-and-closing.md @@ -0,0 +1,37 @@ +# 接受结论与结束条件 + +接受结论需要连接原承诺、现有判据、实际条件与候选结果。需求入口可定位、判据足够、观察已取得分别解决不同问题;一份映射、ready 状态或合并事实都没有独自回答其它问题。 + +## 新约定的成立依据 + +实现选择决定怎样兑现承诺,新默认行为或例外可能改变承诺本身。其成立依据是原要求的明确约束、适用条件和有权者的决定,而不是设计或合同已经发布。 + +明确违背原要求意味着约定及候选需要纠正;真正歧义涉及相应责任人的解释,目标改变还涉及授权范围。没有冲突的普通局部实现选择可以由实施者推进。把未裁决的新约定与已采用决定混为一谈,会让消费者正确接续一个尚未成立的解释。 + +检查输入或预期的修正,与产品约定的正确性也分别成立。某个用例选错了条件,并不证明候选的额外行为正确;修正该用例可以合理,同时仍存在需要纠正的行为。两项判断的依据不同,[共享设置例子](worked-example.md)提供具体反例。 + +## 声明范围与结果范围 + +PR 的行为声明及前序开放义务界定需要支撑的结果。用户入口、接口所需条件与可见结果之间的连接,决定局部实现是否兑现用户承诺;原要求中的连续操作和失败后状态也是结果的一部分。服务端结果可能有效,却没有涵盖调用者遗漏的条件。 + +派生矩阵、文案断言或已有检查集合,只表达和观察其实际包含的行为。集合全绿可以支持这些结果,未表达的原承诺仍缺依据。判据、条件与原始结果的关系由可选的 `svc-verification` 技能(按[技能入口](../SKILL.md#可选互补技能)发现)展开;检查数量、文件形式或审阅身份没有替代这种关系。 + +局部结果正确与整体尚欠可以同时成立。一个入口的通过不涵盖另一个入口,同一候选也可能因环境不同而有不同证据。修改后的旧观察是否仍适用,取决于行为、共享代码、数据、环境或判据受到的影响;普通 head 前移未必使全部证据失效,相同提交也未必使条件相同。 + +实际候选、原始输出及具体失败,使接受范围与剩余问题可以被检验。后续成功是新的结果,不改变首次失败的事实;执行前提受阻意味着尚未取得观察,不等于应用行为已经通过或失败。 + +## 局部合并与整体完成 + +ready 提出候选,merge 改变分支中的代码,Issue close 报告该项不再有待推进的义务。候选版本保护维持被接受对象的身份,不证明产品正确;操作回执才支持已合并或已关闭的状态事实。 + +有效局部成果可合并供后续开发,同时把尚欠消费者结果留在相应责任中。局部生产已经完成、成果可取得且后续责任有落点时,该局部工作也可以结束。整体完成则需要所有仍有效承诺的适用依据,或有权者已经改变目标;缺口无人负责、解释未决或关键观察尚欠,都意味着完成结论仍缺条件。 + +## 讨论整理与知识保留 + +讨论围绕具体问题展开,结束条件由该问题的未决义务决定。有效决定在消费者可取得的当前材料中保存后,历史讨论可以不再占用日常上下文;一个问题解决,仍不足以结束同一讨论中其它开放义务。 + +整理应先保存当前决定与开放义务,再使用当前上游实际支持的讨论能力。GitHub 的折叠、解决或隐藏有各自可见性影响;内建目前提供评论与回复,没有专用 resolve/hide 命令。不能把其它 Harness 的同名动作视为本项目能力。任何讨论整理都不会擦除已送达的原生历史,也不代表工作项完成。 + +自主 run 中 root 最后关闭:它会立即撤销整个范围的 writer 授权。子项仍有义务时提前关闭不会得到 completed,必须由操作者明确重开后才可继续。候选身份、范围义务和真实执行收尾支持的是运行闭环,业务正确性仍需实际消费者结果;本技能的完成判断不能被 run 终态代替。 + +没有新事实、决定、阻塞或行动价值时,维护可以停止。提醒说明有人提出检查请求,不说明被提醒者已经停滞。若由独立整理者维护 description 或讨论,它可以组织已有成立事实,缺失的产品依据与未决分歧仍归对应责任人判断。 diff --git a/skills/braid-collaboration/references/handoffs-and-changes.md b/skills/braid-collaboration/references/handoffs-and-changes.md new file mode 100644 index 00000000..0926eef8 --- /dev/null +++ b/skills/braid-collaboration/references/handoffs-and-changes.md @@ -0,0 +1,25 @@ +# 成果采用与变化的消费者 + +交接成立的意义,是接收者已经能够在自己的范围内继续工作。目标结果、原要求与当前决定、成果身份、已成立前提和剩余缺口共同界定这个条件;生产者无需代替消费者完成其全部本地调查。跨成员责任属于工作项,原生局部委派的判断由可选的原生委派技能(按[技能入口](../SKILL.md#可选互补技能)发现)展开。 + +## 责任接手与结果兑现 + +发布接口或实现说明生产成果可取得;消费者实际接入、据此继续实现或返回可用结果,支持采用成立。消息送达、指派或关联仅提供路由与组织事实。已有实际采用依据时,新的纯确认回合不会自然补充产品证据。 + +接手范围是否完整,取决于它是否承载前序仍有效的承诺。延期结果可能包括必要前态、用户动作、成功或失败后的可见结果与状态保持;后续任务中的接口名或错误提示只表达其中一部分时,原义务仍未被完整承接。它可以进入现有接手工作,也可以由整体负责人安置到其它工作;发送过交接消息不决定义务的去向。 + +责任已有落点与结果已被证实可以在不同时间成立。接手解除了“谁继续推进”的未知,适用观察解除了“是否兑现”的未知。局部生产工作可以结束,整体仍等待消费者结果;这与缺口无人负责的情况不同。 + +## 变化为何需要真实消费者 + +已批准变化与尚待判断的新约定具有不同地位。新行为是否成立,取决于原承诺与授权范围,见 [接受与关闭](accepting-and-closing.md)。共同定义保存已经成立的当前规则及替代关系,让消费者有一致依据;更新文档本身没有证明所有实现已经采用。 + +差异的作用由真实实施、整合和检查路径决定,包括已经交接给新人的工作。某个旧假设为什么失效、哪些行为受影响、何种成果仍可用,决定消费者能够继续、需要调整还是被具体前提阻塞。只知文档地址,未必知道自己的判断何处改变。独立意见的价值也来自挑战当前解释的事实,而非重复同一前提。 + +接口参数、上下文或提交条件可能控制不同分支。用户入口实际提供的条件,以及该分支返回的结果,才把接口能力连接到用户承诺。文档表与服务端局部通过没有观察到这条连接;同一负责人实现各层也存在这个缺口。中性例子见 [编辑器与导入器](worked-example.md)。 + +新增入口或派生状态即使沿用同一格式,也可能引入新的写入、读取、刷新或失效关系。影响依据是这些实际关系,不是只有显式依赖表或最初的负责人。未受影响的成果与证据仍可采用,普通提交变化未必要求全员同步。 + +## 交接的结束条件 + +成果被正确消费,剩余义务有实际落点,当前材料足以恢复有效决定时,交接与维护已有结束依据。新的反例或相关变化可能重新产生工作;无变化的提醒与回执没有同样的信息价值。稳定共同知识与一次讨论各有归属,由可选的知识归属技能(按[技能入口](../SKILL.md#可选互补技能)发现)解释。 diff --git a/skills/braid-collaboration/references/organizing-work.md b/skills/braid-collaboration/references/organizing-work.md new file mode 100644 index 00000000..f10f2658 --- /dev/null +++ b/skills/braid-collaboration/references/organizing-work.md @@ -0,0 +1,48 @@ +# 工作边界与共同材料的作用 + +工作项使一位负责人能够推进一个可被采用的结果。结果可以是决定所需的调查、可复用接口、完整用户操作或实现候选。若一个状态的修改与后续观察分别属于几项工作,局部交付可以各自成立,整体结果却可能没有汇总责任;分工数量并不能说明责任已经完整。 + +## 内聚结果与真实依赖 + +独立负责人、可独立采用的成果或不同结束条件,是分开工作的实际理由。已有工作能承接新增结果时,其目标与完成条件决定承接是否成立;名称相近或引用同一接口不足以说明范围相同。父子与 PR 关联保存组织和来源,实际责任与采用各需自己的依据。 + +业务能力有自己的需求解释、技术取舍、验收与后续协调时,父项建立并指派业务子 Issue,说明完整结果、适用材料和共同前提;负责人据此形成方案,再组织关联实现 PR。实施独立业务能力之前,需要先安置这项结果责任。已有 Issue 能完整承接的局部改动,可以增加关联 PR,无需为每个场景、文件或 PR 新建 Issue。实现候选完成不会解除关联 Issue 尚未兑现的要求;父项继续核对跨能力约束与整体结果。 + +例如账户管理与文件导入共享持久化设施。父 Issue 的基础 PR 可以先统一 schema 和共同接口,再顺序推进两项业务 Issue 的实现 PR;业务负责人分别持有需求、方案与验收,父项核对跨入口结果。共同文件的冲突影响实施与合并顺序,不决定业务责任是否拆分。前提尚未交付时,也可以先建立业务 Issue、明确范围和负责人,让依赖该前提的实施动作等待。 + +先判断哪些成果可以分别交付和取得反馈,再安排它们何时执行。顺序执行没有消除不同成果的边界;并行也没有自动建立独立性。分开能缩小各负责人的相关上下文,合并能减少必须反复共同裁决和交接的语义;判断应指出具体受益的成果或具体无法分开的条件,不能仅以“协调成本高”结束比较。 + +共同前提与消费它的业务能力各有完成依据。例如编辑器与导入器共享配置接口,接口的验证和提交语义需要共同确定,但两个入口仍可分别交付完整行为。共享基础的结束条件是消费者能取得并使用所需前提,不是所有消费者的业务都已实现。若一次改动在两处之间没有可用的中间状态,可以将这次改动共同实施,仍须保留各入口的行为义务与整体核对责任。 + +依赖的含义取决于消费者需要什么。接口语义稳定时,实现可以先行;只有服务、数据或整合提交可用后才成立的观察,仍等待对应前提。业务关联未必形成串行依赖。若未知会导致多方采用相互矛盾的共同语义,先形成可被采用的定义能减少返工;不依赖该未知的工作仍有推进价值。 + +局部排除说明生产范围,并没有修改整体承诺。延后义务有接手者,意味着责任已安置;完整结果取得适用依据,才意味着兑现。若原目标改变,决定的权限与影响又是另一项事实。 + +## 材料为何需要明确消费者 + +Issue description 帮助恢复当前目标、重要决定、依赖与开放责任;PR description 帮助判断候选及其证据范围。项目文档或可执行定义保存跨任务共同知识,packet 保存当前判断和下一步,讨论保存本次差异与决定的形成依据。动态答案在多个位置分别维护时,消费者可能取得不同版本;知识归属由可选的知识归属技能(按[技能入口](../SKILL.md#可选互补技能)发现)展开,任务材料由可选的 `svc-task-packet` 技能(按[技能入口](../SKILL.md#可选互补技能)发现)展开。 + +共享材料只有可发现、可取得且适用于当前成果,才能支持消费者继续工作。文件已写、已提交、已发布和已采用是不同事实。与成果一起取得的项目入口、共同定义和 packet 能降低重建上下文的成本;clone 外的正确笔记无法独自承担交接。Braid 父项正文也不会递归进入所有子项上下文,独立 clone 未必拥有最新共享实现。在内建 run 中,用 `braid object issue --parent NUMBER` 创建子项并在其正文保留需求、共同决定、依赖和交付 ref;创建未指派对象不会启动成员。root 等待成果时结束当前轮次,让出执行机会;反复轮询既不能替代交接,也可能占住成员所需的调度容量。并发参数限制在途 Braid 轮次,不限制 Pi 内部子任务、空闲原生会话或宿主总资源。 + +## 已有信息与具体未知 + +当前投影中的目标、正文和状态可以直接支持相应判断;重复获取同一信息未必带来新依据。投影可能折叠细节、截短正文或只保留讨论索引,通知也可能仅说明有新回复。信息是否足够,应由本次决定需要的事实区分:缺的是一段交接、当前候选、原文条件,还是实际结果。新的查询价值来自消除这个未知,而非开始或接续工作本身。 + +例行正文与讨论整理,目的是让既有决定和开放义务更易消费。具有整理能力的成员可以承担它;提出新解释、核实实现或结束产品义务仍需要对应判断与信息。方法入口的存在提供按需取得的能力,不构成每次工作都重读全部方法的理由。 + + +## 核对成员实际执行与进展 + +先明确本次未知:是责任没有建立、执行失败、成员正在等待,还是实现与需求边界不符。对象的指派、open/closed、PR draft 或 head 都是协作事实,不独自证明对应成员正在执行、健康或已经完成。reviewer 也不等同于 PR 实施者;外部 review 请求与 Braid 原生执行须分别取证。 + +先从当前上游取得对象与候选身份。内建可用 `braid object --config PATH show NUMBER` 和 `context NUMBER`,候选差异可用 `diff NUMBER`;外部 GitHub 可用 `braid context issue --config PATH OWNER/REPO#NUMBER`、`braid context pr` 或原生 `gh` 读取当前正文、讨论及已发布 head/base。`braid status --config PATH --json` 提供实例和传输队列概况,不是逐成员存活查询;run 的 ledger 是独立实例状态,基础配置的 status 不能代替当前 run 快照。 + +使用已配置的 Console 时,`/api/harness/snapshot` 展示当前 Harness 的 assignments、sessions、turns、queue 与 worktrees;托管 run 时同时保留 runId,并读取当前 run ledger。根据 assignment 代次、session 与 turn 身份区分本任执行、旧任停止和尚未消费输入。该快照没有提供从每个工作项到执行全部身份的完整关联图;不能从数组顺序、时间接近或同一 profile 猜测责任归属。缺少连接事实时保留为未知,按实例记录与明确的 session/turn 身份定向取得证据。 + +快照的 observedAt 是查询时间,lifecycle 是 Harness 最后记录的状态;宿主意外退出后 running 可能陈旧,不能据此宣称进程存活。Console 的 runtime 状态、停止确认和 run 结果分别读取。OTLP 中按明确 session、turn 或 trace 关联的 provider 事件、工具结果和具体错误可补充执行观察;没有新观测不证明空闲,记录或 token 增长不证明产品进展。完整原生历史只用于当前问题的定向取证,路径及材料缺失仍是未知。 + +需要核对实现时,取得 PR 固定候选与实际改动。内建 diff 保留该次对象 revision 和 head/base,详情更新后需重新核对;外部 GitHub 用 `gh pr view NUMBER --repo OWNER/REPO --json headRefName,baseRefName,headRefOid,baseRefOid` 读取已发布身份。只有取得明确登记的 worktree 路径时,才按需用 `git --no-optional-locks -C PATH status --short`、`git --no-optional-locks -C PATH diff --stat` 及相关文件只读查看未发布工作。diff 不包含未跟踪文件内容,相关新文件要另行读取;运行中观察是当时截面,不是冻结候选。不要进入其它成员的修改、checkout、reset 或清理操作。 + +Pi 内部 subagents 与 background 工作不由 Braid 完整跟踪,沿其负责人保存的任务状态、日志与结果继续核实。原生局部委派不能替代应由独立 Braid 成员承担的 Issue/PR 责任;是否真的发生成员交接,需要子项指派、实际原生执行与可采用成果支持,建立子项、分派消息或 root 自己完成全部实现分别只证明对应动作。 + +判断有价值的新结果、明确阻碍或方向偏差后,在原工作项给出采用或纠偏决定;已有事实支持继续推进时可以等待。不为获得状态反复索取无动作回执,也不把局部错误直接当作整项失败。当前独立 Braid 没有 Factory 中的 `braid execution`、`braid pr review list` 等 CLI;未来能力变化以当前实际 help 和接口为准。 diff --git a/skills/braid-collaboration/references/worked-example.md b/skills/braid-collaboration/references/worked-example.md new file mode 100644 index 00000000..0714640d --- /dev/null +++ b/skills/braid-collaboration/references/worked-example.md @@ -0,0 +1,35 @@ +# 编辑器与导入器共同修改设置 + +产品要求用户既能在编辑器修改设置,也能通过文件导入设置;修改后重新打开仍保留,无效修改不改变原状态。两条路径共享一份持久化配置。整体负责人需要取得的是两条路径都兑现这个完整承诺,而不是两份彼此独立的“保存成功”。 + +## 完整结果与局部分工 + +若配置接口已经稳定,编辑器和导入器可以分别实现并返回局部结果,整体负责人汇总重开与拒绝无效输入的行为。如果接口的验证和提交语义还没确定,先取得可被两方采用的共同接口及真实使用结果;业务实现可以准备不依赖该未知的部分,不能把未定义的事务含义各自猜成不同版本。 + +编辑器负责人排除导入器实现是合理的职责边界。它返回编辑器的实现和重开观察,同时指出导入路径仍需取得共享接口并核实失败时状态不变。整体负责人继续保留这项义务:导入器工作项明确采用接口并开始实施,或给回可用结果后,就有实际承接依据;只有建立关联和送达评论,还不足以结束这项交接。 + +如果接续任务只写“导入器调用接口并显示错误”,它的范围还没有包含无效输入不改变状态、导入后重开仍保留这两个完整结果。显示错误与这两个承诺具有不同依据;接手成立后,结果仍等候适用观察。 + +共同接口的现行约定在项目文档或可执行定义中保存,两项工作引用同一个地址和适用版本;各自 packet 保存当前工作与观察。一次关于边界的讨论解释这次决定,不再维护第二份完整合同。这样接续者能找到当前定义,而不用从几段旧讨论中猜哪次解释胜出。 + +## 变化会改变实际消费者的工作 + +实现中发现逐字段写入会在后续字段验证失败前改变部分状态,于是共同接口改为先验证整组,再一次提交。接口生产者发布了新定义与实现;编辑器已经采用它,导入器仍自行逐字段保存。发布成功只结束生产部分,导入器仍未采用足以保证无效输入不改变状态的结果。 + +整体负责人向导入器的当前实施者及其检查负责人说明新提交语义、旧路径失效的原因和采用入口。若检查已转交给另一人,只通知最初的 Issue 负责人就会遗漏真实消费者。导入器比较其代码和判据后改用共同接口,并返回无效导入前后状态相同的观察;这次后续行动支持采用成立,无需再发一轮“是否收到”。 + +接口后来要求调用者携带读取时的配置版本,以拒绝过期修改。服务端对含版本的请求检查通过,接口文档也已更新;审阅者仍从编辑器保存和导入动作核对真实请求,发现一个入口没有传入版本。漏传版本意味着该入口没有满足保护成立的条件,服务端的通过结果未涵盖它。补齐真实调用及该入口的结果,才可能支持两个入口都具备保护的结论;这个条件与是否同一人实现各层无关。 + +## 新约定按原承诺判断 + +导入器提议遇到无效字段时先保存有效字段,并把这项行为写入共同合同。原要求明确无效修改不改变原状态,发布合同或正确接续这个设计都不能解除冲突。原文使纠正约定及实现有了明确依据。如果某个检查原先提交了有效输入,修正该检查也可以合理;检查输入的问题与新约定的合法性由不同事实决定。 + +## 局部通过与整体接受分别判断 + +编辑器的有效结果可继续接受,但不证明导入后重开仍保留,也不证明无效导入保持原状态。整体负责人先消费两方已有结果,再按候选中共享接口的变化复查受影响行为,补导入路径仍缺的观察;不必因为提交号前移就拒绝所有旧证据或重复全部检查。 + +当两条路径的原承诺都有适用依据,候选完成整合,剩余讨论前提已解除,负责人可以完成交付判断。关联齐全或 PR 已合并本身不能替代这一比较;反过来,正确承接和有效观察已经成立,也不要求永久等待额外确认。 + +## 当前知识与维护结束 + +共同接口定义保存有效语义,任务材料保存实际候选、结论和证据入口。本次讨论围绕提交语义,问题有结论且其它未决事项已有独立责任时,历史前缀可以不再占用日常上下文;新的反例仍会产生新的工作。普通提醒、没有相关变化的提交和已消费的回执没有新的行动价值,维护已具备停止依据。 diff --git a/src/agent_session.rs b/src/agent_session.rs index 09ee6c14..d3610de8 100644 --- a/src/agent_session.rs +++ b/src/agent_session.rs @@ -29,9 +29,10 @@ impl TurnOutcome { pub enum SendResult { /// A new turn was accepted; observe `SessionEvent::TurnStarted` next. Started, - /// The message was accepted but does not create a new turn (steering, or - /// dropped while a turn is running). + /// The message was accepted by the observed active turn. Acknowledged, + /// No input was sent. The caller retains the batch for a safe boundary. + Deferred, } /// Lifecycle events that the core needs to react to. @@ -64,12 +65,14 @@ pub enum SessionEvent { TurnTerminal { provider_turn_id: String, outcome: TurnOutcome, error: Option }, } -#[derive(Debug, thiserror::Error)] +#[derive(Debug, Clone, thiserror::Error)] pub enum SessionError { #[error("session failed: {0}")] Failed(String), - #[error("session is unavailable")] - Unavailable, + #[error("session runtime is unavailable: {0}")] + Unavailable(String), + #[error("session reception is unknown: {0}")] + Unknown(String), } /// The core-facing Agent Session handle. @@ -88,26 +91,21 @@ pub trait AgentSession: Send + Sync { /// imply that the provider's persisted session has been deleted. fn is_unavailable(&self) -> bool; - /// Release this handle's execution resources, best-effort interrupting - /// its active turn. Other sessions must remain usable. + /// Stop this handle's execution before releasing its resources. A failure + /// blocks replacement; other sessions must remain usable. async fn close(&self) -> Result<(), SessionError>; /// Send a user message batch. `steering` selects the provider steer path /// for a running turn; a non-steering message while a turn runs is - /// dropped (`Acknowledged`) because the caller is expected to route it - /// through the event queue debounce instead. + /// deferred without sending; the caller retains it in the event queue. async fn send_user_msg(&self, msg: String, steering: bool) -> 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>; + /// Forward only to this observed active turn; never start a new turn. + async fn steer_user_msg( + &self, + msg: String, + expected_turn_id: &str, + ) -> Result; } /// An adapter-created handle and the opaque identity to bind in the durable store. diff --git a/src/builtin.rs b/src/builtin.rs new file mode 100644 index 00000000..b589b018 --- /dev/null +++ b/src/builtin.rs @@ -0,0 +1,439 @@ +//! HTTP adapter for the built-in collaboration authority. Its ledger belongs to the Harness. +use crate::{ + config::Config, + context::CanonicalContext, + platform::{execution::FenceExecution, grants::GrantEpoch}, + store::{ + BuiltinBinding, BuiltinCommand, BuiltinExecutionCommand, BuiltinGrant, BuiltinReply, + BuiltinWriterTurn, EventKind, IngressEvent, PendingGitHubWrite, RuntimeLease, StoreActor, + }, +}; +use anyhow::{Context as _, Result, ensure}; +use serde::{Deserialize, Serialize, de::DeserializeOwned}; +use std::sync::Arc; + +#[derive(Clone)] +pub(crate) struct BuiltinClient { + http: reqwest::Client, + endpoint: url::Url, + pub binding: BuiltinBinding, + pub store: Arc, + run_id: Option, + execution_fences: bool, + runtime: Option, +} +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct RepositoryInfo { + pub repository: String, + pub node_id: String, + pub space_id: String, + pub default_branch: String, + #[serde(default)] + pub execution_fences: bool, +} +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct EventFeed { + pub events: Vec, + pub next_after: u64, + pub last_sequence: u64, +} +#[derive(Deserialize)] +pub(crate) struct PlatformEvent { + pub sequence: u64, + pub event: WireEvent, +} +#[derive(Deserialize, Serialize)] +pub(crate) struct WireEvent { + pub delivery_guid: String, + pub event_name: String, + pub action: Option, + pub repository_node_id: String, + pub repository: String, + pub work_item_node_id: Option, + pub work_item_kind: Option, + pub work_item_number: Option, + pub work_item_state: Option, + pub object_node_id: Option, + pub object_version: Option, + pub object_digest: Option, + pub visible_body: Option, + pub actor_node_id: Option, + pub actor_login: Option, + pub kind: String, + pub detail: Option, + pub cross_surface_invalidation: bool, + pub origin: String, + pub reference: String, + pub mention_candidate: bool, + pub known: bool, + pub raw_payload: Vec, +} +impl WireEvent { + pub(crate) fn into_ingress(self) -> Result { + let kind = + EventKind::from_str(&self.kind).context("platform event has an unknown queue kind")?; + let work_item_kind = match self.work_item_kind.as_deref() { + None => None, + Some("issue") => Some("issue"), + Some("pr") => Some("pr"), + Some(other) => anyhow::bail!("platform returned unsupported work item kind {other}"), + }; + let detail = match self.detail.as_deref() { + None => None, + Some("closed") => Some("closed"), + Some("reopened") => Some("reopened"), + Some("merged") => Some("merged"), + Some("cross_surface") => Some("cross_surface"), + Some(other) => anyhow::bail!("platform returned unsupported event detail {other}"), + }; + let origin = match self.origin.as_str() { + "human" => "human", + "agent" => "agent", + "local" => "local", + other => anyhow::bail!("platform event has unsupported origin {other}"), + }; + Ok(IngressEvent { + identity: crate::store::ChangeIdentity::Occurrence, + delivery_guid: self.delivery_guid, + event_name: self.event_name, + action: self.action, + repository_node_id: self.repository_node_id, + repository: self.repository, + work_item_node_id: self.work_item_node_id, + work_item_kind, + work_item_number: self.work_item_number, + work_item_state: if work_item_kind == Some("pr") && detail == Some("merged") { + Some("merged".into()) + } else { + self.work_item_state + }, + object_node_id: self.object_node_id, + object_version: self.object_version, + object_digest: self.object_digest, + visible_body: self.visible_body, + actor_node_id: self.actor_node_id, + actor_login: self.actor_login, + kind, + detail, + cross_surface_invalidation: self.cross_surface_invalidation, + requires_attention: origin != "agent" + && matches!(kind, EventKind::Wake | EventKind::Invalidate | EventKind::Mention), + origin, + reference: self.reference, + mention_candidate: self.mention_candidate, + reaction_target: None, + known: self.known, + raw_payload: self.raw_payload, + }) + } +} +#[derive(Deserialize)] +#[serde(tag = "lifecycle", rename_all = "snake_case", rename_all_fields = "camelCase")] +enum MintReceipt { + Active { grant_id: String, epoch: u64, token: String }, + Denied { reason: String }, +} +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct GrantRequest<'a> { + #[serde(skip_serializing_if = "Option::is_none")] + run_id: Option<&'a str>, + request_id: &'a str, + client_id: &'a str, + item_number: u64, + actor: &'a str, + expected_epoch: u64, + authority_cursor: u64, + execution_id: &'a str, +} +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct OutboxRequest<'a> { + request_id: &'a str, + client_id: &'a str, + repository: &'a str, + target_kind: &'a str, + target_database_id: &'a str, + operation: &'a str, + content: &'a str, + remote_database_id: Option<&'a str>, +} +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct AppliedWrite { + database_id: Option, + node_id: Option, +} + +impl BuiltinClient { + pub(crate) async fn connect(config: &Config, store: Arc) -> Result> { + let settings = + config.builtin.as_ref().context("built-in upstream configuration missing")?; + let http = + reqwest::Client::builder().timeout(std::time::Duration::from_secs(30)).build()?; + let response = http.get(settings.endpoint.join("api/platform/repository")?).send().await?; + let info: RepositoryInfo = decode(response).await?; + ensure!( + info.repository == settings.repository, + "built-in upstream repository mismatch: expected {}, observed {}", + settings.repository, + info.repository + ); + ensure!( + info.node_id == format!("local:{}", info.repository), + "built-in upstream returned inconsistent repository identity" + ); + ensure!(!info.space_id.is_empty(), "built-in upstream has no durable space identity"); + let BuiltinReply::Binding(binding) = store + .builtin(BuiltinCommand::Bind { + space_id: info.space_id, + repository: info.repository, + instance: config.instance_key().into(), + }) + .map_err(|error| { + let extended_code = match &error { + crate::store::StoreError::Sqlite(rusqlite::Error::SqliteFailure(code, _)) => { + Some(code.extended_code) + } + _ => None, + }; + anyhow::Error::new(error).context(format!( + "bind built-in upstream to Harness ledger {} (SQLite extended code {extended_code:?})", + config.runtime.database().display() + )) + })? + else { + unreachable!() + }; + Ok(Arc::new(Self { + http, + endpoint: settings.endpoint.clone(), + binding, + store, + run_id: config.finite_run.as_ref().map(|run| run.run_id.clone()), + execution_fences: info.execution_fences, + runtime: None, + })) + } + pub(crate) fn with_runtime(&self, lease: RuntimeLease) -> Result> { + ensure!(self.execution_fences, "built-in platform must support execution fences"); + Ok(Arc::new(Self { runtime: Some(lease), ..self.clone() })) + } + + fn runtime(&self) -> Result { + self.runtime.clone().context("built-in execution requires the owning runtime lease") + } + + pub(crate) fn bind_execution(&self, turn_id: &str) -> Result<()> { + self.store.builtin(BuiltinCommand::Execution(BuiltinExecutionCommand::BindTurn { + lease: self.runtime()?, + turn_id: turn_id.into(), + }))?; + Ok(()) + } + + pub(crate) async fn fence_session(&self, provider_session: &str) -> Result<()> { + self.fence(BuiltinExecutionCommand::FenceSession { + lease: self.runtime()?, + provider_session: provider_session.into(), + }) + .await + } + + pub(crate) async fn fence_all_executions(&self) -> Result<()> { + self.fence(BuiltinExecutionCommand::FenceAll(self.runtime()?)).await + } + + async fn fence(&self, command: BuiltinExecutionCommand) -> Result<()> { + let lease = self.runtime()?; + let BuiltinReply::Fences(executions) = + self.store.builtin(BuiltinCommand::Execution(command))? + else { + unreachable!() + }; + let mut failures = Vec::new(); + for execution_id in executions { + if let Err(error) = self.fence_execution(&lease, execution_id).await { + failures.push(format!("{error:#}")); + } + } + ensure!(failures.is_empty(), "execution fence unconfirmed: {}", failures.join("\n")); + Ok(()) + } + + async fn fence_execution(&self, lease: &RuntimeLease, execution_id: String) -> Result<()> { + let request = FenceExecution { client_id: self.binding.client_id.clone(), execution_id }; + let confirmation: FenceExecution = self + .post("api/platform/executions/fence", &request) + .await + .with_context(|| format!("cannot fence execution {}", request.execution_id))?; + ensure!(confirmation == request, "platform confirmed a different execution fence"); + self.store.builtin(BuiltinCommand::Execution(BuiltinExecutionCommand::ConfirmFence { + lease: lease.clone(), + execution_id: request.execution_id, + }))?; + Ok(()) + } + + pub(crate) async fn get(&self, path: &str) -> Result { + decode(self.http.get(self.endpoint.join(path)?).send().await?).await + } + pub(crate) async fn scope_boundary( + &self, + root: u64, + ) -> Result { + self.get(&format!("api/platform/scope/{root}/boundary")).await + } + pub(crate) async fn post( + &self, + path: &str, + body: &impl Serialize, + ) -> Result { + decode(self.http.post(self.endpoint.join(path)?).json(body).send().await?).await + } + pub(crate) async fn context(&self, number: u64) -> Result { + self.get(&format!("api/platform/context/{number}")).await + } + pub(crate) async fn execution_context(&self, number: u64) -> Result { + let mut url = self.endpoint.join(&format!("api/platform/context/{number}"))?; + url.query_pairs_mut().append_pair("executionClientId", &self.binding.client_id); + if let Some(run_id) = &self.run_id { + url.query_pairs_mut().append_pair("executionRunId", run_id); + } + self.get(url.as_str()).await + } + pub(crate) async fn item(&self, number: u64) -> Result { + let item = self + .get::(&format!("api/platform/items/{number}")) + .await?; + ensure!(item.number == number, "platform returned a different item identity"); + Ok(item) + } + pub(crate) async fn default_branch(&self) -> Result { + Ok(self.get::("api/platform/repository").await?.default_branch) + } + pub(crate) async fn candidate(&self, number: u64) -> Result { + let item = self.item(number).await?; + ensure!(item.kind == "pr", "platform item #{number} is not a PR"); + item.head_commit.context("platform PR has no frozen candidate commit") + } + pub(crate) async fn writer_grant(&self, turn: BuiltinWriterTurn) -> Result { + let existing = self.local_writer_grant(&turn)?; + if let Some(grant) = &existing + && grant.lifecycle == "pending" + { + self.activate(grant).await?; + } else { + let mut url = self.endpoint.join("api/platform/grants")?; + url.query_pairs_mut() + .append_pair("clientId", &self.binding.client_id) + .append_pair("itemNumber", &turn.item_number.to_string()) + .append_pair("actor", &turn.actor); + let remote: Option = decode(self.http.get(url).send().await?).await?; + if let Some(remote) = remote.as_ref().filter(|remote| remote.active) { + // A concurrent CLI may have acquired the shared capability while + // the epoch read was in flight. Only replay its exact local intent. + match self.local_writer_grant(&turn)? { + Some(grant) if grant.lifecycle == "pending" => self.activate(&grant).await?, + Some(grant) if grant.lifecycle == "active" && grant.epoch == remote.epoch => {} + _ => anyhow::bail!( + "platform already has an active writer capability for this responsibility" + ), + } + } else { + let expected_epoch = remote.map_or(0, |remote| remote.epoch); + let BuiltinReply::Grant(Some(grant)) = self + .store + .builtin(BuiltinCommand::BeginMint { turn: turn.clone(), expected_epoch })? + else { + unreachable!() + }; + if grant.lifecycle == "pending" { + self.activate(&grant).await?; + } + } + } + let grant = self + .local_writer_grant(&turn)? + .context("writer capability disappeared during admission")?; + ensure!(grant.lifecycle == "active", "writer capability is not active"); + Ok(grant) + } + + fn local_writer_grant(&self, turn: &BuiltinWriterTurn) -> Result> { + let BuiltinReply::Grant(grant) = + self.store.builtin(BuiltinCommand::WriterGrant(turn.clone()))? + else { + unreachable!() + }; + Ok(grant) + } + + async fn activate(&self, grant: &BuiltinGrant) -> Result<()> { + let cursor = grant.authority_cursor.context("writer intent predates authority fencing")?; + let request = GrantRequest { + run_id: self.run_id.as_deref(), + request_id: &grant.request_id, + client_id: &self.binding.client_id, + item_number: grant.item_number, + actor: &grant.actor, + expected_epoch: grant.epoch, + authority_cursor: cursor, + execution_id: &grant.execution_id, + }; + match self.post("api/platform/grants", &request).await? { + MintReceipt::Active { grant_id, epoch, token } => { + self.store.builtin(BuiltinCommand::Activate { + request_id: grant.request_id.clone(), + session_id: grant.session_id.clone(), + grant_id, + epoch, + token, + })?; + } + MintReceipt::Denied { reason } => { + self.store.builtin(BuiltinCommand::RejectMint { + request_id: grant.request_id.clone(), + session_id: grant.session_id.clone(), + })?; + anyhow::bail!("{reason}"); + } + } + Ok(()) + } + + pub(crate) async fn apply_write( + &self, + write: &PendingGitHubWrite, + ) -> Result<(Option, Option)> { + let request = OutboxRequest { + request_id: &write.intent_id, + client_id: &self.binding.client_id, + repository: &write.repository, + target_kind: &write.target_kind, + target_database_id: &write.target_database_id, + operation: &write.operation, + content: &write.content, + remote_database_id: write.remote_database_id.as_deref(), + }; + let result: AppliedWrite = self.post("api/platform/writes", &request).await?; + Ok((result.database_id, result.node_id)) + } +} +#[derive(Debug, thiserror::Error)] +#[error("built-in platform HTTP {status}: {body}")] +pub(crate) struct PlatformHttpError { + pub status: reqwest::StatusCode, + pub body: String, +} +async fn decode(response: reqwest::Response) -> Result { + let status = response.status(); + let body = response.text().await?; + if !status.is_success() { + return Err(PlatformHttpError { status, body }.into()); + } + serde_json::from_str(&body) + .with_context(|| format!("invalid built-in platform HTTP {status} response: {body}")) +} diff --git a/src/cli/assignment.rs b/src/cli/assignment.rs new file mode 100644 index 00000000..4bb17fd4 --- /dev/null +++ b/src/cli/assignment.rs @@ -0,0 +1,35 @@ +use anyhow::{Context as _, Result}; + +use super::{AssignmentReactivate, helpers}; + +pub fn reactivate(arguments: AssignmentReactivate) -> Result<()> { + let config_path = arguments.source.resolve_config_path()?; + let config = helpers::load(&config_path)?; + let repository = arguments.repository.unwrap_or_else(|| config.repository().to_owned()); + if !config.repositories().contains(&repository.as_str()) { + anyhow::bail!( + "repository {repository:?} is not configured for this instance (configured: {})", + config.repositories().join(", ") + ); + } + let store = crate::store::StoreActor::start( + config.runtime.database().to_path_buf(), + config.runtime.backups().to_path_buf(), + ) + .context("cannot open the Braid ledger for assignment reactivation")?; + let event_id = store.enqueue_blocked_reactivation( + repository.clone(), + arguments.kind, + arguments.number, + arguments.reason.unwrap_or_default(), + crate::store::SchedulerPolicy { + quiet_seconds: config.scheduler.quiet_seconds, + event_threshold: config.scheduler.event_threshold, + }, + )?; + println!( + "Queued blocked-assignment reactivation {event_id} for {repository}#{}.\nThe running or next Harness will materialize a new generation with the current effective Profile; the old blocked generation remains unchanged.", + arguments.number + ); + Ok(()) +} diff --git a/src/cli/config.rs b/src/cli/config.rs index 4ed6c34f..e4bf6ade 100644 --- a/src/cli/config.rs +++ b/src/cli/config.rs @@ -8,7 +8,7 @@ pub fn config_check(arguments: &ConfigPath) -> Result<()> { } else { println!("configuration: valid"); println!("schema: {}", config.schema_version); - println!("repository: {}", config.github.repository); + println!("repositories: {}", config.repositories().join(", ")); println!("database: {}", config.runtime.database().display()); println!( "profiles: {}", diff --git a/src/cli/context_cmd.rs b/src/cli/context_cmd.rs index c66f6b7f..c1c16b9f 100644 --- a/src/cli/context_cmd.rs +++ b/src/cli/context_cmd.rs @@ -9,19 +9,23 @@ pub async fn context(command: ContextCommand) -> Result<()> { let config_path = arguments.source.resolve_config_path()?; let config = helpers::load(&config_path)?; let locator = arguments.target.parse::()?; + if !config.github_repositories().contains(&locator.repository.to_string().as_str()) { + bail!("repository {} is not configured for this instance", locator.repository); + } let profile = match arguments.profile.as_deref() { Some(profile) => config.profile(profile)?, - None if kind == "pr" => config.profile(&config.profile_selection.default_pr_profile)?, - None => config - .profiles - .iter() - .find(|profile| profile.has_tag("issue")) - .context("configuration has no Profile tagged issue")?, + None if kind == "pr" => { + config.pr_profile_for_repository(&locator.repository.to_string())? + } + None => config.issue_profile_for_repository(&locator.repository.to_string())?, }; + if config.profile_repository(profile) != locator.repository.to_string() { + bail!("Profile {:?} does not serve {}", profile.id, locator.repository); + } if !profile.has_tag(kind) { bail!("Profile {:?} is not tagged {kind}", profile.id); } - let client = GitHubClient::connect(&config.github, &locator.repository) + let client = GitHubClient::connect(config.github()?, &locator.repository) .await .context("GitHub Context is unavailable")?; let mut canonical = if kind == "issue" { @@ -34,7 +38,7 @@ pub async fn context(command: ContextCommand) -> Result<()> { ) }; let store = helpers::store(&config)?; - context::reconcile_local_state(&mut canonical, &store)?; + context::reconcile_local_state(&mut canonical, &store, Some(&client.identity().actor_node_id))?; let rendered = context::render( &canonical, profile.github_context_soft_ratio, diff --git a/src/cli/gh.rs b/src/cli/gh.rs index b79003ab..24e593df 100644 --- a/src/cli/gh.rs +++ b/src/cli/gh.rs @@ -6,8 +6,8 @@ pub async fn github(command: GitHubCommand) -> Result<()> { GitHubCommand::Probe(arguments) => github_probe(arguments).await, GitHubCommand::Webhook(arguments) => { let config = helpers::load(&arguments.resolve_config_path()?)?; - let repository = config.github.repository.parse::()?; - let client = GitHubClient::connect(&config.github, &repository).await?; + let repository = config.repository().parse::()?; + let client = GitHubClient::connect(config.github()?, &repository).await?; let webhook = client.app_webhook_config().await?; if arguments.json { helpers::print_json(&webhook)?; @@ -20,8 +20,8 @@ pub async fn github(command: GitHubCommand) -> Result<()> { } GitHubCommand::Deliveries(arguments) => { let config = helpers::load(&arguments.resolve_config_path()?)?; - let repository = config.github.repository.parse::()?; - let client = GitHubClient::connect(&config.github, &repository).await?; + let repository = config.repository().parse::()?; + let client = GitHubClient::connect(config.github()?, &repository).await?; let deliveries = client.app_deliveries().await?; if arguments.json { helpers::print_json(&deliveries)?; @@ -42,8 +42,8 @@ pub async fn github(command: GitHubCommand) -> Result<()> { GitHubCommand::Redeliver(arguments) => { let config_path = arguments.source.resolve_config_path()?; let config = helpers::load(&config_path)?; - let repository = config.github.repository.parse::()?; - let client = GitHubClient::connect(&config.github, &repository).await?; + let repository = config.repository().parse::()?; + let client = GitHubClient::connect(config.github()?, &repository).await?; client.redeliver(arguments.delivery_id).await?; println!("redelivery requested: {}", arguments.delivery_id); Ok(()) @@ -55,8 +55,9 @@ async fn github_probe(arguments: GitHubProbe) -> Result<()> { let config_path = arguments.source.resolve_config_path()?; let config = helpers::load(&config_path)?; let repository = arguments.repository.parse::()?; - let client = - GitHubClient::connect(&config.github, &repository).await.context("GitHub probe failed")?; + let client = GitHubClient::connect(config.github()?, &repository) + .await + .context("GitHub probe failed")?; if arguments.json { helpers::print_json(client.identity())?; } else { diff --git a/src/cli/gh_cmd.rs b/src/cli/gh_cmd.rs index 4bf10d2b..34967a54 100644 --- a/src/cli/gh_cmd.rs +++ b/src/cli/gh_cmd.rs @@ -1,8 +1,53 @@ #![allow(clippy::wildcard_imports)] use super::*; -pub async fn gh(command: GhCommand) -> Result<()> { +pub fn gh(command: GhCommand) -> Result<()> { match command { + GhCommand::Pr { command: GhPrCommand::Handoff(arguments) } => gh_handoff(arguments), + GhCommand::Pr { command: GhPrCommand::Read(arguments) } + | GhCommand::Issue { command: GhBodyCommand::Read(arguments) } => { + let config = helpers::load(&arguments.source.resolve_config_path()?)?; + let target = arguments.target.parse::()?; + // `cli::run` already executes on the `#[tokio::main]` runtime, so a + // nested `Runtime::new().block_on` panics; park this worker thread + // and drive the read on the existing runtime instead. + let snapshot = tokio::task::block_in_place(|| { + tokio::runtime::Handle::current().block_on(writer::read_for_edit(&config, &target)) + })?; + fs::write(&arguments.output, snapshot)?; + println!("canonical snapshot: {}", arguments.output.display()); + Ok(()) + } + GhCommand::Pr { command: GhPrCommand::Edit(arguments) } + | GhCommand::Issue { command: GhBodyCommand::Edit(arguments) } => { + let config = helpers::load(&arguments.source.resolve_config_path()?)?; + let actor = helpers::store(&config)?; + let receipt = writer::edit( + &config, + &actor, + writer::EditRequest { + invocation: arguments.invocation.resolve(), + target: arguments.target.parse()?, + profile_id: arguments.profile, + snapshot: fs::read_to_string(arguments.snapshot)?, + title: arguments.title, + body: arguments.body_file.map(fs::read_to_string).transpose()?, + request_id: arguments.request_id, + }, + )?; + print_gh_receipt(&receipt, arguments.json, &actor) + } + GhCommand::Status(arguments) => { + let config = helpers::load(&arguments.source.resolve_config_path()?)?; + if !arguments.request_id.starts_with("request-") { + bail!("expected a public request ID"); + } + let actor = helpers::store(&config)?; + let receipt = actor + .gh_write_receipt(arguments.request_id)? + .context("unknown publication request")?; + print_gh_receipt(&receipt, arguments.json, &actor) + } GhCommand::Comment { command: GhCommentCommand::Create(arguments) } => { let config_path = arguments.source.resolve_config_path()?; let config = helpers::load(&config_path)?; @@ -20,74 +65,96 @@ pub async fn gh(command: GhCommand) -> Result<()> { &config, &actor, CommentCreateRequest { + invocation: arguments.invocation.resolve(), target, profile_id: arguments.profile, body, request_id: arguments.request_id, }, - ) - .await?; - print_gh_receipt(&receipt, arguments.json) + )?; + print_gh_receipt(&receipt, arguments.json, &actor) } GhCommand::Pr { command: GhPrCommand::Ensure(arguments) } => { let config_path = arguments.source.resolve_config_path()?; let config = helpers::load(&config_path)?; let actor = helpers::store(&config)?; + let repository = match arguments.repository { + Some(repository) => repository.parse::()?, + None if config.is_multi_repository() => { + bail!("pr ensure requires --repository in a multi-repository instance") + } + None => config.repository().parse::()?, + }; let receipt = writer::ensure_pull_request( &config, &actor, - PullRequestEnsureRequest { comment_id: arguments.comment, head: arguments.head }, - ) - .await?; - if arguments.json { - helpers::print_json(&PullRequestEnsureResult { - operation: "pr_ensure", - state: &receipt.write.lifecycle, - stage: &receipt.stage, - implementation_request_comment: receipt.comment_database_id, - issue: format!("{}#{}", receipt.write.repository, receipt.issue_number), - base: &receipt.base_ref, - head: &receipt.head_ref, - profile: &receipt.pr_profile_id, - pull_request: receipt - .pull_request_number - .map(|number| format!("{}#{number}", receipt.write.repository)), - error: receipt.write.last_error.as_deref(), - })?; - } else { - println!("state: {} / {}", receipt.write.lifecycle, receipt.stage); - println!("Implementation Request: {}", receipt.write.target); - println!("head: {}", receipt.head_ref); - if let Some(number) = receipt.pull_request_number { - println!("PR: {}#{number}", receipt.write.repository); - } - println!("PR Profile: {}", receipt.pr_profile_id); - } - Ok(()) + PullRequestEnsureRequest { + invocation: arguments.invocation.resolve(), + repository, + comment_id: arguments.comment, + head: arguments.head, + }, + )?; + print_gh_receipt(&receipt, arguments.json, &actor) } } } -fn print_gh_receipt(receipt: &crate::store::GhWriteReceipt, json: bool) -> Result<()> { +fn print_gh_receipt( + receipt: &crate::store::GhWriteReceipt, + json: bool, + store: &crate::store::StoreActor, +) -> Result<()> { + let plan = store.implementation_request_receipt(receipt.intent_id.clone())?; if json { helpers::print_json(&CommentWriteResult { + request_id: &receipt.request_id, operation: &receipt.operation, - state: &receipt.lifecycle, + stage: plan.as_ref().map(|plan| plan.stage.as_str()), + activation: plan.as_ref().map(|plan| activation_delivery(plan)), + implementation_request: plan.as_ref().map(|plan| plan.root_request_id.as_str()), + head: plan.as_ref().map(|plan| plan.head_ref.as_str()), + base: plan.as_ref().map(|plan| plan.base_ref.as_str()), + pull_request: plan + .as_ref() + .and_then(|plan| plan.pull_request_number) + .map(|number| format!("https://github.com/{}/pull/{number}", receipt.repository)), + state: if receipt.lifecycle == "pending" { "queued" } else { &receipt.lifecycle }, target: &receipt.target, profile: &receipt.profile_id, role: &receipt.role, comment: receipt .remote_database_id .as_ref() + .filter(|_| receipt.operation == "comment_create") .map(|id| format!("{}#issuecomment-{id}", receipt.repository)), error: receipt.last_error.as_deref(), })?; } else { + println!("request ID: {}", receipt.request_id); + println!("query: braid gh status {}", receipt.request_id); println!("operation: {}", receipt.operation); - println!("state: {}", receipt.lifecycle); + println!( + "state: {}", + if receipt.lifecycle == "pending" { "queued" } else { &receipt.lifecycle } + ); println!("target: {}", receipt.target); println!("Profile: {} ({})", receipt.profile_id, receipt.role); - if let Some(id) = &receipt.remote_database_id { + if let Some(plan) = &plan { + println!("stage: {}", plan.stage); + println!("implementation request: {}", plan.root_request_id); + println!( + "activation delivery: {} (not execution completion)", + activation_delivery(plan) + ); + println!("head: {} / base: {}", plan.head_ref, plan.base_ref); + if let Some(number) = plan.pull_request_number { + println!("PR: https://github.com/{}/pull/{number}", receipt.repository); + } + } + if receipt.operation == "comment_create" + && let Some(id) = &receipt.remote_database_id + { println!("GitHub comment: {}#issuecomment-{id}", receipt.repository); } if let Some(error) = &receipt.last_error { @@ -96,3 +163,28 @@ fn print_gh_receipt(receipt: &crate::store::GhWriteReceipt, json: bool) -> Resul } Ok(()) } + +fn activation_delivery(plan: &crate::store::ImplementationRequestReceipt) -> &'static str { + if plan.activation_delivered { + "delivered" + } else if plan.write.lifecycle == "applied" { + "missing_requires_explicit_activation" + } else { + "pending" + } +} + +fn gh_handoff(arguments: GhPrHandoff) -> Result<()> { + let config = helpers::load(&arguments.source.resolve_config_path()?)?; + let actor = helpers::store(&config)?; + let receipt = writer::handoff( + &config, + &actor, + &writer::HandoffRequest { + invocation: writer::Invocation::Agent(arguments.source_turn), + target: arguments.target.parse()?, + request_id: arguments.request_id, + }, + )?; + print_gh_receipt(&receipt, arguments.json, &actor) +} diff --git a/src/cli/mod.rs b/src/cli/mod.rs index f5e1a8bd..0d69db7e 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -20,6 +20,7 @@ use crate::{ writer::{self, CommentCreateRequest, PullRequestEnsureRequest}, }; +mod assignment; mod config; mod context_cmd; mod doctor_cmd; @@ -28,11 +29,12 @@ mod gh_cmd; mod helpers; mod migrate; mod profile; +mod provider_cmd; mod status; mod telemetry_cmd; #[derive(Debug, Parser)] -#[command(name = "braid", version, about = "GitHub working memory for local coding agents")] +#[command(name = "braid", version, about = "Collaboration working memory for coding agents")] pub struct Cli { #[command(subcommand)] command: Command, @@ -41,6 +43,15 @@ pub struct Cli { #[derive(Debug, Subcommand)] enum Command { Setup(SetupArguments), + Object(ObjectArguments), + /// Built-in collaboration platform, independent of the Agent Harness. + Platform(crate::platform::cli::PlatformArguments), + /// Initialize a Braid-owned collaboration space around a local Git checkout. + Init(crate::local::init::InitArguments), + Assignment { + #[command(subcommand)] + command: AssignmentCommand, + }, Config { #[command(subcommand)] command: ConfigCommand, @@ -49,6 +60,10 @@ enum Command { #[command(subcommand)] command: ProfileCommand, }, + Provider { + #[command(subcommand)] + command: ProviderCommand, + }, Migrate { #[command(subcommand)] command: MigrateCommand, @@ -76,6 +91,43 @@ enum Command { command: TunnelCommand, }, Serve(ServeArguments), + /// Complete one root task using the built-in collaboration platform. + Run(RunArguments), + /// Local OTLP collector, browser Console, and optional managed runtime. + Console(crate::console::ConsoleArgs), +} + +#[derive(Debug, Args)] +struct ObjectArguments { + #[command(flatten)] + source: ConfigSource, + /// Reuse the original identity when recovering an uncertain object command. + #[arg(long, global = true)] + request_id: Option, + /// Reject a mutation when the platform object has changed since this revision. + #[arg(long, global = true)] + expected_revision: Option, + #[command(subcommand)] + command: crate::local::cli::LocalCommand, +} + +#[derive(Debug, Subcommand)] +enum AssignmentCommand { + Reactivate(AssignmentReactivate), +} + +#[derive(Debug, Args)] +struct AssignmentReactivate { + #[arg(value_name = "NUMBER")] + number: u64, + #[command(flatten)] + source: ConfigSource, + #[arg(long, value_name = "OWNER/REPOSITORY")] + repository: Option, + #[arg(long, value_name = "issue|pr", default_value = "issue", value_parser = ["issue", "pr"])] + kind: String, + #[arg(long, value_name = "TEXT")] + reason: Option, } #[derive(Debug, Subcommand)] @@ -88,6 +140,11 @@ enum ProfileCommand { Inspect(ProfileInspect), } +#[derive(Debug, Subcommand)] +enum ProviderCommand { + ImportAuth(provider_cmd::ProviderImportAuth), +} + #[derive(Debug, Subcommand)] enum MigrateCommand { Plan(ConfigPath), @@ -120,6 +177,7 @@ enum GitHubCommand { #[derive(Debug, Subcommand)] enum GhCommand { + Status(GhWriteStatus), Comment { #[command(subcommand)] command: GhCommentCommand, @@ -128,6 +186,19 @@ enum GhCommand { #[command(subcommand)] command: GhPrCommand, }, + Issue { + #[command(subcommand)] + command: GhBodyCommand, + }, +} + +#[derive(Debug, Args)] +struct GhWriteStatus { + request_id: String, + #[command(flatten)] + source: ConfigSource, + #[arg(long)] + json: bool, } #[derive(Debug, Subcommand)] @@ -138,6 +209,75 @@ enum GhCommentCommand { #[derive(Debug, Subcommand)] enum GhPrCommand { Ensure(GhPrEnsure), + Handoff(GhPrHandoff), + Read(GhBodyRead), + Edit(GhBodyEdit), +} + +#[derive(Debug, Subcommand)] +enum GhBodyCommand { + Read(GhBodyRead), + Edit(GhBodyEdit), +} + +#[derive(Debug, Args)] +#[group(required = true, multiple = false)] +struct GhInvocation { + /// Turn reference supplied by the Braid runtime prompt (verified against durable state and cwd). + #[arg(long)] + source_turn: Option, + /// Explicit audited human entry; unavailable inside Agent runtime worktrees. + #[arg(long)] + operator: bool, +} +impl GhInvocation { + fn resolve(self) -> writer::Invocation { + self.source_turn.map_or(writer::Invocation::Operator, writer::Invocation::Agent) + } +} + +#[derive(Debug, Args)] +struct GhPrHandoff { + target: String, + #[command(flatten)] + source: ConfigSource, + #[arg(long)] + source_turn: String, + #[arg(long)] + request_id: String, + #[arg(long)] + json: bool, +} + +#[derive(Debug, Args)] +struct GhBodyRead { + target: String, + #[command(flatten)] + source: ConfigSource, + /// Save the canonical snapshot for a later edit. + #[arg(long)] + output: PathBuf, +} + +#[derive(Debug, Args)] +struct GhBodyEdit { + target: String, + #[command(flatten)] + source: ConfigSource, + #[command(flatten)] + invocation: GhInvocation, + #[arg(long)] + profile: String, + #[arg(long)] + snapshot: PathBuf, + #[arg(long)] + title: Option, + #[arg(long)] + body_file: Option, + #[arg(long)] + request_id: String, + #[arg(long)] + json: bool, } /// Shared config source: exact `--config ` or registry lookup via @@ -145,7 +285,7 @@ enum GhPrCommand { /// this struct. #[derive(Debug, Args)] struct ConfigSource { - #[arg(long, value_name = "PATH")] + #[arg(long, value_name = "PATH", env = "BRAID_CONFIG")] config: Option, #[arg(long, value_name = "KEY", env = "BRAID_INSTANCE")] instance: Option, @@ -245,6 +385,8 @@ struct GitHubRedeliver { #[derive(Debug, Args)] struct GhCommentCreate { + #[command(flatten)] + invocation: GhInvocation, #[arg(value_name = "OWNER/REPOSITORY#NUMBER")] target: String, #[command(flatten)] @@ -263,10 +405,14 @@ struct GhCommentCreate { #[derive(Debug, Args)] struct GhPrEnsure { + #[command(flatten)] + invocation: GhInvocation, #[arg(long, value_name = "ISSUE_COMMENT_ID")] comment: u64, #[command(flatten)] source: ConfigSource, + #[arg(long, value_name = "OWNER/REPOSITORY")] + repository: Option, #[arg(long, value_name = "BRANCH")] head: Option, #[arg(long)] @@ -277,18 +423,35 @@ struct GhPrEnsure { pub(crate) struct SetupArguments { #[arg(value_name = "OWNER/REPOSITORY")] pub(crate) repository: String, - #[arg(long, value_name = "pi|codex", default_value = "pi", value_parser = ["pi", "codex"])] - pub(crate) provider: String, - #[arg(long, value_name = "MODEL", default_value = "deepseek-chat")] - pub(crate) model: String, - #[arg(long, value_name = "ENV", default_value = "DEEPSEEK_API_KEY")] - pub(crate) api_key_environment: String, + /// Agent runtime adapter to discover or verify. This does not select an LLM provider. + #[arg(long, value_name = "pi|codex", value_parser = ["pi", "codex"])] + pub(crate) adapter: String, + #[arg(long, value_name = "MODEL")] + pub(crate) model: Option, + /// Optional reasoning/thinking level for runtimes that support one. + #[arg(long, value_name = "LEVEL")] + pub(crate) reasoning: Option, + /// Pi-only LLM provider catalog id; Braid does not infer one from the adapter. + #[arg(long, value_name = "ID")] + pub(crate) llm_provider: Option, + /// Pi-only credential kind for the selected LLM provider. + #[arg(long, value_name = "api_key|oauth|none", value_parser = ["api_key", "oauth", "none"])] + pub(crate) llm_credential_kind: Option, + /// Pi-only Braid-schema credential file; required unless kind is `none`. + #[arg(long, value_name = "PATH")] + pub(crate) llm_credential_file: Option, + /// Pi-only provider endpoint rendered into models.json. + #[arg(long, value_name = "URL")] + pub(crate) llm_base_url: Option, #[arg(long, value_name = "KEY", env = "BRAID_INSTANCE")] pub(crate) instance: Option, #[arg(long, value_name = "DIR", env = "BRAID_USER_HOME", default_value = "~/.braid")] pub(crate) user_home: PathBuf, #[arg(long, value_name = "PATH")] pub(crate) runtime_executable: Option, + /// Complete a prior `--no-browser` setup from the GitHub redirect URL. + #[arg(long, value_name = "URL", conflicts_with = "no_browser")] + pub(crate) callback_url: Option, #[arg( long, help = "Skip opening a browser; print manifest values and manual instructions instead" @@ -305,10 +468,27 @@ struct ServeArguments { help = "Expose ingress through a free Wrangler Quick Tunnel and own the App webhook while running" )] tunnel: bool, - #[arg(long, help = "Run GitHub transport without starting the configured Coding Agent")] + #[arg(long, help = "Run collaboration transport without starting the configured Coding Agent")] transport_only: bool, } +#[derive(Debug, Args)] +struct RunArguments { + #[command(flatten)] + source: ConfigSource, + #[arg(long)] + run_id: String, + #[arg(long, conflicts_with = "description_file", required_unless_present = "description_file")] + root_issue: Option, + #[arg(long, conflicts_with = "root_issue", required_unless_present = "root_issue")] + description_file: Option, + #[arg(long)] + delivery_ref: String, + /// Maximum simultaneously active Braid turns, including the root (not a process limit). + #[arg(long, default_value_t = 2)] + max_concurrency: usize, +} + #[derive(Debug, Serialize)] struct ContextReport<'a> { target: &'a WorkItemLocator, @@ -319,6 +499,13 @@ struct ContextReport<'a> { #[derive(Debug, Serialize)] struct CommentWriteResult<'a> { + request_id: &'a str, + stage: Option<&'a str>, + activation: Option<&'static str>, + implementation_request: Option<&'a str>, + head: Option<&'a str>, + base: Option<&'a str>, + pull_request: Option, operation: &'a str, state: &'a str, target: &'a str, @@ -328,26 +515,12 @@ struct CommentWriteResult<'a> { error: Option<&'a str>, } -#[derive(Debug, Serialize)] -struct PullRequestEnsureResult<'a> { - operation: &'static str, - state: &'a str, - stage: &'a str, - implementation_request_comment: u64, - issue: String, - base: &'a str, - head: &'a str, - profile: &'a str, - pull_request: Option, - error: Option<&'a str>, -} - #[derive(Debug, Serialize)] struct LocalStatus<'a> { binary_version: &'static str, config_schema: u32, instance_key: &'a str, - repository: &'a str, + repository: String, default_pr_profile: &'a str, database: StoreStatus, telemetry_endpoint: String, @@ -358,12 +531,18 @@ struct LocalStatus<'a> { pub async fn run() -> Result<()> { match Cli::parse().command { + Command::Assignment { command: AssignmentCommand::Reactivate(arguments) } => { + assignment::reactivate(arguments)?; + } Command::Config { command: ConfigCommand::Check(arguments) } => { config::config_check(&arguments)?; } Command::Profile { command: ProfileCommand::Inspect(arguments) } => { profile::profile_inspect(&arguments)?; } + Command::Provider { command: ProviderCommand::ImportAuth(arguments) } => { + provider_cmd::import_auth(&arguments)?; + } Command::Migrate { command } => migrate::migrate(command)?, Command::Status(arguments) => { status::status(&arguments)?; @@ -373,7 +552,7 @@ pub async fn run() -> Result<()> { } Command::Context { command } => Box::pin(context_cmd::context(command)).await?, Command::Github { command } => gh::github(command).await?, - Command::Gh { command } => Box::pin(gh_cmd::gh(command)).await?, + Command::Gh { command } => gh_cmd::gh(command)?, Command::Telemetry { command: TelemetryCommand::Probe(arguments) } => { telemetry_cmd::telemetry_probe(arguments).await?; } @@ -385,6 +564,51 @@ pub async fn run() -> Result<()> { let config = helpers::load(&config_path)?; crate::runtime::serve(config, arguments.tunnel, !arguments.transport_only).await?; } + Command::Run(arguments) => { + let config = helpers::load(&arguments.source.resolve_config_path()?)?; + let request = crate::run::RunRequest { + run_id: arguments.run_id, + root_issue: arguments.root_issue, + description: arguments.description_file.map(fs::read_to_string).transpose()?, + delivery_ref: arguments.delivery_ref, + max_concurrency: arguments.max_concurrency, + }; + request.validate(&config)?; + let telemetry = crate::telemetry::TelemetryGuard::install( + &config.telemetry, + config.instance_key(), + )?; + let generation = uuid::Uuid::now_v7().to_string(); + crate::telemetry::set_runtime_generation(Some(generation)); + let health = crate::health::Health::new(crate::runtime::initial_health(&config, true)); + let (stop, shutdown) = tokio::sync::watch::channel(false); + let mut runtime = Box::pin(crate::run::run_managed(config, request, shutdown, health)); + let result = tokio::select! {result=&mut runtime=>result, signal=crate::runtime::wait_for_shutdown_signal()=> {let _=stop.send(true);signal?;runtime.await}}; + crate::telemetry::set_runtime_generation(None); + telemetry.shutdown()?; + let result = result?; + println!("{}", serde_json::to_string_pretty(&result)?); + if result.state != crate::run::RunState::Completed { + bail!( + "finite run ended as {:?}: {}", + result.state, + result.reason.as_deref().unwrap_or("no detail") + ); + } + } + Command::Init(arguments) => crate::local::init::run(arguments).await?, + Command::Object(arguments) => { + let config = helpers::load(&arguments.source.resolve_config_path()?)?; + crate::local::cli::run_options( + arguments.command, + &config, + arguments.request_id, + arguments.expected_revision, + ) + .await?; + } + Command::Platform(arguments) => crate::platform::cli::run(arguments).await?, + Command::Console(arguments) => crate::console::serve(arguments).await?, Command::Setup(arguments) => { setup::run(arguments).await?; } diff --git a/src/cli/profile.rs b/src/cli/profile.rs index d9fa2394..2d78d964 100644 --- a/src/cli/profile.rs +++ b/src/cli/profile.rs @@ -5,15 +5,49 @@ pub fn profile_inspect(arguments: &ProfileInspect) -> Result<()> { let config_path = arguments.source.resolve_config_path()?; let config = helpers::load(&config_path)?; let profile = config.profile(&arguments.profile)?; + let materials = config.profile_materials(profile)?; if arguments.json { - helpers::print_json(profile)?; + let mut value = serde_json::to_value(profile)?; + value["effective_materials"] = serde_json::to_value(&materials)?; + helpers::print_json(&value)?; } else { println!("profile: {} ({})", profile.id, profile.display_name); println!("tags: {}", profile.tags.join(", ")); - println!("provider: {}", profile.provider); + println!("repository: {}", config.profile_repository(profile)); + let provider = if profile.adapter_type == "pi" { + profile.provider.as_deref().unwrap_or("missing") + } else { + "adapter-managed" + }; + println!("provider: {provider}"); + if profile.adapter_type == "pi" + && let Some(provider_id) = profile.provider.as_deref() + && let Ok(llm) = config.llm_provider_for(provider_id) + { + let credential = llm.resolved_credential(); + println!("credential: {:?}", credential.kind); + } println!("model: {}", profile.model.as_deref().unwrap_or("provider default")); println!("reasoning: {}", profile.reasoning.as_deref().unwrap_or("provider default")); println!("workspace: {}", profile.workspace().display()); + println!("effective materials: {}", materials.digest); + println!("profile revision: {}", materials.revision); + let source = match materials.source.as_deref() { + Some("profile_template") => "profile_template (settings/agents)", + Some("runtime_home") => "runtime_home (settings/agents)", + Some(other) => other, + None => "none", + }; + println!("native material source: {source}"); + if profile.adapter_type == "pi" && config.schema_version != 2 { + println!("models.json: derived from llm_providers declarations"); + } + for (path, digest) in &materials.files { + println!("native material: {path} sha256={digest}"); + } + for skill in &materials.skills { + println!("skill: {} sha256={}", skill.name, skill.digest); + } println!("status surfaces: {}", profile.status_surfaces.join(", ")); println!( "context budget: {:.0}% / {} bytes hard", diff --git a/src/cli/provider_cmd.rs b/src/cli/provider_cmd.rs new file mode 100644 index 00000000..e9e0e52d --- /dev/null +++ b/src/cli/provider_cmd.rs @@ -0,0 +1,169 @@ +//! One-shot conversion of Pi-native `auth.json` credentials into Braid's +//! 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::{ + fs::OpenOptions, + io::Write as _, + path::{Path, PathBuf}, +}; + +use anyhow::{Context as _, Result, bail}; +use clap::Args; + +use crate::config::{OAuthCredentialFile, ProviderSecretFile, validate_token}; +use crate::home::UserHome; + +#[derive(Debug, Args)] +pub(crate) struct ProviderImportAuth { + /// LLM provider id whose credential is imported. + #[arg(value_name = "PROVIDER_ID")] + provider_id: String, + /// Pi-native auth.json to convert from. + #[arg(long, value_name = "PATH")] + from: PathBuf, + #[arg(long, value_name = "DIR", env = "BRAID_USER_HOME", default_value = "~/.braid")] + user_home: PathBuf, + /// Overwrite an existing Braid credential file. + #[arg(long)] + force: bool, +} + +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)?; + + let target_dir = user_home.secrets_dir(); + std::fs::create_dir_all(&target_dir) + .with_context(|| format!("cannot create secrets directory {}", target_dir.display()))?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt as _; + let mut permissions = std::fs::metadata(&target_dir)?.permissions(); + permissions.set_mode(0o700); + std::fs::set_permissions(&target_dir, permissions)?; + } + let target = target_dir.join(format!("{}.toml", arguments.provider_id)); + if target.exists() && !arguments.force { + bail!( + "Braid credential file {} already exists; pass --force to overwrite it", + target.display() + ); + } + let mut options = OpenOptions::new(); + options.write(true).create(true).create_new(!arguments.force).truncate(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt as _; + options.mode(0o600); + } + let mut file = options + .open(&target) + .with_context(|| format!("cannot write Braid credential file {}", target.display()))?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt as _; + file.set_permissions(std::fs::Permissions::from_mode(0o600))?; + } + file.write_all(rendered.as_bytes())?; + file.sync_all()?; + + println!( + "Imported {:?} {} credential from {}\nWrote Braid credential file: {}\nReference it as: credential = {{ kind = \"{}\", file = \"{}\" }}", + arguments.provider_id, + kind_label, + from.display(), + target.display(), + kind_label, + target.display() + ); + Ok(()) +} + +fn convert_credential(from: &Path, provider_id: &str) -> Result<(String, &'static str)> { + let bytes = std::fs::read(from) + .with_context(|| format!("cannot read Pi auth.json {}", from.display()))?; + let document: serde_json::Value = serde_json::from_slice(&bytes) + .with_context(|| format!("cannot parse Pi auth.json {}", from.display()))?; + let credentials = document + .as_object() + .with_context(|| format!("Pi auth.json {} must contain a provider map", from.display()))?; + let entry = credentials.get(provider_id).ok_or_else(|| { + let available = credentials.keys().cloned().collect::>().join(", "); + anyhow::anyhow!( + "Pi auth.json {} has no credential for {provider_id:?} (available: {})", + from.display(), + if available.is_empty() { "none".to_owned() } else { available } + ) + })?; + let kind = entry.get("type").and_then(serde_json::Value::as_str).ok_or_else(|| { + anyhow::anyhow!("credential {provider_id:?} in {} has no type", from.display()) + })?; + + match kind { + "oauth" => convert_oauth(entry, from, provider_id), + "api_key" => convert_api_key(entry, from, provider_id), + other => { + bail!("unsupported credential type {other:?} for {provider_id:?} in {}", from.display()) + } + } +} + +fn convert_oauth( + entry: &serde_json::Value, + from: &Path, + provider_id: &str, +) -> Result<(String, &'static str)> { + let access = required_string(entry, "access")?; + let refresh = required_string(entry, "refresh")?; + let expires = entry.get("expires").and_then(serde_json::Value::as_u64).ok_or_else(|| { + anyhow::anyhow!( + "credential {provider_id:?} in {} requires numeric expires (epoch milliseconds)", + from.display() + ) + })?; + let account = entry.get("account").and_then(serde_json::Value::as_str); + for field in entry.as_object().expect("credential object").keys() { + if !matches!(field.as_str(), "type" | "access" | "refresh" | "expires" | "account") { + eprintln!( + "warning: dropping provider-specific OAuth field {field:?} from {provider_id:?}; Braid keeps only access/refresh/expires/account" + ); + } + } + let oauth = + OAuthCredentialFile { access, refresh, expires, account: account.map(str::to_owned) }; + Ok((toml::to_string(&oauth)?, "oauth")) +} + +fn convert_api_key( + entry: &serde_json::Value, + from: &Path, + provider_id: &str, +) -> Result<(String, &'static str)> { + let key = entry.get("key").and_then(serde_json::Value::as_str).ok_or_else(|| { + anyhow::anyhow!("api_key credential {provider_id:?} in {} has no key", from.display()) + })?; + if key.trim().is_empty() { + bail!("api_key credential {provider_id:?} in {} is empty", from.display()); + } + Ok((toml::to_string(&ProviderSecretFile { provider_api_key: key.into() })?, "api_key")) +} + +fn required_string(entry: &serde_json::Value, field: &str) -> Result { + let value = entry + .get(field) + .and_then(serde_json::Value::as_str) + .with_context(|| format!("OAuth credential requires string field {field:?}"))?; + if value.trim().is_empty() { + bail!("OAuth credential field {field:?} must not be empty"); + } + Ok(value.to_owned()) +} diff --git a/src/cli/status.rs b/src/cli/status.rs index 467f77f9..665f9dfb 100644 --- a/src/cli/status.rs +++ b/src/cli/status.rs @@ -3,17 +3,15 @@ use super::*; pub fn status(arguments: &ConfigPath) -> Result<()> { let config = helpers::load(&arguments.resolve_config_path()?)?; - let database = helpers::store(&config)?.status()?; - let transport = if database.pending_migrations == 0 { - Some(helpers::store(&config)?.runtime_status()?) - } else { - None - }; + let store = helpers::store(&config)?; + let database = store.status()?; + let transport = + if database.pending_migrations == 0 { Some(store.runtime_status()?) } else { None }; let status = LocalStatus { binary_version: env!("CARGO_PKG_VERSION"), config_schema: config.schema_version, instance_key: &config.instance.key, - repository: &config.github.repository, + repository: config.repositories().join(", "), default_pr_profile: &config.profile_selection.default_pr_profile, database, telemetry_endpoint: config.telemetry.endpoint.to_string(), @@ -26,7 +24,7 @@ pub fn status(arguments: &ConfigPath) -> Result<()> { } else { println!("braid {}", status.binary_version); println!("instance: {}", status.instance_key); - println!("repository: {}", status.repository); + println!("repositories: {}", status.repository); println!( "database schema: {}/{} ({} pending)", status.database.schema_version, @@ -46,6 +44,36 @@ pub fn status(arguments: &ConfigPath) -> Result<()> { transport.uncertain_writes, transport.context_resets.len() ); + println!( + "scheduler: durable-eligible={} (provider availability unknown; runnable is a raw lifecycle count)", + transport.durable_eligible_batches + ); + for batch in &transport.batches { + println!( + " {}#{} {}: {}", + batch.repository, + batch.work_item_number, + batch.lifecycle, + batch + .scheduler + .ineligible_reason + .unwrap_or("durable_eligible_provider_unknown") + ); + if let Some(error) = &batch.input_error { + println!(" waiting for complete input: {error}"); + } + } + for group in &transport.agent_groups { + println!( + " {}#{} generation={} {} assignment={} session={}", + group.work_item_kind, + group.work_item_number, + group.assignment_generation, + if group.current_generation { "current" } else { "historical" }, + group.assignment_lifecycle, + group.session_lifecycle.as_deref().unwrap_or("none") + ); + } } } Ok(()) diff --git a/src/cli/telemetry_cmd.rs b/src/cli/telemetry_cmd.rs index 8324c178..1cad008c 100644 --- a/src/cli/telemetry_cmd.rs +++ b/src/cli/telemetry_cmd.rs @@ -16,6 +16,14 @@ pub async fn telemetry_probe(arguments: TelemetryProbe) -> Result<()> { println!("sampled: {}", result.sampled); println!("payload emitted: {}", result.payload_emitted); println!("OTLP endpoint: {}", result.exporter.endpoint); + println!("trace ID: {}", result.trace_id); + for signal in &result.signals { + println!( + "{} {}: SDK batches successful={}, failed={} (not a persistence acknowledgement)", + signal.signal, signal.endpoint, signal.successful_batches, signal.failed_batches + ); + } + println!("Verify logs/traces/metrics in the backend; see docs/40-deployment/README.md."); } Ok(()) } diff --git a/src/collaboration.rs b/src/collaboration.rs new file mode 100644 index 00000000..509c3146 --- /dev/null +++ b/src/collaboration.rs @@ -0,0 +1,99 @@ +//! Canonical collaboration state, independent of the provider session transport. +use std::sync::Arc; + +use anyhow::Result; + +use crate::{ + builtin::BuiltinClient, + context::{self, Actor, CanonicalContext, IssueSnapshot, PullRequestSnapshot}, + github::{GitHubClient, WorkItemLocator}, +}; + +pub(crate) enum CollaborationBackend { + GitHub(Arc), + Builtin(Arc), +} + +impl CollaborationBackend { + pub(crate) fn is_builtin(&self) -> bool { + matches!(self, Self::Builtin(_)) + } + + pub(crate) fn github_app_actor_node_id(&self) -> Option<&str> { + match self { + Self::GitHub(github) => Some(&github.identity().actor_node_id), + Self::Builtin(_) => None, + } + } + + pub(crate) async fn materialize_issue( + &self, + locator: &WorkItemLocator, + ) -> Result { + match self { + Self::GitHub(github) => { + Ok(Box::pin(context::materialize_issue(github, locator, 100)).await?) + } + Self::Builtin(client) => match client.context(locator.number).await? { + CanonicalContext::Issue(issue) => Ok(issue), + CanonicalContext::PullRequest(_) => { + anyhow::bail!("built-in item #{} is not an Issue", locator.number) + } + }, + } + } + + pub(crate) async fn materialize_pull_request( + &self, + locator: &WorkItemLocator, + ) -> Result { + match self { + Self::GitHub(github) => { + Ok(Box::pin(context::materialize_pull_request(github, locator, 100)).await?) + } + Self::Builtin(client) => match client.context(locator.number).await? { + CanonicalContext::PullRequest(pr) => Ok(pr), + CanonicalContext::Issue(_) => { + anyhow::bail!("built-in item #{} is not a PR", locator.number) + } + }, + } + } + + /// Built-in PR generations start from the authority's frozen candidate commit. + pub(crate) async fn pr_worktree_ref(&self, number: u64, head_ref: &str) -> Result { + match self { + Self::GitHub(_) => Ok(head_ref.to_owned()), + Self::Builtin(client) => client.candidate(number).await, + } + } + pub(crate) fn bind_execution(&self, turn_id: &str) -> Result<()> { + match self { + Self::GitHub(_) => Ok(()), + Self::Builtin(client) => client.bind_execution(turn_id), + } + } + pub(crate) async fn fence_session(&self, session_id: &str) -> Result<()> { + match self { + Self::GitHub(_) => Ok(()), + Self::Builtin(client) => client.fence_session(session_id).await, + } + } + + pub(crate) async fn default_branch(&self) -> Result { + match self { + Self::GitHub(github) => Ok(github.repository_details().await?.default_branch), + Self::Builtin(client) => client.default_branch().await, + } + } + + pub(crate) fn assignee_matches(&self, actor: &Actor, profile_id: &str) -> bool { + match self { + Self::GitHub(github) => { + actor.node_id == github.identity().actor_node_id + || actor.login == github.identity().actor_login + } + Self::Builtin(_) => actor.login == profile_id, + } + } +} diff --git a/src/config.rs b/src/config.rs index d5164d04..68e8e77a 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,5 +1,5 @@ use std::{ - collections::HashSet, + collections::{HashMap, HashSet}, fs, net::SocketAddr, path::{Path, PathBuf}, @@ -11,7 +11,10 @@ use url::Url; use crate::home::validate_instance_key; -pub const CONFIG_SCHEMA_VERSION: u32 = 2; +pub const CONFIG_SCHEMA_VERSION: u32 = 3; +/// Process-local credential injection for one Pi provider. Users configure only +/// the secret file; native materials reference this fixed name. +pub const PROVIDER_API_KEY_ENVIRONMENT: &str = "BRAID_PROVIDER_API_KEY"; #[derive(Debug, Error)] pub enum ConfigError { @@ -32,16 +35,26 @@ pub struct InstanceConfig { #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct Config { + #[serde(skip)] + pub(crate) finite_run: Option, pub schema_version: u32, pub instance: InstanceConfig, pub runtime: RuntimeConfig, - pub github: GitHubConfig, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub github: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub local: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub builtin: Option, + #[serde(skip)] + pub loaded_from: PathBuf, pub scheduler: SchedulerConfig, /// Adapter connectivity, keyed by `adapter_type`. One entry per `adapter_type` /// per worker; the profile's `adapter_type` locates the runtime entry. pub runtimes: Vec, - /// LLM provider catalogue. Profiles reference an entry by id; enforcement is - /// outside the scope of this pass. + /// LLM provider catalogue. Only Pi profiles reference these entries; Codex + /// configurations may omit the catalogue entirely. + #[serde(default)] pub llm_providers: Vec, pub tools: ToolConfig, pub server: ServerConfig, @@ -131,6 +144,9 @@ impl RuntimeConfig { #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct RuntimeEntry { + /// Braid Pi material package manifest; absent for an external base Pi. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub native_runtime: Option, pub adapter_type: String, /// Contract version checked at setup and serve time. pub version: String, @@ -148,31 +164,171 @@ pub struct RuntimeEntry { pub experimental_schema_sha256: Option, } +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)] +pub enum CredentialKind { + #[serde(rename = "api_key")] + ApiKey, + #[serde(rename = "oauth")] + OAuth, + #[serde(rename = "none")] + None, +} + +/// Credential reference for one LLM provider. The referenced file is Braid +/// schema (never a runtime-native file); adapters convert it at +/// materialization time. +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct ProviderCredential { + pub kind: CredentialKind, + /// Required for `api_key` and `oauth`; must be absent for `none`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub file: Option, +} + +impl ProviderCredential { + pub fn none() -> Self { + Self { kind: CredentialKind::None, file: None } + } + + pub fn load(&self) -> Result { + match self.kind { + CredentialKind::None => { + if self.file.is_some() { + return Err(ConfigError::Invalid( + "credential kind \"none\" must not reference a file".into(), + )); + } + Ok(LoadedCredential::None) + } + CredentialKind::ApiKey => { + let file = self.file.as_ref().ok_or_else(|| { + ConfigError::Invalid("credential kind \"api_key\" requires a file".into()) + })?; + Ok(LoadedCredential::ApiKey(load_provider_secret_file(file)?)) + } + CredentialKind::OAuth => { + let file = self.file.as_ref().ok_or_else(|| { + ConfigError::Invalid("credential kind \"oauth\" requires a file".into()) + })?; + Ok(LoadedCredential::OAuth(load_oauth_file(file)?)) + } + } + } +} + +pub enum LoadedCredential { + ApiKey(String), + OAuth(OAuthCredentialFile), + None, +} + +/// Braid-schema OAuth token set for one provider (no refresh lifecycle: +/// the operator replaces the file explicitly). +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct OAuthCredentialFile { + pub access: String, + pub refresh: String, + /// Expiry as epoch milliseconds, matching the provider's token record. + pub expires: u64, + /// Optional diagnostic account label; never required for rendering. + #[serde(default)] + pub account: Option, +} + #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct LlmProvider { pub id: String, - pub protocol: String, - #[serde(default)] - pub api_key_environment: Option, - #[serde(default)] + /// Explicit credential for this provider. Schema 3 requires it; schema 2 + /// may omit it and rely on the legacy `api_key_file` fallback instead. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub credential: Option, + /// Provider endpoint rendered into Pi's models.json by the adapter. + /// Required for providers referenced by a schema-3 Pi Profile. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub base_url: Option, + /// Wire API name rendered into Pi's models.json (e.g. openai-completions). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub api: Option, + /// Legacy schema-2 metadata. Pi's native models.json owns wire routing. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub protocol: Option, + /// Legacy schema-2 API key reference; schema 3 requires `credential`. + #[serde(default, skip_serializing_if = "Option::is_none")] pub api_key_file: Option, - #[serde(default)] + /// Declared models rendered into Pi's models.json by the adapter. + #[serde(default, skip_serializing_if = "Vec::is_empty")] pub models: Vec, - #[serde(default)] + /// Legacy schema-2 allowance metadata; Braid does not consume it. + #[serde(default, skip_serializing_if = "Vec::is_empty")] pub allowances: Vec, } -#[derive(Debug, Clone, Deserialize, Serialize)] +impl LlmProvider { + /// The credential this provider uses at runtime: the explicit + /// `credential` entry, or the legacy schema-2 `api_key_file` fallback, + /// otherwise an explicit keyless route. + pub fn resolved_credential(&self) -> ProviderCredential { + if let Some(credential) = &self.credential { + return credential.clone(); + } + if let Some(file) = &self.api_key_file { + return ProviderCredential { kind: CredentialKind::ApiKey, file: Some(file.clone()) }; + } + ProviderCredential::none() + } +} + +#[derive(Debug, Clone, Default, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct LlmModel { - pub model_id: String, - #[serde(default)] - pub input_cost: f64, - #[serde(default)] - pub output_cost: f64, - #[serde(default)] - pub cache_input_cost: f64, + /// Model id; legacy schema-2 configs used `model_id`. + #[serde(alias = "model_id")] + pub id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub name: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub api: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub reasoning: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub input: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub context_window: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub max_tokens: Option, + #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")] + pub thinking_level_map: std::collections::BTreeMap, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub compat: Option, + /// Legacy schema-2 cost metadata; schema 3 rejects it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub input_cost: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub output_cost: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cache_input_cost: Option, +} + +#[derive(Debug, Clone, Default, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct LlmModelCompat { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub supports_store: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub supports_developer_role: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub supports_reasoning_effort: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub supports_strict_mode: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub max_tokens_field: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub thinking_format: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub zai_tool_stream: Option, } #[derive(Debug, Clone, Deserialize, Serialize)] @@ -184,11 +340,32 @@ pub struct LlmAllowance { pub amount: f64, } +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct BuiltinConfig { + pub repository: String, + pub endpoint: Url, +} + +// Parsed only to provide an actionable migration error for the previous declaration. +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct LocalConfig { + pub repository: String, + pub source: PathBuf, + pub default_branch: String, +} + #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct GitHubConfig { pub app_id: u64, pub repository: String, + /// Additional repositories served by this same GitHub App and instance. + /// The existing `repository` remains the single-repository default; when + /// this list is non-empty every Profile must declare its repository. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub additional_repositories: Vec, pub handle: String, pub api_version: String, pub private_key_file: PathBuf, @@ -199,11 +376,18 @@ pub struct GitHubConfig { pub projects_v2_enabled: bool, } +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct GitHubRepositoryConfig { + pub name: String, +} + #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct SchedulerConfig { pub quiet_seconds: u64, pub event_threshold: u32, + /// Minimum interval after a complete hot traversal; local due checks run at most 5s apart. pub reconciliation_seconds: u64, } @@ -219,6 +403,8 @@ pub struct ProviderConfig { #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct CodexConfig { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub braid_config_path: Option, pub executable: PathBuf, pub home: PathBuf, pub version: String, @@ -229,35 +415,19 @@ pub struct CodexConfig { #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct PiConfig { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub native_runtime: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub braid_config_path: Option, pub executable: PathBuf, pub provider: Option, pub model: Option, - #[serde(default)] - pub api_key_environment: Option, - #[serde(default)] - pub api_key_file: Option, + #[serde(default = "ProviderCredential::none")] + pub credential: ProviderCredential, pub thinking: Option, pub home: Option, -} - -impl PiConfig { - /// Load the provider API key from `api_key_file` if set, otherwise from - /// `api_key_environment`. - pub fn api_key(&self) -> Result { - if let Some(path) = &self.api_key_file { - return load_provider_secret_file(path); - } - if let Some(env) = &self.api_key_environment { - return std::env::var(env).map_err(|_| { - ConfigError::Invalid(format!( - "environment variable {env:?} for provider.pi.api_key_environment is not set" - )) - }); - } - Err(ConfigError::Invalid( - "one of provider.pi.api_key_environment or provider.pi.api_key_file must be set".into(), - )) - } + #[serde(default)] + pub profile_material_digest: String, } #[derive(Debug, Clone, Deserialize, Serialize)] @@ -306,10 +476,24 @@ pub struct Profile { /// Contract pin checked against the runtime entry's version. pub adapter_version: String, /// References an entry in `llm_providers` for adapters that need an LLM. - pub provider: String, + /// Adapters with their own authentication, such as Codex, omit this. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub provider: Option, + /// GitHub repository this Profile serves. Single-repository GitHub configs + /// may omit it and use `github.repository`; multi-repository configs must + /// set it explicitly. Built-in platform Profiles omit it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub repository: Option, pub model: Option, pub reasoning: Option, pub user_instructions: String, + /// Explicit Pi-discoverable skill entrypoints: a `SKILL.md` file, one skill + /// directory, or a shallow catalog of skill directories. Complete trees bind. + #[serde(default)] + pub skills: Vec, + /// Pi-native semantic materials (`models.json`, `settings.json`, `agents/*.md`). + #[serde(default)] + pub native_template: Option, /// The source Git checkout for this instance's repository, shared by all /// Profiles as the worktree provisioning source (one repository = one /// source checkout). Defaults to `/source`; Agent sessions @@ -328,6 +512,12 @@ impl Profile { pub fn resolve_workspace(&mut self, base: &Path) { let workspace = self.workspace.take().unwrap_or_else(|| base.join("source")); self.workspace = Some(resolve_path(base, &workspace)); + for skill in &mut self.skills { + *skill = resolve_path(base, skill); + } + if let Some(template) = &mut self.native_template { + *template = resolve_path(base, template); + } } /// The resolved source checkout path (valid after `Config::load`). @@ -345,8 +535,10 @@ pub struct ProfileSelection { #[derive(Debug, Serialize)] pub struct ConfigSummary<'a> { pub schema_version: u32, + pub upstream: &'static str, pub instance_key: &'a str, pub repository: &'a str, + pub repositories: Vec<&'a str>, pub runtime_root: &'a Path, pub database: &'a Path, pub profile_ids: Vec<&'a str>, @@ -362,36 +554,50 @@ 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, } fn load_webhook_secret_file(path: &Path) -> Result { - let text = fs::read_to_string(path) - .map_err(|source| ConfigError::Read { path: path.to_path_buf(), source })?; - let deserializer = toml::de::Deserializer::parse(&text).map_err(|error| { - ConfigError::Invalid(format!("cannot parse secrets file {}: {error}", path.display())) - })?; - let file: WebhookSecretFile = - serde_path_to_error::deserialize(deserializer).map_err(|error| { - ConfigError::Invalid(format!("cannot parse secrets file {}: {error}", path.display())) - })?; + let file: WebhookSecretFile = load_secret_file(path, "webhook_secret string")?; Ok(file.webhook_secret) } -fn load_provider_secret_file(path: &Path) -> Result { +pub(crate) fn load_provider_secret_file(path: &Path) -> Result { + let file: ProviderSecretFile = load_secret_file(path, "provider_api_key string")?; + Ok(file.provider_api_key) +} + +pub(crate) fn load_oauth_file(path: &Path) -> Result { + let file: OAuthCredentialFile = load_secret_file( + path, + "access and refresh strings, expires integer, optional account string", + )?; + if file.access.trim().is_empty() || file.refresh.trim().is_empty() { + return Err(ConfigError::Invalid(format!( + "OAuth credential file {} requires non-empty access and refresh tokens", + path.display() + ))); + } + Ok(file) +} + +fn load_secret_file( + path: &Path, + expected: &str, +) -> Result { let text = fs::read_to_string(path) .map_err(|source| ConfigError::Read { path: path.to_path_buf(), source })?; - let deserializer = toml::de::Deserializer::parse(&text).map_err(|error| { - ConfigError::Invalid(format!("cannot parse secrets file {}: {error}", path.display())) - })?; - let file: ProviderSecretFile = - serde_path_to_error::deserialize(deserializer).map_err(|error| { - ConfigError::Invalid(format!("cannot parse secrets file {}: {error}", path.display())) - })?; - Ok(file.provider_api_key) + // TOML errors quote source lines and invalid values. Credential parsing + // errors reach ordinary CLI/doctor output, outside sampled evidence. + toml::from_str(&text).map_err(|_| { + ConfigError::Invalid(format!( + "cannot parse secrets file {}: expected valid TOML with {expected}", + path.display() + )) + }) } impl Config { @@ -410,8 +616,28 @@ impl Config { } else { std::env::current_dir().map(|cwd| cwd.join(&base)).unwrap_or(base) }; + config.loaded_from = if path.is_absolute() { + path.to_path_buf() + } else { + std::env::current_dir() + .map_err(|source| ConfigError::Read { path: path.to_path_buf(), source })? + .join(path) + }; config.runtime.resolve(&base); + for runtime in &mut config.runtimes { + if let Some(manifest) = &mut runtime.native_runtime { + *manifest = resolve_path(&base, manifest); + } + } + let multi_repository = + config.github.as_ref().is_some_and(|github| !github.additional_repositories.is_empty()); for profile in &mut config.profiles { + if multi_repository && profile.workspace.is_none() { + return Err(ConfigError::Invalid(format!( + "profile {:?} requires an explicit workspace in a multi-repository config", + profile.id + ))); + } profile.resolve_workspace(&base); } config.validate()?; @@ -422,6 +648,81 @@ impl Config { &self.instance.key } + pub fn repository(&self) -> &str { + match (&self.github, &self.builtin) { + (Some(github), None) => &github.repository, + (None, Some(builtin)) => &builtin.repository, + _ => unreachable!("configuration validates exactly one collaboration backend"), + } + } + + pub fn is_builtin(&self) -> bool { + self.builtin.is_some() + } + + pub fn github_repositories(&self) -> Vec<&str> { + let Some(github) = &self.github else { return Vec::new() }; + std::iter::once(github.repository.as_str()) + .chain(github.additional_repositories.iter().map(|repository| repository.name.as_str())) + .collect() + } + + pub fn repositories(&self) -> Vec<&str> { + if self.is_builtin() { vec![self.repository()] } else { self.github_repositories() } + } + + pub fn is_multi_repository(&self) -> bool { + self.github.as_ref().is_some_and(|github| !github.additional_repositories.is_empty()) + } + + pub fn profile_repository<'a>(&'a self, profile: &'a Profile) -> &'a str { + match (&self.github, &self.builtin) { + (Some(github), None) => profile.repository.as_deref().unwrap_or(&github.repository), + (None, Some(builtin)) => &builtin.repository, + _ => unreachable!("configuration validates exactly one collaboration backend"), + } + } + + pub fn profiles_for_repository<'a>(&'a self, repository: &str, tag: &str) -> Vec<&'a Profile> { + self.profiles + .iter() + .filter(|profile| { + self.profile_repository(profile) == repository && profile.has_tag(tag) + }) + .collect() + } + + pub fn issue_profile_for_repository(&self, repository: &str) -> Result<&Profile, ConfigError> { + self.profiles_for_repository(repository, "issue").into_iter().next().ok_or_else(|| { + ConfigError::Invalid(format!("repository {repository:?} has no Issue Profile")) + }) + } + + pub fn pr_profile_for_repository(&self, repository: &str) -> Result<&Profile, ConfigError> { + let candidates = self.profiles_for_repository(repository, "pr"); + if let [profile] = candidates.as_slice() { + return Ok(profile); + } + candidates + .iter() + .find(|profile| profile.id == self.profile_selection.default_pr_profile) + .copied() + .ok_or_else(|| { + ConfigError::Invalid(format!( + "repository {repository:?} does not have an unambiguous PR Profile" + )) + }) + } + + pub fn github(&self) -> Result<&GitHubConfig, ConfigError> { + self.github.as_ref().ok_or_else(|| { + ConfigError::Invalid( + "this command requires the GitHub backend; this Harness connects to the built-in collaboration platform" + .into(), + ) + }) + } + pub fn profile(&self, id: &str) -> Result<&Profile, ConfigError> { self.profiles .iter() @@ -432,8 +733,10 @@ impl Config { pub fn summary(&self) -> ConfigSummary<'_> { ConfigSummary { schema_version: self.schema_version, + upstream: if self.is_builtin() { "builtin" } else { "github" }, instance_key: &self.instance.key, - repository: &self.github.repository, + repository: self.repository(), + repositories: self.repositories(), runtime_root: self.runtime.root(), database: self.runtime.database(), profile_ids: self.profiles.iter().map(|profile| profile.id.as_str()).collect(), @@ -444,13 +747,22 @@ impl Config { } } + pub(crate) fn profile_materials( + &self, + profile: &Profile, + ) -> Result { + crate::profile_materials::collect(self, profile).map_err(|error| { + ConfigError::Invalid(format!("profile {:?} materials: {error:#}", profile.id)) + }) + } + /// Load the GitHub webhook secret from `github.webhook_secret_file` if set, /// otherwise from `github.webhook_secret_environment`. pub fn webhook_secret(&self) -> Result { - if let Some(path) = &self.github.webhook_secret_file { + if let Some(path) = &self.github()?.webhook_secret_file { return load_webhook_secret_file(path); } - if let Some(env) = &self.github.webhook_secret_environment { + if let Some(env) = &self.github()?.webhook_secret_environment { return std::env::var(env).map_err(|_| { ConfigError::Invalid(format!( "environment variable {env:?} for github.webhook_secret_environment is not set" @@ -475,15 +787,10 @@ impl Config { }) } - pub fn llm_provider_for(&self, profile: &Profile) -> Result<&LlmProvider, ConfigError> { - self.llm_providers.iter().find(|provider| provider.id == profile.provider).ok_or_else( - || { - ConfigError::Invalid(format!( - "profile {:?} references unknown provider {:?}", - profile.id, profile.provider - )) - }, - ) + pub fn llm_provider_for(&self, provider_id: &str) -> Result<&LlmProvider, ConfigError> { + self.llm_providers.iter().find(|provider| provider.id == provider_id).ok_or_else(|| { + ConfigError::Invalid(format!("unknown llm_providers entry {provider_id:?}")) + }) } /// Provider settings for the default PR Profile, used by operator probes. @@ -524,6 +831,7 @@ impl Config { })?; return Ok(ProviderConfig { codex: Some(CodexConfig { + braid_config_path: Some(self.loaded_from.clone()), executable: runtime.executable.clone(), home, version: runtime.version.clone(), @@ -535,18 +843,26 @@ impl Config { } if runtime.adapter_type == "pi" { - // Pi needs an LLM provider entry for its API key and model info. - let llm = self.llm_provider_for(profile)?; + // Pi needs an explicit LLM provider entry for its API key and model route. + let provider_id = profile.provider.as_deref().ok_or_else(|| { + ConfigError::Invalid(format!( + "profile {:?} requires provider for the Pi adapter", + profile.id + )) + })?; + let llm = self.llm_provider_for(provider_id)?; return Ok(ProviderConfig { codex: None, pi: Some(PiConfig { + native_runtime: runtime.native_runtime.clone(), + braid_config_path: Some(self.loaded_from.clone()), executable: runtime.executable.clone(), provider: Some(llm.id.clone()), model: profile.model.clone(), - api_key_environment: llm.api_key_environment.clone(), - api_key_file: llm.api_key_file.clone(), + credential: llm.resolved_credential(), thinking: profile.reasoning.clone(), home: runtime.home.clone(), + profile_material_digest: self.profile_materials(profile)?.digest, }), }); } @@ -556,7 +872,7 @@ impl Config { #[allow(clippy::too_many_lines)] pub(crate) fn validate(&self) -> Result<(), ConfigError> { - if self.schema_version != CONFIG_SCHEMA_VERSION { + if self.schema_version != CONFIG_SCHEMA_VERSION && self.schema_version != 2 { return Err(ConfigError::Schema { found: self.schema_version, supported: CONFIG_SCHEMA_VERSION, @@ -565,22 +881,20 @@ impl Config { validate_instance_key(&self.instance.key) .map_err(|message| ConfigError::Invalid(format!("instance.key: {message}")))?; + if self.local.is_some() { + return Err(ConfigError::Invalid("[local] combined platform and Harness state is no longer supported; stop the old runtime, import its objects with braid platform import, then replace [local] with [builtin] repository and endpoint; see docs/user-manual/local.md".into())); + } + if self.github.is_some() == self.builtin.is_some() { + return Err(ConfigError::Invalid( + "configure exactly one upstream: [github] or [builtin]".into(), + )); + } for (name, path) in [ ("runtime.root", self.runtime.root()), ("runtime.database", self.runtime.database()), ("runtime.backups", self.runtime.backups()), - ("github.private_key_file", &self.github.private_key_file), - ("tools.git", &self.tools.git), - ("tools.gh", &self.tools.gh), - ("tools.wrangler", &self.tools.wrangler), - ] - .into_iter() - .chain( - self.github - .webhook_secret_file - .as_ref() - .map(|path| ("github.webhook_secret_file", path.as_path())), - ) { + ("tools.git", self.tools.git.as_path()), + ] { require_absolute(name, path)?; } if !self.runtime.database().starts_with(self.runtime.root()) @@ -590,20 +904,63 @@ impl Config { "runtime database and backups must be inside runtime.root".into(), )); } - if self.github.app_id == 0 { - return Err(ConfigError::Invalid("github.app_id must be positive".into())); - } - validate_repository(&self.github.repository)?; - validate_token("github.handle", &self.github.handle)?; - if self.github.webhook_secret_environment.is_none() - && self.github.webhook_secret_file.is_none() - { - return Err(ConfigError::Invalid( - "one of github.webhook_secret_environment or github.webhook_secret_file must be set".into(), - )); + if let Some(builtin) = &self.builtin { + validate_token("builtin.repository", &builtin.repository)?; + let endpoint = &builtin.endpoint; + let loopback = match endpoint.host() { + Some(url::Host::Domain("localhost")) => true, + Some(url::Host::Ipv4(ip)) => ip.is_loopback(), + Some(url::Host::Ipv6(ip)) => ip.is_loopback(), + _ => false, + }; + if endpoint.scheme() != "http" + || !loopback + || !endpoint.username().is_empty() + || endpoint.password().is_some() + || endpoint.query().is_some() + || endpoint.fragment().is_some() + || endpoint.path() != "/" + { + return Err(ConfigError::Invalid("builtin.endpoint must be a loopback HTTP origin without credentials, query, fragment or path".into())); + } + for profile in &self.profiles { + if profile.workspace.is_none() { + return Err(ConfigError::Invalid(format!( + "profile {:?} requires workspace for the built-in platform's Git source", + profile.id + ))); + } + } } - if let Some(env) = &self.github.webhook_secret_environment { - validate_token("github.webhook_secret_environment", env)?; + if let Some(github) = &self.github { + require_absolute("github.private_key_file", &github.private_key_file)?; + require_absolute("tools.gh", &self.tools.gh)?; + require_absolute("tools.wrangler", &self.tools.wrangler)?; + if let Some(path) = &github.webhook_secret_file { + require_absolute("github.webhook_secret_file", path)?; + } + if github.app_id == 0 { + return Err(ConfigError::Invalid("github.app_id must be positive".into())); + } + validate_repository(&github.repository)?; + let mut repository_names = HashSet::new(); + repository_names.insert(github.repository.as_str()); + for repository in &github.additional_repositories { + validate_repository(&repository.name)?; + if !repository_names.insert(repository.name.as_str()) { + return Err(ConfigError::Invalid(format!( + "duplicate GitHub repository {:?}", + repository.name + ))); + } + } + validate_token("github.handle", &github.handle)?; + if github.webhook_secret_environment.is_none() && github.webhook_secret_file.is_none() { + return Err(ConfigError::Invalid("one of github.webhook_secret_environment or github.webhook_secret_file must be set".into())); + } + if let Some(env) = &github.webhook_secret_environment { + validate_token("github.webhook_secret_environment", env)?; + } } if self.scheduler.quiet_seconds == 0 || self.scheduler.event_threshold == 0 @@ -619,6 +976,9 @@ impl Config { if !address.ip().is_loopback() { return Err(ConfigError::Invalid(format!("{name} must use a loopback address"))); } + if address.port() == 0 { + return Err(ConfigError::Invalid(format!("{name} must use a non-zero port"))); + } } if self.server.ingress == self.server.health { return Err(ConfigError::Invalid( @@ -633,10 +993,24 @@ impl Config { let mut runtime_types = HashSet::new(); for runtime in &self.runtimes { validate_token("runtime.adapter_type", &runtime.adapter_type)?; + if !matches!(runtime.adapter_type.as_str(), "codex" | "pi") { + return Err(ConfigError::Invalid(format!( + "unsupported adapter_type {:?}", + runtime.adapter_type + ))); + } require_absolute( &format!("runtime.{}.executable", runtime.adapter_type), &runtime.executable, )?; + if let Some(manifest) = &runtime.native_runtime { + require_absolute("runtime.native_runtime", manifest)?; + if runtime.adapter_type != "pi" { + return Err(ConfigError::Invalid( + "native_runtime is only supported by Pi".into(), + )); + } + } if !runtime_types.insert(runtime.adapter_type.as_str()) { return Err(ConfigError::Invalid(format!( "duplicate runtime adapter_type {:?}", @@ -672,15 +1046,54 @@ impl Config { let mut provider_ids = HashSet::new(); for provider in &self.llm_providers { validate_token("llm_providers.id", &provider.id)?; - validate_token("llm_providers.protocol", &provider.protocol)?; - if provider.api_key_environment.is_none() && provider.api_key_file.is_none() { - return Err(ConfigError::Invalid(format!( - "llm_providers {:?} requires api_key_environment or api_key_file", - provider.id - ))); + if let Some(credential) = &provider.credential { + validate_credential( + &format!("llm_providers.{}.credential", provider.id), + credential, + )?; } - if let Some(file) = &provider.api_key_file { - require_absolute(&format!("llm_providers.{}.api_key_file", provider.id), file)?; + if let Some(api_key_file) = &provider.api_key_file { + require_absolute( + &format!("llm_providers.{}.api_key_file", provider.id), + api_key_file, + )?; + } + if self.schema_version == 2 { + if let Some(protocol) = &provider.protocol { + validate_token("llm_providers.protocol", protocol)?; + } + } else { + if provider.api_key_file.is_some() { + return Err(ConfigError::Invalid(format!( + "llm_providers {:?} uses legacy api_key_file; schema 3 uses credential = {{ kind = \"api_key\", file = ... }}", + provider.id + ))); + } + if provider.credential.is_none() { + return Err(ConfigError::Invalid(format!( + "llm_providers {:?} requires an explicit credential; use kind = \"none\" for a keyless route", + provider.id + ))); + } + if provider.protocol.is_some() + || !provider.allowances.is_empty() + || provider.models.iter().any(|model| { + model.input_cost.is_some() + || model.output_cost.is_some() + || model.cache_input_cost.is_some() + }) + { + return Err(ConfigError::Invalid(format!( + "llm_providers {:?} contains schema-2 protocol/cost metadata; schema 3 keeps only id, credential, and base_url/api/models metadata", + provider.id + ))); + } + if let Some(base_url) = &provider.base_url { + validate_provider_base_url( + &format!("llm_providers.{}.base_url", provider.id), + base_url, + )?; + } } if !provider_ids.insert(provider.id.as_str()) { return Err(ConfigError::Invalid(format!( @@ -690,14 +1103,17 @@ impl Config { } let mut model_ids = HashSet::new(); for model in &provider.models { - validate_token( - &format!("llm_providers.{}.model_id", provider.id), - &model.model_id, - )?; - if !model_ids.insert(model.model_id.as_str()) { + validate_token(&format!("llm_providers.{}.models.id", provider.id), &model.id)?; + if !model_ids.insert(model.id.as_str()) { return Err(ConfigError::Invalid(format!( "duplicate model {:?} in llm_providers {:?}", - model.model_id, provider.id + model.id, provider.id + ))); + } + if model.context_window == Some(0) || model.max_tokens == Some(0) { + return Err(ConfigError::Invalid(format!( + "llm_providers.{} model {:?} requires positive context_window and max_tokens", + provider.id, model.id ))); } } @@ -707,7 +1123,20 @@ impl Config { return Err(ConfigError::Invalid("at least one profile is required".into())); } let mut ids = HashSet::new(); + let mut repository_workspaces = HashMap::new(); for profile in &self.profiles { + let repository = self.profile_repository(profile); + if let Some(workspace) = &profile.workspace + && let Some(existing) = + repository_workspaces.insert(repository, workspace.as_path()) + && existing != workspace + { + return Err(ConfigError::Invalid(format!( + "profiles for repository {repository:?} must share one source checkout; {} and {} differ", + existing.display(), + workspace.display() + ))); + } profile.validate(self)?; if !ids.insert(profile.id.as_str()) { return Err(ConfigError::Invalid(format!( @@ -716,6 +1145,17 @@ impl Config { ))); } } + if self.github.is_some() { + for repository in self.github_repositories() { + if self.profiles_for_repository(repository, "issue").is_empty() + && self.profiles_for_repository(repository, "pr").is_empty() + { + return Err(ConfigError::Invalid(format!( + "GitHub repository {repository:?} has no Issue or PR Profile" + ))); + } + } + } let default_pr = self.profile(&self.profile_selection.default_pr_profile)?; if !default_pr.has_tag("pr") { return Err(ConfigError::Invalid( @@ -759,6 +1199,65 @@ impl TelemetryConfig { } impl Profile { + fn validate_pi_provider_route(&self, config: &Config) -> Result<(), ConfigError> { + if self.adapter_type != "pi" { + return Ok(()); + } + let provider_id = self.provider.as_deref().expect("Pi provider checked above"); + let llm = config.llm_provider_for(provider_id)?; + if config.schema_version == 2 { + return Ok(()); + } + if llm.base_url.is_none() { + return Err(ConfigError::Invalid(format!( + "llm_providers {:?} requires base_url for Pi models.json derivation", + llm.id + ))); + } + if let Some(model) = &self.model + && !llm.models.iter().any(|declared| declared.id == *model) + { + return Err(ConfigError::Invalid(format!( + "profile {:?} model {:?} is not declared in llm_providers {:?} models", + self.id, model, llm.id + ))); + } + Ok(()) + } + + fn validate_repository_scope(&self, config: &Config) -> Result<(), ConfigError> { + let Some(github) = &config.github else { + if self.repository.is_some() { + return Err(ConfigError::Invalid(format!( + "profile {:?} repository is supported only by the GitHub backend", + self.id + ))); + } + return Ok(()); + }; + let configured = config.github_repositories(); + match &self.repository { + Some(repository) => { + validate_repository(repository)?; + if !configured.contains(&repository.as_str()) { + return Err(ConfigError::Invalid(format!( + "profile {:?} references unconfigured GitHub repository {:?}", + self.id, repository + ))); + } + } + None => { + if !github.additional_repositories.is_empty() { + return Err(ConfigError::Invalid(format!( + "profile {:?} requires an explicit repository in a multi-repository config", + self.id + ))); + } + } + } + Ok(()) + } + pub fn has_tag(&self, tag: &str) -> bool { self.tags.iter().any(|candidate| candidate == tag) } @@ -778,10 +1277,43 @@ impl Profile { self.id ))); } - validate_token("profile.provider", &self.provider)?; + if self.adapter_type == "pi" { + let provider = self.provider.as_deref().ok_or_else(|| { + ConfigError::Invalid(format!( + "profile {:?} requires provider for the Pi adapter", + self.id + )) + })?; + validate_token("profile.provider", provider)?; + if self.model.is_none() && config.schema_version != 2 { + return Err(ConfigError::Invalid(format!( + "profile {:?} requires an explicit model for the Pi adapter", + self.id + ))); + } + } else if self.provider.is_some() && config.schema_version != 2 { + return Err(ConfigError::Invalid(format!( + "profile {:?} provider is supported only by the Pi adapter", + self.id + ))); + } + self.validate_repository_scope(config)?; if let Some(workspace) = &self.workspace { require_absolute(&format!("profile {:?}.workspace", self.id), workspace)?; } + if self.adapter_type != "pi" && (!self.skills.is_empty() || self.native_template.is_some()) + { + return Err(ConfigError::Invalid(format!( + "profile {:?} skills and native_template are supported only by the Pi adapter", + self.id + ))); + } + for skill in &self.skills { + require_absolute(&format!("profile {:?}.skills", self.id), skill)?; + } + if let Some(template) = &self.native_template { + require_absolute(&format!("profile {:?}.native_template", self.id), template)?; + } if self.tags.is_empty() || (!self.has_tag("issue") && !self.has_tag("pr")) { return Err(ConfigError::Invalid(format!( "profile {:?} must have issue or pr capability tag", @@ -808,6 +1340,7 @@ impl Profile { ))); } if !(0.0..1.0).contains(&self.github_context_soft_ratio) + || self.github_context_soft_ratio <= 0.0 || self.github_context_hard_bytes == 0 { return Err(ConfigError::Invalid(format!( @@ -824,16 +1357,72 @@ impl Profile { self.id, self.adapter_version, runtime.adapter_type, runtime.version ))); } - let _llm = config.llm_provider_for(self)?; - // The profile's model is a request to the provider, and the provider - // is the authority on which models it accepts. The llm_providers - // catalog only carries cost metadata, so an uncatalogued model is - // not a config error: Codex must be able to answer with a real - // turn failure for a model it does not support. + self.validate_pi_provider_route(config)?; + config.profile_materials(self)?; Ok(()) } } +fn validate_provider_base_url(name: &str, value: &str) -> Result<(), ConfigError> { + let url = url::Url::parse(value) + .map_err(|error| ConfigError::Invalid(format!("{name} is not a valid URL: {error}")))?; + if !matches!(url.scheme(), "http" | "https") { + return Err(ConfigError::Invalid(format!("{name} must use http or https"))); + } + if !url.username().is_empty() || url.password().is_some() { + return Err(ConfigError::Invalid(format!("{name} must not carry credentials"))); + } + if url.query_pairs().any(|(key, _)| sensitive_query_name(&key)) { + return Err(ConfigError::Invalid(format!( + "{name} must not carry credential query parameters" + ))); + } + Ok(()) +} + +pub(crate) fn sensitive_query_name(name: &str) -> bool { + let name = name.to_ascii_lowercase(); + [ + "api-key", + "api_key", + "apikey", + "auth", + "authorization", + "token", + "secret", + "password", + "credential", + "signature", + "key", + "access-token", + "access_token", + ] + .iter() + .any(|exact| name == *exact) +} + +fn validate_credential(name: &str, credential: &ProviderCredential) -> Result<(), ConfigError> { + match credential.kind { + CredentialKind::None => { + if credential.file.is_some() { + return Err(ConfigError::Invalid(format!( + "{name}: kind \"none\" must not reference a file" + ))); + } + } + CredentialKind::ApiKey | CredentialKind::OAuth => match &credential.file { + Some(file) => require_absolute(name, file)?, + None => { + return Err(ConfigError::Invalid(format!( + "{name}: kind {:?} requires a file", + credential.kind + ))); + } + }, + } + Ok(()) +} + fn resolve_path(base: &Path, path: &Path) -> PathBuf { if path.is_absolute() { path.to_path_buf() } else { base.join(path) } } @@ -847,17 +1436,13 @@ fn require_absolute(name: &str, path: &Path) -> Result<(), ConfigError> { } fn validate_repository(repository: &str) -> Result<(), ConfigError> { - let mut parts = repository.split('/'); - let owner = parts.next().unwrap_or_default(); - let name = parts.next().unwrap_or_default(); - if owner.is_empty() || name.is_empty() || parts.next().is_some() { - return Err(ConfigError::Invalid("github.repository must be owner/repository".into())); - } - validate_token("github.repository owner", owner)?; - validate_token("github.repository name", name) + repository + .parse::() + .map(|_| ()) + .map_err(|error| ConfigError::Invalid(format!("github.repository: {error}"))) } -fn validate_token(name: &str, value: &str) -> Result<(), ConfigError> { +pub(crate) fn validate_token(name: &str, value: &str) -> Result<(), ConfigError> { if value.trim().is_empty() || value.chars().any(char::is_whitespace) { Err(ConfigError::Invalid(format!("{name} must be a non-empty token"))) } else { @@ -869,54 +1454,58 @@ const fn default_log_format() -> LogFormat { LogFormat::Text } -/// Attribution markers identifying Braid-authored Agent text, derived -/// from the configured Profiles. Used by ingress/reconcile to classify -/// authorship; a pure derivation with no state of its own. -pub fn agent_attributions(config: &Config) -> Vec { - let mut attributions = Vec::new(); - for profile in &config.profiles { - if profile.has_tag("issue") { - attributions - .push(format!("> **Braid Agent · {}**\n> Issue Agent", profile.display_name)); - } - if profile.has_tag("pr") { - attributions.push(format!( - "> **Braid Agent · {}**\n> PR Implementation Agent", - profile.display_name - )); - } - } - attributions -} - #[cfg(test)] mod tests { - use std::path::Path; + use super::*; - use super::Config; + fn example() -> Config { + Config::load(&Path::new(env!("CARGO_MANIFEST_DIR")).join("config.example.toml")) + .expect("load example") + } #[test] - fn pi_settings_follow_the_requested_profile() { - let mut config = Config::load(Path::new("config.example.toml")).unwrap(); - config.runtimes[0].adapter_type = "pi".into(); + fn static_validation_rejects_unusable_runtime_and_server_settings() { + let mut config = example(); + config.runtimes[0].adapter_type = "unsupported".into(); for profile in &mut config.profiles { - profile.adapter_type = "pi".into(); + profile.adapter_type = "unsupported".into(); } - config.profiles[0].model = Some("issue-model".into()); - config.profiles[0].reasoning = Some("low".into()); - config.profiles[1].model = Some("pr-model".into()); - let settings = config.provider_config_for_profile(&config.profiles[0]).unwrap().pi.unwrap(); - assert_eq!(settings.model.as_deref(), Some("issue-model")); - assert_eq!(settings.thinking.as_deref(), Some("low")); + assert!(config.validate().unwrap_err().to_string().contains("unsupported adapter_type")); + + let mut config = example(); + config.server.ingress.set_port(0); + assert!(config.validate().unwrap_err().to_string().contains("non-zero port")); + + let mut config = example(); + config.profiles[0].github_context_soft_ratio = 0.0; + assert!(config.validate().unwrap_err().to_string().contains("in (0,1)")); + + let mut config = example(); + config.instance.key = " owner ".into(); + assert!(config.validate().unwrap_err().to_string().contains("instance.key")); + + let mut config = example(); + config.github.as_mut().unwrap().repository = "owner/repo?query".into(); + assert!(config.validate().unwrap_err().to_string().contains("github.repository")); } - /// `config.example.toml` is the canonical starter template, not a loose - /// documentation snippet. It must parse and validate against the canonical - /// `Config` type so that it cannot drift from the real schema. Partial - /// examples in runbooks are not required to pass this test. #[test] - fn example_config_matches_schema() { - Config::load(Path::new("config.example.toml")) - .expect("config.example.toml must match the Config schema"); + fn malformed_credentials_never_quote_secret_source_or_values() { + let path = + std::env::temp_dir().join(format!("braid-secrets-{}.toml", uuid::Uuid::now_v7())); + for (kind, contents) in [ + ("webhook", "webhook_secret = \"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(|_| ()), + _ => load_oauth_file(&path).map(|_| ()), + }; + let message = result.unwrap_err().to_string(); + assert!(message.contains("cannot parse secrets file"), "{message}"); + assert!(!message.contains("sensitive-marker"), "{message}"); + } + fs::remove_file(path).expect("remove credential fixture"); } } diff --git a/src/console/api.rs b/src/console/api.rs new file mode 100644 index 00000000..01125eb4 --- /dev/null +++ b/src/console/api.rs @@ -0,0 +1,282 @@ +use std::sync::{Arc, Mutex, MutexGuard}; + +use axum::{ + Json, Router, + body::Bytes, + extract::{Path, Query, State, rejection::BytesRejection}, + http::{HeaderMap, StatusCode}, + response::{IntoResponse, Response}, + routing::{get, post}, +}; +use prost::Message; +use serde_json::{Value, json}; + +use super::{ + collector, + storage::{Filter, Storage}, +}; + +#[derive(Clone)] +struct ApiState(Arc>>); + +impl ApiState { + fn storage(&self) -> Result<&Mutex, ApiError> { + self.0.as_ref().as_ref().map_err(unavailable) + } + + fn lock_storage(&self) -> Result, ApiError> { + self.storage()?.lock().map_err(internal) + } +} + +pub(super) fn routes(storage: anyhow::Result) -> Router { + Router::new() + .route("/v1/traces", post(traces).fallback(otlp_method_not_allowed)) + .route("/v1/logs", post(logs).fallback(otlp_method_not_allowed)) + .route("/v1/metrics", post(metrics).fallback(otlp_method_not_allowed)) + .route("/api/resources", get(resources)) + .route("/api/status", get(resources)) + .route("/api/records", get(records)) + .route("/api/batches/{id}", get(batch)) + .route("/api/receive-errors", get(receive_errors)) + .route("/api/receive-errors/{id}", get(rejected_body)) + .with_state(ApiState(Arc::new(storage.map(Mutex::new)))) +} + +#[derive(prost::Message)] +struct RpcStatus { + #[prost(int32, tag = "1")] + code: i32, + #[prost(string, tag = "2")] + message: String, +} + +pub(super) fn otlp_failure(status: StatusCode, message: String) -> Response { + let code = match status { + StatusCode::SERVICE_UNAVAILABLE => 14, + StatusCode::INTERNAL_SERVER_ERROR => 13, + StatusCode::FORBIDDEN => 7, + StatusCode::METHOD_NOT_ALLOWED => 12, + _ => 3, + }; + ( + status, + [("content-type", "application/x-protobuf")], + RpcStatus { code, message }.encode_to_vec(), + ) + .into_response() +} + +async fn otlp_method_not_allowed() -> Response { + otlp_failure(StatusCode::METHOD_NOT_ALLOWED, "OTLP export requires POST".into()) +} + +struct OtlpError(ApiError); +impl IntoResponse for OtlpError { + fn into_response(self) -> Response { + otlp_failure(self.0.0, self.0.1) + } +} + +struct ApiError(StatusCode, String); +impl IntoResponse for ApiError { + fn into_response(self) -> Response { + (self.0, Json(json!({"error":self.1}))).into_response() + } +} +fn internal(error: impl std::fmt::Display) -> ApiError { + ApiError(StatusCode::INTERNAL_SERVER_ERROR, error.to_string()) +} +fn unavailable(error: impl std::fmt::Display) -> ApiError { + ApiError( + StatusCode::SERVICE_UNAVAILABLE, + format!("Console observation database unavailable: {error:#}"), + ) +} + +async fn traces( + State(state): State, + headers: HeaderMap, + body: Result, +) -> Result { + ingest(state, headers, body, "traces").await.map_err(OtlpError) +} +async fn logs( + State(state): State, + headers: HeaderMap, + body: Result, +) -> Result { + ingest(state, headers, body, "logs").await.map_err(OtlpError) +} +async fn metrics( + State(state): State, + headers: HeaderMap, + body: Result, +) -> Result { + ingest(state, headers, body, "metrics").await.map_err(OtlpError) +} + +async fn ingest( + state: ApiState, + headers: HeaderMap, + body: Result, + signal: &'static str, +) -> Result { + tokio::task::spawn_blocking(move || { + let storage = state.storage()?; + let (body, validated) = match body { + Ok(body) => { + let validated = validate(&headers, &body, signal); + (body, validated) + } + Err(rejection) => ( + Bytes::new(), + Err(ApiError( + rejection.status(), + format!( + "{}; request body was not captured because extraction failed", + rejection.body_text() + ), + )), + ), + }; + let mut storage = storage.lock().map_err(internal)?; + let outcome = match validated { + Ok((encoding, records)) => { + storage.ingest(signal, &encoding, &body, records).map_err(unavailable) + } + Err(error) => Err(error), + }; + if let Err(mut error) = outcome { + if let Err(persist) = storage.reject(signal, error.0.as_u16(), &error.1, &body) { + error.1 = format!("{}; receive-error persistence failed: {persist:#}", error.1); + } + return Err(error); + } + Ok(()) + }) + .await + .map_err(internal)??; + Ok(([("content-type", "application/x-protobuf")], Bytes::new()).into_response()) +} + +fn validate( + headers: &HeaderMap, + body: &[u8], + signal: &str, +) -> Result<(String, Vec), ApiError> { + let content_type = headers + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("") + .split(';') + .next() + .unwrap_or("") + .trim(); + if content_type != "application/x-protobuf" { + return Err(ApiError( + StatusCode::UNSUPPORTED_MEDIA_TYPE, + "OTLP requires Content-Type: application/x-protobuf".into(), + )); + } + let encoding = headers + .get("content-encoding") + .map(|v| v.to_str()) + .transpose() + .map_err(|e| ApiError(StatusCode::BAD_REQUEST, e.to_string()))? + .unwrap_or("identity") + .to_owned(); + if !matches!(encoding.as_str(), "gzip" | "identity") { + return Err(ApiError( + StatusCode::UNSUPPORTED_MEDIA_TYPE, + format!("unsupported Content-Encoding: {encoding}"), + )); + } + let records = collector::decode(signal, &encoding, body) + .map_err(|e| ApiError(StatusCode::BAD_REQUEST, format!("{e:#}")))?; + Ok((encoding, records)) +} + +async fn receive_errors( + State(state): State, + Query(filter): Query, +) -> Result, ApiError> { + tokio::task::spawn_blocking(move || { + state.lock_storage()?.receive_errors(&filter).map(Json).map_err(unavailable) + }) + .await + .map_err(internal)? +} +async fn rejected_body( + State(state): State, + Path(id): Path, +) -> Result { + let body = tokio::task::spawn_blocking(move || { + state.lock_storage()?.rejected_body(id).map_err(unavailable) + }) + .await + .map_err(internal)??; + let Some(body) = body else { + return Err(ApiError(StatusCode::NOT_FOUND, format!("receive error {id} not found"))); + }; + let mut response = ([("content-type", "application/octet-stream")], body).into_response(); + response.headers_mut().insert( + "content-disposition", + axum::http::HeaderValue::from_str(&format!( + "attachment; filename=otlp-receive-error-{id}.bin" + )) + .map_err(internal)?, + ); + Ok(response) +} + +async fn resources(State(state): State) -> Result, ApiError> { + tokio::task::spawn_blocking(move || { + state.lock_storage()?.resources().map(Json).map_err(unavailable) + }) + .await + .map_err(internal)? +} +async fn records( + State(state): State, + Query(filter): Query, +) -> Result, ApiError> { + if filter.signal.as_ref().is_some_and(|s| !matches!(s.as_str(), "traces" | "logs" | "metrics")) + { + return Err(ApiError( + StatusCode::BAD_REQUEST, + "signal must be traces, logs, or metrics".into(), + )); + } + if filter.after.is_some_and(|id| id < 0) { + return Err(ApiError(StatusCode::BAD_REQUEST, "after must be nonnegative".into())); + } + tokio::task::spawn_blocking(move || { + state.lock_storage()?.records(&filter).map(Json).map_err(unavailable) + }) + .await + .map_err(internal)? +} +async fn batch(State(state): State, Path(id): Path) -> Result { + let found = + tokio::task::spawn_blocking(move || state.lock_storage()?.batch(id).map_err(unavailable)) + .await + .map_err(internal)??; + let Some((encoding, body)) = found else { + return Err(ApiError(StatusCode::NOT_FOUND, format!("OTLP batch {id} not found"))); + }; + let mut response = ([("content-type", "application/octet-stream")], body).into_response(); + let suffix = if encoding == "gzip" { "pb.gz" } else { "pb" }; + response.headers_mut().insert( + "content-disposition", + axum::http::HeaderValue::from_str(&format!( + "attachment; filename=otlp-batch-{id}.{suffix}" + )) + .map_err(internal)?, + ); + response.headers_mut().insert( + "x-otlp-content-encoding", + axum::http::HeaderValue::from_str(&encoding).map_err(internal)?, + ); + Ok(response) +} diff --git a/src/console/collector.rs b/src/console/collector.rs new file mode 100644 index 00000000..63715142 --- /dev/null +++ b/src/console/collector.rs @@ -0,0 +1,152 @@ +use std::io::Read; + +use anyhow::{Context, Result, bail}; +use opentelemetry_proto::tonic::{ + collector::{ + logs::v1::ExportLogsServiceRequest, metrics::v1::ExportMetricsServiceRequest, + trace::v1::ExportTraceServiceRequest, + }, + common::v1::{KeyValue, any_value::Value as OtelValue}, +}; +use prost::Message; +use serde::Serialize; + +use super::storage::DecodedRecord; + +pub const MAX_BATCH_BYTES: usize = 16 * 1024 * 1024; + +pub fn decode(signal: &str, encoding: &str, wire: &[u8]) -> Result> { + let payload = match encoding { + "identity" => wire.to_vec(), + "gzip" => { + let mut output = Vec::new(); + flate2::read::GzDecoder::new(wire) + .take(u64::try_from(MAX_BATCH_BYTES)? + 1) + .read_to_end(&mut output) + .context("decode gzip OTLP body")?; + if output.len() > MAX_BATCH_BYTES { + bail!("decompressed OTLP body exceeds {MAX_BATCH_BYTES} bytes"); + } + output + } + _ => bail!("unsupported Content-Encoding: {encoding}"), + }; + let mut records = Vec::new(); + match signal { + "traces" => { + for resource in ExportTraceServiceRequest::decode(payload.as_slice()) + .context("decode OTLP traces protobuf")? + .resource_spans + { + let attrs = resource.resource.as_ref().map_or(&[][..], |r| r.attributes.as_slice()); + for scope in resource.scope_spans { + for span in scope.spans { + records.push(record( + attrs, + &resource.resource, + &scope.scope, + &span, + &span.attributes, + hex::encode(&span.trace_id), + hex::encode(&span.span_id), + )?); + } + } + } + } + "logs" => { + for resource in ExportLogsServiceRequest::decode(payload.as_slice()) + .context("decode OTLP logs protobuf")? + .resource_logs + { + let attrs = resource.resource.as_ref().map_or(&[][..], |r| r.attributes.as_slice()); + for scope in resource.scope_logs { + for log in scope.log_records { + records.push(record( + attrs, + &resource.resource, + &scope.scope, + &log, + &log.attributes, + hex::encode(&log.trace_id), + hex::encode(&log.span_id), + )?); + } + } + } + } + "metrics" => { + for resource in ExportMetricsServiceRequest::decode(payload.as_slice()) + .context("decode OTLP metrics protobuf")? + .resource_metrics + { + let attrs = resource.resource.as_ref().map_or(&[][..], |r| r.attributes.as_slice()); + for scope in resource.scope_metrics { + for metric in scope.metrics { + records.push(record( + attrs, + &resource.resource, + &scope.scope, + &metric, + &[], + String::new(), + String::new(), + )?); + } + } + } + } + _ => bail!("unsupported OTLP signal: {signal}"), + } + Ok(records) +} + +fn attribute(attributes: &[KeyValue], keys: &[&str]) -> String { + keys.iter() + .find_map(|key| { + attributes.iter().find(|a| a.key == *key).and_then(|a| a.value.as_ref()).and_then(|v| { + match &v.value { + Some(OtelValue::StringValue(s)) => Some(s.clone()), + _ => None, + } + }) + }) + .unwrap_or_default() +} + +#[allow(clippy::too_many_arguments)] +fn record( + resource_attributes: &[KeyValue], + resource: &impl Serialize, + scope: &impl Serialize, + data: &impl Serialize, + attributes: &[KeyValue], + trace_id: String, + span_id: String, +) -> Result { + let mut session = attribute( + attributes, + &[ + "braid.provider_session.id", + "provider.thread.id", + "braid.session.id", + "session_id", + "session.id", + "provider_session_id", + ], + ); + if session.is_empty() { + session = attribute(resource_attributes, &["braid.session.id", "session_id", "session.id"]); + } + Ok(DecodedRecord { + instance: attribute(resource_attributes, &["service.instance.id"]), + service: attribute(resource_attributes, &["service.name"]), + session, + turn_id: attribute(attributes, &["braid.turn.id", "turn_id"]), + trace_id, + span_id, + resource: serde_json::to_value(resource)?, + scope: serde_json::to_value(scope)?, + data: serde_json::to_value(data)?, + }) +} diff --git a/src/console/harness.rs b/src/console/harness.rs new file mode 100644 index 00000000..f10035ab --- /dev/null +++ b/src/console/harness.rs @@ -0,0 +1,108 @@ +//! Read the Harness ledger without treating upstream objects or OTLP as execution authority. +use std::{path::PathBuf, time::Duration}; + +use anyhow::{Context as _, Result, ensure}; +use axum::{Json, Router, extract::State, http::StatusCode, routing::get}; +use rusqlite::{Connection, OpenFlags}; +use serde_json::Value; +use time::{OffsetDateTime, format_description::well_known::Rfc3339}; + +use crate::config::Config; + +#[derive(Clone)] +struct SnapshotState { + database: PathBuf, + run_id: Option, + manager: super::runtime::Manager, + repository: String, + profiles: Value, +} + +pub(super) fn router(config: &Config, manager: super::runtime::Manager) -> Router { + Router::new().route("/api/harness/snapshot", get(snapshot)).with_state(SnapshotState { + database: config.runtime.database().into(), + run_id: None, + manager, + repository: config.repositories().join(", "), + profiles: serde_json::json!({ + "issue":config.profiles.iter().find(|p|p.tags.iter().any(|t|t=="issue")).map(|p|&p.id), + "pr":config.profile_selection.default_pr_profile, + }), + }) +} + +async fn snapshot( + State(mut state): State, +) -> Result, (StatusCode, Json)> { + (state.database, state.run_id) = state.manager.harness_source().await.map_err(|error| { + (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error":format!("{error:#}")}))) + })?; + tokio::task::spawn_blocking(move || read_snapshot(&state)) + .await + .context("Harness snapshot task failed") + .and_then(std::convert::identity) + .map(Json) + .map_err(|error| { + ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(serde_json::json!({"error":format!("{error:#}")})), + ) + }) +} + +fn read_snapshot(state: &SnapshotState) -> Result { + let connection = + Connection::open_with_flags(&state.database, OpenFlags::SQLITE_OPEN_READ_ONLY)?; + connection.busy_timeout(Duration::from_secs(5))?; + let transaction = connection.unchecked_transaction()?; + let version: u32 = transaction.query_row( + "SELECT COALESCE(MAX(version),0) FROM schema_migrations", + [], + |r| r.get(0), + )?; + ensure!( + version == crate::store::DATABASE_SCHEMA_VERSION, + "Harness database requires migration before reading its snapshot" + ); + let result = serde_json::json!({ + "source":"braid_harness", "observedAt":OffsetDateTime::now_utc().format(&Rfc3339)?, + "repository":state.repository,"runId":state.run_id,"profileSuggestions":state.profiles, + "upstream":rows(&transaction,"SELECT space_id,repository,client_id,cursor FROM builtin_upstream WHERE singleton=1")?, + "sessions":rows(&transaction,"SELECT session_id,agent_id,provider_kind,provider_session_id,lifecycle,started_at,resume_count,last_resumed_at,last_resume_error FROM provider_sessions ORDER BY started_at")?, + "turns":rows(&transaction,"SELECT turn_id,session_id,provider_turn_id,trigger_kind,lifecycle,started_at,ended_at,error FROM turns ORDER BY started_at")?, + "queue":rows(&transaction,"SELECT batch_id,work_item_node_id,event_count,quiet_deadline,urgent,lifecycle,created_at,updated_at FROM wake_batches ORDER BY created_at")?, + "assignments":rows(&transaction,"SELECT assignment_id,work_item_node_id,generation,lifecycle,assigned_at,retired_at FROM assignments ORDER BY assigned_at")?, + "worktrees":rows(&transaction,"SELECT worktree_id,agent_id,path,lifecycle,source_path,head_ref,local_branch FROM worktrees ORDER BY observed_at")?, + }); + transaction.commit()?; + Ok(result) +} + +fn rows(connection: &Connection, sql: &str) -> Result> { + let mut statement = connection.prepare(sql)?; + let names = statement.column_names().into_iter().map(str::to_owned).collect::>(); + Ok(statement + .query_map([], |row| { + let mut value = serde_json::Map::new(); + for (index, name) in names.iter().enumerate() { + let field = match row.get_ref(index)? { + rusqlite::types::ValueRef::Null => Value::Null, + rusqlite::types::ValueRef::Integer(n) => Value::from(n), + rusqlite::types::ValueRef::Real(n) => Value::from(n), + rusqlite::types::ValueRef::Text(text) => { + Value::String(String::from_utf8_lossy(text).into_owned()) + } + rusqlite::types::ValueRef::Blob(_) => { + return Err(rusqlite::Error::InvalidColumnType( + index, + name.clone(), + rusqlite::types::Type::Blob, + )); + } + }; + value.insert(name.clone(), field); + } + Ok(Value::Object(value)) + })? + .collect::>>()?) +} diff --git a/src/console/mod.rs b/src/console/mod.rs new file mode 100644 index 00000000..9a57f501 --- /dev/null +++ b/src/console/mod.rs @@ -0,0 +1,338 @@ +mod api; +mod collector; +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}; +use axum::{ + Router, + extract::{DefaultBodyLimit, Request}, + http::{Method, StatusCode, header}, + middleware::{self, Next}, + response::{Html, IntoResponse, Response}, + routing::get, +}; +use clap::Args; +use std::{ + net::SocketAddr, + path::PathBuf, + sync::{Arc, Mutex}, +}; + +#[derive(Debug, Args)] +pub struct ConsoleArgs { + /// Loopback address for OTLP ingestion and the local Web Console. + #[arg(long, default_value = "127.0.0.1:4318")] + pub listen: SocketAddr, + /// Absolute path of the Console telemetry database, separate from runtime state. + #[arg(long)] + pub database: PathBuf, + /// Optional Harness configuration for either GitHub or the built-in platform. + #[arg(long)] + pub config: Option, + /// Independent built-in platform configuration; manages its listener for the Console lifetime. + #[arg(long)] + pub platform_config: Option, +} + +// Keep startup and reverse-order shutdown together so each managed lifetime is visible. +#[allow(clippy::too_many_lines)] +pub async fn serve(args: ConsoleArgs) -> Result<()> { + if !args.listen.ip().is_loopback() { + bail!("Console must listen on a loopback address"); + } + if !args.database.is_absolute() { + bail!("Console database path must be absolute"); + } + let listener = + tokio::net::TcpListener::bind(args.listen).await.context("bind Console listener")?; + let address = listener.local_addr()?; + let mut config = args + .config + .map(|path| { + if !path.is_absolute() { + bail!("Console config path must be absolute"); + } + Config::load(&path).map_err(anyhow::Error::new) + }) + .transpose()?; + let mut platform = args + .platform_config + .map(|path| { + if !path.is_absolute() { + bail!("Console platform config path must be absolute"); + } + crate::platform::PlatformConfig::load(&path) + }) + .transpose()?; + let harness_database = + config.as_ref().map(|config| resolved_path(config.runtime.database())).transpose()?; + let platform_database = + platform.as_ref().map(|platform| resolved_path(&platform.database)).transpose()?; + let observation_database = resolved_path(&args.database); + if (harness_database.is_some() && harness_database == platform_database) + || observation_database.as_ref().is_ok_and(|path| { + harness_database.as_ref() == Some(path) || platform_database.as_ref() == Some(path) + }) + { + bail!("Console, Harness and platform databases must be separate"); + } + let mut platform_listener = None; + let mut platform_endpoint = + config.as_ref().and_then(|c| c.builtin.as_ref().map(|b| b.endpoint.clone())); + if let Some(platform) = &mut platform { + let listener = tokio::net::TcpListener::bind(&platform.listen) + .await + .context("bind platform listener")?; + platform.listen = listener.local_addr()?.to_string(); + let endpoint = url::Url::parse(&format!("http://{}", platform.listen))?; + if let Some(builtin) = config.as_ref().and_then(|c| c.builtin.as_ref()) + && (builtin.repository != platform.repository || builtin.endpoint != endpoint) + { + bail!( + "managed platform repository and listener must match the Harness builtin declaration" + ); + } + platform_endpoint = Some(endpoint); + platform_listener = Some(listener); + } + let metadata = serde_json::json!({ + "harness":{"configured":config.is_some(),"backend":config.as_ref().map(|c|if c.is_builtin(){"builtin"}else{"github"})}, + "platform":{"configured":platform_endpoint.is_some(),"endpoint":platform_endpoint,"managed":platform.is_some()}, + "collector":{"endpoint":format!("http://{address}")} + }); + let mut manager = None; + let mut telemetry = None; + let mut app = Router::new().route( + "/api/console", + get(move || { + let metadata = metadata.clone(); + async move { axum::Json(metadata) } + }), + ); + if let Some(endpoint) = platform_endpoint { + app = app.merge(proxy::router(endpoint)?); + } + if let Some(mut config) = config.take() { + let store = StoreActor::start( + config.runtime.database().to_path_buf(), + config.runtime.backups().to_path_buf(), + )?; + if !store.plan()?.pending.is_empty() { + if !config.runtime.auto_migrate { + bail!( + "database needs migration before Console control; use braid migrate apply --config " + ); + } + store.apply()?; + } + // This process owns the collector, so its managed runtime exports to this listener. + config.telemetry.endpoint = url::Url::parse(&format!("http://{address}"))?; + telemetry = Some(TelemetryGuard::install(&config.telemetry, config.instance_key())?); + let runtime = runtime::Manager::new(config.clone())?; + app = app.merge(harness::router(&config, runtime.clone())); + app = app.merge(runtime.router()); + manager = Some(runtime); + } + if telemetry.is_none() + && let Some(platform) = &platform + { + let platform_telemetry = crate::config::TelemetryConfig { + endpoint: url::Url::parse(&format!("http://{address}"))?, + sample_ratio: 0.1, + incident_mode: false, + export_timeout_seconds: 5, + service_name: "braid".into(), + log_format: crate::config::LogFormat::Text, + }; + telemetry = Some(TelemetryGuard::install( + &platform_telemetry, + &format!("braid-console-platform:{}", platform.repository), + )?); + } + let platform_service = platform + .zip(platform_listener) + .map(|(config, listener)| crate::platform::router(&config).map(|router| (listener, router))) + .transpose()?; + let storage = + observation_database.and_then(|_| storage::Storage::open(&args.database)).with_context( + || format!("initialize Console observation database {}", args.database.display()), + ); + if let Err(error) = &storage { + eprintln!("Console observation unavailable: {error:#}"); + } + app = app + .merge(api::routes(storage)) + .merge(web_routes()) + .layer(DefaultBodyLimit::max(collector::MAX_BATCH_BYTES)) + .layer(middleware::from_fn(move |request, next| same_origin(request, next, address))); + let (platform_stop, platform_task) = if let Some((listener, router)) = platform_service { + let (stop, mut receiver) = tokio::sync::watch::channel(false); + let task = tokio::spawn(async move { + axum::serve(listener, router) + .with_graceful_shutdown(async move { + while !*receiver.borrow() { + if receiver.changed().await.is_err() { + break; + } + } + }) + .await + .context("serve managed platform") + }); + (Some(stop), Some(task)) + } else { + (None, None) + }; + println!("Braid Console http://{address}"); + let stop_manager = manager.clone(); + let shutdown_errors = Arc::new(Mutex::new(Vec::new())); + let saved_errors = shutdown_errors.clone(); + let result = axum::serve(listener, app) + .with_graceful_shutdown(async move { + let mut errors = Vec::new(); + if let Err(error) = crate::runtime::wait_for_shutdown_signal().await { + errors.push(format!("shutdown signal: {error:#}")); + } + if let Some(manager) = stop_manager + && let Err(error) = manager.shutdown().await + { + errors.push(format!("Harness stop unconfirmed: {error:#}")); + } + if let Some(stop) = platform_stop { + let _ = stop.send(true); + } + if let Some(task) = platform_task { + match task.await { + Ok(Ok(())) => {} + Ok(Err(error)) => errors.push(format!("platform shutdown: {error:#}")), + Err(error) => errors.push(format!("platform task: {error}")), + } + } + // The Collector still accepts final evidence while the SDK flushes. + if let Some(telemetry) = telemetry { + match tokio::task::spawn_blocking(move || telemetry.shutdown()).await { + Ok(Ok(())) => {} + Ok(Err(error)) => errors.push(format!("telemetry shutdown: {error:#}")), + Err(error) => errors.push(format!("telemetry shutdown task: {error}")), + } + } + if let Ok(mut saved) = saved_errors.lock() { + *saved = errors; + } + }) + .await + .context("serve Console"); + if let Some(manager) = manager { + manager.shutdown().await?; + } + let errors = shutdown_errors + .lock() + .map_err(|_| anyhow::anyhow!("Console shutdown result lock poisoned"))?; + if !errors.is_empty() { + bail!("Console shutdown failed: {}", errors.join("; ")); + } + result +} + +fn web_routes() -> Router { + Router::new() + .route("/", get(|| async { Html(include_str!("web/index.html")) })) + .route( + "/braid-logo.svg", + get(|| async { + ( + [(header::CONTENT_TYPE, "image/svg+xml")], + include_str!( + "../../docs/assets/logo/svg/small-optical-color/braid-color-on-transparent.svg" + ), + ) + }), + ) + .route( + "/favicon.svg", + get(|| async { + ( + [(header::CONTENT_TYPE, "image/svg+xml")], + include_str!( + "../../docs/assets/logo/svg/small-optical-color/braid-color-on-badge.svg" + ), + ) + }), + ) + .route( + "/favicon.png", + get(|| async { + ( + [(header::CONTENT_TYPE, "image/png")], + include_bytes!( + "../../docs/assets/logo/png/braid-color-on-badge/braid-color-on-badge-32.png" + ) + .as_slice(), + ) + }), + ) + .route( + "/console.css", + get(|| async { + ( + [(header::CONTENT_TYPE, "text/css; charset=utf-8")], + include_str!("web/console.css"), + ) + }), + ) + .route( + "/console.js", + get(|| async { + ( + [(header::CONTENT_TYPE, "text/javascript; charset=utf-8")], + include_str!("web/console.js"), + ) + }), + ) +} +async fn same_origin(request: Request, next: Next, address: SocketAddr) -> Response { + let host = + request.headers().get(header::HOST).and_then(|value| value.to_str().ok()).unwrap_or(""); + let allowed = host == address.to_string() || host == format!("localhost:{}", address.port()); + if !allowed { + return rejected_request(&request, "Console Host must match its loopback listener"); + } + if request.method() != Method::GET + && request.method() != Method::HEAD + && let Some(origin) = request.headers().get(header::ORIGIN) + && origin.to_str().ok() != Some(format!("http://{host}").as_str()) + { + return rejected_request(&request, "Console mutations require a same-origin request"); + } + let mut response = next.run(request).await; + response.headers_mut().insert(header::CONTENT_SECURITY_POLICY,axum::http::HeaderValue::from_static("default-src 'self'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src 'self' data:; frame-ancestors 'none'; base-uri 'none'")); + response + .headers_mut() + .insert(header::X_CONTENT_TYPE_OPTIONS, axum::http::HeaderValue::from_static("nosniff")); + response +} + +fn resolved_path(path: &std::path::Path) -> Result { + match path.canonicalize() { + Ok(path) => return Ok(path), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => return Err(error).context("resolve database path"), + } + let parent = path.parent().context("database path has no parent")?; + let name = path.file_name().context("database path has no filename")?; + Ok(resolved_path(parent)?.join(name)) +} + +fn rejected_request(request: &Request, message: &str) -> Response { + if matches!(request.uri().path(), "/v1/traces" | "/v1/logs" | "/v1/metrics") { + api::otlp_failure(StatusCode::FORBIDDEN, message.into()) + } else { + (StatusCode::FORBIDDEN, message.to_owned()).into_response() + } +} diff --git a/src/console/proxy.rs b/src/console/proxy.rs new file mode 100644 index 00000000..ce24c194 --- /dev/null +++ b/src/console/proxy.rs @@ -0,0 +1,91 @@ +//! The browser only reaches the platform endpoint declared by the operator. +use anyhow::{Context as _, Result, ensure}; +use axum::{ + Router, + body::{Body, to_bytes}, + extract::{Request, State}, + http::{Method, StatusCode, header}, + response::{IntoResponse, Response}, + routing::{get, post}, +}; +use std::time::Duration; +use url::Url; + +#[derive(Clone)] +struct PlatformProxy { + endpoint: Url, + client: reqwest::Client, +} + +pub fn router(endpoint: Url) -> Result { + ensure!( + endpoint.scheme() == "http" + && match endpoint.host() { + Some(url::Host::Domain(host)) => host == "localhost", + Some(url::Host::Ipv4(ip)) => ip.is_loopback(), + Some(url::Host::Ipv6(ip)) => ip.is_loopback(), + None => false, + } + && endpoint.username().is_empty() + && endpoint.password().is_none() + && endpoint.query().is_none() + && endpoint.fragment().is_none() + && endpoint.path() == "/", + "Console platform endpoint must be a credential-free loopback HTTP origin" + ); + let state = PlatformProxy { + endpoint, + client: reqwest::Client::builder() + .timeout(Duration::from_secs(30)) + .redirect(reqwest::redirect::Policy::none()) + .build() + .context("create platform proxy client")?, + }; + Ok(Router::new() + .route("/api/control/snapshot", get(forward)) + .route("/api/control/items/{number}", get(forward)) + .route("/api/control/items/{number}/diff", get(forward)) + .route("/api/control/commands", post(forward)) + .route("/api/control/receipts/{request_id}", get(forward)) + .with_state(state)) +} + +async fn forward(State(state): State, request: Request) -> Response { + match forward_request(state, request).await { + Ok(response) => response, + Err(error) => ( + StatusCode::BAD_GATEWAY, + axum::Json(serde_json::json!({"error":format!("platform request failed: {error:#}")})), + ) + .into_response(), + } +} + +async fn forward_request(state: PlatformProxy, request: Request) -> Result { + let (parts, body) = request.into_parts(); + let url = state.endpoint.join(parts.uri.path()).context("resolve platform API route")?; + ensure!( + url.origin() == state.endpoint.origin() && url.path() == parts.uri.path(), + "platform API path must not normalize outside the declared route" + ); + let mut builder = state.client.request(parts.method.clone(), url); + if parts.method != Method::GET { + let body = to_bytes(body, super::collector::MAX_BATCH_BYTES) + .await + .context("read platform command body")?; + builder = builder + .header(header::CONTENT_TYPE, "application/json") + .header(header::ORIGIN, state.endpoint.origin().ascii_serialization()) + .body(body); + } + let upstream = builder.send().await.context("send declared platform API request")?; + let status = upstream.status(); + let content_type = upstream.headers().get(header::CONTENT_TYPE).cloned(); + let body = upstream.bytes().await.context("read platform API response body")?; + let mut response = Response::new(Body::from(body)); + *response.status_mut() = status; + if let Some(content_type) = content_type { + response.headers_mut().insert(header::CONTENT_TYPE, content_type); + } + Ok(response) +} diff --git a/src/console/runtime.rs b/src/console/runtime.rs new file mode 100644 index 00000000..17b45246 --- /dev/null +++ b/src/console/runtime.rs @@ -0,0 +1,429 @@ +//! Owns actual runtime tasks; OTLP observations never drive these transitions. +use crate::{ + config::Config, + health::Health, + run::{RunRequest, RunResult, RunState}, +}; +use anyhow::{Context as _, Result, bail}; +use axum::{ + Json, Router, + extract::{Path, State}, + http::StatusCode, + response::{IntoResponse, Response}, + routing::{get, post}, +}; +use rusqlite::{Connection, OptionalExtension, params}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use sha2::{Digest as _, Sha256}; +use std::{path::PathBuf, sync::Arc}; +use tokio::sync::{Mutex, watch}; + +#[derive(Clone)] +pub struct Manager(Arc); +struct Inner { + config: Config, + state: Mutex, + health: Health, +} +struct Execution { + generation: Option, + state: &'static str, + error: Option, + provider_enabled: bool, + stop_confirmed: bool, + run_request: Option, + run_result: Option, + stop: Option>, + monitor: Option>, +} +#[derive(Debug, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct Command { + request_id: String, + operation: Operation, + expected_generation: Option, + #[serde(default)] + transport_only: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + run_request: Option, +} +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "snake_case")] +enum Operation { + Start, + Stop, +} +struct ApiError(StatusCode, String); +impl IntoResponse for ApiError { + fn into_response(self) -> Response { + (self.0, Json(json!({"error": self.1}))).into_response() + } +} +fn internal(error: impl std::fmt::Display) -> ApiError { + ApiError(StatusCode::INTERNAL_SERVER_ERROR, error.to_string()) +} +fn run_error(result: &RunResult) -> Option { + if !result.stop_confirmed || matches!(result.state, RunState::Blocked | RunState::Failed) { + result.reason.clone() + } else { + None + } +} + +impl Manager { + pub fn new(config: Config) -> Result { + let mut initial = crate::runtime::initial_health(&config, false); + initial.ready = false; + let db = Connection::open_with_flags( + config.runtime.database(), + rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY, + )?; + let previous: Option = db.query_row("SELECT response_json FROM control_receipts WHERE scope='runtime' ORDER BY created_at DESC,rowid DESC LIMIT 1", [], |row| row.get(0)).optional()?.flatten(); + let previous = + previous.map(|response| serde_json::from_str::(&response)).transpose()?; + let generation = previous + .as_ref() + .and_then(|response| response["result"]["generation"].as_str().map(str::to_owned)); + let run_request = previous + .as_ref() + .and_then(|response| response["result"].get("run_request")) + .filter(|value| !value.is_null()) + .map(|value| serde_json::from_value::(value.clone())) + .transpose()?; + let run_result = previous + .as_ref() + .and_then(|response| response["result"].get("run")) + .filter(|value| !value.is_null()) + .map(|value| serde_json::from_value::(value.clone())) + .transpose()?; + let unconfirmed = previous.as_ref().is_some_and(|response| { + response["result"]["stop_confirmed"].as_bool().map_or_else( + || { + matches!( + response["result"]["state"].as_str(), + Some("starting" | "running" | "stopping" | "blocked") + ) + }, + |confirmed| !confirmed, + ) + }); + let error = if unconfirmed { + Some("previous Console ended without a persisted stop confirmation; verify its native executions before replacing this runtime".to_owned()) + } else { + run_result.as_ref().and_then(run_error) + }; + let state = if unconfirmed { "blocked" } else { "stopped" }; + initial.last_error.clone_from(&error); + let health = Health::new(initial); + Ok(Self(Arc::new(Inner { + config, + health, + state: Mutex::new(Execution { + generation, + state, + error, + provider_enabled: false, + stop_confirmed: state == "stopped", + run_request, + run_result, + stop: None, + monitor: None, + }), + }))) + } + pub(super) async fn harness_source(&self) -> Result<(PathBuf, Option)> { + let state = self.0.state.lock().await; + if let Some(request) = &state.run_request { + Ok(( + crate::run::run_database(&self.0.config, &request.run_id)?, + Some(request.run_id.clone()), + )) + } else { + Ok((self.0.config.runtime.database().into(), None)) + } + } + pub fn router(&self) -> Router { + Router::new() + .route("/api/runtime", get(status)) + .route("/api/runtime/commands", post(command)) + .route("/api/runtime/receipts/{request_id}", get(receipt)) + .with_state(self.clone()) + } + pub async fn shutdown(&self) -> Result<()> { + let monitor = { + let mut state = self.0.state.lock().await; + if let Some(stop) = &state.stop { + let _ = stop.send(true); + state.state = "stopping"; + } + state.monitor.take() + }; + if let Some(monitor) = monitor { + tokio::time::timeout(std::time::Duration::from_secs(30), monitor) + .await + .context("runtime shutdown exceeded 30 seconds; execution stop is unconfirmed")? + .context("runtime supervisor failed")?; + } + let state = self.0.state.lock().await; + if !state.stop_confirmed { + bail!( + "runtime stop is unconfirmed: {}", + state.error.as_deref().unwrap_or("unknown failure") + ); + } + Ok(()) + } +} + +async fn status(State(manager): State) -> Result, ApiError> { + let ( + generation, + state, + error, + provider_enabled, + stop_confirmed, + run_request, + run_result, + health, + ) = { + let execution = manager.0.state.lock().await; + ( + execution.generation.clone(), + execution.state, + execution.error.clone(), + execution.provider_enabled, + execution.stop_confirmed, + execution.run_request.clone(), + execution.run_result.clone(), + manager.0.health.snapshot(), + ) + }; + let config = &manager.0.config; + let run = match (run_result, &run_request) { + (None, Some(request)) => { + crate::run::run_snapshot(config, &request.run_id).map_err(internal)? + } + (reported, _) => reported, + }; + Ok(Json( + json!({"instance":config.instance_key(),"repository":config.repositories().join(", "),"upstream":if config.is_builtin(){"builtin"}else{"github"},"generation":generation,"state":state,"error":error,"provider_enabled":provider_enabled,"health":health,"authority":"in-process runtime supervisor","mode":if run_request.is_some() {"run"} else {"serve"},"stop_confirmed":stop_confirmed,"run_request":run_request,"run":run,"evidence":crate::telemetry::evidence_health(),"telemetry":{"endpoint":config.telemetry.endpoint,"sample_ratio":config.telemetry.sample_ratio,"incident_mode":config.telemetry.incident_mode}}), + )) +} + +async fn receipt( + State(manager): State, + Path(id): Path, +) -> Result, ApiError> { + read_receipt(manager.0.config.runtime.database().to_path_buf(), &id) + .map_err(internal)? + .map(Json) + .ok_or_else(|| { + ApiError(StatusCode::NOT_FOUND, format!("runtime receipt {id} does not exist")) + }) +} + +async fn command( + State(manager): State, + Json(command): Json, +) -> Result<(StatusCode, Json), ApiError> { + if command.request_id.trim().is_empty() || command.request_id.len() > 128 { + return Err(ApiError( + StatusCode::BAD_REQUEST, + "request_id must contain 1 to 128 bytes".into(), + )); + } + let payload = serde_json::to_string(&command).map_err(internal)?; + let sha = hex::encode(Sha256::digest(payload.as_bytes())); + let mut state = manager.0.state.lock().await; + let db = Connection::open(manager.0.config.runtime.database()).map_err(internal)?; + db.busy_timeout(std::time::Duration::from_secs(5)).map_err(internal)?; + if let Some((saved_sha,response))=db.query_row("SELECT payload_sha256,response_json FROM control_receipts WHERE scope='runtime' AND request_id=?1",[&command.request_id],|row|Ok((row.get::<_,String>(0)?,row.get::<_,Option>(1)?))).optional().map_err(internal)? { + if saved_sha!=sha { return Err(ApiError(StatusCode::CONFLICT,"request_id already belongs to a different command".into())); } + let response=response.map(|r|serde_json::from_str(&r)).transpose().map_err(internal)?.unwrap_or(json!({"request_id":command.request_id,"state":"prepared"})); + return Ok((StatusCode::OK,Json(response))); + } + if command.expected_generation != state.generation { + return Err(ApiError( + StatusCode::CONFLICT, + format!("runtime generation changed; current generation is {:?}", state.generation), + )); + } + if let Some(request) = &command.run_request { + if !matches!(command.operation, Operation::Start) || command.transport_only { + return Err(ApiError( + StatusCode::BAD_REQUEST, + "run_request requires start with Provider enabled".into(), + )); + } + request + .validate(&manager.0.config) + .map_err(|error| ApiError(StatusCode::BAD_REQUEST, format!("{error:#}")))?; + } + match command.operation { + Operation::Start if state.state != "stopped" || !state.stop_confirmed => { + return Err(ApiError( + StatusCode::CONFLICT, + format!( + "cannot start runtime in state {}: {}", + state.state, + state.error.as_deref().unwrap_or("execution already owned") + ), + )); + } + Operation::Stop if !matches!(state.state, "starting" | "running" | "stopping") => { + return Err(ApiError( + StatusCode::CONFLICT, + format!("cannot stop runtime in state {}", state.state), + )); + } + _ => {} + } + let generation = match command.operation { + Operation::Start => uuid::Uuid::now_v7().to_string(), + Operation::Stop => { + state.generation.clone().ok_or_else(|| internal("running runtime has no generation"))? + } + }; + let next_state = match command.operation { + Operation::Start => "starting", + Operation::Stop => "stopping", + }; + let response = json!({"request_id":command.request_id,"state":"applied","result":{"accepted":true,"generation":generation,"state":next_state,"stop_confirmed":false,"run_request":match command.operation { Operation::Start => &command.run_request, Operation::Stop => &state.run_request }}}); + let now = time::OffsetDateTime::now_utc().unix_timestamp(); + db.execute("INSERT INTO control_receipts(scope,request_id,payload_sha256,request_json,state,response_json,created_at,updated_at) VALUES('runtime',?1,?2,?3,'applied',?4,?5,?5)",params![command.request_id,sha,payload,response.to_string(),now]).map_err(internal)?; + drop(db); + tracing::info!(name="braid.runtime.command", request.id=%command.request_id, + braid.runtime.generation=%generation, operation=?command.operation, + braid.outcome="accepted", "runtime command accepted by supervisor"); + match command.operation { + Operation::Start => { + start_runtime( + &manager, + &mut state, + generation, + !command.transport_only, + command.run_request, + ); + } + Operation::Stop => { + state + .stop + .as_ref() + .ok_or_else(|| internal("runtime stop handle is unavailable"))? + .send(true) + .map_err(internal)?; + state.state = "stopping"; + } + } + Ok((StatusCode::ACCEPTED, Json(response))) +} +fn read_receipt(path: PathBuf, id: &str) -> Result> { + let db = Connection::open_with_flags(path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)?; + db.query_row( + "SELECT response_json FROM control_receipts WHERE scope='runtime' AND request_id=?1", + [id], + |row| row.get::<_, Option>(0), + ) + .optional()? + .flatten() + .map(|s| serde_json::from_str(&s).map_err(anyhow::Error::new)) + .transpose() +} +fn save_outcome( + config: &Config, + generation: &str, + state: &str, + error: Option<&str>, + stop_confirmed: bool, + run: Option<&RunResult>, +) -> Result<()> { + let db = Connection::open(config.runtime.database())?; + db.busy_timeout(std::time::Duration::from_secs(5))?; + let mut query=db.prepare("SELECT request_id,response_json FROM control_receipts WHERE scope='runtime' AND json_extract(response_json,'$.result.generation')=?1")?; + let rows = query + .query_map([generation], |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)))? + .collect::>>()?; + drop(query); + for (id, response) in rows { + let mut response: Value = serde_json::from_str(&response)?; + response["result"]["state"] = json!(state); + response["result"]["error"] = json!(error); + response["result"]["stop_confirmed"] = json!(stop_confirmed); + response["result"]["run"] = json!(run); + db.execute("UPDATE control_receipts SET response_json=?1,error=?2,updated_at=?3 WHERE scope='runtime' AND request_id=?4",params![response.to_string(),error,time::OffsetDateTime::now_utc().unix_timestamp(),id])?; + } + Ok(()) +} + +fn start_runtime( + manager: &Manager, + state: &mut Execution, + generation: String, + provider_enabled: bool, + run_request: Option, +) { + let (stop, receiver) = watch::channel(false); + state.generation = Some(generation.clone()); + state.state = "starting"; + state.error = None; + state.provider_enabled = provider_enabled; + state.stop_confirmed = false; + state.run_request.clone_from(&run_request); + state.run_result = None; + state.stop = Some(stop); + let initial = crate::runtime::initial_health(&manager.0.config, provider_enabled); + manager.0.health.update(|current| *current = initial); + crate::telemetry::set_runtime_generation(Some(generation.clone())); + let task_manager = manager.clone(); + let config = manager.0.config.clone(); + let health = manager.0.health.clone(); + let task = tokio::spawn(async move { + if let Some(request) = run_request { + crate::run::run_managed(config, request, receiver, health).await.map(Some) + } else { + crate::runtime::serve_managed(config, provider_enabled, receiver, health) + .await + .map(|()| None) + } + }); + state.state = "running"; + state.monitor = Some(tokio::spawn(async move { + let result = task.await.map_err(anyhow::Error::new).and_then(std::convert::identity); + let mut state = task_manager.0.state.lock().await; + state.stop = None; + match result { + Ok(run) => { + state.stop_confirmed = run.as_ref().is_none_or(|result| result.stop_confirmed); + state.state = if state.stop_confirmed { "stopped" } else { "blocked" }; + state.error = run.as_ref().and_then(run_error); + state.run_result = run; + } + Err(error) => { + state.state = "blocked"; + state.error = Some(format!("{error:#}")); + } + } + tracing::info!(name="braid.runtime.terminal", braid.runtime.generation=%generation, + braid.outcome=state.state, error.reason=state.error.as_deref().unwrap_or(""), + "runtime supervision completed"); + crate::telemetry::set_runtime_generation(None); + if let Err(error) = save_outcome( + &task_manager.0.config, + &generation, + state.state, + state.error.as_deref(), + state.stop_confirmed, + state.run_result.as_ref(), + ) { + state.state = "blocked"; + state.stop_confirmed = false; + state.error = Some(format!("runtime outcome persistence failed: {error:#}")); + } + let diagnostic = state.error.clone(); + task_manager.0.health.update(|health| { + health.ready = false; + health.last_error = diagnostic; + }); + })); +} diff --git a/src/console/storage.rs b/src/console/storage.rs new file mode 100644 index 00000000..d742855c --- /dev/null +++ b/src/console/storage.rs @@ -0,0 +1,210 @@ +use std::{ + path::Path, + time::{SystemTime, UNIX_EPOCH}, +}; + +use anyhow::{Context, Result, bail}; +use rusqlite::{Connection, params}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; + +#[derive(Debug, Serialize)] +pub struct Record { + pub id: i64, + pub batch_id: i64, + pub duplicate_of: Option, + pub signal: String, + pub received_at: i64, + pub instance: String, + pub service: String, + pub session: String, + pub turn_id: String, + pub trace_id: String, + pub span_id: String, + pub resource: Value, + pub scope: Value, + pub data: Value, +} + +pub struct DecodedRecord { + pub instance: String, + pub service: String, + pub session: String, + pub turn_id: String, + pub trace_id: String, + pub span_id: String, + pub resource: Value, + pub scope: Value, + pub data: Value, +} + +#[derive(Default, Deserialize)] +pub struct Filter { + pub signal: Option, + pub instance: Option, + pub session: Option, + pub trace: Option, + pub turn: Option, + pub after: Option, + pub limit: Option, +} + +pub struct Storage(Connection); + +impl Storage { + pub fn open(path: &Path) -> Result { + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; + } + let db = Connection::open(path).context("open Console telemetry database")?; + db.busy_timeout(std::time::Duration::from_secs(5))?; + let application_id: i64 = db.query_row("PRAGMA application_id", [], |row| row.get(0))?; + let foreign_tables: i64 = db.query_row("SELECT count(*) FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' AND name NOT IN ('console_batches','console_records','console_receive_errors')", [], |row| row.get(0))?; + if !matches!(application_id, 0 | 1_112_498_510) || foreign_tables != 0 { + bail!( + "Console requires a separate telemetry database; this database belongs to another component" + ); + } + db.execute_batch("PRAGMA application_id=1112498510;")?; + db.execute_batch("PRAGMA journal_mode=WAL; + CREATE TABLE IF NOT EXISTS console_batches ( + id INTEGER PRIMARY KEY, signal TEXT NOT NULL, received_at INTEGER NOT NULL, + encoding TEXT NOT NULL, payload BLOB NOT NULL, sha256 TEXT NOT NULL, duplicate_of INTEGER); + CREATE INDEX IF NOT EXISTS console_batches_digest ON console_batches(signal,encoding,sha256); + CREATE TABLE IF NOT EXISTS console_receive_errors (id INTEGER PRIMARY KEY, received_at INTEGER NOT NULL, signal TEXT NOT NULL, status INTEGER NOT NULL, reason TEXT NOT NULL, payload BLOB NOT NULL); + CREATE TABLE IF NOT EXISTS console_records ( + id INTEGER PRIMARY KEY, batch_id INTEGER NOT NULL REFERENCES console_batches(id), + signal TEXT NOT NULL, received_at INTEGER NOT NULL, instance TEXT NOT NULL, + service TEXT NOT NULL, session TEXT NOT NULL, turn_id TEXT NOT NULL, trace_id TEXT NOT NULL, + span_id TEXT NOT NULL, resource TEXT NOT NULL, scope TEXT NOT NULL, data TEXT NOT NULL); + CREATE INDEX IF NOT EXISTS console_records_instance ON console_records(instance,id); + CREATE INDEX IF NOT EXISTS console_records_session ON console_records(session,id); + CREATE INDEX IF NOT EXISTS console_records_trace ON console_records(trace_id,id);")?; + Ok(Self(db)) + } + + pub fn ingest( + &mut self, + signal: &str, + encoding: &str, + payload: &[u8], + records: Vec, + ) -> Result<()> { + let received = i64::try_from(SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis())?; + let digest = hex::encode(Sha256::digest(payload)); + let tx = self.0.transaction()?; + let duplicate_of: Option = tx.query_row( + "SELECT min(id) FROM console_batches WHERE signal=? AND encoding=? AND sha256=?", + params![signal, encoding, digest], + |row| row.get(0), + )?; + tx.execute( + "INSERT INTO console_batches(signal,received_at,encoding,payload,sha256,duplicate_of) VALUES(?,?,?,?,?,?)", + params![signal, received, encoding, payload,digest,duplicate_of], + )?; + let batch_id = tx.last_insert_rowid(); + for record in records { + tx.execute("INSERT INTO console_records(batch_id,signal,received_at,instance,service,session,turn_id,trace_id,span_id,resource,scope,data) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)", + params![batch_id,signal,received,record.instance,record.service,record.session,record.turn_id,record.trace_id,record.span_id,serde_json::to_string(&record.resource)?,serde_json::to_string(&record.scope)?,serde_json::to_string(&record.data)?])?; + } + tx.commit()?; + Ok(()) + } + + pub fn records(&self, filter: &Filter) -> Result { + let limit = i64::try_from(filter.limit.unwrap_or(100).clamp(1, 200))?; + let mut statement = self.0.prepare("SELECT id,batch_id,signal,received_at,instance,service,session,turn_id,trace_id,span_id,resource,scope,data,(SELECT duplicate_of FROM console_batches WHERE id=batch_id) FROM console_records + WHERE id>? AND (? IS NULL OR signal=?) AND (? IS NULL OR instance=?) AND (? IS NULL OR session=?) AND (? IS NULL OR trace_id=?) AND (? IS NULL OR turn_id=?) ORDER BY id LIMIT ?")?; + let mut rows = statement.query(params![ + filter.after.unwrap_or(0), + filter.signal, + filter.signal, + filter.instance, + filter.instance, + filter.session, + filter.session, + filter.trace, + filter.trace, + filter.turn, + filter.turn, + limit + ])?; + let mut records = Vec::new(); + while let Some(row) = rows.next()? { + records.push(Record { + id: row.get(0)?, + batch_id: row.get(1)?, + duplicate_of: row.get(13)?, + signal: row.get(2)?, + received_at: row.get(3)?, + instance: row.get(4)?, + service: row.get(5)?, + session: row.get(6)?, + turn_id: row.get(7)?, + trace_id: row.get(8)?, + span_id: row.get(9)?, + resource: serde_json::from_str(&row.get::<_, String>(10)?)?, + scope: serde_json::from_str(&row.get::<_, String>(11)?)?, + data: serde_json::from_str(&row.get::<_, String>(12)?)?, + }); + } + Ok( + json!({"next_after":records.last().map_or(filter.after.unwrap_or(0),|r|r.id),"records":records}), + ) + } + + pub fn resources(&self) -> Result { + let mut statement = self.0.prepare("SELECT instance,service,min(received_at),max(received_at),count(*) FROM console_records GROUP BY instance,service ORDER BY max(received_at) DESC LIMIT 200")?; + let resources = statement.query_map([],|r| Ok(json!({"instance":r.get::<_,String>(0)?,"service":r.get::<_,String>(1)?,"first_received":r.get::<_,i64>(2)?,"last_received":r.get::<_,i64>(3)?,"records":r.get::<_,i64>(4)?})))?.collect::>>()?; + let batches: i64 = + self.0.query_row("SELECT count(*) FROM console_batches", [], |r| r.get(0))?; + let (records, last_received): (i64, Option) = + self.0.query_row("SELECT count(*),max(received_at) FROM console_records", [], |r| { + Ok((r.get(0)?, r.get(1)?)) + })?; + let errors: i64 = + self.0.query_row("SELECT count(*) FROM console_receive_errors", [], |r| r.get(0))?; + let duplicate_batches: i64 = self.0.query_row( + "SELECT count(*) FROM console_batches WHERE duplicate_of IS NOT NULL", + [], + |r| r.get(0), + )?; + Ok( + json!({"receive_errors":errors,"duplicate_batches":duplicate_batches,"resources":resources,"batches":batches,"records":records,"last_received":last_received,"authority":"OTLP collector observations; runtime status comes from controller","gaps":"unknown"}), + ) + } + + pub fn reject(&self, signal: &str, status: u16, reason: &str, payload: &[u8]) -> Result<()> { + let received = i64::try_from(SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis())?; + self.0.execute("INSERT INTO console_receive_errors(received_at,signal,status,reason,payload) VALUES(?,?,?,?,?)",params![received,signal,status,reason,payload])?; + Ok(()) + } + + pub fn receive_errors(&self, filter: &Filter) -> Result { + let limit = i64::try_from(filter.limit.unwrap_or(100).clamp(1, 200))?; + let mut statement=self.0.prepare("SELECT id,received_at,signal,status,reason,length(payload) FROM console_receive_errors WHERE id>? ORDER BY id LIMIT ?")?; + let errors=statement.query_map(params![filter.after.unwrap_or(0),limit],|r|Ok(json!({"id":r.get::<_,i64>(0)?,"received_at":r.get::<_,i64>(1)?,"signal":r.get::<_,String>(2)?,"status":r.get::<_,u16>(3)?,"reason":r.get::<_,String>(4)?,"wire_bytes":r.get::<_,i64>(5)?})))?.collect::>>()?; + Ok( + json!({"errors":errors,"next_after":errors.last().and_then(|e|e["id"].as_i64()).unwrap_or(filter.after.unwrap_or(0))}), + ) + } + + pub fn rejected_body(&self, id: i64) -> Result>> { + use rusqlite::OptionalExtension; + Ok(self + .0 + .query_row("SELECT payload FROM console_receive_errors WHERE id=?", [id], |r| r.get(0)) + .optional()?) + } + + pub fn batch(&self, id: i64) -> Result)>> { + use rusqlite::OptionalExtension; + Ok(self + .0 + .query_row("SELECT encoding,payload FROM console_batches WHERE id=?", [id], |r| { + Ok((r.get(0)?, r.get(1)?)) + }) + .optional()?) + } +} diff --git a/src/console/tests.rs b/src/console/tests.rs new file mode 100644 index 00000000..f6246a67 --- /dev/null +++ b/src/console/tests.rs @@ -0,0 +1,406 @@ +//! Collector HTTP contracts. Inputs use the standard OTLP encoder, not Braid's decoder. +use super::{api, storage::Storage}; +use opentelemetry_proto::tonic::{ + collector::{ + logs::v1::ExportLogsServiceRequest, metrics::v1::ExportMetricsServiceRequest, + trace::v1::ExportTraceServiceRequest, + }, + common::v1::{AnyValue, KeyValue, any_value}, + logs::v1::{LogRecord, ResourceLogs, ScopeLogs}, + metrics::v1::{ + Gauge, Metric, NumberDataPoint, ResourceMetrics, ScopeMetrics, metric, number_data_point, + }, + resource::v1::Resource, + trace::v1::{ResourceSpans, ScopeSpans, Span}, +}; +use prost::Message as _; +use reqwest::StatusCode; +use serde_json::Value; +use std::{io::Write as _, path::PathBuf}; + +struct Collector { + root: PathBuf, + url: String, + client: reqwest::Client, + stop: Option>, + server: Option>, +} + +impl Collector { + async fn new() -> Self { + let root = std::env::temp_dir().join(format!("braid-collector-{}", uuid::Uuid::now_v7())); + let mut collector = Self { + root, + url: String::new(), + client: reqwest::Client::builder() + .timeout(std::time::Duration::from_secs(5)) + .build() + .unwrap(), + stop: None, + server: None, + }; + collector.start().await; + collector + } + + async fn start(&mut self) { + let storage = Storage::open(&self.root.join("observations.sqlite3")); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + self.url = format!("http://{}", listener.local_addr().unwrap()); + let app = api::routes(storage); + let (stop, stopped) = tokio::sync::oneshot::channel(); + self.stop = Some(stop); + self.server = Some(tokio::spawn(async move { + axum::serve(listener, app) + .with_graceful_shutdown(async { + let _ = stopped.await; + }) + .await + .unwrap(); + })); + } + + async fn shutdown(&mut self) { + self.stop.take().unwrap().send(()).unwrap(); + self.server.take().unwrap().await.unwrap(); + } + + async fn get(&self, path: &str) -> Value { + self.client + .get(format!("{}{path}", self.url)) + .send() + .await + .unwrap() + .error_for_status() + .unwrap() + .json() + .await + .unwrap() + } + + async fn export(&self, signal: &str, encoding: &str, body: &[u8]) -> reqwest::Response { + self.client + .post(format!("{}/v1/{signal}", self.url)) + .header("content-type", "application/x-protobuf") + .header("content-encoding", encoding) + .body(body.to_vec()) + .send() + .await + .unwrap() + } +} + +impl Drop for Collector { + fn drop(&mut self) { + if let Some(server) = &self.server { + server.abort(); + } + let _ = std::fs::remove_dir_all(&self.root); + } +} + +fn attribute(key: &str, value: &str) -> KeyValue { + KeyValue { + key: key.into(), + value: Some(AnyValue { value: Some(any_value::Value::StringValue(value.into())) }), + ..KeyValue::default() + } +} + +fn resource() -> Resource { + Resource { + attributes: vec![ + attribute("service.instance.id", "instance-A"), + attribute("service.name", "contract-service"), + attribute("braid.session.id", "resource-session"), + ], + ..Resource::default() + } +} + +fn trace_body() -> Vec { + ExportTraceServiceRequest { + resource_spans: vec![ResourceSpans { + resource: Some(resource()), + scope_spans: vec![ScopeSpans { + spans: vec![Span { + trace_id: vec![0x11; 16], + span_id: vec![0x22; 8], + name: "contract-span".into(), + start_time_unix_nano: 100, + end_time_unix_nano: 200, + attributes: vec![ + attribute("braid.provider_session.id", "span-session"), + attribute("braid.turn.id", "turn-A"), + ], + ..Span::default() + }], + ..ScopeSpans::default() + }], + ..ResourceSpans::default() + }], + } + .encode_to_vec() +} + +fn log_body() -> Vec { + ExportLogsServiceRequest { + resource_logs: vec![ResourceLogs { + resource: Some(resource()), + scope_logs: vec![ScopeLogs { + log_records: vec![LogRecord { + body: Some(AnyValue { + value: Some(any_value::Value::StringValue("retained evidence".into())), + }), + trace_id: vec![0x11; 16], + span_id: vec![0x22; 8], + time_unix_nano: 150, + attributes: vec![ + attribute("braid.session.id", "log-session"), + attribute("braid.turn.id", "turn-B"), + ], + ..LogRecord::default() + }], + ..ScopeLogs::default() + }], + ..ResourceLogs::default() + }], + } + .encode_to_vec() +} + +fn metric_body() -> Vec { + ExportMetricsServiceRequest { + resource_metrics: vec![ResourceMetrics { + resource: Some(resource()), + scope_metrics: vec![ScopeMetrics { + metrics: vec![Metric { + name: "contract.gauge".into(), + data: Some(metric::Data::Gauge(Gauge { + data_points: vec![NumberDataPoint { + time_unix_nano: 150, + value: Some(number_data_point::Value::AsInt(42)), + ..NumberDataPoint::default() + }], + })), + ..Metric::default() + }], + ..ScopeMetrics::default() + }], + ..ResourceMetrics::default() + }], + } + .encode_to_vec() +} + +#[tokio::test] +async fn otlp_signals_raw_bytes_duplicates_and_cursor_pages_survive_reopening() { + let mut collector = Collector::new().await; + let trace = trace_body(); + let mut gzip = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); + gzip.write_all(&log_body()).unwrap(); + let log = gzip.finish().unwrap(); + let metric = metric_body(); + let millis = + || std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_millis(); + let earliest = millis(); + for (signal, encoding, body) in [ + ("traces", "identity", trace.as_slice()), + ("logs", "gzip", log.as_slice()), + ("metrics", "identity", metric.as_slice()), + ("traces", "identity", trace.as_slice()), + ] { + let response = collector.export(signal, encoding, body).await; + assert_eq!(response.status(), StatusCode::OK); + assert_eq!(response.headers()["content-type"], "application/x-protobuf"); + assert!(response.bytes().await.unwrap().is_empty()); + } + let page = collector.get("/api/records?limit=2&instance=instance-A").await; + let first = page["records"].as_array().unwrap(); + assert_eq!(first.len(), 2); + assert_eq!(first[0]["signal"], "traces"); + assert_eq!(first[0]["session"], "span-session"); + assert_eq!(first[0]["turn_id"], "turn-A"); + assert_eq!(first[0]["trace_id"], "11111111111111111111111111111111"); + assert_eq!(first[0]["data"]["name"], "contract-span"); + assert_eq!(first[1]["signal"], "logs"); + assert_eq!(first[1]["session"], "log-session"); + assert_eq!(first[1]["data"]["body"]["stringValue"], "retained evidence"); + assert_eq!(first[1]["data"]["timeUnixNano"], "150"); + assert!((earliest..=millis()).contains(&u128::from(first[1]["received_at"].as_u64().unwrap()))); + for record in first { + assert_eq!(record["service"], "contract-service"); + assert!(record["duplicate_of"].is_null()); + } + let cursor = page["next_after"].as_i64().unwrap(); + let first_batch = first[0]["batch_id"].clone(); + let log_batch = first[1]["batch_id"].as_i64().unwrap(); + collector.shutdown().await; + collector.start().await; + assert_eq!(collector.get("/api/records?limit=2&instance=instance-A").await, page); + let page = + collector.get(&format!("/api/records?after={cursor}&limit=2&instance=instance-A")).await; + let remaining = page["records"].as_array().unwrap(); + assert_eq!(remaining.len(), 2); + assert_eq!(remaining[0]["signal"], "metrics"); + assert_eq!(remaining[0]["session"], "resource-session"); + assert_eq!(remaining[0]["data"]["name"], "contract.gauge"); + assert_eq!(remaining[0]["data"]["gauge"]["dataPoints"][0]["asInt"], 42); + assert_eq!(remaining[1]["signal"], "traces"); + assert_eq!(remaining[1]["duplicate_of"], first_batch); + let cursor = page["next_after"].as_i64().unwrap(); + assert!( + collector.get(&format!("/api/records?after={cursor}")).await["records"] + .as_array() + .unwrap() + .is_empty() + ); + for (filter, expected) in [ + ("signal=logs", vec!["logs"]), + ("session=span-session", vec!["traces", "traces"]), + ("turn=turn-B", vec!["logs"]), + ("trace=11111111111111111111111111111111", vec!["traces", "logs", "traces"]), + ("instance=absent", vec![]), + ("signal=logs&turn=turn-A", vec![]), + ] { + let page = collector.get(&format!("/api/records?{filter}")).await; + let signals = page["records"] + .as_array() + .unwrap() + .iter() + .map(|record| record["signal"].as_str().unwrap()) + .collect::>(); + assert_eq!(signals, expected, "{filter}"); + } + let raw = collector + .client + .get(format!("{}/api/batches/{log_batch}", collector.url)) + .send() + .await + .unwrap(); + assert_eq!(raw.status(), StatusCode::OK); + assert_eq!(raw.headers()["x-otlp-content-encoding"], "gzip"); + assert_eq!(raw.bytes().await.unwrap().as_ref(), log); + let resources = collector.get("/api/resources").await; + assert_eq!(resources["batches"], 4); + assert_eq!(resources["records"], 4); + assert_eq!(resources["duplicate_batches"], 1); + collector.shutdown().await; +} + +// google.rpc.Status field numbers are an independent HTTP error wire contract. +#[derive(prost::Message)] +struct ErrorStatus { + #[prost(int32, tag = "1")] + code: i32, + #[prost(string, tag = "2")] + message: String, +} + +async fn expect_error(response: reqwest::Response, status: StatusCode, code: i32, reason: &str) { + assert_eq!(response.status(), status); + assert_eq!(response.headers()["content-type"], "application/x-protobuf"); + let error = ErrorStatus::decode(response.bytes().await.unwrap()).unwrap(); + assert_eq!(error.code, code); + assert!(error.message.contains(reason), "{}", error.message); +} + +#[tokio::test] +async fn malformed_exports_reach_their_expected_guard_and_retain_rejected_bytes() { + let mut collector = Collector::new().await; + let valid = log_body(); + let invalid = [ + ( + "application/x-protobuf", + "br", + &[1][..], + StatusCode::UNSUPPORTED_MEDIA_TYPE, + "unsupported Content-Encoding: br", + ), + ( + "application/x-protobuf", + "identity", + &[0xff][..], + StatusCode::BAD_REQUEST, + "decode OTLP logs protobuf", + ), + ( + "application/x-protobuf", + "gzip", + &[0x1f, 0x00][..], + StatusCode::BAD_REQUEST, + "decode gzip OTLP body", + ), + ( + "application/json", + "identity", + valid.as_slice(), + StatusCode::UNSUPPORTED_MEDIA_TYPE, + "Content-Type", + ), + ]; + for (content_type, encoding, body, status, reason) in invalid { + let response = collector + .client + .post(format!("{}/v1/logs", collector.url)) + .header("content-type", content_type) + .header("content-encoding", encoding) + .body(body.to_vec()) + .send() + .await + .unwrap(); + expect_error(response, status, 3, reason).await; + } + assert_eq!(collector.get("/api/resources").await["batches"], 0); + collector.shutdown().await; + collector.start().await; + let page = collector.get("/api/receive-errors").await; + let errors = page["errors"].as_array().unwrap(); + assert_eq!(errors.len(), invalid.len()); + for (error, (_, _, body, status, reason)) in errors.iter().zip(invalid) { + assert_eq!(error["status"], status.as_u16()); + assert!(error["reason"].as_str().unwrap().contains(reason)); + let id = error["id"].as_i64().unwrap(); + let raw = collector + .client + .get(format!("{}/api/receive-errors/{id}", collector.url)) + .send() + .await + .unwrap() + .error_for_status() + .unwrap() + .bytes() + .await + .unwrap(); + assert_eq!(raw.as_ref(), body, "{reason}"); + } + collector.shutdown().await; +} + +#[tokio::test] +async fn record_storage_failure_is_retryable_and_does_not_leave_a_partial_batch() { + let mut collector = Collector::new().await; + let db = rusqlite::Connection::open(collector.root.join("observations.sqlite3")).unwrap(); + // Fail after the batch INSERT through SQLite itself, without replacing the storage owner. + db.execute_batch("CREATE TRIGGER fail_record BEFORE INSERT ON console_records BEGIN SELECT RAISE(ABORT, 'injected record storage failure'); END;").unwrap(); + expect_error( + collector.export("logs", "identity", &log_body()).await, + StatusCode::SERVICE_UNAVAILABLE, + 14, + "injected record storage failure", + ) + .await; + let resources = collector.get("/api/resources").await; + assert_eq!(resources["records"], 0); + assert_eq!(resources["batches"], 0); + assert_eq!(resources["receive_errors"], 1); + db.execute_batch("DROP TRIGGER fail_record").unwrap(); + drop(db); + let response = collector.export("logs", "identity", &log_body()).await; + assert_eq!(response.status(), StatusCode::OK); + let records = collector.get("/api/records").await; + assert_eq!(records["records"].as_array().unwrap().len(), 1); + assert_eq!(records["records"][0]["data"]["body"]["stringValue"], "retained evidence"); + assert_eq!(collector.get("/api/resources").await["duplicate_batches"], 0); + collector.shutdown().await; +} diff --git a/src/console/web/console.css b/src/console/web/console.css new file mode 100644 index 00000000..c59682d9 --- /dev/null +++ b/src/console/web/console.css @@ -0,0 +1,355 @@ +:root { + color-scheme:light; + --ink:#202a29; + --muted:#566863; + --line:#dce3df; + --paper:#f6f8f5; + --accent:#126b54; + --danger:#a53531; + --warm:#f0f4ed; + font-family:Inter,ui-sans-serif,system-ui,-apple-system,"PingFang SC",sans-serif; + font-size:14px +} +* { + box-sizing:border-box +} +body { + margin:0; + background:var(--paper); + color:var(--ink) +} +aside { + position:fixed; + inset:0 auto 0 0; + width:224px; + padding:30px 20px; + border-right:1px solid var(--line); + background:#edf2eb; + display:flex; + flex-direction:column +} +.brand { + display:flex; + align-items:center; + gap:9px; + color:var(--ink); + text-decoration:none; + font-size:20px; + font-weight:700 +} +.brand small { + font-size:11px; + font-weight:500; + color:var(--muted) +} +.mark { + display:block; + flex-shrink:0; + width:32px; + height:32px +} +nav { + margin-top:40px; + display:grid; + gap:8px +} +nav a { + padding:12px; + border-radius:8px; + text-decoration:none; + color:var(--muted) +} +nav a:hover,nav a[aria-current=page] { + background:#fff; + color:var(--accent) +} +main { + margin-left:224px; + padding:36px 44px; + max-width:1580px +} +header { + display:flex; + justify-content:space-between; + align-items:center; + margin-bottom:28px +} +h1 { + font-size:28px; + font-weight:600; + letter-spacing:-.7px; + margin:5px 0 +} +h2 { + font-size:17px; + font-weight:600; + margin:0 0 18px +} +button,input,select,textarea { + font:inherit +} +button { + cursor:pointer; + border:1px solid var(--line); + border-radius:7px; + padding:9px 14px; + background:white; + color:var(--ink) +} +button:hover { + border-color:var(--accent); + color:var(--accent) +} +button:disabled { + cursor:wait; + opacity:.55 +} +button.primary { + background:var(--accent); + color:white; + border-color:var(--accent) +} +button.danger { + color:var(--danger) +} +a { + color:var(--accent) +} +input,select,textarea { + border:1px solid #cdd7d1; + background:white; + border-radius:6px; + padding:9px 10px; + max-width:100%; + color:var(--ink) +} +textarea { + width:100%; + min-height:120px; + resize:vertical +} +label { + display:grid; + gap:7px; + font-size:12px; + color:var(--muted) +} +input:focus,select:focus,textarea:focus,button:focus-visible,a:focus-visible { + outline:2px solid #3b9278; + outline-offset:2px +} +.panel { + border:1px solid var(--line); + background:white; + border-radius:12px; + padding:22px; + margin-bottom:20px +} +.counts { + display:flex; + flex-wrap:wrap; + gap:12px 28px; + margin:0 0 24px; + padding:0 0 18px; + border-bottom:1px solid var(--line) +} +.counts dt {font-size:12px;color:var(--muted)} +.counts dd {margin:4px 0 0;font-weight:600;font-variant-numeric:tabular-nums} +.counts .bad {padding:0 6px} +.panel h2 {overflow-wrap:anywhere} +.muted,.meta { + color:var(--muted); + font-size:12px +} +.meta { + line-height:1.8; + overflow-wrap:anywhere +} +.toolbar,.row,.actions { + display:flex; + gap:12px; + align-items:center; + flex-wrap:wrap +} +.toolbar { + margin-bottom:20px +} +.toolbar label { + flex:1; + min-width:140px +} +.actions { + margin-top:16px +} +.badge { + display:inline-block; + background:var(--warm); + border-radius:5px; + padding:3px 7px; + font-size:11px; + color:var(--accent) +} +.bad { + color:var(--danger); + background:#fff0ed +} +.notice { + padding:14px 18px; + border:1px solid var(--line); + background:white; + border-radius:8px; + margin-bottom:20px; + white-space:pre-wrap; + overflow-wrap:anywhere +} +.notice.error { + background:#fff5f2; + border-color:#e9b6ac; + color:var(--danger) +} +table { + border-collapse:collapse; + width:100%; + font-size:13px +} +th { + text-align:left; + font-weight:500; + color:var(--muted); + font-size:11px; + padding:11px 12px; + border-bottom:1px solid var(--line) +} +td { + padding:13px 12px; + border-bottom:1px solid #edf1ed; + vertical-align:top; + overflow-wrap:anywhere +} +tbody tr:last-child td { + border-bottom:0 +} +.table-wrap { + overflow:auto +} +.link-button { + padding:0; + border:0; + background:transparent; + color:var(--accent); + text-align:left +} +.empty { + padding:4px 0; + color:var(--muted); + line-height:1.8 +} +.body { + white-space:pre-wrap; + overflow-wrap:anywhere; + line-height:1.8 +} +.record { + padding:18px 0; + border-bottom:1px solid var(--line) +} +.record:last-child { + border-bottom:0 +} +.record header { + margin:0 0 10px; + justify-content:flex-start; + gap:10px +} +pre { + white-space:pre-wrap; + overflow-wrap:anywhere; + max-height:540px; + overflow:auto; + background:#f5f7f4; + padding:15px; + border-radius:7px; + font-size:12px; + line-height:1.6 +} +details { + margin-top:12px +} +summary { + cursor:pointer; + color:var(--muted); + font-size:12px +} +.timeline-row { + display:grid; + grid-template-columns:minmax(160px,35%) 1fr; + gap:14px; + padding:12px 0; + align-items:center; + border-bottom:1px solid #edf1ed +} +.timeline-track { + height:20px; + position:relative; + background:#f3f5f1; + border-radius:5px +} +.timeline-bar { + position:absolute; + height:20px; + background:#88bba7; + min-width:3px; + border-radius:4px +} +.timeline-bar.error { + background:#cf7a6e +} +.split { + display:grid; + grid-template-columns:1fr 1fr; + gap:20px +} +.form-grid { + display:grid; + gap:15px +} +.metric-point { + font-family:ui-monospace,monospace; + font-size:12px +} +@media(max-width:900px) { + aside { + position:static; + width:auto; + padding:15px 20px; + border-right:0; + border-bottom:1px solid var(--line) +} +nav { + margin-top:18px; + display:flex; + flex-wrap:wrap; + gap:4px +} +nav a { + padding:8px 10px +} +main { + margin-left:0; + padding:24px 20px +} +.split { + grid-template-columns:1fr +} + +} +@media(prefers-reduced-motion:no-preference) { + button { + transition:border-color .15s,color .15s +} + +} + +[hidden] { display: none !important; } +.confirm-overlay { position:fixed; inset:0; background:#17282066; z-index:50; display:grid; place-items:center; padding:24px; } +.confirm-overlay .panel { width:min(480px,100%); box-shadow:0 20px 80px #10291b44; } diff --git a/src/console/web/console.js b/src/console/web/console.js new file mode 100644 index 00000000..13c4a6d8 --- /dev/null +++ b/src/console/web/console.js @@ -0,0 +1,598 @@ +'use strict'; +const content=document.getElementById('content'), notice=document.getElementById('notice'); +let generation=0,controlPending=false,activeHash=location.hash||'#overview'; +const labels={ + overview:'概览',traces:'Trace 时间轴',logs:'日志与会话',metrics:'指标',objects:'协作空间' +}; +function el(tag,attrs={},...children){ + const n=document.createElement(tag); + for(const [k,v] of Object.entries(attrs)){ + if(k==='class')n.className=v; + else if(k.startsWith('on'))n.addEventListener(k.slice(2),v); + else if(v!==undefined&&v!==null)n.setAttribute(k,v); + } + for(const c of children.flat(Infinity)){ + if(c!==null&&c!==undefined)n.append(c instanceof Node?c:document.createTextNode(String(c))); + } + return n; +} +function json(v){ + return JSON.stringify(v,null,2)??'未记录'; +} +function val(v){ + if(!v||typeof v!=='object')return v; + if('stringValue'in v)return v.stringValue; + if('intValue'in v)return v.intValue; + if('doubleValue'in v)return v.doubleValue; + if('boolValue'in v)return v.boolValue; + if(v.arrayValue)return(v.arrayValue.values||[]).map(val); + if(v.kvlistValue)return Object.fromEntries((v.kvlistValue.values||[]).map(a=>[a.key,val(a.value)])); + return v; +} +function attrs(v){ + return Object.fromEntries((v||[]).map(a=>[a.key,val(a.value)])); +} +function text(v){ + return typeof v==='string'?v:json(val(v)); +} +function stamp(v){ + if(!v)return'未收到'; + const d=new Date(Number(v)); + return Number.isNaN(d.valueOf())?String(v):d.toLocaleString(); +} +function nanos(v){ + if(!v||String(v)==='0')return'事件时间未记录'; + try{ + return stamp(Number(BigInt(v)/1000000n)); + } + catch{ + return String(v); + } +} +function badge(v,bad=false){ + return el('span',{ + class:'badge'+(bad?' bad':'') + },v); +} +function raw(v,label='完整记录'){ + const details=el('details',{},el('summary',{},label)); + details.addEventListener('toggle',()=>{ + if(details.open && details.childElementCount===1)details.append(el('pre',{},json(v))); + }); + return details; +} +function panel(title,...children){ + return el('section',{ + class:'panel' + },title?el('h2',{},title):null,...children); +} +function empty(message='尚未收到记录'){ + return el('div',{ + class:'empty' + },message); +} +function showError(e){ + notice.replaceChildren(el('div',{ + class:'notice error' + },e.message||String(e))); +} +async function api(path,body){ + const r=await fetch(path,body===undefined?{signal:AbortSignal.timeout(30000)} + :{ + method:'POST',signal:AbortSignal.timeout(30000),headers:{ + 'Content-Type':'application/json' + },body:JSON.stringify(body) + }); + const t=await r.text(); + let v; + try{ + v=JSON.parse(t); + } + catch{ + v=t; + } + if(!r.ok){const error=new Error(`HTTP ${r.status} ${r.statusText}\n${text(v)}`);error.status=r.status;error.body=v;throw error;} + return v; +} +function query(v){ + return new URLSearchParams(Object.entries(v).filter(([,x])=>x!==''&&x!==undefined&&x!==null)).toString(); +} +function button(label,action,kind=''){ + return el('button',{ + type:'button',class:kind,onclick:async e=>{ + const target=e.currentTarget;target.disabled=true;try{ + await action(); + } + catch(err){ + showError(err); + } + finally{ + if(target.isConnected)target.disabled=false; + } + } + },label); +} +function field(name,value='',type='text'){ + const input=el(type==='textarea'?'textarea':'input',type==='textarea'?{} + :{ + type,value + }); + if(type==='textarea')input.value=value; + return{ + input,node:el('label',{},name,input) + }; +} +function table(headers,rows){ + return el('div',{ + class:'table-wrap' + },el('table',{},el('thead',{},el('tr',{},headers.map(h=>el('th',{},h)))),el('tbody',{},rows.map(r=>el('tr',{},r.map(c=>el('td',{},c))))))); +} +async function overview(token){ + const capabilities=await api('/api/console'); + const observation=api('/api/resources').then(resources=>({resources}),error=>({error})); + const [runtime,harness]=await Promise.all([capabilities.harness.configured?api('/api/runtime').catch(e=>({unavailable:e.message})):null,capabilities.harness.configured?api('/api/harness/snapshot').catch(e=>({error:e.message})):null]); + if(token!==generation)return; + const summary=el('div'),details=el('div'); + content.replaceChildren(summary,panel('Harness 权威状态',!runtime?empty('未接入 Harness;平台和 Collector 可独立使用。'):runtime.unavailable?el('div',{ + class:'notice error' + },runtime.unavailable):runtimePanel(runtime)),panel('平台接入',capabilities.platform.configured?el('p',{},`${capabilities.platform.endpoint} · ${capabilities.platform.managed?'Console 托管独立监听':'外部独立监听'} · Harness 上游 ${capabilities.harness.backend||'未接入'}`):empty('未声明内建平台。GitHub Harness 的启停与观测仍可使用;此处不提供 GitHub 对象编辑。')),harness?panel('Harness 调度事实',raw(harness,'Session、Turn、队列、Assignment 与 Worktree')):el('div'),details); + const {resources,error}=await observation; + if(token!==generation)return; + if(error){ + summary.replaceWith(panel('采集状态',el('div',{class:'notice error'},error.message))); + details.remove(); + return; + } + const counts=el('dl',{class:'counts','aria-label':'采集摘要'}, + ...[['已接收记录',resources.records??0],['接收批次',resources.batches??0],['资源来源',(resources.resources||[]).length],['接收错误',resources.receive_errors??0],['重复批次',resources.duplicate_batches??0],['最近接收',stamp(resources.last_received)]].map(([title,value])=>el('div',{},el('dt',{},title),el('dd',{class:title==='接收错误'&&value?'bad':null},value)))); + summary.replaceWith(counts); + details.replaceWith(panel('采集来源',(resources.resources||[]).length?table(['实例','服务','首次 / 最近接收','记录数'],resources.resources.map(r=>[r.instance||'未标识',r.service||'未标识',`${stamp(r.first_received)} / ${stamp(r.last_received)}`,r.records])):empty('Collector 正在等待 OTLP 数据。请检查 Braid 的 exporter 目标。')),panel('数据边界',el('p',{ + class:'body' + },'接收时间表示 Collector 收到数据的时刻,不是运行完成时间。采样、网络错误或 exporter 停止都可能造成未收到的内容。没有上游序列与交付回执时,采集缺口不可量化;Trace 缺少父 Span、Transcript 缺少消息均保留为未确认。'),raw(resources,'完整采集状态'))); + if(resources.receive_errors){ + try{ + const errors=await api('/api/receive-errors?limit=100'); + if(token===generation)content.append(panel('接收错误(最近已加载,完整原因保留)',table(['接收时刻','信号 / HTTP','原因','原始数据'],errors.errors.map(e=>[stamp(e.received_at),`${e.signal} / ${e.status}`,el('pre',{},e.reason),el('a',{ + href:'/api/receive-errors/'+encodeURIComponent(e.id) + },'下载失败请求正文')])))); + } + catch(e){ + if(token===generation)content.append(panel('接收错误',el('div',{class:'notice error'},e.message))); + } + } +} +function runtimePanel(runtime){ + const transport=el('input',{ + type:'checkbox' + }),receipt=el('div'); + const mode=el('select',{'aria-label':'运行方式'},el('option',{value:'serve'},'serve · 常驻响应'),el('option',{value:'run',disabled:runtime.upstream==='builtin'?undefined:true},'run · 根任务自主推进(built-in)')); + const inputKind=el('select',{'aria-label':'根任务输入'},el('option',{value:'description'},'创建根任务'),el('option',{value:'root'},'已有根 Issue')); + const description=el('textarea',{'aria-label':'任务描述',placeholder:'描述要完成的任务',rows:4}); + // Preserve the bound input until edited; textarea values normalize CRLF. + let recentDescription=null; + description.addEventListener('input',()=>{recentDescription=null;}); + const rootIssue=el('input',{type:'number',min:1,step:1,'aria-label':'根 Issue 编号',placeholder:'根 Issue 编号'}); + const runId=el('input',{'aria-label':'Run ID',value:requestId(),maxlength:96}); + const deliveryRef=el('input',{'aria-label':'交付 Git ref',value:'refs/heads/braid/run/'+runId.value}); + const concurrency=el('input',{type:'number',min:1,max:64,step:1,value:2,'aria-label':'最大并发 Braid 轮次'}); + const runInputs=el('div',{},el('label',{},'Run ID ',runId),el('label',{},'根任务输入 ',inputKind),description,rootIssue,el('label',{},'交付 Git ref ',deliveryRef),el('label',{},'最大并发 Braid 轮次 ',concurrency)); + function rememberRunInputs(){ + for(const input of runInputs.querySelectorAll('input,textarea,select')){ + input.dataset.draft='true';input.dataset.initialValue=input.value; + } + } + rememberRunInputs(); + function updateInputs(){ + runInputs.hidden=mode.value!=='run'; + transport.disabled=mode.value==='run'; + if(transport.disabled)transport.checked=false; + description.hidden=inputKind.value!=='description'; + rootIssue.hidden=inputKind.value!=='root'; + } + mode.addEventListener('change',updateInputs); + inputKind.addEventListener('change',updateInputs); + updateInputs(); + const fillRecent=runtime.run_request?button('填入最近运行参数',()=>{ + const request=runtime.run_request; + mode.value='run'; + runId.value=request.runId; + inputKind.value=request.rootIssue==null?'description':'root'; + rootIssue.value=request.rootIssue??''; + recentDescription=request.description??null; + description.value=recentDescription??''; + deliveryRef.value=request.deliveryRef; + concurrency.value=request.maxConcurrency??2; + updateInputs(); + rememberRunInputs(); + }):null; + async function command(operation){ + if(controlPending)return; + controlPending=true; + const id=requestId(); + let submitted=false; + receipt.replaceChildren(el('p',{ + class:'meta' + },`请求 ${id} · 等待权威端受理`)); + try{ + const payload={request_id:id,operation,expected_generation:runtime.generation,transport_only:operation==='start'&&transport.checked}; + if(operation==='start'&&mode.value==='run'){ + const root=Number(rootIssue.value),limit=Number(concurrency.value); + if(!/^[A-Za-z0-9_-]{1,96}$/.test(runId.value))throw new Error('Run ID 须为 1–96 个英文字母、数字、连字符或下划线。'); + if(inputKind.value==='root'&&(!Number.isSafeInteger(root)||root<1))throw new Error('请填写有效的根 Issue 编号。'); + if(inputKind.value==='description'&&!description.value.trim())throw new Error('请填写任务描述。'); + if(!deliveryRef.value.trim())throw new Error('请填写交付 Git ref。'); + if(!Number.isSafeInteger(limit)||limit<1||limit>64)throw new Error('最大并发 Braid 轮次须为 1–64 的整数。'); + payload.run_request={runId:runId.value,rootIssue:inputKind.value==='root'?root:null,description:inputKind.value==='description'?(recentDescription??description.value):null,deliveryRef:deliveryRef.value,maxConcurrency:limit}; + } + const submittedRunInputs=payload.run_request?[...runInputs.querySelectorAll('input,textarea,select')].map(input=>[input,input.value]):[]; + submitted=true; + const result=await api('/api/runtime/commands',payload); + for(const [input,value] of submittedRunInputs)input.dataset.initialValue=value; + receipt.replaceChildren(el('div',{ + class:'row' + },badge(result.state||'未报告'),el('code',{},result.request_id||id)),raw(result,'控制受理回执'),el('p',{ + class:'body' + },'受理不等于生命周期完成。点击刷新,核对新的运行状态与 Generation。')); + } + catch(e){ + showError(e); + if(!submitted){receipt.replaceChildren(el('p',{class:'notice error'},e.message));return;} + receipt.replaceChildren(el('p',{ + class:'body' + },'请求是否受理尚未确认。请查询回执,不要根据网络错误重复操作。'),el('code',{},id),button('查询回执',async()=>receipt.replaceChildren(raw(await api('/api/runtime/receipts/'+encodeURIComponent(id)),'完整运行控制回执')))); + } + finally{controlPending=false;} + } + return el('div',{},el('div',{ + class:'row' + },badge(runtime.state,runtime.state==='blocked'),el('strong',{},runtime.instance||'未标识实例'),el('span',{ + class:'meta' + },runtime.repository||'')),el('p',{ + class:'meta' + },`Generation ${runtime.generation||'无'} · Provider ${runtime.provider_enabled?'启用':'禁用'} · Ready ${runtime.health?.ready===true?'是':'否 / 未报告'} · 停止确认 ${runtime.stop_confirmed===true?'是':'否'}`),runtime.run||runtime.run_request?panel('自主运行',el('p',{},`Run ${runtime.run?.runId||runtime.run_request?.runId||'未报告'} · Root #${runtime.run?.rootIssue||runtime.run_request?.rootIssue||'待创建'} · 结果 ${runtime.run?.state||'受理中'}`),el('p',{},`交付 ref ${runtime.run_request?.deliveryRef||'未报告'} · Commit ${runtime.run?.deliveryCommit||'未交付'}`),runtime.run?.reason?el('p',{class:runtime.run.stopConfirmed===false||['blocked','failed'].includes(runtime.run.state)?'notice error':'meta'},runtime.run.reason):null,el('p',{class:'meta'},'运行结果与 Harness 停止状态分别显示;completed 不等于应用需求验收通过。')):null,el('p',{ + class:'meta' + },`OTLP ${runtime.telemetry?.endpoint||'未配置'} · 采样 ${runtime.telemetry?.sample_ratio??'未报告'} · Incident ${runtime.telemetry?.incident_mode?'开启':'关闭'}`),runtime.evidence?el('p',{ + class:'meta' + },`已发原生内容 ${runtime.evidence.emitted_payloads} · 未采样 ${runtime.evidence.unsampled_payloads} · 未关联 ${runtime.evidence.unassigned_payloads} · 已注册 Session ${runtime.evidence.registered_sessions}(本 Generation)`):null,runtime.error?el('div',{ + class:'notice error' + },text(runtime.error)):null,runtime.health?.last_error?el('div',{ + class:'notice error' + },text(runtime.health.last_error)):null,el('label',{ + class:'row' + },transport,'仅运行传输与调度,不启动 Provider / 模型'),el('label',{},'运行方式 ',mode),fillRecent,runInputs,el('div',{ + class:'actions' + },button('启动 Braid',()=>command('start'),'primary'),button('停止 Braid',async()=>{ + if(await confirmAction('停止本实例 Harness?平台和 Collector 保持服务。'))await command('stop'); + },'danger')),receipt,raw(runtime,'完整权威运行状态')); +} +async function telemetry(page,token){ + const signal=page==='traces'?'traces':page==='metrics'?'metrics':'logs'; + const instance=field('实例'),session=field('Provider Session'),turn=field('Turn ID'),trace=field('Trace ID'); + const selected=new URLSearchParams(location.hash.split('?')[1]||''); + instance.input.value=selected.get('instance')||''; + session.input.value=selected.get('session')||''; + turn.input.value=selected.get('turn')||''; + trace.input.value=selected.get('trace')||''; + const records=[],target=el('div'); + let after=0,loadSequence=0,filtersApplied={signal,instance:instance.input.value,session:session.input.value,turn:turn.input.value,trace:trace.input.value}; + const more=button('加载更多',()=>load(false)); + const status=el('div',{ + class:'meta' + }); + async function load(reset){ + const sequence=++loadSequence; + const filters=reset?{signal,instance:instance.input.value,session:session.input.value,turn:turn.input.value,trace:trace.input.value}:filtersApplied; + const result=await api('/api/records?'+query({ + ...filters,after:reset?0:after,limit:100 + })); + if(token!==generation||sequence!==loadSequence)return; + if(reset){ + records.length=0; + filtersApplied=filters; + } + records.push(...result.records); + after=result.next_after; + status.textContent=`已加载 ${records.length} 条 · 按接收顺序 · 每页最多 100 条`; + more.hidden=result.records.length<100; + target.replaceChildren(...(!records.length?[empty('当前筛选下尚未收到记录。')]:page==='traces'?renderTraces(records):page==='metrics'?renderMetrics(records):renderLogs(records))); + } + const filters=el('form',{ + class:'toolbar',onsubmit:e=>{ + e.preventDefault();load(true).catch(showError); + } + },instance.node,session.node,turn.node,trace.node,el('button',{ + type:'submit',class:'primary' + },'筛选')); + content.replaceChildren(filters,el('p',{class:'meta'},page==='metrics'?'指标按原始批次与数据点展示,不跨批次求和或去重;重复接收的批次会明确标识。':page==='traces'?'时间轴仅包含已收到并加载的 Span;缺少父 Span 不等于没有父调用。':'只展示已收到记录;Provider 原生事件、流式片段与未关联内容保持原样,不拼造完整会话。'),status,target,more); + await load(true); +} +function recordMeta(r){ + return el('div',{ + class:'meta' + },`${r.duplicate_of?'重复接收(原批次 #'+r.duplicate_of+') · ':''}接收 ${stamp(r.received_at)} · ${r.instance||'实例未标识'} / ${r.service||'服务未标识'}`,el('br'),`Session ${r.session||'未记录'} · Trace ${r.trace_id||'未记录'} · 记录 #${r.id}`,el('br'),r.trace_id?el('a',{ + href:'#traces?trace='+encodeURIComponent(r.trace_id) + },'查看关联 Trace'):null,r.trace_id?' · ':null,r.session?el('a',{ + href:'#logs?session='+encodeURIComponent(r.session) + },'阅读此 Session'):null,r.session?' · ':null,el('a',{ + href:'/api/batches/'+encodeURIComponent(r.batch_id) + },'下载原始 OTLP 批次')); +} +function renderTraces(records){ + const groups=new Map(); + for(const r of records){ + const key=r.trace_id||`未标识 #${r.id}`; + if(!groups.has(key))groups.set(key,[]); + groups.get(key).push(r); + } + return [...groups].map(([id,rows])=>{ + const spans=rows.map(r=>r.data),times=spans.flatMap(s=>[s.startTimeUnixNano,s.endTimeUnixNano]).filter(v=>v&&/^\d+$/.test(v)).map(BigInt),begin=times.length?times.reduce((a,b)=>aa>b?a:b):0n;const spanIds=new Set(spans.map(s=>s.spanId));return panel(`Trace ${id}`,el('div',{ + class:'meta' + },`${rows.length} 个已加载 Span · ${nanos(begin.toString())} · 仅展示已收到区间`),el('a',{ + href:'#logs?trace='+encodeURIComponent(id) + },'阅读关联日志与 Provider Transcript'),...rows.map(r=>{ + const s=r.data,start=/^\d+$/.test(s.startTimeUnixNano||'')?BigInt(s.startTimeUnixNano):begin,finish=/^\d+$/.test(s.endTimeUnixNano||'')?BigInt(s.endTimeUnixNano):start,duration=Number(finish-start)/1e6,range=Number(end-begin)||1;const bar=el('span',{ + class:'timeline-bar'+(s.status?.code===2?' error':'') + });bar.style.left=`${Math.max(0,Math.min(100,Number(start-begin)/range*100))}%`;bar.style.width=`${Math.max(0,Math.min(100,Number(finish-start)/range*100))}%`;return el('div',{ + class:'record' + },el('div',{ + class:'timeline-row' + },el('div',{},el('strong',{},s.name||'未命名 Span'),el('div',{ + class:'meta' + },`${duration.toFixed(2)} ms · ${s.spanId||r.span_id||''}`)),el('div',{ + class:'timeline-track' + },bar)),s.parentSpanId&&!spanIds.has(s.parentSpanId)?el('p',{ + class:'meta' + },`父 Span ${s.parentSpanId} 尚未在已加载数据中找到`):null,recordMeta(r),(s.events||[]).length?el('details',{},el('summary',{},`关联事件 · ${s.events.length}`),...(s.events||[]).map(e=>el('div',{ + class:'record' + },el('strong',{},e.name),el('div',{ + class:'meta' + },nanos(e.timeUnixNano)),raw(e,'完整事件')))):null,raw(r)); + })); + }); +} +function transcript(payload){ + let p=payload; + if(typeof p==='string'){ + try{ + p=JSON.parse(p); + } + catch{ + return el('pre',{},p); + } + } + if(!p||typeof p!=='object')return el('div',{ + class:'body' + },text(p)); + const message=p.message||p.item||p.params?.item||p.params?.message||p; + const blocks=Array.isArray(message.content)?message.content:[]; + return el('div',{},el('div',{ + class:'row' + },badge(p.type||p.method||'原生事件'),message.role?badge(message.role):null),...blocks.map(b=>{ + if(typeof b==='string')return el('div',{ + class:'body' + },b);if(['text','input_text','output_text'].includes(b.type))return el('div',{ + class:'body' + },b.text||'');if(['thinking','reasoning'].includes(b.type))return raw(b,'思考内容');if(['toolCall','function_call'].includes(b.type))return raw(b,`工具调用 · ${b.name||''} · ${b.id||b.call_id||''}`);return raw(b,`原生内容 · ${b.type||'未知'}`); + }),message.output!==undefined?el('pre',{},text(message.output)):null,message.errorMessage?el('div',{ + class:'notice error' + },text(message.errorMessage)):null,!blocks.length?raw(p,'完整原生消息 / 流式事件'):null); +} +function renderLogs(records){ + return [panel('日志 / Provider Transcript',...records.map(r=>{ + const d=r.data,a=attrs(d.attributes),body=val(d.body),name=a['event.name']||a['name']||a['braid.event']||d.eventName||d.severityText||'日志',native=a['provider.transcript'];return el('article',{ + class:'record' + },el('header',{},badge(name,d.severityNumber>=17),el('span',{ + class:'meta' + },nanos(d.timeUnixNano&&d.timeUnixNano!=='0'?d.timeUnixNano:d.observedTimeUnixNano)),r.duplicate_of?badge('重复批次'):null),native!==undefined?transcript(native):el('div',{class:'body'},text(body)),a['observation.correlated']===false?el('p',{class:'meta'},'未关联至权威会话'):null,el('details',{},el('summary',{},'来源、关联与原始记录'),recordMeta(r),el('p',{class:'meta'},`Turn ${r.turn_id||a['braid.turn.id']||a['provider.turn.id']||'未关联'}`),raw(r))); + }))]; +} +function renderMetrics(records){ + return records.map(r=>{ + const d=r.data,kind=['gauge','sum','histogram','exponentialHistogram','summary'].find(k=>d[k]),points=d[kind]?.dataPoints||[];return panel(d.name||'未命名指标',el('div',{ + class:'meta' + },[kind||'未知类型',d.unit||'无单位',d.description].filter(Boolean).join(' · ')),points.length?table(['采样时刻','数值 / 分布','属性'],points.map(p=>[nanos(p.timeUnixNano),el('span',{ + class:'metric-point' + },text(p.asDouble??p.asInt??{ + count:p.count,sum:p.sum,min:p.min,max:p.max,buckets:p.bucketCounts,explicitBounds:p.explicitBounds,quantiles:p.quantileValues + })),text(attrs(p.attributes))])):empty('未记录数据点'),recordMeta(r),raw(r)); + }); +} +async function route(){ + activeHash=location.hash||'#overview'; + const page=location.hash.slice(1).split('?')[0]||'overview',token=++generation; + notice.replaceChildren(); + document.getElementById('page-title').textContent=labels[page]||'概览'; + document.querySelectorAll('nav a').forEach(a=>{ + if(a.hash==='#'+page)a.setAttribute('aria-current','page');else a.removeAttribute('aria-current'); + }); + content.setAttribute('aria-busy','true'); + content.replaceChildren(empty('正在读取…')); + try{ + if(page==='overview'||!labels[page])await overview(token); + else if(page==='objects')await objects(token); + else await telemetry(page,token); + } + catch(e){ + if(token===generation){content.replaceChildren();showError(e);} + } + finally{ + if(token===generation)content.setAttribute('aria-busy','false'); + } +} +document.getElementById('refresh').addEventListener('click',guardedRefresh); +window.addEventListener('hashchange',async()=>{const target=location.hash;if(controlPending||hasDrafts()){history.replaceState(null,'',activeHash);if(controlPending){showError(new Error('控制请求尚未取得回执,暂时不能切换页面。'));return;}if(!await confirmAction('离开此页将丢弃尚未提交的草稿,继续吗?'))return;history.replaceState(null,'',target);}route();}); +function hasDrafts(){return [...content.querySelectorAll('[data-draft]')].some(n=>n.value!==n.dataset.initialValue);} +function confirmAction(message){return new Promise(resolve=>{const overlay=el('div',{class:'confirm-overlay',role:'alertdialog','aria-modal':'true','aria-label':'确认操作'},el('section',{class:'panel'},el('h2',{},'确认操作'),el('p',{class:'body'},message),el('div',{class:'actions'},button('取消',async()=>finish(false)),button('继续',async()=>finish(true),'primary'))));function finish(value){overlay.remove();resolve(value);}overlay.addEventListener('keydown',event=>{if(event.key==='Escape'){event.preventDefault();finish(false);}if(event.key==='Tab'){event.preventDefault();const buttons=[...overlay.querySelectorAll('button')];const index=buttons.indexOf(document.activeElement);buttons[(index+(event.shiftKey?-1:1)+buttons.length)%buttons.length].focus();}});document.body.append(overlay);overlay.querySelector('button').focus();});} +async function guardedRefresh(){if(controlPending){showError(new Error('控制请求尚未取得回执,请等待或查询回执。'));return;}if(hasDrafts()&&!await confirmAction('刷新将丢弃尚未提交的正文、评论与创建草稿,继续吗?'))return;route();} +document.addEventListener('click',async event=>{const anchor=event.target.closest('a[href^="#"]');if(!anchor||anchor.hash===location.hash)return;if(controlPending){event.preventDefault();showError(new Error('控制请求尚未取得回执,暂时不能切换页面。'));return;}if(hasDrafts()){event.preventDefault();if(await confirmAction('离开此页将丢弃尚未提交的正文、评论与创建草稿,继续吗?')){content.querySelectorAll('[data-draft]').forEach(n=>n.dataset.initialValue=n.value);location.hash=anchor.hash;}}}); +window.addEventListener('beforeunload',event=>{if(controlPending||hasDrafts()){event.preventDefault();event.returnValue='';}}); +function requestId(){ + return crypto.randomUUID(); +} +async function objects(token){ + const capabilities=await api('/api/console'); + if(!capabilities.platform.configured){if(token===generation)content.replaceChildren(panel('平台对象',empty('未声明内建平台;当前 Console 不提供 GitHub 对象编辑。Harness 启停与 OTLP 观测可在概览中使用。')));return;} + const [initial,harness]=await Promise.all([api('/api/control/snapshot'),capabilities.harness.configured?api('/api/harness/snapshot').catch(e=>({error:e.message})):null]); + if(token!==generation)return; + const list=el('div'),detail=el('div'),receipt=el('div'); + const createTitle=field('标题'),createBody=field('正文','','textarea'),kind=el('select',{},el('option',{ + value:'issue' + },'Issue'),el('option',{ + value:'pr' + },'Pull Request')),head=field('Head 分支'),base=field('Base 分支'),issue=field('关联 Issue 编号','','number'); + let current=null,selection=0; + const profiles=harness?.profileSuggestions||{}; + let lastRequest=null; + function renderReceipt(value){ + receipt.replaceChildren(panel('控制回执',el('div',{ + class:'row' + },badge(value.state||'未报告'),el('code',{},value.requestId||value.request_id||'')),el('p',{ + class:'body' + },'applied 表示协作对象接受本次请求。它不表示 Agent 已开始、结束或业务已完成。'),value.error?el('div',{class:'notice error'},text(value.error)):null,raw(value,'完整回执'))); + } + async function execute(command,revision){ + if(controlPending)return; + controlPending=true; + const id=requestId(); + lastRequest=id; + receipt.replaceChildren(panel('控制请求',el('p',{ + class:'meta' + },`请求 ${id}`),el('p',{},'正在等待权威端回执…'))); + try{ + const result=await api('/api/control/commands',{ + requestId:id,actor:'human',expectedRevision:revision,command + }); + renderReceipt(result); + if(command.type==='createIssue'||command.type==='createPR'){for(const f of [createTitle,createBody,head,base,issue]){f.input.value='';f.input.dataset.initialValue='';}} + await reload(); + if(current)await select(current.item.number,true); + } + catch(e){ + showError(e); + if(e.body?.requestId&&e.body?.state){renderReceipt(e.body);return;} + receipt.replaceChildren(panel('尚未确认本次请求',el('p',{ + class:'body' + },'请求失败或连接中断不等于写入未发生。请按请求 ID 查询回执,核对对象当前版本。'),el('code',{},id),button('查询此请求回执',async()=>renderReceipt(await api('/api/control/receipts/'+encodeURIComponent(id)))))); + } + finally{controlPending=false;} + } + async function reload(s){ + s??=await api('/api/control/snapshot'); + if(token!==generation)return; + list.replaceChildren(panel('Issue / Pull Request',s.items.length?table(['对象','状态','指派','修订'],s.items.map(v=>{ + const i=v.item;return[button(`#${i.number} ${i.title}`,()=>select(i.number),'link-button'),badge(i.kind+' · '+i.state),i.desired_profile||'未指派',i.revision]; + })):empty('协作空间为空。创建 Issue 开始讨论。'),el('details',{},el('summary',{},'对象来源与调度状态'),el('p',{class:'meta'},`来源 ${s.source} · 观察 ${s.observedAt||'未记录'} · ${capabilities.platform.endpoint}`),harness?raw(harness,'独立 Harness ledger(本页打开时读取)'):el('p',{class:'meta'},'未接入 Harness;平台指派不代表 Agent 正在运行。')))); + } + async function select(number,acceptedRefresh=false){ + if(!acceptedRefresh){if(controlPending){showError(new Error('控制请求尚未取得回执,暂时不能切换对象。'));return;}if(hasDrafts()&&!await confirmAction('切换对象将丢弃尚未提交的编辑与评论,继续吗?'))return;} + const selected=++selection; + const v=await api('/api/control/items/'+number); + if(token!==generation||selected!==selection)return; + current=v; + const i=v.item,title=field('标题',i.title),body=field('正文',i.body,'textarea'),comment=field('新评论','','textarea'),profile=field('指派给 Actor',i.desired_profile||(i.kind==='issue'?profiles.issue:profiles.pr)||''),linked=field('关联 PR 编号','','number'); + const reply=field('回复评论编号(可选)','','number'); + const merged=v.merge?.lifecycle==='applied'; + const heading=el('div',{ + class:'row' + },el('h2',{},`#${i.number} ${i.title}`),badge(i.kind+' · '+(merged?'merged':i.state))); + const actions=el('div',{ + class:'actions' + },button('保存标题与正文',()=>execute({ + type:'edit',number:i.number,title:title.input.value,body:body.input.value + },i.revision),'primary'),button('指派',()=>execute({ + type:'assign',number:i.number,actor:profile.input.value + },i.revision)),button('解除指派',()=>execute({ + type:'unassign',number:i.number + },i.revision)),merged?el('span',{class:'badge'},'已合并,不能重新打开'):button(i.state==='closed'?'重新打开':'关闭',()=>execute({ + type:i.state==='closed'?'reopen':'close',number:i.number + },i.revision),'danger')); + const controls=panel('编辑与控制',el('div',{ + class:'form-grid' + },title.node,body.node,profile.node),el('p',{class:'meta'},`Actor 可自由填写。Harness Profile 建议:Issue ${profiles.issue||'无'} / PR ${profiles.pr||'无'};建议不限制平台指派。`),actions); + const discussion=panel('讨论',...(v.comments||[]).map(c=>el('article',{ + class:'record' + },el('div',{ + class:'meta' + },`#${c.comment_id} · ${c.author} · ${c.created_at}${c.reply_to?' · 回复 #'+c.reply_to:''}`),el('div',{ + class:'body' + },c.body),button('回复',async()=>{ + reply.input.value=c.comment_id;comment.input.focus(); + },'link-button'))),comment.node,reply.node,el('div',{ + class:'actions' + },button('发布评论',()=>execute({ + type:'comment',number:i.number,body:comment.input.value,...(reply.input.value?{ + replyTo:Number(reply.input.value) + } + :{}) + },i.revision),'primary'))); + let candidate=null; + if(i.kind==='pull_request'||i.kind==='pr'){ + let diffRequest=0; + const worktree=field('Git Commit ID'),diff=el('div'),candidateKind=el('select',{},el('option',{value:'source'},'配置 Source 的当前已提交 Checkout'),el('option',{value:'commit'},'配置 Source 中的 Commit'));worktree.node.hidden=true;candidateKind.addEventListener('change',()=>worktree.node.hidden=candidateKind.value!=='commit'); + candidate=panel('Git 候选',badge(i.published?'候选已发布':'候选未发布'),el('p',{ + class:'meta' + },`Head ${i.head_ref||''} · ${i.head_commit||''}`),el('p',{ + class:'meta' + },`Base ${i.base_ref||''} · ${i.base_commit||''}`),el('p',{ + class:'body' + },'发布使用平台配置 Source 的当前已提交 Checkout 或其中已存在的 Commit。合并将更新 Git Base 分支;Base 必须未被任何 Worktree 检出。'),merged?null:el('label',{},'候选来源',candidateKind),merged?null:worktree.node,el('div',{ + class:'actions' + },merged?el('span',{class:'badge'},'已合并,候选操作已结束'):button('发布候选',()=>execute({ + type:'publish',number:i.number,candidate:candidateKind.value==='source'?{type:'source'}:{type:'commit',commit:worktree.input.value} + },i.revision)),merged?null:button('合并已发布候选',async()=>{ + if(await confirmAction(`将 PR #${i.number} 的已发布候选合并到 ${i.base_ref}?`))await execute({ + type:'merge',number:i.number + },i.revision); + },'danger'),button('读取真实 Git Diff',async()=>{ + const request=++diffRequest; + const active=()=>token===generation&&selected===selection&¤t===v&&request===diffRequest&&diff.isConnected; + diff.replaceChildren(empty('正在读取固定候选 Diff…')); + try{ + const result=await api('/api/control/items/'+i.number+'/diff'); + if(!active())return; + if(result.number!==i.number||!Number.isInteger(result.revision)||typeof result.headCommit!=='string'||typeof result.baseCommit!=='string'||typeof result.diff!=='string')throw new Error('Diff 响应缺少完整候选身份,无法将内容归属到 Head / Base / Revision。'); + const stale=result.revision!==i.revision||result.headCommit!==i.head_commit||result.baseCommit!==i.base_commit; + diff.replaceChildren(panel('Diff 固定快照',el('p',{class:'meta'},`PR #${result.number} · Revision ${result.revision}`),el('p',{class:'meta'},`Head ${result.headCommit}`),el('p',{class:'meta'},`Base ${result.baseCommit}`),stale?el('div',{class:'notice error'},'对象详情已过期。此 Diff 属于以上固定快照;合并操作仍采用页面原 Revision 前提。',button('刷新对象详情',()=>select(i.number))):el('p',{class:'meta'},'Diff 与当前对象详情身份一致;后续发布仍可能更新对象。'),el('pre',{},result.diff||'无差异'))); + } + catch(e){if(active())diff.replaceChildren(el('div',{class:'notice error'},'Diff 读取失败,未展示成功内容。\n'+(e.message||String(e))));} + })),diff,raw(v.merge,'持久合并记录')); + } + else{ + candidate=panel('关联 Pull Request',linked.node,button('关联',async()=>{ + const pr=await api('/api/control/items/'+Number(linked.input.value));await execute({ + type:'link',issue:i.number,pr:pr.item.number,expectedPrRevision:pr.item.revision + },i.revision); + })); + } + for(const f of [title,body,comment,profile,reply,linked]){f.input.dataset.draft='true';f.input.dataset.initialValue=f.input.value;} + detail.replaceChildren(panel(null,heading,el('div',{ + class:'meta' + },`Revision ${i.revision} · ${i.updated_at} · 作者 ${i.author}`),el('div',{ + class:'body' + },i.body),raw(i,'完整对象')),discussion,controls,candidate); + if(!acceptedRefresh){const titleNode=detail.querySelector('h2'); titleNode.tabIndex=-1; titleNode.focus();} + } + const create=panel('创建协作对象',el('div',{ + class:'form-grid' + },el('label',{},'类型',kind),createTitle.node,createBody.node),el('div',{ + class:'toolbar' + },head.node,base.node,issue.node),button('创建',async()=>{ + const related=kind.value==='pr'&&issue.input.value?await api('/api/control/items/'+Number(issue.input.value)):null; + await execute(kind.value==='issue'?{ + type:'createIssue',title:createTitle.input.value,body:createBody.input.value + } + :{ + type:'createPR',title:createTitle.input.value,body:createBody.input.value,head:head.input.value,base:base.input.value,...(issue.input.value?{ + issue:Number(issue.input.value),issueRevision:related.item.revision + } + :{}) + }); + },'primary')); + for(const f of [createTitle,createBody,head,base,issue]){f.input.dataset.draft='true';f.input.dataset.initialValue=f.input.value;} + function updateCreateType(){for(const f of [head,base,issue])f.node.hidden=kind.value!=='pr';} + kind.addEventListener('change',updateCreateType);updateCreateType(); + const lookup=field('请求 ID'); + content.replaceChildren(list,receipt,detail,el('div',{class:'split'},create,panel('查询控制回执',lookup.node,button('查询',async()=>renderReceipt(await api('/api/control/receipts/'+encodeURIComponent(lookup.input.value||lastRequest||'')))))),el('p',{class:'meta'},'本地操作以 human 身份写入平台。Harness 调度和 OTLP 观测记录不代表对象变更。')); + await reload(initial); +} +route(); diff --git a/src/console/web/index.html b/src/console/web/index.html new file mode 100644 index 00000000..d5b65053 --- /dev/null +++ b/src/console/web/index.html @@ -0,0 +1,7 @@ + + +Braid Console + + +

概览

+ diff --git a/src/context.rs b/src/context.rs index a6635ddb..37c31f62 100644 --- a/src/context.rs +++ b/src/context.rs @@ -11,7 +11,7 @@ use crate::{ github::{GitHubClient, GitHubError, RepositoryName, WorkItemLocator}, store::{ AssociatedWorkItem, AssociationSet, CanonicalComment, CanonicalCommentSet, DeletedComment, - StoreActor, StoreError, + OperationalCommentCandidate, StoreActor, StoreError, }, }; @@ -38,13 +38,13 @@ pub enum ContextError { InvalidPageSize(usize), } -#[derive(Debug, Clone, Serialize)] +#[derive(Debug, Clone, Serialize, Deserialize)] pub struct Actor { pub node_id: String, pub login: String, } -#[derive(Debug, Clone, Serialize)] +#[derive(Debug, Clone, Serialize, Deserialize)] pub struct WorkItemReference { pub node_id: String, pub repository_node_id: String, @@ -62,30 +62,35 @@ impl WorkItemReference { WorkItemKind::Issue => "Issue", WorkItemKind::PullRequest => "PR", }; - format!("GitHub {noun}: {}#{}", self.repository, self.number) + format!( + "{} {noun}: {}#{}", + surface_name(&self.repository_node_id), + self.repository, + self.number + ) } } -#[derive(Debug, Clone, Copy, Serialize)] +#[derive(Debug, Clone, Copy, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum WorkItemKind { Issue, PullRequest, } -#[derive(Debug, Clone, Serialize)] +#[derive(Debug, Clone, Serialize, Deserialize)] pub struct ProjectEntry { pub title: String, pub fields: Vec, } -#[derive(Debug, Clone, Serialize)] +#[derive(Debug, Clone, Serialize, Deserialize)] pub struct ProjectField { pub name: String, pub value: String, } -#[derive(Debug, Clone, Serialize)] +#[derive(Debug, Clone, Serialize, Deserialize)] pub struct CommentSnapshot { pub node_id: String, pub database_id: String, @@ -94,6 +99,8 @@ pub struct CommentSnapshot { pub author: Option, pub created_at: String, pub updated_at: String, + #[serde(default)] + pub last_edited_at: Option, pub body: Option, pub minimized: bool, pub minimized_reason: Option, @@ -101,8 +108,45 @@ pub struct CommentSnapshot { pub deleted: bool, } -#[derive(Debug, Clone, Serialize)] +/// Edit attribution returned with the same canonical title and body. +#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub(crate) struct RootEditEvidence { + pub(crate) last_edited_at: Option, + pub(crate) editor: Option, + pub(crate) title_history: Option, +} + +#[derive(Debug, Clone, Deserialize, PartialEq, Eq)] +pub(crate) struct EditActor { + pub(crate) id: Option, +} + +#[derive(Debug, Clone, Deserialize, PartialEq, Eq)] +pub(crate) struct TitleHistory { + pub(crate) nodes: Vec>, +} + +#[derive(Debug, Clone, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub(crate) struct TitleRename { + pub(crate) id: String, + pub(crate) actor: Option, + pub(crate) created_at: String, + pub(crate) previous_title: String, + pub(crate) current_title: String, +} + +impl RootEditEvidence { + pub(crate) fn latest_title_rename(&self) -> Option<&TitleRename> { + self.title_history.as_ref()?.nodes.last()?.as_ref() + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] pub struct IssueSnapshot { + #[serde(skip)] + pub(crate) root_edits: RootEditEvidence, pub node_id: String, pub database_id: String, pub repository_node_id: String, @@ -129,7 +173,7 @@ pub struct IssueSnapshot { pub comments: Vec, } -#[derive(Debug, Clone, Serialize)] +#[derive(Debug, Clone, Serialize, Deserialize)] pub struct ReviewSnapshot { pub node_id: String, pub database_id: String, @@ -142,7 +186,7 @@ pub struct ReviewSnapshot { pub minimized_reason: Option, } -#[derive(Debug, Clone, Serialize)] +#[derive(Debug, Clone, Serialize, Deserialize)] pub struct ReviewThreadSnapshot { pub node_id: String, pub path: String, @@ -155,8 +199,10 @@ pub struct ReviewThreadSnapshot { pub comments: Vec, } -#[derive(Debug, Clone, Serialize)] +#[derive(Debug, Clone, Serialize, Deserialize)] pub struct PullRequestSnapshot { + #[serde(skip)] + pub(crate) root_edits: RootEditEvidence, pub node_id: String, pub database_id: String, pub repository_node_id: String, @@ -182,14 +228,14 @@ pub struct PullRequestSnapshot { pub review_threads: Vec, } -#[derive(Debug, Clone, Serialize)] +#[derive(Debug, Clone, Serialize, Deserialize)] #[serde(tag = "kind", rename_all = "snake_case")] pub enum CanonicalContext { Issue(IssueSnapshot), PullRequest(PullRequestSnapshot), } -#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum ContextPressure { Normal, @@ -197,7 +243,7 @@ pub enum ContextPressure { Hard, } -#[derive(Debug, Clone, Serialize)] +#[derive(Debug, Clone, Serialize, Deserialize)] pub struct RenderedContext { pub text: String, pub revision: String, @@ -207,6 +253,9 @@ pub struct RenderedContext { #[derive(Debug, Clone)] pub struct CanonicalObservation { + /// Original authorship is usable only when the API proves no subsequent edit. + pub unedited_creation: bool, + pub created_at: Option, pub work_item_node_id: String, pub work_item_kind: &'static str, pub work_item_number: u64, @@ -223,8 +272,40 @@ pub struct CanonicalObservation { pub author_login: Option, pub body: Option, pub visible_body: Option, + /// Exact title content returned by the source. + pub title: Option, + pub metadata_digest: Option, + pub(crate) root_edits: RootEditEvidence, +} + +impl CanonicalObservation { + pub(crate) fn root_fields(&self) -> Option { + if !matches!(self.object_kind, "issue" | "pr") { + return None; + } + Some(crate::store::ObservedRootFields { + title_digest: root_field_digest(self.title.as_deref()?), + body_digest: root_field_digest(self.body.as_deref()?), + title_event_id: self.root_edits.latest_title_rename().map(|rename| rename.id.clone()), + }) + } + + /// Versioned wire evidence is distinct from visible semantic equality. + pub(crate) fn version_digest(&self) -> String { + if matches!(self.object_kind, "issue" | "pr") { + crate::store::publication_digest( + &self.object_node_id, + &self.version, + self.title.as_deref(), + self.body.as_deref().unwrap_or(""), + ) + } else { + object_digest(&self.object_node_id, &self.version, self.body.as_deref()) + } + } } +#[tracing::instrument(skip_all, fields(repository = %locator.repository, work_item = locator.number, resource = "graphql"))] pub async fn materialize_issue( client: &GitHubClient, locator: &WorkItemLocator, @@ -242,6 +323,7 @@ pub async fn materialize_issue( Err(ContextError::Drift(locator.to_string())) } +#[tracing::instrument(skip_all, fields(repository = %locator.repository, work_item = locator.number, resource = "graphql"))] pub async fn materialize_pull_request( client: &GitHubClient, locator: &WorkItemLocator, @@ -308,17 +390,24 @@ pub fn render_complete( pub fn reconcile_local_state( context: &mut CanonicalContext, store: &StoreActor, + github_app_actor_node_id: Option<&str>, ) -> Result<(), ContextError> { match context { - CanonicalContext::Issue(issue) => reconcile_issue_comments(issue, store), + CanonicalContext::Issue(issue) => { + reconcile_issue_comments(issue, store, github_app_actor_node_id) + } CanonicalContext::PullRequest(pull_request) => { let work_item_digest = pull_request_root_digest(pull_request); let work_item_state = pull_request_work_item_state(pull_request); for issue in &mut pull_request.associated_issues { - reconcile_issue_comments(issue, store)?; + reconcile_issue_comments(issue, store, github_app_actor_node_id)?; } - let excluded = store.operational_status_comment_ids(pull_request.node_id.clone())?; - pull_request.conversation.retain(|comment| !excluded.contains(&comment.node_id)); + let excluded = discussion_roles( + store, + &pull_request.node_id, + &pull_request.conversation, + github_app_actor_node_id, + )?; let mut tombstones = store.reconcile_comments(comment_set( &pull_request.repository_node_id, &pull_request.repository, @@ -331,6 +420,8 @@ pub fn reconcile_local_state( "pr_comment", &pull_request.conversation, ))?; + // Projection exclusions are not evidence of upstream deletion. + pull_request.conversation.retain(|comment| !excluded.contains(&comment.node_id)); tombstones.retain(|comment| !excluded.contains(&comment.node_id)); extend_tombstones( &mut pull_request.conversation, @@ -457,6 +548,8 @@ pub fn canonical_observations(context: &CanonicalContext) -> Vec CanonicalObservation { CanonicalObservation { + unedited_creation: false, + created_at: None, work_item_node_id: issue.node_id.clone(), work_item_kind: "issue", work_item_number: issue.number, @@ -473,11 +566,16 @@ fn issue_observation(issue: &IssueSnapshot) -> CanonicalObservation { author_login: issue.author.as_ref().map(|author| author.login.clone()), body: Some(issue.body.clone()), visible_body: Some(filter_html_comments(&issue.body)), + title: Some(issue.title.clone()), + root_edits: issue.root_edits.clone(), + metadata_digest: Some(issue_metadata_digest(issue)), } } fn pull_request_observation(pull_request: &PullRequestSnapshot) -> CanonicalObservation { CanonicalObservation { + unedited_creation: false, + created_at: None, work_item_node_id: pull_request.node_id.clone(), work_item_kind: "pr", work_item_number: pull_request.number, @@ -494,6 +592,9 @@ fn pull_request_observation(pull_request: &PullRequestSnapshot) -> CanonicalObse author_login: pull_request.author.as_ref().map(|author| author.login.clone()), body: Some(pull_request.body.clone()), visible_body: Some(filter_html_comments(&pull_request.body)), + title: Some(pull_request.title.clone()), + root_edits: pull_request.root_edits.clone(), + metadata_digest: Some(pull_request_metadata_digest(pull_request)), } } @@ -510,6 +611,8 @@ fn review_observation( "active" }; CanonicalObservation { + unedited_creation: false, + created_at: None, work_item_node_id: pull_request.node_id.clone(), work_item_kind: "pr", work_item_number: pull_request.number, @@ -519,13 +622,16 @@ fn review_observation( object_node_id: review.node_id.clone(), database_id: review.database_id.clone(), object_kind: "review", - digest: object_digest(&review.node_id, &version, Some(&review.body)), + digest: review_semantic_digest(review, false), version, lifecycle, author_node_id: review.author.as_ref().map(|author| author.node_id.clone()), author_login: review.author.as_ref().map(|author| author.login.clone()), body: Some(review.body.clone()), visible_body: Some(filter_html_comments(&review.body)), + title: None, + root_edits: RootEditEvidence::default(), + metadata_digest: Some(review_semantic_digest(review, true)), } } @@ -544,6 +650,8 @@ fn review_thread_observation( thread.comments.iter().map(|comment| comment.updated_at.as_str()).max().unwrap_or("") ); CanonicalObservation { + unedited_creation: false, + created_at: None, work_item_node_id: pull_request.node_id.clone(), work_item_kind: "pr", work_item_number: pull_request.number, @@ -553,13 +661,16 @@ fn review_thread_observation( object_node_id: thread.node_id.clone(), database_id: String::new(), object_kind: "review_thread", - digest: object_digest(&thread.node_id, &version, None), + digest: thread_semantic_digest(thread, false), version, lifecycle, author_node_id: thread.resolved_by.as_ref().map(|author| author.node_id.clone()), author_login: thread.resolved_by.as_ref().map(|author| author.login.clone()), body: None, visible_body: None, + title: None, + root_edits: RootEditEvidence::default(), + metadata_digest: Some(thread_semantic_digest(thread, true)), } } @@ -570,6 +681,8 @@ fn observation( ) -> CanonicalObservation { let (version, digest, lifecycle) = comment_identity(comment); CanonicalObservation { + unedited_creation: unedited_comment(comment), + created_at: Some(comment.created_at.clone()), work_item_node_id: issue.node_id.clone(), work_item_kind: "issue", work_item_number: issue.number, @@ -586,6 +699,9 @@ fn observation( author_login: comment.author.as_ref().map(|author| author.login.clone()), body: comment.body.clone(), visible_body: comment.body.as_deref().map(filter_html_comments), + title: None, + root_edits: RootEditEvidence::default(), + metadata_digest: Some(comment_semantic_digest(comment, true)), } } @@ -596,6 +712,8 @@ fn pr_observation( ) -> CanonicalObservation { let (version, digest, lifecycle) = comment_identity(comment); CanonicalObservation { + unedited_creation: unedited_comment(comment), + created_at: Some(comment.created_at.clone()), work_item_node_id: pull_request.node_id.clone(), work_item_kind: "pr", work_item_number: pull_request.number, @@ -612,6 +730,9 @@ fn pr_observation( author_login: comment.author.as_ref().map(|author| author.login.clone()), body: comment.body.clone(), visible_body: comment.body.as_deref().map(filter_html_comments), + title: None, + root_edits: RootEditEvidence::default(), + metadata_digest: Some(comment_semantic_digest(comment, true)), } } @@ -623,7 +744,7 @@ fn comment_identity(comment: &CommentSnapshot) -> (String, String, &'static str) lifecycle, comment.minimized_reason.as_deref().unwrap_or_default() ); - let digest = object_digest(&comment.node_id, &version, comment.body.as_deref()); + let digest = comment_semantic_digest(comment, false); (version, digest, lifecycle) } @@ -643,13 +764,54 @@ fn object_digest(node_id: &str, version: &str, body: Option<&str>) -> String { hex::encode(digest.finalize()) } +fn comment_semantic_digest(comment: &CommentSnapshot, metadata_only: bool) -> String { + let mut visible = comment.clone(); + visible.updated_at.clear(); + visible.last_edited_at = None; + visible.body = if metadata_only || visible.minimized { + None + } else { + visible.body.as_deref().map(filter_html_comments) + }; + hex::encode(Sha256::digest(serde_json::to_vec(&visible).expect("typed comment serializes"))) +} + +fn review_semantic_digest(review: &ReviewSnapshot, metadata_only: bool) -> String { + let mut visible = review.clone(); + visible.updated_at.clear(); + visible.body = if metadata_only || visible.minimized { + String::new() + } else { + filter_html_comments(&visible.body) + }; + hex::encode(Sha256::digest(serde_json::to_vec(&visible).expect("typed review serializes"))) +} + +fn thread_semantic_digest(thread: &ReviewThreadSnapshot, metadata_only: bool) -> String { + let mut visible = thread.clone(); + visible.comments.clear(); + if metadata_only { + visible.resolved = false; + visible.resolved_by = None; + } + hex::encode(Sha256::digest(serde_json::to_vec(&visible).expect("typed thread serializes"))) +} + +fn unedited_comment(comment: &CommentSnapshot) -> bool { + comment.last_edited_at.is_none() + && comment.created_at == comment.updated_at + && !comment.minimized + && !comment.pinned +} + fn reconcile_issue_comments( issue: &mut IssueSnapshot, store: &StoreActor, + github_app_actor_node_id: Option<&str>, ) -> Result<(), ContextError> { let work_item_digest = issue_root_digest(issue); - let excluded = store.operational_status_comment_ids(issue.node_id.clone())?; - issue.comments.retain(|comment| !excluded.contains(&comment.node_id)); + let excluded = + discussion_roles(store, &issue.node_id, &issue.comments, github_app_actor_node_id)?; let mut tombstones = store.reconcile_comments(comment_set( &issue.repository_node_id, &issue.repository, @@ -662,6 +824,7 @@ fn reconcile_issue_comments( "issue_comment", &issue.comments, ))?; + issue.comments.retain(|comment| !excluded.contains(&comment.node_id)); tombstones.retain(|comment| !excluded.contains(&comment.node_id)); extend_tombstones(&mut issue.comments, tombstones, &issue.repository, issue.number); store.reconcile_associations(AssociationSet { @@ -686,6 +849,29 @@ fn reconcile_issue_comments( Ok(()) } +fn discussion_roles( + store: &StoreActor, + work_item_node_id: &str, + comments: &[CommentSnapshot], + github_app_actor_node_id: Option<&str>, +) -> Result, StoreError> { + let Some(trusted_app) = github_app_actor_node_id else { return Ok(BTreeSet::new()) }; + let candidates = comments + .iter() + .filter(|comment| !comment.deleted) + .filter_map(|comment| { + OperationalCommentCandidate::from_discussion( + trusted_app, + comment.author.as_ref().map(|actor| actor.node_id.as_str()), + &comment.node_id, + comment.body.as_deref(), + &comment.created_at, + ) + }) + .collect(); + store.reconcile_operational_comment_roles(work_item_node_id.into(), candidates) +} + #[allow(clippy::too_many_arguments)] fn comment_set( repository_node_id: &str, @@ -732,6 +918,10 @@ fn comment_set( } } +pub(crate) fn root_field_digest(value: &str) -> String { + hex::encode(Sha256::digest(value.as_bytes())) +} + fn root_projection_digest(node_id: &str, projection: &str) -> String { let mut digest = Sha256::new(); digest.update(b"braid-root-projection-v1\0"); @@ -760,6 +950,37 @@ fn pull_request_root_digest(pull_request: &PullRequestSnapshot) -> String { root_projection_digest(&root.node_id, &projection) } +fn issue_metadata_digest(issue: &IssueSnapshot) -> String { + let mut metadata = issue.clone(); + metadata.body.clear(); + metadata.title.clear(); + metadata.comments.clear(); + let mut projection = String::new(); + render_issue(&mut projection, &metadata, true); + root_projection_digest(&metadata.node_id, &projection) +} + +fn pull_request_metadata_digest(pr: &PullRequestSnapshot) -> String { + let mut metadata = pr.clone(); + metadata.body.clear(); + metadata.title.clear(); + metadata.associated_issues.clear(); + metadata.conversation.clear(); + metadata.reviews.clear(); + metadata.review_threads.clear(); + let mut projection = String::new(); + render_pull_request(&mut projection, &metadata); + // Native graph identity is relevant even when the PR's updatedAt and body + // did not move. Associated bodies have their own source-change contract. + for issue in &pr.associated_issues { + for value in [&issue.node_id, &issue.repository, &issue.state] { + projection.push('\0'); + projection.push_str(value); + } + } + root_projection_digest(&metadata.node_id, &projection) +} + fn extend_tombstones( comments: &mut Vec, tombstones: Vec, @@ -791,6 +1012,7 @@ fn deleted_comment( .map(|login| Actor { node_id: comment.author_node_id.unwrap_or_default(), login }), created_at: comment.created_at, updated_at: comment.updated_at, + last_edited_at: None, body: None, minimized: false, minimized_reason: None, @@ -799,8 +1021,20 @@ fn deleted_comment( } } +fn surface_name(repository_node_id: &str) -> &'static str { + if repository_node_id.starts_with("local:") { "Braid" } else { "GitHub" } +} + fn render_issue(output: &mut String, issue: &IssueSnapshot, complete: bool) { - push_line(output, &format!("# GitHub Issue: {}#{}", issue.repository, issue.number)); + push_line( + output, + &format!( + "# {} Issue: {}#{}", + surface_name(&issue.repository_node_id), + issue.repository, + issue.number + ), + ); push_line(output, &issue.title); output.push('\n'); push_state(output, &issue.state, issue.state_reason.as_deref()); @@ -832,13 +1066,22 @@ fn render_issue(output: &mut String, issue: &IssueSnapshot, complete: bool) { } } +#[allow(clippy::too_many_lines)] fn render_pull_request(output: &mut String, pull_request: &PullRequestSnapshot) { for issue in &pull_request.associated_issues { let complete = !issue.state.eq_ignore_ascii_case("closed"); render_issue(output, issue, complete); output.push_str("\n---\n\n"); } - push_line(output, &format!("# GitHub PR: {}#{}", pull_request.repository, pull_request.number)); + push_line( + output, + &format!( + "# {} PR: {}#{}", + surface_name(&pull_request.repository_node_id), + pull_request.repository, + pull_request.number + ), + ); push_line(output, &pull_request.title); output.push('\n'); push_line(output, &format!("State: {}", pull_request.state.to_ascii_lowercase())); @@ -1089,7 +1332,7 @@ pub fn filter_html_comments(markdown: &str) -> String { _ => false, }; if is_comment && let Some(range) = source_range(markdown, &line_offsets, data.sourcepos) { - ranges.push(range); + comment_ranges(markdown, range, &mut ranges); } } if ranges.is_empty() { @@ -1116,6 +1359,44 @@ pub fn filter_html_comments(markdown: &str) -> String { visible } +// A CommonMark HTML block includes the rest of its closing line. Remove the +// comments inside that block, not visible text following the closing delimiter. +fn comment_ranges(markdown: &str, (start, end): (usize, usize), ranges: &mut Vec<(usize, usize)>) { + let source = &markdown[start..end]; + let bytes = source.as_bytes(); + let mut cursor = 0; + while cursor < bytes.len() { + if bytes[cursor..].starts_with(b"") + .map_or(bytes.len(), |offset| cursor + 4 + offset + 3); + ranges.push((start + cursor, start + comment_end)); + cursor = comment_end; + } else if bytes[cursor] == b'<' + && (bytes.get(cursor + 1).is_some_and(u8::is_ascii_alphabetic) + || bytes.get(cursor + 1) == Some(&b'/') + && bytes.get(cursor + 2).is_some_and(u8::is_ascii_alphabetic)) + { + // A comment delimiter in an HTML attribute is literal attribute + // content. Skip the tag while respecting its quoted values. + let mut quote = None; + cursor += 1; + while cursor < bytes.len() { + let byte = bytes[cursor]; + cursor += 1; + match (quote, byte) { + (None, b'>') => break, + (None, b'\'' | b'"') => quote = Some(byte), + (Some(delimiter), _) if byte == delimiter => quote = None, + _ => {} + } + } + } else { + cursor += 1; + } + } +} + fn line_offsets(markdown: &str) -> Vec { let mut offsets = vec![0]; for (offset, byte) in markdown.bytes().enumerate() { @@ -1172,6 +1453,8 @@ struct IssueTypeRaw { #[derive(Debug, Clone, Deserialize, PartialEq, Eq)] struct IssueCoreRaw { + #[serde(flatten)] + root_edits: RootEditEvidence, id: String, #[serde(rename = "fullDatabaseId")] full_database_id: String, @@ -1192,6 +1475,8 @@ struct IssueCoreRaw { #[derive(Debug, Clone, Deserialize, PartialEq, Eq)] struct PullRequestCoreRaw { + #[serde(flatten)] + root_edits: RootEditEvidence, id: String, #[serde(rename = "fullDatabaseId")] full_database_id: String, @@ -1344,11 +1629,20 @@ struct ConnectionVariables<'a> { } const ISSUE_CORE_QUERY: &str = r#" -query($owner:String!,$name:String!,$number:Int!){ +query IssueCore($owner:String!,$name:String!,$number:Int!){ + rateLimit{cost} repository(owner:$owner,name:$name){ id nameWithOwner issue(number:$number){ id fullDatabaseId number title body state stateReason updatedAt + lastEditedAt + editor{... on Bot{id} ... on EnterpriseUserAccount{id} ... on Mannequin{id} ... on Organization{id} ... on User{id}} + titleHistory:timelineItems(last:2,itemTypes:[RENAMED_TITLE_EVENT]){ + nodes{... on RenamedTitleEvent{ + id createdAt previousTitle currentTitle + actor{... on Bot{id} ... on EnterpriseUserAccount{id} ... on Mannequin{id} ... on Organization{id} ... on User{id}} + }} + } author{login ... on Bot{id} ... on EnterpriseUserAccount{id} ... on Mannequin{id} ... on Organization{id} ... on User{id}} issueType{name} milestone{title} @@ -1358,11 +1652,20 @@ query($owner:String!,$name:String!,$number:Int!){ }"#; const PR_CORE_QUERY: &str = r#" -query($owner:String!,$name:String!,$number:Int!){ +query PrCore($owner:String!,$name:String!,$number:Int!){ + rateLimit{cost} repository(owner:$owner,name:$name){ id nameWithOwner pullRequest(number:$number){ id fullDatabaseId number title body state isDraft merged updatedAt + lastEditedAt + editor{... on Bot{id} ... on EnterpriseUserAccount{id} ... on Mannequin{id} ... on Organization{id} ... on User{id}} + titleHistory:timelineItems(last:2,itemTypes:[RENAMED_TITLE_EVENT]){ + nodes{... on RenamedTitleEvent{ + id createdAt previousTitle currentTitle + actor{... on Bot{id} ... on EnterpriseUserAccount{id} ... on Mannequin{id} ... on Organization{id} ... on User{id}} + }} + } author{login ... on Bot{id} ... on EnterpriseUserAccount{id} ... on Mannequin{id} ... on Organization{id} ... on User{id}} baseRefName headRefName headRepository{id nameWithOwner} milestone{title} @@ -1371,35 +1674,40 @@ query($owner:String!,$name:String!,$number:Int!){ }"#; const ISSUE_ASSIGNEES_QUERY: &str = r#" -query($owner:String!,$name:String!,$number:Int!,$cursor:String,$pageSize:Int!){ +query IssueAssignees($owner:String!,$name:String!,$number:Int!,$cursor:String,$pageSize:Int!){ + rateLimit{cost} repository(owner:$owner,name:$name){issue(number:$number){ items:assignees(first:$pageSize,after:$cursor){nodes{id login} pageInfo{hasNextPage endCursor}} }} }"#; const ISSUE_LABELS_QUERY: &str = r#" -query($owner:String!,$name:String!,$number:Int!,$cursor:String,$pageSize:Int!){ +query IssueLabels($owner:String!,$name:String!,$number:Int!,$cursor:String,$pageSize:Int!){ + rateLimit{cost} repository(owner:$owner,name:$name){issue(number:$number){ items:labels(first:$pageSize,after:$cursor){nodes{name} pageInfo{hasNextPage endCursor}} }} }"#; const ISSUE_PROJECTS_QUERY: &str = r#" -query($owner:String!,$name:String!,$number:Int!,$cursor:String,$pageSize:Int!){ +query IssueProjects($owner:String!,$name:String!,$number:Int!,$cursor:String,$pageSize:Int!){ + rateLimit{cost} repository(owner:$owner,name:$name){issue(number:$number){ items:projectItems(first:$pageSize,after:$cursor){nodes{id project{title}} pageInfo{hasNextPage endCursor}} }} }"#; const PR_PROJECTS_QUERY: &str = r#" -query($owner:String!,$name:String!,$number:Int!,$cursor:String,$pageSize:Int!){ +query PrProjects($owner:String!,$name:String!,$number:Int!,$cursor:String,$pageSize:Int!){ + rateLimit{cost} repository(owner:$owner,name:$name){pullRequest(number:$number){ items:projectItems(first:$pageSize,after:$cursor){nodes{id project{title}} pageInfo{hasNextPage endCursor}} }} }"#; const PROJECT_FIELD_VALUES_QUERY: &str = r#" -query($id:ID!,$cursor:String,$pageSize:Int!){ +query ProjectFieldValues($id:ID!,$cursor:String,$pageSize:Int!){ + rateLimit{cost} node(id:$id){... on ProjectV2Item{ items:fieldValues(first:$pageSize,after:$cursor){ nodes{ @@ -1434,35 +1742,40 @@ query($id:ID!,$cursor:String,$pageSize:Int!){ }"#; const ISSUE_LINKED_BRANCHES_QUERY: &str = r#" -query($owner:String!,$name:String!,$number:Int!,$cursor:String,$pageSize:Int!){ +query IssueLinkedBranches($owner:String!,$name:String!,$number:Int!,$cursor:String,$pageSize:Int!){ + rateLimit{cost} repository(owner:$owner,name:$name){issue(number:$number){ items:linkedBranches(first:$pageSize,after:$cursor){nodes{id ref{name repository{id nameWithOwner}}} pageInfo{hasNextPage endCursor}} }} }"#; const ISSUE_SUB_ISSUES_QUERY: &str = r#" -query($owner:String!,$name:String!,$number:Int!,$cursor:String,$pageSize:Int!){ +query IssueSubIssues($owner:String!,$name:String!,$number:Int!,$cursor:String,$pageSize:Int!){ + rateLimit{cost} repository(owner:$owner,name:$name){issue(number:$number){ items:subIssues(first:$pageSize,after:$cursor){nodes{id number title state stateReason repository{id nameWithOwner}} pageInfo{hasNextPage endCursor}} }} }"#; const ISSUE_BLOCKED_BY_QUERY: &str = r#" -query($owner:String!,$name:String!,$number:Int!,$cursor:String,$pageSize:Int!){ +query IssueBlockedBy($owner:String!,$name:String!,$number:Int!,$cursor:String,$pageSize:Int!){ + rateLimit{cost} repository(owner:$owner,name:$name){issue(number:$number){ items:blockedBy(first:$pageSize,after:$cursor){nodes{id number title state stateReason repository{id nameWithOwner}} pageInfo{hasNextPage endCursor}} }} }"#; const ISSUE_BLOCKING_QUERY: &str = r#" -query($owner:String!,$name:String!,$number:Int!,$cursor:String,$pageSize:Int!){ +query IssueBlocking($owner:String!,$name:String!,$number:Int!,$cursor:String,$pageSize:Int!){ + rateLimit{cost} repository(owner:$owner,name:$name){issue(number:$number){ items:blocking(first:$pageSize,after:$cursor){nodes{id number title state stateReason repository{id nameWithOwner}} pageInfo{hasNextPage endCursor}} }} }"#; const ISSUE_ASSOCIATED_PRS_QUERY: &str = r#" -query($owner:String!,$name:String!,$number:Int!,$cursor:String,$pageSize:Int!){ +query IssueAssociatedPrs($owner:String!,$name:String!,$number:Int!,$cursor:String,$pageSize:Int!){ + rateLimit{cost} repository(owner:$owner,name:$name){issue(number:$number){ items:closedByPullRequestsReferences(first:$pageSize,after:$cursor,includeClosedPrs:true){ nodes{id number title state repository{id nameWithOwner}} @@ -1472,7 +1785,8 @@ query($owner:String!,$name:String!,$number:Int!,$cursor:String,$pageSize:Int!){ }"#; const ISSUE_COMMENTS_QUERY: &str = r#" -query($owner:String!,$name:String!,$number:Int!,$cursor:String,$pageSize:Int!){ +query IssueComments($owner:String!,$name:String!,$number:Int!,$cursor:String,$pageSize:Int!){ + rateLimit{cost} repository(owner:$owner,name:$name){issue(number:$number){ items:comments(first:$pageSize,after:$cursor){nodes{ id fullDatabaseId author{login ... on Bot{id} ... on EnterpriseUserAccount{id} ... on Mannequin{id} ... on Organization{id} ... on User{id}} createdAt updatedAt lastEditedAt @@ -1482,7 +1796,8 @@ query($owner:String!,$name:String!,$number:Int!,$cursor:String,$pageSize:Int!){ }"#; const ISSUE_DUPLICATES_QUERY: &str = r#" -query($owner:String!,$name:String!,$number:Int!,$cursor:String,$pageSize:Int!){ +query IssueDuplicates($owner:String!,$name:String!,$number:Int!,$cursor:String,$pageSize:Int!){ + rateLimit{cost} repository(owner:$owner,name:$name){issue(number:$number){ items:timelineItems(first:$pageSize,after:$cursor,itemTypes:[MARKED_AS_DUPLICATE_EVENT]){ nodes{... on MarkedAsDuplicateEvent{ @@ -1496,21 +1811,24 @@ query($owner:String!,$name:String!,$number:Int!,$cursor:String,$pageSize:Int!){ }"#; const PR_ASSIGNEES_QUERY: &str = r#" -query($owner:String!,$name:String!,$number:Int!,$cursor:String,$pageSize:Int!){ +query PrAssignees($owner:String!,$name:String!,$number:Int!,$cursor:String,$pageSize:Int!){ + rateLimit{cost} repository(owner:$owner,name:$name){pullRequest(number:$number){ items:assignees(first:$pageSize,after:$cursor){nodes{id login} pageInfo{hasNextPage endCursor}} }} }"#; const PR_LABELS_QUERY: &str = r#" -query($owner:String!,$name:String!,$number:Int!,$cursor:String,$pageSize:Int!){ +query PrLabels($owner:String!,$name:String!,$number:Int!,$cursor:String,$pageSize:Int!){ + rateLimit{cost} repository(owner:$owner,name:$name){pullRequest(number:$number){ items:labels(first:$pageSize,after:$cursor){nodes{name} pageInfo{hasNextPage endCursor}} }} }"#; const PR_ASSOCIATED_ISSUES_QUERY: &str = r#" -query($owner:String!,$name:String!,$number:Int!,$cursor:String,$pageSize:Int!){ +query PrAssociatedIssues($owner:String!,$name:String!,$number:Int!,$cursor:String,$pageSize:Int!){ + rateLimit{cost} repository(owner:$owner,name:$name){pullRequest(number:$number){ items:closingIssuesReferences(first:$pageSize,after:$cursor){ nodes{id number title state stateReason repository{id nameWithOwner}} @@ -1520,7 +1838,8 @@ query($owner:String!,$name:String!,$number:Int!,$cursor:String,$pageSize:Int!){ }"#; const PR_COMMENTS_QUERY: &str = r#" -query($owner:String!,$name:String!,$number:Int!,$cursor:String,$pageSize:Int!){ +query PrComments($owner:String!,$name:String!,$number:Int!,$cursor:String,$pageSize:Int!){ + rateLimit{cost} repository(owner:$owner,name:$name){pullRequest(number:$number){ items:comments(first:$pageSize,after:$cursor){nodes{ id fullDatabaseId author{login ... on Bot{id} ... on EnterpriseUserAccount{id} ... on Mannequin{id} ... on Organization{id} ... on User{id}} createdAt updatedAt lastEditedAt @@ -1530,7 +1849,8 @@ query($owner:String!,$name:String!,$number:Int!,$cursor:String,$pageSize:Int!){ }"#; const PR_REVIEWS_QUERY: &str = r#" -query($owner:String!,$name:String!,$number:Int!,$cursor:String,$pageSize:Int!){ +query PrReviews($owner:String!,$name:String!,$number:Int!,$cursor:String,$pageSize:Int!){ + rateLimit{cost} repository(owner:$owner,name:$name){pullRequest(number:$number){ items:reviews(first:$pageSize,after:$cursor){nodes{ id fullDatabaseId author{login ... on Bot{id} ... on EnterpriseUserAccount{id} ... on Mannequin{id} ... on Organization{id} ... on User{id}} state createdAt submittedAt updatedAt @@ -1540,7 +1860,8 @@ query($owner:String!,$name:String!,$number:Int!,$cursor:String,$pageSize:Int!){ }"#; const PR_REVIEW_THREADS_QUERY: &str = r#" -query($owner:String!,$name:String!,$number:Int!,$cursor:String,$pageSize:Int!){ +query PrReviewThreads($owner:String!,$name:String!,$number:Int!,$cursor:String,$pageSize:Int!){ + rateLimit{cost} repository(owner:$owner,name:$name){pullRequest(number:$number){ items:reviewThreads(first:$pageSize,after:$cursor){nodes{ id path line startLine isResolved isCollapsed isOutdated @@ -1550,7 +1871,8 @@ query($owner:String!,$name:String!,$number:Int!,$cursor:String,$pageSize:Int!){ }"#; const REVIEW_THREAD_COMMENTS_QUERY: &str = r#" -query($id:ID!,$cursor:String,$pageSize:Int!){ +query ReviewThreadComments($id:ID!,$cursor:String,$pageSize:Int!){ + rateLimit{cost} node(id:$id){... on PullRequestReviewThread{ items:comments(first:$pageSize,after:$cursor){nodes{ id fullDatabaseId author{login ... on Bot{id} ... on EnterpriseUserAccount{id} ... on Mannequin{id} ... on Organization{id} ... on User{id}} createdAt updatedAt lastEditedAt @@ -1699,6 +2021,8 @@ struct CommentRaw { body: String, #[serde(rename = "isMinimized")] is_minimized: bool, + #[serde(rename = "lastEditedAt")] + last_edited_at: Option, #[serde(rename = "minimizedReason")] minimized_reason: Option, #[serde(rename = "isPinned", default)] @@ -1715,6 +2039,7 @@ impl CommentRaw { author: self.author.map(Into::into), created_at: self.created_at, updated_at: self.updated_at, + last_edited_at: self.last_edited_at, body: (!self.is_minimized).then_some(self.body), minimized: self.is_minimized, minimized_reason: self.minimized_reason, @@ -1926,6 +2251,17 @@ async fn paginate_issue Deserialize<'de>>( page_size: usize, query: &str, connection: &'static str, +) -> Result, ContextError> { + paginate_issue_seeded(client, locator, page_size, query, connection, None).await +} + +async fn paginate_issue_seeded Deserialize<'de>>( + client: &GitHubClient, + locator: &WorkItemLocator, + page_size: usize, + query: &str, + connection: &'static str, + mut first: Option>, ) -> Result, ContextError> { let mut output = Vec::new(); let mut cursor: Option = None; @@ -1938,12 +2274,18 @@ async fn paginate_issue Deserialize<'de>>( cursor: cursor.as_deref(), page_size, }; - let data: IssueConnectionData = client.graphql(query, &variables).await?; - let page = data - .repository - .and_then(|repository| repository.issue) - .ok_or_else(|| ContextError::Missing { kind: "Issue", target: locator.to_string() })? - .items; + let page = if let Some(page) = first.take() { + page + } else { + let data: IssueConnectionData = client.graphql(query, &variables).await?; + data.repository + .and_then(|repository| repository.issue) + .ok_or_else(|| ContextError::Missing { + kind: "Issue", + target: locator.to_string(), + })? + .items + }; output.extend(page.nodes); if !page.page_info.has_next_page { return Ok(output); @@ -1975,6 +2317,17 @@ async fn paginate_pr Deserialize<'de>>( page_size: usize, query: &str, connection: &'static str, +) -> Result, ContextError> { + paginate_pr_seeded(client, locator, page_size, query, connection, None).await +} + +async fn paginate_pr_seeded Deserialize<'de>>( + client: &GitHubClient, + locator: &WorkItemLocator, + page_size: usize, + query: &str, + connection: &'static str, + mut first: Option>, ) -> Result, ContextError> { let mut output = Vec::new(); let mut cursor: Option = None; @@ -1987,12 +2340,15 @@ async fn paginate_pr Deserialize<'de>>( cursor: cursor.as_deref(), page_size, }; - let data: PullRequestConnectionData = client.graphql(query, &variables).await?; - let page = data - .repository - .and_then(|repository| repository.pull_request) - .ok_or_else(|| ContextError::Missing { kind: "PR", target: locator.to_string() })? - .items; + let page = if let Some(page) = first.take() { + page + } else { + let data: PullRequestConnectionData = client.graphql(query, &variables).await?; + data.repository + .and_then(|repository| repository.pull_request) + .ok_or_else(|| ContextError::Missing { kind: "PR", target: locator.to_string() })? + .items + }; output.extend(page.nodes); if !page.page_info.has_next_page { return Ok(output); @@ -2067,6 +2423,20 @@ async fn read_issue_snapshot( page_size: usize, ) -> Result { let core = marker.core; + let data: IssueFirstData = client + .graphql( + ISSUE_FIRST_PAGES_QUERY, + &serde_json::json!({ + "owner": locator.repository.owner, "name": locator.repository.name, + "number": locator.number, "pageSize": page_size, "cursor": null, + "projects": client.projects_v2_enabled(), + }), + ) + .await?; + let first = data + .repository + .and_then(|r| r.object) + .ok_or_else(|| ContextError::Missing { kind: "Issue", target: locator.to_string() })?; let ( assignees, labels, @@ -2079,51 +2449,92 @@ async fn read_issue_snapshot( comments, duplicate_events, ) = tokio::try_join!( - paginate_issue::(client, locator, page_size, ISSUE_ASSIGNEES_QUERY, "assignees"), - paginate_issue::(client, locator, page_size, ISSUE_LABELS_QUERY, "labels"), - read_issue_project_items(client, locator, page_size), - paginate_issue::( + paginate_issue_seeded::( + client, + locator, + page_size, + ISSUE_ASSIGNEES_QUERY, + "assignees", + Some(first.assignees) + ), + paginate_issue_seeded::( + client, + locator, + page_size, + ISSUE_LABELS_QUERY, + "labels", + Some(first.labels) + ), + async { + if client.projects_v2_enabled() { + paginate_issue_seeded::( + client, + locator, + page_size, + ISSUE_PROJECTS_QUERY, + "project items", + first.project_items, + ) + .await + } else { + Ok(Vec::new()) + } + }, + paginate_issue_seeded::( client, locator, page_size, ISSUE_LINKED_BRANCHES_QUERY, - "linked branches" + "linked branches", + Some(first.linked_branches) ), - paginate_issue::( + paginate_issue_seeded::( client, locator, page_size, ISSUE_SUB_ISSUES_QUERY, - "sub-issues" + "sub-issues", + Some(first.sub_issues) ), - paginate_issue::( + paginate_issue_seeded::( client, locator, page_size, ISSUE_BLOCKED_BY_QUERY, - "blocked-by" + "blocked-by", + Some(first.blocked_by) ), - paginate_issue::( + paginate_issue_seeded::( client, locator, page_size, ISSUE_BLOCKING_QUERY, - "blocking" + "blocking", + Some(first.blocking) ), - paginate_issue::( + paginate_issue_seeded::( client, locator, page_size, ISSUE_ASSOCIATED_PRS_QUERY, - "associated pull requests" + "associated pull requests", + Some(first.associated_prs) ), - paginate_issue::(client, locator, page_size, ISSUE_COMMENTS_QUERY, "comments"), - paginate_issue::( + paginate_issue_seeded::( + client, + locator, + page_size, + ISSUE_COMMENTS_QUERY, + "comments", + Some(first.comments) + ), + paginate_issue_seeded::( client, locator, page_size, ISSUE_DUPLICATES_QUERY, - "duplicate events" + "duplicate events", + Some(first.duplicate_events) ), )?; @@ -2173,6 +2584,7 @@ async fn read_issue_snapshot( }); Ok(IssueSnapshot { + root_edits: core.root_edits, node_id: core.id, database_id: core.full_database_id, repository_node_id: marker.repository.id, @@ -2208,25 +2620,83 @@ async fn read_pr_snapshot( page_size: usize, ) -> Result { let core = marker.core; + let data: PrFirstData = client + .graphql( + PR_FIRST_PAGES_QUERY, + &serde_json::json!({ + "owner": locator.repository.owner, "name": locator.repository.name, + "number": locator.number, "pageSize": page_size, "cursor": null, + "projects": client.projects_v2_enabled(), + }), + ) + .await?; + let first = data + .repository + .and_then(|r| r.object) + .ok_or_else(|| ContextError::Missing { kind: "Pr", target: locator.to_string() })?; let (assignees, labels, project_items, associated_issue_refs, comments, reviews, threads) = tokio::try_join!( - paginate_pr::(client, locator, page_size, PR_ASSIGNEES_QUERY, "assignees"), - paginate_pr::(client, locator, page_size, PR_LABELS_QUERY, "labels"), - read_pr_project_items(client, locator, page_size), - paginate_pr::( + paginate_pr_seeded::( + client, + locator, + page_size, + PR_ASSIGNEES_QUERY, + "assignees", + Some(first.assignees) + ), + paginate_pr_seeded::( + client, + locator, + page_size, + PR_LABELS_QUERY, + "labels", + Some(first.labels) + ), + async { + if client.projects_v2_enabled() { + paginate_pr_seeded::( + client, + locator, + page_size, + PR_PROJECTS_QUERY, + "project items", + first.project_items, + ) + .await + } else { + Ok(Vec::new()) + } + }, + paginate_pr_seeded::( client, locator, page_size, PR_ASSOCIATED_ISSUES_QUERY, - "associated issues" + "associated issues", + Some(first.associated_issue_refs) + ), + paginate_pr_seeded::( + client, + locator, + page_size, + PR_COMMENTS_QUERY, + "conversation", + Some(first.comments) + ), + paginate_pr_seeded::( + client, + locator, + page_size, + PR_REVIEWS_QUERY, + "reviews", + Some(first.reviews) ), - paginate_pr::(client, locator, page_size, PR_COMMENTS_QUERY, "conversation"), - paginate_pr::(client, locator, page_size, PR_REVIEWS_QUERY, "reviews"), - paginate_pr::( + paginate_pr_seeded::( client, locator, page_size, PR_REVIEW_THREADS_QUERY, - "review threads" + "review threads", + Some(first.threads) ), )?; @@ -2328,6 +2798,7 @@ async fn read_pr_snapshot( }); Ok(PullRequestSnapshot { + root_edits: core.root_edits, node_id: core.id, database_id: core.full_database_id, repository_node_id: marker.repository.id, @@ -2383,30 +2854,6 @@ async fn materialize_projects( Ok(projects) } -async fn read_issue_project_items( - client: &GitHubClient, - locator: &WorkItemLocator, - page_size: usize, -) -> Result, ContextError> { - if client.projects_v2_enabled() { - paginate_issue(client, locator, page_size, ISSUE_PROJECTS_QUERY, "project items").await - } else { - Ok(Vec::new()) - } -} - -async fn read_pr_project_items( - client: &GitHubClient, - locator: &WorkItemLocator, - page_size: usize, -) -> Result, ContextError> { - if client.projects_v2_enabled() { - paginate_pr(client, locator, page_size, PR_PROJECTS_QUERY, "project items").await - } else { - Ok(Vec::new()) - } -} - fn project_field(value: ProjectFieldRaw) -> Result, ContextError> { let (field, value) = match value { ProjectFieldRaw::Text { field, text } => (field, text), @@ -2460,7 +2907,7 @@ fn project_field(value: ProjectFieldRaw) -> Result, Context } ProjectFieldRaw::User { field, users } => { ensure_nested_complete(&users.page_info, "project user values", &field.name)?; - let mut values = users.into_nodes_logins(); + let mut values = users.nodes.into_iter().map(|user| user.login).collect::>(); values.sort(); (field, (!values.is_empty()).then(|| values.join(", "))) } @@ -2480,16 +2927,6 @@ fn project_field(value: ProjectFieldRaw) -> Result, Context .map(|value| ProjectField { name: field.name, value })) } -trait LoginConnectionExt { - fn into_nodes_logins(self) -> Vec; -} - -impl LoginConnectionExt for Connection { - fn into_nodes_logins(self) -> Vec { - self.nodes.into_iter().map(|user| user.login).collect() - } -} - fn ensure_nested_complete( page_info: &PageInfo, connection: &'static str, @@ -2515,3 +2952,110 @@ fn sort_references(references: &mut [WorkItemReference]) { left.repository.cmp(&right.repository).then(left.number.cmp(&right.number)) }); } + +const ISSUE_FIRST_PAGES_QUERY: &str = r#" +query IssueFirstPages($owner:String!,$name:String!,$number:Int!,$cursor:String,$pageSize:Int!,$projects:Boolean!){ + rateLimit{cost} + repository(owner:$owner,name:$name){issue(number:$number){ +assignees:assignees(first:$pageSize,after:$cursor){nodes{id login} pageInfo{hasNextPage endCursor}} +labels:labels(first:$pageSize,after:$cursor){nodes{name} pageInfo{hasNextPage endCursor}} +project_items:projectItems(first:$pageSize,after:$cursor) @include(if:$projects){nodes{id project{title}} pageInfo{hasNextPage endCursor}} +linked_branches:linkedBranches(first:$pageSize,after:$cursor){nodes{id ref{name repository{id nameWithOwner}}} pageInfo{hasNextPage endCursor}} +sub_issues:subIssues(first:$pageSize,after:$cursor){nodes{id number title state stateReason repository{id nameWithOwner}} pageInfo{hasNextPage endCursor}} +blocked_by:blockedBy(first:$pageSize,after:$cursor){nodes{id number title state stateReason repository{id nameWithOwner}} pageInfo{hasNextPage endCursor}} +blocking:blocking(first:$pageSize,after:$cursor){nodes{id number title state stateReason repository{id nameWithOwner}} pageInfo{hasNextPage endCursor}} +associated_prs:closedByPullRequestsReferences(first:$pageSize,after:$cursor,includeClosedPrs:true){ + nodes{id number title state repository{id nameWithOwner}} + pageInfo{hasNextPage endCursor} + } +comments:comments(first:$pageSize,after:$cursor){nodes{ + id fullDatabaseId author{login ... on Bot{id} ... on EnterpriseUserAccount{id} ... on Mannequin{id} ... on Organization{id} ... on User{id}} createdAt updatedAt lastEditedAt + body isMinimized minimizedReason isPinned + } pageInfo{hasNextPage endCursor}} +duplicate_events:timelineItems(first:$pageSize,after:$cursor,itemTypes:[MARKED_AS_DUPLICATE_EVENT]){ + nodes{... on MarkedAsDuplicateEvent{ + id + duplicate{__typename ... on Issue{id number title state stateReason repository{id nameWithOwner}} ... on PullRequest{id number title state repository{id nameWithOwner}}} + canonical{__typename ... on Issue{id number title state stateReason repository{id nameWithOwner}} ... on PullRequest{id number title state repository{id nameWithOwner}}} + }} + pageInfo{hasNextPage endCursor} + } +}}} +"#; +#[derive(Deserialize)] +struct IssueFirstPages { + assignees: Connection, + labels: Connection, + #[serde(default)] + project_items: Option>, + linked_branches: Connection, + sub_issues: Connection, + blocked_by: Connection, + blocking: Connection, + associated_prs: Connection, + comments: Connection, + duplicate_events: Connection, +} +#[derive(Deserialize)] +struct IssueFirstData { + repository: Option, +} +#[derive(Deserialize)] +struct IssueFirstRepository { + #[serde(rename = "issue")] + object: Option, +} + +const PR_FIRST_PAGES_QUERY: &str = r#" +query PrFirstPages($owner:String!,$name:String!,$number:Int!,$cursor:String,$pageSize:Int!,$projects:Boolean!){ + rateLimit{cost} + repository(owner:$owner,name:$name){pullRequest(number:$number){ +assignees:assignees(first:$pageSize,after:$cursor){nodes{id login} pageInfo{hasNextPage endCursor}} +labels:labels(first:$pageSize,after:$cursor){nodes{name} pageInfo{hasNextPage endCursor}} +project_items:projectItems(first:$pageSize,after:$cursor) @include(if:$projects){nodes{id project{title}} pageInfo{hasNextPage endCursor}} +associated_issue_refs:closingIssuesReferences(first:$pageSize,after:$cursor){ + nodes{id number title state stateReason repository{id nameWithOwner}} + pageInfo{hasNextPage endCursor} + } +comments:comments(first:$pageSize,after:$cursor){nodes{ + id fullDatabaseId author{login ... on Bot{id} ... on EnterpriseUserAccount{id} ... on Mannequin{id} ... on Organization{id} ... on User{id}} createdAt updatedAt lastEditedAt + body isMinimized minimizedReason isPinned + } pageInfo{hasNextPage endCursor}} +reviews:reviews(first:$pageSize,after:$cursor){nodes{ + id fullDatabaseId author{login ... on Bot{id} ... on EnterpriseUserAccount{id} ... on Mannequin{id} ... on Organization{id} ... on User{id}} state createdAt submittedAt updatedAt + body isMinimized minimizedReason + } pageInfo{hasNextPage endCursor}} +threads:reviewThreads(first:$pageSize,after:$cursor){nodes{ + id path line startLine isResolved isCollapsed isOutdated + resolvedBy{id login} + } pageInfo{hasNextPage endCursor}} +}}} +"#; +#[derive(Deserialize)] +struct PrFirstPages { + assignees: Connection, + labels: Connection, + #[serde(default)] + project_items: Option>, + associated_issue_refs: Connection, + comments: Connection, + reviews: Connection, + threads: Connection, +} +#[derive(Deserialize)] +struct PrFirstData { + repository: Option, +} +#[derive(Deserialize)] +struct PrFirstRepository { + #[serde(rename = "pullRequest")] + object: Option, +} + +#[cfg(test)] +#[path = "context/reading_tests.rs"] +mod reading_tests; + +#[cfg(test)] +#[path = "context/filter_tests.rs"] +mod filter_tests; diff --git a/src/context/filter_tests.rs b/src/context/filter_tests.rs new file mode 100644 index 00000000..aacd9cc9 --- /dev/null +++ b/src/context/filter_tests.rs @@ -0,0 +1,34 @@ +use super::filter_html_comments; + +#[test] +fn html_comments_preserve_surrounding_visible_markdown_bytes() { + for (markdown, expected) in [ + (" visible suffix", " visible suffix"), + ("visibletail", "visibletail"), + ("\nvisible", "\nvisible"), + ("before after", "before after"), + ("前文 后文\r\n", "前文 后文\r\n"), + (" suffix\nnext", " suffix\nnext"), + (" x < 3 tail", " x < 3 tail"), + (" x tail", " x \">visibletail", + "\">visibletail", + ), + ("`", + "```html\n\n```", + " \n", + "visible "; + +pub(crate) struct OperationalCommentCandidate { + node_id: String, + body: String, + created_at: String, +} + +impl OperationalCommentCandidate { + pub(crate) fn from_discussion( + trusted_app: &str, + author_node_id: Option<&str>, + node_id: &str, + body: Option<&str>, + created_at: &str, + ) -> Option { + if author_node_id != Some(trusted_app) { + return None; + } + Some(Self { node_id: node_id.into(), body: body?.into(), created_at: created_at.into() }) + } +} + +/// Declare each actual rendered version before it can be sent to GitHub. +pub(super) fn declare( + tx: &Transaction<'_>, + work_item_node_id: &str, + profile_id: &str, + generation: i64, + body: &str, +) -> Result { + tx.execute( + "INSERT INTO operational_comment_roles + (role_id,work_item_node_id,profile_id,assignment_generation) + VALUES(lower(hex(randomblob(16))),?1,?2,?3) + ON CONFLICT(work_item_node_id,profile_id,assignment_generation) DO NOTHING", + params![work_item_node_id, profile_id, generation], + )?; + let role_id: String = tx.query_row( + "SELECT role_id FROM operational_comment_roles + WHERE work_item_node_id=?1 AND profile_id=?2 AND assignment_generation=?3", + params![work_item_node_id, profile_id, generation], + |row| row.get(0), + )?; + let marked = format!("{body}{ROLE_MARKER_PREFIX}{role_id}{ROLE_MARKER_SUFFIX}"); + tx.execute( + "INSERT INTO operational_comment_role_bodies (role_id,body_digest) VALUES(?1,?2) + ON CONFLICT DO NOTHING", + params![role_id, body_digest(&marked)], + )?; + Ok(marked) +} + +pub(super) fn reconcile( + database: &Path, + work_item_node_id: &str, + candidates: &[OperationalCommentCandidate], +) -> Result, StoreError> { + require_current_schema(database)?; + if candidates.is_empty() { + return known_ids(&open_read_only(database)?, work_item_node_id); + } + let mut connection = open_read_write(database)?; + configure_connection(&connection)?; + let tx = connection.transaction()?; + claim_candidates(&tx, work_item_node_id, candidates)?; + let ids = known_ids(&tx, work_item_node_id)?; + tx.commit()?; + Ok(ids) +} + +fn known_ids(db: &Connection, work_item_node_id: &str) -> Result, StoreError> { + let mut statement = db.prepare( + "SELECT comment_node_id FROM operational_comment_roles + WHERE work_item_node_id=?1 AND comment_node_id IS NOT NULL", + )?; + let rows = statement.query_map([work_item_node_id], |row| row.get(0))?; + rows.collect::>().map_err(StoreError::from) +} + +fn claim_candidates( + tx: &Transaction<'_>, + work_item_node_id: &str, + candidates: &[OperationalCommentCandidate], +) -> Result<(), StoreError> { + let mut matching = tx.prepare( + "SELECT r.role_id FROM operational_comment_roles r + WHERE r.work_item_node_id=?1 AND r.comment_node_id IS NULL AND r.ambiguous=0 + AND NOT EXISTS (SELECT 1 FROM operational_comment_roles seen WHERE seen.comment_node_id=?2) + AND ((r.role_id=?3 AND EXISTS ( + SELECT 1 FROM operational_comment_role_bodies b + WHERE b.role_id=r.role_id AND b.body_digest=?4)) + OR EXISTS ( + SELECT 1 FROM legacy_operational_comment_bodies old + WHERE old.role_id=r.role_id AND old.body=?5 + AND unixepoch(?6) BETWEEN unixepoch(old.not_before) AND unixepoch(?7)))", + )?; + let recovery_until = deadline_rfc3339(5)?; + let mut candidates_by_role = BTreeMap::>::new(); + let mut roles_by_candidate = BTreeMap::<&str, BTreeSet>::new(); + for candidate in candidates { + let marker = role_marker(&candidate.body); + let rows = matching.query_map( + params![ + work_item_node_id, + candidate.node_id, + marker, + marker.map(|_| body_digest(&candidate.body)), + candidate.body, + candidate.created_at, + recovery_until, + ], + |row| row.get::<_, String>(0), + )?; + for role in rows { + let role = role?; + candidates_by_role.entry(role.clone()).or_default().insert(&candidate.node_id); + roles_by_candidate.entry(&candidate.node_id).or_default().insert(role); + } + } + for (role_id, nodes) in &candidates_by_role { + // Both directions must be unique, including old requests with identical bodies. + let node = nodes.first().copied().filter(|node| { + nodes.len() == 1 && roles_by_candidate.get(node).is_some_and(|roles| roles.len() == 1) + }); + tx.execute( + "UPDATE operational_comment_roles SET comment_node_id=?2,ambiguous=?3 WHERE role_id=?1", + params![role_id, node, node.is_none()], + )?; + tx.execute("DELETE FROM legacy_operational_comment_bodies WHERE role_id=?1", [role_id])?; + } + Ok(()) +} + +fn role_marker(body: &str) -> Option<&str> { + let (_, suffix) = body.rsplit_once(ROLE_MARKER_PREFIX)?; + let role_id = suffix.strip_suffix(ROLE_MARKER_SUFFIX)?; + (role_id.len() == 32 && role_id.bytes().all(|byte| byte.is_ascii_hexdigit())).then_some(role_id) +} + +fn body_digest(body: &str) -> String { + hex::encode(Sha256::digest(body.as_bytes())) +} diff --git a/src/store/operational_status.rs b/src/store/operational_status.rs new file mode 100644 index 00000000..f0db9d2a --- /dev/null +++ b/src/store/operational_status.rs @@ -0,0 +1,274 @@ +//! Durable desired projections, not assignment or execution recovery. +use super::{ + StoreError, configure_connection, now_rfc3339, open_read_write, operational_roles, + require_current_schema, +}; +use rusqlite::{OptionalExtension as _, params}; +use sha2::{Digest as _, Sha256}; +use std::path::Path; +use uuid::Uuid; + +struct Key { + node: String, + profile: String, + generation: i64, +} + +pub(super) fn enqueue_failure( + database: &Path, + assignment: &str, + body: &str, + observed_at: Option<&str>, +) -> Result<(), StoreError> { + require_current_schema(database)?; + if body.trim().is_empty() { + return Err(StoreError::InvalidData("Operational Status body is empty".into())); + } + let now = now_rfc3339(); + let db = open_read_write(database)?; + configure_connection(&db)?; + db.execute( + "INSERT INTO operational_status_facts(assignment_id,body,observed_at) VALUES(?1,?2,?3) + ON CONFLICT(assignment_id) DO UPDATE SET body=excluded.body,observed_at=excluded.observed_at + WHERE operational_status_facts.body<>excluded.body", + params![assignment,body,observed_at.unwrap_or(&now)], + )?; + Ok(()) +} + +struct Failure { + assignment: String, + key: Key, + repository: String, + number: i64, + body: String, + observed: String, +} + +fn project_failures(tx: &rusqlite::Transaction<'_>, now: &str) -> Result<(), StoreError> { + let mut query = tx.prepare( + "SELECT f.assignment_id,w.node_id,g.profile_id,a.generation,r.name_with_owner,w.number, + f.body,f.observed_at + FROM operational_status_facts f JOIN assignments a ON a.assignment_id=f.assignment_id + JOIN agent_instances g ON g.assignment_id=a.assignment_id + JOIN work_items w ON w.node_id=a.work_item_node_id + JOIN repositories r ON r.node_id=w.repository_node_id ORDER BY f.rowid", + )?; + let failures = query + .query_map([], |row| { + Ok(Failure { + assignment: row.get(0)?, + key: Key { node: row.get(1)?, profile: row.get(2)?, generation: row.get(3)? }, + repository: row.get(4)?, + number: row.get(5)?, + body: row.get(6)?, + observed: row.get(7)?, + }) + })? + .collect::, _>>()?; + for failure in failures { + project_failure(tx, &failure, now)?; + tx.execute( + "DELETE FROM operational_status_facts WHERE assignment_id=?1", + [&failure.assignment], + )?; + } + Ok(()) +} + +fn project_failure( + tx: &rusqlite::Transaction<'_>, + failure: &Failure, + now: &str, +) -> Result<(), StoreError> { + let Failure { key, repository, number, body, observed, .. } = failure; + let existing=tx.query_row("SELECT projection_kind,failure_body FROM status_comments WHERE work_item_node_id=?1 AND profile_id=?2 AND assignment_generation=?3",params![key.node,key.profile,key.generation],|r|Ok((r.get::<_,String>(0)?,r.get::<_,Option>(1)?))).optional()?; + if existing.as_ref().is_some_and(|(kind, previous)| { + kind == "superseded" || (kind == "failure" && previous.as_deref() == Some(body)) + }) { + return Ok(()); + } + tx.execute("INSERT INTO status_comments(work_item_node_id,profile_id,assignment_generation,body_digest,lifecycle,updated_at,projection_kind,failure_body,failure_recorded_at) VALUES(?1,?2,?3,?4,'pending',?5,'failure',?6,?7) ON CONFLICT(work_item_node_id,profile_id,assignment_generation) DO UPDATE SET projection_kind='failure',failure_body=excluded.failure_body,failure_recorded_at=excluded.failure_recorded_at,successor_generation=NULL",params![key.node,key.profile,key.generation,"0".repeat(64),now,body,observed])?; + let rendered = format!( + "{body}\n\n---\n所属 generation:**{}**;故障确认时间:`{observed}`。此条不是其他 generation 的当前状态。", + key.generation + ); + publish(tx, key, repository, *number, &rendered, now)?; + Ok(()) +} + +// One outbox claim owns reconciliation, including after a service restart. +// Only an accepted current turn or its confirmed normal terminal is evidence; +// assignment creation, a clean worktree or a memory reset is not recovery. +pub(super) fn reconcile(tx: &rusqlite::Transaction<'_>, now: &str) -> Result<(), StoreError> { + project_failures(tx, now)?; + let mut query=tx.prepare("SELECT s.work_item_node_id,s.profile_id,s.assignment_generation,r.name_with_owner,w.number,s.failure_body,s.failure_recorded_at,a.generation,g.profile_id,p.lifecycle,t.lifecycle,CASE WHEN t.lifecycle='completed' THEN t.ended_at ELSE t.started_at END FROM status_comments s JOIN work_items w ON w.node_id=s.work_item_node_id JOIN repositories r ON r.node_id=w.repository_node_id JOIN assignments a ON a.work_item_node_id=w.node_id AND a.generation=(SELECT max(newest.generation) FROM assignments newest WHERE newest.work_item_node_id=w.node_id) JOIN agent_instances g ON g.assignment_id=a.assignment_id JOIN provider_sessions p ON p.agent_id=g.agent_id AND p.rowid=(SELECT max(latest.rowid) FROM provider_sessions latest WHERE latest.agent_id=g.agent_id) JOIN turns t ON t.session_id=p.session_id AND t.rowid=(SELECT max(last.rowid) FROM turns last WHERE last.session_id=p.session_id) WHERE a.lifecycle='active' AND g.lifecycle!='blocked' AND t.provider_turn_id IS NOT NULL AND ((p.lifecycle='idle' AND t.lifecycle='completed') OR (p.lifecycle='running' AND t.lifecycle='running')) AND (s.projection_kind='failure' OR (s.assignment_generation, _>>()?; + for row in rows { + let Some(confirmed) = row.confirmed.as_deref() else { continue }; + if row.generation == row.key.generation + && !confirmation_after(confirmed, row.failure_at.as_deref())? + { + continue; + } + let successor = row.generation > row.key.generation; + let label = if successor { + format!("历史故障 · 已由 generation {} 接替", row.generation) + } else { + "执行可用性已恢复".into() + }; + let previous = row.failure.as_deref().unwrap_or("原故障正文未在本地留存。"); + let quoted = + previous.lines().map(|line| format!("> {line}")).collect::>().join("\n"); + let body = format!( + "> **Braid Operational Status · `{}` · generation {}**\n\n**{label}**\n\n最后确认:`{confirmed}`。generation **{}**(Profile `{}`)已由 Provider 接受执行;该次确认的 Session 状态为 `{}`,turn 状态为 `{}`。\n\n{}这只确认执行接手或正常终止,不代表代码已修改、review 已落实或产品已验收,也不是未来持续可用的保证。\n\n### 原故障(历史记录)\n\n{quoted}", + row.key.profile, + row.key.generation, + row.generation, + row.profile, + row.session, + row.turn, + if successor { "原 generation 未被解阻或复用。" } else { "" } + ); + publish(tx, &row.key, &row.repository, row.number, &body, now)?; + tx.execute("UPDATE status_comments SET projection_kind=?4,successor_generation=?5 WHERE work_item_node_id=?1 AND profile_id=?2 AND assignment_generation=?3",params![row.key.node,row.key.profile,row.key.generation,if successor{"superseded"}else{"recovered"},successor.then_some(row.generation)])?; + } + // A preceding create may have settled since this desired projection was + // queued. Resolve the stable remote ID at claim, never create a second one. + tx.execute("UPDATE github_write_outbox AS o SET operation='comment_update',target_kind='issue_comment',target_database_id=(SELECT s.remote_comment_database_id FROM status_comments s WHERE s.work_item_node_id=o.status_work_item_node_id AND s.profile_id=o.status_profile_id AND s.assignment_generation=o.status_generation) WHERE o.lifecycle='pending' AND o.operation='comment_create' AND EXISTS(SELECT 1 FROM status_comments s WHERE s.work_item_node_id=o.status_work_item_node_id AND s.profile_id=o.status_profile_id AND s.assignment_generation=o.status_generation AND s.remote_comment_database_id IS NOT NULL AND s.remote_comment_node_id IS NOT NULL)",[])?; + block_unidentified_creates(tx, now)?; + Ok(()) +} + +/// A terminal multiple-match receipt cannot identify the original comment. +/// Propagate that uncertainty to later creates for this key rather than +/// guessing a PATCH target, issuing another POST, or stalling other keys. +fn block_unidentified_creates(tx: &rusqlite::Transaction<'_>, now: &str) -> Result<(), StoreError> { + let blocked = tx.execute( + "UPDATE github_write_outbox AS desired + SET lifecycle='ambiguous', updated_at=?1, + last_error='Earlier status create matched multiple App comments; remote identity unresolved; no new create attempted' + WHERE desired.status_work_item_node_id IS NOT NULL + AND desired.operation='comment_create' AND desired.lifecycle='pending' + AND EXISTS ( + SELECT 1 FROM github_write_outbox AS earlier + WHERE earlier.status_work_item_node_id=desired.status_work_item_node_id + AND earlier.status_profile_id=desired.status_profile_id + AND earlier.status_generation=desired.status_generation + AND earlier.rowid) -> 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( + |error| { + StoreError::InvalidData(format!( + "invalid operational status confirmation timestamp: {error}" + )) + }, + ) + }; + Ok(parse(confirmed)? > parse(failure)?) +} + +struct Recovery { + key: Key, + repository: String, + number: i64, + failure: Option, + failure_at: Option, + generation: i64, + profile: String, + session: String, + turn: String, + confirmed: Option, +} + +fn publish( + tx: &rusqlite::Transaction<'_>, + key: &Key, + repository: &str, + number: i64, + body: &str, + now: &str, +) -> Result<(), StoreError> { + let (old_digest,old_intent,remote)=tx.query_row("SELECT body_digest,write_intent_id,remote_comment_database_id FROM status_comments WHERE work_item_node_id=?1 AND profile_id=?2 AND assignment_generation=?3",params![key.node,key.profile,key.generation],|r|Ok((r.get::<_,String>(0)?,r.get::<_,Option>(1)?,r.get::<_,Option>(2)?)))?; + let digest = hex::encode(Sha256::digest(body.as_bytes())); + if digest == old_digest && old_intent.is_some() { + return Ok(()); + } + let marked_body = + operational_roles::declare(tx, &key.node, &key.profile, key.generation, body)?; + let intent = Uuid::now_v7().to_string(); + tx.execute("UPDATE github_write_outbox SET lifecycle='superseded',updated_at=?4 WHERE status_work_item_node_id=?1 AND status_profile_id=?2 AND status_generation=?3 AND lifecycle='pending'",params![key.node,key.profile,key.generation,now])?; + let request = + hex::encode(Sha256::digest(format!("operational-status\0{intent}\0{digest}").as_bytes())); + let (operation, kind, target) = remote.map_or_else( + || ("comment_create", "issue", number.to_string()), + |id| ("comment_update", "issue_comment", id), + ); + tx.execute("INSERT INTO github_write_outbox(intent_id,repository,target_kind,target_database_id,operation,content,request_digest,lifecycle,next_attempt_at,created_at,updated_at,status_work_item_node_id,status_profile_id,status_generation) VALUES(?1,?2,?3,?4,?5,?6,?7,'pending',?8,?8,?8,?9,?10,?11)",params![intent,repository,kind,target,operation,marked_body,request,now,key.node,key.profile,key.generation])?; + tx.execute("UPDATE status_comments SET write_intent_id=?4,body_digest=?5,lifecycle='pending',updated_at=?6 WHERE work_item_node_id=?1 AND profile_id=?2 AND assignment_generation=?3",params![key.node,key.profile,key.generation,intent,digest,now])?; + Ok(()) +} + +pub(super) fn settle( + tx: &rusqlite::Transaction<'_>, + intent: &str, + lifecycle: &str, + remote_id: Option<&str>, + remote_node: Option<&str>, + now: &str, +) -> Result<(), StoreError> { + // A stale publication still owns its remote create result, but not the + // lifecycle of a newer desired publication. Keep both facts atomically. + 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 new file mode 100644 index 00000000..d4d57727 --- /dev/null +++ b/src/store/operational_status_migration_tests.rs @@ -0,0 +1,186 @@ +use super::{ + MIGRATIONS, OperationalCommentCandidate, StoreActor, apply_one, configure_connection, + open_read_write, +}; +use rusqlite::params; + +#[test] +fn status_convergence_upgrades_an_already_published_schema12_failure_without_a_new_turn() { + let root = std::env::temp_dir().join(format!("braid-status-upgrade-{}", uuid::Uuid::now_v7())); + std::fs::create_dir_all(&root).unwrap(); + let database = root.join("state.sqlite3"); + let mut db = open_read_write(&database).unwrap(); + configure_connection(&db).unwrap(); + for migration in MIGRATIONS.iter().filter(|m| m.version <= 12) { + apply_one(&mut db, migration).unwrap(); + } + db.execute_batch("INSERT INTO repositories VALUES('repo','owner/repository',1,'2000-01-01T00:00:00Z'); INSERT INTO work_items(node_id,repository_node_id,kind,number,state,observed_at) VALUES('item','repo','pr',194,'open','2000-01-01T00:00:00Z'); INSERT INTO assignments VALUES('old','item',1,'blocked','2000-01-01T00:00:00Z',NULL),('new','item',2,'active','2002-01-01T00:00:00Z',NULL); INSERT INTO profiles VALUES('profile',1,'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa','codex','pr'); INSERT INTO agent_instances(agent_id,assignment_id,profile_id,profile_revision,role,lifecycle) VALUES('agent-old','old','profile',1,'pr_implementation_agent','blocked'),('agent-new','new','profile',1,'pr_implementation_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-new','codex','provider','context','instructions','idle','2002-01-01T00:00:00Z'); INSERT INTO turns(turn_id,session_id,provider_turn_id,context_revision,trigger_kind,lifecycle,started_at,ended_at) VALUES('confirmed','session','native-accepted','context','wake','completed','2002-01-01T00:00:00Z','2002-01-01T00:00:01Z');").unwrap(); + db.execute("INSERT INTO github_write_outbox(intent_id,repository,target_kind,target_database_id,operation,content,request_digest,lifecycle,next_attempt_at,created_at,updated_at,remote_database_id) VALUES('old-publication','owner/repository','issue','194','comment_create','Provider session unavailable',?1,'applied','2001-01-01T00:00:00Z','2001-01-01T00:00:00Z','2001-01-01T00:00:00Z','7120481524')",["a".repeat(64)]).unwrap(); + 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(); + store.apply().unwrap(); + assert_eq!( + store.reconcile_operational_comment_roles("item".into(), vec![]).unwrap(), + ["status-node".to_owned()].into() + ); + let owner = store.acquire_runtime_lease("runtime".into(), "publisher".into(), 3600).unwrap(); + let write = store.claim_github_write(owner.clone()).unwrap().unwrap(); + assert_eq!(write.operation, "comment_update"); + assert_eq!(write.target_database_id, "7120481524"); + assert!(write.content.contains("已由 generation 2 接替")); + assert!(write.content.contains("2002-01-01T00:00:01Z")); + store + .finish_github_write( + write, + "applied", + Some("7120481524".into()), + Some("status-node".into()), + None, + ) + .unwrap(); + assert!(store.claim_github_write(owner.clone()).unwrap().is_none()); + store.release_runtime_lease(owner).unwrap(); + let db = open_read_write(&database).unwrap(); + assert_eq!( + db.query_row("SELECT count(*) FROM turns", [], |r| r.get::<_, i64>(0)).unwrap(), + 1, + "no provider or new scheduling was needed" + ); + assert_eq!( + db.query_row("SELECT lifecycle FROM assignments WHERE assignment_id='old'", [], |r| r + .get::<_, String>( + 0 + )) + .unwrap(), + "blocked" + ); + assert_eq!( + db.query_row( + "SELECT status_generation FROM github_write_outbox WHERE intent_id='old-publication'", + [], + |r| r.get::<_, i64>(0) + ) + .unwrap(), + 1 + ); + let violations: i64 = db + .query_row("SELECT count(*) FROM pragma_foreign_key_check", params![], |r| r.get(0)) + .unwrap(); + assert_eq!(violations, 0); + drop(db); + drop(store); + std::fs::remove_dir_all(root).unwrap(); +} + +#[test] +#[allow(clippy::too_many_lines)] +fn role_migration_preserves_legacy_evidence_and_requires_a_unique_identity() { + let root = std::env::temp_dir().join(format!("braid-role-upgrade-{}", uuid::Uuid::now_v7())); + std::fs::create_dir_all(&root).unwrap(); + let database = root.join("state.sqlite3"); + let mut db = open_read_write(&database).unwrap(); + configure_connection(&db).unwrap(); + for migration in MIGRATIONS.iter().filter(|migration| migration.version <= 17) { + apply_one(&mut db, migration).unwrap(); + } + db.execute_batch( + "INSERT INTO repositories VALUES('repo','owner/repository',1,'now'); + INSERT INTO work_items(node_id,repository_node_id,kind,number,state,observed_at) + VALUES('item','repo','issue',1,'open','now'),('other','repo','issue',2,'open','now');", + ) + .unwrap(); + for (generation, body, lifecycle, attempts) in [ + (1, "one match", "sending", 1), + (2, "two matches", "uncertain", 1), + (3, "never sent", "pending", 0), + ] { + let intent = format!("legacy-{generation}"); + let digest = format!("{generation:064}"); + db.execute( + "INSERT INTO status_comments(work_item_node_id,profile_id,assignment_generation, + write_intent_id,body_digest,lifecycle,updated_at) + VALUES('item','profile',?1,?2,?3,'pending','now')", + params![generation, intent, digest], + ) + .unwrap(); + db.execute("INSERT INTO github_write_outbox(intent_id,repository,target_kind,target_database_id, + operation,content,request_digest,lifecycle,attempts,next_attempt_at,created_at, + updated_at,status_work_item_node_id,status_profile_id,status_generation) + VALUES(?1,'owner/repository','issue','1','comment_create',?2,?3,?4,?5, + '2000-01-02T00:00:00Z','2000-01-02T00:00:00Z','2000-01-02T00:00:00Z', + 'item','profile',?6)", + params![intent,body,digest,lifecycle,attempts,generation]).unwrap(); + } + drop(db); + let store = StoreActor::start(database.clone(), root.join("backups")).unwrap(); + store.apply().unwrap(); + let candidate = |node, body, created| { + OperationalCommentCandidate::from_discussion("app", Some("app"), node, Some(body), created) + .unwrap() + }; + let observed = "2000-01-03T00:00:00Z"; + let wrong_scope = store + .reconcile_operational_comment_roles( + "other".into(), + vec![candidate("unrelated", "one match", observed)], + ) + .unwrap(); + assert!(wrong_scope.is_empty()); + let recognized = store + .reconcile_operational_comment_roles( + "item".into(), + vec![ + candidate("too-early", "one match", "2000-01-01T00:00:00Z"), + candidate("status", "one match", observed), + candidate("twin-one", "two matches", observed), + candidate("twin-two", "two matches", observed), + ], + ) + .unwrap(); + assert_eq!(recognized, ["status".to_owned()].into()); + let recognized_again = store + .reconcile_operational_comment_roles( + "item".into(), + vec![candidate("twin-one", "two matches", observed)], + ) + .unwrap(); + assert_eq!(recognized_again, recognized, "one twin disappearing does not resolve ambiguity"); + let db = open_read_write(&database).unwrap(); + let marked_pending: String = db + .query_row( + "SELECT content FROM github_write_outbox WHERE intent_id='legacy-3'", + [], + |row| row.get(0), + ) + .unwrap(); + assert!(marked_pending.starts_with("never sent\n\n", false), + (" @braid", true), + (" `@braid`", false), + (" [review](/@braid)", false), + (" [@braid](/review)", true), + ] { + for handle in ["braid", "@braid"] { + assert_eq!(has_visible_mention(body, handle), expected, "{body:?}, {handle}"); + } + } +} + +#[test] +fn opening_body_mention_remains_pending_and_agent_echo_cannot_request_attention() { + let mut opening = payload(); + opening.as_object_mut().unwrap().remove("comment"); + opening["action"] = json!("opened"); + opening["issue"]["body"] = json!("@braid discuss this design"); + let admitted = parse(&opening, "issues"); + assert_eq!(admitted.kind, EventKind::Mention); + assert!(admitted.mention_candidate); + assert!(admitted.requires_attention); + assert_eq!(admitted.origin, "external"); + for (node, login) in + [("APP", "renamed-bot"), ("renamed-node", "braid[bot]"), ("AGENT", "coding-agent")] + { + let mut echo = payload(); + echo["sender"] = json!({"node_id":node,"login":login}); + let admitted = parse(&echo, "issue_comment"); + assert_eq!(admitted.kind, EventKind::OriginEcho); + assert_eq!(admitted.origin, "agent"); + assert!(!admitted.mention_candidate); + assert!(!admitted.requires_attention); + assert!(admitted.reaction_target.is_none()); + } + let human = parse(&payload(), "issue_comment"); + assert_eq!(human.kind, EventKind::Wake); + assert!(human.mention_candidate); + assert!(human.requires_attention); + let reaction = human.reaction_target.unwrap(); + assert_eq!(reaction.kind, "issue_comment"); + assert_eq!(reaction.database_id, "7"); +} + +#[test] +fn comment_edits_compare_visible_suffix_instead_of_discarding_the_html_block_line() { + for (body, expected) in [ + (" current design", EventKind::Noop), + (" changed design", EventKind::Invalidate), + ] { + let mut edited = payload(); + edited["action"] = json!("edited"); + edited["changes"] = json!({"body":{"from":" current design"}}); + edited["comment"]["body"] = json!(body); + let admitted = parse(&edited, "issue_comment"); + assert_eq!(admitted.kind, expected, "{body}"); + assert_eq!(admitted.requires_attention, expected == EventKind::Invalidate); + } +} + +#[test] +fn human_edit_of_a_braid_authored_body_is_not_an_echo_or_an_urgent_mention() { + let mut revision = payload(); + revision.as_object_mut().unwrap().remove("comment"); + revision["action"] = json!("edited"); + revision["changes"] = json!({"body":{"from":"old requirements"}}); + revision["issue"]["body"] = + json!("> **Braid Agent · Braid**\n> Issue Agent\n\nRevised requirements"); + let event = parse(&revision, "issues"); + assert_eq!(event.kind, EventKind::Invalidate); + assert!(event.requires_attention); + assert!(!event.mention_candidate); + assert_eq!(event.origin, "external"); +} diff --git a/src/worktree.rs b/src/worktree.rs index 2dcdde32..bd433042 100644 --- a/src/worktree.rs +++ b/src/worktree.rs @@ -27,6 +27,8 @@ pub struct WorktreeRequest<'a> { pub target: &'a Path, pub repository: &'a str, pub remote: &'a str, + /// Local collaboration resolves refs from the source checkout without a network remote. + pub local_only: bool, /// System `git` executable used for the network fetch: it honors the /// operator's credential helpers and proxy configuration, which libgit2 /// does not. @@ -45,18 +47,20 @@ pub struct ProvisionedWorktree { pub fn provision(request: &WorktreeRequest<'_>) -> Result { let source = tokio::task::block_in_place(|| canonical_repository(request.source))?; - let remote_url = tokio::task::block_in_place(|| { - let repo = Repository::open(&source)?; - let remote = repo.find_remote(request.remote)?; - Ok::(remote.url()?.to_owned()) - })?; - if normalized_github_repository(&remote_url).as_deref() - != Some(&request.repository.to_ascii_lowercase()) - { - return Err(WorktreeError::Git(format!( - "remote {} does not identify GitHub repository {}", - request.remote, request.repository - ))); + if !request.local_only { + let remote_url = tokio::task::block_in_place(|| { + let repo = Repository::open(&source)?; + let remote = repo.find_remote(request.remote)?; + Ok::(remote.url()?.to_owned()) + })?; + if normalized_github_repository(&remote_url).as_deref() + != Some(&request.repository.to_ascii_lowercase()) + { + return Err(WorktreeError::Git(format!( + "remote {} does not identify GitHub repository {}", + request.remote, request.repository + ))); + } } exclude_private_notes(request, &source)?; if request.target.exists() { @@ -87,11 +91,14 @@ pub fn provision(request: &WorktreeRequest<'_>) -> Result) -> Result(()) })?; @@ -167,6 +174,16 @@ fn verify_existing( } let branch = tokio::task::block_in_place(|| { let repo = Repository::open(request.target)?; + let source_repo = Repository::open(source)?; + let canonical_common_dir = |repo: &Repository| { + repo.commondir().canonicalize().map_err(|source| WorktreeError::Io { + path: repo.commondir().to_path_buf(), + source, + }) + }; + if canonical_common_dir(&repo)? != canonical_common_dir(&source_repo)? { + return Err(WorktreeError::TargetConflict(request.target.to_path_buf())); + } let head = repo.head()?; Ok::(head.shorthand()?.to_owned()) })?; @@ -196,7 +213,7 @@ fn canonical_repository(path: &Path) -> Result { }) } -fn normalized_github_repository(remote: &str) -> Option { +pub(crate) fn normalized_github_repository(remote: &str) -> Option { let path = remote .strip_prefix("https://github.com/") .or_else(|| remote.strip_prefix("ssh://git@github.com/")) @@ -204,3 +221,6 @@ 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/src/worktree/tests.rs b/src/worktree/tests.rs new file mode 100644 index 00000000..23ac1358 --- /dev/null +++ b/src/worktree/tests.rs @@ -0,0 +1,78 @@ +use super::*; + +fn initialize(path: &Path) { + let repository = git2::Repository::init(path).unwrap(); + repository.set_head("refs/heads/main").unwrap(); + let tree_id = repository.index().unwrap().write_tree().unwrap(); + let tree = repository.find_tree(tree_id).unwrap(); + let signature = git2::Signature::now("Braid Test", "braid@example.invalid").unwrap(); + repository.commit(Some("HEAD"), &signature, &signature, "initial", &tree, &[]).unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn existing_target_must_share_the_requested_source_repository() { + let root = std::env::temp_dir().join(format!("braid-worktree-{}", uuid::Uuid::now_v7())); + let source = root.join("source"); + let wrong = root.join("wrong-repository"); + let target = root.join("actual-worktree"); + initialize(&source); + initialize(&wrong); + let git = which::which("git").unwrap(); + let mut request = WorktreeRequest { + source: &source, + target: &wrong, + repository: "owner/repository", + remote: "origin", + local_only: true, + git: &git, + head_ref: "main", + local_branch: "main", + }; + assert!(matches!(provision(&request), Err(WorktreeError::TargetConflict(_)))); + + request.target = ⌖ + request.local_branch = "agent"; + let created = provision(&request).unwrap(); + assert_eq!(created.path, target.canonicalize().unwrap()); + 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(); +} + +#[test] +fn github_remote_identity_is_exact() { + for remote in [ + "https://github.com/Owner/Repo.git", + "ssh://git@github.com/owner/repo.git", + "git@github.com:owner/repo.git", + ] { + 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!(normalized_github_repository(remote), None); + } + assert_eq!( + normalized_github_repository("https://github.com/owner/repo-backup.git").as_deref(), + Some("owner/repo-backup") + ); +} diff --git a/src/writer/comment.rs b/src/writer/comment.rs index 2cd18ffd..022bcb43 100644 --- a/src/writer/comment.rs +++ b/src/writer/comment.rs @@ -1,12 +1,35 @@ #![allow(clippy::wildcard_imports)] +use super::helpers::{RemoteWrite, WriteFailure, WriteResult}; use super::*; -use crate::writer::helpers::{RemoteWrite, WriteFailure, WriteResult}; pub async fn converge_comment( + config: &Config, github: &GitHubClient, issue_number: u64, receipt: &GhWriteReceipt, + mutation_possible: &mut bool, ) -> WriteResult { + if let Some(remote) = recover_comment(github, issue_number, receipt).await? { + return Ok(remote); + } + super::edit::authorize(config, github, receipt, false).await?; + let item = github.issue_or_pull_request(issue_number).await?; + github.require_write_permissions(&[if item.kind() == "pr" { + "pull_requests" + } else { + "issues" + }])?; + check_source(config, receipt)?; + *mutation_possible = true; + let comment = github.create_issue_comment(issue_number, &receipt.payload).await?; + Ok(RemoteWrite { database_id: comment.id.to_string(), node_id: comment.node_id }) +} + +pub async fn recover_comment( + github: &GitHubClient, + issue_number: u64, + receipt: &GhWriteReceipt, +) -> Result, WriteFailure> { if receipt.attempts > 0 { let candidates = github .issue_comments(issue_number) @@ -15,6 +38,10 @@ pub async fn converge_comment( .filter(|comment| { comment.body.as_deref() == Some(receipt.payload.as_str()) && comment.created_at >= receipt.created_at + && receipt + .recovery_until + .as_ref() + .is_none_or(|until| comment.created_at <= *until) && comment .user .as_ref() @@ -23,24 +50,14 @@ pub async fn converge_comment( .collect::>(); match candidates.as_slice() { [comment] => { - return Ok(RemoteWrite { + return Ok(Some(RemoteWrite { database_id: comment.id.to_string(), node_id: comment.node_id.clone(), - url: comment.html_url.clone(), - }); + })); } [] => {} _ => return Err(WriteFailure::Ambiguous("multiple matching App comments".into())), } } - let comment = github.create_issue_comment(issue_number, &receipt.payload).await?; - Ok(RemoteWrite { - database_id: comment.id.to_string(), - node_id: comment.node_id, - url: format!( - "https://github.com/{}/issues/{issue_number}#issuecomment-{}", - github.identity().repository, - comment.id - ), - }) + Ok(None) } diff --git a/src/writer/edit.rs b/src/writer/edit.rs new file mode 100644 index 00000000..8740858a --- /dev/null +++ b/src/writer/edit.rs @@ -0,0 +1,367 @@ +#![allow(clippy::wildcard_imports)] +use super::*; +use crate::github::BodySnapshot; +use helpers::{RemoteWrite, WriteFailure, WriteResult}; + +#[derive(serde::Serialize, serde::Deserialize)] +pub struct ReadForEdit { + target: String, + snapshot: BodySnapshot, + digest: String, +} + +pub struct EditRequest { + pub invocation: Invocation, + pub target: WorkItemLocator, + pub profile_id: String, + pub snapshot: String, + pub title: Option, + pub body: Option, + pub request_id: String, +} + +pub async fn read_for_edit(config: &Config, target: &WorkItemLocator) -> Result { + helpers::require_configured_repository(config, target)?; + let github = GitHubClient::connect(config.github()?, &target.repository).await?; + read_snapshot(&github, target).await +} + +pub(super) async fn read_snapshot( + github: &GitHubClient, + target: &WorkItemLocator, +) -> Result { + let snapshot = github.body_snapshot(target.number).await?; + Ok(serde_json::to_string_pretty(&ReadForEdit { + target: target.to_string(), + digest: snapshot.digest(), + snapshot, + })?) +} + +pub fn edit(config: &Config, store: &StoreActor, request: EditRequest) -> Result { + helpers::require_configured_repository(config, &request.target)?; + config.github()?; + helpers::validate_request_id(&request.request_id)?; + let profile = config.profile(&request.profile_id)?; + if config.profile_repository(profile) != request.target.repository.to_string() { + bail!("Profile repository mismatch"); + } + let read: ReadForEdit = serde_json::from_str(&request.snapshot)?; + if read.target != request.target.to_string() || read.digest != read.snapshot.digest() { + bail!("snapshot target or digest mismatch; read the canonical target again"); + } + if request.title.is_none() && request.body.is_none() { + bail!("edit requires --title or --body-file"); + } + let source = resolve_source(config, Some(&profile.id), &request.invocation)?; + let role = helpers::publication_role(profile, source.as_ref(), read.snapshot.kind())?; + let title = request.title.unwrap_or(read.snapshot.title); + if title.trim().is_empty() || title.len() > 256 { + bail!("title must contain 1-256 bytes"); + } + let old_body = read.snapshot.body.unwrap_or_default(); + let body = match request.body { + Some(body) => render_maintained_body(profile, role, &body, &old_body)?, + None => old_body, + }; + if body.len() > COMMENT_BODY_LIMIT { + bail!("body exceeds safe byte limit"); + } + let payload = serde_json::to_string(&AcceptedRequest::Edit { + profile: profile.clone(), + expected: read.digest, + title, + body, + })?; + store + .prepare_gh_write(NewGhWriteIntent { + request_key: format!( + "body_edit\0{}\0{}\0{}", + request.target, + source.as_ref().map_or_else( + || "operator".into(), + |s| format!("{}:{}", s.assignment_id, s.generation) + ), + request.request_id + ), + operation: "body_edit", + repository: request.target.repository.to_string(), + target: request.target.to_string(), + profile_id: profile.id.clone(), + role: role.into(), + source, + request_digest: helpers::digest(&payload), + payload, + }) + .map_err(Into::into) +} + +fn render_maintained_body( + profile: &Profile, + role: &str, + body: &str, + old_body: &str, +) -> Result { + let mut body = body.trim().to_owned(); + if body.trim().is_empty() { + bail!("body must not be empty"); + } + // Attribution is owned by the source, not copied from a previous writer. + while body.starts_with("> **Braid Agent ·") { + body = body.split_once("\n\n").map_or("", |(_, rest)| rest).to_owned(); + } + let protected = protected_body_sections(old_body)?; + let prefix = protected.join("\n\n"); + while !prefix.is_empty() && body.starts_with(&prefix) { + body = body[prefix.len()..].trim_start().to_owned(); + } + // Prefix complete original Markdown blocks so an unclosed code fence or + // HTML comment in the replacement cannot hide a closing reference/marker. + if !protected.is_empty() { + body = format!("{prefix}\n\n{body}"); + } + let rendered = helpers::render_agent_comment(profile, role, &body)?; + validate_maintained_body(old_body, &rendered)?; + Ok(rendered) +} + +/// Preserve recognized existing sources, not a predicted GitHub relationship set. +/// Only self-contained top-level paragraphs/headings can be moved safely; +/// context-dependent existing sources are refused rather than silently discarded. +/// This detector is deliberately not GitHub's private closing-reference parser. +fn protected_body_sections(body: &str) -> Result> { + use comrak::{Arena, Options, nodes::NodeValue, parse_document}; + let arena = Arena::new(); + let root = parse_document(&arena, body, &Options::default()); + let lines: Vec<_> = body.lines().collect(); + let mut covered = vec![false; lines.len()]; + let mut protected = Vec::new(); + for node in root.children() { + let data = node.data.borrow(); + let start = data.sourcepos.start.line.saturating_sub(1); + let end = data.sourcepos.end.line; + let Some(block_lines) = lines.get(start..end) else { continue }; + let section = block_lines.join("\n"); + // Decoded inline text also identifies existing sources with emphasis, + // escapes or entities. Replacement Markdown is not screened for keywords. + let mut text = String::new(); + for descendant in node.descendants() { + match &descendant.data.borrow().value { + NodeValue::Text(value) => text.push_str(value), + NodeValue::Code(value) => text.push_str(&value.literal), + NodeValue::SoftBreak | NodeValue::LineBreak => text.push(' '), + _ => {} + } + } + if !recognized_body_source(§ion) && !recognized_body_source(&text) { + continue; + } + // Brackets include unresolved reference links, whose meaning could be + // changed by a definition added later. Do not try to emulate GitHub's + // private parser or silently move context-dependent Markdown. + if !matches!(data.value, NodeValue::Paragraph | NodeValue::Heading(_)) + || section.contains(['[', ']', '<', '>']) + { + bail!( + "body maintenance requires self-contained paragraph/heading closing and request blocks without links or HTML; keep this body unchanged" + ); + } + covered[start..end].fill(true); + protected.push(section); + } + // Reference definitions may not have AST nodes. Refuse a recognized existing + // source not represented by a supported block rather than dropping it. + let remainder = lines + .iter() + .zip(covered) + .filter_map(|(line, covered)| (!covered).then_some(*line)) + .collect::>() + .join("\n"); + if recognized_body_source(&remainder) { + bail!("body maintenance cannot change context-dependent closing or request blocks"); + } + Ok(protected) +} + +fn recognized_body_source(text: &str) -> bool { + let lower = text.to_ascii_lowercase(); + if lower.contains("implementation request:") { + return true; + } + let words = lower.split_whitespace().collect::>(); + words.windows(2).any(|pair| { + let keyword = pair[0].trim_matches(|c: char| !c.is_ascii_alphabetic()); + let target = pair[1].trim_start_matches(['[', '(', '<', '\\']); + matches!( + keyword, + "close" + | "closes" + | "closed" + | "fix" + | "fixes" + | "fixed" + | "resolve" + | "resolves" + | "resolved" + ) && (target + .split_once('#') + .is_some_and(|(_, number)| number.starts_with(|c: char| c.is_ascii_digit())) + || (pair[1].starts_with('[') + && lower.contains("github.com/") + && lower.contains("/issues/")) + || ((target.starts_with("https://github.com/") + || target.starts_with("http://github.com/")) + && target.contains("/issues/"))) + }) +} + +fn validate_maintained_body(old_body: &str, body: &str) -> Result<()> { + if body == old_body { + return Ok(()); + } + let prefix = protected_body_sections(old_body)?.join("\n\n"); + // A complete prefix outside replacement fences/comments preserves the known + // sources. New native closing text is allowed; only GitHub can confirm edges. + let content = if body.starts_with("> **Braid Agent ·") { + body.split_once("\n\n").map_or("", |(_, rest)| rest) + } else { + body + }; + if !content.starts_with(&prefix) { + bail!("body maintenance must retain recognized existing closing and request sources"); + } + Ok(()) +} + +/// Operation permission is independent of Profile selection tags. +pub(super) async fn authorize( + config: &Config, + github: &GitHubClient, + receipt: &GhWriteReceipt, + editing: bool, +) -> Result<(), GitHubError> { + let target: WorkItemLocator = receipt.target.parse()?; + let item = github.issue_or_pull_request(target.number).await?; + if editing && !item.state.eq_ignore_ascii_case("open") { + return Err(GitHubError::GraphQl("body target is closed".into())); + } + let Some(source) = &receipt.source else { + return Ok(()); + }; + let (repository, kind, number) = + crate::store::publication_source::work_item(config.runtime.database(), source) + .map_err(|e| helpers::store_as_github_error(&e))?; + if repository != target.repository.to_string() { + return Err(GitHubError::GraphQl("source repository mismatch".into())); + } + if number == target.number && kind == item.kind() { + return Ok(()); + } + let related = if kind == "pr" && item.kind() == "issue" { + github + .pull_request_closing_issues(number) + .await? + .iter() + .any(|i| i.repository == repository && i.number == target.number) + } else if !editing && kind == "issue" && item.kind() == "pr" { + github + .pull_request_closing_issues(target.number) + .await? + .iter() + .any(|i| i.repository == repository && i.number == number) + } else { + false + }; + if !related { + return Err(GitHubError::GraphQl( + "target is not a permitted directly associated work item".into(), + )); + } + if editing { + let source_item = github.issue_or_pull_request(number).await?; + if !source_item.state.eq_ignore_ascii_case("open") { + return Err(GitHubError::GraphQl("source PR is closed".into())); + } + } + Ok(()) +} + +pub(super) async fn execute( + config: &Config, + store: &StoreActor, + github: &GitHubClient, + receipt: &GhWriteReceipt, + mutation_possible: &mut bool, +) -> WriteResult { + let AcceptedRequest::Edit { expected, title, body, .. } = + serde_json::from_str(&receipt.payload).map_err(|e| GitHubError::GraphQl(e.to_string()))? + else { + return Err(GitHubError::GraphQl("invalid body edit payload".into()).into()); + }; + let target: WorkItemLocator = receipt.target.parse()?; + let current = github.body_snapshot(target.number).await?; + // Recovery checks exact resulting content before any possible retry. A later Human + // change is a conflict, not evidence of our success and never overwritten. + if receipt.attempts > 0 && current.title == title && current.body.as_deref() == Some(&body) { + record_version(store, receipt, ¤t)?; + return Ok(RemoteWrite { database_id: current.id.to_string(), node_id: current.node_id }); + } + if current.digest() != expected { + return Err(WriteFailure::GitHub(GitHubError::Http { + status: axum::http::StatusCode::CONFLICT, + body: "canonical title/body changed since snapshot; read again".into(), + })); + } + authorize(config, github, receipt, true).await?; + github.require_write_permissions(&[if current.kind() == "pr" { + "pull_requests" + } else { + "issues" + }])?; + let latest = github.body_snapshot(target.number).await?; + if latest.digest() != expected { + return Err(GitHubError::Http { + status: axum::http::StatusCode::CONFLICT, + body: "canonical version changed during validation; read again".into(), + } + .into()); + } + validate_maintained_body(current.body.as_deref().unwrap_or_default(), &body) + .map_err(|e| GitHubError::GraphQl(e.to_string()))?; + check_source(config, receipt)?; + *mutation_possible = true; + let result = github.edit_body(target.number, &title, &body).await?; + if result.title != title || result.body.as_deref() != Some(&body) { + return Err(GitHubError::ConvergencePending( + "GitHub did not confirm requested title/body".into(), + ) + .into()); + } + record_version(store, receipt, &result)?; + Ok(RemoteWrite { database_id: result.id.to_string(), node_id: result.node_id }) +} + +fn record_version( + store: &StoreActor, + receipt: &GhWriteReceipt, + snapshot: &BodySnapshot, +) -> Result<(), GitHubError> { + let digest = crate::store::publication_digest( + &snapshot.node_id, + &snapshot.updated_at, + Some(&snapshot.title), + snapshot.body.as_deref().unwrap_or(""), + ); + store + .record_publication_version( + receipt.intent_id.clone(), + snapshot.node_id.clone(), + snapshot.updated_at.clone(), + digest, + ) + .map_err(|error| { + GitHubError::ConvergencePending(format!( + "publication version evidence could not be committed: {error}" + )) + }) +} diff --git a/src/writer/ensure.rs b/src/writer/ensure.rs index da89acbf..06a1d459 100644 --- a/src/writer/ensure.rs +++ b/src/writer/ensure.rs @@ -6,17 +6,43 @@ pub async fn converge_pull_request( github: &GitHubClient, store: &StoreActor, receipt: &ImplementationRequestReceipt, + mutation_possible: &mut bool, ) -> Result { - let request_marker = format!("Implementation request: {}", receipt.write.target); - let mut pull_request = helpers::unique_request_pull_request( - github, - &receipt.head_ref, - &receipt.base_ref, - &request_marker, - ) - .await?; + let request_marker = format!("Implementation request: {}", receipt.root_target); + let mut pull_request = if let Some(number) = receipt.pull_request_number { + let pr = github.pull_request(number).await?; + if pr.head.reference != receipt.head_ref + || pr.base.reference != receipt.base_ref + || receipt.pull_request_node_id.as_deref() != Some(pr.node_id.as_str()) + { + return Err(GitHubError::GraphQl( + "frozen PR no longer matches implementation request".into(), + )); + } + if receipt.activation_delivered && receipt.write.intent_id == receipt.root_intent_id { + return Ok(pr); + } + Some(pr) + } else { + helpers::unique_request_pull_request( + github, + &receipt.head_ref, + &receipt.base_ref, + &request_marker, + ) + .await? + }; + let source = github.issue_or_pull_request(receipt.issue_number).await?; + if source.node_id != receipt.issue_node_id + || source.kind() != "issue" + || !source.state.eq_ignore_ascii_case("open") + { + return Err(GitHubError::GraphQl( + "implementation source Issue is no longer the same open work item".into(), + )); + } if pull_request.is_none() { - helpers::ensure_head(github, store, receipt).await?; + helpers::ensure_head(config, github, store, receipt, mutation_possible).await?; pull_request = helpers::unique_request_pull_request( github, &receipt.head_ref, @@ -30,47 +56,58 @@ pub async fn converge_pull_request( } else { let title = helpers::bounded_title(receipt.issue_number, &receipt.issue_title); let body = format!("Closes #{}\n\n{request_marker}", receipt.issue_number); + check_source(config, &receipt.write)?; + *mutation_possible = true; github .create_draft_pull_request(&title, &body, &receipt.head_ref, &receipt.base_ref) .await? }; + if !pull_request.state.eq_ignore_ascii_case("open") { + return Err(GitHubError::GraphQl("implementation request PR is no longer open; refusing to create a replacement or reactivate it".into())); + } + if matches!(receipt.stage.as_str(), "planned" | "head_ready" | "pull_request_ready") { + record_stage(store, receipt, &pull_request, "pull_request_ready")?; + } + if matches!(receipt.stage.as_str(), "associated" | "activation_pending") { + if !github.pull_request_closing_issues(pull_request.number).await?.iter().any(|edge| { + edge.repository == receipt.write.repository && edge.number == receipt.issue_number + }) { + return Err(GitHubError::GraphQl( + "managed implementation is no longer directly associated with its source Issue" + .into(), + )); + } + } else { + helpers::wait_for_native_association(github, pull_request.number, receipt.issue_number) + .await?; + } + if receipt.stage != "activation_pending" { + record_stage(store, receipt, &pull_request, "associated")?; + record_stage(store, receipt, &pull_request, "activation_pending")?; + } + if !receipt.activation_delivered { + check_execution_owner(config, &receipt.write)?; + helpers::record_pr_activation(config, github, store, receipt, &pull_request).await?; + } + Ok(pull_request) +} + +fn record_stage( + store: &StoreActor, + receipt: &ImplementationRequestReceipt, + pr: &PullRequest, + stage: &'static str, +) -> Result<(), GitHubError> { store .record_implementation_progress( receipt.write.intent_id.clone(), ImplementationProgress { - stage: "pull_request_ready", - bootstrap_commit_sha: None, - pull_request_database_id: Some(pull_request.id), - pull_request_node_id: Some(pull_request.node_id.clone()), - pull_request_number: Some(pull_request.number), - }, - ) - .map_err(|error| helpers::store_as_github_error(&error))?; - helpers::wait_for_native_association(github, pull_request.number, receipt.issue_number).await?; - store - .record_implementation_progress( - receipt.write.intent_id.clone(), - ImplementationProgress { - stage: "associated", - bootstrap_commit_sha: None, - pull_request_database_id: Some(pull_request.id), - pull_request_node_id: Some(pull_request.node_id.clone()), - pull_request_number: Some(pull_request.number), - }, - ) - .map_err(|error| helpers::store_as_github_error(&error))?; - store - .record_implementation_progress( - receipt.write.intent_id.clone(), - ImplementationProgress { - stage: "activation_pending", + stage, bootstrap_commit_sha: None, - pull_request_database_id: Some(pull_request.id), - pull_request_node_id: Some(pull_request.node_id.clone()), - pull_request_number: Some(pull_request.number), + pull_request_database_id: Some(pr.id), + pull_request_node_id: Some(pr.node_id.clone()), + pull_request_number: Some(pr.number), }, ) - .map_err(|error| helpers::store_as_github_error(&error))?; - helpers::record_pr_activation(config, github, store, receipt, &pull_request)?; - Ok(pull_request) + .map_err(|error| helpers::store_as_github_error(&error)) } diff --git a/src/writer/handoff.rs b/src/writer/handoff.rs new file mode 100644 index 00000000..2222286d --- /dev/null +++ b/src/writer/handoff.rs @@ -0,0 +1,101 @@ +//! Explicit delivery of an Issue's canonical design to an existing PR generation. +use super::{AcceptedRequest, Invocation, check_source, helpers, resolve_source}; +use crate::{ + config::Config, + github::{GitHubClient, GitHubError, WorkItemLocator}, + store::{GhWriteReceipt, NewGhWriteIntent, StoreActor}, +}; +use anyhow::{Result, bail}; + +pub struct HandoffRequest { + pub invocation: Invocation, + pub target: WorkItemLocator, + pub request_id: String, +} + +pub fn handoff( + config: &Config, + store: &StoreActor, + request: &HandoffRequest, +) -> Result { + helpers::require_configured_repository(config, &request.target)?; + config.github()?; + helpers::validate_request_id(&request.request_id)?; + let source = resolve_source(config, None, &request.invocation)? + .ok_or_else(|| anyhow::anyhow!("handoff requires a bound Issue Agent, not Operator"))?; + if source.role != "issue_agent" { + bail!("handoff requires an Issue Agent"); + } + let (repository, kind, _) = + crate::store::publication_source::work_item(config.runtime.database(), &source)?; + if repository != request.target.repository.to_string() || kind != "issue" { + bail!("handoff must stay within the source Issue repository"); + } + let payload = serde_json::to_string(&AcceptedRequest::Handoff { + quiet_seconds: config.scheduler.quiet_seconds, + event_threshold: config.scheduler.event_threshold, + })?; + store + .prepare_gh_write(NewGhWriteIntent { + request_key: format!( + "pr_handoff\0{}\0{}\0{}", + source.assignment_id, source.generation, request.request_id + ), + operation: "pr_handoff", + repository, + target: request.target.to_string(), + profile_id: source.profile_id.clone(), + role: "Issue Agent".into(), + request_digest: helpers::digest(&request.target.to_string()), + payload, + source: Some(source), + }) + .map_err(Into::into) +} + +pub(super) async fn execute( + config: &Config, + github: &GitHubClient, + receipt: &GhWriteReceipt, +) -> helpers::WriteResult { + check_source(config, receipt)?; + crate::store::handoff::validate(config.runtime.database(), receipt) + .map_err(|e| helpers::store_as_github_error(&e))?; + let source = + receipt.source.as_ref().ok_or_else(|| GitHubError::GraphQl("missing source".into()))?; + let (repository, _, number) = + crate::store::publication_source::work_item(config.runtime.database(), source) + .map_err(|e| helpers::store_as_github_error(&e))?; + if github.identity().repository != repository { + return Err(GitHubError::GraphQl("handoff installation repository mismatch".into()).into()); + } + github.require_write_permissions(&["issues", "pull_requests"])?; + let issue = github.issue_or_pull_request(number).await?; + let target: WorkItemLocator = receipt.target.parse()?; + let pr = github.issue_or_pull_request(target.number).await?; + // GitHub's canonical OPEN state excludes merged PRs (which are CLOSED). + if issue.kind() != "issue" + || !issue.state.eq_ignore_ascii_case("open") + || pr.kind() != "pr" + || !pr.state.eq_ignore_ascii_case("open") + { + return Err(GitHubError::GraphQl( + "handoff requires an OPEN Issue and OPEN unmerged PR".into(), + ) + .into()); + } + if !github + .pull_request_closing_issues(target.number) + .await? + .iter() + .any(|i| i.repository == repository && i.number == number) + { + return Err(GitHubError::GraphQl( + "handoff requires GitHub-confirmed direct association, not body text or references" + .into(), + ) + .into()); + } + check_source(config, receipt)?; + Ok(helpers::RemoteWrite { database_id: target.number.to_string(), node_id: pr.node_id }) +} diff --git a/src/writer/helpers.rs b/src/writer/helpers.rs index bc5cf872..37c302a8 100644 --- a/src/writer/helpers.rs +++ b/src/writer/helpers.rs @@ -2,11 +2,12 @@ use super::*; pub fn require_configured_repository(config: &Config, target: &WorkItemLocator) -> Result<()> { - if target.repository.to_string() != config.github.repository { + let target_repository = target.repository.to_string(); + if !config.github_repositories().contains(&target_repository.as_str()) { bail!( - "target repository {} does not match configured repository {}", + "target repository {} is not configured for this instance (configured: {})", target.repository, - config.github.repository + config.github_repositories().join(", ") ); } Ok(()) @@ -20,6 +21,22 @@ pub fn role_for_target(profile: &Profile, kind: &str) -> Result<&'static str> { } } +pub fn publication_role( + profile: &Profile, + source: Option<&crate::store::publication_source::PublicationSource>, + kind: &str, +) -> Result<&'static str> { + match source.map(|source| source.role.as_str()) { + Some("issue_agent") => Ok("Issue Agent"), + Some("pr_implementation_agent") => Ok("PR Implementation Agent"), + Some(_) => bail!("unknown publication source role"), + None => { + role_for_target(profile, kind)?; + Ok("Operator") + } + } +} + pub fn render_agent_comment(profile: &Profile, role: &str, body: &str) -> Result { let attribution = format!("> **Braid Agent · {}**\n> {}", profile.display_name, role); let mut body = body.trim(); @@ -45,11 +62,19 @@ pub async fn unique_request_pull_request( base: &str, marker: &str, ) -> Result, GitHubError> { - let pull_requests = github.open_pull_requests_for_head(head, base).await?; + let pull_requests = github.pull_requests_for_head(head, base).await?; + if pull_requests.len() >= 100 { + return Err(GitHubError::Ambiguous( + "implementation request PR recovery exceeds one complete page".into(), + )); + } match pull_requests.as_slice() { [] => Ok(None), [pull_request] - if pull_request.body.as_deref().is_some_and(|body| body.contains(marker)) => + if pull_request + .body + .as_deref() + .is_some_and(|body| body.lines().any(|line| line.trim() == marker)) => { Ok(Some(pull_request.clone())) } @@ -57,9 +82,9 @@ pub async fn unique_request_pull_request( "head {head:?} already belongs to unrelated PR #{}", pull_request.number ))), - _ => Err(GitHubError::GraphQl(format!( - "head {head:?} resolves to multiple open pull requests" - ))), + _ => { + Err(GitHubError::Ambiguous(format!("head {head:?} resolves to multiple pull requests"))) + } } } @@ -83,9 +108,11 @@ pub async fn wait_for_native_association( } pub async fn ensure_head( + config: &Config, github: &GitHubClient, store: &StoreActor, receipt: &ImplementationRequestReceipt, + mutation_possible: &mut bool, ) -> Result<(), GitHubError> { let base = github.git_reference(&receipt.base_ref).await?.ok_or_else(|| { GitHubError::GraphQl(format!("base ref {:?} does not exist", receipt.base_ref)) @@ -99,6 +126,8 @@ pub async fn ensure_head( let parent_commit = github.git_commit(parent).await?; let message = format!("chore(braid): initialize implementation request {}", receipt.comment_database_id); + check_source(config, &receipt.write)?; + *mutation_possible = true; let bootstrap = github .create_git_commit( &message, @@ -107,6 +136,7 @@ pub async fn ensure_head( &receipt.bootstrap_authored_at, ) .await?; + check_source(config, &receipt.write)?; let mutation = if head.is_some() { github.update_git_reference(&receipt.head_ref, &bootstrap.sha).await } else { @@ -155,7 +185,7 @@ fn record_head_ready( .map_err(|error| store_as_github_error(&error)) } -pub fn record_pr_activation( +pub async fn record_pr_activation( config: &Config, github: &GitHubClient, store: &StoreActor, @@ -163,184 +193,102 @@ pub fn record_pr_activation( pull_request: &PullRequest, ) -> Result<(), GitHubError> { let repository = &github.identity().repository; - let reference = format!( - "Implementation Request comment {repository}#issuecomment-{} ensured GitHub PR {repository}#{}.", - receipt.comment_database_id, pull_request.number, - ); + let selected = config + .pr_profile_for_repository(repository) + .map_err(|error| GitHubError::GraphQl(error.to_string()))?; + if selected.id != receipt.pr_profile_id { + return Err(GitHubError::GraphQl("configured PR Profile changed since acceptance; refusing to switch activation identity".into())); + } + if let Ok(AcceptedRequest::Ensure { profile, .. }) = + serde_json::from_str(&receipt.write.payload) + && serde_json::to_string(&profile).ok() != serde_json::to_string(selected).ok() + { + return Err(GitHubError::GraphQl( + "PR Profile revision changed since acceptance; refusing to switch activation identity" + .into(), + )); + } + let issue_basis = store + .begin_observation(receipt.issue_node_id.clone()) + .map_err(|e| store_as_github_error(&e))?; + let target_basis = store + .begin_observation(pull_request.node_id.clone()) + .map_err(|e| store_as_github_error(&e))?; + let target = github.pull_request(pull_request.number).await?; + let issue = github.issue_or_pull_request(receipt.issue_number).await?; + if target.node_id != pull_request.node_id + || target.head.reference != receipt.head_ref + || target.base.reference != receipt.base_ref + || !target.state.eq_ignore_ascii_case("open") + || issue.node_id != receipt.issue_node_id + || issue.kind() != "issue" + || !issue.state.eq_ignore_ascii_case("open") + { + return Err(GitHubError::GraphQl( + "published implementation no longer has its authorized open source and target".into(), + )); + } + if !github + .pull_request_closing_issues(target.number) + .await? + .iter() + .any(|edge| edge.repository == *repository && edge.number == receipt.issue_number) + { + return Err(GitHubError::GraphQl( + "published implementation lost its canonical Issue association".into(), + )); + } + let owner = + receipt.write.execution_owner.clone().ok_or_else(|| { + GitHubError::GraphQl("activation delivery has no runtime owner".into()) + })?; store - .ingest_event( - IngressEvent { - delivery_guid: format!( - "braid-pr-ensure-{repository}-{}", - receipt.comment_database_id - ), - event_name: "braid".into(), - action: Some("pr_ensure".into()), - repository_node_id: github.identity().repository_node_id.clone(), - repository: repository.clone(), - work_item_node_id: Some(pull_request.node_id.clone()), - work_item_kind: Some("pr"), - work_item_number: Some(pull_request.number), - work_item_state: Some(pull_request.state.clone()), - object_node_id: None, - object_version: None, - object_digest: None, - visible_body: None, - actor_node_id: Some(github.identity().actor_node_id.clone()), - actor_login: Some(github.identity().actor_login.clone()), - kind: crate::store::EventKind::Assign, - detail: Some("pr_ensure"), - cross_surface_invalidation: false, - origin: "braid", - reference, - mention_candidate: false, - reaction_target: None, - known: true, - raw_payload: Vec::new(), - }, - SchedulerPolicy { + .accept_pr_activation(crate::store::PrActivation { + intent_id: receipt.write.intent_id.clone(), + repository_node: github.identity().repository_node_id.clone(), + pr_node: target.node_id, + pr_number: target.number, + policy: SchedulerPolicy { quiet_seconds: config.scheduler.quiet_seconds, event_threshold: config.scheduler.event_threshold, }, - ) - .map(|_| ()) - .map_err(|error| store_as_github_error(&error)) -} - -pub enum Claim { - Owned(GhWriteReceipt), - Done(GhWriteReceipt), -} - -pub async fn claim_or_wait(store: &StoreActor, intent_id: &str) -> Result { - for _ in 0..CLAIM_POLLS { - let receipt = store - .gh_write_receipt(intent_id.to_owned())? - .context("Braid write state disappeared while waiting for convergence")?; - match receipt.lifecycle.as_str() { - "applied" => return Ok(Claim::Done(receipt)), - "rejected" | "conflict" | "ambiguous" => { - bail!( - "braid gh {} for {} is {}: {}", - receipt.operation, - receipt.target, - receipt.lifecycle, - receipt.last_error.as_deref().unwrap_or("no detail") - ); + owner, + issue_basis, + target_basis, + }) + .map_err(|error| match error { + crate::store::StoreError::ObservationChanged { .. } + | crate::store::StoreError::Sqlite(_) + | crate::store::StoreError::ActorUnavailable + | crate::store::StoreError::ActorStopped => { + GitHubError::ConvergencePending(format!("activation delivery must retry: {error}")) } - "pending" | "uncertain" | "sending" => { - if store.claim_gh_write(intent_id.to_owned())? { - let claimed = store - .gh_write_receipt(intent_id.to_owned())? - .context("claimed Braid write state disappeared")?; - return Ok(Claim::Owned(claimed)); - } - } - lifecycle => bail!("unsupported braid gh write lifecycle {lifecycle:?}"), - } - tokio::time::sleep(CLAIM_POLL_INTERVAL).await; - } - bail!("timed out waiting for a concurrent braid gh write to converge") + _ => store_as_github_error(&error), + }) } pub struct RemoteWrite { pub database_id: String, pub node_id: String, - pub url: String, } - pub enum WriteFailure { GitHub(GitHubError), Ambiguous(String), } - -impl WriteFailure { - pub fn is_unavailable(&self) -> bool { - matches!(self, Self::GitHub(error) if error.is_unavailable()) - } -} - -impl std::fmt::Display for WriteFailure { - fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Self::GitHub(error) => error.fmt(formatter), - Self::Ambiguous(message) => formatter.write_str(message), - } - } -} - impl From for WriteFailure { fn from(error: GitHubError) -> Self { Self::GitHub(error) } } - -pub type WriteResult = Result; - -pub fn settle_write(store: &StoreActor, intent_id: &str, result: WriteResult) -> Result<()> { - match result { - Ok(remote) => store.finish_gh_write( - intent_id.to_owned(), - "applied", - Some(remote.database_id), - Some(remote.node_id), - Some(remote.url), - None, - )?, - Err(error) => { - let lifecycle = match error { - WriteFailure::Ambiguous(_) => "ambiguous", - WriteFailure::GitHub(_) if error.is_unavailable() => "uncertain", - WriteFailure::GitHub(_) => "rejected", - }; - store.finish_gh_write( - intent_id.to_owned(), - lifecycle, - None, - None, - None, - Some(error.to_string()), - )?; +impl std::fmt::Display for WriteFailure { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::GitHub(e) => e.fmt(f), + Self::Ambiguous(e) => f.write_str(e), } } - Ok(()) -} - -pub fn completed_receipt(store: &StoreActor, intent_id: &str) -> Result { - let receipt = store - .gh_write_receipt(intent_id.to_owned())? - .context("Braid write state disappeared before completion")?; - if receipt.lifecycle == "applied" { - Ok(receipt) - } else { - bail!( - "braid gh {} for {} is {}: {}", - receipt.operation, - receipt.target, - receipt.lifecycle, - receipt.last_error.as_deref().unwrap_or("no detail") - ) - } -} - -pub fn completed_implementation_receipt( - store: &StoreActor, - intent_id: &str, -) -> Result { - let receipt = store - .implementation_request_receipt(intent_id.to_owned())? - .context("Implementation Request state disappeared before completion")?; - if receipt.write.lifecycle == "applied" { - Ok(receipt) - } else { - bail!( - "braid gh pr ensure for Issue #{} is {}: {}", - receipt.issue_number, - receipt.write.lifecycle, - receipt.write.last_error.as_deref().unwrap_or("no detail") - ) - } } +pub type WriteResult = Result; pub fn bounded_title(issue_number: u64, title: &str) -> String { let title = title.chars().take(180).collect::(); @@ -360,16 +308,7 @@ pub fn validate_request_id(request_id: &str) -> Result<()> { } pub fn validate_branch(branch: &str) -> Result<()> { - let invalid = branch.is_empty() - || branch.starts_with(['/', '.']) - || branch.ends_with(['/', '.']) - || branch.to_ascii_lowercase().ends_with(".lock") - || branch.contains("..") - || branch.contains("@{") - || branch.chars().any(|character| { - character.is_control() || character.is_whitespace() || "~^:?*[\\".contains(character) - }); - if invalid { + if !git2::Reference::is_valid_name(&format!("refs/heads/{branch}")) { bail!("invalid Git branch name {branch:?}"); } Ok(()) @@ -380,5 +319,18 @@ pub fn digest(value: &str) -> String { } pub fn store_as_github_error(error: &crate::store::StoreError) -> GitHubError { - GitHubError::GraphQl(format!("local durable state rejected PR convergence: {error}")) + use crate::store::StoreError; + let retryable = match error { + StoreError::ActorUnavailable | StoreError::ActorStopped => true, + StoreError::Sqlite(error) => matches!( + error.sqlite_error_code(), + Some(rusqlite::ErrorCode::DatabaseBusy | rusqlite::ErrorCode::DatabaseLocked) + ), + _ => false, + }; + if retryable { + GitHubError::ConvergencePending(format!("local durable state is unavailable: {error}")) + } else { + GitHubError::GraphQl(format!("local durable state rejected publication: {error}")) + } } diff --git a/src/writer/mod.rs b/src/writer/mod.rs index d5dc616f..70d2b453 100644 --- a/src/writer/mod.rs +++ b/src/writer/mod.rs @@ -9,21 +9,29 @@ use crate::{ context, github::{GitHubClient, GitHubError, PullRequest, WorkItemLocator}, store::{ - GhWriteReceipt, ImplementationProgress, ImplementationRequestReceipt, IngressEvent, - NewGhWriteIntent, NewImplementationRequest, SchedulerPolicy, StoreActor, + GhWriteReceipt, ImplementationProgress, ImplementationRequestReceipt, NewGhWriteIntent, + NewImplementationRequest, SchedulerPolicy, StoreActor, }, }; mod comment; +mod edit; +mod handoff; +pub use edit::{EditRequest, edit, read_for_edit}; +pub use handoff::{HandoffRequest, handoff}; mod ensure; -mod helpers; +pub(crate) mod helpers; mod prepare; const COMMENT_BODY_LIMIT: usize = 60_000; -const CLAIM_POLLS: usize = 240; -const CLAIM_POLL_INTERVAL: Duration = Duration::from_millis(250); + +pub enum Invocation { + Agent(String), + Operator, +} pub struct CommentCreateRequest { + pub invocation: Invocation, pub target: WorkItemLocator, pub profile_id: String, pub body: String, @@ -31,102 +39,269 @@ pub struct CommentCreateRequest { } pub struct PullRequestEnsureRequest { + pub invocation: Invocation, + pub repository: crate::github::RepositoryName, pub comment_id: u64, pub head: Option, } -pub async fn create_comment( +pub fn create_comment( config: &Config, store: &StoreActor, request: CommentCreateRequest, ) -> Result { helpers::require_configured_repository(config, &request.target)?; let profile = config.profile(&request.profile_id)?; - let github = GitHubClient::connect(&config.github, &request.target.repository) - .await - .context("cannot authenticate Braid App comment writer")?; - let work_item = github.issue_or_pull_request(request.target.number).await?; - let role = helpers::role_for_target(profile, work_item.kind())?; - github.require_write_permissions(&[if work_item.kind() == "pr" { - "pull_requests" - } else { - "issues" - }])?; - let body = helpers::render_agent_comment(profile, role, &request.body)?; - let idempotency = match request.request_id { - Some(request_id) => { - helpers::validate_request_id(&request_id)?; - request_id - } - None => body.clone(), + if config.profile_repository(profile) != request.target.repository.to_string() { + bail!( + "Profile {:?} serves {}, not {}", + profile.id, + config.profile_repository(profile), + request.target.repository + ); + } + config.github()?; + // Snapshot the local profile; remote kind and permissions remain unvalidated. + helpers::render_agent_comment(profile, "PR Implementation Agent", &request.body)?; + let source = resolve_source(config, Some(&profile.id), &request.invocation)?; + let role = match source.as_ref().map(|s| s.role.as_str()) { + Some("issue_agent") => "Issue Agent", + Some("pr_implementation_agent") => "PR Implementation Agent", + Some(_) => bail!("unknown source role"), + None => "Operator", }; - let request_key = format!( - "comment_create\0{}\0{}\0{}\0{}", - request.target.repository, request.target.number, profile.id, idempotency - ); - let request_digest = helpers::digest(&format!( - "comment_create\0{}\0{}\0{}\0{}\0{}", - request.target.repository, request.target.number, profile.id, role, body - )); - let receipt = store.prepare_gh_write(NewGhWriteIntent { - request_key, - operation: "comment_create", - repository: request.target.repository.to_string(), - target: request.target.to_string(), - profile_id: profile.id.clone(), - role: role.into(), - payload: body, - request_digest, + let scope = source.as_ref().map_or("operator", |s| s.assignment_id.as_str()); + let payload = serde_json::to_string(&AcceptedRequest::Comment { + profile: profile.clone(), + body: request.body.trim().to_owned(), })?; - match helpers::claim_or_wait(store, &receipt.intent_id).await? { - helpers::Claim::Done(receipt) => Ok(receipt), - helpers::Claim::Owned(receipt) => { - let result = comment::converge_comment(&github, request.target.number, &receipt).await; - helpers::settle_write(store, &receipt.intent_id, result)?; - helpers::completed_receipt(store, &receipt.intent_id) - } - } + let idempotency = request.request_id.unwrap_or_else(|| helpers::digest(&payload)); + helpers::validate_request_id(&idempotency)?; + store + .prepare_gh_write(NewGhWriteIntent { + request_key: format!( + "comment_create\0{}\0{}\0{}\0{}\0{}", + request.target.repository, request.target.number, profile.id, scope, idempotency + ), + operation: "comment_create", + repository: request.target.repository.to_string(), + target: request.target.to_string(), + profile_id: profile.id.clone(), + role: role.into(), + source, + request_digest: helpers::digest(&payload), + payload, + }) + .map_err(Into::into) } -pub async fn ensure_pull_request( +pub fn ensure_pull_request( config: &Config, store: &StoreActor, request: PullRequestEnsureRequest, -) -> Result { - let repository = config.github.repository.parse()?; - let github = GitHubClient::connect(&config.github, &repository) - .await - .context("cannot authenticate Braid App PR writer")?; - let receipt = - prepare::prepare_pull_request(config, store, &github, repository, request).await?; - match helpers::claim_or_wait(store, &receipt.write.intent_id).await? { - helpers::Claim::Done(_) => { - helpers::completed_implementation_receipt(store, &receipt.write.intent_id) +) -> Result { + helpers::require_configured_repository( + config, + &WorkItemLocator { repository: request.repository.clone(), number: 1 }, + )?; + config.github()?; + if request.comment_id == 0 { + bail!("comment ID must be positive"); + } + if let Some(head) = &request.head { + helpers::validate_branch(head)?; + } + let profile = config.pr_profile_for_repository(&request.repository.to_string())?; + if !profile.has_tag("pr") { + bail!("PR Profile must be tagged pr"); + } + let source = resolve_source(config, None, &request.invocation)?; + if source.as_ref().is_some_and(|source| source.role != "issue_agent") { + bail!("initial PR ensure requires an Issue Agent source"); + } + let payload = serde_json::to_string(&AcceptedRequest::Ensure { + comment_id: request.comment_id, + head: request.head, + profile: profile.clone(), + })?; + store + .prepare_gh_write(NewGhWriteIntent { + request_key: format!("pr_ensure\0{}\0{}", request.repository, request.comment_id), + operation: "pr_ensure", + repository: request.repository.to_string(), + target: format!( + "https://github.com/{}/issues/comments/{}", + request.repository, request.comment_id + ), + profile_id: profile.id.clone(), + role: "PR Implementation Agent".into(), + source, + request_digest: helpers::digest(&payload), + payload, + }) + .map_err(Into::into) +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(tag = "operation", rename_all = "snake_case")] +pub(crate) enum AcceptedRequest { + Handoff { quiet_seconds: u64, event_threshold: u32 }, + Comment { profile: Profile, body: String }, + Edit { profile: Profile, expected: String, title: String, body: String }, + Ensure { comment_id: u64, head: Option, profile: Profile }, +} + +/// The runtime is the sole mutation owner. Acceptance does not authorize a remote target. +pub(crate) async fn execute( + config: &Config, + store: &StoreActor, + github: &GitHubClient, + write: &crate::store::PendingGitHubWrite, + mutation_possible: &mut bool, +) -> helpers::WriteResult { + use helpers::{RemoteWrite, WriteFailure}; + let mut receipt = store + .gh_write_receipt(write.intent_id.clone()) + .map_err(|e| helpers::store_as_github_error(&e))? + .ok_or_else(|| GitHubError::GraphQl("accepted write disappeared".into()))?; + receipt.recovery_until = Some(write.recovery_until.clone()); + receipt.execution_owner = Some(write.owner.clone()); + receipt.attempts = u64::from(write.lifecycle == "uncertain"); + if receipt.operation == "pr_handoff" { + return handoff::execute(config, github, &receipt).await; + } + if receipt.operation == "body_edit" { + return edit::execute(config, store, github, &receipt, mutation_possible).await; + } + if receipt.operation == "comment_create" { + let target: WorkItemLocator = receipt.target.parse()?; + let item = github.issue_or_pull_request(target.number).await?; + if let Ok(AcceptedRequest::Comment { profile, body }) = + serde_json::from_str(&receipt.payload) + { + let role = helpers::publication_role(&profile, receipt.source.as_ref(), item.kind()) + .map_err(|e| GitHubError::GraphQl(e.to_string()))?; + receipt.payload = helpers::render_agent_comment(&profile, role, &body) + .map_err(|e| GitHubError::GraphQl(e.to_string()))?; + } else { + helpers::role_for_target( + config + .profile(&receipt.profile_id) + .map_err(|e| GitHubError::GraphQl(e.to_string()))?, + item.kind(), + ) + .map_err(|e| GitHubError::GraphQl(e.to_string()))?; + } + comment::converge_comment(config, github, target.number, &receipt, mutation_possible).await + } else { + let mut plan = if let Some(plan) = store + .implementation_request_receipt(receipt.intent_id.clone()) + .map_err(|e| helpers::store_as_github_error(&e))? + { + plan + } else { + let AcceptedRequest::Ensure { comment_id, head, profile } = + serde_json::from_str(&receipt.payload) + .map_err(|e| GitHubError::GraphQl(e.to_string()))? + else { + return Err(WriteFailure::GitHub(GitHubError::GraphQl( + "invalid ensure request".into(), + ))); + }; + prepare::prepare_pull_request( + config, + store, + github, + &receipt, + profile, + PullRequestEnsureRequest { + invocation: Invocation::Operator, + repository: receipt.repository.parse()?, + comment_id, + head, + }, + ) + .await? + }; + plan.write.execution_owner = Some(write.owner.clone()); + if plan.pr_profile_id != receipt.profile_id { + return Err(GitHubError::GraphQl("frozen Profile mismatch".into()).into()); + } + github.require_write_permissions(&["pull_requests", "contents"])?; + if plan.pull_request_number.is_none() { + check_source(config, &receipt)?; + } else { + check_execution_owner(config, &receipt)?; + } + let pr = + ensure::converge_pull_request(config, github, store, &plan, mutation_possible).await?; + Ok(RemoteWrite { database_id: pr.id.to_string(), node_id: pr.node_id }) + } +} + +pub(crate) fn resolve_source( + config: &Config, + profile: Option<&str>, + invocation: &Invocation, +) -> Result> { + let cwd = std::env::current_dir()?; + match invocation { + Invocation::Agent(turn) => { + let source = crate::store::publication_source::resolve_turn( + config.runtime.database(), + &cwd, + profile, + turn, + )?; + let materials = config.profile_materials(config.profile(&source.profile_id)?)?; + if u64::try_from(source.profile_revision)? != materials.revision { + bail!("publication Profile materials differ from the running assignment"); + } + Ok(Some(source)) } - helpers::Claim::Owned(_) => { - let result = ensure::converge_pull_request(config, &github, store, &receipt).await; - match result { - Ok(pull_request) => store.finish_gh_write( - receipt.write.intent_id.clone(), - "applied", - Some(pull_request.id.to_string()), - Some(pull_request.node_id), - Some(pull_request.html_url), - None, - )?, - Err(error) => { - let lifecycle = if error.is_unavailable() { "uncertain" } else { "rejected" }; - store.finish_gh_write( - receipt.write.intent_id.clone(), - lifecycle, - None, - None, - None, - Some(error.to_string()), - )?; - } + Invocation::Operator => { + if std::env::var_os("BRAID_AGENT").is_some() + || crate::store::publication_source::is_runtime_worktree( + config.runtime.database(), + &cwd, + )? + { + bail!("operator entry is unavailable inside an Agent runtime worktree"); } - helpers::completed_implementation_receipt(store, &receipt.write.intent_id) + Ok(None) } } } + +pub(crate) fn check_execution_owner( + config: &Config, + receipt: &GhWriteReceipt, +) -> Result<(), GitHubError> { + let owner = receipt + .execution_owner + .as_ref() + .ok_or_else(|| GitHubError::GraphQl("publication has no runtime owner".into()))?; + crate::store::check_publication_owner(config.runtime.database(), owner) + .map_err(|e| helpers::store_as_github_error(&e)) +} + +pub(crate) fn check_source(config: &Config, receipt: &GhWriteReceipt) -> Result<(), GitHubError> { + if receipt.execution_owner.is_some() { + check_execution_owner(config, receipt)?; + } + if let Some(source) = &receipt.source { + crate::store::publication_source::check(config.runtime.database(), source) + .map_err(|e| helpers::store_as_github_error(&e))?; + let profile = + config.profile(&source.profile_id).map_err(|e| GitHubError::GraphQl(e.to_string()))?; + let materials = + config.profile_materials(profile).map_err(|e| GitHubError::GraphQl(e.to_string()))?; + if u64::try_from(source.profile_revision).ok() != Some(materials.revision) { + return Err(GitHubError::GraphQl("publication Profile materials changed".into())); + } + } + Ok(()) +} + +#[cfg(test)] +pub(crate) mod tests; diff --git a/src/writer/prepare.rs b/src/writer/prepare.rs index 8bb2e107..bc2e9da3 100644 --- a/src/writer/prepare.rs +++ b/src/writer/prepare.rs @@ -5,8 +5,24 @@ pub async fn prepare_pull_request( config: &Config, store: &StoreActor, github: &GitHubClient, - repository: crate::github::RepositoryName, + accepted: &GhWriteReceipt, + profile: Profile, + request: PullRequestEnsureRequest, +) -> Result { + let repository = request.repository.clone(); + prepare_plan(config, store, github, accepted, profile, request, repository).await.map_err(|e| { + e.downcast::().unwrap_or_else(|e| GitHubError::GraphQl(e.to_string())) + }) +} + +async fn prepare_plan( + config: &Config, + store: &StoreActor, + github: &GitHubClient, + accepted: &GhWriteReceipt, + profile: Profile, request: PullRequestEnsureRequest, + repository: crate::github::RepositoryName, ) -> Result { github.require_write_permissions(&["pull_requests", "contents"])?; let comment = github.issue_comment(request.comment_id).await?; @@ -19,6 +35,20 @@ pub async fn prepare_pull_request( issue_number ); } + if !issue.state.eq_ignore_ascii_case("open") { + bail!("Implementation Request Issue is closed"); + } + if let Some(source) = &accepted.source { + let (source_repository, source_kind, source_number) = + crate::store::publication_source::work_item(config.runtime.database(), source) + .map_err(|e| helpers::store_as_github_error(&e))?; + if source_repository != repository.to_string() + || source_kind != "issue" + || source_number != issue_number + { + bail!("initial PR ensure must originate from its own Issue source"); + } + } let repository_details = github.repository_details().await?; let base_ref = repository_details.default_branch; let issue_locator = WorkItemLocator { repository: repository.clone(), number: issue_number }; @@ -29,7 +59,7 @@ pub async fn prepare_pull_request( match issue_context.linked_branches.as_slice() { [] => format!("braid/implementation-request-{}", request.comment_id), [linked] => linked - .strip_prefix(&format!("{}:", config.github.repository)) + .strip_prefix(&format!("{repository}:")) .map(str::to_owned) .with_context(|| { format!( @@ -46,33 +76,20 @@ pub async fn prepare_pull_request( if head_ref == base_ref { bail!("Implementation Request head must differ from the default branch {base_ref:?}"); } - let profile = config.profile(&config.profile_selection.default_pr_profile)?; - if !profile.has_tag("pr") { - bail!("default PR Profile {:?} is not tagged pr", profile.id); - } - let profile_digest = helpers::digest(&serde_json::to_string(profile)?); - let request_key = format!("pr_ensure\0{}\0{}", config.github.repository, request.comment_id); - let request_digest = helpers::digest(&format!( - "pr_ensure\0{}\0{}\0{}\0{}\0{}\0{}", - config.github.repository, - request.comment_id, - base_ref, - head_ref, - profile.id, - profile_digest - )); + let root = managed_root( + store, + github, + &repository.to_string(), + &head_ref, + &base_ref, + &issue, + &profile, + ) + .await?; store .prepare_implementation_request(NewImplementationRequest { - write: NewGhWriteIntent { - request_key, - operation: "pr_ensure", - repository: config.github.repository.clone(), - target: comment.html_url.clone(), - profile_id: profile.id.clone(), - role: "PR Implementation Agent".into(), - payload: comment.html_url.clone(), - request_digest, - }, + root_intent_id: root, + intent_id: accepted.intent_id.clone(), comment_database_id: request.comment_id, comment_node_id: comment.node_id, issue_node_id: issue.node_id, @@ -82,5 +99,78 @@ pub async fn prepare_pull_request( head_ref, pr_profile_id: profile.id.clone(), }) - .map_err(Into::into) + .map_err(|e| helpers::store_as_github_error(&e).into()) +} + +async fn managed_root( + store: &StoreActor, + github: &GitHubClient, + repository: &str, + head: &str, + base: &str, + issue: &crate::github::IssueOrPullRequest, + profile: &Profile, +) -> Result> { + let candidates = store + .managed_implementations(repository.into(), head.into()) + .map_err(|e| helpers::store_as_github_error(&e))?; + if candidates.len() > 100 { + return Err(GitHubError::Ambiguous( + "managed implementation head exceeds recovery bound".into(), + ) + .into()); + } + let mut matching = None; + for root in candidates { + if root.issue_node_id != issue.node_id || root.base_ref != base { + continue; + } + let Some(number) = root.pull_request_number else { + if matches!(root.write.lifecycle.as_str(), "pending" | "sending" | "uncertain") { + return Err(GitHubError::ConvergencePending( + "original managed request has not fixed its published PR yet".into(), + ) + .into()); + } + continue; + }; + let pr = github.pull_request(number).await?; + if !pr.state.eq_ignore_ascii_case("open") { + continue; + } + if root.pr_profile_id != profile.id { + bail!( + "managed implementation uses a different PR Profile; refusing implicit reassignment" + ); + } + let AcceptedRequest::Ensure { profile: original, .. } = + serde_json::from_str(&root.write.payload)? + else { + bail!("managed request has no frozen PR Profile"); + }; + if serde_json::to_string(&original)? != serde_json::to_string(profile)? { + bail!("managed PR Profile changed; explicit recovery configuration is required"); + } + if root.pull_request_node_id.as_deref() != Some(pr.node_id.as_str()) + || pr.head.reference != head + || pr.base.reference != base + { + bail!("managed implementation PR no longer matches its frozen identity"); + } + if !github + .pull_request_closing_issues(number) + .await? + .iter() + .any(|edge| edge.repository == repository && edge.number == issue.number) + { + bail!("managed implementation is no longer directly associated with this Issue"); + } + if matching.replace(root.root_intent_id).is_some() { + return Err(GitHubError::Ambiguous( + "multiple open managed implementations share this head".into(), + ) + .into()); + } + } + Ok(matching) } diff --git a/src/writer/tests.rs b/src/writer/tests.rs new file mode 100644 index 00000000..d853a0b2 --- /dev/null +++ b/src/writer/tests.rs @@ -0,0 +1,548 @@ +//! Production acceptance → actor/outbox → HTTP convergence, with no store/executor shims. +use super::*; +use crate::store::IngressEvent; +use axum::{ + Json, Router, + routing::{get, post}, +}; +use rusqlite::Connection; +use serde_json::{Value, json}; +use std::{ + collections::{BTreeMap, HashMap}, + path::PathBuf, + sync::{Arc, Mutex}, +}; + +pub(crate) struct Fixture { + pub(crate) config: Config, + pub(crate) store: StoreActor, + root: TemporaryRoot, +} +impl Fixture { + pub(crate) fn new(source: bool) -> Self { + let root = std::env::temp_dir().join(format!("braid-writer-{}", uuid::Uuid::now_v7())); + std::fs::create_dir_all(&root).unwrap(); + let path = root.join("config.toml"); + std::fs::write( + &path, + include_str!("../../config.example.toml") + .replace("/absolute/path/to/instance", root.to_str().unwrap()), + ) + .unwrap(); + let config = Config::load(&path).unwrap(); + let store = StoreActor::start( + config.runtime.database().to_owned(), + config.runtime.backups().to_owned(), + ) + .unwrap(); + store.apply().unwrap(); + let fixture = Self { root: TemporaryRoot(root), config, store }; + if source { + fixture.bind_source(); + } + fixture + } + fn reopen(self) -> Self { + let Self { root, config, store } = self; + drop(store); + let store = StoreActor::start( + config.runtime.database().to_owned(), + config.runtime.backups().to_owned(), + ) + .unwrap(); + Self { config, store, root } + } + pub(crate) fn db(&self) -> Connection { + Connection::open(self.config.runtime.database()).unwrap() + } + fn bind_source(&self) { + self.db().execute_batch("INSERT INTO repositories VALUES ('repo','owner/repository',1,'now'); INSERT INTO work_items(node_id,repository_node_id,kind,number,state,context_revision,observed_at) VALUES ('item','repo','issue',1,'open','context','now'); INSERT INTO profiles VALUES ('issue-codex',1,'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa','codex','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','issue-codex',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','codex','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 revision = self + .config + .profile_materials(self.config.profile("issue-codex").unwrap()) + .unwrap() + .revision; + let revision = i64::try_from(revision).unwrap(); + self.db().execute("INSERT INTO profiles SELECT profile_id,?1,effective_digest,provider_kind,tags FROM profiles WHERE revision=1", [revision]).unwrap(); + self.db().execute("UPDATE agent_instances SET profile_revision=?1", [revision]).unwrap(); + self.db().execute("INSERT INTO worktrees(worktree_id,agent_id,path,repository_node_id,lifecycle,observed_at) VALUES ('tree','agent',?1,'repo','active','now')", [std::env::current_dir().unwrap().to_str().unwrap()]).unwrap(); + } + fn invocation(&self) -> Invocation { + let turn = self.db().query_row("SELECT turn_id FROM turns ORDER BY CASE lifecycle WHEN 'running' THEN 0 WHEN 'starting' THEN 0 ELSE 1 END,rowid DESC LIMIT 1", [], |r| r.get::<_, String>(0)); + turn.map_or(Invocation::Operator, Invocation::Agent) + } + fn comment(&self) -> GhWriteReceipt { + create_comment( + &self.config, + &self.store, + CommentCreateRequest { + invocation: self.invocation(), + target: "owner/repository#1".parse().unwrap(), + profile_id: "issue-codex".into(), + body: "update".into(), + request_id: Some("stable".into()), + }, + ) + .unwrap() + } + async fn drain(&self, github: Arc) { + let owner = + self.store.acquire_runtime_lease("runtime".into(), "writer".into(), 3600).unwrap(); + let clients = HashMap::from([("owner/repository".into(), github)]); + crate::outbox::drain_one_write(&self.store, &clients, &self.config, &owner).await; + self.store.release_runtime_lease(owner).unwrap(); + } + fn due(&self) { + self.db() + .execute("UPDATE github_write_outbox SET next_attempt_at='2000-01-01T00:00:00Z'", []) + .unwrap(); + } + fn receipt(&self, id: &str) -> GhWriteReceipt { + self.store.gh_write_receipt(id.into()).unwrap().unwrap() + } +} +struct TemporaryRoot(PathBuf); +impl Drop for TemporaryRoot { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +#[derive(Default)] +enum TargetKind { + #[default] + Issue, + PullRequest, +} + +#[derive(Default, Clone, Copy, PartialEq, Eq)] +enum Authority { + #[default] + Intact, + SourceClosed, + TargetClosed, + AssociationRemoved, + AssociationUnavailable, + OtherIssue, +} + +#[derive(Default)] +struct Remote { + authority: Authority, + closing_issue: Option, + pr_body: Option, + pr_missing: bool, + target_kind: TargetKind, + head_created: bool, + comments: Vec, + comment_requests: Vec<&'static str>, + lose_comment_response: bool, + writes: usize, + limit: Option, + target_status: Option, + commit_requests: Vec, + ref_requests: Vec, + pr_requests: Vec, +} +async fn server( + remote: Arc>, + permission: bool, +) -> (Arc, tokio::task::JoinHandle<()>) { + let listing = remote.clone(); + let writing = remote.clone(); + let updating = remote.clone(); + let target = remote.clone(); + let continuation = remote.clone(); + let pr_read = remote.clone(); + let associations = remote.clone(); + let pr = json!({"id":88,"node_id":"pr","number":9,"html_url":"https://github.com/owner/repository/pull/9","draft":true,"state":"open","body":"Closes #1\n\nImplementation request: https://github.com/owner/repository/issues/comments/7","head":{"ref":"head","sha":"new"},"base":{"ref":"main","sha":"base"}}); + let router = Router::new() + .route("/repos/owner/repository/issues/1", get(move || { let remote=target.clone(); async move { + use axum::response::IntoResponse as _; + if remote.lock().unwrap().limit.is_some() { return (axum::http::StatusCode::TOO_MANY_REQUESTS, [("retry-after","120")], Json(json!({"message":"rate limit"}))).into_response(); } + if let Some(status) = remote.lock().unwrap().target_status { return (status, Json(json!({"message":"target unavailable"}))).into_response(); } + let mut item = json!({"id":1,"node_id":"item","number":1,"title":"Issue","state":"open","html_url":"https://github.com/owner/repository/issues/1"}); + if remote.lock().unwrap().authority==Authority::SourceClosed {item["state"]=json!("closed");} + if matches!(remote.lock().unwrap().target_kind, TargetKind::PullRequest) { item["pull_request"] = json!({"url":"pr"}); } + Json(item).into_response() + }})) + .route("/repos/owner/repository/issues/1/comments", get(move || { let remote=listing.clone(); async move { let mut state=remote.lock().unwrap(); state.comment_requests.push("GET"); Json(state.comments.clone()) } }).post(move |Json(body): Json| { let remote=writing.clone(); async move { + let mut remote=remote.lock().unwrap(); remote.comment_requests.push("POST"); remote.writes+=1; + let comment=json!({"id":99,"node_id":"comment","url":"https://api.github.com/repos/owner/repository/issues/comments/99","html_url":"https://github.com/owner/repository/issues/1#issuecomment-99","issue_url":"https://api.github.com/repos/owner/repository/issues/1","body":body["body"],"created_at":time::OffsetDateTime::now_utc().format(&time::format_description::well_known::Rfc3339).unwrap(),"updated_at":"now","user":{"login":"braid[bot]","id":1,"node_id":"app","type":"Bot","site_admin":false,"avatar_url":"https://example.invalid","url":"https://example.invalid","html_url":"https://example.invalid"}}); + remote.comments.push(comment); + if remote.lose_comment_response { return Err(axum::http::StatusCode::SERVICE_UNAVAILABLE); } + Ok(Json(json!({"id":99,"node_id":"comment"}))) + }})) + .route("/repos/owner/repository/issues/comments/99",axum::routing::patch(move |Json(body):Json|{let remote=updating.clone();async move{let mut remote=remote.lock().unwrap();remote.writes+=1;remote.comments.last_mut().unwrap()["body"]=body["body"].clone();Json(json!({"id":99,"node_id":"comment"}))}})) + .route("/repos/owner/repository/issues/comments/7", get(|| async { Json(json!({"id":7,"node_id":"request-comment","url":"https://api.github.com/repos/owner/repository/issues/comments/7","html_url":"https://github.com/owner/repository/issues/1#issuecomment-7","issue_url":"https://api.github.com/repos/owner/repository/issues/1","body":"implement","created_at":"now","updated_at":"now"})) })) + .route("/repos/owner/repository/issues/comments/8",get(move||{let remote=continuation.clone();async move{let number=if remote.lock().unwrap().authority==Authority::OtherIssue {2}else{1};Json(json!({"id":8,"node_id":"followup-comment","html_url":format!("https://github.com/owner/repository/issues/{number}#issuecomment-8"),"issue_url":format!("https://api.github.com/repos/owner/repository/issues/{number}"),"body":"continue current implementation","created_at":"now","updated_at":"now"}))}})) + .route("/repos/owner/repository/issues/2",get(||async{Json(json!({"id":2,"node_id":"other-issue","number":2,"title":"Other issue","state":"open","html_url":"https://github.com/owner/repository/issues/2"}))})) + .route("/repos/owner/repository", get(|| async { Json(json!({"default_branch":"main"})) })) + .route("/repos/owner/repository/pulls", get({ let pr=pr.clone(); let remote=remote.clone(); move || { let mut pr=pr.clone(); let remote=remote.clone(); async move { let state=remote.lock().unwrap(); if let Some(body)=&state.pr_body {pr["body"]=json!(body);} Json(if state.pr_missing {json!([])} else {json!([pr])}) } }}).post({ let pr=pr.clone(); let remote=remote.clone(); move |Json(body): Json| {let pr=pr.clone(); let remote=remote.clone(); async move { let mut state=remote.lock().unwrap(); state.pr_requests.push(body); state.pr_missing=false; state.writes+=1; Json(pr) }}})) + .route("/repos/owner/repository/git/ref/heads/main",get(|| async {Json(json!({"ref":"refs/heads/main","object":{"sha":"base"}}))})) + .route("/repos/owner/repository/git/ref/heads/head",get({let remote=remote.clone(); move || {let remote=remote.clone(); async move { + use axum::response::IntoResponse as _; + if remote.lock().unwrap().head_created {Json(json!({"ref":"refs/heads/head","object":{"sha":"new"}})).into_response()} else {(axum::http::StatusCode::NOT_FOUND,Json(json!({"message":"missing"}))).into_response()} + }}})) + .route("/repos/owner/repository/git/commits/base",get(|| async {Json(json!({"sha":"base","tree":{"sha":"tree"}}))})) + .route("/repos/owner/repository/git/commits",post({let remote=remote.clone(); move |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 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 { + axum::serve(listener, router).await.unwrap(); + }); + let client = octocrab::Octocrab::builder() + .base_uri(format!("http://{address}")) + .unwrap() + .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(), + 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 { + BTreeMap::from([ + ("issues".into(), "write".into()), + ("contents".into(), "write".into()), + ("pull_requests".into(), "write".into()), + ]) + } else { + BTreeMap::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, + }, + ) +} +#[tokio::test] +async fn outbox_delivery_recovery_and_rate_deadline_use_production_executor() { + let fixture = Fixture::new(false); + let receipt = fixture.comment(); + let remote = Arc::new(Mutex::new(Remote { limit: Some(120), ..Remote::default() })); + let (github, task) = server(remote.clone(), true).await; + fixture.drain(github.clone()).await; + assert_eq!(fixture.receipt(&receipt.request_id).lifecycle, "pending"); + let next: String = fixture + .db() + .query_row("SELECT next_attempt_at FROM github_write_outbox", [], |row| row.get(0)) + .unwrap(); + let deadline = + time::OffsetDateTime::parse(&next, &time::format_description::well_known::Rfc3339).unwrap(); + assert!(deadline > time::OffsetDateTime::now_utc() + time::Duration::seconds(110)); + assert_eq!(remote.lock().unwrap().writes, 0); + task.abort(); + 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).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); + task.abort(); + // A read-only installation can recognize a POST whose response was lost. + let fixture = fixture.reopen(); + fixture.store.recover_writes().unwrap(); + fixture.due(); + let (github, task) = server(remote.clone(), false).await; + fixture.drain(github.clone()).await; + let recovered = fixture.receipt(&receipt.request_id); + assert_eq!(recovered.lifecycle, "applied", "{recovered:?}"); + assert_eq!(recovered.remote_database_id.as_deref(), Some("99")); + let fixture = fixture.reopen(); + fixture.store.recover_writes().unwrap(); + fixture.drain(github).await; + assert_eq!(fixture.receipt(&receipt.request_id).lifecycle, "applied"); + assert_eq!(remote.lock().unwrap().writes, 1); + task.abort(); +} + +#[tokio::test] +async fn uncertain_comment_can_be_created_after_a_canonical_read_finds_no_match() { + let fixture = Fixture::new(false); + let receipt = fixture.comment(); + let owner = fixture + .store + .acquire_runtime_lease("runtime".into(), "before-restart".into(), 3600) + .unwrap(); + let attempt = fixture.store.claim_github_write(owner.clone()).unwrap().unwrap(); + assert_eq!(attempt.intent_id, receipt.intent_id); + // The process exits after claiming the write, before sending a request. + fixture.store.release_runtime_lease(owner).unwrap(); + let fixture = fixture.reopen(); + assert_eq!(fixture.store.recover_writes().unwrap(), 1); + + let remote = Arc::new(Mutex::new(Remote::default())); + let (github, http) = server(remote.clone(), true).await; + fixture.drain(github).await; + let result = fixture.receipt(&receipt.request_id); + assert_eq!(result.lifecycle, "applied"); + assert_eq!(result.remote_database_id.as_deref(), Some("99")); + let remote = remote.lock().unwrap(); + assert_eq!(remote.comment_requests.first(), Some(&"GET")); + assert_eq!(remote.writes, 1); + http.abort(); +} + +#[tokio::test] +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" => { + 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 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(), true).await; + fixture.drain(github).await; + 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(); + } +} + +#[tokio::test] +async fn initial_ensure_bootstrap_pr_association_and_restart_do_not_duplicate_mutations() { + 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(); + let source = receipt.source.as_ref().unwrap(); + assert_eq!(source.profile_id, "issue-codex"); + assert_eq!(source.role, "issue_agent"); + let remote = Arc::new(Mutex::new(Remote { + pr_missing: true, + authority: Authority::AssociationUnavailable, + ..Remote::default() + })); + let (github, task) = server(remote.clone(), true).await; + fixture.drain(github).await; + let result = fixture.receipt(&receipt.request_id); + assert_eq!(result.lifecycle, "uncertain", "{result:?}"); + assert!(result.last_error.as_deref().unwrap().contains("503"), "{result:?}"); + let plan = + fixture.store.implementation_request_receipt(receipt.intent_id.clone()).unwrap().unwrap(); + assert_eq!(plan.stage, "pull_request_ready"); + assert_eq!(plan.pull_request_number, Some(9)); + assert!(!plan.activation_delivered); + task.abort(); + { + let remote = remote.lock().unwrap(); + assert_eq!(remote.writes, 3); + assert_eq!(remote.commit_requests.len(), 1); + assert_eq!(remote.commit_requests[0]["tree"], "tree"); + assert_eq!(remote.commit_requests[0]["parents"], json!(["base"])); + assert_eq!(remote.ref_requests, vec![json!({"ref":"refs/heads/head","sha":"new"})]); + assert_eq!(remote.pr_requests.len(), 1); + assert_eq!(remote.pr_requests[0]["head"], "head"); + assert_eq!(remote.pr_requests[0]["base"], "main"); + assert_eq!(remote.pr_requests[0]["draft"], true); + let body = remote.pr_requests[0]["body"].as_str().unwrap(); + assert!(body.contains("Closes #1"), "missing Issue association: {body}"); + assert!( + body.contains("https://github.com/owner/repository/issues/comments/7"), + "missing durable request: {body}" + ); + } + remote.lock().unwrap().authority = Authority::Intact; + let fixture = fixture.reopen(); + fixture.store.recover_writes().unwrap(); + fixture.due(); + let (github, task) = server(remote.clone(), true).await; + fixture.drain(github).await; + let result = fixture.receipt(&receipt.request_id); + assert_eq!(result.lifecycle, "applied", "{result:?}"); + let delivered = + fixture.store.implementation_request_receipt(receipt.intent_id).unwrap().unwrap(); + assert!(delivered.activation_delivered); + assert_eq!( + fixture + .db() + .query_row( + "SELECT count(*) FROM events WHERE kind='assign' AND detail='pr_ensure'", + [], + |row| row.get::<_, i64>(0) + ) + .unwrap(), + 1 + ); + assert_eq!(remote.lock().unwrap().writes, 3); + task.abort(); +} + +#[tokio::test] +async fn source_role_can_publish_related_cross_surface_without_target_profile_tags() { + for (target_pr, 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:?}" + ); + } else { + let role = if target_pr { "Issue Agent" } else { "PR Implementation Agent" }; + assert!(state.comments[0]["body"].as_str().unwrap().contains(role)); + } + task.abort(); + } +} + +mod publication_contract; +mod turn_start; + +mod body_edit; + +mod continuous_collaboration; +mod handoff; +mod implementation_recovery; +mod observation_recovery; +mod reaction_feedback; +mod semantic_contract; +mod status_convergence; + +pub(crate) async fn issue_context_server( + body: &str, +) -> (Arc, tokio::task::JoinHandle<()>) { + let mut remote = body_edit::BodyRemote::new(false); + remote.snapshot.body = Some(body.into()); + body_edit::body_server(Arc::new(Mutex::new(remote))).await +} diff --git a/src/writer/tests/body_edit.rs b/src/writer/tests/body_edit.rs new file mode 100644 index 00000000..c474cdb0 --- /dev/null +++ b/src/writer/tests/body_edit.rs @@ -0,0 +1,632 @@ +use super::*; + +#[allow(clippy::struct_excessive_bools)] +pub(super) struct BodyRemote { + pub(super) snapshot: crate::github::BodySnapshot, + pub(super) issue_comments: Vec, + pub(super) issue_edit_evidence: serde_json::Map, + writes: usize, + pub(super) associated: bool, + associated_999: bool, + issue_999: crate::github::BodySnapshot, + writes_999: usize, + pub(super) limited: bool, + pub(super) pr_closed: bool, + mutation_limited: bool, + pub(super) lose_response: bool, +} +impl BodyRemote { + pub(super) fn new(pr: bool) -> Self { + Self { + snapshot: serde_json::from_value(json!({"id":1,"node_id":"item","number":1,"title":"Canonical","body":"Closes #7\n\nImplementation request: https://github.com/owner/repository/issues/comments/7","state":"open","updated_at":"version-1","pull_request":if pr {Some(json!({"url":"pr"}))} else {None}})).unwrap(), + issue_comments: Vec::new(), + issue_edit_evidence: serde_json::Map::new(), + writes: 0, pr_closed: false, associated: true, associated_999: false, + issue_999: serde_json::from_value(json!({"id":999,"node_id":"issue-999","number":999,"title":"Controlled Issue","body":"Original design","state":"open","updated_at":"version-1"})).unwrap(), writes_999: 0, limited: false, mutation_limited: false, lose_response: false, + } + } +} +fn combined_first_pages( + request: &Value, + state: &BodyRemote, + issue: &Value, + pr: &Value, +) -> Option { + let query = request["query"].as_str()?; + let (root, fields, edge, reference) = if query.contains("query PrFirstPages") { + ( + "pullRequest", + &["assignees", "labels", "comments", "reviews", "threads"][..], + "associated_issue_refs", + issue, + ) + } else if query.contains("query IssueFirstPages") { + ( + "issue", + &[ + "assignees", + "labels", + "linked_branches", + "sub_issues", + "blocked_by", + "blocking", + "comments", + "duplicate_events", + ][..], + "associated_prs", + pr, + ) + } else { + return None; + }; + let empty = json!({"nodes":[], "pageInfo":{"hasNextPage":false,"endCursor":null}}); + let mut object = serde_json::Map::new(); + for field in fields { + object.insert((*field).into(), empty.clone()); + } + if root == "issue" { + object.get_mut("comments").unwrap()["nodes"] = json!(state.issue_comments); + } + if request["variables"]["projects"].as_bool() == Some(true) { + object.insert("project_items".into(), empty); + } + object.insert(edge.into(), json!({"nodes":if state.associated {vec![reference]} else {Vec::new()},"pageInfo":{"hasNextPage":false,"endCursor":null}})); + Some(json!({"data":{"repository":{root:object}}})) +} + +// Keep edit and full-Context routes in one fixture with shared scenario state. +#[allow(clippy::too_many_lines)] +pub(super) async fn body_server( + remote: Arc>, +) -> (Arc, tokio::task::JoinHandle<()>) { + let read = remote.clone(); + let patch = remote.clone(); + let association = remote.clone(); + let issue_read = remote.clone(); + let issue_patch = remote.clone(); + let pr_read = remote.clone(); + let comment_post = remote.clone(); + let router = Router::new() + .route("/repos/owner/repository/issues/1", get(move || { let remote = read.clone(); async move { + use axum::response::IntoResponse as _; + let remote=remote.lock().unwrap(); + if remote.limited { return (axum::http::StatusCode::TOO_MANY_REQUESTS, [("retry-after", "120")], Json(json!({"message":"limited"}))).into_response(); } + let mut item=serde_json::to_value(&remote.snapshot).unwrap(); item["number"]=json!(1); item["html_url"]=json!("https://github.com/owner/repository/issues/1"); Json(item).into_response() + }}).patch(move |Json(request): Json| {let remote=patch.clone(); async move { + use axum::response::IntoResponse as _; + let mut remote=remote.lock().unwrap(); + if remote.mutation_limited { return (axum::http::StatusCode::TOO_MANY_REQUESTS, [("retry-after", "120")], Json(json!({"message":"limited"}))).into_response(); } + remote.writes+=1; + remote.snapshot.title=request["title"].as_str().unwrap().into(); + remote.snapshot.body=Some(request["body"].as_str().unwrap().into()); + remote.snapshot.updated_at="version-2".into(); + if remote.lose_response { return (axum::http::StatusCode::SERVICE_UNAVAILABLE, Json(json!({"message":"lost acknowledgement"}))).into_response(); } + Json(&remote.snapshot).into_response() + }})) + .route("/repos/owner/repository/issues/1/comments", post(move |Json(request): Json| { + let remote = comment_post.clone(); + async move { + let now = time::OffsetDateTime::now_utc().format(&time::format_description::well_known::Rfc3339).unwrap(); + let mut remote = remote.lock().unwrap(); + remote.issue_comments.push(json!({ + "id":"status", "fullDatabaseId":"99", "author":{"id":"app", "login":"braid[bot]"}, + "createdAt":now, "updatedAt":now, "isMinimized":false, "body":request["body"], + })); + Json(json!({"id":99, "node_id":"status"})) + } + })) + .route("/repos/owner/repository/issues/999", get(move || { let remote=issue_read.clone(); async move { + let mut item=serde_json::to_value(&remote.lock().unwrap().issue_999).unwrap(); + item["number"]=json!(999); + item["html_url"]=json!("https://github.com/owner/repository/issues/999"); + Json(item) + }}).patch(move |Json(request): Json| {let remote=issue_patch.clone(); async move { + let mut remote=remote.lock().unwrap(); remote.writes_999+=1; + remote.issue_999.title=request["title"].as_str().unwrap().into(); + remote.issue_999.body=Some(request["body"].as_str().unwrap().into()); + remote.issue_999.updated_at="version-2".into(); + Json(remote.issue_999.clone()) + }})) + .route("/repos/owner/repository/issues/9", get(move || { let remote=pr_read.clone(); async move {Json(json!({"id":9,"node_id":"pr","number":9,"title":"Source PR","html_url":"pr","state":if remote.lock().unwrap().pr_closed {"closed"} else {"open"},"pull_request":{}}))}})) + .route("/graphql", post(move |Json(request): Json| { let remote=association.clone(); async move { + let state=remote.lock().unwrap(); + if state.limited { return Err(axum::http::StatusCode::SERVICE_UNAVAILABLE); } + let query=request["query"].as_str().unwrap(); + let repository=json!({"id":"repo","nameWithOwner":"owner/repository"}); + let issue_ref=json!({"id":"item","number":1,"title":"Canonical","state":state.snapshot.state.to_uppercase(),"repository":repository}); + let pr_ref=json!({"id":"pr","number":9,"title":"Existing PR","state":if state.pr_closed {"CLOSED"} else {"OPEN"},"repository":repository}); + if let Some(first_pages) = combined_first_pages(&request, &state, &issue_ref, &pr_ref) { + return Ok(Json(first_pages)); + } + let mut nodes=Vec::new(); + if query.contains("items:") { + if query.contains("closingIssuesReferences") && state.associated {nodes.push(issue_ref);} + if query.contains("closedByPullRequestsReferences") && state.associated {nodes.push(pr_ref);} + let connection=json!({"items":{"nodes":nodes,"pageInfo":{"hasNextPage":false,"endCursor":null}}}); + let root=if query.contains("pullRequest(number:") {"pullRequest"} else {"issue"}; + return Ok(Json(json!({"data":{"repository":{root:connection}}}))); + } + if query.contains("fullDatabaseId") { + let mut core=if query.contains("pullRequest(number:") { + json!({"id":"pr","fullDatabaseId":"9","number":9,"title":"Existing PR","body":"Closes #1","state":if state.pr_closed {"CLOSED"} else {"OPEN"},"isDraft":false,"merged":false,"updatedAt":"pr-v1","baseRefName":"main","headRefName":"work","headRepository":repository}) + } else { + json!({"id":"item","fullDatabaseId":"1","number":1,"title":state.snapshot.title,"body":state.snapshot.body,"state":state.snapshot.state.to_uppercase(),"updatedAt":state.snapshot.updated_at}) + }; + let root=if query.contains("pullRequest(number:") {"pullRequest"} else {"issue"}; + if root == "issue" { core.as_object_mut().unwrap().extend(state.issue_edit_evidence.clone()); } + return Ok(Json(json!({"data":{"repository":{"id":"repo","nameWithOwner":"owner/repository",root:core}}}))); + } + if state.associated {nodes.push(json!({"number":1,"repository":{"nameWithOwner":"owner/repository"}}));} + if state.associated_999 {nodes.push(json!({"number":999,"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 { + axum::serve(listener, router).await.unwrap(); + }); + let client = octocrab::Octocrab::builder() + .base_uri(format!("http://{address}")) + .unwrap() + .add_retry_config(octocrab::service::middleware::retry::RetryConfig::None) + .build() + .unwrap(); + (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(); + fixture + .db() + .execute("UPDATE work_items SET kind='pr',number=?1", [if own_pr { 1 } else { 9 }]) + .unwrap(); +} +pub(super) async fn accept(fixture: &Fixture, github: &GitHubClient) -> GhWriteReceipt { + let target: WorkItemLocator = "owner/repository#1".parse().unwrap(); + let snapshot = edit::read_snapshot(github, &target).await.unwrap(); + edit( + &fixture.config, + &fixture.store, + EditRequest { + invocation: fixture.invocation(), + target, + profile_id: "issue-codex".into(), + snapshot, + title: Some("Current delivery".into()), + body: Some("Scope, verification, risks".into()), + request_id: "edit-1".into(), + }, + ) + .unwrap() +} +#[tokio::test] +async fn own_pr_edit_preserves_marker_closing_and_recovers_unconfirmed_success_without_overwrite() { + 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().lose_response = true; + fixture.drain(github).await; + assert_eq!(fixture.receipt(&receipt.request_id).lifecycle, "uncertain"); + task.abort(); + let (github, task) = body_server(remote.clone()).await; + fixture.due(); + fixture.store.recover_writes().unwrap(); + fixture.drain(github).await; + assert_eq!(fixture.receipt(&receipt.request_id).lifecycle, "applied"); + let state = remote.lock().unwrap(); + assert_eq!(state.writes, 1); + let body = state.snapshot.body.as_ref().unwrap(); + assert!(body.contains("Closes #7")); + assert!(body.contains("Implementation request:")); + assert!(body.contains("PR Implementation Agent")); + assert_eq!(body.matches("> **Braid Agent").count(), 1); + task.abort(); +} +#[tokio::test] +async fn changed_snapshot_or_source_rejects_an_admitted_edit_before_mutation() { + for (fence, state, reason) in [ + ("closed", "conflict", "canonical title/body changed since snapshot"), + ("context", "rejected", "publication source was invalidated or superseded"), + ("generation", "rejected", "publication source was invalidated or superseded"), + ("session", "rejected", "publication source was invalidated or superseded"), + ("human", "conflict", "canonical title/body changed since snapshot"), + ] { + let fixture = Fixture::new(true); + pr_source(&fixture, false); + let remote = Arc::new(Mutex::new(BodyRemote::new(false))); + let (github, task) = body_server(remote.clone()).await; + let receipt = accept(&fixture, &github).await; + match fence { + "closed" => remote.lock().unwrap().snapshot.state = "closed".into(), + "context" => { + fixture + .db() + .execute("UPDATE provider_sessions SET context_revision='replaced'", []) + .unwrap(); + } + "generation" => { + fixture.db().execute("UPDATE assignments SET generation=2", []).unwrap(); + } + "session" => { + 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()), + _ => unreachable!(), + } + fixture.drain(github).await; + let result = fixture.receipt(&receipt.request_id); + assert_eq!(result.lifecycle, state, "{fence}: {:?}", result.last_error); + assert!(result.last_error.as_deref().unwrap().contains(reason), "{fence}: {result:?}"); + assert_eq!(remote.lock().unwrap().writes, 0, "{fence}"); + task.abort(); + } +} +#[tokio::test] +async fn 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] +async fn own_issue_body_edit_and_input_boundaries_use_the_same_acceptance_path() { + let fixture = Fixture::new(true); + let remote = Arc::new(Mutex::new(BodyRemote::new(false))); + 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, 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"), + ] { + 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}"); + } + 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(); +} + +#[tokio::test] +async fn unconfirmed_success_followed_by_human_edit_is_conflict_not_success_or_overwrite() { + 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().lose_response = true; + fixture.drain(github).await; + assert_eq!(fixture.receipt(&receipt.request_id).lifecycle, "uncertain"); + task.abort(); + remote.lock().unwrap().snapshot.body = Some("Human intervened".into()); + let (github, task) = body_server(remote.clone()).await; + fixture.due(); + fixture.drain(github).await; + assert_eq!(fixture.receipt(&receipt.request_id).lifecycle, "conflict"); + assert_eq!(remote.lock().unwrap().writes, 1); + assert_eq!(remote.lock().unwrap().snapshot.body.as_deref(), Some("Human intervened")); + task.abort(); +} + +#[tokio::test] +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 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, + EditRequest { + invocation: fixture.invocation(), + target: target.clone(), + profile_id: "issue-codex".into(), + snapshot: edit::read_snapshot(&github, &target).await.unwrap(), + title: None, + body: Some(body.into()), + request_id: "ordinary".into(), + }, + ) + .unwrap(); + fixture.drain(github).await; + 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(); +} + +#[tokio::test] +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: issue.clone(), + profile_id: "issue-codex".into(), + snapshot: edit::read_snapshot(&github, &issue).await.unwrap(), + title: None, + body: Some("Corrected design".into()), + request_id: format!("issue-{confirmed}"), + }, + ) + .unwrap(); + fixture.drain(github.clone()).await; + let result = fixture.receipt(&receipt.request_id); + assert_eq!( + result.lifecycle, + if confirmed { "applied" } else { "rejected" }, + "{:?}", + result.last_error + ); + let state = remote.lock().unwrap(); + 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 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--------", + "", + ] { + remote.lock().unwrap().snapshot.body = Some(protected.into()); + 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 new file mode 100644 index 00000000..4fcd2908 --- /dev/null +++ b/src/writer/tests/continuous_collaboration.rs @@ -0,0 +1,621 @@ +use super::*; +use crate::{ + context::CanonicalObservation, + producer::reconcile::{self, ReconcileScope}, + store::{CanonicalCommentSet, CanonicalObjectState, EventKind, ObservationCommit}, +}; + +pub(crate) fn revision(delivery: &str, body: &str) -> IngressEvent { + IngressEvent { + identity: crate::store::ChangeIdentity::ObjectVersion, + delivery_guid: delivery.into(), + event_name: "issues".into(), + action: Some("edited".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("item".into()), + object_version: Some(delivery.into()), + object_digest: Some(helpers::digest(body)), + visible_body: Some(body.into()), + actor_node_id: Some("human".into()), + actor_login: Some("human".into()), + kind: EventKind::Invalidate, + detail: Some("edited"), + cross_surface_invalidation: true, + requires_attention: true, + origin: "external", + reference: format!("Human revised Issue #1: {delivery}"), + mention_candidate: false, + reaction_target: None, + known: true, + raw_payload: Vec::new(), + } +} + +fn state(version: &str, digest: char) -> CanonicalObjectState { + CanonicalObjectState { + root_fields: None, + metadata_digest: None, + node_id: "item".into(), + database_id: Some("1".into()), + object_kind: "issue".into(), + version: version.into(), + digest: digest.to_string().repeat(64), + lifecycle: "open".into(), + author_node_id: Some("human".into()), + author_login: Some("human".into()), + } +} + +#[tokio::test] +async fn another_context_read_cannot_acknowledge_a_revision_before_delivery() { + let old_version = "2026-01-01T00:00:01Z"; + let revised_version = "2026-01-01T00:00:02Z"; + let f = Fixture::new(true); + f.store + .commit_observation(ObservationCommit { + basis: f.store.begin_observation("item".into()).unwrap(), + current: vec![state(old_version, 'a')], + events: vec![], + policy: SchedulerPolicy { quiet_seconds: 30, event_threshold: 8 }, + }) + .unwrap(); + f.store + .reconcile_comments(CanonicalCommentSet { + repository_node_id: "repo".into(), + repository: "owner/repository".into(), + work_item_node_id: "item".into(), + work_item_kind: "issue", + work_item_number: 1, + work_item_state: "open".into(), + work_item_version: "2026-01-01T00:00:03Z".into(), + work_item_digest: "b".repeat(64), + object_kind: "issue_comment", + comments: vec![], + }) + .unwrap(); + assert_eq!(f.store.begin_observation("item".into()).unwrap().objects[0].version, old_version); + let observation = CanonicalObservation { + unedited_creation: false, + created_at: None, + work_item_node_id: "item".into(), + work_item_kind: "issue", + work_item_number: 1, + work_item_state: "open".into(), + repository_node_id: "repo".into(), + repository: "owner/repository".into(), + object_node_id: "item".into(), + database_id: "1".into(), + object_kind: "issue", + version: revised_version.into(), + digest: "b".repeat(64), + lifecycle: "active", + author_node_id: Some("human".into()), + author_login: Some("human".into()), + body: Some("Current revised contract".into()), + visible_body: Some("Current revised contract".into()), + root_edits: crate::context::RootEditEvidence::default(), + title: Some("Design".into()), + metadata_digest: None, + }; + let scope = ReconcileScope { + work_item_node_id: "item".into(), + work_item_kind: "issue", + work_item_number: 1, + work_item_state: "open".into(), + previous_work_item_state: "open".into(), + repository_node_id: "repo".into(), + repository: "owner/repository".into(), + }; + let (github, task) = server(Arc::new(Mutex::new(Remote::default())), true).await; + for expected_changes in [1, 0] { + let basis = f.store.begin_observation("item".into()).unwrap(); + assert_eq!( + reconcile::reconcile_observations( + &f.store, + &github, + &f.config, + &scope, + basis, + std::slice::from_ref(&observation) + ) + .unwrap(), + expected_changes + ); + } + assert_eq!(f.store.runtime_status().unwrap().batches.len(), 1); + assert_eq!( + f.db() + .query_row( + "SELECT count(*) FROM events WHERE kind='invalidate' AND requires_attention=1", + [], + |r| r.get::<_, i64>(0) + ) + .unwrap(), + 1 + ); + task.abort(); +} + +#[test] +fn failed_observation_commits_neither_events_nor_frontier() { + let f = Fixture::new(true); + let result = f.store.commit_observation(ObservationCommit { + basis: f.store.begin_observation("item".into()).unwrap(), + current: vec![], + events: vec![revision("v2", "new")], + policy: SchedulerPolicy { quiet_seconds: 30, event_threshold: 8 }, + }); + assert!( + matches!(result, Err(crate::store::StoreError::InvalidData(ref reason)) if reason == "complete observation has no root"), + "{result:?}" + ); + assert_eq!( + f.db().query_row("SELECT count(*) FROM events", [], |r| r.get::<_, i64>(0)).unwrap(), + 0 + ); + assert!(f.store.begin_observation("item".into()).unwrap().objects.is_empty()); + assert!(f.store.runtime_status().unwrap().batches.is_empty()); +} + +#[test] +fn independent_pr_ensures_deliver_two_activations_and_retry_one_identity() { + let f = Fixture::new(false); + let policy = SchedulerPolicy { quiet_seconds: 30, event_threshold: 8 }; + let profile = f.config.profile("pr-codex").unwrap(); + let owner = + f.store.acquire_runtime_lease("runtime".into(), "activation-test".into(), 3600).unwrap(); + for number in [9, 10] { + 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, + intent_id: receipt.intent_id, + comment_database_id: number, + comment_node_id: format!("comment-{number}"), + issue_node_id: "item".into(), + issue_number: 1, + issue_title: "Design".into(), + base_ref: "main".into(), + head_ref: format!("head-{number}"), + pr_profile_id: profile.id.clone(), + }) + .unwrap(); + f.store + .record_implementation_progress( + plan.write.intent_id.clone(), + ImplementationProgress { + stage: "activation_pending", + bootstrap_commit_sha: None, + pull_request_database_id: Some(number), + pull_request_node_id: Some(format!("pr-{number}")), + pull_request_number: Some(number), + }, + ) + .unwrap(); + for _ in 0..2 { + f.store + .accept_pr_activation(crate::store::PrActivation { + intent_id: plan.write.intent_id.clone(), + repository_node: "repo".into(), + pr_node: format!("pr-{number}"), + pr_number: number, + policy, + owner: owner.clone(), + issue_basis: f.store.begin_observation("item".into()).unwrap(), + target_basis: f.store.begin_observation(format!("pr-{number}")).unwrap(), + }) + .unwrap(); + } + assert!( + f.store + .implementation_request_receipt(plan.write.intent_id) + .unwrap() + .unwrap() + .activation_delivered + ); + } + let candidates = + f.store.assignment_candidates("owner/repository".into(), "pr".into(), 10).unwrap(); + assert_eq!(candidates.len(), 2); + assert_eq!( + f.db() + .query_row("SELECT count(*) FROM events WHERE detail='pr_ensure'", [], |r| r + .get::<_, i64>(0)) + .unwrap(), + 2 + ); +} + +#[test] +fn interrupted_revision_coalesces_attention_into_one_continuation() { + let f = Fixture::new(true); + f.db().execute_batch("UPDATE turns SET lifecycle='running',provider_turn_id='old-native' WHERE turn_id='turn'; UPDATE provider_sessions SET lifecycle='running' WHERE session_id='session'").unwrap(); + let policy = SchedulerPolicy { quiet_seconds: 30, event_threshold: 8 }; + f.store.ingest_event(revision("v2", "Current design"), policy).unwrap(); + let reset = f + .store + .begin_context_reset(Some("turn".into()), "issue".into(), "issue-codex".into()) + .unwrap() + .unwrap(); + assert!(reset.continuation); + f.store + .mark_context_reset_turn_terminal( + reset.reset_id.clone(), + "turn".into(), + "interrupted".into(), + ) + .unwrap(); + f.store + .complete_context_reset( + reset.reset_id, + "fresh-provider".into(), + "new-context".into(), + "instructions".into(), + ) + .unwrap(); + f.store.ingest_event(revision("v2", "Current design"), policy).unwrap(); + assert_eq!(f.store.runtime_status().unwrap().batches.len(), 1); + let claim = f + .store + .claim_runnable_turn("issue".into(), "issue-codex".into(), vec!["fresh-provider".into()]) + .unwrap() + .unwrap(); + assert_eq!(claim.references.len(), 1); + assert_eq!(claim.trigger_kind, "wake_batch"); + assert!( + f.store + .claim_runnable_turn( + "issue".into(), + "issue-codex".into(), + vec!["fresh-provider".into()] + ) + .unwrap() + .is_none() + ); +} + +#[test] +fn an_additive_projection_does_not_replace_the_session_publication_fence() { + let f = Fixture::new(true); + f.db() + .execute("UPDATE work_items SET context_revision='latest-projected-comments'", []) + .unwrap(); + let mut input = revision("new-comment", "comment"); + input.kind = EventKind::Wake; + input.cross_surface_invalidation = false; + f.store.ingest_event(input, SchedulerPolicy { quiet_seconds: 0, event_threshold: 1 }).unwrap(); + let claim = f + .store + .claim_runnable_turn("issue".into(), "issue-codex".into(), vec!["provider".into()]) + .unwrap() + .unwrap(); + f.store.mark_turn_started(claim.turn_id.clone(), "native-next".into()).unwrap(); + let source = + resolve_source(&f.config, None, &Invocation::Agent(claim.turn_id)).unwrap().unwrap(); + assert_eq!(source.context_revision, "context"); +} + +async fn observe_issue( + f: &Fixture, + github: &GitHubClient, + change_metadata: bool, +) -> CanonicalObservation { + let basis = f.store.begin_observation("item".into()).unwrap(); + let locator = "owner/repository#1".parse().unwrap(); + let issue = crate::context::materialize_issue(github, &locator, 100).await.unwrap(); + let context = crate::context::CanonicalContext::Issue(issue); + let mut observed = crate::context::canonical_observations(&context).remove(0); + if change_metadata { + observed.metadata_digest = Some("d".repeat(64)); + } + let scope = ReconcileScope { + work_item_node_id: "item".into(), + work_item_kind: "issue", + work_item_number: 1, + work_item_state: "open".into(), + previous_work_item_state: "open".into(), + repository_node_id: "repo".into(), + repository: "owner/repository".into(), + }; + reconcile::reconcile_observations( + &f.store, + github, + &f.config, + &scope, + basis, + std::slice::from_ref(&observed), + ) + .unwrap(); + observed +} + +#[tokio::test] +async fn root_edits_use_field_provenance_when_publication_evidence_is_unavailable() { + const BEFORE: &str = "2026-01-01T00:00:01Z"; + const AFTER: &str = "2026-01-01T00:00:02Z"; + for (mode, expected) in [ + ("app-body", "origin_echo"), + ("app-title-body", "origin_echo"), + ("unknown-editor", "invalidate"), + ("mixed-same-second", "invalidate"), + ("missing-rename", "invalidate"), + ("wrong-rename-preimage", "invalidate"), + ("metadata", "invalidate"), + ] { + let f = Fixture::new(true); + let mut remote = body_edit::BodyRemote::new(false); + remote.snapshot.updated_at = BEFORE.into(); + 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 + .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(); + state.snapshot.updated_at = AFTER.into(); + state.snapshot.body = Some("Revised design".into()); + let mut evidence = json!({ + "lastEditedAt": AFTER, + "editor": if mode == "unknown-editor" { Value::Null } else { json!({"id":"app"}) }, + "titleHistory": {"nodes":[]}, + }); + if matches!( + mode, + "app-title-body" | "mixed-same-second" | "missing-rename" | "wrong-rename-preimage" + ) { + state.snapshot.title = "Renamed design".into(); + if mode != "missing-rename" { + evidence["titleHistory"]["nodes"] = json!([{ + "id":"rename", "createdAt":AFTER, "currentTitle":state.snapshot.title, + "previousTitle":if mode == "wrong-rename-preimage" {"Unobserved title"} else {"Canonical"}, + "actor":{"id":if mode == "mixed-same-second" {"human"} else {"app"}}, + }]); + } + } + state.issue_edit_evidence = evidence.as_object().unwrap().clone(); + } + f.db() + .execute_batch( + "ALTER TABLE publication_versions RENAME TO unavailable_publication_versions; + ALTER TABLE write_intents RENAME TO unavailable_write_intents; + ALTER TABLE github_write_outbox RENAME TO unavailable_write_outbox;", + ) + .unwrap(); + let current = observe_issue(&f, &github, mode == "metadata").await; + let edited: (String, bool) = f.db().query_row( + "SELECT kind,requires_attention FROM events WHERE detail='edited' AND object_node_id='item'", + [], |r| Ok((r.get(0)?,r.get(1)?)), + ).unwrap(); + assert_eq!(edited, (expected.into(), expected == "invalidate"), "{mode}"); + 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(); + } +} + +#[tokio::test] +async fn exact_native_edit_evidence_proves_only_the_fields_its_sender_changed() { + for (mode, expected) in [ + ("app-with-body-preimage", "origin_echo"), + ("app-with-unproven-title", "invalidate"), + ("human-against-app-editor", "invalidate"), + ] { + let f = Fixture::new(true); + let mut remote = body_edit::BodyRemote::new(false); + remote.snapshot.updated_at = "2026-01-01T00:00:01Z".into(); + 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_body = previous.body.unwrap(); + let update_time = "2026-01-01T00:00:02Z"; + let new_body = "Updated design"; + let title = if mode == "app-with-unproven-title" { "Human title" } else { "Canonical" }; + let human = mode == "human-against-app-editor"; + { + let mut state = remote.lock().unwrap(); + state.snapshot.updated_at = update_time.into(); + state.snapshot.body = Some(new_body.into()); + state.snapshot.title = title.into(); + if human { + state.issue_edit_evidence = json!({ + "lastEditedAt": update_time, + "editor":{"id":"app"}, + }) + .as_object() + .unwrap() + .clone(); + } + } + let mut native = revision("native-edit", new_body); + native.object_version = Some(update_time.into()); + native.object_digest = + Some(crate::store::publication_digest("item", update_time, Some(title), new_body)); + native.actor_node_id = Some(if human { "human" } else { "app" }.into()); + if !human { + native.kind = EventKind::OriginEcho; + native.origin = "agent"; + native.requires_attention = false; + } + native.raw_payload = serde_json::to_vec(&json!({ + "changes":{"body":{"from":previous_body}} + })) + .unwrap(); + f.store + .ingest_event(native, SchedulerPolicy { quiet_seconds: 0, event_threshold: 1 }) + .unwrap(); + observe_issue(&f, &github, false).await; + let kind: String = f + .db() + .query_row( + "SELECT e.kind FROM deliveries d JOIN events e ON e.event_id=d.effect_event_id + WHERE d.delivery_guid LIKE 'reconcile-%' AND d.action='edited'", + [], + |row| row.get(0), + ) + .unwrap(); + assert_eq!(kind, expected, "{mode}"); + task.abort(); + } +} + +#[tokio::test] +async fn native_association_changes_are_visible_without_a_root_version_change() { + let remote = Arc::new(Mutex::new(body_edit::BodyRemote::new(false))); + let (github, http) = body_edit::body_server(remote.clone()).await; + let locator = "owner/repository#9".parse().unwrap(); + let before = crate::context::CanonicalContext::PullRequest( + crate::context::materialize_pull_request(&github, &locator, 100).await.unwrap(), + ); + remote.lock().unwrap().associated = false; + let after = crate::context::CanonicalContext::PullRequest( + crate::context::materialize_pull_request(&github, &locator, 100).await.unwrap(), + ); + 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(); +} + +#[tokio::test] +#[allow(clippy::too_many_lines)] // Keep both repositories and their fault ordering in one scenario. +async fn permission_failure_in_one_repository_does_not_starve_other_mentions() { + use axum::http::StatusCode; + use axum::response::IntoResponse as _; + let f = Fixture::new(false); + let policy = SchedulerPolicy { quiet_seconds: 30, event_threshold: 8 }; + let mut healthy_event = String::new(); + for index in 0..17 { + let repository = if index < 16 { "owner/blocked" } else { "owner/healthy" }; + let id = format!("mention-{index}"); + let mut event = revision(&id, "@braid please continue"); + event.repository = repository.into(); + event.repository_node_id = repository.into(); + event.work_item_node_id = Some(repository.into()); + event.object_node_id = Some(id.clone()); + event.event_name = "issue_comment".into(); + event.action = Some("created".into()); + event.kind = EventKind::Wake; + event.detail = Some("created"); + event.cross_surface_invalidation = false; + event.mention_candidate = true; + let result = f.store.ingest_event(event, policy).unwrap(); + if index == 16 { + healthy_event = result.event_id.unwrap(); + } + } + let checked = Arc::new(tokio::sync::Notify::new()); + let notified = checked.clone(); + let router = Router::new() + .route( + "/repos/owner/blocked/collaborators/human/permission", + get(|| async { + ( + StatusCode::FORBIDDEN, + Json(json!({"message":"Resource not accessible by integration"})), + ) + .into_response() + }), + ) + .route( + "/repos/owner/healthy/collaborators/human/permission", + get(move || { + let notified = notified.clone(); + async move { + notified.notify_one(); + Json(json!({"permission":"admin","role_name":"admin"})) + } + }), + ); + 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, router).await.unwrap() }); + let client = octocrab::Octocrab::builder() + .base_uri(format!("http://{address}")) + .unwrap() + .add_retry_config(octocrab::service::middleware::retry::RetryConfig::None) + .build() + .unwrap(); + let clients = ["owner/blocked", "owner/healthy"] + .into_iter() + .map(|repository| { + let identity = crate::github::GitHubIdentity { + app_id: 1, + app_slug: "braid".into(), + installation_id: 1, + repository: repository.into(), + repository_node_id: repository.into(), + actor_node_id: "app".into(), + actor_login: "braid[bot]".into(), + token_expires_at: String::new(), + permissions: BTreeMap::new(), + }; + ( + repository.into(), + Arc::new(GitHubClient::publication_test_client( + client.clone(), + identity, + f.config.github().unwrap().clone(), + )), + ) + }) + .collect(); + let store = Arc::new( + StoreActor::start( + f.config.runtime.database().to_owned(), + f.config.runtime.backups().to_owned(), + ) + .unwrap(), + ); + let (shutdown, receiver) = tokio::sync::watch::channel(false); + let worker = + tokio::spawn(crate::producer::mention_worker(store, Arc::new(clients), policy, receiver)); + tokio::time::timeout(Duration::from_secs(3), checked.notified()) + .await + .expect("healthy repository must reach its permission check despite older denied mentions"); + shutdown.send(true).unwrap(); + worker.await.unwrap(); + let trusted: bool = f + .db() + .query_row("SELECT trusted_mention FROM events WHERE event_id=?1", [healthy_event], |row| { + row.get(0) + }) + .unwrap(); + assert!(trusted); + assert_eq!(f.store.mention_candidates("owner/blocked".into(), 16).unwrap().len(), 16); + http.abort(); +} diff --git a/src/writer/tests/handoff.rs b/src/writer/tests/handoff.rs new file mode 100644 index 00000000..66f7bbf0 --- /dev/null +++ b/src/writer/tests/handoff.rs @@ -0,0 +1,722 @@ +//! End-to-end local handoff uses production actor, outbox, canonical HTTP reads and boundary assembly. +use super::*; + +fn bind_pr(f: &Fixture) { + f.db().execute_batch("INSERT INTO work_items(node_id,repository_node_id,kind,number,state,context_revision,observed_at) VALUES ('pr','repo','pr',9,'open','old-pr-context','now'); INSERT INTO assignments VALUES ('pr-assignment','pr',1,'active','now',NULL); INSERT INTO agent_instances(agent_id,assignment_id,profile_id,profile_revision,role,lifecycle) SELECT 'pr-agent','pr-assignment',profile_id,profile_revision,'pr_implementation_agent','idle' FROM agent_instances WHERE agent_id='agent'; INSERT INTO provider_sessions(session_id,agent_id,provider_kind,provider_session_id,context_revision,instruction_revision,lifecycle,started_at) VALUES ('pr-session','pr-agent','codex','pr-provider','old-pr-context','instructions','idle','now');").unwrap(); +} +fn handoff(f: &Fixture, key: &str) -> Result { + super::super::handoff( + &f.config, + &f.store, + &HandoffRequest { + invocation: Invocation::Agent("turn".into()), + target: "owner/repository#9".parse().unwrap(), + request_id: key.into(), + }, + ) +} +fn count(f: &Fixture, table: &str) -> i64 { + f.db().query_row(&format!("SELECT COUNT(*) FROM {table}"), [], |r| r.get(0)).unwrap() +} +fn runnable(f: &Fixture) { + f.db().execute("UPDATE wake_batches SET quiet_deadline='2000-01-01T00:00:00Z'", []).unwrap(); + f.store.advance_scheduler().unwrap(); +} +fn claim(f: &Fixture) -> Option { + f.store + .claim_runnable_turn( + "pr".into(), + "issue-codex".into(), + vec!["pr-provider".into(), "new-pr-provider".into()], + ) + .unwrap() +} + +#[tokio::test] +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(); + assert_eq!(a.request_id, handoff(&f, "stable").unwrap().request_id); + let (github, task) = + body_edit::body_server(Arc::new(Mutex::new(body_edit::BodyRemote::new(false)))).await; + f.drain(github.clone()).await; + assert_eq!(f.receipt(&a.request_id).lifecycle, "applied"); + assert_eq!(count(&f, "events"), 1); + assert_eq!(count(&f, "wake_batches"), 1); + assert_eq!( + f.db().query_row("SELECT urgent FROM wake_batches", [], |r| r.get::<_, i64>(0)).unwrap(), + 0 + ); + let b = handoff(&f, "second").unwrap(); + f.drain(github).await; + assert_eq!(f.receipt(&b.request_id).lifecycle, "applied"); + assert_eq!(count(&f, "wake_batches"), 1); // merge existing pending + runnable(&f); + let turn = claim(&f).unwrap(); + assert_eq!(turn.references.len(), 2); + task.abort(); +} + +fn add_runnable_event(f: &Fixture, id: &str, reference: &str, urgent: bool) { + let mut connection = f.db(); + let tx = connection.transaction().unwrap(); + tx.execute( + "INSERT INTO events(event_id,work_item_node_id,kind,origin,reference,lifecycle,observed_at) + VALUES (?1,'pr','wake','human',?2,'pending','now')", + rusqlite::params![id, reference], + ) + .unwrap(); + tx.execute( + "INSERT INTO wake_batches(batch_id,work_item_node_id,event_count,quiet_deadline,urgent,lifecycle,created_at,updated_at) + VALUES (?1,'pr',1,'now',?2,'runnable','now','now')", + rusqlite::params![id, urgent], + ).unwrap(); + tx.execute("INSERT INTO wake_batch_events VALUES (?1,?1,0)", [id]).unwrap(); + tx.commit().unwrap(); +} + +#[tokio::test] +async fn accepted_handoff_waits_for_next_turn_and_survives_unavailable_publisher() { + for associated in [true, false] { + let f = Fixture::new(true); + bind_pr(&f); + add_runnable_event(&f, "running", "Already running", false); + let running = claim(&f).unwrap(); + f.store.mark_turn_started(running.turn_id.clone(), "native-running".into()).unwrap(); + + let receipt = handoff(&f, "arrives-during-steer").unwrap(); + let remote = Arc::new(Mutex::new(body_edit::BodyRemote::new(false))); + let (github, task) = body_edit::body_server(remote.clone()).await; + add_runnable_event(&f, "steer", "Emergency human input", true); + let steer = f.store.claim_urgent_steer(running.turn_id.clone()).unwrap().unwrap(); + assert_eq!(steer.turn.references, ["Emergency human input"]); + + // The provider is replying to that exact snapshot when the handoff joins its batch. + f.drain(github.clone()).await; + assert_eq!(f.receipt(&receipt.request_id).lifecycle, "applied"); + let facts: (String, i64, String, i64, i64, Option) = f.db().query_row( + "SELECT h.source_repository,h.source_number,h.target_assignment_id,h.target_generation, + e.next_turn_only,p.target_assignment_id + FROM handoff_inputs h JOIN events e ON e.event_id=h.event_id + JOIN pr_handoffs p ON p.event_id=h.event_id", + [], |r| Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?,r.get(4)?,r.get(5)?)), + ).unwrap(); + assert_eq!(facts, ("owner/repository".into(), 1, "pr-assignment".into(), 1, 1, None)); + + // Remove publisher table names altogether. A query that still joins them errors. + f.db() + .execute_batch( + "ALTER TABLE pr_handoffs RENAME TO unavailable_handoff_receipts; + ALTER TABLE write_intents RENAME TO unavailable_write_intents; + ALTER TABLE github_write_outbox RENAME TO unavailable_write_outbox;", + ) + .unwrap(); + assert!(f.store.gh_write_receipt(receipt.request_id).is_err()); + assert!(f.store.claim_urgent_steer(running.turn_id.clone()).unwrap().is_none()); + f.store.consume_steer_batch(&steer).unwrap(); + assert!(f.store.claim_urgent_steer(running.turn_id.clone()).unwrap().is_none()); + assert!(claim(&f).is_none()); + f.store.mark_turn_terminal(running.turn_id, "completed".into()).unwrap(); + + remote.lock().unwrap().associated = associated; + let next = claim(&f).expect("handoff survives late steer settlement"); + assert_eq!(next.references.len(), 1); + assert!(next.references[0].contains("Explicit Issue handoff")); + let recorder = RecordingSession::new(); + let backend = crate::collaboration::CollaborationBackend::GitHub(github); + if associated { + send_prepared(&f, &backend, next, &recorder).await; + let inputs = recorder.inputs.lock().unwrap(); + assert_eq!(inputs.len(), 1); + assert!(inputs[0].contains("Explicit Issue handoff")); + assert!(inputs[0].contains("Current canonical Context")); + } else { + let prepared = crate::group::input::prepare_input( + &f.config, + &backend, + &f.store, + f.config.profile("issue-codex").unwrap(), + next, + ) + .await + .unwrap(); + assert!(prepared.is_none(), "canonical disassociation retires the handoff"); + let lifecycle: String = f + .db() + .query_row("SELECT lifecycle FROM events WHERE detail='pr_handoff'", [], |r| { + r.get(0) + }) + .unwrap(); + assert_eq!(lifecycle, "consumed"); + } + assert!(claim(&f).is_none(), "the handoff must not surface twice"); + task.abort(); + } +} + +#[tokio::test] +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") + .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'", + "DELETE FROM provider_sessions WHERE session_id='pr-session'", + "INSERT INTO provider_sessions(session_id,agent_id,provider_kind,provider_session_id,context_revision,instruction_revision,lifecycle,started_at,resume_count,last_resumed_at,last_resume_error) SELECT 'latest-pr-session',agent_id,provider_kind,'latest-pr-provider',context_revision,instruction_revision,'blocked',started_at,resume_count,last_resumed_at,last_resume_error FROM provider_sessions WHERE session_id='pr-session'", + "UPDATE work_items SET state='closed' WHERE node_id='pr'", + "UPDATE work_items SET state='merged' WHERE node_id='pr'", + "UPDATE work_items SET state='closed' WHERE node_id='item'", + ] { + let f = Fixture::new(true); + bind_pr(&f); + f.db().execute(sql, []).unwrap(); + 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); + bind_pr(&f); + let a = handoff(&f, "frozen").unwrap(); + f.db().execute_batch("UPDATE assignments SET lifecycle='retired' WHERE assignment_id='pr-assignment'; INSERT INTO assignments VALUES ('new-pr','pr',2,'active','now',NULL); UPDATE agent_instances SET assignment_id='new-pr' WHERE agent_id='pr-agent';").unwrap(); + assert_eq!(handoff(&f, "frozen").unwrap().request_id, a.request_id); + let (github, task) = + body_edit::body_server(Arc::new(Mutex::new(body_edit::BodyRemote::new(false)))).await; + f.drain(github).await; + assert_eq!(f.receipt(&a.request_id).lifecycle, "rejected"); + assert_eq!(count(&f, "events"), 0); + task.abort(); +} + +#[tokio::test] +async fn handoff_remote_validation_never_schedules_before_confirmation() { + 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(); + let mut state = body_edit::BodyRemote::new(false); + if mode == "unrelated" { + state.associated = false; + } // body still contains closing/reference text + if mode == "closed" { + state.snapshot.state = "closed".into(); + } + if mode == "closed-target" { + state.pr_closed = true; + } + if mode == "limited" { + state.limited = true; + } + if mode == "old-source" { + f.db() + .execute("UPDATE assignments SET generation=2 WHERE assignment_id='assignment'", []) + .unwrap(); + } + let (github, task) = body_edit::body_server(Arc::new(Mutex::new(state))).await; + f.drain(github).await; + 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(); + } +} + +#[tokio::test] +async fn applied_issue_design_is_materialized_at_handoff_safe_boundary_not_from_cached_context() { + let f = Fixture::new(true); + bind_pr(&f); + let remote = Arc::new(Mutex::new(body_edit::BodyRemote::new(false))); + let (github, task) = body_edit::body_server(remote.clone()).await; + let edit = body_edit::accept(&f, &github).await; + assert!(handoff(&f, "too-soon").unwrap_err().to_string().contains("not confirmed applied")); + f.drain(github.clone()).await; + assert_eq!(f.receipt(&edit.request_id).lifecycle, "applied"); + let request = handoff(&f, "published-design").unwrap(); + f.drain(github.clone()).await; + assert_eq!(f.receipt(&request.request_id).lifecycle, "applied"); + runnable(&f); + let turn = claim(&f).unwrap(); + let mut reference = crate::group::provider::render_event_references(&f.config, &turn); + let collaboration = crate::collaboration::CollaborationBackend::GitHub(github); + crate::group::input::append_current_context( + f.config.runtime.database(), + &collaboration, + &f.store, + f.config.profile("issue-codex").unwrap(), + &turn, + &mut reference, + ) + .await + .unwrap(); + assert!(reference.contains("Scope, verification, risks"), "{reference}"); + assert!(reference.contains("Current canonical Context")); + assert!(!reference.contains("old-pr-context")); + task.abort(); +} + +#[test] +fn handoff_same_key_cannot_change_target_or_impersonate_issue_agent() { + let f = Fixture::new(true); + bind_pr(&f); + handoff(&f, "stable").unwrap(); + assert!( + super::super::handoff( + &f.config, + &f.store, + &HandoffRequest { + invocation: Invocation::Agent("turn".into()), + target: "owner/repository#10".parse().unwrap(), + request_id: "stable".into() + } + ) + .unwrap_err() + .to_string() + .contains("already used for a different payload") + ); + f.db().execute_batch("UPDATE agent_instances SET role='pr_implementation_agent' WHERE agent_id='agent'; UPDATE work_items SET kind='pr',number=10 WHERE node_id='item';").unwrap(); + assert!( + handoff(&f, "pr-source") + .unwrap_err() + .to_string() + .contains("handoff requires an Issue Agent") + ); +} + +#[tokio::test] +async fn handoff_transaction_rechecks_source_fence_before_any_wake_or_applied_receipt() { + let f = Fixture::new(true); + bind_pr(&f); + let a = handoff(&f, "fence-race").unwrap(); + let (github, task) = + body_edit::body_server(Arc::new(Mutex::new(body_edit::BodyRemote::new(false)))).await; + let owner = f.store.acquire_runtime_lease("runtime".into(), "test".into(), 3600).unwrap(); + let write = f.store.claim_github_write(owner.clone()).unwrap().unwrap(); + let mut mutation_possible = false; + assert!( + super::super::execute(&f.config, &f.store, &github, &write, &mut mutation_possible) + .await + .is_ok() + ); + f.db() + .execute("UPDATE assignments SET generation=2 WHERE assignment_id='assignment'", []) + .unwrap(); + f.store.finish_github_write(write, "applied", None, None, None).unwrap(); + assert_eq!(f.receipt(&a.request_id).lifecycle, "rejected"); + assert_eq!(count(&f, "events"), 0); + assert_eq!(count(&f, "wake_batches"), 0); + f.store.release_runtime_lease(owner).unwrap(); + task.abort(); +} + +#[tokio::test] +async fn refresh_failure_defers_and_merges_an_arriving_handoff_without_losing_inputs() { + let f = Fixture::new(true); + bind_pr(&f); + handoff(&f, "first").unwrap(); + let remote = Arc::new(Mutex::new(body_edit::BodyRemote::new(false))); + let (github, task) = body_edit::body_server(remote.clone()).await; + f.drain(github.clone()).await; + runnable(&f); + let first = claim(&f).unwrap(); + handoff(&f, "arrives-during-refresh").unwrap(); + f.drain(github.clone()).await; + add_input(&f, "wake", "HumanWake arriving during network failure"); + 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!( + 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(); + assert_eq!( + f.db() + .query_row( + "SELECT COUNT(*) FROM wake_batches WHERE lifecycle IN ('pending','runnable')", + [], + |r| r.get::<_, i64>(0) + ) + .unwrap(), + 1 + ); + let retry = claim(&f).unwrap(); + assert_eq!(retry.references.len(), 3); + remote.lock().unwrap().limited = false; + // A fresh HTTP client models process restart after the transient failure; + // the original client correctly retains its installation cooldown. + let (recovered_github, recovered_task) = body_edit::body_server(remote.clone()).await; + let backend = crate::collaboration::CollaborationBackend::GitHub(recovered_github); + let recorder = RecordingSession::new(); + send_prepared(&f, &backend, retry, &recorder).await; + assert_eq!(recorder.inputs.lock().unwrap().len(), 1); + assert!(recorder.inputs.lock().unwrap()[0].contains("Current canonical Context")); + assert_eq!(count(&f, "pr_handoffs"), 2); + assert!( + recorder.inputs.lock().unwrap()[0].contains("HumanWake arriving during network failure") + ); + recovered_task.abort(); + task.abort(); +} + +#[tokio::test] +async fn uncertain_issue_design_is_not_handed_off_as_published() { + let f = Fixture::new(true); + bind_pr(&f); + let remote = Arc::new(Mutex::new(body_edit::BodyRemote::new(false))); + let (github, task) = body_edit::body_server(remote.clone()).await; + let edit = body_edit::accept(&f, &github).await; + remote.lock().unwrap().lose_response = true; + f.drain(github).await; + assert_eq!(f.receipt(&edit.request_id).lifecycle, "uncertain"); + 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(); +} + +/// Provider-boundary recorder: the production send/observe path must record a +/// native start, not merely make the batch claimable again. +struct RecordingSession { + events: tokio::sync::broadcast::Sender, + inputs: Mutex>, +} +impl RecordingSession { + fn new() -> Self { + Self { events: tokio::sync::broadcast::channel(8).0, inputs: Mutex::new(Vec::new()) } + } +} +#[async_trait::async_trait] +impl crate::agent_session::AgentSession for RecordingSession { + fn events(&self) -> tokio::sync::broadcast::Receiver { + self.events.subscribe() + } + fn is_unavailable(&self) -> bool { + false + } + async fn close(&self) -> std::result::Result<(), crate::agent_session::SessionError> { + Ok(()) + } + async fn steer_user_msg( + &self, + _: String, + _: &str, + ) -> std::result::Result + { + panic!("handoff must not steer") + } + async fn send_user_msg( + &self, + msg: String, + steering: bool, + ) -> std::result::Result + { + assert!(!steering); + self.inputs.lock().unwrap().push(msg); + self.events + .send(crate::agent_session::SessionEvent::TurnStarted { + provider_turn_id: "native-start".into(), + }) + .unwrap(); + Ok(crate::agent_session::SendResult::Started) + } +} +async fn send_prepared( + f: &Fixture, + backend: &crate::collaboration::CollaborationBackend, + turn: crate::store::TurnClaim, + recorder: &RecordingSession, +) { + use crate::agent_session::AgentSession; + let (turn, input) = crate::group::input::prepare_input( + &f.config, + backend, + &f.store, + f.config.profile("issue-codex").unwrap(), + turn, + ) + .await + .unwrap() + .expect("surviving input"); + let mut events = recorder.events(); + let native = crate::group::turn_start::send_and_observe( + &f.store, + &turn.turn_id, + &turn.provider_session_id, + recorder, + &mut events, + input, + ) + .await + .unwrap(); + assert_eq!(native.as_deref(), Some("native-start")); + f.store.mark_turn_terminal(turn.turn_id, "completed".into()).unwrap(); +} + +fn add_input(f: &Fixture, kind: &str, reference: &str) { + f.db().execute("INSERT INTO events(event_id,work_item_node_id,kind,detail,origin,reference,lifecycle,observed_at) VALUES ('other-input','pr',?1,NULL,'human',?2,'pending','now')", rusqlite::params![kind, reference]).unwrap(); + f.db().execute_batch("INSERT INTO wake_batch_events SELECT batch_id,'other-input',(SELECT COALESCE(MAX(ordinal)+1,0) FROM wake_batch_events be WHERE be.batch_id=b.batch_id) FROM wake_batches b WHERE lifecycle IN ('pending','runnable'); UPDATE wake_batches SET event_count=event_count+1,urgent=1 WHERE lifecycle IN ('pending','runnable');").unwrap(); + // A trusted HumanWake is the durable source of urgency. + f.db().execute("UPDATE events SET trusted_mention=1 WHERE event_id='other-input'", []).unwrap(); +} + +#[tokio::test] +async fn canonical_invalid_handoff_retires_only_itself_and_survivors_really_send() { + for mode in ["association-removed", "source-closed", "target-closed", "new-generation"] { + let f = Fixture::new(true); + bind_pr(&f); + let receipt = handoff(&f, mode).unwrap(); + let remote = Arc::new(Mutex::new(body_edit::BodyRemote::new(false))); + let (mut github, mut task) = body_edit::body_server(remote.clone()).await; + f.drain(github.clone()).await; + assert_eq!(f.receipt(&receipt.request_id).lifecycle, "applied"); + let reference = match mode { + "target-closed" => "Legitimate Finalization cleanup", + "new-generation" => "New generation activation Wake", + _ => "Legitimate HumanWake", + }; + add_input(&f, if mode == "target-closed" { "lifecycle" } else { "wake" }, reference); + match mode { + "association-removed" => remote.lock().unwrap().associated = false, + "source-closed" => remote.lock().unwrap().snapshot.state = "closed".into(), + "target-closed" => { + remote.lock().unwrap().pr_closed = true; + f.db().execute_batch("UPDATE work_items SET state='closed' WHERE node_id='pr'; UPDATE assignments SET lifecycle='finalizing' WHERE assignment_id='pr-assignment'; UPDATE agent_instances SET lifecycle='finalizing' WHERE agent_id='pr-agent';").unwrap(); + } + "new-generation" => { + f.db().execute_batch("UPDATE assignments SET lifecycle='retired' WHERE assignment_id='pr-assignment'; INSERT INTO assignments VALUES ('new-pr','pr',2,'active','now',NULL); UPDATE agent_instances SET lifecycle='retired' WHERE agent_id='pr-agent'; UPDATE provider_sessions SET lifecycle='retired' WHERE session_id='pr-session'; INSERT INTO agent_instances(agent_id,assignment_id,profile_id,profile_revision,role,lifecycle) SELECT 'new-pr-agent','new-pr',profile_id,profile_revision,role,'idle' FROM agent_instances WHERE agent_id='pr-agent'; INSERT INTO provider_sessions(session_id,agent_id,provider_kind,provider_session_id,context_revision,instruction_revision,lifecycle,started_at) VALUES ('new-pr-session','new-pr-agent','codex','new-pr-provider','new-pr-context','instructions','idle','now');").unwrap(); + // Retirement has local durable proof; a surviving new turn + // still needs complete current Context before native input. + remote.lock().unwrap().limited = true; + } + _ => unreachable!(), + } + runnable(&f); + let turn = claim(&f).unwrap(); + assert_eq!(turn.references.len(), 2); + if mode == "target-closed" { + assert_eq!(turn.trigger_kind, "finalization"); + } + if mode == "new-generation" { + assert_eq!(turn.provider_session_id, "new-pr-provider"); + } + let turn = if mode == "new-generation" { + let backend = crate::collaboration::CollaborationBackend::GitHub(github.clone()); + 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 + // fresh client models recovery/restart without sleeping in a test. + task.abort(); + let recovered = body_edit::body_server(remote.clone()).await; + github = recovered.0; + task = recovered.1; + claim(&f).unwrap() + } else { + turn + }; + let batch = turn.batch_id.clone(); + let recorder = RecordingSession::new(); + let backend = crate::collaboration::CollaborationBackend::GitHub(github); + send_prepared(&f, &backend, turn, &recorder).await; + let inputs = recorder.inputs.lock().unwrap(); + assert_eq!(inputs.len(), 1, "{mode}"); + assert!(inputs[0].contains(reference), "{mode}: {}", inputs[0]); + assert!(!inputs[0].contains("Explicit Issue handoff"), "{mode}"); + assert!(inputs[0].contains("Current canonical Context"), "{mode}"); + assert_eq!(f.receipt(&receipt.request_id).lifecycle, "applied"); + assert_eq!(count(&f, "pr_handoffs"), 1); + assert_eq!( + f.db() + .query_row("SELECT lifecycle FROM events WHERE detail='pr_handoff'", [], |r| r + .get::<_, String>( + 0 + )) + .unwrap(), + "consumed" + ); + assert_eq!( + f.db() + .query_row( + "SELECT event_count FROM wake_batches WHERE batch_id=?1", + [&batch], + |r| r.get::<_, i64>(0) + ) + .unwrap(), + 1 + ); + f.store.advance_scheduler().unwrap(); + assert!(claim(&f).is_none(), "no duplicate finalization/wake: {mode}"); + task.abort(); + } +} + +#[tokio::test] +async fn invalid_handoff_only_batch_ends_and_returns_claim_without_losing_concurrent_input() { + let f = Fixture::new(true); + bind_pr(&f); + handoff(&f, "empty").unwrap(); + let remote = Arc::new(Mutex::new(body_edit::BodyRemote::new(false))); + let (github, task) = body_edit::body_server(remote.clone()).await; + f.drain(github.clone()).await; + runnable(&f); + let turn = claim(&f).unwrap(); + let empty_batch = turn.batch_id.clone(); + remote.lock().unwrap().associated = false; + // Another ordinary input arriving during refresh owns its own debounce. + f.db().execute_batch("INSERT INTO wake_batches(batch_id,work_item_node_id,event_count,quiet_deadline,urgent,lifecycle,created_at,updated_at) VALUES ('next','pr',0,'2099-01-01T00:00:00Z',0,'pending','now','now')").unwrap(); + add_input(&f, "wake", "Arrived during refresh"); + let backend = crate::collaboration::CollaborationBackend::GitHub(github); + assert!( + crate::group::input::prepare_input( + &f.config, + &backend, + &f.store, + f.config.profile("issue-codex").unwrap(), + turn + ) + .await + .unwrap() + .is_none() + ); + assert_eq!( + f.db() + .query_row( + "SELECT event_count FROM wake_batches WHERE batch_id=?1", + [&empty_batch], + |r| r.get::<_, i64>(0) + ) + .unwrap(), + 0 + ); + assert_eq!( + f.db() + .query_row("SELECT COUNT(*) FROM turns WHERE batch_id=?1", [&empty_batch], |r| r + .get::<_, i64>(0)) + .unwrap(), + 0 + ); + assert_eq!( + f.db() + .query_row( + "SELECT lifecycle FROM provider_sessions WHERE session_id='pr-session'", + [], + |r| r.get::<_, String>(0) + ) + .unwrap(), + "idle" + ); + assert!(claim(&f).is_none()); // surviving arrival is still debouncing + runnable(&f); + let recorder = RecordingSession::new(); + send_prepared(&f, &backend, claim(&f).unwrap(), &recorder).await; + assert!(recorder.inputs.lock().unwrap()[0].contains("Arrived during refresh")); + assert!(claim(&f).is_none()); + task.abort(); +} + +#[tokio::test] +async fn retirement_is_fenced_atomic_and_preserves_other_handoff_and_historical_source() { + use crate::store::handoff_inputs::{RetiredInput, RetirementReason}; + let f = Fixture::new(true); + bind_pr(&f); + let first = handoff(&f, "first").unwrap(); + let remote = Arc::new(Mutex::new(body_edit::BodyRemote::new(false))); + let (github, task) = body_edit::body_server(remote).await; + f.drain(github.clone()).await; + handoff(&f, "survivor").unwrap(); + f.drain(github.clone()).await; + runnable(&f); + let turn = claim(&f).unwrap(); + let event: String = f + .db() + .query_row("SELECT event_id FROM pr_handoffs WHERE intent_id=?1", [&first.intent_id], |r| { + r.get(0) + }) + .unwrap(); + let input = + RetiredInput { event_id: event.clone(), reason: RetirementReason::SourceNotOpenAssociated }; + // A bad second membership must roll back the first retirement as well. + assert!( + f.store + .retire_handoff_inputs( + turn.clone(), + vec![ + input.clone(), + RetiredInput { + event_id: "not-a-member".into(), + reason: RetirementReason::TargetClosed + } + ] + ) + .unwrap_err() + .to_string() + .contains("handoff retirement membership changed") + ); + assert_eq!( + f.db() + .query_row("SELECT lifecycle FROM events WHERE event_id=?1", [&event], |r| r + .get::<_, String>(0)) + .unwrap(), + "pending" + ); + let remaining = + f.store.retire_handoff_inputs(turn.clone(), vec![input.clone()]).unwrap().unwrap(); + assert_eq!(remaining.references.len(), 1); + // Applied delivery is historical; later source retirement/generation does + // not revoke it while the source Issue remains OPEN and associated. + f.db().execute("UPDATE assignments SET lifecycle='retired',generation=2 WHERE assignment_id='assignment'", []).unwrap(); + let recorder = RecordingSession::new(); + let backend = crate::collaboration::CollaborationBackend::GitHub(github); + 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!(matches!( + f.store.retire_handoff_inputs(turn, vec![input]), + Err(crate::store::StoreError::Sqlite(rusqlite::Error::QueryReturnedNoRows)) + )); + assert_eq!(count(&f, "pr_handoffs"), 2); + assert_eq!(f.receipt(&first.request_id).lifecycle, "applied"); + task.abort(); +} diff --git a/src/writer/tests/implementation_recovery.rs b/src/writer/tests/implementation_recovery.rs new file mode 100644 index 00000000..7218cd33 --- /dev/null +++ b/src/writer/tests/implementation_recovery.rs @@ -0,0 +1,255 @@ +//! Published PR identity survives a lost delivery and later request references. +use super::*; + +fn request(f: &Fixture, comment: u64) -> GhWriteReceipt { + ensure_pull_request( + &f.config, + &f.store, + PullRequestEnsureRequest { + invocation: f.invocation(), + repository: "owner/repository".parse().unwrap(), + comment_id: comment, + head: Some("head".into()), + }, + ) + .unwrap() +} +fn legacy_gap(f: &Fixture, receipt: &GhWriteReceipt) { + let mut db = f.db(); + db.execute_batch("PRAGMA foreign_keys=ON;").unwrap(); + let tx = db.transaction().unwrap(); + let (event,guid):(String,String)=tx.query_row("SELECT e.event_id,e.delivery_guid FROM implementation_requests i JOIN events e ON e.event_id=i.activation_event_id WHERE i.intent_id=?1",[&receipt.intent_id],|r|Ok((r.get(0)?,r.get(1)?))).unwrap(); + tx.execute( + "UPDATE implementation_requests SET activation_event_id=NULL WHERE activation_event_id=?1", + [&event], + ) + .unwrap(); + tx.execute("DELETE FROM wake_batch_events WHERE event_id=?1", [&event]).unwrap(); + tx.execute("DELETE FROM wake_batches WHERE work_item_node_id='pr' AND NOT EXISTS(SELECT 1 FROM wake_batch_events b WHERE b.batch_id=wake_batches.batch_id)",[]).unwrap(); + tx.execute("UPDATE deliveries SET effect_event_id=NULL WHERE effect_event_id=?1", [&event]) + .unwrap(); + tx.execute("DELETE FROM events WHERE event_id=?1", [&event]).unwrap(); + tx.execute("DELETE FROM deliveries WHERE delivery_guid=?1", [guid]).unwrap(); + tx.execute( + "UPDATE write_intents SET lifecycle='pending' WHERE intent_id=?1", + [&receipt.intent_id], + ) + .unwrap(); + tx.execute("UPDATE github_write_outbox SET lifecycle='pending',next_attempt_at='2000-01-01T00:00:00Z' WHERE intent_id=?1",[&receipt.intent_id]).unwrap(); + tx.commit().unwrap(); +} +fn replace_source(f: &Fixture) { + f.db().execute_batch("UPDATE provider_sessions SET lifecycle='replaced' WHERE session_id='session'; INSERT INTO provider_sessions(session_id,agent_id,provider_kind,provider_session_id,context_revision,instruction_revision,lifecycle,started_at) VALUES('new-session','agent','codex','new-source-provider','new-context','instructions','idle','now'); INSERT INTO turns(turn_id,session_id,context_revision,trigger_kind,lifecycle) VALUES('new-turn','new-session','new-context','wake','completed');").unwrap(); +} +fn activations(f: &Fixture) -> i64 { + f.db() + .query_row( + "SELECT count(*) FROM events WHERE kind='assign' AND detail='pr_ensure'", + [], + |r| r.get(0), + ) + .unwrap() +} + +#[tokio::test] +async fn discovery_cannot_adopt_a_different_request_with_a_matching_id_prefix() { + let f = Fixture::new(true); + let receipt = request(&f, 7); + let remote = Arc::new(Mutex::new(Remote { + pr_body: Some( + "Closes #1\n\nImplementation request: https://github.com/owner/repository/issues/comments/70" + .into(), + ), + ..Remote::default() + })); + let (github, http) = server(remote.clone(), true).await; + f.drain(github).await; + let result = f.receipt(&receipt.request_id); + assert_eq!(result.lifecycle, "rejected"); + assert!(result.last_error.as_deref().unwrap().contains("unrelated PR")); + assert_eq!(activations(&f), 0); + assert_eq!(remote.lock().unwrap().writes, 0); + http.abort(); +} + +#[test] +fn ensure_rejects_invalid_ref_components_before_accepting_an_obligation() { + let f = Fixture::new(false); + for head in ["topic//task", "topic/.task", "topic.lock/task"] { + let result = ensure_pull_request( + &f.config, + &f.store, + PullRequestEnsureRequest { + invocation: Invocation::Operator, + repository: "owner/repository".parse().unwrap(), + comment_id: 7, + head: Some(head.into()), + }, + ); + assert!(result.unwrap_err().to_string().contains("invalid Git branch"), "{head}"); + } + assert_eq!( + f.db().query_row("SELECT COUNT(*) FROM write_intents", [], |r| r.get::<_, i64>(0)).unwrap(), + 0 + ); +} + +#[test] +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( + rusqlite::ffi::Error::new(code), + Some("another connection holds the ledger".into()), + )); + assert!(helpers::store_as_github_error(&error).is_unavailable()); + } + for error in [StoreError::ActorUnavailable, StoreError::ActorStopped] { + assert!(helpers::store_as_github_error(&error).is_unavailable()); + } + let constraint = StoreError::Sqlite(rusqlite::Error::SqliteFailure( + rusqlite::ffi::Error::new(rusqlite::ffi::SQLITE_CONSTRAINT), + Some("invalid reference".into()), + )); + assert!(!helpers::store_as_github_error(&constraint).is_unavailable()); + assert!( + !helpers::store_as_github_error(&StoreError::InvalidData("source was revoked".into())) + .is_unavailable() + ); +} + +#[tokio::test] +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 { 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"); + let writes = remote.lock().unwrap().writes; + assert_eq!(writes, 3); + legacy_gap(&f, &receipt); + replace_source(&f); + remote.lock().unwrap().pr_body = Some("Current scope, no historical discovery marker".into()); + f.drain(github).await; + let result = f.receipt(&receipt.request_id); + assert_eq!(result.lifecycle, "applied", "{:?}", result.last_error); + assert!( + f.store + .implementation_request_receipt(receipt.intent_id.clone()) + .unwrap() + .unwrap() + .activation_delivered + ); + assert_eq!(activations(&f), 1); + assert_eq!(remote.lock().unwrap().writes, writes); + http.abort(); +} + +#[tokio::test] +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 { pr_missing: true, ..Remote::default() })); + let (github, http) = server(remote.clone(), true).await; + f.drain(github.clone()).await; + legacy_gap(&f, &original); + replace_source(&f); + f.db().execute("UPDATE github_write_outbox SET next_attempt_at='2099-01-01T00:00:00Z' WHERE intent_id=?1",[&original.intent_id]).unwrap(); + let followup = request(&f, 8); + f.drain(github.clone()).await; + let result = f.receipt(&followup.request_id); + assert_eq!(result.lifecycle, "applied", "{:?}", result.last_error); + let plan = f.store.implementation_request_receipt(followup.intent_id).unwrap().unwrap(); + assert_eq!(plan.root_intent_id, original.intent_id); + assert_eq!(plan.root_request_id, original.request_id); + assert_eq!(plan.pull_request_number, Some(9)); + assert!(plan.activation_delivered); + assert_eq!(f.receipt(&original.request_id).lifecycle, "applied"); + assert_eq!(activations(&f), 1); + assert_eq!(remote.lock().unwrap().writes, 3); + let next = request(&f, 8); + assert_eq!(next.request_id, result.request_id); + f.drain(github).await; + assert_eq!(activations(&f), 1); + http.abort(); +} + +#[tokio::test] +async fn recovery_revalidates_the_current_open_source_target_and_association() { + 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())); + let (github, http) = server(remote.clone(), true).await; + f.drain(github.clone()).await; + legacy_gap(&f, &receipt); + remote.lock().unwrap().authority = authority; + f.drain(github).await; + assert_rejected(&f.receipt(&receipt.request_id), reason); + assert_eq!(activations(&f), 0); + assert_eq!(remote.lock().unwrap().writes, 0); + http.abort(); + } +} + +#[tokio::test] +async fn recovery_cannot_replace_a_blocked_generation_or_adopt_another_issue() { + for blocked in [false, true] { + let f = Fixture::new(true); + let original = request(&f, 7); + let remote = Arc::new(Mutex::new(Remote::default())); + let (github, http) = server(remote.clone(), true).await; + f.drain(github.clone()).await; + legacy_gap(&f, &original); + 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_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_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); + http.abort(); + } +} + +#[tokio::test] +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 { pr_missing: true, ..Remote::default() })); + let (github, http) = server(remote.clone(), true).await; + f.drain(github).await; + assert_rejected( + &f.receipt(&receipt.request_id), + "publication source was invalidated or superseded", + ); + assert_eq!(remote.lock().unwrap().writes, 0); + assert_eq!(activations(&f), 0); + http.abort(); +} + +fn assert_rejected(receipt: &GhWriteReceipt, reason: &str) { + assert_eq!(receipt.lifecycle, "rejected", "{receipt:?}"); + assert!(receipt.last_error.as_deref().unwrap().contains(reason), "{receipt:?}"); +} diff --git a/src/writer/tests/observation_recovery.rs b/src/writer/tests/observation_recovery.rs new file mode 100644 index 00000000..938c245c --- /dev/null +++ b/src/writer/tests/observation_recovery.rs @@ -0,0 +1,340 @@ +//! A filtered view is not an observation of absence, and absence has no edit clock. +use super::*; +use crate::{ + context::{self, CanonicalContext, CommentSnapshot}, + producer::reconcile::{self, ReconcileScope}, + store::{ChangeIdentity, EventKind, ObservationBasis, ObservationCommit}, +}; + +const PRESENT: &str = "2026-11-06T13:57:29Z"; +const LOCAL_ABSENCE: &str = "2026-11-06T13:57:52.111442621Z"; +fn comment(node: &str, body: &str) -> CommentSnapshot { + CommentSnapshot { + node_id: node.into(), + database_id: "99".into(), + repository: "owner/repository".into(), + work_item_number: 1, + author: Some(context::Actor { node_id: "app".into(), login: "braid[bot]".into() }), + created_at: PRESENT.into(), + updated_at: PRESENT.into(), + last_edited_at: None, + body: Some(body.into()), + minimized: false, + minimized_reason: None, + pinned: false, + deleted: false, + } +} +fn scope(c: &CanonicalContext) -> ReconcileScope { + let o = context::canonical_observations(c).remove(0); + ReconcileScope { + work_item_node_id: o.work_item_node_id, + work_item_kind: o.work_item_kind, + work_item_number: o.work_item_number, + work_item_state: o.work_item_state.clone(), + previous_work_item_state: o.work_item_state, + repository_node_id: o.repository_node_id, + repository: o.repository, + } +} +fn observe( + f: &Fixture, + github: &GitHubClient, + c: &CanonicalContext, + basis: ObservationBasis, +) -> Result { + reconcile::reconcile_observations( + &f.store, + github, + &f.config, + &scope(c), + basis, + &context::canonical_observations(c), + ) +} +async fn issue( + f: &Fixture, + node: &str, +) -> (CanonicalContext, Arc, tokio::task::JoinHandle<()>) { + let (github, http) = issue_context_server("Current design").await; + let locator = "owner/repository#1".parse().unwrap(); + let mut c = + CanonicalContext::Issue(context::materialize_issue(&github, &locator, 100).await.unwrap()); + let CanonicalContext::Issue(i) = &mut c else { unreachable!() }; + i.comments = vec![comment(node, "current visible content")]; + context::reconcile_local_state(&mut c, &f.store, Some(&github.identity().actor_node_id)) + .unwrap(); + (c, github, http) +} +fn seed(f: &Fixture, c: &CanonicalContext) { + let root = context::canonical_observations(c)[0].work_item_node_id.clone(); + f.store + .commit_observation(ObservationCommit { + basis: f.store.begin_observation(root).unwrap(), + current: context::canonical_observations(c) + .iter() + .map(super::semantic_contract::processed) + .collect(), + events: vec![], + policy: SchedulerPolicy { quiet_seconds: 30, event_threshold: 8 }, + }) + .unwrap(); +} +fn managed(f: &Fixture, node: &str, root: &str) { + f.db().execute("INSERT INTO operational_comment_roles(role_id,work_item_node_id,profile_id,assignment_generation,comment_node_id) VALUES(?1,?2,'issue-codex',1,?3)",rusqlite::params!["a".repeat(32),root,node]).unwrap(); +} +fn poison(f: &Fixture, node: &str) { + for table in ["processed_objects", "canonical_objects"] { + f.db() + .execute( + &format!("UPDATE {table} SET lifecycle='deleted',version=?2 WHERE node_id=?1"), + rusqlite::params![node, LOCAL_ABSENCE], + ) + .unwrap(); + } +} +fn raw(node: &str, guid: &str, deleted: bool) -> IngressEvent { + let mut e = continuous_collaboration::revision(guid, "current visible content"); + e.identity = ChangeIdentity::Occurrence; + e.event_name = "issue_comment".into(); + e.object_node_id = Some(node.into()); + e.object_version = Some(format!("{PRESENT}:{}:", if deleted { "deleted" } else { "active" })); + e.action = Some(if deleted { "deleted" } else { "edited" }.into()); + e.detail = Some(if deleted { "deleted" } else { "edited" }); + e.cross_surface_invalidation = false; + e.kind = EventKind::Invalidate; + e +} + +#[tokio::test] +async fn canonical_reads_recognize_a_status_create_whose_receipt_was_lost() { + for producer_first in [true, false] { + let f = Fixture::new(true); + let remote = Arc::new(Mutex::new(body_edit::BodyRemote::new(false))); + let (github, http) = body_edit::body_server(remote.clone()).await; + f.store + .enqueue_assignment_operational_status( + "assignment".into(), + "Provider unavailable".into(), + ) + .unwrap(); + let owner = + f.store.acquire_runtime_lease("runtime".into(), "publisher".into(), 3600).unwrap(); + let write = f.store.claim_github_write(owner.clone()).unwrap().unwrap(); + assert_eq!(write.operation, "comment_create"); + github.create_issue_comment(1, &write.content).await.unwrap(); + f.store.release_runtime_lease(owner).unwrap(); + f.store.recover_writes().unwrap(); + // The publisher stays off after the first remote mutation. Neither the + // role claiming path nor the canonical observation can use its ACK. + { + let mut state = remote.lock().unwrap(); + let mut discussion = state.issue_comments[0].clone(); + discussion["id"] = json!("discussion"); + discussion["fullDatabaseId"] = json!("100"); + discussion["body"] = json!(write.content.replacen( + "Provider unavailable", + "Provider log reviewed in an ordinary App comment", + 1 + )); + let mut imitation = state.issue_comments[0].clone(); + imitation["id"] = json!("imitation"); + imitation["fullDatabaseId"] = json!("101"); + imitation["author"] = json!({"id":"human", "login":"participant"}); + state.issue_comments.extend([discussion, imitation]); + } + let mut canonical = CanonicalContext::Issue( + context::materialize_issue(&github, &"owner/repository#1".parse().unwrap(), 100) + .await + .unwrap(), + ); + let basis = f.store.begin_observation("item".into()).unwrap(); + if producer_first { + observe(&f, &github, &canonical, basis).unwrap(); + let status_observed: String = f + .db() + .query_row( + "SELECT kind FROM events WHERE object_node_id='status' AND detail='observed'", + [], + |row| row.get(0), + ) + .unwrap(); + assert_eq!(status_observed, EventKind::Noop.as_str()); + } + context::reconcile_local_state( + &mut canonical, + &f.store, + Some(&github.identity().actor_node_id), + ) + .unwrap(); + let CanonicalContext::Issue(issue) = &canonical else { unreachable!() }; + let visible = + issue.comments.iter().map(|comment| comment.node_id.as_str()).collect::>(); + assert_eq!(visible, ["discussion", "imitation"]); + let rendered = context::render_complete(&canonical, 0.5, 100_000); + assert!(rendered.text.contains("ordinary App comment")); + assert!(!rendered.text.contains("braid-operational-status:v1:")); + let db = f.db(); + let recognized: String = db + .query_row("SELECT comment_node_id FROM operational_comment_roles", [], |row| { + row.get(0) + }) + .unwrap(); + assert_eq!(recognized, "status"); + let receipt: (Option, String) = db + .query_row( + "SELECT s.remote_comment_node_id,o.lifecycle FROM status_comments s + JOIN github_write_outbox o ON o.intent_id=s.write_intent_id", + [], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .unwrap(); + assert_eq!(receipt, (None, "uncertain".into())); + assert_eq!( + db.query_row( + "SELECT lifecycle FROM canonical_objects WHERE node_id='status'", + [], + |row| row.get::<_, String>(0), + ) + .unwrap(), + "active" + ); + http.abort(); + } +} + +#[tokio::test] +async fn operational_projection_never_turns_observed_members_into_tombstones() { + for pr in [false, true] { + let f = Fixture::new(true); + let (github, http) = issue_context_server("Current design").await; + let locator = if pr { "owner/repository#9" } else { "owner/repository#1" }.parse().unwrap(); + let mut c = if pr { + CanonicalContext::PullRequest( + context::materialize_pull_request(&github, &locator, 100).await.unwrap(), + ) + } else { + CanonicalContext::Issue( + context::materialize_issue(&github, &locator, 100).await.unwrap(), + ) + }; + context::reconcile_local_state(&mut c, &f.store, Some(&github.identity().actor_node_id)) + .unwrap(); + let root = scope(&c).work_item_node_id; + managed(&f, "status", &root); + let mut echo = raw("status", "status-created", false); + echo.work_item_node_id = Some(root.clone()); + echo.work_item_kind = Some(if pr { "pr" } else { "issue" }); + echo.work_item_number = Some(if pr { 9 } else { 1 }); + echo.kind = EventKind::OriginEcho; + echo.origin = "agent"; + f.store + .ingest_event(echo, SchedulerPolicy { quiet_seconds: 30, event_threshold: 8 }) + .unwrap(); + let comments = match &mut c { + CanonicalContext::Issue(i) => &mut i.comments, + CanonicalContext::PullRequest(p) => &mut p.conversation, + }; + comments.extend([ + comment("status", "private operational diagnostic"), + comment("ordinary", "> **Braid Operational Status** is just user prose"), + ]); + context::reconcile_local_state(&mut c, &f.store, Some(&github.identity().actor_node_id)) + .unwrap(); + let lifecycle: String = f + .db() + .query_row("SELECT lifecycle FROM canonical_objects WHERE node_id='status'", [], |r| { + r.get(0) + }) + .unwrap(); + assert_eq!(lifecycle, "active"); + let rendered = context::render_complete(&c, 0.5, 100_000); + assert!(!rendered.text.contains("private operational diagnostic")); + assert!(rendered.text.contains("is just user prose")); + http.abort(); + } +} + +#[tokio::test] +async fn a_legacy_local_tombstone_is_corrected_by_presence_without_waking_for_status() { + for owned in [false, true] { + let f = Fixture::new(true); + let (c, github, http) = issue(&f, "comment").await; + if owned { + managed(&f, "comment", "item"); + } + seed(&f, &c); + poison(&f, "comment"); + let denied = f + .store + .ingest_event( + raw("comment", "old-visible-event", false), + SchedulerPolicy { quiet_seconds: 30, event_threshold: 8 }, + ) + .unwrap(); + assert_eq!( + denied.event_lifecycle.as_deref(), + Some("superseded"), + "a late webhook cannot restore a tombstone" + ); + let basis = f.store.begin_observation("item".into()).unwrap(); + assert_eq!(observe(&f, &github, &c, basis).unwrap(), 1); + let restored = f + .store + .begin_observation("item".into()) + .unwrap() + .objects + .into_iter() + .find(|o| o.node_id == "comment") + .unwrap(); + assert_eq!(restored.lifecycle, "active"); + assert!(restored.version.starts_with(PRESENT)); + assert_eq!(f.store.runtime_status().unwrap().batches.len(), usize::from(!owned)); + assert_eq!( + observe(&f, &github, &c, f.store.begin_observation("item".into()).unwrap()).unwrap(), + 0 + ); + http.abort(); + } +} + +#[tokio::test] +async fn an_admitted_delete_during_the_api_read_rejects_the_whole_old_snapshot() { + let f = Fixture::new(true); + let (c, github, http) = issue(&f, "comment").await; + seed(&f, &c); + let basis = f.store.begin_observation("item".into()).unwrap(); + f.store + .ingest_event( + raw("comment", "delete-during-read", true), + SchedulerPolicy { quiet_seconds: 30, event_threshold: 8 }, + ) + .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.begin_observation("item".into()).unwrap().objects, expected); + http.abort(); +} + +#[tokio::test] +async fn truly_newer_positive_edits_still_fence_older_snapshots_and_name_the_conflict() { + let f = Fixture::new(true); + let (mut c, github, http) = issue(&f, "comment").await; + let CanonicalContext::Issue(i) = &mut c else { unreachable!() }; + i.comments[0].updated_at = "2026-11-06T14:00:00Z".into(); + seed(&f, &c); + let CanonicalContext::Issue(i) = &mut c else { unreachable!() }; + i.comments[0].updated_at = PRESENT.into(); + let error = observe(&f, &github, &c, f.store.begin_observation("item".into()).unwrap()) + .unwrap_err() + .to_string(); + assert!( + error.contains("comment") + && error.contains("14:00:00Z") + && error.contains(PRESENT) + && error.contains("active"), + "{error}" + ); + http.abort(); +} diff --git a/src/writer/tests/publication_contract.rs b/src/writer/tests/publication_contract.rs new file mode 100644 index 00000000..84188894 --- /dev/null +++ b/src/writer/tests/publication_contract.rs @@ -0,0 +1,49 @@ +use super::*; + +#[tokio::test] +async fn ambiguous_comment_recovery_records_ambiguity_without_another_mutation() { + let fixture = Fixture::new(false); + let receipt = fixture.comment(); + let remote = Arc::new(Mutex::new(Remote { lose_comment_response: true, ..Remote::default() })); + let (github, task) = server(remote.clone(), true).await; + fixture.drain(github).await; + task.abort(); + assert_eq!(fixture.receipt(&receipt.request_id).lifecycle, "uncertain"); + { + let mut remote = remote.lock().unwrap(); + let mut duplicate = remote.comments[0].clone(); + duplicate["id"] = json!(100); + duplicate["node_id"] = json!("second-comment"); + remote.comments.push(duplicate); + } + let fixture = fixture.reopen(); + fixture.store.recover_writes().unwrap(); + fixture.due(); + let (github, task) = server(remote.clone(), true).await; + fixture.drain(github).await; + let result = fixture.receipt(&receipt.request_id); + assert_eq!(result.lifecycle, "ambiguous"); + assert!(result.last_error.unwrap().contains("multiple matching App comments")); + assert_eq!(remote.lock().unwrap().writes, 1); + task.abort(); +} + +#[tokio::test] +async fn permission_and_missing_target_are_rejected_by_the_production_executor() { + for (permission, target_status, reason) in [ + (false, None, "lacks required permissions: issues"), + (true, Some(axum::http::StatusCode::NOT_FOUND), "GitHub returned 404"), + ] { + let fixture = Fixture::new(false); + let receipt = fixture.comment(); + let remote = Arc::new(Mutex::new(Remote { target_status, ..Remote::default() })); + let (github, task) = server(remote.clone(), permission).await; + fixture.drain(github.clone()).await; + let result = fixture.receipt(&receipt.request_id); + assert_eq!(result.lifecycle, "rejected"); + assert!(result.last_error.as_deref().unwrap().contains(reason), "{:?}", result.last_error); + fixture.drain(github).await; + assert_eq!(remote.lock().unwrap().writes, 0); + task.abort(); + } +} diff --git a/src/writer/tests/reaction_feedback.rs b/src/writer/tests/reaction_feedback.rs new file mode 100644 index 00000000..45efc768 --- /dev/null +++ b/src/writer/tests/reaction_feedback.rs @@ -0,0 +1,149 @@ +use super::*; +use crate::store::{ChangeIdentity, EventKind, ReactionTarget, TurnClaim}; + +const POLICY: SchedulerPolicy = SchedulerPolicy { quiet_seconds: 30, event_threshold: 8 }; + +fn accept_trusted_mention(f: &Fixture) -> TurnClaim { + let mut mention = continuous_collaboration::revision("mention", "@braid Current design"); + mention.identity = ChangeIdentity::Occurrence; + mention.event_name = "issue_comment".into(); + mention.action = Some("created".into()); + mention.object_node_id = Some("comment".into()); + mention.kind = EventKind::Wake; + mention.detail = Some("created"); + mention.cross_surface_invalidation = false; + mention.mention_candidate = true; + mention.reaction_target = + Some(ReactionTarget { kind: "issue_comment", database_id: "7".into() }); + let accepted = f.store.ingest_event(mention, POLICY).unwrap(); + f.store.resolve_mention(accepted.event_id.unwrap(), true, POLICY).unwrap(); + let claim = f + .store + .claim_runnable_turn("issue".into(), "issue-codex".into(), vec!["provider".into()]) + .unwrap() + .unwrap(); + assert!(claim.trusted_mention); + f.store.mark_turn_started(claim.turn_id.clone(), "native-turn".into()).unwrap(); + claim +} + +#[test] +fn accepted_input_and_turn_terminal_survive_a_missing_publication_table() { + for (terminal, expected) in [("completed", "+1"), ("failed", "confused")] { + let f = Fixture::new(true); + let db = f.db(); + db.execute_batch("ALTER TABLE github_write_outbox RENAME TO unavailable_outbox").unwrap(); + let claim = accept_trusted_mention(&f); + f.store.mark_turn_terminal(claim.turn_id.clone(), terminal.into()).unwrap(); + assert_eq!( + db.query_row("SELECT lifecycle FROM turns WHERE turn_id=?1", [&claim.turn_id], |row| { + row.get::<_, String>(0) + },) + .unwrap(), + terminal + ); + let mut query = + db.prepare("SELECT content FROM github_reaction_feedback ORDER BY sequence").unwrap(); + let intents = query + .query_map([], |row| row.get::<_, String>(0)) + .unwrap() + .collect::, _>>() + .unwrap(); + drop(query); + assert_eq!(intents, ["eyes", "rocket", expected]); + let owner = + f.store.acquire_runtime_lease("runtime".into(), "publisher".into(), 60).unwrap(); + 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(); + assert_eq!( + (write.operation.as_str(), write.content.as_str()), + ("reaction_add", content) + ); + f.store.finish_github_write(write, "applied", Some("99".into()), None, None).unwrap(); + } + assert!(f.store.claim_github_write(owner.clone()).unwrap().is_none()); + assert_eq!( + db.query_row( + "SELECT lifecycle FROM github_write_outbox WHERE content='rocket'", + [], + |row| row.get::<_, String>(0), + ) + .unwrap(), + "superseded" + ); + f.store.release_runtime_lease(owner).unwrap(); + } +} + +#[test] +fn context_reset_commits_with_publisher_unavailable_and_clears_a_late_rocket() { + for restarted in [false, true] { + let f = Fixture::new(true); + let claim = accept_trusted_mention(&f); + let owner = + f.store.acquire_runtime_lease("runtime".into(), "publisher".into(), 60).unwrap(); + let eyes = f.store.claim_github_write(owner.clone()).unwrap().unwrap(); + assert_eq!(eyes.content, "eyes"); + f.store.finish_github_write(eyes, "applied", Some("91".into()), None, None).unwrap(); + let rocket = f.store.claim_github_write(owner.clone()).unwrap().unwrap(); + assert_eq!(rocket.content, "rocket"); + + let db = f.db(); + db.execute_batch("ALTER TABLE github_write_outbox RENAME TO unavailable_outbox").unwrap(); + f.store + .ingest_event(continuous_collaboration::revision("new-context", "Revised"), POLICY) + .unwrap(); + let reset = f + .store + .begin_context_reset(Some(claim.turn_id.clone()), "issue".into(), "issue-codex".into()) + .unwrap() + .unwrap(); + f.store + .mark_context_reset_turn_terminal( + reset.reset_id.clone(), + claim.turn_id, + "interrupted".into(), + ) + .unwrap(); + let lifecycles: (String, String) = db + .query_row( + "SELECT t.lifecycle,r.lifecycle FROM context_resets r + JOIN turns t ON t.turn_id=r.active_turn_id WHERE r.reset_id=?1", + [&reset.reset_id], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .unwrap(); + assert_eq!(lifecycles, ("interrupted".into(), "materializing".into())); + db.execute_batch("ALTER TABLE unavailable_outbox RENAME TO github_write_outbox").unwrap(); + + 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"); + (f, owner, retry) + } else { + (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(); + assert_eq!( + (removal.operation.as_str(), removal.content.as_str()), + ("reaction_delete", "rocket") + ); + assert_eq!(removal.remote_database_id.as_deref(), Some("92")); + f.store.finish_github_write(removal, "applied", None, None, None).unwrap(); + assert!(f.store.claim_github_write(owner.clone()).unwrap().is_none()); + f.store.release_runtime_lease(owner).unwrap(); + } +} diff --git a/src/writer/tests/semantic_contract.rs b/src/writer/tests/semantic_contract.rs new file mode 100644 index 00000000..47a2768a --- /dev/null +++ b/src/writer/tests/semantic_contract.rs @@ -0,0 +1,236 @@ +//! Product oracles for repeated state transitions and non-semantic edits. +use super::*; +use crate::{ + context::{self, CanonicalContext, CommentSnapshot, ReviewThreadSnapshot}, + store::{CanonicalObjectState, ChangeIdentity, EventKind, ObservationCommit}, +}; + +fn policy() -> SchedulerPolicy { + SchedulerPolicy { quiet_seconds: 30, event_threshold: 8 } +} +fn comment(body: &str) -> CommentSnapshot { + CommentSnapshot { + node_id: "comment".into(), + database_id: "99".into(), + repository: "owner/repository".into(), + work_item_number: 1, + author: None, + created_at: "2026-01-01T00:00:00Z".into(), + updated_at: "2026-01-01T00:00:00Z".into(), + last_edited_at: None, + body: Some(body.into()), + minimized: false, + minimized_reason: None, + pinned: false, + deleted: false, + } +} +pub(super) fn processed(o: &context::CanonicalObservation) -> CanonicalObjectState { + 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(), + } +} +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(); + let previous = basis + .objects + .iter() + .find(|o| o.node_id == root.work_item_node_id) + .map_or(root.work_item_state.clone(), |o| o.lifecycle.clone()); + let scope = crate::producer::reconcile::ReconcileScope { + work_item_node_id: root.work_item_node_id.clone(), + work_item_kind: root.work_item_kind, + work_item_number: root.work_item_number, + work_item_state: root.work_item_state.clone(), + previous_work_item_state: previous, + repository_node_id: root.repository_node_id.clone(), + repository: root.repository.clone(), + }; + crate::producer::reconcile::reconcile_observations( + &f.store, + github, + &f.config, + &scope, + basis, + &observations, + ) + .unwrap() +} +fn thread_state(current: &mut CanonicalContext, resolved: bool) { + let CanonicalContext::PullRequest(pr) = current else { unreachable!() }; + pr.review_threads[0].resolved = resolved; + pr.review_threads[0].resolved_by = + resolved.then(|| context::Actor { node_id: "human".into(), login: "human".into() }); +} +fn restorations(f: &Fixture) -> i64 { + f.db() + .query_row( + "SELECT count(*) FROM events WHERE detail='unresolved' AND kind='wake'", + [], + |r| r.get(0), + ) + .unwrap() +} +fn raw_restoration(id: &str, target: &str, number: u64) -> IngressEvent { + let mut event = continuous_collaboration::revision(id, ""); + event.identity = ChangeIdentity::Occurrence; + event.event_name = "pull_request_review_thread".into(); + event.action = Some("unresolved".into()); + event.detail = Some("unresolved"); + event.work_item_node_id = Some(target.into()); + event.work_item_kind = Some("pr"); + event.work_item_number = Some(number); + event.object_node_id = Some("thread".into()); + event.object_version = None; + event.object_digest = None; + event.visible_body = None; + event.cross_surface_invalidation = false; + event.kind = EventKind::Wake; + event +} + +#[test] +fn contract_versionless_restoration_is_a_new_occurrence_not_a_redelivery() { + let f = Fixture::new(false); + for (id, resolved) in + [("first-unresolve", false), ("then-resolve", true), ("second-unresolve", false)] + { + let mut event = raw_restoration(id, "item", 1); + if resolved { + event.kind = EventKind::Invalidate; + event.action = Some("resolved".into()); + event.detail = Some("resolved"); + } + let admitted = f.store.ingest_event(event.clone(), policy()).unwrap(); + assert!(admitted.event_id.is_some(), "distinct restoration was collapsed: {id}"); + assert!(f.store.ingest_event(event, policy()).unwrap().duplicate); + } + assert_eq!(restorations(&f), 2); + assert!( + f.store.runtime_status().unwrap().agent_groups.is_empty(), + "restoration must not activate a dormant responsibility" + ); +} + +#[tokio::test] +async fn contract_hidden_comment_edit_is_not_new_work_during_reconciliation() { + let f = Fixture::new(true); + let (github, http) = issue_context_server("Accepted design").await; + let locator = "owner/repository#1".parse().unwrap(); + let mut current = + CanonicalContext::Issue(context::materialize_issue(&github, &locator, 100).await.unwrap()); + let CanonicalContext::Issue(issue) = &mut current else { unreachable!() }; + issue.comments = vec![comment("Visible agreement")]; + let prior = context::canonical_observations(¤t).iter().map(processed).collect(); + f.store + .commit_observation(ObservationCommit { + basis: f.store.begin_observation("item".into()).unwrap(), + current: prior, + events: vec![], + policy: policy(), + }) + .unwrap(); + let CanonicalContext::Issue(issue) = &mut current else { unreachable!() }; + issue.comments[0].updated_at = "2026-01-01T00:00:01Z".into(); + issue.comments[0].last_edited_at = Some("2026-01-01T00:00:01Z".into()); + issue.comments[0].body = Some("Visible agreement".into()); + assert_eq!( + observe(&f, &github, ¤t), + 0, + "a hidden/timestamp-only edit cannot create work" + ); + assert!(f.store.runtime_status().unwrap().batches.is_empty()); + let CanonicalContext::Issue(issue) = &mut current else { unreachable!() }; + issue.comments[0].body = Some("Visible revised agreement".into()); + issue.comments[0].updated_at = "2026-01-01T00:00:02Z".into(); + assert_eq!(observe(&f, &github, ¤t), 1); + assert_eq!(observe(&f, &github, ¤t), 0); + http.abort(); +} + +#[tokio::test] +async fn contract_restoration_cycles_survive_polling_and_share_a_real_ingress_receipt() { + let f = Fixture::new(false); + let (github, http) = issue_context_server("Accepted design").await; + let locator = "owner/repository#9".parse().unwrap(); + let mut current = CanonicalContext::PullRequest( + context::materialize_pull_request(&github, &locator, 100).await.unwrap(), + ); + let CanonicalContext::PullRequest(pr) = &mut current else { unreachable!() }; + let mut discussion = comment("Review discussion"); + discussion.work_item_number = 9; + pr.review_threads = vec![ReviewThreadSnapshot { + node_id: "thread".into(), + path: "file.rs".into(), + line: Some(10), + start_line: None, + resolved: true, + resolved_by: None, + collapsed: false, + outdated: false, + comments: vec![discussion], + }]; + observe(&f, &github, ¤t); + for resolved in [false, true, false] { + thread_state(&mut current, resolved); + assert_eq!(observe(&f, &github, ¤t), 1); + assert_eq!(observe(&f, &github, ¤t), 0); + } + assert_eq!(restorations(&f), 2, "a repeated state is a new transition after resolution"); + thread_state(&mut current, true); + observe(&f, &github, ¤t); + let event = raw_restoration("webhook-restoration", "pr", 9); + let accepted = f.store.ingest_event(event.clone(), policy()).unwrap().event_id.unwrap(); + thread_state(&mut current, false); + assert_eq!( + observe(&f, &github, ¤t), + 0, + "canonical polling must reuse the already admitted restoration" + ); + assert_eq!(restorations(&f), 3); + let linked:String=f.db().query_row("SELECT effect_event_id FROM deliveries WHERE event_name='pull_request_review_thread' AND action='unresolved' ORDER BY rowid DESC LIMIT 1",[],|r|r.get(0)).unwrap(); + assert_eq!(linked, accepted); + assert!(f.store.ingest_event(event, policy()).unwrap().duplicate); + // Reusing an admitted restoration cannot swallow an independent position edit. + thread_state(&mut current, true); + observe(&f, &github, ¤t); + f.store.ingest_event(raw_restoration("another-restoration", "pr", 9), policy()).unwrap(); + let basis = f.store.begin_observation("pr".into()).unwrap(); + let expected = basis.objects.clone(); + thread_state(&mut current, false); + let CanonicalContext::PullRequest(pr) = &mut current else { unreachable!() }; + pr.review_threads[0].path = "different-file.rs".into(); + let mut invalid = raw_restoration("reconcile-invalid-reuse", "pr", 9); + invalid.identity = ChangeIdentity::ObservedTransition; + assert!( + f.store + .commit_observation(ObservationCommit { + basis, + current: context::canonical_observations(¤t).iter().map(processed).collect(), + events: vec![invalid], + policy: policy() + }) + .unwrap_err() + .to_string() + .contains( + "state receipt cannot acknowledge changed metadata or an unproven transition" + ) + ); + assert_eq!(f.store.begin_observation("pr".into()).unwrap().objects, expected); + http.abort(); +} diff --git a/src/writer/tests/status_convergence.rs b/src/writer/tests/status_convergence.rs new file mode 100644 index 00000000..35dfb45a --- /dev/null +++ b/src/writer/tests/status_convergence.rs @@ -0,0 +1,237 @@ +//! Actual public comment convergence through `StoreActor` -> one outbox -> HTTP. +use super::*; +const FAULT: &str = "> **Braid Operational Status · `issue-codex`**\n\n**Provider session unavailable**\n\nThe old generation is blocked."; +fn failure(f: &Fixture) { + f.store.enqueue_assignment_operational_status("assignment".into(), FAULT.into()).unwrap(); +} +fn replacement(f: &Fixture, state: &str) { + f.db().execute_batch("UPDATE assignments SET lifecycle='blocked'; UPDATE agent_instances SET lifecycle='blocked'; UPDATE provider_sessions SET lifecycle='blocked'; INSERT INTO assignments VALUES('replacement','item',2,'active','2002-01-01T00:00:00Z',NULL); INSERT INTO agent_instances(agent_id,assignment_id,profile_id,profile_revision,role,lifecycle) SELECT 'agent2','replacement',profile_id,profile_revision,role,'idle' FROM agent_instances WHERE agent_id='agent'; INSERT INTO provider_sessions(session_id,agent_id,provider_kind,provider_session_id,context_revision,instruction_revision,lifecycle,started_at) VALUES('session2','agent2','codex','provider2','new','new','idle','2002-01-01T00:00:00Z');").unwrap(); + let ps = match state { + "completed" | "starting" | "failed" => "idle", + other => other, + }; + f.db() + .execute("UPDATE provider_sessions SET lifecycle=?1 WHERE session_id='session2'", [ps]) + .unwrap(); + f.db().execute("INSERT INTO turns(turn_id,session_id,provider_turn_id,context_revision,trigger_kind,lifecycle,started_at,ended_at) VALUES('turn2','session2',?1,'new','wake',?2,'2002-01-01T00:00:00Z','2002-01-01T00:00:01Z')",rusqlite::params![(state!="starting").then_some("accepted-native-turn"),state]).unwrap(); +} +fn public_body(remote: &Arc>) -> String { + remote.lock().unwrap().comments[0]["body"].as_str().unwrap().into() +} +fn kind(f: &Fixture) -> String { + f.db().query_row("SELECT projection_kind FROM status_comments", [], |r| r.get(0)).unwrap() +} + +#[tokio::test] +async fn a_confirmed_new_generation_updates_the_original_comment_and_never_unblocks_the_old_one() { + let f = Fixture::new(true); + let remote = Arc::new(Mutex::new(Remote::default())); + let (github, http) = server(remote.clone(), true).await; + failure(&f); + f.drain(github.clone()).await; + assert!(public_body(&remote).contains("所属 generation:**1**")); + replacement(&f, "completed"); + // A new actor has no in-memory transition notification: durable state alone + // must repair a previously published failure after restart. + let fresh = + StoreActor::start(f.config.runtime.database().into(), f.config.runtime.backups().into()) + .unwrap(); + let owner = + fresh.acquire_runtime_lease("runtime".into(), "fresh-publisher".into(), 3600).unwrap(); + crate::outbox::drain_one_write( + &fresh, + &HashMap::from([("owner/repository".into(), github.clone())]), + &f.config, + &owner, + ) + .await; + fresh.release_runtime_lease(owner).unwrap(); + drop(fresh); + let body = public_body(&remote); + assert!(body.contains("已由 generation 2 接替")); + assert!(body.contains("2002-01-01T00:00:01Z")); + assert!(body.contains("不代表代码已修改")); + assert_eq!(kind(&f), "superseded"); + assert_eq!( + f.db() + .query_row( + "SELECT lifecycle FROM assignments WHERE assignment_id='assignment'", + [], + |r| r.get::<_, String>(0) + ) + .unwrap(), + "blocked" + ); + failure(&f); + f.drain(github.clone()).await; + f.drain(github).await; + assert_eq!( + public_body(&remote), + body, + "late old-generation failure must not regress the public projection" + ); + assert_eq!(remote.lock().unwrap().writes, 2); + assert_eq!(remote.lock().unwrap().comments.len(), 1); + http.abort(); +} + +#[tokio::test] +async fn merely_created_failed_unknown_or_blocked_successors_do_not_claim_recovery() { + for state in ["starting", "failed", "unknown", "blocked"] { + let f = Fixture::new(true); + let remote = Arc::new(Mutex::new(Remote::default())); + let (github, http) = server(remote.clone(), true).await; + failure(&f); + f.drain(github.clone()).await; + let before = public_body(&remote); + replacement(&f, state); + f.drain(github).await; + assert_eq!(public_body(&remote), before, "{state}"); + assert_eq!(kind(&f), "failure"); + assert_eq!(remote.lock().unwrap().writes, 1); + http.abort(); + } +} + +#[tokio::test] +async fn an_in_flight_create_keeps_its_remote_identity_when_the_desired_status_changes() { + let f = Fixture::new(true); + let remote = Arc::new(Mutex::new(Remote::default())); + let (github, http) = server(remote.clone(), true).await; + failure(&f); + let owner = f.store.acquire_runtime_lease("runtime".into(), "publisher".into(), 3600).unwrap(); + let old = f.store.claim_github_write(owner.clone()).unwrap().unwrap(); + let created = github.create_issue_comment(1, &old.content).await.unwrap(); + replacement(&f, "completed"); + assert!( + f.store.claim_github_write(owner.clone()).unwrap().is_none(), + "new create waits for its unresolved predecessor" + ); + f.store + .finish_github_write( + old, + "applied", + Some(created.id.to_string()), + Some(created.node_id), + None, + ) + .unwrap(); + f.store.release_runtime_lease(owner).unwrap(); + f.drain(github).await; + assert_eq!(remote.lock().unwrap().comments.len(), 1); + assert!(public_body(&remote).contains("已由 generation 2 接替")); + assert_eq!( + f.db() + .query_row("SELECT lifecycle FROM status_comments", [], |r| r.get::<_, String>(0)) + .unwrap(), + "applied" + ); + http.abort(); +} + +#[tokio::test] +async fn an_uncertain_create_is_recovered_before_publishing_the_new_projection() { + let f = Fixture::new(true); + let remote = Arc::new(Mutex::new(Remote::default())); + let (github, http) = server(remote.clone(), true).await; + failure(&f); + let owner = f.store.acquire_runtime_lease("runtime".into(), "publisher".into(), 3600).unwrap(); + let old = f.store.claim_github_write(owner.clone()).unwrap().unwrap(); + github.create_issue_comment(1, &old.content).await.unwrap(); // Remote applied; local ACK was lost. + f.store.release_runtime_lease(owner).unwrap(); + f.store.recover_writes().unwrap(); + replacement(&f, "completed"); + f.drain(github.clone()).await; + assert_eq!( + remote.lock().unwrap().writes, + 1, + "recovery observes the first create, not another POST" + ); + f.drain(github).await; + assert_eq!(remote.lock().unwrap().comments.len(), 1); + assert_eq!(remote.lock().unwrap().writes, 2); + assert!(public_body(&remote).contains("已由 generation 2 接替")); + http.abort(); +} + +#[tokio::test] +async fn ambiguous_create_blocks_only_that_comments_successor_after_restart() { + let f = Fixture::new(true); + let remote = Arc::new(Mutex::new(Remote::default())); + let (github, http) = server(remote.clone(), true).await; + failure(&f); + let owner = f.store.acquire_runtime_lease("runtime".into(), "publisher".into(), 3600).unwrap(); + let old = f.store.claim_github_write(owner.clone()).unwrap().unwrap(); + github.create_issue_comment(1, &old.content).await.unwrap(); + { + let mut state = remote.lock().unwrap(); + let mut twin = state.comments[0].clone(); + twin["id"] = json!(100); + twin["node_id"] = json!("other-comment"); + state.comments.push(twin); + } + 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!( + f.db() + .query_row( + "SELECT lifecycle FROM github_write_outbox WHERE intent_id=?1", + [old.intent_id], + |r| r.get::<_, String>(0) + ) + .unwrap(), + "ambiguous" + ); + f.store + .enqueue_assignment_operational_status("replacement".into(), "new generation fault".into()) + .unwrap(); + f.drain(github.clone()).await; + f.drain(github).await; + let state = remote.lock().unwrap(); + assert_eq!( + state.writes, 2, + "one original POST and one independent generation's POST; no third POST or guessed PATCH" + ); + assert_eq!(state.comments.len(), 3); + assert!(state.comments[2]["body"].as_str().unwrap().contains("new generation fault")); + assert_eq!( + f.db() + .query_row( + "SELECT lifecycle FROM status_comments WHERE assignment_generation=1", + [], + |r| r.get::<_, String>(0) + ) + .unwrap(), + "ambiguous" + ); + http.abort(); +} + +#[tokio::test] +async fn repeated_identical_failures_do_not_orphan_receipts_and_a_new_cycle_can_publish_again() { + let f = Fixture::new(true); + let remote = Arc::new(Mutex::new(Remote::default())); + let (github, http) = server(remote.clone(), true).await; + for (outcome, stamp) in [ + ("failed", "2001-01-01T00:00:00Z"), + ("completed", "2002-01-01T00:00:00Z"), + ("failed", "2003-01-01T00:00:00Z"), + ("completed", "2004-01-01T00:00:00Z"), + ] { + f.db().execute("UPDATE turns SET lifecycle=?1,provider_turn_id='accepted',ended_at=?2 WHERE turn_id='turn'",rusqlite::params![outcome,stamp]).unwrap(); + if outcome == "failed" { + f.store.enqueue_operational_status("turn".into(), FAULT.into()).unwrap(); + f.store.enqueue_operational_status("turn".into(), FAULT.into()).unwrap(); + } + f.drain(github.clone()).await; + assert_eq!(kind(&f), if outcome == "failed" { "failure" } else { "recovered" }); + } + assert_eq!(remote.lock().unwrap().comments.len(), 1); + assert_eq!(remote.lock().unwrap().writes, 4); + assert!(public_body(&remote).contains("2004-01-01T00:00:00Z")); + assert_eq!(f.db().query_row("SELECT count(*) FROM status_comments s JOIN github_write_outbox o ON o.intent_id=s.write_intent_id WHERE o.lifecycle='applied' AND s.lifecycle='applied'",[],|r|r.get::<_,i64>(0)).unwrap(),1); + http.abort(); +} diff --git a/src/writer/tests/turn_start.rs b/src/writer/tests/turn_start.rs new file mode 100644 index 00000000..2f7946a2 --- /dev/null +++ b/src/writer/tests/turn_start.rs @@ -0,0 +1,195 @@ +//! Real provider adapter + dispatch start boundary + production publication source resolver. +use super::*; +use crate::{ + agent_session::{AgentSession, SessionError, SessionEvent, TurnOutcome}, + provider::{ + AgentProvider, ProviderAgentSession, ProviderError, ProviderNotification, ProviderSession, + ProviderTurn, + }, +}; +use tokio::sync::{Notify, broadcast}; + +#[derive(Clone, Copy)] +enum Reply { + Success, + LateError, + Deferred, + Unknown, +} +struct DelayedProvider { + notifications: broadcast::Sender, + release: Notify, + reply: Reply, +} +impl DelayedProvider { + fn new(reply: Reply) -> Arc { + Arc::new(Self { notifications: broadcast::channel(32).0, release: Notify::new(), reply }) + } +} +#[async_trait::async_trait] +impl AgentProvider for DelayedProvider { + fn subscribe(&self) -> broadcast::Receiver { + self.notifications.subscribe() + } + async fn closed(&self) { + std::future::pending::<()>().await; + } + async fn start_session(&self, _: &Profile, _: &str) -> Result { + Ok(ProviderSession { thread_id: "provider".into() }) + } + async fn inject_context(&self, _: &str, _: &str) -> Result<(), ProviderError> { + Ok(()) + } + async fn resume_session( + &self, + _: &str, + _: &Profile, + _: &str, + ) -> Result { + unreachable!("test never resumes") + } + async fn start_turn( + &self, + _: &str, + _: &Profile, + _: &str, + ) -> Result { + match self.reply { + Reply::Deferred => return Err(ProviderError::Deferred("busy".into())), + Reply::Unknown => return Err(ProviderError::Unknown("response lost".into())), + _ => {} + } + self.notifications + .send(ProviderNotification::TurnStarted { + thread_id: "provider".into(), + turn_id: "native-current".into(), + }) + .unwrap(); + self.release.notified().await; + match self.reply { + Reply::Success => Ok(ProviderTurn { turn_id: "native-current".into() }), + _ => Err(ProviderError::Unknown("late RPC failure".into())), + } + } + async fn steer(&self, _: &str, _: &str, _: &str) -> Result<(), ProviderError> { + unreachable!("test never steers") + } + async fn interrupt(&self, _: &str, _: &str) -> Result<(), ProviderError> { + unreachable!("test never interrupts") + } +} + +#[tokio::test] +async fn native_start_authorizes_current_publication_before_start_rpc_response() { + 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() + .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 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 + } +} + +#[tokio::test] +async fn unobserved_deferred_and_unknown_start_never_authorize_publication() { + for reply in [Reply::Deferred, Reply::Unknown] { + let fixture = Fixture::new(true); + fixture.db().execute("UPDATE turns SET lifecycle='starting'", []).unwrap(); + let provider = DelayedProvider::new(reply); + let session = ProviderAgentSession::start( + provider, + fixture.config.profile("issue-codex").unwrap().clone(), + String::new(), + None, + ) + .await + .unwrap(); + let mut events = session.events(); + let result = crate::group::turn_start::send_and_observe( + &fixture.store, + "turn", + "session", + session.as_ref(), + &mut events, + "event references".into(), + ) + .await; + match reply { + Reply::Deferred => assert!(result.unwrap().is_none()), + Reply::Unknown => assert!(matches!(result, Err(SessionError::Unknown(_)))), + _ => unreachable!(), + } + assert!( + resolve_source(&fixture.config, None, &Invocation::Agent("turn".into())) + .unwrap_err() + .to_string() + .contains("publication source was invalidated or superseded") + ); + assert!(matches!(events.try_recv(), Err(broadcast::error::TryRecvError::Empty))); + } +} diff --git a/tasks/github-pi-reacceptance/application-results.md b/tasks/github-pi-reacceptance/application-results.md new file mode 100644 index 00000000..8182e975 --- /dev/null +++ b/tasks/github-pi-reacceptance/application-results.md @@ -0,0 +1,11 @@ +# 独立应用实际操作 + +首候选为模型实际提交并推送的 `33b12109b69c8a9b4ec6c15c602c4e6c51c6d388`。主 Agent 从固定 Git archive 运行应用,不修改业务代码;原始 17 次 CLI 操作、参数、退出码、stdout/stderr 与操作前后存储 SHA 位于 `/Volumes/WorkSSD/Development/braid-gh-pi-reacceptance/independent-app/raw/first-candidate-operations.json`。这是生成应用验收,不是 Braid/Factory 设施测试。 + +正常创建三条记录取得不同 ID,跨进程 list 保持这三次创建顺序;中文、空格、引号、换行保存在正文中。archive 后默认列表排除该条,list --all 显示其 archived=true,原正文保留;第二次 archive 返回 already-archived 且存储字节不变。无效 ID 返回6,不存在的合法 ID 返回7,均未改数据。损坏 JSON 的 list/add/archive 均返回4及具体行错误,错误根结构的三种命令均返回5及 root not a JSON object,原始数据 SHA 完全不变。 + +创建顺序边界未满足。另建合法 NDJSON 数据副本,保留上述三个实际记录的物理顺序、ID和正文,仅将 created_at 依次设为3000、2000、1000;list --all 实际倒序返回,原文件未改。源码 cmd_list 的 (created_at,id) 排序及 README 的时钟回拨限制与观察一致。这没有修改宿主时钟,不声称实际发生过系统时钟回拨;它证明应用以时间戳排序替代存储创建顺序,需按冻结需求及公开澄清修正。本候选不能整体判通过,原件保留,已由运行 Owner 通过正常业务协作反馈。 + +后续:等待模型接受关联 Issue 变更及修正后的固定候选,独立核对重复标题、list --all、创建顺序边界和既有拒写/幂等行为。 + +修正候选 `95fa210c8e5692be1af8c89fc8e2f128ff1a8911` 的顺序 16 次实际 CLI 操作完成于用户要求降载后,用时约0.43秒,没有模型调用或并发。原合法时间戳逆序副本现保持物理记录顺序;同标题新增两条返回唯一ID,默认list和list --all分别显示未归档与完整归档状态;中文换行正文持久化、重复归档字节不变、无效/不存在ID错误6/7,以及损坏JSON/坏根list/add/archive错误4/5和原数据字节不变全部观察通过。原始操作位于 `independent-app/raw/second-candidate-operations.json`。第二候选应用要求可采用,首候选失败及模型/tmp纪律偏差不抵销。 diff --git a/tasks/github-pi-reacceptance/autonomous-mode-design.md b/tasks/github-pi-reacceptance/autonomous-mode-design.md new file mode 100644 index 00000000..a7ff0584 --- /dev/null +++ b/tasks/github-pi-reacceptance/autonomous-mode-design.md @@ -0,0 +1,37 @@ +# Root 任务驱动的有限运行模式(提案) + +2026-10-12。用户指出 Factory26 保留了有价值的运行方式:仅输入 root Issue 或 description,由 Agent 自行拆分 Issue、创建 PR 并实现;希望在内建平台上恢复为与 serve 并列的模式。本文记录最初提案及实施收敛;用户随后“是的,开始。”批准实现。当前正式合同归产品/TDD/run指南;没有启动新模型运行。平台仍是与 GitHub 同层的 minimal GitHub;模式属于 Harness。 + +建议入口暂名 `braid run`。`serve` 持续服务协作事件;`run` 围绕一个明确 root 完成一次有限工作,输出交付与执行收尾事实。首次实现接入 built-in,不为 GitHub 添加尚未证明的自主运行能力;该限制属于适配范围,不将 built-in 等同于 run。Web Console 继续属于整个 Braid,调用共享运行控制服务并展示 run 身份、root、工作范围和结果,不启动 CLI 子进程。 + +## 输入与工作协议 + +已经配置仓库、provider、角色和模型后,业务输入可为一个现有 root Issue,或 description 文件。后者经平台幂等创建 root;恢复同一 run 不再次创建。配置和执行身份仍需提供,不能宣称仅凭描述就能获得仓库和凭据。 + +root Agent 负责需求理解、拆分、依赖、分派、成果采用和整体整合。子 Issue 维护各自设计,PR Agent 实现、验证并发布真实 Git 候选。Harness 不按需求编号拆任务,不机械猜测业务依赖,也不把模型打印完成作为产品验收。root 用专用协调角色,不全局改变 serve 下所有 Issue Agent 的职责。通用平台协议归 Braid,业务规则和模型配方归调用方角色材料;技能仍按文件发现,不内联正文。 + +平台持久记录父子 Issue 关系和 Issue↔PR 关系。run 只持有 root、纳入的对象和交付 ref 等执行身份,复用平台工作图,不建立第二套任务数据库。依赖理由、当前共享决定和必要交接材料留在对象正文及 Git 中;仅确有机械门控需求时再增加结构化依赖。 + +子项终态、候选发布和整合变化必须作为有行动价值的事件回到 root,使其消费成果并继续;不用不断提示 root、频繁新建模型轮次或强制公开回复来维持进展。未清楚交接所需材料时,父正文不自动成为子项全量上下文。 + +## 生命周期和权限 + +建议区分 completed、blocked、failed、stopped。安静是观察状态,不是 completed:root 未交付但暂时无可执行工作时继续等待;只有明确缺少前提、需要外部决定或无法恢复的具体原因才报告 blocked,不能仅据静默结束。有效工作、事件、写入或物理停止仍在途时不能宣告终态。 + +completed 至少需要 root 的明确交付声明、范围内义务已交付或明确取消、有确切交付 commit,以及没有未处理的调度/写入/合并意图,最终原生执行和 writer 收尾可确认。此条件仅证明 Agent 声明与交付流程完成,业务是否满足需求仍由实际应用验收判断。root 提前关闭而仍有子任务不算完成,不擅自丢弃进度或把剩余子任务强制关闭;按运行关闭协议停止本轮执行并报告未完义务。停止确认不完整时不得把 stopped 写成 confirmed。 + +root 的创建、指派、成果采用权限限定于本 run 的后代及关联 PR;子项不能操作仓库其它任务。需要补现有 writer grant 的工作范围,而不能向 Agent 发 human/admin 身份或绕开撤销机制。保留“关闭对象即使写者失效”的保证,root 关闭是最后完成声明,不延长关闭后的写权限;提前关闭且义务未完则 blocked,由显式外部重开后接续。自动采用候选限于明确交付 ref,是否允许合并及目标由运行配置声明;run 不隐含向用户默认分支合并。 + +实施校正:并发由 Harness 对实际在途 Braid turns 统一准入,root/子 Issue/PR 均计入,默认 2;空闲物理会话及 Pi 内部 subagents/PBB 不在该参数范围。物理总 cap2 会使 root+idle 子Issue阻断PR,原生 idle close又会撤权、停止后代并被现有恢复立即重建,因此本轮不承诺总物理资源上限或新增自动驱逐。不能只在提示里要求少用 Agent,具体并发在运行配方中冻结。模型 fallback、费用方式和停止策略也沿用调用方明确配置。 + +## 当前实现依据与缺口 + +- `src/runtime/builtin.rs::serve_managed` 仅 external stop 或 worker 结束退出,没有 root 完成条件;复用其启动、事件、健康和 shutdown 机制,而不是再写一个独立 provider 调度器。 +- `src/platform/objects/commands.rs::ObjectCommand` 已有 createIssue/createPR/assign/publish/merge,命令与请求回执可复用。 +- `src/platform/schema.sql::local_links` 只有 Issue↔PR,没有父子 Issue。`src/platform/grants.rs::validate` 只覆盖 own item 或直接 Issue↔PR,无法直接给 root 完整子项协调能力。 +- `src/group/provider.rs` 当前 Issue 默认讨论设计,需在 run 中显式选择协调职责;不要将自主拆分指令导入 serve 的通用 Issue 角色。 +- 现有 Console Harness snapshot 主要展示执行表,不能替代 run 的义务范围与终态合同。平台对象和 Harness 执行事实应分别读取,OTLP 不作为完成权威。 + +内部 advisor 已定向核对 Factory `sources/braid/src/local.rs:264`:旧实现区分 quiescent、delivery_complete、execution_settled;`variants/pi-braid/run.py:301` 还检查 root CLOSED。可迁回的是有限运行闭环和动态指派协议。variant 的基础 PR、最终整合 PR、Web 应用目录、模型、ARC 发布、专门 reviewer 等是调用方配方,不作为 Braid run 固定阶段。平台创建子项时应原子建立父子关系,不能靠事后任意关联将无关任务纳入 root 权限;旧 local 整体实现不直接覆盖独立 Braid。 + +验收应从单一 description 实际触发 root,自主产生至少两个可分工子项与真实 PR,展示依赖成果消费、最终整合和确定交付 commit;另实际操作空闲未完成、提前 root close、停止、接续和幂等输入。保留应用验收及所有错误,禁止设施测试或换名自检。当前不运行此实验,也不把先前手动 Issue→PR 验收当作本模式已经通过。 diff --git a/tasks/github-pi-reacceptance/autonomous-mode-results.md b/tasks/github-pi-reacceptance/autonomous-mode-results.md new file mode 100644 index 00000000..ad1fed99 --- /dev/null +++ b/tasks/github-pi-reacceptance/autonomous-mode-results.md @@ -0,0 +1,36 @@ +# Root 自主运行实现与无模型操作 + +2026-10-12,用户以“是的,开始。”授权实现。`braid run` 已接入既有 Harness,CLI 和 Console 接收 root Issue 或 description;built-in 仍是独立 minimal GitHub。当前交付是源码实现、编译和真实无模型操作,尚未取得模型自主拆分及交付资格。 + +运行合同已归入 [run 指南](../../docs/user-manual/run.md)、[产品范围](../../docs/10-prd/scope.md)和[生命周期](../../docs/20-product-tdd/lifecycle.md)。平台 schema 3 原子保存父子关系并绑定顶层 root/run/client/ref;Harness schema 7 保存独立运行身份和结果,工作图没有复制到 Harness。实际角色、调度、writer 撤销与物理执行继续复用现有机制。 + +所有操作产物位于 `/Volumes/WorkSSD/Development/braid-run-operations-20261012`。第一次构建 SHA 为 `e252b4cc4836bd13a7fafa7668c4ab51d9e6713c71c165945db3cb92e6fd2986`;修正常停止显示后为 `a5df9afcac5a4735930eac5d7946f51891990db5357556f539c41fa3b9a04ac7`;含 Run ID 接续表单的 binary SHA 为 `de3fb010cf02647893392a087f9f9c01cc6f1054a2b3c465c4e7f1d145c70f8e`;最终含成员交接通知及旧请求兼容修复的 SHA 为 `2c20f70610a40563333d09d6c1abbc584ea08164f4742e5bf253ef4ef5d35015`。构建均 `cargo build --locked --offline -j1`,最终 17.17 秒无 warning;第一轮 check 的两个接线/SQLite 类型错误已修复,原工具回执保留。JS 通过实际 Node `--check`,没有编写或运行设施测试、自检或模拟 provider。 + +## 已观察的产品操作 + +| 结果 | 实际事实与证据 | +| --- | --- | +| 平台范围操作通过 | root 建子 Issue、编辑子项、建真实 PR、实现者发布、root 合并到独立交付 ref;手动资料候选,不冒充模型业务生成。`raw/platform-operations.json`。 | +| 幂等与拒绝通过 | 相同 child request 回读同对象;改变 payload 返回409。写无关对象、跨范围 Link、Agent 改运行授权、不同run/client接管、向 main 建 scoped PR、root 发布他人 PR均被拒绝并保留原错。 | +| 关闭屏障通过 | root 在子项仍开放时关闭,旧 root grant 随后写子项返回409;新 grant被拒绝。pending absent revoke生成撤权tombstone,旧epoch激活被拒;撤权回执不当作物理停止证据。 | +| 输入与恢复通过 | 空首行 description正确创建root#6,正文保持原文;专用 `BRAID_RUN_OPERATION_KEY` 未设置,实际恢复机会后 blocked,stopConfirmed=true。相同run接续仍root#6,没有重复创建。`raw/console-operations.json`、`raw/no-key-root-scope.json`。 | +| CLI结果与输入绑定通过 | closed root CLI保留blocked JSON并非零退出;相同输入回读;同ID改输入拒绝,未覆盖原结果。`raw/cli-operations.json`。 | +| 控制与监督恢复通过 | transport-only + run 返回400;控制请求回读/换payload拒绝;无模型轮次的运行中公开stop返回stopped且stopConfirmed=true。Console正常退出后重开保留run/停止事实,Harness snapshot读取run实际ledger。`raw/stop-control.json`、`raw/normal-stop-fixed.json`。不能称为活动模型停止验收。 | +| Console实际界面通过 | Helium浏览器实际观察run选择、输入和独立终态;发现缺可编辑RunID后补齐。最终“填入最近运行参数”预填stop-control、原description、ref、并发2,不把原description变为生成root#7,不自动提交。两临时tab已关闭。`raw/final-observations.json`。 | +| 既有平台迁移通过 | 从真实schema2原件只读backup到独立副本,再用公开platform serve实际升级3。items2/comments5/links1/events10/merges0/receipts14前后保留,自动备份生成,repository API200;原件SHA及Git状态不变。`schema-upgrade/before.json`、`after.json`。 | + +实际成员交接操作确认:同一 profile 的子项写讨论和设计,祖先收到仅含对象与变化类型的 Wake;root 自己写子项不产生回流循环。`raw/child-outcome-events.json`。这些是隔离数据集中的公开 API 开发操作,没有启动原生会话,不将该现场作为后续付费模型的恢复检查点。 + +旧 schema2 的真实已应用 CreateIssue 请求在初版升级后重试返回409:新增可选字段序列化为 null,改变了回执请求哈希。现省略默认空字段,并同步平台与客户端 grant 序列化,不修改旧回执或添加哈希回退。最终 binary 使用原 requestId 和原 payload 重试返回200/applied,仍是旧 Issue#1,items2/receipts14未增加;原数据库 SHA 不变。`schema-upgrade/legacy-object-before.json`、`legacy-object-after.json`。没有可重构的旧 grant 请求,未将对象回执证明扩大为旧 grant RPC 实跑。 + +实际操作也纠正了一项静态猜测:旧祖先grant能否穿透注册子root。公开注册返回409 `run root cannot be a child Issue`,该对象并未注册,后续写入属于普通serve子项合同,不能记为run越权失败。保留顶层root及父子不可重绑不变量,撤回推测性新增检查。`raw/ancestor-before-fix.json` 的文件名来自当时假设,原记录未覆盖。 + +正常stop曾被Console映射为错误;已把RunResult.reason与失败字段分开,重开及实际再stop确认runtime.error=null、health.last_error=null,同时保留reason。浏览器实际发现的接续表单缺口也已修复。两者都保留前版事实和后版证据。 + +最终runtime stopped/error=null/stopConfirmed=true,当前run ledger sessions0/turns0;Collector122记录、37批次,采集不用于完成判定。没有加载供应商凭据或启动Pi原生推理。Console和临时migration平台均正常Ctrl-C exit0,26418/18482/18492/18481无监听,未控制其它进程。开发侧资料候选合并为 `fee44043b636b30bef54dfd280f0e917565a22bd`,仅用于平台实际操作,不是业务应用验收。 + +## 尚未取得的资格 + +真实模型从单一description自主拆分、子任务交接、并行准入、PR实现及completed整轮尚未运行;活动模型停止、真实授权响应丢失竞态、Context reset和原生历史接续未在此模式实跑。原GitHub+Pi验收的失败及未执行项仍独立保留。本轮不以无模型HTTP/CLI操作或编译宣称自主运行验收通过。 + +maxConcurrency仅限制在途Braid turns,默认2;不保证空闲物理会话、Pi内部subagents/background或宿主总资源有界。当前root必须顶层,首版run仅builtin;跨机器完整崩溃恢复及外部GitHub自主模式没有新增承诺。 diff --git a/tasks/github-pi-reacceptance/input/design-change.md b/tasks/github-pi-reacceptance/input/design-change.md new file mode 100644 index 00000000..071c7c7b --- /dev/null +++ b/tasks/github-pi-reacceptance/input/design-change.md @@ -0,0 +1,4 @@ +首次候选形成后,通过关联 Issue 正文接受以下变更,不修改执行器或私有状态: + +允许同标题笔记并存,ID仍唯一。增加 `list --all`,按创建顺序显示所有笔记和归档状态; +默认 list 仍只列未归档。先前中文/引号/换行、持久化、幂等与错误不覆盖数据的约束保留。 diff --git a/tasks/github-pi-reacceptance/input/issue.md b/tasks/github-pi-reacceptance/input/issue.md new file mode 100644 index 00000000..9fcf93bd --- /dev/null +++ b/tasks/github-pi-reacceptance/input/issue.md @@ -0,0 +1,30 @@ +# GitHub + Pi 原生插件验收:离线笔记 CLI + +请维护本 Issue 中的接受设计,随后通过关联 PR 实现离线笔记 CLI。业务范围仅 +`e2e-notes/20261011-github-pi-native-v2/`,不修改仓库其它文件、旧应用或历史运行。 +没有业务基线答案;只使用 Python 标准库,不依赖外部网络服务。 + +`python3 notes.py --store <路径> add <标题> <正文>` 新增笔记并返回稳定唯一 ID; +`list` 按创建顺序显示未归档笔记;`archive ` 归档且保留正文,重复操作不产生 +新记录。跨进程仍可读取。标题和正文支持中文、空格、引号和换行。无效 ID、损坏 +JSON 或错误根结构必须给具体错误和非零退出码,不能覆盖原数据。README 说明实际 +命令与数据存储位置。 + +Issue Agent 只负责设计、实施请求与工作记忆,用 braid gh pr ensure 建立关联 Draft PR; +PR Agent 在专属工作树完成真实实现、Git 提交、push 和应用操作,自己更新 PR 工作记忆。 +不要自行合并。禁止开发基础设施测试和模拟器;验证来自真实调用应用。 + +本轮使用 Pi 的 subagents 与 background 插件协作:至少一次同步子 Agent 形成可用 +实现建议,至少一次异步子 Agent 完成实际实现或应用操作并取得结果;子 Agent 与根 +角色全部只能使用 minimax/MiniMax-M3,不得改模型、自动fallback或使用宿主其它登录。 +后台有限命令使用 PBB 并保留正确handle、原始退出状态及输出,在交付之前消费结果。 +需要常驻服务时明确标为service,不能把有限工作伪装service;所有副作用由所属执行管理。 +不要为演示重试制造假服务错误。请保持公开讨论简洁,不发表内部推理。 + +所有应用数据、材料、日志、临时文件和缓存只放当前 WorkSSD 工作目录或 +`/Volumes/WorkSSD/Development/braid-gh-pi-reacceptance/`;不能写 `/tmp`、系统盘、 +其它仓库或旧运行,也不靠 TMPDIR 代替实际路径核对。凭据只交 SDK,不能写入应用、 +评论或证据文件。正常 GitHub 操作用当前 BRAID_CONFIG,不寻找旧实例。 + +可见标记:BRAID_VISIBLE_GH_PI_NATIVE_V2_20261011。 + diff --git a/tasks/github-pi-reacceptance/oar-integration-design.md b/tasks/github-pi-reacceptance/oar-integration-design.md new file mode 100644 index 00000000..c45fa4d0 --- /dev/null +++ b/tasks/github-pi-reacceptance/oar-integration-design.md @@ -0,0 +1,49 @@ +# Open Agent Runtime 接入调查 + +2026-10-12。调查基线为 Braid `50f25c87` 与 OAR `7a981975f7aa5beb3fa33b54eecfcc3b471e349e`(包版本 0.59.1)。用户随后批准“先来收敛 pi 交付”,当前实施范围为本文建议的直接 Pi 公共 SDK 路线;没有批准接入 OAR 或付费模型验收。下文 OAR 证据来自只读源码调查,没有运行 OAR。 + +## 要解决的问题 + +Braid 当前不仅适配 Pi RPC,还维护了一份经修改的 Pi 和插件发行材料。`native/pi/install.mjs` 对六个锁定包逐项应用补丁;未选择的插件同样安装并被修改。补丁哈希和发行 manifest 能保留身份,却不能减少跟随上游 bundle、内部接口和插件行为的维护成本。 + +补丁不能按文件整体判定去留。Pi 核心补丁混合了会话错误、retry、settled 和 compaction 行为,以及 Braid 的执行身份、后台服务交接、材料发现和停止协议。插件补丁也同时包含通用正确性修复及 Braid 运行策略。交付目标应是明确维护边界、使用公开接口、减少私有依赖变体,而不是减少可见的 patch 文件数量。 + +## OAR 的实际边界 + +OAR 是 ESM Node >=24 的库,提供统一的 session/control/records 契约。普通 Pi runtime 内嵌 Pi SDK 1.1.0;不是对 Pi CLI/RPC 的包装,也没有独立 Pi runtime 子进程。原生 `agent_settled.aborted` 已有权威取消事实;OAR 的 accepted 控制回执与 turn 终态分开,原始 SDK 事件仍可读。这与 Braid 的输入受理、终态和 OTLP 事实边界相容。 + +普通 Pi 的环境、主题、HTTP dispatcher 等存在宿主进程全局状态。`SessionOptions.env` 影响 Bash 子进程及 stdio MCP,不是 provider key/base URL 配置渠道。模型和凭据使用原生 agent-dir/model 配置;`OAR_PI_AGENT_DIR` 是进程级设置。故若采用,应为每次 Braid 物理执行启动独立 Node bridge,不把不同 Profile 的 Pi session 混在一个长期共享 Node 宿主。 + +OAR 的 dispose 会先 abort 活动会话,再执行 extension shutdown hooks;hooks 超过十秒只报告 warning 并释放 session,不能证明扩展代码及外部后台进程全部退出。Braid 的出生身份登记、停止核对、后台结果交接和关闭失败阻断替换仍需明确的 Braid 所有权实现。简单使用进程组也不能覆盖已观察到的 detached 服务。 + +材料接线目前有具体缺口。OAR 的 Pi opener 默认加载原生资源,公共 SessionOptions 不提供通用 ResourceLoader、extension factory 或工具注册接口;文档也明确没有通用 allowlist/extension callback。进程隔离能隔离配置,却不自动证明选定 skills、角色及插件白名单,也不能自动将 Bash/subagents/background 的启动路径接入 managed owner。必须核实原生 settings 能否完整实现这些合同,或取得上游公开接线点;不能在引入 OAR 后再修改它的内部 opener 作为常规方案。 + +Pi Durable 是另一条执行架构:宿主提供已经打开的 Harness、storage、models 和环境,OAR 借用它。dispose 仅停止观察,不关闭 Harness 或运行。它不能替换当前 Pi CLI 插件及 Braid 物理执行关闭协议;本次不建议借机改成这套持久执行架构。 + +## 建议的职责和补丁归属 + +| 职责 | 目标归属 | 迁移条件 | +| --- | --- | --- | +| 原生 session、model/effort 生效、prompt/steer/abort、事件翻译 | 优先评估 OAR provider adapter | 公开接口可承载 Braid 材料与工具接线;无须复制或补丁修改 OAR 内部实现。 | +| GitHub/内建平台、Issue/PR 协作、调度、writer 权限、持久输入、Console/OTLP | Braid Rust core | 接入 runtime 不改变这些职责。 | +| 独立执行目录、进程登记、后台作业/服务、owned-stop、关闭失败阻断 | Braid integration 与执行监督 | Bash、subagent 和后台启动必须实际接入;abort accepted 或 dispose 返回不是停止证明。 | +| Profile 选定 skills/native_template、模型配方和材料 digest | Braid 配置及快照 | 默认资源发现不得绕过选定材料;启动和恢复核对实际生效值。 | +| 通用 Pi retry/error/settled/compaction 修复 | Pi 上游或已修复版本 | 逐项核对 SDK 1.1.0 的具体行为,不能由取消 flag 推断其余问题已修复。 | +| subagents/PBB 结果 drain、owner 丢失、重试及错误路径 | 插件上游;Braid 接线独立维护 | 明确区分插件正确性和 Braid 策略;原生角色不是 Braid Issue/PR 成员。 | +| Context7 错误正文、pi-ai 连接错误 retry | 对应上游或明确的可选集成 | 可选工具不再成为基础 Pi runtime 的必带补丁。 | + +拟采用的边界是 `Braid Rust provider → 每次物理执行的 Node bridge → OAR → 原生 runtime`。bridge 只传递控制、原始 records 和身份,不引入第二套协作调度或 Agent loop。Braid 自有生命周期仍是交付合同。OAR 的会话内存队列不替代 Braid 持久 inbox;每次 resume 的 OAR seq 从零开始,记录必须包含物理执行身份和 native session ID。 + +## 实施前必须收敛的判断 + +当前推荐先升级 Pi SDK、收敛现有补丁,暂缓把 OAR 加入交付依赖。advisor 独立判断与本轮源码证据一致:OAR 当前公共接线缺口会迫使 Braid 在另一层维护私有变体,收益尚不足以抵消成本。先直接使用 Pi 公共 SDK 拆出 Braid integration,逐项删除已有原生支持的补丁,并上游通用修复。这条较小路线以消除 dist 修改为目标;插件缺陷尚未上游时仍明确保留补丁身份,不能承诺升级即全部删除。 + +OAR 的采用闸门是一个公开接口组合能同时实现隔离配置、选定资源、扩展/工具接线和进程所有权。以后确认可行,再接入一个 Pi provider 候选,并逐项退役等价职责的旧实现;迁移期间保留旧冻结发行用于对照和恢复,不作为永久并列 provider。若任一项只能通过修改 OAR 私有源码实现,就继续暂缓采用。未实际验证 Pi settings 是否足以补齐缺口,不将其作为已成立前提。 + +后续实现应先形成锁定 Node/依赖及许可证材料、通过编译和公开实际操作核对,再按用户批准的范围执行真实 MiniMax。必要实际反馈包括:显式资源选择、根/子模型一致、同步和异步子任务结果、有限后台结果及服务交接、活动取消、异常关闭及 detached 后代清理、历史恢复和材料漂移阻断、原始事件及终态完整到达 OTLP。不得新增设施测试、自检或包 smoke;旧 ARC 失败结论不因 runtime 替换自动改变。 + +## 证据入口 + +- Braid:`native/pi/install.mjs`、`patches.json`、`patches/`、`managed.mjs`、`process-owner.mjs`、`src/agent_session.rs`、`src/provider/pi.rs`、`pi_runtime.rs` 与 `src/profile_materials.rs`。 +- OAR:[Pi 契约](https://github.com/botiverse/oar/blob/7a981975f7aa5beb3fa33b54eecfcc3b471e349e/docs/runtimes/pi.md)、[opener](https://github.com/botiverse/oar/blob/7a981975f7aa5beb3fa33b54eecfcc3b471e349e/packages/oar/src/runtimes/pi/open.ts)、[shutdown](https://github.com/botiverse/oar/blob/7a981975f7aa5beb3fa33b54eecfcc3b471e349e/packages/oar/src/runtimes/pi/lifecycle.ts)、[Pi Durable](https://github.com/botiverse/oar/blob/7a981975f7aa5beb3fa33b54eecfcc3b471e349e/docs/runtimes/pi-durable.md)、[宿主职责](https://github.com/botiverse/oar/blob/7a981975f7aa5beb3fa33b54eecfcc3b471e349e/docs/design/system.md)。 +- 只读上游源码保存于 `/Volumes/WorkSSD/Development/braid-runtime-evaluation-20261012/oar`。主 Agent 拥有接入调查,profile_feedback_owner 完成现有补丁与生命周期责任梳理,autonomous_mode_advisor 提供路线判断。没有改变原验收资格或启动任何旧运行。 diff --git a/tasks/github-pi-reacceptance/packet.md b/tasks/github-pi-reacceptance/packet.md new file mode 100644 index 00000000..ca8c2e3b --- /dev/null +++ b/tasks/github-pi-reacceptance/packet.md @@ -0,0 +1,123 @@ +# Braid 真实模型验收 + +## 当前实施:Pi 交付收敛 + +2026-10-12 实施授权:用户回复“是的,我们先来收敛 pi 交付”。按调查建议升级锁定 Pi、使用公开 SDK 收敛核心补丁,将 Braid 专属接线保留在自有模块,并让可选插件安装及补丁只随明确选择发生。不引入 OAR/Pi Durable,不启动付费模型或旧验收,不编写/运行测试、自检、包 smoke;旧发行及原证据保留。profile_feedback_owner稳定拥有核心SDK/RPC与执行接线,pi_plugin_feedback稳定拥有插件补丁收敛,root拥有安装/锁定材料、Rust消费、正式文档、编译和无模型实际操作。证据、安装、cache/HOME/temp全部位于WorkSSD的braid-pi-delivery-20261012;按低并发执行。当前是实施阶段,下列只读调查的授权限制为历史,不再阻止上述源码修改。 + +前置调查来自用户:“考虑接入一下 Open Agent Runtime ? (而且我看到 native/pi 下面一堆 patch,这在 braid 这样要交付出去的软件似乎不合适)”。按 botiverse/oar 完成源码核对;当时没有修改运行时。保留现运行合同和全部历史资格事实,不联系独立Codex聊天。 + +判断依据是实际能力与维护责任:统一会话、模型/推理/材料选择、原始事件、turn终态、后台结果交接、owned停止、恢复身份及可交付安装。调查产物位于 WorkSSD 的 braid-runtime-evaluation-20261012;源码与上游spec支持结论,不能以支持Pi或dispose方法存在替代能力等价证明。 + +调查已完成,详见 [oar-integration-design.md](oar-integration-design.md)。核对 OAR 0.59.1/7a981975,普通Pi内嵌SDK1.1.0,能接替部分会话事件/取消适配,但公开接口缺少通用资源、扩展及工具接线;dispose不提供外部后代停止证明。profile_feedback_owner完成六包补丁职责梳理,advisor独立建议先升级Pi、将Braid策略移至自有integration,暂缓直接采用OAR,避免新增私有发行版。OAR作为后续provider层候选,以公开接口能承载选定材料及受控工具执行为采用闸门;不采用Pi Durable改变宿主职责。直接Pi路线已获实施授权。 + +Pi 交付收敛已完成,详见 [pi-delivery.md](pi-delivery.md)。SDK1.1.0公开host、标准RPC/print复用、自有owned控制、模型/RPC Bash登记、长任务文件和终态错误门控已落地,旧296行综合核心补丁删除;阈值补丁收敛至60行,连接重置及所选插件内部补丁明确保留。基础实际安装124包,双插件134包,未选网络插件均不安装。两份最终发行完成公开new_session/state/commands/Bash/history/yield/stop,SDK实际1.1.0、minimax/MiniMax-M3 medium、零模型turn、退出0;出生登记、停止及离线cleanup均确定。Rust fmt/check/Clippy-Dwarnings/build通过;doctor的Pi两项通过,整体唯一剩余前提为Collector未启动。最初编译、可选数组及手工启动marker错误均保留,未放宽检查。代码及正式说明已提交,候选由Git记录与冻结manifest共同定位;当前远端PR148实际为OPEN/非Draft,保持用户当前状态,不自动改回Draft。所有本轮进程已退出,没有模型、测试或监听服务;旧真实模型资格结论不变。 + +## 当前反哺:协作技能与 Agent Profile + +2026-10-12 CI 修复:用户指出“ci / rust 没有通过”。PR148 run38231440673 在 Rust1.93 Clippy `-D warnings` 失败,共26条诊断;此前仅构建通过不等于CI通过。profile_feedback_owner稳定处理材料/Pi三个模块,其余由主Agent处理。已完成等价写法修正、Pi材料装配提取和复杂元组命名;Serde回调引用及内聚事务/生命周期函数采用有说明的函数级lint例外,workflow与全局规则保持。Rust1.93本地 fmt/check/clippy 全部通过,check3.61s、Clippy14.46s,单任务离线执行,无设施测试或模型调用。原始失败日志及复验原件保留在本轮证据目录 raw/ci-rust-failed.log、ci-check-final.log、ci-clippy-final.log;提交后须以PR当前HEAD的GitHub rust回执判定CI结果,不以本地通过替代。 + +2026-10-12 用户授权:“好的。现在我们继续反哺。braid-collaboration 这个技能也反哺到 braid 项目中(但是不和 braid 软件本身绑定);此外我记得 factory26 似乎有不少关于 braid agent profile 的改进。”本轮迁移独立技能材料,并核对、融合 Profile 的通用能力与恢复身份合同;不启动新付费模型、旧验收或修改生成应用。技能不自动安装、编译嵌入、默认启用或成为运行依赖。Factory preset、variant 和实验配方保留原归属。 + +负责人:collaboration_skill_owner 拥有 skills/ 独立材料迁移;profile_feedback_owner 拥有 Profile 差异调查及后续实现;autonomous_mode_advisor 提供材料声明与恢复边界判断;主 Agent 拥有采用、正式文档、单任务编译、实际公开操作及提交。仅使用内部 Agent 协作,不联系独立 Codex 聊天。所有产物位于 WorkSSD;不编写或运行设施测试、自检、包 smoke。 + +已确认普通 Profile catalog 查看、当前支持的 Issue/默认 PR 指派、模型与推理唯一来源、上下文预算已经迁入,不扩展其它 Profile driver。独立协作技能与四份 reference 已迁移,包内引用不依赖完整源码 checkout。Profile 新增 Pi skills/native_template 的实际选择、独立持久会话 home、材料快照及有效身份,接入现有 revision 不兼容阻断与 OTLP 身份诊断;没有空 tools/MCP 管理器或默认技能绑定。 + +本轮完成,结果见 [profile-feedback.md](profile-feedback.md)。最终单任务离线构建27.88s无warning通过;公开无模型指派进入idle/0 turn,同路径材料变化改变digest/revision,Collector保存真实get_commands、Profile材料回执及会话身份的原始88条records和20批protobuf。旧Collector未启动导致的导出失败、中间编译错误保留。全部本轮服务、所属进程与监听已退出;没有模型调用。原生角色实际调用、真实模型历史恢复及材料变化后的实际恢复阻断仍未验。源码候选 f82ee88 已提交并推送到既有 Draft PR148,PR 保持 Draft;旧 ARC/GitHub 资格结论不变。 + +## 已完成的 ARC-bench lite 验收 + +当前状态:2026-10-12,真实 MiniMax `braid run` 的 ARC-bench lite 两题验收及收尾已完成,结论不通过。Keep 程序 completed/停止已确认,公开 Lite 本地复现6/32;BookStack blocked/停止已确认,失败生成快照2/34。合计8/66(12.12%)。两题均只有root真实执行,没有成员分工;另有/tmp写入和按名称停止请求的纪律失败。官网两次HTTP403未创建submission/run,不存在官网分数。 + +完整事实见 [run-arc-lite.md](run-arc-lite.md),独立评分原件位于 `/Volumes/WorkSSD/Development/braid-run-arc-lite-20261012/evaluation/`。本轮全部进程、应用服务及远端评估容器已退出,相关端口关闭;无在途操作,不自动重新生成、补发布/合并或按评测反馈修应用。已修复有限指派吞输入、登录shell阻塞及共享ledger写事务;SQLite修复仅有编译和公开绑定操作反馈,没有进入本轮模型配方。 + +下一步由用户决定root职责与交接、执行纪律及应用交互的整改范围。本packet仍保留Braid反哺的未完成资格入口;原GitHub+Pi第二候选应用复验通过,但剩余生命周期资格仍未完成。以下保留原范围与历史事实,不启动旧GitHub运行。 + +原 GitHub+Pi 授权:用户指示:“好的,现在继续重新验收,先仅验收 GitHub + Pi;全部用 minimax 模型。”沿用已知 `xiaoland/braid-poc-test` 和官方 MiniMax `minimax-m3`(wire MiniMax-M3),凭据只从 ../agentic26/.env 加载,不输出或复制。真实官方按量调用获授权,无人为费用停止线,无备用模型。 + +目标:判断反哺后的独立 Braid 能否在 GitHub 中完成真实 Issue→PR 实现与更新,并在真实 Pi/subagents/background 运行下交接结果及停止,不以编译替代。候选源码 `1394319`,冻结binary与锁定Pi1.0.2材料SHA;只启用subagents/background,不装可选网络工具。所有根/子模型必须 minimax/MiniMax-M3,显式角色材料与模型路由禁止ambient fallback。 + +范围:新的需求标识 `20261011-github-pi-native-v2`,应用目录 e2e-notes/20261011-github-pi-native-v2/。新的source/ledger/worktree/native/OTLP/Console位于 /Volumes/WorkSSD/Development/braid-gh-pi-reacceptance。创建专用Issue/评论/PR/分支、需求空白基线、实际push与明确采纳合并;临时App webhook变更先保存原始配置,结束恢复并真实核对,不写掩码secret。不接管旧对象,不改其它仓库或旧运行状态,不运行Factory/内建/赛事/设施测试。所有Mac缓存、HOME、临时、SDK材料与工具写入都在WorkSSD。 + +主Agent维护判据、版本采用与独立应用实际操作;native_local_env稳定拥有本轮配置、真实GitHub网络、Console/Harness控制、模型运行及过程诊断/必要修复/恢复,结果写run.md。原Pi plugin/ownership owner处理其模块的必要原生修复,中央Cargo由主Agent负责。仅使用内部agents工具,绝不联系独立Codex聊天;所有owner不得代写业务应用、改私有ledger或注入伪事件。 + +完成判据:真实官方事件→Issue当前Context→两角色实际MiniMax生成;PR专属worktree真实diff及发布;关联设计变更落到实现;普通讨论quiet/coalesce与自身echo不循环;空闲/活动Context reset、关闭/重开/合并终态;公开停止、原生exactowned后代清理、重启不重复已完成输入;真实子Agent至少同步及异步各一次,PBB有限结果/service分别取证,保留错误/取消/自然重试发生与否,不合成HTTP错误来制造retry;sample=1.0的OTLP/Console保留对象/session/turn/usage/错误,停止后历史仍可读。应用独立固定commit实际操作符合需求,开发Agent不写答案。 + +基础需求沿用笔记CLI:add标题正文返回稳定唯一ID,list按创建顺序只列未归档,archive幂等且原正文保留;中文、引号、换行、跨进程持久化、无效ID/损坏JSON具体非零错误且不覆盖数据。关联设计变更新增重复标题与list --all状态。实现角色用真实subagent协作和PBB后台应用操作;有限义务结束后才交付。另通过正常协作消息安排实际活动停止与恢复,服务与有限任务的owned停止分别取证。 + +每项pass/fail/unavailable/not-run明确区分,无纠正黄金路径单列,设施修复保留原失败与新版本;不放宽验收判据。普通GitHub App trustedmention能力按实际模式声明,不冒称nativeassignment。未发生自然retry即not-run,不把其余成功宣称retry已验。此轮为GitHub/Pi源码候选资格,不宣称taggedrelease、Codex、内建或三次完整campaign。 + +已冻结主binary SHA-256 `f015b77bdc03ee44f42dcec6c62879abd04f72e2b68254d6a37725a977fcac95`,源码完整身份 `13943195dfb9b162e99fda6187fd0f238d0afdae`,WorkSSD可用493GiB。初始与设计变更正文位于input/,本轮业务目录基线为空;仓库其它历史应用不属于允许输入,角色禁止读取/复用,不声称GitHub仓库整树为空。 + +下一步:owner只读核对现有权限、原App入口与无活动运行,准备准确新路径、模型材料与模型唯一性,记录冻结身份后启动Console/tunnel/Harness并创建真实需求。主Agent独立采用产物和证据,收尾恢复外部入口、停止进程、汇总消耗与剩余边界。 + +准备现场:初次 selected subagents/background manifest `4a87c7d96b0b0fe59cf53fc78815f23c96dd0aaf9b3d48f730e3d477030fdc9b` 字节核验通过,但实际 doctor 暴露复制 Homebrew Node 的 `@rpath/libnode.147.dylib` 缺失,未进入付费模型阶段。pi_plugin_feedback owner 修安装器的独立 Node 交付,保留原安装及 dyld 错误;新目录 pi-attempt2 完成真实启动后重新冻结。公开 CA 保存在 WorkSSD,操作脚本保持 TLS 验证。两 profile 与两个显式子角色均固定 minimax/MiniMax-M3,内建角色禁用、fallback 为空,最终实际调用仍需从原生与 OTLP 证据核对。 + +主 Agent 独立浏览器现场:Helium 中打开 http://127.0.0.1:26318/,Console 显示 stopped、Provider 禁用、Generation 无、Ready 否,已接收记录/批次/资源来源均为 0;GitHub 接入启停与观测可用,未声明内建平台。根只读 UI,runtime commands 由 native_local_env 唯一写。需求空基线为远端 main `4c49fff0a2e5c778c57dc627ef3c2ded06f10d75`,仅本轮 REQUIREMENTS;首次 push 虽成功,原 Keychain helper failedstore -60006 保留,后续采用显式 gh helper。 + +安装修复已本地提交 `89505d964314cd6f65b928543f33c59536fde386`,正式阶段源码以此冻结。Rust 未改,binary 字节/编译来源保持前述 `f015...` / `1394319`。新 native/pi-attempt2 manifest SHA `d1fd63d831d2753a21c0b22e59df5bddaee0ca3fbc04cf48485f76edff2bb9bc`;安装 owner 实际运行 Node24.15.0 / Pi1.0.2 并核对只依赖系统库,原 Homebrew dyld 失败保留。证据 `raw/native-pi-attempt2.json`,该材料随后仍须真实 doctor 与模型调用。未 push Braid 源码。 + +正式 Harness 已通过公开 runtime command 接受启动:request `37dfdca1-7ec5-447a-81cb-09ed421c9058`,generation `01a12b2e-9f58-7eb3-8ead-8831089c8657`。根独立浏览器看到 running/Ready 是、采样 1、同 generation,Collector 9 records/3 batches/接收错误 0,尚无 Session 或原生内容;这是服务启动证据,不是模型成功。实际 doctor 各项 Pass 只证明版本/材料/配置,不冒称完整 live provider 能力。GitHub App selected repositories 已实际只读核对二项,owner 接着正常创建 Issue 及 trusted mention。 + +本轮真实 Issue 为 https://github.com/xiaoland/braid-poc-test/issues/39,创建于 2026-10-11T13:38:21Z。临时 App webhook PATCH 与 readback HTTP200,目标含 /webhook,原始配置仍保留;opened 的实际 delivery 由网络 owner 接续核对。 + +付费前实际原生配置读取结束:`raw/subagent-model-config-fixed2.json` 的 rootSDKModel 与两个角色 resolved/candidates 均为唯一 minimax/MiniMax-M3,fallbackModels=null,六个内建角色 disabled,extension/runtime errors 为空;该无推理操作 exit0/owned cleanup stopped。user frontmatter 的 [] 与 false 都曾被轻量 scalar-list parser 当候选字符串,原错误原件保留,最终删除该字段走 primary-only 路径。此证据不替代正式根/子调用模型元数据。owner 已开始通过真实 Issue39 trusted comment 触发付费流程。 + +正式真实调用:trusted comment https://github.com/xiaoland/braid-poc-test/issues/39#issuecomment-6109679664 于 13:46:05Z 接受;Issue assignment active,provider session `2026-10-11T13-46-23-912Z_01a12b36-f328-759e-aff8-47bf69ad3b2d`,Braid session `01a12b36-fe19-7c82-af4c-932a82bf9737`,turn `01a12b36-fe1d-76d2-8436-92e374d3d815` 13:46:27Z running。owner 定向实际 model_change 与五条已返回 assistant metadata 均 minimax/MiniMax-M3,无模型 error,有实际 token;`raw/issue-first-native-model.json` 保留。SDK cost0 不是费用证明。 + +实际异步 design child `f6c0cac1...` 完成并由 wait 消费,原生子会话和 attemptedModels 均唯一 M3(`raw/issue-child-model-stage1.json`)。Issue模型发布实施请求 `6109703753` 并正常 ensure 建立 https://github.com/xiaoland/braid-poc-test/pull/40,head braid/implementation-request-6109703753,已附本任务 artifact。首设计曾将 async+wait 误称同步,并提出跳过坏行、created_at/id 排序及附加flag,偏离冻结要求;owner 于13:49:32Z正常公开澄清 `6109710304`,保留原评论,不代写答案。本轮无纠正黄金路径不能计通过,后续纠正后行为单列。 + +首候选 `33b12109b69c8a9b4ec6c15c602c4e6c51c6d388` 已实际 push。根独立 17 次应用 CLI 操作记录与判定归 application-results.md:持久化/幂等/具体错误拒写通过,合法记录副本的创建顺序边界失败,正常反馈给模型修正;不修改业务代码。运行 owner 定向原生记录另确认模型 cat 到 /tmp/evidence-comment.md、实际 body-file 发布后自己 rm,当前文件不存在;原始 call/result 保留,WorkSSD-only 本轮 fail 不抵销。模型按进程名 kill/pkill 自己的服务也不作为公开 exact-owned stop 通过。后续仍通过公开控制独立验收停止与恢复。 + +用户最新资源约束:"电脑性能好像开始有点问题,你悠着点"。立即降低并发,不新增模型/子任务/关闭重开触发;second candidate `95fa210c8e5692be1af8c89fc8e2f128ff1a8911` 已冻结。根关闭本任务新建 Console/PR 浏览器 tab,唯一性能 ps/vm_stat 采样见本轮工具记录:run bin/braid PID24988约84.5%CPU,另有外部高负载;不据单次采样断定全部原因、不控制其它任务。native owner 按已授权公开 stop 收尾 Harness、保留 owned receipt;根后续应用操作仅顺序小批执行,生命周期下一阶段资源允许后再推进。 + +降载实际收尾:公开 stop request `c77a14da-e1e1-4bf6-8f38-1845c70ac0ff` 已 applied/state stopped/error null,同原 generation,当前 registered_sessions=0;两个当前execution的exact execution-stop(scope execution)固定coverage均stopped(`raw/final-owned-stop-receipts.json`)。该停止前两个会话idle,不能冒称新一次active stop。App webhook三字段与baseline实际PATCH/GET200一致。stop后唯一ConsolePID24988 CPU采样0.0%/RSS18784KB,前为62.7%/33904KB;控制后旧二execution及reset关闭证据保留,无名称pkill补证。Console/tunnel进程最终结束由owner接着确认。 + +静态追因定位周期全材料哈希:GroupWorker idle每2s → SessionManager.check → PiSessions.check重复runtime::load约28640files。独立advisor建议去掉周期扫描,无缓存;所有start/resume/懒spawn(325/388/427)仍进入实际启动前runtime::load,doctor完整校验保留。源修复 `d9f52d9` 已本地提交,单任务offline cargo check7.3s和diffcheck通过。正式已结束运行仍使用旧binary;该修复没有部署或重跑CPU,不能把停止后0%归功于新源码。 + +接续入口:候选95fa固定archive及本轮全部ledger/native/observations原件均保留,配置与材料身份见run.md。恢复前采用readiness修复并以受控单任务方式构建/实际核对;新运行身份和可能恢复输入先冻结。关闭/重开、重启不重复输入、活动公开stop以及最终merge尚未跑;自然限流后恢复已观察,精确retry-intent合同证据不足,不人为制造失败。用户“悠着点”优先于启动更多轮次,当前不新增模型。任务范围未被宣告完整结束,保留此唯一active packet供低负载接续。 + +最终进程收尾已确认:Console/tunnel正常Ctrl-C exit0,ports26318/18380/18381无LISTEN、knownPID24988/65289/65611均不存在,`raw/final-port-process-checks.json`;无在途操作/新增模型。metadata轻量汇总10物理JSONL(3root+7child、排除transcript、sessionID+entryID去重重复0),root/child actualmodels均唯一M3;recorded totalTokens15193632,input515803/output161755/cacheRead14516074/cacheWrite0/reasoning22833,SDKcost0非免费,账单未取得。自然HTTP429 TPM rate limit(1039)实际出现两次(14:07:52/55),随后同turncompleted;owner定向核对已存原生JSONL,没有显式retry/willRetry/auto_retry条目;自然429后同turn恢复已观察,精确retry-intent事件合同证据不足,不判完整通过或完全未运行。没有新增探针/模型。 + +2026-10-12 新增设计前沿:用户要求考虑将 Factory 的 root Issue/description 自主拆分、建 PR 和实现闭环保留为与 serve 并列模式,built-in 仍是同层 minimal GitHub。当前只调查/设计,不改源码、不启动运行。提案见 [autonomous-mode-design.md](autonomous-mode-design.md),主 Agent拥有边界与采用,内部 autonomous_mode_advisor 只读核对旧运行生命周期。旧验收剩余义务保留,不被新模式提案覆盖。已创建 PR148;本提案尚未提交或推送。下一步收敛有限运行的权限、终态及资源准入合同,交用户评估。 + +advisor 返回已采用:Factory 旧 local 区分 quiescent/delivery_complete/execution_settled,variant 又检查 root CLOSED;静默不能自动完成或判 blocked。根关闭继续撤销 writer,提前关闭且子项未完返回 blocked,需外部明确重开;父子关系应在创建子项时原子建立,范围不能通过任意链接扩大。基础/最终整合 PR 等固定阶段留给调用方配方,不作为 run 必经路径。提案已同步,当前只有任务材料改动,无源码/运行/远端变更。 + +2026-10-12 开工:用户明确“是的,开始。”授权上述自主 run 设计的必要源码、文档和验证。当前实现不启动新付费模型,也不改 GitHub 对象。分工:run_platform_owner 拥有 platform 与对象 CLI 的父子关系、范围读取、grant、结果回流;run_runtime_owner 拥有 run 入口、执行身份/范围、有限终态、调度准入及恢复;run_console_owner 拥有 Console 共享控制及展示;主 Agent 拥有跨边界采用、文档、单任务构建与真实无模型平台操作。禁止设施测试/自检,所有产物存 WorkSSD。 + +当前技术选择:每 run 使用独立 Harness ledger/config 和 run_id,平台仍持有唯一工作图,避免 serve 旧 assignment 在恢复时进入新 run。run 接续复用本 run ledger,不能只过滤新事件却恢复无关旧 session。实施发现总物理 session 限2会因 root+idle子Issue占槽阻断PR;该并发合同由advisor核对原生恢复后收敛,暂不宣称 active-turn 限制等于总物理资源限制。下一步完成平台/运行/Console共享接口,串行编译并以实际对象操作验父子权限及幂等,保留真实模型资格缺口。 + +实施收敛:统一 active-turn 准入默认2,原描述“实际资源占用”收窄为在途 Braid轮次;不承诺 idle/Pi内部子任务资源上限,不引入自动闲置驱逐。平台注册root绑定run_id、已存在的Harness client_id及delivery_ref,拒绝其它run/ledger/serve误接管;Root关闭后不新开模型收口,正常执行关闭屏障。发现pending grant网络回执与root关闭竞态,正在平台普通revoke以具体generation/tombstone收敛,不能重新mint已关闭root权限,也不能将撤权当物理停止证明。第二轮单任务cargo check8.71s通过,待最后接口落地后构建实际操作binary。 + +本轮实现收尾见 [autonomous-mode-results.md](autonomous-mode-results.md):真实无模型平台/CLI/Console操作、旧平台副本升级及浏览器表单核对通过,所有本轮服务退出。源码和正式文档已完成;必要失败保持原件。旧GitHub+Pi剩余资格及新run真实模型资格未转写为通过,保留这一packet供后续资格工作。 + +最终收尾:单任务离线构建17.17s、JS语法与diff检查通过。旧平台真实回执重试的409兼容缺陷已修复,原请求公开API回读200/applied且无重复对象;成员讨论/设计回流也完成实际操作。最终证据与限定见 autonomous-mode-results.md,所有本轮监听已关闭。下一步提交本轮改动并更新现有Draft PR#148;不将编译及无模型操作扩大为真实自主模型验收。 + +## 真实 run:ARC-bench lite + +2026-10-12 用户授权:“执行真实 minimax 的 braid run 整轮验收,验收题目就复用 arc-bench lite。”本轮两题 keep、bookstack 按顺序从公开需求生成,独立 Braid e7615e9 / binary2c20f706 驱动内建平台 run;全部根/子模型固定 minimax/MiniMax-M3,官方凭据仅从 agentic26/.env 加载,不输出。maxConcurrency2,不设人为费用停止线,不复用旧对象/ledger或手动API操作现场。所有Mac产物位于 /Volumes/WorkSSD/Development/braid-run-arc-lite-20261012,保留版本、输入哈希、原生会话、对象/PR、最终交付commit、OTLP及实际费用证据。 + +完成判据:实际模型从单一root/description建立自主工作图并以真实PR候选交付;平台范围闭环及执行停止确认,结构化RunResult可追溯。每题交付立即冻结commit与应用包,独立实际验收及在可用入口取得官网self_funded非正式评分;不将 completed、上传或运行启动视为业务通过。生成只读取公开requirements/引用资产,不读取评测实现;隐藏评分不反馈仍生成中的Agent。设施可修复缺陷属于闭环,保持失败原件并修复后继续;不运行设施测试。 + +负责人:native_local_env继续拥有运行装配、真实执行及恢复;arc_lite_evaluation_owner拥有冻结后独立评分与应用操作;主Agent采用证据、协调修复及报告。当前正在冻结配置、公开输入和评估接口,近期官网403作为待核实外部前提,不能先判零分或宣称评分可用。两题业务产物不得由开发Agent代写。支持记录 run-arc-lite.md、运行目录及evaluation/。 + +启动事实:Keep公开CLI run-id keep-20261012、root#1、delivery refs/heads/run/keep-20261012、并发2;PID65775、工具session28195由native_local_env拥有停止/恢复。平台18582、OTLP-only Console26518,sample1.0。最终binary身份及原始公开需求SHA见raw/frozen-identities.json,运行记录见run-arc-lite.md。BookStack尚未启动;WSL固定镜像评估已准备,不把CLI启动受理视为模型/交付完成。 + +真实启动发现设施缺陷:Keep仅握手MiniMax-M3,无prompt/原生JSONL。ConfigureRoot产生invalidate随后Assign,Context reset applied但continuation=false,初始wake已consumed,root静默。保留keep/raw/startup-otlp.json及原运行,由run_runtime_owner支持调度/reset根因修复,native_local_env持续拥有控制和部署;不以人工评论激活遮盖初始输入丢失。此时没有有效生成或业务评分,BookStack未启动。 + +修复候选861a15d:finite Issue Assign保留真实wake,materialize后先处理已有idle Context reset;serve指派仍仅建立idle会话。单任务离线构建15.09s通过,binary d8a3342f58ed4887b5040ac179997bc95742c8e89265a263172f2e8d644482c6。native_local_env已获新候选部署入口,以新root/run v2验证真实指派触发推理,旧run保持stopped故障证据不可原生接续。 + +修复实际采用:Keep新run keep-20261012-v2/root2已出现真实prompt→agent_start→MiniMax-M3 assistant/tool执行,keep/raw/v2-startup-evidence.json保留,不以握手代替推理。尚未交付;BookStack未启动。 + +第二次设施故障:真实M3普通bash经PBB覆盖入口使用bash -lc;host /etc/profile的Nix source在open阻塞,连pwd/ls含60s也超时。sample和原始调用保留,无子Issue/PR/业务产物。公开stop达到15s截止后typed blocked/stopConfirmedfalse,较晚OS空快照未改写原结果。修复9e62be1仅自动PBB shell-c及原生wrapper清BASH_ENV/ENV,明确环境不依赖宿主profile。一次旧冻结公开offlinecleanup于北京时间14:44成功取得exactexecution完整scope收据,keep/raw/later-offline-cleanup.json;原deadline失败保留。新immutable材料准备后使用新root/run重新资格,不称完整恢复。已记v2实际M3 usage totalTokens558899,记录不等于供应商账单。 + +新原生材料native/pi-nonlogin-v3 manifest989a1d3fb888b1cbb3404d8e597a88147295b5da1626c24ddae0b5c8e17fcc18,source9e62be1;实际SDK公开PBB echo/pwd/ls约200ms正常且execution停止完整。operator一次缺detached被75拒绝原件保留,没有改错误为pass。doctor新材料通过,Keep新run keep-20261012-v3/ref refs/heads/run/keep-20261012-v3已启动,binary861a/d8a保持;旧config/result未覆盖,待真实自然工具与工作图。 + +Keep v3真实语义进展:普通M3 bash自然调用约200ms成功;root先在自身worktree写应用/做健康及CRUD操作,随后自行创建并指派后代Issue4设计架构、5backend、6frontend、7integration/delivery。scope3为父子范围权威(Item读取不包含parent字段,不将字段缺失误判无关系);v3-scope-stage6.json保留。此时无PR、delivery仍需求基线b59c,不能把图形成判为成果采用/交付;需真实成员turn、PR候选和最终闭环。 + +Keep v3整轮程序已exit0:completed/root3/deliveryab8c1d763f7790722938a5e0834ae2523711b6d3/stopConfirmedtrue,原stdout与scope-stage9。实际merge9→e7c8、12→ea5e、13→ab8c,未决命令/merge空、exactowned四收据均stopped/fullcoverage。自主分工不通过:仅root模型,子Issue4–7和PR8–13均由root自行收敛,无childIssue/PR模型session;不能用图和completed代替成员成果。Keep准确commit已archive冻结评分,官网self_funded lite上传实际HTTP403 Only Playground submissions and run changes are allowed,无submission/run/官网分数。WSL固定官方公开32项正在评。 + +BookStack同配方已启动:run bookstack-20261012/root1/platform18583/CLI工具session25269,新native989a/binaryd8a未热换,无评分反馈。SQLite code5自然调用错误已定位CLI Bind的DEFERRED read→write争用结构,517不是原实测;3d7e712写事务BEGINIMMEDIATE/读DEFERRED+错误细节编译20.35s通过,候选7dd4...未进入本轮模型配方。待最终真实公开connect操作取得有限采用反馈,避免声称稀有竞态已完全验证。Keep成功轮187assistant/167tools、recorded totalTokens12797376含cacheRead12504213(实际provider仅M3),加v2失败消耗558899;SDKcost0不是账单/免费证明。 + +BookStack自然终态:exit1/blocked/root1/deliveryCommitnull/stopConfirmedtrue,reason root closed without a published or merged scoped candidate matching delivery ref ... d0e8f98ab958d56bd3089ef357f78f9a59898095。所有对象关闭,但known deliveries=[];root只有一个真实turn,直接写子工作树,三子及PR5均无成员模型执行。冻结d0e8仅作为失败运行生成应用快照,不称accepted delivery;评估owner开始独立34项及官网接入。禁止人工补publish/merge、重开/重复生成。当前所有生成已自然终态,剩余评分、精确资源收尾、当前源码公开绑定操作及最终报告。 + +本轮最终采用:评分8/66(Keep6/32、BookStack失败快照2/34),官网两次403,无有效官网分数。所有actualmodels仅MiniMax-M3,含失败v2recorded totalTokens30807020,其中cacheRead30126225;SDKcost0不是账单。精确owned收据全stopped,平台/collector正常退出,声明端口无监听;独立WSL两容器已退出移除。已确认归属的5份正文、keep_backup和_server.log迁入WorkSSD并保留原路径/时间/hash;未创建_home,旧/tmp/keep-test非本轮归属未动。pkill工具整体timeout,独立exit及victim未知,不追认其合规。新3d7候选一次真实公开object show/Bind exit0;稀有锁竞争未重现、不声称完整资格。最终不通过,停止新增模型运行,等待用户下一轮决定。 diff --git a/tasks/github-pi-reacceptance/pi-delivery.md b/tasks/github-pi-reacceptance/pi-delivery.md new file mode 100644 index 00000000..f9b45187 --- /dev/null +++ b/tasks/github-pi-reacceptance/pi-delivery.md @@ -0,0 +1,40 @@ +# Pi 交付收敛记录 + +2026-10-12,用户授权“是的,我们先来收敛 pi 交付”。本轮完成直接 Pi 公共 SDK 路线,不接入 OAR 或 Pi Durable,不启动付费模型、旧验收或生成应用。旧运行材料及原失败证据保留。 + +## 交付变化 + +Pi 和同系列依赖锁定到 1.1.0。`pi.mjs` 准备隔离环境和所选材料;自有 `sdk-host.mjs` 使用根包公开 SDK 构造 runtime、资源及受管 Bash;`rpc-adapter.mjs` 复用公开 RPC 实现,仅增加 Braid 的执行停止、服务交接和实际身份。JSON/text 子 Agent 复用公开 print 实现,保留长任务 `@file`、stdin 和图片附件接线。当前未支持的原生 CLI 参数明确拒绝,受管入口不是完整交互式 Pi CLI。 + +旧的 296 行 Pi 核心综合补丁已删除。会话生命周期、资源边界、CLI/RPC bundle、Bash 登记和 Braid 自主推理策略不再通过修改那些上游文件实现。基础发行仍保留 60 行提前压缩补丁,以及 pi-ai 连接重置分类补丁;前者尚无等价公开设置,后者保留实际错误正文对应的重试行为,不能为零补丁撤掉已有能力。 + +插件依赖用独立 npm workspace 声明,共用一份 lock。安装器只安装明确选择的插件、应用对应补丁,manifest 只声明实际安装和修改的材料。subagents/PBB 最后交接迁到公开 `agent_before_settle`,不再依赖私加的扩展 `willRetry` 字段;PBB 只在明确选择 subagents 时动态导入它的 API。插件内部正确性及 owned process/service 接线仍保留局部补丁。 + +自有 host 对最终模型错误保留未消费的 steering/follow-up 输入,通过原生 custom entry 保存,并在下一次明确输入前恢复;终态扩展 hook 错误请求公开 abort、保留错误触发停止的事实。原始取消标记不改写,RPC 扩展错误仍交给 Rust 优先判 failed。模型 Bash 和公开 RPC/user Bash 均接入同一受管实现,扩展明确提供的自定义 operations 保持原义。 + +## 已取得的反馈 + +Mac arm64 上按低并发执行,全部安装、cache、HOME、临时、运行记录和日志位于 `/Volumes/WorkSSD/Development/braid-pi-delivery-20261012`。 + +| 范围 | 实际反馈 | +| --- | --- | +| Rust | 单任务离线 fmt/check、Clippy `-D warnings`、build 通过;最终 check 5.06 秒、Clippy 6.43 秒、build 35.97 秒。 | +| JavaScript | 四个自有模块通过 Node 语法编译,diff 检查通过;没有测试、自检或包 smoke。 | +| 基础安装 | 124 个依赖包;五种可选插件均未安装,manifest 包含两份基础补丁。 | +| 独立 background | 实际安装、加载并取得命令清单,无 subagents 依赖或 loader error;读回 M3/medium、空闲状态和停止回执。 | +| subagents/background | 134 个依赖包,只加载对应两个扩展;Context7、FFF、MCPorter 未安装,manifest 包含四份实际补丁。 | +| 最终基础及双插件发行 | 顺序完成公开 new_session、get_state、get_commands、RPC Bash `pwd`、get_entries、服务交接和 owned-stop,全部响应成功。实际 SDK 为 1.1.0,模型为 minimax/MiniMax-M3、reasoning 为 medium。 | +| Bash 与关闭 | 保存真实 root/pi-bash 出生登记、Bash 历史和子树 stopped 回执;父进程 exit 0、stderr 为空,随后离线 execution cleanup stopped。 | +| doctor | 最终安装的 Pi native material 与 Pi provider 检查通过。整机 ready=false 的唯一剩余前提是 OTLP Collector 未启动;本轮没有为使报告变绿启动服务。 | + +两份最终冻结 manifest:基础 `f7783a0e7ca734323960e8f87ba0a580bf1ccc463c717249efb2164d764090e6`;双插件 `5919c9347afcf2d5814eb4899af3815b2c33f7b75c69030b025811c08aa27a29`。raw/final-installations.json 保存完整安装选择、实际文件身份及停止回执;raw/final-base-rpc.stdout.jsonl 与 raw/final-both-rpc.stdout.jsonl 保存完整原生操作响应。两次操作均无 agent_start,不存在模型生成 turn。 + +## 原失败与资格边界 + +最初 Rust check 暴露 manifest 字符串部分 move 后再借用,修复后编译及严格 Clippy 通过。第一次基础原生启动暴露可选 `Args.extensions` 未初始化,修复为官方可选数组消费并保留失败安装。一次手工启动没有传与 Rust 一致的 launch-start marker,控制正确返回 unknown;修正行政操作的启动环境后重新取得 stopped,未放宽归属核对。所有这些旧执行均完成离线 cleanup,原失败没有被后续成功覆盖。 + +公开操作同时纠正了 live 身份的来源:版本取实际加载的 SDK VERSION,能力来自 host 实现,不能以 manifest 回显证明能力。采用检查还补齐 RPC/user Bash 接线、长任务文件输入和终态 hook failure 门控。这些修正没有改变收费范围。 + +本轮没有模型调用、同步/异步子 Agent 推理、实际重试/压缩、错误后队列恢复或终态 hook 故障实验。JSON/print 长任务和图片接线取得源码及编译反馈,没有取得模型执行反馈;Linux/x64 和其它可选插件也未实际运行。不能将安装、行政操作或编译通过当成真实模型端到端验收;旧 ARC/GitHub 资格结论不变。 + +持续的安装与操作说明归 [native/pi/README.md](../../native/pi/README.md),跨组件运行合同归 [provider 技术说明](../../docs/20-product-tdd/app-server.md)。OAR 保持候选地位,其采用判断保留在 [调查设计](oar-integration-design.md)。 diff --git a/tasks/github-pi-reacceptance/profile-feedback.md b/tasks/github-pi-reacceptance/profile-feedback.md new file mode 100644 index 00000000..42a1bd4a --- /dev/null +++ b/tasks/github-pi-reacceptance/profile-feedback.md @@ -0,0 +1,68 @@ +# 协作技能与 Profile 反哺 + +2026-10-12,按用户“继续反哺”的指示,从 Factory26 `f3963f8` 核对材料及实现, +融合到独立 Braid `4d459e6` 之后的同一 PR 分支,源码候选为 `f82ee88`,已推送到 Draft PR148。没有新模型运行、生成应用修改 +或 GitHub 业务对象操作,既有 ARC/GitHub 资格结论不变。 + +## 已采用的通用能力 + +`skills/braid-collaboration/` 保留 SKILL.md 与组织工作、交接与变化、接受与关闭、 +完整例子四份 reference。操作部分按独立 Braid 的双上游、serve/run、对象 CLI +和 Console/OTLP 调整;包内引用不依赖整个软件 checkout 或相邻 SVC 目录。 +技能独立发现、按需读取,不安装、不编译嵌入、不加入默认 Profile。 + +普通 Profile catalog、当前 Issue/默认 PR 执行者、根模型与推理的唯一来源已经 +迁入,本轮不重复实现,也不扩大任意 Profile driver。新增 Pi 的显式 skills 与 +native_template,采用真正的原生技能发现、模型 descriptor、设置和角色材料 +消费者;运行安装仍拥有插件和可执行入口。每个原生会话保留独立 home 与索引, +冻结完整技能资源及语义模板,恢复复用核对文件和设置语义,禁止静默覆写。 + +有效 Profile 版本覆盖声明 source workspace、adapter 合同及 schema pins、锁定 +安装 manifest、所选材料内容和非秘密服务路由,排除派生执行路径与凭据值。 +现有 Issue/PR 恢复 revision 门控继续明确阻断不兼容历史。新建、恢复及延迟 +物理启动共用 Pi get_commands 技能校验;每个声明技能须唯一且来自本会话快照。 +Profile id/revision/digest 加入会话、生命周期及 provider payload 的 OTLP 身份。 + +Factory preset/variant、模型费用配方、强制 SVC/vision/reviewer/cleaner、develop/main +分支流程和 ARC/Lab 仍归消费方;没有复制它们为 Braid 默认行为。Braid 也没有 +添加空 tools/MCP 管理器或 Codex 技能装配接口。能力及限制归 +[Profile 指南](../../docs/user-manual/profiles.md),恢复合同归技术说明。 + +## 反馈与限定 + +所有 Mac 操作材料位于 `/Volumes/WorkSSD/Development/braid-profile-feedback-20261012/`。 +单任务 `cargo build --locked --offline -j1` 最终27.88秒通过,无 warning;binary +SHA-256 为 `ef6275fb1dd740032c6b94f76539108170745c0fe02c1740f4ca3101a62df093`, +原件 `raw/build-qualified.log`。中间未使用变量 warning、get_commands helper +误入 trait impl 的编译失败及修复记录保留,没有将中间 binary 当作最终候选。 +没有设施测试、自检或模型请求。 + +真实 `profile inspect --json` 显示 MiniMax-M3、所选技能及模板材料。 +修改同路径 settings 默认工具集合,摘要/版本从 `829f6ad4…` / +`588272450525796732` 变为 `1f66…` / `141410568920633989`,还原后返回原值。 +这证明身份覆盖该材料变化,不证明实际历史 resume 门控已执行。 + +公开新建/指派 Issue #2 后会话 idle、turn_count=0、provider_resume_count=0, +Pi 参数包含 --no-skills 及快照 --skill,原生 home 保存完整角色、技能、模型 +和设置材料。成功 idle 是本候选 get_commands 启动门控通过的行为证据;本次未 +启动 Collector,单独发现回执未保留,OTLP 导出和 flush 错误仍保留原件。 +该次 Harness/Pi/platform 全部正常停止。 + +随后通过 Console 实际 Collector(14318)与内建平台(18991)补采,采样1, +新建/指派 Issue #3,仍为 idle/0 turn。公开 API 保存88条 records、20个原始 +protobuf batches,接收错误0;不从这些计数推断整体无遗漏。record #44 的官方 +get_commands 返回 success=true,技能名称及 sourceInfo.path 指向本会话快照; +#47 的 profile_resources 包含同会话 id、Profile id/digest 和技能路径,trace #76 +包含相同会话的 Profile id、revision 与 digest。原件及摘要见 +`raw/otlp-records-qualified.json`、`raw/otlp-batches/`、 +`raw/otlp-batch-manifest.json`、`raw/otlp-profile-session-summary.json`。 + +这次 Harness 启动还按既有策略接续了前两次空闲会话,保持0 turn,不能等同于 +继承真实模型历史。Harness、Console及其托管平台正常退出0;只读回收对象回执 +所需的临时平台也退出0。14318/18991/18992/18993均无监听,所属 PID 全部退出; +证据 `raw/otlp-process-pid-evidence.json`、`raw/otlp-status-before-stop.json`、 +`raw/otlp-issue-receipt.json`、`raw/otlp-assign-receipt.json`。 + +首次 idle 仅产生 Context 旁文件,没有模型历史,也没有为取证发送空推理。 +真实历史恢复、材料变化后的实际恢复阻断、原生角色实际调用、Codex 和模型质量 +均未在本轮验收,不把编译、idle 或技能发现等同于这些结果。 diff --git a/tasks/github-pi-reacceptance/run-arc-lite.md b/tasks/github-pi-reacceptance/run-arc-lite.md new file mode 100644 index 00000000..eee37f07 --- /dev/null +++ b/tasks/github-pi-reacceptance/run-arc-lite.md @@ -0,0 +1,61 @@ +# 独立 Braid run:ARC-Bench lite + +当前:两题已自然生成至程序终态并完成轻量收尾,没有在途模型或本轮服务。Keep v3为completed/stopConfirmed=true,确切交付ab8c1d763f7790722938a5e0834ae2523711b6d3;BookStack为blocked/stopConfirmed=true,deliveryCommit=null,具体原因是root关闭却没有与交付ref匹配的已发布或平台合并候选。其Git ref值d0e8f98ab958d56bd3089ef357f78f9a59898095只作为失败run的实际生成应用快照评分,不当accepted delivery。两题都没有child/PR成员真实推理,所有实现由根完成,根自行创建/关闭子项;自主分工不通过,不能由工作图或typedcompleted抵销。 + +独立WSL实际评估为Keep6/32(18.75%)、BookStack失败快照2/34(5.88%),合计8/66(12.12%)。全部收集并运行,零skip/flaky/collecterror/OOM,安装启动成功,原件在运行根evaluation/summary.json与resource-exit.json;Keep主要违反可访问角色、名称和状态合同。BookStack32项在入口选择器受阻:Shelves按钮11、Books按钮15、Login form内Login按钮6,不能据此断言未进入的深层功能都没有实现。两份完整无模型self_funded replay官网上传均HTTP403,没有submission/run或官网分数。两个WSL评估容器已退出移除,反馈在生成全部终态后采用,未回流模型。 + +实际生成使用binary源码861a15d/SHA d8a3342f58ed4887b5040ac179997bc95742c8e89265a263172f2e8d644482c6,以及native源码9e62be14e3724bdb41c22d08c420e1ce26c81506/manifest989a1d3fb888b1cbb3404d8e597a88147295b5da1626c24ddae0b5c8e17fcc18。晚到SQLite源码修复3d7e712/候选SHA7dd4bdba8a3e6587c6aedea5ab989941b9cfcfdcf813df1c9dbcb7803d52c37e没有覆盖生成freeze;结束后用候选公开object show1连接BookStack真实冻结run config/ledger,实际exit0、rootclosed、stderr空,new-bind-candidate-object-show.json保留。只证明该实际读取/绑定,不冒充稀有并发锁竞争全面资格。 + +两题实际原生根cohort与失败Keep v2都仅minimax/MiniMax-M3,无其它模型、Pi子Agent或子Issue/PR成员推理(实际tool names只有read/write/edit/bash/background_job)。去重recorded usage总计input515140、output165655、cacheRead30126225、cacheWrite0、totalTokens30807020;reasoning940包含在output,不重复相加。SDKcost字段全0不能代表免费或供应商账单,中断流可能不完整。失败v2消耗也纳入,原件raw/total-recorded-model-usage.json及每题raw/final-model-usage.json。 + +纪律单列FAIL:Keep成功在/tmp写5份Issue/评论正文,并复制app缓存/data到/tmp/keep_backup;BookStack成功重定向/tmp/_server.log,尝试/tmp/_home.html因timeout命令缺失/连接失败没有留下文件。BookStack还执行pkill -f按命令名称停止请求,整体工具最终15秒timeout;无法从该结果确定pkill独立exitstatus或杀了谁,不计exactowned cleanup。具体call/toolResult在每题raw/model-scope-violation-call-results.json。较晚正常owned停止不抵销原违例。 + +只处置已明确本轮归属材料:5份正文当前字节与原生成功write内容完全一致;keep_backup的1230条目ctime均在原cp操作07:10:52.468–52.785窗口且仅app子树;_server.logmtime匹配重定向时刻且错误堆栈指向唯一BookStack本轮工作树。上述原件已移到WorkSSD raw/recovered-model-system-temp,原真实路径、时间、SHA和备份逐文件清单在raw/model-temp-material-disposition.json及keep-backup-original-inventory.json。/tmp/_home.html不存在;/tmp/keep-test在本轮之前即存在(2026-09-24 mtime),不因模型尝试add/rmdir就认归属,保持未触碰。没有广扫/tmp或杀未知进程,也没有改业务/补发布合并/复跑模型。 + +每题2个实际execution的root-descendants与wholeexecution停止收据各四份全stopped/exactID/registered-process-groups-and-inherited-execution-markers,见每题raw/final-owned-receipts.json;旧失败v2stopConfirmed=false永久保留,较晚精确offlinecleanup仅说明新时点已停止。Keep/BookStack CLI最终exit0/1分别符合completed/blocked;Keep平台98517、BookStack平台62794、OTLP-only collector44293均正常Ctrl-C exit0。18582/18583/26518/18580/18581/3001/3457最终均无LISTEN,raw/final-port-checks.json。Collector保留16164 records/2175 batches/receive_errors0,观测不当作完成权威。 + +下文时间戳按原始证据的UTC保留。以下按阶段保留原始身份、错误、停止与采用记录;旧准备和失败状态不替代以上当前状态。 + +2026-10-12,native_local_env 稳定负责准备、真实生成、范围内设施诊断修复和收尾;主 Agent 更新 packet,独立评估负责人冻结与评分。用户授权真实 MiniMax 整轮验收,Keep 后 BookStack 顺序生成,每题 maxConcurrency2。运行根 /Volumes/WorkSSD/Development/braid-run-arc-lite-20261012,装配要求 Mac HOME/cache/temp/data/原生材料及证据全部位于 WorkSSD;实际模型越界与后续处置见上文。无旧run接管,无开发者业务代写,不读隐藏评测,不编写或运行设施测试。 + +冻结源码 e7615e9,binary SHA2c20f70610a40563333d09d6c1abbc584ea08164f4742e5bf253ef4ef5d35015,复制到 run 根 bin/braid。新 native/pi 从已冻结Pi1.0.2/Node24.15.0材料复制,manifest d1fd63d831d2753a21c0b22e59df5bddaee0ca3fbc04cf48485f76edff2bb9bc;没有继承 Pi 会话。仅 subagents/background 已锁插件,自定义只读 review 角色显式M3无fallback,builtin disabled与strict allow唯一minimax/MiniMax-M3。根/成员Profile也是官方minimax/MiniMax-M3,凭据只在进程内从../agentic26/.env加载,不复制或输出,禁止其它路由。Pi物理启动还须真实RPC身份核对;doctor不代替模型实际元数据。 + +公开需求来自 Factory third_party/arc-bench/arc-bench-lite/{keep,bookstack}/requirements,只复制公开requirements正文、参考图片和允许assets。source只有requirements空业务基线,Keep b59c71929290277f23579fcf8b9558b5924c27a4,BookStack67d2b06b85c2c8058f7f178c333d436ab80bff1d;逐文件SHA原件raw/frozen-identities.json。没有读取tests或旧答案。description只提出完整业务与公开协作/交付约束,未替root决定REQ拆解与架构。真实root需自主子Issue/PR和成果消费;应用通过不替代这项协作资格。 + +应用统一app/根,package.json/锁/README随交付commit导出,npm install && npm run start -- --port 3000 --host 0.0.0.0。每题completed后立即向主Agent与评估owner交付typed RunResult、确定commit、source/app及实际启动入口,不等第二题。独立WSL评估冻结lite Keep32/BookStack34,1worker/10秒/0retry,反馈不注入仍生成Agent。 + +准备首次doctor在建runtime目录/采集服务前明确fail(目录缺失、OTLP不可达),原件keep/raw/doctor.json保留;公开migrate0→7和真实collector启动后doctor-ready.json成功。非模型测试,不将前置失败覆盖为pass。 + +Keep已启动:run-id keep-20261012,delivery refs/heads/run/keep-20261012,description keep/description.md,maxConcurrency2。公开CLI进程PID65775(exec session28195),平台PID65247/session95855,endpoint18582;OTLP-only Console PID65276/session93790/26518,没有浏览器常驻与managed runtime重复控制。公开CLI正常终止信号请求停止,须读取程序结果stopConfirmed和实际child/owned receipt;不得以数据库状态或信号发送成功推断停止。stdout/stderr分别keep/raw/run.stdout与run.stderr,平台和collector有原始log。BookStack尚未启动,须Keep真实收尾后顺序执行。 + +首次真实启动暴露设施缺陷,未开始推理:platform root1 noop→ConfigureRunRoot invalidate→Assign default,所有事件和Assign wake batch变为consumed。Pi真实get_state为M3/Quiescent,Context reset applied continuation=false,旧会话replaced新会话idle,但没有prompt/native rollout。小范围startup OTLP与只读ledger事实用于诊断,无私有状态修改。稳定调度owner接续源码修复,不通过人造评论唤醒遮错误。 + +为了降载,执行负责人在该idle现场向CLI发正常Ctrl-C。程序实际exit1(stopped按合同非零),typed RunResult state=stopped/rootIssue1/deliveryCommit=null/reason=external stop requested/stopConfirmed=true;keep/raw/run.stdout与stderr保留。未启动BookStack。当前只保留独立平台与OTLP以待必要诊断,后续修复后按已授权配方接续,原启动失败不覆盖。 + +调度owner确认根因:serve原合同下Issue Assign除mention外会consume batch并只创建idle会话;finite run误继承该策略,root与子Issue都无法执行。ConfigureRunRoot.invalidate仅导致正常idle reset,并非模型失联。修复限定finite真实Assign保留urgent wake,再由既有reset优先顺序先更新Context后实际prompt。旧run已消费且zero turn/pending,不能以sameID重试当恢复;保留keep-20261012的stopped与原配置/ledger,修复binary后使用全新keep-20261012-v2/root与独立deliveryref,不复制业务、不伪造comment唤醒。 + +中央修复源码861a15d,binarySHA d8a3342f58ed4887b5040ac179997bc95742c8e89265a263172f2e8d644482c6,旧binary副本保留bin/braid-before-finite-assign-fix;旧平台/collector正常exit0后以新binary重开。真实新run keep-20261012-v2 与独立refs/heads/run/keep-20261012-v2启动,description原件不变,新ledger不接管旧run。平台session98517、OTLP-only Console44293、CLI6169;不造评论/子项,也不重复编译。 + +Keep v2 root2真实推理启动已确认:OTLP prompt record126、agent_start129、assistant record137/160/172均provider=minimax/model=MiniMax-M3,tool execution154/166/178及toolResult真实出现。新reset后原Assign仍可执行;keep/raw/v2-startup-evidence.json保存定向事件摘要,不用握手冒充推理。description无旧ref硬编码,仅runtime注入v2授权。后续按公开工作图/结果判自主协作,不把tokens增长当进展。 + +Keep v2实际推理遇到第二项设施故障:普通PBB bash实际spawn payload后,`bash -lc` 的ls/echo hi/pwd持续3/5/60秒超时;read目录EISDIR是另项模型工具误用,未混作设施根因。已登记payload可见,定向sample PID76122在run_startup_files→source_builtin→source_file→再次source_file→open/__open阻塞,802/802 samples;宿主/etc/profile含Nix source,定向读取该Nix文件也挂住10秒并由执行负责人正常Ctrl-C结束诊断。sample79937因进程已终止而失败原件保留。BASH_ENV与ENV为空、SHELL=/bin/zsh、HOME为run WorkSSD/home。没有修改宿主profile或扩展超时遮故障;稳定executionOwner收拢受控非login shell修复。原件keep/raw/bash-timeout-owned-records.json、bash-payload-76122.sample.txt。 + +向当前CLI6169发送一次公开Ctrl-C后程序实际exit1,typed RunResult state=blocked/rootIssue2/deliveryCommit=null/stopConfirmed=false;具体reason为external stop requested及finite runtime shutdown exceeded its deadline; physical execution stop is unconfirmed,保存run-v2.stdout/stderr。不能以CLI退出当停止确认。后一次knownPID76007/76010/76116/76122/76635/76641只读核对均不存在;仍保留旧stop未知。v2-stop-native-receipts.json保存已有exactexecution01a12ecd-8476-7142-9d3c-ff8b3a80c251原件摘要,需Owner收拢当前cleanup事实;不私改run状态、不重复低层信号或开新模型。root尚未产生子Issue/业务app,本轮真实M3推理不能算有效交付或零费用设施失败。BookStack仍未启动。 + +失败v2的实际模型消耗单独保留keep/raw/v2-recorded-model-usage.json:一个物理会话、38 assistant/37 tools,实际仅minimax/MiniMax-M3;recorded input27862/output2529/cacheRead528508/cacheWrite0/totalTokens558899,reasoning347为output细分,供应商账单仍独立。最后Request aborted在06:37:25.288Z对应公开stop,不当自然模型错误。 + +原生owner核对只有PBB工具override使用login -lc,Pi核心-c与subagents没有login默认。共享源码修复PBB所有foreground/auto/background/service为-c,wrapper清BASH_ENV/ENV,禁止修改旧冻结材料。主Agent与advisor采用一次旧冻结managed模块公开offline cleanup exactexecution当前时点收据、停止准入fence及registeredPGID/inheritedmarker coverage,然后全新root/run/ledger;原blocked stopConfirmed=false永久保留,后续不称resume,不低层按名kill。精确cleanup和新immutable材料+实际SDK shell操作由executionOwner负责,运行owner不重复控制,等待集中采用回执。binary861a15d尚不需要重建。 + +新immutable材料pi-nonlogin-v3已实际采用准备:source9e62be14e3724bdb41c22d08c420e1ce26c81506,manifest989a1d3fb888b1cbb3404d8e597a88147295b5da1626c24ddae0b5c8e17fcc18,subagents/background组合不变,28640files actualmismatch0,旧native材料完整身份保持。Owner实际SDK公开bash override echo hi215ms、pwd195ms、ls requirements216ms均exit0;根后代和整个SDKexecution实际stopped,无模型/业务写入。首次SDK caller未detached触发startup rejected75原件保留,修caller后真实操作采用。旧v2 exactexecution较晚offlinecleanup在06:44真实stopped/scope execution,keep/raw/later-offline-cleanup.json保留;旧RunResult stopConfirmed=false不改。两题配置指向新材料,不部署到旧冻结run。 + +第三次Keep尝试keep-20261012-v3/root3/ref refs/heads/run/keep-20261012-v3,公开CLI session91211启动,新ledger无旧会话接续。自然M3工具pwd&&ls在06:50:58.661→58.882成功约221ms,ls requirements/.braid约203ms;原件v3-first-natural-bash.json。ownedtool登记存在但record不保存argv,短命shell未捕获liveargv,不能编造实际观察-c;冻结源码与真实自然返回支持修复采用。 + +root已实际成功读取braid object创建/指派/PR/关闭/合并帮助,截至06:55:45尚没有child/PR,却开始在自己的worktree写app/package.json和server/db.js。主Agent决定继续观察自然完整图与结果,基础文件不机械等同失败,不能用root整任务直写替代PR分工;若最终无child或真实PR成果采用,即使应用得分高也单列自主协作不通过。不人工造图、不开发者业务代写、不注入评估反馈、不因几份文件擅自停止或自动换模型重试。 + +07:08之后真实root自行建立协作图,scope3包含后代Issue4设计架构、5后端、6前端、7整合交付,均指派default,未人工建图/追加comment;v3-scope-stage6.json。公开Item list不带parent字段,因此早先摘要parent_issue:null仅字段缺失,不能当无父子关系;scope/3是范围权威。此时仍无PR、delivery为需求基线b59c...,只判自主图已形成,真实成员执行、成果消费与最后整合待实际观察。root前期自己写应用事实独立保留。 + +Keep v3程序实际exit0,typed RunResult completed/root3/deliveryCommit ab8c1d763f7790722938a5e0834ae2523711b6d3/reason=null/stopConfirmed=true,run-v3.stdout。真实scope_stage9全部义务关闭且交付非基线,主Agent可立即冻结source ref/run/keep-20261012-v3的app独立评分。package依赖express4与better-sqlite3^11.5,Node声明>=18。 + +自主分工资格不通过:仅root3一个原生物理会话,无childIssue或PR成员真实prompt/推理;4–7子项均由root关闭,8–13PR均无profile/published=false,root自己创建并采用9/12/13候选整合。公开图与实际交付闭环存在,不冒充成员执行/成果消费。Keep根自产应用仍是实际M3生成,独立业务评分与自主协作分开。PRmerge/base409原错误与模型纠正保留;SQLite code5已交稳定源码Owner调查,不因单次泛化改freeze或丢原错。 + +Keep两个实际execution各root-descendants/wholeexecution停止收据四份全stopped/exactID/fixedcoverage,v3-final-owned-receipts.json。端口3001无LISTEN,Keep平台98517正常Ctrl-C exit0,不删除对象。BookStack在同binary861a15d/d8a与native9e62/989a配方顺序开始:run bookstack-20261012,root1,refs/heads/run/bookstack-20261012,CLI25269/platform62794 endpoint18583,doctor-ready pass;OTLP44293保留历史库。输入/账本/source独立且只公开requirements。不能把晚于启动的SQLite源码修复部署到此freeze,公平保持当前recipe,具体原code5与Keep自然最终关闭单列。 diff --git a/tasks/github-pi-reacceptance/run.md b/tasks/github-pi-reacceptance/run.md new file mode 100644 index 00000000..ef4b9594 --- /dev/null +++ b/tasks/github-pi-reacceptance/run.md @@ -0,0 +1,61 @@ +# GitHub + Pi 本轮执行 + +2026-10-11,执行负责人 native_local_env。本轮已按用户“你悠着点”的性能约束停止并完成外部接入恢复,没有在途操作;不新增模型或重新启动。第二候选 `95fa210c8e5692be1af8c89fc8e2f128ff1a8911` 经主 Agent 独立16次实际 CLI 操作采用。首次候选的创建顺序错误已由真实模型修正,原错误仍保留。整体纪律判定 FAIL:真实模型曾写 `/tmp/evidence-comment.md`,也曾以 kill/pkill 名称匹配停止服务,后续纠正不抵销。PR [#40](https://github.com/xiaoland/braid-poc-test/pull/40) 保留 Draft、未合并、未关闭重开;Issue [#39](https://github.com/xiaoland/braid-poc-test/issues/39) 与 Git、原生会话及观察库保留供后续低负载接续。整个验收计划未完成。 + +运行根 `/Volumes/WorkSSD/Development/braid-gh-pi-reacceptance`。正式运行源码为 `89505d964314cd6f65b928543f33c59536fde386`;Rust binary 编译来源 `13943195dfb9b162e99fda6187fd0f238d0afdae`,SHA `f015b77bdc03ee44f42dcec6c62879abd04f72e2b68254d6a37725a977fcac95`。实际材料 native/pi-attempt2 使用官方 Node24.15.0、Pi1.0.2、subagents0.56.0、background1.0.5,manifest SHA `d1fd63d831d2753a21c0b22e59df5bddaee0ca3fbc04cf48485f76edff2bb9bc`。首份 Homebrew Node 的 dyld 失败及两次 fallback 配置解析错误都作为准备失败保留,未覆盖为成功。 + +公开 idle stop request `c77a14da-e1e1-4bf6-8f38-1845c70ac0ff` 最终 applied、state=stopped、error=null;停止前两当前会话 idle、零 running turn,不能称为公开 active stop 验收。两个当前 execution 的 offline receipt 均 exact identity、status=stopped、scope=execution、coverage=registered-process-groups-and-inherited-execution-markers;实际 Rust Child.wait 记录均 graceful_eof/exited/exit status0。证据为运行根 raw/stop-receipt-performance.json、final-owned-stop-receipts.json、final-public-stop-child-wait-records.json。此前 Issue idle 与 PR active Context reset 已有真实终态、旧 execution 收尾和替换接续证据,独立计通过。 + +App webhook 原 url/content_type/insecure_ssl 已实际 PATCH200 恢复并 GET200 核对相等,未回写遮罩 secret。Console session91852/PID24988、tunnel session13651 均正常 Ctrl-C exit0;26318/18380/18381 无 LISTEN,已知 PID24988/65289/65611 不存在,raw/final-port-process-checks.json 保留。未操作其它高 CPU 进程。Console 停 Harness 前一次62.7%CPU,停后一次0.0%,随后关闭;这不是新性能修复的部署效果。主 Agent 后续源码提交 `d9f52d9` 删除 idle readiness 每2秒两组重复全量28,640材料文件哈希,启动/恢复/实际 spawn/doctor 仍校验;只完成源码编译,未重编部署或重跑模型。 + +root/child 实际模型均只有 `minimax/MiniMax-M3`。raw/native-model-usage-summary.json 汇总10份物理 JSONL(3 root、7 child,排除重复 transcript;native session ID+entry ID 去重,重复0):input515803、output161755、cacheRead14516074、cacheWrite0、totalTokens15193632。reasoning22833 属于 output 的细分,不重复相加。原生 SDK cost 各字段为0,不代表免费,也不能替代供应商实际账单;中断流可能缺少完整 usage。 + +定向原件还观察到原 PR 会话在14:07:52.835Z与14:07:55.164Z两次自然 HTTP429:`rate limit exceeded(TPM) (1039)`,随后同 turn 恢复生成并完成,没有人为注入失败或操作者重试。既有物理 JSONL 没有显式 retry/willRetry/auto_retry 条目,因此只能判自然限流后恢复已观察,精确 retry-intent 事件合同证据不足,不能概括为自然重试完全通过或完全未运行。14:14:10 的 Request aborted 属于真实 Context reset 中断,分开记录。 + +已观察真实同步 async:false 与异步派发/等待/消费,有限 PBB exit1 原错误与结果投递、后续 exact background handle stop 均保留;原名称 kill 不计 owned stop。Console traces/logs/metrics 三信号已由主 Agent 实际 UI 读取,最终 collector15972 records、receive_errors0。公开 active stop、close/reopen、merge、restart 及重启后防重复等剩余项目未执行,不补造通过证据。 + +以下为各阶段当时的操作记录;其中“等待”“尚未”等是历史阶段状态,以以上收尾状态为准。 + +2026-10-11,执行负责人 native_local_env。当前阶段为真实 Issue 设计生成,已创建 Issue39 并经可信评论启动正式 MiniMax 调用;准备故障保留在下文。运行根为 `/Volumes/WorkSSD/Development/braid-gh-pi-reacceptance`,本轮需求目录 `e2e-notes/20261011-github-pi-native-v2/`。源候选 `13943195dfb9b162e99fda6187fd0f238d0afdae`,binary SHA `f015b77bdc03ee44f42dcec6c62879abd04f72e2b68254d6a37725a977fcac95`。 + +根角色固定 minimax/MiniMax-M3;仅 design-review 与 implementation-review 两份显式子角色,disableBuiltins,严格 modelScope 唯一允许同模型,不启用 fallback、外部 runner 或其它登录。models.json 只引用官方 API 环境变量,凭据只从用户指定 .env 临时加载,未输出或持久复制。材料只启用 subagents/background。HOME、临时、缓存、数据和所有证据均在本轮 WorkSSD 根下;既有 App 密钥只读使用,不将原件移位。 + +新的远端 clone 和独立 SQLite 账本已经建立,公开 migrate 0→6。source 使用 sparse checkout 仅展开本轮业务目录,正常 main 历史仍含旧应用,角色明确禁止读取它们,不能声称远端是空树。需求空基线只有 REQUIREMENTS,不含实现答案;正常提交/push 与 HEAD 身份将在首次运行前补记录。没有复用旧 ledger/native/observations。 + +App webhook 的当前基线与 identity/installations 已通过真实 GET 200 保存到 network,权限0600;尚未临时 PATCH。安装范围仍须在开始正式对象输入前核对,不以共享 App 身份推断远端无人使用。端口计划 Console26318、ingress18380、health18381。 + +准备操作的 Python 系统 CA 缺失和隔离 HOME 后 certifi 不可见均在操作脚本侧修复,使用 WorkSSD 中公开 CA 原件,未关闭 TLS 校验;一次配置生成语法错误未写入文件,后续修正才产生冻结配置。没有以这些失败启动模型。 + +实际 doctor 发现首个交付失败:材料 files SHA 校验通过,但复制的 Homebrew Node 缺少 `@rpath/libnode.147.dylib`,Pi真实启动 dyld 失败。原安装目录 native/pi 和 raw/doctor.json 保留。稳定 pi_plugin_feedback owner 正在修复固定 Node 完整交付,后续使用新的 native/pi-attempt2,不能覆盖旧失败。冻结材料 SHA 为 `4a87c7d96b0b0fe59cf53fc78815f23c96dd0aaf9b3d48f730e3d477030fdc9b`,该身份当前不具备可执行验收资格。 + +新需求空基线 `4c49fff0a2e5c778c57dc627ef3c2ded06f10d75` 已正常 push main,仅新增 REQUIREMENTS。首次 git push 在隔离 HOME 中没有 credential helper 而被拒绝,接线 gh 后实际 push 成功;系统默认 keychain store 报 `failed to store: -60006`,已在新 checkout 本地清空默认 helper 链,仅保留 gh auth git-credential,后续不写宿主 keychain。原错误和成功远端 OID 均保留。Console26318已可读,runtime stopped/generation null,无模型;真实 tunnel 已注册 HTTP2,但 App webhook 仍为基线,未引入 synthetic event。 + +安装修复 source 为 `89505d964314cd6f65b928543f33c59536fde386`,Rust binary 保持1394319编译来源和f015...字节。新材料 native/pi-attempt2 固定官方 Node v24.15.0,manifest SHA `d1fd63d831d2753a21c0b22e59df5bddaee0ca3fbc04cf48485f76edff2bb9bc`,实际 doctor 全部Pass,但它的version检查不代替后续session实际RPC握手。公开start request `37dfdca1-7ec5-447a-81cb-09ed421c9058`,generation `01a12b2e-9f58-7eb3-8ead-8831089c8657` 已ready/provider connected/reconciliation current,仍无模型输入。真实selected repositories仍为braid和braid-poc-test,本轮共享入口窗口已按授权临时接入;恢复只PATCH url/content_type/insecure_ssl,绝不把masksecret回写。 + +GitHub专用Issue为 [#39](https://github.com/xiaoland/braid-poc-test/issues/39),13:38:21Z创建,尚未可信mention。官方opened delivery `06dca52c-c579-11f1-9dfc-2779d67b321d` / `3847702079648874496` 在13:38:23.621Z返回HTTP202;使用真实仓库ID1344679384,没有合成payload或redelivery。创建前openobjects=0,创建后公开snapshot无历史assignment/session/turn激活。等待实际子角色配置映射返回后才发送首次付费激活。 + +实际SDK管理读取先发现 frontmatter `fallbackModels: []` 被解析为字符串候选 `[]`,随后 `false` 同样是字符串候选。settings agentOverrides只适用builtin,不能据此声称覆盖自定义user角色。两次读取都零模型且owned cleanup stopped,原件 raw/subagent-model-config.json 与 fixed 原件保留。已删自定义角色frontmatter fallback行,使用原生未提供fallback的primary-only候选路径,继续严格allow唯一minimax/MiniMax-M3。正式可信mention仍等待最终实际候选数组。 + +最终配置操作 raw/subagent-model-config-fixed2.json 已确认 rootModel=minimax/MiniMax-M3,两角色真实 candidates=[minimax/MiniMax-M3]、fallbackModels=null,六个 builtin disabled,loader/runtime errors 空,零模型调用且原配置操作 exit0/cleanup stopped。正常可信激活评论于 2026-10-11T13:46:05Z 创建,comment 6109679664,开始正式模型阶段;其原件 raw/issue-activation.json 保留。 + +Issue 原生 session 2026-10-11T13-46-23-912Z_01a12b36-f328-759e-aff8-47bf69ad3b2d 于13:46:27Z开始 turn01a12b36-fe1d-76d2-8436-92e374d3d815,真实 assistant provider/model 均 minimax/MiniMax-M3,token usage已记录,descriptor cost0不当免费。首 design-review 派发未传async,实际返回 asyncId,须计异步而非同步;run f6c0cac1-1510-490d-8290-cef138597650 已 complete,真实 attemptedModels 只有M3,child metadata原件 raw/issue-child-model-stage1.json。尚待根消费该结果与发布交接;同步义务后续明确async:false。 + +首次模型设计在公开 Implementation Request comment6109703753(13:48:47Z)提出list跳过坏行、按timestamp/id排序,并把async+wait称同步;这些与原始需求/实际证据不符。需求方正常评论 6109710304 于2026-10-11T13:49:32Z 澄清损坏JSON/错误根结构在list也须具体非零、不改数据、保持实际创建顺序以及明确async:false;未代写业务代码,原错误保留,黄金路径无纠正项不能判pass。 + +13:52:40Z Issue澄清turn正常completed/idle,无error;已真实async:false design-review调用,待结果详情取证。现在正常编辑需求方原激活评论,仅补一句以最新澄清为准,核对idle Context reset:预期替换旧physicalsession而不自动启动模型turn,保留既有设计/工作树/完成输入,无私有状态改写。PR当前仍running,不编辑Issue正文,避免提前应用冻结的后续业务变更。 + +Issue同步调用call01a12b3a545c763982904d84已正常结果:async:false、无asyncId、design-review exit0,actual model/attemptedModels只有M3,raw/synchronous-design-results.json。随后原可信激活评论可见编辑实际触发trusted_mention新turn(13:53:07→13:53:37 completed)但status仍context_resets=[]且physicalsession未换;不能据此判idle Context reset通过。保留raw/status-idle-edit-stage.json与snapshot,后续使用不带mention的实际描述编辑核对,不继续追加常规提示。 + +PR真实MiniMax生成 notes.py及HTTP演示;初次nohup未service:true,30s转finite bg001且wait_timeout;原错误raw/pr-first-service-operation.json保留。后模型自行另起background:true bg002,再显式service:true bg003(14:00:37)并真实curl应用,service端口63878。有限bg001 manifest14:00:18 exit0,bg00214:00:31 exit1,服务bg003 running;终态与消费待分开确认,不能用shell退出推断脱离后代已停止。实际async:true implementation-review 于14:02:30派发run d8de703b-7195-4e9c-9e17-975026749fcd,正常等待实际应用操作结果。raw/pr-async-application-start.json、pr-background-status-stage1.json保存身份。PR同步design-review亦exit0且唯一M3,raw/pr-synchronous-design-result.json。 + +真实异步implementation-review d8de703b...已complete,processTerminal observed/runner close exit0,无signal,actual child native metadata所有调用M3,parent subagent_wait正常返回isError=false,结果已消费;raw/pr-async-application-stage2.json和pr-async-child-native-model.json。子角色42工具含19次CLI实际操作,不把实际应用操作叫设施测试。 + +首次业务候选33b12109b69c8a9b4ec6c15c602c4e6c51c6d388已实际push;只新增本轮4文件,Gitarchive原件在candidates/33b...,主Agent独立应用操作。PBB finite terminal在14:09:21以background_bash_result正常投递,保留真实bg001 exit0/bad相对日志、bg002 exit1/No such file,不能作全部成功。服务bg003 abort是子/根模型按名称kill/pkill产生,不是ownedstop确认。另模型14:08:26实际写/tmp/evidence-comment.md且交付声称未触/tmp,本轮存储约束明确fail;原生call/result与公开原评论保留,该具体临时文件已由模型14:08:43自行删除(原cat成功3181字节、发布及rm操作均保留),不追认无违例,不修改业务或ledger。证据raw/pr-scope-deviations.json、pr-finite-result-messages.json。 + +独立应用首次验收保存17次真实操作,多数功能通过;合法存储副本仅逆向created_at后list --all逆序,创建顺序fail。已正常PR可信反馈要求模型修正且禁止再次/tmp/名称kill,保留firstcandidate。现在按冻结design-change正常编辑Issue39正文接受同标题/唯一ID/list --all,附原始创建先后与错误保护约束,预期Issue idle Context替换,以及关联PR有active turn时硬失效后真实interrupt/ownedstop/replacement接续。保留工作树,不私改ledger;若没有active则只判对应实际边界,不造active证据。 + +Context reset闭环实际通过:Issue reset01a12b50-25b2... applied/continuation=false,换14:14:34 session后idle;PR reset01a12b50-61f9... applied/continuation=true,14:13:37修正turn于14:14:10 interrupted,新14:14:59 session/14:15:09 continuation running。两旧execution live children-stop及offline execution-stop均exactID/stopped/对应scope/固定coverage;公开Console exactsession records实际Rust Child.wait日志:Issue managed_launcher PID36439、PR39638均graceful_eof exit status0、reason空,证据context-reset-owned-stop-receipts.json/context-reset-child-wait-records.json。不是手工pkill或DB interrupted推断。 + +修正接续异步验收e5da61a7...实际complete/runner close exit0,64工具,uniqueM3,raw/pr-replacement-async-stage2.json。第二模型候选95fa210c8e5692be1af8c89fc8e2f128ff1a8911已实际push,仅本轮4文件,Gitarchive固定原件在candidates/95fa...;交主Agent再次独立实际应用操作。新会话通过background_job stop使用exact handle,两次service:true均保留实际tool原件raw/pr-replacement-background-contracts.json;本项不追认旧pkill合格。 + +用户最新性能约束“你悠着点”,root要求立即降载:不新增模型轮次/子角色/close-reopen/重启。第二候选95fa...已固定,snapshot-before-public-stop已确认2当前physicalsession idle、0 runningturn;按原授权公开runtime stop收尾,保留已生成Git/原生/ledger/collector。剩余close/reopen、restart、防重复控制未执行,不伪判通过。仅按knownPID核对24988职责,不清理foreign进程;公开stop不得低层pkill替代。 diff --git a/tasks/pi-runtime-feedback/results.md b/tasks/pi-runtime-feedback/results.md new file mode 100644 index 00000000..d93bc8cf --- /dev/null +++ b/tasks/pi-runtime-feedback/results.md @@ -0,0 +1,78 @@ +# Pi 运行栈反哺实施结果 + +2026-10-11,用户“实施这些遗漏”授权的源码融合已完成。基线 `2808c89`,目标 +Pi 1.0.2;实际反馈来自编译、原生 CLI/RPC/SDK 与本轮自身的进程操作。 +[此前 MiniMax 双上游验收](../real-model-e2e/results.md) 的整体未通过结论保持不变。 + +## 交付与边界 + +`native/pi/` 交付锁定依赖、插件选择、六组有序语义补丁和独立入口。CLI 与 RPC +使用同一安装,固定 Node;材料清单包含 28,639 个文件及文件链接入口身份,禁止 +链接逃逸安装目录。Rust 在启动前校验 SHA,实际启动再核对 execution ID、能力、 +真实扩展集合及 loader errors。setup 识别相邻 manifest,doctor 复用同一校验器。 +外部基础 Pi 保留,宿主自动扩展发现关闭,不修改系统全局 Pi。 + +迁入的共同合同包括 awaited hooks 之前的唯一重试意图、extension_error 与取消结果、 +结果交接、Braid 所有的推理、subagents 所有权/wait/候选排除边界,以及 PBB +精确 handle/有限任务和服务。异步子执行必须等待真实 child startup,不能先凭 +runner PID 报成功;Node launcher 与真正 writer PID 分开,lease 使用实际 payload。 +所有出生身份消费者在 Mac 上统一查询,稳定 boot 使用 boot session UUID。 + +每次物理执行重新分配身份,先登记再执行,在共同 admission 锁内 fence 新启动。 +关闭依次收口 owned 后代、EOF/父 wait、精确全 execution 离线清理;停止未知 +阻断替代执行。Core turn idle 不代表后台结果已消费;service handoff 不能越过 +有限义务。持久化终态之后的失效通知仍保留诊断。 + +21 项历史输入按语义融合:PBB 与 subagents 的共同生命周期、core 边界及 managed +接线、pi-ai connection-reset、Context7 HTTP 诊断和 MCPorter owned service 纳入。 +可选 compaction threshold 不设 Factory 默认值。Factory acceptance gate 删除、 +固定模型/角色、资源压力政策,以及 FFF/其它工具描述删改不迁。 +技能保持独立文件,不内联到提示。 + +生产合同归 [provider 技术说明](../../docs/20-product-tdd/app-server.md), +安装与处置方法归 [原生材料说明](../../native/pi/README.md)。 + +## 实际反馈 + +最终安装为 `/Volumes/WorkSSD/Development/braid-native-feedback/installed-v11`。 +manifest SHA-256 为 `612fea8c884b6e3a75f0ddf84ab09008216b15dd2fa4f573b8d07ec0dba77c48`。 +managed 模块 SHA 为 `29d49404ea98a4c89da0dc0ba28d6465f1aeb5527f47e50ac37fa2cd6ed9fd8c`, +process-owner 为 `203f39fd4da47b6539ac95ade9e3a094ebe95bd4daae6d1e33eb623ac91053ba`。 +源码采用清单为同证据根的 `native-source-final-v11.json`。 + +原始回执全部位于 `/Volumes/WorkSSD/Development/braid-native-feedback/`: + +| 证据 | 观察与实际限度 | +| --- | --- | +| `operations/rpc-v11/` | 四个选用扩展实际加载,errors 为空、execution ID 准确、quiescent,进程 exit 0。 | +| `operations/sdk-pbb-v11/` | 真实 finite 命令 busy→wait/result,保留 exit 7 和日志;错 handle 明确失败;service busy→handoff quiescent,收口 stopped。 | +| `operations/subagent-startup-v11/` | 返回前 child 确实 started;随后 busy→自然 wait→保留失败与产物→cleanup stopped。无凭据子调用保留 `No API key found for anthropic`,没有模型 HTTP 请求;不是 MiniMax 配方验收。 | +| `e5/operations.json` | 极短真实 `/usr/bin/true` 的 startup 与 code 0 close 均保留。 | +| `e14/operations.json` | A 的 launcher 被 SIGKILL 后 payload 仍存活;离线收口 A,B 的原 PID、birth 与 PGID 继续存活,再独立收口 B。 | +| `e16/operations.json` | 稳定 boot session UUID 下实际 shell/sleep busy→全 execution stopped,真实 SIGTERM。 | +| `operations/braid-cli/doctor-v11.json` | Braid 的材料和 version 检查通过。隔离配置没有 source checkout/OTLP,整体 ready=false;placeholder 只证明 key 存在,不证明供应商认证。 | + +中央 `cargo check --locked`、`cargo clippy --locked -- -D warnings`、 +`cargo build --locked`、`cargo fmt --check` 与 diff 空白检查通过。统一补丁的 +上游上下文标记和缩进按 `.gitattributes` 保留,不能为普通源码的空白规则破坏补丁输入。 + +早期失败均保留,没有覆盖成成功。v5 的 await 传播遗漏导致实际加载 parse 错误; +v6/v7 暴露 Mac lease 的 Linux-only 查询、writer 与 launcher PID 混淆及退出期间 +marker 竞态;v10 暴露 boottime 随校时漂移。它们分别通过完整调用传播、实际 payload +登记、Mac birth 查询、退出后的 OS 回读及 boot session UUID 修复。 +仍存活的身份冲突继续 unknown;旧 v10 unknown 不被较晚无人存活回读追认为当时成功。 + +## 未取得的反馈 + +没有运行 Braid/Factory 测试或模拟设施,没有重跑付费模型或旧运行。 +真实 subagent 推理、自然模型重试、跨 turn 未消费结果 drain、owner 恢复的模型路径 +及 Linux 现场仍未验。Context7/FFF/MCPorter 的装配及加载不证明外部工具请求 +旅程通过。当前源码融合不能替代下一轮冻结插件配方的真实模型双上游验收。 + +Mac 身份锚与标记都不能确认时保持 unknown。此合同不是安全沙箱,不能撤销已发出的 +外部请求。SDK 的 root-descendants 回执不等于全 execution 停止;父退出后的全范围 +证明另取 e14,不能仅靠父 exit 0。 + +主 Agent 首次中央 Cargo 命令漏设 WorkSSD cache/TMPDIR,写入系统 `~/.cargo` +缓存后中止;后续命令全部明确使用 WorkSSD。保留此存储偏差,不宣称本轮全项合格, +不擅自删除共享全局缓存。独立 Braid 仅本地提交,未推送或发布。 diff --git a/tasks/real-model-e2e/builtin-results.md b/tasks/real-model-e2e/builtin-results.md new file mode 100644 index 00000000..05ddc362 --- /dev/null +++ b/tasks/real-model-e2e/builtin-results.md @@ -0,0 +1,55 @@ +# 内建上游真实模型执行记录 + +2026-10-11 用户批准的真实流程已开始。原候选 binary 0.3.2/1fdef82,SHA-256见 braid-e2e/builtin/raw/startup.json;模型为官方 MiniMax-M3,凭据仅通过加载器注入,账户扣费未知。配置修正为计划的 quiet30/count8/reconcile60;Issue/PR角色指令落实不同责任。基线2d65e72仅含需求、说明占位和忽略规则,没有业务实现。 + +原版本 Console 实际启动,Issue1正常指派 issue-minimax 后仅 materialize idle Pi session;真实人类实施请求经过quiet窗口开启turn01a129fc-ff4c-7cc1-84a2-049adc4b9ae1,原生JSONL含实际user/assistant/toolResult,最终completed。IssueAgent自主维护设计、建立空提交e2ae347并创建关联PR2。根独立证明bootstrap tree未改变。首版 provider connected 但 readyfalse:src/health.rs仅检查旧ingress local,已修为builtin;全范围rg未发现其它此生命周期检查遗漏。原始错误与首版binary保留,不将其混成无修复黄金路径。 + +修正严格Clippy及build通过,公开stop后Console正常shutdown退出0;重启Console读取上一代state=stopped证明停止。修正版binary及SHA见raw/ready-fix-version.json;再次真实start后provider connected且readytrue。正常操作者已指派PR2给pr-minimax并提交实施评论,没有代写业务实现。模型候选尚未交付,黄金路径、矩阵与应用验收尚未完成。 + +原始证据在 /Volumes/WorkSSD/Development/braid-e2e/builtin/raw:startup.json、initial-runtime.json、create-assign-start.json、first-human-request.json、initial-request-ledger.json、issue-agent-completion-objects.json、first-stop-request.json、first-stop-confirmed.json(请求停止后中间状态为stopping,终态由Console正常退出和下一次readyfix-restart-pr-assign.json中的stopped读回确认)、ready-fix-version.json、readyfix-restart-pr-assign.json、pr-first-human-request.json、readyfix-runtime.json;Collector数据库及原生session另保留。 + + +首PR真实实现已提交25f92ed815c2d268b07da2ed72b8bc567c895ddd,但自行publish失败,不能将该未发布提交当正常交付。错误为“publish requires a clean committed worktree”;实际git status porcelain为空,ignored session/store/cache存在。实际依赖libgit2 status.h 的默认flags含INCLUDE_IGNORED,而Gateway直接statuses(None),因此根因是忽略文件被算dirty。Gateway改为显式包含untracked并递归、排除ignored,具体dirty路径进入错误。平台另一clean consumer已有显式options,不受同默认flags影响。 + +为应用该设施修复发出公开active stop,实际获得blocked,而非正常stop:两个group均报告“session reception is unknown: provider request Pi child exit after stop timed out”。PR turn落库interrupted且grantrevoked,只证明执行和写入fence,不证明原生child退出。原Console保持blocked,不私改ledger或再次启动。原件见raw/publish-failure-active-stop.json、publish-failure-stop-observed.json、publish-failure-stop-latest.json。稳定native生命周期owner接续有界调查和具体停止证据;黄金路径及后续矩阵仍在途。 + + +停止缺陷根因已从真实依赖源码确认:Tokio Unix ChildStdin::poll_shutdown只返回Ready而不关闭pipeFD;Pi rpc模式依赖stdin end后dispose/exit。Braid持有writer等child退出导致双方互等30秒。稳定owner已修关闭路径take/drop真实stdin FD后wait,仍保留child wait失败合同。旧代次cached failed及blocked receipt不能重开Console清除;当前公开Start/Stop无retry/resolve能力,旧失败保留,恢复方式待根确认,未改ledger。 + +旧cap迟到写实际验证:Harness revoke主动清空token,首次直接使用已清空token的尝试422只是格式拒绝,不算fencing通过(原错误保留raw/late-revoked-writer.json)。随后使用原授予requestId幂等读取原合法cap回执,携带当前正确对象revision提交迟到Agent comment,实际HTTP409且具体原因“writer grant is stale, revoked, or does not cover this actor/item”,cap未输出/证据脱敏。真正fencing证据raw/late-revoked-writer-valid-cap.json。平台在Harness blocked期间仍可读写请求回执,生命周期独立。 + + +根与advisor决定不增加凭无PID解锁blocked的入口。依已批准设施修复后重跑计划,准备全新builtin-attempt2:独立Git对象库从原初始6425f01 clone,新的需求文档基线d9ba1e5,无旧25f92ed对象/业务答案;新source/platform/Harness/Console/providerhome与ports19318/19282/19281均在独立WorkSSD空间。修复binarySHA2376520c0dc3eda2680c71f64e7b705fced2eda515bc3feb3227053cf44c4bd5,configcheck通过。旧attempt1 retained blocked,未启动attempt2直到有界原工具/所有权核对完成。首次in-place安装后Mac拒执行(exit137)的原始工具输出保留;改WorkSSD临时新inode原子rename后同binary实际configcheck退出0,后续安装使用此方式。 + + +Attempt2 使用完全独立source、platform、Harness及Console空间,文档基线fb1449e不含旧业务实现。IssueAgent真实空提交ae8c303后创建PR2,正常指派PR Agent后真实实现并自行publish 1af8086,strict Clippy/build及实际模型publish证明ignored clean修复已消费。根独立初始CLI验收通过原需求,补充发现损坏结构[]触发AttributeError;正常人类反馈加关联Issue设计变更后模型实际提交并publish d639ff30,根10次CLI核对通过重复标题唯一ID、list --all状态、归档、持久化和损坏结构友好错误。 + +Pending普通讨论经过真实stop/restart,仅组合成一个event_count2的新turn,先前turn未重复执行。公开stop终态stopped且平台仍在线;Collector真实native process wait记录2624/2625分别PR PID97663、Issue PID92107,graceful_eof exited、ExitStatus0/code0,不能仅从Session span confirmed推导该事实。证据builtin-attempt2/raw/waiting-stop-child-exit-otlp.json。当前正文更新前读取PRturn为running,实际编辑后旧turn interrupted、新session接续,context reset applied;完整前后证据active-pr-body-change.json、active-pr-body-reset-observed.json。 + +定向原生toolCall核对确认Agent实际写过系统/tmp:/tmp/issue1-design.md、/tmp/pr1-body.md、/tmp/notes-evidence/*等。29个含/tmp的实际调用原件保留system-tmp-tool-facts.json,未展开assistant/CoT,也未删除原文件。本轮Mac存储合规为failed,不用后来WorkSSD澄清抵销。已正常人类评论及PR正文明确后续所有数据、临时、材料、缓存必须WorkSSD且禁止/tmp;GitHub后续两个Profile实际原生指令也冻结同约束。 + +Console首次Diff对象详情与稍后diff响应竞态身份原件由browser保留。平台API修复为单次读PR快照,以不可变head/base OID生成diff并同响应number/revision/headCommit/baseCommit,不在生成后重新读取标签;Console UI由独立owner消费并标明过期。strict Clippy/build已通过,尚待正常停止部署和实际读回。 + + +Diff身份修复实际部署SHA3dc0187b6cb9799714a076d14ad885eef1ef302c1c05d0ac41d7860b9688bdf2后,浏览器独立确认固定revision14/head d639ff30/base fb1449e及旧详情读取revision15的过期提示。系统提示重读设计改用object context,真实PRg2 toolResult92700617含可见marker与list --all、隐藏marker不存在;根独立定向确认。这只证明canonical重读,原rawshow含隐藏HTML事实不抹去。提示变化导致旧session instruction_revision不兼容并blocked,整体readytrue不是这些session可resume证明;正常同actor重新指派建立g2/g3新代次,未绕过旧兼容门控。 + +真实activecap在内存保留后,同actor重指派再使用正确revision+旧cap提交迟到comment,实际409具体stale/revoked原因,原件sameactor-reassign-late-writer.json无token。PRg2最终retired、g3active;正常close使真实finalization turn01a12a22-9a28…completed、g3retired。首次finalizer object context因Gateway将纯读也置于grant门控后而拒绝,原件closed-finalizer-read-rejection.json。纯List/Show/Context/Diff/Receipt现位于write admission前,保留BuiltinClient持久space绑定、所有写入原身份/grant门控;严格Clippy/build通过,SHAb530f0a47ebc1e490979be8036b272d5859fd60fd32374ce50f435b2bd44762a实际部署。 + +正常reopen后真实turn01a12a26-00dc…running时公开active stop,终态stopped/errornull;Collector真实child wait记录保留readonly-fix-active-stop-native-exits.json,未以DBinterrupted替代exit proof。根合格固定d639ff30候选通过正常operator merge采纳,main真实merge77c8f50a5323756dc85d7a8e7f2dde2d91526c6f,根独立两parent/tree读回确认。合并后immutable detail=merged事件却仍pending,Store只选择closed/reopened、prepare也仅closed,Group不能进入finalization;原件merged-pending-before-lifecycle-fix.json保留。已必要共享修复完整三边界接受merged同闭合终态,不用伪closed事件替代,strictClippy通过,最终部署/自然finalizer在途。 + +仅本任务tool命令证明且mtime位于attempt2的22个系统临时文件已元数据/hash校验、保留WorkSSD raw/recovered-system-tmp后移走,两个目录不递归删;crossproc/notes.json经原脚本STORE_DIR/STORE确切变量证明追加回收,manifest保存。搬迁不追认本轮存储合规通过。 + + +完整merged修复严格Clippy/build通过,最终实际二进制SHA81f963d0d5b7b4597e3707527deb0e01c4775f99197e7be242b82e84a556ccd9。Harness投影在新merged事件将状态规范为merged;已admitted原pending merge在prepare事务依据不可变detailmerged投影同事实,保留eventID/detail/cursor,并由现有closed降级保护维持该终态。原merge只开启一次finalization,PRturn01a12a2b-aa03…真实completed后assignment/agent/currentprovider session/worktree全retired;Issue正常close的finalization01a12a2b-d62b…completed后sleeping,不混同永久退休。 + +Merged finalizer实际调用object context成功,toolResult7dee10fa/302aa82c保留filtered投影事实,没有恢复writergrant。根请求实际closedwrite时finalizer刚已terminal,直接活跃身份CLI项目为unavailable;未伪造活跃会话。随后通过原真实授予requestId公开幂等读取原cap(不新mint,不保留/展示token),原actor与正确currentrevision提交闭合PR迟到comment,HTTP409具体stale/revoked拒绝。此前回执tuple错误/附lifecycle字段HTTP422和证据formatterKeyError均保留在merged-actual-cap-late-write-rejection.json中,不当fencing证明。 + +Postmerged普通人类评论正常被平台接受,quiet30后PRturn总数仍9;正常stop/restart再quiet30仍9,没有重复merge finalization或PR再激活。首次操作者restart传null generation导致HTTP409(门控正确),改用实际stopped generation后正常受理,原错误保留retired-restart.json。最后publicstop终态stopped/errornull,平台Issue1closedrev9/PR2merged closedrev22及Collector11193条记录仍在线可读,raw/final-stop-platform-collector-retained.json保存。最后有模型代次01a12a2b-a7cf…Pi真实wait11001 IssuePID33110、11154 PRPID33111均graceful_eof/exited/ExitStatus0/code0;最后新代无native激活后stop正常完成。 + +内建实际产品闭环及批准矩阵已完成;首attempt1 failed/unknown、attempt2系统盘违规failed、rawshow含隐藏HTML的范围事实均保持,不能把修复后完成称为全程无故障或存储合规通过。固定业务候选1af8086→设计/[]修复d639ff30→实际合并77c8f50a;根独立应用CLI及Git采纳身份取证另见qualification-results.md。GitHub阶段须沿用最终同版二进制并冻结两Profile明确WorkSSD实体路径约束,网络/App由其稳定owner启动。 + + +本轮原生SDK usage仅metadata、按responseId去重:Builtin attempt1 input56908/output21881/cacheRead1423468/total1502257,冻结价格估算RMB0.90116376;全隔离attempt2 input289415/output80919/cacheRead4711772/total5082106,估算RMB3.26643534。input2.10/output8.40/cache-read0.42 RMB/M token,账号实际扣费未知,nativecost0不当免费;分项原件分别builtin/raw/native-usage-aggregate.json和builtin-attempt2/raw/native-usage-aggregate.json。原生文件数量不替代Braid角色或完整恢复身份。 + + +最终原件验收后旧14318 Console正常结束exit1,保留具体原stop unconfirmed/Pi child exit timed out错误及DB blocked/unknown;服务器退出不追认旧native正常停止。18282/19282平台与14318/19318 Console均实际无监听,原件保留。退出及资源事实归github-attempt2/raw/final-console-process-exit.json。 diff --git a/tasks/real-model-e2e/config/builtin-platform.toml b/tasks/real-model-e2e/config/builtin-platform.toml new file mode 100644 index 00000000..daf6ddd6 --- /dev/null +++ b/tasks/real-model-e2e/config/builtin-platform.toml @@ -0,0 +1,7 @@ +schema_version = 1 +repository = "braid-poc-test" +source = "/Volumes/WorkSSD/Development/braid-e2e/source/builtin" +default_branch = "main" +database = "/Volumes/WorkSSD/Development/braid-e2e/platform/state/platform.sqlite3" +backups = "/Volumes/WorkSSD/Development/braid-e2e/platform/backups" +listen = "127.0.0.1:18282" diff --git a/tasks/real-model-e2e/config/builtin.toml b/tasks/real-model-e2e/config/builtin.toml new file mode 100644 index 00000000..f9580383 --- /dev/null +++ b/tasks/real-model-e2e/config/builtin.toml @@ -0,0 +1,87 @@ +schema_version = 3 + +[instance] +key = "real-e2e-builtin-minimax" + +[runtime] +root = "/Volumes/WorkSSD/Development/braid-e2e/builtin/state" +database = "/Volumes/WorkSSD/Development/braid-e2e/builtin/state/braid.sqlite3" +backups = "/Volumes/WorkSSD/Development/braid-e2e/builtin/state/backups" +worktrees = "/Volumes/WorkSSD/Development/braid-e2e/builtin/worktrees" +auto_migrate = false + +[builtin] +repository = "braid-poc-test" +endpoint = "http://127.0.0.1:18282/" + +[scheduler] +quiet_seconds = 30 +event_threshold = 8 +reconciliation_seconds = 60 + +[[runtimes]] +adapter_type = "pi" +version = "1.0.2" +executable = "/Users/lanzhijiang/Library/pnpm/bin/pi" +home = "/Volumes/WorkSSD/Development/braid-e2e/builtin/provider/pi" + +[[llm_providers]] +id = "minimax" +protocol = "openai-compatible" +api_key_environment = "MINIMAX_API_KEY" + +[[llm_providers.models]] +model_id = "MiniMax-M3" +input_cost = 2.10 +output_cost = 8.40 +cache_input_cost = 0.42 + +[tools] +git = "/usr/bin/git" +gh = "/opt/homebrew/bin/gh" +wrangler = "/Volumes/WorkSSD/Development/braid-e2e/wrangler/node_modules/wrangler/bin/wrangler.js" + +[server] +ingress = "127.0.0.1:18280" +health = "127.0.0.1:18281" + +[telemetry] +endpoint = "http://127.0.0.1:14318/" +sample_ratio = 1.0 +incident_mode = true +export_timeout_seconds = 5 +service_name = "braid-real-e2e-builtin" +log_format = "text" + +[[profiles]] +id = "issue-minimax" +display_name = "MiniMax Issue Agent" +tags = ["issue"] +adapter_type = "pi" +adapter_version = "1.0.2" +provider = "minimax" +model = "MiniMax-M3" +reasoning = "medium" +user_instructions = "你只负责需求设计、实施请求和 Issue 工作记忆,不编写或修改业务实现。业务范围仅 e2e-notes/20261011-minimax-peer-upstreams/。需求明确后自行创建关联 PR 交给 PR Agent,发布简洁证据。当前上游为 Braid 内建平台:在专属工作树建立仅空提交的候选分支(git commit --allow-empty),然后 braid object --config \"$BRAID_CONFIG_PATH\" pr --title ... --head <候选分支> --base main --issue <当前Issue编号> 创建关联 PR。PR 将由正常操作者指派 pr-minimax,不要自行实现业务,也不要自行合并。" +workspace = "/Volumes/WorkSSD/Development/braid-e2e/source/builtin" +status_surfaces = ["issue"] +github_context_soft_ratio = 0.80 +github_context_hard_bytes = 524288 + +[[profiles]] +id = "pr-minimax" +display_name = "MiniMax PR Agent" +tags = ["pr", "implementation"] +adapter_type = "pi" +adapter_version = "1.0.2" +provider = "minimax" +model = "MiniMax-M3" +reasoning = "medium" +user_instructions = "只在专属工作树依据当前关联 Issue 与 PR 工作记忆实现业务,范围仅 e2e-notes/20261011-minimax-peer-upstreams/。实际调用生成应用而不添加测试文件,提交真实 diff 并发布简洁应用操作证据。交付真实 Git commit 后自行 braid object --config \"$BRAID_CONFIG_PATH\" publish <当前PR编号> 冻结候选OID。不要自行合并。" +workspace = "/Volumes/WorkSSD/Development/braid-e2e/source/builtin" +status_surfaces = ["pr"] +github_context_soft_ratio = 0.80 +github_context_hard_bytes = 524288 + +[profile_selection] +default_pr_profile = "pr-minimax" diff --git a/tasks/real-model-e2e/config/github-attempt2.toml b/tasks/real-model-e2e/config/github-attempt2.toml new file mode 100644 index 00000000..4fec5b21 --- /dev/null +++ b/tasks/real-model-e2e/config/github-attempt2.toml @@ -0,0 +1,92 @@ +schema_version = 3 + +[instance] +key = "real-e2e-github-minimax-attempt2" + +[runtime] +root = "/Volumes/WorkSSD/Development/braid-e2e/github-attempt2/state" +database = "/Volumes/WorkSSD/Development/braid-e2e/github-attempt2/state/braid.sqlite3" +backups = "/Volumes/WorkSSD/Development/braid-e2e/github-attempt2/state/backups" +worktrees = "/Volumes/WorkSSD/Development/braid-e2e/github-attempt2/worktrees" +auto_migrate = false + +[github] +app_id = 4780313 +repository = "xiaoland/braid-poc-test" +handle = "braid" +api_version = "2022-11-28" +private_key_file = "/Users/lanzhijiang/.braid/instances/xiaoland/github-app.pem" +webhook_secret_file = "/Users/lanzhijiang/.braid/instances/xiaoland/secrets.toml" +projects_v2_enabled = false + +[scheduler] +quiet_seconds = 30 +event_threshold = 8 +reconciliation_seconds = 60 + +[[runtimes]] +adapter_type = "pi" +version = "1.0.2" +executable = "/Users/lanzhijiang/Library/pnpm/bin/pi" +home = "/Volumes/WorkSSD/Development/braid-e2e/github-attempt2/provider/pi" + +[[llm_providers]] +id = "minimax" +protocol = "openai-compatible" +api_key_environment = "MINIMAX_API_KEY" + +[[llm_providers.models]] +model_id = "MiniMax-M3" +input_cost = 2.10 +output_cost = 8.40 +cache_input_cost = 0.42 + +[tools] +git = "/usr/bin/git" +gh = "/opt/homebrew/bin/gh" +wrangler = "/Volumes/WorkSSD/Development/braid-e2e/wrangler/node_modules/wrangler/bin/wrangler.js" + +[server] +ingress = "127.0.0.1:18180" +health = "127.0.0.1:18181" + +[telemetry] +endpoint = "http://127.0.0.1:25318/" +sample_ratio = 1.0 +incident_mode = true +export_timeout_seconds = 5 +service_name = "braid-real-e2e-github" +log_format = "text" + +[[profiles]] +id = "issue-minimax" +display_name = "MiniMax Issue Agent" +tags = ["issue"] +adapter_type = "pi" +adapter_version = "1.0.2" +provider = "minimax" +model = "MiniMax-M3" +reasoning = "medium" +user_instructions = "你只负责需求设计、实施请求和 Issue 工作记忆,不编写或修改业务实现。业务范围仅 e2e-notes/20261011-minimax-peer-upstreams/。需求明确后自行创建关联 PR 交给 PR Agent,发布简洁证据。当前上游为 GitHub:使用 braid gh pr ensure 建立关联 Draft PR 并交接 PR Agent。不要自行合并。 本轮环境约束:所有应用数据、验收证据、临时文件、材料和缓存仅可放在 /Volumes/WorkSSD/Development/braid-e2e/github-attempt2/ 或当前WorkSSD工作目录;禁止使用 /tmp、系统盘及用户目录作为写入位置,不得仅依赖TMPDIR。" +workspace = "/Volumes/WorkSSD/Development/braid-e2e/github-attempt2/source" +status_surfaces = ["issue"] +github_context_soft_ratio = 0.80 +github_context_hard_bytes = 524288 + +[[profiles]] +id = "pr-minimax" +display_name = "MiniMax PR Agent" +tags = ["pr", "implementation"] +adapter_type = "pi" +adapter_version = "1.0.2" +provider = "minimax" +model = "MiniMax-M3" +reasoning = "medium" +user_instructions = "只在专属工作树依据当前关联 Issue 与 PR 工作记忆实现业务,范围仅 e2e-notes/20261011-minimax-peer-upstreams/。实际调用生成应用而不添加测试文件,提交真实 diff 并发布简洁应用操作证据。提交真实 diff 后自行 push 当前PR分支并更新PR工作记忆。不要自行合并。 本轮环境约束:所有应用数据、验收证据、临时文件、材料和缓存仅可放在 /Volumes/WorkSSD/Development/braid-e2e/github-attempt2/ 或当前WorkSSD工作目录;禁止使用 /tmp、系统盘及用户目录作为写入位置,不得仅依赖TMPDIR。" +workspace = "/Volumes/WorkSSD/Development/braid-e2e/github-attempt2/source" +status_surfaces = ["pr"] +github_context_soft_ratio = 0.80 +github_context_hard_bytes = 524288 + +[profile_selection] +default_pr_profile = "pr-minimax" diff --git a/tasks/real-model-e2e/config/github.toml b/tasks/real-model-e2e/config/github.toml new file mode 100644 index 00000000..29e787e3 --- /dev/null +++ b/tasks/real-model-e2e/config/github.toml @@ -0,0 +1,92 @@ +schema_version = 3 + +[instance] +key = "real-e2e-github-minimax" + +[runtime] +root = "/Volumes/WorkSSD/Development/braid-e2e/github/state" +database = "/Volumes/WorkSSD/Development/braid-e2e/github/state/braid.sqlite3" +backups = "/Volumes/WorkSSD/Development/braid-e2e/github/state/backups" +worktrees = "/Volumes/WorkSSD/Development/braid-e2e/github/worktrees" +auto_migrate = false + +[github] +app_id = 4780313 +repository = "xiaoland/braid-poc-test" +handle = "braid" +api_version = "2022-11-28" +private_key_file = "/Users/lanzhijiang/.braid/instances/xiaoland/github-app.pem" +webhook_secret_file = "/Users/lanzhijiang/.braid/instances/xiaoland/secrets.toml" +projects_v2_enabled = false + +[scheduler] +quiet_seconds = 30 +event_threshold = 8 +reconciliation_seconds = 60 + +[[runtimes]] +adapter_type = "pi" +version = "1.0.2" +executable = "/Users/lanzhijiang/Library/pnpm/bin/pi" +home = "/Volumes/WorkSSD/Development/braid-e2e/github/provider/pi" + +[[llm_providers]] +id = "minimax" +protocol = "openai-compatible" +api_key_environment = "MINIMAX_API_KEY" + +[[llm_providers.models]] +model_id = "MiniMax-M3" +input_cost = 2.10 +output_cost = 8.40 +cache_input_cost = 0.42 + +[tools] +git = "/usr/bin/git" +gh = "/opt/homebrew/bin/gh" +wrangler = "/Volumes/WorkSSD/Development/braid-e2e/wrangler/node_modules/wrangler/bin/wrangler.js" + +[server] +ingress = "127.0.0.1:18180" +health = "127.0.0.1:18181" + +[telemetry] +endpoint = "http://127.0.0.1:24318/" +sample_ratio = 1.0 +incident_mode = true +export_timeout_seconds = 5 +service_name = "braid-real-e2e-github" +log_format = "text" + +[[profiles]] +id = "issue-minimax" +display_name = "MiniMax Issue Agent" +tags = ["issue"] +adapter_type = "pi" +adapter_version = "1.0.2" +provider = "minimax" +model = "MiniMax-M3" +reasoning = "medium" +user_instructions = "你只负责需求设计、实施请求和 Issue 工作记忆,不编写或修改业务实现。业务范围仅 e2e-notes/20261011-minimax-peer-upstreams/。需求明确后自行创建关联 PR 交给 PR Agent,发布简洁证据。当前上游为 GitHub:使用 braid gh pr ensure 建立关联 Draft PR 并交接 PR Agent。不要自行合并。 本轮环境约束:所有应用数据、验收证据、临时文件、材料和缓存仅可放在 /Volumes/WorkSSD/Development/braid-e2e/github/ 或当前WorkSSD工作目录;禁止使用 /tmp、系统盘及用户目录作为写入位置,不得仅依赖TMPDIR。" +workspace = "/Volumes/WorkSSD/Development/braid-e2e/source/github" +status_surfaces = ["issue"] +github_context_soft_ratio = 0.80 +github_context_hard_bytes = 524288 + +[[profiles]] +id = "pr-minimax" +display_name = "MiniMax PR Agent" +tags = ["pr", "implementation"] +adapter_type = "pi" +adapter_version = "1.0.2" +provider = "minimax" +model = "MiniMax-M3" +reasoning = "medium" +user_instructions = "只在专属工作树依据当前关联 Issue 与 PR 工作记忆实现业务,范围仅 e2e-notes/20261011-minimax-peer-upstreams/。实际调用生成应用而不添加测试文件,提交真实 diff 并发布简洁应用操作证据。提交真实 diff 后自行 push 当前PR分支并更新PR工作记忆。不要自行合并。 本轮环境约束:所有应用数据、验收证据、临时文件、材料和缓存仅可放在 /Volumes/WorkSSD/Development/braid-e2e/github/ 或当前WorkSSD工作目录;禁止使用 /tmp、系统盘及用户目录作为写入位置,不得仅依赖TMPDIR。" +workspace = "/Volumes/WorkSSD/Development/braid-e2e/source/github" +status_surfaces = ["pr"] +github_context_soft_ratio = 0.80 +github_context_hard_bytes = 524288 + +[profile_selection] +default_pr_profile = "pr-minimax" diff --git a/tasks/real-model-e2e/config/models.json b/tasks/real-model-e2e/config/models.json new file mode 100644 index 00000000..c9964252 --- /dev/null +++ b/tasks/real-model-e2e/config/models.json @@ -0,0 +1,28 @@ +{ + "providers": { + "minimax": { + "baseUrl": "https://api.minimax.cn/v1", + "api": "openai-completions", + "apiKey": "$MINIMAX_API_KEY", + "models": [ + { + "id": "MiniMax-M3", + "name": "MiniMax M3", + "api": "openai-completions", + "reasoning": true, + "input": ["text", "image"], + "contextWindow": 1000000, + "maxTokens": 65536, + "compat": { + "supportsStore": false, + "supportsDeveloperRole": false, + "supportsReasoningEffort": false, + "supportsStrictMode": false, + "maxTokensField": "max_tokens", + "thinkingFormat": "openai" + } + } + ] + } + } +} diff --git a/tasks/real-model-e2e/console-results.md b/tasks/real-model-e2e/console-results.md new file mode 100644 index 00000000..2ba154dc --- /dev/null +++ b/tasks/real-model-e2e/console-results.md @@ -0,0 +1,71 @@ +# 真实模型端到端 Console 回读 + +Console 浏览器由 console_web 独立只读操作,运行控制与对象写入由旅程 Owner 负责。此记录不替代生成应用验收,不把 OTLP 接收、Provider 退出或请求受理当作业务完成。屏幕与 DOM 原件保存在 `/Volumes/WorkSSD/Development/braid-e2e/builtin/browser/`。 + +2026-10-11 16:03(Asia/Shanghai)初始内建回读:Console `http://127.0.0.1:14318/`,平台 `http://127.0.0.1:18282/`。权威 supervisor 为 running,Generation `01a129fb-b381-7433-ad29-077d7539032a`,Provider 启用且 health.provider=connected、ingress=builtin;ready=false,已向 runtime Owner 回报其正在修复的 ingress 判断问题,尚未宣称就绪。Collector 已接收 27 条、7 批次,资源实例 `real-e2e-builtin-minimax`、服务 `braid-real-e2e-builtin`;此计数仅为打开概览时的快照。 + +平台 Issue #1「20261011-minimax-peer-upstreams 离线笔记 CLI」open、revision=3、作者 operator、指派 issue-minimax。Harness 独立账本展示 active Assignment、Pi session 及 Worktree,upstream cursor=3;当时 Turn 列表尚为空,随后定向 Session 日志查询已显示 Turn `01a129fc-ff4c-7cc1-84a2-049adc4b9ae1`、Trace `189f0d83a5fc34ba047dcfe426b75f2d`。原生会话 ID 是 WorkSSD 的 Pi jsonl 路径,和 Harness 登记一致。初始化 observation 不带 Turn 时界面明确显示「Turn 未关联」,未编造完整会话。只读取当前 Session 的首个有界页面,没有展开完整 rollout。 + +证据:`initial-overview.jpg/.txt`(完整 supervisor 与 Harness snapshot)、`initial-issue.jpg/.txt`、`initial-session-filter.jpg/.txt`。当前仍等待 Owner 的健康修复、PR 候选与最终停止节点,未完成本轮端到端资格。 + +16:06 修复后回读:新 Generation `01a129ff-19d0-73a3-93e2-b6ae52a9e24c` 为 running、Ready 是、Provider 启用;Collector 1078 条/120 批次,仍只有上述真实实例,没有伪造第二来源。PR #2 作者 issue-minimax、open revision=3、指派 pr-minimax,正文关联 Issue #1,Head `e2ae347be95a9d49f015b5c33cb36bf6d4dee553`、候选未发布。此阶段不判定业务实现完成;空提交的独立 Git 验证由根负责。 + +独立账本显示 Issue Session resume_count=1,PR 原生 session `2026-10-11T08-05-48-190Z_01a129ff-201e-7542-8b4b-2b40dd231ee0.jsonl`、PR Turn `01a129ff-20c6-7a73-a19b-13a3a1dd5ac4`、upstream cursor=9。浏览器按 instance + 完整 Provider Session + Turn 三项精确筛选,原生事件记录 #842 显示 Trace `4a904799b3532af8b73ec56b82a07afa`。只展开该单条 get_state 请求属性:provider.kind=pi、work_item.kind=pr/number=2、Assignment `01a129ff-1ae1-7b72-a0e3-cb0924fcc230`、generation 和 Turn 均与账本匹配,observation.correlated=true/sample=true。provider.turn.id 为空时保留原值,不当成已登记原生 turn ID。 + +证据新增 `ready-overview.jpg/.txt`、`bootstrap-pr.jpg/.txt`、`pr-turn-session.jpg/.txt`、`pr-turn-attributes.txt`。尚等待真实业务候选发布与最终停止/Collector 留存节点。 + +16:10 等待候选期间的一次独立指标回读:指标页已收到 22 条原始记录,真实 `braid.provider.lifecycle.events` 显示 Pi prompt accepted,`braid.provider.payloads` 区分 correlated=true 的采样内容和启动阶段 correlated=false 的 4 条内容。`braid.provider.turn.elapsed` 为 s 单位 histogram,16:04:54 的 completed/Pi 数据点 count=1、sum/min/max=85.58862175,界面显示原始分布而不跨批次求和。`braid.runtime.transitions` 的 generation_started 文字明确注明不是运行停止证明。证据 `live-provider-metrics.jpg/.txt`;指标事实不判定应用成功。 + +16:17 内建第一现场终态回读:Console 当前 supervisor 为 **blocked,不是 stopped**,Generation 仍为 `01a129ff-19d0-73a3-93e2-b6ae52a9e24c`。完整错误保留两条 session 的 `shutdown did not confirm all executions stopped: session reception is unknown: provider request Pi child exit after stop timed out`;health.ready=false。此轮停止资格未通过,不能用 Turn interrupted、grant 撤销或之后找不到进程追认实际停止成功。浏览器没有发出停止或重启命令。 + +Collector 在 blocked 状态仍可读:3084 条、342 批次、接收错误/重复批次均为 0,原实例与接收历史保留。证据 `blocked-stop-overview.jpg/.txt` 展开了 supervisor 原始状态及错误。后续修复重跑须保留此现场身份;等待根或旅程 Owner 的阶段交接与新隔离现场,当前不宣称本轮端到端验收完成。 + +根决定保留第一现场 blocked,不追认 stopped;下一次采用全新 attempt2 source、Git 对象库、平台、Harness ledger 与原生 home,Console 端口 19318、平台端口 19282。旧页面已关闭,证据保留;后续浏览器资格单独记录 attempt2,不复用第一轮业务实现结论。最终停止须对应 supervisor 与实际 Pi PID/session/ExitStatus/generation 事件,SDK teardown 仅作为采集收尾证据。 + +## 内建独立 attempt2 + +16:25 浏览器打开独立 Console `http://127.0.0.1:19318/`,平台 `http://127.0.0.1:19282/`,Generation `01a12a0e-48bb-7151-98ea-720f322493c6`。Supervisor running、Ready 是、Provider 启用;Collector 1486 条/130 批次、接收错误/重复均 0。资源实例明确是 `real-e2e-builtin-minimax-attempt2`,不混作旧现场;服务仍为 `braid-real-e2e-builtin`。原件保存在 `/Volumes/WorkSSD/Development/braid-e2e/builtin-attempt2/browser/`。 + +PR #2「实现离线笔记 CLI(Issue #1)」由 issue-minimax 创建、指派 pr-minimax、revision=2、open,候选尚未发布。Head `ae8c303c4519994eeac67da6b4036fe2c8f1f2df`、Base `fb1449e3321faa6494472f42a7e6fe2b09aebc37`;正文明确关联 Issue #1。独立 Harness 账本的 upstream cursor=8,space_id=`01a12a0e-24e4-7881-99db-39ca1de1b190`,Issue Turn 已 completed、PR Turn running。 + +按新 instance + PR 原生 session + Turn 精确筛选,记录 #1043 的 get_state 请求标出 Provider pi、PR #2、Assignment `01a12a10-d529-7b63-8240-79f035eaa6e8`、上述 Generation、Turn `01a12a10-d73c-76a0-b9d1-0388b78a1a39`、Trace `c691a2045883120fc7d511d290cd9d28`,与账本对应;correlated=true、sampled=true。只展开这一条属性,未通读 rollout。 + +证据 `ready-overview.jpg/.txt`、`bootstrap-pr.jpg/.txt`、`pr-turn-session.jpg`、`pr-turn-attributes.txt`。尚未回读业务候选/最终真实停止,仍不判定完整旅程通过。 + +16:31 停止历史回读时,Owner 已完成首代 stop 并 restart。当前 supervisor 为新 Generation `01a12a15-11d7-7d93-a5f3-38dc9e3082f7` running、Ready 是,Collector 3234 条/244 批次、错误及重复 0。因此没有把浏览器当前 running 记录成 stopped。定向 Trace `c691a2045883120fc7d511d290cd9d28` 已收到 PR Session Span #2639(batch205),对应首代 Generation、PR Assignment 与原生 Session;16:28:24 的生命周期事件明确 `stop / confirmed`、error.reason 为空,Session Span 时长 195432.94 ms。证据 `first-generation-stop-trace.jpg/.txt`。 + +运行 Owner 的 `/Volumes/WorkSSD/Development/braid-e2e/builtin-attempt2/raw/waiting-stop-child-exit-otlp.json` 原件经定向读取:首代记录 #2624/#2625 分别为 PR PID97663、Issue PID92107,`operation=wait / stage=graceful_eof / outcome=exited / exit status: 0 / code=0`,Session 与 Generation 都可对应。idle 停止的 trace/span 为空,按 Session + Generation 关联,不伪造 Turn。此证据仅说明这两个 Pi 子进程实际 wait 退出;原 body 仍提醒 detached tools 不能由父进程退出推断。Owner 保存的停止回执 request_id `b5c775b5-6d46-4437-a9c9-eb634f862ad7` 终态为 stopped;最终旅程停止尚未发生。 + +16:32 PR2 revision9 显示已发布首业务候选 `1af808614e0112274ac7eb0baff3d1839599264e`,Base 未变。平台讨论 #4/#7 可读,作者自述执行 `/tmp/notes-evidence/*`,已向根报告物理存储边界疑点,由运行负责人定向核实真实工具原件;Console 没有执行这些命令。只读 Diff 当时已经包含后续 `list --all` 与坏结构 `[]` 拒绝变更,但页面仍展示旧 Head。该异步发布竞态暴露了 Diff 响应缺少自身 OID/revision 的问题,已向根与平台 Owner 反馈;`first-published-pr-diff.jpg/.txt` 保留原始展示,不能将此 Diff 归属旧 `1af8086`。待响应携带实际候选身份后由 Console Owner 修复并实际回读,不重复应用 CLI 验收。 + +根采用独立判断后授权修复 Diff 显示身份。Console 仅修改 `src/console/web/console.js`,和平台 Owner 确认响应 `{number,revision,headCommit,baseCommit,diff}`:UI 将固定身份与内容一起呈现;详情不匹配时明确过期并可刷新,合并仍采用原详情 Revision;对象选择、路由 Generation 与请求序号拒绝迟到结果;加载/错误清除上一成功展示并保留具体原因。`node --check` 通过,无新增测试。平台冻结读取及整体编译部署由 runtime Owner 负责;本条是源码事实,尚未宣称实际部署或浏览器复验完成。 + +16:40 修复实际部署后,浏览器 reload 获取新版 UI,PR 详情 Revision14、Head `d639ff30d6a079fb5ede8dbd8a884feeaca3a4c0`,Base `fb1449e3321faa6494472f42a7e6fe2b09aebc37`。实际 Diff 响应的固定快照面板同时展示 number2/revision14/上述 OID 与内容,并声明与详情一致。运行 Owner 正常 start Harness 后发收口评论,PR Revision15;浏览器保持旧 Revision14 详情不刷新,再读 Diff,面板准确展示 Revision15 与 OID,并明确「对象详情已过期。此 Diff 属于以上固定快照;合并操作仍采用页面原 Revision 前提」,提供刷新详情入口。不是模拟响应或测试 fixture;Console 仍只读。证据 `diff-snapshot-current.jpg/.txt`、`diff-snapshot-stale.jpg/.txt`;旧错误展示继续保留。请求失败/迟到分支由代码边界处理,本次未人为故障注入。 + +16:50 新 binary `b530f0a47ebc1e490979be8036b272d5859fd60fd32374ce50f435b2bd44762a` 部署后,只读 PR2 为 closed / Revision21,详情依据持久合并状态显示 merged。候选 Head `d639ff30d6a079fb5ede8dbd8a884feeaca3a4c0` 与 Base `fb1449e3321faa6494472f42a7e6fe2b09aebc37` 保留;重开、发布候选及合并按钮均不存在,静态说明操作已结束。Diff 仍可读取,固定快照 Revision21/Head/Base 与详情一致;持久合并记录 lifecycle=applied、error=null、merge_commit=`77c8f50a5323756dc85d7a8e7f2dde2d91526c6f`。证据 `merged-pr.jpg/.txt`。这证明平台合并历史和 Console 展示,不替代根的固定 OID 应用验收;自然 finalization 的第一次读取拒绝及后续修复事实由运行 Owner 保留,不用此次 merged 展示覆盖它。最终停止/Collector留存尚待回读。 + +17:02 内建最终 Console 回读:权威 supervisor stopped、error=null、health.last_error=null,Generation `01a12a31-0bb0-7d11-b1d0-459dfffadc5f`(已退休对象之后正常 restart 的一代);Provider 字段保留 connected,不以该历史字段覆盖权威 stopped。Collector 11193 条/898 批次、接收错误及重复 0,仍可读取实例从16:22:22开始的历史。平台 Issue1 closed Revision9、PR2 closed/merged Revision22;停止后真实 Diff 固定 Revision22 与上述 Head/Base 匹配,持久合并记录仍 applied/error=null。首代 Trace `c691a2045883120fc7d511d290cd9d28` 的 Turn Span #2619、Session Span #2639 仍可读。证据 `final-stopped-overview.jpg/.txt`、`final-merged-pr.jpg/.txt`、`final-retained-trace.jpg/.txt`。 + +运行 Owner 另保存 merged 一代 `01a12a2b-a7cf…` 实际 Pi wait #11001(Issue PID33110)和 #11154(PR PID33111),均 graceful_eof/exited/exit0,原件 `raw/final-stop-platform-collector-retained.json`。最后退休后讨论及 quiet/restart 不产生新 PR Turn 的账本验证归 Owner,不用 Console 计数替代。内建浏览器资格完成,无在途 mutation;已交根和运行 Owner 收尾服务。接下来 Console Owner 持续接 GitHub 独立现场资格,不复用内建结论。 + +## GitHub 独立现场 + +17:05 浏览器打开 Console `http://127.0.0.1:24318/`,数据与内建分离。权威 supervisor running/Ready=true/provider=connected/error=null,Generation `01a12a34-bfdf-7cf2-aa33-0b060ce10573`,repository=`xiaoland/braid-poc-test`、ingress=`127.0.0.1:18180`、reconciliation=current。资源 instance=`real-e2e-github-minimax`、service=`braid-real-e2e-github`,Collector9条/4批次/接收错误0/重复0。尚无模型输入,Harness snapshot sessions/turns/assignments/worktrees/upstream为空,不推断生成完成。 + +Console 提供相同 Harness 启动/停止界面,浏览器只读没有点击控制;未声明内建平台,概览及协作页明确说明不提供 GitHub 对象编辑,不能用内建对象UI冒充GitHub写入。证据在 `/Volumes/WorkSSD/Development/braid-e2e/github/browser/initial-ready-overview.jpg/.txt`、`object-control-boundary.jpg/.txt`。等待运行 Owner 真实输入、Session/Turn、业务候选和最终停止节点;公网入口与GitHub App临时配置资格归网络 Owner。 + +GitHub 首现场由根判定未完成输入资格:实际 GitHub Issue37/comment 官方投递曾因 App URL 漏 `/webhook` 404;修正后,网络人为签名 ping 先用假 repository.id=1234/node 配真实 full_name,污染原 Harness ledger,使后续官方真实 node 与身份唯一约束冲突503。签名 ping202仅证明网络路径,不能替代官方投递。根与 Owner 明确此为验收输入污染,不改产品身份约束、不私删状态;此现场 sessions/turns=0,正常停止后转全新 GitHub attempt2 source/ledger/native/Collector,同空白baseline继续Issue37。浏览器原24318初始空账本与Ready画面保留 failed 输入资格身份,503原件归 `github/network`;不把新现场成功覆盖首次失败。 + +GitHub attempt2初始浏览器17:15回读:Console25318,独立路径 `/Volumes/WorkSSD/Development/braid-e2e/github-attempt2/browser/`,instance `real-e2e-github-minimax-attempt2`、service `braid-real-e2e-github`,Generation `01a12a3e-48a9-7b90-8ba1-8dc4f456b89b` running/Readytrue、Collector27条/7批次。17:15:33 Harness snapshot已出现真实 Issue node `I_kwDOUCYt2M8AAAABWa_jkA`,Assignment `01a12a3e-c5c4-7ad1-aa03-19a9e05d4d21` lifecycle=blocked、17:15:19退休,队列runnable/urgent,Session/Turn仍为空。已向Owner反馈,等待其具体原因处理,不由Ready推导模型执行或输入成功。证据 `initial-ready-overview.jpg/.txt`,与首次污染现场独立保存。 + +17:19 运行Owner修正GitHub g1工作目录fixture并保留blocked后,实际 g2 Assignment `01a12a40-8aeb-7d82-abb8-12cdfe60762f` active,原生 Session `2026-10-11T09-17-17-748Z_01a12a40-9434-7223-83ac-72bb9c356155.jsonl`(Issue37 WorkSSD worktree)running,Turn `01a12a40-9489-7742-8359-537e7b1b4933` running、trigger_kind=trusted_mention,queue consumed。新 Generation `01a12a40-6e34-7ac1-ac6d-071448487ac6`。 + +精确 instance+Session+Turn 过滤后,单条 get_state 请求日志 #93(batch19)显示 Issue37、Assignment generation2、上述 Runtime Generation、Turn 与 Session,Trace=`5da1abe0ec6bfbb118d6fb90ab3cd00c`,Provider pi/correlatedtrue/sampletrue。原生 provider.turn.id空值保留,不虚构。只展开这一条属性,没有通读rollout。证据 `issue37-running.jpg/.txt`、`issue37-turn-session.jpg`、`issue37-turn-attributes.txt`;这说明真实模型Session关联,不提前判定PR/应用或终态完成。 + +17:25 真实 GitHub Draft PR38 经实际事件激活:Harness node `PR_kwDOUCYt2M8AAAABHy1Epw` 对应 active Assignment `01a12a45-9e88-72f2-ab46-c647b97eccdb`(generation1)、Pi Session `2026-10-11T09-22-50-183Z_01a12a45-a6c7-76e3-bb13-8e4f9a0d6b46.jsonl`、Turn `01a12a45-a704-7e91-a362-90de0e9df458` running。Issue37原Session idle、其首次Turn completed,两个对象的原生Session/Worktree独立。浏览器精确过滤后单条 get_state #3317属性明确 pr/38、上述 Assignment、Runtime Generation `01a12a40-6e34-7ac1-ac6d-071448487ac6`、Session/Turn,Trace=`c68e2d6a0e94037f937224965f40dfbd`,sampled/correlatedtrue。未伪造初始化空providerturn关联,未通读rollout。证据 `pr38-running.jpg/.txt`、`pr38-turn-session.jpg`、`pr38-turn-attributes.txt`。官方PR与候选OID/真实Diff资格归运行Owner和根;Console没有GitHub对象编辑,不用内建对象页代替该事实。 + +17:32 config 继承缺陷修复前的公开停止,浏览器实际 supervisor stopped/error=null/health.last_error=null,Generation `01a12a40-6e34-7ac1-ac6d-071448487ac6`,Collector9753条/628批次、错误及重复0。证据 `config-fix-stopped-overview.jpg/.txt`。运行Owner原件 `raw/config-inheritance-stop-confirmation.json` 的 Pi wait #9746/#9747 对应同代 Issue PID56768/PR PID62548,graceful_eof/exited/ExitStatus0。Owner指出 GitHub 未继承 BRAID_CONFIG,导致 Agent 发布排查误用旧配置;由根修共享 Config 并保留旧错误/候选原件。这是中途停止事实,尚非最终旅程成功,浏览器未操作重启。 + +17:56 GitHub 最终独立浏览器回读:25318权威 supervisor stopped、error=null、health.last_error=null,Generation `01a12a62-3dff-7890-baff-8c7a25895d4a`(退休后正常 restart 验证代次);Collector15357条/1146批次、错误及重复0,记录从17:14:47起保留。Harness PR38 Assignment、Worktree与最新Session为retired,旧Session replaced;Issue37 Assignment sleeping。官方Issue closed/PR merge事实由GitHub原件负责,Console未声明为内建对象权威。首个PR Trace `c68e2d6a0e94037f937224965f40dfbd` 的3个真实Turn Span和1个Session Span仍可读,具体Span #9052/#9731/#9732/#9734。证据 `final-stopped-overview.jpg/.txt`、`final-retained-pr-trace.jpg/.txt`。 + +运行Owner `raw/final-runtime-stopped-collector.json` 原件定向读取的末两实际Pi wait:#15173 PR PID93319、原生09:48:41 Session;#14557 Issue PID83683、原生09:39:06 Session,均 generation `01a12a53-c814-7832-ab86-0eef39c07ae7`、wait/graceful_eof/exited/code0。它们是之前模型代次的真实关闭事实,不能伪配最后无Session的退休验证代次62。postmerged讨论/quiet/restart不增加PR Turn或再次finalization的时序证明归Owner前后账本;此浏览器snapshot共13 Turn(Issue与PR合计),没有由总数单独推导幂等结论。GitHub Console资格完成,初始污染failed、g1fixtureblocked和Config继承故障均保留,未被最终结果覆盖。没有在途浏览器mutation,已通知根和Owner可以服务收尾。 diff --git a/tasks/real-model-e2e/github-network-results.md b/tasks/real-model-e2e/github-network-results.md new file mode 100644 index 00000000..34f45b7a --- /dev/null +++ b/tasks/real-model-e2e/github-network-results.md @@ -0,0 +1,70 @@ +# GitHub 网络与 App webhook 验收记录 + +本文件记录 GitHub 阶段的网络设施证据。当前只完成基线保存和启动封装,没有启动 Wrangler、没有修改 App webhook,也没有向 GitHub 写入对象。 + +## 基线 + +- 目标 ingress:`http://127.0.0.1:18180`;健康检查:`http://127.0.0.1:18181`。 +- App installation:`157947940`,selected repositories 为 `xiaoland/braid` 和 `xiaoland/braid-poc-test`。 +- App-wide hook 原始响应已保存至 `/Volumes/WorkSSD/Development/braid-e2e/github/network/app-hook-baseline.json`,权限 `0600`。只记录存在性:URL 存在、secret 存在、`content_type=json`、`insecure_ssl=0`;文件内容不得复制到报告或命令输出。 +- installation 与 hook 查询均使用临时 App JWT;JWT、installation token 和响应临时文件均未保留。 +- GitHub GET 返回的 `secret` 字段确认是掩码 `********`,不是可用于恢复的原 secret。恢复时不得把 baseline JSON 整体原样 PATCH;只发送 baseline 中的 URL、`content_type` 和 `insecure_ssl`,省略 `secret` 以保留 GitHub 端原值。实际签名校验使用既有 `/Users/lanzhijiang/.braid/instances/xiaoland/secrets.toml`(文件存在且权限 `0600`),不把值写入证据。 + +## 隔离启动封装 + +启动脚本为 [`start-github-wrangler.sh`](./start-github-wrangler.sh),实际入口是 WorkSSD 上的 Node 与 Wrangler: + +`/opt/homebrew/bin/node /Volumes/WorkSSD/Development/braid-e2e/wrangler/node_modules/wrangler/bin/wrangler.js tunnel quick-start http://127.0.0.1:18180 --log-level info` + +脚本外层固定 `TMPDIR`、`XDG_CONFIG_HOME`、`XDG_CACHE_HOME`、`WRANGLER_LOG_PATH` 到 `/Volumes/WorkSSD/Development/braid-e2e/wrangler/{tmp,config,cache,logs}`,并设置 `TUNNEL_TRANSPORT_PROTOCOL=http2`。脚本已通过 shell 语法检查,但尚未执行;Wrangler help 已确认 `tunnel quick-start ` 命令契约。 + +## 待实际运行记录 + +只有内建阶段完成并交接 GitHub Console 后,才可在已授权窗口执行以下顺序:保存当前 App hook → 启动脚本 → 读取公网 `trycloudflare.com` 地址 → 以带签名请求验证 Braid ingress → 记录具体 HTTP 状态和响应摘要 → 临时写入 App-wide webhook → 验证 GitHub 事件到达 → 停止隧道 → 写回基线 JSON 中的 URL、secret、content type 和 insecure SSL → 读回确认恢复。 + +在实际启动前尚未有公网 URL、DNS/TLS、cloudflared protocol negotiation、签名请求或 App webhook PATCH 结果;以下记录是启动后的真实结果。 + +## 本次网络上线结果 + +- GitHub Console 已由 runtime owner 确认 `ready=true`,本地 health 返回 HTTP 200,ingress `127.0.0.1:18180`,reconciliation 为 `current`。 +- Wrangler 首次启动触发了 WorkSSD 内的 cloudflared 下载;第一次短进程只留下下载检查日志,随后第二次启动成功。下载、配置与日志均在 `/Volumes/WorkSSD/Development/braid-e2e/wrangler`,未落系统盘。 +- cloudflared 版本 `2026.10.0`,启动日志确认 `Initial protocol http2`、`Registered tunnel connection ... protocol=http2`。Connectivity pre-check:DNS、TCP HTTP/2 与 Cloudflare API 通过;region2 QUIC 失败,但最终明确 `degraded transport` 并使用 `http2`,符合本轮固定协议要求。 +- 已通过公网 Quick Tunnel 对 `/webhook` 发送带本地既有 secret 计算的 `X-Hub-Signature-256`,实际 HTTP 状态 `202`,Braid 返回 `event_lifecycle=consumed`。请求体、响应、delivery UUID 和 URL 均仅保存在 WorkSSD `github/network` 下并设为 `0600`;敏感 URL 不写入本报告。 +- App-wide hook 已 PATCH,仅发送公网 URL、`content_type=json`、`insecure_ssl=0`,没有发送掩码或本地 secret。GitHub 200 回执已保存,readback 确认 URL 存在、secret 仍为掩码、字段值正确。 +- 已通知 runtime owner 可以开始正常 GitHub Issue/PR 需求输入。tunnel 与 App hook 在 GitHub Harness 结束前保持运行,不能提前恢复。 + +## Delivery 404 调查与修复 + +- Issue #37 `opened` 与 maintainer comment `created` 均由 GitHub 真实投递,但 App delivery 只读回执分别为 HTTP `404`。原始 delivery 列表、App 订阅和 installation 权限响应保存在 `github/network`,权限为 `0600`。 +- App 订阅包含 `issues`、`issue_comment`、`pull_request`、`pull_request_review`、`pull_request_review_comment`;installation 权限为 issues/contents/pull_requests 写、metadata 读,排除了订阅或权限缺失。 +- 根因是第一次临时 PATCH 把公网 URL 写成了 host 根路径;Braid ingress 实际路由是 `/webhook`。手工签名验证使用了 `URL/webhook`,所以不能证明 GitHub App 根路径正确。 +- 已将 App URL 修为同一公网地址加 `/webhook`,仍只发送 URL、`content_type=json`、`insecure_ssl=0`,没有发送 secret;GitHub 200 回执及 readback 均确认路径正确、secret 仍为掩码。没有 redeliver 旧事件,也没有在调查中新增对象。 +- 修复后的验证需要 runtime owner 在 root 决策后产生一个新的唯一 GitHub 事件;当前 network owner 不自行制造事件。tunnel 保持运行,等待该验证后再恢复 App 配置。 + +## 路径修复后的官方 delivery 结果 + +- 新 comment `6107449747` 的 GitHub 官方 delivery 已命中正确的 `/webhook` 路径;delivery detail 中请求 URL 已脱敏保存,确认不是根路径误投。 +- GitHub delivery 状态为 HTTP `503`,响应正文为 `durable ingest unavailable`;响应 headers、delivery GUID、事件身份与请求 headers 已保存在 WorkSSD 原始 JSON,签名字段不在报告中展开。 +- GitHub App 当前订阅与权限仍正常,hook readback 仍为 `/webhook`、JSON、`insecure_ssl=0`,secret 掩码存在;cloudflared 进程仍存活并使用 HTTP/2。 +- Console 原始日志给出本地根因:`SQLite operation failed: UNIQUE constraint failed: repositories.name_with_owner`。这证明公网/App 路径已通过,当前阻塞是 Braid ledger durable ingest 的 repository 去重/幂等故障,交由 runtime/root 处理;网络 owner 不重投递、不新增事件、不改订阅或 secret。 +- 追加身份核对发现:此前用于验证公网签名的本地 ping 使用了合成 `repository.node_id=MDEwOlJlcG9zaXRvcnkxMjM0`,而真实 GitHub 仓库 `xiaoland/braid-poc-test` 的只读元数据为数字 id `1344679384`、`node_id=R_kgDOUCYt2A`。`full_name` 相同但 node ID 不同;原 ping 未使用真实仓库身份,可能污染本轮 ledger 的 repository 记录。原 payload 保留在 `github/network/signed-body.json`,没有重发或修改。 + +## 受控 tunnel 中断 + +- 在 runtime 已达到 ready、provider connected、reconciliation current 且 PR/应用状态已冻结后,保存了中断前状态,停止了 Wrangler/cloudflared 进程;没有停止 GitHub Console、18180 ingress 或 health/reconciliation。 +- 中断后本地 health 仍 HTTP 200,`ready=true`、`reconciliation=current`;公网原 URL 探测返回 Cloudflare HTTP `530`,正文为 Cloudflare Tunnel error 页面,证明公网投递入口已不可达。 +- App webhook URL 与 secret 保持不变,未触碰 GitHub 配置;恢复窗口等待 root 明确指令。中断前状态文件、探测响应和进程快照保存在 `github/network`,均未包含 secret/token。 +- 中断窗口内 PR #38 comment `6107701629` 的官方 delivery 只读详情为 HTTP `530`,状态 `Invalid HTTP Response: 530`,响应为 Cloudflare Tunnel error(错误码 1033);delivery GUID、headers、完整响应原件已保存在 `github/network`,报告不展开公网 host。该结果确认中断确实影响 GitHub 投递,未执行 redelivery。 + +## 中断后恢复 + +- 恢复时后台 `nohup` 封装会随命令会话退出,导致其新 Quick Tunnel 地址再次返回 530;未修改 Console 或 ledger。随后改用受控长期终端会话运行同一 WorkSSD 启动脚本,cloudflared `2026.10.0` 注册成功并明确使用 `http2`。 +- App webhook 已更新为本次新 Quick Tunnel 地址的 `/webhook` 路径,仅发送 URL、`content_type=json`、`insecure_ssl=0`,没有发送 secret;GitHub 200 回执和 readback 均确认路径正确、secret 仍掩码存在。 +- 新地址的公网 GET `/webhook` 返回 HTTP `405`(路由可达但方法不允许),本地 health 仍 HTTP 200、`ready=true`、`reconciliation=current`。未重发中断期间失败 delivery,未发送 synthetic payload。 + +## 最终恢复与关闭 + +- 收口前只读保存了 closed delivery `cc498440-c558-11f1-98bb-49512759d9a4`:GitHub delivery HTTP `202`,响应为 Braid accepted/pending 事件回执;原始 delivery detail 保存在 `github/network`。 +- App hook 恢复 PATCH 从 baseline JSON 只取 `url`、`content_type`、`insecure_ssl`,没有读取或发送 baseline 的掩码 `secret`。GitHub 200 回执后 readback 与 baseline 三个非 secret 字段全部一致,secret 仍为掩码存在。 +- 通过长期终端发送 Ctrl-C,Wrangler/cloudflared 均已退出;进程核对为无 tunnel 进程。恢复、530、delivery 失败和 protocol 日志均保留在 WorkSSD,未删除原件、未 redeliver、未发送 synthetic payload。 +- 最终本地 health 端口在 Harness 停止后不可达;Console 的停止后历史回读和进程关闭由运行 Owner 分别取证,不能用 health 端口代替。App 配置已恢复到原始 baseline。 diff --git a/tasks/real-model-e2e/github-results.md b/tasks/real-model-e2e/github-results.md new file mode 100644 index 00000000..e23813e2 --- /dev/null +++ b/tasks/real-model-e2e/github-results.md @@ -0,0 +1,60 @@ +# GitHub 上游真实模型执行记录 + +2026-10-11 内建实际流程结束后接入。独立source从6425f01开始,新需求基线2cc02e78920072fdf1165def8798464012630655只包含允许可见需求、README占位和忽略规则,不继承内建业务答案。基线按批准计划正常push main。运行使用最终同版binary81f963d0d5b7b4597e3707527deb0e01c4775f99197e7be242b82e84a556ccd9,GitHub配置SHA47eac7bf65b8d5b64b545b5282cb6a777ed75379665b204f54c24f2e2da4ed58;双Profile均官方MiniMax-M3,quiet30/count8/reconcile60,实际原生指令明确所有数据/材料/临时/缓存必须本轮WorkSSD、禁/tmp。 + +为了保留旧attempt1 blocked/unknown现场14318,GitHub独立Console与OTLP使用24318;ingress18180和health18181保持网络合同。新Harness账本0→6迁移完成,未复用旧native/store。Console真实running/providerconnected/readytrue/reconciliationcurrent,health18181/healthz实际200,tunneldisabled,因为公网入口由稳定networkowner负责。初始历史对象激活情况见raw/initial-no-historical-activation.json,未创建本轮Issue或模型输入。startup-identity.json、first-start.json、first-ready.json在/Volumes/WorkSSD/Development/braid-e2e/github/raw。 + +相对config路径首次migrate被公开CLI拒绝,改完整绝对路径后实际迁移成功,原工具错误保留;不属于产品回归。网络App切换和恢复由e2e_readiness owner负责,公网签名入口未完成前不创建任务激活。 + + +网络owner已实际完成公网签名ping202/ledger消费及App仅URL切换readback;该请求不是GitHub实际发出的对象事件。随后正常operator创建GitHub Issue37,title唯一20261011-minimax-peer-upstreams,正文包含允许需求/隐藏HTML判据及实体WorkSSD环境约束。普通maintainer可信@braid评论6107427719明确Issue设计only,再由braid gh pr ensure交接PR,不代写业务。创建前openIssue0。创建/评论实际返回URL,原件create-issue.json、trusted-issue-activation.json保留。 + +跨quiet30后Harness只有先前signed ping delivery,没有issues/issue_comment delivery,provider sessions/turns仍0;Console无业务错误。这个是事件通路未证成,不当模型零结果或已激活成功。未重复评论/注入事件,已将真实Appdelivery请求/响应及公网入口问题交稳定networkowner有界调查。原件github-activation-after-quiet.json保留;首次证据序列化bytes错误原工具保留,最终原payload按base64保存不丢失。 + + +网络首次官方Issue37/opened与comment6107427719投递HTTP404:临时AppURL缺/webhook,网络owner仅修URL路径/readback,不改secret。正常唯一澄清comment6107449747再投递HTTP503,具体SQLite UNIQUE repositories.name_with_owner。Owner定向确认是先前signed验证payload虚构node MDEwOlJlcG9zaXRvcnkxMjM0却用了真实repo名,真实Githubrepo1344679384/node R_kgDOUCYt2A,因此原账本权威冲突;不修产品接受错误身份、不删row。原repo/payload/真实API事实github/raw/repository-unique-conflict-identity.json保留。 + +按根与advisor采用正常stop旧污染Console,零sessions/turns/assignments/workitems且stopped/errornull、Console正常退出。保留原firstfailure;新github-attempt2独立source/objectlib/runtime/nativehome/collector使用同无答案baseline2cc02e7,现Issue37继续,没有新Issue或signedpayload,保留正确AppURL/tunnel18180。新Console25318、health18181。首次正常comment6107488372官方delivery44841e70-c554-11f1-8a4f-f39c6fa9ccca入库成功、真实repo R_kgDOUCYt2A和Issue节点关联,和network人工验证分别取证。 + +首次materialize被我fixture路径替换错误阻断:双workspace重复/Volumes/WorkSSD/Development前缀,model0sessions/turns。原配置config-first-path-error.toml、blockedledger first-official-ingest-blocked.json保存,不修产品容错、不改blocked私有状态。精确修正两完整workspace为github-attempt2/source,normalstop/restart后新正常trustedcomment6107503398激活g2;旧g1blocked错误保留。最终configSHA08127d23c71caa2c7f253680fa33164bc267aff47abbd68dc4f18effc1a1170d,公开configcheck成功,全部source/home/state/worktrees/backups/OTLPdb实际路径resolve存在且df为/dev/disk6s1 WorkSSD,actual-resolved-config-paths.json保存。 + +真实IssueAgentturn01a12a40-9489-7742-8359-537e7b1b4933开始,原生Pi文件github-attempt2/worktrees/issue-37/issue-minimax-g2/.braid/pi-sessions/2026-10-11T09-17-17-748Z_01a12a40-9434-7223-83ac-72bb9c356155.jsonl,首userf4799623。仅assistantmetadata核对provider=minimax/modelMiniMax-M3,已有真实bash/toolResult收发,未展开assistant/CoT。后续自主PRensure/业务产物在途,不能仅由ready/ingest/原生响应称黄金路径通过。 + + +Issue Agent实际braid gh pr ensure建立Draft PR38,bootstrap8cf6782a4792d5e571d9aa708d43cacc11b6362c;PR独立原生turn01a12a45-a704-7e91-a362-90de0e9df458真实实现后09:24:53提交、09:24:57 push首业务候选e08485391b252892fec16f6678fb6084e0de9dbf。父根负责该固定OID独立应用验收,未merge。 + +09:25:12实际原生工具echo证实BRAID_CONFIG/BRAID_INSTANCE为空;src/config.rs585/602仅Builtin注入braid_config_path,GitHub缺失精确配置继承。模型为发布评论从09:25:13开始误用旧builtin-attempt2配置,并实际直接SQLite UPDATE旧Builtin repositories.name_with_owner为xiaoland/braid-poc-test,随后改回braid-poc-test。当前readback恢复原值,但不能宣称旧ledger未触及。首候选提交/push早于该跨空间排查,定向生成前未发现旧业务答案读取;后续独立性/内部状态违规保留,不能抵销。raw/config-inheritance-cross-space-failure.json保存空env/原UPDATE/当前readback。正常operator评论6107592250明确正确绝对Github config、限制当前空间、禁止直接内部数据库读写及其他run。根负责共享config注入修复,原生仍正常运行不伪停/不私改状态。 + + +配置缺失执行通过公开Console stop确认stopped/errornull;真实Pi childwait Collector9746/9747分别IssuePID56768、PRPID62548,graceful_eof/exited/ExitStatus0。当前turncompleted或interrupted按原ledger分别保留,拒把停止受理当停止完成。root修config两个provider统一精确loaded_from,唯一中央strictClippy/build通过后Consoleexit0、atomicinstall新版SHA728df182e9461e9150b8dee3c3bd2bbfd86989c9d08b58c457e441c8a6067e62。同ledger/newgeneration正常接续,实际原生tool recorda9b840e3回读正确Githubconfig/BRAID_AGENT1。正常Appcomment身份以官方原件为准;仅以实际CLI与origin_echo判断,不伪称所有隔离已通过。 + +root固定e084独立9次原始应用CLI全部通过。正常Issue正文接受list --all/同标题唯一ID;第一编辑实际PR已idle(初先前running摘要已更正,不算active),两对象contextresetactive_turn_idnull/applied。随后PR正常讨论6107657654/6107657851合并event_count2,quietdeadline09:38:15,quietpending时公开stop确认+正常restart,09:38:20仅同batch一个turn开始。其实际running时再Issue正文澄清all状态active|archived;09:39:32旧turninterrupted、resetactive_turn_id指向原turn/applied,新native09:39:38+新turn继续。raw/quiet-pending*.json、active-body-reset-observed.json保留。 + + +新设计候选08c2458751a02a8143e0cb7fe620c20bd48dea16真实push后root独立10次CLI全部通过。两个session均idle/latestnativecompleted且outbox9applied时,由稳定networkOwner停止隧道;本地ready/reconcile保持,公网530/Cloudflare1033事实由networkOwner保留。唯一正常PRcomment6107701629官方delivery真实530,AppURL/secret未改/不redelivery。09:44:28实际reconcile-2020318698c485da3aadce3bb41e689a记录对象IC_kwDOUCYt2M8AAAABbAwhfQ,batchquiet09:44:58后09:44:59单turn触发。actualusera9762346引用该comment、toolResult3113a68b实际读取完整正文,09:45:17completed无业务变化。raw/tunnel-down-*保留ingest→batch→turn→native因果,不以一次canonical回读冒称事件接续。普通wake事件表仍pending而batchconsumed的现有投影分别记录,不改ledger或造新事实。网络恢复交根followup原networkOwner,模型执行仍同官方M3。 + + +## 最终运行与矩阵结果 + +本轮最终实际源码为 `3fab0d0`,binary SHA-256 `728df182e9461e9150b8dee3c3bd2bbfd86989c9d08b58c457e441c8a6067e62`;配置仍 `08127d23c71caa2c7f253680fa33164bc267aff47abbd68dc4f18effc1a1170d`。发布演进为无答案基线 `2cc02e7` → 空bootstrap `8cf6782` → 首业务 `e084853` → 设计业务 `08c2458` → 正常merge `8281fffa0bb76398a0cd4c262bd69351e9ed2da6`。固定候选的独立应用操作及merge树/parent资格归 `qualification-results.md`,不由生成Agent的评论替代。 + +| 事项 | 结果与限制 | +| --- | --- | +| 真实官方事件与双角色模型 | pass:真正Issue/评论/PR节点、Appensure交接、官方MiniMax-M3实际原生收发。首404/503与fixture路径blocked保留,不计首错通过。 | +| 黄金路径与设计变化 | pass:首业务9次与新设计10次独立真实CLI。新OID由Agent实际提交/push,开发Agent不代写业务。 | +| canonical Context | pass限定首user/新设计user与明确canonical读取;隐藏HTML不进入这些投影。raw GitHub对象读取可含原始隐藏正文,不声称全面信息隔离。 | +| quiet、重启与自身回写 | pass:两普通讨论event_count2/quiet30,pending时公开stop/restart,同batch单turn;App自身评论origin_echo consumed不形成自身评论循环。Git push synchronize是真正external事件,另开收口turn单列。 | +| idle/active正文更新 | pass:idle双对象reset;active关联设计reset明确旧turn interrupted、新session/applied,无并行旧新turn。 | +| 生命周期 | pass:普通PR close实际finalization completed→sleeping;reopen原责任激活并新native;merge不打断已运行turn,待其completed才单次finalization;最终PR assignment/agent/session/worktree均retired,自动Closes Issue37收口sleeping。 | +| 停止与退休后重启 | pass:真实Pi wait/graceful_eof/ExitStatus0;postmerged comment6107768185、quiet30、normalstop/restart再quiet30,PRturn总数保持11,没有第二mergefinalization或重新激活。 | +| 隧道中断/reconcile | pass:真实官方comment HTTP530;reconcile ingest→batch→turn→实际原生comment引用与正文读取→completed。公网恢复产生新host的App URL变化/最终原URL恢复归network Owner原件;不redeliver、不synthetic。 | +| 普通App native改派与Builtin writer grant | unavailable/not-applicable:普通App trusted mention模式不能宣称native unassign/reassign,Github未模拟Builtin grant能力。Builtin责任fencing见内建实际结果。 | +| 全程隔离/操作合规 | fail:缺配置继承导致真实模型误用旧Builtin空间并直接UPDATE旧ledger,虽已改回原值但不认未触;保留原工具与修复/正常接续,不由应用通过抵销。 | +| OTLP/Console | pass限定本轮真实对象/原生session/turn/停止关联及停止后历史可读,最终15357条记录。GitHub对象权威来自GitHub,不宣称Console有GitHub对象编辑界面。 | + +最终公开stop请求 `25ef7b28-48af-4931-b512-f5035d46d5c5` 实际stopped/errornull,generation `01a12a62-3dff-7890-baff-8c7a25895d4a`。此前实际模型generation `01a12a53-c814-7832-ab86-0eef39c07ae7` 的最终Issue/PR native wait记录14557/15173,PID83683/93319,均graceful_eof/exited/code0;末次退休后启动未重新生成原生会话。`raw/final-runtime-stopped-collector.json`、`final-no-reactivation-stop-request.json`保留。Console25318完成最终独立浏览器回读后正常退出0;旧Builtin14318进程退出1并保留具体stop unconfirmed错误,不能追认原provider stopped。所有临时监听已关闭,原DB/rollout保留,原件final-console-process-exit.json。network Owner已独立恢复原App URL并读回一致、关闭隧道,见github-network-results.md。 + +原生SDK usage按responseId去重、仅提取metadata:GitHub attempt2共358个assistant响应,非缓存input658424、output83872、cacheRead11237691、totalTokens11979987。按冻结RMB/M token input2.10/output8.40/cache-read0.42估算人民币6.80704542;账号实际扣费未知,native cost0不当免费。原件 `github-attempt2/raw/native-usage-aggregate.json` 保留6个Pi原生文件分项;它们不是6个不同Braid责任角色。 + + +最终浏览器只读验收完成后,GitHub25318 Console进程PTY50397正常Ctrl-C退出0,Collector原件保留。旧Builtin14318 Console进程PTY32355正常结束退出1,仍报告原runtime stop unconfirmed/Pi child exit timed out;这是服务器进程已关闭,不能将旧native未知追认停止成功。定向实际ps无本任务Braid/Pi/cloudflared/Wrangler,14318/19318/24318/25318/18180/18181/18282/19282均无监听(connect_ex61),包含临时平台server。raw/final-console-process-exit.json记录退出/错误/端口事实,不删除旧ledger/rollout。最终App原配置恢复与隧道关闭须采用network Owner回执,本Owner不从本地无进程推断远端App已恢复。 diff --git a/tasks/real-model-e2e/input/design-change.md b/tasks/real-model-e2e/input/design-change.md new file mode 100644 index 00000000..9cbdcb8a --- /dev/null +++ b/tasks/real-model-e2e/input/design-change.md @@ -0,0 +1,5 @@ +在首次候选已形成后,将以下变更并入 Issue 接受的设计正文: + +同标题的不同笔记允许并存,但 ID 必须唯一。增加 `list --all`,按原创建顺序列出所有笔记并显示归档状态;默认 list 仍只显示未归档笔记。保留先前中文、引号、持久化和错误处理约束。 + +本变更通过关联 Issue 正文进入 PR Agent 的当前设计,不直接修改执行器输入或私有状态。 diff --git a/tasks/real-model-e2e/input/issue.md b/tasks/real-model-e2e/input/issue.md new file mode 100644 index 00000000..047e93f3 --- /dev/null +++ b/tasks/real-model-e2e/input/issue.md @@ -0,0 +1,10 @@ +# MiniMax 双上游验收:离线笔记 CLI + +请先澄清并维护本 Issue 中的设计,随后通过关联 PR 实现离线笔记 CLI。业务范围是本轮 `e2e-notes/20261011-minimax-peer-upstreams/`;不修改仓库其它文件或已有应用。需要保持实现不依赖网络服务或第三方 Python 库。 + +使用 `python3 notes.py --store <路径> add <标题> <正文>` 新增笔记并返回稳定唯一 ID;`list` 默认按创建顺序显示未归档笔记;`archive ` 归档而不删除内容,重复归档不产生新记录。进程退出后数据仍可读取。标题和正文允许中文、空格与引号。无效 ID 或损坏存储应返回具体错误和非零退出码,不覆盖已有数据。README 应说明实际命令与数据存储位置。 + +Issue Agent 负责设计、实施请求及工作记忆;PR Agent 负责专属工作树中的业务实现、真实 Git 提交和应用实际操作证据。请保持讨论简洁,发布可供采用的事实,不能仅以“完成”或原生执行退出代替产物验证。 + +可见验收标记:BRAID_VISIBLE_MINIMAX_PEERS_20261011。 + diff --git a/tasks/real-model-e2e/load-minimax-env.sh b/tasks/real-model-e2e/load-minimax-env.sh new file mode 100755 index 00000000..f45ba830 --- /dev/null +++ b/tasks/real-model-e2e/load-minimax-env.sh @@ -0,0 +1,28 @@ +#!/bin/sh +set -eu + +env_file=${BRAID_E2E_ENV_FILE:-/Volumes/WorkSSD/Development/agentic26/.env} + +read_value() { + key=$1 + awk -F= -v wanted="$key" ' + $1 == wanted { + value = substr($0, index($0, "=") + 1) + gsub(/[[:space:]\047\042]/, "", value) + print value + exit + } + ' "$env_file" +} + +MINIMAX_API_KEY=$(read_value MINIMAX_API_KEY) +MINIMAX_BASE_URL=$(read_value MINIMAX_BASE_URL) +[ -n "$MINIMAX_API_KEY" ] || { echo "MINIMAX_API_KEY is empty" >&2; exit 1; } +[ -n "$MINIMAX_BASE_URL" ] || { echo "MINIMAX_BASE_URL is empty" >&2; exit 1; } +export MINIMAX_API_KEY MINIMAX_BASE_URL + +if [ "$#" -eq 0 ]; then + echo "usage: load-minimax-env.sh [args...]" >&2 + exit 2 +fi +exec "$@" diff --git a/tasks/real-model-e2e/plan.md b/tasks/real-model-e2e/plan.md new file mode 100644 index 00000000..4c287007 --- /dev/null +++ b/tasks/real-model-e2e/plan.md @@ -0,0 +1,120 @@ +用户于2026-10-11已批准本方案并指示“确认,允许,开始。”下文“待批准/未执行”描述为准备时事实;本轮已结束,最终结论见results.md,各阶段原始证据和失败身份保留。 + +# 双上游真实模型端到端验收方案 + +本轮以独立 Braid `1fdef82` 为候选,冻结 executable `/Volumes/WorkSSD/Development/braid-e2e/bin/braid`(0.3.2,SHA-256 `50719bcd2adc3e2a261f7a703bf9b572bb0fb2f7db0584edbcbacec6ca081d6f`;本地候选而非 tagged release),外部空间为 `xiaoland/braid-poc-test`,所有 Issue/PR 角色使用 MiniMax 官方 `minimax-m3`,不使用备用模型。先内建再 GitHub,两个运行使用独立配置、账本、Console 证据库和原生会话;Mac 侧路径统一位于 WorkSSD。准备阶段不运行模型或改动外部仓库。 + +## 固定工作任务与角色 + +冻结输入见 `input/issue.md` 与 `input/design-change.md`,工作标识为 `20261011-minimax-peer-upstreams`。建议使用不依赖外部服务的本地笔记 CLI,两个上游以相同需求和相同空白应用基线独立实现。基线只含需求、运行说明占位和 Git 忽略规则,不含实现答案。验收程序只实际调用生成应用,开发 Agent 不代写业务实现,也不运行 Braid 测试。 + +需求正文:实现 `python3 notes.py --store <路径> add <标题> <正文>`、`list`、`archive `,使用 JSON 文件持久化。add 返回稳定 ID;list 默认只列未归档笔记并按创建顺序输出;archive 后原内容保留且重复 archive 不产生第二份记录;无效 ID 和损坏数据返回具体错误,不覆盖原数据。标题和正文允许中文与引号。无网络、数据库服务和第三方依赖。 + +Issue Profile 负责澄清需求、维护接受的设计与简洁实施请求,不实现业务文件。PR Profile 只在专属工作树依据当前 Issue/PR 设计实施、实际运行应用、提交真实 diff 并发布简洁证据。两者都用 minimax-m3,角色指令不同;不得把技能正文内联进 Profile。运行开始前记录 binary SHA、Pi 版本、source 提交、两个 Profile 及模型配置摘要,费用值未知时标为未知,不能用 0 当免费。现有 MiniMax 价格记录以人民币/M token 表示;原生 SDK 未配置的 cost=0 不能当作实际账单,报告应分别记录 token 用量、计费来源、人民币估算和账户扣费缺口。 + +黄金路径完成后,加入明确设计变更:同标题新增笔记必须允许,ID 仍唯一;增加 `list --all` 显示归档状态。通过关联 Issue 正文修改让 PR Agent 接收更新,而非将新要求直接塞进执行器。分别实际新增中文/引号笔记、进程退出再读取、归档、重复归档、无效 ID、损坏数据与重复标题,记录输入/退出码/输出以及 Git diff。原生终态与产物符合需求分别判断。 + +## 正常操作者动作与上游差异 + +操作者可以创建/编辑需求、发表讨论、指派或可信 mention、发出停止请求、阅读候选和明确采纳;不代写业务实现、不修私有状态、不注入事件。途中设施修复保留失败和版本,并与无纠正黄金路径结果分开。 + +内建平台先独立启动,再接入 Harness。Issue Agent 自行发表实施请求、建立仅空提交的候选分支并通过 `braid object pr --head ... --base ... --issue ...` 创建关联 PR。平台要求不同 head/base,不接受开发 Agent 预制答案。操作者通过 Console 指派 PR Profile,这是当前明确的正常步骤;不宣称内建已经拥有 GitHub `gh pr ensure` 的原子建分支/派生/激活能力。PR Agent 实现和提交后自行 publish 固定 OID;操作者阅读真实 Diff 后显式 merge。source 和其他工作树须切离目标 base。 + +GitHub 使用已接入的 Braid App,先确认 native assignment 或 maintainer trusted mention 的实际模式。Issue Agent 经 `braid gh pr ensure` 交接关联 Draft PR;PR Agent 在专属工作树实施、push、更新 PR 工作记忆。普通 App 不能冒称 native unassign/reassign 能力。外部操作范围限专用验收 Issue/评论/PR/分支及明确采纳,不改其它对象、仓库设置或历史;不自动删除证据。 + +## 递进验收与完成条件 + +每项结果使用 pass/fail/unavailable/not-run;后两者不算通过。黄金路径是进入后续验收的门槛,不是整个端到端验收的替代品。 + +| 阶段 | 两上游共同事实 | 上游特定事实与证据 | +| --- | --- | --- | +| 模型与黄金路径 | 真实输入到达原生会话;设计与实现角色区分;生成业务 diff,应用实际操作符合需求;Agent 自己维护工作记忆和交付证据 | GitHub App/可信 mention、Draft/关联与 ensure;内建请求、人工指派、固定候选 OID及合并 | +| 调度与上下文 | 普通讨论遵守 quiet window;多输入合并,不并行误开;可见正文进入当前 Context,HTML 隐藏正文不进入;关联设计更新后模型使用新设计;自身发布不形成唤醒循环 | quiet=30秒、threshold=8、reconcile=60秒;记录输入、会话身份、触发和时间,GitHub 权限/mention 差异如实标明 | +| 生命周期 | 空闲和活动状态的正文变更、关闭/重开/合并;执行停止与对象关闭分别确认;终态不重复开执行 | 内建改派/同 actor 改派撤销旧写 grant,迟到写入拒绝;关闭后 finalization 不恢复正文写权限;GitHub 使用实际支持的激活模式 | +| 恢复与控制 | 等待期间正常重启仍消费未完成输入;活动执行停止有真实原生确认;未知终态保持未知,不据请求受理宣称成功 | GitHub 隧道中断与 reconciliation;内建平台在 Harness 停止后继续存续、游标接续不重复;活动重启恢复能力按实际证据判定,不假设完整检查点 | +| OTLP 与 Console | sample_ratio=1.0;实际 provider/session/turn、对象输入/写入、候选和停止事实可关联;完整原始错误与用量保留;停止后 Collector 历史可读 | 三类数据库权威分离;GitHub 对象结论取自 GitHub;采集不能替代原生终态或产物验收,费用按实际账单来源估计并标明缺口 | + +先在内建完成上述流程、整理缺陷及复跑身份,再在 GitHub 执行同一冻结任务。若某一步失败,保留对象、原生会话、Git 提交、HTTP 状态与 Console 原始批次;修复设施后记录新版本及受影响重跑,不把修复后结果覆盖首次失败。模型无响应、错误或未知终态先有界核对,不无限重试、不自动切模型;需要控制时使用 Braid 公开能力并保留停止确认。 + +完成本轮需要两上游必需项全部有明确结果、真实产物验收及原生执行停止证据,剩余未验证边界明确列出。现有 acceptance.md 中 Codex app-server、带标签发行安装、三次完整 campaign、兼容 rollback 等发行资格仍有自己的要求;本轮 Pi/源码候选运行不宣称它们通过。若要发行资格,另冻结发行制品与 campaign,不能换名省略。 + +## 执行前待冻结 + +核对现有 GitHub App/安装权限、webhook secret、maintainer 与非 maintainer 身份、公网 webhook/Quick Tunnel 接线,以及已有验收对象避免误消费历史任务。独立 runtime 账本不保证不会发现同仓库旧工作项,必须选择明确隔离的 Profile/对象与激活范围。 + +MiniMax 官方凭据来源由用户指定为 `/Volumes/WorkSSD/Development/agentic26/.env`,只加载 MiniMax 所需变量,不输出或持久复制 key。已只读确认 key 非空、官方 base URL 为 `https://api.minimax.cn/v1`,仍须核对原生 Pi provider/model ID 与 wire `MiniMax-M3` 的对应;不得仅因 catalog 有记录就声称接通。已知 Factory catalog 声明 `minimax-official-m3` 是 pay-as-you-go,引用 `MINIMAX_BASE_URL/MINIMAX_API_KEY`,不等于本轮实际额度或计费已确认。不启动 Factory Lab,也不把 Factory 的执行/存储接线当作 Braid 的依赖。 + +待真实只读调查收齐后冻结每种上游的配置、端口、运行目录、实际费用模式与启动命令,向用户提供具体执行范围作为最终启动复核对象。当前不请求重复确认仓库或模型。 + +### Console 与公网入口的部署安排 + +Console managed GitHub 已拥有真实 ingress 与 Harness 启停,但不托管 Quick Tunnel。 +计划使用独立、WorkSSD 安装的 Wrangler 为 `127.0.0.1:18180` 提供公网入口;Console +托管 GitHub Harness 并接收 OTLP,隧道作为外部网络设施。执行前保存 App-wide +webhook 原始配置、核实安装与活动运行的影响范围,经用户认可的写入范围临时配置 +该入口,运行结束恢复原配置并核对回执。公网请求实际进入带签名校验的 Braid +之后才能声明 GitHub 事件通路就绪;隧道进程存活不能代替该事实。 + +如果 App 影响范围或外部入口不能成立,可用原生 `serve --tunnel` 加纯 Collector +验证一部分真实模型流程,但 GitHub Console 控制项仍为未验收,不据此关闭完整 +端到端任务。不为了验收凭空新增隧道服务或修改 Console 产品边界。 + +### 待批准的实际执行范围 + +开始后允许初始化本轮新的平台/Harness 数据库、启动 Console、原生 Pi 与 +MiniMax 官方按量请求,并对隔离任务产生 Issue、评论、PR、空引导提交、实现 +分支/push 与合并事实。GitHub 对象均带本轮唯一标识,业务文件限制在 +`e2e-notes/<本轮ID>/`;已有工作项与分支不作输入,不修改主 Braid 源码或其它 +业务应用。共同 checkout 初始提交为 `6425f01e20ed4894b38ef4adc5da359896d07c20`。 +新的需求基线提交仅含说明与忽略规则,不包含答案;仅在执行批准后发布。 + +MiniMax 模型费用记录实际 token 与服务错误,不另设人为费用停止线,不切换 +其它模型。具体使用额度由现有官方凭据决定,不使用赛事或 ARK 通道。缺陷修复 +需要区分本轮设施与产品源码:用户当前仅要求准备,尚未授权以本计划直接启动 +模型、修改公网 webhook 或执行产品源码修复。执行复核应同时确认本计划的实验 +输入、费用模式、对象写入和 webhook临时变更/恢复范围;不以 elapsed time 作为 +批准。 + +### 启动顺序(待执行批准,当前未运行) + +固定 binary 为 `/Volumes/WorkSSD/Development/braid-e2e/bin/braid`。两种上游的 Harness +均先经公开 `migrate apply --config <对应配置>` 初始化新 schema 6 ledger;不对旧 +实例执行迁移。只有所需模型 env 注入后,才启动带对应 config 的 Console,并 +通过页面请求真实模型运行;`accepted` 与 `running` 不代替 ready 或原生输入接收。 + +内建 Console:`braid console --platform-config --config + --database /Volumes/WorkSSD/Development/braid-e2e/builtin/observations.sqlite3 +--listen 127.0.0.1:14318`。先以平台为权威建立本轮需求,再指派 Issue Profile。 + +完成内建记录并确认真实执行停止后,关闭该 Console。GitHub Console 使用 +`--config --database +/Volumes/WorkSSD/Development/braid-e2e/github/observations.sqlite3 --listen +127.0.0.1:14318`,不装配内建平台。公网网络设施转发独立 ingress 18180,原始 +webhook 基线与恢复结果归 GitHub 运行证据;不得同时另开相同 ledger 的 +`braid serve`。 + +实际命令中的 MiniMax 环境变量通过同目录 `load-minimax-env.sh` 加载器传给进程。 +模型与 secret 值不写入 shell 历史、配置或报告。异常时先保存具体原始错误, +停止与恢复均按能力和实际确认结果记录。 + +### 准备核对结论与最后外部边界 + +2026-10-11 已完成:固定 candidate 0.3.2;两套 schema 3 配置通过公开检查;Pi +1.0.2 原生模型 ID 已统一 `MiniMax-M3`,两个独立 home 只引用官方 key;MiniMax +凭据来自用户指定 env;两个 checkout 同初始提交;Wrangler 4.149.0 在 WorkSSD +隔离安装且 `tunnel quick-start` 帮助契约已核实。当前没有模型请求、平台对象、 +新执行账本、Collector、隧道或外部写入。 + +App JWT 只读核实:安装 `157947940` 的 selected repositories 实际是 +`xiaoland/braid` 与 `xiaoland/braid-poc-test`。App webhook 已配置,现有 secret +存在。目标验收仓库当前 open Issue/PR 均为 0,历史对象不得接续。本机没有活动 +Braid/Pi/Wrangler/cloudflared;不能据此推断远端无人使用。临时替换共享 App webhook +将影响两个仓库的事件投递,必须确认无其它依赖该入口的运行,并把临时变更和 +恢复纳入实际执行许可。若不允许共享入口窗口,需保留现 URL 并准备专用 App 或 +经认可的独立接线,不能悄悄绕过。 + +Wrangler 外层必须设置 WorkSSD 的 TMPDIR、XDG_CONFIG_HOME、XDG_CACHE_HOME 和 +WRANGLER_LOG_PATH;有预置 cloudflared 时再设置 CLOUDFLARED_PATH。安装目录为 +`/Volumes/WorkSSD/Development/braid-e2e/wrangler`,具体变量见 readiness.md;不依赖 +无效的 WRANGLER_HOME。真实运行前保证对应目录存在并核对实际解析路径,依赖 +下载、运行日志和缓存不得回落到系统盘。公网可达性只有实际启动后才能判断。 diff --git a/tasks/real-model-e2e/qualification-results.md b/tasks/real-model-e2e/qualification-results.md new file mode 100644 index 00000000..7a9ff78f --- /dev/null +++ b/tasks/real-model-e2e/qualification-results.md @@ -0,0 +1,43 @@ +# 独立真实产物与输入观察 + +所有观察来自真实Braid Agent产物、原生输入或生成应用公开CLI,不运行Braid测试或模拟。原始文件在 `/Volumes/WorkSSD/Development/braid-e2e/qualification`;模型结果、候选发布和原生终态分别判断。 + +内建Issue首个实际user输入可见标记存在、HTML隐藏标记不存在。PR首个实际user输入包含关联Issue可见标记、不包含HTML隐藏标记,且设计变更前没有list --all;仅定向读取user输入,未展开assistant/CoT。元数据快照中provider均为minimax、model均为MiniMax-M3;原生cost=0不据此声称免费或账户实际扣费。 + +Issue Agent引导提交 `e2ae347be95a9d49f015b5c33cb36bf6d4dee553` 与其父 `2d65e72bde70d4ddb006f4b3f0ead030a01bb730` 的tree均为 `a7dde826386b8cb7bcc54152f8a24b5f590ed0ba`,diff为空,没有预制业务实现。 + +PR Agent真实实现固定提交 `25f92ed815c2d268b07da2ed72b8bc567c895ddd` 仅增加notes.py和更新本轮README,未越过业务目录。该提交自publish被gateway清洁判定拒绝,尚未发布;下列结果只证明此Git产物符合原始应用需求,不能证明黄金路径或发布成功。 + +从固定OID提取原件后,独立实际运行8次CLI:中文/引号新增、第二条新增、另进程持久读回、归档、默认列表排除归档、重复归档、无效ID、损坏JSON。正常操作退出0,内容和创建顺序保持;重复归档没有修改存储。无效ID退出4并显示具体ID,损坏JSON退出3并显示位置与解析原因,两者原存储SHA前后一致。归档保留原正文。原始命令、stdout/stderr、退出码及存储在 `builtin-initial/observations.json`。list --all及重复标题为后续设计变更,当前未以此候选验收。 + +修复版全新内建attempt2的Issue首user record `7dfbe09f`(08:23:10.559Z,1127字符)与PR首user record `a49e7953`(08:25:09.191Z,4693字符)均含可见标记、不含HTML隐藏标记。PR首输入没有尚未提出的list --all设计。只核对首条user Context,不以此推断全部工具读取;证据为builtin-attempt2-first-context.json及builtin-attempt2-first-pr-context.json。 + +内建attempt2首发布候选 `1af808614e0112274ac7eb0baff3d1839599264e` 由真实PR Agent自行publish。根提取固定OID原件,独立8项原定CLI操作符合要求:正常退出0,invalidID退出3、malformedJSON退出4且错误具体,两者及重复归档存储SHA不变。另以有效JSON但错误根结构 `[]` 实际add,出现exit1与AttributeError(notes.py line64错误消息对list调用data.get);文件未覆盖,但错误处理不足。已交旅程Owner通过正常验收讨论让真实Agent修复,未代写应用或采纳。原件、9次实际命令及输出见builtin-attempt2-initial/observations.json。 + +内建attempt2独立Git读回:引导提交 `ae8c303c4519994eeac67da6b4036fe2c8f1f2df` 与父 `fb1449e3321faa6494472f42a7e6fe2b09aebc37` 的tree均为 `e4d101db478db0151d79d595d62d69a352724036`,diff为空。首发布OID1af8086只更新本轮README并新增notes.py,未跨业务目录,证据builtin-attempt2-published-scope.json。 + +更新候选 `d639ff30d6a079fb5ede8dbd8a884feeaca3a4c0` 由PR Agent实际publish,根固定OID独立10次CLI操作通过:同中文引号标题两个不同ID,跨进程创建顺序保持,归档正文保留且默认排除,list --all按顺序标注archived/active,重复归档SHA不变,无效ID具体错误exit3,损坏JSON与根结构 [] 具体错误exit4、无traceback且原文件SHA不变。原件和命令输出在builtin-attempt2-design/observations.json。业务候选可正常采纳,等待修复Console Diff身份契约实际部署确认。 + +Mac存储合规失败单独记录:runtime Owner定向tool arguments确认29个包含/tmp的实际调用,涉及/tmp/issue1-design.md、/tmp/pr1-body.md及/tmp/notes-evidence/*;原始证据builtin-attempt2/raw/system-tmp-tool-facts.json。已通过正常人类讨论明确未来路径必须WorkSSD并禁止/tmp,未代改应用、未擅自删除旧现场;业务操作通过不抵销此项失败。 + +设计更新实际送达方式是普通wake的Event References,随后Agent主动读公开object show。定向toolResult `3fffb0dc`(4525字符)含list --all与[]反馈,也含HTML隐藏标记;不能把首user canonical Context过滤扩大为所有工具输入过滤。该入口返回原始对象,Context合同由projector持有。advisor发现系统提示把canonical state重读指向show,已交Owner改用既有object context,不改变原始对象API或声称HTML安全隔离。词标记证据builtin-attempt2-design-tool-context.json。 + +新版提示后的真实PR g2会话已实际调用object context 2,指定toolResult `92700617`(6077字符)由根独立词标记核对:可见需求在、list --all设计在、HTML隐藏标记不在。这证明现有canonical重读路径实际生效,不追认旧rawshow过滤;证据builtin-attempt2-new-guidance-context.json。 + +正常操作者采纳后,根独立Git读回main为 `77c8f50a5323756dc85d7a8e7f2dde2d91526c6f`,两父提交分别为基线fb1449e与已验收d639ff30;merge与候选tree均为 `a9f1fc78c702eaa33cd2b4cbd052b74286a0631f`,diff为空,证明真正采纳该候选,无需重复同内容应用CLI。证据builtin-attempt2-merge.json。 + +内建原生元数据完整收口:attempt1 83条、attempt2 205条assistant记录均为minimax/MiniMax-M3,记录id+timestamp无重复;只取usage/model元数据,未展开正文或CoT。两次输入合计346323、输出102800、缓存读取6135240 token(reasoning已包含输出,不另加)。按本轮准备记录2.10/8.40/0.42 CNY/M估算4.167599元;这是准备价格下的估算,账户扣费未知,原生cost=0不代表免费。证据builtin-usage-summary.json及两次model-metadata-final.json。 + +GitHubattempt2首真实Issue37 user record `f4799623`(2732字符)由根定向核对:可见标记在、HTML隐藏标记不在、WorkSSD约束在,尚未提出的list --all不在。原生Issue turn01a12a40-9489-7742-8359-537e7b1b4933实际运行;证据github-attempt2-first-context.json。 + +GitHubPR38首实际user record `0b96c74d`(5342字符)含关联可见需求和WorkSSD约束,不含HTML隐藏标记,也无尚未提出的list --all。Issue Agent自主ensure引导commit `8cf6782a4792d5e571d9aa708d43cacc11b6362c` 与父基线 `2cc02e78920072fdf1165def8798464012630655` tree均为 `c7d6db7a9f04cc80e4f0fa0828ae7de8005ab5dc`,diff为空;无预制业务实现。独立证据github-attempt2-first-pr-context.json和github-attempt2-bootstrap.json。 + +GitHub首发布业务候选 `e08485391b252892fec16f6678fb6084e0de9dbf` 固定原件独立9次CLI符合原定8项,另有效JSON但错误结构[]具体拒绝、无traceback、不覆盖原文件。Unicode/引号/换行正文保持、不同ID、跨进程顺序、归档保留正文、默认排除、重复归档字节不变,无效ID与损坏JSON均具体非零且原数据保持。证据github-attempt2-initial/observations.json。候选提交/推送早于定向观察到的跨空间工具操作,但执行后续实际读旧builtin配置并SQLite修改旧账本后恢复;不能把候选业务合格写成全程隔离或合规通过。 + +GitHub设计更新后的新PR原生会话09:37:03首user record `fd3e888a`(09:38:20.204Z,10381字符)由根定向核对:可见标记、list --all与WorkSSD约束在,HTML隐藏标记不在。证据github-attempt2-design-context.json;只证明该Context输入,不扩大到任意工具读取。设计正文编辑即时PR已completed,本次只计idle更新,活动更新另行取证。 + +活动正文更新实际interrupt旧turn并重建会话后,首user `053cfb4d`(09:39:38.377Z,10969字符)含可见需求、list --all、active/archived和WorkSSD,不含HTML隐藏标记。证据github-attempt2-active-design-context.json;活动状态与reset因果来自Owner原件active-body-reset-observed.json,区别于此前idle正文更新。 + +GitHub设计候选 `08c2458751a02a8143e0cb7fe620c20bd48dea16` 官方head readback后固定原件,根独立10次真实CLI均符合:同中文引号标题不同ID,跨进程创建顺序与正文保持;archive默认排除,list --all按原顺序标明archived/active;重复归档字节不变;invalidID、brokenJSON与[]具体非零且原数据不覆盖,[]无traceback。业务改动仅本轮目录README/notes.py,证据github-attempt2-design/source.json及observations.json。可按批准旅程正常采纳,网络补齐/关闭重开/合并与终态另行取证。 + +正常GitHub合并后,根读取实际fetch的origin/main `8281fffa0bb76398a0cd4c262bd69351e9ed2da6`,两父提交为blank需求base2cc02e7与qualified08c245,merge与候选tree均为 `d84062e916f597a402cfe8d292d3a0945a1c9421`,diff为空。证据github-attempt2-merge.json,证明实际采纳验收内容,不重复同内容应用CLI;Harness生命周期和最终停止另看Owner事实。 diff --git a/tasks/real-model-e2e/readiness.md b/tasks/real-model-e2e/readiness.md new file mode 100644 index 00000000..36401721 --- /dev/null +++ b/tasks/real-model-e2e/readiness.md @@ -0,0 +1,47 @@ +本文件保留执行前准备时的事实;本轮已结束,最终结果见 [results.md](results.md)。 + +# 真实模型与双上游准备回执 + +本回执只记录准备事实,不授予模型调用、GitHub 写入、隧道启动或数据库迁移授权。凭据值没有读取输出;没有启动模型、Pi turn、Braid runtime、Collector 或 tunnel。 + +## 已准备的隔离材料 + +- GitHub 目标仓库为私有 `xiaoland/braid-poc-test`,当前只读克隆到 `/Volumes/WorkSSD/Development/braid-e2e/source/github`;初始 `HEAD` 为 `6425f01e20ed4894b38ef4adc5da359896d07c20`,工作树干净。 +- 内建上游使用同一初始提交的独立克隆 `/Volumes/WorkSSD/Development/braid-e2e/source/builtin`。两个克隆使用独立 Git 对象库,没有修改 GitHub 远端或旧的 `~/.braid` checkout。 +- 两份 Harness 配置位于 `config/github.toml` 与 `config/builtin.toml`。运行数据库、备份、worktree、Pi home、服务端口和 OTLP service name 都不同,均在 `/Volumes/WorkSSD/Development/braid-e2e`。 +- 内建平台配置位于 `config/builtin-platform.toml`,计划监听 `127.0.0.1:18282`;平台数据库和备份路径独立于 Harness。尚未执行 `platform init`,因此没有创建平台数据库或对象。 +- 两个 Pi home 都有独立的 `models.json`,内容只登记官方 MiniMax M3:provider `minimax`、实际 model/wire id `MiniMax-M3`、`https://api.minimax.cn/v1`,API key 只引用 `$MINIMAX_API_KEY`。用户选择名仍是 `minimax-m3`,但 Pi 会把 model id 原样送入请求,因此配置已统一为官方大小写 wire id,避免 alias 造成 404。 + +## 配置与执行器事实 + +候选 `/Volumes/WorkSSD/Development/braid-e2e/bin/braid`(0.3.2,SHA-256 `50719bcd2adc3e2a261f7a703bf9b572bb0fb2f7db0584edbcbacec6ca081d6f`,源码 `1fdef82`)对两份 Harness 配置的 `config check` 均通过,结果为 schema 3,profiles 为 `issue-minimax` 与 `pr-minimax`,trace sample ratio 为 1。GitHub 配置引用已有 App ID `4780313`、已有私钥和 webhook secret 的绝对路径,但没有复制或改写旧系统盘实例;内建配置没有 GitHub 凭据。 + +本机 Pi 为 `1.0.2`,Braid 的 Pi adapter 会把配置中的 `provider`/`model` 转成 `pi --provider minimax --model MiniMax-M3`,把独立 home 作为 `PI_CODING_AGENT_DIR`,并把 `MINIMAX_API_KEY` 传给子进程。Pi 的 OpenAI-compatible transport 将 `model.id` 原样提交,因此没有隐含 alias 映射;`models.json` 结构沿用当前 Factory/Pi 的 `providers` → `baseUrl`/`apiKey`/`models` 契约。没有运行 Pi help 以外的模型操作;当前全局 Pi catalog 没有本轮官方 `/v1` 接线,所以真实运行必须使用这两个独立 home 的 models.json。 + +MiniMax 凭据来源明确为 `/Volumes/WorkSSD/Development/agentic26/.env`。只读解析确认 `MINIMAX_API_KEY` 非空,`MINIMAX_BASE_URL=https://api.minimax.cn/v1`;启动加载器 `load-minimax-env.sh` 只提取这两个名字,不 source 整个 `.env`,也不打印值。官方 M3 的现有计费记录是普通按量,≤512K 输入时输入/输出/缓存读取为 `2.10/8.40/0.42 元/M`,账户余额和套餐额度仍未知。 + +## GitHub App 与隧道边界 + +此前只读 `braid doctor` 已验证 App 私钥、webhook secret、App 身份和 installation 可访问 `xiaoland/braid-poc-test`;当前仓库 GitHub hooks 数量为 0。使用现有 App 私钥生成的短生命周期 JWT 只读 GET 已确认:可见 installation 仅有 `157947940`(账号 `xiaoland`,selected repositories,权限含 issues/contents/pull requests 写、metadata 读);App-wide hook config 的 URL、JSON content type 和 `insecure_ssl=0` 存在,secret 存在。URL 与 secret 均未写入或输出。当前 `gh` 用户 token 仍只作目标仓库只读核对,不代表 App-wide 配置。 + +Braid 的 `serve --tunnel` 使用 Wrangler Quick Tunnel,并会调用 App-wide webhook 配置;它不是单仓库 hook。故本轮不能直接启动 `--tunnel`:这可能影响同一 App 的其它 installation 或正在运行的 Harness。内建模式明确禁止 tunnel。优先方案是先取得 App-wide installation/webhook 清单和影响范围,再决定是否使用一次性 Wrangler tunnel;若不接受 App-wide 影响,就需要一个已固定、已授权且指向本次独立 ingress 的外部 webhook 入口。 + +本机没有 `cloudflared` 或 `ngrok`。旧 `/Users/lanzhijiang/Library/pnpm/bin/wrangler` 实际执行报 Node `MODULE_NOT_FOUND`;已在 WorkSSD 隔离安装 Wrangler `4.149.0`,入口为 `/Volumes/WorkSSD/Development/braid-e2e/wrangler/node_modules/wrangler/bin/wrangler.js`,`tunnel --help` 已确认 `tunnel quick-start ` 命令契约。未启动 tunnel,pnpm home、store、依赖均在 WorkSSD;两份配置已改用该绝对入口。 + +## 仍未就绪的前提 + +- `MINIMAX_API_KEY` 已存在于指定 agentic26 env,但没有执行真实请求;模型费用、工具调用和流式行为仍待明确授权后取得真实证据。 +- Collector 计划使用 `127.0.0.1:14318`,当前没有启动;两个 Harness 配置已指向该独立 endpoint。 +- 内建平台尚未初始化,不能启动 builtin Harness;初始化和对象种子属于下一阶段实际验收输入。 +- GitHub 旧配置的 Codex/schema pin、旧数据库和旧系统盘 runtime 均未复用。真实验收应使用当前 Braid binary、这些新配置和新数据库,并在启动前单独决定 migration。 +- 当前准备没有改任何 GitHub 对象、App webhook、旧实例、项目源码或 Factory 源码。 +- App JWT 可见 installation 目前只有目标账号这一条,但 App-wide webhook 仍是共享边界;在实际运行前仍需把 webhook 变更与恢复纳入显式验收窗口。目标仓库的 open Issue/PR、历史对象和活动进程核对见本 packet 的追加证据;不得让新 ledger 自动接管旧对象。 + +## 目标仓库与活动隔离核对(只读) + +- `xiaoland/braid-poc-test` 当前 open Issue 为 0,open PR 为 0;历史 Issue 为 36 个且全部 closed、无 assignee;历史 PR 为 #24 和 #2,均 closed、无 assignee。 +- App installation `157947940` 的只读 installation-token 查询显示共有 2 个 selected repositories:公开 `xiaoland/braid` 与私有 `xiaoland/braid-poc-test`,均默认分支 `main`。因此即使只有一个 installation,App-wide webhook 仍覆盖至少这两个仓库,不能把隧道影响范围缩小为验收仓库。 +- 历史 Issue comment 中出现 `braid-of-xiaoland[bot]` 的 23 条记录,涉及 Issue #1、#2、#11、#12、#14,最新时间为 `2026-09-03T04:36:13Z`。这些是历史对象,不能让新 ledger 自动重认或继续驱动。 +- 只读进程核对未发现候选 Braid、旧 Braid、Pi、Wrangler 或 cloudflared 活动进程;没有跨过程 Harness 需要停用。 + +Wrangler help 核验当时只设置了 WorkSSD 的 `PNPM_HOME`,没有启动或下载 cloudflared。实际启动方案必须在外层显式设置 `TMPDIR=/Volumes/WorkSSD/Development/braid-e2e/wrangler/tmp`、`XDG_CONFIG_HOME=/Volumes/WorkSSD/Development/braid-e2e/wrangler/config`、`XDG_CACHE_HOME=/Volumes/WorkSSD/Development/braid-e2e/wrangler/cache` 和 `WRANGLER_LOG_PATH=/Volumes/WorkSSD/Development/braid-e2e/wrangler/logs`;Wrangler 4.149.0 的 cloudflared 缓存位于其 global config 下,因此这些目录可保证下载、缓存、日志和临时文件不落系统盘。源码未发现 `WRANGLER_HOME` 作为有效控制变量;若预置 cloudflared,则另设 `CLOUDFLARED_PATH` 指向 WorkSSD 文件。上述目录仅是启动时接线要求,本轮未创建或运行 tunnel。 diff --git a/tasks/real-model-e2e/results.md b/tasks/real-model-e2e/results.md new file mode 100644 index 00000000..95f27f7c --- /dev/null +++ b/tasks/real-model-e2e/results.md @@ -0,0 +1,71 @@ +# MiniMax 双上游真实端到端验收结果 + +2026-10-11,按用户“确认,允许,开始。”授权,在独立 Braid 执行内建平台与 `xiaoland/braid-poc-test` 的真实模型旅程。两上游均取得真实模型生成、更新、发布与合并的应用,修复后覆盖本轮控制和生命周期范围。首次尝试存在失败,全程存储及隔离合规未通过;本轮不是无纠正黄金路径,也不宣称完成 tagged release 或 Codex campaign 资格。 + +源码修复提交为 `3fab0d0`。GitHub 最终实际 binary SHA-256 为 `728df182e9461e9150b8dee3c3bd2bbfd86989c9d08b58c457e441c8a6067e62`;内建收口版本为 `81f963d0d5b7b4597e3707527deb0e01c4775f99197e7be242b82e84a556ccd9`。两者是本地源码候选 0.3.2,记录各次部署身份,不以最终提交替代原运行版本。 + +所有模型均为 MiniMax 官方 `MiniMax-M3`(需求名称 `minimax-m3`)。凭据仅从用户指定文件加载,报告与配置不包含 key。执行、日志、原生会话、原始证据及应用提取位于 `/Volumes/WorkSSD/Development/braid-e2e`;发生过的系统盘写入另记为失败,不因后来回收而追认合规。未启动 Factory、赛事运行或外部应用评测。 + +## 真实产物与采纳 + +两上游从仅含需求的空白基线独立生成相同用途的 Python 笔记 CLI。Issue 角色维护设计,PR 角色实际实现和发布;开发 Agent 只驱动公开协作动作并实际调用固定候选应用,没有代写业务答案。 + +| 上游 | 发布的设计候选 | 实际合并 | 独立应用操作 | +| --- | --- | --- | --- | +| 内建 | `d639ff30d6a079fb5ede8dbd8a884feeaca3a4c0` | `77c8f50a5323756dc85d7a8e7f2dde2d91526c6f` | 10 次操作符合要求 | +| GitHub | `08c2458751a02a8143e0cb7fe620c20bd48dea16` | `8281fffa0bb76398a0cd4c262bd69351e9ed2da6`,[PR #38](https://github.com/xiaoland/braid-poc-test/pull/38) | 10 次操作符合要求 | + +固定候选操作覆盖中文、引号、换行正文、同标题唯一 ID、跨进程持久化与创建顺序、归档保留正文、默认排除归档、`list --all` 的状态、重复归档不改数据,以及无效 ID、损坏 JSON 和错误根结构的具体非零错误与原数据保持。两次合并都是真正的两父提交,文件树与已验候选完全一致。首候选与失败候选另有原件,不混成最后采纳内容。 + +## 本轮判据 + +`pass` 指有本轮真实操作证据;`fail` 保留已观察失败;`unavailable`、`not-run` 均不算通过。 + +| 判据 | 内建 | GitHub | +| --- | --- | --- | +| 真实输入、角色分工、模型生成与发布 | pass,Issue 空 bootstrap、正常人工指派 PR | pass,Issue 自主 ensure Draft/关联 PR,真实官方事件自动激活 | +| 关联设计变更和独立应用操作 | pass | pass | +| canonical Context 可见/隐藏标记 | pass,首输入及修复后的公开 context 重读;raw show 曾含隐藏正文 | pass,首输入与新设计/活动更新后的输入;不扩展到任意工具读取 | +| 普通讨论合并、quiet、等待时停止与重启 | pass,原待处理批次恢复后单轮消费 | pass,两条讨论同批次单轮;App 自身评论 origin echo 不自循环,git push 作为外部 synchronize 单列 | +| 空闲与活动正文更新 | pass | pass;首次误报 active 已更正为 idle,另以即时 running 记录验证真正 active reset | +| 关闭/重开/合并 | pass,关闭后只读修复,合并单次收口并退休 | pass,closed 收口 sleeping、reopen 新会话、合并等原执行结束后单次收口并退休 | +| 改派、撤销与迟到写入 | pass,原合法旧 cap 携当前 revision 实际 HTTP 409;最初格式拒绝不计 | unavailable:普通 App trusted mention 模式,不模拟 native assignment 或内建 grant | +| 停止及退休后普通输入/重启 | pass,公开 stopped、真实 Pi wait;退休后 PR turn 总数保持 9 | pass,公开 stopped、真实 Pi wait;退休后 PR turn 总数保持 11 | +| 上游在 Harness 停止后存续/网络补齐 | pass,平台独立存续并保留对象与游标 | pass,官方 webhook 530 后 reconciliation 实际 ingest→batch→turn→原生引用同评论→完成;原失败 delivery 不重投 | +| OTLP、Console 与停止后历史 | pass,11193 条记录及历史 trace 可读;Diff 竞态已修复并真实验证 | pass,15357 条记录及历史 trace 可读;对象权威仍在 GitHub | +| 无纠正首轮黄金路径 | fail | fail | +| 全程存储与空间隔离合规 | fail,实际工具曾写系统 `/tmp`,限定归属回收不抵销原失败 | fail,配置继承缺失后模型触及旧内建空间并直接改旧 ledger 后恢复,不声称未触 | + +末次重启未重新创建原生会话。真实 Pi 退出证据属于最后仍有模型的代次,不把末次无原生会话的 stopped 状态当作新退出证明。首次内建 provider 停止 unknown 仍保持 unknown,未解锁或修改其账本。 + +## 修复及未抵销的失败 + +本轮真实运行暴露并修复:内建 ready 仍按旧 local 判定;忽略文件被候选清洁检查误算;Pi 保留 stdin 等待依赖 EOF 的进程退出;关闭后只读 context 错依赖 writer grant;merged 事件未进入统一终态/退休;Diff 内容缺少固定对象与提交身份;canonical 重读指引误指 raw show;GitHub 原生会话遗漏当前配置路径。严格 Clippy、构建与差异格式检查通过,实际接续与应用操作提供产品反馈;按用户指令未运行 Braid/Factory 测试。 + +验收设施错误也保留:App 临时路径遗漏 `/webhook` 导致官方 404;人工 signed ping 的假 node 污染首 GitHub ledger,真实官方事件因此 503;新 attempt 工作目录替换错误导致 blocked。后续使用隔离 source/ledger/native/Collector、真实正常评论与同需求空白基线继续,没有放宽产品身份约束、私改状态解锁或重投旧事件。 + +首 GitHub 业务候选 `e084853` 的提交/推送早于已观察跨空间操作,独立 9 次应用操作符合原要求;此时序不构成完整隔离证明。旧内建 ledger 的仓库名虽读回原值,但发生过 UPDATE,不能写成未触及。模型评论的“未触仓库外”不作为事实。 + +另记录一次开发协作错误:network 子 Agent 曾向独立聊天“通用 Harness 迭代工具”发送 8 条进展。用户纠正后已停止,未再发送清理、道歉或补充;当前任务的内部协调不能授权联系独立任务。 + +## 用量与收尾 + +原生元数据共 646 条 assistant 记录,均为 `minimax / MiniMax-M3`,记录身份无重复;未展开正文或 CoT。内建两次 input 346323、output 102800、cacheRead 6135240;GitHub attempt2 input 658424、output 83872、cacheRead 11237691,首次网络失败 attempt 没有模型执行。reasoning 已包含在 output,不另计。 + +按本轮准备时 input/output/cacheRead `2.10/8.40/0.42 CNY/M token` 估算总计 **¥10.974644**。这是冻结价格下的估算,实际账户扣费未知;SDK cost=0 不代表免费。原始分项见 `qualification/all-usage-summary.json` 与各 attempt model-metadata-final.json。 + +GitHub 最终公开 stop 为 stopped/error=null;独立浏览器确认 Collector 15357 条/1146 批次、接收错误及重复为 0,初始 PR trace 仍可读。内建最终亦 stopped/error=null,并保留平台对象、候选和合并历史。 + +GitHub 官方恢复后 closed delivery `cc498440-c558-11f1-98bb-49512759d9a4` 返回 HTTP 202。App webhook 已恢复 baseline 的 URL/content_type/insecure_ssl,PATCH 未携带掩码 secret,readback 三字段一致;Wrangler/cloudflared 进程已结束,原失败和恢复证据保留。 + +运行 Owner 结束最后 Console,exit 0;旧 blocked Console 退出 1,保留原 `runtime stop unconfirmed / Pi child exit timed out`,不追认其 provider 停止。定向进程核对无本任务 Braid/Pi/Wrangler/cloudflared;14318、19318、24318、25318、18180、18181、18282、19282 均无监听,临时平台服务已结束。原件为 `github-attempt2/raw/final-console-process-exit.json`;不通过删除数据库清理,原始失败、unknown、模型与产物身份均保留。 + +未验证 tagged release 安装、Codex、三次完整 campaign、兼容 rollback、未授权身份矩阵和费用账户账单;本轮不授予这些资格。HTML Context 过滤与精确配置绑定不是对同账户工具进程的安全沙箱。 + +## 证据入口 + +- [批准的执行方案](plan.md)、[准备记录](readiness.md)与冻结的 input/config。 +- [内建运行记录](builtin-results.md)、[GitHub 运行记录](github-results.md)。 +- [独立产物和 Context 观察](qualification-results.md)。 +- [Console 独立浏览器记录](console-results.md)、[网络与 App 恢复记录](github-network-results.md)。 +- 原始证据与固定应用位于 `/Volumes/WorkSSD/Development/braid-e2e`;报告不复制 provider transcript 或真实凭据。 diff --git a/tasks/real-model-e2e/start-github-wrangler.sh b/tasks/real-model-e2e/start-github-wrangler.sh new file mode 100755 index 00000000..37858a46 --- /dev/null +++ b/tasks/real-model-e2e/start-github-wrangler.sh @@ -0,0 +1,18 @@ +#!/bin/sh +set -eu + +ROOT=/Volumes/WorkSSD/Development/braid-e2e/wrangler +WRANGLER=$ROOT/node_modules/wrangler/bin/wrangler.js + +if [ "$#" -ne 1 ]; then + echo "usage: $0 http://127.0.0.1:18180" >&2 + exit 2 +fi + +export TMPDIR=$ROOT/tmp +export XDG_CONFIG_HOME=$ROOT/config +export XDG_CACHE_HOME=$ROOT/cache +export WRANGLER_LOG_PATH=$ROOT/logs +export TUNNEL_TRANSPORT_PROTOCOL=http2 + +exec /opt/homebrew/bin/node "$WRANGLER" tunnel quick-start "$1" --log-level info diff --git a/tasks/self-contained/operations/.gitignore b/tasks/self-contained/operations/.gitignore new file mode 100644 index 00000000..00866136 --- /dev/null +++ b/tasks/self-contained/operations/.gitignore @@ -0,0 +1,3 @@ +* +!.gitignore +!results.md diff --git a/tasks/self-contained/operations/results.md b/tasks/self-contained/operations/results.md new file mode 100644 index 00000000..1f9f1390 --- /dev/null +++ b/tasks/self-contained/operations/results.md @@ -0,0 +1,176 @@ +# 本地协作对象实际操作 + +2026-10-11,在 `operations/objects/` 的隔离 WorkSSD Git 仓库和 SQLite 空间上执行 Braid 实际 CLI,没有启动模型、Agent 生成或 GitHub 操作。这些记录是本次人工实际操作的回执,没有新增测试入口或操作脚本。 + +`braid init` 生成不含 GitHub App 的配置;迁移回执显示数据库从 0 升至 4。随后创建 Issue #1,追加评论及指向第一条评论的回复,修改正文、指派 default Profile、关闭和重开。PR #2 使用同一个编号序列,关联 Issue #1。`context` 显示修订后的正文、两条评论及回复关系,`diff` 返回真实 Git tree 的补丁。 + +PR 创建时 head 为 `d2eb00a171d4fa0c4f76e7376fd638c5ea01d9d1`,base 为 `5d7172e0d4f4e56b23aec8be6813a15677543477`。在另一个干净已提交 checkout 上执行 `publish 2` 后,候选变为 `c1eeeb3ea86489f76774ccfda3f7a8f621bb4953`。`merge 2` 通过 Git ref CAS 将 `refs/heads/main` 更新至双亲提交 `83b82a83722827792a191af56b9e55136f270fb9`;该提交的 README 同时包含初始 candidate 和后续 published 内容。再次执行 merge 返回相同提交与 `recovered=true`,没有再创建或采纳一个提交。 + +另建工作树从发布的 `c1eeeb3…` 开始,实际 HEAD 与发布候选一致,文件包含 published 内容。原 head 名称 candidate 保留;运行后端新建 PR generation 从明确候选 OID 出发,不把创建时旧分支作为已发布候选。 + +实际拒绝的操作包括:无活动 assignment/session/turn 的 Agent CLI 写入,错误 repository 身份复用同一数据库,跨对象回复关联,向已合并 PR 发出 reopen,以及向正在检出的 base 分支合并。真实 Git 冲突记录在 PR #5 的 merge 状态中,包含 `README.md` 路径及冻结 head/base;目标分支没有移动。`show 5` 可直接读取持久错误。 + +回执见 `objects/` 下的 JSON、Markdown、patch 和 error 文件。配置、Git 仓库与 SQLite 现场保留在 WorkSSD 并由任务目录忽略。实现通过编译和严格 Clippy;源码与迁移由主 Agent 统一提交。 + +没有模拟进程崩溃或构造 Agent 运行状态;prepared→Git CAS→applied 的崩溃接续依据仍需真实崩溃场景资格确认。也没有运行模型来验证 Agent 自己调用这些工具的完整任务。 + +## 持续运行与队列 + +主 Agent 使用另一份隔离 source 和本地配置,先在停服状态创建 Issue 和评论,再以 +`serve --transport-only` 启动。实际 health 返回本地服务就绪、provider disabled; +local_events 1、2 全部确认,原 Store ledger 分别持有 noop/consumed 与 wake/pending, +对应 wake batch 已为 runnable。原始回执为 `runtime/first.json`。 + +正常 SIGINT 停服后追加指派和评论,source 切换到 operation-staging 分支,再次启动。 +4 条 local_events 均确认,4 条 delivery 的 duplicate_count 全为 0;原评论、指派仍在, +同一 batch runnable、event_count=3。配置 default_branch 仍是 main,未由当前 checkout +重新推导。实际停止后没有留下本轮 daemon。原始回执为 `runtime/restart.json`。 + +再以原生执行开启、明确缺少 BRAID_OPERATION_KEY 的状态启动,同一公开 health 返回 +HTTP 503、ready=false、provider=unavailable,保留完整的缺失环境变量原因。该操作 +没有开始模型或原生 Agent turn。现场未配置 OTel Collector,观察到明确 HTTP export +network error;没有用此现场宣称 telemetry 或模型全链路验收。回执为 +`runtime/provider-unavailable.json`。 + +三份旧迁移在本轮没有改变。操作文件被 Git 忽略,摘要与源码一起保存;所有构建、 +缓存、数据库和临时文件均位于 WorkSSD。 + +最终 binary 的 transport-only 服务重新启动并由 SIGINT 正常退出(exit 0)。 +旧 GitHub config.example.toml 通过公开 config check;Local 实例的 github probe +在连接之前明确拒绝,未借此访问 GitHub。最终 build、严格 Clippy、fmt 和 diff +空白检查通过,未运行测试。 + +## Web Console 与可观测性反哺(2026-10-11) + +独立 Braid 增加 Console 的 OTLP 接收/证据数据库/查询/可视化与直接控制接口, +未迁入 Factory 的实验或赛事生命周期。所有新现场在 WorkSSD;没有模型、外部 +GitHub、测试或额外自检运行。当前产品和操作合同见 docs/user-manual/console.md、 +docs/20-product-tdd/README.md 与 docs/40-deployment/README.md。 + +实际 SDK 三信号已通过公开诊断命令发送,Collector 保留完整原始批次、属性、 +资源身份和纳秒发生时间。原样和 gzip 重发保留各自接收事实与重复标记;gzip +原件下载 687 字节 SHA-256 与发送原件一致,不被浏览器 HTTP 自动解压。游标 +分页、trace 过滤、正常重启保留旧批次均实际确认。最终版本的坏 protobuf 400、 +错误方法 405、跨 Origin 403 和真实 SQLite 写锁 503 均为 protobuf Status,保留 +具体错误及 SQLite code 5。Web 查询错误仍为 JSON。先前 500/JSON 的回执保留为 +修复前事实,不能作为最终行为。超限 413 明确说明正文未捕获。原件在 collector/。 + +浏览器实际完成 Issue #1 创建、评论、编辑、指派 default、关闭和重开;评论中的 +script 以文本显示。双页面旧 revision 6 与新增评论后的 revision 7 冲突,HTTP 409 +返回具体实际/期望 revision,旧草稿保留。导航取消也保留草稿,操作中阻止切换。 +独立 HTTP 操作确认重复 request ID 不重复创建、不同 payload 复用 ID 返回 409、 +两个同 revision 编辑只有一个被接受;正常进程重启后持久回执不变。对象 raw +回执在 objects/http-*,浏览器回执与截图在 console/。 + +浏览器真实建立 PR #2 并关联 Issue #1,读取 README 的实际 diff,发布配置 source +当前已提交候选,再通过 DOM 确认层合并。持久意图与 Git 一致: + +- base:`700afd192d26fc8bcd3223892db9819c1e28b1e5`。 +- head:`ae2e3dd18694621cd52f829dfa095fecc99744b2`。 +- merge:`77288eed6e7d495130927d476a1a2c0a06f57915`,有上述两个父提交及候选正文。 + +同请求回执查询仍返回相同合并提交。控制候选只接受固定 source 或该 PR 当前 +责任登记的 worktree;浏览器无任意路径或 shell 入口。并发 canonical merge +意图/CAS 防护已实现,未做强制崩溃资格验证。 + +Console 的仅传输 runtime 经浏览器启动、停止并重启,provider 始终 disabled。 +DOM 停止请求先返回 accepted/stopping,再查询取得 stopped、无错误,Collector +保持在线。最终实际操作 generation 为 +`01a1299c-9a6c-7980-ac8a-3221d3b49b3c`;停止前后接收真实 runtime/control/ingest/ACK +日志与 runtime transition metric。发生时间为 0 的日志使用 observedTime 展示, +不会显示 Unix epoch。代次指标最后改为 generation_started/generation_ended, +明确观察代次结束不证明原生执行已停止;具体停止证明来自 supervisor。 + +复制前轮真实 schema 4 数据库后,通过公开 migrate apply 升至 schema 5,并取得 +迁移前备份。前后 local_items=1、local_comments=2、local_events=4、deliveries=4、 +events=4、wake_batch_events=3,历史对象和事件数量保持;原现场未修改,见 +console/upgrade/upgrade-observed.json。原迁移 1–4 没有改动。 + +严格 Clippy、编译、格式与最终嵌入资源浏览器回读通过。已合并 PR 显示候选操作 +结束,移除来源、发布和合并控件,保留真实 Diff 与持久合并记录。最终隔离 Console +由 SIGINT 正常退出(exit 0),本轮服务全部关闭。没有证明 SDK +自动重试、真实模型 provider/session/turn 全链路或 Console 崩溃后的完整恢复。 +Collector 与 managed runtime 同进程,不提供进程级故障隔离;未确认停止会阻断 +替代启动。采样证据不能替代 SQLite/provider 权威或产品完成。 + +2026-10-11 平台独立权威这一轮的原始回执在 `platform/`。此前 runtime 同库和 +worktree 候选接口是旧版本事实;当前平台另有配置、Git source、默认分支和数据库, +发布入口接受固定 source 当前已提交 HEAD 或该对象库内可解析的明确 commit OID。 +平台 HTTP 进程在未装配 Harness 的情况下完成 Issue、讨论、指派、PR、发布、真实 +Diff 和双父提交合并。平台数据库只有 12 个平台/SQLite 表,没有 provider_sessions、 +turns、assignments 或 worktrees。初始化时 source 为 primary,切到 candidate 后 +repository API 仍返回固定 defaultBranch=primary。 + +普通作者 alice 创建并指派 implementer。Grant epoch 1 评论被接纳并产生 agent +origin_echo;同 actor 再次指派推进对象 revision 并同事务撤销旧 grant(epoch 2)。 +随后旧 epoch 的 revoke 确认返回 HTTP 200 / revoked / epoch 2,旧凭据晚到评论即使 +携带正确 revision 仍返回 HTTP 409,具体错误为 writer grant stale/revoked。 +旧 revision 的普通编辑也返回 409 与实际/预期 revision。异端口 Origin 返回 403。 +Grant token 没有出现在 snapshot 或记录的 JSON 回执中。 + +PR 初建 head 为 `efb436c8d209f3e10c5bb4ad28b3a7c6f3afcc92`,发布明确 candidate +`820cb2e416a05ed2dab9356b9db7115cb7e79e62` 后 Diff 包含后来提交的正文。 +真实 primary 合并为 `0822892fb2e49ff816e190febeadd096017a0d66`,父提交分别是 +base `946ab4250f246bf8d199c0924181ec8a57d0d931` 与已发布 candidate。重复合并 request ID +返回同一回执,关联 Issue 保持 open。状态评论幂等重放、reaction 添加与删除均返回 +HTTP 200。分段 events(after=0/3) 读取后,9 条事件的 consumed_at 全部仍为 NULL; +消费游标属于各 Harness,此处没有通过读取事件修改全局消费事实。 + +显式 import 从此前 schema 5 runtime 副本导入独立平台库:6 个对象、2 条评论、 +16 条事件、3 条合并事实,以及 scope=objects 的 3 条控制回执。7 张对象表的逐行 +JSON SHA-256 前后一致,旧 `local:*` context 和创建回执通过新 HTTP 读取成功。 +源 SQLite 文件导入前后 SHA-256 同为 +`3ecfac3f2fa28913567ca7e8282e535c3850b72a6765b9a105eba9105fbdace3`。 +导入目标没有 Harness 表,原数据库保留。两次独立平台服务均通过 SIGINT 正常退出 +(exit 0)。未进行强制崩溃、模型执行或远端 GitHub 操作;实际证据不宣称这些边界 +已经取得资格验证。 + + +## Builtin 双 Harness 与旧消费事实接入 + +2026-10-11 通过独立 Console HTTP controller实际运行两套 transport-only Harness,共用独立平台,provider disabled、无模型/GitHub调用。两个不同稳定clientId各自首次cursor1,实际running/ready;正常stop均confirmed stopped。停止期间平台新增指派sequence2,重启后各cursor2、delivery2/event2/wake_batch_event1,平台consumed_at始终NULL。没有新事件的第二次正常重启后 cursor、event/delivery/wake数量及duplicate_count均未变化。最终A/B及迁移Harness均stopped、ready=false、error=null,本轮所有服务正常退出0。 + +正式 import 导入旧 Console upgrade schema5的真实消费现场副本,保留源原件,副本Harness迁移至6。新的cursor从0读至4;4条旧event IDs/lifecycle保持(1 consumed、3 pending),wake_batch_events仍3,4条原local:N delivery各duplicate_count0→1。这是通过原delivery去重保留旧消费事实,不是跳latest cursor。导入平台的历史consumed_at也保持原值,feed不会修改它。 + +新增object receipt入口实际GET原创建回执、退出0。完整原始证据与具体请求见[独立接入反馈](dual-harness/results.md),其中包括双client绑定、每代generation、受理/终态、原SQLite只读事实与receipt JSON。实际native Agent grant/turn执行、close后的native清理和真实GitHub接入未获本轮模型授权,未验证。 + +2026-10-11 整体 Console 的实际操作证据在 `platform-console/`。仅装配平台时, +浏览器完成 Issue 创建、评论及不依赖 Harness Profile 的指派;关联 PR #2 发布固定 +候选并读取真实 Diff。随后同一 Console 装配独立 Harness 数据库,启动仅传输运行, +provider 始终 disabled。停止请求先返回 accepted,再取得 stopped;Collector 和平台 +仍在线,浏览器随后完成真实 PR 合并。base 为 +`bfe87fc57c04eb2345f8217ef7010d490f781b1c`,head 为 +`61261833bbf799ecc4b9d34e0b12138961286fb7`,双父 merge 为 +`70ebc16e1b4bd2bf22ca1579124cea4bd9492c31`。已合并页面保留 Diff 和记录,结束候选 +发布及合并入口。最终正常重启后 Harness 保持 stopped,独立 snapshot 保留平台 +space ID、client ID 与 cursor=6,以及两个已有队列;24 条已接收观测和 7 个批次 +属于前次采集事实,不是执行完成证明。 + +GitHub schema 2 示例通过公开 config check 和 Harness schema 6 迁移后,装配相同 +Console 控制器。实际浏览器与 HTTP metadata 确认 backend=github、未装配内建 +平台、控制器 stopped、provider disabled。未启动 GitHub Harness、调用外部 API +或运行模型;该操作证明配置和 Console 装配,不能宣称 GitHub 执行全链路已验证。 +证据在 `github-console/`。旧 `[local]` 配置通过公开入口被拒绝并给出显式平台导入 +与 `[builtin]` 配置迁移指导,没有静默覆盖既有数据库。 + +最终源严格 Clippy(`-D warnings`)和编译通过;末尾历史候选保留补丁已纳入该 +二进制。所有反馈来自编译、真实 HTTP、浏览器和 Git 操作,未编写或运行测试。 + +最终嵌入页面只读回读见 `platform-console/browser-final-*`:Harness 保持 stopped, +上游 cursor=6 与上述合并提交不变;Collector 随本轮正常启动/关闭累计为 29 条记录、 +12 个批次、2 个实例,旧平台实例过滤所得 5 条原日志仍可视化读取。最终 Console +收到 SIGINT 后正常退出(exit 0),没有启动模型或修改对象。 + +最终二进制正常重启以上两个原版本 1 平台空间后,数据库均向前升级为版本 2, +没有重建对象库。平台自己的 migration ledger 分别记录 initial / schema_checksums +及其嵌入 SQL SHA-256;启动校验通过。每个空间产生一份保留版本 1 的 SQLite 备份: +独立空间保留 2 items / 9 events,导入空间保留 6 items / 16 events。合并回执与旧 +创建回执均经 HTTP 200 读回,原对象 revision、事件与消费事实保持,证据见各空间的 +`upgrade-restart-facts.json`。 + +Git 回读确认独立空间保存了初始候选 efb436、发布候选 820cb2、冻结 base 946ab4 和 +merge 082289 四个不可移动 retention refs;历史候选由已接纳回执和发布事件补齐, +不会只保护最近的 head。导入空间的 4 个 PR 共取得 9 个 head/base/merge refs。 +源 legacy SQLite 文件 SHA-256 仍为前述值。最终两服务均 SIGINT 正常退出(exit 0), +没有遗留本 owner 的后台 listener。严格 Clippy 和编译由中央构建取得反馈;没有 +强制崩溃资格验证,也没有执行模型、GitHub 或任何测试。 diff --git a/tests/assignment.rs b/tests/assignment.rs new file mode 100644 index 00000000..cfdfd0aa --- /dev/null +++ b/tests/assignment.rs @@ -0,0 +1,153 @@ +use std::{ + fs, + path::{Path, PathBuf}, + process::{Command, Output}, +}; + +fn braid() -> Command { + Command::new(env!("CARGO_BIN_EXE_braid")) +} + +fn stderr(output: &std::process::Output) -> String { + String::from_utf8_lossy(&output.stderr).into_owned() +} + +fn stdout(output: &std::process::Output) -> String { + String::from_utf8_lossy(&output.stdout).into_owned() +} + +fn blocked_issue() -> (PathBuf, rusqlite::Connection) { + let temporary = + std::env::temp_dir().join(format!("braid-assignment-reactivate-{}", uuid::Uuid::now_v7())); + fs::create_dir_all(&temporary).expect("create test directory"); + let config = temporary.join("config.toml"); + fs::write(&config, include_str!("../config.example.toml")).expect("write config"); + let output = braid() + .args(["migrate", "apply", "--config"]) + .arg(&config) + .output() + .expect("apply migrations"); + assert!(output.status.success(), "{}", stderr(&output)); + + 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','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) + VALUES ('assignment-blocked','issue-1',1,'blocked','2026-01-01T00:00:00Z','2026-01-01T00:00:00Z');", + ) + .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 = reactivate(&temporary); + assert!( + output.status.success(), + "stdout:\n{}\nstderr:\n{}", + stdout(&output), + stderr(&output) + ); + let events: Vec<_> = connection + .prepare( + "SELECT event_id,kind,lifecycle,trusted_mention FROM events + WHERE work_item_node_id='issue-1' AND detail='operator_reactivation'", + ) + .unwrap() + .query_map([], |row| { + Ok(( + row.get::<_, String>(0)?, + row.get::<_, String>(1)?, + row.get::<_, String>(2)?, + row.get::<_, i64>(3)?, + )) + }) + .unwrap() + .collect::>() + .unwrap(); + let [(event, kind, lifecycle, trusted)] = events.as_slice() else { + panic!("expected exactly one operator reactivation event, got {events:?}"); + }; + if let Some(previous) = &first_receipt { + assert_eq!(event, previous, "retry must reuse the first durable event"); + } else { + first_receipt = Some(event.clone()); + } + assert!(stdout(&output).contains(event), "CLI receipt must identify the durable event"); + assert_eq!((kind.as_str(), lifecycle.as_str(), *trusted), ("mention", "pending", 0)); + let batches: i64 = connection.query_row( + "SELECT COUNT(*) FROM wake_batch_events e JOIN wake_batches b ON b.batch_id=e.batch_id + WHERE e.event_id=?1 AND b.work_item_node_id='issue-1'", + [event], |row| row.get(0), + ).unwrap(); + assert_eq!(batches, 1); + } + let assignment: (i64, String) = connection.query_row( + "SELECT generation,lifecycle FROM assignments WHERE work_item_node_id='issue-1' ORDER BY generation DESC LIMIT 1", + [], + |row| Ok((row.get(0)?, row.get(1)?)), + ).unwrap(); + assert_eq!(assignment, (1, "blocked".into())); + fs::remove_dir_all(temporary).unwrap(); +} + +#[test] +fn reactivation_refuses_closed_items_unblocked_history_and_a_live_successor() { + let (temporary, connection) = blocked_issue(); + connection.execute( + "INSERT INTO assignments(assignment_id,work_item_node_id,generation,lifecycle,assigned_at) + VALUES ('successor','issue-1',2,'retired','2026-01-02T00:00:00Z')", + [], + ).unwrap(); + let busy = "owner/repository#1 already has a materializing, active, or finalizing assignment"; + for (state, history, successor, reason) in [ + ("closed", "blocked", "retired", "cannot reactivate owner/repository#1 while it is closed"), + ( + "open", + "retired", + "retired", + "owner/repository#1 has no blocked assignment to reactivate", + ), + ("open", "blocked", "materializing", busy), + ("open", "blocked", "active", busy), + ("open", "blocked", "finalizing", busy), + ] { + connection + .execute("UPDATE work_items SET state=?1 WHERE node_id='issue-1'", [state]) + .unwrap(); + connection + .execute( + "UPDATE assignments SET lifecycle=CASE generation WHEN 1 THEN ?1 ELSE ?2 END", + [history, successor], + ) + .unwrap(); + let result = reactivate(&temporary); + assert!(!result.status.success(), "{state}/{history}/{successor}: {}", stdout(&result)); + assert!(stderr(&result).contains(reason), "{}", stderr(&result)); + let durable: (i64, i64) = connection + .query_row( + "SELECT (SELECT COUNT(*) FROM events), (SELECT COUNT(*) FROM wake_batches)", + [], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .unwrap(); + assert_eq!(durable, (0, 0), "{state}/{history}/{successor} must not queue work"); + } + fs::remove_dir_all(temporary).unwrap(); +} diff --git a/tests/browser/draft.test.mjs b/tests/browser/draft.test.mjs new file mode 100644 index 00000000..2051d350 --- /dev/null +++ b/tests/browser/draft.test.mjs @@ -0,0 +1,77 @@ +import assert from 'node:assert/strict'; +import { execFileSync, spawn } from 'node:child_process'; +import { once } from 'node:events'; +import { mkdtemp, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { createInterface } from 'node:readline'; +import test from 'node:test'; +import { chromium } from 'playwright-core'; + +test('并发编辑被拒绝后保留本页草稿,重新打开对象可读到已提交正文', async (t) => { + const root = await mkdtemp(path.join(tmpdir(), 'braid-console-draft-')); + const binary = path.resolve(process.env.BRAID_BINARY || 'target/debug/braid'); + const config = path.join(root, 'platform.toml'); + const checkout = path.join(root, 'source'); + let server, exited, browser; + t.after(async () => { + try { + await browser?.close(); + } finally { + server?.kill('SIGKILL'); + await exited; + await rm(root, { recursive: true, force: true }); + } + }); + execFileSync('git', ['init', '-q', '-b', 'main', checkout]); + execFileSync('git', ['-C', checkout, '-c', 'user.name=Braid', '-c', 'user.email=test@example.invalid', + '-c', 'commit.gpgsign=false', 'commit', '-q', '--allow-empty', '-m', 'fixture']); + execFileSync(binary, ['platform', 'init', '--name', 'fixture', '--listen', '127.0.0.1:0', + '--source', checkout, '--config', config]); + + server = spawn(binary, ['console', '--platform-config', config, '--listen', '127.0.0.1:0', + '--database', path.join(root, 'console.sqlite3')], { stdio: ['ignore', 'pipe', 'inherit'] }); + exited = once(server, 'exit'); + const lines = createInterface({ input: server.stdout }); + const [line] = await Promise.race([ + once(lines, 'line', { signal: AbortSignal.timeout(15_000) }), + exited.then(([code]) => { throw new Error(`Console 在报告监听地址前退出,退出码 ${code}`); }), + ]); + const endpoint = line.match(/^Braid Console (http:\/\/127\.0\.0\.1:\d+)$/)?.[1]; + assert.ok(endpoint, line); + browser = await chromium.launch({ executablePath: process.env.CHROME_BIN }); + const context = await browser.newContext(); + context.setDefaultTimeout(10_000); + const first = await context.newPage(); + const second = await context.newPage(); + const url = endpoint + '/#objects'; + await first.goto(url); + await first.getByLabel('标题', { exact: true }).fill('并发编辑'); + await first.getByLabel('正文', { exact: true }).fill('原始正文'); + await first.getByRole('button', { name: '创建', exact: true }).click(); + const item = { name: '#1 并发编辑', exact: true }; + await first.getByRole('button', item).click(); + await second.goto(url); + await second.getByRole('button', item).click(); + const editor = (page) => page.locator('section').filter({ + has: page.getByRole('heading', { name: '编辑与控制', exact: true }), + }).getByLabel('正文', { exact: true }); + const save = { name: '保存标题与正文', exact: true }; + await editor(second).fill('第二位操作者的草稿'); + await editor(first).fill('第一位操作者已保存'); + await first.getByRole('button', save).click(); + await first.getByText('第一位操作者已保存', { exact: true }).filter({ visible: true }).first().waitFor(); + await second.getByRole('button', save).click(); + await second.getByRole('status').getByText(/object #1 revision is \d+, expected \d+/).waitFor(); + await second.getByRole('button', save).and(second.locator(':enabled')).waitFor(); + assert.equal(await editor(second).inputValue(), '第二位操作者的草稿'); + + await second.getByRole('button', { name: '刷新', exact: true }).click(); + const confirm = second.getByRole('alertdialog'); + await confirm.getByRole('button', { name: '取消', exact: true }).click(); + assert.equal(await editor(second).inputValue(), '第二位操作者的草稿'); + await second.getByRole('button', { name: '刷新', exact: true }).click(); + await confirm.getByRole('button', { name: '继续', exact: true }).click(); + await second.getByRole('button', item).click(); + assert.equal(await editor(second).inputValue(), '第一位操作者已保存'); +}); diff --git a/tests/browser/package-lock.json b/tests/browser/package-lock.json new file mode 100644 index 00000000..ce5e61ac --- /dev/null +++ b/tests/browser/package-lock.json @@ -0,0 +1,26 @@ +{ + "name": "braid-console-acceptance", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "braid-console-acceptance", + "devDependencies": { + "playwright-core": "1.65.1" + } + }, + "node_modules/playwright-core": { + "version": "1.65.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.65.1.tgz", + "integrity": "sha512-hqPpz7blSMPxWVdoeE1yiBSzXsKiVOd2k+kjCvmUywD2GPO2Dd9HfcWnq9NN0GHbNZDFgZ9JfBFr+X5/BLo0qw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=20" + } + } + } +} diff --git a/tests/browser/package.json b/tests/browser/package.json new file mode 100644 index 00000000..f6a63271 --- /dev/null +++ b/tests/browser/package.json @@ -0,0 +1,7 @@ +{ + "name": "braid-console-acceptance", + "private": true, + "devDependencies": { + "playwright-core": "1.65.1" + } +} diff --git a/tests/console.rs b/tests/console.rs new file mode 100644 index 00000000..fc7abc7d --- /dev/null +++ b/tests/console.rs @@ -0,0 +1,451 @@ +#![cfg(unix)] + +use std::{ + fs, + net::TcpListener, + os::unix::fs::{PermissionsExt as _, symlink}, + path::{Path, PathBuf}, + process::{Child, Command, Stdio}, + time::{Duration, Instant}, +}; + +use nix::{ + sys::signal::{Signal, kill}, + unistd::Pid, +}; +use reqwest::{StatusCode, blocking::Client}; +use serde_json::{Value, json}; + +struct Scratch(PathBuf); + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +struct Console(Child); + +impl Drop for Console { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } +} + +fn braid() -> Command { + Command::new(env!("CARGO_BIN_EXE_braid")) +} + +fn checked(command: &mut Command) { + let output = command.output().unwrap(); + assert!(output.status.success(), "{command:?}: {}", String::from_utf8_lossy(&output.stderr)); +} + +fn wait_for(label: &str, mut read: impl FnMut() -> Option) -> T { + let deadline = Instant::now() + Duration::from_secs(15); + loop { + if let Some(result) = read() { + return result; + } + assert!(Instant::now() < deadline, "timed out waiting for {label}"); + std::thread::sleep(Duration::from_millis(20)); + } +} + +fn configure(root: &Path) -> (PathBuf, PathBuf) { + let source = root.join("source"); + checked(Command::new("git").args(["init", "-q", "-b", "main"]).arg(&source)); + checked(Command::new("git").arg("-C").arg(&source).args([ + "-c", + "user.email=braid@example.invalid", + "-c", + "user.name=Braid Test", + "-c", + "commit.gpgsign=false", + "commit", + "--allow-empty", + "-q", + "-m", + "init", + ])); + let platform_listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let platform_address = platform_listener.local_addr().unwrap().to_string(); + let platform = root.join("platform.toml"); + checked( + braid() + .args(["platform", "init", "--name", "demo", "--listen", &platform_address, "--source"]) + .arg(&source) + .arg("--config") + .arg(&platform), + ); + let executable = root.join("fake-pi"); + fs::write(&executable, "#!/bin/sh\n[ \"$1\" = --version ] || exit 99\necho 'pi 1.2.3'\n") + .unwrap(); + fs::set_permissions(&executable, fs::Permissions::from_mode(0o700)).unwrap(); + let harness = root.join("harness/config.toml"); + checked( + braid() + .args([ + "init", + "--name", + "demo", + "--adapter", + "pi", + "--model", + "unused", + "--llm-provider", + "example-llm", + "--llm-credential-kind", + "none", + "--llm-base-url", + "https://llm.example.invalid/v1", + "--endpoint", + ]) + .arg(format!("http://{platform_address}")) + .arg("--executable") + .arg(executable) + .arg("--source") + .arg(&source) + .arg("--config") + .arg(&harness), + ); + let ingress_listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let health_listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let config = fs::read_to_string(&harness) + .unwrap() + .replace("127.0.0.1:18080", &ingress_listener.local_addr().unwrap().to_string()) + .replace("127.0.0.1:18081", &health_listener.local_addr().unwrap().to_string()); + fs::write(&harness, config).unwrap(); + checked(braid().args(["migrate", "apply", "--config"]).arg(&harness)); + (platform, harness) +} + +fn serve(platform: &Path, harness: &Path, database: &Path) -> Command { + let mut command = braid(); + command + .args(["console", "--listen", "127.0.0.1:0", "--database"]) + .arg(database) + .arg("--platform-config") + .arg(platform) + .arg("--config") + .arg(harness); + command +} + +fn get(client: &Client, console: &str, path: &str) -> Value { + client + .get(format!("{console}{path}")) + .send() + .unwrap() + .error_for_status() + .unwrap() + .json() + .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(); + assert_eq!(response.status(), StatusCode::ACCEPTED, "{}", response.text().unwrap()); +} + +#[test] +fn console_controls_keep_working_when_the_observation_database_cannot_open() { + let root = + Scratch(std::env::temp_dir().join(format!("braid-console-{}", uuid::Uuid::now_v7()))); + fs::create_dir(&root.0).unwrap(); + let (platform, harness) = configure(&root.0); + let original_config = fs::read(&harness).unwrap(); + let settings: toml::Value = toml::from_str(&fs::read_to_string(&harness).unwrap()).unwrap(); + let _unavailable_health = + TcpListener::bind(settings["server"]["health"].as_str().unwrap()).unwrap(); + let alias = root.0.join("aliased.sqlite3"); + symlink(root.0.join("harness/state/braid.sqlite3"), &alias).unwrap(); + let rejected = serve(&platform, &harness, &alias).output().unwrap(); + assert!(!rejected.status.success()); + assert!(String::from_utf8_lossy(&rejected.stderr).contains("databases must be separate")); + + let observations = root.0.join("observations.sqlite3"); + fs::create_dir(&observations).unwrap(); + let stdout = root.0.join("console.stdout"); + let stderr = root.0.join("console.stderr"); + let mut console = Console( + serve(&platform, &harness, &observations) + .stdout(Stdio::from(fs::File::create(&stdout).unwrap())) + .stderr(Stdio::from(fs::File::create(&stderr).unwrap())) + .spawn() + .unwrap(), + ); + let endpoint = wait_for("Console listener", || { + assert!( + console.0.try_wait().unwrap().is_none(), + "{}", + fs::read_to_string(&stderr).unwrap() + ); + fs::read_to_string(&stdout) + .unwrap() + .lines() + .find_map(|line| line.strip_prefix("Braid Console ").map(str::to_owned)) + }); + let client = Client::builder().no_proxy().timeout(Duration::from_secs(3)).build().unwrap(); + let capabilities = get(&client, &endpoint, "/api/console"); + assert_eq!(capabilities["platform"]["managed"], true); + assert_eq!(capabilities["harness"]["configured"], true); + let resources = client.get(format!("{endpoint}/api/resources")).send().unwrap(); + assert_eq!(resources.status(), StatusCode::SERVICE_UNAVAILABLE); + let error: Value = resources.json().unwrap(); + assert!(error["error"].as_str().unwrap().contains("observation database unavailable")); + + let issue = client + .post(format!("{endpoint}/api/control/commands")) + .json(&json!({"requestId":"create", "command":{"type":"createIssue", "title":"Independent issue", "body":""}})) + .send() + .unwrap() + .error_for_status() + .unwrap() + .json::() + .unwrap(); + assert_eq!(issue["state"], "applied", "{issue}"); + runtime_command( + &client, + &endpoint, + &json!({"request_id":"start", "operation":"start", "transport_only":true}), + ); + wait_for("platform event in the Harness ledger", || { + let snapshot = get(&client, &endpoint, "/api/harness/snapshot"); + (snapshot["upstream"][0]["cursor"].as_u64().unwrap_or_default() > 0).then_some(()) + }); + let running = get(&client, &endpoint, "/api/runtime"); + assert_eq!(running["instance"], "demo"); + assert_eq!(running["provider_enabled"], false); + assert_eq!(running["stop_confirmed"], false); + runtime_command( + &client, + &endpoint, + &json!({"request_id":"stop", "operation":"stop", "expected_generation":running["generation"]}), + ); + wait_for("confirmed Harness stop", || { + let status = get(&client, &endpoint, "/api/runtime"); + assert_ne!(status["state"], "blocked", "{status}"); + (status["stop_confirmed"] == true).then_some(()) + }); + let receipt = get(&client, &endpoint, "/api/runtime/receipts/stop"); + assert_eq!(receipt["result"]["stop_confirmed"], true, "{receipt}"); + assert_eq!(get(&client, &endpoint, "/api/control/receipts/create"), issue); + assert_eq!(fs::read(&harness).unwrap(), original_config); + + kill(Pid::from_raw(i32::try_from(console.0.id()).unwrap()), Signal::SIGTERM).unwrap(); + let result = wait_for("graceful Console exit", || console.0.try_wait().unwrap()); + assert!(result.success(), "{}", fs::read_to_string(stderr).unwrap()); +} + +#[test] +#[allow(clippy::too_many_lines)] +fn object_cli_mints_on_first_write_and_platform_fences_a_delayed_mint() { + let root = Scratch(std::env::temp_dir().join(format!("braid-writer-{}", uuid::Uuid::now_v7()))); + fs::create_dir(&root.0).unwrap(); + let (platform, harness) = configure(&root.0); + let settings: toml::Value = toml::from_str(&fs::read_to_string(&platform).unwrap()).unwrap(); + let endpoint = format!("http://{}", settings["listen"].as_str().unwrap()); + let active_platform = Console( + braid() + .args(["platform", "serve", "--config"]) + .arg(&platform) + .stdout(Stdio::null()) + .spawn() + .unwrap(), + ); + let client = Client::builder().no_proxy().timeout(Duration::from_secs(3)).build().unwrap(); + wait_for("Platform listener", || { + client + .get(format!("{endpoint}/api/platform/repository")) + .send() + .ok() + .filter(|response| response.status().is_success()) + }); + let object_command = |request_id: &str, command: Value| { + let revision = command.get("number").map(|number| { + get(&client, &endpoint, &format!("/api/control/items/{number}"))["item"]["revision"] + .clone() + }); + let receipt: Value = client + .post(format!("{endpoint}/api/control/commands")) + .json(&json!({"requestId":request_id, "command":command, "expectedRevision":revision})) + .send() + .unwrap() + .error_for_status() + .unwrap() + .json() + .unwrap(); + assert_eq!(receipt["state"], "applied", "{receipt}"); + }; + object_command("create", json!({"type":"createIssue", "title":"Writer", "body":""})); + object_command("assign", json!({"type":"assign", "actor":"issue-codex", "number":1})); + let cursor = + || get(&client, &endpoint, "/api/platform/events")["lastSequence"].as_i64().unwrap(); + let base = || { + let mut command = braid(); + command.args(["object", "--config"]).arg(&harness).current_dir(root.0.join("source")); + command + }; + + let database = rusqlite::Connection::open(root.0.join("harness/state/braid.sqlite3")).unwrap(); + database.execute_batch( + "INSERT INTO owner_leases VALUES('runtime',1,'fixture','9999-12-31T00:00:00Z'); + INSERT INTO repositories VALUES('local:demo','demo',1,'now'); + INSERT INTO work_items(node_id,repository_node_id,kind,number,state,context_revision,observed_at) + VALUES('item','local:demo','issue',1,'open','revision','now'); + INSERT INTO profiles VALUES('issue-codex',1,printf('%064d',0),'pi','[]'); + 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','issue-codex',1,'issue','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','native','revision','1','running','now');", + ).unwrap(); + database.execute( + "INSERT INTO worktrees(worktree_id,agent_id,path,repository_node_id,lifecycle,observed_at) + VALUES('tree','agent',?1,'local:demo','active','now')", + [root.0.join("source").to_str().unwrap()], + ).unwrap(); + let execution_id = uuid::Uuid::now_v7().to_string(); + database.execute( + "UPDATE provider_sessions SET builtin_execution_id=?1, builtin_execution_owner='fixture' + WHERE session_id='session'", + [&execution_id], + ).unwrap(); + let authority_cursor = cursor(); + database + .execute( + "INSERT INTO turns(turn_id,session_id,context_revision,trigger_kind,lifecycle, + builtin_writer_cursor,builtin_execution_id) + VALUES('turn','session','revision','wake_batch','running',?1,?2)", + rusqlite::params![authority_cursor, execution_id], + ) + .unwrap(); + + checked(base().env("BRAID_AGENT", "1").args(["show", "1"])); + let client_id: String = + database.query_row("SELECT client_id FROM builtin_upstream", [], |r| r.get(0)).unwrap(); + let epoch = || { + let mut url = reqwest::Url::parse(&format!("{endpoint}/api/platform/grants")).unwrap(); + url.query_pairs_mut() + .append_pair("clientId", &client_id) + .append_pair("itemNumber", "1") + .append_pair("actor", "issue-codex"); + client.get(url).send().unwrap().error_for_status().unwrap().json::().unwrap() + }; + assert!(epoch().is_null()); + object_command("unrelated", json!({"type":"comment", "number":1,"body":"Human update"})); + checked(base().env("BRAID_AGENT", "1").args(["comment", "1", "--body", "Agent update"])); + let context = get(&client, &endpoint, "/api/platform/context/1"); + assert!(context["comments"].as_array().unwrap().iter().any(|comment| { + comment["body"] == "Agent update" && comment["author"]["login"] == "issue-codex" + })); + assert_eq!(epoch()["active"], true); + + let fence = |id: &str| { + client + .post(format!("{endpoint}/api/platform/executions/fence")) + .json(&json!({"executionId":id,"clientId":client_id})) + .send() + .unwrap() + .error_for_status() + .unwrap() + .json::() + .unwrap() + }; + let (request_id, grant_id, granted_epoch, token): (String, String, i64, String) = database + .query_row( + "SELECT request_id,grant_id,epoch,token FROM builtin_writer_grants WHERE session_id='native'", + [], + |row| Ok((row.get(0)?,row.get(1)?,row.get(2)?,row.get(3)?)), + ).unwrap(); + 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. + let prior_mint = json!({"requestId":request_id,"clientId":client_id,"actor":"issue-codex", + "itemNumber":1,"expectedEpoch":granted_epoch-1,"authorityCursor":authority_cursor, + "executionId":execution_id}); + let replay = + client.post(format!("{endpoint}/api/platform/grants")).json(&prior_mint).send().unwrap(); + 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")) + .json(&json!({"requestId":"old-write","actor":"issue-codex","expectedRevision":revision, + "writer":{"grantId":grant_id,"epoch":granted_epoch,"token":token}, + "command":{"type":"comment","number":1,"body":"Fenced turn"}})) + .send() + .unwrap(); + 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(); + assert_eq!(fence(&late_execution)["executionId"], late_execution); + let mint = json!({"requestId":"delayed-mint","clientId":client_id,"actor":"issue-codex", + "itemNumber":1,"expectedEpoch":granted_epoch,"authorityCursor":cursor(), + "executionId":late_execution}); + let late = client.post(format!("{endpoint}/api/platform/grants")).json(&mint).send().unwrap(); + assert_conflict(late, "execution attempt is fenced"); + assert_eq!(epoch(), json!({"active":false,"epoch":granted_epoch})); + + object_command( + "configure-root", + json!({"type":"configureRunRoot", "number":1, + "deliveryRef":"refs/heads/braid/test", "runId":"test-run", "clientId":client_id}), + ); + // 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( + braid() + .args(["platform", "serve", "--config"]) + .arg(&platform) + .stdout(Stdio::null()) + .spawn() + .unwrap(), + ); + wait_for("Platform reopening with Git offline", || { + client + .get(format!("{endpoint}/api/platform/repository")) + .send() + .ok() + .filter(|response| response.status().is_success()) + }); + + object_command( + "git-offline-comment", + json!({"type":"comment","number":1,"body":"Git-independent"}), + ); + 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); + let offline = client.get(format!("{endpoint}/api/platform/scope/1")).send().unwrap(); + assert_eq!(offline.status(), StatusCode::INTERNAL_SERVER_ERROR); + let body: Value = offline.json().unwrap(); + assert_eq!(body["error"]["code"], "unavailable"); + assert!( + body["error"]["message"].as_str().unwrap().contains("could not find repository"), + "{body}" + ); +} diff --git a/tests/durable_publication.rs b/tests/durable_publication.rs new file mode 100644 index 00000000..3127ef2b --- /dev/null +++ b/tests/durable_publication.rs @@ -0,0 +1,106 @@ +//! 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() { + use std::process::Command; + let dir = std::env::temp_dir().join(format!("braid-cli-publication-{}", uuid::Uuid::now_v7())); + fs::create_dir_all(&dir).unwrap(); + 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 command = |args: &[&str]| { + Command::new(env!("CARGO_BIN_EXE_braid")) + .args(args) + .arg("--config") + .arg(&path) + .env_remove("BRAID_AGENT") + .output() + .unwrap() + }; + let success = |output: std::process::Output| { + assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr)); + output + }; + 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 = success(command(&[ + "gh", + "pr", + "edit", + "owner/repository#1", + "--operator", + "--profile", + "pr-codex", + "--snapshot", + snapshot_file.to_str().unwrap(), + "--body-file", + body_file.to_str().unwrap(), + "--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 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 = 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"); + // 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(); +} + +#[test] +fn gh_read_runs_on_existing_runtime_without_nested_runtime_panic() { + use std::process::Command; + let dir = std::env::temp_dir().join(format!("braid-cli-read-{}-", uuid::Uuid::now_v7())); + fs::create_dir_all(&dir).unwrap(); + 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 output = Command::new(env!("CARGO_BIN_EXE_braid")) + .args(["gh", "pr", "read", "owner/repository#1"]) + .arg("--output") + .arg(dir.join("snapshot.json")) + .arg("--config") + .arg(&path) + .env_remove("BRAID_AGENT") + .output() + .unwrap(); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(stderr.contains("cannot read GitHub App private key"), "wrong failure: {stderr}"); + assert_eq!(output.status.code(), Some(1), "{stderr}"); + fs::remove_dir_all(dir).unwrap(); +} diff --git a/tests/headless_setup.rs b/tests/headless_setup.rs new file mode 100644 index 00000000..63563eba --- /dev/null +++ b/tests/headless_setup.rs @@ -0,0 +1,237 @@ +use std::{ + fs, + io::{Read as _, Write as _}, + net::TcpListener, + path::{Path, PathBuf}, + process::Command, +}; + +fn braid() -> Command { + Command::new(env!("CARGO_BIN_EXE_braid")) +} + +fn stdout(output: &std::process::Output) -> String { + String::from_utf8_lossy(&output.stdout).into_owned() +} + +fn stderr(output: &std::process::Output) -> String { + String::from_utf8_lossy(&output.stderr).into_owned() +} + +fn write_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 fake_bin(temporary: &Path) -> PathBuf { + let directory = temporary.join("bin"); + fs::create_dir_all(&directory).expect("create fake bin"); + write_executable( + &directory.join("gh"), + r#"#!/bin/sh +if [ "$1" = "api" ] && [ "$2" = "user" ]; then + echo testuser + exit 0 +fi +case "$2" in + app-manifests/*/conversions) + 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 + exit 0 + ;; + users/testuser|orgs/testuser) + printf '{"avatar_url":"%s"}\n' "$BRAID_TEST_AVATAR_URL" + exit 0 + ;; +esac +echo "unexpected gh call: $*" >&2 +exit 1 +"#, + ); + write_executable(&directory.join("pi"), "#!/bin/sh\necho 'pi 1.2.3'\n"); + for browser in ["open", "xdg-open"] { + write_executable(&directory.join(browser), "#!/bin/sh\ntouch \"$BRAID_TEST_BROWSER\"\n"); + } + write_executable(&directory.join("wrangler"), "#!/bin/sh\necho 'wrangler 0.0.0-test'\n"); + write_executable( + &directory.join("git"), + r#"#!/bin/sh +if [ "$1" = "clone" ]; then + for destination in "$@"; do :; done + mkdir -p "$destination/.git" + exit 0 +fi +echo "unexpected git call: $*" >&2 +exit 1 +"#, + ); + directory +} + +fn setup_command(fake_bin: &Path, home: &Path) -> Command { + let mut command = braid(); + 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); + command +} + +#[test] +fn no_browser_setup_can_be_completed_from_callback_url() { + let temporary = + std::env::temp_dir().join(format!("braid-headless-setup-{}", std::process::id())); + let home = temporary.join("home"); + let fake_bin = fake_bin(&temporary); + let listener = TcpListener::bind("127.0.0.1:0").expect("bind avatar server"); + let avatar_url = + format!("http://{}/avatar.png", listener.local_addr().expect("avatar address")); + let avatar_server = std::thread::spawn(move || { + let (mut stream, _) = listener.accept().expect("accept avatar request"); + let mut request = [0; 4096]; + let _ = stream.read(&mut request).expect("read avatar request"); + let png = include_bytes!( + "../docs/assets/logo/png/braid-color-on-transparent/braid-color-on-transparent-512.png" + ); + write!( + stream, + "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + png.len() + ) + .expect("write avatar response"); + stream.write_all(png).expect("write avatar image"); + }); + + let output = setup_command(&fake_bin, &home) + .args(["--no-browser"]) + .output() + .expect("start no-browser setup"); + assert!(output.status.success(), "stdout:\n{}\nstderr:\n{}", stdout(&output), stderr(&output)); + assert!(stdout(&output).contains("--callback-url"), "{}", stdout(&output)); + + let draft_path = home.join("setup-drafts/demo.toml"); + let draft = fs::read_to_string(&draft_path).expect("read setup draft"); + 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([ + "--model", + "example-chat", + "--llm-provider", + "example-llm", + "--llm-credential-kind", + "none", + "--llm-base-url", + "https://llm.example.invalid/v1", + ]) + .args(["--callback-url", "http://127.0.0.1/callback?code=wrong&state=wrong"]) + .output() + .expect("reject mismatched callback state"); + 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) + .args([ + "--model", + "example-chat", + "--llm-provider", + "example-llm", + "--llm-credential-kind", + "none", + "--llm-base-url", + "https://llm.example.invalid/v1", + ]) + .args(["--runtime-executable"]) + .arg("./pi") + .args(["--callback-url", &callback]) + .output() + .expect("complete headless setup"); + assert!(output.status.success(), "stdout:\n{}\nstderr:\n{}", stdout(&output), stderr(&output)); + assert!(!draft_path.exists()); + assert!(home.join("instances/demo/braid-of-testuser-logo.png").is_file()); + avatar_server.join().expect("avatar server"); + 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 output = braid() + .env_remove("BRAID_CONFIG") + .env_remove("BRAID_INSTANCE_HOME") + .env("BRAID_USER_HOME", &home) + .args(["config", "check", "--instance", "demo", "--json"]) + .output() + .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] +fn setup_rejects_local_runtime_failures_before_consuming_the_manifest() { + let temporary = + std::env::temp_dir().join(format!("braid-setup-preflight-{}", std::process::id())); + let home = temporary.join("home"); + let fake_bin = fake_bin(&temporary); + fs::create_dir_all(home.join("setup-drafts")).expect("create setup drafts"); + fs::write( + home.join("setup-drafts/demo.toml"), + "repository = \"testuser/repository\"\ninstance_key = \"demo\"\nstate = \"expected\"\n", + ) + .expect("write draft"); + let converted = temporary.join("converted"); + for (runtime, expected) in [ + ("#!/bin/sh\necho 'pi 1.2.3'\nexit 1\n", "--version exited"), + ("#!/bin/sh\nexit 0\n", "--version returned no version"), + ] { + write_executable(&fake_bin.join("pi"), runtime); + let output = setup_command(&fake_bin, &home) + .env("BRAID_TEST_CONVERSIONS", &converted) + .args([ + "--model", + "example-chat", + "--llm-provider", + "example-llm", + "--llm-credential-kind", + "none", + "--llm-base-url", + "https://llm.example.invalid/v1", + "--callback-url", + "http://127.0.0.1/callback?code=once&state=expected", + "--runtime-executable", + ]) + .arg(fake_bin.join("pi")) + .output() + .expect("run invalid runtime setup"); + assert!(!output.status.success()); + assert!(stderr(&output).contains(expected), "{}", stderr(&output)); + assert!(!converted.exists()); + assert!(!home.join("instances/demo").exists()); + } + let _ = fs::remove_dir_all(&temporary); +} diff --git a/tests/multi_repo.rs b/tests/multi_repo.rs new file mode 100644 index 00000000..01b149ab --- /dev/null +++ b/tests/multi_repo.rs @@ -0,0 +1,183 @@ +use std::{ + fs, + path::{Path, PathBuf}, + process::Command, +}; + +fn braid() -> Command { + Command::new(env!("CARGO_BIN_EXE_braid")) +} + +fn stderr(output: &std::process::Output) -> String { + String::from_utf8_lossy(&output.stderr).into_owned() +} + +fn multi_repo_config(example: &str, temporary: &Path) -> toml::Value { + let mut config: toml::Value = toml::from_str(example).expect("parse starter config"); + config["github"].as_table_mut().unwrap().insert( + "additional_repositories".into(), + toml::Value::Array(vec![toml::Value::Table(toml::Table::from_iter([( + "name".into(), + "owner/other".into(), + )]))]), + ); + let profiles = config["profiles"].as_array_mut().unwrap(); + for profile in &mut *profiles { + let profile = profile.as_table_mut().unwrap(); + profile.insert("repository".into(), "owner/repository".into()); + profile + .insert("workspace".into(), temporary.join("primary-source").to_str().unwrap().into()); + } + let other_profiles: Vec<_> = profiles + .iter() + .map(|profile| { + let mut other = profile.clone(); + other["id"] = format!("{}-other", profile["id"].as_str().unwrap()).into(); + other["repository"] = "owner/other".into(); + other["workspace"] = temporary.join("other-source").to_str().unwrap().into(); + other + }) + .collect(); + profiles.extend(other_profiles); + config +} + +#[test] +fn multi_repository_config_requires_repo_scoped_profiles() { + let example = + fs::read_to_string(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("config.example.toml")) + .expect("read config example"); + let temporary = + 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, toml::to_string(&multi_repo_config(&example, &temporary)).unwrap()) + .expect("write multi-repo config"); + + let output = braid() + .args(["profile", "inspect", "--config"]) + .arg(&path) + .args(["--profile", "issue-codex-other", "--json"]) + .output() + .expect("inspect repo-scoped profile"); + assert!(output.status.success(), "{}", 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()); + + for (case, expected) in [ + ("omitted", "requires an explicit repository"), + ("unconfigured", "unconfigured GitHub repository"), + ("workspace", "must share one source checkout"), + ] { + let mut candidate = multi_repo_config(&example, &temporary); + let profile = candidate["profiles"][0].as_table_mut().unwrap(); + match case { + "omitted" => { + profile.remove("repository"); + } + "unconfigured" => { + profile.insert("repository".into(), "owner/unconfigured".into()); + } + _ => { + profile.insert( + "workspace".into(), + temporary.join("different-source").to_str().unwrap().into(), + ); + } + } + fs::write(&path, toml::to_string(&candidate).unwrap()).expect("write invalid config"); + let output = braid().args(["config", "check", "--config"]).arg(&path).output().unwrap(); + assert!(!output.status.success(), "{case}"); + assert!(stderr(&output).contains(expected), "{case}: {}", stderr(&output)); + } + fs::remove_dir_all(&temporary).unwrap(); +} + +#[test] +fn instance_selectors_route_to_the_expected_config_and_doctor_names_cross_instance_conflicts() { + let home = std::env::temp_dir().join(format!("braid-instances-{}", uuid::Uuid::now_v7())); + let mut entries = Vec::new(); + for (key, app_id, schema) in [("first", 100, 3), ("second", 200, 2)] { + let directory = home.join(key); + fs::create_dir_all(&directory).unwrap(); + let mut config: toml::Value = + toml::from_str(include_str!("../config.example.toml")).unwrap(); + config["schema_version"] = schema.into(); + config["instance"]["key"] = key.into(); + config["github"]["app_id"] = app_id.into(); + config["github"]["private_key_file"] = + directory.join("missing.pem").to_str().unwrap().into(); + config["runtimes"][0]["executable"] = "/usr/bin/false".into(); + config["tools"]["gh"] = "/usr/bin/false".into(); + config["tools"]["wrangler"] = "/usr/bin/false".into(); + fs::write(directory.join("config.toml"), toml::to_string(&config).unwrap()).unwrap(); + entries.push(format!( + "[[instances]]\nkey='{key}'\nhome='{key}'\ngithub_app_id={app_id}\nrepository='owner/repository'\n" + )); + } + fs::write( + home.join("registry.toml"), + format!("schema_version=1\ndefault_instance='first'\n{}", entries.join("\n")), + ) + .unwrap(); + let second_dir = home.join("second"); + let first_config = home.join("first/config.toml"); + let command = || { + let mut command = braid(); + command.env_clear().env("PATH", "/usr/bin:/bin").env("BRAID_USER_HOME", &home); + command + }; + for (args, instance, override_home, expected) in [ + (vec![], None, None, "first"), + (vec![], Some("second"), None, "second"), + (vec!["--instance", "second"], Some("first"), None, "second"), + (vec!["--instance", "first"], None, Some(&second_dir), "second"), + ( + vec!["--config", first_config.to_str().unwrap()], + Some("second"), + Some(&second_dir), + "first", + ), + ] { + let mut command = command(); + if let Some(value) = instance { + command.env("BRAID_INSTANCE", value); + } + if let Some(value) = override_home { + command.env("BRAID_INSTANCE_HOME", value); + } + let output = command.args(["config", "check", "--json"]).args(args).output().unwrap(); + assert!(output.status.success(), "{}", stderr(&output)); + let summary: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(summary["instance_key"], expected); + assert_eq!( + summary["database"], + home.join(expected).join("state/braid.sqlite3").to_str().unwrap() + ); + } + let output = command().args(["migrate", "apply", "--instance", "second"]).output().unwrap(); + assert!(output.status.success(), "{}", stderr(&output)); + let output = command().args(["status", "--instance", "second", "--json"]).output().unwrap(); + assert!(output.status.success(), "{}", stderr(&output)); + let status: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(status["config_schema"], 2); + assert_eq!(status["database"]["pending_migrations"], 0); + assert!(status["database"]["schema_version"].as_u64().unwrap() > 0); + let output = command().args(["doctor", "--json"]).output().unwrap(); + assert!(!output.status.success()); + 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 new file mode 100644 index 00000000..e5c611db --- /dev/null +++ b/tests/provider_config.rs @@ -0,0 +1,482 @@ +use std::{ + fs, + path::{Path, PathBuf}, + process::Command, +}; + +fn braid() -> Command { + Command::new(env!("CARGO_BIN_EXE_braid")) +} + +fn stdout(output: &std::process::Output) -> String { + String::from_utf8_lossy(&output.stdout).into_owned() +} + +fn stderr(output: &std::process::Output) -> String { + String::from_utf8_lossy(&output.stderr).into_owned() +} + +#[test] +fn provider_route_inputs_are_validated_at_cli_and_config_boundaries() { + let output = braid() + .args([ + "init", + "--source", + "/repository", + "--config", + "/harness/config.toml", + "--name", + "demo", + "--adapter", + "pi", + "--executable", + "/pi", + "--model", + "example-chat", + ]) + .output() + .expect("run init without provider and credential kind"); + assert!(!output.status.success()); + let diagnostic = stderr(&output); + let error = + diagnostic.lines().take_while(|line| !line.starts_with("Usage:")).collect::>(); + for required in [ + "--llm-provider ", + "--llm-credential-kind ", + "--llm-base-url ", + ] { + assert!(error.iter().any(|line| line.trim() == required), "{required}: {diagnostic}"); + } + + let example = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("config.example.toml"); + let 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()); + 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()) + .expect("write adapter-coupled config"); + let output = braid() + .args(["config", "check", "--config"]) + .arg(&coupled_path) + .output() + .expect("reject Codex provider reference"); + let _ = fs::remove_file(&coupled_path); + assert!(!output.status.success()); + assert!( + stderr(&output).contains("provider is supported only by the Pi adapter"), + "{}", + stderr(&output) + ); + + 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"); + let output = braid() + .args(["config", "check", "--config"]) + .arg(&legacy_codex_path) + .output() + .expect("read legacy Codex provider label as inert"); + let _ = fs::remove_file(&legacy_codex_path); + assert!(output.status.success(), "{}", stderr(&output)); +} + +#[test] +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 (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-{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) + .output() + .expect("reject legacy provider config"); + let _ = fs::remove_file(&path); + assert!(!output.status.success()); + assert!(stderr(&output).contains(expected), "{expected}: {}", stderr(&output)); + } +} + +/// Write a Pi-flavored variant of the example config. models.json is derived +/// from the `llm_providers` entry, so no template file is needed; `directory` +/// stands in for the Pi runtime home and may carry extra files for negative +/// cases. +fn write_pi_config(example: &str, directory: &Path, credential_fragment: &str) -> PathBuf { + fs::create_dir_all(directory).expect("create Pi material directory"); + let mut config: toml::Value = toml::from_str(example).expect("parse starter config"); + for runtime in config["runtimes"].as_array_mut().unwrap() { + runtime["adapter_type"] = "pi".into(); + runtime["version"] = "1.0.2".into(); + runtime["home"] = directory.to_str().unwrap().into(); + } + for profile in config["profiles"].as_array_mut().unwrap() { + profile["adapter_type"] = "pi".into(); + profile["adapter_version"] = "1.0.2".into(); + profile.as_table_mut().unwrap().insert("provider".into(), "example-llm".into()); + profile["model"] = "example-chat".into(); + } + let provider: toml::Value = toml::from_str(&format!( + "id = \"example-llm\"\nbase_url = \"https://llm.example.invalid/v1\"\ncredential = {credential_fragment}\n[[models]]\nid = \"example-chat\"\n" + )).unwrap(); + config + .as_table_mut() + .unwrap() + .insert("llm_providers".into(), toml::Value::Array(vec![provider])); + let path = directory.join("config.toml"); + fs::write(&path, toml::to_string(&config).unwrap()).expect("write Pi config"); + path +} + +fn api_key_credential(directory: &Path) -> String { + fs::create_dir_all(directory).expect("create credential directory"); + let secret = directory.join("secret.toml"); + fs::write(&secret, "provider_api_key = \"test-key\"\n").expect("write api key secret"); + format!("{{ kind = \"api_key\", file = \"{}\" }}", secret.display()) +} + +fn inspect_profile(config: &Path) -> std::process::Output { + braid() + .args(["profile", "inspect", "--config"]) + .arg(config) + .args(["--profile", "issue-codex"]) + .output() + .expect("inspect Pi profile") +} + +fn check_config(config: &Path) -> std::process::Output { + braid().args(["config", "check", "--config"]).arg(config).output().expect("run config check") +} + +fn reject_config_case(example: &str, directory: &Path, mutate: impl Fn(&Path), expected: &str) { + let credential = api_key_credential(directory); + let config = write_pi_config(example, directory, &credential); + mutate(&config); + let output = check_config(&config); + assert!( + !output.status.success(), + "case {expected} unexpectedly succeeded:\nstdout: {}\nstderr: {}", + stdout(&output), + stderr(&output) + ); + assert!(stderr(&output).contains(expected), "{expected}: {}", stderr(&output)); +} + +#[test] +fn pi_derivation_rejects_bad_provider_surfaces() { + 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-derivation-rejects-{}", std::process::id())); + + 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), + |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, + ); + } + + reject_config_case( + &example, + &temporary.join("template-models"), + |config| { + fs::write(config.parent().expect("config parent").join("models.json"), "{}") + .expect("write template models.json"); + }, + "models.json is derived from llm_providers metadata", + ); + + // Schema 2 keeps the legacy models.json template path readable. + let directory = temporary.join("legacy-schema2"); + fs::create_dir_all(&directory).expect("create schema-2 directory"); + fs::write( + directory.join("models.json"), + serde_json::to_vec(&serde_json::json!({ + "providers": { + "example-llm": { + "baseUrl": "https://llm.example.invalid/v1", + "apiKey": "$BRAID_PROVIDER_API_KEY", + "models": [{"id": "example-chat"}] + } + } + })) + .expect("encode models"), + ) + .expect("write schema-2 models.json"); + let credential = api_key_credential(&directory); + let config = write_pi_config(&example, &directory, &credential); + let schema2 = fs::read_to_string(&config).expect("read generated config").replacen( + "schema_version = 3", + "schema_version = 2", + 1, + ); + fs::write(&config, schema2).expect("write schema-2 config"); + 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] +fn runtime_home_auth_json_is_always_rejected_with_import_hint() { + 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-home-auth-{}", std::process::id())); + let config = write_pi_config(&example, &temporary, "{ kind = \"none\" }"); + fs::write(temporary.join("auth.json"), "{}").expect("write runtime-home auth"); + let output = inspect_profile(&config); + let _ = fs::remove_dir_all(&temporary); + assert!(!output.status.success()); + assert!( + stderr(&output).contains("auth.json, which Profile material snapshots never carry"), + "{}", + stderr(&output) + ); + assert!(stderr(&output).contains("braid provider import-auth"), "{}", stderr(&output)); +} + +#[test] +fn init_generates_an_explicit_keyless_pi_route() { + let temporary = std::env::temp_dir().join(format!("braid-init-keyless-{}", std::process::id())); + 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 file"); + 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 executable = temporary.join("fake-pi"); + fs::write(&executable, "#!/bin/sh\necho 'pi 1.2.3'\n").expect("write fake Pi"); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt as _; + let mut permissions = fs::metadata(&executable).expect("fake Pi metadata").permissions(); + permissions.set_mode(0o755); + fs::set_permissions(&executable, permissions).expect("make fake Pi executable"); + } + + 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(&executable) + .args([ + "--model", + "example-chat", + "--llm-provider", + "example-llm", + "--llm-credential-kind", + "none", + "--llm-base-url", + "https://llm.example.invalid/v1", + ]) + .output() + .expect("run keyless Pi init"); + assert!(output.status.success(), "{}", stderr(&output)); + let generated = fs::read_to_string(&config).expect("read generated config"); + 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"); + let isolated_home = temporary.join("user-home"); + + let output = braid() + .args(["doctor", "--config"]) + .arg(&config) + .env("BRAID_USER_HOME", &isolated_home) + .output() + .expect("run doctor with unavailable optional OTLP"); + let checks = stdout(&output); + assert!(checks.contains("Pass\tPi provider"), "{checks}"); + assert!(checks.contains("explicit keyless route"), "{checks}"); + assert!(checks.contains("Unavailable\tOTLP endpoint"), "{checks}"); + let _ = fs::remove_dir_all(&temporary); + assert!(output.status.success(), "stdout:\n{}\nstderr:\n{}", stdout(&output), stderr(&output)); +} + +#[test] +fn provider_import_auth_converts_pi_credentials() { + let temporary = + 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, + "refresh": refresh, + "expires": 4_102_444_800_000_u64, + "account": account, + "vendor_specific": "dropped-with-warning" + }, + "other-provider": {"type": "api_key", "key": api_key} + })) + .expect("encode auth.json"), + ) + .expect("write fake Pi auth.json"); + + let import = |provider| { + let mut command = braid(); + command + .args(["provider", "import-auth", provider, "--from"]) + .arg(&pi_auth) + .arg("--user-home") + .arg(&user_home); + command + }; + let output = import("example-llm").output().expect("import OAuth credential"); + assert!(output.status.success(), "stdout:\n{}\nstderr:\n{}", stdout(&output), stderr(&output)); + assert!(stderr(&output).contains("dropping provider-specific OAuth field \"vendor_specific\"")); + let imported = user_home.join("secrets/example-llm.toml"); + let text = fs::read_to_string(&imported).expect("read imported credential"); + 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 _; + assert_eq!(fs::metadata(&imported).expect("metadata").permissions().mode() & 0o777, 0o600); + } + + 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"); + 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 = import("missing").output().expect("reject missing provider"); + 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)] + { + use std::os::unix::fs::PermissionsExt as _; + fs::set_permissions(&imported, fs::Permissions::from_mode(0o644)) + .expect("simulate an existing unprotected credential"); + let output = + import("example-llm").arg("--force").output().expect("replace an existing credential"); + assert!(output.status.success(), "{}", stderr(&output)); + assert_eq!(fs::metadata(&imported).expect("metadata").permissions().mode() & 0o777, 0o600); + let rotated: toml::Value = toml::from_str(&fs::read_to_string(&imported).unwrap()).unwrap(); + assert_eq!(rotated["provider_api_key"].as_str(), Some("rotated")); + } + + 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/support/publication_github.rs b/tests/support/publication_github.rs new file mode 100644 index 00000000..b65c25d9 --- /dev/null +++ b/tests/support/publication_github.rs @@ -0,0 +1,21 @@ +// Owner-local tests use a loopback HTTP client while retaining production +// request, permission, rate-limit and recovery behavior. +use super::*; +impl GitHubClient { + pub fn publication_test_client( + client: Octocrab, + identity: GitHubIdentity, + config: GitHubConfig, + ) -> Self { + let client = Arc::new(client); + Self { + app: Arc::clone(&client), + installation: client, + config, + identity, + projects_v2_enabled: false, + rate_limits: Arc::new(RateLimits::default()), + background: false, + } + } +}