Compare commits

..
Author SHA1 Message Date
bsodfather 35a21f8ab5 fix(ci): fall back to pinned GitHub asset API for Trivy
CI / UI Checks (pull_request) Successful in 11s
CI / Rust Checks (pull_request) Successful in 25m14s
CI / Rust Feature Validation (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Required Checks (pull_request) Successful in 1s
CI / Deploy (pull_request) Skipped
2026-11-08 13:02:56 +03:00
bsodfather 2d0deb8963 Merge pull request 'fix(ci): download Trivy database from reachable official registry' (#116) from fix/release-db-source-20261107 into main
CI / UI Checks (push) Successful in 14s
CI / Rust Checks (push) Successful in 25m23s
CI / Rust Feature Validation (push) Skipped
CI / Frontend E2E (push) Skipped
CI / Community Image Smoke (push) Skipped
CI / Required Checks (push) Successful in 1s
CI / Deploy (push) Skipped
2026-11-08 09:40:01 +00:00
bsodfather f0a79362eb fix(ci): prefer reachable official Trivy database source
CI / UI Checks (pull_request) Successful in 11s
CI / Rust Checks (pull_request) Successful in 30m33s
CI / Rust Feature Validation (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Required Checks (pull_request) Successful in 1s
CI / Deploy (pull_request) Skipped
2026-11-07 18:24:08 +03:00
bsodfather 27f86d4916 Merge pull request 'fix(ci): continue interrupted releases without replacing assets' (#115) from fix/release-resume-20261107 into main
CI / UI Checks (push) Successful in 10s
CI / Rust Checks (push) Successful in 33m36s
CI / Rust Feature Validation (push) Skipped
CI / Frontend E2E (push) Skipped
CI / Community Image Smoke (push) Skipped
CI / Required Checks (push) Successful in 1s
CI / Deploy (push) Skipped
fix(ci): safely resume incomplete immutable releases
2026-11-07 14:49:41 +00:00
bsodfather f728d31dbf fix(ci): safely resume incomplete immutable releases
CI / UI Checks (pull_request) Successful in 9s
CI / Rust Checks (pull_request) Successful in 24m48s
CI / Rust Feature Validation (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Required Checks (pull_request) Successful in 3s
CI / Deploy (pull_request) Skipped
2026-11-07 17:24:26 +03:00
bsodfather 29ee01b6ef Merge pull request 'Prototype isolated rmcp Tools adapter (#106)' (#114) from feat/rmcp106-tools-adapter into main
CI / UI Checks (push) Successful in 9s
CI / Rust Checks (push) Successful in 24m5s
CI / Rust Feature Validation (push) Skipped
CI / Frontend E2E (push) Skipped
CI / Community Image Smoke (push) Skipped
CI / Required Checks (push) Successful in 1s
CI / Deploy (push) Skipped
Community Release / release (push) Failing after 35m1s
2026-11-07 08:57:25 +00:00
bsodfather bcf8b43516 fix(ci): reuse installed pinned Rust toolchain
CI / UI Checks (pull_request) Successful in 8s
CI / Rust Checks (pull_request) Successful in 24m46s
CI / Rust Feature Validation (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Required Checks (pull_request) Successful in 2s
CI / Deploy (pull_request) Skipped
2026-11-07 11:29:53 +03:00
bsodfather 1c256e6c75 Add isolated rmcp Tools adapter prototype
CI / Rust Checks (pull_request) Failing after 40s
CI / Rust Feature Validation (pull_request) Skipped
CI / UI Checks (pull_request) Successful in 12s
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Required Checks (pull_request) Failing after 2s
CI / Deploy (pull_request) Skipped
2026-11-06 07:56:21 +00:00
23 changed files with 2661 additions and 113 deletions

No files matched your search

+21 -9
View File
@@ -48,9 +48,13 @@ jobs:
echo "Unable to read Rust toolchain channel from rust-toolchain.toml" >&2
exit 1
fi
rustup toolchain install "$toolchain" --profile minimal --component clippy --component rustfmt
rustup default "$toolchain"
host="$(rustc -vV | sed -n 's/^host: //p')"
if ! rustup run "$toolchain" rustc --version >/dev/null 2>&1 || \
! rustup run "$toolchain" cargo --version >/dev/null 2>&1 || \
! rustup run "$toolchain" rustfmt --version >/dev/null 2>&1 || \
! rustup run "$toolchain" cargo-clippy --version >/dev/null 2>&1; then
rustup toolchain install "$toolchain" --profile minimal --component clippy --component rustfmt
fi
host="$(rustup run "$toolchain" rustc -vV | sed -n 's/^host: //p')"
toolchain_dir="${RUSTUP_HOME:-$HOME/.rustup}/toolchains/${toolchain}-${host}"
toolchain_bin="$toolchain_dir/bin"
if [ ! -x "$toolchain_bin/rustc" ] || [ ! -x "$toolchain_bin/cargo" ]; then
@@ -187,9 +191,13 @@ jobs:
echo "Unable to read Rust toolchain channel from rust-toolchain.toml" >&2
exit 1
fi
rustup toolchain install "$toolchain" --profile minimal --component clippy --component rustfmt
rustup default "$toolchain"
host="$(rustc -vV | sed -n 's/^host: //p')"
if ! rustup run "$toolchain" rustc --version >/dev/null 2>&1 || \
! rustup run "$toolchain" cargo --version >/dev/null 2>&1 || \
! rustup run "$toolchain" rustfmt --version >/dev/null 2>&1 || \
! rustup run "$toolchain" cargo-clippy --version >/dev/null 2>&1; then
rustup toolchain install "$toolchain" --profile minimal --component clippy --component rustfmt
fi
host="$(rustup run "$toolchain" rustc -vV | sed -n 's/^host: //p')"
toolchain_dir="${RUSTUP_HOME:-$HOME/.rustup}/toolchains/${toolchain}-${host}"
toolchain_bin="$toolchain_dir/bin"
if [ ! -x "$toolchain_bin/rustc" ] || [ ! -x "$toolchain_bin/cargo" ]; then
@@ -266,9 +274,13 @@ jobs:
echo "Unable to read Rust toolchain channel from rust-toolchain.toml" >&2
exit 1
fi
rustup toolchain install "$toolchain" --profile minimal --component clippy --component rustfmt
rustup default "$toolchain"
host="$(rustc -vV | sed -n 's/^host: //p')"
if ! rustup run "$toolchain" rustc --version >/dev/null 2>&1 || \
! rustup run "$toolchain" cargo --version >/dev/null 2>&1 || \
! rustup run "$toolchain" rustfmt --version >/dev/null 2>&1 || \
! rustup run "$toolchain" cargo-clippy --version >/dev/null 2>&1; then
rustup toolchain install "$toolchain" --profile minimal --component clippy --component rustfmt
fi
host="$(rustup run "$toolchain" rustc -vV | sed -n 's/^host: //p')"
toolchain_dir="${RUSTUP_HOME:-$HOME/.rustup}/toolchains/${toolchain}-${host}"
toolchain_bin="$toolchain_dir/bin"
if [ ! -x "$toolchain_bin/rustc" ] || [ ! -x "$toolchain_bin/cargo" ]; then
+74 -8
View File
@@ -12,10 +12,20 @@ on:
options: [story, feature]
default: story
required: true
resume_tag:
description: Existing draft release tag to resume with image-only steps
type: string
default: ""
required: false
resume_source_sha:
description: Exact accepted source commit SHA for the resume tag
type: string
default: ""
required: false
env:
REGISTRY: git.itexp.me
IMAGE_TAG: ${{ gitea.ref_name }}
IMAGE_TAG: ${{ inputs.resume_tag || gitea.ref_name }}
ADMIN_API_IMAGE: git.itexp.me/bsodfather/crank-community-admin-api
MCP_SERVER_IMAGE: git.itexp.me/bsodfather/crank-community-mcp-server
UI_IMAGE: git.itexp.me/bsodfather/crank-community-ui
@@ -31,12 +41,47 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
with:
fetch-depth: 0
- name: Verify existing release before resume
id: resume
if: inputs.resume_tag != ''
env:
GITEA_SERVER_URL: https://git.itexp.me
GITEA_REPOSITORY: ${{ gitea.repository }}
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
RELEASE_TAG: ${{ inputs.resume_tag }}
RESUME_SOURCE_SHA: ${{ inputs.resume_source_sha }}
run: python3 scripts/ci-release-resume.py
- name: Preserve updated image scanner for resume
id: pin_resume_scanner
if: inputs.resume_tag != ''
run: |
set -eu
scanner_dir="$(mktemp -d "${RUNNER_TEMP:?RUNNER_TEMP is unavailable}/crank-release-scanner.XXXXXX")"
cp scripts/scan-images.sh "$scanner_dir/scan-images.sh"
cp scripts/check-image-scan.py "$scanner_dir/check-image-scan.py"
chmod +x "$scanner_dir/scan-images.sh"
printf 'path=%s\n' "$scanner_dir/scan-images.sh" >> "$GITHUB_OUTPUT"
- name: Checkout validated release source
if: inputs.resume_tag != ''
uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
with:
ref: ${{ steps.resume.outputs.release_tag }}
fetch-depth: 0
- name: Assert exact release source checkout
if: inputs.resume_tag != ''
env:
EXPECTED_SOURCE_SHA: ${{ steps.resume.outputs.source_sha }}
run: test "$(git rev-parse HEAD)" = "$EXPECTED_SOURCE_SHA"
- name: Clear optional release evidence
if: inputs.resume_tag == ''
run: rm -f .tmp/openapi-playwright.json .tmp/openapi-ui-evidence.json
- name: Use preinstalled Rust toolchain
if: inputs.resume_tag == ''
run: |
set -eu
toolchain_dir="${RUSTUP_HOME:-$HOME/.rustup}/toolchains/1.96.1-x86_64-unknown-linux-gnu"
@@ -54,6 +99,7 @@ jobs:
"$toolchain_bin/cargo-clippy" --version
- name: Verify runner toolchain
if: inputs.resume_tag == ''
run: |
python3 --version
rustc --version
@@ -65,19 +111,23 @@ jobs:
bao version
- name: Install dependency policy tool
if: inputs.resume_tag == ''
run: cargo install cargo-deny --version 0.20.2 --locked
- name: Check formatting
if: inputs.resume_tag == ''
run: cargo fmt --all --check
- name: Audit Rust dependencies
if: inputs.resume_tag == ''
run: cargo deny --locked check advisories bans licenses sources
- name: Run tooling unit tests
if: inputs.validation_level == 'feature'
if: inputs.resume_tag == '' && inputs.validation_level == 'feature'
run: python3 -m unittest discover -s tests/unit
- name: Check typed runtime configuration contract
if: inputs.resume_tag == ''
run: |
cargo run -p crank-config --bin crank-config-contract -- --check
python3 scripts/check-runtime-config.py --root .
@@ -85,14 +135,17 @@ jobs:
scripts/check-rust-boundaries.sh
- name: Check canonical migration contract
if: inputs.resume_tag == ''
run: cargo run -p admin-api --bin crank-migrate -- plan --check
- name: Check typed metrics contract
if: inputs.resume_tag == ''
run: |
cargo run -p crank-metrics --bin crank-metrics-contract -- --check
python3 scripts/check-metrics-boundaries.py --root .
- name: Check Capability Inventory
if: inputs.resume_tag == ''
run: |
required_args=""
for number in $(seq 1 54); do
@@ -105,6 +158,7 @@ jobs:
$required_args
- name: Check Capability Baseline
if: inputs.resume_tag == ''
run: |
python3 scripts/validate-capability-baseline.py \
--root . \
@@ -112,40 +166,46 @@ jobs:
--schema docs/schemas/capability-baseline.schema.json
- name: Check Community scope
if: inputs.resume_tag == ''
run: scripts/check-community-scope.sh
- name: Run Crank story ATDD
if: inputs.resume_tag == ''
run: scripts/ci-story-checks.sh
- name: Run release quality gates
if: inputs.validation_level == 'feature'
if: inputs.resume_tag == '' && inputs.validation_level == 'feature'
run: |
cargo clippy --workspace --all-targets --all-features -- -D warnings
cargo test --workspace --all-targets -- --test-threads=1
- name: Build release binaries
if: inputs.resume_tag == ''
run: cargo build --release -p admin-api -p mcp-server
- name: Install UI dependencies
if: inputs.resume_tag == ''
working-directory: apps/ui
run: npm ci
- name: Audit UI dependencies
if: inputs.resume_tag == ''
working-directory: apps/ui
run: npm audit --audit-level=high
- name: Build UI dist
if: inputs.resume_tag == ''
working-directory: apps/ui
run: npm run build
- name: Install Playwright browser
if: inputs.validation_level == 'feature'
if: inputs.resume_tag == '' && inputs.validation_level == 'feature'
working-directory: apps/ui
run: npx playwright install --with-deps chromium
- name: Run release end-to-end tests
if: inputs.validation_level == 'feature'
if: inputs.resume_tag == '' && inputs.validation_level == 'feature'
working-directory: apps/ui
run: |
mkdir -p ../../.tmp
@@ -153,7 +213,7 @@ jobs:
PLAYWRIGHT_JSON_OUTPUT=../../.tmp/openapi-playwright.json npm run e2e
- name: Collect sanitized OpenAPI UI release evidence
if: inputs.validation_level == 'feature'
if: inputs.resume_tag == '' && inputs.validation_level == 'feature'
working-directory: apps/ui
run: |
trap 'rm -f ../../.tmp/openapi-playwright.json' EXIT
@@ -175,12 +235,14 @@ jobs:
--require-accepted
- name: Validate deployment manifests
if: inputs.resume_tag == ''
run: |
docker compose -f docker-compose.yml --env-file .env.example config -q
docker compose -f deploy/community/docker-compose.yml --env-file deploy/community/.env.example config -q
docker compose -f deploy/community/docker-compose.images.yml --env-file deploy/community/.env.images.example --profile local-db config -q
- name: Package release artifacts
if: inputs.resume_tag == ''
run: |
set -euo pipefail
mkdir -p dist/release
@@ -204,13 +266,14 @@ jobs:
sha256sum "${files[@]}" > "dist/crank-community-${IMAGE_TAG}-checksums.txt"
- name: Generate SBOM
if: inputs.resume_tag == ''
run: |
docker run --rm -v "$PWD:/workspace" anchore/syft:latest \
dir:/workspace -o spdx-json \
> dist/crank-community-${IMAGE_TAG}-sbom.spdx.json
- name: Publish release bundles, checksums, evidence, and SBOM to Gitea
if: startsWith(gitea.ref, 'refs/tags/v')
if: inputs.resume_tag == '' && startsWith(gitea.ref, 'refs/tags/v')
env:
# gitea.server_url inside the job container is the internal http://gitea:3000 origin;
# the publisher only forwards its token to the public HTTPS origin.
@@ -249,6 +312,8 @@ jobs:
docker login '${{ env.REGISTRY }}' -u "$DEPLOY_REGISTRY_USER" --password-stdin
- name: Build and push release images
env:
RELEASE_IMAGE_SCANNER: ${{ steps.pin_resume_scanner.outputs.path || 'scripts/scan-images.sh' }}
run: |
docker build -f apps/admin-api/Dockerfile \
-t '${{ env.ADMIN_API_IMAGE }}:${{ env.IMAGE_TAG }}' \
@@ -285,7 +350,7 @@ jobs:
--env-file .tmp/release-migration-smoke.env --profile local-db up -d --wait
docker compose -f deploy/community/docker-compose.images.yml \
--env-file .tmp/release-migration-smoke.env --profile local-db logs migrate | grep '"status":"applied"'
scripts/scan-images.sh \
"$RELEASE_IMAGE_SCANNER" \
'${{ env.ADMIN_API_IMAGE }}:${{ env.IMAGE_TAG }}' \
'${{ env.MCP_SERVER_IMAGE }}:${{ env.IMAGE_TAG }}' \
'${{ env.UI_IMAGE }}:${{ env.IMAGE_TAG }}'
@@ -297,5 +362,6 @@ jobs:
docker push '${{ env.UI_IMAGE }}:latest'
- name: Show release bundle summary
if: inputs.resume_tag == ''
run: |
ls -lh dist
Generated
+204 -62
View File
@@ -25,7 +25,7 @@ dependencies = [
"async-trait",
"axum",
"axum-extra",
"base64",
"base64 0.22.1",
"crank-artifacts",
"crank-community-auth",
"crank-community-mcp",
@@ -186,7 +186,7 @@ checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d"
dependencies = [
"proc-macro2",
"quote",
"syn",
"syn 2.0.118",
]
[[package]]
@@ -197,7 +197,7 @@ checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb"
dependencies = [
"proc-macro2",
"quote",
"syn",
"syn 2.0.118",
]
[[package]]
@@ -349,6 +349,12 @@ version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
name = "base64"
version = "0.23.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
[[package]]
name = "base64ct"
version = "1.8.3"
@@ -398,7 +404,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee04c4c84f1f811b017f2fbb7dd8815c976e7ca98593de9c1e2afad0f636bff4"
dependencies = [
"async-stream",
"base64",
"base64 0.22.1",
"bitflags",
"bollard-buildkit-proto",
"bollard-stubs",
@@ -455,7 +461,7 @@ version = "1.52.1-rc.29.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0f0a8ca8799131c1837d1282c3f81f31e76ceb0ce426e04a7fe1ccee3287c066"
dependencies = [
"base64",
"base64 0.22.1",
"bollard-buildkit-proto",
"bytes",
"prost",
@@ -653,7 +659,7 @@ version = "0.3.1"
dependencies = [
"async-trait",
"axum",
"base64",
"base64 0.22.1",
"crank-core",
"crank-metrics",
"crank-trace",
@@ -688,7 +694,7 @@ dependencies = [
"argon2",
"async-trait",
"axum-extra",
"base64",
"base64 0.22.1",
"crank-core",
"crank-registry",
"rand 0.10.2",
@@ -705,7 +711,7 @@ version = "0.3.1"
dependencies = [
"async-trait",
"axum",
"base64",
"base64 0.22.1",
"crank-adapter-rest",
"crank-artifacts",
"crank-core",
@@ -722,6 +728,7 @@ dependencies = [
"opentelemetry",
"opentelemetry_sdk",
"reqwest 0.12.28",
"rmcp",
"serde",
"serde_json",
"sha2 0.10.9",
@@ -850,7 +857,7 @@ dependencies = [
"aes-gcm",
"async-trait",
"axum",
"base64",
"base64 0.22.1",
"crank-adapter-rest",
"crank-core",
"crank-import",
@@ -992,8 +999,18 @@ version = "0.23.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "25ae13da2f202d56bd7f91c25fba009e7717a1e4a1cc98a76d844b65ae912e9d"
dependencies = [
"darling_core",
"darling_macro",
"darling_core 0.23.0",
"darling_macro 0.23.0",
]
[[package]]
name = "darling"
version = "0.24.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec"
dependencies = [
"darling_core 0.24.1",
"darling_macro 0.24.1",
]
[[package]]
@@ -1006,7 +1023,20 @@ dependencies = [
"proc-macro2",
"quote",
"strsim",
"syn",
"syn 2.0.118",
]
[[package]]
name = "darling_core"
version = "0.24.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff"
dependencies = [
"ident_case",
"proc-macro2",
"quote",
"strsim",
"syn 3.0.9",
]
[[package]]
@@ -1015,9 +1045,20 @@ version = "0.23.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac3984ec7bd6cfa798e62b4a642426a5be0e68f9401cfc2a01e3fa9ea2fcdb8d"
dependencies = [
"darling_core",
"darling_core 0.23.0",
"quote",
"syn",
"syn 2.0.118",
]
[[package]]
name = "darling_macro"
version = "0.24.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785"
dependencies = [
"darling_core 0.24.1",
"quote",
"syn 3.0.9",
]
[[package]]
@@ -1069,7 +1110,7 @@ checksum = "1ac70aa55017e108007fbaf5aa0f54b021c98f92ff8af59d42eda9da96e3dd4f"
dependencies = [
"proc-macro2",
"quote",
"syn",
"syn 2.0.118",
]
[[package]]
@@ -1078,7 +1119,7 @@ version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29547a1dc60885a552306986316bc9701ba120c1a8db6769fa68691529ad373d"
dependencies = [
"base64",
"base64 0.22.1",
"serde",
"serde_json",
]
@@ -1147,7 +1188,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys 0.52.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -1309,7 +1350,7 @@ checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b"
dependencies = [
"proc-macro2",
"quote",
"syn",
"syn 2.0.118",
]
[[package]]
@@ -1661,7 +1702,7 @@ version = "0.1.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0"
dependencies = [
"base64",
"base64 0.22.1",
"bytes",
"futures-channel",
"futures-util",
@@ -1672,7 +1713,7 @@ dependencies = [
"libc",
"percent-encoding",
"pin-project-lite",
"socket2 0.5.10",
"socket2 0.6.4",
"tokio",
"tower-service",
"tracing",
@@ -1920,7 +1961,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264"
dependencies = [
"quote",
"syn",
"syn 2.0.118",
]
[[package]]
@@ -2056,7 +2097,7 @@ version = "0.3.1"
dependencies = [
"async-trait",
"axum",
"base64",
"base64 0.22.1",
"crank-artifacts",
"crank-community-mcp",
"crank-config",
@@ -2121,7 +2162,7 @@ version = "0.18.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1db0d8f1fc9e62caebd0319e11eaec5822b0186c171568f0480b46a0137f9108"
dependencies = [
"base64",
"base64 0.22.1",
"evmap",
"indexmap 2.14.0",
"metrics",
@@ -2457,7 +2498,7 @@ dependencies = [
"regex",
"regex-syntax",
"structmeta",
"syn",
"syn 2.0.118",
]
[[package]]
@@ -2471,6 +2512,12 @@ dependencies = [
"subtle",
]
[[package]]
name = "pastey"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4"
[[package]]
name = "percent-encoding"
version = "2.3.2"
@@ -2494,7 +2541,7 @@ checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b"
dependencies = [
"proc-macro2",
"quote",
"syn",
"syn 2.0.118",
]
[[package]]
@@ -2580,7 +2627,7 @@ dependencies = [
"itertools",
"proc-macro2",
"quote",
"syn",
"syn 2.0.118",
]
[[package]]
@@ -2636,7 +2683,7 @@ dependencies = [
"quinn-udp",
"rustc-hash",
"rustls",
"socket2 0.5.10",
"socket2 0.6.4",
"thiserror 2.0.18",
"tokio",
"tracing",
@@ -2675,9 +2722,9 @@ dependencies = [
"cfg_aliases",
"libc",
"once_cell",
"socket2 0.5.10",
"socket2 0.6.4",
"tracing",
"windows-sys 0.52.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -2852,7 +2899,7 @@ checksum = "b7186006dcb21920990093f30e3dea63b7d6e977bf1256be20c3563a5db070da"
dependencies = [
"proc-macro2",
"quote",
"syn",
"syn 2.0.118",
]
[[package]]
@@ -2890,7 +2937,7 @@ version = "0.12.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"
dependencies = [
"base64",
"base64 0.22.1",
"bytes",
"cookie",
"cookie_store",
@@ -2934,7 +2981,7 @@ version = "0.13.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "219c5811de6525e5416c7d5d53bb656d3afdbc6c5af816e0802bcfa42dbdc1c3"
dependencies = [
"base64",
"base64 0.22.1",
"bytes",
"futures-channel",
"futures-core",
@@ -2981,6 +3028,52 @@ dependencies = [
"windows-sys 0.52.0",
]
[[package]]
name = "rmcp"
version = "3.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ece64e19631fc38758181e637c15509a2c2709ee53bfde1e1d58f9dc991f919e"
dependencies = [
"async-trait",
"base64 0.23.1",
"bytes",
"chrono",
"futures",
"http",
"http-body",
"http-body-util",
"indexmap 2.14.0",
"libc",
"pastey",
"pin-project-lite",
"rand 0.10.2",
"rmcp-macros",
"schemars 1.2.1",
"serde",
"serde_json",
"sse-stream",
"thiserror 2.0.18",
"tokio",
"tokio-stream",
"tokio-util",
"tower-service",
"tracing",
"uuid",
]
[[package]]
name = "rmcp-macros"
version = "3.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b3140f24a766f80f9ec1607bde85680959a69b83d46fa9ce87dadab7e67ab029"
dependencies = [
"darling 0.24.1",
"proc-macro2",
"quote",
"serde_json",
"syn 3.0.9",
]
[[package]]
name = "rustc-demangle"
version = "0.1.28"
@@ -3016,7 +3109,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys 0.12.1",
"windows-sys 0.52.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -3075,7 +3168,7 @@ dependencies = [
"security-framework",
"security-framework-sys",
"webpki-root-certs",
"windows-sys 0.52.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -3144,12 +3237,26 @@ version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2b42f36aa1cd011945615b92222f6bf73c599a102a300334cd7f8dbeec726cc"
dependencies = [
"chrono",
"dyn-clone",
"ref-cast",
"schemars_derive",
"serde",
"serde_json",
]
[[package]]
name = "schemars_derive"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d115b50f4aaeea07e79c1912f645c7513d81715d0420f8bc77a18c6260b307f"
dependencies = [
"proc-macro2",
"quote",
"serde_derive_internals",
"syn 2.0.118",
]
[[package]]
name = "scoped-tls"
version = "1.0.1"
@@ -3293,7 +3400,18 @@ checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
dependencies = [
"proc-macro2",
"quote",
"syn",
"syn 2.0.118",
]
[[package]]
name = "serde_derive_internals"
version = "0.29.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.118",
]
[[package]]
@@ -3328,7 +3446,7 @@ checksum = "175ee3e80ae9982737ca543e96133087cbd9a485eecc3bc4de9c1a37b47ea59c"
dependencies = [
"proc-macro2",
"quote",
"syn",
"syn 2.0.118",
]
[[package]]
@@ -3349,7 +3467,7 @@ version = "3.21.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "76a5c54c7310e7b8b9577c286d7e399ddd876c3e12b3ed917a8aabc4b96e9e8c"
dependencies = [
"base64",
"base64 0.22.1",
"bs58",
"chrono",
"hex",
@@ -3369,10 +3487,10 @@ version = "3.21.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "84d57bc0c8b9a17920c178daa6bb924850d54a9c97ab45194bb8c17ad66bb660"
dependencies = [
"darling",
"darling 0.23.0",
"proc-macro2",
"quote",
"syn",
"syn 2.0.118",
]
[[package]]
@@ -3410,7 +3528,7 @@ checksum = "94e153fc76e1c6a068703d6d29c508a0b15c061c4b7e43da59cc097bc342673c"
dependencies = [
"proc-macro2",
"quote",
"syn",
"syn 2.0.118",
]
[[package]]
@@ -3544,7 +3662,7 @@ dependencies = [
name = "sqlx-core"
version = "0.9.0"
dependencies = [
"base64",
"base64 0.22.1",
"bytes",
"cfg-if",
"crc",
@@ -3586,7 +3704,7 @@ dependencies = [
"quote",
"sqlx-core",
"sqlx-macros-core",
"syn",
"syn 2.0.118",
]
[[package]]
@@ -3609,7 +3727,7 @@ dependencies = [
"sqlx-mysql",
"sqlx-postgres",
"sqlx-sqlite",
"syn",
"syn 2.0.118",
"thiserror 2.0.18",
"tokio",
"url",
@@ -3650,7 +3768,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "87a2bdd6e83f6b3ea525ca9fee568030508b58355a43d0b2c1674d5f79dcd65e"
dependencies = [
"atoi",
"base64",
"base64 0.22.1",
"bitflags",
"byteorder",
"crc",
@@ -3706,6 +3824,19 @@ dependencies = [
"uuid",
]
[[package]]
name = "sse-stream"
version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c25ac7aff0abd1dbc474536e40416e1102c7dd9bfba0b9861c6d357f835dcfb4"
dependencies = [
"bytes",
"futures-util",
"http-body",
"http-body-util",
"pin-project-lite",
]
[[package]]
name = "stable_deref_trait"
version = "1.2.1"
@@ -3738,7 +3869,7 @@ dependencies = [
"proc-macro2",
"quote",
"structmeta-derive",
"syn",
"syn 2.0.118",
]
[[package]]
@@ -3749,7 +3880,7 @@ checksum = "152a0b65a590ff6c3da95cabe2353ee04e6167c896b28e3b14478c2636c922fc"
dependencies = [
"proc-macro2",
"quote",
"syn",
"syn 2.0.118",
]
[[package]]
@@ -3769,6 +3900,17 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "syn"
version = "3.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "sync_wrapper"
version = "1.0.2"
@@ -3786,7 +3928,7 @@ checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"
dependencies = [
"proc-macro2",
"quote",
"syn",
"syn 2.0.118",
]
[[package]]
@@ -3855,7 +3997,7 @@ checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"
dependencies = [
"proc-macro2",
"quote",
"syn",
"syn 2.0.118",
]
[[package]]
@@ -3866,7 +4008,7 @@ checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5"
dependencies = [
"proc-macro2",
"quote",
"syn",
"syn 2.0.118",
]
[[package]]
@@ -3957,7 +4099,7 @@ checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496"
dependencies = [
"proc-macro2",
"quote",
"syn",
"syn 2.0.118",
]
[[package]]
@@ -4002,7 +4144,7 @@ checksum = "ac2a5518c70fa84342385732db33fb3f44bc4cc748936eb5833d2df34d6445ef"
dependencies = [
"async-trait",
"axum",
"base64",
"base64 0.22.1",
"bytes",
"h2",
"http",
@@ -4103,7 +4245,7 @@ checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
dependencies = [
"proc-macro2",
"quote",
"syn",
"syn 2.0.118",
]
[[package]]
@@ -4232,7 +4374,7 @@ version = "3.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dea7109cdcd5864d4eeb1b58a1648dc9bf520360d7af16ec26d0a9354bafcfc0"
dependencies = [
"base64",
"base64 0.22.1",
"log",
"percent-encoding",
"rustls",
@@ -4248,7 +4390,7 @@ version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e994ba84b0bd1b1b0cf92878b7ef898a5c1760108fe7b6010327e274917a808c"
dependencies = [
"base64",
"base64 0.22.1",
"http",
"httparse",
"log",
@@ -4385,7 +4527,7 @@ dependencies = [
"bumpalo",
"proc-macro2",
"quote",
"syn",
"syn 2.0.118",
"wasm-bindgen-shared",
]
@@ -4477,7 +4619,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys 0.52.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -4507,7 +4649,7 @@ checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
dependencies = [
"proc-macro2",
"quote",
"syn",
"syn 2.0.118",
]
[[package]]
@@ -4518,7 +4660,7 @@ checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
dependencies = [
"proc-macro2",
"quote",
"syn",
"syn 2.0.118",
]
[[package]]
@@ -4734,7 +4876,7 @@ checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e"
dependencies = [
"proc-macro2",
"quote",
"syn",
"syn 2.0.118",
"synstructure",
]
@@ -4755,7 +4897,7 @@ checksum = "4714fd92cf900833d49538023a9b3915155210801d1c1169eba513b2addefd71"
dependencies = [
"proc-macro2",
"quote",
"syn",
"syn 2.0.118",
]
[[package]]
@@ -4775,7 +4917,7 @@ checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1"
dependencies = [
"proc-macro2",
"quote",
"syn",
"syn 2.0.118",
"synstructure",
]
@@ -4815,7 +4957,7 @@ checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555"
dependencies = [
"proc-macro2",
"quote",
"syn",
"syn 2.0.118",
]
[[package]]
+2
View File
@@ -21,6 +21,7 @@ crank-schema = { path = "../crank-schema" }
crank-trace = { path = "../crank-trace" }
futures-util = "0.3"
reqwest.workspace = true
serde.workspace = true
serde_json.workspace = true
sha2.workspace = true
@@ -32,6 +33,7 @@ tracing.workspace = true
uuid.workspace = true
[dev-dependencies]
rmcp = { version = "=3.7.0", features = ["transport-streamable-http-server"] }
crank-mapping = { path = "../crank-mapping" }
crank-test-support = { path = "../crank-test-support" }
metrics-util = "0.20.4"
+12
View File
@@ -34,6 +34,18 @@ pub(crate) mod lifecycle;
mod metrics;
mod request;
mod response;
#[cfg(test)]
mod rmcp_http;
#[cfg(test)]
#[path = "rmcp_http_tests.rs"]
mod rmcp_http_tests;
#[cfg(test)]
mod rmcp_session_tests;
#[cfg(test)]
mod rmcp_tools;
#[cfg(test)]
#[path = "rmcp_tools_tests.rs"]
mod rmcp_tools_tests;
mod stages;
mod tool_resolution;
pub(crate) use self::approval_policy::{
@@ -144,7 +144,7 @@ fn increment(counter: impl Fn(&CounterSet) -> &AtomicUsize) {
/// execution-boundary reason as the tests below).
#[cfg(test)]
#[path = "../dispatch_observer_support.rs"]
mod support;
pub(crate) mod support;
/// The behavioural section 7.2 harness: real app, real PostgreSQL, one counted loopback upstream and
/// one request-scoped observer per request. Its file lives outside `src/app/` only because the
@@ -133,7 +133,7 @@ pub(crate) struct ProgressEvent {
/// The pinned `notifications/progress` frame. Both supported revisions declare the same parameters,
/// so the projection is shared; the token is echoed verbatim and never validated as a credential.
fn progress_frame(token: &ProgressToken, event: &ProgressEvent) -> Value {
pub(super) fn progress_frame(token: &ProgressToken, event: &ProgressEvent) -> Value {
json!({
"jsonrpc": "2.0",
"method": "notifications/progress",
@@ -0,0 +1,197 @@
//! Isolated single-Agent loopback experiment. Not installed in the production router.
//! Each instance owns one route and one SDK manager; no durable store is replaced.
use super::{
AgentRoutePath, AppState,
lifecycle::InFlightScope,
metrics::ActiveStreamGuard,
rmcp_tools::{RmcpRequestIdentity, RmcpTools},
stages::{enforce_traced_rate_limit, require_traced_machine_access},
};
use crate::{
protocol::{self, ContinuationSupport, RequestEra},
transport,
};
use axum::{
Router,
body::{Body, to_bytes},
extract::Request,
http::{Method, StatusCode},
response::{IntoResponse, Response},
};
use crank_core::PlatformApiKeyScope;
use futures_util::StreamExt;
use rmcp::transport::streamable_http_server::{
StreamableHttpServerConfig, StreamableHttpService, session::local::LocalSessionManager,
};
use serde_json::Value;
use std::sync::Arc;
const BODY_LIMIT: usize = 2 * 1024 * 1024;
pub(super) fn router(
state: Arc<AppState>,
path: AgentRoutePath,
active: Arc<std::sync::atomic::AtomicUsize>,
) -> Router {
let handler_state = state.clone();
let mut config = StreamableHttpServerConfig::default().with_json_response(true);
config.max_request_body_bytes = BODY_LIMIT;
let shutdown = Arc::new(config.cancellation_token.clone().drop_guard());
let mut manager = LocalSessionManager::default();
manager.session_config.channel_capacity = 16;
let service = StreamableHttpService::new(
move || {
Ok(RmcpTools {
state: handler_state.clone(),
active: active.clone(),
})
},
Arc::new(manager),
config,
);
let route = format!("/v1/{}/{}", path.workspace_slug, path.agent_slug);
Router::new()
.route(
&route,
axum::routing::any(move |request: Request| {
let state = state.clone();
let path = path.clone();
let service = service.clone();
let shutdown = shutdown.clone();
async move {
let _shutdown = shutdown;
let (mut parts, body) = request.into_parts();
if let Err(status) =
transport::validate_origin(&state.allowed_origins, &parts.headers)
{
return status.into_response();
}
let bytes = match to_bytes(body, BODY_LIMIT).await {
Ok(bytes) => bytes,
Err(_) => return StatusCode::PAYLOAD_TOO_LARGE.into_response(),
};
let message: Value = if parts.method == Method::POST {
match serde_json::from_slice(&bytes) {
Ok(message) => message,
Err(_) => return StatusCode::BAD_REQUEST.into_response(),
}
} else {
Value::Null
};
let method = message["method"].as_str().unwrap_or("");
let required = if method == "tools/call" {
PlatformApiKeyScope::Write
} else {
PlatformApiKeyScope::Read
};
let credential = match require_traced_machine_access(
&state,
&path,
&parts.headers,
required,
)
.await
{
Ok(credential) => credential,
Err(error) => return error.into_response(),
};
let session = match transport::session_id_from_headers(&parts.headers) {
Ok(session) => session,
Err(_) => {
return protocol::ambiguous_session_carrier_response(
&parts.headers,
&message,
);
}
};
let era = if parts.method == Method::POST {
if let Err(response) = protocol::validate_jsonrpc_envelope(&message) {
return *response;
}
if let Err(status) = transport::negotiate_post_response_mode(&parts.headers)
{
return status.into_response();
}
match protocol::resolve_request_identity(&parts.headers, &message) {
Ok(identity) => identity.era,
Err(response) => return *response,
}
} else {
if let Err(response) = protocol::session_lifecycle_admission(&parts.headers)
{
return *response;
}
RequestEra::Legacy
};
if matches!(era, RequestEra::Modern) && session.is_some() {
return protocol::modern_carrier_conflict_response(&message);
}
if let Err(error) =
enforce_traced_rate_limit(&state, &path, &parts.headers).await
{
return crate::rate_limit::rate_limited_status_response(error);
}
// SDK cancellation is keyed only by request id. Never forward an unchecked cancel.
if method == "notifications/cancelled" {
if let Some(session_id) = session {
state.in_flight.cancel(
&InFlightScope {
session_id,
owner: credential
.platform_api_key_id
.as_ref()
.map(|id| id.as_str())
.unwrap_or("")
.to_owned(),
},
&message["params"]["requestId"],
);
}
return StatusCode::ACCEPTED.into_response();
}
let Some(context) = parts
.extensions
.get::<crate::request_context::RequestContext>()
else {
return StatusCode::INTERNAL_SERVER_ERROR.into_response();
};
let correlation = context.correlation.clone();
parts.extensions.insert(RmcpRequestIdentity {
workspace_slug: path.workspace_slug,
agent_slug: path.agent_slug,
credential,
correlation,
continuation: ContinuationSupport::from_supported(false),
locale: crate::tool_error::execution_locale(&message),
session_id: session,
progress_meta: message.pointer("/params/_meta").cloned(),
sse_acceptable: transport::accepts_event_stream(&parts.headers),
});
// Legacy SDK calls outlive disconnected bodies: both lifetimes share one slot.
let permit = match ActiveStreamGuard::try_acquire(&state.session_slots) {
Ok(permit) => Arc::new(permit),
Err(_) => return StatusCode::TOO_MANY_REQUESTS.into_response(),
};
if method == "tools/call" {
parts.extensions.insert(permit.clone());
}
let response = service
.handle(Request::from_parts(parts, Body::from(bytes)))
.await;
let (parts, body) = response.into_parts();
let stream = futures_util::stream::unfold(
(Box::pin(Body::new(body).into_data_stream()), permit),
|(mut stream, permit)| async move {
stream.next().await.map(|chunk| (chunk, (stream, permit)))
},
);
Response::from_parts(parts, Body::from_stream(stream))
}
}),
)
.layer(axum::middleware::from_fn(
crate::request_context::apply_request_context,
))
}
@@ -0,0 +1,43 @@
//! Behavioural ATDD for rmcp 3.7.0 LocalSessionManager reconnect/restart semantics.
use rmcp::transport::streamable_http_server::session::{
SessionManager, local::LocalSessionManager,
};
#[tokio::test]
async fn rmcp_local_session_manager_preserves_access_to_created_session() {
let manager = LocalSessionManager::default();
let (session_id, _transport) = manager
.create_session()
.await
.expect("local manager must create a session");
assert!(
manager
.has_session(&session_id)
.await
.expect("live manager must answer has_session"),
"a live manager must keep access to a session it created"
);
}
#[tokio::test]
async fn rmcp_fresh_session_manager_without_external_store_rejects_known_session_id() {
let first_manager = LocalSessionManager::default();
let (session_id, _transport) = first_manager
.create_session()
.await
.expect("first local manager must create a session");
let second_manager = LocalSessionManager::default();
assert!(
!second_manager
.has_session(&session_id)
.await
.expect("fresh manager must answer has_session"),
"a fresh in-memory manager must not claim ownership of another manager's session"
);
}
@@ -0,0 +1,258 @@
//! Isolated rmcp 3.7.0 Tools adapter over Crank's existing typed Tools service.
//!
//! This module deliberately does not provide a second command engine. It owns only
//! the verified request identity (`ServiceContext` data) and delegates both
//! `tools/list` and `tools/call` to `handle_tools_command` via rmcp's
//! `ServerHandler` trait. HTTP admission must supply identity for each request.
use std::sync::Arc;
use crank_core::{CorrelationContext, ExecutionLocale};
use crate::app::{AppState, lifecycle::ToolCallLifecycle};
use crate::auth::VerifiedMachineCredential;
use crate::protocol::{
ContinuationSupport, ServiceContext, ToolCallCommand, ToolsCommand, ToolsListCommand,
ToolsOutcome, handle_tools_command,
};
/// Long-lived handler: never stores credentials obtained on initialization.
#[derive(Clone)]
pub(super) struct RmcpTools {
pub(super) state: Arc<AppState>,
pub(super) active: Arc<std::sync::atomic::AtomicUsize>,
}
struct ActiveCall(Arc<std::sync::atomic::AtomicUsize>);
impl Drop for ActiveCall {
fn drop(&mut self) {
self.0.fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
}
}
/// Server-created identity attached to the individual admitted HTTP request.
#[derive(Clone)]
pub(super) struct RmcpRequestIdentity {
pub(super) workspace_slug: String,
pub(super) agent_slug: String,
pub(super) credential: VerifiedMachineCredential,
pub(super) correlation: CorrelationContext,
pub(super) continuation: ContinuationSupport,
pub(super) locale: ExecutionLocale,
pub(super) session_id: Option<String>,
pub(super) progress_meta: Option<serde_json::Value>,
pub(super) sse_acceptable: bool,
}
impl RmcpRequestIdentity {
/// Build the neutral `ServiceContext` borrowed from this adapter's owned data.
pub(super) fn service_context(&self) -> ServiceContext<'_> {
ServiceContext {
workspace_slug: &self.workspace_slug,
agent_slug: &self.agent_slug,
credential: &self.credential,
correlation: &self.correlation,
continuation: self.continuation,
locale: self.locale,
}
}
}
impl RmcpTools {
/// Delegate one neutral Tools command to the existing shared service.
pub(super) async fn handle(
&self,
identity: &RmcpRequestIdentity,
command: ToolsCommand,
lifecycle: Option<ToolCallLifecycle>,
) -> ToolsOutcome {
handle_tools_command(&self.state, identity.service_context(), command, lifecycle).await
}
pub(super) async fn list_tools(
&self,
identity: &RmcpRequestIdentity,
command: ToolsListCommand,
lifecycle: Option<ToolCallLifecycle>,
) -> ToolsOutcome {
self.handle(identity, ToolsCommand::List(command), lifecycle)
.await
}
pub(super) async fn call_tool(
&self,
identity: &RmcpRequestIdentity,
command: ToolCallCommand,
lifecycle: Option<ToolCallLifecycle>,
) -> ToolsOutcome {
self.handle(identity, ToolsCommand::Call(command), lifecycle)
.await
}
}
use rmcp::ErrorData as McpError;
use rmcp::model::{
CallToolRequestParams, CallToolResult, ContentBlock, ListToolsResult, PaginatedRequestParams,
Tool,
};
use rmcp::service::RequestContext;
use rmcp::{RoleServer, ServerHandler};
fn request_identity(context: &RequestContext<RoleServer>) -> Result<RmcpRequestIdentity, McpError> {
context
.extensions
.get::<axum::http::request::Parts>()
.and_then(|parts| parts.extensions.get::<RmcpRequestIdentity>())
.cloned()
.ok_or_else(|| McpError::internal_error("missing authenticated request context", None))
}
impl ServerHandler for RmcpTools {
fn supported_protocol_versions(
&self,
) -> std::borrow::Cow<'static, [rmcp::model::ProtocolVersion]> {
std::borrow::Cow::Borrowed(&[
rmcp::model::ProtocolVersion::V_2025_11_25,
rmcp::model::ProtocolVersion::V_2026_07_28,
])
}
fn get_info(&self) -> rmcp::model::ServerConfig {
let mut info = rmcp::model::ServerConfig::default();
info.capabilities = rmcp::model::ServerCapabilities::builder()
.enable_tools()
.build();
info
}
fn list_tools(
&self,
request: Option<PaginatedRequestParams>,
context: RequestContext<RoleServer>,
) -> impl std::future::Future<Output = Result<ListToolsResult, McpError>> + Send + '_ {
let request = request.unwrap_or_default();
async move {
let identity = request_identity(&context)?;
let cursor = request.cursor;
let command = crate::protocol::ToolsListCommand {
cursor,
limit: None,
};
match self.list_tools(&identity, command, None).await {
crate::protocol::ToolsOutcome::List { tools, next_cursor } => {
let tools = tools
.into_iter()
.map(serde_json::from_value::<Tool>)
.collect::<Result<Vec<_>, _>>()
.map_err(|_| {
McpError::internal_error("invalid tool catalog entry", None)
})?;
Ok(ListToolsResult {
tools,
next_cursor,
..Default::default()
})
}
crate::protocol::ToolsOutcome::InvalidParams(message) => {
Err(McpError::invalid_params(message, None))
}
_ => Err(McpError::internal_error("crate catalog unavailable", None)),
}
}
}
async fn call_tool(
&self,
request: CallToolRequestParams,
context: RequestContext<RoleServer>,
) -> Result<rmcp::model::CallToolResponse, McpError> {
let identity = request_identity(&context)?;
let arguments = request
.arguments
.map(serde_json::Value::Object)
.unwrap_or_else(|| serde_json::json!({}));
let command = crate::protocol::ToolCallCommand {
tool_name: request.name.to_string(),
arguments,
confirmation_token: None,
};
let token = identity
.sse_acceptable
.then(|| super::lifecycle::token_from_meta(identity.progress_meta.as_ref()))
.flatten();
// Observe future cleanup directly in the isolated loopback oracle.
self.active
.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
let _active = ActiveCall(self.active.clone());
let (mut lifecycle, mut events) = ToolCallLifecycle::new(token.clone());
let entry = identity.session_id.as_ref().and_then(|session_id| {
self.state.in_flight.register(
&super::lifecycle::InFlightScope {
session_id: session_id.clone(),
owner: identity
.credential
.platform_api_key_id
.as_ref()
.map(|id| id.as_str())
.unwrap_or("")
.to_owned(),
},
&serde_json::to_value(&context.id).expect("request id serializes"),
)
});
if let Some(entry) = &entry {
lifecycle = lifecycle.with_cancel(entry.cancel_signal());
}
let call = self.call_tool(&identity, command, Some(lifecycle.clone()));
tokio::pin!(call);
let outcome = loop {
tokio::select! {
biased;
event = async { match events.as_mut() { Some(events) => events.recv().await, None => std::future::pending().await } } => {
if let Some(event) = event {
if let Some(token) = &token {
let params = serde_json::from_value(super::lifecycle::progress_frame(token, &event)["params"].clone()).map_err(|_| McpError::internal_error("invalid progress event", None))?;
let _ = context.peer.notify_progress(params).await;
}
} else { events = None; }
}
outcome = &mut call => break outcome,
_ = lifecycle.cancelled() => { return Err(McpError::internal_error("request cancelled", None)); },
_ = context.ct.cancelled() => { return Err(McpError::internal_error("request cancelled", None)); },
}
};
match outcome {
crate::protocol::ToolsOutcome::Call(outcome) => match outcome {
crate::protocol::ToolCallOutcome::Completed(value)
| crate::protocol::ToolCallOutcome::ApprovalPending(value) => {
let text = value.to_string();
let mut result = CallToolResult::default();
result.content = vec![ContentBlock::text(text)];
result.structured_content = if value.is_null() { None } else { Some(value) };
Ok(result.into())
}
crate::protocol::ToolCallOutcome::ApprovalUnavailable(_) => {
let mut result = CallToolResult::default();
result.is_error = Some(true);
result.content = vec![ContentBlock::text("approval elicitation not supported")];
Ok(result.into())
}
crate::protocol::ToolCallOutcome::InvalidParams(message) => {
Err(McpError::invalid_params(message, None))
}
crate::protocol::ToolCallOutcome::Error(contract) => {
let text = serde_json::to_string(&contract).unwrap_or_default();
let mut result = CallToolResult::default();
result.is_error = Some(true);
result.content = vec![ContentBlock::text(text)];
Ok(result.into())
}
crate::protocol::ToolCallOutcome::InternalFailure => {
Err(McpError::internal_error("tool execution failed", None))
}
},
crate::protocol::ToolsOutcome::InvalidParams(message) => {
Err(McpError::invalid_params(message, None))
}
_ => Err(McpError::internal_error("crate catalog unavailable", None)),
}
}
}
@@ -415,7 +415,7 @@ pub(super) fn agent_id() -> AgentId {
AgentId::new(format!("agent_{AGENT_SLUG}"))
}
pub(super) async fn publish_agent(
pub(crate) async fn publish_agent(
registry: &PostgresRegistry,
operation: &Operation<Schema, MappingSet>,
) {
@@ -470,7 +470,7 @@ pub(super) async fn publish_agent(
.expect("the agent must be published");
}
pub(super) async fn create_api_key(registry: &PostgresRegistry) -> String {
pub(crate) async fn create_api_key(registry: &PostgresRegistry) -> String {
let secret = format!("crk_dispatch_observer_{}", uuid::Uuid::now_v7().simple());
let api_key = PlatformApiKey {
id: PlatformApiKeyId::new("pk_dispatch_observer"),
@@ -500,7 +500,7 @@ pub(super) fn hash_access_secret(secret: &str) -> String {
URL_SAFE_NO_PAD.encode(Sha256::digest(secret.as_bytes()))
}
pub(super) fn test_operation(base_url: &str) -> Operation<Schema, MappingSet> {
pub(crate) fn test_operation(base_url: &str) -> Operation<Schema, MappingSet> {
Operation {
id: OperationId::new(format!("op_{TOOL_NAME}")),
name: TOOL_NAME.to_owned(),
@@ -0,0 +1,409 @@
use super::*;
#[tokio::test]
async fn rmcp_http_catalog_follows_new_publication_without_reinitializing() {
let h = Harness::new().await;
let session = h.initialize().await;
let list = json!({"jsonrpc":"2.0","id":60,"method":"tools/list"});
let listed = frames(
h.request("2025-11-25", Some(&session), &list)
.send()
.await
.unwrap(),
)
.await;
assert_eq!(
listed.last().unwrap()["result"]["tools"][0]["name"],
"create_lead"
);
let workspace = crank_core::WorkspaceId::new("ws_default");
let agent = crank_core::AgentId::new("agent_dispatch-observer");
let now = time::OffsetDateTime::now_utc();
let version = crank_core::AgentVersion {
agent_id: agent.clone(),
version: 2,
status: crank_core::AgentStatus::Draft,
instructions: json!({}),
tool_selection_policy: crank_core::ToolSelectionPolicy::default(),
created_at: now,
};
let bindings = [crank_core::AgentOperationBinding {
operation_id: crank_core::OperationId::new("op_create_lead"),
operation_version: 1,
tool_name: "new_publication_tool".into(),
tool_title: "New Tool".into(),
tool_description_override: None,
enabled: true,
}];
h.state
.registry
.create_agent_draft_version(crank_registry::CreateAgentDraftVersionRequest {
workspace_id: &workspace,
agent_id: &agent,
version: &version,
bindings: &bindings,
updated_at: &now,
})
.await
.unwrap();
h.state
.registry
.publish_agent(crank_registry::PublishAgentRequest {
workspace_id: &workspace,
agent_id: &agent,
version: 2,
published_at: &now,
published_by: Some("alice"),
expected_state: None,
})
.await
.unwrap();
let listed = frames(
h.request("2025-11-25", Some(&session), &list)
.send()
.await
.unwrap(),
)
.await;
assert_eq!(
listed.last().unwrap()["result"]["tools"][0]["name"],
"new_publication_tool"
);
let mut message = call(61, "new-publication@example.test", false, false);
message["params"]["name"] = json!("new_publication_tool");
let result = frames(
h.request("2025-11-25", Some(&session), &message)
.send()
.await
.unwrap(),
)
.await;
assert_eq!(
result.last().unwrap()["result"]["structuredContent"]["id"],
"lead_for_new-publication@example.test"
);
assert_eq!(h.calls.load(Ordering::SeqCst), 1);
}
#[tokio::test]
async fn rmcp_http_identical_request_ids_in_two_sessions_cancel_independently() {
let h = Harness::new().await;
let a = h.initialize().await;
let b = h.initialize().await;
let message = call(62, "slow-same-id@example.test", false, true);
let first = h
.request("2025-11-25", Some(&a), &message)
.send()
.await
.unwrap();
let second = h
.request("2025-11-25", Some(&b), &message)
.send()
.await
.unwrap();
wait_count(&h.calls, 2).await;
let cancel =
json!({"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":62}});
assert_eq!(
h.request("2025-11-25", Some(&a), &cancel)
.send()
.await
.unwrap()
.status(),
202
);
wait_count(&h.active, 1).await;
assert_eq!(
h.request("2025-11-25", Some(&b), &cancel)
.send()
.await
.unwrap()
.status(),
202
);
wait_count(&h.active, 0).await;
for response in [first, second] {
assert_eq!(
frames(response).await.last().unwrap()["error"]["message"],
"request cancelled"
);
}
assert_eq!(h.calls.load(Ordering::SeqCst), 2);
}
// Independent QA: dropped legacy response bodies must not bypass the stream ceiling.
#[tokio::test]
async fn rmcp_http_qa_legacy_disconnect_does_not_bypass_admission() {
let h = Harness::new().await;
let session = h.initialize().await;
let mut admitted = Vec::new();
for id in 100..117 {
let response = h
.request(
"2025-11-25",
Some(&session),
&call(id, "slow-qa-limit@example.test", false, true),
)
.send()
.await
.unwrap();
if response.status() == 429 {
break;
}
assert_eq!(response.status(), 200);
admitted.push(id);
wait_count(&h.calls, admitted.len()).await;
drop(response);
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
}
let active_before_cleanup = h.active.load(Ordering::SeqCst);
let free_slots = h.state.session_slots.available_permits();
let calls_before_cleanup = h.calls.load(Ordering::SeqCst);
for id in &admitted {
let cancel =
json!({"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":id}});
assert_eq!(
h.request("2025-11-25", Some(&session), &cancel)
.send()
.await
.unwrap()
.status(),
202
);
}
wait_count(&h.active, 0).await;
assert!(
admitted.len() <= 16 && calls_before_cleanup <= 16 && active_before_cleanup <= 16,
"legacy disconnect bypassed admission: admitted={}, calls={calls_before_cleanup}, active={active_before_cleanup}, free_slots={free_slots}",
admitted.len()
);
tokio::time::timeout(std::time::Duration::from_secs(2), async {
while h.state.session_slots.available_permits() != 16 {
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
})
.await
.expect("owned cancellation cleanup must release all admission permits");
assert_eq!(h.state.session_slots.available_permits(), 16);
// After cleanup, normal admission and REST execution must work again.
let calls_before = h.calls.load(Ordering::SeqCst);
let message = call(199, "recovery-after-cleanup@example.test", false, false);
let response = h
.request("2025-11-25", Some(&session), &message)
.send()
.await
.unwrap();
assert_eq!(response.status(), 200);
let result = frames(response).await;
assert_eq!(
result.last().unwrap()["result"]["structuredContent"]["id"],
"lead_for_recovery-after-cleanup@example.test"
);
assert_eq!(h.calls.load(Ordering::SeqCst), calls_before + 1);
}
#[tokio::test]
async fn rmcp_http_correlation_headers_preserve_each_concurrent_request() {
let h = Harness::new().await;
let first = call(50, "correlation-first@example.test", true, false);
let second = call(51, "correlation-second@example.test", true, false);
let (a, b) = tokio::join!(
h.request("2026-07-28", None, &first)
.header("x-request-id", "rmcp-oracle-first")
.send(),
h.request("2026-07-28", None, &second)
.header("x-request-id", "rmcp-oracle-second")
.send()
);
let a = a.unwrap();
let b = b.unwrap();
assert_eq!(a.headers()["x-request-id"], "rmcp-oracle-first");
assert_eq!(b.headers()["x-request-id"], "rmcp-oracle-second");
assert_eq!(
frames(a).await[0]["result"]["structuredContent"]["id"],
"lead_for_correlation-first@example.test"
);
assert_eq!(
frames(b).await[0]["result"]["structuredContent"]["id"],
"lead_for_correlation-second@example.test"
);
}
#[tokio::test]
async fn rmcp_http_stream_limit_rejects_without_dispatch_then_recovers() {
let h = Harness::new().await;
let permits = h
.state
.session_slots
.clone()
.acquire_many_owned(16)
.await
.unwrap();
let message = call(40, "limit@example.test", true, false);
assert_eq!(
h.request("2026-07-28", None, &message)
.send()
.await
.unwrap()
.status(),
429
);
assert_eq!(h.calls.load(Ordering::SeqCst), 0);
drop(permits);
let response = h
.request("2026-07-28", None, &message)
.send()
.await
.unwrap();
assert_eq!(
frames(response).await[0]["result"]["structuredContent"]["id"],
"lead_for_limit@example.test"
);
assert_eq!(h.calls.load(Ordering::SeqCst), 1);
}
#[tokio::test]
async fn rmcp_http_rate_limit_is_existing_admission_not_sdk_default() {
let h = Harness::with_rate(1).await;
let list = json!({"jsonrpc":"2.0","id":41,"method":"tools/list","params":{"_meta":meta()}});
assert_eq!(
h.request("2026-07-28", None, &list)
.send()
.await
.unwrap()
.status(),
200
);
assert_eq!(
h.request(
"2026-07-28",
None,
&call(42, "rate@example.test", true, false)
)
.send()
.await
.unwrap()
.status(),
429
);
assert_eq!(h.calls.load(Ordering::SeqCst), 0);
}
#[tokio::test]
async fn rmcp_http_current_durable_store_survives_recreation_but_is_not_sdk_store() {
use crate::session::{PostgresTransportSessionStore, TransportSessionStore};
let h = Harness::new().await;
let store = PostgresTransportSessionStore::from_pool(h.state.registry.pool().clone())
.await
.unwrap();
let now = time::OffsetDateTime::now_utc();
let id = store
.create(
"2025-11-25",
"default",
"dispatch-observer",
false,
now,
Some(now + time::Duration::hours(24)),
)
.await
.unwrap();
assert!(store.mark_initialized(&id, now).await.unwrap());
drop(store);
let restarted = PostgresTransportSessionStore::from_pool(h.state.registry.pool().clone())
.await
.unwrap();
let persisted = restarted.get(&id).await.unwrap().unwrap();
assert!(persisted.initialized);
assert_eq!(persisted.workspace_slug, "default");
assert_eq!(persisted.protocol_version, "2025-11-25");
assert_eq!(
h.request(
"2025-11-25",
Some(&id),
&call(43, "durable@example.test", false, false)
)
.send()
.await
.unwrap()
.status(),
404
);
assert!(
restarted.get(&id).await.unwrap().is_some(),
"SDK experiment never mutates existing storage"
);
assert_eq!(h.calls.load(Ordering::SeqCst), 0);
}
#[tokio::test]
async fn rmcp_http_json_modern_and_legacy_sse_only_gap_are_observed() {
let h = Harness::new().await;
let session = h.initialize().await;
let response = h
.request(
"2026-07-28",
None,
&call(44, "json@example.test", true, false),
)
.send()
.await
.unwrap();
assert!(
response.headers()["content-type"]
.to_str()
.unwrap()
.starts_with("application/json")
);
assert_eq!(
frames(response).await[0]["result"]["structuredContent"]["id"],
"lead_for_json@example.test"
);
// Build a JSON-only request (not two contradictory Accept carriers).
let response = reqwest::Client::new()
.post(format!("{}/v1/default/dispatch-observer", h.server.1))
.bearer_auth(&h.key)
.header("Accept", "application/json")
.header("MCP-Protocol-Version", "2025-11-25")
.header("MCP-Session-Id", &session)
.json(&call(45, "legacy-json@example.test", false, false))
.send()
.await
.unwrap();
assert_eq!(
response.status(),
406,
"bundled SDK legacy mode requires SSE Accept; not transport parity"
);
assert_eq!(h.calls.load(Ordering::SeqCst), 1);
}
#[tokio::test]
async fn rmcp_http_concurrent_keys_keep_outputs_and_cancel_ownership_separate() {
let h = Harness::new().await;
let session = h.initialize().await;
sqlx::query("insert into platform_api_keys (id, workspace_id, agent_id, key_kind, name, prefix, secret_hash, scopes_json, status, created_at) select 'pk_second', workspace_id, agent_id, key_kind, 'second', prefix, $1, scopes_json, status, created_at from platform_api_keys where id = 'pk_dispatch_observer'")
.bind(crate::access::hash_access_secret("test-second-valid-key")).execute(h.state.registry.pool()).await.unwrap();
let first = call(46, "first@example.test", false, false);
let second = call(47, "second@example.test", false, false);
let (a, b) = tokio::join!(
h.request("2025-11-25", Some(&session), &first).send(),
h.request_as(
"2025-11-25",
Some(&session),
&second,
"test-second-valid-key"
)
.send()
);
assert_eq!(
frames(a.unwrap()).await.last().unwrap()["result"]["structuredContent"]["id"],
"lead_for_first@example.test"
);
assert_eq!(
frames(b.unwrap()).await.last().unwrap()["result"]["structuredContent"]["id"],
"lead_for_second@example.test"
);
assert_eq!(h.calls.load(Ordering::SeqCst), 2);
}
@@ -0,0 +1,563 @@
//! Wire oracle for the isolated SDK adapter, with real registry and REST execution.
#[path = "rmcp_http_limits.rs"]
mod limits;
use super::{AgentRoutePath, dispatch_observer::support, rmcp_http, rmcp_tools_tests::test_state};
use axum::{Json, Router, extract::State, routing::post};
use serde_json::{Value, json};
use std::sync::{
Arc,
atomic::{AtomicUsize, Ordering},
};
struct Server(tokio::task::JoinHandle<()>, String);
impl Drop for Server {
fn drop(&mut self) {
self.0.abort();
}
}
async fn serve(router: Router) -> Server {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("http://{}", listener.local_addr().unwrap());
Server(
tokio::spawn(async move {
axum::serve(listener, router).await.unwrap();
}),
url,
)
}
async fn upstream(State(count): State<Arc<AtomicUsize>>, Json(body): Json<Value>) -> Json<Value> {
count.fetch_add(1, Ordering::SeqCst);
if body["email"].as_str().unwrap().starts_with("slow") {
tokio::time::sleep(std::time::Duration::from_secs(8)).await;
}
Json(json!({"id": format!("lead_for_{}", body["email"].as_str().unwrap())}))
}
struct Harness {
server: Server,
_upstream: Server,
key: String,
calls: Arc<AtomicUsize>,
state: Arc<super::AppState>,
active: Arc<AtomicUsize>,
}
impl Harness {
async fn new() -> Self {
Self::with_rate(10_000).await
}
async fn with_rate(burst: u32) -> Self {
let mut state = test_state().await;
Arc::get_mut(&mut state).unwrap().api_rate_limiter = crank_runtime::RequestRateLimiter::new(
crank_runtime::RequestRateLimitConfig::new(burst, burst).unwrap(),
);
let calls = Arc::new(AtomicUsize::new(0));
let upstream = serve(
Router::new()
.route("/crm/leads", post(upstream))
.with_state(calls.clone()),
)
.await;
let mut operation = support::test_operation(&upstream.1);
operation.execution_config.timeout_ms = 10_000;
state
.registry
.create_operation(
&crank_core::WorkspaceId::new("ws_default"),
&operation,
Some("alice"),
)
.await
.unwrap();
state
.registry
.publish_operation(crank_registry::PublishRequest {
workspace_id: &crank_core::WorkspaceId::new("ws_default"),
operation_id: &operation.id,
version: 1,
published_at: &operation.created_at,
published_by: Some("alice"),
})
.await
.unwrap();
support::publish_agent(&state.registry, &operation).await;
let key = support::create_api_key(&state.registry).await;
let active = Arc::new(AtomicUsize::new(0));
let server = serve(rmcp_http::router(
state.clone(),
AgentRoutePath {
workspace_slug: "default".into(),
agent_slug: "dispatch-observer".into(),
},
active.clone(),
))
.await;
Self {
server,
_upstream: upstream,
key,
calls,
state,
active,
}
}
fn request(
&self,
revision: &str,
session: Option<&str>,
message: &Value,
) -> reqwest::RequestBuilder {
self.request_as(revision, session, message, &self.key)
}
fn request_as(
&self,
revision: &str,
session: Option<&str>,
message: &Value,
key: &str,
) -> reqwest::RequestBuilder {
let mut request = reqwest::Client::new()
.post(format!("{}/v1/default/dispatch-observer", self.server.1))
.bearer_auth(key)
.header("Accept", "application/json, text/event-stream")
.header("MCP-Protocol-Version", revision);
if let Some(session) = session {
request = request.header("MCP-Session-Id", session);
}
if revision == "2026-07-28" {
request = request.header("Mcp-Method", message["method"].as_str().unwrap());
if let Some(name) = message.pointer("/params/name").and_then(Value::as_str) {
request = request.header("Mcp-Name", name);
}
}
request
.json(message)
.timeout(std::time::Duration::from_secs(10))
}
async fn initialize(&self) -> String {
let message = json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"oracle","version":"1"}}});
let response = self
.request("2025-11-25", None, &message)
.send()
.await
.unwrap();
assert_eq!(response.status(), 200);
let session = response.headers()["MCP-Session-Id"]
.to_str()
.unwrap()
.to_owned();
let body = frames(response).await;
assert_eq!(
body.last().unwrap()["result"]["protocolVersion"],
"2025-11-25"
);
let response = self
.request(
"2025-11-25",
Some(&session),
&json!({"jsonrpc":"2.0","method":"notifications/initialized"}),
)
.send()
.await
.unwrap();
assert_eq!(response.status(), 202);
session
}
}
fn meta() -> Value {
json!({"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{},"io.modelcontextprotocol/clientInfo":{"name":"oracle","version":"1"}})
}
async fn frames(response: reqwest::Response) -> Vec<Value> {
let status = response.status();
let text = response.text().await.unwrap();
if let Ok(json) = serde_json::from_str(&text) {
return vec![json];
}
let values: Vec<Value> = text
.lines()
.filter_map(|line| line.strip_prefix("data:"))
.filter_map(|data| serde_json::from_str(data.trim()).ok())
.collect();
assert!(!values.is_empty(), "{status}: {text}");
values
}
#[tokio::test]
async fn rmcp_http_positive_tools_both_revisions() {
let h = Harness::new().await;
let session = h.initialize().await;
for (revision, session) in [("2025-11-25", Some(session.as_str())), ("2026-07-28", None)] {
if session.is_none() {
let discover = json!({"jsonrpc":"2.0","id":2,"method":"server/discover","params":{"_meta":meta()}});
let response = h.request(revision, None, &discover).send().await.unwrap();
assert_eq!(response.status(), 200);
assert!(!frames(response).await[0]["result"].is_null());
}
let list = json!({"jsonrpc":"2.0","id":3,"method":"tools/list","params":{"_meta": if session.is_none() { meta() } else { json!({}) }}});
let response = h.request(revision, session, &list).send().await.unwrap();
assert_eq!(response.status(), 200);
assert!(response.headers().contains_key("x-request-id"));
let listed = frames(response).await;
assert_eq!(
listed.last().unwrap()["result"]["tools"][0]["name"],
"create_lead"
);
let call = json!({"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"create_lead","arguments":{"email":"rmcp@example.test"},"_meta":if session.is_none() { meta() } else { json!({}) }}});
let response = h.request(revision, session, &call).send().await.unwrap();
assert_eq!(response.status(), 200);
if session.is_none() {
assert!(!response.headers().contains_key("MCP-Session-Id"));
}
let result = frames(response).await;
assert_eq!(
result.last().unwrap()["result"]["structuredContent"]["id"],
"lead_for_rmcp@example.test",
"{result:?}"
);
}
assert_eq!(h.calls.load(Ordering::SeqCst), 2);
}
fn call(id: i64, email: &str, modern: bool, progress: bool) -> Value {
let mut metadata = if modern { meta() } else { json!({}) };
if progress {
metadata["progressToken"] = json!("wire-progress");
}
json!({"jsonrpc":"2.0","id":id,"method":"tools/call","params":{"name":"create_lead","arguments":{"email":email},"_meta":metadata}})
}
#[tokio::test]
async fn rmcp_http_credentials_revalidated_after_initialize_and_no_outbound() {
let h = Harness::new().await;
let session = h.initialize().await;
let message = call(10, "denied@example.test", false, false);
assert_eq!(
h.request_as("2025-11-25", Some(&session), &message, "invalid-test-key")
.send()
.await
.unwrap()
.status(),
401
);
// A scope change and expiry are authoritative registry changes, not session credentials.
sqlx::query("update platform_api_keys set scopes_json = '[\"read\"]'::jsonb where id = 'pk_dispatch_observer'").execute(h.state.registry.pool()).await.unwrap();
assert_eq!(
h.request("2025-11-25", Some(&session), &message)
.send()
.await
.unwrap()
.status(),
403
);
sqlx::query("update platform_api_keys set scopes_json = '[\"read\",\"write\"]'::jsonb, expires_at = now() - interval '1 second' where id = 'pk_dispatch_observer'").execute(h.state.registry.pool()).await.unwrap();
assert_eq!(
h.request("2025-11-25", Some(&session), &message)
.send()
.await
.unwrap()
.status(),
401
);
sqlx::query("update platform_api_keys set expires_at = null where id = 'pk_dispatch_observer'")
.execute(h.state.registry.pool())
.await
.unwrap();
h.state
.registry
.revoke_platform_api_key(
&crank_core::WorkspaceId::new("ws_default"),
&crank_core::PlatformApiKeyId::new("pk_dispatch_observer"),
&time::OffsetDateTime::now_utc(),
)
.await
.unwrap();
for method in [reqwest::Method::GET, reqwest::Method::DELETE] {
assert_eq!(
reqwest::Client::new()
.request(
method,
format!("{}/v1/default/dispatch-observer", h.server.1)
)
.bearer_auth(&h.key)
.header("MCP-Session-Id", &session)
.header("MCP-Protocol-Version", "2025-11-25")
.header("Accept", "text/event-stream")
.send()
.await
.unwrap()
.status(),
401
);
}
assert_eq!(
h.request("2025-11-25", Some(&session), &message)
.send()
.await
.unwrap()
.status(),
401
);
assert_eq!(h.calls.load(Ordering::SeqCst), 0);
}
#[tokio::test]
async fn rmcp_http_admission_rejects_foreign_route_revision_headers_and_body_overflow() {
let h = Harness::new().await;
let message = call(11, "denied@example.test", true, false);
let response = h
.request("2026-07-28", Some("foreign"), &message)
.send()
.await
.unwrap();
assert_eq!(response.status(), 400);
let response = h
.request("2026-07-28", None, &message)
.header("Mcp-Name", "foreign")
.send()
.await
.unwrap();
assert_eq!(response.status(), 400);
let response = h
.request("2026-07-28", None, &message)
.header("Origin", "https://evil.example")
.send()
.await
.unwrap();
assert_eq!(response.status(), 403);
assert_eq!(
h.request("2030-01-01", None, &message)
.send()
.await
.unwrap()
.status(),
400
);
let response = reqwest::Client::new()
.post(format!("{}/v1/default/foreign-agent", h.server.1))
.bearer_auth(&h.key)
.json(&message)
.send()
.await
.unwrap();
assert_eq!(response.status(), 404);
let response = h
.request("2026-07-28", None, &message)
.body(vec![b' '; 2 * 1024 * 1024 + 1])
.send()
.await
.unwrap();
assert_eq!(response.status(), 413);
assert_eq!(h.calls.load(Ordering::SeqCst), 0);
}
#[tokio::test]
async fn rmcp_http_progress_is_real_and_tool_error_is_not_protocol_error() {
let h = Harness::new().await;
let session = h.initialize().await;
for (revision, session) in [("2025-11-25", Some(session.as_str())), ("2026-07-28", None)] {
let response = h
.request(
revision,
session,
&call(20, "progress@example.test", session.is_none(), true),
)
.send()
.await
.unwrap();
assert_eq!(response.status(), 200);
assert!(
response.headers()["content-type"]
.to_str()
.unwrap()
.starts_with("text/event-stream")
);
let messages = frames(response).await;
let progress: Vec<_> = messages
.iter()
.filter(|m| m["method"] == "notifications/progress")
.collect();
assert_eq!(progress.len(), 3, "{messages:?}");
for (index, phase) in [
"tool_resolved",
"authorization_resolved",
"execution_dispatched",
]
.iter()
.enumerate()
{
assert_eq!(progress[index]["params"]["message"], *phase);
assert_eq!(
progress[index]["params"]["progress"].as_f64(),
Some((index + 1) as f64)
);
assert_eq!(progress[index]["params"]["progressToken"], "wire-progress");
}
let mut invalid = call(21, "unused", session.is_none(), false);
invalid["params"]["arguments"] = json!({"email":123});
let response = h.request(revision, session, &invalid).send().await.unwrap();
let messages = frames(response).await;
let result = messages.last().unwrap();
assert_eq!(result["result"]["isError"], true, "{messages:?}");
assert!(result.get("error").is_none());
}
assert_eq!(h.calls.load(Ordering::SeqCst), 2);
}
#[tokio::test]
async fn rmcp_http_reconnect_live_manager_and_restart_loses_sdk_session() {
let h = Harness::new().await;
let session = h.initialize().await;
for _ in 0..2 {
let response = reqwest::Client::new()
.get(format!("{}/v1/default/dispatch-observer", h.server.1))
.bearer_auth(&h.key)
.header("MCP-Session-Id", &session)
.header("MCP-Protocol-Version", "2025-11-25")
.header("Accept", "text/event-stream")
.send()
.await
.unwrap();
assert_eq!(response.status(), 200);
drop(response);
}
let response = h
.request(
"2025-11-25",
Some(&session),
&call(22, "reconnect@example.test", false, false),
)
.send()
.await
.unwrap();
assert_eq!(
frames(response).await.last().unwrap()["result"]["structuredContent"]["id"],
"lead_for_reconnect@example.test"
);
let fresh = serve(rmcp_http::router(
h.state.clone(),
AgentRoutePath {
workspace_slug: "default".into(),
agent_slug: "dispatch-observer".into(),
},
h.active.clone(),
))
.await;
let response = reqwest::Client::new()
.post(format!("{}/v1/default/dispatch-observer", fresh.1))
.bearer_auth(&h.key)
.header("MCP-Session-Id", &session)
.header("MCP-Protocol-Version", "2025-11-25")
.header("Accept", "application/json, text/event-stream")
.json(&call(23, "restart@example.test", false, false))
.send()
.await
.unwrap();
assert_eq!(
response.status(),
404,
"new SDK manager cannot restore from Crank session storage"
);
assert_eq!(h.calls.load(Ordering::SeqCst), 1);
}
async fn wait_count(counter: &AtomicUsize, expected: usize) {
tokio::time::timeout(std::time::Duration::from_secs(3), async {
while counter.load(Ordering::SeqCst) != expected {
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
})
.await
.expect("bounded wait for the real execution/cleanup");
}
#[tokio::test]
async fn rmcp_http_legacy_cancel_is_owned_by_session_and_current_key() {
let h = Harness::new().await;
let session = h.initialize().await;
let foreign_session = h.initialize().await;
// A second valid credential can use this Agent/session but does not own the first call.
sqlx::query("insert into platform_api_keys (id, workspace_id, agent_id, key_kind, name, prefix, secret_hash, scopes_json, status, created_at) select 'pk_second', workspace_id, agent_id, key_kind, 'second', prefix, $1, scopes_json, status, created_at from platform_api_keys where id = 'pk_dispatch_observer'")
.bind(crate::access::hash_access_secret("test-second-valid-key")).execute(h.state.registry.pool()).await.unwrap();
let response = h
.request(
"2025-11-25",
Some(&session),
&call(30, "slow-cancel@example.test", false, true),
)
.send()
.await
.unwrap();
wait_count(&h.calls, 1).await;
let cancel =
json!({"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":30}});
assert_eq!(
h.request_as(
"2025-11-25",
Some(&session),
&cancel,
"test-second-valid-key"
)
.send()
.await
.unwrap()
.status(),
202
);
assert_eq!(
h.request("2025-11-25", Some(&foreign_session), &cancel)
.send()
.await
.unwrap()
.status(),
202
);
tokio::time::sleep(std::time::Duration::from_millis(75)).await;
assert_eq!(
h.active.load(Ordering::SeqCst),
1,
"foreign cancel must not stop call"
);
assert_eq!(
h.request("2025-11-25", Some(&session), &cancel)
.send()
.await
.unwrap()
.status(),
202
);
wait_count(&h.active, 0).await;
// Gap: SDK emits an error frame where the existing transport suppresses all terminal frames.
let messages = frames(response).await;
assert_eq!(
messages.last().unwrap()["error"]["message"],
"request cancelled"
);
assert!(!messages.iter().any(|m| m.get("result").is_some()));
}
#[tokio::test]
async fn rmcp_http_modern_disconnect_drops_execution_and_releases_stream_slot() {
let h = Harness::new().await;
let response = h
.request(
"2026-07-28",
None,
&call(31, "slow-disconnect@example.test", true, true),
)
.send()
.await
.unwrap();
wait_count(&h.calls, 1).await;
assert_eq!(h.active.load(Ordering::SeqCst), 1);
drop(response);
wait_count(&h.active, 0).await;
tokio::time::timeout(std::time::Duration::from_secs(2), async {
while h.state.session_slots.available_permits() != 16 {
tokio::task::yield_now().await;
}
})
.await
.unwrap();
assert_eq!(
h.calls.load(Ordering::SeqCst),
1,
"disconnect never retries a possible external effect"
);
}
@@ -0,0 +1,178 @@
//! Behavioural ATDD for the rmcp 3.7.0 Tools adapter over the existing typed Tools service.
use std::sync::Arc;
use std::time::Duration;
use crank_core::{
AdmissionSchedulerConfig, CoordinationStateStore, CorrelationContext, ExecutionLocale,
MachineAccessMode, OperationSecurityLevel, PlatformApiKeyScope,
};
use crank_registry::{AdmissionLimits, MigrationAuthority, PostgresRegistry, PostgresTaskStore};
use crank_runtime::{
InMemoryCoordinationStateStore, RequestRateLimitConfig, RequestRateLimiter, SecretCrypto,
TaskService,
};
use rmcp::model::{CallToolRequestParams, PaginatedRequestParams, RequestId};
use rmcp::service::{RequestContext, serve_directly};
use rmcp::{RoleServer, ServerHandler};
use super::{
AppState,
rmcp_tools::{RmcpRequestIdentity, RmcpTools},
};
use crate::app::TaskApplication;
use crate::auth::{CommunityMachineCredentialVerifier, VerifiedMachineCredential};
use crate::catalog::PublishedToolCatalog;
use crate::session::{ActiveSessionMetrics, InMemorySessionStore};
use crate::transport::AllowedOrigins;
pub(super) async fn test_state() -> Arc<AppState> {
let database_url =
crank_test_support::postgres_schema_url_for_task("rmcp_tools_tests", "t_fdcc7df8").await;
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
MigrationAuthority::apply(&pool).await.unwrap();
let registry = PostgresRegistry::connect(&database_url).await.unwrap();
let coordination: Arc<dyn CoordinationStateStore> =
Arc::new(InMemoryCoordinationStateStore::default());
let sessions = Arc::new(InMemorySessionStore::default());
let session_metrics = ActiveSessionMetrics::start(sessions.clone());
let catalog = PublishedToolCatalog::new(registry.clone(), Duration::ZERO, coordination.clone());
let tasks_store = PostgresTaskStore::new(
registry.pool().clone(),
AdmissionLimits::default(),
AdmissionSchedulerConfig::default(),
)
.expect("default admission limits and scheduler weights are valid");
let tasks = Arc::new(TaskApplication::new(
registry.clone(),
Duration::from_secs(60),
coordination.clone(),
TaskService::new(Arc::new(tasks_store)),
));
Arc::new(AppState {
registry,
catalog,
runtime: crank_runtime::community_with_outbound_policy(
crank_runtime::OutboundHttpPolicy::allowing_hosts(["127.0.0.1"]),
)
.build(),
api_rate_limiter: RequestRateLimiter::new(RequestRateLimitConfig {
requests_per_second: 10_000,
burst: 10_000,
}),
artifact_store: None,
secret_crypto: SecretCrypto::new("01234567890123456789012345678901")
.expect("test master key"),
sessions,
session_metrics,
session_slots: Arc::new(tokio::sync::Semaphore::new(16)),
credential_verifier: Arc::new(CommunityMachineCredentialVerifier),
allowed_origins: AllowedOrigins::new(None),
logging_levels: Arc::new(crate::protocol::LogLevelStore::new()),
signal_streams: Arc::new(crate::protocol::StreamRegistry::new()),
in_flight: Arc::new(super::lifecycle::InFlightCalls::new(
super::lifecycle::MAX_IN_FLIGHT_CALLS,
)),
tasks,
})
}
fn verified_credential() -> VerifiedMachineCredential {
VerifiedMachineCredential {
machine_access_mode: MachineAccessMode::StaticAgentKey,
max_security_level: OperationSecurityLevel::Standard,
scopes: vec![PlatformApiKeyScope::Write],
platform_api_key_id: None,
}
}
fn rmcp_tools(state: Arc<AppState>) -> RmcpTools {
RmcpTools {
state,
active: Arc::default(),
}
}
async fn request_context(adapter: &RmcpTools) -> RequestContext<RoleServer> {
let (client_io, server_io) = tokio::io::duplex(1024);
let (server_reader, server_writer) = tokio::io::split(server_io);
let running = serve_directly::<RoleServer, _, _, _, _>(
adapter.clone(),
(server_reader, server_writer),
None,
);
// keep client side alive for transport lifetime
let _ = client_io;
let mut context = RequestContext::new(RequestId::Number(1), running.peer().clone());
let (mut parts, _) = axum::http::Request::new(()).into_parts();
parts.extensions.insert(RmcpRequestIdentity {
workspace_slug: "missing-workspace".into(),
agent_slug: "missing-agent".into(),
credential: verified_credential(),
correlation: CorrelationContext::generate(),
continuation: crate::protocol::ContinuationSupport::from_supported(false),
locale: ExecutionLocale::En,
session_id: None,
progress_meta: None,
sse_acceptable: false,
});
context.extensions.insert(parts);
context
}
#[tokio::test]
async fn rmcp_adapter_rejects_missing_request_identity() {
let adapter = rmcp_tools(test_state().await);
let mut context = request_context(&adapter).await;
context.extensions.remove::<axum::http::request::Parts>();
let result = <RmcpTools as ServerHandler>::list_tools(&adapter, None, context).await;
assert!(
result
.unwrap_err()
.message
.contains("missing authenticated request context")
);
}
#[tokio::test]
async fn rmcp_adapter_list_tools_reports_catalog_unavailable_for_unknown_agent() {
let state = test_state().await;
let adapter = rmcp_tools(state);
let ctx = request_context(&adapter).await;
match <RmcpTools as ServerHandler>::list_tools(
&adapter,
Some(PaginatedRequestParams::default()),
ctx,
)
.await
{
Err(err) => assert!(
err.message.contains("crate catalog unavailable"),
"unexpected error: {}",
err.message
),
Ok(_) => panic!("expected error outcome for unknown agent"),
}
}
#[tokio::test]
async fn rmcp_adapter_call_tool_reports_catalog_unavailable_for_unknown_agent() {
let state = test_state().await;
let adapter = rmcp_tools(state);
let ctx = request_context(&adapter).await;
let request = CallToolRequestParams::new("missing_tool");
match <RmcpTools as ServerHandler>::call_tool(&adapter, request, ctx).await {
Err(err) => assert!(
err.message.contains("crate catalog unavailable"),
"unexpected error: {}",
err.message
),
Ok(_) => panic!("expected error outcome for unknown agent"),
}
}
+17 -4
View File
@@ -19,11 +19,20 @@ struct TestPostgres {
}
pub async fn postgres_database_url() -> &'static str {
&test_postgres().await.database_url
&test_postgres("local-tests").await.database_url
}
pub async fn postgres_schema_url(prefix: &str) -> String {
let database_url = postgres_database_url().await;
create_schema_url(prefix, database_url).await
}
/// The first caller owns the process-wide disposable PostgreSQL container.
pub async fn postgres_schema_url_for_task(prefix: &str, task: &str) -> String {
create_schema_url(prefix, &test_postgres(task).await.database_url).await
}
async fn create_schema_url(prefix: &str, database_url: &str) -> String {
let schema = unique_schema_name(prefix);
let mut connection = connect_admin_with_retry(database_url).await;
@@ -73,22 +82,26 @@ pub fn unique_schema_name(prefix: &str) -> String {
format!("{}_{}", normalized_prefix, uuid::Uuid::now_v7().simple())
}
async fn test_postgres() -> &'static TestPostgres {
async fn test_postgres(task: &str) -> &'static TestPostgres {
POSTGRES
.get_or_init(|| async {
tokio::task::spawn_blocking(start_postgres)
let task = task.to_owned();
tokio::task::spawn_blocking(move || start_postgres(task))
.await
.expect("test PostgreSQL container startup task must complete")
})
.await
}
fn start_postgres() -> TestPostgres {
fn start_postgres(task: String) -> TestPostgres {
let container = Postgres::default()
.with_db_name("crank")
.with_user("crank")
.with_password("crank")
.with_tag("16-alpine")
.with_label("hermes.disposable", "true")
.with_label("hermes.task", task)
.with_label("hermes.board", "crank")
.start()
.expect("test PostgreSQL container must start");
register_container_cleanup(container.id().to_owned());
+27 -19
View File
@@ -195,7 +195,7 @@
| 0 — исполняемый фундамент | `1.1 → 1.2 → 1.3 → 1.4 → 1.5 → 1.6` | Capability Inventory/baseline сначала; затем единые config, migrations, correlation и typed metric contracts. |
| 1 — hardened core | `1.7 → … → 1.16` | Immutable Operation/runtime/outbound и security identity последовательно дают catalog, approvals, history и manual onboarding. |
| 2 — import и modern MCP | `2.1 → … → 2.15`; `3.1 → 3.2 → 3.3 → 3.4 → 3.5`, Resource branch `3.6 → 3.7 → {3.8,3.9,3.10 → 3.11}`, Prompt branch `3.12 → 3.13 → 3.14 → 3.15`, composition `3.16`, затем `3.17 → 3.18 → 3.19 → 3.20` | OpenAPI branch закрывает immutable storage, scoped metadata, reconciliation/recovery, Admin API и UX/evidence; MCP foundation открывает независимые Resources, Prompts и Tasks branches. |
| 3 — durable execution | после `3.4`: `4.1 → 4.2 → 4.3 → {4.4,4.5,4.6} → 4.7 → 4.8 → 4.9 → 4.10` | Admission/persistence/leases предшествуют lifecycle policy, Tasks extension/UI и capacity/recovery evidence. |
| 3 — durable execution | после `3.4`: `4.1 → 4.2 → 4.3 → {4.4,4.5} → 4.7 → 4.8 → 4.9 → 4.10`; business scope 4.6 cancelled | Admission/persistence/leases предшествуют lifecycle policy, Tasks extension/UI и capacity/recovery evidence; business reconciliation не является prerequisite. |
| 4 — operational visibility | `5.1 → … → 5.13` | Correlation/search предшествуют browser/server export; spool/loss evidence и metrics предшествуют Prometheus/Grafana/SLO. |
| 5 — встроенная нагрузка | `6.1 → {6.2,6.3} → 6.4 → 6.5 → 6.6` | Versioned Scenario → модель/authorization → runner → live control/report. |
| 6 — поставка и recovery | `7.1 → … → 7.9` | Config/migration и profiles предшествуют exposure/bundle/hardening; backup/restore предшествуют upgrade. |
@@ -276,7 +276,7 @@ Explicit зависимости Epic 8: `8.1 → 8.2`; `8.3,8.4,8.5,8.7,8.8` з
| 4.3 | 4 | FR-22, FR-23 | 10 | `AT-4.3-01 … AT-4.3-10` |
| 4.4 | 4 | FR-25 | 8 | `AT-4.4-01 … AT-4.4-08` |
| 4.5 | 4 | FR-25 | 4 | `AT-4.5-01 … AT-4.5-04` |
| 4.6 | 4 | FR-25 | 3 | `AT-4.6-01 … AT-4.6-03` |
| 4.6 (business scope cancelled) | 4 | FR-25 | 1 active invariant, 2 historical N/A | `AT-4.6-02`; `AT-4.6-01/03` cancelled, не PASS |
| 4.7 | 4 | FR-21, FR-22, FR-25 | 11 | `AT-4.7-01 … AT-4.7-11` |
| 4.8 | 4 | FR-26 | 6 | `AT-4.8-01 … AT-4.8-06` |
| 4.9 | 4 | FR-26 | 5 | `AT-4.9-01 … AT-4.9-05` |
@@ -1243,16 +1243,23 @@ Explicit зависимости Epic 8: `8.1 → 8.2`; `8.3,8.4,8.5,8.7,8.8` з
**FR:** FR-20 (Tasks cells), FR-21..FR-26.
Пользователь запускает долгие Tools как durable Tasks, наблюдает progress, отменяет, восстанавливает после restart и разрешает `outcome_unknown` без неконтролируемого повторения side effects.
Пользователь запускает долгие Tools как durable Tasks, наблюдает progress, отменяет и восстанавливает protocol-level состояние после restart. При `outcome_unknown` Crank честно сообщает неопределённость; подтверждение внешнего бизнес-эффекта и решение о новой бизнес-попытке принадлежат потребителю.
**Canonical amendment FR-25 / FR-26 / AR9 (решение владельца 31.10.2026, [issue #34](https://git.itexp.me/bsodfather/crank/issues/34)):**
- FR-25 сохраняет input continuation, retry/cancel policy и unknown safety. Business reconciliation, external effect verifier, evidence-bearing operator resolution и confirmed new attempt исключены; исторические AC 4.6 cancelled/not_applicable, не реализованы и не PASS.
- FR-26 сохраняет Task input UI, permission-aware lifecycle, честный unknown и safety-warning. Business reconciliation/evidence UI и новое cross-owner полномочие больше не являются требованием.
- AR9: Crank — MCP proxy/gateway, не business-workflow engine. Temporal/Kafka/verifier не добавляются. Timeout, disconnect и cancel ack не доказывают отсутствие внешнего эффекта; автоматический повтор опасного write запрещён. Опубликованный код и миграции 4.3–4.5 не удаляются.
- Итоговая квалификация использует активную scope; исключённые business AC фиксируются N/A, не PASS, и не блокируют 4.7/4.9/4.10. Остальные release gates, blockers 3.3/P4/auth3.20 и production NO_GO сохраняются. Выполнение #106 не разрешает #107/#108/4.7 или production без отдельного решения.
**Пошаговый интеграционный сценарий:**
1. Опубликовать execution mode и применить admission limits; sync/background/adaptive + fallback (4.1).
2. Атомарно принять durable Task с dispatch intent до acknowledgement (4.2).
3. Исполнить Tasks через PostgreSQL CAS leases и fencing; исключить stale writes/duplicate terminal transitions (4.3).
4. Проверить retry/cancellation/outcome_unknown; input update; reconciliation evidence (4.4–4.6).
4. Проверить retry/cancellation/outcome_unknown; input update и safety warning для unknown (4.4, 4.5; 4.6 business reconciliation отменена).
5. Проверить MCP Tasks extension (`tools/call`, `tasks/get|update|cancel`) и fallback для клиентов без extension (4.7).
6. Найти Tasks и выполнить безопасные Admin actions; проверить input/reconciliation UI (4.8, 4.9).
6. Найти Tasks и выполнить безопасные Admin actions; проверить input UI и unknown-outcome safety display (4.8, 4.9; business reconciliation UI не требуется).
7. Доказать capacity/recovery envelope: ≥128 concurrent, 10 000 queued, restart recovery, crash/partition matrix (4.10).
#### Story 4.1: Публиковать execution mode и применять admission limits
@@ -1345,22 +1352,23 @@ Explicit зависимости Epic 8: `8.1 → 8.2`; `8.3,8.4,8.5,8.7,8.8` з
| `AT-4.5-03` | **Given** input TTL истёк<br>**When** sweeper обрабатывает Task<br>**Then** Task становится `failed` без нового dispatch<br>**And** expiry reason сохраняется в audit. | Отчёт AT-4.5-03: фактический результат указанного When и наблюдения/значения для каждого Then/And; процедура, revision/config/environment, исполнитель/дата и bounded артефакты с digest. Для мутации/отказа — состояние до/после и число side effects. | Task становится `failed` без нового dispatch; expiry reason сохраняется в audit. |
| `AT-4.5-04` | **Given** input-update suite<br>**When** выполняются TTL/replay/conflict/scope/race tests<br>**Then** доказаны schema validation и idempotent update<br>**And** `just verify` проходит. | Отчёт AT-4.5-04: фактический результат указанного When и наблюдения/значения для каждого Then/And; процедура, revision/config/environment, исполнитель/дата и bounded артефакты с digest. Для мутации/отказа — состояние до/после и число side effects. | доказаны schema validation и idempotent update; `just verify` проходит. |
#### Story 4.6: Разрешать outcome_unknown через reconciliation evidence
#### Story 4.6 (CANCELLED / OUT-OF-SCOPE): Разрешать outcome_unknown — только safety invariant, без business reconciliation
**Requirements:** FR-25 · **Depends on:** Story 4.4 · **Work type:** implementation
**Requirements:** FR-25 · **Depends on:** Story 4.4 · **Work type:** historical/cancelled for business scope
- **Deliverable:** Разрешать outcome_unknown через reconciliation evidence.
- **Completion:** outcome этой story и все её AC проверены; будущая qualification не выполняется попутно.
- **Deliverable:** Базовая безопасность `outcome_unknown` остаётся: честное состояние, safety-warning, запрет auto retry/cancel-as-success. Business reconciliation, evidence gathering и подтверждённый новый attempt сняты из scope Crank и выполняются потребителем/его оркестрацией.
- **Canonical scope amendment (issue #34, 31.10.2026):** исторические `AT-4.6-01` и `AT-4.6-03` — CANCELLED / NOT_APPLICABLE, не PASS. Сохраняется только `AT-4.6-02` invariant: timeout/cancel не доказывают отсутствие внешнего эффекта, `outcome_unknown` не может быть обычной retriable failure, автоматический повтор опасного write запрещён. Gitea verifier, общий reconciliation framework и cross-owner permission не разрабатывать. Уже опубликованные 4.3–4.5 сохраняются; исторические blockers и production NO_GO сохраняются.
- **Completion:** безопасный invariant подтверждается; reconciliation business completion не требуется для завершения Epic 4 и 4.7/4.9/4.10.
| Case ID | Проверка (Given / When / Then) | Expected evidence | PASS criterion |
|---|---|---|---|
| `AT-4.6-01` | **Given** `outcome_unknown`<br>**When** оператор предоставляет reconciliation evidence<br>**Then** разрешены только переходы в `completed`, `failed` либо новый явно подтверждённый attempt<br>**And** evidence immutable, bounded, redacted и связано с attempt/trace без raw secrets или произвольного payload. | Отчёт AT-4.6-01: фактический результат указанного When и наблюдения/значения для каждого Then/And; процедура, revision/config/environment, исполнитель/дата и bounded артефакты с digest. Для мутации/отказа — состояние до/после и число side effects. | разрешены только переходы в `completed`, `failed` либо новый явно подтверждённый attempt; evidence immutable, bounded, redacted и связано с attempt/trace без raw secrets или произвольного payload. |
| `AT-4.6-02` | **Given** обычный retry/cancel request для `outcome_unknown`<br>**When** reconciliation отсутствует<br>**Then** request блокируется с предупреждением о side effect<br>**And** protocol adapter не отображает состояние как retriable failure. | Отчёт AT-4.6-02: фактический результат указанного When и наблюдения/значения для каждого Then/And; процедура, revision/config/environment, исполнитель/дата и bounded артефакты с digest. Для мутации/отказа — состояние до/после и число side effects. | request блокируется с предупреждением о side effect; protocol adapter не отображает состояние как retriable failure. |
| `AT-4.6-03` | **Given** reconciliation suite<br>**When** выполняются replay/conflict/scope/race tests<br>**Then** доказаны evidence-bearing transitions и запрет retry/cancel без reconciliation<br>**And** `just verify` проходит. | Отчёт AT-4.6-03: фактический результат указанного When и наблюдения/значения для каждого Then/And; процедура, revision/config/environment, исполнитель/дата и bounded артефакты с digest. Для мутации/отказа — состояние до/после и число side effects. | доказаны evidence-bearing transitions и запрет retry/cancel без reconciliation; `just verify` проходит. |
| `AT-4.6-01` (historical, cancelled, not PASS) | **Given** `outcome_unknown`<br>**When** оператор ранее рассчитывал предоставить reconciliation evidence<br>**Then** business-reconciliation transition, evidence-bearing operator resolution и confirmed new attempt больше не являются AC Crank<br>**And** verification внешнего бизнес-эффекта выполняется потребителем в собственной оркестрацией. | Запись canonical amendment issue #34 (cancelled/out-of-scope); нет business PASS evidence. | historical / not applicable; не входит в PASS criterion Epic 4. |
| `AT-4.6-02` | **Given** обычный retry/cancel request для `outcome_unknown`<br>**When** внешний исход ещё неизвестен<br>**Then** request блокируется с предупреждением о side effect<br>**And** protocol adapter не отображает состояние как retriable failure. | Отчёт AT-4.6-02: фактический результат указанного When и наблюдения/значения для каждого Then/And; процедура, revision/config/environment, исполнитель/дата и bounded артефакты с digest. Для мутации/отказа — состояние до/после и число side effects. | request блокируется с предупреждением о side effect; protocol adapter не отображает состояние как retriable failure. |
| `AT-4.6-03` (historical, cancelled, not PASS) | **Given** reconciliation suite<br>**When** ранее ожидались evidence-bearing reconciliation tests<br>**Then** business-reconciliation/race/evidence suite снята из активного scope и не считается PASS<br>**And** остаётся обычный timeout/cancel safety contract из 4.4. | Запись canonical amendment issue #34 (cancelled/out-of-scope); нет business PASS evidence. | historical / not applicable; не входит в PASS criterion Epic 4. |
#### Story 4.7: Предоставить MCP Task operations и fallback
**Requirements:** FR-21, FR-22, FR-25 · **Depends on:** Story 4.4, Story 4.5, Story 4.6 · **Work type:** implementation
**Requirements:** FR-21, FR-22, FR-25 · **Depends on:** Story 4.4, Story 4.5 · **Work type:** implementation
- **Deliverable:** Предоставить MCP Task operations и fallback.
- **Completion:** outcome этой story и все её AC проверены; будущая qualification не выполняется попутно.
@@ -1395,20 +1403,20 @@ Explicit зависимости Epic 8: `8.1 → 8.2`; `8.3,8.4,8.5,8.7,8.8` з
| `AT-4.8-05` | **Given** оператор открывает Tasks navigation, filters либо detail<br>**When** он использует keyboard, back/forward, refresh или reconnect<br>**Then** URL-addressable state, permission-aware visibility, focus restoration, semantic labels/errors и `aria-live` updates сохраняют authoritative context<br>**And** contrast соответствует WCAG 2.2 AA, смысл не зависит только от цвета, animation уважает reduced-motion, stale response не перезаписывает новый state. | Отчёт AT-4.8-05: фактический результат указанного When и наблюдения/значения для каждого Then/And; процедура, revision/config/environment, исполнитель/дата и bounded артефакты с digest. Для мутации/отказа — состояние до/после и число side effects. | URL-addressable state, permission-aware visibility, focus restoration, semantic labels/errors и `aria-live` updates сохраняют authoritative context; contrast соответствует WCAG 2.2 AA, смысл не зависит только от цвета, animation уважает reduced-motion, stale response не перезаписывает новый state. |
| `AT-4.8-06` | **Given** Task UI suite<br>**When** выполняется Playwright/API testing<br>**Then** покрыты filters, lifecycle, races, bulk confirmation и localization<br>**And** `just verify` проходит. | Отчёт AT-4.8-06: фактический результат указанного When и наблюдения/значения для каждого Then/And; процедура, revision/config/environment, исполнитель/дата и bounded артефакты с digest. Для мутации/отказа — состояние до/после и число side effects. | покрыты filters, lifecycle, races, bulk confirmation и localization; `just verify` проходит. |
#### Story 4.9: Предоставить Task input и reconciliation UI
#### Story 4.9: Предоставить Task input и unknown-outcome safety UI
**Requirements:** FR-26 · **Depends on:** Story 4.8, Story 4.5, Story 4.6 · **Work type:** implementation
**Requirements:** FR-26 · **Depends on:** Story 4.8, Story 4.5 · **Work type:** implementation
- **Deliverable:** Предоставить Task input и reconciliation UI.
- **Deliverable:** Предоставить Task input и unknown-outcome safety UI без business reconciliation/evidence/confirmed new attempt.
- **Completion:** outcome этой story и все её AC проверены; будущая qualification не выполняется попутно.
| Case ID | Проверка (Given / When / Then) | Expected evidence | PASS criterion |
|---|---|---|---|
| `AT-4.9-01` | **Given** `input_required`<br>**When** вводится дополнительный input<br>**Then** form строится из versioned schema и server validates again<br>**And** duplicate submit idempotent, conflicting stale submit видим. | Отчёт AT-4.9-01: фактический результат указанного When и наблюдения/значения для каждого Then/And; процедура, revision/config/environment, исполнитель/дата и bounded артефакты с digest. Для мутации/отказа — состояние до/после и число side effects. | form строится из versioned schema и server validates again; duplicate submit idempotent, conflicting stale submit видим. |
| `AT-4.9-02` | **Given** `outcome_unknown`<br>**When** details открыты<br>**Then** обычные Retry/Cancel disabled, отображается предупреждение и reconciliation flow<br>**And** evidence/explicit new attempt требуют confirmation. | Отчёт AT-4.9-02: фактический результат указанного When и наблюдения/значения для каждого Then/And; процедура, revision/config/environment, исполнитель/дата и bounded артефакты с digest. Для мутации/отказа — состояние до/после и число side effects. | обычные Retry/Cancel disabled, отображается предупреждение и reconciliation flow; evidence/explicit new attempt требуют confirmation. |
| `AT-4.9-02` | **Given** `outcome_unknown`<br>**When** details открыты<br>**Then** обычные Retry/Cancel disabled, отображается предупреждение о возможном внешнем эффекте<br>**And** UI не предлагает business reconciliation, evidence upload или confirmed new attempt. | Фактическое состояние UI/actions и safety-warning; historical business reconciliation AC cancelled, не PASS. | Честный unknown и предупреждение; автоматический повтор опасного write запрещён; business-reconciliation flow не требуется. |
| `AT-4.9-03` | **Given** UI polling/live updates<br>**When** workspace/filter/request generation меняется<br>**Then** old response не перезаписывает новый context<br>**And** listeners не дублируются. | Отчёт AT-4.9-03: фактический результат указанного When и наблюдения/значения для каждого Then/And; процедура, revision/config/environment, исполнитель/дата и bounded артефакты с digest. Для мутации/отказа — состояние до/после и число side effects. | old response не перезаписывает новый context; listeners не дублируются. |
| `AT-4.9-04` | **Given** оператор открывает Task input либо reconciliation flow<br>**When** он использует keyboard, back/forward, refresh или reconnect<br>**Then** URL-addressable state, permission-aware visibility, focus restoration, semantic labels/errors и `aria-live` updates сохраняют authoritative context<br>**And** contrast соответствует WCAG 2.2 AA, смысл не зависит только от цвета, animation уважает reduced-motion, stale response не перезаписывает новый state. | Отчёт AT-4.9-04: фактический результат указанного When и наблюдения/значения для каждого Then/And; процедура, revision/config/environment, исполнитель/дата и bounded артефакты с digest. Для мутации/отказа — состояние до/после и число side effects. | URL-addressable state, permission-aware visibility, focus restoration, semantic labels/errors и `aria-live` updates сохраняют authoritative context; contrast соответствует WCAG 2.2 AA, смысл не зависит только от цвета, animation уважает reduced-motion, stale response не перезаписывает новый state. |
| `AT-4.9-05` | **Given** Task UI suite<br>**When** выполняется Playwright/API testing<br>**Then** покрыты input, reconciliation, races, confirmation и localization<br>**And** `just verify` проходит. | Отчёт AT-4.9-05: фактический результат указанного When и наблюдения/значения для каждого Then/And; процедура, revision/config/environment, исполнитель/дата и bounded артефакты с digest. Для мутации/отказа — состояние до/после и число side effects. | покрыты input, reconciliation, races, confirmation и localization; `just verify` проходит. |
| `AT-4.9-04` | **Given** оператор открывает Task input либо unknown-outcome safety details<br>**When** он использует keyboard, back/forward, refresh или reconnect<br>**Then** URL-addressable state, permission-aware visibility, focus restoration, semantic labels/errors и `aria-live` updates сохраняют authoritative context<br>**And** contrast соответствует WCAG 2.2 AA, смысл не зависит только от цвета, animation уважает reduced-motion, stale response не перезаписывает новый state. | Отчёт AT-4.9-04: фактический результат указанного When и наблюдения/значения для каждого Then/And; процедура, revision/config/environment, исполнитель/дата и bounded артефакты с digest. Для мутации/отказа — состояние до/после и число side effects. | URL-addressable state, permission-aware visibility, focus restoration, semantic labels/errors и `aria-live` updates сохраняют authoritative context; contrast соответствует WCAG 2.2 AA, смысл не зависит только от цвета, animation уважает reduced-motion, stale response не перезаписывает новый state. |
| `AT-4.9-05` | **Given** Task UI suite<br>**When** выполняется Playwright/API testing<br>**Then** покрыты input, unknown safety, races, confirmation и localization<br>**And** `just verify` проходит. | Отчёт AT-4.9-05: фактический результат указанного When и наблюдения/значения для каждого Then/And; процедура, revision/config/environment, исполнитель/дата и bounded артефакты с digest. Для мутации/отказа — состояние до/после и число side effects. | покрыты input, unknown safety, races, confirmation и localization; `just verify` проходит. |
#### Story 4.10: Доказать Task capacity и recovery envelope
+1 -1
View File
@@ -1,6 +1,6 @@
# Переход Crank на официальный MCP SDK rmcp
Статус: планирование одобрено владельцем 27.10.2026. Полная миграция и production-переключение этим планом не запускаются. Владелец планирования и очереди — hermes_tl; реализация — hermes_dev; независимая проверка — hermes_qa; Git/CI/релизы — hermes_devops. ARC подключается к конкретному техническому затруднению, не как обязательный новый этап.
Статус: планирование одобрено владельцем 27.10.2026; 05.11.2026 отдельно разрешён только изолированный опыт этапа 1 (#106). Этапы 2/3 (#107/#108), новая реализация 4.7 и production-переключение этим разрешением не запускаются. Исполняемый кандидат и конкретные несовместимости: [rmcp106-tools-adapter.md](rmcp106-tools-adapter.md); это не завершённая миграция. Владелец очереди — hermes_tl; реализация — hermes_dev; независимая проверка — hermes_qa; Git/CI/релизы — hermes_devops. ARC подключается к конкретному техническому затруднению, не как обязательный новый этап. Business reconciliation 4.6 отменена решением владельца и [issue #34](https://git.itexp.me/bsodfather/crank/issues/34); она не prerequisite SDK. Input/unknown safety и остальные защитные ограничения сохраняются.
## Результат
+59
View File
@@ -0,0 +1,59 @@
# Изолированный rmcp Tools adapter (#106)
## Граница кандидата
База: `e4953abcd2f5320e1729249221ce9472a175c5f1` (принятый main 4.5).
W: `/home/codex/code/crank-worktrees/rmcp106-tools-adapter`.
Основание: [#106](https://git.itexp.me/bsodfather/crank/issues/106), comment 2277 и отдельное разрешение владельца 05.11.2026 на этап 1.
Это работающий изолированный опыт, не завершённая миграция и не production endpoint.
Независимая QA и решение TL следуют после DEV-проверок; документ не заменяет их.
`app/rmcp_http.rs` создаёт один настоящий `StreamableHttpService` и `LocalSessionManager` на один явно заданный Agent route. Это test-only router, запускаемый wire-набором через настоящий TCP loopback; в `build_app_inner` он не подключён. Отдельный manager на Agent делает session/route ownership явным без новой session database. Все проверки доступа (POST/GET/DELETE), scopes, rate admission, Origin, envelope/revision/session carrier используют существующие Crank helpers. SDK получает только проверенный snapshot текущего запроса через HTTP `Parts.extensions`, не credential из initialize.
`app/rmcp_tools.rs` реализует официальный `ServerHandler`, но делегирует list/call существующему `handle_tools_command`: опубликованный каталог, runtime, REST mapping, security и error contracts не заменяются. Перезапись публикации и фоновые бизнес-workflows не добавлены. Новый handler рекламирует только Tools и две поддерживаемые revisions.
SDK закреплён как `rmcp = "=3.7.0"`, HTTP server feature включён, зависимость только dev/test. Cargo.lock сохраняется вместе с кандидатом; фактический transitive `rmcp-macros` — 3.9.0 по semver SDK. Автоматического обновления rmcp нет. Существующие package versions не повышались; lock содержит новые SDK-зависимости и переразрешённые dependency edges.
## Исполняемые результаты
Команды выполняются в W с `CARGO_BUILD_JOBS=2 CARGO_INCREMENTAL=0 SQLX_OFFLINE=true`, `HERMES_KANBAN_TASK=t_fdcc7df8`, `HERMES_KANBAN_BOARD=crank`.
- `cargo test --locked -p crank-community-mcp --lib rmcp_ -- --nocapture --test-threads=1`: exit 0, 20 passed, 0 ignored; 15 wire-тестов и 5 прежних direct-handler/manager проверок. Финальный тестовый прогон — 56.07 s, без полной workspace suite.
- `cargo test --locked -p crank-community-mcp --lib app::lifecycle -- --test-threads=1`: exit 0, 7 passed, 0 ignored. Подтверждает существующие progress queue=8, token bound=128, cancellation table=256 и full-table/cleanup семантику. Это existing GREEN, не новый transport benchmark.
- Wire positive control: legacy initialize/initialized/session и modern discover/stateless; dynamic list после публикации Agent v2 без reinitialize; реальные calls с проверяемым output и outbound counter. Modern single response — JSON; progress — SSE в обеих revisions.
- Реальная проверка invalid/revoked/expired/scope-changed credentials после initialize, чужого route, Origin, неверной revision/name, конфликтующего modern session carrier и body overflow. Rejected calls не достигают upstream. Два валидных ключа могут использовать одну session, без credential pinning.
- Progress отражает только три реально пройденные фазы (`tool_resolved`, `authorization_resolved`, `execution_dispatched`), token возвращается клиенту. Tool input-validation error остаётся `isError`, не JSON-RPC protocol error.
- Cancel проверен до SDK по `session + platform_api_key_id + typed requestId`: чужой ключ/другая session не отменяют оригинал, одинаковые ids двух sessions независимы. Своё уведомление прекращает pending execution; modern disconnect прекращает future и возвращает stream permit. Эти факты не доказывают отсутствие внешнего бизнес-эффекта; повторного dispatch нет.
- Live SDK manager допускает GET reconnect и последующий call. Новый manager со старым SDK id получает 404. Отдельно существующий PostgreSQL session store переживает пересоздание, его запись не удаляется SDK-опытом, но SDK не может обслужить такой durable id.
- Небольшой admission smoke: удержанные 16 stream permits дают 429 до dispatch; освобождение восстанавливает call. QA дополнительно выявила обход при legacy disconnect: response body освобождал permit, пока SDK execution продолжался. Correction F1 делит один permit между body и request-local HTTP Parts SDK; слот освобождается только после завершения обеих жизней. Owned cancel проходит до admission, поэтому доступен и при заполненном бюджете. Регрессия использует реальные slow upstream calls с закрытием response, а не ручной захват semaphore. Настроенный существующий rate limiter даёт 429 без outbound. Request body ограничен прежним Axum default 2 MiB; ceilings не увеличены.
- Correlation oracle сначала реально упал (exit 101): сервер подменял `x-request-id` сгенерированным UUID. После подключения существующего request-context middleware два конкурентных запроса сохраняют каждый свой id/output, тест GREEN. Это behavioral RED, не compile/setup failure. Для первоначального Tools positive control ранний behavioral RED не записан; последующие успешные проверки не выдаются за исторический RED.
Correction F1 после первой независимой QA: `cargo test --locked -p crank-community-mcp --lib rmcp_http_ -- --nocapture --test-threads=1` — exit 0, 16 passed, 0 ignored, 50.94 s (отдельно 2m05s пересборки). Включены legacy disconnect/admission regression, восстановление всех 16 permits после owned cancel и новый реальный call с output/counter; также owned/foreign cancel, reconnect, modern disconnect и обычные list/call. Исходный behavioral RED QA (17 продолжающихся executions при 16 свободных slots) переиспользован, не подменён setup failure. Beam `t_c21c9876` усилил этот же oracle; DEV проверил cleanup до assertions и исполнил итоговый файл. Повторные affected clippy и все перечисленные cheap gates — exit 0. Неизменённые 5 direct/manager и 7 lifecycle tests переиспользованы; нового full suite нет.
Исходные native logs и обновлённый SHA-256 manifest точной дельты приложены к Kanban handoff. Первоначальные setup/compile ошибки и исправленная тестовая ошибка с добавлением второго Authorization header не считаются behavioral RED.
Дешёвые gates финального кандидата: `cargo clippy --locked -p crank-community-mcp -p crank-test-support --all-targets -- -D warnings`, `cargo fmt --all -- --check`, `git diff --check`, `bash -n scripts/ci-story-checks.sh`, `scripts/check-rust-code-health.sh`, `scripts/check-rust-boundaries.sh` (включая config/migration/metrics/execution boundaries), явный Community-scope scan всех 11 изменённых/новых Rust files — exit 0. Clippy findings исправлены без suppressions. Labels test fixture передаются явно, без чтения environment вне crank-config. Story CI получил тот же непустой `rmcp_` selector; остальные required selectors не удалены. Full workspace, нагрузочная кампания и UI не запускались: production/UI/runtime execution logic не менялись.
## Конкретные несовместимости — не включать опыт в production
1. **Хранение сессий — не drop-in.** `TransportSessionStore` хранит Crank-generated id, revision, initialized, elicitation flag, route и TTL; SDK `SessionStore` требует SDK-generated id и полные `InitializeRequestParams` (clientInfo/capabilities). Их нельзя без потерь восстановить из существующего DTO. `LocalSessionManager` умеет restore, но это не совместимость с Crank store: runtime oracle выше отдельно показывает live reconnect, потерю session новым manager и сохранность Crank PostgreSQL state. Last-Event-ID replay и восстановление in-flight execution не доказаны.
2. **Legacy JSON-only — несовместимость.** Реальный `Accept: application/json` получает 406 у SDK legacy session path, тогда как modern simple call возвращает JSON. `json_response=true` не исправляет legacy mode. Не скрывать это преобразующим transport framework без отдельного решения.
3. **Legacy cancelled terminal frame — несовместимость.** Владение отменой и остановка future работают. Однако при завершении handler с ошибкой SDK пишет `request cancelled` JSON-RPC error frame, а действующий Crank lifecycle заканчивает отменённый stream без terminal frame. Это явно asserted gap, не объявленная wire parity. Бесконечно pending handler ради подавления frame не используется: он удерживал бы execution/память.
4. **Budgets SDK требуют дальнейшего решения.** Сохранены Crank limits и bounded queue перед forwarding; SDK channel capacity явно 16, EventStore не включён. SDK session map, request-router/cache и completed-cache TTL (60 s), idle keepalive (300 s) не дают автоматически прежний durable TTL 24 h или доказанный общий memory budget. Smoke выше не является long-run/slow-reader/load qualification. Await SDK notification delivery также требует проверки backpressure до общего включения.
Минимальные варианты для TL после независимой QA: сохранить Crank endpoint/session/lifecycle и применять SDK на request-scoped dispatch/model seam (вариант ARC), либо отдельно согласовать тонкую persistence mapping и точную transport parity перед #107. Не заменять PostgreSQL in-memory хранилищем, не ослаблять JSON/cancel contract и не строить новый общий framework молча. Текущий опыт доказывает работоспособность Tools, но не даёт GO на замену transport.
## Остальные MCP-функции и ближайший потребитель
- Resources/read/list/templates, Prompts/get/list, completion и composition не перенесены; их существующие shared services остаются будущими границами SDK handlers.
- Catalog change notifications, subscriptions/listen, resume/replay и logging policy не подключены. Наличие SDK traits не означает parity; эти capabilities не рекламируются новым handler.
- Background/adaptive Tasks, input continuation/elicitation, approval flows и Tasks extension этим router не реализованы. `ContinuationSupport=false` — явная граница опыта; сохранённый 4.3–4.5 task state/runtime не меняется. Подтверждён только synchronous shared Tools path.
- Ближайший реальный потребитель — #107: `build_app_inner` и действующие endpoint/era adapters могли бы подключить SDK на проверенной typed-command границе после решения по перечисленным gaps. #107/#108/4.7 не запущены и требуют отдельного разрешения. Production NO_GO, blockers3.3/P4/auth3.20 остаются.
## Передача и сохранность
Переиспользованы вклады Ornith `t_1597bde6`/`t_de107aae` (частичный Tools handler), Beam `t_c5472eeb` (direct negative tests), Beam `t_1a3e54ff` (два manager tests), Ornith `t_c5611492` (частичная acceptance-plan правка), решение ARC `t_e76984d9`. HTTP поручение `t_bf7332df` осталось superseded partial, не готовой реализацией. Неделимую admission/Parts/cancel/HTTP интеграцию и wire oracle завершил DEV: повторное поручение с запретом integration paths уже приводило к deadlock.
Общий acceptance plan содержит ограниченный canonical amendment FR-25/FR-26/AR9 по live #34: business reconciliation отменена, не PASS; input/unknown safety сохранены. Исторические архивы PRD/epics не force-added, R WIP не перенесён. План rmcp остаётся планом этапов 2/3.
Новые loopback servers принадлежат RAII guards и abort при выходе теста; SDK cancellation token связан с lifetime router. Test PostgreSQL получает disposable/task/board labels и удаляется существующим atexit cleanup. Пример одного из проверенных прогонов: контейнер `9737b010c3dd` (task `t_fdcc7df8`, board `crank`, disposable=true). Чужие контейнеры не затрагиваются. `app.rs.orig`/`app.rs.rej` сохранены как прежний WIP, не входят в delivery manifest.
+267
View File
@@ -0,0 +1,267 @@
#!/usr/bin/env python3
"""Validate an existing draft release before resuming its image build."""
from __future__ import annotations
import hashlib
import importlib.util
import os
import re
import subprocess
import sys
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.parse import quote, urlsplit
from urllib.request import Request, build_opener
_HERE = Path(__file__).resolve().parent
_ASSETS_SCRIPT = _HERE / "ci-release-assets.py"
_spec = importlib.util.spec_from_file_location("ci_release_assets", _ASSETS_SCRIPT)
if _spec is None or _spec.loader is None:
raise RuntimeError("Could not load release asset helpers")
_assets_module = importlib.util.module_from_spec(_spec)
sys.modules[_spec.name] = _assets_module
_spec.loader.exec_module(_assets_module)
PublishError = _assets_module.PublishError
_NoRedirect = _assets_module._NoRedirect
_assets = _assets_module._assets
_inputs = _assets_module._inputs
_json_request = _assets_module._json_request
_COMMIT = re.compile(r"[0-9a-fA-F]{40}\Z")
_ARCHIVES = re.compile(r"crank-community-(?:admin-api|mcp-server|ui)-.+\.tar\.gz\Z")
_MAX_ASSET_SIZE = 512 * 1024 * 1024
_MAX_TOTAL_SIZE = 1024 * 1024 * 1024
_REQUIRED_SOURCE_STATUSES = (
"CI / Required Checks (push)",
"CI / Rust Checks (push)",
"CI / UI Checks (push)",
)
def _fail(message: str) -> None:
raise PublishError(message)
def _git(*args: str) -> str:
try:
result = subprocess.run(
["git", *args], check=False, stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL, text=True,
)
except OSError:
_fail("Could not inspect checked out Git history")
if result.returncode:
_fail("Resume source tag is unavailable or is not based on checked out main")
return result.stdout.strip()
def _check_source(tag: str, source_sha: str, env: dict[str, str]) -> None:
if env.get("GITHUB_EVENT_NAME") != "workflow_dispatch" or env.get("GITHUB_REF") != "refs/heads/main":
_fail("Resume is allowed only for manual dispatches from main")
if not _COMMIT.fullmatch(source_sha):
_fail("RESUME_SOURCE_SHA must be an exact 40-character commit SHA")
tag_sha = _git("rev-parse", "--verify", f"refs/tags/{tag}^{{commit}}")
if tag_sha.lower() != source_sha.lower():
_fail("Release tag does not point to the requested source commit")
try:
result = subprocess.run(
["git", "merge-base", "--is-ancestor", tag_sha, "HEAD"],
check=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
except OSError:
_fail("Could not verify release source ancestry")
if result.returncode:
_fail("Release source is not an ancestor of checked out main")
def _api_tag_commit(api: str, tag: str, token: str, opener) -> str:
result, status = _json_request(
opener, "GET", f"{api}/tags/{quote(tag, safe='')}", token
)
if status != 200 or not isinstance(result, dict) or result.get("name") != tag:
_fail("Gitea did not return the requested tag")
commit = result.get("commit")
if not isinstance(commit, dict) or not isinstance(commit.get("sha"), str):
_fail("Gitea returned a malformed tag commit")
return commit["sha"]
def _download(origin: str, item: dict, token: str, opener) -> bytes:
url = urlsplit(item["browser_download_url"])
trusted = urlsplit(origin)
if (
url.scheme != "https" or url.netloc != trusted.netloc
or url.username or url.password or url.fragment or not url.path.startswith("/")
):
_fail(f"Release asset {item['name']} has an untrusted download URL")
size = item["size"]
if size < 0 or size > _MAX_ASSET_SIZE:
_fail(f"Release asset {item['name']} exceeds the download size limit")
request = Request(item["browser_download_url"], headers={"Authorization": f"token {token}"})
chunks: list[bytes] = []
total = 0
try:
with opener.open(request, timeout=30) as response:
while True:
chunk = response.read(min(1024 * 1024, size + 1 - total))
if not chunk:
break
total += len(chunk)
if total > size:
_fail(f"Release asset {item['name']} size does not match Gitea metadata")
chunks.append(chunk)
except PublishError:
raise
except HTTPError as exc:
status = exc.code
exc.close()
_fail(f"Could not download release asset (HTTP {status})")
except (URLError, TimeoutError, OSError):
_fail("Could not download release asset or request timed out")
if total != size:
_fail(f"Release asset {item['name']} size does not match Gitea metadata")
return b"".join(chunks)
def _sha_manifest(data: bytes, expected: set[str]) -> dict[str, str]:
try:
lines = data.decode("utf-8").splitlines()
except UnicodeDecodeError:
_fail("SHA256SUMS is not valid UTF-8")
parsed: dict[str, str] = {}
for line in lines:
match = re.fullmatch(r"([0-9a-fA-F]{64}) [ *](?:dist/)?([^\s/\\]+)", line)
if not match or match.group(2) in parsed:
_fail("SHA256SUMS has an invalid or duplicate entry")
parsed[match.group(2)] = match.group(1).lower()
if set(parsed) != expected:
_fail("SHA256SUMS does not cover exactly all release payload assets")
return parsed
def _verify_payloads(payload: dict[str, bytes], manifest_data: bytes, tag: str) -> dict[str, str]:
archives = sorted(name for name in payload if _ARCHIVES.fullmatch(name))
checksums = [name for name in payload if name.endswith("-checksums.txt")]
sboms = [name for name in payload if name.endswith("-sbom.spdx.json")]
expected_archives = {
f"crank-community-admin-api-{tag}.tar.gz",
f"crank-community-mcp-server-{tag}.tar.gz",
f"crank-community-ui-{tag}.tar.gz",
}
if (
set(archives) != expected_archives
or checksums != [f"crank-community-{tag}-checksums.txt"]
or sboms != [f"crank-community-{tag}-sbom.spdx.json"]
):
_fail("Draft release is missing an expected archive, checksums file, or SBOM")
if len(payload) != 5:
_fail("Draft release contains an unexpected payload asset set")
manifest = _sha_manifest(manifest_data, set(payload))
hashes = {name: hashlib.sha256(data).hexdigest() for name, data in payload.items()}
if any(manifest[name] != digest for name, digest in hashes.items()):
_fail("SHA256SUMS does not match a release payload asset")
try:
checksum_lines = payload[checksums[0]].decode("utf-8").splitlines()
except UnicodeDecodeError:
_fail("Release checksums file is not valid UTF-8")
checksum_entries: dict[str, str] = {}
for line in checksum_lines:
match = re.fullmatch(r"([0-9a-fA-F]{64}) [ *](?:dist/)?([^\s/\\]+)", line)
if not match or match.group(2) in checksum_entries:
_fail("Release checksums file has an invalid or duplicate entry")
checksum_entries[match.group(2)] = match.group(1).lower()
if set(checksum_entries) != set(archives) or any(
checksum_entries[name] != hashlib.sha256(payload[name]).hexdigest() for name in archives
):
_fail("Release checksums file does not match all three release archives")
return hashes
def _require_source_ci(status_data: object, status_code: int) -> None:
if status_code != 200 or not isinstance(status_data, dict):
_fail("Could not read required source CI statuses")
statuses = status_data.get("statuses")
if not isinstance(statuses, list):
_fail("Gitea did not return source CI status records")
for context in _REQUIRED_SOURCE_STATUSES:
matches = [
item for item in statuses
if isinstance(item, dict) and item.get("context") == context
]
if not matches:
_fail(f"Required source CI status is missing: {context}")
if any(not isinstance(item.get("updated_at"), str) for item in matches):
_fail(f"Required source CI status has invalid timestamp: {context}")
latest = max(matches, key=lambda item: item["updated_at"])
if latest.get("status") != "success":
_fail(f"Required source CI status is not successful: {context}")
def verify(env=None, opener=None) -> dict[str, object]:
env = os.environ if env is None else env
origin, api, tag, token = _inputs(env)
source_sha = env.get("RESUME_SOURCE_SHA", "")
_check_source(tag, source_sha, env)
opener = opener or build_opener(_NoRedirect())
release, status = _json_request(
opener, "GET", f"{api}/releases/tags/{quote(tag, safe='')}", token, allow_404=True
)
if status == 404 or not isinstance(release, dict):
_fail("The requested release does not already exist")
release_id = release.get("id")
if (
release.get("tag_name") != tag or release.get("draft") is not True
or not isinstance(release_id, int) or release_id <= 0
):
_fail("The requested release is not the expected existing draft")
if _api_tag_commit(api, tag, token, opener).lower() != source_sha.lower():
_fail("Gitea tag does not point to the requested source commit")
status_data, status_code = _json_request(
opener, "GET", f"{api}/commits/{source_sha}/status", token
)
_require_source_ci(status_data, status_code)
existing = _assets(api, release_id, token, opener)
if len(existing) != 6:
_fail("Draft release must contain exactly the five expected payloads and SHA256SUMS")
sums_names = [name for name in existing if name == "SHA256SUMS"]
if len(sums_names) != 1:
_fail("Draft release must contain one canonical SHA256SUMS asset")
if sum(item["size"] for item in existing.values()) > _MAX_TOTAL_SIZE:
_fail("Draft release payload exceeds the total download size limit")
payload: dict[str, bytes] = {}
for name, item in existing.items():
payload[name] = _download(origin, item, token, opener)
if "SHA256SUMS" not in payload:
_fail("Draft release must contain one canonical SHA256SUMS asset")
sums = payload.pop("SHA256SUMS")
hashes = _verify_payloads(payload, sums, tag)
return {
"tag": tag,
"release_id": release_id,
"source_sha": source_sha.lower(),
"assets": hashes,
}
def main() -> int:
try:
result = verify()
except PublishError as exc:
print(f"Gitea release resume: {exc}", file=sys.stderr)
return 1
output = os.environ.get("GITHUB_OUTPUT")
if not output:
print("GITHUB_OUTPUT is unavailable", file=sys.stderr)
return 1
with open(output, "a", encoding="utf-8") as target:
target.write(f"release_id={result['release_id']}\n")
target.write(f"source_sha={result['source_sha']}\n")
target.write(f"release_tag={result['tag']}\n")
print(f"Validated existing draft {result['tag']} (id {result['release_id']}) and source CI")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+3
View File
@@ -99,3 +99,6 @@ run_atdd "durable task retry attempt spans" -p crank-runtime --test stages retry
# durable_tasks::` (the full application -> worker -> PG -> counted upstream input
# continuation ATDD, including TTL/replay/conflict/scope races). Duplicating them here
# would only run the same bounded set twice.
# Isolated rmcp #106: real loopback HTTP Tools oracle, plus manager/handler contracts.
run_atdd "isolated rmcp Tools adapter" --locked -p crank-community-mcp --lib rmcp_ -- --test-threads=1
+15 -1
View File
@@ -45,6 +45,10 @@ trivy_version="0.70.0"
archive="trivy_${trivy_version}_Linux-64bit.tar.gz"
expected_sha256="8b4376d5d6befe5c24d503f10ff136d9e0c49f9127a4279fd110b727929a5aa9"
download_url="https://github.com/aquasecurity/trivy/releases/download/v${trivy_version}/${archive}"
# Fixed GitHub asset ID for the Trivy 0.70.0 Linux 64-bit release archive.
asset_api_url="https://api.github.com/repos/aquasecurity/trivy/releases/assets/398381981"
db_repository_primary="ghcr.io/aquasecurity/trivy-db:2"
db_repository_fallback="mirror.gcr.io/aquasec/trivy-db:2"
output_dir="${CRANK_IMAGE_SCAN_OUTPUT_DIR:-.tmp/image-scan-evidence}"
if ! mkdir -p "$output_dir"; then
@@ -104,7 +108,15 @@ PY
if ! curl --fail --silent --show-error --location --max-time 300 \
"$download_url" --output "$temp_dir/$archive" \
>"$output_dir/scanner-download.log" 2>&1; then
fail_all "could not download pinned Trivy ${trivy_version}"
rm -f "$temp_dir/$archive"
if ! curl --fail --silent --show-error --location --max-time 300 \
--header 'Accept: application/octet-stream' \
"$asset_api_url" --output "$temp_dir/$archive" \
>"$output_dir/scanner-api-download.log" 2>&1; then
fail_all "could not download pinned Trivy ${trivy_version} from release URL or GitHub asset API"
fi
printf 'Downloaded pinned Trivy %s from GitHub release asset API.\n' "$trivy_version" \
>>"$output_dir/scanner-api-download.log"
fi
if ! printf '%s %s\n' "$expected_sha256" "$temp_dir/$archive" \
| sha256sum --check --status; then
@@ -120,6 +132,8 @@ fi
# Download one fresh vulnerability database; every scan reuses it read-only.
if ! "$trivy_bin" image --config /dev/null --download-db-only --cache-dir "$cache_dir" \
--db-repository "$db_repository_primary" \
--db-repository "$db_repository_fallback" \
--no-progress --skip-version-check \
>"$output_dir/db-download.log" 2>&1; then
fail_all "could not download the Trivy vulnerability database"
+238
View File
@@ -0,0 +1,238 @@
from __future__ import annotations
import hashlib
import importlib.util
import unittest
from pathlib import Path
from unittest.mock import patch
ROOT = Path(__file__).resolve().parents[2]
SCRIPT = ROOT / "scripts" / "ci-release-resume.py"
spec = importlib.util.spec_from_file_location("ci_release_resume", SCRIPT)
assert spec and spec.loader
resume = importlib.util.module_from_spec(spec)
spec.loader.exec_module(resume)
TAG = "v0.4.0-rc.15"
SHA = "29ee01b6efced04b027569fbeed2e865991c8f55"
FILES = {
f"crank-community-admin-api-{TAG}.tar.gz": b"admin archive",
f"crank-community-mcp-server-{TAG}.tar.gz": b"mcp archive",
f"crank-community-ui-{TAG}.tar.gz": b"ui archive",
f"crank-community-{TAG}-checksums.txt": b"",
f"crank-community-{TAG}-sbom.spdx.json": b"{}",
}
def payloads():
files = dict(FILES)
archives = [name for name in files if name.endswith(".tar.gz")]
files[f"crank-community-{TAG}-checksums.txt"] = "".join(
f"{hashlib.sha256(files[name]).hexdigest()} dist/{name}\n" for name in archives
).encode()
manifest = "".join(
f"{hashlib.sha256(data).hexdigest()} {name}\n" for name, data in files.items()
).encode()
return files, manifest
class ResumeValidationTests(unittest.TestCase):
def setUp(self):
self.env = {
"GITEA_SERVER_URL": "https://git.itexp.me",
"GITEA_REPOSITORY": "bsodfather/crank-community",
"GITEA_TOKEN": "test-token",
"RELEASE_TAG": TAG,
"RESUME_SOURCE_SHA": SHA,
"GITHUB_EVENT_NAME": "workflow_dispatch",
"GITHUB_REF": "refs/heads/main",
}
self.files, self.manifest = payloads()
self.calls = []
def api(self, _opener, method, url, token, payload=None, allow_404=False):
self.calls.append((method, url, payload))
if url.endswith("/releases/tags/" + TAG):
return ({"id": 426, "tag_name": TAG, "draft": True}, 200)
if url.endswith("/tags/" + TAG):
return ({"name": TAG, "commit": {"sha": SHA}}, 200)
if url.endswith("/commits/" + SHA + "/status"):
contexts = {"CI / Required Checks (push)", "CI / Rust Checks (push)", "CI / UI Checks (push)"}
return ({
"state": "failure",
"statuses": [
{"context": context, "status": "success", "updated_at": "2026-11-07T10:00:00Z"}
for context in contexts
] + [
{"context": "Community Release (push)", "status": "failure", "updated_at": "2026-11-07T10:01:00Z"}
],
}, 200)
raise AssertionError(f"Unexpected API URL: {url}")
def assets(self, _api, release_id, token, opener):
self.assertEqual(release_id, 426)
result = {}
for name, data in {**self.files, "SHA256SUMS": self.manifest}.items():
result[name] = {"name": name, "id": len(result) + 1, "size": len(data),
"browser_download_url": f"https://git.itexp.me/releases/download/{name}"}
return result
def download(self, origin, item, token, opener):
self.assertEqual(origin, "https://git.itexp.me")
return self.files.get(item["name"], self.manifest)
def run_verify(self):
with (
patch.object(resume, "_inputs", return_value=("https://git.itexp.me", "https://git.itexp.me/api/v1/repos/bsodfather/crank-community", TAG, "test-token")),
patch.object(resume, "_check_source") as check_source,
patch.object(resume, "_json_request", side_effect=self.api),
patch.object(resume, "_assets", side_effect=self.assets),
patch.object(resume, "_download", side_effect=self.download),
):
result = resume.verify(self.env, opener=object())
check_source.assert_called_once_with(TAG, SHA, self.env)
return result
def test_valid_draft_is_read_only_and_outputs_source_receipt(self):
result = self.run_verify()
self.assertEqual(result["release_id"], 426)
self.assertEqual(result["source_sha"], SHA)
self.assertEqual(set(result["assets"]), set(self.files))
self.assertTrue(self.calls)
self.assertTrue(all(call[0] == "GET" and call[2] is None for call in self.calls))
def test_missing_release_rejected(self):
with patch.object(resume, "_inputs", return_value=("https://git.itexp.me", "https://api", TAG, "token")), \
patch.object(resume, "_check_source"), \
patch.object(resume, "_json_request", return_value=(None, 404)):
with self.assertRaisesRegex(resume.PublishError, "does not already exist"):
resume.verify(self.env, opener=object())
def test_source_mismatch_rejected_before_api(self):
with patch.object(resume, "_inputs", return_value=("https://git.itexp.me", "https://api", TAG, "token")), \
patch.object(resume, "_check_source", side_effect=resume.PublishError("tag mismatch")), \
patch.object(resume, "_json_request") as request:
with self.assertRaisesRegex(resume.PublishError, "tag mismatch"):
resume.verify(self.env, opener=object())
request.assert_not_called()
def test_api_tag_commit_mismatch_rejected(self):
with patch.object(resume, "_inputs", return_value=("https://git.itexp.me", "https://api", TAG, "token")), \
patch.object(resume, "_check_source"), \
patch.object(resume, "_json_request", side_effect=self.api), \
patch.object(resume, "_api_tag_commit", return_value="0" * 40):
with self.assertRaisesRegex(resume.PublishError, "Gitea tag does not point"):
resume.verify(self.env, opener=object())
def test_unexpected_asset_set_rejected_before_download(self):
assets = self.assets(None, 426, "token", None)
assets["unexpected.txt"] = {
"name": "unexpected.txt", "id": 99, "size": 0,
"browser_download_url": "https://git.itexp.me/unexpected.txt",
}
with patch.object(resume, "_inputs", return_value=("https://git.itexp.me", "https://api", TAG, "token")), \
patch.object(resume, "_check_source"), \
patch.object(resume, "_json_request", side_effect=self.api), \
patch.object(resume, "_api_tag_commit", return_value=SHA), \
patch.object(resume, "_assets", return_value=assets), \
patch.object(resume, "_download") as download:
with self.assertRaisesRegex(resume.PublishError, "exactly the five expected"):
resume.verify(self.env, opener=object())
download.assert_not_called()
def test_required_source_status_missing_or_failed_is_rejected(self):
cases = (
{"state": "failure", "statuses": []},
{"state": "failure", "statuses": [
{"context": "CI / Required Checks (push)", "status": "failure", "updated_at": "2026-11-07T10:00:00Z"},
{"context": "CI / Rust Checks (push)", "status": "success", "updated_at": "2026-11-07T10:00:00Z"},
{"context": "CI / UI Checks (push)", "status": "success", "updated_at": "2026-11-07T10:00:00Z"},
]},
{"state": "failure", "statuses": [
{"context": "CI / Required Checks (push)", "status": "success", "updated_at": "2026-11-07T09:00:00Z"},
{"context": "CI / Required Checks (push)", "status": "failure", "updated_at": "2026-11-07T10:00:00Z"},
{"context": "CI / Rust Checks (push)", "status": "success", "updated_at": "2026-11-07T10:00:00Z"},
{"context": "CI / UI Checks (push)", "status": "success", "updated_at": "2026-11-07T10:00:00Z"},
]},
)
for status_data in cases:
with self.subTest(status_data=status_data):
with self.assertRaises(resume.PublishError):
resume._require_source_ci(status_data, 200)
def test_missing_expected_asset_rejected(self):
files = dict(self.files)
files.pop(f"crank-community-{TAG}-sbom.spdx.json")
with self.assertRaisesRegex(resume.PublishError, "missing an expected"):
resume._verify_payloads(files, self.manifest, TAG)
def test_checksum_manifest_rejects_missing_or_bad_payload_entries(self):
for manifest in (b"", b"0" * 64 + b" wrong.tar.gz\n"):
with self.subTest(manifest=manifest):
with self.assertRaises(resume.PublishError):
resume._verify_payloads(self.files, manifest, TAG)
def test_checksum_manifest_rejects_mismatched_archive_checksum(self):
files = dict(self.files)
checksum_name = f"crank-community-{TAG}-checksums.txt"
files[checksum_name] = b"0" * 64 + b" crank-community-admin-api-" + TAG.encode() + b".tar.gz\n"
updated_manifest = "".join(
f"{hashlib.sha256(data).hexdigest()} {name}\n" for name, data in files.items()
).encode()
with self.assertRaisesRegex(resume.PublishError, "checksums file"):
resume._verify_payloads(files, updated_manifest, TAG)
def test_download_rejects_untrusted_origin_before_network(self):
item = {"name": "payload", "size": 1, "browser_download_url": "https://evil.example/payload"}
opener = unittest.mock.Mock()
with self.assertRaisesRegex(resume.PublishError, "untrusted download URL"):
resume._download("https://git.itexp.me", item, "token", opener)
opener.open.assert_not_called()
def test_download_rejects_redirect_without_following(self):
class Redirecting:
def open(self, request, timeout):
raise resume.PublishError("redirect refused")
item = {"name": "payload", "size": 1, "browser_download_url": "https://git.itexp.me/payload"}
with self.assertRaisesRegex(resume.PublishError, "redirect refused"):
resume._download("https://git.itexp.me", item, "token", Redirecting())
class WorkflowResumeTests(unittest.TestCase):
def test_resume_selects_tag_source_and_skips_asset_production(self):
workflow = (ROOT / ".gitea/workflows/release.yml").read_text()
self.assertIn("resume_tag:", workflow)
self.assertIn("resume_source_sha:", workflow)
self.assertIn("IMAGE_TAG: ${{ inputs.resume_tag || gitea.ref_name }}", workflow)
self.assertIn("python3 scripts/ci-release-resume.py", workflow)
self.assertIn("ref: ${{ steps.resume.outputs.release_tag }}", workflow)
self.assertIn('test "$(git rev-parse HEAD)" = "$EXPECTED_SOURCE_SHA"', workflow)
for step in ("Build release binaries", "Build UI dist", "Package release artifacts", "Generate SBOM"):
start = workflow.index(f"- name: {step}")
self.assertIn("if: inputs.resume_tag == ''", workflow[start : start + 180])
self.assertIn("if: inputs.resume_tag == '' && startsWith(gitea.ref, 'refs/tags/v')", workflow)
self.assertIn("if: inputs.resume_tag == ''\n run: |\n ls -lh dist", workflow)
def test_resume_preserves_updated_scanner_before_old_source_checkout(self):
workflow = (ROOT / ".gitea/workflows/release.yml").read_text()
pin = workflow.index("- name: Preserve updated image scanner for resume")
old_checkout = workflow.index("- name: Checkout validated release source")
source_assert = workflow.index("- name: Assert exact release source checkout")
image_build = workflow.index("- name: Build and push release images")
self.assertLess(pin, old_checkout)
self.assertLess(old_checkout, source_assert)
self.assertLess(source_assert, image_build)
pin_step = workflow[pin:old_checkout]
self.assertIn("if: inputs.resume_tag != ''", pin_step)
self.assertIn('cp scripts/scan-images.sh "$scanner_dir/scan-images.sh"', pin_step)
self.assertIn('cp scripts/check-image-scan.py "$scanner_dir/check-image-scan.py"', pin_step)
build_step = workflow[image_build:]
self.assertIn("RELEASE_IMAGE_SCANNER: ${{ steps.pin_resume_scanner.outputs.path || 'scripts/scan-images.sh' }}", build_step)
self.assertIn('"$RELEASE_IMAGE_SCANNER" \\', build_step)
self.assertIn("ref: ${{ steps.resume.outputs.release_tag }}", workflow)
self.assertIn('test "$(git rev-parse HEAD)" = "$EXPECTED_SOURCE_SHA"', workflow)
if __name__ == "__main__":
unittest.main()
+68 -4
View File
@@ -27,9 +27,18 @@ import os
import sys
args = sys.argv[1:]
if os.environ.get("FAKE_CURL_FAIL") == "1":
sys.stderr.write("curl: (7) failed to connect\\n")
url = next((value for value in args if value.startswith("https://")), "")
api_download = url == "https://api.github.com/repos/aquasecurity/trivy/releases/assets/398381981"
failed = os.environ.get("FAKE_CURL_FAIL") == "1"
failed = failed or (not api_download and os.environ.get("FAKE_CURL_DIRECT_FAIL") == "1")
failed = failed or (api_download and os.environ.get("FAKE_CURL_API_FAIL") == "1")
if failed:
sys.stderr.write("curl: (22) fixture download failure for " + url + "\\n")
sys.exit(7)
if api_download:
if "--header" not in args or args[args.index("--header") + 1] != "Accept: application/octet-stream":
sys.stderr.write("curl: missing octet-stream Accept header\\n")
sys.exit(2)
output = None
for index, value in enumerate(args):
if value in ("--output", "-o"):
@@ -37,7 +46,8 @@ for index, value in enumerate(args):
if output is None:
sys.stderr.write("curl: missing --output\\n")
sys.exit(2)
with open(os.environ["FAKE_CURL_ARCHIVE"], "rb") as source:
archive_path = os.environ.get("FAKE_CURL_API_ARCHIVE", os.environ["FAKE_CURL_ARCHIVE"]) if api_download else os.environ["FAKE_CURL_ARCHIVE"]
with open(archive_path, "rb") as source:
payload = source.read()
with open(output, "wb") as target:
target.write(payload)
@@ -176,6 +186,9 @@ class ScanImagesWrapperTests(unittest.TestCase):
images=(VULN_TAG, CLEAN_TAG),
trivy_fail_id=None,
curl_fail=False,
curl_direct_fail=False,
curl_api_fail=False,
api_checksum_mismatch=False,
extra_env=None,
workdir_files=None,
run_in_workdir=False,
@@ -214,6 +227,8 @@ class ScanImagesWrapperTests(unittest.TestCase):
archive_path = root / "trivy-fixture.tar.gz"
archive_path.write_bytes(fixture_archive)
api_archive_path = root / "trivy-api-fixture.tar.gz"
api_archive_path.write_bytes(fixture_archive + b"tampered" if api_checksum_mismatch else fixture_archive)
reports = root / "reports"
reports.mkdir()
@@ -248,6 +263,7 @@ class ScanImagesWrapperTests(unittest.TestCase):
"PATH": f"{bin_dir}:{env['PATH']}",
"CRANK_IMAGE_SCAN_OUTPUT_DIR": str(evidence),
"FAKE_CURL_ARCHIVE": str(archive_path),
"FAKE_CURL_API_ARCHIVE": str(api_archive_path),
"FAKE_IMAGE_MAP": str(image_map),
"FAKE_REPORT_DIR": str(reports),
"FAKE_DOCKER_LOG": str(docker_log),
@@ -258,6 +274,10 @@ class ScanImagesWrapperTests(unittest.TestCase):
env["FAKE_TRIVY_FAIL_ID"] = trivy_fail_id
if curl_fail:
env["FAKE_CURL_FAIL"] = "1"
if curl_direct_fail:
env["FAKE_CURL_DIRECT_FAIL"] = "1"
if curl_api_fail:
env["FAKE_CURL_API_FAIL"] = "1"
if extra_env:
env.update(extra_env)
@@ -412,6 +432,18 @@ class ScanImagesWrapperTests(unittest.TestCase):
self.assertEqual(result.returncode, 2, result.stderr)
self.assertEqual(receipt["overall"]["status"], "error")
def test_database_download_uses_official_priority_and_fallback(self):
result, _, _, _, _, trivy_calls = self.run_scan(images=(CLEAN_TAG,))
self.assertEqual(result.returncode, 0, result.stderr)
downloads = [call["args"] for call in trivy_calls if "--download-db-only" in call["args"]]
self.assertEqual(len(downloads), 1)
args = downloads[0]
repositories = [args[index + 1] for index, item in enumerate(args) if item == "--db-repository"]
self.assertEqual(
repositories,
["ghcr.io/aquasecurity/trivy-db:2", "mirror.gcr.io/aquasec/trivy-db:2"],
)
def test_rerun_cannot_reuse_an_old_successful_raw_report(self):
result, _, evidence, receipt, _, _ = self.run_scan(images=(CLEAN_TAG,), repeat_without_output=True)
self.assertEqual(result.returncode, 2, result.stderr)
@@ -430,6 +462,37 @@ class ScanImagesWrapperTests(unittest.TestCase):
self.assertEqual(docker_calls, [])
self.assertEqual(trivy_calls, [])
def test_pinned_asset_api_fallback_downloads_and_verifies_same_archive(self):
result, _, evidence, receipt, _, trivy_calls = self.run_scan(
images=(CLEAN_TAG,), curl_direct_fail=True
)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(receipt["overall"]["status"], "pass")
self.assertIn("fixture download failure", (evidence / "scanner-download.log").read_text())
self.assertIn("GitHub release asset API", (evidence / "scanner-api-download.log").read_text())
self.assertTrue(any("--download-db-only" in call["args"] for call in trivy_calls))
scanner = json.loads((evidence / "scanner.json").read_text(encoding="utf-8"))
self.assertEqual(scanner["expected_version"], "0.70.0")
def test_pinned_asset_api_fallback_failure_fails_closed_with_both_logs(self):
result, _, evidence, receipt, _, trivy_calls = self.run_scan(
images=(CLEAN_TAG,), curl_direct_fail=True, curl_api_fail=True
)
self.assertEqual(result.returncode, 2)
self.assertEqual(receipt["overall"]["status"], "error")
self.assertIn("fixture download failure", (evidence / "scanner-download.log").read_text())
self.assertIn("fixture download failure", (evidence / "scanner-api-download.log").read_text())
self.assertEqual(trivy_calls, [])
def test_pinned_asset_api_fallback_checksum_mismatch_never_executes_trivy(self):
result, _, evidence, receipt, _, trivy_calls = self.run_scan(
images=(CLEAN_TAG,), curl_direct_fail=True, api_checksum_mismatch=True
)
self.assertEqual(result.returncode, 2)
self.assertEqual(receipt["overall"]["status"], "error")
self.assertIn("checksum mismatch", result.stderr)
self.assertEqual(trivy_calls, [])
def test_unknown_image_is_error_and_is_never_scanned(self):
missing = "crank/missing:ci"
result, _, _, receipt, _, trivy_calls = self.run_scan(images=(missing, CLEAN_TAG))
@@ -445,7 +508,8 @@ class ScanImagesWrapperTests(unittest.TestCase):
result, _, evidence, receipt, _, _ = self.run_scan(curl_fail=True)
self.assertEqual(result.returncode, 2, result.stderr)
self.assertEqual(receipt["overall"]["status"], "error")
self.assertIn("failed to connect", (evidence / "scanner-download.log").read_text())
self.assertIn("fixture download failure", (evidence / "scanner-download.log").read_text())
self.assertIn("fixture download failure", (evidence / "scanner-api-download.log").read_text())
def test_evidence_kept_even_when_gate_is_red(self):
_, _, evidence, receipt, _, _ = self.run_scan()