diff --git a/.github/workflows/case-pinning.yml b/.github/workflows/case-pinning.yml index 299028e4..b0d50484 100644 --- a/.github/workflows/case-pinning.yml +++ b/.github/workflows/case-pinning.yml @@ -40,53 +40,33 @@ jobs: timeout-minutes: 150 steps: - uses: actions/checkout@v4 - with: - path: apcore - - # The sweep runs the real drivers, so all three SDKs must be present and - # buildable. A missing checkout is not a pass: the tool raises NoTestsRan - # rather than reading "no tests ran" as "nothing went red", which is the - # bug that manufactured its own first Rust result. - - uses: actions/checkout@v4 - with: - repository: aiperceivable/apcore-python - path: apcore-python - - uses: actions/checkout@v4 - with: - repository: aiperceivable/apcore-typescript - path: apcore-typescript - - uses: actions/checkout@v4 - with: - repository: aiperceivable/apcore-rust - path: apcore-rust - uses: actions/setup-python@v5 with: python-version: "3.11" - uses: pnpm/action-setup@v4 with: - version: 9 + version: 10 - uses: actions/setup-node@v4 with: - node-version: "20" + node-version: "22" cache: pnpm - cache-dependency-path: apcore-typescript/pnpm-lock.yaml + cache-dependency-path: typescript/pnpm-lock.yaml - uses: dtolnay/rust-toolchain@stable - name: Test the mutation checker - working-directory: apcore run: python3 -m unittest conformance.test_check_case_pinning -v - name: Install SDKs run: | - python3 -m pip install --quiet -e apcore-python[dev] - pnpm --dir apcore-typescript install --frozen-lockfile - cargo build --manifest-path apcore-rust/Cargo.toml --tests --all-features + python3 -m pip install --quiet -e "./python[dev]" + pnpm --dir typescript install --frozen-lockfile + cargo build --manifest-path rust/Cargo.toml --tests --all-features # Warm the Rust build so the first mutated case is not charged for a full # compile inside the per-case timeout. - name: Prebuild Rust tests - run: cargo test --manifest-path apcore-rust/Cargo.toml --all-features --no-run + run: cargo test --manifest-path rust/Cargo.toml --all-features --no-run # Four scopes. `any` is the weak question — does SOME driver run this case — # and it is kept because a wholly dead case fails it first and cheapest. @@ -97,20 +77,21 @@ jobs: # positive cases were fixed in apcore-python and stayed broken in the other # two for exactly that reason (apcore#93). - name: Every fixture case is run by some driver, and by each of them - working-directory: apcore # The baseline is EMPTY: all 651 measurable cases are pinned as of # apcore#92. The diff below therefore fails on the first case that stops # being pinned, which is the state this job exists to hold. If the # baseline ever gains entries again, they are a backlog to shrink, not a # permanent exemption. + env: + FIXTURE: ${{ inputs.fixture }} + ONLY: ${{ inputs.sdk }} + shell: bash run: | - FIXTURE="${{ github.event.inputs.fixture }}" - ONLY="${{ github.event.inputs.sdk }}" : > pinning.txt for scope in any python typescript rust; do [ -n "$ONLY" ] && [ "$scope" != "$ONLY" ] && continue echo "===== scope: $scope" | tee -a pinning.txt - python3 conformance/check_case_pinning.py --sdk-root .. \ + python3 conformance/check_case_pinning.py --sdk-root . \ ${FIXTURE:+--fixture "$FIXTURE"} \ $([ "$scope" != any ] && echo "--sdk $scope") | tee -a pinning.txt done @@ -154,4 +135,4 @@ jobs: uses: actions/upload-artifact@v4 with: name: case-pinning - path: apcore/pinning.txt + path: pinning.txt diff --git a/.github/workflows/conformance-integrity.yml b/.github/workflows/conformance-integrity.yml index 4877a6f0..7cd30f31 100644 --- a/.github/workflows/conformance-integrity.yml +++ b/.github/workflows/conformance-integrity.yml @@ -201,7 +201,7 @@ jobs: # of them a configuration version, each stale the moment the next # release shipped. A reader copies the number and takes it for # something they must keep in step with their dependency. - run: python3 conformance/check_config_version_examples.py --sdk-root .. + run: python3 conformance/check_config_version_examples.py --sdk-root . - name: config_key_governance.json is in sync with schemas/ run: python3 conformance/generate_config_key_governance.py @@ -224,37 +224,15 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - with: - path: apcore - - - uses: actions/checkout@v4 - with: - repository: aiperceivable/apcore-python - path: apcore-python - continue-on-error: true - - - uses: actions/checkout@v4 - with: - repository: aiperceivable/apcore-typescript - path: apcore-typescript - continue-on-error: true - - - uses: actions/checkout@v4 - with: - repository: aiperceivable/apcore-rust - path: apcore-rust - continue-on-error: true - uses: actions/setup-python@v5 with: python-version: "3.11" - name: Every symbol the docs import resolves against the SDK - working-directory: apcore - run: python3 conformance/check_doc_examples.py --sdk-root .. + run: python3 conformance/check_doc_examples.py --sdk-root . - name: Every `expected` key is asserted by a driver - working-directory: apcore # --strict, because the backlog is closed: every top-level `expected` # key is asserted by at least one driver. A key no driver reads is not # a contract — it reads as covered everywhere while nothing is checked. @@ -268,7 +246,7 @@ jobs: # This is the guard that would have caught `wrapped_in`, declared by the # fixture and read by nobody, which let the MiddlewareChainError # wrapping be removed from two SDKs with every test still green. - run: python3 conformance/check_expected_keys_read.py --strict --sdk-root .. + run: python3 conformance/check_expected_keys_read.py --strict --sdk-root . # The probes below EXECUTE apcore-python. Without its runtime # dependencies every probe raises ImportError, and this job's whole point @@ -279,7 +257,6 @@ jobs: run: pip install --quiet "pydantic>=2.7,<3" "pyyaml>=6.0,<7" "jsonschema>=4.21,<5" - name: Every declared config key reaches a consumer - working-directory: apcore # config_key_governance.json pins that every declared key is ACCEPTED. It # is generated FROM schemas/, so a key wrong in the schema and in all # three SDKs identically is invisible to it — the same blind spot the @@ -292,10 +269,9 @@ jobs: # observe an effect OUTSIDE Config: four observability.* keys round-trip # through Config perfectly and are consumed by nothing, so a set-then-get # check — the one anybody would write — passes on all four. - run: python3 conformance/check_config_key_consumers.py --sdk-root .. + run: python3 conformance/check_config_key_consumers.py --sdk-root . - name: The ratchet ledger rejects every way around it - working-directory: apcore # The ratchet's "may fall, may not rise" lived in a code comment, and the # first raise under it was made in the same commit that changed the number. # A ceiling now has to equal the last entry of an append-only ledger, so a @@ -305,17 +281,15 @@ jobs: run: python3 conformance/check_config_key_consumers.py --self-test - name: Every fixture is driven by all three SDKs - working-directory: apcore # --strict, because the backlog is closed: all 60 fixtures are driven by # apcore-python, apcore-typescript AND apcore-rust. A fixture only two # SDKs load proves two implementations agree, not three — and it reads # as covered in every inventory. Strict keeps a new fixture from landing # undriven, which is how the backlog accumulated in the first place. - run: python3 conformance/check_driver_coverage.py --strict --sdk-root .. + run: python3 conformance/check_driver_coverage.py --strict --sdk-root . - name: Every behavioural decision names an executed case - working-directory: apcore # --strict, because the ratchet reached ZERO: all 44 behavioural # decisions from the 2026-09 deep-chain audit are pinned by an executed # case or by per-SDK tests covering every SDK they bind. The backlog @@ -328,10 +302,9 @@ jobs: # all failures. Those were never backlog — they are the map claiming # coverage it does not have, the exact failure this audit spent three # corrections on (D-125, D-126, and D-106's authority attribution). - run: python3 conformance/check_decision_coverage.py --strict --sdk-root .. + run: python3 conformance/check_decision_coverage.py --strict --sdk-root . - name: A clause one SDK disabled is a claim about that SDK - working-directory: apcore # NOT --strict: 24 clauses are disabled in one SDK and live in another, # and several are real API differences rather than defects. What this # DOES enforce is that the set cannot grow, and that the RECORD cannot @@ -350,4 +323,4 @@ jobs: # `@pytest.mark.skip`. Both directions are pinned in SELF_TEST. run: | python3 conformance/check_skip_asymmetry.py --self-test - python3 conformance/check_skip_asymmetry.py --sdk-root .. + python3 conformance/check_skip_asymmetry.py --sdk-root . diff --git a/.github/workflows/packages.yml b/.github/workflows/packages.yml new file mode 100644 index 00000000..23839d8f --- /dev/null +++ b/.github/workflows/packages.yml @@ -0,0 +1,92 @@ +name: Core distribution verification + +on: + pull_request: + paths: &sdk-paths + - 'python/**' + - 'rust/**' + - 'typescript/**' + - '.github/workflows/packages.yml' + push: + branches: [main] + paths: *sdk-paths + workflow_dispatch: + +permissions: + contents: read + +jobs: + python: + runs-on: ubuntu-latest + defaults: + run: + working-directory: python + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 + with: + python-version: '3.12' + - name: Build wheel and sdist + run: | + python -m pip install build + python -m build + - name: Verify installed wheel + shell: bash + run: | + wheel=( "$PWD"/dist/*.whl ) + temporary=$(mktemp -d) + python -m venv "$temporary/venv" + cd "$temporary" + "$temporary/venv/bin/python" -m pip install "${wheel[0]}" + "$temporary/venv/bin/python" -m pip check + "$temporary/venv/bin/python" -c 'from apcore import APCore, Registry' + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 + with: + name: core-python-distributions + path: python/dist/ + + rust: + runs-on: ubuntu-latest + defaults: + run: + working-directory: rust + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + - uses: dtolnay/rust-toolchain@stable + - run: cargo package --locked + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 + with: + name: core-rust-distribution + path: rust/target/package/*.crate + + typescript: + runs-on: ubuntu-latest + defaults: + run: + working-directory: typescript + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + - uses: actions/setup-node@v4 + with: + node-version: '22' + - uses: pnpm/action-setup@v4 + with: + version: '10.30.1' + - run: pnpm install --frozen-lockfile + - run: pnpm build + - name: Verify packed Node and browser entry points + shell: bash + run: | + temporary=$(mktemp -d) + mkdir -p "$GITHUB_WORKSPACE/dist-archives" + pnpm pack --pack-destination "$GITHUB_WORKSPACE/dist-archives" + archive=( "$GITHUB_WORKSPACE"/dist-archives/*.tgz ) + cd "$temporary" + npm init -y + npm install --ignore-scripts "${archive[0]}" + node --input-type=module -e 'import {APCore} from "apcore-js"; import "apcore-js/context-keys"; if (!APCore) throw new Error("APCore is missing");' + node --conditions=browser --input-type=module -e 'if (!import.meta.resolve("apcore-js").endsWith("/dist/browser/index.js")) throw new Error("browser entry did not resolve"); await import("apcore-js");' + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 + with: + name: core-npm-distribution + path: dist-archives/*.tgz diff --git a/.github/workflows/sdk-python.yml b/.github/workflows/sdk-python.yml new file mode 100644 index 00000000..68a56028 --- /dev/null +++ b/.github/workflows/sdk-python.yml @@ -0,0 +1,59 @@ +name: Core SDK (python) + +permissions: + contents: read + +on: + push: + branches: [ "main" ] + pull_request: + branches: [ "main" ] + +jobs: + test: + name: Test on Python ${{ matrix.python-version }} + runs-on: ubuntu-latest + defaults: + run: + working-directory: python + env: + CONFORMANCE_SPEC_REPO: ${{ github.workspace }} + # container: + # image: python:${{ matrix.python-version }} + strategy: + fail-fast: false + matrix: + # Pin CI to a single, consistent Python version to reduce version-related + # test flakiness. Use 3.12 for CI stability; expand matrix later if desired. + python-version: ["3.12"] + + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + + - name: Set up Python + uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 + with: + python-version: ${{ matrix.python-version }} + cache: pip + cache-dependency-path: python/pyproject.toml + + - name: Install dependencies + run: | + python -m pip install --upgrade pip + # If a constraints.txt file is present, use it to pin critical dependency versions. + if [ -f constraints.txt ]; then + pip install -e ".[dev]" -c constraints.txt + else + pip install -e ".[dev]" + fi + + - name: Verify canonical conformance fixture checkout + run: pytest tests/conformance/test_fixture_checkout.py -q + + - name: Lint with Ruff + run: | + ruff check src/ tests/ + + - name: Run tests + run: | + pytest diff --git a/.github/workflows/sdk-rust.yml b/.github/workflows/sdk-rust.yml new file mode 100644 index 00000000..39d4f71a --- /dev/null +++ b/.github/workflows/sdk-rust.yml @@ -0,0 +1,76 @@ +name: Core SDK (rust) + +permissions: + contents: read + +on: + push: + branches: ["main"] + pull_request: + branches: ["main"] + +jobs: + test: + name: Test on Rust ${{ matrix.rust }} + runs-on: ubuntu-latest + defaults: + run: + working-directory: rust + strategy: + fail-fast: false + matrix: + # Pin CI to stable. Add `beta` / `nightly` later if desired. + rust: ["stable"] + + steps: + - name: Free disk space + working-directory: ${{ github.workspace }} + run: | + df -h + sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc /opt/hostedtoolcache/CodeQL + sudo docker image prune --all --force || true + df -h + + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + + - name: Install Rust toolchain + uses: dtolnay/rust-toolchain@stable + with: + toolchain: ${{ matrix.rust }} + components: rustfmt, clippy + + - name: Cache cargo registry & build + uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3 + with: + path: | + ~/.cargo/registry + ~/.cargo/git + rust/target + key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} + restore-keys: | + ${{ runner.os }}-cargo- + + - name: Install apdev-rs + run: cargo install apdev-rs + continue-on-error: true + + - name: Check characters + run: apdev-rs check-chars src/ + continue-on-error: true + + - name: Check formatting + run: cargo fmt --all -- --check + + - name: Lint with Clippy + run: cargo clippy --all-targets --all-features -- -D warnings + + - name: Build + run: cargo build --all-features + + - name: Run tests + run: cargo test --all-features + env: + CONFORMANCE_SPEC_REPO: ${{ github.workspace }} + + - name: Build examples + run: cargo build --examples diff --git a/.github/workflows/sdk-typescript.yml b/.github/workflows/sdk-typescript.yml new file mode 100644 index 00000000..1f32fbd3 --- /dev/null +++ b/.github/workflows/sdk-typescript.yml @@ -0,0 +1,49 @@ +name: Core SDK (typescript) + +on: + push: + branches: [main] + pull_request: + branches: [main] + +jobs: + build-and-test: + runs-on: ubuntu-latest + defaults: + run: + working-directory: typescript + env: + CONFORMANCE_SPEC_REPO: ${{ github.workspace }} + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Set up Node.js + uses: actions/setup-node@v4 + with: + node-version: '22' + + - name: Install pnpm + uses: pnpm/action-setup@v4 + with: + version: 10 + + - name: Install dependencies + run: pnpm install + + - name: Verify canonical conformance fixture checkout + run: pnpm exec vitest run tests/test-conformance-checkout.test.ts + + - name: Check characters and imports + run: | + pnpm exec apdev-js check-chars src tests examples + pnpm exec apdev-js check-imports --package apcore-js + + - name: Typecheck library and examples + run: pnpm run typecheck + + - name: Build + run: pnpm build + + - name: Run tests + run: pnpm test:coverage diff --git a/CLAUDE.md b/CLAUDE.md index f4a20176..df71c08d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,14 +1,8 @@ -# CLAUDE.md — apcore Protocol Specification Repository +# APCore Protocol and SDK Repository ## Project Context -**apcore** is a language-agnostic **protocol specification** — not a runtime library. -This repo contains specs, docs, JSON Schemas, and conformance fixtures. The SDKs live in separate repos. - -| Repo | Role | -|---|---| -| `apcore` (here) | Protocol spec, docs, schemas, conformance tests | -| `apcore-python` / `apcore-typescript` / `apcore-rust` | Language SDK implementations | +This repository contains the language-agnostic protocol specification, docs, JSON Schemas, shared conformance fixtures, and independently published Python, TypeScript, and Rust SDKs. Toolkit, MCP, A2A, and CLI live in [apcore-surfaces](https://github.com/aiperceivable/apcore-surfaces). Tech stack: **MkDocs Material** + GitHub Pages + JSON Schema Draft 2020-12. @@ -19,6 +13,9 @@ apcore/ ├── docs/spec/protocol-spec.md # Single source of truth (RFC 2119) ├── schemas/ # Canonical JSON Schema files (*.schema.json) ├── conformance/fixtures/ # Cross-language test fixtures (*.json) +├── python/ # Python runtime SDK +├── rust/ # Rust runtime SDK +├── typescript/ # TypeScript runtime SDK ├── docs/ │ ├── features/ # One reference page per runtime subsystem (current behaviour, 3-language examples) │ ├── guides/ # How-to tutorials and cookbooks for SDK users @@ -108,7 +105,7 @@ Use standardized terms consistently: ### Cross-Language Consistency - Do NOT document behavior changes for one SDK without noting cross-language impact - Do NOT add Python-specific idioms to language-agnostic spec sections -- Do NOT assume SDK behavior matches without verifying the relevant SDK repo +- Verify behavior in the relevant SDK directories ### ACL & Security - Do NOT change `default_effect` from `deny` to `allow` without a prominent warning diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a37b9fee..fa5608d5 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -18,13 +18,15 @@ Spec changes must be reviewed and approved by at least 2 maintainers — **or by ## Language SDKs -Each SDK has its own repository with language-specific setup instructions: +Clone this repository once. Each SDK has its own setup and test commands. -| SDK | Repository | Setup | +| SDK | Directory | Setup | |-----|-----------|-------| -| Python | [apcore-python](https://github.com/aiperceivable/apcore-python) | Python 3.11+, `pip install -e .` | -| TypeScript | [apcore-typescript](https://github.com/aiperceivable/apcore-typescript) | Node 18+, `npm install` | -| Rust | [apcore-rust](https://github.com/aiperceivable/apcore-rust) | Rust 1.75+, `cargo build` | +| Python | [`python/`](./python/) | `python -m pip install -e '.[dev]'` | +| TypeScript | [`typescript/`](./typescript/) | `pnpm install --frozen-lockfile` | +| Rust | [`rust/`](./rust/) | `cargo build` | + +Run the commands from the corresponding SDK directory. The test suites read the shared fixtures in `conformance/` at the repository root. ## Pull Request Process @@ -48,16 +50,15 @@ the project's license. See [developercertificate.org](https://developercertifica ## Coding Guidelines -- Follow the existing code style in each repository +- Follow the existing code style in each SDK - Write tests for new functionality - Keep PRs focused — one logical change per PR - Update documentation when changing user-facing behavior ## Cross-Language Consistency -When making changes that affect the protocol or module behavior, consider -the impact across all three language implementations. Ideally, changes to -the spec should be accompanied by PRs to all affected SDK repositories. +When a change affects the protocol or module behavior, include the affected +SDKs and their conformance drivers in the same pull request. ## Reporting Security Issues diff --git a/README.md b/README.md index d8e7606f..1d75d7a9 100644 --- a/README.md +++ b/README.md @@ -10,23 +10,19 @@ [![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) [![OpenSSF Best Practices](https://www.bestpractices.dev/projects/12294/badge)](https://www.bestpractices.dev/projects/12294) -[![Python Version](https://img.shields.io/badge/python-3.11%2B-blue)](https://github.com/aiperceivable/apcore-python) -[![TypeScript Version](https://img.shields.io/badge/TypeScript-Node_18%2B-blue)](https://github.com/aiperceivable/apcore-typescript) -[![Rust Version](https://img.shields.io/badge/Rust-1.75%2B-blue)](https://github.com/aiperceivable/apcore-rust) - apcore is a **governed, protocol-neutral runtime and module standard** for application capabilities that agents or code can call. You define a capability once — a description, an input schema, an output schema and behavioral annotations. The runtime then applies identity, access control, approval, validation, middleware, execution, structured errors and trace context on every call. Surface adapters project the same capability to MCP, A2A, CLI, HTTP or direct code. MCP tells an agent what it *can* call. apcore decides whether *this* call — with these arguments, by this identity — should run at all, and leaves evidence that it did. -This repository holds the **protocol specification**, JSON Schemas and cross-language conformance fixtures. The runtimes live in separate repositories: +This repository holds the **protocol specification**, JSON Schemas, cross-language conformance fixtures and three independently published runtime SDKs. -| SDK | Language | Install | Repository | -|-----|----------|---------|------------| -| `apcore` | Python 3.11+ | `pip install apcore` | [apcore-python](https://github.com/aiperceivable/apcore-python) | -| `apcore-js` | TypeScript (Node 18+) | `npm install apcore-js` | [apcore-typescript](https://github.com/aiperceivable/apcore-typescript) | -| `apcore` | Rust 1.75+ | `cargo add apcore` | [apcore-rust](https://github.com/aiperceivable/apcore-rust) | +| Language | Install | Source | +|----------|---------|--------| +| Python | `pip install apcore` | [Python SDK](./python/) | +| TypeScript | `npm install apcore-js` | [TypeScript SDK](./typescript/) | +| Rust | `cargo add apcore` | [Rust SDK](./rust/) | Current versions are listed on the [documentation home](./docs/index.md). @@ -154,10 +150,10 @@ Adapters are independently versioned and available for Python, TypeScript and Ru | Adapter | Projects modules as | Repository | |---|---|---| -| `apcore-mcp` | MCP tools (with a Tool Explorer UI) | [apcore-mcp](https://github.com/aiperceivable/apcore-mcp) | -| `apcore-a2a` | A2A skills and Agent Card metadata | [apcore-a2a](https://github.com/aiperceivable/apcore-a2a) | -| `apcore-cli` | CLI commands and arguments | [apcore-cli](https://github.com/aiperceivable/apcore-cli) | -| `apcore-toolkit` | Shared scanners, schema extraction and output writers for adapter authors | [apcore-toolkit](https://github.com/aiperceivable/apcore-toolkit) | +| `apcore-mcp` | MCP tools (with a Tool Explorer UI) | [apcore-mcp](https://github.com/aiperceivable/apcore-surfaces/tree/main/mcp) | +| `apcore-a2a` | A2A skills and Agent Card metadata | [apcore-a2a](https://github.com/aiperceivable/apcore-surfaces/tree/main/a2a) | +| `apcore-cli` | CLI commands and arguments | [apcore-cli](https://github.com/aiperceivable/apcore-surfaces/tree/main/cli) | +| `apcore-toolkit` | Shared scanners, schema extraction and output writers for adapter authors | [apcore-toolkit](https://github.com/aiperceivable/apcore-surfaces/tree/main/toolkit) | Framework integrations bind HTTP endpoints to modules: `fastapi-apcore`, `django-apcore`, `flask-apcore`, `nestjs-apcore`, `express-apcore`, `hono-apcore`, `axum-apcore`. To write your own, see the [Adapter Development guide](./docs/guides/adapter-development.md). diff --git a/SCOPE.md b/SCOPE.md index 411ace77..3952697a 100644 --- a/SCOPE.md +++ b/SCOPE.md @@ -90,7 +90,7 @@ Things explicitly **not within the project scope**: | Won't Do | Reason | Owned By | |------|------|--------| | **Workflow Engine** | Application-layer orchestration logic, not framework core | apflow and other upstream projects | -| **MCP/A2A/CLI Adapters** | Protocol and surface adaptation, not core standard | [apcore-mcp](https://github.com/aiperceivable/apcore-mcp), [apcore-a2a](https://github.com/aiperceivable/apcore-a2a), [apcore-cli](https://github.com/aiperceivable/apcore-cli) | +| **MCP/A2A/CLI Adapters** | Protocol and surface adaptation, not core standard | [apcore-mcp](https://github.com/aiperceivable/apcore-surfaces/tree/main/mcp), [apcore-a2a](https://github.com/aiperceivable/apcore-surfaces/tree/main/a2a), [apcore-cli](https://github.com/aiperceivable/apcore-surfaces/tree/main/cli) | | **Rate Limiting** | Runtime resilience middleware, not module definition | apcore-toolkit (middleware implementations) | | **Secret Injection / Vault Integration** | Runtime infrastructure, not module standard | apcore-toolkit | | **Testing Framework** | Developer tooling, not protocol | [apcore-testing](https://github.com/aiperceivable/apcore-testing) | @@ -172,9 +172,9 @@ Use these scenarios to validate whether our boundaries are correct: | `module()` registration (Decorator / function call) | ✅ Core | Least intrusive integration for existing applications | | External Schema Binding | ✅ Core | Zero code modification integration | | Type inference Schema generation | ✅ Core | Foundational capability for module() and Binding | -| **MCP Adapter** | ⚡ Ecosystem ([apcore-mcp](https://github.com/aiperceivable/apcore-mcp)) | Protocol adaptation | -| **A2A Adapter** | ⚡ Ecosystem ([apcore-a2a](https://github.com/aiperceivable/apcore-a2a)) | Protocol adaptation | -| **CLI Adapter** | ⚡ Ecosystem ([apcore-cli](https://github.com/aiperceivable/apcore-cli)) | Surface adaptation | +| **MCP Adapter** | ⚡ Ecosystem ([apcore-mcp](https://github.com/aiperceivable/apcore-surfaces/tree/main/mcp)) | Protocol adaptation | +| **A2A Adapter** | ⚡ Ecosystem ([apcore-a2a](https://github.com/aiperceivable/apcore-surfaces/tree/main/a2a)) | Protocol adaptation | +| **CLI Adapter** | ⚡ Ecosystem ([apcore-cli](https://github.com/aiperceivable/apcore-surfaces/tree/main/cli)) | Surface adaptation | | **Rate Limiting** | ⚡ Ecosystem (apcore-toolkit) | Runtime resilience; implemented as middleware | | **Circuit Breaker** | ✅ Core (`CircuitBreakerMiddleware`) | Resilience middleware shipped in all three SDKs | | **Secret Injection** | ⚡ Ecosystem (apcore-toolkit) | Runtime infrastructure; `x-sensitive` marking is Core | diff --git a/conformance/check_case_pinning.py b/conformance/check_case_pinning.py index e74a3e97..4676cbac 100644 --- a/conformance/check_case_pinning.py +++ b/conformance/check_case_pinning.py @@ -59,6 +59,11 @@ import tempfile from pathlib import Path +if __package__: + from .sdk_layout import sdk_dir +else: + from sdk_layout import sdk_dir + REPO = Path(__file__).resolve().parent.parent FIXTURES = REPO / "conformance" / "fixtures" BASELINE = REPO / "conformance" / "case_pinning_baseline.json" @@ -203,7 +208,7 @@ def driver_files(sdk_root: Path) -> dict[str, dict[str, list[Path]]]: stems = [p.stem for p in FIXTURES.glob("*.json")] out: dict[str, dict[str, list[Path]]] = {s: {} for s in stems} for sdk, repo, suffix in SDKS: - base = sdk_root / repo / "tests" + base = sdk_dir(sdk_root, repo) / "tests" if not base.is_dir(): continue for path in base.rglob(f"*{suffix}"): @@ -255,7 +260,7 @@ def run_drivers_verbose(sdk: str, sdk_root: Path, files: list[Path]) -> tuple[bo target is named after its file, so every Rust verdict in the first per-SDK sweep was manufactured by this bug rather than measured. """ - repo = sdk_root / dict((s, r) for s, r, _ in SDKS)[sdk] + repo = sdk_dir(sdk_root, dict((s, r) for s, r, _ in SDKS)[sdk]) # The drivers must exercise the CHECKOUT, not whatever `apcore` happens to be # installed. CI gets that from `pip install -e`, but a developer with a stale # non-editable wheel in site-packages runs the whole sweep against it: the @@ -482,7 +487,7 @@ def load_allowlist() -> dict[tuple[str, str], set[str]]: def main() -> int: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) - ap.add_argument("--sdk-root", type=Path, default=REPO.parent) + ap.add_argument("--sdk-root", type=Path, default=REPO) ap.add_argument("--fixture", help="limit to one fixture (stem, no .json)") ap.add_argument("--sdk", choices=[s[0] for s in SDKS], help="ask the question of ONE SDK: which cases does it not run? " diff --git a/conformance/check_config_key_consumers.py b/conformance/check_config_key_consumers.py index e15cdb1a..34ceaae8 100644 --- a/conformance/check_config_key_consumers.py +++ b/conformance/check_config_key_consumers.py @@ -55,6 +55,11 @@ import warnings from collections.abc import Iterator from pathlib import Path + +if __package__: + from .sdk_layout import sdk_dir +else: + from sdk_layout import sdk_dir from typing import Callable HERE = Path(__file__).resolve().parent @@ -2210,7 +2215,7 @@ def discover(patterns: list[str] | None) -> set[str]: def main() -> int: ap = argparse.ArgumentParser(description=__doc__) - ap.add_argument("--sdk-root", default="..", help="directory holding the sibling SDK checkouts") + ap.add_argument("--sdk-root", default=str(HERE.parent), help="directory holding the sibling SDK checkouts") ap.add_argument( "--self-test", action="store_true", @@ -2243,7 +2248,7 @@ def main() -> int: problems.append(f"{key}: listed here but no longer a declared configuration key") # 2. Shape, and probes. - python_src = Path(args.sdk_root).resolve() / "apcore-python" / "src" + python_src = sdk_dir(Path(args.sdk_root).resolve(), "apcore-python") / "src" have_python = python_src.is_dir() if have_python: sys.path.insert(0, str(python_src)) diff --git a/conformance/check_config_version_examples.py b/conformance/check_config_version_examples.py index 28c883e2..a8515517 100644 --- a/conformance/check_config_version_examples.py +++ b/conformance/check_config_version_examples.py @@ -27,6 +27,11 @@ import sys from pathlib import Path +if __package__: + from .sdk_layout import sdk_dir +else: + from sdk_layout import sdk_dir + REPO = Path(__file__).resolve().parent.parent SCHEMA = REPO / "schemas" / "apcore-config.schema.json" @@ -101,7 +106,7 @@ def scan(path: Path, allowed: set[str]) -> list[str]: def main() -> int: parser = argparse.ArgumentParser() - parser.add_argument("--sdk-root", type=Path, default=REPO.parent) + parser.add_argument("--sdk-root", type=Path, default=REPO) args = parser.parse_args() allowed = sanctioned_versions() @@ -109,7 +114,7 @@ def main() -> int: for pattern in DOC_GLOBS: files.extend(sorted(REPO.glob(pattern))) for sdk in ("apcore-python", "apcore-typescript", "apcore-rust"): - readme = args.sdk_root / sdk / "README.md" + readme = sdk_dir(args.sdk_root, sdk) / "README.md" if readme.is_file(): files.append(readme) diff --git a/conformance/check_decision_coverage.py b/conformance/check_decision_coverage.py index 45f91c15..aa6943aa 100644 --- a/conformance/check_decision_coverage.py +++ b/conformance/check_decision_coverage.py @@ -45,6 +45,11 @@ import sys from pathlib import Path +if __package__: + from .sdk_layout import sdk_dir +else: + from sdk_layout import sdk_dir + REPO = Path(__file__).resolve().parent.parent FIXTURES = REPO / "conformance" / "fixtures" MAP = REPO / "conformance" / "decision_coverage.json" @@ -102,7 +107,7 @@ def unmeasurable_cases() -> dict[str, set[str]]: def main() -> int: ap = argparse.ArgumentParser(description=__doc__) - ap.add_argument("--sdk-root", type=Path, default=REPO.parent) + ap.add_argument("--sdk-root", type=Path, default=REPO) ap.add_argument("--strict", action="store_true", help="exit 1 while any behavioural decision is unpinned") ap.add_argument("--write-ratchet", action="store_true", @@ -166,7 +171,7 @@ def main() -> int: # checking the file: a test function renamed out from under the # map goes red here instead of quietly reading as coverage. path, _, node = rel.partition("::") - target = args.sdk_root / SDK_DIRS[sdk] / path + target = sdk_dir(args.sdk_root, SDK_DIRS[sdk]) / path if not target.exists(): rot.append(f"{key}: {sdk} test {path!r} does not exist") elif node and node.rsplit("::", 1)[-1] not in target.read_text( diff --git a/conformance/check_doc_examples.py b/conformance/check_doc_examples.py index 8eb96f2e..35f59a91 100644 --- a/conformance/check_doc_examples.py +++ b/conformance/check_doc_examples.py @@ -37,6 +37,11 @@ import sys from pathlib import Path +if __package__: + from .sdk_layout import sdk_dir +else: + from sdk_layout import sdk_dir + REPO = Path(__file__).resolve().parent.parent # ---------------------------------------------------------------- extraction @@ -324,13 +329,13 @@ def check_rust(blocks, exports: set[str], variants: set[str], out: list[Violatio def main() -> int: ap = argparse.ArgumentParser(description=__doc__) - ap.add_argument("--sdk-root", type=Path, default=REPO.parent, + ap.add_argument("--sdk-root", type=Path, default=REPO, help="directory holding apcore-python / apcore-typescript / apcore-rust") args = ap.parse_args() - py_sdk = args.sdk_root / "apcore-python" - ts_sdk = args.sdk_root / "apcore-typescript" - rs_sdk = args.sdk_root / "apcore-rust" + py_sdk = sdk_dir(args.sdk_root, "apcore-python") + ts_sdk = sdk_dir(args.sdk_root, "apcore-typescript") + rs_sdk = sdk_dir(args.sdk_root, "apcore-rust") present = [p.name for p in (py_sdk, ts_sdk, rs_sdk) if p.is_dir()] if not present: print(f"No SDK checkouts under {args.sdk_root} — skipping. " diff --git a/conformance/check_driver_coverage.py b/conformance/check_driver_coverage.py index 33201949..a7f43da1 100644 --- a/conformance/check_driver_coverage.py +++ b/conformance/check_driver_coverage.py @@ -28,6 +28,11 @@ import sys from pathlib import Path +if __package__: + from .sdk_layout import sdk_dir +else: + from sdk_layout import sdk_dir + REPO = Path(__file__).resolve().parent.parent FIXTURES = REPO / "conformance" / "fixtures" BASELINE = REPO / "conformance" / "driver_coverage_baseline.json" @@ -113,7 +118,7 @@ def loads_fixtures(text: str, suffix: str) -> bool: def drivers_for(sdk_root: Path, sdk: str, fixture_stem: str) -> list[str]: """Test files in `sdk` that load `.json` by name.""" repo, test_dirs, suffixes = SDKS[sdk] - base = sdk_root / repo + base = sdk_dir(sdk_root, repo) if not base.is_dir(): return [] # Loaders name a fixture either with its extension (Python's @@ -146,14 +151,14 @@ def drivers_for(sdk_root: Path, sdk: str, fixture_stem: str) -> list[str]: def main() -> int: ap = argparse.ArgumentParser(description=__doc__) - ap.add_argument("--sdk-root", type=Path, default=REPO.parent) + ap.add_argument("--sdk-root", type=Path, default=REPO) ap.add_argument("--strict", action="store_true", help="exit 1 on any gap") ap.add_argument("--baseline", action="store_true", help="exit 1 only on gaps not in driver_coverage_baseline.json") ap.add_argument("--write-baseline", action="store_true") args = ap.parse_args() - present = [s for s, (repo, *_) in SDKS.items() if (args.sdk_root / repo).is_dir()] + present = [s for s, (repo, *_) in SDKS.items() if sdk_dir(args.sdk_root, repo).is_dir()] if len(present) < 3: print(f"Need all three SDK checkouts under {args.sdk_root} " f"(found: {', '.join(present) or 'none'}) — skipping.") @@ -176,7 +181,7 @@ def main() -> int: for path in sorted(FIXTURES.glob("*.json")): for sdk, (repo, *_rest) in SDKS.items(): for rel in drivers_for(args.sdk_root, sdk, path.stem): - q, d = quarantine_ratio(args.sdk_root / repo / rel) + q, d = quarantine_ratio(sdk_dir(args.sdk_root, repo) / rel) if d and q >= d: vacuous.append(f"{path.stem} / {sdk}: {rel} — {q} quarantine marker(s) " f"for {d} test(s); this may be counted as driven while " diff --git a/conformance/check_expected_keys_read.py b/conformance/check_expected_keys_read.py index c9e6c30c..b5a5eb7e 100644 --- a/conformance/check_expected_keys_read.py +++ b/conformance/check_expected_keys_read.py @@ -37,6 +37,11 @@ class name all three SDKs share, and was green while they emitted three differen import sys from pathlib import Path +if __package__: + from .sdk_layout import sdk_dir +else: + from sdk_layout import sdk_dir + REPO = Path(__file__).resolve().parent.parent FIXTURES = REPO / "conformance" / "fixtures" BASELINE = REPO / "conformance" / "expected_keys_baseline.json" @@ -73,7 +78,7 @@ def drivers_for(sdk_root: Path, fixture_stem: str) -> dict[str, str]: out: dict[str, str] = {} pattern = _fixture_pattern(fixture_stem) for sdk, (repo, suffix) in SDKS.items(): - base = sdk_root / repo / "tests" + base = sdk_dir(sdk_root, repo) / "tests" if not base.is_dir(): continue chunks = [] @@ -90,7 +95,7 @@ def drivers_for(sdk_root: Path, fixture_stem: str) -> dict[str, str]: def available_sdks(sdk_root: Path) -> list[str]: """Which SDK checkouts are present — the script needs all three to be honest.""" - return [sdk for sdk, (repo, _) in SDKS.items() if (sdk_root / repo / "tests").is_dir()] + return [sdk for sdk, (repo, _) in SDKS.items() if (sdk_dir(sdk_root, repo) / "tests").is_dir()] #: How a driver asserts EVERY key of `expected` without naming any of them. @@ -154,7 +159,7 @@ def load_allowlist() -> dict[str, set[str]]: def main() -> int: ap = argparse.ArgumentParser(description=__doc__) - ap.add_argument("--sdk-root", type=Path, default=REPO.parent) + ap.add_argument("--sdk-root", type=Path, default=REPO) ap.add_argument("--strict", action="store_true", help="exit 1 on any unread key") ap.add_argument("--baseline", action="store_true", help="exit 1 only on keys not in expected_keys_baseline.json") diff --git a/conformance/check_skip_asymmetry.py b/conformance/check_skip_asymmetry.py index 4c7a820d..93884e24 100644 --- a/conformance/check_skip_asymmetry.py +++ b/conformance/check_skip_asymmetry.py @@ -68,6 +68,11 @@ import sys from pathlib import Path +if __package__: + from .sdk_layout import sdk_dir +else: + from sdk_layout import sdk_dir + REPO = Path(__file__).resolve().parent.parent BASELINE = REPO / "conformance" / "skip_asymmetry_baseline.json" @@ -262,7 +267,7 @@ def self_test() -> list[str]: def asymmetries(sdk_root: Path) -> dict[str, dict[str, str]]: - seen = {sdk: scan(sdk_root / d / "tests", SDK_EXT[sdk]) for sdk, d in SDK_DIRS.items()} + seen = {sdk: scan(sdk_dir(sdk_root, d) / "tests", SDK_EXT[sdk]) for sdk, d in SDK_DIRS.items()} every_id = set().union(*(s.keys() for s in seen.values())) out: dict[str, dict[str, str]] = {} for cid in sorted(every_id): @@ -275,7 +280,7 @@ def asymmetries(sdk_root: Path) -> dict[str, dict[str, str]]: def main() -> int: ap = argparse.ArgumentParser(description=__doc__) - ap.add_argument("--sdk-root", type=Path, default=REPO.parent) + ap.add_argument("--sdk-root", type=Path, default=REPO) ap.add_argument("--strict", action="store_true", help="exit 1 on any asymmetry") ap.add_argument( "--self-test", diff --git a/conformance/sdk_layout.py b/conformance/sdk_layout.py new file mode 100644 index 00000000..6c775d49 --- /dev/null +++ b/conformance/sdk_layout.py @@ -0,0 +1,11 @@ +"""Resolve SDK checkouts from the monorepo or an older sibling layout.""" + +from pathlib import Path + + +def sdk_dir(root: Path, legacy_name: str) -> Path: + """Find a language SDK under the given root.""" + member = root / legacy_name.removeprefix("apcore-") + if member.is_dir(): + return member + return root / legacy_name diff --git a/docs/SCOPE.md b/docs/SCOPE.md index 1f2c5aee..fc055acc 100644 --- a/docs/SCOPE.md +++ b/docs/SCOPE.md @@ -92,7 +92,7 @@ Things explicitly **not within the project scope**: | Won't Do | Reason | Owned By | |------|------|--------| | **Workflow Engine** | Application-layer orchestration logic, not framework core | apflow and other upstream projects | -| **MCP/A2A/CLI Adapters** | Protocol and surface adaptation, not core standard | [apcore-mcp](https://github.com/aiperceivable/apcore-mcp), [apcore-a2a](https://github.com/aiperceivable/apcore-a2a), [apcore-cli](https://github.com/aiperceivable/apcore-cli) | +| **MCP/A2A/CLI Adapters** | Protocol and surface adaptation, not core standard | [apcore-mcp](https://github.com/aiperceivable/apcore-surfaces/tree/main/mcp), [apcore-a2a](https://github.com/aiperceivable/apcore-surfaces/tree/main/a2a), [apcore-cli](https://github.com/aiperceivable/apcore-surfaces/tree/main/cli) | | **Rate Limiting** | Runtime resilience middleware, not module definition | apcore-toolkit (middleware implementations) | | **Secret Injection / Vault Integration** | Runtime infrastructure, not module standard | apcore-toolkit | | **Testing Framework** | Developer tooling, not protocol | [apcore-testing](https://github.com/aiperceivable/apcore-testing) | @@ -174,9 +174,9 @@ Use these scenarios to validate whether our boundaries are correct: | `module()` registration (Decorator / function call) | ✅ Core | Least intrusive integration for existing applications | | External Schema Binding | ✅ Core | Zero code modification integration | | Type inference Schema generation | ✅ Core | Foundational capability for module() and Binding | -| **MCP Adapter** | ⚡ Ecosystem ([apcore-mcp](https://github.com/aiperceivable/apcore-mcp)) | Protocol adaptation | -| **A2A Adapter** | ⚡ Ecosystem ([apcore-a2a](https://github.com/aiperceivable/apcore-a2a)) | Protocol adaptation | -| **CLI Adapter** | ⚡ Ecosystem ([apcore-cli](https://github.com/aiperceivable/apcore-cli)) | Surface adaptation | +| **MCP Adapter** | ⚡ Ecosystem ([apcore-mcp](https://github.com/aiperceivable/apcore-surfaces/tree/main/mcp)) | Protocol adaptation | +| **A2A Adapter** | ⚡ Ecosystem ([apcore-a2a](https://github.com/aiperceivable/apcore-surfaces/tree/main/a2a)) | Protocol adaptation | +| **CLI Adapter** | ⚡ Ecosystem ([apcore-cli](https://github.com/aiperceivable/apcore-surfaces/tree/main/cli)) | Surface adaptation | | **Rate Limiting** | ⚡ Ecosystem (apcore-toolkit) | Runtime resilience; implemented as middleware | | **Circuit Breaker** | ✅ Core (`CircuitBreakerMiddleware`) | Resilience middleware shipped in all three SDKs | | **Secret Injection** | ⚡ Ecosystem (apcore-toolkit) | Runtime infrastructure; `x-sensitive` marking is Core | diff --git a/docs/getting-started.md b/docs/getting-started.md index 189b9958..753c7dd4 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -509,7 +509,7 @@ See [System Modules](features/system-modules.md) for the full module reference. - [ACL Configuration](guides/acl-configuration.md) - Secure your modules. - [Event System](features/event-system.md) - Framework event bus and subscribers. - [System Modules](features/system-modules.md) - Built-in health, usage, and control modules. -- [apcore-toolkit](https://github.com/aiperceivable/apcore-toolkit) - Shared scanner, schema extraction, and output toolkit. -- [apcore-mcp](https://github.com/aiperceivable/apcore-mcp) - Expose these modules as an MCP Server. -- [apcore-a2a](https://github.com/aiperceivable/apcore-a2a) - Expose these modules as an A2A Agent. -- [apcore-cli](https://github.com/aiperceivable/apcore-cli) - Expose these modules as CLI commands. +- [apcore-toolkit](https://github.com/aiperceivable/apcore-surfaces/tree/main/toolkit) - Shared scanner, schema extraction, and output toolkit. +- [apcore-mcp](https://github.com/aiperceivable/apcore-surfaces/tree/main/mcp) - Expose these modules as an MCP Server. +- [apcore-a2a](https://github.com/aiperceivable/apcore-surfaces/tree/main/a2a) - Expose these modules as an A2A Agent. +- [apcore-cli](https://github.com/aiperceivable/apcore-surfaces/tree/main/cli) - Expose these modules as CLI commands. diff --git a/migration/sources.tsv b/migration/sources.tsv new file mode 100644 index 00000000..55b581f9 --- /dev/null +++ b/migration/sources.tsv @@ -0,0 +1,5 @@ +Path Source Imported commit +. https://github.com/aiperceivable/apcore 6530227e5de58f3988810eed38e15f66ecc7ee18 +python https://github.com/aiperceivable/apcore-python 958e79da54ce15907c8eeeb743dcb62e1ee3e3a9 +rust https://github.com/aiperceivable/apcore-rust 3fd2244a4702e5117c48426d2099227a0af09657 +typescript https://github.com/aiperceivable/apcore-typescript 8f94d9e3a653ab4111bc4089a5537ed50d63e0ea diff --git a/python/.code-forge.json b/python/.code-forge.json new file mode 100644 index 00000000..c55af86a --- /dev/null +++ b/python/.code-forge.json @@ -0,0 +1,23 @@ +{ + "_tool": { + "name": "code-forge", + "description": "Transform documentation into actionable development plans with task breakdown and status tracking", + "url": "https://github.com/tercel/code-forge", + "skills_collection": "https://github.com/tercel/claude-code-skills" + }, + "directories": { + "base": "./", + "input": "../apcore/docs/features", + "output": "implementation/" + }, + "git": { + "auto_commit": false, + "commit_state_file": true, + "gitignore_patterns": [] + }, + "execution": { + "default_mode": "ask", + "auto_tdd": true, + "task_granularity": "medium" + } +} diff --git a/python/.forge/feature-manifest.md b/python/.forge/feature-manifest.md new file mode 100644 index 00000000..e81f4ade --- /dev/null +++ b/python/.forge/feature-manifest.md @@ -0,0 +1,291 @@ +# Feature Manifest: apcore-python Protocol Compliance (v0.7.1 → v0.8.0) + +**Generated:** 2026-03-04 +**Project:** apcore-python SDK +**Goal:** Achieve Level 1 full conformance (100%) and Level 2 substantial conformance (≥90%) +**Current State:** Level 1 ~85%, Level 2 ~70% + +--- + +## Dependency Graph + +``` +F01 Config (A12) ─────────┬──→ F02 Timeout (A22) + ├──→ F07 Guard Call Chain (A20) + ├──→ F08 Version Negotiation (A14) + └──→ F09 Safe Hot-Reload (A21) + +F04 ID Normalization (A02) ──→ (standalone) + +F05 Error Code Collision (A17) ──→ (standalone, enhances errors.py) + +F06 ACL Specificity (A10) ──→ F10 ACL Audit Logging + +F11 Retry Middleware ──→ (standalone, uses error.retryable) + +F12 Streaming Deep Merge ──→ (standalone bug fix) + +F03 Conformance Tests ──→ depends on F01, F02, F04, F05, F06, F07 (runs last) +``` + +--- + +## Phase 1: Foundation (No Dependencies) + +### F01: Config System (A12) — MUST, P0 +- **Scope:** Replace `config.py` stub with full YAML loading, env var overrides, validation +- **Files:** `src/apcore/config.py` (rewrite), `tests/test_config.py` (new) +- **Spec:** Algorithm A12 `validate_config()` +- **Estimated Size:** ~250 LOC source + ~400 LOC tests +- **Dependencies:** None (foundation for F02, F07, F08, F09) +- **Blocked by:** Nothing +- **Blocks:** F02, F07, F08, F09 +- **Key Requirements:** + - YAML file loading with `Config.load(path)` + - Environment variable overrides: `APCORE_{SECTION}_{KEY}` prefix + - Merge priority: env vars > config file > defaults + - Schema validation: required fields, type checking, constraint checking + - Dot-path access preserved (backward compatible) + - Hot-reload via `Config.reload()` + - Required fields: `version`, `extensions.root`, `schema.root`, `acl.root`, `acl.default_effect`, `project.name` + - Constraint validation: sampling_rate ∈ [0.0, 1.0], max_depth ∈ [1, 16], etc. + +### F04: Cross-Language ID Normalization (A02) — MUST, P1 +- **Scope:** New utility function for cross-language module ID conversion +- **Files:** `src/apcore/utils/normalize.py` (new), `tests/test_normalize.py` (new) +- **Spec:** Algorithm A02 `normalize_to_canonical_id()` +- **Estimated Size:** ~100 LOC source + ~200 LOC tests +- **Dependencies:** None +- **Blocked by:** Nothing +- **Blocks:** F03 +- **Key Requirements:** + - Input: `(local_id: str, language: str)` where language ∈ {python, rust, go, java, typescript} + - Language-specific separators: Python ".", Rust "::", Go ".", Java ".", TypeScript "." + - Case normalization: PascalCase/camelCase → snake_case + - Acronym handling: `HttpJsonParser` → `http_json_parser` (not `h_t_t_p_...`) + - Output validated against Canonical ID EBNF grammar + - Export from `apcore.__init__` + +### F05: Error Code Collision Detection (A17) — MUST, P1 +- **Scope:** Error code registry with collision detection +- **Files:** `src/apcore/errors.py` (extend), `tests/test_error_codes.py` (new) +- **Spec:** Algorithm A17 `detect_error_code_collisions()` +- **Estimated Size:** ~80 LOC source + ~150 LOC tests +- **Dependencies:** None +- **Blocked by:** Nothing +- **Blocks:** F03 +- **Key Requirements:** + - `ErrorCodeRegistry` class with `register(module_id, codes)` method + - Framework reserved codes: prefixes `MODULE_`, `SCHEMA_`, `ACL_`, `GENERAL_`, `CONFIG_`, `CIRCULAR_`, `DEPENDENCY_` + - Detect: module code collides with framework code → error + - Detect: module code collides with another module's code → error + - Return complete code registry set + - Run at framework startup (integrate with Registry.discover()) + - Thread-safe + +### F06: ACL Specificity Scoring (A10) — SHOULD, P1 +- **Scope:** Pattern specificity calculation for ACL debugging +- **Files:** `src/apcore/utils/pattern.py` (extend), `tests/test_specificity.py` (new) +- **Spec:** Algorithm A10 `calculate_specificity()` +- **Estimated Size:** ~40 LOC source + ~100 LOC tests +- **Dependencies:** None +- **Blocked by:** Nothing +- **Blocks:** F10 +- **Key Requirements:** + - `calculate_specificity(pattern: str) -> int` + - Scoring: `"*"` → 0, exact segment → +2, partial wildcard segment → +1 + - Examples: `"*"` → 0, `"api.*"` → 2, `"api.handler.*"` → 4, `"api.handler.task_submit"` → 6 + - Export from `apcore.__init__` + +### F12: Streaming Deep Merge (Bug Fix) — P0 +- **Scope:** Fix shallow merge in executor streaming accumulation +- **Files:** `src/apcore/executor.py` (fix ~5 lines), `tests/test_executor_stream.py` (extend) +- **Estimated Size:** ~30 LOC source + ~50 LOC tests +- **Dependencies:** None +- **Blocked by:** Nothing +- **Blocks:** Nothing +- **Key Requirements:** + - Replace `{**accumulated, **chunk}` with recursive deep merge + - Nested dicts merged recursively, lists replaced (not concatenated) + - Existing flat streaming behavior unchanged + - New test: overlapping nested keys across chunks + +--- + +## Phase 2: Executor Enhancements (Depend on F01) + +### F02: Timeout Enforcement (A22) — MUST, P0 +- **Scope:** Cooperative cancellation with grace period for sync modules +- **Files:** `src/apcore/executor.py` (refactor timeout section), `tests/test_executor.py` (extend) +- **Spec:** Algorithm A22 `enforce_timeout()` +- **Estimated Size:** ~100 LOC source + ~150 LOC tests +- **Dependencies:** F01 (reads timeout config) +- **Blocked by:** F01 +- **Blocks:** F03 +- **Key Requirements:** + - If timeout_ms == 0: skip timeout enforcement + - Cooperative cancellation: set CancelToken before force-killing + - Grace period: 5 seconds after cancel signal before giving up + - Async path: `asyncio.wait_for()` + cancel token (already partially works) + - Sync path: thread + cancel token signal + join(grace_period) + - Log warning when thread cannot be killed (Python limitation) + - Timing starts from first middleware before() + +### F07: Guard Call Chain (A20) — MUST, P1 +- **Scope:** Extract call chain safety into standalone algorithm +- **Files:** `src/apcore/utils/call_chain.py` (new), `src/apcore/executor.py` (refactor), `tests/test_call_chain.py` (new) +- **Spec:** Algorithm A20 `guard_call_chain()` +- **Estimated Size:** ~80 LOC source + ~120 LOC tests +- **Dependencies:** F01 (reads max_depth, max_repeat config) +- **Blocked by:** F01 +- **Blocks:** F03 +- **Key Requirements:** + - `guard_call_chain(module_id, call_chain, config) -> None` (raises on violation) + - Three checks: depth limit, circular detection, frequency throttling + - Extract from `executor._check_safety()`, keep executor calling the utility + - Configurable via Config: `executor.max_call_depth`, `executor.max_module_repeat` + - Same error types: `CallDepthExceededError`, `CircularCallError`, `CallFrequencyExceededError` + +### F08: Version Negotiation (A14) — MUST, P2 +- **Scope:** Semver compatibility checking between declared and SDK versions +- **Files:** `src/apcore/version.py` (new), `tests/test_version.py` (new) +- **Spec:** Algorithm A14 `negotiate_version()` +- **Estimated Size:** ~80 LOC source + ~150 LOC tests +- **Dependencies:** F01 (reads declared version from config) +- **Blocked by:** F01 +- **Blocks:** F03 +- **Key Requirements:** + - `negotiate_version(declared_version: str, sdk_version: str) -> str` + - Parse semver (major.minor.patch, optional pre-release) + - Major mismatch → `VERSION_INCOMPATIBLE` error + - Declared minor > SDK minor → error (SDK too old) + - Declared minor < SDK minor by >2 → deprecation warning + - Same minor → effective = max(declared, sdk) + - New error class: `VersionIncompatibleError` + - Integrate into Config.load() or Executor initialization + +--- + +## Phase 3: Advanced Features + +### F09: Safe Hot-Reload (A21) — SHOULD, P2 +- **Scope:** Reference-counted safe module unregistration +- **Files:** `src/apcore/registry/registry.py` (extend), `src/apcore/executor.py` (add ref counting), `tests/registry/test_hot_reload.py` (new) +- **Spec:** Algorithm A21 `safe_unregister()` +- **Estimated Size:** ~120 LOC source + ~200 LOC tests +- **Dependencies:** F01 (config for timeout), F07 (executor awareness) +- **Blocked by:** F01 +- **Blocks:** F03 +- **Key Requirements:** + - `Registry.safe_unregister(module_id) -> bool` + - Reference counting: executor increments on call start, decrements on call end + - Mark module state as "UNLOADING" (new calls get MODULE_NOT_FOUND) + - Wait for ref_count == 0 with configurable timeout (default 30s) + - Call `on_unload()` hook after all executions finish + - Idempotent: unregistering non-existent module returns True + - Force-unload on timeout with logging + - Thread-safe with atomic state transitions + +### F10: ACL Audit Logging — P2 +- **Scope:** Structured audit trail for ACL decisions +- **Files:** `src/apcore/acl.py` (extend), `tests/test_acl_audit.py` (new) +- **Estimated Size:** ~80 LOC source + ~100 LOC tests +- **Dependencies:** F06 (includes specificity in audit entries) +- **Blocked by:** F06 +- **Blocks:** Nothing +- **Key Requirements:** + - `AuditEntry` dataclass: timestamp, caller_id, target_id, decision, matched_rule, specificity, context_summary + - `ACL.set_audit_handler(handler)` — pluggable handler protocol + - Default: no-op (zero overhead when not configured) + - Built-in: `InMemoryAuditHandler` for testing, `LoggingAuditHandler` for production + - Every `check()` call produces an audit entry + - Thread-safe + +### F11: Retry Middleware — P2 +- **Scope:** Configurable retry strategy middleware +- **Files:** `src/apcore/middleware/retry.py` (new), `tests/test_retry_middleware.py` (new) +- **Estimated Size:** ~120 LOC source + ~200 LOC tests +- **Dependencies:** None (uses existing middleware + error.retryable) +- **Blocked by:** Nothing +- **Blocks:** Nothing +- **Key Requirements:** + - `RetryMiddleware(max_retries=3, strategy="exponential", base_delay_ms=100, max_delay_ms=10000)` + - Strategies: "exponential" (base * 2^attempt), "fixed" (constant delay), "linear" (base * attempt) + - Only retries if `error.retryable is True` + - Jitter: optional random jitter to prevent thundering herd + - Respects module timeout (total retry time < module timeout) + - Implemented via `on_error()` hook — returns recovery by re-executing + - Configurable per-module overrides via annotations + +--- + +## Phase 4: Validation + +### F03: Cross-Language Conformance Test Suite — P0 +- **Scope:** JSON fixture-based tests validating protocol compliance +- **Files:** `tests/conformance/` (new directory), `tests/conformance/fixtures/` (JSON fixtures) +- **Estimated Size:** ~500 LOC tests + ~300 LOC fixtures +- **Dependencies:** F01, F02, F04, F05, F06, F07 +- **Blocked by:** All Phase 1-2 features +- **Blocks:** Nothing +- **Key Requirements:** + - JSON fixtures define input → expected output for each algorithm + - Fixtures shareable with TypeScript SDK (same JSON, different test runner) + - Coverage sections: + - §2: ID normalization (A01, A02) + - §6: ACL pattern matching (A08), evaluation (A09), specificity (A10) + - §8: Error codes and propagation (A11, A17) + - §9: Config validation (A12) + - §10: Redaction (A13) + - §12: Executor pipeline (10 steps), timeout (A22), call chain (A20) + - §13: Version negotiation (A14) + - Each fixture: `{"algorithm": "A02", "input": {...}, "expected": {...}, "description": "..."}` + - pytest parametrize over fixture files + +--- + +## Implementation Order (Recommended) + +``` +Week 1: Foundation + F12 Streaming Deep Merge (bug fix, 1h) + F06 ACL Specificity (small, 2h) + F05 Error Code Collision (small, 3h) + F04 ID Normalization (medium, 4h) + F01 Config System (large, 8h) + +Week 2: Executor & Protocol + F02 Timeout Enforcement (medium, 6h) + F07 Guard Call Chain (medium, 4h) + F08 Version Negotiation (medium, 4h) + F11 Retry Middleware (medium, 6h) + +Week 3: Advanced + Validation + F10 ACL Audit Logging (medium, 4h) + F09 Safe Hot-Reload (large, 8h) + F03 Conformance Tests (large, 8h) +``` + +--- + +## Version Bump Plan + +After all features complete: +- Version: 0.7.1 → **0.8.0** (minor bump — new features, no breaking changes) +- `Config` API is additive (new class methods, existing `get()` preserved) +- `ACL` API is additive (new `set_audit_handler()`, specificity export) +- `Executor` behavior change: timeout now cooperative (may affect edge cases) +- `errors.py` additive (new `ErrorCodeRegistry`, `VersionIncompatibleError`) +- New public exports: `normalize_to_canonical_id`, `calculate_specificity`, `guard_call_chain`, `negotiate_version`, `ErrorCodeRegistry`, `RetryMiddleware`, `AuditEntry` + +--- + +## Risk Assessment + +| Risk | Impact | Mitigation | +|------|--------|------------| +| Config rewrite breaks existing users | High | Preserve `Config(data=dict)` constructor + `get()` method | +| Timeout change affects sync modules | Medium | Grace period + cooperative cancel before force | +| Ref counting in executor adds overhead | Low | Atomic counter, negligible cost per call | +| New dependencies needed | Low | All features use existing deps (pydantic, pyyaml) | +| Conformance fixtures diverge from TS | Medium | Generate fixtures from spec, not from implementation | diff --git a/python/.githooks/prepare-commit-msg b/python/.githooks/prepare-commit-msg new file mode 100755 index 00000000..a5ec95e9 --- /dev/null +++ b/python/.githooks/prepare-commit-msg @@ -0,0 +1,9 @@ +#!/bin/sh +# Automatically add Signed-off-by line (DCO) if not already present + +SOB=$(git var GIT_COMMITTER_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p') + +if ! grep -qs "^$SOB" "$1"; then + echo "" >> "$1" + echo "$SOB" >> "$1" +fi diff --git a/python/.github/CODEOWNERS b/python/.github/CODEOWNERS new file mode 100644 index 00000000..53a651f4 --- /dev/null +++ b/python/.github/CODEOWNERS @@ -0,0 +1,3 @@ +# all workflow and CODEOWNERS itself modification must be approved by repository owner or core maintainer +.github/workflows/ @tercel +.github/CODEOWNERS @tercel \ No newline at end of file diff --git a/python/.github/copilot-ignore b/python/.github/copilot-ignore new file mode 100644 index 00000000..c0619a02 --- /dev/null +++ b/python/.github/copilot-ignore @@ -0,0 +1,13 @@ +# Environment variables (sensitive data) +.env +.data + +# Secrets +secrets/ +*.pem +*.key + +.claude/ +CLAUDE.md +.cursor/ + diff --git a/python/.github/copilot-instructions.md b/python/.github/copilot-instructions.md new file mode 100644 index 00000000..84ad35a8 --- /dev/null +++ b/python/.github/copilot-instructions.md @@ -0,0 +1,61 @@ +# High-Quality Code Specification – Simplicity, Readability, and Maintainability First + +## Project Overview +The core of `apcore` is **task orchestration and execution specifications**. It provides a unified task orchestration framework that supports execution of multiple task types. + +## Core Principles +- Prioritize **simplicity, readability, and maintainability** above all. +- Avoid premature abstraction, optimization, or over-engineering. +- Code should be understandable in ≤10 seconds; favor straightforward over clever. +- Always follow: Understand → Plan → Implement minimally → Test/Validate → Commit. + +## Python Code Quality + +### Readability +- Use precise, full-word names (standard abbreviations only when conventional). +- Functions ≤50 lines, single responsibility, verb-named. +- Avoid obscure tricks, heavy comprehensions, excessive *args/**kwargs, unnecessary decorators. +- Break complex logic into small, well-named helpers. + +### Types (Mandatory) +- Full type annotations everywhere. +- Avoid `Any` except for dynamic/external data. +- Prefer `dataclass`, `TypedDict`, `Protocol`, `NewType`. + +### Design +- Favor functional style + data classes; minimize inheritance. +- Composition > inheritance; use Protocols/ABCs only for true interfaces. +- No circular imports. +- Dependency injection for config, logging, DB, etc. + +### Errors & Resources +- Explicit exception handling; no bare `except:`. +- Context managers for files/DB/connections. +- Validate/sanitize all public inputs. + +### Logging +- Use `logging.info` for key paths. +- `logging.error` + context for exceptions. +- No `print()` in production/debug code. + +### Testing +- Unit tests in `tests/`, ≥90% coverage on core logic. +- Name: `test__`. +- Never change prod code without/updating tests. + +### Formatting & Linting +- After changes, always run: + - ruff check --fix . + - black . + - pyright . +- Zero errors/warnings before commit. + +### Security & Performance +- Never hardcode secrets; use env/config. +- Validate/sanitize inputs. +- Avoid unjustified quadratic+ complexity in hot paths. + +## General Guidelines +- English ONLY for comments, docstrings, logs, errors, commit messages. +- Fully understand surrounding code before changes. +- Do not generate unnecessary documentation, examples, stubs, or bloated `__init__.py` files unless explicitly requested. \ No newline at end of file diff --git a/python/.gitignore b/python/.gitignore new file mode 100644 index 00000000..86dd69f3 --- /dev/null +++ b/python/.gitignore @@ -0,0 +1,23 @@ +__pycache__/ +*.py[cod] +*.egg-info/ +dist/ +build/ +.eggs/ +.claude/ +.idea/ +.vscode/ +.DS_Store +.ruff_cache/ +.pytest_cache/ +.coverage +.venv/ +venv/ +env/ +.env +docs/issues/ +# Forge planning artifacts (internal only) +.forge/ + +# Spec repo schemas — SSOT is in apcore/schemas/, do not copy +schemas/ diff --git a/python/.gitmessage b/python/.gitmessage new file mode 100644 index 00000000..13607a73 --- /dev/null +++ b/python/.gitmessage @@ -0,0 +1,60 @@ +# (): +# +# +# +#