Skip to content

Latest commit

 

History

History
1049 lines (843 loc) · 121 KB

integration.md

File metadata and controls

1049 lines (843 loc) · 121 KB

Mega2 integration tests

This document describes the active integration-test contract. Compose service registration and lifecycle rules live in test-infra.md.

Planned Libra evidence integration coverage

libra.md §9 registers planned acceptance scenarios AC-LB-01…15: real Libra ingestion, immutable uploads, interrupted sync/GC, task isolation, revision invalidation, delegation/access control, derived-data privacy, trusted CI, multi-process landing, provenance, projection replay, crash/restore, retention/deletion, and optional dependency-graph/SCM integrations. That table is the scenario source of truth. These are requirement IDs, not implemented cargo targets or passing tests. Implementation must register actual targets and CI coverage using the migrations and compose lifecycle below; required live-client/multi-process checks must not pass by skipping. The landing cases depend on the shared root writer specified in trunk-push.md.

Test stack

docker/docker-compose.test.yml provides PostgreSQL, Redis, RustFS, optional profiled git-cli, profile app mega2, and profile web website-next. The default data plane does not start an SMTP capture service. Use the fixed project name:

docker compose -p mega2-it -f docker/docker-compose.test.yml up -d --wait

The embedded VaultCore is part of mega2; no external Vault container is used. Database schemas must be created through the project's migrations.

Active integration targets

Git 用户场景的完整矩阵(HTTP/SSH/auth/repo-shape、字面 git pull、LFS、DEFER)以 protocol.md 的「场景覆盖表」 为唯一事实源;本文件只登记 cargo target 索引,不复制矩阵单元格。

Target Purpose Prerequisites
integration_vault CLI config, Vault bootstrap, redaction, and HTTP smoke PostgreSQL and Redis
integration_git_cli Git HTTP protocol round trips(BRH-08:CL/ACL 合并场景改经桩会话调用 POST /api/v1/cl/{link}/merge) PostgreSQL, Redis, --profile git
integration_git_cli filter integration_git_cli_view_ 视图 URL 的真实 Git 客户端黑盒(plan-20261002) PostgreSQL, Redis, --profile git
integration_git_cli filter trunk / push_auth Trunk 直推 e2e:integration_git_cli_trunk_n1_identity_three_ff_and_no_cl_refs、integration_git_cli_trunk_n_gt1_squash_sideband_and_nff_align、integration_git_cli_trunk_requester_token_name、integration_git_cli_push_auth_token_rejects_without_token_and_out_of_path PostgreSQL, Redis;本机防火墙下 compose git-cli 可能不可达,用例走 host git + 127.0.0.1
integration_git_lfs Git HTTP LFS push → fetch → git lfs pull round trip(plan-20260803 / GM-05 review/CL);WH-05 追加 integration_git_lfs_storage_events_basic_upload(basic 一次投递日志)与 integration_git_lfs_storage_events_presigned_gap(RustFS 直传零事件,DEFER-WH-01 缺口证据) PostgreSQL, Redis, --profile git, git-lfs
integration_git_lfs filter trunk storage-only LFS(plan-20260909 / LF-03):integration_git_lfs_trunk_push_auth_none_round_trip、integration_git_lfs_trunk_push_auth_token_round_trip;直推 main 子路径,非 CL。Compose 黑盒对照:scripts/git_protocol_smoke_storage_only.sh case HTTP LFS push and pull (trunk) + config/compose.env.storage-only.lfs-innetwork(plan-20260906 SO-03 / ADR-SO-04) PostgreSQL, Redis, git-lfs;本机防火墙下 compose git-cli 可能不可达时走 host git + MEGA2_IT_ALLOW_HOST_GIT=1
integration_storage_events_media storage-only FastCDC media finalize 出站进程级门(plan-20260912 / WH-06):feature-on/off 两个独立 target-dir 二进制(off:路由 404、零事件;on:OpenAPI 列 media 路由、匿名/静态 token 401、DB token 404 业务证明、零事件、SIGINT 清理尾段);正向事件由 fastcdc lib collector 覆盖 PostgreSQL, Redis;嵌套 cargo 构建两个 feature 二进制;--test-threads=1
integration_git_ssh Git SSH cargo-native self-start clone/pull/push(plan-20260803 / GM-06..08;BRH-08:ACL 合并场景改经桩会话调用 POST /api/v1/cl/{link}/merge) PostgreSQL, Redis, --profile git
integration_git_ssh filter integration_git_ssh_view_ 视图 URL 的 SSH 原始应答与宿主 Git 客户端诊断(plan-20261002;完整前缀避免误匹配 integration_git_ssh_review_pubkey_*) PostgreSQL, Redis, --profile git;部分用例由宿主 ssh 与 git 经 127.0.0.1 回环执行,需 ssh、git、timeout
integration_views 视图 URL 入口的进程级 raw HTTP 黑盒(plan-20261002) PostgreSQL, Redis;--test-threads=1;媒体接口需 --features fastcdc,无需 git-cli runner
integration_git_ssh filter trunk_none / token_anon storage-only SSH 只读(plan-20260908 / SP-01):integration_git_ssh_trunk_none_anon_on_clone、integration_git_ssh_trunk_none_anon_off_clone_fail、integration_git_ssh_trunk_token_anon_on_clone PostgreSQL, Redis;--profile git 或 host git
integration_git_ssh filter token_anon_off / review_pubkey storage-only SSH password-token(plan-20260908 / SP-02):integration_git_ssh_trunk_token_anon_off_clone_fail、integration_git_ssh_trunk_token_anon_off_password_clone、integration_git_ssh_trunk_token_anon_off_password_fetch、integration_git_ssh_trunk_token_anon_off_password_pull、integration_git_ssh_trunk_token_push_receive_pack_disabled、integration_git_ssh_review_pubkey_anon_off_clone、integration_git_ssh_review_pubkey_anon_on_push PostgreSQL, Redis;host git + 127.0.0.1(compose git-cli 无法 hairpin 时)
integration_website_auth Better Auth cookie to mega2 session bridge --profile app --profile web, WEBSITE_IT=1
integration_authz_audit 只读装配零副作用黑盒(UN-30 / UN-43)+ authz-audit CLI(UN-29 审计/fsync + UN-37 promote) PostgreSQL, Redis,且必须 -- --test-threads=1
integration_oci storage-only OCI /v2 进程级黑盒(plan-20260902 / DR-12):integration_oci_auth_matrix、integration_oci_protocol_walkthrough、integration_oci_docker_gated(daemon 不可用 → SKIP,不 FAIL);WH-04 追加 integration_oci_storage_events_publication(enabled+播种 secret 的 manifest 发布 201 + 一次有界投递日志 + digest 不符 400 + SIGINT 清理尾段) PostgreSQL, Redis;raw HTTP(reqwest);docker CLI 仅 docker_gated 组可选
integration_api_write_trunk trunk 产品 API 写(plan-20260904 / AW-03;plan-20260917 LB-02..04;plan-20260918 FT-02..07)及 review 写鉴权与显式 CL 复用(plan-20261128 / BRH-06/14/07/24/26):token create-entry / edit/save 前进 tip、无 CL、无凭据 401;delete_entry_* 与 move_entry_* 覆盖目录与文件删移、双路径 401/403、traversal、ImportRepo 409、缺目录 404、.gitkeep、Review CL 复用与 tree 一致性;review 侧覆盖 create-entry/delete-entry/move-entry/edit/save/tags 匿名 401(零 DB/对象写入)、会话归属校验(PAT 归属校验见 api::oauth 与路由单测)、显式复用路由预检 404/403、单事务 SELECT … FOR UPDATE + 5s lock_timeout 并发冲突 409 / 锁超时 503 与 trunk TryReuse 行为保持;tag_*(8 例,含 tag_path_isolation_same_name)覆盖 storage-only tag 路由挂载、trunk 写鉴权、GET list、(path, name) 隔离与运行时 OpenAPI。每个 case 各自 boot 一次真实 service http。Compose 黑盒对照:scripts/api_write_smoke_storage_only.sh 的 delete-entry-git-visible / move-entry-git-visible / tags-list-create-delete / delete-entry-unauth-401(LB-05)以及 delete-file-git-visible / move-file-git-visible / tags-get-list-create-delete / tags-path-get-delete / delete-file-unauth-401(FT-07) PostgreSQL, Redis;raw HTTP(reqwest);push_policy=trunk + push_auth=token 及 review 鉴权对照;必须 -- --test-threads=1
integration_agent_capture 旧 Capture HTTP 退场断言(MTR-26):真实服务、agent_capture.enabled=true 下 12 条旧路径 404,运行时 OpenAPI 不含旧路径/DTO;新 traces GET 仍由 integration_traces 覆盖 PostgreSQL, Redis;隔离 local object backend;raw HTTP(reqwest);--test-threads=1
integration_storage_events_runtime storage-only 出站事件关停接线进程级门(plan-20260912 / WH-13):默认 disabled 的 service http SIGINT 优雅退出并记录 storage_events_shutdown_complete、占用端口启动失败仍经清理尾段、service multi http SIGINT 退出、config validate 无清理日志的 AC7 回归;WH-11 secret_binding:enabled+valid secret 经 config secret set 种子后启动/SIGINT 退出、enabled+missing 与 wrong-namespace 快速失败且日志无 SecretRef URI(脱敏)、disabled+dangling ref 正常启动 PostgreSQL, Redis;--test-threads=1
integration_storage_events_git storage-only 出站 repo.push 进程级门(plan-20260912 / WH-03):enabled+已播种 secret 下真实 host-git trunk push 落地、真实运输记录一次有界投递尝试(类别日志)、SIGINT 经清理尾段退出;review 形态拒绝 enabled;review 分支 push 建 CL 回归。WH-15 追加:每条 emitter 投递/drop 行带播种的 installation_id、drop 行不命中投递过滤器、被静态过滤的 seed push 恰好产生一条 dropped_filter 行(API 写用例为零条) PostgreSQL, Redis;host git;--test-threads=1
integration_github_sync outbound GitHub-sync SSH session(plan-20260916 / GS-07)与出站 worker(plan-20260920 OX-72/OX-01/OX-235/OX-44/OX-25):回环 russh 服务端覆盖公钥认证、advertise、有界 reported pack 桥接错误/取消、首推 full + 增量 have=[C] 推送及 GS-15 完整 report 要求、失败保留与旧 lease 失效、无 packfile 删除与远端 ng park、以及首推/增量 crash replay 与 OX-36 自完成;AppContext::new 仅被动注入 GithubSyncWorker 依赖;Q8 vault_create_once 并发自举与定向修复手册(OX-64..OX-07)见 github-sync.md 回环 only;不连 GitHub;--test-threads=1
integration_traces filter trace_typed_reader_paths TRB-14:真实 HTTP/SSH 二进制上,fetch、closure 与 publication validation 走统一 reader。push 与 fetch 构造传入 DB connection 和对象 store。legacy 增量发布与 fetch 返回原对象字节。切到 active 且没有 typed 行后,对象键仍在,读取 fail-closed。store-only 构造不承载这次 active 读取。ingest 四个底层读取由 lib ceres::traces::ingest::tests::trace_typed_ingest_reads 验收,且不新增生产调用方 PostgreSQL, Redis;真实 service multi http ssh;git-cli;--test-threads=1
integration_traces filter trace_typed_activation_and_fence TRB-31:cfg 接缝经 prepare-indexes、begin、verify、ready、record-recovery、activate_for_test 进入 active;断言状态转换、journal 水位不超过锁内 W0、active 上非只读 verify 拒绝、未标记 DML 被 fence 拒绝 PostgreSQL;--test-threads=1
integration_traces filter trace_typed_projection_and_transcript TRB-12:真实 HTTP push 的 checkpoint 经 projection 与 transcript 统一 reader 读取,trace_fragment 正文等于发布的 transcript 成员字节;lib trace_typed_transcript_membership 覆盖 membership、非成员降级、调用方事务连接与 active fail-closed PostgreSQL, Redis;真实 service multi http ssh;git-cli;--test-threads=1
lib trace_typed_raw_api_boundary / trace_typed_constructor_inventory TRB-17:traces rebuild-index 与 context worker 都走 TraceIndexWorker::production,传入 DB connection、对象 store 和 PRODUCTION_TYPED_WRITE_MODE。测试构造 TraceObjectService::new 与这个生产入口分开 PostgreSQL
integration_traces filter schema_identity_ traces 身份 schema(plan-20261015 / MTR-02):schema_identity_principal_persists、schema_identity_namespaces_are_independent、schema_identity_path_rebuild_keeps_code_and_capture_tables。经 traces_migration_ops::apply_migrations 跑真实 runner,再按公开实体与 SQL 观察 PostgreSQL;--test-threads=1
integration_traces filter schema_publication_ traces 发布 schema(plan-20261015 / MTR-03):schema_publication_stream_natural_key、schema_publication_ref_journal_unique、schema_publication_keeps_code_and_capture_rows PostgreSQL;--test-threads=1
integration_traces filter schema_projection_ traces 投影 schema(plan-20261015 / MTR-04):schema_projection_checkpoint_resource_and_fragment。经 traces_migration_ops::apply_migrations 跑真实 runner,再按公开实体与 SQL 观察 checkpoint 键、original_tree、resource 序数与字节范围、fragment index_version/ascii_fold 和 membership 出处 PostgreSQL;--test-threads=1

Storage-only compose black-box coverage

These scripts run in the interop-smoke service (--profile interop) against the published loopback endpoints of the default mega2-trunk stack. They complement, not replace, the process-level integration targets above. Run them as documented in deploy-trunk.md; each case and its task card are indexed in plan-20261001.md.

Script Default-stack result Opt-in coverage
scripts/oci_client_smoke_storage_only.sh 12 passed, 0 failed (1 skipped) auth-none case through scripts/bb_optin_run.sh
scripts/artifacts_smoke_storage_only.sh 14 passed, 0 failed (3 skipped) auth-none, GC, and local-storage cases through scripts/bb_optin_run.sh
scripts/libra_smoke_storage_only.sh 24 passed, 0 failed (0 skipped) None; Libra is the client under test, with Git used only as a read-only observer

storage-only outbound events(plan-20260912)地址策略、HMAC 运输与有界 emitter 由 lib 测试(jupiter::service::storage_event_transport / storage_event_emitter)覆盖;WH-15 的 drop 记账与 installation_id 记录字段由 storage_event_emitter::tests::drop_accounting_and_installation_id(thread-local tracing 捕获,覆盖七类 disposition、per-target 行、record_invalid_event 与 disabled/- 情形)覆盖,投递行的 installation_id 与「drop 行不命中投递过滤器」由 integration_storage_events_git 的 assert_emitter_lines_carry_installation_id 在真实进程 stdout 上断言;WH-13 的 CLI/service 关停接线与 WH-11 的启动 secret 绑定由进程级 target integration_storage_events_runtime 覆盖(见上表)。生产运输没有 HTTP/私网逃逸开关。WH-03 已在 B3 真实 push 提交挂钩(repo.push),进程级证据见 integration_storage_events_git;WH-07 Agent events.committed 的进程级认证/OpenAPI 证据见 integration_agent_capture 的 storage_events_batch;WH-08 checkpoint 见同 target 的 storage_events_checkpoint。

Passed-count runner

scripts/check_test_count.py is the single command that starts a Cargo or unittest process, writes its combined output to --log, and exits 0 only when that process exits 0 and the log has exactly one accepted result line whose passed count equals --expected. A missing line, a second line, a zero count, or a non-zero ignored/skipped count is a failure. Cargo accepts test result: ok. N passed; 0 failed; 0 ignored; .... Unittest accepts one Ran N tests in ... line followed by a plain OK.

