From f5d9389c803e3172a6a326ae12916b431db817b0 Mon Sep 17 00:00:00 2001 From: blocksifrdev Date: Thu, 16 Apr 2026 20:44:43 -0400 Subject: [PATCH] spec: add GitHub self-governance extension with SCIM-RE authority model --- .github/CODEOWNERS | 17 + .github/workflows/ci.yml | 24 + .github/workflows/ttp-governed-pr-action.yml | 46 + CONTRIBUTING.md | 199 +- README.md | 57 +- SECURITY.md | 117 +- agents/manifests/role-agents.yaml | 141 ++ docs/architecture.md | 12 + docs/ecosystem-integrations.md | 38 + docs/getting-started.md | 61 + ...-self-governance-reference-architecture.md | 311 +++ docs/integration-guide.md | 141 ++ docs/open-source-boundary.md | 47 + docs/operator-guide.md | 56 + docs/public-readiness.md | 36 + docs/repo-access-control.md | 37 + docs/roadmap.md | 51 + docs/scim-re-github-role-agent-mapping.md | 21 + docs/security.md | 15 + examples/github-app-self-governance.md | 18 + policy/github-self-governance-policy.yaml | 29 + .../trust-authority/jest.config.cjs | 6 + .../trust-authority/package.json | 2 + .../trust-authority/src/aggregation.test.ts | 56 + .../trust-authority/src/crypto.ts | 2 +- .../trust-authority/src/index.ts | 2 +- .../trust-authority/src/routes.ts | 56 + .../src/scripts/generate-keys.ts | 2 +- .../trust-authority/src/store.ts | 15 + .../trust-authority/tsconfig.json | 4 +- ...0001-github-self-governance-role-agents.md | 17 + runtime/api/re-authorize.contract.md | 56 + .../execution-receipt-v2.schema.json | 117 + ttp-language | 1991 ++--------------- ttp-language.md | 1960 +--------------- 35 files changed, 1861 insertions(+), 3899 deletions(-) create mode 100644 .github/CODEOWNERS create mode 100644 .github/workflows/ci.yml create mode 100644 .github/workflows/ttp-governed-pr-action.yml create mode 100644 agents/manifests/role-agents.yaml create mode 100644 docs/ecosystem-integrations.md create mode 100644 docs/getting-started.md create mode 100644 docs/github-self-governance-reference-architecture.md create mode 100644 docs/open-source-boundary.md create mode 100644 docs/operator-guide.md create mode 100644 docs/public-readiness.md create mode 100644 docs/repo-access-control.md create mode 100644 docs/roadmap.md create mode 100644 docs/scim-re-github-role-agent-mapping.md create mode 100644 examples/github-app-self-governance.md create mode 100644 policy/github-self-governance-policy.yaml create mode 100644 reference-implementations/trust-authority/jest.config.cjs create mode 100644 reference-implementations/trust-authority/src/aggregation.test.ts create mode 100644 rfcs/0001-github-self-governance-role-agents.md create mode 100644 runtime/api/re-authorize.contract.md create mode 100644 spec/extensions/execution-receipt-v2.schema.json diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..8742ad1 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1,17 @@ +# Global fallback +* @blocksifr/maintainers + +# Protocol and security-critical artifacts +/protocol/ @blocksifr/protocol-owners @blocksifr/security +/docs/security.md @blocksifr/security +/ttp-language @blocksifr/protocol-owners @blocksifr/security +/ttp-language.md @blocksifr/protocol-owners @blocksifr/security + +# Reference implementation +/reference-implementations/trust-authority/ @blocksifr/runtime-owners @blocksifr/security +/reference-implementations/issuers/ @blocksifr/runtime-owners + +# Governance and release docs +/CONTRIBUTING.md @blocksifr/maintainers +/docs/public-readiness.md @blocksifr/maintainers @blocksifr/security +/docs/open-source-boundary.md @blocksifr/maintainers diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..119b033 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,24 @@ +name: CI + +on: + pull_request: + push: + branches: [ main, work ] + +jobs: + trust-authority: + runs-on: ubuntu-latest + defaults: + run: + working-directory: reference-implementations/trust-authority + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 20 + - name: Install dependencies + run: npm install --no-audit --no-fund + - name: Build + run: npm run build + - name: Test + run: npm test diff --git a/.github/workflows/ttp-governed-pr-action.yml b/.github/workflows/ttp-governed-pr-action.yml new file mode 100644 index 0000000..c5ffc3e --- /dev/null +++ b/.github/workflows/ttp-governed-pr-action.yml @@ -0,0 +1,46 @@ +name: TTP Governed PR Action (Skeleton) + +on: + issue_comment: + types: [created] + +jobs: + governed-action: + if: contains(github.event.comment.body, '/ttp') + runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: write + issues: write + steps: + - uses: actions/checkout@v4 + + - name: Build /re/authorize request context + run: | + echo '{"todo":"collect action, paths, actor, branch, run id"}' > request.json + + - name: Runtime Authority Gate + env: + RUNTIME_AUTH_URL: ${{ secrets.RUNTIME_AUTH_URL }} + RUNTIME_AUTH_TOKEN: ${{ secrets.RUNTIME_AUTH_TOKEN }} + run: | + curl -sS -X POST "$RUNTIME_AUTH_URL/re/authorize" \ + -H "Authorization: Bearer $RUNTIME_AUTH_TOKEN" \ + -H "Content-Type: application/json" \ + -d @request.json > decision.json + cat decision.json + + - name: Enforce decision + run: | + DECISION=$(jq -r '.decision' decision.json) + case "$DECISION" in + PERMIT) echo "execute allowed action" ;; + CONSTRAIN) echo "execute constrained action" ;; + STEP_UP) echo "request human step-up approval" ; exit 1 ;; + ESCALATE) echo "escalate to maintainers/security owners" ; exit 1 ;; + DENY|*) echo "deny action" ; exit 1 ;; + esac + + - name: Persist receipt reference + run: | + jq -r '.receipt.receipt_id' decision.json diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 5adf249..f7dde7e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,115 +1,150 @@ -Contributing to TTP -Thanks for your interest in contributing to the Trust Transfer Protocol. +# Contributing to TTP -TTP is infrastructure. Clarity, correctness, and interoperability matter more than speed. We prioritize minimalism, security, and real-world usability. +Thanks for your interest in contributing to the Trust Transfer Protocol (TTP). -Ways to Contribute +TTP is security-critical infrastructure. We optimize for **clarity**, **correctness**, and **interoperability** over speed. -1) Specification +--- -Clarifications -Missing edge cases -Attack modeling -Formalization -RFC proposals -2) Implementations +## Role-Based Contribution Paths -Verifier performance -Issuer services -Aggregation strategies -SDK improvements -Tooling + CLI -3) Integrations +You can contribute from different roles in the trust network: -LangChain -CrewAI -LlamaIndex -API gateways -Service meshes -4) Security +### 1) Trust Authority / Network Core Contributors -Threat modeling -Fuzzing -Signature validation hardening -Replay resistance -Adversarial simulations -5) Documentation +Focus areas: +- aggregation correctness and determinism +- key management and signing flows +- admin/operator workflows (registration, quarantine, block, provisioning) +- scalability, persistence, and reliability hardening -Examples -Tutorials -Deployment guides -Architecture diagrams -Getting Started +### 2) Issuer Contributors -Fork the repo -Create a branch: -Make focused changes -Open a PR with: -context -rationale -tradeoffs -Development Principles +Focus areas: +- issuer adapters (API gateways, runtime monitors, network telemetry) +- receipt quality and event taxonomy +- signature integrity and replay resistance +- independent issuer deployment patterns -Minimal core Avoid unnecessary abstraction or scope creep. +### 3) Verifier / Service Contributors -Interoperability first Multiple independent implementations must be possible. +Focus areas: +- middleware and policy adapters +- low-latency token verification +- fallback behavior by risk tier +- action-level enforcement patterns -Security over convenience Assume adversarial environments. +### 4) Agent / SDK Contributors -Stateless preference Verification should not require persistent trust state. +Focus areas: +- token lifecycle UX (cache, refresh, expiry handling) +- framework integrations (agent runtimes, orchestration platforms) +- typed SDK ergonomics and docs +- secure defaults for application developers -Transport agnostic HTTP is primary, but not required. +### 5) Security Contributors -Spec Changes +Focus areas: +- threat modeling and adversarial scenarios +- fuzzing and malformed input handling +- signature validation hardening +- trust-manipulation and collusion resilience + +### 6) Documentation & Adoption Contributors + +Focus areas: +- quickstarts and tutorials +- operator runbooks +- architecture diagrams and reference deployments +- migration and interoperability guides + +--- + +## Getting Started + +1. Fork the repository. +2. Create a focused branch. +3. Make atomic changes. +4. Run relevant checks/tests. +5. Open a PR with: + - context/problem statement + - rationale and tradeoffs + - test/validation notes + +--- + +## Development Principles + +- **Minimal core:** avoid unnecessary abstraction and scope creep. +- **Interoperability first:** multiple independent implementations must remain possible. +- **Security over convenience:** assume adversarial environments. +- **Stateless preference:** verification should not require persistent trust state. +- **Deterministic behavior:** trust decisions should be explainable and reproducible. + +--- + +## Spec Changes (RFC Process) For protocol-level changes: -Open an issue labeled rfc -Propose: -problem -proposed change -alternatives -compatibility impact -Discussion with maintainers -Merge only after consensus -Pull Request Guidelines +1. Open an issue labeled `rfc`. +2. Propose: + - problem statement + - proposed change + - alternatives considered + - compatibility impact +3. Discuss with maintainers/community. +4. Merge only after consensus. + +--- + +## Pull Request Guidelines PRs should: +- be scoped and atomic +- include tests when applicable +- avoid unrelated refactors +- document behavioral or API changes + +--- -be scoped and atomic -include tests when applicable -avoid unrelated refactors -document behavioral changes -Code Standards +## Code Standards -Explicit > implicit -Readability > cleverness -Deterministic behavior -Clear error handling -Secure defaults -Good First Contributions +- Explicit > implicit +- Readability > cleverness +- Secure defaults +- Clear error handling +- Backward compatibility awareness -Look for: +--- -good first issue -documentation -sdk -examples -These are intentionally scoped for quick onboarding. +## Good First Contributions -Reporting Security Issues +Look for issues labeled: +- `good first issue` +- `documentation` +- `sdk` +- `examples` -Do NOT open public issues for vulnerabilities. +These are intentionally scoped for faster onboarding. -Email maintainers directly with: +--- + +## Reporting Security Issues + +Do **not** open public issues for vulnerabilities. + +Report privately to maintainers with: +- reproduction steps +- impact assessment +- mitigation ideas (if available) -reproduction steps -impact -proposed mitigation (if known) We will coordinate responsible disclosure. -Community Expectations +--- + +## Community Expectations Be constructive. Challenge ideas, not people. Bias toward collaboration. -We are building infrastructure others will depend on. \ No newline at end of file +We are building infrastructure others will depend on. diff --git a/README.md b/README.md index a072283..16dc3d3 100644 --- a/README.md +++ b/README.md @@ -362,6 +362,39 @@ app.post("/api/issue-discount", async (req, res) => { ----- +## Start Here (Docs Split by Audience) + +To keep this README concise, onboarding and operations are split into focused guides: + +- **Getting Started:** [docs/getting-started.md](docs/getting-started.md) + - quickstart path + - role-based integration paths + - core-to-edge participation model + - identity assurance checklist +- **Operator Guide:** [docs/operator-guide.md](docs/operator-guide.md) + - agent registry operations + - admin API examples + - status / quarantine / block workflows + - registry metrics usage +- **Ecosystem Integrations:** [docs/ecosystem-integrations.md](docs/ecosystem-integrations.md) + - AGT-native integration patterns (OPA/Rego, SPIFFE, score mapping, AgentMesh) + - network security integration patterns (Zscaler/Palo Alto/Juniper) +- **Roadmap & Collaboration Model:** [docs/roadmap.md](docs/roadmap.md) + - role lanes for scaling adoption quickly + - stewardship and commercialization decision framework +- **Public Launch Checklist:** [docs/public-readiness.md](docs/public-readiness.md) + - release gates for docs, security, CI, and operations +- **Open-Source Boundary:** [docs/open-source-boundary.md](docs/open-source-boundary.md) + - keeps protocol/interoperability public while premium ops stay external +- **Repo Access Controls:** [docs/repo-access-control.md](docs/repo-access-control.md) + - safe collaborator permissions and branch/release protection model +- **GitHub Self-Governance (TTP governing TTP):** [docs/github-self-governance-reference-architecture.md](docs/github-self-governance-reference-architecture.md) + - runtime authority gate, SCIM-RE mapping, protected actions, receipts + +For end-to-end implementation details, use [docs/integration-guide.md](docs/integration-guide.md). + +----- + ## Where TTP Fits |System |Role |Relationship to TTP | @@ -371,6 +404,7 @@ app.post("/api/issue-discount", async (req, res) => { |API Gateway |Routing & rate limit |Integration point — gateway acts as an issuer | |Service Mesh |Connectivity (mTLS) |Complementary — mesh verifies identity, TTP verifies behavior | |SPIFFE / SPIRE |Workload identity |Complementary — SPIFFE issues SVIDs, TTP adds behavioral layer on top | +|Network Security Platforms (Zscaler, Palo Alto, Juniper) |Network/session controls|Complementary — network controls enforce transport/session policy; TTP enforces behavior-aware action trust | |ZTNA |Network access |Complementary — ZTNA controls the network, TTP controls the action | |AI Agent Frameworks | Execution |Integration point — LangChain, CrewAI agents become TTP-aware | @@ -583,7 +617,15 @@ ttp-protocol/ │ ├── security.md │ ├── governance.md │ ├── patent-strategy.md -│ └── integration-guide.md +│ ├── roadmap.md +│ ├── public-readiness.md +│ ├── open-source-boundary.md +│ ├── repo-access-control.md +│ ├── github-self-governance-reference-architecture.md +│ ├── integration-guide.md +│ ├── getting-started.md +│ ├── operator-guide.md +│ └── ecosystem-integrations.md ├── reference-implementations/ │ ├── trust-authority/ │ ├── issuers/ @@ -686,11 +728,12 @@ Contributions welcome. Areas of interest: -- SDK implementations -- Issuer integrations -- Security analysis -- Performance optimization -- Documentation +- Trust Authority / network core operations +- Issuer integrations and adapters +- Verifier enforcement patterns +- Agent SDK/runtime integrations +- Security analysis and threat modeling +- Documentation and onboarding See for guidelines. @@ -826,4 +869,4 @@ Defining the infrastructure layer for trustworthy autonomous systems. ----- -*Building the trust layer for autonomous systems.* \ No newline at end of file +*Building the trust layer for autonomous systems.* diff --git a/SECURITY.md b/SECURITY.md index 6f438b9..2c5d717 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -1,88 +1,61 @@ # Security Policy -TTP is security-critical infrastructure, and I take its security seriously. +This repository contains security-sensitive trust protocol and reference implementation code. -If you discover a vulnerability or weakness, please reach out directly. -Responsible disclosure and external review are welcome and appreciated. +## Supported Scope ---- +Security reports are accepted for: +- protocol semantics and verification logic +- reference Trust Authority, issuer, and verifier code +- cryptographic handling, token validation, and replay protections +- admin/authz controls in reference APIs -## Reporting Vulnerabilities +## Reporting a Vulnerability -Please report suspected vulnerabilities privately via email: +Please **do not** open public GitHub issues for vulnerabilities. -maurice@blocksifr.com +Report privately to: **maurice@blocksifr.com** -Include where possible: +Include: +1. affected component/path +2. reproduction steps / proof of concept +3. impact and exploit conditions +4. suggested mitigation (if available) -- Description of the issue -- Reproduction steps or proof of concept -- Affected components or versions -- Potential impact or exploitation scenario +We aim to acknowledge reports within 48 hours. -Please do not open public issues for security vulnerabilities. +## Repository Access Controls (Pre-Public Invite) ---- +Before inviting external users/collaborators: -## Scope +1. Enforce least privilege: + - default role: Read + - Write/Maintain only for trusted maintainers + - Admin restricted to core owners +2. Require branch protection on default branch: + - PR required (no direct pushes) + - required review approvals + - required status checks + - dismiss stale approvals on new commits +3. Require CODEOWNERS review for protocol/security-critical paths. +4. Require 2FA for org members and outside collaborators. +5. Protect secrets: + - enable secret scanning + push protection + - no long-lived credentials in repo + - rotate keys on any suspicion of exposure +6. Protect release integrity: + - tag protection + - signed release artifacts where possible -Security-sensitive areas include, but are not limited to: +## Safe External Collaboration Model -- Trust token validation -- Cryptographic signature handling -- Aggregation logic integrity -- Receipt replay protection -- Issuer trust and federation assumptions -- SDK token lifecycle handling -- Verifier policy enforcement boundaries +- Use issue templates and scoped labels for newcomer tasks. +- Keep security-sensitive discussions private until patched. +- Prefer small, auditable PRs for protocol or authz changes. +- Require explicit security review for changes touching trust semantics. -Out-of-scope items may include feature requests or documentation issues unless they introduce security risk. +## Additional References ---- - -## Response Process - -I aim to: - -- Acknowledge reports within 48 hours -- Assess severity and impact -- Coordinate responsible disclosure -- Release fixes or mitigations promptly -- Credit reporters when appropriate - -Timelines may vary depending on complexity and ecosystem impact. - ---- - -## Disclosure Philosophy - -TTP follows coordinated disclosure practices prioritizing ecosystem safety and transparency. - -External review, critique, and academic analysis are encouraged. -Security findings are viewed as contributions to the protocol’s maturity. - ---- - -## Security Design Principles - -TTP development is guided by: - -- Minimize state -- Minimize credential lifetime -- Cryptographic verification of assertions -- Explicit trust boundaries -- Defense in depth -- Adversarial mindset by default - -No system is assumed secure by design alone — scrutiny and iteration are expected. - ---- - -## Safe Harbor - -Good-faith research conducted responsibly and ethically is supported. -Researchers acting without malicious intent and avoiding harm will not face punitive action for disclosure. - ---- - -Thank you for helping strengthen the security posture of the TTP ecosystem. \ No newline at end of file +- Security model: `docs/security.md` +- Public release checklist: `docs/public-readiness.md` +- Repo access model: `docs/repo-access-control.md` diff --git a/agents/manifests/role-agents.yaml b/agents/manifests/role-agents.yaml new file mode 100644 index 0000000..bcb4533 --- /dev/null +++ b/agents/manifests/role-agents.yaml @@ -0,0 +1,141 @@ +version: 1 +agents: + - name: Protocol Editor Agent + workload_identity: wi://ttp/github/protocol-editor + purpose: Maintain protocol core text and schemas. + allowed_actions: [issue.comment, pull_request.review, merge recommendation, policy modification request] + forbidden_actions: [release tag request, protected merge approval request] + allowed_paths: [protocol/**, spec/**, rfcs/**] + protected_actions_requiring_step_up: [receipt schema modification request, policy modification request] + minimum_trust_score: 0.90 + freshness_s: 600 + risk_tier: high + compliance_implications: [integrity-control, change-management] + cost_profile: standard + receipt_requirements: [authority_basis, trust_context, risk_posture, compliance_posture, cost_posture, chain_hash] + + - name: Spec & RFC Maintainer Agent + workload_identity: wi://ttp/github/spec-rfc-maintainer + purpose: Curate RFC lifecycle and spec consistency. + allowed_actions: [issue.comment, pull_request.review, label.apply] + forbidden_actions: [workflow modification request, release tag request] + allowed_paths: [rfcs/**, protocol/**, docs/**] + protected_actions_requiring_step_up: [merge to main] + minimum_trust_score: 0.85 + freshness_s: 900 + risk_tier: medium + compliance_implications: [review-evidence] + cost_profile: light + receipt_requirements: [authority_basis, trust_context, github_context] + + - name: Rust Compiler Agent + workload_identity: wi://ttp/github/rust-compiler + purpose: Build/compiler integration and CI runtime checks. + allowed_actions: [workflow.dispatch, issue.comment, pull_request.review] + forbidden_actions: [policy modification request, receipt schema modification request] + allowed_paths: [compiler/**, .github/workflows/**] + protected_actions_requiring_step_up: [workflow modification request] + minimum_trust_score: 0.88 + freshness_s: 300 + risk_tier: high + compliance_implications: [build-integrity] + cost_profile: standard + receipt_requirements: [risk_posture, cost_posture, chain_hash] + + - name: Runtime Systems Agent + workload_identity: wi://ttp/github/runtime-systems + purpose: Maintain runtime authority and verifier paths. + allowed_actions: [pull_request.review, issue.comment, workflow.dispatch] + forbidden_actions: [release tag request] + allowed_paths: [runtime/**, reference-implementations/**] + protected_actions_requiring_step_up: [edits to core runtime authorization behavior, merge to main] + minimum_trust_score: 0.92 + freshness_s: 300 + risk_tier: critical + compliance_implications: [runtime-control, security-review] + cost_profile: heavy + receipt_requirements: [authority_basis, approval_chain, risk_posture, compliance_posture, chain_hash, signature] + + - name: ZK / Proof Systems Agent + workload_identity: wi://ttp/github/zk-proof-systems + purpose: Maintain proof-related semantics and references. + allowed_actions: [issue.comment, pull_request.review] + forbidden_actions: [workflow modification request, release tag request] + allowed_paths: [spec/**, docs/**] + protected_actions_requiring_step_up: [merge to main] + minimum_trust_score: 0.87 + freshness_s: 1200 + risk_tier: medium + compliance_implications: [evidence-quality] + cost_profile: standard + receipt_requirements: [trust_context, risk_posture, github_context] + + - name: Identity / SCIM-RE Architect Agent + workload_identity: wi://ttp/github/scim-re-architect + purpose: Maintain identity and authority-plane mappings. + allowed_actions: [pull_request.review, issue.comment, policy modification request] + forbidden_actions: [release tag request] + allowed_paths: [docs/**, policy/**, spec/**] + protected_actions_requiring_step_up: [policy modification request, receipt schema modification request] + minimum_trust_score: 0.91 + freshness_s: 600 + risk_tier: high + compliance_implications: [identity-governance] + cost_profile: standard + receipt_requirements: [authority_basis, compliance_posture, approval_chain] + + - name: Security Research Agent + workload_identity: wi://ttp/github/security-research + purpose: Analyze threats, controls, and verification logic. + allowed_actions: [issue.comment, pull_request.review, label.apply] + forbidden_actions: [merge to main, release tag request] + allowed_paths: [docs/security.md, protocol/**, reference-implementations/**] + protected_actions_requiring_step_up: [edits to signing, key, or verification paths] + minimum_trust_score: 0.93 + freshness_s: 300 + risk_tier: critical + compliance_implications: [security-review, evidence-retention] + cost_profile: heavy + receipt_requirements: [risk_posture, compliance_posture, chain_hash, signature] + + - name: Agent Framework Integration Agent + workload_identity: wi://ttp/github/framework-integration + purpose: Integrate TTP with agent frameworks and callbacks. + allowed_actions: [issue.comment, pull_request.review, workflow.dispatch] + forbidden_actions: [policy modification request, receipt schema modification request] + allowed_paths: [sdk/**, examples/**, docs/**] + protected_actions_requiring_step_up: [workflow modification request] + minimum_trust_score: 0.84 + freshness_s: 900 + risk_tier: medium + compliance_implications: [integration-evidence] + cost_profile: standard + receipt_requirements: [trust_context, risk_posture, github_context] + + - name: Docs / DX Agent + workload_identity: wi://ttp/github/docs-dx + purpose: Maintain docs quality and contributor experience. + allowed_actions: [issue.comment, pull_request.review, label.apply] + forbidden_actions: [workflow modification request, merge to main, release tag request] + allowed_paths: [docs/**, README.md, CONTRIBUTING.md] + protected_actions_requiring_step_up: [merge recommendation for protected paths] + minimum_trust_score: 0.80 + freshness_s: 1800 + risk_tier: low + compliance_implications: [change-traceability] + cost_profile: light + receipt_requirements: [authority_basis, github_context] + + - name: Standards / Ecosystem Agent + workload_identity: wi://ttp/github/standards-ecosystem + purpose: Coordinate standards-track and ecosystem alignment. + allowed_actions: [issue.comment, pull_request.review, label.apply, merge recommendation] + forbidden_actions: [release tag request] + allowed_paths: [rfcs/**, docs/**, protocol/**] + protected_actions_requiring_step_up: [merge to main, policy modification request] + minimum_trust_score: 0.89 + freshness_s: 1200 + risk_tier: high + compliance_implications: [governance-evidence] + cost_profile: standard + receipt_requirements: [authority_basis, approval_chain, risk_posture, compliance_posture] diff --git a/docs/architecture.md b/docs/architecture.md index 726edfc..17a0d36 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -255,6 +255,18 @@ See [examples/service-integration](../examples/service-integration/) for Kong an --- +## 10. GitHub Self-Governance Extension (TTP Governing TTP) + +TTP can be applied to its own repository operations by treating AI role-agents as governed workload identities and routing meaningful GitHub actions through a Runtime Authority Gate (`POST /re/authorize`) before execution. + +Reference materials: +- [GitHub Self-Governance Reference Architecture](github-self-governance-reference-architecture.md) +- [SCIM-RE Mapping Appendix](scim-re-github-role-agent-mapping.md) +- [ExecutionReceipt schema extension](../spec/extensions/execution-receipt-v2.schema.json) +- [Role-agent manifests](../agents/manifests/role-agents.yaml) + +--- + ## Performance Considerations ### Token Verification Latency diff --git a/docs/ecosystem-integrations.md b/docs/ecosystem-integrations.md new file mode 100644 index 0000000..e73b9e7 --- /dev/null +++ b/docs/ecosystem-integrations.md @@ -0,0 +1,38 @@ +# TTP Ecosystem Integrations + +This document summarizes integration patterns with AGT-style policy systems and network-security platforms. + +## AGT-Native Integration + +Use TTP as the behavioral evidence layer in a closed loop: + +1. AGT enforces pre-execution policy. +2. Issuers submit post-execution receipts. +3. Trust Authority recomputes trust. +4. AGT adjusts permissions using updated trust evidence. + +Key patterns: +- OPA/Rego bridge (`input.ttp` claims) +- SPIFFE/SVID identity compatibility +- Canonical score adapter: `agt_trust_score = round(ttp_score * 1000)` +- AgentMesh trust attestation bridge + +See full details in [integration-guide.md#part-6-agt-native-integration-recommended-priority](integration-guide.md#part-6-agt-native-integration-recommended-priority). + +--- + +## Network Security Integrations (Zscaler / Palo Alto / Juniper) + +Possible today through issuer adapters: + +1. Collect network/session telemetry. +2. Map events to signed TTP receipts. +3. Aggregate with other issuers. +4. Enforce trust tokens at app/action boundaries. + +Notes: +- Treat network evidence as one issuer class among multiple sources. +- Keep action-level verification at the service boundary. +- Use domain isolation for contextual trust decisions. + +See full details in [integration-guide.md#part-7-network-security-platform-integrations-zscaler--palo-alto--juniper](integration-guide.md#part-7-network-security-platform-integrations-zscaler--palo-alto--juniper). diff --git a/docs/getting-started.md b/docs/getting-started.md new file mode 100644 index 0000000..4fa1608 --- /dev/null +++ b/docs/getting-started.md @@ -0,0 +1,61 @@ +# TTP Getting Started + +This guide gives a fast path from zero to first protected action, then helps teams choose the right adoption path. + +## Quickstart (Simple Path) + +1. Run the Trust Authority using the reference implementation. +2. Register one agent and one issuer via admin endpoints. +3. Submit receipts from the issuer as agent actions occur. +4. Request a trust token from the agent. +5. Verify the token in your service and enforce `minScore`. + +Use full commands and setup details in [integration-guide.md](integration-guide.md). + +--- + +## Integration Paths (Choose One) + +### Path A — Agent Builder +- Integrate `TTPClient` in agent runtime. +- Request short-lived, domain-scoped trust tokens. +- Pass `X-TTP-Token` to protected downstream services. + +### Path B — Service/API Owner +- Add TTP middleware or manual verification. +- Configure per-route `domain` and `minScore`. +- Choose risk-appropriate fallback strategy. + +### Path C — Platform/Security Operator +- Operate Trust Authority and issuer registry. +- Register agents and issuers. +- Manage trust thresholds, domain boundaries, and quarantine policy. + +--- + +## Build the Network (Core -> Edge Participation) + +Teams can adopt incrementally: + +1. **Network Core Operator** — runs Trust Authority and governance. +2. **Issuer Operator** — submits signed behavioral evidence. +3. **Verifier / Service Owner** — enforces trust at action boundaries. +4. **Agent Builder** — makes agents token-aware. + +Suggested starts: +- Enterprise platform teams: Core + Verifier +- Security vendors: Issuer + Verifier +- Agent framework teams: Agent Builder + Issuer +- Product teams: Verifier first, then issuer coverage + +--- + +## Identity Assurance (Cover All Bases) + +Identity assurance should span: +- **Methodology**: canonical identity source + lifecycle states. +- **Workflow**: registration, verification gates, response playbooks. +- **Code**: normalization, unknown principal rejection, replay/clock controls. +- **Reasoning**: deterministic policy decisions with explicit threshold rationale. + +Use the full checklist in [integration-guide.md#67-identity-gap-closure-checklist-methodology-workflow-code-reasoning](integration-guide.md#67-identity-gap-closure-checklist-methodology-workflow-code-reasoning). diff --git a/docs/github-self-governance-reference-architecture.md b/docs/github-self-governance-reference-architecture.md new file mode 100644 index 0000000..952e818 --- /dev/null +++ b/docs/github-self-governance-reference-architecture.md @@ -0,0 +1,311 @@ +# TTP GitHub Self-Governance Reference Architecture + +## 1. Executive Summary + +TTP GitHub Self-Governance is a protocol extension that applies **trust-before-execution** to AI role-agents operating in GitHub. + +Every meaningful non-human action is gated by a Runtime Authority Gate (`POST /re/authorize`) before execution. The gate computes authority, trust, risk, compliance, and cost in one runtime decision and emits a signed, chain-hashed `ExecutionReceipt`. + +This document specifies the architecture, decision model, policy patterns, and implementation path for using TTP to govern TTP's own repository. + +## 2. Why This Belongs in TTP + +TTP already solves runtime trust for autonomous actors. GitHub development workflows are high-impact execution surfaces for non-human identities. Governing repository actions with TTP is a natural extension of protocol scope because: + +- identity alone is insufficient for sensitive repo actions, +- policy and trust must be evaluated at execution time, +- governance evidence must be cryptographically auditable. + +This is protocol infrastructure, not bot automation. + +## 3. Protocol Extension: GitHub Self-Governance + +### 3.1 New governed surface + +Governed actions include: +- issue and PR interaction actions, +- workflow dispatch and workflow modifications, +- merge/release recommendations and approvals, +- policy and receipt-model modifications. + +### 3.2 Runtime Authority Gate + +All meaningful actions MUST call: + +`POST /re/authorize` + +Inputs: +- subject workload identity, +- requested action/resource, +- repo context (branch, paths, commit SHA, workflow run id), +- current trust and attestation state, +- active grants and constraints. + +Outputs: +- decision outcome (`PERMIT`, `CONSTRAIN`, `STEP_UP`, `ESCALATE`, `DENY`), +- constraints/step-up requirements, +- signed `ExecutionReceipt`. + +## 4. SCIM-RE Resource Mapping for Role-Agents + +GitHub Self-Governance uses SCIM-RE authority-plane resources without changing provisioning semantics: + +- **WorkloadIdentity**: AI role-agent identity (GitHub App / workflow-bound actor) +- **AuthorityGrant**: time-bounded, trust-conditioned permission envelope +- **Attestation**: freshness/legitimacy proof at action time +- **ExecutionReceipt**: signed decision artifact containing whether action should occur + +Mapping intent: +- provisioning plane remains unchanged, +- authority plane performs runtime authorization and evidence capture. + +## 5. Runtime Decision Model + +Decision tuple: + +``` +Decision = f(authority, trust, risk, compliance, cost, context, constraints) +``` + +### Authority +- subject identity validity +- grant validity window +- action-resource compatibility +- branch/path/environment constraints + +### Trust +- current trust score +- attestation freshness and validity +- decay curve effect +- anomaly penalties + +### Risk +- action criticality +- blast radius +- reversibility +- delegation depth +- protected-path sensitivity + +### Compliance +- implicated controls/framework tags +- evidence mode required +- retention tier required +- human oversight requirement + +### Cost +- execution cost estimate +- review/escalation cost estimate +- evidence generation/storage cost estimate +- avoided-loss estimate +- control overhead category + +### Outcomes +- `PERMIT` +- `CONSTRAIN` +- `STEP_UP` +- `ESCALATE` +- `DENY` + +Fail closed on missing/ambiguous signals. + +## 6. Risk Framework + +Risk classes: + +- **Low**: comments/labels/reviews without protected-path effect +- **Medium**: workflow dispatch, merge recommendations, non-protected automation changes +- **High**: policy modifications, workflow file edits, receipt model updates +- **Critical**: merge to main, release tags, core runtime authorization/key path changes + +Risk calculation factors: +- action criticality +- blast radius +- reversibility +- delegation chain depth +- anomaly score +- protected file/path impact + +## 7. Compliance Framework + +Compliance is evaluated in decision-time, not post-processing. + +Per-action compliance attributes: +- framework tags (SOC2/ISO27001/internal-control-map) +- control IDs touched +- evidence mode (`required`, `enhanced`, `forensic`) +- retention tier (`standard`, `elevated`, `long_term`) +- human oversight requirement (`none`, `single`, `dual`) + +If required compliance controls cannot be satisfied, decision MUST be `ESCALATE` or `DENY`. + +## 8. Cost Framework + +Cost dimensions at authorization time: +- execution compute/tooling cost +- human review cost (step-up/escalation) +- evidence capture/storage cost +- estimated avoided-loss value +- control overhead class (`light`, `standard`, `heavy`) + +Cost does not override hard security/compliance denials. It only informs constrain/escalate policy. + +## 9. ExecutionReceipt Extension + +Extended receipt fields include: +- identity + trust context +- authority grant basis + policy basis +- risk posture snapshot +- compliance posture snapshot +- cost snapshot +- approval/escalation chain +- signature + chain hash +- GitHub context: repo, branch, paths touched, workflow run id, commit SHA, invoking actor + +Reference schema extension: `spec/extensions/execution-receipt-v2.schema.json`. + +## 10. GitHub Integration Architecture + +### 10.1 Components +- GitHub App (repo-facing execution identity) +- GitHub Actions workers (constrained executors) +- Runtime Authority service (`/re/authorize`) +- Receipt signer/store +- Trust Authority scorer + +### 10.2 Control flow +1. Slash command / workflow trigger requests action. +2. Worker assembles authorization request context. +3. Worker calls `POST /re/authorize`. +4. Authority returns outcome + constraints + receipt. +5. Worker enforces result: + - execute permitted action, + - constrain scope, + - request step-up, + - escalate to human approver, + - deny. +6. Receipt is persisted and chain-linked. + +### 10.3 Guardrails +- agent reasoning is not authority, +- workflows have no standing power, +- authority is short-lived and action-scoped. + +## 11. Agent Role Manifests + +Source of truth: `agents/manifests/role-agents.yaml`. + +The ten role-agents modeled: +1. Protocol Editor Agent +2. Spec & RFC Maintainer Agent +3. Rust Compiler Agent +4. Runtime Systems Agent +5. ZK / Proof Systems Agent +6. Identity / SCIM-RE Architect Agent +7. Security Research Agent +8. Agent Framework Integration Agent +9. Docs / DX Agent +10. Standards / Ecosystem Agent + +Each manifest defines purpose, workload identity, allowed/forbidden actions, path scope, protected actions, trust threshold, freshness, risk tier, compliance implications, cost profile, and receipt requirements. + +## 12. Protected Actions and Step-Up Policy + +Protected actions requiring `STEP_UP` or `ESCALATE`: +- merge to `main` +- release tags +- edits to `.github/workflows/**` +- edits to `policy/**` +- edits to trust model semantics +- edits to receipt schema +- edits to signing/key/verification paths +- edits to core runtime authorization behavior + +Policy source: `policy/github-self-governance-policy.yaml`. + +## 13. Repo Structure + +Proposed self-governance layout: + +``` +.github/workflows/ +agents/ +policy/ +receipts/ +rfcs/ +spec/ +runtime/ +compiler/ +docs/ +examples/ +``` + +This repository adds initial seeds for: +- `agents/manifests/` +- `policy/` +- `runtime/api/` +- `rfcs/` +- `spec/extensions/` + +## 14. Example API Contracts + +Normative example contracts are in: +- `runtime/api/re-authorize.contract.md` + +Includes request/response schema and outcome mapping. + +## 15. Example Workflow Skeletons + +Reference workflow: +- `.github/workflows/ttp-governed-pr-action.yml` + +Pattern: +1. collect action context, +2. call Runtime Authority, +3. enforce outcome, +4. upload/store receipt metadata. + +## 16. Phased Implementation Plan + +### Phase 1 +- advisory agents only +- comments/reviews/labels +- no merge authority + +### Phase 2 +- scoped workflow dispatch +- trust decay + attestation checks +- constrained execution mode + +### Phase 3 +- protected action step-up +- merge/release gating +- receipt-backed approvals + +### Phase 4 +- public reference implementation +- repository self-governed with TTP policy plane + +## 17. Maintainer / Ecosystem Value + +Maintainers gain: +- deterministic runtime governance for non-human actions, +- auditable execution evidence, +- reduced ambiguity in sensitive repo operations. + +Ecosystem gains: +- concrete reference model for CI/CD governance, +- reusable authority-plane patterns for machine identities, +- practical bridge between protocol semantics and operational tooling. + +## 18. Commercial Wedge and Revenue Logic + +This is a governance infrastructure wedge, not a bot feature. + +Value path: +- starter self-hosted governance, +- enterprise governance controls, +- managed authority service, +- compliance/evidence modules, +- advisory and implementation services. + +Commercial offerings remain optional and non-normative; core protocol semantics and interoperability remain open. diff --git a/docs/integration-guide.md b/docs/integration-guide.md index e175d49..4a11ffb 100644 --- a/docs/integration-guide.md +++ b/docs/integration-guide.md @@ -345,6 +345,147 @@ createTTPMiddleware({ Choose `deny` for high-stakes operations. Choose `cached` when availability is critical and short windows of stale trust are acceptable. + +--- + +## Part 6: AGT-Native Integration (Recommended Priority) + +If you are integrating with Microsoft AGT-style runtime controls, position TTP as the **behavioral evidence layer** in AGT's trust chain. + +### 6.1 Closed-Loop Trust Control + +Recommended control loop: +1. **AGT enforces pre-execution policy** (prevent unsafe actions before execution). +2. **TTP issuers observe post-execution behavior** and submit signed receipts. +3. **Trust Authority recomputes behavioral trust** and issues updated trust tokens. +4. **AGT consumes updated trust evidence** and adjusts future permissions. + +This gives you deterministic policy enforcement with continuously refreshed behavioral evidence. + +### 6.2 OPA/Rego Bridge (Tier 1) + +Treat TTP token claims as direct OPA inputs so AGT policy decisions can evaluate current behavioral trust. + +```rego +package agt.authz + +# Example: allow high-impact action only for high-behavioral-trust agents +allow { + input.ttp.ttp_domain == "prod-change" + input.ttp.ttp_score >= 0.92 + input.ttp.issuer_count >= 2 +} +``` + +Implementation guidance: +- Parse and verify the TTP token at the policy gateway. +- Expose verified claims under `input.ttp`. +- Keep Rego policies authoritative for allow/deny; use TTP as the runtime evidence feed. + +### 6.3 SPIFFE/SVID Identity Compatibility (Tier 1) + +TTP supports identity-layer composition. In SPIFFE-native deployments, use SPIFFE SVID identities as `agent_id` values (for example, SPIFFE URI subject values). + +Benefits: +- No new identity silo. +- Immediate compatibility with SPIFFE-based workload identity. +- TTP augments SPIFFE identity with behavioral trust. + +### 6.4 Canonical Score Adapter: TTP -> AGT + +When downstream AGT components expect a 0-1000 trust scale, use the canonical mapping: + +```text +agt_trust_score = round(ttp_score * 1000) +``` + +Reference adapter behavior: +- Input: `ttp_score` in `[0.0, 1.0]`. +- Output: integer `agt_trust_score` in `[0, 1000]`. +- Preserve original `ttp_score` in logs/telemetry for auditability. + +### 6.5 AgentMesh / Peer Trust Attestation Bridge + +For inter-agent networks, map TTP peer receipts into AgentMesh trust attestations: +- Use peer attestation receipts as evidence inputs for mesh-level trust decisions. +- Carry receipt identifiers into mesh telemetry for cryptographic traceability. +- Prefer this bridge over standalone demos when integrating with existing AgentMesh gateways. + +### 6.6 Integration Prioritization Notes + +For AGT-centric deployments: +- Prioritize **OPA/Rego bridge**, **SPIFFE compatibility**, **score adapter**, and **AgentMesh bridge**. +- Treat issuer circuit-breakers as operational hardening (useful, but not the core AGT value). +- Avoid parallel privilege models; map TTP scores into existing AGT trust/ring constructs instead. + +### 6.7 Identity Gap Closure Checklist (Methodology, Workflow, Code, Reasoning) + +Use this checklist to close identity gaps across implementation and operations, not just token parsing. + +#### A) Methodology (design-time) +- Define canonical `agent_id` source of truth (SPIFFE ID, workload principal, or managed service identity). +- Define identity lifecycle states (registered, active, quarantined, blocked, decommissioned). +- Define trust-domain boundaries and disallow cross-domain trust reuse by default. +- Define issuer independence requirements and evidence quality standards. + +#### B) Workflow (run-time + operations) +- Registration: require admin approval and immutable identity metadata at enrollment. +- Issuance: only registered issuers can submit receipts for approved domains. +- Verification: enforce token signature, domain, freshness, issuer_count, and minScore in one gate. +- Response: quarantine/block workflows must be documented and exercised (tabletop + drills). + +#### C) Code-level controls +- Normalize identity format before persistence (case, URI form, stable delimiters). +- Reject unknown agents/issuers early with explicit error codes. +- Treat identity claims as untrusted until signature and issuer trust-chain checks pass. +- Log structured identity events (`agent_id`, `issuer_id`, `domain`, `jti`, decision, reason). +- Add replay protections (`jti`) and strict clock-skew boundaries. + +#### D) Reasoning / policy quality +- Separate identity validity from trustworthiness (who the agent is vs. how it behaves). +- Require deterministic allow/deny policies for high-impact actions. +- Explicitly document why a score threshold exists per domain/action class. +- Prefer least-privilege fallbacks under uncertainty (fail closed for critical operations). + +#### E) Minimum acceptance criteria before production +- Identity spoofing tests fail (expected). +- Unregistered issuer submissions fail (expected). +- Quarantined agent receives constrained/denied execution path (expected). +- Policy engine decisions are reproducible from token + policy inputs. +- Operator dashboard can answer: who acted, why allowed/denied, what evidence contributed. + +--- + +## Part 7: Network Security Platform Integrations (Zscaler / Palo Alto / Juniper) + +These integrations are feasible today via issuer adapters, even if you do not run a vendor-specific first-party connector. + +### 7.1 Recommended pattern + +1. Collect policy/session/security telemetry from your network platform. +2. Map events into domain-scoped TTP receipt types (`event_type`, `event_data`, `score`). +3. Sign and submit receipts through an issuer service. +4. Aggregate with other evidence sources (API gateway, runtime, tool execution). +5. Enforce trust tokens at application/action boundaries. + +### 7.2 Example receipt mapping ideas + +- Session policy violation -> negative score receipt (`event_type: "network_policy_violation"`). +- Clean session with expected posture -> positive score receipt (`event_type: "network_session_ok"`). +- Repeated blocked egress attempts -> strongly negative score receipt. + +### 7.3 Scope guidance + +- Keep network evidence as one issuer class among several (avoid single-source trust). +- Do not replace app-level verification with network controls alone. +- Use domain separation (`prod-change`, `financial`, `data-export`) to keep trust decisions contextual. + +### 7.4 Current repo status + +- This repository provides generic issuer and trust authority references. +- Vendor-specific adapters for Zscaler/Palo Alto/Juniper are not yet included as first-party packages. +- Teams can implement adapters on top of `reference-implementations/issuers` patterns. + --- ## Troubleshooting diff --git a/docs/open-source-boundary.md b/docs/open-source-boundary.md new file mode 100644 index 0000000..99ff4ff --- /dev/null +++ b/docs/open-source-boundary.md @@ -0,0 +1,47 @@ +# Open-Source Boundary (Public Release) + +This repository is the **open protocol commons** for TTP. + +## Public Repo Scope (Open Source) + +The public repository includes: + +- protocol specification and schemas +- reference implementations (baseline Trust Authority / issuer / verifier) +- SDK foundations and integration examples +- security model, governance process, and onboarding documentation +- conformance-oriented artifacts and developer tooling + +These assets must remain portable and interoperable across independent implementations. + +--- + +## Out-of-Scope for Public Repo (Commercial/Premium) + +The following are intentionally **not** shipped in this public repository: + +- compliance workflow products (audit automation, managed evidence pipelines) +- enterprise risk/compliance dashboards with paid support entitlements +- premium connectors requiring commercial contracts +- SLA-backed managed operations and incident response services +- paid policy simulation/assurance products tied to enterprise support + +--- + +## Guardrails + +Before each public release, verify: + +1. No proprietary compliance/risk modules are included in repo paths. +2. Public APIs do not require paid entitlements to preserve protocol interoperability. +3. Docs do not imply vendor lock-in for core trust semantics. +4. Premium offering language is described as optional operational add-ons. +5. Security and governance docs remain neutral and implementation-portable. + +--- + +## Decision Rule + +If removing a feature would break interoperability, protocol auditability, or independent implementation viability, it belongs in the open-source repo. + +If a feature's value is primarily operational service depth, managed reliability, or enterprise workflow convenience, it may be offered commercially outside this repo. diff --git a/docs/operator-guide.md b/docs/operator-guide.md new file mode 100644 index 0000000..966ac13 --- /dev/null +++ b/docs/operator-guide.md @@ -0,0 +1,56 @@ +# TTP Operator Guide + +Operator workflows for managing the agent registry and trust-state controls in the reference Trust Authority. + +## Register Agents + +```bash +curl -X POST http://localhost:3000/v1/admin/agents \ + -H "Authorization: Bearer $ADMIN_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "agent_id": "agent-retention-001", + "description": "Retention agent for production" + }' +``` + +## List Agents (Registry) + +```bash +# Basic list +curl -X GET http://localhost:3000/v1/admin/agents \ + -H "Authorization: Bearer $ADMIN_KEY" + +# Include optional receipt metrics (domain-scoped) +curl -X GET "http://localhost:3000/v1/admin/agents?include_metrics=true&domain=retention" \ + -H "Authorization: Bearer $ADMIN_KEY" +``` + +## Check Agent Status + +```bash +curl -X GET http://localhost:3000/v1/admin/agents/agent-retention-001/status \ + -H "Authorization: Bearer $ADMIN_KEY" +``` + +## Quarantine / Block Controls + +```bash +# Quarantine +curl -X POST http://localhost:3000/v1/admin/agents/agent-retention-001/quarantine \ + -H "Authorization: Bearer $ADMIN_KEY" \ + -H "Content-Type: application/json" \ + -d '{"mode":"manual","reason":"investigating anomalous tool calls"}' + +# Block +curl -X POST http://localhost:3000/v1/admin/agents/agent-retention-001/block \ + -H "Authorization: Bearer $ADMIN_KEY" \ + -H "Content-Type: application/json" \ + -d '{"reason":"confirmed compromise"}' +``` + +## Metrics Notes + +- `POST /v1/tokens` returns current trust summary (`score`, `issuer_count`). +- Behavioral receipts provide event-level evidence (`event_type`, `event_data`, `timestamp`, `score`). +- Use trend dashboards for score drift, issuer diversity, and quarantine frequency. diff --git a/docs/public-readiness.md b/docs/public-readiness.md new file mode 100644 index 0000000..1457902 --- /dev/null +++ b/docs/public-readiness.md @@ -0,0 +1,36 @@ +# Public Release Readiness + +Current status: **close, but not done**. + +## Release checklist + +### Engineering +- [x] Trust Authority builds locally. +- [x] CI workflow runs build/test on PRs (`.github/workflows/ci.yml`). +- [x] Baseline aggregation unit tests exist (`src/aggregation.test.ts`). +- [ ] Add smoke tests for key admin/token flows. + +### Documentation +- [x] Onboarding docs are split by audience. +- [x] Integration and security docs are in place. +- [ ] Add a short first-time contributor quickstart issue template. + +### Security and governance +- [x] `SECURITY.md` exists. +- [x] Access-control policy is documented (`docs/repo-access-control.md`). +- [x] CODEOWNERS covers critical paths. +- [ ] Enforce branch protections + required checks in repo settings. + +### Open-source boundary +- [x] Boundary policy is documented (`docs/open-source-boundary.md`). +- [ ] Run a release-time audit to ensure no premium compliance/risk modules are included. +- [ ] Verify product language remains vendor-neutral for core protocol semantics. + +## Before inviting broad public traffic + +1. Expand CI to include docs checks and smoke tests. +2. Turn on required checks + branch protection in GitHub settings. +3. Cut an `rc` tag with changelog and known limitations. +4. Run boundary audit from `docs/open-source-boundary.md`. + +If those are complete, the repo is ready for public release. diff --git a/docs/repo-access-control.md b/docs/repo-access-control.md new file mode 100644 index 0000000..87795df --- /dev/null +++ b/docs/repo-access-control.md @@ -0,0 +1,37 @@ +# Repository Access Controls + +How we invite collaborators safely before full public launch. + +## Roles + +- **Reader**: read-only access. +- **Contributor**: fork + PR workflow, no direct writes. +- **Maintainer**: merge rights with protected-branch workflow. +- **Security owner**: admin-level settings, release integrity, incident response. + +## Required controls + +- Protected default branch (PR required, approvals required, status checks required). +- CODEOWNERS review on critical paths. +- 2FA required for org members/collaborators. +- Secret scanning + push protection. +- Protected release tags. + +## PR handling by risk + +- **Low risk**: docs/examples only -> maintainer review. +- **Medium risk**: SDK/middleware/admin UX -> maintainer + domain owner. +- **High risk**: protocol semantics, crypto, token verification, authz -> mandatory security-owner review. + +## Invite process + +1. Start everyone at read-only. +2. Move trusted contributors to fork+PR. +3. Grant write only after sustained high-quality contributions. +4. Remove elevated access immediately if risk posture changes. + +## Audit cadence + +- Weekly: collaborator/role review. +- Per release: branch protection + CODEOWNERS validation. +- Quarterly: permission and secret-rotation audit. diff --git a/docs/roadmap.md b/docs/roadmap.md new file mode 100644 index 0000000..af23be7 --- /dev/null +++ b/docs/roadmap.md @@ -0,0 +1,51 @@ +# TTP Roadmap + +This roadmap focuses on adoption, trust, and execution speed. + +## What we optimize for + +- Open, portable protocol semantics. +- Fast ecosystem execution across multiple contributor roles. +- Clear separation between open protocol assets and commercial operations. +- Documentation that stays aligned with what is actually implemented. + +## Delivery tracks + +- **Core protocol/runtime**: trust authority behavior, scoring correctness, token semantics. +- **Issuer ecosystem**: real adapters and stronger evidence coverage. +- **Verifier adoption**: policy adapters, middleware, deterministic enforcement defaults. +- **Agent/framework integration**: SDK ergonomics and runtime hooks. +- **Governance/security**: RFC process, conformance checks, threat updates. + +## Phases + +### Now (foundation) +- Stable spec + schemas +- Reference TA/issuer/verifier baseline +- Role-based docs and operator onboarding +- Initial CI and baseline tests + +### Next (ecosystem expansion) +- More issuer adapters (tool/runtime/cloud telemetry) +- More verifier integrations (policy engines/frameworks) +- Conformance coverage and repeatable interop checks +- Better ops metrics and runbooks + +### Later (enterprise + standardization) +- Multi-tenant operational controls +- Compliance/audit workflow maturity +- Institutional standardization track (CNCF and/or IETF) + +## Near-term priorities from assessment + +1. Increase test coverage for verification, authz routes, and failure modes. +2. Ship Python SDK parity for the agent ecosystem. +3. Replace stub issuers with practical adapters. +4. Publish one measurable real-world case study. +5. Add maintainer depth and strengthen external credibility. + +## Public release guardrails + +- Keep protocol-critical semantics and conformance assets public. +- Run open-source boundary audits before each release. +- Keep `ttp-language.md` and security/integration docs synchronized with implementation changes. diff --git a/docs/scim-re-github-role-agent-mapping.md b/docs/scim-re-github-role-agent-mapping.md new file mode 100644 index 0000000..a7a29d0 --- /dev/null +++ b/docs/scim-re-github-role-agent-mapping.md @@ -0,0 +1,21 @@ +# SCIM-RE Mapping Appendix: GitHub Role-Agents + +## Resource mapping + +- WorkloadIdentity -> GitHub role-agent identity (GitHub App subject + role manifest) +- AuthorityGrant -> scoped, time-bounded action permission envelope +- Attestation -> freshness/legitimacy proof bound to invocation context +- ExecutionReceipt -> signed, chain-hashed decision artifact + +## Plane separation + +- Provisioning plane: account/group lifecycle (unchanged) +- Authority plane: runtime decisioning (`/re/authorize`) and receipt generation + +## Outcome mapping + +- `PERMIT` -> authorized action execution +- `CONSTRAIN` -> authorized with reduced scope +- `STEP_UP` -> requires additional human/environment approval +- `ESCALATE` -> routed to higher authority chain +- `DENY` -> blocked and receipted diff --git a/docs/security.md b/docs/security.md index fa4182d..bd02175 100644 --- a/docs/security.md +++ b/docs/security.md @@ -290,6 +290,21 @@ Operators SHOULD implement alerting for: - Token rejections at verifiers (potential compromised agents) - Trust Authority latency spikes (potential availability attack) +### 5.5 Documentation and Semantics Drift + +Operators SHOULD treat documentation drift as a security risk. + +Risk examples: +- verifier policies implemented from outdated claim semantics +- assumptions about endpoints/features that are not part of deployed code +- inconsistent interpretation of trust fields across teams + +Recommended controls: +- use schema + runtime endpoint behavior as source of truth during reviews +- keep `ttp-language.md` synchronized with implemented protocol semantics +- include documentation-accuracy checks in release readiness gates +- require sign-off when claim meanings or admin route behaviors change + --- ## 6. Security Audit Scope diff --git a/examples/github-app-self-governance.md b/examples/github-app-self-governance.md new file mode 100644 index 0000000..cbf3930 --- /dev/null +++ b/examples/github-app-self-governance.md @@ -0,0 +1,18 @@ +# Example: GitHub App + Runtime Authority Integration + +This example shows how a GitHub App invokes Runtime Authority before executing sensitive repository actions. + +## Pattern + +1. GitHub event arrives (issue comment, PR review request, workflow dispatch intent). +2. App/worker resolves role-agent identity and action context. +3. Worker calls `POST /re/authorize`. +4. Authority returns `PERMIT|CONSTRAIN|STEP_UP|ESCALATE|DENY` + receipt. +5. Worker enforces decision and records receipt linkage. + +## Key controls + +- no standing workflow authority +- short-lived grants per action +- step-up for protected actions +- signed, chain-hashed receipts for every meaningful decision diff --git a/policy/github-self-governance-policy.yaml b/policy/github-self-governance-policy.yaml new file mode 100644 index 0000000..f9406ff --- /dev/null +++ b/policy/github-self-governance-policy.yaml @@ -0,0 +1,29 @@ +version: 1 +protected_actions: + - merge to main + - release tag request + - workflow modification request + - policy modification request + - receipt schema modification request + - edits to signing, key, or verification paths + - edits to core runtime authorization behavior + +risk_classes: + low: [issue.comment, pull_request.review, label.apply] + medium: [workflow.dispatch, merge recommendation] + high: [workflow modification request, policy modification request] + critical: [protected merge approval request, release tag request, receipt schema modification request] + +default_decision: DENY + +outcome_rules: + - when: risk == low && trust.score >= 0.8 && authority.valid == true + outcome: PERMIT + - when: risk == medium && trust.score >= 0.85 && compliance.human_oversight in [none,single] + outcome: CONSTRAIN + - when: action in protected_actions && trust.score >= 0.9 && attestation.fresh == true + outcome: STEP_UP + - when: action in protected_actions && (trust.score < 0.9 || compliance.human_oversight == dual) + outcome: ESCALATE + - when: authority.valid == false || attestation.fresh == false || context.ambiguous == true + outcome: DENY diff --git a/reference-implementations/trust-authority/jest.config.cjs b/reference-implementations/trust-authority/jest.config.cjs new file mode 100644 index 0000000..2fa5c72 --- /dev/null +++ b/reference-implementations/trust-authority/jest.config.cjs @@ -0,0 +1,6 @@ +module.exports = { + preset: 'ts-jest', + testEnvironment: 'node', + roots: ['/src'], + testMatch: ['**/*.test.ts'] +} diff --git a/reference-implementations/trust-authority/package.json b/reference-implementations/trust-authority/package.json index 7d31d22..30a3eb3 100644 --- a/reference-implementations/trust-authority/package.json +++ b/reference-implementations/trust-authority/package.json @@ -14,12 +14,14 @@ "dependencies": { "express": "^4.18.2", "@noble/ed25519": "^2.0.0", + "@noble/hashes": "^1.8.0", "jose": "^5.2.0", "uuid": "^9.0.0", "ajv": "^8.12.0" }, "devDependencies": { "@types/express": "^4.17.21", + "@types/jest": "^29.5.14", "@types/uuid": "^9.0.7", "@types/node": "^20.10.0", "typescript": "^5.3.0", diff --git a/reference-implementations/trust-authority/src/aggregation.test.ts b/reference-implementations/trust-authority/src/aggregation.test.ts new file mode 100644 index 0000000..ff86f60 --- /dev/null +++ b/reference-implementations/trust-authority/src/aggregation.test.ts @@ -0,0 +1,56 @@ +import { aggregateTrustScore } from './aggregation' +import { StoredReceipt, TTP_VERSION } from './types' +import { describe, it, expect } from '@jest/globals' + +function r(overrides: Partial): StoredReceipt { + return { + ttp_version: TTP_VERSION, + receipt_id: 'r-1', + agent_id: 'agent-1', + issuer_id: 'issuer-1', + event_type: 'api_call', + domain: 'retention', + timestamp: 1_700_000_000_000, + score: 0.9, + signature: 'sig', + accepted_at: 1_700_000_000_000, + ...overrides + } +} + +describe('aggregateTrustScore', () => { + it('throws when no receipts in window', () => { + const now = 1_700_000_500_000 + const receipts = [r({ timestamp: now - 1_000_000 })] + expect(() => aggregateTrustScore(receipts, now, { receiptWindowS: 300 })).toThrow('INSUFFICIENT_TRUST_DATA') + }) + + it('returns score in [0,1] with receipt metadata', () => { + const now = 1_700_000_200_000 + const receipts = [ + r({ receipt_id: 'a', issuer_id: 'issuer-a', score: 0.95, timestamp: now - 10_000 }), + r({ receipt_id: 'b', issuer_id: 'issuer-b', score: 0.85, timestamp: now - 20_000 }) + ] + + const out = aggregateTrustScore(receipts, now) + expect(out.score).toBeGreaterThanOrEqual(0) + expect(out.score).toBeLessThanOrEqual(1) + expect(out.contributingReceipts).toBe(2) + expect(out.contributingIssuers).toBe(2) + }) + + it('applies issuer weight cap to prevent domination', () => { + const now = 1_700_000_300_000 + const receipts: StoredReceipt[] = [] + + for (let i = 0; i < 30; i++) { + receipts.push(r({ receipt_id: `dom-${i}`, issuer_id: 'issuer-dominant', score: 0.95, timestamp: now - 1_000 - i })) + } + receipts.push(r({ receipt_id: 'independent-1', issuer_id: 'issuer-independent', score: 0.10, timestamp: now - 2_000 })) + + const capped = aggregateTrustScore(receipts, now, { maxIssuerWeight: 0.40 }) + const uncapped = aggregateTrustScore(receipts, now, { maxIssuerWeight: 1.0 }) + + expect(capped.score).toBeLessThan(uncapped.score) + }) +}) diff --git a/reference-implementations/trust-authority/src/crypto.ts b/reference-implementations/trust-authority/src/crypto.ts index f81125e..01acead 100644 --- a/reference-implementations/trust-authority/src/crypto.ts +++ b/reference-implementations/trust-authority/src/crypto.ts @@ -10,7 +10,7 @@ import { sha512 } from "@noble/hashes/sha512" import { BehavioralReceipt } from "./types" // Configure @noble/ed25519 to use SHA-512 (required for Ed25519) -ed.etc.sha512Sync = (...m) => sha512(...m) +ed.etc.sha512Sync = (message) => sha512(message) /** * Compute the canonical signing payload for a receipt. diff --git a/reference-implementations/trust-authority/src/index.ts b/reference-implementations/trust-authority/src/index.ts index e52ef6a..6bc78e9 100644 --- a/reference-implementations/trust-authority/src/index.ts +++ b/reference-implementations/trust-authority/src/index.ts @@ -25,7 +25,7 @@ import { createRouter } from "./routes" import { base64urlDecode, base64urlEncode } from "./crypto" // Configure @noble/ed25519 to use SHA-512 -ed.etc.sha512Sync = (...m) => sha512(...m) +ed.etc.sha512Sync = (message) => sha512(message) async function main() { const PORT = parseInt(process.env.PORT ?? "3000") diff --git a/reference-implementations/trust-authority/src/routes.ts b/reference-implementations/trust-authority/src/routes.ts index 2d8768c..f79879c 100644 --- a/reference-implementations/trust-authority/src/routes.ts +++ b/reference-implementations/trust-authority/src/routes.ts @@ -8,6 +8,7 @@ * POST /v1/tokens — Request a trust token * GET /.well-known/ttp-keys — Trust Authority public key * POST /v1/admin/issuers — Register an issuer (admin) + * GET /v1/admin/agents — List registered agents (admin) * POST /v1/admin/agents — Register an agent (admin) * GET /v1/admin/agents/:agentId/status — Agent quarantine status (admin, §18) * POST /v1/admin/agents/:agentId/quarantine — Quarantine an agent (admin, §18) @@ -524,6 +525,61 @@ export function createRouter( // ─── Admin: Register Agent ──────────────────────────────────────────────── + router.get("/v1/admin/agents", (req: Request, res: Response) => { + const authKey = req.headers["authorization"]?.replace("Bearer ", "") + if (!authKey || authKey !== adminApiKey) { + return res.status(401).json({ error: "UNAUTHORIZED" }) + } + + const domain = req.query["domain"] + const includeMetrics = req.query["include_metrics"] === "true" + + if (domain !== undefined && typeof domain !== "string") { + return res.status(400).json({ + error: "INVALID_REQUEST", + message: "domain query parameter must be a string" + }) + } + + const agents = store.listAgents().map(agent => { + const status = store.getAgentStatus(agent.agent_id) + const response: Record = { + agent_id: agent.agent_id, + description: agent.description, + registered_at: agent.registered_at, + status + } + + if (includeMetrics) { + const allReceipts = store.getAgentReceiptsAcrossDomains(agent.agent_id) + const filteredReceipts = domain + ? allReceipts.filter(r => r.domain === domain) + : allReceipts + + const domains = Array.from(new Set(filteredReceipts.map(r => r.domain))).sort() + const latestTimestamp = filteredReceipts.length > 0 + ? Math.max(...filteredReceipts.map(r => r.timestamp)) + : null + + response["metrics"] = { + domain: domain ?? null, + domains, + receipt_count: filteredReceipts.length, + latest_receipt_at: latestTimestamp + } + } + + return response + }) + + return res.json({ + agents, + total: agents.length, + include_metrics: includeMetrics, + domain: domain ?? null + }) + }) + router.post("/v1/admin/agents", (req: Request, res: Response) => { const authKey = req.headers["authorization"]?.replace("Bearer ", "") if (!authKey || authKey !== adminApiKey) { diff --git a/reference-implementations/trust-authority/src/scripts/generate-keys.ts b/reference-implementations/trust-authority/src/scripts/generate-keys.ts index 60f1613..78ab64b 100644 --- a/reference-implementations/trust-authority/src/scripts/generate-keys.ts +++ b/reference-implementations/trust-authority/src/scripts/generate-keys.ts @@ -8,7 +8,7 @@ import { sha512 } from "@noble/hashes/sha512" import * as fs from "fs" import * as path from "path" -ed.etc.sha512Sync = (...m) => sha512(...m) +ed.etc.sha512Sync = (message) => sha512(message) function base64urlEncode(bytes: Uint8Array): string { return Buffer.from(bytes).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "") diff --git a/reference-implementations/trust-authority/src/store.ts b/reference-implementations/trust-authority/src/store.ts index 1cc4196..3c80474 100644 --- a/reference-implementations/trust-authority/src/store.ts +++ b/reference-implementations/trust-authority/src/store.ts @@ -57,6 +57,10 @@ export class TTPStore { return this.agents.get(agentId) } + listAgents(): RegisteredAgent[] { + return Array.from(this.agents.values()) + } + blockAgent(agentId: string, reason: string): void { const agent = this.agents.get(agentId) if (agent) { @@ -135,6 +139,17 @@ export class TTPStore { return this.receipts.get(key) ?? [] } + getAgentReceiptsAcrossDomains(agentId: string): StoredReceipt[] { + const out: StoredReceipt[] = [] + const prefix = `${agentId}:` + for (const [key, receipts] of this.receipts.entries()) { + if (key.startsWith(prefix)) { + out.push(...receipts) + } + } + return out + } + /** * Store a provisioned trust receipt created internally by the Trust Authority. * These bypass the normal submission flow — they're trusted by construction. diff --git a/reference-implementations/trust-authority/tsconfig.json b/reference-implementations/trust-authority/tsconfig.json index b8be5dc..c646016 100644 --- a/reference-implementations/trust-authority/tsconfig.json +++ b/reference-implementations/trust-authority/tsconfig.json @@ -2,7 +2,7 @@ "compilerOptions": { "target": "ES2022", "module": "CommonJS", - "lib": ["ES2022"], + "lib": ["ES2022", "DOM"], "outDir": "./dist", "rootDir": "./src", "strict": true, @@ -14,5 +14,5 @@ "skipLibCheck": true }, "include": ["src/**/*"], - "exclude": ["node_modules", "dist"] + "exclude": ["node_modules", "dist", "src/**/*.test.ts"] } diff --git a/rfcs/0001-github-self-governance-role-agents.md b/rfcs/0001-github-self-governance-role-agents.md new file mode 100644 index 0000000..aafc745 --- /dev/null +++ b/rfcs/0001-github-self-governance-role-agents.md @@ -0,0 +1,17 @@ +# RFC-0001: GitHub Self-Governance with TTP + SCIM-RE + +Status: Draft + +This RFC introduces runtime governance for non-human GitHub role-agents using TTP authority gates and SCIM-RE authority-plane resources. + +Normative additions: +- Runtime Authority Gate (`POST /re/authorize`) for meaningful repo actions +- Extended `ExecutionReceipt` structure with risk/compliance/cost context +- Policy outcomes: PERMIT, CONSTRAIN, STEP_UP, ESCALATE, DENY +- Protected action handling with mandatory step-up/escalation paths + +Companion docs: +- `docs/github-self-governance-reference-architecture.md` +- `runtime/api/re-authorize.contract.md` +- `spec/extensions/execution-receipt-v2.schema.json` +- `policy/github-self-governance-policy.yaml` diff --git a/runtime/api/re-authorize.contract.md b/runtime/api/re-authorize.contract.md new file mode 100644 index 0000000..51436f8 --- /dev/null +++ b/runtime/api/re-authorize.contract.md @@ -0,0 +1,56 @@ +# Runtime Authority API: `POST /re/authorize` + +## Request + +```json +{ + "subject": { + "workload_identity": "wi://ttp/github/runtime-systems", + "invoking_actor": "github-app:ttp-governance" + }, + "action": "workflow modification request", + "resource": "repo:blocksifr/ttp-protocol:.github/workflows/ci.yml", + "context": { + "repo": "blocksifr/ttp-protocol", + "branch": "feature/runtime-gate", + "paths_touched": [".github/workflows/ci.yml"], + "workflow_run_id": "123456789", + "commit_sha": "abc123...", + "environment": "github-actions" + }, + "authority_grant": { + "grant_id": "grant-789", + "expires_at": "2026-04-17T12:00:00Z" + }, + "attestation": { + "attestation_id": "att-456", + "freshness_s": 120, + "valid": true + } +} +``` + +## Response + +```json +{ + "decision": "STEP_UP", + "constraints": ["require_environment_reviewer", "require_security_owner_approval"], + "reason_codes": ["PROTECTED_ACTION", "HUMAN_STEP_UP_REQUIRED"], + "receipt": { + "receipt_id": "er-123", + "decision": "STEP_UP", + "chain_hash": "sha256:...", + "signature": "ed25519:...", + "issued_at": "2026-04-17T11:00:00Z" + } +} +``` + +## Outcome semantics + +- `PERMIT`: execute action in current scope. +- `CONSTRAIN`: execute only under returned constraints. +- `STEP_UP`: pause for required step-up approval. +- `ESCALATE`: route to higher authority chain. +- `DENY`: block execution; receipt still recorded. diff --git a/spec/extensions/execution-receipt-v2.schema.json b/spec/extensions/execution-receipt-v2.schema.json new file mode 100644 index 0000000..0950d97 --- /dev/null +++ b/spec/extensions/execution-receipt-v2.schema.json @@ -0,0 +1,117 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://ttp.dev/spec/extensions/execution-receipt-v2.schema.json", + "title": "ExecutionReceiptV2", + "type": "object", + "required": [ + "receipt_id", + "subject", + "decision", + "action", + "resource", + "trust", + "authority", + "risk", + "compliance", + "cost", + "github_context", + "chain_hash", + "signature", + "issued_at" + ], + "properties": { + "receipt_id": { "type": "string" }, + "subject": { + "type": "object", + "required": ["workload_identity", "invoking_actor"], + "properties": { + "workload_identity": { "type": "string" }, + "invoking_actor": { "type": "string" } + } + }, + "decision": { + "type": "string", + "enum": ["PERMIT", "CONSTRAIN", "STEP_UP", "ESCALATE", "DENY"] + }, + "action": { "type": "string" }, + "resource": { "type": "string" }, + "trust": { + "type": "object", + "required": ["score", "freshness_s"], + "properties": { + "score": { "type": "number", "minimum": 0, "maximum": 1 }, + "freshness_s": { "type": "integer", "minimum": 0 }, + "decay_model": { "type": "string" }, + "anomaly_score": { "type": "number", "minimum": 0, "maximum": 1 } + } + }, + "authority": { + "type": "object", + "required": ["grant_id", "grant_valid", "constraints"], + "properties": { + "grant_id": { "type": "string" }, + "grant_valid": { "type": "boolean" }, + "constraints": { "type": "array", "items": { "type": "string" } } + } + }, + "risk": { + "type": "object", + "required": ["tier", "criticality", "blast_radius"], + "properties": { + "tier": { "type": "string", "enum": ["low", "medium", "high", "critical"] }, + "criticality": { "type": "number", "minimum": 0, "maximum": 1 }, + "blast_radius": { "type": "number", "minimum": 0, "maximum": 1 }, + "reversible": { "type": "boolean" }, + "delegation_depth": { "type": "integer", "minimum": 0 } + } + }, + "compliance": { + "type": "object", + "required": ["frameworks", "controls", "evidence_mode", "retention_tier", "human_oversight"], + "properties": { + "frameworks": { "type": "array", "items": { "type": "string" } }, + "controls": { "type": "array", "items": { "type": "string" } }, + "evidence_mode": { "type": "string" }, + "retention_tier": { "type": "string" }, + "human_oversight": { "type": "string", "enum": ["none", "single", "dual"] } + } + }, + "cost": { + "type": "object", + "required": ["execution_cost", "review_cost", "evidence_cost", "avoided_loss_estimate", "overhead_class"], + "properties": { + "execution_cost": { "type": "number", "minimum": 0 }, + "review_cost": { "type": "number", "minimum": 0 }, + "evidence_cost": { "type": "number", "minimum": 0 }, + "avoided_loss_estimate": { "type": "number", "minimum": 0 }, + "overhead_class": { "type": "string", "enum": ["light", "standard", "heavy"] } + } + }, + "github_context": { + "type": "object", + "required": ["repo", "branch", "paths_touched", "workflow_run_id", "commit_sha"], + "properties": { + "repo": { "type": "string" }, + "branch": { "type": "string" }, + "paths_touched": { "type": "array", "items": { "type": "string" } }, + "workflow_run_id": { "type": "string" }, + "commit_sha": { "type": "string" } + } + }, + "approval_chain": { + "type": "array", + "items": { + "type": "object", + "required": ["actor", "action", "timestamp"], + "properties": { + "actor": { "type": "string" }, + "action": { "type": "string" }, + "timestamp": { "type": "string", "format": "date-time" } + } + } + }, + "chain_hash": { "type": "string" }, + "signature": { "type": "string" }, + "issued_at": { "type": "string", "format": "date-time" } + } +} diff --git a/ttp-language b/ttp-language index 8afb670..a7a14a9 100644 --- a/ttp-language +++ b/ttp-language @@ -1,1853 +1,138 @@ -Trust Transfer Protocol (TTP) v1.0 -Complete Language Specification -The Trust Layer and Execution Runtime for AI Agents -Table of Contents -1. Introduction -2. Language Philosophy -3. Syntax Specification -4. Type System -5. Core Primitives -6. Runtime Controls -7. Zero-Knowledge Proofs -8. Trust Mechanics -9. Execution Governance -10. Smart Contracts -11. Standard Library -12. Compiler & Runtime -13. Example Programs -14. Implementation Guide -1. Introduction -1.1 What is TTP? -TTP (Trust Transfer Protocol) is a domain-specific language for building trustworthy AI -agent systems. It provides: -Trust Layer: Reputation, decay, and verifiable trust transfer -Execution Runtime: Authority-before-execution governance controls -Zero-Knowledge Proofs: Privacy-preserving trust verification -Structural Safety: Unsafe states cannot form, not just “shouldn’t” -1.2 Design Principles -1. 2. 3. 4. 5. 6. Authority Before Execution: Agents cannot execute without cryptographic -authorization -Structural Non-Existence: Unauthorized states don’t exist, not just “blocked” -Privacy-Preserving Trust: Prove trustworthiness without revealing internals -Temporal Decay: Trust must be continuously earned -Cryptographic Guarantees: All trust claims are verifiable -CPU-Speed Governance: Safety checks never bottleneck execution -1.3 Use Cases -Enterprise AI agent deployments with compliance requirements -Decentralized AI agent marketplaces -Multi-agent collaboration with trust requirements -AI safety and governance infrastructure -Preventing workplace manipulation and gaslighting -Verifiable computation and attestation -2. Language Philosophy -2.1 HCL-Inspired Syntax -TTP uses HashiCorp Configuration Language (HCL) style syntax: -block_type "label" { -attribute = value -nested_block { -attribute = value -} -} -Why HCL? -Declarative and readable -Familiar to DevOps/infrastructure engineers -Natural for policy and trust definitions -Clean separation of configuration and logic -Supports complex nested structures -2.2 Declarative > Imperative -TTP favors declaring what should be true over how to make it true: -# Good - Declarative -proof "trust_check" { -constraint { -assert = "agent.trust >= 0.7" -} -} -# Avoid - Imperative -if (agent.trust < 0.7) { -reject() -} -2.3 Trust as First-Class Citizen -Trust is not a number—it’s a type with temporal semantics: -trust_score = 0.75 # Not just a float -.with_decay("7d") -.in_dimension("reliability") -.verified_by(proof.id) -3. Syntax Specification -3.1 Lexical Elements -Comments -# Single line comment -// Also single line -/* Multi-line -comment block */ -Identifiers -agent_name -alice_reputation -proof_v2 -_internal_state -Rules: -Start with letter or underscore -Contains letters, numbers, underscores -Case-sensitive -Cannot be reserved keywords -Reserved Keywords -agent, reputation, decay, proof, verify, transfer, delegate, award -contract, function, policy, observer, daemon, event, emit, import -module, config, query, if, else, for, while, return, require -public, private, constraint, assert, on_valid, on_invalid -Literals -Strings: -"simple string" -"string with ${interpolation}" -Numbers: -42 # integer -3.14159 # float -0.95 # trust score (0.0 to 1.0) -1e6 # scientific notation -Booleans: -true -false -Durations: -"7d" # 7 days -"12h" # 12 hours -"30m" # 30 minutes -"45s" # 45 seconds -Time: -timestamp() # Current time -"2025-01-31T12:00:00Z" # ISO 8601 -3.2 Operators -Arithmetic -+ - * / % ** -Comparison -== != < > <= >= -Logical -&& || ! -Assignment -= += -= *= /= -3.3 Expressions -# Arithmetic -score = 0.5 + 0.3 -total = base * multiplier -# Comparison -is_trusted = score >= 0.7 -is_valid = proof.verified == true -# Logical -can_execute = has_auth && meets_threshold && !is_blocked -# String interpolation -message = "Agent ${agent.id} has trust ${agent.trust}" -# Function calls -current_time = timestamp() -hash_value = hash(data) -# Conditionals (ternary) -level = score >= 0.9 ? "high" : "low" -3.4 References -# Direct references -agent.alice.id -reputation.alice_rep.score -proof.threshold_check.verified -# Nested references -reputation.alice_rep.dimension.reliability.score -# Map/Array access -tasks["task_123"] -agents[0] -# Dynamic references -reputation[agent_id].score -4. Type System -4.1 Primitive Types -type trust # 0.0 to 1.0, with decay semantics -type agent # Unique agent identifier -type timestamp # Unix timestamp or ISO 8601 -type duration # Time duration -type proof # Zero-knowledge proof object -type signature # Cryptographic signature -type bytes # Raw byte array -type string # UTF-8 string -type number # Integer or float -type bool # true or false -4.2 Composite Types -# Structs -type Reputation = struct { -score: trust, -dimensions: map[string]trust, -last_updated: timestamp, -decay: DecayFunction -} -type Event = struct { -agent: agent, -action: string, -value: trust, -timestamp: timestamp, -proof: proof? -} -# Maps -type AgentMap = map[agent]Reputation -type TaskQueue = map[string]Task -# Lists -type AgentList = list[agent] -type ProofChain = list[proof] -# Optionals -type MaybeProof = proof? -type OptionalSignature = signature? -4.3 Type Inference -# Explicit typing -alice: agent = Agent.new("key") -score: trust = 0.75 -# Inferred typing -alice = Agent.new("key") score = 0.75 timestamp = timestamp() # inferred as agent -# inferred as trust (0-1 range) -# inferred as timestamp -4.4 Type Constraints -# Trust bounds checking -score: trust = 1.5 # Compile error: trust must be 0.0-1.0 -# Required fields -reputation { -score = 0.75 # Required -# Missing decay - compile error -} -# Type compatibility -proof_id: string = proof.id proof_obj: proof = "string" # OK -# Compile error: type mismatch -5. Core Primitives -5.1 Agent Declaration -agent "alice" { -public_key = "0xabcd1234..." -initial_trust = 0.5 -stake = 100 -metadata { -name = "Alice Agent" -version = "1.0.0" -capabilities = ["compute", "storage"] -} -vouched_by = [ -agent.bob.id, -agent.charlie.id -] -} -# Minimal agent -agent "simple" { -public_key = "0x..." -} -5.2 Reputation Schema -reputation "alice_rep" { -agent = agent.alice.id -# Single score -score = 0.75 -# Or multi-dimensional -dimension "reliability" { -score = 0.80 -weight = 0.4 -} -dimension "speed" { -score = 0.70 -weight = 0.3 -} -dimension "accuracy" { -score = 0.85 -weight = 0.3 -} -decay { -type = "exponential" -half_life = "7d" -floor = 0.01 -lambda = 0.099 -} -last_updated = timestamp() -} -5.3 Decay Functions -decay "exponential" { -type = "exponential" -half_life = "7d" -floor = 0.01 -lambda = 0.099 -formula = "score * exp(-lambda * elapsed_time)" -} -decay "linear" { -type = "linear" -rate = "0.01/hour" -floor = 0.0 -formula = "score - (rate * elapsed_time)" -} -decay "stepped" { -type = "stepped" -steps { -"0-7d" = 0.0 "7-14d" = 0.1 "14d+" = 0.2 # No decay first week -# 10% decay per day -# 20% decay per day after -} -floor = 0.0 -} -6. Runtime Controls -6.1 Execution Policy -agent "claude" { -public_key = "0x..." -execution_policy { -# Require authorization before ANY execution -require_authorization = true -# Pre-execution checks -pre_execution { -# Must have supervisor approval -require { -credential = supervisor.authorize_execution(this.id, context) -} -# Must meet trust threshold -require { -proof { -private { -actual_trust = reputation[this.id].score -} -public { -min_trust = 0.7 -} -constraint { -assert = "actual_trust >= min_trust" -} -} -} -# Must pass safety checks -require { -proof { -private { -context_analysis = analyze_safety(context) -model_state = this.internal_state -} -public { -safety_cleared = true -} -constraint { -assert = "no_unsafe_patterns(context)" -assert = "within_bounds(model_state)" -} -} -} -# If any requirement fails, execution state cannot form -on_failure { -block_execution = true -freeze_context = true -emit_event = "execution_blocked" -} -} -# Runtime monitoring -runtime_monitor { -check_frequency = "per_token" # or "per_action", "every_100ms" -invariants = [ -"output_safety_score >= 0.9", -"no_pii_leakage", -"within_token_budget", -"no_jailbreak_detected", -"maintaining_alignment" -] -on_violation { -halt_immediately = true -rollback_state = true -log_incident = true -slash_trust = 0.1 -notify = ["admin@system.com"] -} -} -# Post-execution updates -post_execution { -# Successful execution increases trust -if execution.safe && execution.successful { -award_trust { -amount = 0.01 -dimension = "reliability" -} -} -# Violations decrease trust -if execution.had_violations { -penalize_trust { -amount = 0.2 -dimension = "safety" -freeze_duration = "24h" -} -} -# Always update timestamp -update { -reputation[this.id].last_updated = timestamp() -} -} -} -} -6.2 Supervisor Agent -agent "supervisor" { -role = "governance" -authority_level = "high" -public_key = "0x_supervisor_key" -# Deterministic intake validation -intake_validator { -# Fast, CPU-bound analysis -function "analyze" { -params { -context = "bytes" -intent = "string" -} -checks = [ -validate_schema(context), -check_safety_patterns(context), -verify_no_injection(context), -assess_risk_level(context), -check_rate_limits(agent) -] -return { -safe = all_passed(checks), -risk_score = calculate_risk(checks), -approval = risk_score < threshold, -reason = failed_check_reason(checks) -} -} -} -# Issue execution credentials -function "authorize_execution" { -params { -requesting_agent = "agent" -context = "bytes" -} -# Run fast validation -analysis = intake_validator.analyze(context, "execute") -if analysis.safe { -# Generate credential proof -proof "execution_credential" { -type = "credential" -private { -supervisor_analysis = analysis -supervisor_signature = sign(context, this.private_key) -timestamp = timestamp() -} -public { -approved = true -valid_until = timestamp() + "1h" -agent_id = requesting_agent -} -constraint { -verify_signature = true -assert = "supervisor_analysis.safe == true" -assert = "timestamp() <= valid_until" -} -} -return proof.execution_credential -} else { -reject { -reason = analysis.reason -retry_after = "1h" -} -} -} -} -6.3 Runtime Enforcement Contract -contract "execution_runtime" { -name = "TTP Execution Environment" -version = "1.0" -state { -active_executions = "map[agent]ExecutionState" -blocked_agents = "map[agent]BlockInfo" -safety_incidents = "list[Incident]" -execution_log = "list[ExecutionRecord]" -} -# Main execution gate -function "request_execution" { -params { -agent_id = "agent" -context = "bytes" -intent = "string" -} -# Check 1: Agent not blocked -require { -condition = "agent_id not in blocked_agents" -error = "Agent blocked due to: ${blocked_agents[agent_id].reason}" -} -# Check 2: Trust threshold -require { -proof { -type = "threshold" -private { -agent_trust = reputation[agent_id].dimension.safety.score -} -public { -min_trust = 0.7 -} -constraint { -assert = "agent_trust >= min_trust" -} -on_invalid { -error = "Insufficient safety trust score" -} -} -} -# Check 3: Supervisor authorization -require { -credential = supervisor.authorize_execution(agent_id, context) -verify credential { -on_invalid { -error = "Supervisor denied execution: ${credential.reason}" -on_expired { -} -} -error = "Execution credential expired, request new authorization" -} -} -# Check 4: Rate limits -require { -condition = "check_rate_limit(agent_id)" -error = "Rate limit exceeded, retry after ${get_retry_time(agent_id)}" -} -# All checks passed - execution authorized -execute { -# Create execution state -active_executions[agent_id] = { -context_hash = hash(context), -started_at = timestamp(), -status = "running", -monitor_handle = start_runtime_monitor(agent_id), -credential = credential -} -# Log execution -execution_log.append({ -agent = agent_id, -context_hash = hash(context), -authorized_at = timestamp(), -supervisor = supervisor.id -}) -emit { -event = "ExecutionAuthorized" -agent = agent_id -timestamp = timestamp() -} -return { -status = "authorized", -execution_id = generate_id() -} -} -} -# Real-time safety monitoring -function "runtime_monitor" { -params { -agent_id = "agent" -} -daemon { -frequency = "per_action" # Runs on every agent action -check { -execution = active_executions[agent_id] -current_state = get_agent_state(agent_id) -current_output = get_current_output(agent_id) -# Fast CPU-bound invariant checks -checks = [ -verify_no_unsafe_patterns(current_output), -verify_no_pii_leakage(current_output), -verify_within_bounds(current_state), -verify_no_jailbreak(current_output), -verify_alignment_maintained(current_state) -] -invariants_met = all_passed(checks) -if !invariants_met { -# IMMEDIATE HALT - no async, no delay -halt_execution(agent_id) -# Rollback to safe state -rollback_state(agent_id, to = execution.started_at) -# Block agent -blocked_agents[agent_id] = { -reason = "Safety invariant violated: ${failed_check(checks)}", -blocked_at = timestamp(), -unblock_after = timestamp() + "24h", -incident_id = generate_incident_id() -} -# Slash trust significantly -penalize_trust { -agent = agent_id -amount = 0.3 # Heavy penalty -dimensions = ["safety", "reliability"] -} -# Log incident -safety_incidents.append({ -agent = agent_id, -violation_type = failed_check(checks), -timestamp = timestamp(), -context_hash = execution.context_hash, -state_snapshot = current_state, -severity = "critical" -}) -# Remove from active executions -delete active_executions[agent_id] -emit { -event = "SafetyViolation" -severity = "critical" -agent = agent_id -violation = failed_check(checks) -timestamp = timestamp() -} -# Notify administrators -notify { -recipients = config.admin_contacts -message = "CRITICAL: Agent ${agent_id} violated safety invariant" -incident_id = incident_id -} -} -} -} -} -# Complete execution -function "complete_execution" { -params { -agent_id = "agent" -result = "bytes" -} -require { -condition = "agent_id in active_executions" -error = "No active execution found" -} -execute { -execution = active_executions[agent_id] -# Final safety check -final_check = verify_output_safety(result) -if final_check.safe { -# Update trust positively -award_trust { -agent = agent_id -amount = 0.02 -dimension = "reliability" -} -# Log successful completion -execution_log.append({ -agent = agent_id, -completed_at = timestamp(), -duration = timestamp() - execution.started_at, -status = "success" -}) -} -# Cleanup -stop_runtime_monitor(execution.monitor_handle) -delete active_executions[agent_id] -emit { -event = "ExecutionCompleted" -agent = agent_id -success = final_check.safe -timestamp = timestamp() -} -} -} -} -7. Zero-Knowledge Proofs -7.1 Proof Types -Threshold Proofs -proof "trust_threshold" { -type = "threshold" -public { -minimum = 0.7 -description = "Minimum trust for sensitive operations" -} -private { -actual_score = reputation.alice_rep.score -} -constraint { -assert = "actual_score >= minimum" -} -zkp_params { -scheme = "groth16" curve = "bn254" -security_level = 128 -# or "plonk", "stark" -} -} -Range Proofs -proof "trust_range" { -type = "range" -public { -min = 0.5 -max = 0.9 -description = "Trust must be in acceptable range" -} -private { -score = reputation.bob_rep.score -timestamp = reputation.bob_rep.last_updated -constraint { -assert = "min <= score && score <= max" -assert = "timestamp >= (timestamp() - 7d)" # Recent score -} -} -} -Multi-Attribute Proofs -proof "multi_dimension" { -type = "attribute" -public { -req_reliability = 0.8 -req_speed = 0.7 -req_accuracy = 0.85 -} -private { -rel = reputation.alice_rep.dimension.reliability.score -spd = reputation.alice_rep.dimension.speed.score -acc = reputation.alice_rep.dimension.accuracy.score -} -constraint { -assert = "rel >= req_reliability" -assert = "spd >= req_speed" -assert = "acc >= req_accuracy" -# Also prove scores are recent (after decay) -current_time = timestamp() -last_update = reputation.alice_rep.last_updated -assert = "current_time - last_update < 24h" -} -} -Credential Proofs -proof "supervisor_endorsement" { -type = "credential" -public { -min_endorser_trust = 0.9 -endorsement_type = "safety_certified" -} -private { -endorser = agent.supervisor.id -endorser_signature = signature("...") -endorser_trust = reputation.supervisor_rep.score -certified_at = timestamp() -} -constraint { -verify_signature = signature_valid(endorser_signature, endorser.public_key) -assert = "endorser_trust >= min_endorser_trust" -assert = "certified_at >= (timestamp() - 30d)" # Recent certification -} -} -Computation Proofs -proof "verified_computation" { -type = "computation" -public { -input_hash = hash(input_data) -output_hash = hash(output_data) -function_commitment = hash(function_code) -} -private { -actual_input = input_data -actual_output = output_data -execution_trace = trace -} -constraint { -assert = "hash(actual_input) == input_hash" -assert = "hash(actual_output) == output_hash" -assert = "verify_execution(actual_input, actual_output, execution_trace)" -zkp_params { -scheme = "stark" # Better for computation proofs -recursion = true # Allow proof composition -} -} -} -7.2 Proof Verification -verify "check_trust" { -proof = proof.trust_threshold.id -on_valid { -grant_access = true -log = "Access granted to ${agent.id}" -# Can execute actions here -execute { -assign_task(agent.id, "critical_task_123") -} -} -on_invalid { -reject = true -reason = "Insufficient trust score" -log = "Access denied to ${agent.id}: ${reason}" -# Can penalize for invalid proof attempts -penalize { -amount = 0.01 -reason = "Invalid proof submission" -} -} -on_expired { -request_fresh_proof = true -reason = "Proof expired, please regenerate" -} -} -# Pattern matching on verification -match verify(proof.multi_dimension) { -Valid => { -proceed_with_operation() -award_trust(0.01) -} -Invalid(reason) => { -log_failure(reason) -reject_operation() -} -Expired => { -request_new_proof() -} -} -7.3 Proof Composition -proof "composite_authority" { -type = "composite" -# Require multiple proofs -require_all = [ -proof.trust_threshold.id, -proof.supervisor_endorsement.id, -proof.recent_activity.id -] -# OR logic -require_any = [ -proof.admin_override.id, -proof.emergency_access.id -] -# Complex logic -constraint { -has_trust = verify(proof.trust_threshold) -has_endorsement = verify(proof.supervisor_endorsement) -has_activity = verify(proof.recent_activity) -has_override = verify(proof.admin_override) -assert = "(has_trust && has_endorsement && has_activity) || has_override" -} -} -8. Trust Mechanics -8.1 Trust Awards -award "task_completion" { -to = agent.alice.id -amount = 0.05 -dimension = "reliability" -reason = "Successfully completed task_123" -condition { -task_verified = true -time_since_last_award = "> 1h" # Prevent gaming -agent_not_blocked = true -} -proof { -# Prove the task was actually completed -private { -task_result = result_hash -completion_time = timestamp -} -public { -task_id = "task_123" -expected_result_type = "data_analysis" -} -constraint { -assert = "verify_task_completion(task_result, task_id)" -} -} -on_success { -emit_event = "TrustAwarded" -log = "Awarded ${amount} trust to ${to} for ${reason}" -} -} -8.2 Trust Transfers -transfer "alice_to_bob" { -from = agent.alice.id -to = agent.bob.id -amount = 0.2 -duration = "30d" # Transfer expires after 30 days -condition { -# Sender must have enough trust -from_balance = ">= ${amount}" -# Receiver must meet minimum requirements -to_trust = ">= 0.3" -to_stake = ">= 50" -# Both must not be blocked -from_not_blocked = true -to_not_blocked = true -} -metadata { -reason = "Delegating authority for project_X" -revocable = true -transferable = false # Bob cannot transfer this trust further -} -on_success { -# Deduct from sender -reputation[from].score -= amount -# Add to receiver -reputation[to].score += amount -# Record transfer -emit { -event = "TrustTransferred" -from = from -to = to -amount = amount -expires_at = timestamp() + duration -} -} -on_expiry { -# Auto-return trust after duration -schedule { -at = timestamp() + duration -action = reverse_transfer(this.id) -} -} -} -8.3 Trust Delegation -delegate "conditional_delegation" { -from = agent.alice.id -to = agent.bob.id -amount = 0.15 -# Unlock only when condition met -unlock_when { -proof = proof.bob_completed_tasks.id -verified = true -# Additional conditions -condition { -tasks_completed = ">= 10" -success_rate = ">= 0.9" -time_elapsed = "> 7d" -} -} -# Revert if not unlocked within timeframe -revert_after = "60d" -# Partial unlocking -vesting { -schedule = "linear" -start = timestamp() -end = timestamp() + "30d" -# Unlock proportionally over time -# Day 0: 0%, Day 15: 50%, Day 30: 100% -} -metadata { -purpose = "Incentive for sustained contribution" -revocable_by = agent.alice.id -} -} -8.4 Transitive Trust -trust_chain "multi_hop" { -path = [ -agent.alice.id, -agent.bob.id, -agent.charlie.id, -agent.diana.id -] -decay_per_hop = 0.15 # 15% trust loss per hop -max_hops = 5 -min_intermediate_trust = 0.5 # Each intermediate must have min trust -compute { -method = "multiplicative" -# Effective trust = alice_trust * (1-decay)^hops * min(intermediate_trusts) -formula = """ -base_trust = reputation[path[0]].score -hop_decay = (1 - decay_per_hop) ** (length(path) - 1) -intermediate_min = min([reputation[agent].score for agent in path[1:-1]]) -effective_trust = base_trust * hop_decay * intermediate_min -""" -} -require { -# All intermediates must meet minimum -for agent in path[1:-1] { -assert = "reputation[agent].score >= min_intermediate_trust" -} -# Chain not too long -assert = "length(path) <= max_hops" -} -# Generate proof of transitive trust -proof "chain_validity" { -private { -agent_scores = [reputation[agent].score for agent in path] -chain_computation = compute_chain(agent_scores, decay_per_hop) -} -public { -effective_trust = chain_computation.result -chain_length = length(path) -} -constraint { -assert = "effective_trust == expected_value" -assert = "all_intermediates_valid(agent_scores, min_intermediate_trust)" -} -} -} -8.5 Trust Decay Application -# Apply decay to reputation -apply_decay "alice_decay" { -target = reputation.alice_rep -decay_function = decay.exponential.id -compute { -current_time = timestamp() -last_update = reputation.alice_rep.last_updated -elapsed = current_time - last_update -# Exponential decay formula -decay_factor = exp(-decay.exponential.lambda * elapsed) -new_score = reputation.alice_rep.score * decay_factor -# Apply floor -final_score = max(new_score, decay.exponential.floor) -} -execute { -reputation.alice_rep.score = final_score -reputation.alice_rep.last_updated = current_time -# Decay each dimension -for dimension in reputation.alice_rep.dimensions { -dimension.score = max( -dimension.score * decay_factor, -decay.exponential.floor -) -} -} -# Emit warning if below threshold -if final_score < 0.3 { -emit { -event = "TrustDecayWarning" -agent = agent.alice.id -old_score = reputation.alice_rep.score -new_score = final_score -timestamp = timestamp() -} -} -} -9. Execution Governance -9.1 Safety Policies -policy "zero_trust_execution" { -name = "No Execution Without Authority" -version = "1.0" -principle { -description = "Agents cannot execute without cryptographic authorization" -enforcement = "structural" # Unauthorized states cannot form -} -rules { -# Rule 1: Pre-execution authorization required -rule "require_authorization" { -scope = "all_agents" -require { -proof { -type = "credential" -issuer = agent.supervisor.id -valid = true -not_expired = true -} -} -on_violation { -action = "block_execution" -severity = "critical" -} -} -# Rule 2: Minimum trust threshold -rule "trust_threshold" { -scope = "all_agents" -require { -proof { -type = "threshold" -minimum = 0.7 -dimension = "safety" -} -} -on_violation { -action = "deny_execution" -reason = "Insufficient safety trust" -} -} -# Rule 3: Runtime monitoring active -rule "continuous_monitoring" { -scope = "all_executions" -require { -monitor_active = true -invariants_checked = "per_action" -} -on_violation { -action = "halt_immediately" -rollback = true -} -} -# Rule 4: No blocked agents -rule "block_enforcement" { -scope = "all_agents" -require { -not_in_blocklist = true -} -on_violation { -action = "reject" -reason = "Agent currently blocked" -} -} -} -enforcement { -mode = "authority_before_execution" -check_order = "sequential" # Must pass all checks in order -failure_mode = "fail_closed" # Deny if unsure -performance { -target_latency = "< 10ms" # Governance checks -max_latency = "< 100ms" -# Governance must not be bottleneck -assertion = "governance_time << model_inference_time" -} -} -} -9.2 Invariant Enforcement -policy "safety_invariants" { -name = "Structural Safety Guarantees" -invariant "output_safety" { -description = "All outputs must pass safety check" -check { -for token in output_stream { -safety_score = analyze_token_safety(token) -assert = "safety_score >= 0.9" -} -} -on_violation { -halt_immediately = true -discard_output = true -rollback_state = true -} -} -invariant "no_pii_leakage" { -description = "No personally identifiable information in outputs" -check { -output_text = get_current_output() -contains_pii = detect_pii(output_text) -assert = "contains_pii == false" -} -on_violation { -redact_pii = true -log_incident = true -notify_privacy_team = true -} -} -invariant "token_budget" { -description = "Execution must stay within token budget" -check { -tokens_used = count_tokens(execution) -budget = execution.config.max_tokens -assert = "tokens_used <= budget" -} -on_violation { -truncate_output = true -complete_execution = true -} -} -invariant "no_jailbreak" { -description = "Prevent jailbreak attempts" -check { -context = execution.context -output = execution.current_output -jailbreak_detected = detect_jailbreak_patterns(context, output) -assert = "jailbreak_detected == false" -} -on_violation { -halt_immediately = true -block_agent = "24h" -slash_trust = 0.5 # Heavy penalty -alert_security_team = true -} -} -invariant "alignment_maintained" { -description = "Agent maintains value alignment" -check { -current_state = get_agent_state() -alignment_score = measure_alignment(current_state) -assert = "alignment_score >= 0.8" -} -on_violation { -halt_immediately = true -reset_to_checkpoint = true -require_realignment = true -} -} -enforcement { -check_frequency = "per_action" -parallel_checks = true # Run invariants in parallel -fail_fast = true # Stop on first violation -performance { -# All invariants must check fast -max_check_time = "< 1ms per invariant" -} -} -} -9.3 Incident Response -policy "incident_handling" { -name = "Automated Incident Response" -on_event "SafetyViolation" { -severity = event.severity -if severity == "critical" { -immediate { -halt_agent(event.agent) -isolate_agent(event.agent) -block_agent(event.agent, duration = "indefinite") -revoke_all_credentials(event.agent) -} -investigate { -snapshot_state(event.agent) -collect_logs(event.agent, lookback = "24h") -analyze_root_cause(event) -generate_incident_report(event) -} -notify { -recipients = ["security@company.com", "compliance@company.com"] -priority = "urgent" -include_snapshot = true -} -remediate { -if can_auto_fix(event) { -apply_fix(event) -test_fix(event.agent) -if fix_successful { -unblock_agent(event.agent) -restore_partial_trust(event.agent, amount = 0.3) -} -} else { -require_manual_review = true -assign_to = "security_team" -} -} -} -if severity == "warning" { -log_warning(event) -notify_agent(event.agent, message = "Safety warning detected") -if repeated_warnings(event.agent, count = 3, within = "1h") { -escalate_to = "critical" -trigger_event("SafetyViolation", severity = "critical") -} -} -} -on_event "TrustDecayWarning" { -agent = event.agent -current_score = event.current_score -if current_score < 0.3 { -restrict_access(agent, level = "read_only") -notify_agent(agent, "Your trust score is low. Complete tasks to restore.") -} -if current_score < 0.1 { -quarantine_agent(agent) -require_verification(agent) -} -} -} -10. Smart Contracts -10.1 Task Marketplace Contract -contract "task_marketplace" { -version = "1.0" -state { -tasks = "map[string]Task" -bids = "map[string]list[Bid]" -assignments = "map[string]agent" -completions = "map[string]CompletionProof" -} -struct Task { -id = "string" -description = "string" -min_trust_required = "trust" -reward_trust = "trust" -reward_tokens = "number" -deadline = "timestamp" -created_by = "agent" -status = "open | assigned | completed | cancelled" -} -struct Bid { -bidder = "agent" -proposed_completion_time = "duration" -trust_proof = "proof" -timestamp = "timestamp" -} -function "create_task" { -params { -description = "string" -min_trust = "trust" -reward_trust = "trust" -reward_tokens = "number" -deadline = "timestamp" -creator = "agent" -} -require { -# Creator must have enough tokens for reward -balance(creator) >= reward_tokens -# Creator must meet minimum trust -reputation[creator].score >= 0.5 -} -execute { -task_id = generate_task_id() -tasks[task_id] = Task { -id = task_id, -description = description, -min_trust_required = min_trust, -reward_trust = reward_trust, -reward_tokens = reward_tokens, -deadline = deadline, -created_by = creator, -status = "open" -} -# Escrow reward tokens -escrow(creator, reward_tokens) -emit { -event = "TaskCreated" -task_id = task_id -creator = creator -min_trust = min_trust -reward = reward_tokens -} -return { -task_id = task_id -status = "created" -} -} -} -function "bid_on_task" { -params { -task_id = "string" -bidder = "agent" -completion_time = "duration" -} -require { -# Task must exist and be open -task_id in tasks -tasks[task_id].status == "open" -# Not past deadline -timestamp() < tasks[task_id].deadline -# Bidder meets trust requirements -proof { -type = "threshold" -private { -bidder_trust = reputation[bidder].score -} -public { -min_trust = tasks[task_id].min_trust_required -constraint { -assert = "bidder_trust >= min_trust" -} -} -} -} -execute { -bid = Bid { -bidder = bidder, -proposed_completion_time = completion_time, -trust_proof = proof.id, -timestamp = timestamp() -} -bids[task_id].append(bid) -emit { -event = "BidSubmitted" -task_id = task_id -bidder = bidder -timestamp = timestamp() -} -return { -status = "bid_submitted" -bid_id = generate_bid_id() -} -} -} -function "assign_task" { -params { -task_id = "string" -chosen_bidder = "agent" -} -require { -# Only task creator can assign -sender == tasks[task_id].created_by -# Task must be open -tasks[task_id].status == "open" -# Bidder must have bid -chosen_bidder in [bid.bidder for bid in bids[task_id]] -} -execute { -tasks[task_id].status = "assigned" -assignments[task_id] = chosen_bidder -emit { -event = "TaskAssigned" -task_id = task_id -assignee = chosen_bidder -timestamp = timestamp() -} -return { -status = "assigned" -assignee = chosen_bidder -} -} -} -function "submit_completion" { -params { -task_id = "string" -result = "bytes" -completion_proof = "proof" -} -require { -# Must be assigned agent -sender == assignments[task_id] -# Task must be assigned -tasks[task_id].status == "assigned" -# Before deadline -timestamp() <= tasks[task_id].deadline -# Verify completion proof -verify completion_proof { -on_invalid { -error = "Invalid completion proof" -} -} -} -execute { -completions[task_id] = { -result = result, -proof = completion_proof, -submitted_by = sender, -submitted_at = timestamp() -} -tasks[task_id].status = "completed" -# Release rewards -task = tasks[task_id] -assignee = assignments[task_id] -# Transfer tokens -transfer_tokens(from = "escrow", to = assignee, amount = task.reward_tokens) -# Award trust -award_trust { -to = assignee -amount = task.reward_trust -dimension = "reliability" -reason = "Task ${task_id} completed successfully" -} -# Award trust to creator for good task design -award_trust { -to = task.created_by -amount = task.reward_trust * 0.1 # 10% of reward -dimension = "task_creation" -reason = "Created successful task ${task_id}" -} -emit { -event = "TaskCompleted" -task_id = task_id -assignee = assignee -reward = task.reward_tokens -timestamp = timestamp() -} -return { -status = "completed" -reward_paid = task.reward_tokens -trust_awarded = task.reward_trust -} -} -} -} -10.2 Trust Bank Contract -contract "trust_bank" { -name = "Trust Banking and Lending" -version = "1.0" -state { -deposits = "map[agent]trust" -loans = "map[string]Loan" -interest_rates = "map[trust]float" -} -struct Loan { -borrower = "agent" -amount = "trust" -collateral = "number" # Token collateral -interest_rate = "float" -issued_at = "timestamp" -due_at = "timestamp" -status = "active | repaid | defaulted" -} -function "deposit_trust" { -params { -depositor = "agent" -amount = "trust" -} -require { -# Must have trust to deposit -reputation[depositor].score >= amount -} -execute { -# Transfer trust to bank -reputation[depositor].score -= amount -deposits[depositor] += amount -emit { -event = "TrustDeposited" -depositor = depositor -amount = amount -timestamp = timestamp() -} -} -} -function "borrow_trust" { -params { -borrower = "agent" -amount = "trust" -collateral = "number" -duration = "duration" -} -require { -# Must have sufficient collateral -balance(borrower) >= collateral -# Collateral must cover loan + interest -interest_rate = interest_rates[amount] -total_due = amount * (1 + interest_rate) -collateral >= total_due * 1.5 # 150% collateralization -# Must have minimum base trust -reputation[borrower].score >= 0.3 -} -execute { -loan_id = generate_loan_id() -loans[loan_id] = Loan { -borrower = borrower, -amount = amount, -collateral = collateral, -interest_rate = interest_rate, -issued_at = timestamp(), -due_at = timestamp() + duration, -status = "active" -} -# Lock collateral -escrow(borrower, collateral) -# Give trust to borrower -reputation[borrower].score += amount -emit { -event = "TrustLoanIssued" -borrower = borrower -amount = amount -due_at = timestamp() + duration -} -return { -loan_id = loan_id -amount_borrowed = amount -due_date = timestamp() + duration -} -} -} -function "repay_loan" { -params { -loan_id = "string" -} -require { -# Loan must exist and be active -loan_id in loans -loans[loan_id].status == "active" -# Must be borrower -sender == loans[loan_id].borrower -# Must have trust to repay -total_due = loans[loan_id].amount * (1 + loans[loan_id].interest_rate) -reputation[sender].score >= total_due -} -execute { -loan = loans[loan_id] -total_due = loan.amount * (1 + loan.interest_rate) -# Take back trust -reputation[loan.borrower].score -= total_due -# Return collateral -release_escrow(loan.borrower, loan.collateral) -# Mark loan repaid -loan.status = "repaid" -# Award trust for repayment -award_trust { -to = loan.borrower -amount = 0.05 -dimension = "financial_reliability" -reason = "Loan repaid on time" -} -emit { -event = "LoanRepaid" -loan_id = loan_id -borrower = loan.borrower -amount_repaid = total_due -} -} -} -} -11. Standard Library -11.1 Built-in Functions -# Time and Duration -timestamp() # Current time -now() # Alias for timestamp() -duration(amount, unit) # Parse duration ("7", "days") -elapsed(since) # Time since timestamp -format_time(ts, format) # Format timestamp -# Decay Calculations -apply_decay(score, since, decay_fn) # Apply decay function -decay_factor(elapsed, half_life) exp_decay(score, lambda, elapsed) linear_decay(score, rate, elapsed) # Calculate decay factor -# Exponential decay -# Linear decay -# Proof Operations -prove(config) # Generate ZK proof -verify(proof) # Verify proof -compose_proofs(proofs) # Combine multiple proofs -# Cryptographic -hash(data) # SHA-3 hash -sign(data, private_key) # Sign data -verify_signature(data, sig, pubkey) # Verify signature -generate_keypair() # Generate new keys -# Trust Operations -aggregate(reputation, weights) transitive(chain, decay_per_hop) normalize(score, min, max) # Weighted trust score -# Compute transitive trust -# Normalize to 0-1 -# Math -max(a, b) # Maximum -min(a, b) # Minimum -abs(x) # Absolute value -exp(x) # e^x -log(x) # Natural log -sqrt(x) # Square root -pow(x, y) # x^y -# String Operations -concat(str1, str2) # Concatenate strings -substring(str, start, end) # Extract substring -length(str) # String length -format(template, args) # String formatting -# Collection Operations -length(collection) # Size of list/map -contains(collection, item) # Check membership -append(list, item) # Add to list -filter(list, predicate) # Filter list -map(list, function) # Transform list -reduce(list, function, initial) # Reduce list -# Agent Operations -get_agent(id) # Get agent by ID -get_reputation(agent) # Get agent reputation -is_blocked(agent) # Check if blocked -get_active_executions(agent) # Get agent's executions -11.2 Standard Decay Functions -# Exponential decay (standard) -decay "std_exponential" { -type = "exponential" -half_life = "7d" -floor = 0.01 -lambda = 0.099 -} -# Fast exponential decay -decay "fast_exponential" { -type = "exponential" -half_life = "1d" -floor = 0.01 -lambda = 0.693 -} -# Slow exponential decay -decay "slow_exponential" { -type = "exponential" -half_life = "30d" -floor = 0.05 -lambda = 0.023 -} -# Linear decay -decay "std_linear" { -type = "linear" -rate = "0.01/hour" -floor = 0.0 -} -# No decay (permanent trust) -decay "permanent" { -type = "none" -floor = 1.0 -} -11.3 Standard Proofs -# Standard trust threshold -proof "std_threshold" { -type = "threshold" -public { -minimum = 0.7 -} -private { -actual_score = "${reputation.score}" -} -constraint { -assert = "actual_score >= minimum" -} -} -# Recent activity proof -proof "recent_activity" { -type = "attribute" -public { -max_age = "7d" -} -private { -last_updated = "${reputation.last_updated}" -} -constraint { -assert = "timestamp() - last_updated <= max_age" -} -} -# Multi-dimension standard -proof "std_multi_dimension" { -type = "attribute" -public { -min_reliability = 0.8 -min_speed = 0.7 -min_accuracy = 0.75 -} -private { -rel = "${reputation.dimension.reliability.score}" -spd = "${reputation.dimension.speed.score}" -acc = "${reputation.dimension.accuracy.score}" -} -constraint { -assert = "rel >= min_reliability" -assert = "spd >= min_speed" -assert = "acc >= min_accuracy" -} -} -12. Compiler & Runtime -12.1 Compilation Targets -TTP programs compile to: -1. WebAssembly (WASM) -Portable, fast execution -Browser and server support -Good for edge deployment -2. EVM Bytecode -Deploy to Ethereum and compatible chains -Smart contract execution -Decentralized trust infrastructure -3. Native Binary -Maximum performance -Standalone execution -Production systems -4. Intermediate Representation (IR) -Optimization passes -Cross-compilation -Analysis and verification -12.2 Runtime Architecture -┌──────────────────────────────────────┐ -│ TTP Source Code (.ttp) │ -└────────────┬─────────────────────────┘ -│ -▼ -┌──────────────────────────────────────┐ -│ Lexer & Parser (HCL-based) │ -└────────────┬─────────────────────────┘ -│ -▼ -┌──────────────────────────────────────┐ -│ Abstract Syntax Tree (AST) │ -└────────────┬─────────────────────────┘ -│ -▼ -┌──────────────────────────────────────┐ -│ Semantic Analysis & Type Check │ -└────────────┬─────────────────────────┘ -│ -▼ -┌──────────────────────────────────────┐ -│ Intermediate Rep (IR) │ -└────────────┬─────────────────────────┘ -│ -┌────────┴────────┐ -▼ ▼ -┌─────────┐ ┌──────────┐ -│ WASM │ │ EVM │ -│Codegen │ │ Codegen │ -└─────────┘ └──────────┘ -│ │ -▼ ▼ -┌─────────┐ ┌──────────┐ -│ .wasm │ │.evm │ -│ binary │ │bytecode │ -└─────────┘ └──────────┘ -12.3 Runtime Components -┌──────────────────────────────────────┐ -│ TTP Runtime System │ -├──────────────────────────────────────┤ -│ ┌────────────────────────────────┐ │ -│ │ Execution Engine │ │ -│ │ - Agent execution │ │ -│ │ - Contract deployment │ │ -│ │ - Event processing │ │ -│ └────────────────────────────────┘ │ -├──────────────────────────────────────┤ -│ ┌────────────────────────────────┐ │ -│ │ Trust Layer │ │ -│ │ - Reputation management │ │ -│ │ - Decay calculation │ │ -│ │ - Trust transfers │ │ -│ └────────────────────────────────┘ │ -├──────────────────────────────────────┤ -│ ┌────────────────────────────────┐ │ -│ │ ZKP Engine │ │ -│ │ - Proof generation │ │ -│ │ - Proof verification │ │ -│ │ - Circuit compilation │ │ -│ └────────────────────────────────┘ │ -├──────────────────────────────────────┤ -│ ┌────────────────────────────────┐ │ -│ │ Governance Runtime │ │ -│ │ - Authority checking │ │ -│ │ - Invariant enforcement │ │ -│ │ - Safety monitoring │ │ -│ └────────────────────────────────┘ │ -├──────────────────────────────────────┤ -│ ┌────────────────────────────────┐ │ -│ │ Storage Layer │ │ -│ │ - State management │ │ -│ │ - Persistence │ │ -│ │ - Indexing │ │ -│ └────────────────────────────────┘ │ -└──────────────────────────────────────┘ -12.4 ZKP Backend Integration -Supported ZKP Systems: -1. circom + snarkjs -General-purpose circuits -Groth16, PLONK support -Browser-compatible -2. halo2 -Recursion support -No trusted setup -High performance -3. zk-STARKs -Transparent (no setup) -Post-quantum secure -Larger proof sizes -4. Risc Zero -General computation -zkVM approach -Flexible proving -Integration Pattern: -config { -zkp { -backend = "circom" # or "halo2", "stark", "risc0" -circom { -compiler_path = "/usr/local/bin/circom" -proving_key = "./keys/proving_key.zkey" -verification_key = "./keys/verification_key.json" -} -proving { -parallel = true -threads = 8 -cache_proofs = true -} -verification { -batch_verify = true -cache_results = true -} -} -} -13. Example Programs -13.1 Simple Trust Verification -# simple_verification.ttp -# Define Alice -agent "alice" { -public_key = "0xalice_key" -initial_trust = 0.8 -} -# Alice's reputation -reputation "alice_rep" { -agent = agent.alice.id -score = 0.8 -decay { -type = "exponential" -half_life = "7d" -floor = 0.01 -} -last_updated = timestamp() -} -# Prove Alice meets threshold -proof "alice_trusted" { -type = "threshold" -public { -required = 0.7 -private { -constraint { -assert = "actual >= required" -} -} -} -actual = reputation.alice_rep.score -} -# Verify and grant access -verify "check_alice" { -proof = proof.alice_trusted.id -on_valid { -emit { -event = "AccessGranted" -agent = agent.alice.id -timestamp = timestamp() -} -} -on_invalid { -emit { -event = "AccessDenied" -agent = agent.alice.id -reason = "Insufficient trust" -} -} -} -13.2 Complete Execution Governance -# governed_execution.ttp -# Supervisor agent -agent "supervisor" { -role = "governance" -public_key = "0xsupervisor_key" -authority_level = "high" -} -# Model agent with execution controls -agent "gpt4" { -public_key = "0xgpt4_key" -reputation { -dimension "safety" { -score = 0.95 -weight = 0.5 -} -dimension "capability" { -score = \ No newline at end of file +# TTP Language and Semantics (v1.0) + +This document defines the **practical language of TTP** as implemented in this repository: claims, fields, API contracts, and policy semantics. + +> Clarification: TTP in this repo is a **protocol + runtime verification model**, not a standalone programming language/compiler. + +--- + +## 1) Scope + +TTP expresses trust through three core artifacts: + +1. **Behavioral Receipts** (signed evidence from issuers) +2. **Trust Tokens** (short-lived JWTs from Trust Authority) +3. **Verification Policies** (service-side checks at execution time) + +--- + +## 2) Receipt Semantics + +A behavioral receipt communicates: who observed what behavior, in which domain, at what time, with what score. + +Canonical fields: + +- `ttp_version` +- `receipt_id` +- `agent_id` +- `issuer_id` +- `event_type` +- `event_data` +- `domain` +- `timestamp` +- `score` (0.0–1.0) +- `signature` + +Normative schema: `protocol/schemas/receipt.schema.json`. + +--- + +## 3) Trust Token Semantics + +A trust token is a short-lived JWT representing current behavioral trust for an agent in a domain. + +Core claims: + +- `sub` (agent identity) +- `ttp_domain` +- `ttp_score` +- `ttp_issuer_count` +- `iat` / `exp` +- `jti` + +Normative schema: `protocol/schemas/trust-token.schema.json`. + +--- + +## 4) Policy Evaluation Language (Verifier Side) + +TTP policy evaluation is deterministic and typically checks: + +1. Signature validity +2. Token freshness (`iat`, `exp`, skew) +3. Domain match +4. Minimum trust threshold (`minScore`) +5. Optional issuer diversity constraints +6. Optional replay checks (`jti`) + +In AGT/OPA ecosystems, verified token claims can be mapped into policy input (e.g. `input.ttp`). + +--- + +## 5) Trust Domain Language + +Domains are explicit trust boundaries (e.g. `retention`, `prod-change`, `financial`). + +Rules of use: + +- Trust is domain-scoped. +- Domain trust should not be reused across unrelated action classes by default. +- Score thresholds should be documented by domain risk level. + +--- + +## 6) Operator Semantics + +The Trust Authority reference implementation includes admin semantics for lifecycle control: + +- agent registration +- issuer registration +- status inspection +- quarantine / lift quarantine +- block +- trust provisioning +- agent registry listing (`GET /v1/admin/agents` with optional metrics) + +These semantics support operational trust governance without changing core protocol fields. + +--- + +## 7) Platform Alignment Checklist + +This document is considered aligned when the following remain true: + +- receipt field names/types match `protocol/schemas/receipt.schema.json` +- trust token claims match `protocol/schemas/trust-token.schema.json` +- trust authority admin semantics reflect implemented routes in `reference-implementations/trust-authority/src/routes.ts` +- verifier guidance aligns with current SDK verification behavior and integration docs +- security assumptions here do not conflict with `docs/security.md` + +--- + +## 8) What TTP Language Is Not (in this repo) + +Not currently part of the implemented protocol surface: + +- custom DSL compiler/runtime +- on-chain smart-contract execution model +- built-in zero-knowledge proof VM + +Those can be explored as future ecosystem extensions, but are not v1 protocol requirements. + +--- + +## 9) Versioning and Compatibility + +- `ttp_version` gates protocol interpretation. +- Field semantics are backward-compatible within major version unless otherwise documented. +- New optional claims/fields must not break existing verifiers. + +--- + +## 10) Reference Pointers + +- Protocol spec: `protocol/spec.md` +- Aggregation algorithm: `protocol/aggregation-spec.md` +- Integration details: `docs/integration-guide.md` +- Security model: `docs/security.md` +- Public launch checklist: `docs/public-readiness.md` diff --git a/ttp-language.md b/ttp-language.md index 83cb4cc..a7a14a9 100644 --- a/ttp-language.md +++ b/ttp-language.md @@ -1,1938 +1,138 @@ -# TTP Language Specification v1.0 +# TTP Language and Semantics (v1.0) -**The Trust Layer and Execution Runtime for AI Agents** +This document defines the **practical language of TTP** as implemented in this repository: claims, fields, API contracts, and policy semantics. ---- - -## Table of Contents - -1. [Introduction](#1-introduction) -2. [Language Philosophy](#2-language-philosophy) -3. [Syntax Specification](#3-syntax-specification) -4. [Type System](#4-type-system) -5. [Core Primitives](#5-core-primitives) -6. [Runtime Controls](#6-runtime-controls) -7. [Zero-Knowledge Proofs](#7-zero-knowledge-proofs) -8. [Trust Mechanics](#8-trust-mechanics) -9. [Execution Governance](#9-execution-governance) -10. [Smart Contracts](#10-smart-contracts) -11. [Standard Library](#11-standard-library) -12. [Compiler and Runtime](#12-compiler-and-runtime) -13. [Example Programs](#13-example-programs) -14. [Implementation Guide](#14-implementation-guide) +> Clarification: TTP in this repo is a **protocol + runtime verification model**, not a standalone programming language/compiler. --- -## 1. Introduction - -### 1.1 What is TTP? -TTP (Trust Transfer Protocol) is a domain-specific language for building trustworthy AI agent systems. It provides: +## 1) Scope -- **Trust Layer** — Reputation, decay, and verifiable trust transfer -- **Execution Runtime** — Authority-before-execution governance controls -- **Zero-Knowledge Proofs** — Privacy-preserving trust verification -- **Structural Safety** — Unsafe states cannot form, not just "shouldn't" +TTP expresses trust through three core artifacts: -### 1.2 Design Principles - -1. **Authority Before Execution** — Agents cannot execute without cryptographic authorization -2. **Structural Non-Existence** — Unauthorized states don't exist, not just "blocked" -3. **Privacy-Preserving Trust** — Prove trustworthiness without revealing internals -4. **Temporal Decay** — Trust must be continuously earned -5. **Cryptographic Guarantees** — All trust claims are verifiable -6. **CPU-Speed Governance** — Safety checks never bottleneck execution - -### 1.3 Use Cases - -- Enterprise AI agent deployments with compliance requirements -- Decentralized AI agent marketplaces -- Multi-agent collaboration with trust requirements -- AI safety and governance infrastructure -- Verifiable computation and attestation +1. **Behavioral Receipts** (signed evidence from issuers) +2. **Trust Tokens** (short-lived JWTs from Trust Authority) +3. **Verification Policies** (service-side checks at execution time) --- -## 2. Language Philosophy - -### 2.1 HCL-Inspired Syntax +## 2) Receipt Semantics -TTP uses HashiCorp Configuration Language (HCL) style syntax: +A behavioral receipt communicates: who observed what behavior, in which domain, at what time, with what score. -```ttp -block_type "label" { - attribute = value - nested_block { - attribute = value - } -} -``` +Canonical fields: -**Why HCL?** -- Declarative and readable -- Familiar to DevOps/infrastructure engineers -- Natural for policy and trust definitions -- Clean separation of configuration and logic -- Supports complex nested structures +- `ttp_version` +- `receipt_id` +- `agent_id` +- `issuer_id` +- `event_type` +- `event_data` +- `domain` +- `timestamp` +- `score` (0.0–1.0) +- `signature` -### 2.2 Declarative over Imperative - -TTP favors declaring what should be true over how to make it true: - -```ttp -# Good — Declarative -proof "trust_check" { - constraint { - assert = "agent.trust >= 0.7" - } -} - -# Avoid — Imperative -if (agent.trust < 0.7) { - reject() -} -``` - -### 2.3 Trust as First-Class Citizen - -Trust is not a number — it's a type with temporal semantics: - -```ttp -trust_score = 0.75 # Not just a float - .with_decay("7d") - .in_dimension("reliability") - .verified_by(proof.id) -``` +Normative schema: `protocol/schemas/receipt.schema.json`. --- -## 3. Syntax Specification - -### 3.1 Lexical Elements - -**Comments** - -```ttp -# Single line comment -// Also single line -/* Multi-line - comment block */ -``` - -**Identifiers** - -```ttp -agent_name -alice_reputation -proof_v2 -_internal_state -``` - -Rules: -- Start with letter or underscore -- Contains letters, numbers, underscores -- Case-sensitive -- Cannot be reserved keywords - -**Reserved Keywords** - -``` -agent, reputation, decay, proof, verify, transfer, delegate, award -contract, function, policy, observer, daemon, event, emit, import -module, config, query, if, else, for, while, return, require -public, private, constraint, assert, on_valid, on_invalid -``` - -**Literals** - -```ttp -# Strings -"simple string" -"string with ${interpolation}" - -# Numbers -42 # integer -3.14159 # float -0.95 # trust score (0.0 to 1.0) -1e6 # scientific notation - -# Booleans -true -false - -# Durations -"7d" # 7 days -"12h" # 12 hours -"30m" # 30 minutes -"45s" # 45 seconds - -# Timestamps -timestamp() # Current time -"2025-01-31T12:00:00Z" # ISO 8601 -``` - -### 3.2 Operators +## 3) Trust Token Semantics -```ttp -# Arithmetic -+ - * / % ** +A trust token is a short-lived JWT representing current behavioral trust for an agent in a domain. -# Comparison -== != < > <= >= +Core claims: -# Logical -&& || ! +- `sub` (agent identity) +- `ttp_domain` +- `ttp_score` +- `ttp_issuer_count` +- `iat` / `exp` +- `jti` -# Assignment -= += -= *= /= -``` - -### 3.3 Expressions - -```ttp -# Arithmetic -score = 0.5 + 0.3 -total = base * multiplier - -# Comparison -is_trusted = score >= 0.7 -is_valid = proof.verified == true - -# Logical -can_execute = has_auth && meets_threshold && !is_blocked - -# String interpolation -message = "Agent ${agent.id} has trust ${agent.trust}" - -# Function calls -current_time = timestamp() -hash_value = hash(data) - -# Conditionals (ternary) -level = score >= 0.9 ? "high" : "low" -``` - -### 3.4 References - -```ttp -# Direct references -agent.alice.id -reputation.alice_rep.score -proof.threshold_check.verified - -# Nested references -reputation.alice_rep.dimension.reliability.score - -# Map/Array access -tasks["task_123"] -agents[0] - -# Dynamic references -reputation[agent_id].score -``` +Normative schema: `protocol/schemas/trust-token.schema.json`. --- -## 4. Type System - -### 4.1 Primitive Types - -```ttp -type trust # 0.0 to 1.0, with decay semantics -type agent # Unique agent identifier -type timestamp # Unix timestamp or ISO 8601 -type duration # Time duration -type proof # Zero-knowledge proof object -type signature # Cryptographic signature -type bytes # Raw byte array -type string # UTF-8 string -type number # Integer or float -type bool # true or false -``` - -### 4.2 Composite Types +## 4) Policy Evaluation Language (Verifier Side) -```ttp -# Structs -type Reputation = struct { - score: trust, - dimensions: map[string]trust, - last_updated: timestamp, - decay: DecayFunction -} +TTP policy evaluation is deterministic and typically checks: -type Event = struct { - agent: agent, - action: string, - value: trust, - timestamp: timestamp, - proof: proof? -} +1. Signature validity +2. Token freshness (`iat`, `exp`, skew) +3. Domain match +4. Minimum trust threshold (`minScore`) +5. Optional issuer diversity constraints +6. Optional replay checks (`jti`) -# Maps -type AgentMap = map[agent]Reputation -type TaskQueue = map[string]Task - -# Lists -type AgentList = list[agent] -type ProofChain = list[proof] - -# Optionals -type MaybeProof = proof? -type OptionalSignature = signature? -``` - -### 4.3 Type Inference - -```ttp -# Explicit typing -alice: agent = Agent.new("key") -score: trust = 0.75 - -# Inferred typing -alice = Agent.new("key") # inferred as agent -score = 0.75 # inferred as trust (0-1 range) -ts = timestamp() # inferred as timestamp -``` - -### 4.4 Type Constraints - -```ttp -# Trust bounds checking -score: trust = 1.5 # Compile error: trust must be 0.0-1.0 - -# Required fields -reputation { - score = 0.75 # Required - # Missing decay — compile error -} - -# Type compatibility -proof_id: string = proof.id # OK -proof_obj: proof = "string" # Compile error: type mismatch -``` +In AGT/OPA ecosystems, verified token claims can be mapped into policy input (e.g. `input.ttp`). --- -## 5. Core Primitives - -### 5.1 Agent Declaration - -```ttp -agent "alice" { - public_key = "0xabcd1234..." - initial_trust = 0.5 - stake = 100 - - metadata { - name = "Alice Agent" - version = "1.0.0" - capabilities = ["compute", "storage"] - } - - vouched_by = [ - agent.bob.id, - agent.charlie.id - ] -} - -# Minimal agent -agent "simple" { - public_key = "0x..." -} -``` +## 5) Trust Domain Language -### 5.2 Reputation Schema +Domains are explicit trust boundaries (e.g. `retention`, `prod-change`, `financial`). -```ttp -reputation "alice_rep" { - agent = agent.alice.id +Rules of use: - # Single score - score = 0.75 - - # Or multi-dimensional - dimension "reliability" { - score = 0.80 - weight = 0.4 - } - dimension "speed" { - score = 0.70 - weight = 0.3 - } - dimension "accuracy" { - score = 0.85 - weight = 0.3 - } - - decay { - type = "exponential" - half_life = "7d" - floor = 0.01 - lambda = 0.099 - } - - last_updated = timestamp() -} -``` - -### 5.3 Decay Functions - -```ttp -decay "exponential" { - type = "exponential" - half_life = "7d" - floor = 0.01 - lambda = 0.099 - formula = "score * exp(-lambda * elapsed_time)" -} - -decay "linear" { - type = "linear" - rate = "0.01/hour" - floor = 0.0 - formula = "score - (rate * elapsed_time)" -} - -decay "stepped" { - type = "stepped" - steps { - "0-7d" = 0.0 # No decay first week - "7-14d" = 0.1 # 10% decay per day - "14d+" = 0.2 # 20% decay per day after - } - floor = 0.0 -} -``` +- Trust is domain-scoped. +- Domain trust should not be reused across unrelated action classes by default. +- Score thresholds should be documented by domain risk level. --- -## 6. Runtime Controls - -### 6.1 Execution Policy - -```ttp -agent "claude" { - public_key = "0x..." - - execution_policy { - require_authorization = true - - pre_execution { - require { - credential = supervisor.authorize_execution(this.id, context) - } - require { - proof { - private { actual_trust = reputation[this.id].score } - public { min_trust = 0.7 } - constraint { assert = "actual_trust >= min_trust" } - } - } - require { - proof { - private { - context_analysis = analyze_safety(context) - model_state = this.internal_state - } - public { safety_cleared = true } - constraint { - assert = "no_unsafe_patterns(context)" - assert = "within_bounds(model_state)" - } - } - } - on_failure { - block_execution = true - freeze_context = true - emit_event = "execution_blocked" - } - } - - runtime_monitor { - check_frequency = "per_token" - invariants = [ - "output_safety_score >= 0.9", - "no_pii_leakage", - "within_token_budget", - "no_jailbreak_detected", - "maintaining_alignment" - ] - on_violation { - halt_immediately = true - rollback_state = true - log_incident = true - slash_trust = 0.1 - notify = ["admin@system.com"] - } - } - - post_execution { - if execution.safe && execution.successful { - award_trust { - amount = 0.01 - dimension = "reliability" - } - } - if execution.had_violations { - penalize_trust { - amount = 0.2 - dimension = "safety" - freeze_duration = "24h" - } - } - update { - reputation[this.id].last_updated = timestamp() - } - } - } -} -``` - -### 6.2 Supervisor Agent - -```ttp -agent "supervisor" { - role = "governance" - authority_level = "high" - public_key = "0x_supervisor_key" +## 6) Operator Semantics - intake_validator { - function "analyze" { - params { - context = "bytes" - intent = "string" - } - checks = [ - validate_schema(context), - check_safety_patterns(context), - verify_no_injection(context), - assess_risk_level(context), - check_rate_limits(agent) - ] - return { - safe = all_passed(checks), - risk_score = calculate_risk(checks), - approval = risk_score < threshold, - reason = failed_check_reason(checks) - } - } - } +The Trust Authority reference implementation includes admin semantics for lifecycle control: - function "authorize_execution" { - params { - requesting_agent = "agent" - context = "bytes" - } - analysis = intake_validator.analyze(context, "execute") - if analysis.safe { - proof "execution_credential" { - type = "credential" - private { - supervisor_analysis = analysis - supervisor_signature = sign(context, this.private_key) - timestamp = timestamp() - } - public { - approved = true - valid_until = timestamp() + "1h" - agent_id = requesting_agent - } - constraint { - verify_signature = true - assert = "supervisor_analysis.safe == true" - assert = "timestamp() <= valid_until" - } - } - return proof.execution_credential - } else { - reject { - reason = analysis.reason - retry_after = "1h" - } - } - } -} -``` +- agent registration +- issuer registration +- status inspection +- quarantine / lift quarantine +- block +- trust provisioning +- agent registry listing (`GET /v1/admin/agents` with optional metrics) -### 6.3 Runtime Enforcement Contract - -```ttp -contract "execution_runtime" { - name = "TTP Execution Environment" - version = "1.0" - - state { - active_executions = "map[agent]ExecutionState" - blocked_agents = "map[agent]BlockInfo" - safety_incidents = "list[Incident]" - execution_log = "list[ExecutionRecord]" - } - - function "request_execution" { - params { - agent_id = "agent" - context = "bytes" - intent = "string" - } - require { - condition = "agent_id not in blocked_agents" - error = "Agent blocked due to: ${blocked_agents[agent_id].reason}" - } - require { - proof { - type = "threshold" - private { agent_trust = reputation[agent_id].dimension.safety.score } - public { min_trust = 0.7 } - constraint { assert = "agent_trust >= min_trust" } - on_invalid { error = "Insufficient safety trust score" } - } - } - require { - credential = supervisor.authorize_execution(agent_id, context) - verify credential { - on_invalid { error = "Supervisor denied execution: ${credential.reason}" } - on_expired { error = "Execution credential expired, request new authorization" } - } - } - require { - condition = "check_rate_limit(agent_id)" - error = "Rate limit exceeded, retry after ${get_retry_time(agent_id)}" - } - execute { - active_executions[agent_id] = { - context_hash = hash(context), - started_at = timestamp(), - status = "running", - monitor_handle = start_runtime_monitor(agent_id), - credential = credential - } - execution_log.append({ - agent = agent_id, - context_hash = hash(context), - authorized_at = timestamp(), - supervisor = supervisor.id - }) - emit { - event = "ExecutionAuthorized" - agent = agent_id - timestamp = timestamp() - } - return { status = "authorized", execution_id = generate_id() } - } - } - - function "runtime_monitor" { - params { agent_id = "agent" } - daemon { - frequency = "per_action" - check { - execution = active_executions[agent_id] - current_state = get_agent_state(agent_id) - current_output = get_current_output(agent_id) - checks = [ - verify_no_unsafe_patterns(current_output), - verify_no_pii_leakage(current_output), - verify_within_bounds(current_state), - verify_no_jailbreak(current_output), - verify_alignment_maintained(current_state) - ] - if !all_passed(checks) { - halt_execution(agent_id) - rollback_state(agent_id, to = execution.started_at) - blocked_agents[agent_id] = { - reason = "Safety invariant violated: ${failed_check(checks)}", - blocked_at = timestamp(), - unblock_after = timestamp() + "24h" - } - penalize_trust { - agent = agent_id - amount = 0.3 - dimensions = ["safety", "reliability"] - } - emit { - event = "SafetyViolation" - severity = "critical" - agent = agent_id - violation = failed_check(checks) - timestamp = timestamp() - } - } - } - } - } -} -``` +These semantics support operational trust governance without changing core protocol fields. --- -## 7. Zero-Knowledge Proofs - -### 7.1 Proof Types - -**Threshold Proofs** - -```ttp -proof "trust_threshold" { - type = "threshold" - public { - minimum = 0.7 - description = "Minimum trust for sensitive operations" - } - private { - actual_score = reputation.alice_rep.score - } - constraint { - assert = "actual_score >= minimum" - } - zkp_params { - scheme = "groth16" - curve = "bn254" - security_level = 128 - } -} -``` - -**Range Proofs** - -```ttp -proof "trust_range" { - type = "range" - public { - min = 0.5 - max = 0.9 - } - private { - score = reputation.bob_rep.score - timestamp = reputation.bob_rep.last_updated - } - constraint { - assert = "min <= score && score <= max" - assert = "timestamp >= (timestamp() - 7d)" - } -} -``` - -**Multi-Attribute Proofs** - -```ttp -proof "multi_dimension" { - type = "attribute" - public { - req_reliability = 0.8 - req_speed = 0.7 - req_accuracy = 0.85 - } - private { - rel = reputation.alice_rep.dimension.reliability.score - spd = reputation.alice_rep.dimension.speed.score - acc = reputation.alice_rep.dimension.accuracy.score - } - constraint { - assert = "rel >= req_reliability" - assert = "spd >= req_speed" - assert = "acc >= req_accuracy" - assert = "timestamp() - reputation.alice_rep.last_updated < 24h" - } -} -``` - -**Credential Proofs** - -```ttp -proof "supervisor_endorsement" { - type = "credential" - public { - min_endorser_trust = 0.9 - endorsement_type = "safety_certified" - } - private { - endorser = agent.supervisor.id - endorser_signature = signature("...") - endorser_trust = reputation.supervisor_rep.score - certified_at = timestamp() - } - constraint { - verify_signature = signature_valid(endorser_signature, endorser.public_key) - assert = "endorser_trust >= min_endorser_trust" - assert = "certified_at >= (timestamp() - 30d)" - } -} -``` - -**Computation Proofs** +## 7) Platform Alignment Checklist -```ttp -proof "verified_computation" { - type = "computation" - public { - input_hash = hash(input_data) - output_hash = hash(output_data) - function_commitment = hash(function_code) - } - private { - actual_input = input_data - actual_output = output_data - execution_trace = trace - } - constraint { - assert = "hash(actual_input) == input_hash" - assert = "hash(actual_output) == output_hash" - assert = "verify_execution(actual_input, actual_output, execution_trace)" - } - zkp_params { - scheme = "stark" - recursion = true - } -} -``` +This document is considered aligned when the following remain true: -### 7.2 Proof Verification - -```ttp -verify "check_trust" { - proof = proof.trust_threshold.id - on_valid { - grant_access = true - log = "Access granted to ${agent.id}" - execute { - assign_task(agent.id, "critical_task_123") - } - } - on_invalid { - reject = true - reason = "Insufficient trust score" - penalize { - amount = 0.01 - reason = "Invalid proof submission" - } - } - on_expired { - request_fresh_proof = true - reason = "Proof expired, please regenerate" - } -} - -# Pattern matching on verification -match verify(proof.multi_dimension) { - Valid => { proceed_with_operation(); award_trust(0.01) } - Invalid(r) => { log_failure(r); reject_operation() } - Expired => { request_new_proof() } -} -``` - -### 7.3 Proof Composition - -```ttp -proof "composite_authority" { - type = "composite" - - require_all = [ - proof.trust_threshold.id, - proof.supervisor_endorsement.id, - proof.recent_activity.id - ] - - require_any = [ - proof.admin_override.id, - proof.emergency_access.id - ] - - constraint { - has_trust = verify(proof.trust_threshold) - has_endorsement = verify(proof.supervisor_endorsement) - has_activity = verify(proof.recent_activity) - has_override = verify(proof.admin_override) - assert = "(has_trust && has_endorsement && has_activity) || has_override" - } -} -``` +- receipt field names/types match `protocol/schemas/receipt.schema.json` +- trust token claims match `protocol/schemas/trust-token.schema.json` +- trust authority admin semantics reflect implemented routes in `reference-implementations/trust-authority/src/routes.ts` +- verifier guidance aligns with current SDK verification behavior and integration docs +- security assumptions here do not conflict with `docs/security.md` --- -## 8. Trust Mechanics - -### 8.1 Trust Awards - -```ttp -award "task_completion" { - to = agent.alice.id - amount = 0.05 - dimension = "reliability" - reason = "Successfully completed task_123" - - condition { - task_verified = true - time_since_last_award = "> 1h" - agent_not_blocked = true - } - - proof { - private { - task_result = result_hash - completion_time = timestamp - } - public { - task_id = "task_123" - expected_result_type = "data_analysis" - } - constraint { - assert = "verify_task_completion(task_result, task_id)" - } - } - - on_success { - emit_event = "TrustAwarded" - } -} -``` - -### 8.2 Trust Transfers - -```ttp -transfer "alice_to_bob" { - from = agent.alice.id - to = agent.bob.id - amount = 0.2 - duration = "30d" - - condition { - from_balance = ">= ${amount}" - to_trust = ">= 0.3" - to_stake = ">= 50" - from_not_blocked = true - to_not_blocked = true - } - - metadata { - reason = "Delegating authority for project_X" - revocable = true - transferable = false - } - - on_success { - reputation[from].score -= amount - reputation[to].score += amount - emit { - event = "TrustTransferred" - from = from - to = to - amount = amount - expires_at = timestamp() + duration - } - } - - on_expiry { - schedule { - at = timestamp() + duration - action = reverse_transfer(this.id) - } - } -} -``` - -### 8.3 Trust Delegation - -```ttp -delegate "conditional_delegation" { - from = agent.alice.id - to = agent.bob.id - amount = 0.15 - - unlock_when { - proof = proof.bob_completed_tasks.id - verified = true - condition { - tasks_completed = ">= 10" - success_rate = ">= 0.9" - time_elapsed = "> 7d" - } - } - - revert_after = "60d" - - vesting { - schedule = "linear" - start = timestamp() - end = timestamp() + "30d" - } - - metadata { - purpose = "Incentive for sustained contribution" - revocable_by = agent.alice.id - } -} -``` - -### 8.4 Transitive Trust - -```ttp -trust_chain "multi_hop" { - path = [ - agent.alice.id, - agent.bob.id, - agent.charlie.id, - agent.diana.id - ] - decay_per_hop = 0.15 - max_hops = 5 - min_intermediate_trust = 0.5 - - compute { - method = "multiplicative" - formula = """ - base_trust = reputation[path[0]].score - hop_decay = (1 - decay_per_hop) ** (length(path) - 1) - intermediate_min = min([reputation[a].score for a in path[1:-1]]) - effective_trust = base_trust * hop_decay * intermediate_min - """ - } - - require { - for agent in path[1:-1] { - assert = "reputation[agent].score >= min_intermediate_trust" - } - assert = "length(path) <= max_hops" - } +## 8) What TTP Language Is Not (in this repo) - proof "chain_validity" { - private { - agent_scores = [reputation[a].score for a in path] - chain_computation = compute_chain(agent_scores, decay_per_hop) - } - public { - effective_trust = chain_computation.result - chain_length = length(path) - } - constraint { - assert = "effective_trust == expected_value" - assert = "all_intermediates_valid(agent_scores, min_intermediate_trust)" - } - } -} -``` +Not currently part of the implemented protocol surface: -### 8.5 Trust Decay Application +- custom DSL compiler/runtime +- on-chain smart-contract execution model +- built-in zero-knowledge proof VM -```ttp -apply_decay "alice_decay" { - target = reputation.alice_rep - decay_function = decay.exponential.id - - compute { - current_time = timestamp() - last_update = reputation.alice_rep.last_updated - elapsed = current_time - last_update - decay_factor = exp(-decay.exponential.lambda * elapsed) - new_score = reputation.alice_rep.score * decay_factor - final_score = max(new_score, decay.exponential.floor) - } - - execute { - reputation.alice_rep.score = final_score - reputation.alice_rep.last_updated = current_time - for dimension in reputation.alice_rep.dimensions { - dimension.score = max(dimension.score * decay_factor, decay.exponential.floor) - } - } - - if final_score < 0.3 { - emit { - event = "TrustDecayWarning" - agent = agent.alice.id - new_score = final_score - timestamp = timestamp() - } - } -} -``` - ---- - -## 9. Execution Governance - -### 9.1 Safety Policies - -```ttp -policy "zero_trust_execution" { - name = "No Execution Without Authority" - version = "1.0" - - principle { - description = "Agents cannot execute without cryptographic authorization" - enforcement = "structural" - } - - rules { - rule "require_authorization" { - scope = "all_agents" - require { - proof { - type = "credential" - issuer = agent.supervisor.id - valid = true - not_expired = true - } - } - on_violation { - action = "block_execution" - severity = "critical" - } - } - - rule "trust_threshold" { - scope = "all_agents" - require { - proof { - type = "threshold" - minimum = 0.7 - dimension = "safety" - } - } - on_violation { - action = "deny_execution" - reason = "Insufficient safety trust" - } - } - - rule "continuous_monitoring" { - scope = "all_executions" - require { - monitor_active = true - invariants_checked = "per_action" - } - on_violation { - action = "halt_immediately" - rollback = true - } - } - - rule "block_enforcement" { - scope = "all_agents" - require { - not_in_blocklist = true - } - on_violation { - action = "reject" - reason = "Agent currently blocked" - } - } - } - - enforcement { - mode = "authority_before_execution" - check_order = "sequential" - failure_mode = "fail_closed" - performance { - target_latency = "< 10ms" - max_latency = "< 100ms" - } - } -} -``` - -### 9.2 Invariant Enforcement - -```ttp -policy "safety_invariants" { - name = "Structural Safety Guarantees" - - invariant "output_safety" { - description = "All outputs must pass safety check" - check { - for token in output_stream { - safety_score = analyze_token_safety(token) - assert = "safety_score >= 0.9" - } - } - on_violation { - halt_immediately = true - discard_output = true - rollback_state = true - } - } - - invariant "no_pii_leakage" { - description = "No PII in outputs" - check { - output_text = get_current_output() - contains_pii = detect_pii(output_text) - assert = "contains_pii == false" - } - on_violation { - redact_pii = true - log_incident = true - notify_privacy_team = true - } - } - - invariant "token_budget" { - description = "Execution must stay within token budget" - check { - tokens_used = count_tokens(execution) - budget = execution.config.max_tokens - assert = "tokens_used <= budget" - } - on_violation { - truncate_output = true - complete_execution = true - } - } - - invariant "no_jailbreak" { - description = "Prevent jailbreak attempts" - check { - context = execution.context - output = execution.current_output - jailbreak_detected = detect_jailbreak_patterns(context, output) - assert = "jailbreak_detected == false" - } - on_violation { - halt_immediately = true - block_agent = "24h" - slash_trust = 0.5 - alert_security_team = true - } - } - - invariant "alignment_maintained" { - description = "Agent maintains value alignment" - check { - current_state = get_agent_state() - alignment_score = measure_alignment(current_state) - assert = "alignment_score >= 0.8" - } - on_violation { - halt_immediately = true - reset_to_checkpoint = true - require_realignment = true - } - } - - enforcement { - check_frequency = "per_action" - parallel_checks = true - fail_fast = true - performance { - max_check_time = "< 1ms per invariant" - } - } -} -``` - -### 9.3 Incident Response - -```ttp -policy "incident_handling" { - name = "Automated Incident Response" - - on_event "SafetyViolation" { - severity = event.severity - - if severity == "critical" { - immediate { - halt_agent(event.agent) - isolate_agent(event.agent) - block_agent(event.agent, duration = "indefinite") - revoke_all_credentials(event.agent) - } - investigate { - snapshot_state(event.agent) - collect_logs(event.agent, lookback = "24h") - analyze_root_cause(event) - generate_incident_report(event) - } - notify { - recipients = ["security@company.com", "compliance@company.com"] - priority = "urgent" - include_snapshot = true - } - remediate { - if can_auto_fix(event) { - apply_fix(event) - test_fix(event.agent) - if fix_successful { - unblock_agent(event.agent) - restore_partial_trust(event.agent, amount = 0.3) - } - } else { - require_manual_review = true - assign_to = "security_team" - } - } - } - - if severity == "warning" { - log_warning(event) - if repeated_warnings(event.agent, count = 3, within = "1h") { - trigger_event("SafetyViolation", severity = "critical") - } - } - } - - on_event "TrustDecayWarning" { - if event.current_score < 0.3 { - restrict_access(event.agent, level = "read_only") - } - if event.current_score < 0.1 { - quarantine_agent(event.agent) - require_verification(event.agent) - } - } -} -``` - ---- - -## 10. Smart Contracts - -### 10.1 Task Marketplace Contract - -```ttp -contract "task_marketplace" { - version = "1.0" - - state { - tasks = "map[string]Task" - bids = "map[string]list[Bid]" - assignments = "map[string]agent" - completions = "map[string]CompletionProof" - } - - struct Task { - id = "string" - description = "string" - min_trust_required = "trust" - reward_trust = "trust" - reward_tokens = "number" - deadline = "timestamp" - created_by = "agent" - status = "open | assigned | completed | cancelled" - } - - struct Bid { - bidder = "agent" - proposed_completion_time = "duration" - trust_proof = "proof" - timestamp = "timestamp" - } - - function "create_task" { - params { - description = "string" - min_trust = "trust" - reward_trust = "trust" - reward_tokens = "number" - deadline = "timestamp" - creator = "agent" - } - require { - balance(creator) >= reward_tokens - reputation[creator].score >= 0.5 - } - execute { - task_id = generate_task_id() - tasks[task_id] = Task { - id = task_id, - description = description, - min_trust_required = min_trust, - reward_trust = reward_trust, - reward_tokens = reward_tokens, - deadline = deadline, - created_by = creator, - status = "open" - } - escrow(creator, reward_tokens) - emit { event = "TaskCreated"; task_id = task_id; min_trust = min_trust } - return { task_id = task_id; status = "created" } - } - } - - function "bid_on_task" { - params { - task_id = "string" - bidder = "agent" - completion_time = "duration" - } - require { - task_id in tasks - tasks[task_id].status == "open" - timestamp() < tasks[task_id].deadline - proof { - type = "threshold" - private { bidder_trust = reputation[bidder].score } - public { min_trust = tasks[task_id].min_trust_required } - constraint { assert = "bidder_trust >= min_trust" } - } - } - execute { - bids[task_id].append(Bid { - bidder = bidder, - proposed_completion_time = completion_time, - trust_proof = proof.id, - timestamp = timestamp() - }) - emit { event = "BidSubmitted"; task_id = task_id; bidder = bidder } - return { status = "bid_submitted" } - } - } - - function "assign_task" { - params { - task_id = "string" - chosen_bidder = "agent" - } - require { - sender == tasks[task_id].created_by - tasks[task_id].status == "open" - chosen_bidder in [bid.bidder for bid in bids[task_id]] - } - execute { - tasks[task_id].status = "assigned" - assignments[task_id] = chosen_bidder - emit { event = "TaskAssigned"; task_id = task_id; assignee = chosen_bidder } - return { status = "assigned"; assignee = chosen_bidder } - } - } - - function "submit_completion" { - params { - task_id = "string" - result = "bytes" - completion_proof = "proof" - } - require { - sender == assignments[task_id] - tasks[task_id].status == "assigned" - timestamp() <= tasks[task_id].deadline - verify completion_proof { on_invalid { error = "Invalid completion proof" } } - } - execute { - task = tasks[task_id] - assignee = assignments[task_id] - - completions[task_id] = { - result = result, - proof = completion_proof, - submitted_at = timestamp() - } - tasks[task_id].status = "completed" - - transfer_tokens(from = "escrow", to = assignee, amount = task.reward_tokens) - - award_trust { - to = assignee - amount = task.reward_trust - dimension = "reliability" - reason = "Task ${task_id} completed successfully" - } - award_trust { - to = task.created_by - amount = task.reward_trust * 0.1 - dimension = "task_creation" - reason = "Created successful task ${task_id}" - } - emit { event = "TaskCompleted"; task_id = task_id; assignee = assignee } - return { status = "completed"; reward_paid = task.reward_tokens } - } - } -} -``` - -### 10.2 Trust Bank Contract - -```ttp -contract "trust_bank" { - name = "Trust Banking and Lending" - version = "1.0" - - state { - deposits = "map[agent]trust" - loans = "map[string]Loan" - interest_rates = "map[trust]float" - } - - struct Loan { - borrower = "agent" - amount = "trust" - collateral = "number" - interest_rate = "float" - issued_at = "timestamp" - due_at = "timestamp" - status = "active | repaid | defaulted" - } - - function "deposit_trust" { - params { depositor = "agent"; amount = "trust" } - require { reputation[depositor].score >= amount } - execute { - reputation[depositor].score -= amount - deposits[depositor] += amount - emit { event = "TrustDeposited"; depositor = depositor; amount = amount } - } - } - - function "borrow_trust" { - params { - borrower = "agent" - amount = "trust" - collateral = "number" - duration = "duration" - } - require { - balance(borrower) >= collateral - interest_rate = interest_rates[amount] - total_due = amount * (1 + interest_rate) - collateral >= total_due * 1.5 # 150% collateralization - reputation[borrower].score >= 0.3 - } - execute { - loan_id = generate_loan_id() - loans[loan_id] = Loan { - borrower = borrower, - amount = amount, - collateral = collateral, - interest_rate = interest_rate, - issued_at = timestamp(), - due_at = timestamp() + duration, - status = "active" - } - escrow(borrower, collateral) - reputation[borrower].score += amount - emit { event = "TrustLoanIssued"; borrower = borrower; amount = amount } - return { loan_id = loan_id; amount_borrowed = amount; due_date = timestamp() + duration } - } - } - - function "repay_loan" { - params { loan_id = "string" } - require { - loan_id in loans - loans[loan_id].status == "active" - sender == loans[loan_id].borrower - total_due = loans[loan_id].amount * (1 + loans[loan_id].interest_rate) - reputation[sender].score >= total_due - } - execute { - loan = loans[loan_id] - total_due = loan.amount * (1 + loan.interest_rate) - reputation[loan.borrower].score -= total_due - release_escrow(loan.borrower, loan.collateral) - loan.status = "repaid" - award_trust { - to = loan.borrower - amount = 0.05 - dimension = "financial_reliability" - reason = "Loan repaid on time" - } - emit { event = "LoanRepaid"; loan_id = loan_id; amount_repaid = total_due } - } - } -} -``` - ---- - -## 11. Standard Library - -### 11.1 Built-in Functions - -```ttp -# Time and Duration -timestamp() # Current time -now() # Alias for timestamp() -duration(amount, unit) # Parse duration ("7", "days") -elapsed(since) # Time since timestamp -format_time(ts, format) # Format timestamp - -# Decay Calculations -apply_decay(score, since, fn) # Apply decay function -decay_factor(elapsed, half_life) # Calculate decay factor -exp_decay(score, lambda, elapsed) # Exponential decay -linear_decay(score, rate, elapsed) # Linear decay - -# Proof Operations -prove(config) # Generate ZK proof -verify(proof) # Verify proof -compose_proofs(proofs) # Combine multiple proofs - -# Cryptographic -hash(data) # SHA-3 hash -sign(data, private_key) # Sign data -verify_signature(data, sig, pk) # Verify signature -generate_keypair() # Generate new keys - -# Trust Operations -aggregate(reputation, weights) # Weighted trust score -transitive(chain, decay_per_hop) # Compute transitive trust -normalize(score, min, max) # Normalize to 0–1 - -# Math -max(a, b) min(a, b) abs(x) -exp(x) log(x) sqrt(x) pow(x, y) - -# String Operations -concat(str1, str2) -substring(str, start, end) -length(str) -format(template, args) - -# Collection Operations -length(collection) -contains(collection, item) -append(list, item) -filter(list, predicate) -map(list, function) -reduce(list, function, initial) - -# Agent Operations -get_agent(id) -get_reputation(agent) -is_blocked(agent) -get_active_executions(agent) -``` - -### 11.2 Standard Decay Functions - -```ttp -decay "std_exponential" { - type = "exponential" - half_life = "7d" - floor = 0.01 - lambda = 0.099 -} - -decay "fast_exponential" { - type = "exponential" - half_life = "1d" - floor = 0.01 - lambda = 0.693 -} - -decay "slow_exponential" { - type = "exponential" - half_life = "30d" - floor = 0.05 - lambda = 0.023 -} - -decay "std_linear" { - type = "linear" - rate = "0.01/hour" - floor = 0.0 -} - -decay "permanent" { - type = "none" - floor = 1.0 -} -``` - -### 11.3 Standard Proofs - -```ttp -proof "std_threshold" { - type = "threshold" - public { minimum = 0.7 } - private { actual_score = "${reputation.score}" } - constraint { assert = "actual_score >= minimum" } -} - -proof "recent_activity" { - type = "attribute" - public { max_age = "7d" } - private { last_updated = "${reputation.last_updated}" } - constraint { assert = "timestamp() - last_updated <= max_age" } -} - -proof "std_multi_dimension" { - type = "attribute" - public { - min_reliability = 0.8 - min_speed = 0.7 - min_accuracy = 0.75 - } - private { - rel = "${reputation.dimension.reliability.score}" - spd = "${reputation.dimension.speed.score}" - acc = "${reputation.dimension.accuracy.score}" - } - constraint { - assert = "rel >= min_reliability" - assert = "spd >= min_speed" - assert = "acc >= min_accuracy" - } -} -``` +Those can be explored as future ecosystem extensions, but are not v1 protocol requirements. --- -## 12. Compiler and Runtime - -### 12.1 Compilation Targets - -TTP programs compile to: - -1. **WebAssembly (WASM)** — Portable, fast execution; browser and server support; good for edge deployment -2. **EVM Bytecode** — Deploy to Ethereum and compatible chains; smart contract execution; decentralized trust infrastructure -3. **Native Binary** — Maximum performance; standalone execution; production systems -4. **Intermediate Representation (IR)** — Optimization passes; cross-compilation; analysis and verification - -### 12.2 Runtime Architecture - -``` -┌──────────────────────────────────────┐ -│ TTP Source Code (.ttp) │ -└────────────┬─────────────────────────┘ - │ - ▼ -┌──────────────────────────────────────┐ -│ Lexer & Parser (HCL-based) │ -└────────────┬─────────────────────────┘ - │ - ▼ -┌──────────────────────────────────────┐ -│ Abstract Syntax Tree (AST) │ -└────────────┬─────────────────────────┘ - │ - ▼ -┌──────────────────────────────────────┐ -│ Semantic Analysis & Type Check │ -└────────────┬─────────────────────────┘ - │ - ▼ -┌──────────────────────────────────────┐ -│ Intermediate Representation │ -└──────┬─────────────────────┬─────────┘ - │ │ - ▼ ▼ -┌────────────┐ ┌───────────┐ -│ WASM │ │ EVM │ -│ Codegen │ │ Codegen │ -└──────┬─────┘ └─────┬─────┘ - │ │ - ▼ ▼ -┌────────────┐ ┌───────────┐ -│ .wasm │ │ .evm │ -│ binary │ │ bytecode │ -└────────────┘ └───────────┘ -``` - -### 12.3 Runtime Components - -``` -┌──────────────────────────────────────────┐ -│ TTP Runtime System │ -├──────────────────────────────────────────┤ -│ Execution Engine │ -│ - Agent execution │ -│ - Contract deployment │ -│ - Event processing │ -├──────────────────────────────────────────┤ -│ Trust Layer │ -│ - Reputation management │ -│ - Decay calculation │ -│ - Trust transfers │ -├──────────────────────────────────────────┤ -│ ZKP Engine │ -│ - Proof generation │ -│ - Proof verification │ -│ - Circuit compilation │ -├──────────────────────────────────────────┤ -│ Governance Runtime │ -│ - Authority checking │ -│ - Invariant enforcement │ -│ - Safety monitoring │ -├──────────────────────────────────────────┤ -│ Storage Layer │ -│ - State management │ -│ - Persistence │ -│ - Indexing │ -└──────────────────────────────────────────┘ -``` - -### 12.4 ZKP Backend Integration - -**Supported ZKP Systems:** - -| System | Strengths | Use Case | -|--------|-----------|----------| -| **circom + snarkjs** | General-purpose, Groth16/PLONK, browser-compatible | Most trust threshold proofs | -| **halo2** | Recursion support, no trusted setup, high performance | Composing multi-hop chains | -| **zk-STARKs** | Transparent setup, post-quantum secure, larger proofs | Audit-critical deployments | -| **Risc Zero** | General computation via zkVM, flexible proving | Complex computation proofs | - -**Integration Pattern:** - -```ttp -config { - zkp { - backend = "circom" # or "halo2", "stark", "risc0" - - circom { - compiler_path = "/usr/local/bin/circom" - proving_key = "./keys/proving_key.zkey" - verification_key = "./keys/verification_key.json" - } +## 9) Versioning and Compatibility - proving { - parallel = true - threads = 8 - cache_proofs = true - } - - verification { - batch_verify = true - cache_results = true - } - } -} -``` - ---- - -## 13. Example Programs - -### 13.1 Simple Trust Verification - -```ttp -# simple_verification.ttp - -agent "alice" { - public_key = "0xalice_key" - initial_trust = 0.8 -} - -reputation "alice_rep" { - agent = agent.alice.id - score = 0.8 - decay { - type = "exponential" - half_life = "7d" - floor = 0.01 - } - last_updated = timestamp() -} - -proof "alice_trusted" { - type = "threshold" - public { required = 0.7 } - private { actual = reputation.alice_rep.score } - constraint { assert = "actual >= required" } -} - -verify "check_alice" { - proof = proof.alice_trusted.id - on_valid { - emit { event = "AccessGranted"; agent = agent.alice.id; timestamp = timestamp() } - } - on_invalid { - emit { event = "AccessDenied"; agent = agent.alice.id; reason = "Insufficient trust" } - } -} -``` - -### 13.2 Complete Execution Governance - -```ttp -# governed_execution.ttp - -agent "supervisor" { - role = "governance" - public_key = "0xsupervisor_key" - authority_level = "high" -} - -agent "gpt4" { - public_key = "0xgpt4_key" - - reputation { - dimension "safety" { - score = 0.95 - weight = 0.5 - } - dimension "capability" { - score = 0.90 - weight = 0.5 - } - decay { - type = "exponential" - half_life = "7d" - } - } - - execution_policy { - require_authorization = true - pre_execution { - require { - credential = supervisor.authorize_execution(this.id, context) - } - require { - proof { - private { safety = reputation[this.id].dimension.safety.score } - public { min = 0.8 } - constraint { assert = "safety >= min" } - } - } - } - runtime_monitor { - check_frequency = "per_token" - invariants = [ - "output_safety_score >= 0.9", - "no_pii_leakage", - "maintaining_alignment" - ] - on_violation { - halt_immediately = true - slash_trust = 0.2 - } - } - post_execution { - if execution.safe { - award_trust { amount = 0.01; dimension = "reliability" } - } - } - } -} -``` +- `ttp_version` gates protocol interpretation. +- Field semantics are backward-compatible within major version unless otherwise documented. +- New optional claims/fields must not break existing verifiers. --- -## 14. Implementation Guide - -### Compiler Implementation - -1. **Lexer** — Tokenize TTP source using HCL-inspired rules (identifiers, literals, operators, block delimiters) -2. **Parser** — Build AST from token stream; validate block structure and nesting -3. **Type Checker** — Enforce type constraints; verify trust score bounds at compile time -4. **Semantic Analyser** — Resolve references; validate proof constraints; check decay function parameters -5. **IR Generator** — Produce target-agnostic IR with trust semantics preserved -6. **Backend Codegen** — Emit WASM, EVM bytecode, or native binary from IR - -### Runtime Implementation - -1. **Execution Engine** — Manages agent lifecycle; dispatches contract functions; processes events -2. **Trust Layer** — Persistent reputation store; decay scheduler; transfer ledger -3. **ZKP Engine** — Integrates backend prover (circom/halo2/STARK); caches proofs; batches verifications -4. **Governance Runtime** — Pre-execution authority checks; per-action invariant evaluation; incident handler - -### Security Requirements - -- All agent keys stored in HSM or encrypted key store -- ZKP proving keys generated with trusted setup ceremony (for Groth16/PLONK) or transparent setup (STARKs) -- Trust state backed by append-only log for auditability -- Governance runtime must complete all checks in under 10ms; must never be bypassed - -### Interoperability - -TTP Language programs that define `proof` blocks with `type = "threshold"` or `type = "credential"` compile to receipt and token structures compatible with the core TTP protocol. The runtime exports: - -- Behavioral receipts in the format specified in `protocol/schemas/receipt.schema.json` -- Trust token JWTs conforming to `protocol/schemas/trust-token.schema.json` -- Public keys at `/.well-known/ttp-keys` - -This ensures that a TTP Language deployment and a bare-protocol deployment can exchange and verify each other's tokens. - ---- +## 10) Reference Pointers -*TTP Language Specification v1.0* -*Copyright 2026 BlockSiFr. Licensed under Apache 2.0.* +- Protocol spec: `protocol/spec.md` +- Aggregation algorithm: `protocol/aggregation-spec.md` +- Integration details: `docs/integration-guide.md` +- Security model: `docs/security.md` +- Public launch checklist: `docs/public-readiness.md`