Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 10 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,24 @@

## What this repository is

CodexAuditBridge is the QuantStrategyLab AI audit automation bridge. It runs Codex VPS/service-backed audit workflows first, with OpenAI/Anthropic API fallback for approved reviews and low-risk fix pull requests.
AIAuditBridge is the QuantStrategyLab AI audit automation bridge. It runs Codex VPS/service-backed audit workflows first, with OpenAI/Anthropic API fallback for approved reviews and low-risk fix pull requests.

It produces research, audit, or orchestration artifacts. It should not submit broker orders or mutate live allocations by itself.

## Architecture boundary

CodexAuditBridge is the organization-local AI audit boundary for QuantStrategyLab. Source repositories dispatch review requests to this repository; they should not embed raw `codex exec` commands, direct provider API calls, model routing, or fallback policy themselves.
AIAuditBridge is the organization-local AI audit boundary for QuantStrategyLab. Source repositories dispatch review requests to this repository; they should not embed raw `codex exec` commands, direct provider API calls, model routing, or fallback policy themselves.

Current execution model:

1. A source repository creates or identifies an audit issue.
2. The source repository dispatches this repository's monthly review workflow. The workflow filename is still `codex_audit.yml` for dispatch compatibility, but Codex execution is service-backed.
3. CodexAuditBridge validates the source repository and task mapping, clones the source repository with a scoped GitHub token, and runs the selected provider/backend.
4. Only CodexAuditBridge performs GitHub writes such as comments, branches, commits, pushes, and pull requests.
3. AIAuditBridge validates the source repository and task mapping, clones the source repository with a scoped GitHub token, and runs the selected provider/backend.
4. Only AIAuditBridge performs GitHub writes such as comments, branches, commits, pushes, and pull requests.

Keep this boundary inside the `QuantStrategyLab` organization. Do not move QuantStrategyLab audit execution or source-repository write tokens to another organization.

Codex execution is service-only: the workflow calls a QuantStrategyLab-owned HTTPS/443 Codex audit service from a standard GitHub-hosted runner. The service returns review text or structured patch suggestions only. CodexAuditBridge still owns clone, path validation, patch application, commit, push, PR creation, and issue comments.
Codex execution is service-only: the workflow calls a QuantStrategyLab-owned HTTPS/443 Codex audit service from a standard GitHub-hosted runner. The service returns review text or structured patch suggestions only. AIAuditBridge still owns clone, path validation, patch application, commit, push, PR creation, and issue comments.

When `CODEX_AUDIT_AUTO_MERGE=true`, the bridge requests guarded auto-merge by adding the `auto-merge-ok` label to the generated PR only after the changed-file surface is low or medium risk and the file / total changed-line caps stay within policy. The bridge ensures the configured label exists before applying it; if the source token cannot create labels, create the label manually before enabling guarded auto-merge. If a source checkout contains `.github/codex_auto_merge_policy.json`, the bridge reads the baseline policy before Codex edits run, then uses that baseline policy before falling back to its built-in defaults. High-risk, unknown, policy-changing, file-removal/rename/copy, or invalid-policy surfaces are labeled with the configured human-review label (`human-review-required` by default) instead of `auto-merge-ok`, and the source issue comment includes the risk reasons and files for operator review. The bridge does not call GitHub native auto-merge directly; source repositories must keep their own CI and merge-guard workflow in control of the final merge decision.

Expand All @@ -33,9 +33,9 @@ This avoids hard-coding Codex CLI setup in every source repository and avoids de

## Compatibility governance role

QuantStrategyLab `AIAuditBridge` is an ops/control-plane consumer only:
Compatibility governance metadata in this repository is ops/control-plane only:

- It consumes compatibility governance metadata to align audit/review execution contracts.
- It aligns audit/review execution contracts across QuantStrategyLab repositories.
- It must **not** participate in trading runtime dependency graphs or strategy/runtime upgrade flows.
- All governance references from this repo should be interpreted as control-plane/tooling compatibility, not runtime coupling.