Run the normal project gate with the test environment loaded:

source .env.test && cargo test --all

Integration test sources live under tests/integration_*.rs on the mega2 package (lib mega2_core). Black-box tests drive the real CLI via CARGO_BIN_EXE_mega2.

For the real website-session check:

docker compose -p mega2-it -f docker/docker-compose.test.yml \
  --profile app --profile web up -d --wait
source .env.test
WEBSITE_IT=1 cargo test -p mega2 --test integration_website_auth -- --test-threads=1

When WEBSITE_IT=1 is set, unavailable mega2 or website-next endpoints are failures, not passing skips.

integration_traces filter trace_typed_activation_ddl observes the activation fence installed by migration m20261202_000400_trace_typed_activation. It checks the statement-level BEFORE triggers, legacy unmarked publish and worker DML, importing and ready rejection, and the active typed-v2 mark. A rejected membership write leaves previously stored object bytes in place and does not make them visible.

integration_traces filter trace_typed_fence_hardening checks that fenced DML in every storage state accepts only READ COMMITTED, that a read-only REPEATABLE READ snapshot still reads, that legacy READ COMMITTED writes still succeed, and that TRUNCATE is rejected while importing or ready.

integration_traces filters trace_typed_offline_migration and trace_typed_import_capacity_pause compile only when the test binary is built with --cfg mega2_test_seam. They call traces_typed_test_ops::begin for the importing state and W0. They do not call the production begin CLI and they do not issue SQL to begin.

integration_traces filter trace_typed_ready_gate compiles only with --cfg mega2_test_seam. It calls traces_typed_test_ops::begin and traces_typed_test_ops::ready. It does not issue SQL to enter ready.

Notification coverage

Mega2 tests cover trigger selection, user preferences, and generic webhook delivery under [notification.webhook]. Product email is not a mega2 outbound path; see the tombstone in website-mail.md.

Do not add or retain tests that:

  • seed or query email_jobs;
  • set [mail], mail.password, or SMTP endpoint configuration;
  • require this repo to deliver mail or start an SMTP capture service;
  • treat SMTP capture availability as a mega2 startup gate.

授权首建与 shadow→enforce 集成(UN-02)

HTTP 服务启动时在 listener 绑定前完成共享授权快照首建(ensure_authz_first_build,ADR-UN-02):off 不构建;shadow/enforce 下首建失败使 server 启动失败。push 门三态(check_push_permission)在 shadow 下放行并记录 would-deny,enforce 下拒绝无权限 push。SSH 面(UN-03)与 HTTP 面共享同一 AppContext.entity_store 实例;独立 service ssh 对 enforcement != off 拒绝启动(指引 service multi 或 off)。UN-02 的 5 门 shadow→enforce 判据脚本使用 MEGA_IT_PG* 环境变量(登记于 .env.test.example,ER-11:凭据只经环境变量)。

授权快照传播与主干删除防护集成(UN-16)

integration_git_cli 与 integration_git_ssh 覆盖快照传播闭合的端到端行为:

  • integration_git_cli_authz_revoke_grant_immediate_effect:enforce 下非 admin push 被拒 → admin 合并授予变更后同一 push 通过 → 合并撤销变更后再次被拒,全程不重启服务。
  • integration_git_cli_rejects_main_branch_delete:receive-pack 删除主干 ref 被拒绝,错误对 git 客户端可操作。
  • integration_git_ssh_authz_grant_immediate_effect:ACL 变更经 HTTP 腿的 merge 漏斗合入,SSH 腿在下一次 push 即刻生效——service multi 下两腿共享同一实例的直接证据。

授权变更后再次 push 前必须先 git fetch 并从新的 origin/main 起分支:Monorepo::check_entry 只接受每次 push 携带单个 commit,陈旧克隆会把父提交一并打包而被拒。

写点 allowlist 守卫(scripts/authz_write_points_guard.sh)与其两个自测变异(--selftest-add / --selftest-remove)是三道独立门,任何未登记的主干 ref 写入口都会使守卫非零退出。

Kill Switch 骨架与安全写原语(UN-33;REL-02)

运维入口:bash scripts/authz_kill_switch.sh(生产与 fixture 同一文件;家族内后续卡在同一 --selftest 入口叠加门)。

  • 分派:--branch systemd|compose|file(目标分别取自 KILL_SWITCH_ENV_FILE / KILL_SWITCH_COMPOSE / KILL_SWITCH_CONFIG)。无 --apply-content 时走 UN-41 变换;有则仅为骨架/元数据低层替换。可选 --restart -- <argv...>(UN-46:argv 数组恰好一次执行,禁二次分词)。启动时先跑 UN-50 preflight;重启成功后若设置 KILL_SWITCH_URLS 则跑 UN-36 HTTP 探测。
  • preflight(UN-50):Linux 专属;校验 cp/yq/jq/rg/flock/stat/getfacl/getfattr 存在性、GNU cp --preserve=all、KILL_SWITCH_BIN authz-audit fsync --probe、版本下限(coreutils≥8.30 / yq≥4.18 / jq≥1.6 / rg≥13 / util-linux≥2.27);任一缺失/不足 fail-closed 并给出安装指引。
  • HTTP 探测(UN-36):KILL_SWITCH_URLS + KILL_SWITCH_EXPECT_CODE + KILL_SWITCH_DEPLOY_HTTP;canonical origin 绑定(默认端口/IPv6);https 强制证书链校验;失败终态 T2 → 退出码 6、配置保持 off;不自称恢复绿。
  • evidence 记录(UN-53):探测前经 KILL_SWITCH_BIN authz-audit run-init --restricted-root "$KILL_SWITCH_RESTRICTED_DIR" 分配 run;脚本自持 runs/<run-id>/.lease.lock(长生命周期,≠ UN-56 .evidence.lock);逐项经 evidence-append(channel/check/verdict[/status])写入,禁止脚本内拼 JSON;成功 run-commit(RUN_CAP),异常 run-abort;256 KiB 硬上限与未知枚举拒绝由 CLI 透传。
  • 日志通道(UN-47):KILL_SWITCH_LOG_DIR;重启前按 inode 捕获字节游标;重启后有界轮询落盘(默认 30×2s);只读增量;rg would-deny 按 0/1/>1 分支(>1 硬失败、不转零命中);零新增则 log_no_would_deny=pass,否则 T2。
  • Git HTTP 只读(UN-42):KILL_SWITCH_GIT_REMOTE + KILL_SWITCH_DEPLOY_GIT + KILL_SWITCH_GIT_ASKPASS;git ls-remote(凭据仅经 ASKPASS,禁 argv);canonical origin 绑定;stderr 脱敏;可选 KILL_SWITCH_GIT_ZEROCHECK_REPO 断言 refs/objects 零变化。
  • SSH 只读与跨通道绑定(UN-44):KILL_SWITCH_SSH_HOST/PORT/USER/KEY + KNOWN_HOSTS + REPO + DEPLOY_SSH;启动时三通道 early bind(不符 → 退出码 7、零写入);pinned known_hosts;git ls-remote over SSH。
  • 变换与读回(UN-41):systemd 将 MEGA_CEDAR__ENFORCEMENT= 替换为 =off;compose 仅 mapping 形态经 yq 写 "off"(list/缺键 fail-closed);file 改写 [cedar].enforcement 为 "off"(缺键 fail-closed),必选 MEGA_PROFILE,并以 UN-01 config validate --show-sources --format json 断言 winning source 为该文件(环境源获胜则禁用)。落盘后恰好一次读回校验为 off(KILL_SWITCH_READBACK_FAIL=1 可注入)。
  • 写原语:同目录临时文件 O_EXCL|O_NOFOLLOW → cp --preserve=all 播种 → 原地改写字节 → 元数据逐项校验 → KILL_SWITCH_BIN authz-audit fsync <tmp> → renameat → authz-audit fsync <target>;目标须为 no-follow 普通文件;systemd EnvironmentFile 拒绝重复键。
  • 重启与失败终态(UN-46):--restart -- <argv...> 恰好一次;T1 重启失败 → 退出码 4、配置保持 off、打印人工重启指引;T3 rename 后 fsync 失败 → 退出码 5、不回滚为 on、重跑幂等收敛。
  • 元数据保持(UN-48):owner / mode / ACL / xattr;写后 stat/getfacl/xattr 比对,不符即失败(可用 KILL_SWITCH_META_VERIFY_FAIL 注入)。
  • 自测:bash scripts/authz_kill_switch.sh --selftest(… + UN-42×6 + UN-44×7 = 58/58;fsync stub = scripts/authz_kill_switch_fsync_stub.sh)。需可用的 KILL_SWITCH_BIN 或 target/debug/mega2;compose/preflight 需 yq(或 KILL_SWITCH_YQ);缺 getfattr 时自测会在临时 PATH 放入存在性 stub。
  • 发布:REL-02 十子卡本地提交后由 UN-45 原子发布为 v0.2.65(脚本入口 / 三分支 / 拓扑绑定 / 失败终态安全方向见上;降级 = 不执行该脚本)。

迁移覆盖:traces 投影(MTR-04)

m20261015_000300_trace_projection 创建 trace_checkpoint、trace_session、trace_resource、trace_code_link、trace_fragment 与 trace_fragment_membership。checkpoint 键在 stream 内唯一,更新 original_tree 被触发器拒绝。resource 保存 ordinal、byte_start 与 byte_end。fragment 在 stream 内按 content_digest 加 index_version 唯一,并保存 ascii_fold 文本列。membership 保存 checkpoint 与 resource 出处,更新这些列被触发器拒绝。复合外键要求 resource、code link 和 membership 引用的 checkpoint、resource、fragment 属于同一 stream。普通 btree 索引可以存在。该迁移不创建或删除扩展,也不建 trigram GIN。down 是空实现,不删除这些表。

库内契约在各自 db_contract,无扩展升级在 ordinary_schema_without_extensions_,外部观察在 integration_traces 的 schema_projection_。

迁移覆盖:traces 发布(MTR-03)

m20261015_000200_trace_publication 创建 trace_stream、trace_ingest_attempt、trace_object 与 trace_ref_update。stream 自然键是 (principal_id, target_id, source_repo_id, epoch_id)。更新 hash_kind 被触发器拒绝。同一 stream 的 ref_sequence 唯一,journal 的 idempotency_key 唯一。down 是空实现,不删除这些表,也不改已有 git_repo 或 agent_capture_session 行。

迁移覆盖:traces 身份(MTR-02)

m20261015_000100_trace_identity 创建 trace_principal、trace_credential_binding 与 trace_target。principal id、binding id 和 target id 都是服务端指定的 UUID 文本。同一 credential id 可以在 static_push_token 与 mono_account 两个 namespace 各有一条活动绑定;同一 namespace 的活动绑定唯一。retired_at 写入后,同一 namespace 与 credential id 才能再次绑定。同一 project_path 同时只有一个 active target;停用后再插入是新的 target id,旧行保留。target_kind 只接受 native 或 import。

恢复是 forward-only。down 是空实现,不删除这三张表,也不改 git_repo 或 agent_capture_session。库内契约在各自 db_contract,外部观察在 integration_traces 的 schema_identity_。

迁移覆盖:mega_cl.link 唯一索引(UN-10)

m20260815_000000_unique_mega_cl_link 为 mega_cl.link 建唯一索引 idx_mega_cl_link_unique(既有索引只有复合的 (path, link),link 单列查询既非索引等值探测也不保证唯一)。up 在同一事务内先取 LOCK TABLE mega_cl IN SHARE ROW EXCLUSIVE MODE,再扫描重复 link;发现重复即中止并在错误里列出全部冲突 link 与各自行数,不修改任何业务行。锁从扫描前持有到索引建成,杜绝「扫描通过后、建索引前插入重复」的竞态。

恢复为 forward-only:运行时 runner 只暴露 up/refresh,已发布索引只能由新迁移前滚修复;down 仅供隔离测试与开发 refresh,不得作为生产回退。

迁移模块内 #[cfg(test)] 覆盖四条:up 建唯一索引且 down 删除、重复数据使 up 带完整冲突清单失败且行数不变、并发插入在迁移事务提交前被锁阻塞(提交后被唯一索引拒绝)、SET LOCAL enable_seqscan = off 下 EXPLAIN 的计划命中新索引名。get_cl 的按 link 回归在 src/jupiter/storage/cl_storage.rs 内。

迁移覆盖:视图表(HP-09)

m20261006_000100_add_view_tables 按顺序创建八张无外键的表: mega_view_filter、mega_view、mega_view_root_chain、 mega_view_root_chain_scan、mega_view_commit_map、mega_view_object、 mega_view_object_ref 与 mega_view_register_log。最后一张表及其 (requester, created_at) 索引位于迁移的最后一组语句,确保故障注入能 验证整个迁移的事务边界。

恢复是 forward-only。运行期只有 up 与开发用的 refresh,down 是空实现; 已发布的 DDL 问题必须用后续迁移前滚修复。升级时服务启动会自动执行待处理 迁移;未启用视图的部署会保留这八张空表。

jupiter::migration::tests 中的 view_tables_match_design_schema、view_tables_have_no_foreign_keys、 view_tables_migration_up_replays_over_existing_schema、 view_tables_leave_existing_schema_unchanged、view_entities_round_trip 和 view_tables_migration_rolls_back_and_recovers 覆盖完整列、可空性、默认值与 索引集合;没有外键;对已有 schema 重放 up 的空操作;新迁移不改变既有 schema;八个 SeaORM 实体各写入后按主键读回;以及预建同名 mega_view_register_log view 使最终索引失败时,八张表和迁移记录全部回滚, 移除冲突对象后可直接重跑。

DB 模块覆盖:视图根链(HP-10)

ViewStorage::extend_root_chain(budget, batch_size, lock_mode) 在短事务中持有 根链锁 L_C,返回 CaughtUp、NotCaughtUp 或 RolledBack、Forked、 UnrelatedHistory、MultiParent、MissingFirstParent、RowConflict 六种不连续原因。扫描提交的首父链 先落入 mega_view_root_chain_scan,再按 seq 递增分段写入 mega_view_root_chain;每段把插入和锚点切换放在同一个事务中。预算同时计算暂存 写入与根链插入,每批回走和每段接入都按剩余预算截断;锚点判定不写行,也不耗 预算。耗尽时保留锚点供下次继续。insert_segment 在调用方的段事务内 执行;主键冲突核对失败时,调用方回滚整个段,因此不会留下该段已先插入的部分行。 不连续事务不改根链表,同一调用先前已经提交的段保持有效。

锁键使用 VIEW_LOCK_NS、VIEW_FILTER_LOCK_NS、ROOT_CHAIN_KEY、 OBJECT_GC_KEY 与 REGISTER_KEY;段上限是 ROOT_CHAIN_SEGMENT_ROWS = 10_000。hash32(x) = ((x as u64) ^ ((x as u64) >> 32)) as u32 as i32 折叠 64 位 id 的高低两半。 测试 schema 把第二键映射为 hashtext(current_schema() || ':' || d),使并行 schema 不相互阻塞。Blocking 模式以绑定的 set_config('lock_timeout', $1, true) 设置 VIEW_LOCK_TIMEOUT(两秒)等待上限;超时按 SQLSTATE 55P03 返回未追上,取消等 其他数据库错误原样上抛。返回 Ok(false) 的事务已经 aborted,调用方只能回滚; 成功设置的 lock_timeout 一直持续到事务结束。取锁语句由 view_lock_stmt_prod 与 view_lock_stmt_test 单独拼装,语句本身不带 lock_timeout;需要不限时等待的调用方 可直接执行 Blocking 语句。

