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 @@
+
\ 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 @@
+
\ 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 @@
+
\ 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 @@
+
\ 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 @@
+
\ 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 @@
+
\ 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 @@
+
\ 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 @@
+
\ 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 @@
+
\ 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 @@
+
\ 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 @@
+
\ 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 @@
+
\ 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 @@
+
\ 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 @@
+
\ 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 @@
+
\ 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 @@
+
\ 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 @@
+
\ 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 @@
+
\ 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 @@
+
\ 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 @@
+
\ 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 @@
+
\ 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 @@
+
\ 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 @@
+
\ 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 @@
+
\ 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 @@
+
\ 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 @@
+
\ 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 @@
+
\ 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 @@
+
\ 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 @@
+
\ 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 @@
+
\ 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 @@
+
\ 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 @@
+
\ 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 @@
+
\ 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 @@
+
\ 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 @@
+
\ 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 @@
+
\ 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 @@
+
\ 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 @@
+
\ 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 @@
+
\ 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 @@
+
\ 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