Expand All @@ -53,7 +53,7 @@ When adding a new dispatcher, update `SOURCE_REPO_TASKS` in `scripts/run_monthly

## Codex service configuration

CodexAuditBridge uses the service backend only. The workflow runs on `ubuntu-latest` and requires a QuantStrategyLab-owned HTTPS/443 Codex audit service.
AIAuditBridge uses the service backend only. The workflow runs on `ubuntu-latest` and requires a QuantStrategyLab-owned HTTPS/443 Codex audit service.

Configure these values in `QuantStrategyLab/AIAuditBridge`:

Expand Down Expand Up @@ -99,7 +99,7 @@ Configure these values in `QuantStrategyLab/AIAuditBridge`:
Run the service host with:

```bash
CODEX_AUDIT_SERVICE_ALLOWED_REPOSITORIES=QuantStrategyLab/AIAuditBridge,QuantStrategyLab/CodexAuditBridge \
CODEX_AUDIT_SERVICE_ALLOWED_REPOSITORIES=QuantStrategyLab/AIAuditBridge \
CODEX_AUDIT_SERVICE_ALLOWED_SOURCE_REPOSITORIES='QuantStrategyLab/CryptoLivePoolPipelines,QuantStrategyLab/HkEquitySnapshotPipelines,QuantStrategyLab/UsEquitySnapshotPipelines,QuantStrategyLab/ResearchSignalContextPipelines' \
CODEX_AUDIT_SERVICE_AUDIENCE=quant-codex-audit \
CODEX_AUDIT_SERVICE_MODEL=gpt-5.4 \
Expand Down Expand Up @@ -133,7 +133,7 @@ In `review_and_fix` mode, the service must return exactly one JSON object:
}
```

CodexAuditBridge rejects absolute paths, `.git` paths, secret-like paths, and blocked data paths before writing files locally.
AIAuditBridge rejects absolute paths, `.git` paths, secret-like paths, and blocked data paths before writing files locally.

## Output boundary

Expand Down
20 changes: 10 additions & 10 deletions README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,24 @@

## 这个仓库是什么

CodexAuditBridge 是 QuantStrategyLab 的 AI 审计自动化桥接工具。优先运行 Codex VPS/service-backed 审计 workflow,并对获批的 review 和低风险修复 PR 提供 OpenAI/Anthropic API fallback。
AIAuditBridge 是 QuantStrategyLab 的 AI 审计自动化桥接工具。优先运行 Codex VPS/service-backed 审计 workflow,并对获批的 review 和低风险修复 PR 提供 OpenAI/Anthropic API fallback。

它产出研究、审计或编排类 artifact,不应自行提交券商订单,也不应直接修改 live allocation。

## 架构边界

CodexAuditBridge 是 QuantStrategyLab 组织内的 AI 审计调用边界。各 source repository 只负责派发审计请求,不应在自身 workflow 中直接拼接 `codex exec`、直接调用 provider API、实现模型路由或 fallback 策略。
AIAuditBridge 是 QuantStrategyLab 组织内的 AI 审计调用边界。各 source repository 只负责派发审计请求,不应在自身 workflow 中直接拼接 `codex exec`、直接调用 provider API、实现模型路由或 fallback 策略。

当前执行模型:

1. source repository 创建或定位审计 issue。
2. source repository 派发本仓库的 monthly review workflow。workflow 文件名仍为 `codex_audit.yml` 以保持 dispatch 入口稳定,但 Codex 执行已经是 service-backed。
3. CodexAuditBridge 校验 source repository 和 task mapping,使用受限 GitHub token clone source repository,并运行指定 provider/backend。
4. 评论、分支、commit、push、PR 等 GitHub 写操作只由 CodexAuditBridge 负责。
3. AIAuditBridge 校验 source repository 和 task mapping,使用受限 GitHub token clone source repository,并运行指定 provider/backend。
4. 评论、分支、commit、push、PR 等 GitHub 写操作只由 AIAuditBridge 负责。

这个边界应留在 `QuantStrategyLab` 组织内。不要把 QuantStrategyLab 审计执行或 source repository 写 token 移到其他组织。

Codex 执行现在只走 service backend:workflow 从 GitHub-hosted runner 调用 QuantStrategyLab 自有的 HTTPS/443 Codex audit service。service 只返回 review 文本或结构化 patch 建议;clone、路径校验、patch apply、commit、push、PR 和 issue comment 仍由 CodexAuditBridge 负责。
Codex 执行现在只走 service backend:workflow 从 GitHub-hosted runner 调用 QuantStrategyLab 自有的 HTTPS/443 Codex audit service。service 只返回 review 文本或结构化 patch 建议;clone、路径校验、patch apply、commit、push、PR 和 issue comment 仍由 AIAuditBridge 负责。

当 `CODEX_AUDIT_AUTO_MERGE=true` 时,bridge 会先检查变更文件面和总增删行数,只在低风险或中风险且未超过 policy 上限时给生成的 PR 添加 `auto-merge-ok` label,请求源仓库的受控自动合并。bridge 会在打标前按需创建配置的 label;如果源仓 token 没有创建 label 的权限,需要先手动创建该 label。若 source checkout 里存在 `.github/codex_auto_merge_policy.json`,bridge 会在 Codex 执行修改前读取基线策略,否则才使用内置默认值。高风险、未知文件面、策略文件变更、文件移除/重命名/复制或无效 policy 配置不会添加 `auto-merge-ok`,而是给 PR 添加配置的人工复核 label(默认 `human-review-required`),并在源 issue 评论中列出风险原因和文件,等待人工复核。bridge 不会直接调用 GitHub native auto-merge。最终是否合并仍由源仓库自己的 CI 和 merge-guard workflow 决定。

Expand All @@ -33,9 +33,9 @@ Codex 执行现在只走 service backend:workflow 从 GitHub-hosted runner 调

## 兼容性治理定位

`QuantStrategyLab/AIAuditBridge` 只作为 ops/control-plane 的消费侧参与兼容治理
本仓库中的兼容性治理元数据只用于 ops/control-plane:

- 仅消费兼容矩阵和治理元数据,确保审计/评审边界行为一致
- 对齐 QuantStrategyLab 各仓库的审计/评审执行契约
- 不参与策略/交易运行时的依赖图、升级决策或 runtime 级联;
- 本仓库中的兼容关系只用于审计与 review 运营(control-plane),不应被源仓库当作交易策略运行时依赖。

Expand All @@ -52,7 +52,7 @@ Codex 执行现在只走 service backend:workflow 从 GitHub-hosted runner 调

## Codex service 配置

CodexAuditBridge 只使用 service backend。workflow 运行在 `ubuntu-latest`,并调用 QuantStrategyLab 自有 HTTPS/443 Codex audit service。
AIAuditBridge 只使用 service backend。workflow 运行在 `ubuntu-latest`,并调用 QuantStrategyLab 自有 HTTPS/443 Codex audit service。

需要在 `QuantStrategyLab/AIAuditBridge` 配置:

Expand All @@ -75,7 +75,7 @@ CodexAuditBridge 只使用 service backend。workflow 运行在 `ubuntu-latest`
service host 启动示例:

```bash
CODEX_AUDIT_SERVICE_ALLOWED_REPOSITORIES=QuantStrategyLab/AIAuditBridge,QuantStrategyLab/CodexAuditBridge \
CODEX_AUDIT_SERVICE_ALLOWED_REPOSITORIES=QuantStrategyLab/AIAuditBridge \
CODEX_AUDIT_SERVICE_ALLOWED_SOURCE_REPOSITORIES='QuantStrategyLab/CryptoLivePoolPipelines,QuantStrategyLab/HkEquitySnapshotPipelines,QuantStrategyLab/UsEquitySnapshotPipelines,QuantStrategyLab/ResearchSignalContextPipelines' \
CODEX_AUDIT_SERVICE_AUDIENCE=quant-codex-audit \
CODEX_AUDIT_SERVICE_MODEL=gpt-5.4 \
Expand Down Expand Up @@ -107,7 +107,7 @@ service host 应使用已登录的 Codex CLI session。服务在启动 Codex
}
```

CodexAuditBridge 会在本地写文件前拒绝绝对路径、`.git` 路径、疑似 secret 路径和被禁止的 data 路径。
AIAuditBridge 会在本地写文件前拒绝绝对路径、`.git` 路径、疑似 secret 路径和被禁止的 data 路径。

## 输出边界

Expand Down
20 changes: 10 additions & 10 deletions docs/async_service_deployment.md
Original file line number Diff line number Diff line change
@@ -1,28 +1,28 @@
# Async Codex Audit Service Deployment

CodexAuditBridge uses an async service contract to avoid keeping a GitHub Actions request open while Codex runs on the VPS.
AIAuditBridge uses an async service contract to avoid keeping a GitHub Actions request open while Codex runs on the VPS.

## Architecture

1. A source repository creates or updates an audit issue, then dispatches `QuantStrategyLab/AIAuditBridge`.
2. CodexAuditBridge clones the source repository with a scoped GitHub App token, builds the audit prompt, and requests a GitHub Actions OIDC token with audience `quant-codex-audit`.
3. CodexAuditBridge submits `POST /v1/codex-audit/jobs` through the Cloudflare Worker.
2. AIAuditBridge clones the source repository with a scoped GitHub App token, builds the audit prompt, and requests a GitHub Actions OIDC token with audience `quant-codex-audit`.
3. AIAuditBridge submits `POST /v1/codex-audit/jobs` through the Cloudflare Worker.
4. The Worker forwards only Quant audit routes with bearer tokens to the VPS origin. The VPS service validates OIDC signature, audience, repository, workflow ref, git ref, source repository allowlists, and payload size.
5. The VPS service returns a random `job_id`, runs Codex in a background thread, and persists job state in a private local directory.
6. CodexAuditBridge polls `GET /v1/codex-audit/jobs/{job_id}` until the job succeeds, fails, or times out.
6. AIAuditBridge polls `GET /v1/codex-audit/jobs/{job_id}` until the job succeeds, fails, or times out.

The synchronous `POST /v1/codex-audit` endpoint remains available for local diagnostics, but production workflows should use the async job endpoints.

## Boundary with Pigbibi CodexGateway

`CodexAuditBridge` intentionally stays separate from `Pigbibi/AIGateway`.
`AIAuditBridge` intentionally stays separate from `Pigbibi/AIGateway`.

- `CodexGateway` is a generic Codex invocation facade for prompt/context/image/schema calls.
- `CodexAuditBridge` owns QuantStrategyLab monthly audit semantics: source issue context, bounded repository snapshots, service patch contracts, source repository allowlists, GitHub App writeback, and generated remediation PRs.
- `AIAuditBridge` owns QuantStrategyLab monthly audit semantics: source issue context, bounded repository snapshots, service patch contracts, source repository allowlists, GitHub App writeback, and generated remediation PRs.
- Do not route Quant monthly audits through the Pigbibi gateway Worker or Pigbibi repository allowlist.
- Do not move audit-specific issue/PR behavior into `CodexGateway`; share only low-level primitives after the HTTP contracts are stable.

The historical self-hosted direct-Codex workflows in `SelfHostedCodexAuditBridge` and `CryptoCodexAuditBridge` should be treated as compatibility fallback. The preferred production path is the GitHub-hosted `CodexAuditBridge` workflow plus async VPS service. After parity is verified for current monthly sources, the self-hosted direct-Codex workflows can be disabled or deleted.
The historical self-hosted direct-Codex workflows in `SelfHostedCodexAuditBridge`, `CryptoCodexAuditBridge`, and the legacy `CodexAuditBridge` repository should be treated as compatibility fallback. The preferred production path is the GitHub-hosted `AIAuditBridge` workflow plus async VPS service. After parity is verified for current monthly sources, the legacy direct-Codex and bridge workflows can be disabled or archived.

## Permission and secret boundary

Expand Down Expand Up @@ -55,8 +55,8 @@ For public source repositories:
After merging the async service code, run the manual `VPS Codex Service Ops` workflow with deploy mode, or run on the VPS:

```bash
CODEX_AUDIT_SERVICE_ALLOWED_REPOSITORIES=QuantStrategyLab/AIAuditBridge,QuantStrategyLab/CodexAuditBridge \
CODEX_AUDIT_SERVICE_ALLOWED_WORKFLOW_REFS='QuantStrategyLab/AIAuditBridge/.github/workflows/codex_audit.yml@refs/heads/main,QuantStrategyLab/CodexAuditBridge/.github/workflows/codex_audit.yml@refs/heads/main' \
CODEX_AUDIT_SERVICE_ALLOWED_REPOSITORIES=QuantStrategyLab/AIAuditBridge \
CODEX_AUDIT_SERVICE_ALLOWED_WORKFLOW_REFS='QuantStrategyLab/AIAuditBridge/.github/workflows/codex_audit.yml@refs/heads/main' \
CODEX_AUDIT_SERVICE_ALLOWED_REFS='refs/heads/main' \
CODEX_AUDIT_SERVICE_ALLOWED_REPOSITORY_VISIBILITIES='public' \
CODEX_AUDIT_SERVICE_ALLOWED_SOURCE_REPOSITORIES='QuantStrategyLab/CryptoLivePoolPipelines,QuantStrategyLab/HkEquitySnapshotPipelines,QuantStrategyLab/UsEquitySnapshotPipelines,QuantStrategyLab/ResearchSignalContextPipelines' \
Expand Down Expand Up @@ -95,7 +95,7 @@ curl -sS -o /tmp/codex-audit-probe.json -w '%{http_code}\n' \
The unauthenticated submit probe should return `401`. If the request is sent to
the Worker URL, the Worker may reject it before it reaches the origin service.

