From 55cefb213776d9c5e68c4e72732a15e9023918b6 Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sat, 28 Nov 2026 14:34:05 +0800 Subject: [PATCH 1/4] =?UTF-8?q?chore(baseline):=20=E4=BF=AE=E5=A4=8D?= =?UTF-8?q?=E5=BC=80=E5=8F=91=E5=AF=BC=E8=88=AA=E5=B9=B6=E9=80=80=E5=BD=B9?= =?UTF-8?q?=E6=97=A9=E6=9C=9F=E4=BB=BB=E5=8A=A1=E5=8C=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 通过现行 SVC CLI 恢复受管配置和导航 - 保留已关闭任务的 Git 历史,校正源码验证与 Tunnel 入口 --- .gitignore | 5 + AGENTS.md | 23 ++- README.md | 6 +- docs/index.md | 6 +- docs/user-manual/tunnel.md | 9 +- svc.json | 3 +- tasks/code-docs-cleanup.md | 37 ----- tasks/poc-homebrew-setup.md | 58 -------- tasks/rust-mvp-implementation.md | 232 ------------------------------- 9 files changed, 36 insertions(+), 343 deletions(-) delete mode 100644 tasks/code-docs-cleanup.md delete mode 100644 tasks/poc-homebrew-setup.md delete mode 100644 tasks/rust-mvp-implementation.md diff --git a/.gitignore b/.gitignore index fbc18486..cac6f90b 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,8 @@ .DS_Store .pi/ .wrangler/ + +# svc:begin local-config sha256=0cb2591848c4e5675766aa516f16dfb9981fc52e1dcbadd8cec89b6982db927d +svc.local.json +AGENTS.local.md +# svc:end local-config diff --git a/AGENTS.md b/AGENTS.md index 90f9fa18..6d160ba3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,12 +4,6 @@ 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; do not modify user-scope Agent instructions. - -## SVC - -Use the installed `svc` CLI when SVC guidance or project integration is relevant. Discover the current interface through `svc --help` and `svc --help`; `svc lookup` reads the SVC Corpus, not CLI help. Treat unmarked project instructions and documentation as Consumer-owned. - - ## Knowledge Owners - Product purpose, promises, workflows, and scope: @@ -53,9 +47,13 @@ Use the installed `svc` CLI when SVC guidance or project integration is relevant ## Repository Workflow +- After fetching, use the remote default branch for mainline work. For work + based on a pending PR, verify its head and base and use a dedicated worktree. +- Use the binary built from that checkout for source verification. The + installed `braid` can be from a different release. - The clean Rust runtime replaces the obsolete Python prototype; do not carry old turn-mirror abstractions, schemas, or compatibility aliases into Rust. -- Runtime: Rust 1.93+ for the first implementation; commit `Cargo.lock`. +- Use the toolchain pinned by `rust-toolchain.toml` and commit `Cargo.lock`. - Prefer readable deep modules aligned with the Product TDD owners. Do not pass `serde_json::Value` across internal boundaries when a typed enum/struct owns the contract. @@ -69,3 +67,14 @@ Use the installed `svc` CLI when SVC guidance or project integration is relevant - 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. + + +## SVC + +Use `svc --help` or `svc --help`. + +- `svc status`: inspect project state +- `svc dev`: manage declared development targets + +If `AGENTS.local.md` exists, read it after this file. It is ignored local guidance; shared rules belong here. + diff --git a/README.md b/README.md index c1b83fe2..ed2c8218 100644 --- a/README.md +++ b/README.md @@ -74,6 +74,7 @@ braid setup owner/repository --provider pi --model deepseek-chat --api-key-envir Follow the printed GitHub App installation link, then check the instance and start the local runtime: ```sh +braid migrate apply --instance owner braid doctor --instance owner braid serve --instance owner --tunnel ``` @@ -106,5 +107,8 @@ A repository maintainer can activate Braid by posting a visible, trusted `@braid | [Deployment & observability](docs/40-deployment/README.md) | Configuration, migrations, diagnostics, and operations. | | [Real end-to-end acceptance](docs/10-prd/acceptance.md) | How the complete GitHub-to-agent workflow is verified. | -For source development, Braid is a single Rust package that produces a portable `braid` executable. Build with `cargo build --locked`; the repository's product and technical contracts live in [`docs/`](docs/10-prd/README.md). See the [MIT license](LICENSE). +For source development, run `cargo build --locked` from the checkout and invoke +`target/debug/braid` to exercise that build. For the documentation map and +repository workflow, see the [documentation index](docs/index.md) and +[`AGENTS.md`](AGENTS.md). See the [MIT license](LICENSE). diff --git a/docs/index.md b/docs/index.md index f00c6628..d782ec1b 100644 --- a/docs/index.md +++ b/docs/index.md @@ -1,9 +1,9 @@ # Braid Documentation - -## SVC Corpus + +## SVC CLI -Use `svc lookup` when packaged Sustainable Vibe Coding Corpus guidance is relevant, and discover its browse/search/read grammar through `svc lookup --help`. Project documentation outside this marked block remains Consumer-owned. +Use `svc --help` and the installed SVC Skills for framework guidance. Project documentation outside this marked block remains Consumer-owned. Read owners progressively from the problem being changed: diff --git a/docs/user-manual/tunnel.md b/docs/user-manual/tunnel.md index 33c41d78..e3324b56 100644 --- a/docs/user-manual/tunnel.md +++ b/docs/user-manual/tunnel.md @@ -23,7 +23,8 @@ Braid performs these steps automatically: 3. Parses the tunnel output to obtain a public HTTPS URL such as `https://.trycloudflare.com`. 4. Appends `/webhook` to form the public webhook endpoint. -5. Sends a signed `ping` probe to that endpoint to confirm GitHub can reach it. +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. @@ -57,7 +58,9 @@ maps instance keys to their home directories, so `--instance` (or ## Troubleshooting -- If the tunnel does not converge within 45 seconds, Braid retries up to 3 - tunnel candidates and then fails with `QuickTunnel` error details in the logs. +- 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. - `braid tunnel probe --instance --url ` can verify a specific URL manually, but normal `serve --tunnel` does this automatically. diff --git a/svc.json b/svc.json index 911cea9e..9980368a 100644 --- a/svc.json +++ b/svc.json @@ -1,4 +1,3 @@ { - "schema_version": 3, - "corpus_version": "12.0.0" + "schema_version": 5 } diff --git a/tasks/code-docs-cleanup.md b/tasks/code-docs-cleanup.md deleted file mode 100644 index 04c1459a..00000000 --- a/tasks/code-docs-cleanup.md +++ /dev/null @@ -1,37 +0,0 @@ -# [Pivoted to tasks/setup-mvp.md] Code and Documentation Cleanup - -- **Goal**: Get the Rust codebase into a maintainable, pre-release shape before any production artifact ships. -- **Scope**: - 1. **Migrations**: Merge the 11 pre-release migrations into a single `0001_initial.sql` migration. No production databases exist yet, so a clean slate is acceptable. - 2. **Repository layout**: Split oversized `src/` files (especially `store.rs`, `runtime.rs`, `context.rs`, `github.rs`, `provider.rs`, `writer.rs`, `cli.rs`) into focused modules aligned with the Product TDD owners. Keep readable deep modules; avoid splitting purely by line count. - 3. **Dependency / duplication audit**: Remove dependencies that are no longer used. Identify places where Braid re-implements a mature crate's happy path (e.g., GitHub App auth, JWT, GraphQL pagination, worktree handling) and replace them where it reduces code without losing the TDD contract. - 4. **Docs**: Trim stale examples, update README/setup docs if the CLI surface changes, and ensure doc comments on public items. - 5. **Verification**: `cargo fmt/check/clippy/test` must pass after each cleanup step. The packaged release must still install via Homebrew and `braid setup --no-browser` must still produce valid output. - -## Done - -- [x] Migrations collapsed to one init migration. -- [x] Unused dependencies removed from `Cargo.toml`/`Cargo.lock`. -- [x] `provider.rs` refactored into a module tree (`provider/mod.rs`, `provider/codex.rs`, `provider/pi.rs`, `provider/util.rs`) with clean public API. -- [ ] `store.rs` refactored into a module tree (deferred: module cohesion requires keeping `StoreActor`/`Command`/`actor_loop` in `mod.rs`; will extract pure helpers later if needed). -- [x] `runtime.rs` refactored into a module tree (`runtime/mod.rs`, `runtime/ingress.rs`, `runtime/outbox.rs`, `runtime/reconcile.rs`, `runtime/scheduler.rs`, `runtime/issue_agent.rs`, `runtime/pr_agent.rs`, `runtime/provider.rs`, `runtime/tunnel.rs`). -- [ ] `context.rs` refactored into a module tree or typed GraphQL client (deferred: requires AST-aware extraction; manual sed is too risky). -- [x] `github.rs` reviewed and split if needed (migrated to `octocrab`; kept as single module due to tight identity/REST coupling). -- [x] `cli.rs` refactored into a module tree (`cli/mod.rs`, `cli/config.rs`, `cli/profile.rs`, `cli/context_cmd.rs`, `cli/gh.rs`, `cli/gh_cmd.rs`, `cli/migrate.rs`, `cli/doctor_cmd.rs`, `cli/status.rs`, `cli/telemetry_cmd.rs`, `cli/helpers.rs`). -- [x] `writer.rs` refactored into a module tree (`writer/mod.rs`, `writer/prepare.rs`, `writer/ensure.rs`, `writer/comment.rs`, `writer/helpers.rs`). -- [x] Replace worktree shell commands with `git2`. -- [x] Replace hand-written GitHub App client with `octocrab`. -- [ ] Replace manual GraphQL query building with typed client (deferred: `octocrab` raw `/graphql` is sufficient for current query surface). -- [ ] Replace JSON-RPC-ish provider loop with a typed crate (deferred: split into modules; typed crate not yet adopted). -- [x] PR #94 review: CI formatting failure fixed. -- [x] PR #94 review: docs reorganized — `docs/setup.md` → `docs/user-manual/setup.md`, `glossary.md` → `docs/10-prd/glossary.md`, split `docs/10-prd/README.md` into focused capability files, clarified `acceptance.md` role, added boundary notes to TDD `context.md`/`github.md`. -- [x] PR #94 body updated: schema references changed from v11 to v1. -- [x] Clean release rebuilt and Homebrew formula updated to v0.2.2. - -## Verification - -- `cargo fmt/check/clippy/test` -- `brew reinstall xiaoland/braid/braid && braid --version` -- `braid setup xiaoland/braid-poc-test --no-browser` produces the HTML form and manifest JSON - -Delete this packet when the cleanup branch is merged into the release line. diff --git a/tasks/poc-homebrew-setup.md b/tasks/poc-homebrew-setup.md deleted file mode 100644 index 12a5e8ac..00000000 --- a/tasks/poc-homebrew-setup.md +++ /dev/null @@ -1,58 +0,0 @@ -# Homebrew + Bootstrap PoC - -> **Status: pivoted.** The Homebrew tap, packaged release, and `braid setup` skeleton are in place. The active task packet is now `tasks/code-docs-cleanup.md`. - -- **Goal**: Make Braid installable via Homebrew and bootstrappable through a single `braid setup` / `braid bootstrap` flow, so a user can go from zero to a working Braid Issue Agent / PR Agent on their own repository with minimal operator steps. -- **Scope for this PoC**: - 1. Homebrew distribution: a public tap (`xiaoland/homebrew-braid`) with a macOS arm64 formula. - 2. A `braid setup` command that: - - Detects or initiates `gh auth login`. - - Generates a GitHub App Manifest for `braid-of-` and opens the browser for one-click App creation. - - Starts a temporary local HTTP callback server, captures the manifest `code`, and exchanges it for App credentials. - - Persists the App ID, PEM private key, webhook secret, and generated `braid.toml` in `~/.braid/`. - - Creates/updates the repository webhook and verifies a signed `ping`. - - Starts a persistent public tunnel (localtunnel) for webhook delivery. - - Generates default issue and PR profiles. - - Runs `braid doctor` and reports remaining gaps. -- **Guardrails**: Do not place secrets in the repo or conversation. Use env vars and files outside the repo. Keep the provider seam agnostic; the bootstrap can default to Pi if Codex credentials are not present, but must not hardcode a single provider. Use public boundaries and the `gh` CLI wherever possible. Keep system prompts provider-agnostic. -- **Verification**: A clean macOS machine (or fresh VM) can `brew install xiaoland/braid/braid`, run `braid setup --repository owner/repo`, click once in the browser, and end with a passing `braid doctor` and a repository webhook that receives a signed GitHub ping. - -## Linear Steps - -### Step 1 — Homebrew tap and release artifact -- [x] Create the public tap repository `xiaoland/homebrew-braid`. -- [x] Create a GitHub Release `v0.1.0` on `xiaoland/braid` with the packaged macOS arm64 tarball. -- [x] Write `Formula/braid.rb` with the release URL and checksum. -- [x] Verify `brew install xiaoland/braid/braid` works and `braid --version` prints the expected version. - -### Step 2 — `braid setup` skeleton -- [x] Add a new `Setup` command to the CLI (`src/cli.rs`). -- [x] Add an interactive module (`src/setup.rs`) that: - - Resolves the target owner (user or org) and repository. - - Checks `gh auth status` and aborts with instructions if not authenticated. - - Generates a webhook secret (32 bytes hex). - - Builds the GitHub App Manifest JSON with required permissions/events. - - Encodes the manifest and opens `https://github.com/settings/apps/new?manifest=...` (or org variant). - - Starts an ephemeral Axum/HTTP server on a free localhost port and waits for the redirect. - - Exchanges the `code` via `POST /app-manifests/{code}/conversions`. - - Writes the PEM to `~/.braid/braid-of-.pem`, the webhook secret to `~/.braid/braid-of-.webhook_secret`, and the TOML config to `~/.braid/braid.toml`. - - Provides `--no-browser` guidance with the manifest URL, JSON, webhook secret, and install URL. - -### Step 3 — Tunnel and webhook verification -- [ ] In setup, start a localtunnel (or Cloudflare Quick Tunnel) and obtain the public URL. -- [ ] Create the repository webhook via the GitHub API with the public URL + `/webhook` and the secret. -- [ ] Trigger or await a `ping` delivery, verify HMAC signature, and confirm Braid health is ready. -- **PoC compromise**: setup currently prints the install URL, expects the user to install the App manually, and leaves `braid serve --tunnel` to create the public webhook. Full automation is deferred. - -### Step 4 — Profiles and doctor -- [x] Generate default `issue-pi` / `pr-pi` profiles (or Codex if configured) in the generated TOML. -- [ ] Run `braid doctor` equivalent diagnostics inline and print a concise report. -- [x] Print the final `braid serve --config ~/.braid/braid.toml` command. - -### Step 5 — Documentation -- [x] Update `README.md` with `brew install xiaoland/braid/braid` and `braid setup --repository owner/repo`. -- [x] Add a short `docs/setup.md` describing the one-time bootstrap flow. - -## Done / Closed - -Delete this packet after a user other than the author runs the complete flow successfully on a fresh machine. diff --git a/tasks/rust-mvp-implementation.md b/tasks/rust-mvp-implementation.md deleted file mode 100644 index 6af25700..00000000 --- a/tasks/rust-mvp-implementation.md +++ /dev/null @@ -1,232 +0,0 @@ -# Rust MVP Implementation - -> **Status: pivoted.** The acceptance campaign against real GitHub + Pi was interrupted by external GitHub API/network flakiness. The core journeys repeatedly converged, so the team decided to declare the acceptance gate passed for PR #94 purposes and move on to the PoC goal: Homebrew distribution + one-command bootstrap. The active task packet is now `tasks/poc-homebrew-setup.md`. - -- **Goal**: Bring PR #94 — *Rebuild Braid around GitHub working memory* — to a mergeable state. The Rust runtime, GitHub Context, lifecycle, PR Agent worktree, `braid gh`, migrations, packaging, and operational convergence are implemented through schema v11. Acceptance pivoted from Codex to Pi because the Codex account hit its usage limit. Pi now works as a real provider via its `bash` tool, and the core Issue Agent journeys have converged. The remaining work is to make one clean full Slice 3 run (and then Slices 4–6) against real GitHub + Pi + the packaged binary, accounting for flaky GitHub API/network behavior. -- **Objective**: Replace the withdrawn Python turn-mirror prototype with the packaged Rust MVP specified by the Product Truth, Product TDD, provider/GitHub contracts, deployment contract, and real black-box acceptance oracle. -- **Guardrails**: GitHub Context is canonical working memory; do not preserve Python mirror/thread assumptions or add compatibility aliases. Do not constrain Agent `gh`/`git` beyond GitHub/provider/Profile permissions. Treat digest/hash as an exceptional internal mechanism, not a product or domain primitive: first repair the owning identity, version, lifecycle, or authority contract at the preceding architecture layer. Do not place hashes, UUIDs, delivery IDs, provider/session/turn/item IDs, or SQLite IDs in Agent Context; unavoidable internal identifiers remain transport-local and semantically inert. No GitHub/network await inside SQLite transactions. No internal fake/unit/component test suite; public diagnostic and campaign helpers live under `scripts/tests/`. Sampled telemetry intentionally preserves full evidence and is treated as sensitive. Keep this as the only active task packet and delete it after the three clean acceptance campaigns and durable release evidence close the task. -- **Verification**: `cargo fmt --check`, `cargo check --locked --all-targets`, and strict Clippy diagnose every slice. Each slice also has its public-boundary gate below. Product acceptance requires the clean packaged macOS arm64 artifact to pass every journey in `docs/10-prd/acceptance.md` three consecutive times without corrective operator action; internal state/logs never substitute. Linux x86_64 packaging is the immediate follow-on gate, not a blocker for the first macOS MVP release. -- **Handoff Baseline (2026-08-19)**: The working tree is clean at commit `8504cd6` (`feat(runtime): converge PR lifecycle and operations`), plus one task-packet commit on `feat/docs-namespace-migration`. `cargo fmt --check`, `cargo check --locked --all-targets`, and `cargo clippy --locked --all-targets` all pass. The previous agent's in-progress uncertain-write test harness (modified `scripts/tests/60_operations.sh`, `scripts/tests/README.md`, `src/github.rs`, and new `scripts/tests/connect_delay_proxy.py`) was moved to a WIP branch `handoff/slice7-wip` so the baseline branch remains known-good. The questionable `GitHubError::Response` → `is_unavailable()` change was reverted with that WIP; `Response` means a deterministic response-shape error and must not be treated as an uncertain transport outcome. -- **Realignment**: The active branch is `feat/rust-working-memory`, tracking PR #94. The old PR #2 was closed as superseded. The uncertain-write proxy harnesses and `60_operations` fragments stay on local `handoff/slice7-wip` and are not blocking baseline. Slice 7/acceptance remains the remaining gate for the PR. -- **Current Truth**: Product, Context, lifecycle, provider, GitHub, SQLite/OTel/deployment, and acceptance designs are closed in their durable owners. Slices 0–5 are implemented and previously had bounded real public-boundary evidence with Codex. Schema v11 carries Issue and PR lifecycle uniformly. With Pi, the provider seam works and the Issue Agent can use `gh`/`braid gh` through Pi's `bash` tool to publish real Agent comments. Slice 6 convergence implementations are present but some external-fault fixtures remain unproven. -- **Current Slice Evidence**: The expanded Slice 4 campaign previously passed against closed Issue #28 with Codex. Slice 3 evidence with Pi is accumulating below. -- **Latest Evidence**: With Pi, Braid accepts trusted `@braid` mentions, applies `eyes`/`rocket`/`+1`, and the Agent publishes attributed comments via `braid gh`. Ordinary debounce and count-threshold turns have converged. Recent failures are external GitHub API/network flakiness and the provider-disconnect fixture. -- **Slice 5 Evidence**: The final schema-v11 `scripts/tests/50_issue_to_pr.sh` campaign previously passed with Codex. It has not been rerun with Pi yet. -- **Slice 6 Evidence**: `scripts/tests/60_operations.sh` previously passed with Codex. It has not been rerun with Pi yet. -- **Environment Setup (2026-08-24)**: - - GitHub App `braid-by-xiaoland`: App ID `4558000`, installation `153412294`, permissions `contents=write`, `issues=write`, `metadata=read`, `pull_requests=write`; required webhook events enabled. - - App private key at `/Users/lanzhijiang/.braid/braid-by-xiaoland.pem` (mode `0600`). - - Webhook secret exported as `BRAID_WEBHOOK_SECRET`. - - Pi config `/Users/lanzhijiang/.braid/braid-pi.toml` uses `[provider.pi]` with `deepseek-chat`. - - `config check`, `doctor` (except OTLP), `github probe`, `migrate apply` pass for the Pi config. - - Packaged release artifact built and extracted: `/Users/lanzhijiang/.braid/install/braid-v0.1.0-aarch64-apple-darwin/bin/braid`. - - Fixed stale schema assertions in `scripts/tests/30_issue_agent.sh` and `scripts/tests/40_context_lifecycle.sh` (10 → 11). - - Cleaned up all prior Slice 2/3 fixture issues and stale webhooks. -- **Tunnel workaround**: Cloudflare Quick Tunnel public routes intermittently return Cloudflare error 1033. To unblock acceptance, installed `localtunnel` and patched scripts 20/30/40/50 to accept `BRAID_TEST_PUBLIC_WEBHOOK_URL` with any `https://*/webhook` host. A local HMAC-signing relay restores the `X-Hub-Signature-256` header because localtunnel strips it. A fresh localtunnel is started per run. -- **Campaign Progress**: - - Slice 0 clean-install ✅ passed. - - Slice 2 transport/scheduler ✅ passed via localtunnel repository-webhook mode. - - Slice 3 Issue Agent (Pi): **core journeys converge**. The Agent reads the Issue, sleeps, publishes an attributed comment via `braid gh comment create`, and Braid applies `eyes`/`rocket`/`+1` correctly. Ordinary debounce and count-threshold also converge. Recent runs failed on external GitHub API flakiness (`EOF`, `TLS handshake timeout`) and the provider-disconnect fixture (killing the Pi shell wrapper leaves the Node child alive). - - Slices 4–6 not yet rerun with Pi. -- **Provider pivot findings**: - - Localtunnel strips GitHub's `X-Hub-Signature-256`; a local HMAC-signing relay restores signed webhook delivery to Braid. - - Pi `--mode rpc` has a working `bash` tool; the Agent can call `gh` and `braid gh` directly. - - Pi `--mode rpc` with `--no-session` does not return `sessionFile`; `--session-dir /.braid/pi-sessions` fixes provider session materialization. - - Pi does not emit a reliable `turn_end` per Braid turn; it emits `turn_end` after each assistant response step and `agent_settled` only when the session settles. Braid now treats `agent_settled` or `message_end` with `stopReason == "stop"` as terminal. - - `github_actor_node_id` must be the App actor node id (`BOT_kgDOEtKIgA`), not the human user, for human `@braid` mentions to be trusted external activations. - - `PiProvider` passes the current `braid` binary directory in `PATH` and `BRAID_CONFIG` to the Pi process so `braid gh` commands work. - - The Slice 3 script must count Agent comments by `app_actor` (the GitHub App) because `braid gh` publishes as the App. -- **Code cleanup done**: - - Renamed branch to `feat/rust-working-memory`; updated PR #94 head. - - Closed/superseded PR #2. - - Refactored provider into `AgentProvider` trait with `CodexProvider` and `PiProvider`. - - Fixed Pi environment, notification thread/turn IDs, and terminal event handling. - - Updated `scripts/tests/30_issue_agent.sh` for Pi (App actor, count-throttle delay, recursive provider kill). - - Satisfied `cargo fmt --check`, `cargo check --locked --all-targets`, and `cargo clippy --locked --all-targets`. -- **Next Step**: - 1. Fix the provider-disconnect fixture so it reliably terminates the Pi Node child process. - 2. Run one final clean Slice 3 campaign; if it passes, proceed to Slices 4–6. - 3. On three clean full runs: update `CHANGELOG.md`, tag/release the macOS arm64 artifact, open the Linux x86_64 follow-on task, delete this packet. - -## Impact Handshake - -### Address and State Diff - -- Remove `pyproject.toml`, `pdm.lock`, `.pdm-python`, `.pdm-build/`, `config.example.json`, and every Python file under `src/braid/`. -- Add one Rust package: `Cargo.toml`, committed `Cargo.lock`, `rust-toolchain.toml`, `rustfmt.toml`, `src/main.rs`, and deep modules named in `docs/20-product-tdd/README.md`. -- Add `CHANGELOG.md`, `LICENSE` if absent, versioned `config.example.toml`, embedded `migrations/`, and release/build metadata. -- Retain and update `README.md`, `AGENTS.md`, `glossary.md`, `docs/`, `docs/assets/`, and `scripts/tests/` as canonical/public surfaces. -- The CLI command remains `braid`; Python module imports, PDM commands, config JSON, and Python SQLite schema are intentionally unsupported. - -### Data and Runtime Compatibility - -- Rust DB schema begins at version 1 in a new configured database. It does not import the obsolete prototype DB. Startup detects a non-Braid-Rust or unsupported schema and refuses with an operator instruction to move it aside; it never mutates it speculatively. -- GitHub objects are reused only through canonical reread. No old mirror comment IDs or provider binding is imported; the withdrawn Braid instance must be stopped before the Rust App/webhook begins. -- The GitHub App may be reused after its permissions/subscriptions satisfy the new contract. Existing App-authored comments remain ordinary canonical comments unless explicitly recorded as Operational Status during the new generation. -- Codex 0.147/schema digests remain the first provider pin; no Python adapter code is copied. - -### Blast Radius and Rollback - -- Source/build/config/runtime change is intentionally repository-wide. Product docs and branding stay stable. -- Git history is the rollback for source. Runtime rollback to Python is not promised because it implements a withdrawn product. Before every DB migration, the stopped DB is backed up; binary rollback follows the declared schema compatibility matrix. -- External GitHub mutations begin only in the slice whose gate requires them and use the dedicated acceptance App/repository fixture. - -## Linear Slices - -The following slices are already implemented and are kept here as a reference for acceptance troubleshooting. The active work is now the PR-level gate described in **Next Step**. - -### Slice 0 — Rust, Configuration, Storage, Telemetry, and Distribution Foundation - -Implement the replacement and dependency baseline exactly as Product TDD specifies. The first binary exposes: - -- `braid --version`; -- `braid config check --config ...`; -- `braid profile inspect --config ... --profile ...`; -- `braid migrate plan|apply --config ...`; -- `braid status --config ...` for stopped/local state; -- `braid doctor --config ...` with filesystem, SQLite, Codex schema, Git/gh, Wrangler, GitHub, and OTLP checks. - -Install OTel at process composition from the first slice: metrics plus parent-based trace-ID ratio, OTLP exporter, payload log/event helper, incident override, and exporter health. Implement the dedicated blocking SQLite actor, pragmas, schema/checksum ledger, exclusive migration lease, pre-migration backup, and schema-newer refusal before domain tables. - -Produce a macOS arm64 release binary/tarball/checksum locally. Add -`scripts/tests/00_clean_install.sh` to unpack it into a temporary directory and -drive only public CLI/config/migration/doctor boundaries. - -Gate: formatting/check/Clippy pass; a clean directory with no Python/PDM/Cargo on PATH runs version/config/migration/profile/status; a local OTLP receiver observes one full-payload trace at ratio 1.0 and no orphan spans at ratio 0; upgrading a schema-0 and prior-schema fixture to the candidate schema, plus rejecting a future schema, are externally observable. - -### Slice 1 — Canonical GitHub Read and Context Projection - -Implement GitHub App JWT/installation-token HTTP, typed GraphQL page walkers, -REST supplements, canonical snapshot types, HTML-comment filtering, deterministic -Markdown projection, lifecycle tombstones, Context Revision, pressure, and -Event Reference rendering. Add public diagnostic commands: - -- `braid context issue owner/repo#N --config ...`; -- `braid context pr owner/repo#N --config ...`; -- `braid github probe --config ... --repository ...`. - -Persist only object/version/tombstone/association metadata needed for later -diffing. A complete query is read twice around the root/association graph and -retries drift; any incomplete connection is a typed unavailable result. - -Gate: `scripts/tests/10_context_projection.sh` reads real controlled Issue/PR -objects through the packaged binary and validates deterministic bytes, metadata -ordering, 1:N/N:1 association, open/closed Issue projection, HTML exclusion, -folded/deleted lifecycle, complete pagination, Context Revision stability, and -hard-budget refusal without importing Rust internals. - -### Slice 2 — Webhook, Reconciliation, Event Ledger, Reactions, and Tunnel - -Implement Axum raw-body ingress/HMAC, typed open webhook enums, durable delivery -ingest before 2xx, reconciliation, canonical diff classification, scheduler -batches/deadlines/count, Braid App reactions, write-outbox convergence, owner -lease, loopback health, Wrangler Quick Tunnel supervision, signed public probe, -and graceful webhook restoration. Provider turns remain disabled in this slice; -runnable batches are visible in status only. - -Gate: `scripts/tests/20_ingress_scheduler.sh` uses a real GitHub App/tunnel and -real comments to prove `eyes`, delivery/redelivery dedupe, older-after-newer -non-regression, 30-second quiet reset, eight-event release, trusted mention -permission/Markdown grammar, reconciliation after tunnel loss, and restart of a -pending batch. No Agent comment/turn occurs yet. - -### Slice 3 — Profiles, Assignment, Codex Sessions, and Turns - -Implement Profile parsing/materialization diagnostics, Braid System Prompt, -Codex NDJSON request/notification ownership, schema pin probe, Issue assignment -generation, `thread/start`, complete Context `thread/inject_items`, idle session, -turn start/steer/interrupt/terminal/unknown, sampled provider transcript, and -trusted-mention lifecycle reactions. Bind scheduler runnable batches to one -active Issue Agent in MVP. - -Gate: `scripts/tests/30_issue_agent.sh` uses native Agent App assignment when -that capability exists, otherwise the explicit trusted-mention activation -fallback. It observes an ordinary debounced turn without terminal reactions, -an eight-event turn, a trusted/edited mention steer with rocket/+1, an -unexpected mention terminal with confused, and provider disconnect unknown -with status. The Agent publishes its own attributed comment; Braid mirrors -nothing. The full Slice 3 row is now exercised by Issues #19 and #20 as recorded -in Current Truth. - -### Slice 4 — Context Invalidation and Work Item Lifecycle - -Implement same-surface Hard Invalidation, Cross-surface description debounce, -Dependency Dirty, stale-output fencing, fresh Codex session replacement, -unassignment debounce, sleeping/retired states, one Finalization Turn, reopen, -Operational Status desired state, and context-pressure blocking. - -Gate: the first `scripts/tests/40_context_lifecycle.sh` campaign proves idle and -provider-active Issue-description Hard Invalidation, fresh physical sessions, -stale-turn reaction fencing, and one continuation using current complete -Context. Extend the same public helper with minimize/unminimize, delete, -unassign/reassign, close/reopen/finalization, provider restart, and -context-too-large/unavailable journeys before declaring the whole slice closed. - -### Slice 5 — Braid GitHub Writes, PR Ensure, Worktree, and PR Agent - -Implement `braid gh` command families and attribution, write receipts, -correlated Agent-origin suppression, uncertain-create reconciliation, -comment-ID-keyed `pr ensure`, native association, deterministic PR Profile -selection, ActivationIntent, PR Agent Group, and one provisioned worktree for the -v1 Implementation Agent. When the chosen remote branch equals base, create the -same-tree Braid App bootstrap commit/ref before the Draft PR, without force. -Implement current multi-Issue PR Context, PR lifecycle, review/review-thread -Event References, and Cross-surface invalidation. - -Do not mediate ordinary Git or `gh`; recognize the Profile's configured stable -GitHub actor and expose unconfigured/shared-identity feedback-loop behavior -exactly as Product Truth states. - -Gate: `scripts/tests/50_issue_to_pr.sh` runs the real implementation request -twice concurrently, observes one same-tree bootstrap commit plus one Draft -PR/association/worktree/Agent, produces a real verified diff, handles review, -updates Issue design, exercises direct `gh` -under configured and unconfigured identities, closes/reopens/merges with exactly -one finalization turn, and proves no Braid turn mirror exists. - -### Slice 6 — Restart, Migration, Packaging, and Operational Convergence - -Complete process supervisors, persisted compatible session resume, active-turn -unknown, outbox recovery, App webhook repair/status, graceful/forced shutdown, -release metadata, CHANGELOG workflow, artifact checksums, and upgrade/compatible -rollback. Add optional Collector tail-sampling example without making it a -runtime dependency. - -Gate: `scripts/tests/60_operations.sh` runs clean install, pending/active/unknown -restart, tunnel death, uncertain write, DB upgrade/backup/schema-newer refusal, -declared compatible rollback, 10% trace-consistent sampling, incident 100%, and -artifact checksum verification using only public/operator boundaries. - -### Slice 7 — Full Acceptance and Release Closure - -Run every journey in `docs/10-prd/acceptance.md` on a fresh real fixture three -consecutive times. Preserve the public GitHub evidence, artifact/config/schema/ -provider versions, OTLP evidence, process/worktree snapshots, and explicit Human -verdicts. Fix failures in the owning slice, then restart the three-run sequence; -do not weaken the oracle around observed behavior. - -After three clean runs: update Product Truth only for proven behavior, finalize -`CHANGELOG.md`, tag/release the macOS arm64 artifact, open the Linux x86_64 -follow-on task, delete this packet, and leave no Python/PDM residue. - -## Pi Provider Pivot - -- **Reason**: Codex account hit its usage limit on 2026-08-23. Real-provider acceptance is blocked until credits are added or the weekly limit resets on 2026-08-27. The user has a working `pi` CLI with a DeepSeek API key and wants to accept against that instead. -- **Implementation Done**: - 1. Introduced `AgentProvider` trait and refactored `CodexClient` into `CodexProvider`. - 2. Added `provider.pi` configuration (executable, provider name, model, API key environment, thinking level, optional home). - 3. Implemented `PiProvider` that spawns `pi --mode rpc`, drives `new_session`/`prompt`/`steer`/`abort`/`get_state`, and maps `turn_start`/`turn_end`/`agent_settled` events to Braid notifications. - 4. Fixed an async runtime panic in `PiProvider::subscribe()` by moving the `broadcast::Sender` out of the async-locked `PiState`. - 5. Fixed `PiProvider` session persistence: switched from `--no-session` to `--session-dir /.braid/pi-sessions` so `get_state` returns `sessionFile` as Braid expects. - 6. Updated `config check`, `doctor`, runtime health, and CLI `serve` to use `Box`. - 7. Built packaged binary and updated Pi acceptance config `/Users/lanzhijiang/.braid/braid-pi.toml` with `[provider.pi]` and `deepseek-chat` model. -- **Acceptance Status with Pi**: - - Slice 0 clean-install ✅ passed. - - Slice 2 transport/scheduler ✅ passed via localtunnel repository-webhook mode. - - Slice 3 Issue Agent: **partial**. Braid now receives signed webhooks (via a localtunnel + HMAC-signing relay workaround because localtunnel strips GitHub's `X-Hub-Signature-256`), acknowledges the trusted mention with `eyes`, accepts the turn with `rocket`, and starts the Issue Agent session. However, the Pi provider does not have the GitHub tool interface that Braid expects: it cannot publish Agent comments or apply reactions. The `pi --mode rpc` CLI streams reasoning events but does not expose the App-server tool surface that `CodexProvider` uses, so the agent turn never produces the required GitHub side effects. The Slice 3 script times out waiting for the Agent comment/rocket. -- **Blocker**: Pi in RPC mode is a chat/reasoning provider, not an App-server with GitHub tools. Braid's runtime currently relies on the provider to perform all GitHub side effects (comments, reactions, worktree operations). Bridging this would require either (a) giving Pi a custom skill/tool interface that talks back to Braid, or (b) restructuring Braid so the runtime applies provider-intended writes itself. Both are out of scope for PR #94 readiness. -- **Decision Needed**: - - Option A: Wait for the Codex usage limit to reset (2026-08-27) and run acceptance against Codex. - - Option B: Purchase/add Codex credits now. - - Option C: Invest in a Pi skill/tool bridge to make Pi a full Braid Agent provider. -- **Current Recommendation**: Treat PR #94 as implemented with both provider seams present and verified up to the point where a real provider turn is accepted. Full three-run acceptance still requires a provider with GitHub tool capability; Pi cannot substitute without additional integration work. From 7ad781593254d9cd4cc3a63e58b5306268c774f6 Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sat, 28 Nov 2026 14:34:05 +0800 Subject: [PATCH 2/4] =?UTF-8?q?fix(baseline):=20=E6=A0=A1=E6=AD=A3?= =?UTF-8?q?=E4=B8=BB=E7=BA=BF=E5=AE=89=E8=A3=85=E5=85=A5=E5=8F=A3=E4=B8=8E?= =?UTF-8?q?=E8=BF=81=E7=A7=BB=E8=AF=8A=E6=96=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 移除无法运行的 setup HTTP adapter 选项,先校验受支持的 runtime - 同步安装、调度、部署和验收说明,以数据库迁移账本检验升级 --- docs/10-prd/README.md | 6 +----- docs/10-prd/acceptance.md | 5 ----- docs/10-prd/scope.md | 4 ++-- docs/40-deployment/README.md | 28 +++++++++++++-------------- docs/user-manual/setup.md | 28 ++++++++++++++++----------- scripts/tests/00_clean_install.sh | 18 ++++++----------- scripts/tests/README.md | 13 ++++++------- src/cli/mod.rs | 6 ++---- src/config.rs | 5 ++--- src/runtime/mod.rs | 2 +- src/setup.rs | 18 ++++------------- src/setup/discovery.rs | 32 ++++--------------------------- 12 files changed, 58 insertions(+), 107 deletions(-) diff --git a/docs/10-prd/README.md b/docs/10-prd/README.md index 3cb55926..4b7118b9 100644 --- a/docs/10-prd/README.md +++ b/docs/10-prd/README.md @@ -5,13 +5,9 @@ local Coding Agent. GitHub holds the current collaboration state; provider sessions are replaceable execution contexts built from that state. The project vocabulary is owned by [`glossary.md`](glossary.md). -This document owns product purpose, promises, workflows, and exclusions. The -cross-unit realization is owned by [`../20-product-tdd/`](../20-product-tdd/), -and only the real campaign in [`acceptance.md`](acceptance.md) accepts them. - This directory owns product purpose, promises, workflows, and exclusions. The cross-unit realization is owned by [`../20-product-tdd/`](../20-product-tdd/), -and only the real campaign in [`acceptance.md`](acceptance.md) accepts them. +and [`acceptance.md`](acceptance.md) defines the product acceptance campaign. - [`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 d43e4770..4d738323 100644 --- a/docs/10-prd/acceptance.md +++ b/docs/10-prd/acceptance.md @@ -1,10 +1,5 @@ # End-to-End Acceptance -This document is the PRD acceptance oracle. It defines what "done" means for -Braid: 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. - 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 diff --git a/docs/10-prd/scope.md b/docs/10-prd/scope.md index 897ac168..a40fce59 100644 --- a/docs/10-prd/scope.md +++ b/docs/10-prd/scope.md @@ -1,11 +1,11 @@ ## Scope and Exclusions -The MVP includes Codex app-server, macOS arm64, real GitHub, SQLite, a free +The MVP includes Codex and Pi runtime adapters, 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 Pi/Claude adapters, hosted ingress, deterministic +The MVP does not promise a Claude adapter, 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. diff --git a/docs/40-deployment/README.md b/docs/40-deployment/README.md index 3c355b62..bdaca563 100644 --- a/docs/40-deployment/README.md +++ b/docs/40-deployment/README.md @@ -11,7 +11,7 @@ It runs without Python, PDM, Cargo, or a source checkout. Linux x86_64 is the next target. Runtime prerequisites remain explicit: - Git and `gh` for Agent workflows; -- pinned Codex executable and authenticated provider home; +- the configured Codex or Pi executable and its credentials; - 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. @@ -40,8 +40,9 @@ names. The main sections are: - log format and bounded health/status settings. `braid config check` prints the effective non-secret declaration and validates -its static invariants. `braid doctor` runs filesystem, SQLite, GitHub, Codex -schema, Git/gh, OTLP, and Wrangler precondition probes. Profiles expose +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 their effective mapped provider settings through `braid profile inspect`. ## Filesystem Layout @@ -109,18 +110,15 @@ retained span preserved all five controlled full-payload attributes. ## Startup and Supervision -Startup is ordered: - -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. +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. + +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. The provider adapter reconnects and resumes compatible sessions where the provider contract makes that safe. Any other supervised worker exit makes diff --git a/docs/user-manual/setup.md b/docs/user-manual/setup.md index f9a3a742..419d489d 100644 --- a/docs/user-manual/setup.md +++ b/docs/user-manual/setup.md @@ -17,9 +17,11 @@ 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*. + setup time). An existing user-level provider secret also works. ## Bootstrap @@ -41,6 +43,8 @@ Options: the user-level secrets file, so the env var is only needed at setup time. - `--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. `braid setup` performs these steps: @@ -48,15 +52,15 @@ Options: 2. Resolves the Braid user home (`~/.braid` by default) and instance key (owner by default). 3. Generates a random webhook secret. -4. Reads the provider API key from the environment variable named by - `--api-key-environment`. -5. Builds a GitHub App Manifest with the permissions Braid needs +4. Builds a GitHub App Manifest with the permissions Braid needs (`contents:write`, `issues:write`, `pull_requests:write`, `metadata:read`). -6. Starts a temporary local HTTP callback server. -7. Opens a browser to `github.com/settings/apps/new` (or the organization +5. Starts a temporary local HTTP callback server. +6. Opens a browser to `github.com/settings/apps/new` (or the organization variant) with the manifest pre-filled. -8. Captures the browser redirect and exchanges the code for the App's +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. 9. Writes files under `~/.braid`: - `registry.toml` — the instance registry (SSoT for `BRAID_INSTANCE` resolution). @@ -75,9 +79,10 @@ environment variable. `BRAID_WEBHOOK_SECRET` is no longer required. After setup: 1. Install the App on your repository by visiting the printed install URL. -2. Run diagnostics: +2. Initialize the instance database and run diagnostics. ```shell + braid migrate apply --instance braid doctor --instance ``` @@ -95,9 +100,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 wakes the Issue Agent -(after the Quiet Window). Braid acknowledges the mention with an `eyes` -reaction. +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. Native Issue assignment is a GitHub-side *Agent App* provisioning (the same capability that makes Copilot assignable), not a permission an ordinary diff --git a/scripts/tests/00_clean_install.sh b/scripts/tests/00_clean_install.sh index e9ac2380..c388c9b5 100755 --- a/scripts/tests/00_clean_install.sh +++ b/scripts/tests/00_clean_install.sh @@ -25,7 +25,7 @@ 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; no GitHub API call is made in Slice 0' > "$private_key" +printf '%s\n' 'diagnostic placeholder for the intentionally unready instance' > "$private_key" touch "$secrets_file" write_config() { @@ -178,30 +178,24 @@ 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" -v1_schema=$(run_clean "$braid" status --config "$v1_config" --json | /usr/bin/sed -n 's/.*"config_schema": \([0-9][0-9]*\).*/\1/p') -test "$v1_schema" = "2" +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$' -test "$(/usr/bin/sqlite3 "$v1" "SELECT count(*) FROM issue_context_sources;")" = "0" -if /usr/bin/sqlite3 "$v1" "SELECT issue_content_digest FROM associations LIMIT 1;" \ - >"$temporary_root/removed-column.out" 2>&1; then - echo "schema 11 retained the obsolete association digest column" >&2 - exit 1 -fi +/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 (12,"future","0000000000000000000000000000000000000000000000000000000000000000","future");' +/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 12 is newer' "$temporary_root/newer.out" +/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);' @@ -239,4 +233,4 @@ else exit 1 fi -echo "clean-install Slice 0 diagnostics passed" +echo "clean-install diagnostics passed" diff --git a/scripts/tests/README.md b/scripts/tests/README.md index a6adbfcc..ec572916 100644 --- a/scripts/tests/README.md +++ b/scripts/tests/README.md @@ -11,13 +11,12 @@ 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 Rust foundation gate. It unpacks the release -artifact, scrubs Python/PDM/Cargo from the binary's `PATH`, exercises only the -public CLI, verifies schema 0→1, schema 1→1 with a no-op re-apply, and -schema-newer refusal, and uses the adjacent -bounded OTLP/HTTP capture helper to observe sampling. Its direct SQLite write is -limited to constructing declared migration-compatibility fixtures; it does not -inject product events or count as workflow acceptance. +`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 diff --git a/src/cli/mod.rs b/src/cli/mod.rs index 396a61a6..f5e1a8bd 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -277,7 +277,7 @@ struct GhPrEnsure { pub(crate) struct SetupArguments { #[arg(value_name = "OWNER/REPOSITORY")] pub(crate) repository: String, - #[arg(long, value_name = "pi|codex", default_value = "pi")] + #[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, @@ -287,10 +287,8 @@ pub(crate) struct SetupArguments { 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", conflicts_with = "runtime_api_url")] + #[arg(long, value_name = "PATH")] pub(crate) runtime_executable: Option, - #[arg(long, value_name = "URL", conflicts_with = "runtime_executable")] - pub(crate) runtime_api_url: Option, #[arg( long, help = "Skip opening a browser; print manifest values and manual instructions instead" diff --git a/src/config.rs b/src/config.rs index e97bbc92..d5164d04 100644 --- a/src/config.rs +++ b/src/config.rs @@ -134,9 +134,9 @@ pub struct RuntimeEntry { pub adapter_type: String, /// Contract version checked at setup and serve time. pub version: String, - /// Adapter-defined connectivity. Examples: local executable path, HTTP - /// runtime API URL, runtime home directory. + /// Local adapter executable. pub executable: PathBuf, + /// Optional runtime API URL in the configuration format. #[serde(default)] pub api_url: Option, #[serde(default)] @@ -418,7 +418,6 @@ impl Config { Ok(config) } - #[allow(dead_code)] pub fn instance_key(&self) -> &str { &self.instance.key } diff --git a/src/runtime/mod.rs b/src/runtime/mod.rs index 232e8eaa..a419feb4 100644 --- a/src/runtime/mod.rs +++ b/src/runtime/mod.rs @@ -82,7 +82,7 @@ pub async fn serve(config: Config, quick_tunnel: bool, provider_enabled: bool) - .get("issues") .is_some_and(|permission| permission == "write" || permission == "admin") { - bail!("Slice 2 requires GitHub App Issues: write for Braid-owned reactions"); + bail!("GitHub App requires Issues: write for Braid-owned reactions"); } let secret = config .webhook_secret() diff --git a/src/setup.rs b/src/setup.rs index 0c51d272..d6d61624 100644 --- a/src/setup.rs +++ b/src/setup.rs @@ -33,14 +33,11 @@ use crate::config::{ use crate::config::{LlmAllowance, LlmModel, LlmProvider}; use crate::home::{InstanceEntry, UserHome, allocate_server_ports, validate_instance_key}; -#[allow(dead_code)] #[derive(Debug, Deserialize)] struct AppConversion { id: u64, slug: String, - name: String, pem: String, - webhook_secret: String, html_url: String, } @@ -223,7 +220,7 @@ pub async fn run(arguments: SetupArguments) -> Result<()> { println!("Wrote provider secret to: {}", provider_secret_path.display()); println!("\nNext, install the App on {}:\n{}\n", arguments.repository, install_url(&app.slug)); println!( - "Then run:\n braid doctor --instance {instance_key}\n braid serve --instance {instance_key} --tunnel\n" + "Then run:\n braid migrate apply --instance {instance_key}\n braid doctor --instance {instance_key}\n braid serve --instance {instance_key} --tunnel\n" ); println!( "Once serving, activate Braid on an issue with a visible @braid comment from a \ @@ -307,7 +304,7 @@ fn print_manual_guide( println!( "\nFinally, install the App on {repository}:\n\ https://github.com/apps/braid-of-{owner}/installations/new\n\n\ - Then run `braid doctor --instance {instance_key}` and\n\ + Run `braid migrate apply --instance {instance_key}`, `braid doctor --instance {instance_key}`, and\n\ `braid serve --instance {instance_key} --tunnel` (the tunnel step pushes\n\ the webhook URL and secret to the App).\n" ); @@ -441,9 +438,6 @@ fn write_secret(path: &Path, contents: &[u8]) -> Result<()> { } async fn select_runtime(arguments: &SetupArguments) -> Result { - if let Some(api_url) = &arguments.runtime_api_url { - return discovery::from_api_url(&arguments.provider, api_url.clone()); - } if let Some(executable) = &arguments.runtime_executable { return discovery::from_executable(&arguments.provider, executable).await; } @@ -653,11 +647,6 @@ fn build_config( Ok(config) } -/// Prepare the instance-scoped provider home so the runtime can actually -/// authenticate. Codex isolates `CODEX_HOME` per instance, so its global -/// credentials do not apply: import `~/.codex/auth.json` when present, -/// otherwise print explicit login instructions. Pi authenticates through the -/// persisted provider API key and needs no home bootstrap. /// The instance source checkout: one Git clone of the configured repository, /// shared by all Profiles as the worktree provisioning source. Clone when /// missing or empty; never overwrite a non-Git directory. @@ -684,6 +673,8 @@ fn ensure_source_checkout(source: &Path, repository: &str, git: &Path) -> Result Ok(()) } +/// Populate the instance's Codex home from `~/.codex/auth.json` or print login +/// instructions. Pi uses the configured API key. fn bootstrap_provider_home(home: &Path, adapter_type: &str) -> Result<()> { fs::create_dir_all(home) .with_context(|| format!("cannot create provider home {}", home.display()))?; @@ -735,7 +726,6 @@ mod tests { instance: None, user_home: PathBuf::from("/tmp/braid-setup-test"), runtime_executable: None, - runtime_api_url: None, no_browser: false, } } diff --git a/src/setup/discovery.rs b/src/setup/discovery.rs index 5a84954e..88906a8c 100644 --- a/src/setup/discovery.rs +++ b/src/setup/discovery.rs @@ -111,36 +111,12 @@ pub async fn from_executable(adapter_type: &str, executable: &Path) -> Result Result { - if adapter_type != "deepseek-harness" { - bail!("--runtime-api-url is only supported for deepseek-harness in this release"); - } - Ok(RuntimeEntry { - adapter_type: adapter_type.to_owned(), - version: "manual".to_owned(), - executable: PathBuf::from("n/a"), - api_url: Some(api_url), - home: None, - stable_schema_sha256: None, - experimental_schema_sha256: None, - }) -} - pub fn install_hint(adapter_type: &str) -> String { match adapter_type { - "pi" => "Install the Pi CLI:\n\ - pnpm add -g @anthropic-ai/pi-cli # preferred\n\ - # or: npm install -g @anthropic-ai/pi-cli\n\ - # Then re-run `braid setup`." - .to_owned(), - "codex" => "Install the Codex CLI:\n\ - npm install -g codex-cli\n\ - # Then re-run `braid setup`." - .to_owned(), - "deepseek-harness" => { - "Start the DeepSeek harness HTTP runtime and pass --runtime-api-url.".to_owned() + "pi" => "Install the Pi CLI from https://pi.dev/ and re-run `braid setup`.".to_owned(), + "codex" => { + "Install the Codex CLI from https://github.com/openai/codex and re-run `braid setup`." + .to_owned() } other => format!("No install instructions for adapter_type {other:?}"), } From bd67622e1697db72369fdb752465df9a7b432d89 Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sat, 28 Nov 2026 14:36:31 +0800 Subject: [PATCH 3/4] =?UTF-8?q?fix(ci):=20=E6=81=A2=E5=A4=8D=E4=B8=BB?= =?UTF-8?q?=E7=BA=BF=20macOS=20=E5=AE=89=E8=A3=85=E6=A3=80=E6=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 使用已验证的 macOS 15 arm64 runner,恢复原有检查 - 从打包 CLI 验证保留的 setup 参数和已退役入口 --- .github/workflows/ci.yml | 2 +- scripts/tests/00_clean_install.sh | 7 +++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index eeb88c54..30cff0bc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -10,7 +10,7 @@ permissions: jobs: rust: - runs-on: macos-14 + runs-on: macos-15 steps: - uses: actions/checkout@v4 - run: rustup toolchain install 1.93.0 --profile minimal --component clippy,rustfmt --target aarch64-apple-darwin diff --git a/scripts/tests/00_clean_install.sh b/scripts/tests/00_clean_install.sh index c388c9b5..542d9c9d 100755 --- a/scripts/tests/00_clean_install.sh +++ b/scripts/tests/00_clean_install.sh @@ -130,6 +130,13 @@ run_clean() { } run_clean "$braid" --version +run_clean "$braid" setup --help | /usr/bin/grep -q -- '--runtime-executable' +if run_clean "$braid" setup owner/repo --runtime-api-url https://example.invalid \ + > "$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" From f71996ee35ceae72b3c6b24c035904aa2947b489 Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sat, 28 Nov 2026 14:39:21 +0800 Subject: [PATCH 4/4] =?UTF-8?q?docs(deployment):=20=E6=A0=A1=E6=AD=A3?= =?UTF-8?q?=E5=8F=91=E5=B8=83=E5=8C=85=E4=B8=8E=E5=AE=9E=E4=BE=8B=E7=9B=AE?= =?UTF-8?q?=E5=BD=95=E8=AF=B4=E6=98=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 对齐实际的 SHA-256 发布资产和 source checkout - 将工作树具体布局指向已有技术合同 --- docs/40-deployment/README.md | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/docs/40-deployment/README.md b/docs/40-deployment/README.md index bdaca563..1c8978b9 100644 --- a/docs/40-deployment/README.md +++ b/docs/40-deployment/README.md @@ -6,9 +6,9 @@ GitHub mutation authority by itself. ## Supported Shape -The first supported artifact is a signed/checksummed macOS arm64 `braid` binary. -It runs without Python, PDM, Cargo, or a source checkout. Linux x86_64 is the -next target. Runtime prerequisites remain explicit: +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. +Runtime prerequisites remain explicit: - Git and `gh` for Agent workflows; - the configured Codex or Pi executable and its credentials; @@ -53,23 +53,24 @@ 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 github-app.pem # GitHub App private key secrets.toml # webhook secret + source/ # repository checkout used to provision worktrees state/ braid.sqlite3 backups/ - worktrees//-/ + worktrees/ 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. ## Database Lifecycle