ViewStorage 聚合在 AppService 中,访问器返回克隆而不新建实例,以便同一进程 共享告警记录。它的 base 字段保持私有;同级实现经 Deref<Target = BaseStorage> 取得连接。view_test_fixtures 以 pub(crate) 提供参数绑定的路径到 blob 字节和 预构造 tree 列表、线性/多父/首父缺失/无关根历史,以及可回退的 root main CAS 夹具;它写入 tree 层、返回 blobs,但不写 blob。

六个 lib 用例分别覆盖:线性冷启动和增量;预算耗尽后的续接及回走中途重启;分段 锚点、每段后的重启、两个连接池按 Try/Blocking 换手,以及扫描期间 main@/ 前进; 五类根历史不连续、三种 insert_segment 既有行输入和第二段冲突;不成功的 Try/Blocking/取消等锁;以及全部锁键与同 schema 的两两隔离。 不连续事件仅从 view_root_chain 发出,带 reason 与 commit_id,按进程中的 (reason, commit_id) 去重,并在 CaughtUp 后清除记录。带数据库的事件捕获在 单线程 Tokio 测试中安装按该模块 target 过滤的线程局部 subscriber,同时持有第二个 tracing::Dispatch,避免并行测试首次命中 callsite 时缓存 no-op interest。取消等锁 用持锁事务之外的自动提交查询在一秒内轮询 pg_stat_activity;事务快照不会看到之后 才出现的等待者。代码审查点是根链只按 seq 递增插入,绝不以 max(seq)+1 追加单行。

DB 模块覆盖:视图注册准入(HP-13)

ViewStorage::admit(req, limits) 在一个短事务中实现注册准入。Register 按 filter_id 查找定义,Rewarm 按主键查找;不存在的 Rewarm 返回 MegaError::NotFound。两种模式都在定义新建或处于回收态时判定冷启动,依次检查 活跃过滤器总数和冷启动名额。命名 Register 只读取该 name 的最新 (version, filter_pk):同一活跃定义且不需新版本时返回 Idempotent,其余成功 请求返回 Admitted;version 是请求 name 的最终最新版本(无 name 时为 None),ready 是第 2 步读到的 ready_seq 是否非空。第 3 步的速率窗口和 mega_view_register_log 读写由 HP-31 接入,本卡不读写该表。

AdmitRequest、AdmitMode、FilterDefinition、AdmitLimits、 AdmitOutcome 与 RejectReason 都限定在 storage crate 内。限额仅来自调用方传入的 AdmitLimits:HP-13 的 max_filters 与 max_concurrent_cold_starts,以及 HP-31 追加的 register_rate_per_token 都由 From<&ViewsConfig> 读取;准入自身不读取 Storage 的配置快照。总数与名额拒绝返回 Rejected { reason, retry_after: 30 秒 } 并回滚;幂等命中没有写入。新过滤器以 ON CONFLICT (filter_id) DO NOTHING RETURNING 写入,若 L_R 以外的写入方在查询后 抢先提交,SeaORM 的零返回行会规范为 MegaError::Db(DbErr::RecordNotInserted),事务回滚,绝不会用未插入的 id 创建 mega_view。

第 1 步直接执行 admit_lock_stmt(cfg!(test)) 返回的 HP-10 view_lock_stmt_prod 或 view_lock_stmt_test 的 ViewLock::Register、Blocking 语句。该纯函数只负责委托拼装;准入不调用 acquire_view_lock,因为后者会设置两秒 lock_timeout,而设计 §6.5 要求 L_R 不限时等待。事务不取得其他视图锁,也不重写 §4.4 的锁键方案。

七个 lib 用例覆盖 concurrent_last_slot、same_filter_concurrent、 rejection_and_idempotent_hit、checks_follow_design、cold_start_marks_warming、 named_register_versions 与 limits_follow_reload。并发用例用 test_db_config 和 database_connection 建同一 schema 的多个连接池,由第三个连接的未提交事务持有 L_R,并轮询确认两个准入正在等待再释放;轮询失败分支会显式回滚 H,每轮的 tokio::join! 外包 30 秒超时,延时轮分别确认两个请求都在释放 L_R 后才返回,因而等待 超过通常锁超时仍可成功。其余用例直接构造就绪、预热、部分投影和回收态行,以三表 JSON 快照验证拒绝、幂等、Rewarm 与错误都不写行;改名列注入第 6 步写失败,并让 L_R 外部 未提交的同键插入与准入经 tokio::join! 在 30 秒内运行,在观测到 transactionid 等待后 提交;观测失败先显式回滚写入事务,验证零行冲突回滚。

DB 模块覆盖:视图注册速率窗口(HP-31)

AdmitLimits 从调用方的配置快照额外携带 register_rate_per_token,RejectReason::Rate 表示按 requester 的速率拒绝。 ViewStorage::admit 在 Register 的幂等判定之后、总数和冷启动名额之前,以同一短事务 读取 requester 在 REGISTER_RATE_WINDOW_SECS(3600 秒)内的注册行数和最早一行的 离窗秒数。达到阈值时显式回滚并返回向上取整、最多 3600 秒的 retry_after;成功的 计速率 Register 在提交前插入一条默认时间戳的日志,并仅删除该 requester 的过期行。 Idempotent 与 Rewarm 不读写 mega_view_register_log。

六个 lib 用例覆盖:rate_rejects_iff_requester_window_full 的三类计速率 Register、 过期行、requester 隔离和热加载阈值;rate_rejection_writes_nothing 的速率、总数和 名额拒绝逐行三表快照;rate_retry_after_from_oldest_row 的 SQL 时间边界和 3600 秒上限; rate_admitted_appends_and_trims 的插入与 requester 范围内清理; rate_idempotent_and_rewarm_not_counted 的不计数路径;以及 rate_concurrent_last_quota 的跨副本最后一个速率配额。窗口状态由直接插入的 created_at = localtimestamp - k 秒 行构造,并在各状态之间清空运行态表;重试秒数由 调用前后的 SQL 值夹定,Rust 不直接比较时间。并发用例用 test_db_config 和 database_connection 共享 schema,先预热三个连接池,再由第三个连接以 ViewLockMode::Blocking 持有 L_R;只有观察到两个等待者才释放锁,10 秒内未观察到则 显式回滚,整个 tokio::join! 另有 30 秒上限。

DB 模块覆盖:根链停追与恢复(HP-28)

ROOT_CHAIN_HALTED_SQL 是不带绑定参数、不引用外层别名的完整布尔表达式。读者可把它 原样嵌入自己的单条快照查询;ViewStorage::root_chain_halted() 只执行一条 SELECT,从不取得根链 advisory lock。它依事实校准第 7 项的顺序先判断暂存表顶行是否已在 根链中:该行只有不再是链尾时才停追;不在根链中时才依次判定无父而链表非空、多父、和 首父缺失。因此,暂存表为空、已追平,以及无父的 bootstrap 仍是链尾或冷启动尚未接入时 都不会误报停追。

暂存表顶行持久化了五种根历史不连续的判定。后续 extend_root_chain 在锁内只复核该顶行, 不改根链表或暂存表;语句数与历史长度无关。把 main@/ 恢复到旧链尾的单父后代后,删除 暂存表即可重新追赶;若不恢复 main@/,相同操作会重新得出原来的不连续原因。

view_root_chain 的七个 lib 用例覆盖:五类不连续经同 schema 的新连接池重启后复现;8 行 与 256 行历史的停追调用等语句数和单语句谓词;停追后 main@/ 前进仍不写两张表;另一个 连接池在根链锁被持有时仍读取停追;从未扫描、追平、预算扫描、段间锚点、bootstrap 与冷 启动等正常状态均为假。分段接入期间再在同一条快照 SQL 中读取谓词和两张表的行数, 并断言谓词为假;恢复后清空暂存表会重新追赶;未恢复时清空暂存表会再次停追。需要第二个 连接池或重启的用例通过 test_db_config 保持同一 schema,并用 database_connection 创建新的连接池。

DB 模块覆盖:视图 tree 读取(HP-29)

MonoStorage::get_commits_by_hashes_fallible 与 MonoStorage::get_trees_by_hashes_fallible 先对请求 id 去重,再以 1000 条为一组在给定 连接或事务上读取;查询错误以 MegaError 返回,数据库中没有的 id 不会被误报为查询错误。 ViewTreeSource 只在异步 prefetch 中访问数据库:它先读 mega_view_object(kind = 2), 再用剩余 id 读 mega_tree,并且只在两个阶段都成功后写入本实例的已预取与缺失集合。同步的 TreeSource::read_tree 不发 SQL;已确认缺行、坏字节和未预取 id 分别给出 Absent、 Malformed 与 Unprefetched。EMPTY_TREE 不进入预取集合,由 HP-04 的 read_tree 直接处理。

六个 lib 用例是 fallible_batch_reads_rows_then_query_error、 fallible_batch_reads_chunk_statement_count、lookup_order_view_object_first、 read_tree_outcomes_over_db_source、prefetch_statement_count 和 prefetch_query_error_keeps_state:它们分别覆盖连接和事务上的去重、缺行、分块和查询错误; 视图对象优先于 L0 tree、kind = 1 回退、显式 SHA-1/SHA-256 解析及事务构造;三种 MissingObject 原因和补行后的新实例读取;prefetch 的 1000 条分块、缓存命中与同步读取 零查询;以及在测试 schema 内改列名后,预取失败不污染既有缓存或把新 id 误记为缺失。 语句计数用 test_db_config 自建连接并安装 metric callback,避免替换 test_db_connection 持有 schema 守卫的回调。失败注入只改列名,不改表名,也不用 DatabaseConnection::default()。每个批量查询的语句数为 ⌈n / 1000⌉;HP-11 的语句数断言 按同一公式计算。调用方收到 Unprefetched 说明漏做预取,它不表示对象缺失。

DB 模块覆盖:视图投影追赶(HP-11)

ViewProjectionService 在单个事务中按 filter_pk 读取过滤器、复核规范定义,取得连续 根链批次,并经 ViewTreeSource 按层预取 tree。它依次尝试过滤器锁与对象 GC 共享锁;未准入 或试锁失败不写入。批中 seq = s0 只提供父 tree,不重复投影;每个后续根链行直接使用前一行 的 tree_id,不会为每个提交另查父链。成功批仅为实际写出视图提交的段写提交对象、生成 tree 与引用,以 GREATEST 推进水位;最后一批在同一事务内检查 main@/ 覆盖并标记就绪。预取后 同一 tree id 仍报告未加载会作为内部错误终止,避免循环重试。

jupiter::service::view_projection_service::tests::determinism、 jupiter::service::view_projection_service::tests::commit_map_matches_design、 jupiter::service::view_projection_service::tests::object_refs_match_design、 jupiter::service::view_projection_service::tests::ready_same_txn、 jupiter::service::view_projection_service::tests::noop_returns、 jupiter::service::view_projection_service::tests::failed_batch_no_effect 和 jupiter::service::view_projection_service::tests::statement_count_independent_of_batch 覆盖批次收敛、映射游程、对象与引用、同事务就绪、无操作返回、前提失败与内部错误,以及批量 路径。映射用例用内存 TreeSource 加逐提交 project_commit 形成独立参照,覆盖起始空段、未预取 重算和父提交为空的首段;对象用例先单批持久化起始空段,确认该段没有对象或引用。夹具根提交以固定 author/committer 签名和时间戳构造,因而可跨 schema 比较投影字节。 determinism 覆盖 Subdir、Prefix、Exclude 与 Compose:以一个 B=1000 基准结果比较两个独立 schema 的冷启动、清表重建、同一过滤器上共享服务实例克隆的并发追赶(遇 NotRun 重试)、B=1/B=1000, 以及批间钩子调用 ConfigHandle::reload 将 views.batch_size 从 3 改为 2;钩子记录实际水位 3、5 与应用字段 views.batch_size,防止热改用例退化为单一批大小。

服务实例持有同一份 memo 与计数器;测试构建下的钩子记录 memo 命中、补预取次数、每批预取的 id 集合、已提交批的水位和终态 s0 >= tip 检查,并能在试算和段计算之间清空 memo、在批间触发 回调。对象引用用例会删去仅由 Exclude 视图引用的对象并复位该视图,再以同一服务重跑,核对 memo 命中后补写的对象字节、类型和引用行;共享的 EMPTY_TREE 则保留并核对 gc_marked_at 被清空。 TreeSource 钩子可模拟漏记未加载与持续未加载,分别覆盖未经过包装层的读取和补预取后仍报告未加载的 fail-closed 路径。补预取的生产来源是 seq=1 的 is_empty_root 递归与 HP-06 登记的 R8 例外; 试算产出的 FilterOutput 直接交给 project_with_output,因此 memo 在两阶段之间被清空也不会使 段计算重新执行 filter_tree。语句数用 test_db_config 取得独立 schema,并以 Storage::new_with_connection 在自建连接上安装 metric callback;B=10 与 B=500 的常规档各断言一 个推进事务和一个终态事务,预热 memo 后强制清空的两档各在新 schema 比较,后两档不与前两档比较。 ready_same_txn 还让尚未 ready 的过滤器追到链尾时发现 main@/ 在链外、再回退到链尾,验证 s0 >= tip 分支首次写入 ready_seq;另以新过滤器验证扩展根链后的批内写入路径。

批事务每次重新调用 recheck_definition;不存在的过滤器行和 DefinitionCorrupt 都按内部错误 回滚。failed_batch_no_effect 是同步测试,capture_tracing 在 current-thread runtime 内驱动异步 调用,保持 _pin_registry 存活并使用 with_ansi(false) 捕获 ERROR 事件。它以 H=6 的 Prefix 夹具 逐一验证 B=0(s0=0、s0=2)和根链空洞三种前提失败;内部错误的七个子例为:过滤器缺失、定义往返 损坏、定义哈希损坏、Compose 冲突导致的 ProjectFailure::Internal、不记录未预取、持续未预取,及在 测试 schema 内把 mega_view_object_ref.object_id 改名造成的查询失败。每次调用都单独核对新增的一条 ERROR 事件、状态回滚、指标与脱敏字段;列名恢复后,同一服务可重新追平并与独立 schema 的参照快照 逐字节比较,证明失败事务不污染水位或映射;ON CONFLICT DO NOTHING 的整批冲突也通过无返回值插入 执行,不会把合法对象复用变成失败。

DB 模块覆盖:视图投影停止(HP-12)

ViewProjectionService 在单批事务中把 ProjectFailure::Data 交给纯停止分派: 前提校验失败、缺失 tree 行、无法解析 tree 字节和缺失 commit 行分别以 premise_check_failed、row_absent、unparsable、commit_row_missing 停止; MissingObjectReason::Unprefetched 仍按内部错误回滚。停止点为 s 时仅写入 seq < s 的段、对象和引用,将 projected_seq 推至 s - 1,不标记 ready。提交成功后才 递增 view_projection_stops_total 并发出一条 ERROR 事件。事件字段为 metric、filter_id、 s、commit_id 和 reason;缺对象时另有 tree_id。字符串字段以 Display 记录。字段断言 只分析事件 target 之后的文本;任何 span 上下文都不算事件字段,且事件不回显作者、提交者或消息。