### 3. Point CodexAuditBridge at the Worker
### 3. Point AIAuditBridge at the Worker

```bash
gh secret set CODEX_AUDIT_SERVICE_URL -R QuantStrategyLab/AIAuditBridge
Expand Down
23 changes: 13 additions & 10 deletions service/ai_gateway_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -583,14 +583,17 @@ def log_message(self, format: str, *args: object) -> None: # noqa: A002
# -- GET --

def do_GET(self) -> None:
if self.path == "/healthz":
from urllib.parse import urlparse
request_path = urlparse(self.path).path

if request_path == "/healthz":
health = get_health_monitor()
_json_response(self, HTTPStatus.OK, {
"status": health.status,
"uptime_seconds": health.uptime_seconds,
})
return
if self.path == "/v1/ai/health":
if request_path == "/v1/ai/health":
try:
claims = authenticate(self.headers, audience=DEFAULT_AUDIENCE)
except PermissionError as exc:
Expand All @@ -599,29 +602,29 @@ def do_GET(self) -> None:
health = get_health_monitor()
_json_response(self, HTTPStatus.OK, {"status": "ok", **health.snapshot()})
return
if self.path == "/v1/ai/quota":
if request_path == "/v1/ai/quota":
self._handle_quota_status()
return

# Feedback: list changes or get effectiveness report
if self.path == "/v1/ai/changes/effectiveness":
if request_path == "/v1/ai/changes/effectiveness":
self._handle_effectiveness()
return
if self.path.startswith("/v1/ai/changes/"):
change_id = self.path[len("/v1/ai/changes/"):]
if request_path.startswith("/v1/ai/changes/"):
change_id = request_path[len("/v1/ai/changes/"):]
self._handle_get_change(change_id)
return
if self.path.startswith("/v1/ai/changes"):
if request_path.startswith("/v1/ai/changes"):
self._handle_list_changes()
return
if self.path == "/v1/ai/feedback/shadow":
if request_path == "/v1/ai/feedback/shadow":
self._handle_get_shadow()
return

# async job polling: /v1/ai/execute/jobs/{id} or /v1/codex-audit/jobs/{id}
for prefix in ("/v1/ai/execute/jobs/", "/v1/codex-audit/jobs/"):
if self.path.startswith(prefix):
job_id = self.path[len(prefix):]
if request_path.startswith(prefix):
job_id = request_path[len(prefix):]
if not re.fullmatch(r"[A-Za-z0-9_-]{24,96}", job_id):
_json_response(self, HTTPStatus.BAD_REQUEST, {"status": "error", "error": "invalid job_id"})
return
Expand Down
Loading