jupiter::service::view_projection_service::tests::stop_state_equals_prefix_reference 覆盖四种 故障在 B=1 与 B=1000 时的前缀状态、重复追赶和显式单批入口; jupiter::service::view_projection_service::tests::stop_alert_and_counter 覆盖逐次 ERROR 告警、 脱敏和共享计数器; jupiter::service::view_projection_service::tests::non_stop_inputs_reach_ready 覆盖被 J4 丢弃、 未读取缺失 tree 和真实不存在路径; jupiter::service::view_projection_service::tests::stop_dispatch_excludes_not_prefetched 覆盖 分派表;jupiter::service::view_projection_service::tests::stop_resumes_after_repair 覆盖补回 L0 行或字节后的续追;jupiter::service::view_projection_service::tests::stop_changes_only_projected_seq 覆盖冷启动及已就绪状态只修改水位; jupiter::service::view_projection_service::tests::cold_start_slots_gauge 覆盖快照和冷启动名额。

夹具先建立 12 个固定哨兵签名与 message 的根提交和根链,在第 7 个提交制造四类故障;P 组以带前导零 author 时间戳的原始字节经 Commit::from_bytes 和 into_mega_model 写入,所有组的作者与 message 哨兵为 hp12-sentinel-author 和 hp12-sentinel-message。独立 schema 的前六个根提交提供前缀参照; 缺行和缺提交修复时恢复原模型,损坏 tree 恢复原字节。语句计数通过 test_db_config 和 database_connection 自建连接,并以 Storage::new_with_connection 复用该连接;metric callback 只记录 mega_commit 的 SELECT。多个 schema 可以共享同一份 ViewMetrics,因其计数由 Arc 维护。 告警捕获使用带 _pin_registry 的、闭包内可读取缓冲的 DEBUG helper,按每次调用前后的差值断言; 查询失败在测试 schema 中把 mega_view_object_ref.object_id 改名而非改表名。 ViewMetrics::counters() 只读取原子总数;ViewMetricsSnapshot 以 #[serde(flatten)] 展平它们, metrics_snapshot() 另以一条 warming_since IS NOT NULL 计数查询填入 view_cold_start_slots_in_use,并在每个快照步骤与同一原生 SELECT 的结果比较。

DB 模块覆盖:视图 worker(HP-14)

六个 lib 用例是 view_worker_spawned_only_when_enabled、worker_hot_reload、 round_selection、compensation_liveness、round_errors_do_not_stop_worker 与 view_runtime_wiring。它们覆盖启动时 [views].enabled 门控、正在执行的轮被取消、 热加载、候选选择、周期补偿、候选与整轮错误隔离,以及共享运行时的作用域。视图 trunk 配置使用 push_policy = "trunk"、push_auth = "none"、ssh_receive_pack = false 与 cedar.enforcement = "off",并显式启用 views。

spawn_view_worker_with_round 是测试替换轮函数的接缝,production_round 是取得生产轮的 唯一入口。每轮先读配置快照、试锁扩展根链、查询候选,再按主键顺序调用共享服务的 catch_up;每批的 batch_size 仍由 catch_up 自行读取,所以热改在下一批生效。候选 失败只记录错误并继续其余候选;根链或候选查询失败只记录该轮错误,下一 tick 继续。测试 通过 compensation_round 的逐候选函数注入错误或记录候选集合。

ViewRuntime 随一个 Storage 及其克隆共享 ViewMetrics、ViewSignal 和一次性的 OnceLock 服务槽。view_projection_service() 传给服务的内部 Storage 使用空槽,避免 服务反向持有同一槽产生 Arc 环;因此服务、memo 和计数器在同一进程 Storage 内共享,而 测试 schema 的连接仍可释放。notify_worker() 用 notify_one 保留许可;HP-32、HP-19、 HP-33 和 HP-21 分别消费该信号接口。

worker 只在启动时 enabled 才注册热加载订阅者。订阅者只持有 watch 控制结构,不捕获 Storage;收到 views. 应用字段后转发新的 ViewsConfig,worker_interval_secs 改变时以 .max(1) 重建 ticker。循环把进行中的轮与 token.cancelled() 放在同一个 tokio::select! 中,取消时丢弃本轮而不等待无上界的冷启动;短事务、根链段和投影批会各自回滚或保留已 提交状态。后台根链扩展传入 budget = None,不受 max_append_walk 限制,保证超过前台 上限的根链仍在后台追平。

worker_hot_reload 与 compensation_liveness 的双连接池情形使用 test_db_config 和 database_connection 建 worker、持锁两个连接池,持锁事务不占 worker 的池连接。 worker_hot_reload 以 mega_view_filter 的表锁让首轮已取旧配置快照、但还未开始第一批, 再热改 batch_size;根链缺口使新批大小 1 的第一批推进到 seq 3,区别于缓存旧值的结果。 compensation_liveness 覆盖冷启动在 seq 1 中断后由另一个 worker 继续、链尾水位但尚未就绪的 过滤器、持有视图锁后释放且不发送信号,以及超过 max_append_walk 的根链在后台无预算追平。 故障注入只改列名,不改表名,避免 search_path 回退到 public 表。start_http 以 ctx.storage.clone() 启动 worker,并在关闭时以 30 秒上限等待任务结束。

迁移覆盖:merge_queue.requester nullable 列(UN-18)

历史表。 plan-20260910.md MW-05 已 DROP TABLE merge_queue;下列描述 UN-18 当时的加列迁移,不再是现行 schema。

m20260815_000100_merge_queue_requester 为 merge_queue 增加 nullable requester 列(无默认值、无回填、不修改既有行)。排队的合并由后台 worker 稍后执行,请求主体必须随队列项持久化,否则执行时没有自己的授权主体。本卡只加列:写入/读出链归 UN-20,NULL(legacy 行)的执行判定归 UN-17。

恢复路径按消费面状态区分(forward-only,运行时无 down 入口):

  • pre-consumer(UN-20 未发布,列恒为空):可由新迁移前滚删列。
  • post-consumer(列已在写入 requester):禁止无条件删列——会丢失授权主体与审计数据。只能保留列并停用消费方,或以新列替代并复制数据。

迁移模块内 #[cfg(test)] 覆盖:列为 nullable 且无默认值、既有行读回 NULL、隔离库内 down 删列后 up 可前滚回已发布状态。

写迁移测试时注意:单元测试库按 schema 隔离(search_path,见 src/jupiter/tests.rs),而 information_schema / pg_indexes 跨全部 schema,因此目录查询必须带 current_schema() 限定,否则会读到并发用例的表。

merge queue requester 读写链(UN-20;BRH-09 收口为必选认证身份)

自 BRH-09 起,/merge-queue/add 与 /merge-queue/retry/{cl_link} 改用 WriteActor(cookie 会话或 Mono PAT)提取必选请求者身份,鉴权先于入队:匿名请求固定返回 401,不再写入 requester = NULL 的新行。UN-20 早期或更早历史写入的 requester = NULL 存量行仍保留既有只读兼容与冻结指引。

链路:router → MonoApiService::{add_to_merge_queue_as, retry_merge_queue_item_as} → MergeQueueService::{add_to_queue_with_requester, retry_queue_item_with_requester} → storage。requester 与队列行在同一条插入/更新语句里落库——排队的合并稍后由后台 worker 执行,行存在而主体缺失就是一次没有主体的合并。

既有 storage 方法签名零变更:add_to_queue / retry_failed_item 保留并委派。语义差别值得记住:retry_failed_item(不知道主体)不动已记录的 requester,而 retry_failed_item_with_requester(link, None)(显式匿名)会把它清空。

读出面 get_requester(cl_link) -> Option<Option<String>>:外层 None = 没有该队列行,内层 None = 匿名或 UN-18 之前写入的 legacy NULL 行。执行时的主体判定由 UN-17 消费该读出面。

单测提示:jupiter::tests::test_storage 的 merge_queue_service 原本是 mock()(disconnected 连接),驱动队列链路会 panic;已改为与该 storage 共用同一测试库。

CI

.github/workflows/config-validation.yml runs formatting, Clippy, the compose-backed integration targets (including integration_website_auth under WEBSITE_IT=1), and the real website session check after checking out the website frontend sibling. Mega2 notification paths do not require a local SMTP dependency.

只读装配的零副作用比对(UN-30 / UN-43)

integration_authz_audit 的立论方式是前后对照,不是通读代码。播种走真实二进制(mega2 service http 起来再 SIGINT),因此迁移、init_monorepo() 写下的 refs 与对象全都真的发生过——手搓出来的库只包含我们想到的东西,而「零写入」恰恰是关于没想到的那些。

快照有七个面:schema(范围是除系统 schema 外的全部 schema)、每表内容摘要(整行转文本排序聚合后 md5,而不是行数——一次 UPDATE 不改变计数)、pg_sequences 当前值(被回滚的插入不留行却推进序列,那同样是一次写)、mega_refs 全行、三张对象表全行、对象存储目录逐文件散列,以及 MEGA_BASE_DIR + MEGA_CACHE_DIR 的逐文件指纹(vault 的 core_key.json 就在这一面里)。文件指纹是内容散列 + 尺寸 + 权限位 + mtime:一次「内容相同」的重写不会改变内容散列,却仍然是一次写,只有 mtime 能发现它。目录本身也收(路径 + 权限位),因此创建/删除/改名目录与只改目录权限都看得见。

用例分两幕:

  1. 本地对象存储:只读装配读根 ref 与授权源(这条路径同时用到 DB 与对象存储),前后七面全等。
  2. 需要 vault 的部署(UN-43):先用 config secret set 把两个对象存储凭据写进 vault,再切到 s3compatible,于是只读装配真的打开 vault。断言它拿到的是 UN-31 的只读句柄、denied_writes() 为 0,且 vault 表与 core key 文件一字未动——bootstrap 路径会轮换 runtime 凭据并回写 key 文件,那正是这一幕要排除的东西。用本地存储时 vault 根本不会被打开,「Vault 状态零变化」会退化成一句空话,所以第二幕不能省。

最后做两次量具校准:插入一行探针(快照必须变)、再原地改写同一行(行数不变、摘要必须变)。否则「前后相等」可能只是因为这份快照什么都没量到。

受限根目录产物的排除项写在 RESTRICTED_ROOTS 常量里,今天为空;留着是因为「排除了什么」必须是一份明写的清单,而不是某处 diff 里悄悄少掉的几行。匹配用路径前缀而不是子串——受限根目录是一个路径祖先,子串匹配既会误伤中间路径同名的文件,也会漏掉本该排除的;且比的是相对于受监视根的路径(受限根目录就是这样登记的),拿拼好的绝对路径去比前缀永远对不上,排除清单会变成一个从不生效的摆设。

这个 target 只有一个用例,且必须 --test-threads=1:它用 std::env::set_var 把数据库与对象存储指向本用例专属的库(.env.test 里的 MEGA_DATABASE__DB_URL 指向共享 admin 库,而环境变量优先级高于配置文件)。这条约束不是靠注释请求后来者小心,而是运行期强制:第二次构造 fixture 直接 panic 并说明原因——两个 fixture 会互相覆盖对方的数据库地址,而且谁都不会报错,于是比对会静悄悄地跑在别人的库上。

这一面量得到什么、量不到什么:快照收录的是「最终存在的条目」,因此创建后又删除的临时文件不会被发现;两个受监视根目录之外的写也不会。前者是快照法的固有边界(要抓它需要的是事件流而不是快照),后者是登记范围的选择。两条都写在这里,是因为一份不说明边界的「零副作用」证明会被读成比它实际更强的东西。

DB 模块覆盖:C 段信号与推送驱动投影(HP-32)

PushQueueService 在已提交轮次的 C 段索引结束后只向所属 Storage 的 ViewSignal 写入一个 Notify::notify_one 许可。该动作不等待 worker,也不查询 mega_view_* 表;索引成功、被后续同路径轮次跳过和索引失败的补偿路径都保留这一 通知。句柄在 PushQueueService 构造时注入,随后不再变更。detach 中无根树的 Done 路径与已挂载 ImportRepo 只更新 refs 的 Done 路径均不经过 C 段,根不前进, 因此不发送通知。缺省关闭 [views].enabled 时没有 worker 消费许可。

spawn_view_worker_with_round 同时等待周期 tick 与同一信号。worker 正在执行一轮时 到达的多个通知由 Notify 合并为一个许可,因此当前轮结束后只追加一轮;worker 不会 给自己发送信号。信号是进程内机制,其他副本通过周期补偿追平。

覆盖入口(进程级用例需要 docker compose ... --profile git up -d --wait,且 MEGA2_IT_SKIP_GIT_CLI 不得设置):

  • jupiter::service::push_queue_service::tests::c_segment_signal_after_done 覆盖 push、merge、attach、跳过和索引错误;
  • c_segment_signal_no_view_sql 记录 push 与 merge 的 SQL,断言没有 mega_view_ 表访问;
  • c_segment_signal_never_blocks_round 对 push、merge、attach 各自比较无 worker、worker 轮次暂停和任务终止时的有界 B3 返回;
  • jupiter::service::view_worker::tests::signal_permit_rules 通过实例级钩子在补偿轮开始前暂停,并在 per_candidate 包装中记录真实 catch_up 返回值,验证许可合并及不会自行续发;补偿轮本身不变;
  • out_of_order_signals_numbering 在三个独立 schema 中按不同顺序落地根提交并发送无内容信号,与第四个冷启动 schema 逐行比较根链及映射行;
  • integration_git_cli_view_push_driven_projection_rows 以 3600 秒周期排除后续 tick,覆盖 N=1、N>1、源路径外和排除目录的推送;净零推送确认根链及映射行不变;
  • integration_git_cli_view_enabled_trunk_path_regression 复用原有两个 trunk 用例的完整正文与断言,通过注册及关停前回调额外验证启用侧追平与 I3。两个进程级用例覆盖 start_http 启动 worker 与 SIGINT 关停等待 worker 的路径。

ER-05 检查点:sea-orm 的 metric 回调不记录 execute_unprepared,因此 c_segment_signal_no_view_sql 的 SQL 记录不能覆盖这类语句。push B3、merge B3、 C 段的生产路径及本卡新增生产代码均不调用它:blob_path_index.rs、 push_queue_storage.rs 无此调用,push_queue_service.rs 与 mono_storage.rs 的命中只在测试模块内。启用视图的物化链回归按 ADR-HP-11 重跑 N=1 三轮快进与 N>1 squash 对齐两例并增加 I3;其他缺省配置下的 trunk 用例仍由全量门覆盖。

旧 Capture 清除 schema(MTR-23)

cargo nextest run --test integration_traces -E "test(/^purge_schema_/)" 只通过真实迁移 runner 观察 catalog:三张 journal 表、其命名约束与 12 张旧表上的 *_legacy_write_fence trigger。实体级 db_contract 门另行验证 fence 的 purge_id 唯一外键及 active/inactive 下的 barrier 行为;该测试不执行任何清除或 DROP。

Legacy schema maintenance migrator (MTR-32)

jupiter::migration::traces_maintenance::TracesMaintenanceMigrator is the only migrator that carries drop_legacy_capture; the normal startup migrator keeps the historic add migration. The maintenance ledger is traces_maintenance_schema_migrations, written only after the single-transaction DROP succeeds. cargo test --test integration_traces -E "test(/^legacy_drop_guard_/)" is the black-box gate.

Review OpenAPI 缺席、写操作分类与 storage-only 快照守卫(BRH-10)

src/server/http_server.rs 抽出与 app() 共享单一真源的 build_openapi(config),并在 server::http_server::tests 中固定以下装配期回归守卫:

  • bot_routes_absent_from_review_openapi 与 anonymous_merge_route_absent_from_review_openapi:断言 review 与 storage-only 装配后的 OpenAPI 均不含 /bots 与 merge-no-auth。
  • review_write_operations_are_classified(默认特性,59 项)与 review_fastcdc_write_operations_are_classified(--features fastcdc,含 5 项 FastCDC media 写路由共 64 项):逐项核对 review OpenAPI 全部 POST/PUT/DELETE/PATCH 操作均归类为 actor、admin、ci-hmac、retired-410、read-via-post、lfs-token 或 lfs-grant,任何新增未分类写路由都会立即失败;非 OpenAPI 写面(/info/lfs 别名、raw /file/*、MST/2 三写入口、Git smart HTTP)随清单一并登记。
  • storage_only_route_snapshot:基于 config/config-storage-only.toml(oci.enabled=true、views.enabled=false、traces.enabled=false)断言 storage-only 37 路由集合与 BRH-01 基线 SHA-256(f8c9e0b872b711d6513699360cf390171283c366e95d75a5beb691267d7d1d60)完全一致(--features fastcdc 时另精确匹配 13 条 media 路由)。

验证命令:source .env.test && cargo test -p mega2 --lib 'server::' 与 source .env.test && cargo test -p mega2 --features fastcdc --lib 'server::'。

Review MST/2 与 FastCDC Media 逐端点匿名 401 运行时守卫(BRH-33)

src/server/http_server.rs 的 #[cfg(test)] 模块经完整装配 http_server::app() 对两类非 Phase 2 逐端点实测的 review 写入口执行匿名拒绝 401 回归守卫:

  • MST/2 三写入口(review、mst2.enabled=true、mst2.auth_token 已配置):review_mst2_resolve_rejects_anonymous_401(POST /api/v2/snapshots/resolve)、review_mst2_lease_renew_rejects_anonymous_401(POST /api/v2/snapshots/leases/{lease_id}/renew)、review_mst2_lease_release_rejects_anonymous_401(DELETE /api/v2/snapshots/leases/{lease_id})。
  • fastcdc media 五写入口(#[cfg(feature = "fastcdc")]):review_media_prepare_rejects_anonymous_401(POST /api/v1/lfs/libra/media/v1/manifests)、review_media_put_page_rejects_anonymous_401(PUT .../pages/{page_no})、review_media_seal_rejects_anonymous_401(POST .../seal)、review_media_upload_chunk_rejects_anonymous_401(PUT .../chunks/{chunk_hash})、review_media_finalize_rejects_anonymous_401(POST .../finalize)。

验证命令:source .env.test && cargo test -p mega2 --lib 'server::' 与 source .env.test && cargo test -p mega2 --features fastcdc --lib 'server::'。

GitHub sync operator status cursor projection (OX-109 / OX-53)

GET /api/v1/github-sync/bindings/{id}/status exposes the closed GithubSyncCursorStatusDto { last_pushed, in_flight_new_oid, generation } under cursor in both HTTP JSON and OpenAPI (#/components/schemas/GithubSyncCursorStatusDto), read from the same persisted github_sync_cursor snapshot used by write CAS with zero live SSH probes and zero cursor mutations (status_ai_cursor_http_shape, status_ai_cursor_openapi_shape).

Fake Q7 operator auth & stale-tip contract (OX-82)

tests/integration_github_sync.rs::ai_operator_auth_and_stale_tip_contract introduces FakeQ7OperatorClient (Q7 HTTP only, zero direct cursor access) and proves against live start_http + fake SSH that: (1) unauthenticated requests return 401, (2) cursor_reset-only scope requesting force returns 403, and (3) stale expected_remote_tip / expected_local_oid on cursor-reset or force return 409 without mutating the persisted cursor or sending receive-pack commands. Scope boundary (OX-108 / DEFER-OX-03): local Q7 contract feasibility only; does not implement or claim completion of any real external AI consumer (PT-16).

Fake Q7 operator park -> align -> reset sequence (OX-117)

tests/integration_github_sync.rs::ai_operator_park_align_reset_contract reuses FakeQ7OperatorClient against live start_http + real background GithubSyncWorker + fake SSH: the worker parks on a third remote OID (remote_diverged), the fake client reads parked over Q7 /status, stale-tip resets return 409 both before and after out-of-band remote alignment, a fresh aligned cursor-reset returns 200 with zero receive-pack commands, and subsequent /status reads idle with updated cursor.last_pushed and generation. Real external AI operator integration remains deferred under DEFER-OX-03.

Q4 periodic poll pure classification (OX-126 / OX-54 / OX-91 / OX-122 / OX-115 / OX-61 / OX-100 / OX-92 / OX-127 / OX-63 / OX-94 / OX-116 / OX-121 / OX-132 / OX-55 / OX-95 / OX-59)

ceres::github_sync::poller defines the pure, I/O-free PollClassifier::classify(&PollSnapshot, &AdvertisedOid) -> PollClassification interface (OX-126, classifier_type_is_pure), existing-cursor three-tip classifier (OX-54, classify_existing_three_tips), empty-cursor classifiers with and without persisted intent (OX-91 classify_empty_without_intent, OX-122 classify_empty_with_persisted_intent), pinned host-key read-only SSH advertiser with bounded cancel (OX-115, poll_advertise_auth_timeout_cancel), single-round read-only verdict poll_once_classify (OX-61, poll_once_advertise_and_classify, verifying zero cursor writes and zero receive-pack commands), atomic poll self-complete cursor CAS apply_poll_self_complete / poll_self_complete_cas (OX-100, poll_self_complete_cas_and_no_resend, poll_self_complete_worker_race), sealed cursor-only third-OID park with intent DivergedWithIntent / PollParkCursorWriter / apply_poll_park_diverged_with_intent (OX-92, poll_third_oid_parks_preserving_intent, diverged_with_intent_cursor_only_signature), poll-only third-OID park without intent DivergedWithoutIntent / PollParkWithoutIntentCursorWriter / apply_poll_park_diverged_without_intent (OX-127, poll_third_oid_without_intent_parks, preserving last_pushed with zero intent/outbox creation), eventless parked -> idle recovery apply_poll_recover_parked_to_idle / poll_recover_parked_without_intent_cas (OX-63, poll_parked_returns_to_last_pushed, rejecting active in_flight, stale generation, and repeat polls), pure parked-intent retry eligibility RetryCandidate / classify_parked_intent_retry (OX-94, parked_intent_retry_eligibility, containing no idle variant), identity/generation-fenced parked -> in_flight retry CAS apply_poll_parked_intent_retry / poll_promote_parked_intent_cas (OX-116, poll_parked_intent_retry_cas, preserving exact original command identity without creating new intents), exhaustive single-round verdict dispatcher dispatch_poll_verdict / run_poll_round (OX-121, poll_round_dispatch_self_and_diverged), parked RemoteUnchanged recovery dispatch (OX-132, poll_round_unchanged_recovery_dispatch, poll_round_error_no_git_write, keeping advertise/CAS errors terminal with zero Git writes), bounded github_sync.poll_interval_seconds config (OX-55, config::tests::github_sync_poll_interval_validation, default 60, range 10..=3600, restart-required, backward-compatible when omitted), bounded eligible-binding tick selector PollTickSelector (OX-95, eligible_cadence_and_bound), and singleton HTTP service lifecycle wiring GithubSyncPollerService / spawn_github_sync_poller_task (OX-59, poll_service_cadence_shutdown_and_disabled, poll_shutdown_blocked_advertisement_joins, proving cadence, disabled no-op, singleton start, and bounded join on blocked SSH advertisement).

Isolated live GitHub acceptance runner (OX-21..OX-234 / OX-237 / OX-372..OX-379 / OX-238 / OX-05)

Test-tier boundary (OX-05): Default cargo gates (cargo test --all, focused cargo test -p mega2 --test integration_github_sync, and loopback SSH/REST mocks) do NOT count as live GitHub acceptance; real GitHub acceptance remains strictly gated on explicit MEGA_TEST_GITHUB_LIVE=1 + OX-375 durable accepted receipt in OX-24 (first push) and OX-06 (same-run two-push + terminal cleanup), both of which are still pending live execution:

  • Focused & loopback suites (default / offline, zero GitHub traffic): source .env.test && cargo test -p mega2 --test integration_github_sync -- --test-threads=1 (covers Q1–Q8 product paths, loopback SSH LoopServer, fake Q7 operator contract, Q4 poller, and all 73 Track 8 live_* offline/loopback harness guards).
  • Isolated live runner (scripts/github-sync-live.sh, explicit MEGA_TEST_GITHUB_LIVE=1 only):
    • Mode-0600 live proof permission guard (OX-237, live_proof_file_uses_private_mode);
    • Durable operator preflight wait marker (OX-372, --persist-operator-preflight-wait-marker), 300s bounded monotonic wait & restart recovery (OX-385, --evaluate-operator-preflight-wait-deadline), schema v1 & fingerprint equality validator (OX-373, --validate-operator-preflight-schema-v1), UTC created_at bounds (OX-386, --validate-operator-preflight-created-at), semantic manifest/authority/scope matcher (OX-374, --match-operator-preflight-authority), and durable immutable accepted receipt gate (OX-375, --accept-operator-preflight-receipt, --verify-operator-preflight-accepted-receipt);
    • Sanitized UUID-scoped evidence bundle writer & verifier (OX-376, --write-evidence-archive, --verify-archive <dir>);
    • Atomic mode-0600 operator-done marker (OX-377, --write-operator-done-marker, --validate-operator-done-marker) and wake-only proof recheck (OX-378, --held-open-marker-wake-recheck);
    • Sole live REST/SSH dispatch (OX-238, --worker-first-push / --worker-two-push gated on MEGA_TEST_GITHUB_LIVE=1 + OX-375 receipt, PAT REST-only, deploy key SSH-only, zero runner DELETE paths);
    • Sole safe terminal exit gate (OX-379, --terminal-archive-exit-gate, requiring same-UUID OX-210 PASS proof + verified OX-376 archive before exit 0 and blocking old-UUID crash replay as PASS).

scripts/github-sync-live.sh isolates live GitHub acceptance away from standard cargo test loopback gates: missing or non-"1" MEGA_TEST_GITHUB_LIVE exits non-zero at guard_stage=opt_in with zero REST/SSH requests, and live modes without a durable OX-375 accepted receipt fail closed at guard_stage=dispatch before any network traffic (OX-21, live_opt_in_isolation); after explicit opt-in, missing or whitespace-only MEGA_TEST_GITHUB_TOKEN fails closed at guard_stage=credentials naming only the variable without echoing any secret (OX-119, live_credentials_preflight_no_requests), MEGA_TEST_GITHUB_NAMESPACE is strictly validated as a single ASCII owner slug ^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$ without echoing raw values (OX-149, live_namespace_syntax_preflight), MEGA_TEST_GITHUB_NAMESPACE_KIND is strictly gated to personal or org before any network traffic (OX-147, live_namespace_kind_guard), pure route selection maps personal to POST /user/repos and org to POST /orgs/{namespace}/repos with zero REST/SSH requests (OX-97, live_namespace_route_selection), build_run_repo_identity generates a fresh per-run UUIDv4 repository name and immutable expected owner/name identity input without network I/O or DELETE capability (OX-150, live_unique_repo_name_and_identity_input), probe_personal_identity performs a read-only GET /user probe in personal mode using the same PAT (env-only, never argv/logs), rejecting non-200/missing-login/malformed-JSON before any repo POST (OX-148, live_personal_identity_probe_before_create), verify_personal_owner_match verifies ASCII case-insensitive equality between probed PAT login and configured personal namespace, promoting GitHub's canonical login into EXPECTED_OWNER or failing closed with zero POSTs (OX-146, live_personal_namespace_matches_token_owner), create_private_empty_repo sends private=true, auto_init=false using OX-97/OX-150, accepting only HTTP 201 for OX-42 handoff and failing closed on non-201 without advancing to deploy-key/worker stages (OX-19, live_repo_create_status), pure offline guard_repo_identity_core_from_stdin accepts only source=create_201 HTTP 201 payloads matching positive integer id, ASCII case-insensitive owner.login, full_name, and OX-150 UUID name while rejecting non-201 and pre-create manifests (OX-42, live_repo_identity_payload_guard), guard_repo_identity_proof_from_stdin extends RepoIdentityCore strictly with the same-run create=201 non-empty node_id to seal RepoIdentityProof while rejecting GET payloads, substituted node IDs, and cross-run forgery (OX-225, live_repo_create_node_id_proof), guard_repo_get_payload_from_stdin verifies read-only GET HTTP 200 payloads strictly against a caller-supplied confirmed create=201 RepoIdentityProof (matching positive integer repo_id, canonical owner, full_name, and UUID name) while returning null with zero network I/O whenever the confirmed create=201 proof is missing or any field mismatches (OX-141, live_repo_get_payload_requires_confirmed_201), guard_manual_cleanup_target_from_stdin binds this run's create=201 proof (+ optional OX-141 GET verification) to the expected run UUID to produce an immutable operator-only ManualCleanupIdentityTarget (runner_delete_allowed=false) while rejecting bare repo names, GET-self-reported IDs, and cross-run proof reuse (OX-98, live_cleanup_target_rejects_reuse), register_deploy_key_adapter_from_stdin generates a run-scoped Ed25519 identity under a 0700 run directory (0600 private key), posts a writable (read_only=false) deploy key strictly against an OX-98 target using fixture-only PAT headers, and matches the public key reloaded into the product SSH worker hold (OX-22, live_deploy_key_matches_held_key), cleanup_local_private_key_for_run (--cleanup-local-private-key --run-uuid <uuid>) provides the idempotent run-scoped local private-key deletion primitive that isolates other runs, preserves the run manifest on failure, and sends zero remote REST requests (OX-23, live_fixture_local_private_key_cleanup), cleanup_local_vault_secret_for_run (--cleanup-local-vault-secret --run-uuid <uuid>) provides the independent idempotent run-scoped isolated vault-secret deletion primitive preserving other runs and this run's manifest with zero remote REST requests (OX-204, live_fixture_local_vault_secret_cleanup), guard_held_open_failure_handoff_from_stdin (--held-open-failure-handoff) provides the held-open live case failure/panic compensation wrapper that preserves original FAIL across REST/SSH/GS-15/panic errors, enforces release of both DB and file locks prior to compensation wait, verifies restricted 0600/0700 manifest permissions, and delivers only sanitized run_uuid and manifest_path to the named operator (OX-39, live_held_open_failure_guard), build_precreate_manifest_identity_draft_from_stdin (--build-precreate-manifest-draft) constructs the pre-POST fixture identity manifest draft strictly from preflight-verified OX-97/OX-146/OX-150 inputs with non-reusable run_uuid, namespace_kind, canonical_owner, unique UUID repo_name, and UTC RFC 3339 created_at (OX-129, live_manifest_precreate_identity), build_precreate_manifest_safe_dto_from_stdin (--build-precreate-manifest-safe-dto) extends OX-129 into a closed manifest DTO carrying only the pending deploy key SHA-256 public fingerprint and two unconfirmed ID slots while strictly excluding test PATs, Ed25519 private keys, and raw REST bodies (OX-207, live_manifest_precreate_safe_fields), persist_precreate_manifest_gate_from_stdin (--persist-precreate-manifest-gate) exclusively creates the 0700 run directory (rejecting collisions), fsyncs the parent directory, writes a <=0600 temp file, fsyncs temp file data, atomically renames manifest.json, and fsyncs the run directory before permitting OX-19 repo create POST (OX-143, live_manifest_persisted_before_create), commit_create_201_repo_manifest_from_stdin (--commit-create-201-manifest) atomically persists repo_id, repo_node_id, and repo_id_state=confirmed_201 from an OX-225 create=201 proof into the matching OX-143 manifest with file/dir fsync while rejecting non-201 proofs, identity mismatches, and conflicting replays (OX-144, live_create_201_manifest_commit), admit_confirmed_repo_cleanup_target_from_stdin (--admit-confirmed-repo-target) enforces crash/restart admission so write/fsync/rename faults stay strictly unconfirmed, half-confirmed or GET-promoted records are rejected, and only a complete persisted OX-144 confirmed_201 manifest admits CleanupTarget (OX-226, live_confirmed_repo_crash_admission), init_key_not_attempted_manifest_from_stdin (--init-key-not-attempted-manifest) atomically initializes durable not_attempted deploy-key state on a confirmed OX-144/OX-226 repo manifest while forbidding rollback from non-initial states and sending zero key POSTs (OX-168, live_key_not_attempted_manifest), acquire_key_post_write_ahead_permit_from_stdin (--acquire-key-post-write-ahead-permit) runs a cross-process flock one-time CAS over OX-168 not_attempted, durably persisting unknown_after_request before permitting a single key POST while blocking losers, restarts on unknown/confirmed, and persistence failures with zero key POSTs (OX-160, live_key_post_write_ahead_gate, live_key_post_write_ahead_crash), validate_key_201_candidate_from_stdin (--validate-key-201-candidate) validates HTTP 201 positive integer key IDs strictly from OX-160-permitted key POST responses bound to the same run_uuid/repo_id to seal Key201Candidate while rejecting GET sources, non-201 statuses, non-positive/bool IDs, and cross-run/cross-repo responses (OX-169, live_key_201_candidate_validation), commit_key_201_confirmation_from_stdin (--commit-key-201-confirmation) atomically commits confirmed_201 + key_id from a matching OX-169 candidate with file/dir fsync (runner_delete_allowed=false), leaving unknown_after_request intact on durability faults and rejecting conflicting key ID replays (OX-163, live_key_201_durable_confirmation, live_key_201_confirmation_crash), classify_key_non201_response_from_stdin (--classify-key-non201-response) conservatively keeps unknown_after_request across all non-201 HTTP responses (401/403/422/other) with zero automatic key DELETE permits and zero key-absence conclusions (OX-166, live_key_non201_stays_unknown), seal_key_ambiguous_result_from_stdin (--seal-key-ambiguous-result) preserves unknown_after_request across POST timeout, response loss, 201 confirmation persistence failure, and GET self-reported key IDs without GET promotion, POST retry, automatic DELETE, or absence claims (OX-170, live_key_ambiguous_create_result), diagnose_unconfirmed_repo_readonly_from_stdin (--diagnose-unconfirmed-repo-readonly) issues only a single read-only GET /repos/{owner}/{name} for an unconfirmed repo create and unconditionally returns ManualCleanupRequired for 200, 404, or any error with zero POST/DELETE requests (OX-145, live_lost_create_response_read_only_diagnostic), revalidate_confirmed_repo_readonly_from_stdin (--revalidate-confirmed-repo-readonly) requires a persisted OX-144 confirmed_201 repo ID, issues only a read-only GET /repos/{owner}/{name}, and revalidates HTTP 200 strictly via OX-141 while staying blocked on 404, errors, or identity drift with zero DELETE calls (OX-130, live_confirmed_create_get_revalidates_identity), provision_fixture_mock_from_stdin (--provision-fixture-mock) persists write-ahead unknown_after_request before repo/key POSTs, stops all downstream writes/worker start/live PASS/automatic DELETE on 401/403/422 or ambiguous failures, refuses duplicate POST retries on durable unknown_after_request, and keeps real-network dispatch blocked until OX-238 (OX-99, live_fixture_permission_denial_partial_cleanup), and cleanup_local_test_db_for_run (--cleanup-local-test-db --run-uuid <uuid>) provides the idempotent run-scoped isolated test DB row cleanup helper preserving other runs and returning status=blocked on DB faults (OX-134, live_cleanup_only_run_db_scope), while literal --cleanup-only --run-uuid <uuid> (run_cleanup_only_for_run) admits ONLY a matching OX-143 same-run manifest, delivers one UUID-scoped LocalCleanupPlan to the local coordinator invoking OX-23/OX-204/OX-134 in order, propagates coordinator or helper failures while preserving manifest.json and the run directory, and sends zero external REST requests (OX-128, live_cleanup_only_run_local_scope), and verify_local_absence_from_stdin (--verify-local-absence) independently re-checks the same-UUID private key, vault secret, and test DB row in read-only mode with zero network handles before sealing LocalCleanupProof (OX-212, live_same_case_local_absence_verify), and guard_first_advertisement_from_stdin (--guard-first-advertisement) pairs with ceres::github_sync::send_pack::advertise to normalize legal empty-repo no-refs sentinels to ZERO_OID while rejecting non-zero refs/heads/main or malformed pkt-lines before any B3 change set or SSH write (OX-131, live_first_advertisement_guard), and guard_first_pre_send_from_stdin (--guard-first-pre-send) consumes OX-131 together with a real B3 candidate OID-1, visible pending github_sync_outbox row, and have=[] to emit FirstPushPreSendPermit for OX-156 while blocking non-zero remote main, missing/non-pending outbox, or non-empty have with zero ReceivePack::write_pack calls (OX-124, live_first_pre_send_guard), and guard_first_send_dispatch_from_stdin (--guard-first-send-dispatch) enforces that first-push delivery requires a valid OX-124 permit, routes exclusively through ReceivePack::write_pack with ref-update pkt-line + flush strictly preceding PACK bytes, and forbids direct ref-update or pack bypass writes (OX-156, live_first_send_dispatch_guard), and build_first_push_receipt_from_stdin (--build-first-push-receipt) seals VerifiedFirstPushReceipt strictly from an OX-156 same-run dispatch, unpack=ok, exact single ok refs/heads/main, and receive-pack exit=0 uniformly across mock and real SSH transports (OX-213, live_first_push_typed_receipt), and guard_incremental_pre_send_from_stdin (--guard-incremental-pre-send) consumes ONLY a same-run OX-213 receipt together with a real second B3 OID-2 != OID-1, visible pending outbox row, and exact have=[OID-1] to seal IncrementalPushPreSendPermit with zero second write_pack calls on gate failure (OX-125, live_incremental_pre_send_guard), and build_second_push_receipt_from_stdin (--build-second-push-receipt) seals VerifiedSecondPushReceipt strictly when manifest run_uuid/repo identity, same-run OX-125 permit, SSH exit=0, GS-15 unpack=ok, exact single ok refs/heads/main, and reported OID-2 all match (OX-382, live_second_push_verified_receipt_accepts_positive_report, live_second_push_verified_receipt_rejects_ng_or_transport_failure), and guard_incremental_send_dispatch_from_stdin (--guard-incremental-send-dispatch) enforces that incremental second-push delivery requires a valid OX-125 permit, routes exclusively through ReceivePack::write_pack with <OID-1> <OID-2> refs/heads/main pkt-line + flush strictly preceding PACK, and rejects any direct ref-update or pack bypass (OX-159, live_incremental_send_dispatch_guard), and guard_operator_repo_target_from_stdin (--guard-operator-repo-target) admits ONLY same-run confirmed 201 repo_id/node_id + active OX-211 exclusive window + immediate pre-delete GET 200 to seal RepoDeleteTargetProof with zero runner DELETE (OX-215, live_operator_repo_target_guard), and guard_operator_repo_delete_transcript_from_stdin (--guard-operator-repo-delete-transcript) consumes ONLY a same-run OX-215 proof with exact /repos/{owner}/{repo} targeting, OX-203 operator identity, HTTP 204, zero redirects, and 1 attempt to seal RepoDeleteTranscript (proves_repo_absent=false, zero runner DELETE) (OX-219, live_operator_repo_delete_transcript_guard), and guard_key_delete_transcript_from_stdin (--guard-key-delete-transcript) validates same-run manifest UUID, persisted 201 numeric key_id, OX-203 operator login, HTTP 204, zero redirects, and 1 attempt to seal KeyDeleteTranscript (key_cleanup_evidence_generated=false, zero runner DELETE) (OX-227, live_key_delete_transcript_guard), and verify_key_absence_from_stdin (--verify-key-absence) consumes same-UUID confirmed manifest + OX-227 transcript + OX-130 repo revalidation and issues a single read-only GET /repos/{owner}/{repo}/keys/{key_id} (zero DELETE) sealing KeyCleanupEvidence strictly on 404 while blocking on 401/403/200 (OX-40, live_same_case_key_absence_verify), and admit_repo_post_delete_read_permit_from_stdin (--admit-repo-post-delete-read-permit) combines same-UUID OX-40 KeyCleanupEvidence, OX-219 RepoDeleteTranscript, still-active OX-211 exclusive window, continuous OX-203 operator identity, and owner/admin authority into RepoReadPermit (proves_repo_absent=false, zero runner DELETE) (OX-228, live_repo_post_delete_read_permit), and verify_repo_absence_from_stdin (--verify-repo-absence) consumes OX-228 RepoReadPermit to re-check continuous operator auth/scopes, observe no-redirect GET /repos/{owner}/{repo} == 404, and execute read-only GraphQL node(id:) trace on persisted repo_node_id, sealing RepoCleanupEvidence only when all hold with zero runner DELETE (OX-41, live_same_case_repo_absence_verify), and evaluate_same_case_terminal_gate_from_stdin (--evaluate-same-case-terminal-gate) requires all three same-UUID restricted proofs (OX-40, OX-41, OX-212), treats operator done markers strictly as wake-only, preserves OX-39 original FAIL outcomes, and emits TerminalPassProofCandidate (with process exit 0 still gated by OX-376/OX-379) only when all three proofs and positive push outcome hold (OX-210, live_same_case_terminal_gate), and held_open_deadline_gate_from_stdin (--held-open-deadline-gate) persists a create-only 0600 fsynced 1800s deadline on first entry into AwaitingHumanCleanup, tracks elapsed time via monotonic clock, reloads the persisted deadline on restart without resetting, and fails FAIL/blocked on expiration while preserving manifest.json and never inferring remote absence (OX-240, live_held_open_deadline_survives_restart_and_times_out), and run_two_push_saga_mock_from_stdin (--two-push-saga-mock) + verify_live_evidence_file (--verify-evidence <path>) implement the single-invocation same-run two-push saga (FirstPushProof -> same-UUID OX-125 permit -> OX-382 SecondPushProof -> AwaitingHumanCleanup), atomic 0600 $OX_LIVE_RUN_DIR/live-proof.json persistence, and explicit-path proof verification (OX-234, live_two_push_single_invocation_saga_and_proof).

歧义 Live Run 人工补偿手册与五资源证据模板(OX-155)

当隔离 live GitHub 验收出现远端或进程状态歧义时,原 run 永久保持 FAIL/blocked,绝不自动重发 POST/DELETE,也不得由 GET 自报数字 ID、可编辑日志或私仓裸 GET 404 补造成功。具名操作员须依据 0700 run 目录下 0600 持久 manifest(OX-143/OX-144/OX-160/OX-163)在 runner 外核查并收口全部五项资源,随后以全新 run UUID 与新私有仓库重跑验收。

1. 四类 Blocked 入口与处置边界

编号 歧义入口 触发条件 0600 Manifest 保留字段(未确认项显式 unknown) Runner 禁止动作 具名操作员人工补偿动作
SC-1 repo POST unknown repo 创建 POST 超时、响应丢失或 OX-144 201 确认持久失败 run UUID、canonical_owner、repo_name、namespace_kind、created_at、repo_id_state=unconfirmed(repo_id=unknown)、key_id_state=unconfirmed、original_failure_reason 零自动重发 repo POST、零自动 DELETE、不凭 OX-145 只读 GET 200/404 生成创建证明 操作员在 runner 外核实远端同名仓库是否已创建,若存在则核对创建者与名称后手工删除,并记录五资源证据;原 run 保持 FAIL/blocked,以新 run UUID 重跑
SC-2 key POST unknown OX-160 write-ahead 已落盘 unknown_after_request,但 key POST 返回非 201(OX-166)、超时/丢包或 OX-163 确认持久失败(OX-170) run UUID、canonical_owner、repo_name、namespace_kind、已确认 repo_id / repo_node_id、key_id_state=unknown_after_request(key_id=unknown)、deploy_key_public_fingerprint、original_failure_reason 零重启重发 key POST、零自动 key DELETE、拒绝以 GET 自报 key ID 升级 confirmed_201、不宣称 key 缺席 操作员按 deploy_key_public_fingerprint 在 runner 外列查该确认 repo_id 下的 deploy keys,手工删除匹配 key(如有)再按 key→repo 顺序删除测试私仓,填报五资源证据;原 run 保持 FAIL/blocked,以新 run UUID 重跑
SC-3 DELETE unknown 操作员在 runner 外执行 key/repo DELETE 时超时、5xx 或回执不明 run UUID、canonical_owner、repo_name、namespace_kind、已确认 repo_id / repo_node_id、已确认或 unknown 的 key_id、original_failure_reason 零由私仓裸 GET 404 或可编辑文本日志单方宣称缺席并放行 操作员凭独立权威会话/命名空间查询核实 key 与 repo 是否真实消除;未决资源标为 pending_operator 并继续保持 blocked,待确认消除且本地三项归零后以新 run UUID 重跑
SC-4 SIGKILL / 断电硬崩溃 进程遭遇不可捕获 SIGKILL、OOM 或主机断电 重启后以磁盘 0600 manifest.json 权威版本为准:保留 run UUID、canonical_owner、repo_name、namespace_kind、已持久的确认数字 ID(未持久项仍为 unknown)及 crash_recovery=blocked 零自动恢复推送、零自动重发 POST/DELETE、零自动清除源 manifest 操作员先定位磁盘 manifest 版本,核清远端 deploy key 与 repo,再按同 run UUID 执行本地清理(临时私钥、隔离 vault secret、run-scoped 测试 DB)并填写五资源证据;原 run 永久 FAIL/blocked,清完后仅以新 run UUID 重跑

2. 具名 Mock Manifest 演练夹具(OX-155-M1..OX-155-M4)

  1. OX-155-M1(repo POST unknown): { "run_uuid": "15500001-1111-4222-8333-444444444444", "namespace_kind": "personal", "canonical_owner": "Alice-Dev", "repo_name": "mega2-gs-live-15500001-1111-4222-8333-444444444444", "repo_id_state": "unconfirmed", "repo_id": "unknown", "key_id_state": "unconfirmed", "key_id": "unknown", "original_failure_reason": "repo_post_response_lost" } → 演练核验:blocked、零自动重发 POST/DELETE、五资源槽齐备、提示使用新 run UUID 重跑。
  2. OX-155-M2(key POST unknown): { "run_uuid": "15500002-1111-4222-8333-444444444444", "namespace_kind": "personal", "canonical_owner": "Alice-Dev", "repo_name": "mega2-gs-live-15500002-1111-4222-8333-444444444444", "repo_id_state": "confirmed_201", "repo_id": 155002, "key_id_state": "unknown_after_request", "key_id": "unknown", "deploy_key_public_fingerprint": "SHA256:+DiY3wvvV6TuJJhbpZisF/zLDA0zPMSvHdkr4UvCOqU", "original_failure_reason": "key_post_timeout" } → 演练核验:blocked、零自动重发 POST/DELETE、拒绝 GET 自报 key ID 升级、五资源槽齐备、提示使用新 run UUID 重跑。
  3. OX-155-M3(DELETE unknown): { "run_uuid": "15500003-1111-4222-8333-444444444444", "namespace_kind": "org", "canonical_owner": "Acme-Org", "repo_name": "mega2-gs-live-15500003-1111-4222-8333-444444444444", "repo_id_state": "confirmed_201", "repo_id": 155003, "key_id_state": "confirmed_201", "key_id": 888155, "original_failure_reason": "operator_delete_timeout" } → 演练核验:blocked、拒绝私仓裸 GET 404 或可编辑日志单方解除 blocked、零自动重发 POST/DELETE、五资源槽齐备、提示使用新 run UUID 重跑。
  4. OX-155-M4(SIGKILL / 断电): { "run_uuid": "15500004-1111-4222-8333-444444444444", "namespace_kind": "personal", "canonical_owner": "Alice-Dev", "repo_name": "mega2-gs-live-15500004-1111-4222-8333-444444444444", "repo_id_state": "confirmed_201", "repo_id": 155004, "key_id_state": "unknown_after_request", "key_id": "unknown", "original_failure_reason": "sigkill_hard_crash" } → 演练核验:blocked、零自动重发 POST/DELETE、五资源槽齐备、原 run 永久 FAIL/blocked 并提示以新 run UUID 重跑。

3. 具名操作员五资源证据模板(runner 外填写)

序号 资源项 权威定位标识(来自 0600 manifest) 清理/核验状态(cleaned / pending_operator / not_created_verified) 具名操作员、UTC 时间戳与独立证据引用(禁止凭裸私仓 404 或可编辑日志结案)
1 远端私有仓库(repo) run UUID + canonical_owner/repo_name + repo_id(或 unknown) <status> <operator> / <UTC RFC 3339> / <authoritative delete/list proof>
2 远端 deploy key run UUID + repo_id + key_id(或 unknown)+ deploy_key_public_fingerprint <status> <operator> / <UTC RFC 3339> / <authoritative delete/list proof>
3 本地临时私钥 <run_root>/<run_uuid>/id_ed25519 <status> <operator> / <UTC RFC 3339> / OX-23 cleanup + absence check>
4 隔离 vault secret <vault_root>/<run_uuid>/ssh_key.secret <status> <operator> / <UTC RFC 3339> / OX-204 cleanup + absence check>
5 run-scoped 测试 DB <run_uuid> 对应测试数据库/表行 <status> <operator> / <UTC RFC 3339> / OX-134 cleanup + absence check>

终态铁律: 原歧义 run 永不从 FAIL/blocked 改写为 PASS;全部五项资源由具名操作员清零并留档后,必须启动带全新 run UUID 与新私有仓库的新 live run 重新验收。

具名操作员手工删除前独立身份与权限 Preflight 手册(OX-203)

在任何真实 GitHub POST /user/repos 或 POST /orgs/{org}/repos 发出之前,具名人类操作员必须在与 runner 完全隔离的独立 shell 完成自身凭据、账号与目标 namespace 权限 preflight,并产出两份 mode 0600 的脱敏 JSON 工件(operator-preflight.expected.json 与 operator-preflight.json),供 OX-372/OX-385/OX-373/OX-386/OX-374/OX-375 校验放行。本手册不赋予 runner 任何 REST DELETE 能力。

1. 凭据隔离铁律

  • 具名操作员仅从本地受限文件 OX_OPERATOR_TOKEN_FILE(权限 0600)读取自己的 classic PAT;计算 token_fingerprint_sha256 时仅移除单个可选末尾 \r\n 或 \n(不做其他空白 trim),再对精确 bearer token 字节取 64 位小写 SHA-256。
  • 严禁继承 runner 环境变量 MEGA_TEST_GITHUB_TOKEN。
  • 严禁继承 GH_TOKEN、GITHUB_TOKEN 或本地 gh auth 缓存(执行前须 unset MEGA_TEST_GITHUB_TOKEN GH_TOKEN GITHUB_TOKEN)。
  • Token 原文、完整 Authorization header 与任何 secret 绝不得出现在命令行 argv、终端日志、operator-preflight.expected.json、operator-preflight.json、operator-authority-evidence.json 或可提交计划证据中。

2. Step A(API 请求前):生成 Trusted Input $OX_LIVE_RUN_DIR/operator-preflight.expected.json(mode 0600)

发出任何 GET /user 或 scope 查询请求前,操作员在独立 shell 依据 OX-143 持久化 manifest 的 run_uuid、预先声明的 MEGA_TEST_GITHUB_EXPECTED_OPERATOR_LOGIN、MEGA_TEST_GITHUB_NAMESPACE_KIND(personal|org)、MEGA_TEST_GITHUB_NAMESPACE、带外核实的 namespace_authority 与 OX_OPERATOR_TOKEN_FILE 字节指纹,原子写入 mode 0600 的 $OX_LIVE_RUN_DIR/operator-preflight.expected.json。严禁由 /user 或 X-OAuth-Scopes 响应或事后复制 operator-preflight.json 生成该文件。

精确 9 字段(禁止未知字段、禁止 secret 原文):

{
  "schema_version": 1,
  "run_uuid": "<same-run OX-143 manifest UUID>",
  "operator_login": "<canonical MEGA_TEST_GITHUB_EXPECTED_OPERATOR_LOGIN>",
  "namespace_kind": "personal | org",
  "namespace_owner": "<canonical owner slug>",
  "namespace_authority": "personal-owner | org-admin-create-delete-verified",
  "scopes": ["delete_repo", "repo"],
  "token_fingerprint_sha256": "<64-hex lowercase SHA-256 of bearer token bytes>",
  "created_at": "<UTC RFC 3339 generated BEFORE /user API request>"
}

3. Step B(Org Namespace 专属,真实 repo POST 前):生成 $OX_LIVE_RUN_DIR/operator-authority-evidence.json(mode 0600)

  • personal namespace: 由 GET /user 返回的 login 与 expected owner 相等证明 namespace_authority=personal-owner(不要求 org-only 权限证据文件)。
  • org namespace: 仅 X-OAuth-Scopes 名称不足以证明组织内创建/删除私仓权限;具名操作员须在真实 repo POST 前额外写入 mode 0600 的 $OX_LIVE_RUN_DIR/operator-authority-evidence.json:
    {
      "run_uuid": "<same-run UUID>",
      "operator_login": "<canonical operator login>",
      "namespace_kind": "org",
      "namespace_owner": "<canonical org slug>",
      "authority": "org-admin-create-delete-verified",
      "verified_at": "<UTC RFC 3339 <= expected.created_at>",
      "source_refs": [
        { "file": "org-membership-admin.redacted.json", "sha256": "<64-hex>" },
        { "file": "org-private-repo-create-policy.redacted.json", "sha256": "<64-hex>" },
        { "file": "org-repo-delete-policy.redacted.json", "sha256": "<64-hex>" }
      ]
    }
    source_refs 仅包含脱敏证据文件名与 SHA-256,不含凭证;runner 仅按 OX-375/OX-376 核验文件、schema、权限、同 run 身份绑定与文件哈希,底层权限充分性由 OX-118 人工独立复核。

4. Step C(独立身份查询):调用 GET /user 并原子写入 $OX_LIVE_RUN_DIR/operator-preflight.json(mode 0600)

使用 OX_OPERATOR_TOKEN_FILE 同一 classic PAT 发起只读 GET /user(禁跟随 3xx redirect,凭据经 stdin/文件传入 Python 标准库 urllib.request,绝不进 argv),校验响应账号身份与 X-OAuth-Scopes 明示 repo 与 delete_repo(排序去重后精确为 ["delete_repo", "repo"],缺任一项或含额外未授权 scope 均拒绝),再通过同目录临时文件 + fsync + 原子 rename 写入 mode 0600 的 $OX_LIVE_RUN_DIR/operator-preflight.json(精确 10 字段,禁止未知字段与 token/header/secret 原文):

{
  "schema_version": 1,
  "run_uuid": "<same-run UUID>",
  "repo_owner": "<manifest canonical owner>",
  "repo_name": "mega2-gs-live-<run_uuid>",
  "namespace_kind": "personal | org",
  "operator_login": "<login from GET /user>",
  "namespace_authority": "personal-owner | org-admin-create-delete-verified",
  "scopes": ["delete_repo", "repo"],
  "token_fingerprint_sha256": "<64-hex lowercase SHA-256>",
  "created_at": "<UTC RFC 3339 >= expected.created_at>"
}

任一账号、namespace 权限/作用域不明、鉴权失败、expected 与 artifact 错配或凭证来源混入 runner/GH_TOKEN/GITHUB_TOKEN 时,禁止任何 live POST 与 OX-209,旧 run 保持 blocked。

5. OX-203 七分支脱敏桌面演练矩阵

分支 脱敏输入与模拟回包 预期结论
OX-203-B1 独立 OX_OPERATOR_TOKEN_FILE,/user 返回 Alice-Dev 匹配 personal owner,X-OAuth-Scopes: repo, delete_repo,expected 与 artifact 两份 schema 精确匹配 PASS(允许进入 OX-373..375)
OX-203-B2 /user 返回 Bob-Other 与 personal owner Alice-Dev 不匹配 FAIL / blocked(禁 live POST 与 OX-209)
OX-203-B3 X-OAuth-Scopes: delete_repo(缺 repo) FAIL / blocked
OX-203-B4 X-OAuth-Scopes: repo(缺 delete_repo) FAIL / blocked
OX-203-B5 X-OAuth-Scopes: repo, delete_repo, admin:org(出现额外 scope) FAIL / blocked
OX-203-B6 expected 与 artifact 的 operator_login / token_fingerprint_sha256 / scopes 不一致 FAIL / blocked
OX-203-B7 凭证来源混入 runner MEGA_TEST_GITHUB_TOKEN、GH_TOKEN、GITHUB_TOKEN 或 gh auth cache FAIL / blocked

操作员同 Run 远端目标身份核对清单与脱敏证据表(OX-209)

在通过 OX-203 操作员独立凭据与权限 preflight 后、执行任何 OX-202/OX-216 远端人工删除之前,具名操作员必须仅凭已通过 OX-203 的自身 OX_OPERATOR_TOKEN_FILE 凭据完成同 run 远端目标核对;任一项不明即停在 blocked,禁止转入 key 或 repo DELETE 命令。

1. 同 Run 目标核对九项硬约束

  1. 不可复用 run UUID: 从同一受限 0600 $OX_LIVE_RUN_DIR/manifest.json 读取不可复用 run UUID。
  2. 已确认 201 repo 数字 ID: manifest.repo_id_state == "confirmed_201" 且 repo_id 必须来自本次 create=201 持久化记录(禁止 GET 自报 ID)。
  3. 已确认 201 deploy-key 数字 ID: manifest.key_id_state == "confirmed_201" 且 key_id 必须来自本次 create=201 持久化记录(unknown_after_request 转 OX-155)。
  4. 唯一仓名与命名空间: namespace_kind(personal|org)、canonical_owner 与 repo_name == "mega2-gs-live-<run_uuid>" 严格匹配本次唯一仓名。
  5. 只读 GET /repos/{owner}/{repo} 禁 redirect: 删除前对 GET /repos/{owner}/{repo} 发单次只读请求,必须返回 HTTP 200,任何 3xx redirect(如 301/307/308)立即拒绝且禁跟随。
  6. 数字 id 严格一致: GET /repos/{owner}/{repo} 返回的正整数 id 必须等于 manifest 已持久的 201 repo_id。
  7. node_id 严格一致: GET /repos/{owner}/{repo} 返回的 node_id 必须等于 manifest 已持久的 201 repo_node_id。
  8. Namespace 权限归属核验: personal 目标由具名操作员本人拥有(GET /user login == canonical_owner);org 目标须具备 state=active、role=admin 及实际仓库管理权限的独立脱敏证据(关联 OX-203 operator-authority-evidence.json)。
  9. Fail-Closed 阻断: 任一 ID、owner/name、权限或响应状态不明时立即停在 blocked,绝不向 OX-202/OX-216 交付 DELETE 命令。

2. OX-209 六份脱敏回包桌面演练证据表

场景 脱敏输入与模拟 GET /repos/{owner}/{repo} 回包 判定结论(可删除 / blocked)
OX-209-T1 同 run UUID manifest(201 repo_id=209001、node_id=R_kgDO_209、201 key_id=880209)、GET /repos HTTP 200(无 redirect)且 id/node_id/owner/name 全匹配、personal owner 本人拥有 可转入 OX-202 删除
OX-209-T2 GET /repos 返回 HTTP 200 但 id=999999 与 manifest 201 repo_id=209001 不符 blocked(禁止 DELETE)
OX-209-T3 manifest key_id_state=unknown_after_request 或待删 key_id 与 201 manifest key_id 不匹配 blocked(禁止 DELETE,转 OX-155)
OX-209-T4 GET /repos/{owner}/{repo} 返回 HTTP 307 redirect(疑似改名或转移) blocked(禁跟随 redirect,禁止 DELETE)
OX-209-T5 namespace_kind=personal,但操作员 GET /user login=Bob-Other != canonical_owner=Alice-Dev blocked(个人 owner 不符,禁止 DELETE)
OX-209-T6 namespace_kind=org,但缺失 active/admin 成员资格或实际仓库管理权限独立证据 blocked(org 权限不明,禁止 DELETE)

具名人工 Deploy Key 补偿命令与回执证据模板(OX-202)

本步骤仅在 OX-209 核准本 run 已确认 201 repo_id、node_id 与 201 key_id 后、且在删除私有仓库之前由具名人类操作员在独立 shell 中执行;本步骤不删除仓库,也绝不向 runner 交付任何可自动重放的 DELETE 凭据。

1. 可复制执行的一次性 Python 标准库命令(禁 redirect、单次尝试、零 argv 令牌)

unset MEGA_TEST_GITHUB_TOKEN GH_TOKEN GITHUB_TOKEN
python3 - <<'PY'
import datetime, http.client, json, os, pathlib, sys, urllib.parse

token = pathlib.Path(os.environ["OX_OPERATOR_TOKEN_FILE"]).read_bytes()
if token.endswith(b"\r\n"):
    token = token[:-2]
elif token.endswith(b"\n"):
    token = token[:-1]
token_str = token.decode("utf-8")

manifest = json.loads(pathlib.Path(os.environ["OX_LIVE_RUN_DIR"], "manifest.json").read_text("utf-8"))
assert manifest.get("repo_id_state") == "confirmed_201", "repo_id must be confirmed_201"
assert manifest.get("key_id_state") == "confirmed_201", "key_id must be confirmed_201"
owner = manifest["canonical_owner"]
repo = manifest["repo_name"]
key_id = int(manifest["key_id"])
expected_repo_id = int(manifest["repo_id"])
expected_node_id = manifest["repo_node_id"]

api_base = urllib.parse.urlsplit(os.environ.get("OX_OPERATOR_API_BASE", "https://api.github.com"))
def single_request(method, path):
    conn_cls = http.client.HTTPSConnection if api_base.scheme == "https" else http.client.HTTPConnection
    conn = conn_cls(api_base.hostname, api_base.port, timeout=30)
    try:
        conn.request(method, path, headers={
            "Authorization": f"Bearer {token_str}",
            "Accept": "application/vnd.github+json",
            "X-GitHub-Api-Version": "2022-11-28",
            "User-Agent": "mega2-ox202-operator-manual-key-cleanup",
        })
        resp = conn.getresponse()
        body = resp.read()
        return resp.status, resp.getheader("X-GitHub-Request-Id", ""), body
    finally:
        conn.close()

# 1) Single-shot DELETE /repos/{owner}/{repo}/keys/{key_id} (no 3xx redirect following, never retry)
del_status, del_req_id, _ = single_request("DELETE", f"/repos/{owner}/{repo}/keys/{key_id}")
del_at = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
if 300 <= del_status < 400 or del_status != 204:
    print(json.dumps({"status": "blocked", "stage": "key_delete", "http_status": del_status, "request_id": del_req_id, "at": del_at}))
    sys.exit(4)

# 2) While original repo still returns confirmed 200 identity, read same key_id and observe GET 404
repo_status, repo_req_id, repo_body = single_request("GET", f"/repos/{owner}/{repo}")
if repo_status != 200:
    print(json.dumps({"status": "blocked", "stage": "repo_reverify", "http_status": repo_status, "request_id": repo_req_id}))
    sys.exit(4)
repo_json = json.loads(repo_body.decode("utf-8"))
if repo_json.get("id") != expected_repo_id or repo_json.get("node_id") != expected_node_id:
    print(json.dumps({"status": "blocked", "stage": "repo_identity_drift"}))
    sys.exit(4)

key_get_status, key_get_req_id, _ = single_request("GET", f"/repos/{owner}/{repo}/keys/{key_id}")
if key_get_status != 404:
    print(json.dumps({"status": "blocked", "stage": "key_absence_get", "http_status": key_get_status, "request_id": key_get_req_id}))
    sys.exit(4)

print(json.dumps({
    "kind": "OperatorKeyDeleteRecord",
    "run_uuid": manifest["run_uuid"],
    "canonical_owner": owner,
    "repo_name": repo,
    "repo_id": expected_repo_id,
    "key_id": key_id,
    "delete_http_status": 204,
    "delete_request_id": del_req_id,
    "delete_attempts": 1,
    "redirect_count": 0,
    "deleted_at": del_at,
    "post_delete_repo_get_status": 200,
    "post_delete_key_get_status": 404,
    "post_delete_key_get_request_id": key_get_req_id,
}))
PY

2. OX-202 五场景脱敏桌面演练记录

场景 脱敏输入与模拟回包 判定结果
OX-202-K1 同 run 201 key_id=880202、DELETE /repos/{owner}/{repo}/keys/880202 仅发 1 次返回 204 + Request-Id、repo GET 200 身份一致后 GET /repos/{owner}/{repo}/keys/880202 返回 404 PASS(交 OX-227 / OX-40,仓库未删)
OX-202-K2 DELETE /repos/{owner}/{repo}/keys/{key_id} 返回 307 redirect blocked(禁跟随 redirect、零重试、转 OX-155)
OX-202-K3 DELETE 或 GET 返回 401 / 403(权限失效或凭据错误) blocked(不声称已删、零重试、转 OX-155)
OX-202-K4 DELETE 发生网络超时/结果不明 blocked(零自动重发、转 OX-155)
OX-202-K5 DELETE 返回 204 但随后 repo GET 身份漂移或 GET /keys/{key_id} 返回 200/500(非 404) blocked(不声称 key 缺席、转 OX-155)

受控排他命名窗口前提与操作员确认记录(OX-211)

由于 GitHub REST 仓库删除接口仅支持按 owner/name 路径定址、无法按数字 repo_id 执行原子删除,在执行 OX-216 仓库 DELETE 前,具名 owner/admin 必须先建立并登记本 run UUID 仓名的受控排他变更窗口(exclusive window)。

重要边界声明: 排他窗口是降低同名重绑/转移风险的操作性前提(operational precondition),绝不能将按路径返回的 204 + 404 当作数学意义上的“原数字 ID 原子删除证明”;删除后仍须由 OX-217/OX-41 经同一具名身份与 GraphQL node(id:) 复核。

1. 排他变更窗口六项前提与确认记录模板

{
  "kind": "ExclusiveRepoNameWindowRecord",
  "run_uuid": "<same-run UUID>",
  "namespace_kind": "personal | org",
  "namespace_owner": "<canonical owner slug>",
  "repo_name": "mega2-gs-live-<run_uuid>",
  "operator_login": "<named operator from OX-203>",
  "authority_evidence_ref": "<personal: null | org: OX-203 operator-authority-evidence.json ref>",
  "window_started_at": "<UTC RFC 3339>",
  "window_expires_at": "<UTC RFC 3339>",
  "other_admins_or_collaborators_absent": true,
  "other_automation_or_sessions_stopped": true,
  "runner_quiesced_and_locks_released": true,
  "org_equivalent_exclusive_admin_verified": "<personal: null | org: true>"
}
  1. 具名 owner/admin 登记本 UUID 仓名的 window_started_at/window_expires_at、namespace_kind 与受控 namespace_owner;personal 记录 owner 身份,org 还须引用 OX-203 的脱敏 operator-authority-evidence.json。
  2. 删除前核对私仓没有其它可改名或转移仓库的管理员或 collaborator。
  3. 具名 owner 确认窗口内没有其它操作该仓名的 automation 或并发登录会话。
  4. runner 在窗口内已停止全部远端写入并释放 DB 锁与文件锁。
  5. org namespace 若缺乏等效排他管理证据,禁止进入 OX-216 删除命令。
  6. 任一排他前提无法由具名操作员确认时,旧 run 必须保持 blocked 并交 OX-155 处置。

2. OX-211 四场景脱敏桌面演练表

场景 脱敏窗口条件 判定结果
OX-211-W1 personal 具名 owner 本人、无其它管理员/collaborator、无并发 automation/会话、runner 已静止并释放锁、窗口未过期 PASS(允许进入 OX-216)
OX-211-W2 仓库存在其它具有 admin/maintain 权限的管理员或 collaborator blocked(禁止进入 OX-216,转 OX-155)
OX-211-W3 窗口内存在未停止的仓库管理 automation 或并发会话 blocked(禁止进入 OX-216,转 OX-155)
OX-211-W4 org namespace 缺失等效排他管理证据或未引用 OX-203 脱敏 authority evidence blocked(禁止进入 OX-216,转 OX-155)

具名人工私有仓库 Name-Path DELETE 命令与回执模板(OX-216)

在 OX-202 完成 deploy key 补偿且 OX-211 有效排他窗口(exclusive window)仍在有效期内时,具名操作员在独立 shell 中即时核对 OX-209 的原 repo 数字 id 与 node_id,并对该 /repos/{owner}/{repo} 仅发送一次官方 REST DELETE。

语义提醒: GitHub 无按不可变数字 ID 原子删除仓库的 REST 接口;HTTP 204 仅记录为本次 name-path DELETE 响应,绝不等同于“原数字 ID 原子删除证明”,后续必须由 OX-217/OX-41 完成同身份路径缺席与 GraphQL node(id:) 追查。

1. 可复制执行的一次性 Python 标准库命令(消费 OX-211 窗口、禁 redirect、单次 DELETE、零 argv 令牌)

unset MEGA_TEST_GITHUB_TOKEN GH_TOKEN GITHUB_TOKEN
python3 - <<'PY'
import datetime, http.client, json, os, pathlib, sys, urllib.parse

token = pathlib.Path(os.environ["OX_OPERATOR_TOKEN_FILE"]).read_bytes()
if token.endswith(b"\r\n"):
    token = token[:-2]
elif token.endswith(b"\n"):
    token = token[:-1]
token_str = token.decode("utf-8")

run_dir = pathlib.Path(os.environ["OX_LIVE_RUN_DIR"])
manifest = json.loads((run_dir / "manifest.json").read_text("utf-8"))
window = json.loads((run_dir / "exclusive-window.json").read_text("utf-8"))

# AC-1: Consume valid OX-211 exclusive window record for the same run UUID & repo.
assert window.get("kind") == "ExclusiveRepoNameWindowRecord"
assert window.get("run_uuid") == manifest["run_uuid"]
assert window.get("repo_name") == manifest["repo_name"]
assert window.get("other_admins_or_collaborators_absent") is True
assert window.get("other_automation_or_sessions_stopped") is True
assert window.get("runner_quiesced_and_locks_released") is True
now_utc = datetime.datetime.now(datetime.timezone.utc)
exp_utc = datetime.datetime.fromisoformat(window["window_expires_at"].replace("Z", "+00:00"))
assert now_utc <= exp_utc, "OX-211 exclusive window expired"

assert manifest.get("repo_id_state") == "confirmed_201"
owner = manifest["canonical_owner"]
repo = manifest["repo_name"]
expected_repo_id = int(manifest["repo_id"])
expected_node_id = manifest["repo_node_id"]
operator_login = window["operator_login"]

api_base = urllib.parse.urlsplit(os.environ.get("OX_OPERATOR_API_BASE", "https://api.github.com"))
def single_request(method, path):
    conn_cls = http.client.HTTPSConnection if api_base.scheme == "https" else http.client.HTTPConnection
    conn = conn_cls(api_base.hostname, api_base.port, timeout=30)
    try:
        conn.request(method, path, headers={
            "Authorization": f"Bearer {token_str}",
            "Accept": "application/vnd.github+json",
            "X-GitHub-Api-Version": "2022-11-28",
            "User-Agent": "mega2-ox216-operator-manual-repo-cleanup",
        })
        resp = conn.getresponse()
        body = resp.read()
        return resp.status, resp.getheader("X-GitHub-Request-Id", ""), body
    finally:
        conn.close()

# AC-2..AC-4: Immediate pre-delete GET /repos/{owner}/{repo} == 200, no 3xx redirect, matching id & node_id.
get_status, get_req_id, get_body = single_request("GET", f"/repos/{owner}/{repo}")
if 300 <= get_status < 400 or get_status != 200:
    print(json.dumps({"status": "blocked", "stage": "pre_delete_get", "http_status": get_status, "request_id": get_req_id}))
    sys.exit(4)
repo_obj = json.loads(get_body.decode("utf-8"))
if repo_obj.get("id") != expected_repo_id or repo_obj.get("node_id") != expected_node_id:
    print(json.dumps({"status": "blocked", "stage": "pre_delete_identity_rebind_detected"}))
    sys.exit(4)

# AC-5..AC-8: Single-shot DELETE /repos/{owner}/{repo} (no redirect following, never auto-retry).
del_status, del_req_id, _ = single_request("DELETE", f"/repos/{owner}/{repo}")
del_at = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
if 300 <= del_status < 400 or del_status != 204:
    print(json.dumps({"status": "blocked", "stage": "repo_delete", "http_status": del_status, "request_id": del_req_id, "at": del_at}))
    sys.exit(4)

print(json.dumps({
    "kind": "OperatorRepoDeleteRecord",
    "run_uuid": manifest["run_uuid"],
    "operator_login": operator_login,
    "canonical_owner": owner,
    "repo_name": repo,
    "pre_delete_get_status": 200,
    "pre_delete_get_request_id": get_req_id,
    "pre_delete_repo_id": expected_repo_id,
    "pre_delete_node_id": expected_node_id,
    "delete_path": f"/repos/{owner}/{repo}",
    "delete_http_status": 204,
    "delete_request_id": del_req_id,
    "delete_attempts": 1,
    "redirect_count": 0,
    "deleted_at": del_at,
    "proves_atomic_id_deletion": False,
}))
PY

2. OX-216 五场景脱敏桌面演练表

场景 脱敏响应与模拟情形 判定结果
OX-216-R1 发生 A→B 同名重绑:预删除 GET /repos/{owner}/{repo} 返回 200 但 id/node_id 变为仓库 B blocked(立即阻断 DELETE /repos/{owner}/{repo})
OX-216-R2 预删除 GET /repos/{owner}/{repo} 返回 307 redirect blocked(禁跟随 redirect、阻断 DELETE)
OX-216-R3 DELETE /repos/{owner}/{repo} 返回 307 redirect blocked(禁跟随 redirect、零重试、转 OX-155)
OX-216-R4 有效 OX-211 exclusive 窗口 + 预删除 GET 200 同 id/node_id + 单次 DELETE /repos/{owner}/{repo} 返回 204 + Request-Id + UTC 时间 + 具名账号 记录 204 删除响应(proves_atomic_id_deletion=false,交 OX-217/OX-215/OX-219)
OX-216-R5 DELETE /repos/{owner}/{repo} 超时/断连结果不明 blocked(零自动重试、转 OX-155)

仓库人工删除后的同身份观察边界与证据表(OX-217)

OX-216 记录的 HTTP 204 只是按 owner/name 路径发出的删除响应。为防范 GitHub 私仓 404 权限歧义与同名重绑,具名操作员必须在同一连续身份与受控窗口内完成后续路径缺席与原 node_id GraphQL 追查,并遵守以下八项观察边界:

  1. 连续操作员身份: 删除后同一凭据再次执行 GET /user,返回的 login 仍严格等于 OX-203 预检的原具名操作员。
  2. 连续作用域: 删除后响应头 X-OAuth-Scopes 仍同时包含 repo 与 delete_repo。
  3. 连续 Namespace 权限: 该操作员对目标 namespace 的 owner/admin 管理权限连续有效(无吊销/降权)。
  4. 同身份路径 GET 404: 对原 /repos/{owner}/{repo} 路径在同身份下观察 HTTP 404(禁 redirect);单独 404 仅记录为“路径缺席”,绝不单独构成原仓已删除证明。
  5. 原 node_id GraphQL 追查: 以 201 manifest 持久化的 node_id 执行只读 GraphQL 查询:
    query ($id: ID!) {
      node(id: $id) {
        ... on Repository {
          id
          fullDatabaseId
          nameWithOwner
        }
      }
    }
    若仍返回原 fullDatabaseId 或任何(含改名/转移后的)新 nameWithOwner,直接证明原仓库残留,立即判定 blocked。
  6. GraphQL null 不可单独放行: GraphQL node(id:) 返回 null、查询报错或操作员权限不明时,均不得单独解除 blocked;仅当 OX-211 有效排他窗口、OX-216 单次 204 回执、连续身份/作用域/owner-admin 权限、路径 404 与 GraphQL node == null 全部同时成立时,方可产出供 held-open case(OX-41/OX-210)复核的人工观察记录。
  7. 缺前置不产记录: 缺少 OX-211 有效排他窗口或 OX-216 本次 204 回执时,严禁产出人工观察记录。
  8. 异常一律 FAIL/blocked: 出现任何残留、权限漂移、3xx redirect 或同名重绑迹象时,旧 run 永久保留 FAIL/blocked 并交 OX-155 处置。

OX-217 四场景脱敏桌面演练证据表

场景 脱敏观察结果 旧 run 终态判定
OX-217-O1 路径 GET 404,但 GraphQL node(id:) 仍返回原 fullDatabaseId(或新 nameWithOwner) FAIL / blocked(证明原仓仍存活,交 OX-155)
OX-217-O2 GraphQL node(id:) 返回 null,但凭据 repo 或 delete_repo 作用域/namespace 权限已丢失 FAIL / blocked(权限不明时 null 不可放行)
OX-217-O3 原路径观察到 404,但 GET /user 账号已变更为另一非 OX-203 操作员 FAIL / blocked(账号漂移,裸 404 不可判成功)
OX-217-O4 有效 OX-211 窗口 + OX-216 204 回执 + 同一 OX-203 账号且 repo/delete_repo 与 owner/admin 权限连续 + 路径 404 + GraphQL node(id:) 返回 null 产出受限人工观察记录(供 OX-41 / OX-210 独立复核)