Help us shape the future of Go! Take the 2026 Go Developer Survey

pidl

package module
v0.10.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 27, 2026 License: MIT Imports: 23 Imported by: 1

README

PIDL

Go CI Go Lint Go SAST Docs Docs Visualization License

Protocol Interaction Description Language - A JSON-based DSL for describing protocol choreography that compiles to diagrams.

PIDL models protocols as directed interaction graphs between entities, enabling generation of sequence diagrams, data flow diagrams, and other visualizations. It's designed for protocols where the primary concern is "who talks to whom, in what order" rather than message schemas or transport details.

Features

  • 📋 JSON-based DSL for describing protocol flows
  • 🗂️ Scenarios: one file holds a protocol's roles and an ordered list of journeys, with shared fragments drawn as labeled boxes
  • 🔢 Consistent ordering: roles, scenarios and steps follow the file's order in every diagram, table and outline
  • 📑 Overview outputs: roles-by-scenario matrix, token table, and an ordered outline for guides and slide decks
  • 🖥️ Walkthrough viewer: a self-contained HTML page that steps through each scenario, highlighting the active roles and message and showing example requests, responses and decoded tokens
  • 🌍 Embeddable viewer: @grokify/pidl-viewer loads from a CDN with one script tag and shows any walkthrough file, inline or by URL
  • 🧾 Walkthrough format: pidl-walkthrough/v1, the processed form viewers read, with a JSON Schema and TypeScript types
  • 💻 Code samples and cURL: each request as HTTP, a generated curl command, or SDK code taken from tested source files; each implementation can keep its samples in its own sample set, so the protocol document names none
  • 🎙️ Narration: spoken text by language, scenario briefings and pronunciations, for audio and narrated video
  • 🔭 Observed runs: a real system's run beside the walkthrough's examples, matched to its steps by rules in the document and a deployment binding, with tokens decoded and raw values masked
  • 📮 Postman collections: a runnable collection per protocol, with values chained between requests, checks on every response, and signed requests sent through a signing proxy
  • 🎨 Multiple output formats: PlantUML, Mermaid, Graphviz DOT, D2, SVG
  • 🎬 Animated SVG with CSS flow visualizations and moving dots
  • 🌐 Network boundary diagrams for trust zone visualization
  • 🎭 SVG templates: default, minimal, sketch, blueprint, dark, high-contrast
  • ♿ Accessibility: WCAG AA compliant high-contrast template
  • 📦 Phase boxes: Visual grouping of flows by phase with color-coded depth
  • 🔀 Alternative badges: ALT indicators on flows with alternative paths
  • ✨ Interactive SVG: Hover effects on participants, messages, and flow dots
  • 💫 Animation effects: Pulse and glow for error/warning/highlight presets
  • 📚 Built-in examples: OAuth 2.0, PKCE, OIDC, MCP, A2A
  • ⌨️ CLI tool for validation and diagram generation
  • 📦 Go library for programmatic use
  • 🔀 Conditional flows with condition field for when clauses
  • 🔄 Alternative paths with alternatives for error handling and branching
  • 📝 Annotations with typed notes (security, performance, deprecated, etc.)
  • 📊 Nested phases with parent hierarchy support
  • 🔄 State model with entity states and state transitions
  • 📈 State diagrams via Mermaid stateDiagram-v2 output
  • 🔐 Security annotations with requirements (token, encryption, mTLS, signature)
  • 🛡️ Trust levels for entity classification (trusted, semi_trusted, untrusted, authoritative)
  • 🎫 Token definitions with issuer, audience, and binding
  • 🔄 Protocol composition with imports and inheritance
  • ▶️ Protocol simulation with state tracking and execution traces
  • 🔍 Protocol comparison (diff) for change detection
  • 🐛 Interactive debugger for step-through protocol execution
  • 🛡️ Security analysis with built-in attack surface detection rules
  • 🔎 Flow verification provenance with evidentiary tiers (reported/corroborated/reproduced) for incident attack-flows, renderer badges, and an analyzer rule
  • 🔄 Process specifications for data pipelines and AI workflows
  • 📊 Infographic renderer for LinkedIn and datasheet visuals
  • 📈 Data lineage tracking for tracing data flow through process steps
  • ⚡ Parallel execution modeling with fork/join, race, and scatter/gather patterns
  • 💰 Cost tracking for LLM tokens, API calls, and time-based pricing
  • 🔌 Workflow exports to Temporal (Go), Prefect (Python), and BPMN 2.0
  • 🔧 IDE integration: VS Code extension with syntax highlighting and preview
  • 🚀 CI/CD integration: GitHub Action for validation in pipelines
  • 📖 MkDocs plugin for rendering PIDL diagrams in documentation

Installation

go install github.com/grokify/pidl/cmd/pidl@latest

Or clone and build:

git clone https://github.com/grokify/pidl.git
cd pidl
go build -o pidl ./cmd/pidl

Quick Start

List available examples
pidl examples
Generate a diagram from an example
# PlantUML sequence diagram
pidl generate oauth2_authorization_code

# Mermaid sequence diagram
pidl generate -f mermaid oauth2_pkce

# Graphviz DOT data flow diagram
pidl generate -f dot mcp_tool_invocation

# D2 sequence diagram
pidl generate -f d2 oauth2_pkce

# D2 data flow diagram
pidl generate -f d2-flow oauth2_pkce

# D2 architecture diagram
pidl generate -f d2-arch oauth2_pkce

# SVG sequence diagram
pidl generate -f svg oauth2_pkce

# Animated SVG with flow dots
pidl generate -f svg-animated --theme=dark oauth2_pkce

# SVG with template
pidl generate -f svg --template=sketch oauth2_pkce

# Network boundary diagram
pidl generate -f svg-network oauth2_pkce

# Mermaid state diagram (for entities with states)
pidl generate -f mermaid-state oauth2_with_states

# State diagram for specific entity
pidl generate -f mermaid-state --entity=client oauth2_with_states

# Infographic for social media
pidl generate -f infographic --size=linkedin-square --title="OAuth Flow" oauth2_pkce

# Compact infographic for datasheets
pidl generate -f infographic --size=datasheet-tile --theme=minimal etl_pipeline
Create a new protocol file
# Create from scratch
pidl init my-protocol.json

# Copy from an example
pidl init -from oauth2_authorization_code my-oauth.json
Validate protocol files
pidl validate my-protocol.json
pidl validate *.json

Process Specifications

PIDL supports process specifications for modeling data pipelines and AI workflows. Process specs use step types to classify processing stages:

{
  "protocol": {
    "id": "etl-pipeline",
    "name": "ETL Pipeline",
    "kind": "process"
  },
  "entities": [
    {"id": "extract", "name": "Extract", "type": "server", "step_type": "deterministic"},
    {"id": "transform", "name": "Transform", "type": "server", "step_type": "llm"},
    {"id": "review", "name": "Human Review", "type": "server", "step_type": "human"},
    {"id": "load", "name": "Load", "type": "server", "step_type": "external"}
  ],
  "flows": [
    {"from": "extract", "to": "transform", "action": "send"},
    {"from": "transform", "to": "review", "action": "review"},
    {"from": "review", "to": "load", "action": "approve"}
  ]
}
Step Types
Step Type Icon Description
deterministic ⚙️ Predictable processing (same input → same output)
llm 🧠 AI/ML processing (non-deterministic)
human 👤 Human involvement (review, approval)
external ☁️ External services (API calls)
tool 🔧 Tool invocations (function calls)
Generate Process Diagrams
# SVG with step type styling
pidl generate -f svg etl_pipeline

# Infographic for LinkedIn
pidl generate -f infographic --size=linkedin-square --title="ETL Pipeline" etl_pipeline

# Security analysis with process-aware rules
pidl analyze etl_pipeline

See Process Guide for detailed documentation.

PIDL Format

A PIDL document is a JSON file with three main sections:

{
  "protocol": {
    "id": "my-protocol",
    "name": "My Protocol",
    "version": "1.0",
    "description": "A sample protocol",
    "category": "auth"
  },
  "entities": [
    {"id": "client", "name": "Client", "type": "client"},
    {"id": "server", "name": "Server", "type": "server"}
  ],
  "phases": [
    {"id": "main", "name": "Main Flow"},
    {"id": "error_handling", "name": "Error Handling", "parent": "main"}
  ],
  "flows": [
    {
      "from": "client",
      "to": "server",
      "action": "request",
      "label": "Request",
      "mode": "request",
      "phase": "main",
      "condition": "token_valid",
      "note": "Requires valid token",
      "annotations": [
        {"type": "security", "text": "Validate token signature"}
      ],
      "alternatives": [
        {
          "condition": "token_expired",
          "flows": [
            {"from": "server", "to": "client", "action": "refresh_required", "mode": "response"}
          ]
        }
      ]
    },
    {"from": "server", "to": "client", "action": "response", "label": "Response", "mode": "response", "phase": "main"}
  ]
}

Protocol Architecture

PIDL models protocols as directed graphs where nodes are entities/components and edges are interactions/relationships.

Nodes
Entity Types

Entity types are classified as client-side (initiators) or server-side (responders):

Type Classification Description
client Client Application or service initiating requests
user Client Human actor
browser Client User agent / web browser
agent Client AI/LLM agent
delegated_agent Client Agent receiving delegated tasks (A2A)
authorization_server Server Issues tokens and handles authentication
resource_server Server Hosts protected resources
identity_provider Server Authenticates users and issues identity assertions
service_provider Server Consumes identity assertions
server Server Generic server
tool_server Server Exposes tools via protocol (MCP)
tool Other Individual tool capability
other Other Custom entity type
Protocol Roles

Entities can implement protocol-specific roles:

Protocol Description Common Roles
oauth OAuth 2.0 / OIDC authorization_server, client, resource_server
scim SCIM Provisioning client, service_provider
spiffe SPIFFE Identity workload, spire_server, spire_agent
aauth Agent Authentication person_server, access_server, client
idjag ID-JAG Identity client, person_server, access_server
authzen AuthZEN Authorization pep, pdp, pip, pap
mcp Model Context Protocol client, server, tool
a2a Agent-to-Agent client_agent, remote_agent
Deployment Components (Logical Applications)

Components group entities into logical deployment units:

Component Type Description Example Products
idp Identity Provider Okta, Entra ID, Auth0
agent_provider AI Agent Platform Claude, ChatGPT, Gemini
person_server AAuth Person Server Identity verification service
access_server AAuth Access Server Token issuance service
pdp Policy Decision Point OPA, Cedar, Topaz
gateway API Gateway Kong, Apigee, AWS API Gateway
mcp_client MCP Client Claude Code, Cursor
mcp_server MCP Server Custom tool servers
resource_api Resource API Backend services
spire SPIFFE Runtime SPIRE Server/Agent
Edges

PIDL supports two types of edges: protocol flows (sequential actions) and trust relationships (static trust).

Protocol Flows (Sequential Actions)

Flows are ordered interactions between entities that define protocol choreography. They are the primary edge type and generate sequence diagrams.

Field Description
from Source entity ID
to Target entity ID
action Action identifier
mode Flow type: request, response, redirect, callback, event, tool_call, tool_result
phase Optional phase grouping
condition Optional conditional execution
alternatives Optional alternative paths
Protocols

Protocols define the interaction patterns between entities:

Protocol Full Name Specification
oauth OAuth 2.0 / OpenID Connect RFC 6749, RFC 6750, OIDC Core
scim System for Cross-domain Identity Management RFC 7643, RFC 7644
spiffe Secure Production Identity Framework SPIFFE/SPIRE
aauth Agent Authentication AAuth Spec
idjag Identity for Just-in-time Access Grant ID-JAG Spec
authzen Authorization API OpenID AuthZEN
mcp Model Context Protocol MCP Specification
a2a Agent-to-Agent Protocol A2A Specification
Trust Relationship Types

Trust relationships define how entities establish trust:

Type Description Direction
authenticates Verifies identity A authenticates B
validates Validates credentials/tokens A validates B's tokens
delegates Grants delegated authority A delegates to B
authorizes Grants access permissions A authorizes B
issues Creates credentials/tokens A issues tokens for B
trusts General trust relationship A trusts B
provisions Creates/manages accounts A provisions B
attests Provides identity attestation A attests B's identity
Credential Types

Credentials exchanged in trust relationships:

Credential Description Used By
x509_svid X.509 SVID certificate SPIFFE/SPIRE
jwt_svid JWT SVID token SPIFFE/SPIRE
jwt_assertion JWT assertion for client auth OAuth 2.0
access_token OAuth access token OAuth 2.0
id_token OIDC ID token OpenID Connect
aa_agent_jwt AAuth Agent JWT AAuth
aa_auth_jwt AAuth Authorization JWT AAuth
mtls Mutual TLS certificate mTLS
api_key API key Various
Diagram Outputs

PIDL generates multiple diagram types from the same protocol definition:

Diagram Type Format Source Data Description
Sequence Diagram plantuml, mermaid, d2, svg, svg-animated Flows Shows ordered interactions between entities
Data Flow Diagram dot, d2-flow Flows Shows data movement between entities
Architecture Diagram d2-arch Entities, Flows Shows system architecture
Network Diagram svg-network Entities, Trust Levels Shows network boundaries and trust zones
State Diagram mermaid-state Entity States, Flows Shows entity state machines
Component Diagram (planned) Components Shows logical deployment units
Trust Diagram (planned) Trust Relations Shows trust relationships between entities
Diagram Generation
# Sequence diagrams (from flows)
pidl generate -f plantuml protocol.json    # PlantUML
pidl generate -f mermaid protocol.json     # Mermaid
pidl generate -f svg protocol.json         # SVG
pidl generate -f svg-animated protocol.json # Animated SVG

# Data flow diagrams (from flows)
pidl generate -f dot protocol.json         # Graphviz DOT
pidl generate -f d2-flow protocol.json     # D2 flow

# Architecture diagrams (from entities + flows)
pidl generate -f d2-arch protocol.json     # D2 architecture

# Network diagrams (from entities + trust levels)
pidl generate -f svg-network protocol.json # Network boundaries

# State diagrams (from entity states + flow mutations)
pidl generate -f mermaid-state protocol.json           # All entities
pidl generate -f mermaid-state --entity=client protocol.json  # Single entity
Flow Modes
Mode Description Arrow Style
request Synchronous request Solid ->
response Synchronous response Dashed -->
redirect HTTP redirect Solid with annotation
callback Callback/webhook Solid with annotation
interactive Human interaction Solid
event Asynchronous event Dashed
tool_call Tool invocation (MCP) Solid with annotation
tool_result Tool result (MCP) Dashed with annotation
Flow Extensions
Field Description
condition Conditional execution clause (renders as opt block)
note Visible note displayed on diagram
annotations Array of typed annotations for tooling
alternatives Alternative paths (renders as alt/else blocks)
Annotation Types
Type Description
security Security-related notes
performance Performance considerations
deprecated Deprecated functionality
info General information
warning Warning messages
error Error conditions
Nested Phases

Phases support hierarchical nesting via the parent field:

{
  "phases": [
    {"id": "auth", "name": "Authentication"},
    {"id": "mfa", "name": "Multi-Factor Auth", "parent": "auth"},
    {"id": "token", "name": "Token Exchange", "parent": "auth"}
  ]
}
Entity States

Entities can define states to track their lifecycle:

{
  "entities": [
    {
      "id": "client",
      "name": "Client",
      "type": "client",
      "states": [
        {"id": "idle", "name": "Idle", "initial": true},
        {"id": "authenticated", "name": "Authenticated"},
        {"id": "error", "name": "Error", "final": true}
      ]
    }
  ]
}
Field Description
id Unique state identifier within the entity
name Human-readable display name
description Optional state description
initial Marks this as the initial state (at most one per entity)
final Marks this as a terminal/final state
State Mutations

Flows can trigger state changes via the sets field:

{
  "flows": [
    {
      "from": "client",
      "to": "server",
      "action": "login",
      "sets": [
        {"entity": "client", "from": "idle", "to": "authenticated"}
      ]
    }
  ]
}
Field Description
entity Entity ID whose state changes
to Target state ID (required)
from Optional required prior state (for validation)
Trust Levels

Entities can be assigned trust levels to indicate their security posture:

{
  "entities": [
    {
      "id": "client",
      "name": "Client",
      "type": "client",
      "trust_level": "semi_trusted"
    }
  ]
}
Trust Level Description
trusted Fully trusted internal systems
semi_trusted Partially trusted (DMZ, partners)
untrusted External/public systems
authoritative Source of truth (IdPs, CAs)

Trust levels are used by svg-network format to automatically infer network boundaries.

Security Requirements

Flows can specify security requirements:

{
  "flows": [
    {
      "from": "client",
      "to": "server",
      "action": "api_request",
      "security": {
        "requires": ["token", "encryption"],
        "token": "access_token",
        "confidential": true,
        "description": "Bearer token required"
      }
    }
  ]
}
Requirement Description
token Requires a bearer or bound token
signature Requires message signing
encryption Requires message encryption
mtls Requires mutual TLS authentication
mac Requires message authentication code
Token Definitions

Protocols can define token types used in flows:

{
  "metadata": {
    "tokens": [
      {
        "id": "access_token",
        "name": "Access Token",
        "type": "jwt",
        "issuer": "auth_server",
        "audience": "resource_server",
        "binding": "bearer"
      }
    ]
  }
}
Field Description
id Unique token identifier
name Human-readable display name
type Token format: jwt, opaque, saml, api_key
issuer Entity ID that issues this token
audience Entity ID that consumes this token
binding Token binding: bearer, mtls, dpop
verified_by Entity IDs that check this token
claims Claims checkers rely on, each with name, checked_by and description

Flow security can also record signed_by (who signs the request), issues (tokens the flow delivers) and verifies (tokens the receiver checks), so pidl analyze can follow each token through a scenario.

CLI Reference

pidl <command> [options] [arguments]

Commands:
  validate   Validate PIDL JSON files
  generate   Generate diagrams from PIDL files
  scenarios  List scenarios in a PIDL file, in output order
  samples    Resolve and check code samples from source repositories
  roles      List protocol roles
  components List deployment components
  trust      List trust relationships
  examples   List or show built-in examples
  init       Create a new PIDL file from template
  simulate   Run protocol simulation with state tracking
  diff       Compare two protocols and show differences
  debug      Interactive step-through protocol debugger
  analyze    Security analysis with attack surface detection
  resolve    Resolve protocol imports and inheritance
  version    Print version information
  help       Show help message
validate
pidl validate [options] <file> [file...]

Options:
  -q    Quiet mode (only show errors)
generate
pidl generate [options] <file>

Options:
  -f string         Output format (default "plantuml")
  -o string         Output file (default: stdout)
  --template        SVG template: default, minimal, sketch, blueprint, dark, high-contrast
  --template-dir    Path to custom SVG template directory
  --theme           SVG theme: light, dark, auto
  --boundary        Network boundary override (repeatable)
  --entity          Entity ID to filter (for mermaid-state format)
  --show-security   Show security annotations on flows (default true)
  --show-trust      Show trust levels and infer boundaries from trust (default true)
  --scenario        Scenario to render (files with scenarios)
  --expand          Show included fragments step by step instead of as boxes
  --all-scenarios   Render every main scenario to NN-<id><ext> in the -o directory
  --include-fragments  With --all-scenarios, also render fragments
  --observation     walkthrough-json and viewer: a run observed in a real system (pidl-observation/v1)
  --binding         With --observation: the deployment's binding (pidl-binding/v1)
  --scenarios       With --observation: scenario IDs to look for, in order (default: all but fragments)
  --from, --to      With --observation: match only exchanges in this RFC 3339 time range
  --raw             With --observation: keep raw tokens and signatures instead of masking them

Formats:

Format Description
plantuml PlantUML sequence diagram
mermaid Mermaid sequence diagram
mermaid-state Mermaid state diagram (requires entity states)
dot Graphviz DOT data flow diagram
d2 D2 sequence diagram
d2-flow D2 data flow diagram
d2-arch D2 architecture diagram
svg SVG sequence diagram
svg-animated Animated SVG with flow dots
svg-network Network boundary diagram
infographic Compact infographic with animated data flow
scenario-matrix Markdown table of roles by scenario (whole file)
token-table Markdown table of tokens, checkers and claims (whole file)
outline Markdown outline of roles, scenarios and tokens (whole file)
outline-json The outline as JSON (whole file)
walkthrough-json A walkthrough (pidl-walkthrough/v1): expanded scenarios with examples and findings, for viewers (whole file)
viewer Self-contained HTML walkthrough viewer (whole file)
postman Postman collection: a folder per scenario, chained requests and checks (whole file)
postman-environment Postman environment for one target in a --targets file
observe
pidl observe import --from sandbox [-o <file>] <capture>

Converts a capture of a real run into an observation (pidl-observation/v1): sandbox reads the aauth-go sandbox's trace. Show it beside a document's steps with pidl generate -f viewer --observation <file> --binding <file> <document>.

samples
pidl samples <resolve|check> [options] <file>

Options:
  --root <dir>       Directory holding repository checkouts at <root>/<repo> (default: $GOPATH/src)
  --lock <file>      A document's lock file (default: <file without .json>.samples.json)
  --repo-dir <dir>   Read every source from this checkout
  --protocol <file>  With a sample set, check every step address against this document

<file> is a document or a sample set (pidl-samples/v1). resolve records each sample's code and hash, in the document's lock file or in the set; check fails when a sample has fallen behind its source.

examples
pidl examples [options] [name]

Options:
  -json   Show example JSON content
init
pidl init [options] <filename>

Options:
  -name string   Protocol name
  -from string   Initialize from example
simulate
pidl simulate [options] <file>

Options:
  -steps int           Maximum steps to execute (0 = all)
  -v                   Verbose output with each step
  -json                Output trace as JSON
  --trace-format       Trace output format: text, json, svg, mermaid
  --trace-output       Write trace to file
  --show-states        Show entity states in trace
  --show-timings       Show timing information
diff
pidl diff [options] <base-file> <new-file>

Options:
  -f, --format         Output format: text, json, markdown (default: text)
  -o, --output         Output file (default: stdout)
  --ignore-metadata    Ignore metadata differences
  -q, --quiet          Summary only
debug
pidl debug <file>

Interactive Commands:
  step, s              Execute next flow
  continue, c          Run until breakpoint/completion
  break <idx> [cond]   Set breakpoint at flow index
  delete <idx>         Remove breakpoint
  breakpoints          List all breakpoints
  inspect              Show current state
  inspect entity <id>  Show entity details and state
  inspect flow <idx>   Show flow details
  list                 List flows with position marker
  set <entity> <state> Set entity state
  reset                Restart execution
  quit, q              Exit debugger
analyze
pidl analyze [options] <file>

Options:
  -f, --format         Output format: text, json, markdown (default: text)
  -o, --output         Output file (default: stdout)
  --min-severity       Minimum severity: critical, high, medium, low, info
  --category           Filter by category (repeatable)
  --fail-on            Exit with code 1 if risks at this severity
  -q, --quiet          Summary only

Built-in security rules:

Rule Severity Description
SEC001 High Trust boundary violation (untrusted to trusted without security)
SEC002 High Missing encryption on confidential flow
SEC003 Medium Unbound bearer token (no mTLS/DPoP binding)
SEC004 High Missing authentication on external flow
SEC005 Medium JWT without defined audience
SEC006 Medium Token transmitted in redirect
SEC007 Medium Missing mTLS on sensitive flow
SEC008 Low Entity without defined trust level
SEC009 Medium Sensitive data in redirect parameters
SEC010 Medium Weak authentication method

Go Library

import (
    "github.com/grokify/pidl"
    "github.com/grokify/pidl/render"
    "github.com/grokify/pidl/examples"
    "github.com/grokify/pidl/analyze"
)

// Parse a PIDL file
p, err := pidl.ParseFile("protocol.json")

// Validate
if errs := p.Validate(); errs.HasErrors() {
    log.Fatal(errs)
}

// Generate PlantUML
diagram, err := render.RenderString(render.FormatPlantUML, p)

// Use built-in examples
names := examples.List()
oauth, err := examples.GetProtocol("oauth2_authorization_code")

// Create a new protocol
p := pidl.NewMinimalProtocol("my-protocol", "My Protocol")
pidl.WriteProtocolFile("output.json", p)

// Compare two protocols
diff := pidl.Compare(base, updated, pidl.DiffOptions{})
fmt.Println(diff.String())

// Run protocol simulation
executor := pidl.NewExecutor(p)
trace, err := executor.Execute()
fmt.Println(trace.String())

// Interactive debugging
session := pidl.NewDebugSession(p)
session.SetBreakpoint(2, "")
step, _ := session.Step()
state := session.Inspect()

// Security analysis
analysis := analyze.Analyze(p, analyze.DefaultAnalysisOptions())
fmt.Println(analysis.String())
if analysis.HasRisksAtOrAbove(analyze.SeverityHigh) {
    // handle high-severity risks
}

// Data lineage analysis
lineage := pidl.AnalyzeDataLineage(p)
upstream := lineage.GetUpstream("transform", "input")
impacted := lineage.GetImpactedEntities("extract")
sources := lineage.GetDataProvenance("load")

// Parallel execution analysis
graph := pidl.AnalyzeExecutionGraph(p)
canParallel := pidl.CanExecuteInParallel(p, "stepA", "stepB")
maxParallel := pidl.GetMaxParallelism(p)

// Cost tracking
costAnalysis := pidl.AnalyzeProcessCosts(p)
fmt.Printf("Estimated cost: $%.4f\n", costAnalysis.TotalEstimate.ExpectedCost)

// Workflow exports
import "github.com/grokify/pidl/export"
temporal := export.NewTemporalExporter()
goCode, _ := temporal.Export(p)
prefect := export.NewPrefectExporter()
pythonCode, _ := prefect.Export(p)
bpmn := export.NewBPMNExporter()
xml, _ := bpmn.Export(p)

Built-in Examples

Protocol Examples
Example Protocol
oauth2_api_access OAuth 2.0 API access worked end to end: authorization code with PKCE, client credentials, a scope challenge, an asynchronous request and a signed request, as scenarios with example requests, responses and tokens
oauth2_authorization_code OAuth 2.0 Authorization Code Flow
oauth2_pkce OAuth 2.0 with PKCE
oauth2_with_states OAuth 2.0 with State Tracking
oauth2_with_security OAuth 2.0 with Security Annotations
oidc_authentication OpenID Connect Authentication
mcp_tool_invocation MCP Tool Invocation
a2a_agent_delegation A2A Agent Delegation
saml2_sso SAML 2.0 Web Browser SSO
webauthn_registration WebAuthn/FIDO2 Credential Registration
scim_provisioning SCIM User Provisioning
Process Spec Examples
Example Description
etl_pipeline Extract-Transform-Load pipeline
llm_document_review LLM processing with human approval
ci_cd_pipeline Build-test-deploy workflow
visionspec_execution MRD → PRD → TRD document pipeline

Target Protocols

PIDL is designed for describing:

  • Authentication/Authorization: OAuth 2.0, OpenID Connect, SAML 2.0, WebAuthn/FIDO2
  • Identity Management: SCIM provisioning, user lifecycle
  • Agent Protocols: AAuth, MCP (Model Context Protocol), A2A (Agent-to-Agent)
  • API Flows: Multi-party API choreography

Documentation

License

MIT License - see LICENSE for details.

Documentation

Overview

Package pidl provides types and utilities for the Protocol Interaction Description Language. PIDL is a JSON-based DSL for describing protocol choreography that compiles to diagrams.

Index

Constants

View Source
const (
	RepresentationHTTP = "http"
	RepresentationCurl = "curl"
)

Representation names for narration overrides. Sample languages, such as "go" or "python", are representations too.

View Source
const (
	ProtocolOAuth    = "oauth"
	ProtocolSCIM     = "scim"
	ProtocolSPIFFE   = "spiffe"
	ProtocolAAuth    = "aauth"
	ProtocolIDJAG    = "idjag"
	ProtocolAuthZEN  = "authzen"
	ProtocolMCP      = "mcp"
	ProtocolA2A      = "a2a"
	ProtocolSAML     = "saml"
	ProtocolWebAuthn = "webauthn"
	ProtocolFIDO2    = "fido2"
	ProtocolOIDC     = "oidc"
)

Protocol identifier constants.

View Source
const (
	ComponentTypeIdP           = "idp"
	ComponentTypeIGA           = "iga"
	ComponentTypeAgentProvider = "agent_provider"
	ComponentTypePersonServer  = "person_server"
	ComponentTypeAccessServer  = "access_server"
	ComponentTypePDP           = "pdp"
	ComponentTypeGateway       = "gateway"
	ComponentTypeMCPClient     = "mcp_client"
	ComponentTypeMCPServer     = "mcp_server"
	ComponentTypeResourceAPI   = "resource_api"
	ComponentTypeSPIRE         = "spire"
)

Component type constants.

View Source
const (
	TrustTypeAuthenticates = "authenticates"
	TrustTypeValidates     = "validates"
	TrustTypeDelegates     = "delegates"
	TrustTypeAuthorizes    = "authorizes"
	TrustTypeIssues        = "issues"
	TrustTypeTrusts        = "trusts"
	TrustTypeProvisions    = "provisions"
	TrustTypeAttests       = "attests"
)

Trust relationship type constants.

View Source
const (
	CredentialX509SVID        = "x509_svid"
	CredentialJWTSVID         = "jwt_svid"
	CredentialJWTAssertion    = "jwt_assertion"
	CredentialAccessToken     = "access_token"
	CredentialIDToken         = "id_token"
	CredentialAAAgentJWT      = "aa_agent_jwt"
	CredentialAAAuthJWT       = "aa_auth_jwt"
	CredentialMTLS            = "mtls"
	CredentialAPIKey          = "api_key"
	CredentialX509Certificate = "x509_certificate"
	CredentialAttestationCert = "attestation_certificate"
	CredentialBearerToken     = "bearer_token"
	CredentialSAMLAssertion   = "saml_assertion"
	CredentialSessionCookie   = "session_cookie"
)

Credential type constants.

View Source
const (
	ObservedMatched      = "matched"
	ObservedNotSeen      = "notSeen"
	ObservedSkipped      = "skipped"
	ObservedUnmatchable  = "unmatchable"
	ObservedUnobservable = "unobservable"
	ObservedStrong       = "strong"
	ObservedWeak         = "weak"
)

Observed status and strength values of a walkthrough step.

View Source
const BindingFormat = "pidl-binding/v1"

BindingFormat names the binding format and its major version.

View Source
const DefaultBodyLimit = 64 << 10

DefaultBodyLimit is the size above which NewObservedBody cuts a body.

View Source
const DefaultLanguage = "en-US"

DefaultLanguage is the source language of narration when the protocol does not set one.

View Source
const ObservationFormat = "pidl-observation/v1"

ObservationFormat names the observation format and its major version.

View Source
const SampleLockSuffix = ".samples.json"

SampleLockSuffix ends the name of a document's sample lock file.

View Source
const SampleSetFormat = "pidl-samples/v1"

SampleSetFormat names the sample set format and its major version.

View Source
const WalkthroughFormat = "pidl-walkthrough/v1"

WalkthroughFormat identifies the walkthrough format and its major version. Within a major version, changes only add optional fields.

Variables

View Source
var LLMCostPresets = map[string]struct {
	InputCost  float64
	OutputCost float64
}{
	"gpt-4":           {InputCost: 0.03, OutputCost: 0.06},
	"gpt-4-turbo":     {InputCost: 0.01, OutputCost: 0.03},
	"gpt-3.5-turbo":   {InputCost: 0.0005, OutputCost: 0.0015},
	"claude-3-opus":   {InputCost: 0.015, OutputCost: 0.075},
	"claude-3-sonnet": {InputCost: 0.003, OutputCost: 0.015},
	"claude-3-haiku":  {InputCost: 0.00025, OutputCost: 0.00125},
}

LLMCostPresets provides common LLM pricing (per 1K tokens, in USD).

View Source
var StepTypeLatencyDefaults = map[StepType]struct {
	P50      time.Duration
	P95      time.Duration
	P99      time.Duration
	Max      time.Duration
	Variance LatencyVarianceClass
}{
	StepTypeDeterministic: {
		P50:      50 * time.Millisecond,
		P95:      100 * time.Millisecond,
		P99:      200 * time.Millisecond,
		Max:      500 * time.Millisecond,
		Variance: LatencyVarianceLow,
	},
	StepTypeLLM: {
		P50:      2 * time.Second,
		P95:      8 * time.Second,
		P99:      15 * time.Second,
		Max:      30 * time.Second,
		Variance: LatencyVarianceHigh,
	},
	StepTypeHuman: {
		P50:      5 * time.Minute,
		P95:      30 * time.Minute,
		P99:      2 * time.Hour,
		Max:      24 * time.Hour,
		Variance: LatencyVarianceHigh,
	},
	StepTypeExternal: {
		P50:      200 * time.Millisecond,
		P95:      1 * time.Second,
		P99:      3 * time.Second,
		Max:      10 * time.Second,
		Variance: LatencyVarianceMedium,
	},
	StepTypeTool: {
		P50:      100 * time.Millisecond,
		P95:      500 * time.Millisecond,
		P99:      1 * time.Second,
		Max:      5 * time.Second,
		Variance: LatencyVarianceMedium,
	},
}

StepTypeLatencyDefaults provides default latency estimates by step type.

Functions

func CalculateExecutionCost added in v0.5.0

func CalculateExecutionCost(entity *Entity, metrics ExecutionMetrics) float64

CalculateExecutionCost calculates actual cost from execution metrics.

func CanExecuteInParallel added in v0.5.0

func CanExecuteInParallel(p *Protocol, entityA, entityB string) bool

CanExecuteInParallel determines if two entities can execute concurrently.

func EstimateLatencyPercentile added in v0.5.0

func EstimateLatencyPercentile(analysis *ProcessLatencyAnalysis, percentile int) time.Duration

EstimateLatencyPercentile returns a specific percentile latency estimate.

func ExtractRegion added in v0.9.0

func ExtractRegion(content []byte, name string) (string, error)

ExtractRegion returns the lines between "pidl:begin <name>" and "pidl:end <name>", with marker lines of other regions removed, common indentation removed, and leading and trailing blank lines trimmed. Markers may sit in any comment syntax.

func FormatLatencyReport added in v0.5.0

func FormatLatencyReport(analysis *ProcessLatencyAnalysis) string

FormatLatencyReport generates a human-readable latency report.

func GetCostEfficiency added in v0.5.0

func GetCostEfficiency(analysis *ProcessCostAnalysis) map[string]float64

GetCostEfficiency returns cost per unit of output for comparison.

func GetLatencyBreakdown added in v0.5.0

func GetLatencyBreakdown(analysis *ProcessLatencyAnalysis) map[string]time.Duration

GetLatencyBreakdown returns latency contribution by step type.

func GetMaxParallelism added in v0.5.0

func GetMaxParallelism(p *Protocol) int

GetMaxParallelism returns the maximum number of entities that can execute concurrently.

func IsObservation added in v0.10.0

func IsObservation(data []byte) bool

IsObservation reports whether data is an observation, by its format.

func IsSampleSet added in v0.9.0

func IsSampleSet(data []byte) bool

IsSampleSet reports whether data is a sample set rather than a sample lock, by its format.

func IsValidAnnotationType added in v0.2.0

func IsValidAnnotationType(t AnnotationType) bool

IsValidAnnotationType checks if the annotation type is valid.

func IsValidCategory added in v0.4.0

func IsValidCategory(c Category) bool

IsValidCategory checks if the category is valid.

func IsValidComponentType added in v0.4.0

func IsValidComponentType(t string) bool

IsValidComponentType checks if the component type is a known type.

func IsValidCredential added in v0.4.0

func IsValidCredential(c string) bool

IsValidCredential checks if the credential type is a known type.

func IsValidEntityType added in v0.4.0

func IsValidEntityType(t EntityType) bool

IsValidEntityType checks if the entity type is valid.

func IsValidExampleKind added in v0.8.0

func IsValidExampleKind(k ExampleKind) bool

IsValidExampleKind reports whether k is a known example kind.

func IsValidFlowMode added in v0.4.0

func IsValidFlowMode(m FlowMode) bool

IsValidFlowMode checks if the flow mode is valid.

func IsValidProtocol added in v0.4.0

func IsValidProtocol(protocol string) bool

IsValidProtocol checks if the protocol identifier is a known protocol.

func IsValidSchemaURI added in v0.5.0

func IsValidSchemaURI(uri string) bool

IsValidSchemaURI checks if a schema URI is syntactically valid.

func IsValidSecurityRequirement added in v0.4.0

func IsValidSecurityRequirement(r SecurityRequirement) bool

IsValidSecurityRequirement checks if the security requirement is valid.

func IsValidTrustLevel added in v0.4.0

func IsValidTrustLevel(t TrustLevel) bool

IsValidTrustLevel checks if the trust level is valid.

func IsValidTrustRelationType added in v0.4.0

func IsValidTrustRelationType(t string) bool

IsValidTrustRelationType checks if the trust relation type is a known type.

func NewObservedBody added in v0.10.0

func NewObservedBody(data []byte, mediaType string, limit int) (body json.RawMessage, truncated bool, err error)

NewObservedBody encodes a captured body: as a JSON value when it is JSON, as a JSON string when it is other text, and as a BinaryBody otherwise. A body longer than limit bytes is cut to limit, in which case truncated is true and a JSON body is kept as text. A limit of zero or less means DefaultBodyLimit. An empty body gives a nil result.

func SampleLockPath added in v0.9.0

func SampleLockPath(docPath string) string

SampleLockPath returns the conventional lock path for a document: "aauth.json" uses "aauth.samples.json".

func SanitizeID

func SanitizeID(s string) string

SanitizeID converts a string to a valid PIDL ID (lowercase, alphanumeric, underscores/hyphens).

func StepKeys added in v0.10.0

func StepKeys(scenario, expandedID, definedIn, flowID string) []string

StepKeys returns the keys that can name a step, most specific first: the step in its scenario, the flow where it is defined, and any flow with its ID. expandedID is the walkthrough's qualified step ID, definedIn the scenario or fragment that defines the flow, and flowID the flow's own ID.

func TitleCase

func TitleCase(s string) string

TitleCase converts a string to title case (first letter of each word capitalized).

func ValidateFile

func ValidateFile(filename string) (*Protocol, ValidationErrors, error)

ValidateFile parses and validates a PIDL file, returning any validation errors.

func WireBody added in v0.9.0

func WireBody(body json.RawMessage) ([]byte, error)

WireBody returns the bytes an example body stands for on the wire, which is what a Content-Digest covers. A JSON string is sent as its contents, for media types that are not JSON; any other value is sent as compact JSON with its keys in written order.

Types

type Alternative added in v0.2.0

type Alternative struct {
	// Condition describes when this alternative is taken.
	Condition string `json:"condition"`

	// Flows are the steps in this alternative path.
	Flows []Flow `json:"flows"`

	// Description provides additional context.
	Description string `json:"description,omitempty"`
}

Alternative represents an alternative path in the flow.

type AnimationPreset added in v0.3.0

type AnimationPreset string

AnimationPreset represents a semantic animation preset.

const (
	// AnimationPresetRequest is the default for outgoing requests.
	AnimationPresetRequest AnimationPreset = "request"
	// AnimationPresetResponse is for return values (gray, dashed).
	AnimationPresetResponse AnimationPreset = "response"
	// AnimationPresetSuccess indicates successful operations (green).
	AnimationPresetSuccess AnimationPreset = "success"
	// AnimationPresetError indicates errors/failures (red, pulsing).
	AnimationPresetError AnimationPreset = "error"
	// AnimationPresetWarning indicates warnings (orange, pulsing).
	AnimationPresetWarning AnimationPreset = "warning"
	// AnimationPresetHighlight emphasizes critical paths (yellow, larger dot).
	AnimationPresetHighlight AnimationPreset = "highlight"
	// AnimationPresetNone disables animation (static arrow).
	AnimationPresetNone AnimationPreset = "none"
)

type Annotation added in v0.2.0

type Annotation struct {
	// Type categorizes the annotation.
	Type AnnotationType `json:"type"`

	// Text is the annotation message.
	Text string `json:"text"`

	// Details provides additional context.
	Details string `json:"details,omitempty"`
}

Annotation represents a typed annotation on a flow.

type AnnotationType added in v0.2.0

type AnnotationType string

AnnotationType represents the type of annotation.

const (
	AnnotationTypeSecurity    AnnotationType = "security"
	AnnotationTypePerformance AnnotationType = "performance"
	AnnotationTypeDeprecated  AnnotationType = "deprecated"
	AnnotationTypeInfo        AnnotationType = "info"
	AnnotationTypeWarning     AnnotationType = "warning"
	AnnotationTypeError       AnnotationType = "error"
)

type BinaryBody added in v0.10.0

type BinaryBody struct {
	Base64    string `json:"base64"`
	MediaType string `json:"mediaType,omitempty"`
}

BinaryBody is the encoding of a body that is not text.

type Binding added in v0.10.0

type Binding struct {
	// Format names the format and its major version: pidl-binding/v1.
	Format string `json:"format"`

	// Participants maps a document participant ID to how a capture names it.
	Participants map[string]BindingParticipant `json:"participants"`

	// LabelsByPath resolves a generic sender label, such as a trace's
	// "client", by the request path.
	LabelsByPath []BindingLabelRule `json:"labelsByPath,omitempty"`

	// Paths gives, per participant, the path of a step where the
	// deployment's path differs from the document's example. Keys are step
	// keys, as in Steps.
	Paths map[string]map[string]string `json:"paths,omitempty"`

	// Rewrite rewrites every exchange's URL before matching, in order.
	Rewrite []BindingRewrite `json:"rewrite,omitempty"`

	// Unobservable lists participants a capture cannot see, in addition to
	// those whose role type is user.
	Unobservable []string `json:"unobservable,omitempty"`

	// Steps replaces a step's rule for this deployment. A key names, from
	// most to least specific: "<scenario>/<expanded-id>", the step in one
	// scenario as the walkthrough qualifies it ("ps-authorization/consent.poll");
	// "<defining-scenario>/<flow-id>", the flow wherever it appears, as
	// sample sets address steps ("consent/poll"); or "*/<flow-id>", any flow
	// with that ID. Step IDs repeat across scenarios, so a bare ID is not a key.
	Steps map[string]BindingStep `json:"steps,omitempty"`
}

Binding describes one deployment of a protocol, so observed exchanges can be matched to a document's steps: the labels a capturing tool uses for each participant and the hosts it answers at, paths that differ from the document's examples, URL rewrites a capture needs, and rules that replace a step's own for this deployment.

func ParseBinding added in v0.10.0

func ParseBinding(data []byte) (*Binding, error)

ParseBinding parses a binding. It refuses another major version of the format.

func ReadBinding added in v0.10.0

func ReadBinding(path string) (*Binding, error)

ReadBinding reads a binding file.

func (*Binding) StepPath added in v0.10.0

func (b *Binding) StepPath(participant, scenario, expandedID, definedIn, flowID string) (string, string, bool)

StepPath returns the binding's path for a step at a participant and the key that named it, trying StepKeys in order.

func (*Binding) StepRule added in v0.10.0

func (b *Binding) StepRule(scenario, expandedID, definedIn, flowID string) (StepMatch, string, bool)

StepRule returns the binding's rule for a step and the key that named it, trying StepKeys in order.

func (*Binding) Validate added in v0.10.0

func (b *Binding) Validate() ValidationErrors

Validate checks the binding's structure: its format, regular expressions, step keys and the participants its rules name.

func (*Binding) WriteFile added in v0.10.0

func (b *Binding) WriteFile(path string) error

WriteFile writes the binding as indented JSON.

type BindingLabelRule added in v0.10.0

type BindingLabelRule struct {
	// Label is the sender label the rule applies to, such as "client".
	Label string `json:"label"`
	// Path is a regular expression the request path must match.
	Path string `json:"path"`
	// Participant is the participant the sender is taken to be.
	Participant string `json:"participant"`
}

BindingLabelRule resolves a sender label by the request path.

type BindingParticipant added in v0.10.0

type BindingParticipant struct {
	// Labels are the capturing tool's names for the participant.
	Labels []string `json:"labels,omitempty"`
	// Hosts are the host names the participant answers at.
	Hosts []string `json:"hosts,omitempty"`
}

BindingParticipant is how a capture names one participant.

type BindingRewrite added in v0.10.0

type BindingRewrite struct {
	// Match is a regular expression over the whole URL.
	Match string `json:"match"`
	// To is the replacement, with $1-style references to Match's groups.
	To string `json:"to"`
}

BindingRewrite rewrites a URL by a regular expression.

type BindingStep added in v0.10.0

type BindingStep struct {
	Match StepMatch `json:"match"`
}

BindingStep is a deployment's rule for one step.

type Breakpoint added in v0.4.0

type Breakpoint struct {
	// FlowIndex is the flow index where the breakpoint is set.
	FlowIndex int

	// Condition is an optional condition expression (evaluated by ConditionEvaluator).
	Condition string

	// Enabled indicates if the breakpoint is active.
	Enabled bool

	// HitCount tracks how many times this breakpoint was hit.
	HitCount int
}

Breakpoint represents a debug breakpoint.

type Briefing added in v0.9.0

type Briefing struct {
	// Why explains, as prose, why the scenario exists and what problem it
	// solves.
	Why string `json:"why,omitempty"`

	// Points are the key points, in display order.
	Points []string `json:"points,omitempty"`

	// Narration is spoken over the briefing.
	Narration Narration `json:"narration,omitempty"`
}

Briefing introduces a scenario before its steps, for example on slides that open a video.

type Category

type Category string

Category represents the protocol category.

const (
	CategoryAuth         Category = "auth"
	CategoryAgent        Category = "agent"
	CategoryMessaging    Category = "messaging"
	CategoryProvisioning Category = "provisioning"
	CategoryOther        Category = "other"
)

type CostEstimate added in v0.5.0

type CostEstimate struct {
	// EntityID is the entity this estimate is for (empty for total).
	EntityID string `json:"entity_id,omitempty"`
	// MinCost is the minimum expected cost.
	MinCost float64 `json:"min_cost"`
	// MaxCost is the maximum expected cost.
	MaxCost float64 `json:"max_cost"`
	// ExpectedCost is the average/expected cost.
	ExpectedCost float64 `json:"expected_cost"`
	// CostUnit is the currency or unit.
	CostUnit string `json:"cost_unit"`
	// Breakdown shows cost by category.
	Breakdown map[string]float64 `json:"breakdown,omitempty"`
}

CostEstimate represents an estimated cost for a step or process.

type CostModel added in v0.5.0

type CostModel struct {
	// Type classifies the cost model.
	Type CostModelType `json:"type"`

	// FixedCost is the base cost per execution (in the cost unit).
	FixedCost float64 `json:"fixed_cost,omitempty"`

	// VariableCost is the cost per unit of work.
	VariableCost float64 `json:"variable_cost,omitempty"`

	// CostUnit is the currency or unit for costs (e.g., "USD", "tokens", "credits").
	CostUnit string `json:"cost_unit,omitempty"`

	// TokenCosts for LLM steps (per 1K tokens).
	InputTokenCost  float64 `json:"input_token_cost,omitempty"`
	OutputTokenCost float64 `json:"output_token_cost,omitempty"`

	// EstimatedInputTokens for LLM cost estimation.
	EstimatedInputTokens int `json:"estimated_input_tokens,omitempty"`
	// EstimatedOutputTokens for LLM cost estimation.
	EstimatedOutputTokens int `json:"estimated_output_tokens,omitempty"`

	// ComputeCostPerSecond for compute-based steps.
	ComputeCostPerSecond float64 `json:"compute_cost_per_second,omitempty"`

	// APICallCost for external API steps.
	APICallCost float64 `json:"api_call_cost,omitempty"`
}

CostModel defines the cost characteristics of a processing step.

type CostModelType added in v0.5.0

type CostModelType string

CostModelType classifies how costs are calculated.

const (
	// CostModelTypeFixed has a fixed cost per execution.
	CostModelTypeFixed CostModelType = "fixed"
	// CostModelTypeTokenBased costs based on input/output tokens.
	CostModelTypeTokenBased CostModelType = "token_based"
	// CostModelTypeTimeBased costs based on execution time.
	CostModelTypeTimeBased CostModelType = "time_based"
	// CostModelTypeAPICall costs per API call.
	CostModelTypeAPICall CostModelType = "api_call"
	// CostModelTypeHybrid combines multiple cost factors.
	CostModelTypeHybrid CostModelType = "hybrid"
)

type DataLineage added in v0.5.0

type DataLineage struct {
	// ProtocolID is the ID of the source protocol.
	ProtocolID string `json:"protocol_id"`
	// Edges are the data flow connections.
	Edges []LineageEdge `json:"edges"`
	// Sources are ports that have no upstream connections.
	Sources []PortReference `json:"sources"`
	// Sinks are ports that have no downstream connections.
	Sinks []PortReference `json:"sinks"`
	// SensitiveDataPaths tracks paths containing sensitive data.
	SensitiveDataPaths [][]PortReference `json:"sensitive_paths,omitempty"`
}

DataLineage represents the complete data lineage graph for a protocol.

func AnalyzeDataLineage added in v0.5.0

func AnalyzeDataLineage(p *Protocol) *DataLineage

AnalyzeDataLineage extracts the data lineage graph from a process protocol. It traces data flow from sources through transformations to sinks.

func (*DataLineage) GetDataProvenance added in v0.5.0

func (l *DataLineage) GetDataProvenance(entityID string) []string

GetDataProvenance returns all source entities that contribute to the specified entity's inputs (upstream provenance analysis).

func (*DataLineage) GetDownstream added in v0.5.0

func (l *DataLineage) GetDownstream(entityID, portName string) []PortReference

GetDownstream returns all ports that receive data from the specified port.

func (*DataLineage) GetImpactedEntities added in v0.5.0

func (l *DataLineage) GetImpactedEntities(entityID string) []string

GetImpactedEntities returns all entities that would be affected if the specified entity's output changes (downstream impact analysis).

func (*DataLineage) GetUpstream added in v0.5.0

func (l *DataLineage) GetUpstream(entityID, portName string) []PortReference

GetUpstream returns all ports that feed data into the specified port.

func (*DataLineage) HasSensitiveDataFlow added in v0.5.0

func (l *DataLineage) HasSensitiveDataFlow() bool

HasSensitiveDataFlow returns true if there's any sensitive data flowing through the lineage graph.

type DataPort added in v0.5.0

type DataPort struct {
	// Kind classifies the data type.
	Kind DataPortKind `json:"kind"`

	// Name is the identifier for this port.
	Name string `json:"name"`

	// Description provides additional context.
	Description string `json:"description,omitempty"`

	// Schema is an optional reference to a JSON Schema.
	Schema string `json:"schema,omitempty"`

	// Required indicates if this input must be provided.
	Required bool `json:"required,omitempty"`

	// Sensitive marks data as containing PII or secrets.
	Sensitive bool `json:"sensitive,omitempty"`
}

DataPort represents an input or output of a process step.

type DataPortKind added in v0.5.0

type DataPortKind string

DataPortKind classifies the type of data port.

const (
	// DataPortKindFile represents file-based data.
	DataPortKindFile DataPortKind = "file"
	// DataPortKindObject represents in-memory object data.
	DataPortKindObject DataPortKind = "object"
	// DataPortKindAPI represents API endpoint data.
	DataPortKindAPI DataPortKind = "api"
	// DataPortKindDatabase represents database data.
	DataPortKindDatabase DataPortKind = "database"
	// DataPortKindQueue represents message queue data.
	DataPortKindQueue DataPortKind = "queue"
	// DataPortKindStream represents streaming data.
	DataPortKindStream DataPortKind = "stream"
)

type DataPortMapping added in v0.5.0

type DataPortMapping struct {
	// OutputPort is the source port name on the From entity.
	OutputPort string `json:"output_port"`
	// InputPort is the target port name on the To entity.
	InputPort string `json:"input_port"`
	// Transformation describes any data transformation applied.
	Transformation string `json:"transformation,omitempty"`
}

DataPortMapping explicitly maps output ports to input ports across a flow.

type DebugSession added in v0.4.0

type DebugSession struct {
	// Executor runs the protocol.
	Executor *Executor

	// Context holds the execution state.
	Context *ExecutionContext

	// Breakpoints maps flow indices to breakpoints.
	Breakpoints map[int]*Breakpoint

	// Watchpoints maps entity IDs to watched state patterns.
	Watchpoints map[string]string
	// contains filtered or unexported fields
}

DebugSession provides interactive debugging of protocol execution.

func NewDebugSession added in v0.4.0

func NewDebugSession(p *Protocol) *DebugSession

NewDebugSession creates a new debug session for a protocol.

func (*DebugSession) Continue added in v0.4.0

func (d *DebugSession) Continue() (*ExecutionStep, error)

Continue runs until a breakpoint is hit or execution completes. Returns the step where it stopped (breakpoint or final step).

func (*DebugSession) EnableBreakpoint added in v0.4.0

func (d *DebugSession) EnableBreakpoint(flowIndex int, enabled bool) error

EnableBreakpoint enables or disables a breakpoint.

func (*DebugSession) FormatFlowList added in v0.4.0

func (d *DebugSession) FormatFlowList() string

FormatFlowList returns a formatted string of all flows.

func (*DebugSession) Inspect added in v0.4.0

func (d *DebugSession) Inspect() *DebugState

Inspect returns the current debug state.

func (*DebugSession) InspectEntity added in v0.4.0

func (d *DebugSession) InspectEntity(id string) (*Entity, string, error)

InspectEntity returns the entity and its current state.

func (*DebugSession) InspectFlow added in v0.4.0

func (d *DebugSession) InspectFlow(index int) (*Flow, error)

InspectFlow returns a flow by index.

func (*DebugSession) ListBreakpoints added in v0.4.0

func (d *DebugSession) ListBreakpoints() []*Breakpoint

ListBreakpoints returns all breakpoints.

func (*DebugSession) ListFlows added in v0.4.0

func (d *DebugSession) ListFlows() []FlowListItem

ListFlows returns all flows with their status.

func (*DebugSession) Protocol added in v0.4.0

func (d *DebugSession) Protocol() *Protocol

Protocol returns the protocol being debugged.

func (*DebugSession) RemoveBreakpoint added in v0.4.0

func (d *DebugSession) RemoveBreakpoint(flowIndex int) error

RemoveBreakpoint removes a breakpoint at the specified flow index.

func (*DebugSession) Reset added in v0.4.0

func (d *DebugSession) Reset()

Reset restarts the debug session from the beginning.

func (*DebugSession) SetBreakpoint added in v0.4.0

func (d *DebugSession) SetBreakpoint(flowIndex int, condition string) error

SetBreakpoint sets a breakpoint at the specified flow index.

func (*DebugSession) SetEntityState added in v0.4.0

func (d *DebugSession) SetEntityState(entityID, stateID string) error

SetEntityState manually sets an entity's state.

func (*DebugSession) Step added in v0.4.0

func (d *DebugSession) Step() (*ExecutionStep, error)

Step executes the next flow and returns the step details. Returns nil when execution is complete.

func (*DebugSession) Trace added in v0.4.0

func (d *DebugSession) Trace() *ExecutionTrace

Trace returns the current execution trace.

type DebugState added in v0.4.0

type DebugState struct {
	// FlowIndex is the current position in the protocol.
	FlowIndex int

	// StepsExecuted is the number of steps executed so far.
	StepsExecuted int

	// CurrentFlow is the next flow to be executed (nil if complete).
	CurrentFlow *Flow

	// EntityStates maps entity IDs to their current states.
	EntityStates map[string]string

	// IsCompleted indicates if execution has finished.
	IsCompleted bool

	// AtBreakpoint indicates if execution stopped at a breakpoint.
	AtBreakpoint bool

	// Error holds any execution error.
	Error error
}

DebugState represents the current state of a debug session.

func (*DebugState) String added in v0.4.0

func (d *DebugState) String() string

DebugStateString returns a human-readable representation of the debug state.

type DependencyAnalysis added in v0.5.0

type DependencyAnalysis struct {
	// EntityID is the step being analyzed.
	EntityID string `json:"entity_id"`

	// Name is the entity name.
	Name string `json:"name"`

	// StepType is the step type.
	StepType StepType `json:"step_type"`

	// DirectDependencies are steps that must complete before this one.
	DirectDependencies []string `json:"direct_dependencies"`

	// TransitiveDependencies are all upstream steps (direct and indirect).
	TransitiveDependencies []string `json:"transitive_dependencies"`

	// DirectDependents are steps that depend on this one.
	DirectDependents []string `json:"direct_dependents"`

	// TransitiveDependents are all downstream steps (direct and indirect).
	TransitiveDependents []string `json:"transitive_dependents"`

	// RequiredInputs lists required input ports.
	RequiredInputs []string `json:"required_inputs"`

	// ProducedOutputs lists output ports.
	ProducedOutputs []string `json:"produced_outputs"`

	// CriticalPath indicates if this step is on the critical path.
	CriticalPath bool `json:"critical_path"`
}

DependencyAnalysis returns a detailed analysis of step dependencies.

type DeploymentComponent added in v0.4.0

type DeploymentComponent struct {
	// ID is the unique identifier for this component.
	ID string `json:"id"`
	// Name is the human-readable display name.
	Name string `json:"name"`
	// Type classifies the component (e.g., "idp", "iga", "gateway", "mcp_client").
	Type string `json:"type"`
	// Description provides additional context.
	Description string `json:"description,omitempty"`
	// Entities lists the entity IDs contained in this component.
	Entities []string `json:"entities,omitempty"`
	// Implements lists the protocol roles this component implements.
	Implements []ProtocolRole `json:"implements,omitempty"`
	// Examples lists real-world products that represent this component type.
	Examples []string `json:"examples,omitempty"`
}

DeploymentComponent defines a logical deployment component that groups entities.

type Determinism added in v0.5.0

type Determinism string

Determinism classifies processing predictability.

const (
	// DeterminismDeterministic indicates repeatable, predictable results.
	DeterminismDeterministic Determinism = "deterministic"
	// DeterminismNonDeterministic indicates variable results (e.g., LLM output).
	DeterminismNonDeterministic Determinism = "non_deterministic"
)

type DiffCategory added in v0.4.0

type DiffCategory string

DiffCategory represents the category of a diff item.

const (
	DiffCategoryEntity   DiffCategory = "entity"
	DiffCategoryFlow     DiffCategory = "flow"
	DiffCategoryPhase    DiffCategory = "phase"
	DiffCategoryMetadata DiffCategory = "metadata"
	DiffCategoryScenario DiffCategory = "scenario"
	DiffCategoryOrder    DiffCategory = "order"
)

type DiffItem added in v0.4.0

type DiffItem struct {
	// Type indicates whether the item was added, removed, or modified.
	Type DiffType `json:"type"`

	// Category classifies what was changed.
	Category DiffCategory `json:"category"`

	// Path identifies the location of the change (e.g., "entities[0]", "flows[2].action").
	Path string `json:"path"`

	// OldValue is the value before the change (nil for additions).
	OldValue interface{} `json:"old_value,omitempty"`

	// NewValue is the value after the change (nil for removals).
	NewValue interface{} `json:"new_value,omitempty"`

	// Summary is a human-readable description of the change.
	Summary string `json:"summary"`
}

DiffItem represents a single difference between two protocols.

type DiffOptions added in v0.4.0

type DiffOptions struct {
	// IgnoreMetadata skips metadata comparison.
	IgnoreMetadata bool

	// IgnoreDescriptions skips description field comparisons.
	IgnoreDescriptions bool

	// DeepFlowCompare enables detailed flow field comparison.
	DeepFlowCompare bool
}

DiffOptions controls comparison behavior.

func DefaultDiffOptions added in v0.4.0

func DefaultDiffOptions() DiffOptions

DefaultDiffOptions returns default comparison options.

type DiffSummary added in v0.4.0

type DiffSummary struct {
	// TotalChanges is the total number of differences.
	TotalChanges int `json:"total_changes"`

	// Added counts items that were added.
	Added int `json:"added"`

	// Removed counts items that were removed.
	Removed int `json:"removed"`

	// Modified counts items that were modified.
	Modified int `json:"modified"`

	// ByCategory breaks down changes by category.
	ByCategory map[DiffCategory]int `json:"by_category"`
}

DiffSummary provides counts of changes by category.

type DiffType added in v0.4.0

type DiffType string

DiffType represents the type of difference.

const (
	// DiffTypeAdded indicates an element was added.
	DiffTypeAdded DiffType = "added"
	// DiffTypeRemoved indicates an element was removed.
	DiffTypeRemoved DiffType = "removed"
	// DiffTypeModified indicates an element was modified.
	DiffTypeModified DiffType = "modified"
)

type Entity

type Entity struct {
	// ID is the unique identifier used in flow references.
	ID string `json:"id"`

	// Name is the human-readable display name.
	Name string `json:"name"`

	// Type classifies the entity.
	Type EntityType `json:"type"`

	// Description of the entity's role.
	Description string `json:"description,omitempty"`

	// TrustLevel classifies the trust level of this entity.
	TrustLevel TrustLevel `json:"trust_level,omitempty"`

	// Metadata contains additional entity properties for rendering.
	Metadata *EntityMetadata `json:"metadata,omitempty"`

	// States defines the possible states for this entity.
	States []EntityState `json:"states,omitempty"`

	// ProtocolRoles defines the protocol-specific roles this entity implements.
	ProtocolRoles []ProtocolRole `json:"protocol_roles,omitempty"`

	// StepType classifies the processing nature (process profile).
	StepType StepType `json:"step_type,omitempty"`

	// Inputs defines input specifications (process profile).
	Inputs []DataPort `json:"inputs,omitempty"`

	// Outputs defines output specifications (process profile).
	Outputs []DataPort `json:"outputs,omitempty"`

	// Processing configures step execution (process profile).
	Processing *ProcessingConfig `json:"processing,omitempty"`

	// FailureModes lists possible failure scenarios (process profile).
	FailureModes []FailureMode `json:"failure_modes,omitempty"`

	// RetryStrategy configures retry behavior (process profile).
	RetryStrategy *RetryStrategy `json:"retry_strategy,omitempty"`

	// Parallel configures parallel execution for this step.
	Parallel *ParallelConfig `json:"parallel,omitempty"`
}

Entity represents a participant in the protocol.

func (Entity) FailureModeByID added in v0.5.0

func (e Entity) FailureModeByID(id string) *FailureMode

FailureModeByID returns the failure mode with the given ID, or nil if not found.

func (Entity) HasInputs added in v0.5.0

func (e Entity) HasInputs() bool

HasInputs returns true if this entity has inputs defined.

func (Entity) HasOutputs added in v0.5.0

func (e Entity) HasOutputs() bool

HasOutputs returns true if this entity has outputs defined.

func (Entity) HasProtocolRoles added in v0.4.0

func (e Entity) HasProtocolRoles() bool

HasProtocolRoles returns true if the entity has protocol roles defined.

func (Entity) HasRole added in v0.4.0

func (e Entity) HasRole(protocol, role string) bool

HasRole checks if the entity has a specific protocol role.

func (Entity) HasStates added in v0.4.0

func (e Entity) HasStates() bool

HasStates returns true if the entity has any states defined.

func (Entity) InitialState added in v0.4.0

func (e Entity) InitialState() *EntityState

InitialState returns the initial state, or nil if none is marked as initial.

func (Entity) InputByName added in v0.5.0

func (e Entity) InputByName(name string) *DataPort

InputByName returns the input with the given name, or nil if not found.

func (Entity) IsDeterministic added in v0.5.0

func (e Entity) IsDeterministic() bool

IsDeterministic returns true if this is a deterministic step.

func (Entity) IsExternalStep added in v0.5.0

func (e Entity) IsExternalStep() bool

IsExternalStep returns true if this is an external service step.

func (Entity) IsHumanStep added in v0.5.0

func (e Entity) IsHumanStep() bool

IsHumanStep returns true if this is a human-in-the-loop step.

func (Entity) IsLLMStep added in v0.5.0

func (e Entity) IsLLMStep() bool

IsLLMStep returns true if this is an LLM-powered step.

func (Entity) IsNonDeterministic added in v0.5.0

func (e Entity) IsNonDeterministic() bool

IsNonDeterministic returns true if this step may produce different outputs for the same inputs.

func (Entity) IsProcessStep added in v0.5.0

func (e Entity) IsProcessStep() bool

IsProcessStep returns true if this entity has process step semantics.

func (Entity) IsToolStep added in v0.5.0

func (e Entity) IsToolStep() bool

IsToolStep returns true if this is a tool invocation step.

func (Entity) OutputByName added in v0.5.0

func (e Entity) OutputByName(name string) *DataPort

OutputByName returns the output with the given name, or nil if not found.

func (Entity) RequiredInputs added in v0.5.0

func (e Entity) RequiredInputs() []DataPort

RequiredInputs returns inputs that are marked as required.

func (Entity) RolesByProtocol added in v0.4.0

func (e Entity) RolesByProtocol(protocol string) []ProtocolRole

RolesByProtocol returns all roles for a specific protocol.

func (Entity) SensitiveInputs added in v0.5.0

func (e Entity) SensitiveInputs() []DataPort

SensitiveInputs returns inputs that are marked as sensitive.

func (Entity) SensitiveOutputs added in v0.5.0

func (e Entity) SensitiveOutputs() []DataPort

SensitiveOutputs returns outputs that are marked as sensitive.

func (Entity) StateByID added in v0.4.0

func (e Entity) StateByID(id string) *EntityState

StateByID returns the state with the given ID, or nil if not found.

func (Entity) StateIDs added in v0.4.0

func (e Entity) StateIDs() []string

StateIDs returns a slice of all state IDs for this entity.

type EntityMetadata added in v0.3.0

type EntityMetadata struct {
	// Network is the network boundary this entity belongs to.
	Network string `json:"network,omitempty"`
	// ServiceType classifies the service (e.g., "api", "database", "gateway").
	ServiceType string `json:"type,omitempty"`
}

EntityMetadata contains additional entity properties.

type EntityState added in v0.4.0

type EntityState struct {
	// ID is the unique identifier for this state within the entity.
	ID string `json:"id"`

	// Name is the human-readable display name.
	Name string `json:"name,omitempty"`

	// Description provides additional context.
	Description string `json:"description,omitempty"`

	// Initial marks this as the initial state.
	Initial bool `json:"initial,omitempty"`

	// Final marks this as a terminal/final state.
	Final bool `json:"final,omitempty"`
}

EntityState represents a possible state for an entity.

type EntityType

type EntityType string

EntityType represents the type of an entity.

const (
	EntityTypeClient              EntityType = "client"
	EntityTypeAuthorizationServer EntityType = "authorization_server"
	EntityTypeResourceServer      EntityType = "resource_server"
	EntityTypeUser                EntityType = "user"
	EntityTypeBrowser             EntityType = "browser"
	EntityTypeAgent               EntityType = "agent"
	EntityTypeToolServer          EntityType = "tool_server"
	EntityTypeTool                EntityType = "tool"
	EntityTypeDelegatedAgent      EntityType = "delegated_agent"
	EntityTypeIdentityProvider    EntityType = "identity_provider"
	EntityTypeServiceProvider     EntityType = "service_provider"
	EntityTypeServer              EntityType = "server"
	EntityTypeOther               EntityType = "other"
)

type ExampleHeader added in v0.8.0

type ExampleHeader struct {
	Name  string `json:"name"`
	Value string `json:"value"`
}

ExampleHeader is one HTTP header. Headers are a list, not a map, so they keep the order they are written in.

type ExampleKind added in v0.8.0

type ExampleKind string

ExampleKind says where a flow example comes from.

const (
	// ExampleKindDraft is taken from the cited source, with values aligned
	// to the scenario so steps link up.
	ExampleKindDraft ExampleKind = "draft"
	// ExampleKindDerived is written from the cited source's normative text
	// where the source has no example.
	ExampleKindDerived ExampleKind = "derived"
)

type ExampleRequest added in v0.8.0

type ExampleRequest struct {
	Method  string          `json:"method"`
	URL     string          `json:"url"`
	Headers []ExampleHeader `json:"headers,omitempty"`
	// Body is the request body as JSON, kept byte for byte so key order
	// survives a round trip.
	Body json.RawMessage `json:"body,omitempty"`
}

ExampleRequest is an illustrative HTTP request.

func (*ExampleRequest) Curl added in v0.9.0

func (r *ExampleRequest) Curl() (string, error)

Curl returns a curl command equivalent to the request: method, URL, each header in order, and the wire body. curl cannot create HTTP message signatures, so when the request is signed a leading comment says the signature headers are replayed from the example.

type ExampleResponse added in v0.8.0

type ExampleResponse struct {
	Status  int             `json:"status"`
	Headers []ExampleHeader `json:"headers,omitempty"`
	Body    json.RawMessage `json:"body,omitempty"`
}

ExampleResponse is an illustrative HTTP response.

type ExampleToken added in v0.8.0

type ExampleToken struct {
	// Token is the token definition ID.
	Token string `json:"token"`
	// Label says where the token travels, such as "Signature-Key header".
	Label string `json:"label,omitempty"`
	// Header and Payload are the decoded JWT header and claims.
	Header  json.RawMessage `json:"header,omitempty"`
	Payload json.RawMessage `json:"payload,omitempty"`
}

ExampleToken is a decoded token carried by a message.

type Exchange added in v0.10.0

type Exchange struct {
	// Time is when the request was made. A tool that has no clock keeps the
	// order and leaves it unset.
	Time *time.Time `json:"time,omitempty"`

	// From and To are the capturing tool's labels for the sender and the
	// receiver, kept as written. A binding maps them to participants.
	From string `json:"from,omitempty"`
	To   string `json:"to,omitempty"`

	// RequestID is the value of a request ID header, when the capture has
	// one. It joins client events and other sources to the exchange.
	RequestID string `json:"requestId,omitempty"`

	Request  ObservedRequest  `json:"request"`
	Response ObservedResponse `json:"response"`

	// BodyTruncated reports that a body was cut at the size limit.
	BodyTruncated bool `json:"bodyTruncated,omitempty"`

	// Label is a name a tool gave the exchange, such as a Newman request's
	// name. It never changes a match.
	Label string `json:"label,omitempty"`

	// Annotations are evidence a tool produced about the exchange, such as
	// assertions or a client's own events. They never change a match.
	Annotations []ExchangeAnnotation `json:"annotations,omitempty"`
}

Exchange is one HTTP request and its response.

type ExchangeAnnotation added in v0.10.0

type ExchangeAnnotation struct {
	// Kind classifies the annotation, such as "assertion" or "client-event".
	Kind string `json:"kind"`

	// Text is the annotation as a person reads it.
	Text string `json:"text"`

	// OK is the result of an assertion; unset for other kinds.
	OK *bool `json:"ok,omitempty"`

	// Time is when the annotated event happened, when it differs from the
	// exchange's time.
	Time *time.Time `json:"time,omitempty"`
}

ExchangeAnnotation is a piece of evidence about an exchange.

type ExecutionContext added in v0.4.0

type ExecutionContext struct {
	// Protocol being executed.
	Protocol *Protocol

	// EntityStates maps entity ID to current state ID.
	EntityStates map[string]string

	// FlowIndex is the current position in the protocol's flows.
	FlowIndex int

	// Trace records execution history.
	Trace *ExecutionTrace

	// EventQueue holds pending events for event-driven execution.
	EventQueue []ExecutionEvent

	// Completed indicates execution has finished.
	Completed bool

	// Error holds any execution error.
	Error error
}

ExecutionContext holds the runtime state of a protocol execution.

func (*ExecutionContext) CurrentFlow added in v0.4.0

func (ctx *ExecutionContext) CurrentFlow() *Flow

CurrentFlow returns the next flow to be executed, or nil if complete.

func (*ExecutionContext) GetEntityState added in v0.4.0

func (ctx *ExecutionContext) GetEntityState(entityID string) string

GetEntityState returns the current state of an entity.

func (*ExecutionContext) Progress added in v0.4.0

func (ctx *ExecutionContext) Progress() float64

Progress returns execution progress as a percentage (0-100).

func (*ExecutionContext) SetEntityState added in v0.4.0

func (ctx *ExecutionContext) SetEntityState(entityID, stateID string)

SetEntityState manually sets an entity's state.

type ExecutionEvent added in v0.4.0

type ExecutionEvent struct {
	// Type categorizes the event.
	Type string `json:"type"`

	// FlowIndex references a specific flow (if applicable).
	FlowIndex int `json:"flow_index,omitempty"`

	// EntityID references a specific entity (if applicable).
	EntityID string `json:"entity_id,omitempty"`

	// Data holds event-specific payload.
	Data map[string]interface{} `json:"data,omitempty"`
}

ExecutionEvent represents a pending event in the queue.

type ExecutionGraph added in v0.5.0

type ExecutionGraph struct {
	// ProtocolID is the source protocol ID.
	ProtocolID string
	// Stages are ordered groups of steps that can execute in parallel.
	Stages []ExecutionStage
	// CriticalPath is the longest path through the graph.
	CriticalPath []string
	// EstimatedDuration is the estimated total execution time.
	EstimatedDuration time.Duration
}

ExecutionGraph represents the execution order of steps.

func AnalyzeExecutionGraph added in v0.5.0

func AnalyzeExecutionGraph(p *Protocol) *ExecutionGraph

AnalyzeExecutionGraph builds an execution graph from a process protocol.

type ExecutionMetrics added in v0.5.0

type ExecutionMetrics struct {
	// Duration is the actual execution time.
	Duration time.Duration `json:"duration"`
	// InputTokens is the actual input token count.
	InputTokens int `json:"input_tokens,omitempty"`
	// OutputTokens is the actual output token count.
	OutputTokens int `json:"output_tokens,omitempty"`
	// APICallCount is the number of API calls made.
	APICallCount int `json:"api_call_count,omitempty"`
}

ExecutionMetrics captures actual execution data for cost calculation.

type ExecutionReadiness added in v0.5.0

type ExecutionReadiness struct {
	// TotalSteps is the total number of process steps.
	TotalSteps int `json:"total_steps"`

	// ReadySteps is the number of steps ready to execute.
	ReadySteps int `json:"ready_steps"`

	// BlockedSteps is the number of blocked steps.
	BlockedSteps int `json:"blocked_steps"`

	// CompletedSteps is the number of completed steps.
	CompletedSteps int `json:"completed_steps"`

	// InProgressSteps is the number of steps currently executing.
	InProgressSteps int `json:"in_progress_steps"`

	// FailedSteps is the number of failed steps.
	FailedSteps int `json:"failed_steps"`

	// NextSteps lists the entity IDs of steps ready to execute.
	NextSteps []string `json:"next_steps"`

	// BlockedReasons maps blocked step IDs to their blocking reasons.
	BlockedReasons map[string][]string `json:"blocked_reasons"`
}

ExecutionReadiness summarizes the execution readiness of the process.

type ExecutionStage added in v0.5.0

type ExecutionStage struct {
	// ID is the stage identifier.
	ID string
	// Steps are entity IDs that can execute in parallel at this stage.
	Steps []string
	// Dependencies are stage IDs that must complete before this stage.
	Dependencies []string
	// IsParallelBlock indicates this stage is an explicit parallel block.
	IsParallelBlock bool
	// ParallelConfig is the configuration for parallel execution.
	ParallelConfig *ParallelConfig
}

ExecutionStage represents a group of steps that can execute concurrently.

type ExecutionStep added in v0.4.0

type ExecutionStep struct {
	// StepNumber is the 1-based step counter.
	StepNumber int `json:"step_number"`

	// FlowIndex is the index in Protocol.Flows.
	FlowIndex int `json:"flow_index"`

	// Timestamp when this step executed.
	Timestamp time.Time `json:"timestamp"`

	// From is the source entity ID.
	From string `json:"from"`

	// To is the target entity ID.
	To string `json:"to"`

	// Action is the flow action.
	Action string `json:"action"`

	// Label is the flow display label.
	Label string `json:"label,omitempty"`

	// Mode is the flow mode.
	Mode FlowMode `json:"mode,omitempty"`

	// Phase is the phase ID.
	Phase string `json:"phase,omitempty"`

	// Condition is the flow's condition (if any).
	Condition string `json:"condition,omitempty"`

	// ConditionMet indicates if condition was satisfied (for conditional flows).
	ConditionMet *bool `json:"condition_met,omitempty"`

	// StateChanges records state mutations from this step.
	StateChanges []StateChange `json:"state_changes,omitempty"`

	// Skipped indicates this flow was skipped (condition not met).
	Skipped bool `json:"skipped,omitempty"`

	// SkipReason explains why flow was skipped.
	SkipReason string `json:"skip_reason,omitempty"`
}

ExecutionStep records a single flow execution.

type ExecutionTrace added in v0.4.0

type ExecutionTrace struct {
	// ProtocolID identifies the executed protocol.
	ProtocolID string `json:"protocol_id"`

	// ProtocolName is the human-readable protocol name.
	ProtocolName string `json:"protocol_name"`

	// StartTime when execution began.
	StartTime time.Time `json:"start_time"`

	// EndTime when execution completed.
	EndTime time.Time `json:"end_time,omitempty"`

	// Steps records each executed flow.
	Steps []ExecutionStep `json:"steps"`

	// InitialStates captures entity states at start.
	InitialStates map[string]string `json:"initial_states,omitempty"`

	// FinalStates captures entity states at end.
	FinalStates map[string]string `json:"final_states,omitempty"`

	// Completed indicates if execution ran to completion.
	Completed bool `json:"completed"`

	// Error message if execution failed.
	Error string `json:"error,omitempty"`
}

ExecutionTrace records the complete execution history.

func (*ExecutionTrace) Duration added in v0.4.0

func (t *ExecutionTrace) Duration() time.Duration

Duration returns the execution duration so far.

func (*ExecutionTrace) SkippedCount added in v0.4.0

func (t *ExecutionTrace) SkippedCount() int

SkippedCount returns the number of skipped steps.

func (*ExecutionTrace) StateChangeCount added in v0.4.0

func (t *ExecutionTrace) StateChangeCount() int

StateChangeCount returns the total number of state changes.

func (*ExecutionTrace) StepCount added in v0.4.0

func (t *ExecutionTrace) StepCount() int

StepCount returns the number of executed steps.

func (*ExecutionTrace) ToJSON added in v0.4.0

func (t *ExecutionTrace) ToJSON() ([]byte, error)

ToJSON returns the trace as JSON bytes.

type Executor added in v0.4.0

type Executor struct {
	// Protocol to execute.
	Protocol *Protocol

	// ConditionEvaluator is called to evaluate flow conditions.
	// If nil, all conditions are assumed to be met.
	ConditionEvaluator func(ctx *ExecutionContext, flow *Flow) bool
}

Executor runs protocol simulations.

func NewExecutor added in v0.4.0

func NewExecutor(p *Protocol) *Executor

NewExecutor creates an Executor for the given protocol.

func (*Executor) NewContext added in v0.4.0

func (e *Executor) NewContext() *ExecutionContext

NewContext creates a fresh execution context with initial states.

func (*Executor) Reset added in v0.4.0

func (e *Executor) Reset(ctx *ExecutionContext)

Reset restarts execution from the beginning.

func (*Executor) Run added in v0.4.0

func (e *Executor) Run(ctx *ExecutionContext) (*ExecutionTrace, error)

Run executes all flows to completion.

func (*Executor) RunN added in v0.4.0

func (e *Executor) RunN(ctx *ExecutionContext, n int) (*ExecutionTrace, error)

RunN executes up to n steps.

func (*Executor) Step added in v0.4.0

func (e *Executor) Step(ctx *ExecutionContext) (*ExecutionStep, error)

Step executes the next flow and returns the step details. Returns nil when execution is complete.

type FailureMode added in v0.5.0

type FailureMode struct {
	// ID is the unique identifier for this failure mode.
	ID string `json:"id"`

	// Name is the human-readable name.
	Name string `json:"name"`

	// Description explains the failure scenario.
	Description string `json:"description,omitempty"`

	// Severity indicates the impact level.
	Severity string `json:"severity,omitempty"`

	// Recovery describes how to handle this failure.
	Recovery string `json:"recovery,omitempty"`
}

FailureMode describes a possible failure scenario.

type FileValidationResult

type FileValidationResult struct {
	Filename string
	Protocol *Protocol
	Errors   ValidationErrors
	ParseErr error
}

FileValidationResult contains the result of validating a single file.

func ValidateFiles

func ValidateFiles(filenames []string) []FileValidationResult

ValidateFiles validates multiple PIDL files, returning results for each.

func (FileValidationResult) IsValid

func (r FileValidationResult) IsValid() bool

IsValid returns true if the file parsed and validated successfully.

type Finding added in v0.8.0

type Finding struct {
	ID          string `json:"id"`
	Severity    string `json:"severity"`
	Title       string `json:"title"`
	Description string `json:"description,omitempty"`
	Location    string `json:"location,omitempty"`
}

Finding is an analysis result attached to a step. Location uses the written-flow form, such as "scenarios[1].flows[0] (consent)" or "flows[3]", optionally followed by a field path.

type Flow

type Flow struct {
	// ID identifies the step within its scenario, for deep links, samples
	// and narration. It is optional, unique within the scenario, and
	// stable when steps are added or moved.
	ID string `json:"id,omitempty"`

	// Narration is spoken for this step, keyed by language. Without it,
	// tools fall back to Description.
	Narration Narration `json:"narration,omitempty"`

	// Representations override the narration when the step is viewed as
	// "http", "curl" or a sample language.
	Representations map[string]RepresentationNarration `json:"representations,omitempty"`

	// From is the source entity ID.
	From string `json:"from,omitempty"`

	// To is the target entity ID.
	To string `json:"to,omitempty"`

	// Action identifies the action being performed.
	Action string `json:"action,omitempty"`

	// Include is the ID of a fragment scenario whose flows take this
	// step's place. An include step has no From, To or Action.
	Include string `json:"include,omitempty"`

	// Label is the display label (defaults to Action).
	Label string `json:"label,omitempty"`

	// Mode is the interaction mode.
	Mode FlowMode `json:"mode,omitempty"`

	// Phase is the phase ID this flow belongs to.
	Phase string `json:"phase,omitempty"`

	// Description provides additional details.
	Description string `json:"description,omitempty"`

	// Sequence is a display-only step number. It never affects order:
	// flows run in array order.
	//
	// Deprecated: move the flow within the flows array to change its order.
	Sequence int `json:"sequence,omitempty"`

	// Condition specifies when this flow is executed (e.g., "token_valid", "error").
	Condition string `json:"condition,omitempty"`

	// Note is a visible annotation displayed on the diagram.
	Note string `json:"note,omitempty"`

	// Annotations are typed annotations for tooling and documentation.
	Annotations []Annotation `json:"annotations,omitempty"`

	// Alternatives are alternative paths from this flow point.
	Alternatives []Alternative `json:"alternatives,omitempty"`

	// Animation configures animation for this flow in animated SVG output.
	// Can be a string (preset name) or FlowAnimation object.
	Animation *FlowAnimation `json:"animation,omitempty"`

	// Sets defines state mutations that occur when this flow executes.
	Sets []StateMutation `json:"sets,omitempty"`

	// Security specifies security requirements for this flow.
	Security *FlowSecurity `json:"security,omitempty"`

	// Verification records the evidentiary provenance/tier of this flow.
	Verification *FlowVerification `json:"verification,omitempty"`

	// DataMappings explicitly maps output ports to input ports for data lineage.
	DataMappings []DataPortMapping `json:"data_mappings,omitempty"`

	// Example is an illustrative request, response and decoded tokens for
	// this step, used by walkthrough viewers.
	Example *FlowExample `json:"example,omitempty"`

	// Match is the rule that says which observed exchanges are this step,
	// when the example's method, path and status are not enough or the
	// step has no example request. A binding can replace it for one
	// deployment.
	Match *StepMatch `json:"match,omitempty"`
}

Flow represents an interaction between two entities.

func (Flow) DisplayLabel

func (f Flow) DisplayLabel() string

DisplayLabel returns the label for display, falling back to Action if Label is empty.

func (Flow) EffectiveMode

func (f Flow) EffectiveMode() FlowMode

EffectiveMode returns the flow mode, defaulting to FlowModeRequest if empty.

func (Flow) HasAlternatives added in v0.2.0

func (f Flow) HasAlternatives() bool

HasAlternatives returns true if the flow has alternative paths.

func (Flow) HasAnnotations added in v0.2.0

func (f Flow) HasAnnotations() bool

HasAnnotations returns true if the flow has annotations.

func (Flow) HasCondition added in v0.2.0

func (f Flow) HasCondition() bool

HasCondition returns true if the flow has a condition.

func (Flow) HasNote added in v0.2.0

func (f Flow) HasNote() bool

HasNote returns true if the flow has a note.

func (Flow) HasSecurity added in v0.4.0

func (f Flow) HasSecurity() bool

HasSecurity returns true if the flow has security requirements.

func (Flow) HasStateMutations added in v0.4.0

func (f Flow) HasStateMutations() bool

HasStateMutations returns true if the flow has any state mutations.

func (Flow) HasVerification added in v0.6.0

func (f Flow) HasVerification() bool

HasVerification returns true if the flow has verification provenance recorded.

func (*Flow) IsInclude added in v0.7.0

func (f *Flow) IsInclude() bool

IsInclude reports whether the flow is an include step.

func (Flow) RequiresEncryption added in v0.4.0

func (f Flow) RequiresEncryption() bool

RequiresEncryption returns true if the flow requires encryption.

func (Flow) RequiresToken added in v0.4.0

func (f Flow) RequiresToken() bool

RequiresToken returns true if the flow requires a token.

type FlowAnimation added in v0.3.0

type FlowAnimation struct {
	// Enabled controls whether this flow is animated. Defaults to true.
	Enabled *bool `json:"enabled,omitempty"`

	// Preset is a semantic preset name (request, success, error, warning, highlight, none).
	Preset AnimationPreset `json:"preset,omitempty"`

	// Duration is the animation cycle duration (e.g., "2s", "1.5s").
	Duration string `json:"duration,omitempty"`

	// Delay is the animation start delay (e.g., "0.5s").
	Delay string `json:"delay,omitempty"`

	// DotColor is the animated dot fill color.
	DotColor string `json:"dot_color,omitempty"`

	// DotSize is the animated dot radius in pixels.
	DotSize int `json:"dot_size,omitempty"`

	// Pulse adds a pulsing effect (useful for errors/warnings).
	Pulse bool `json:"pulse,omitempty"`

	// Easing is the CSS easing function (linear, ease-in-out, etc.).
	Easing string `json:"easing,omitempty"`
}

FlowAnimation configures animation for a flow in animated SVG output.

func (*FlowAnimation) EffectiveDotColor added in v0.3.0

func (f *FlowAnimation) EffectiveDotColor(defaultColor string) string

EffectiveDotColor returns the dot color, applying preset defaults.

func (*FlowAnimation) EffectiveDotSize added in v0.3.0

func (f *FlowAnimation) EffectiveDotSize(defaultSize int) int

EffectiveDotSize returns the dot size, applying preset defaults.

func (*FlowAnimation) IsAnimationEnabled added in v0.3.0

func (f *FlowAnimation) IsAnimationEnabled() bool

IsAnimationEnabled returns whether animation is enabled for this flow.

func (*FlowAnimation) ShouldGlow added in v0.4.0

func (f *FlowAnimation) ShouldGlow() bool

ShouldGlow returns whether the dot should have a glow effect.

func (*FlowAnimation) ShouldPulse added in v0.3.0

func (f *FlowAnimation) ShouldPulse() bool

ShouldPulse returns whether the dot should pulse.

type FlowExample added in v0.8.0

type FlowExample struct {
	// Source cites where the example comes from, such as "draft-11 §7.2.1".
	Source string `json:"source"`

	// Kind is draft or derived.
	Kind ExampleKind `json:"kind"`

	// Request is the HTTP request, for steps that send one.
	Request *ExampleRequest `json:"request,omitempty"`

	// Response is the HTTP response, for steps that return one.
	Response *ExampleResponse `json:"response,omitempty"`

	// Tokens are decoded tokens the message carries, in display order.
	Tokens []ExampleToken `json:"tokens,omitempty"`

	// Samples are code that sends or handles this message, such as SDK
	// calls, shown beside the HTTP form.
	Samples []Sample `json:"samples,omitempty"`

	// Note explains anything the reader should notice in this example.
	Note string `json:"note,omitempty"`
}

FlowExample is an illustrative message for one step: the HTTP request, the HTTP response and decoded tokens. Examples are for explanation; they are not message schemas.

type FlowListItem added in v0.4.0

type FlowListItem struct {
	Index         int
	Flow          *Flow
	IsCurrent     bool
	HasBreakpoint bool
	IsExecuted    bool
}

FlowListItem represents a flow for listing purposes.

type FlowMode

type FlowMode string

FlowMode represents the type of interaction.

const (
	FlowModeRequest     FlowMode = "request"
	FlowModeResponse    FlowMode = "response"
	FlowModeRedirect    FlowMode = "redirect"
	FlowModeCallback    FlowMode = "callback"
	FlowModeInteractive FlowMode = "interactive"
	FlowModeEvent       FlowMode = "event"
	FlowModeToolCall    FlowMode = "tool_call"
	FlowModeToolResult  FlowMode = "tool_result"
)

type FlowSecurity added in v0.4.0

type FlowSecurity struct {
	// Requires lists security mechanisms required for this flow.
	Requires []SecurityRequirement `json:"requires,omitempty"`
	// Token is the token definition ID used for this flow.
	Token string `json:"token,omitempty"`
	// Confidential indicates if the flow carries sensitive data.
	Confidential bool `json:"confidential,omitempty"`
	// Description provides additional security context.
	Description string `json:"description,omitempty"`
	// SignedBy is the entity that signs the request. It defaults to the
	// flow's From entity; set it when someone else signs, for example an
	// intermediary signing on an agent's behalf.
	SignedBy string `json:"signed_by,omitempty"`
	// Issues lists token definition IDs this flow delivers.
	Issues []string `json:"issues,omitempty"`
	// Verifies lists token definition IDs the receiver checks.
	Verifies []string `json:"verifies,omitempty"`
}

FlowSecurity describes security requirements for a flow.

type FlowVerification added in v0.6.0

type FlowVerification struct {
	Tier     VerificationTier `json:"tier"`
	Source   string           `json:"source,omitempty"`   // e.g. "OpenAI technical report", "METR"
	Citation string           `json:"citation,omitempty"` // URL or reference locating the source
}

FlowVerification records the evidentiary provenance of a single flow: its verification tier and where it is sourced from. Used for incident attack-flows where every step must trace to a primary or independent source (or be marked reproduced/inferred).

type Group added in v0.9.0

type Group struct {
	// ID is the unique identifier scenarios refer to.
	ID string `json:"id"`

	// Name is the display name.
	Name string `json:"name"`

	// Description of the group.
	Description string `json:"description,omitempty"`
}

Group is a navigation section that scenarios are listed under.

type JoinCondition added in v0.5.0

type JoinCondition string

JoinCondition specifies when parallel execution is considered complete.

const (
	// JoinConditionAll waits for all branches to complete.
	JoinConditionAll JoinCondition = "all"
	// JoinConditionAny completes when any branch completes.
	JoinConditionAny JoinCondition = "any"
	// JoinConditionMajority completes when majority of branches complete.
	JoinConditionMajority JoinCondition = "majority"
	// JoinConditionQuorum completes when a quorum of branches complete.
	JoinConditionQuorum JoinCondition = "quorum"
)

type LatencyBudget added in v0.5.0

type LatencyBudget struct {
	// P50 is the 50th percentile latency target.
	P50 string `json:"p50,omitempty"`
	// P95 is the 95th percentile latency target.
	P95 string `json:"p95,omitempty"`
	// P99 is the 99th percentile latency target.
	P99 string `json:"p99,omitempty"`
	// Max is the maximum acceptable latency (hard limit).
	Max string `json:"max,omitempty"`
	// ExpectedLatency is the expected typical latency.
	ExpectedLatency string `json:"expected_latency,omitempty"`
	// Critical marks this step as on the critical path.
	Critical bool `json:"critical,omitempty"`
	// VarianceClass indicates latency variability (low, medium, high).
	VarianceClass LatencyVarianceClass `json:"variance_class,omitempty"`
}

LatencyBudget defines timing SLIs (Service Level Indicators) for a step.

type LatencyBudgetViolation added in v0.5.0

type LatencyBudgetViolation struct {
	// EntityID is the violating entity.
	EntityID string `json:"entity_id"`
	// Metric is the violated metric (p50, p95, p99, max).
	Metric string `json:"metric"`
	// Budget is the budgeted latency.
	Budget time.Duration `json:"budget"`
	// Estimated is the estimated latency.
	Estimated time.Duration `json:"estimated"`
	// Severity indicates the violation severity.
	Severity string `json:"severity"`
}

LatencyBudgetViolation describes a step exceeding its latency budget.

type LatencyEstimate added in v0.5.0

type LatencyEstimate struct {
	// EntityID is the entity this estimate is for (empty for total).
	EntityID string `json:"entity_id,omitempty"`
	// P50 is the 50th percentile latency.
	P50 time.Duration `json:"p50"`
	// P95 is the 95th percentile latency.
	P95 time.Duration `json:"p95"`
	// P99 is the 99th percentile latency.
	P99 time.Duration `json:"p99"`
	// Max is the maximum expected latency.
	Max time.Duration `json:"max"`
	// Expected is the expected typical latency.
	Expected time.Duration `json:"expected"`
	// VarianceClass indicates the latency variability.
	VarianceClass LatencyVarianceClass `json:"variance_class"`
	// OnCriticalPath indicates if this step is on the critical path.
	OnCriticalPath bool `json:"on_critical_path"`
}

LatencyEstimate represents an estimated latency for a step.

type LatencyMeasurement added in v0.5.0

type LatencyMeasurement struct {
	// EntityID is the entity that was measured.
	EntityID string `json:"entity_id"`
	// Duration is the actual execution duration.
	Duration time.Duration `json:"duration"`
	// ExceedsP50 indicates if duration exceeded P50 budget.
	ExceedsP50 bool `json:"exceeds_p50,omitempty"`
	// ExceedsP95 indicates if duration exceeded P95 budget.
	ExceedsP95 bool `json:"exceeds_p95,omitempty"`
	// ExceedsP99 indicates if duration exceeded P99 budget.
	ExceedsP99 bool `json:"exceeds_p99,omitempty"`
	// ExceedsMax indicates if duration exceeded Max budget.
	ExceedsMax bool `json:"exceeds_max,omitempty"`
}

LatencyMeasurement records actual execution latency.

func CalculateActualLatency added in v0.5.0

func CalculateActualLatency(entity *Entity, duration time.Duration) *LatencyMeasurement

CalculateActualLatency calculates latency from execution metrics.

type LatencyVarianceClass added in v0.5.0

type LatencyVarianceClass string

LatencyVarianceClass classifies the variability of step latency.

const (
	// LatencyVarianceLow indicates consistent, predictable latency.
	LatencyVarianceLow LatencyVarianceClass = "low"
	// LatencyVarianceMedium indicates moderate latency variance.
	LatencyVarianceMedium LatencyVarianceClass = "medium"
	// LatencyVarianceHigh indicates high variance (e.g., LLM, human tasks).
	LatencyVarianceHigh LatencyVarianceClass = "high"
)

type LineageEdge added in v0.5.0

type LineageEdge struct {
	// SourceEntity is the ID of the entity providing the data.
	SourceEntity string `json:"source_entity"`
	// SourcePort is the name of the output port.
	SourcePort string `json:"source_port"`
	// TargetEntity is the ID of the entity consuming the data.
	TargetEntity string `json:"target_entity"`
	// TargetPort is the name of the input port.
	TargetPort string `json:"target_port"`
	// FlowIndex is the index of the flow that creates this connection.
	FlowIndex int `json:"flow_index"`
	// Transformation describes any data transformation applied.
	Transformation string `json:"transformation,omitempty"`
}

LineageEdge represents a data flow connection between ports.

type Narration added in v0.9.0

type Narration map[string]string

Narration is text written to be spoken, keyed by BCP 47 language tag. It is always an object, so a document can carry several languages and the schema needs no union type.

func (Narration) Languages added in v0.9.0

func (n Narration) Languages() []string

Languages returns the narration's languages, sorted.

func (Narration) Text added in v0.9.0

func (n Narration) Text(lang, source string) (text string, ok bool)

Text returns the narration in lang, falling back to source, the document's source language. ok is false when neither is present.

type NetworkConfig added in v0.3.0

type NetworkConfig struct {
	// Name is the display name for the boundary.
	Name string `json:"name,omitempty"`
	// Style is the visual style: trusted, dmz, external, cloud.
	Style string `json:"style,omitempty"`
	// Entities explicitly lists entity IDs in this boundary.
	Entities []string `json:"entities,omitempty"`
	// Description provides tooltip/hover text.
	Description string `json:"description,omitempty"`
	// Color overrides the default boundary color.
	Color string `json:"color,omitempty"`
}

NetworkConfig defines a network boundary.

type NetworkLayoutConfig added in v0.3.0

type NetworkLayoutConfig struct {
	// Direction is the layout direction: horizontal or vertical.
	Direction string `json:"direction,omitempty"`
	// Order specifies the boundary ordering.
	Order []string `json:"order,omitempty"`
}

NetworkLayoutConfig configures network diagram layout.

type Observation added in v0.10.0

type Observation struct {
	// Format names the format and its major version: pidl-observation/v1.
	Format string `json:"format"`

	// Source says which tool produced the observation and what it covers.
	Source ObservationSource `json:"source"`

	// Exchanges are the requests and responses, in the order they happened.
	Exchanges []Exchange `json:"exchanges"`
}

Observation is a captured run of a real system: the HTTP exchanges it made, in order, whatever tool captured them. Generation matches its exchanges to a document's steps, using a Binding for the deployment, and shows them beside the steps' examples.

func ParseObservation added in v0.10.0

func ParseObservation(data []byte) (*Observation, error)

ParseObservation parses an observation. It refuses another major version of the format.

func ReadObservation added in v0.10.0

func ReadObservation(path string) (*Observation, error)

ReadObservation reads an observation file.

func (*Observation) Validate added in v0.10.0

func (o *Observation) Validate() ValidationErrors

Validate checks the observation's structure: a format, a source tool, and for each exchange a method, an absolute URL and a response status.

func (*Observation) WriteFile added in v0.10.0

func (o *Observation) WriteFile(path string) error

WriteFile writes the observation as indented JSON.

type ObservationSource added in v0.10.0

type ObservationSource struct {
	// Tool names the tool that captured the exchanges, such as
	// "aauth-sandbox", "har" or "newman".
	Tool string `json:"tool"`

	// RequestFidelity is wire or client; empty when unknown.
	RequestFidelity RequestFidelity `json:"requestFidelity,omitempty"`

	// From and To bound the time the observation covers.
	From *time.Time `json:"from,omitempty"`
	To   *time.Time `json:"to,omitempty"`
}

ObservationSource describes where an observation came from.

type ObservedExtra added in v0.10.0

type ObservedExtra struct {
	// AfterStep is the number of the step it followed, or 0 when it came
	// before the first matched step.
	AfterStep int `json:"after_step"`
	// From and To are the participants, when the binding resolved them.
	From     string          `json:"from,omitempty"`
	To       string          `json:"to,omitempty"`
	Observed ObservedMessage `json:"observed"`
}

ObservedExtra is an observed exchange that matched no step.

type ObservedHeaders added in v0.10.0

type ObservedHeaders [][2]string

ObservedHeaders are header fields as name and value pairs, in their original order and case.

func (ObservedHeaders) Get added in v0.10.0

func (h ObservedHeaders) Get(name string) (string, bool)

Get returns the first value of the named header, comparing names without regard to case.

type ObservedMessage added in v0.10.0

type ObservedMessage struct {
	Time *time.Time `json:"time,omitempty"`
	// From and To are the capturing tool's labels for sender and receiver.
	From string `json:"from,omitempty"`
	To   string `json:"to,omitempty"`
	// RequestID is the value of a request ID header, when the capture has one.
	RequestID string           `json:"request_id,omitempty"`
	Request   *ExampleRequest  `json:"request,omitempty"`
	Response  *ExampleResponse `json:"response,omitempty"`
	// Tokens are the tokens found in the message, decoded and not verified.
	Tokens []ExampleToken `json:"tokens,omitempty"`
	// Label and Annotations are evidence the capturing tool recorded.
	Label       string               `json:"label,omitempty"`
	Annotations []ExchangeAnnotation `json:"annotations,omitempty"`
	// Repeats is how many exchanges a repeated step took, when more than one.
	Repeats int `json:"repeats,omitempty"`
	// BodyTruncated reports that a body was cut at the capture's size limit.
	BodyTruncated bool `json:"body_truncated,omitempty"`
}

ObservedMessage is an exchange observed in a real system, shown as a step's example is: request, response and decoded tokens.

type ObservedRequest added in v0.10.0

type ObservedRequest struct {
	Method  string          `json:"method"`
	URL     string          `json:"url"`
	Headers ObservedHeaders `json:"headers,omitempty"`
	// Body is a JSON value for a JSON body, a JSON string for other text,
	// or {"base64": "…", "mediaType": "…"} for binary content.
	Body json.RawMessage `json:"body,omitempty"`
}

ObservedRequest is a captured HTTP request.

type ObservedResponse added in v0.10.0

type ObservedResponse struct {
	Status  int             `json:"status"`
	Headers ObservedHeaders `json:"headers,omitempty"`
	// Body is encoded as ObservedRequest.Body is.
	Body json.RawMessage `json:"body,omitempty"`
}

ObservedResponse is a captured HTTP response.

type ObservedRun added in v0.10.0

type ObservedRun struct {
	// Scenario is the ID of the scenario this entry is an instance of.
	Scenario string `json:"scenario"`
	// Source names the tool that captured the run; RequestFidelity says
	// whether its requests are the wire messages or a client's.
	Source          string          `json:"source"`
	RequestFidelity RequestFidelity `json:"request_fidelity,omitempty"`
	// Instance is this instance's number, from 1, of Instances found.
	Instance  int `json:"instance"`
	Instances int `json:"instances"`
	// From and To bound the instance's exchanges in time.
	From *time.Time `json:"from,omitempty"`
	To   *time.Time `json:"to,omitempty"`
	// RunnerUp is the next-best scenario at this point of the capture.
	RunnerUp string `json:"runner_up,omitempty"`
	// Counts of step outcomes; Matched counts every matched step and Weak
	// the matched steps that are weak. Explained counts exchanges matched
	// to steps and Extra those that matched none.
	Matched      int `json:"matched"`
	Weak         int `json:"weak"`
	NotSeen      int `json:"not_seen"`
	Skipped      int `json:"skipped"`
	Unmatchable  int `json:"unmatchable"`
	Unobservable int `json:"unobservable"`
	Explained    int `json:"explained"`
	Extra        int `json:"extra"`
	// Redacted reports that raw token, signature and credential values
	// were masked.
	Redacted bool `json:"redacted"`
}

ObservedRun summarizes one instance of a scenario found in a capture.

type Outline added in v0.7.0

type Outline struct {
	ID          string            `json:"id"`
	Name        string            `json:"name"`
	Description string            `json:"description,omitempty"`
	Roles       []OutlineRole     `json:"roles"`
	Groups      []Group           `json:"groups,omitempty"`
	Scenarios   []OutlineScenario `json:"scenarios"`
	Tokens      []OutlineToken    `json:"tokens,omitempty"`
}

Outline is an ordered summary of a protocol for building guides and presentations: roles in entities order, then scenarios in output order (main scenarios, then fragments) with numbered steps, then tokens in declared order. Every list keeps document order, so material built from an outline matches the diagrams generated from the same file.

type OutlineRole added in v0.7.0

type OutlineRole struct {
	Position    int    `json:"position"`
	ID          string `json:"id"`
	Name        string `json:"name"`
	Type        string `json:"type,omitempty"`
	Description string `json:"description,omitempty"`
}

OutlineRole is one entity in an outline.

type OutlineScenario added in v0.7.0

type OutlineScenario struct {
	Position     int           `json:"position"`
	ID           string        `json:"id"`
	Name         string        `json:"name"`
	Description  string        `json:"description,omitempty"`
	Fragment     bool          `json:"fragment,omitempty"`
	Group        string        `json:"group,omitempty"`
	VariantOf    string        `json:"variant_of,omitempty"`
	VariantLabel string        `json:"variant_label,omitempty"`
	Participants []string      `json:"participants"`
	Steps        []OutlineStep `json:"steps"`
}

OutlineScenario is one scenario in an outline.

type OutlineStep added in v0.7.0

type OutlineStep struct {
	Number   int    `json:"number"`
	From     string `json:"from,omitempty"`
	To       string `json:"to,omitempty"`
	Label    string `json:"label"`
	Response bool   `json:"response,omitempty"`
	Phase    string `json:"phase,omitempty"`
	// Include is the fragment ID for an include step, and IncludePosition
	// its position among the outline's scenarios.
	Include         string `json:"include,omitempty"`
	IncludePosition int    `json:"include_position,omitempty"`
}

OutlineStep is one numbered step of a scenario: a message, or an include of a fragment.

type OutlineToken added in v0.7.0

type OutlineToken struct {
	ID         string   `json:"id"`
	Name       string   `json:"name"`
	Issuer     string   `json:"issuer,omitempty"`
	Audience   string   `json:"audience,omitempty"`
	VerifiedBy []string `json:"verified_by,omitempty"`
}

OutlineToken is one token definition in an outline.

type ParallelBlock added in v0.5.0

type ParallelBlock struct {
	// ID is the unique identifier for this block.
	ID string
	// ForkEntity is the entity that starts the parallel execution.
	ForkEntity string
	// JoinEntity is the entity that collects results (if any).
	JoinEntity string
	// Branches are the parallel branches.
	Branches []ParallelBranch
	// Mode is the parallel execution mode.
	Mode ParallelMode
	// JoinCondition specifies completion criteria.
	JoinCondition JoinCondition
}

ParallelBlock represents a detected parallel execution block.

func DetectParallelBlocks added in v0.5.0

func DetectParallelBlocks(p *Protocol) []ParallelBlock

DetectParallelBlocks identifies explicit parallel execution blocks in the protocol.

type ParallelBranch added in v0.5.0

type ParallelBranch struct {
	// ID is the unique identifier for this branch.
	ID string `json:"id"`
	// Name is the human-readable name.
	Name string `json:"name,omitempty"`
	// EntityID is the target entity for this branch (optional).
	EntityID string `json:"entity_id,omitempty"`
	// FlowRefs lists flow indices that belong to this branch.
	FlowRefs []int `json:"flow_refs,omitempty"`
	// Condition specifies when this branch is executed.
	Condition string `json:"condition,omitempty"`
	// Weight for load balancing in scatter mode.
	Weight float64 `json:"weight,omitempty"`
}

ParallelBranch represents a branch in parallel execution.

type ParallelConfig added in v0.5.0

type ParallelConfig struct {
	// Mode specifies the parallel execution mode.
	Mode ParallelMode `json:"mode"`
	// Branches lists the parallel branches (entity IDs or flow groups).
	Branches []ParallelBranch `json:"branches,omitempty"`
	// JoinCondition specifies when parallel execution is considered complete.
	JoinCondition JoinCondition `json:"join_condition,omitempty"`
	// MaxConcurrency limits the number of concurrent executions.
	MaxConcurrency int `json:"max_concurrency,omitempty"`
	// Timeout for the entire parallel block.
	Timeout string `json:"timeout,omitempty"`
}

ParallelConfig configures parallel execution for a step or flow.

type ParallelMode added in v0.5.0

type ParallelMode string

ParallelMode specifies how parallel execution is structured.

const (
	// ParallelModeForkJoin executes branches in parallel and waits for all.
	ParallelModeForkJoin ParallelMode = "fork_join"
	// ParallelModeRace executes branches in parallel, first to complete wins.
	ParallelModeRace ParallelMode = "race"
	// ParallelModeScatter distributes work across multiple instances.
	ParallelModeScatter ParallelMode = "scatter"
	// ParallelModeGather collects results from parallel branches.
	ParallelModeGather ParallelMode = "gather"
)

type Phase

type Phase struct {
	// ID is the unique identifier.
	ID string `json:"id"`

	// Name is the human-readable name.
	Name string `json:"name"`

	// Description of the phase.
	Description string `json:"description,omitempty"`

	// Parent is the ID of the parent phase for nested phases.
	Parent string `json:"parent,omitempty"`
}

Phase represents a logical grouping of flows.

type PortReference added in v0.5.0

type PortReference struct {
	// EntityID is the ID of the entity.
	EntityID string `json:"entity_id"`
	// PortName is the name of the port.
	PortName string `json:"port_name"`
	// PortKind indicates if this is an input or output port.
	PortKind string `json:"port_kind"` // "input" or "output"
	// Sensitive indicates if the port handles sensitive data.
	Sensitive bool `json:"sensitive,omitempty"`
}

PortReference identifies a specific port on an entity.

type PortSchemaValidator added in v0.5.0

type PortSchemaValidator struct {
	// contains filtered or unexported fields
}

PortSchemaValidator validates data ports against their schemas.

func NewPortSchemaValidator added in v0.5.0

func NewPortSchemaValidator() *PortSchemaValidator

NewPortSchemaValidator creates a new port schema validator.

func (*PortSchemaValidator) SetBasePath added in v0.5.0

func (v *PortSchemaValidator) SetBasePath(path string)

SetBasePath sets the base directory for resolving relative schema paths.

func (*PortSchemaValidator) ValidateEntityInputs added in v0.5.0

func (v *PortSchemaValidator) ValidateEntityInputs(entity Entity, inputs map[string]interface{}) (*SchemaValidationResult, error)

ValidateEntityInputs validates all input data for an entity.

func (*PortSchemaValidator) ValidateEntityOutputs added in v0.5.0

func (v *PortSchemaValidator) ValidateEntityOutputs(entity Entity, outputs map[string]interface{}) (*SchemaValidationResult, error)

ValidateEntityOutputs validates all output data from an entity.

func (*PortSchemaValidator) ValidatePortData added in v0.5.0

func (v *PortSchemaValidator) ValidatePortData(port DataPort, data interface{}) (*SchemaValidationResult, error)

ValidatePortData validates data against a port's schema.

type ProcessCostAnalysis added in v0.5.0

type ProcessCostAnalysis struct {
	// ProtocolID is the source protocol.
	ProtocolID string `json:"protocol_id"`
	// TotalEstimate is the total estimated cost.
	TotalEstimate CostEstimate `json:"total_estimate"`
	// StepEstimates are per-step cost estimates.
	StepEstimates []CostEstimate `json:"step_estimates"`
	// CostByType shows costs grouped by step type.
	CostByType map[StepType]float64 `json:"cost_by_type"`
	// CriticalPathCost is the cost of the critical path.
	CriticalPathCost float64 `json:"critical_path_cost"`
	// ParallelSavings is estimated savings from parallelization.
	ParallelSavings float64 `json:"parallel_savings,omitempty"`
}

ProcessCostAnalysis provides complete cost analysis for a process.

func AnalyzeProcessCosts added in v0.5.0

func AnalyzeProcessCosts(p *Protocol) *ProcessCostAnalysis

AnalyzeProcessCosts calculates cost estimates for a process protocol.

type ProcessExecutionContext added in v0.5.0

type ProcessExecutionContext struct {
	*ExecutionContext

	// AvailableInputs tracks which data ports have data available.
	// Key is "entityID.portName", value is true if available.
	AvailableInputs map[string]bool

	// ProducedOutputs tracks which outputs have been produced.
	// Key is "entityID.portName", value is true if produced.
	ProducedOutputs map[string]bool

	// BlockedSteps tracks which steps are blocked and why.
	BlockedSteps map[string][]string // entityID -> list of missing inputs

	// ExecutionOrder is the topologically sorted execution order.
	ExecutionOrder []string

	// StepStatus tracks the status of each step.
	StepStatus map[string]StepExecutionStatus
}

ProcessExecutionContext extends ExecutionContext with process-specific tracking.

type ProcessExecutor added in v0.5.0

type ProcessExecutor struct {
	*Executor

	// DataFlowGraph maps entity outputs to consuming entity inputs.
	// Key is "sourceEntityID.outputName", value is list of "targetEntityID.inputName".
	DataFlowGraph map[string][]string

	// Dependencies maps entity ID to its required predecessor entity IDs.
	Dependencies map[string][]string

	// Dependents maps entity ID to entities that depend on it.
	Dependents map[string][]string
}

ProcessExecutor provides process-aware execution with data flow tracking.

func NewProcessExecutor added in v0.5.0

func NewProcessExecutor(p *Protocol) (*ProcessExecutor, error)

NewProcessExecutor creates a ProcessExecutor for process spec simulation.

func (*ProcessExecutor) AnalyzeDependencies added in v0.5.0

func (pe *ProcessExecutor) AnalyzeDependencies() []DependencyAnalysis

AnalyzeDependencies returns dependency analysis for all process steps.

func (*ProcessExecutor) CompleteStep added in v0.5.0

func (pe *ProcessExecutor) CompleteStep(ctx *ProcessExecutionContext, entityID string) error

CompleteStep marks a step as completed and produces its outputs.

func (*ProcessExecutor) FailStep added in v0.5.0

func (pe *ProcessExecutor) FailStep(ctx *ProcessExecutionContext, entityID string) error

FailStep marks a step as failed.

func (*ProcessExecutor) GetBlockedSteps added in v0.5.0

func (pe *ProcessExecutor) GetBlockedSteps(ctx *ProcessExecutionContext) map[string][]string

GetBlockedSteps returns steps that cannot execute due to missing inputs.

func (*ProcessExecutor) GetExecutionReadiness added in v0.5.0

func (pe *ProcessExecutor) GetExecutionReadiness(ctx *ProcessExecutionContext) ExecutionReadiness

GetExecutionReadiness returns a summary of execution readiness.

func (*ProcessExecutor) GetReadySteps added in v0.5.0

func (pe *ProcessExecutor) GetReadySteps(ctx *ProcessExecutionContext) []string

GetReadySteps returns steps that have all required inputs available.

func (*ProcessExecutor) MarkInputAvailable added in v0.5.0

func (pe *ProcessExecutor) MarkInputAvailable(ctx *ProcessExecutionContext, entityID, inputName string)

MarkInputAvailable marks a data port as having data available.

func (*ProcessExecutor) MarkOutputProduced added in v0.5.0

func (pe *ProcessExecutor) MarkOutputProduced(ctx *ProcessExecutionContext, entityID, outputName string)

MarkOutputProduced marks an output as produced and propagates to connected inputs.

func (*ProcessExecutor) NewProcessContext added in v0.5.0

func (pe *ProcessExecutor) NewProcessContext() *ProcessExecutionContext

NewProcessContext creates a fresh process execution context.

func (*ProcessExecutor) StartStep added in v0.5.0

func (pe *ProcessExecutor) StartStep(ctx *ProcessExecutionContext, entityID string) error

StartStep marks a step as in progress.

func (*ProcessExecutor) TopologicalSort added in v0.5.0

func (pe *ProcessExecutor) TopologicalSort() []string

TopologicalSort returns entities in topological execution order. Steps with no dependencies come first.

type ProcessLatencyAnalysis added in v0.5.0

type ProcessLatencyAnalysis struct {
	// ProtocolID is the source protocol.
	ProtocolID string `json:"protocol_id"`
	// TotalLatency is the estimated end-to-end latency.
	TotalLatency LatencyEstimate `json:"total_latency"`
	// StepLatencies are per-step latency estimates.
	StepLatencies []LatencyEstimate `json:"step_latencies"`
	// CriticalPathLatency is the latency of the critical path.
	CriticalPathLatency LatencyEstimate `json:"critical_path_latency"`
	// CriticalPath is the list of entity IDs on the critical path.
	CriticalPath []string `json:"critical_path"`
	// ParallelSavings is the latency saved by parallel execution.
	ParallelSavings time.Duration `json:"parallel_savings"`
	// BudgetViolations lists steps exceeding their latency budget.
	BudgetViolations []LatencyBudgetViolation `json:"budget_violations,omitempty"`
	// LatencyByType shows latencies grouped by step type.
	LatencyByType map[StepType]time.Duration `json:"latency_by_type"`
}

ProcessLatencyAnalysis provides complete latency analysis for a process.

func AnalyzeProcessLatency added in v0.5.0

func AnalyzeProcessLatency(p *Protocol) *ProcessLatencyAnalysis

AnalyzeProcessLatency calculates latency estimates for a process protocol.

type ProcessingConfig added in v0.5.0

type ProcessingConfig struct {
	// Engine identifies the processing engine.
	Engine string `json:"engine,omitempty"`

	// Determinism indicates processing predictability.
	Determinism Determinism `json:"determinism,omitempty"`

	// ModelPolicy specifies model selection for LLM steps.
	ModelPolicy string `json:"model_policy,omitempty"`

	// Timeout is the maximum processing duration.
	Timeout string `json:"timeout,omitempty"`

	// Idempotent indicates if repeated execution is safe.
	Idempotent bool `json:"idempotent,omitempty"`

	// Cacheable indicates if outputs can be cached.
	Cacheable bool `json:"cacheable,omitempty"`

	// CacheTTL is the cache time-to-live if cacheable.
	CacheTTL string `json:"cache_ttl,omitempty"`

	// CostModel specifies the cost tracking model for this step.
	CostModel *CostModel `json:"cost_model,omitempty"`

	// LatencyBudget specifies timing SLIs for this step.
	LatencyBudget *LatencyBudget `json:"latency_budget,omitempty"`
}

ProcessingConfig describes how a step processes its inputs.

type ProjectOptions added in v0.7.0

type ProjectOptions struct {
	// Expand replaces include steps with the included fragment's flows,
	// recursively. When false, include steps are kept so renderers can
	// draw them as a labeled box.
	Expand bool
}

ProjectOptions controls how a scenario is projected into a single-flow Protocol.

type Protocol

type Protocol struct {
	// ProtocolMeta contains metadata about the protocol.
	ProtocolMeta ProtocolMeta `json:"protocol"`

	// Extends specifies a base protocol to extend.
	Extends *ProtocolExtends `json:"extends,omitempty"`

	// Imports specifies other protocol files to import from.
	Imports []ProtocolImport `json:"imports,omitempty"`

	// Entities are the participants in the protocol (systems, actors, services).
	Entities []Entity `json:"entities"`

	// Phases provide optional logical grouping of flows.
	Phases []Phase `json:"phases,omitempty"`

	// Flows are the interactions between entities. A document has either
	// Flows (a single unnamed scenario) or Scenarios, not both.
	Flows []Flow `json:"flows,omitempty"`

	// Pronunciations map a term to its spoken form per language, such as
	// {"agent_jkt": {"en-US": "agent J K T"}}, in the shape videoascode
	// reads. Entries are looked up by term, never listed in order.
	Pronunciations map[string]map[string]string `json:"pronunciations,omitempty"`

	// Groups are ordered sections for navigation, such as "Signing" or
	// "Access modes". Scenarios name their group; group order, then
	// scenario order within a group, sets the output order.
	Groups []Group `json:"groups,omitempty"`

	// Scenarios are named, ordered sequences of flows. Array position is
	// the scenario order.
	Scenarios []Scenario `json:"scenarios,omitempty"`

	// Fragments holds the fragment scenarios that include steps in a
	// collapsed projection refer to, so renderers can label and size the
	// include boxes. Protocol.Scenario sets it; it is never serialized.
	Fragments []Scenario `json:"-"`

	// Metadata contains additional protocol-level configuration.
	Metadata *ProtocolMetadata `json:"metadata,omitempty"`
	// contains filtered or unexported fields
}

Protocol represents a complete PIDL document describing a protocol's choreography.

func MustParse

func MustParse(data []byte) *Protocol

MustParse parses PIDL JSON data and panics on error. Use only in tests or initialization code.

func MustParseFile

func MustParseFile(filename string) *Protocol

MustParseFile reads and parses a PIDL JSON file, panicking on error. Use only in tests or initialization code.

func NewMinimalProtocol

func NewMinimalProtocol(id, name string) *Protocol

NewMinimalProtocol creates a minimal valid protocol scaffold.

func Parse

func Parse(data []byte) (*Protocol, error)

Parse parses PIDL JSON data into a Protocol.

func ParseFile

func ParseFile(filename string) (*Protocol, error)

ParseFile reads and parses a PIDL JSON file.

func ParseReader

func ParseReader(r io.Reader) (*Protocol, error)

ParseReader parses PIDL JSON from an io.Reader.

func (*Protocol) AllComponentTypes added in v0.4.0

func (p *Protocol) AllComponentTypes() []string

AllComponentTypes returns a unique list of all component types. Returns an empty slice if no components exist or Metadata is nil.

func (*Protocol) AllProtocols added in v0.4.0

func (p *Protocol) AllProtocols() []string

AllProtocols returns a unique list of all protocols referenced in entity roles. Returns an empty slice if no protocols are found.

func (*Protocol) AllTrustRelationTypes added in v0.4.0

func (p *Protocol) AllTrustRelationTypes() []string

AllTrustRelationTypes returns a unique list of all trust relation types. Returns an empty slice if no trust relations exist or Metadata is nil.

func (*Protocol) CheckSamples added in v0.9.0

func (p *Protocol) CheckSamples(lock *SampleLock, read SourceReader) []string

CheckSamples compares the lock with the sources. It reports sources missing from the lock, locked code whose hash is wrong, sources whose region changed since it was resolved, and lock entries no sample uses.

func (*Protocol) ChildPhases added in v0.2.0

func (p *Protocol) ChildPhases(parentID string) []Phase

ChildPhases returns phases that have the given parent ID.

func (*Protocol) ComponentByID added in v0.4.0

func (p *Protocol) ComponentByID(id string) *DeploymentComponent

ComponentByID returns the component with the given ID, or nil if not found.

func (*Protocol) ComponentForEntity added in v0.4.0

func (p *Protocol) ComponentForEntity(entityID string) *DeploymentComponent

ComponentForEntity returns the component that contains an entity, or nil if not found.

func (*Protocol) ComponentsByType added in v0.4.0

func (p *Protocol) ComponentsByType(componentType string) []DeploymentComponent

ComponentsByType returns all components of a given type. Returns an empty slice if no components match or Metadata is nil.

func (*Protocol) DeterministicSteps added in v0.5.0

func (p *Protocol) DeterministicSteps() []Entity

DeterministicSteps returns all entities that are deterministic steps.

func (*Protocol) DirectParticipants added in v0.7.0

func (p *Protocol) DirectParticipants(id string) []string

DirectParticipants returns the entities that scenario id's own message flows use, in entities order, leaving out entities that appear only in included fragments. It returns nil for an unknown scenario.

func (*Protocol) EntitiesByProtocol added in v0.4.0

func (p *Protocol) EntitiesByProtocol(protocol string) []Entity

EntitiesByProtocol returns all entities that implement a role for a specific protocol.

func (*Protocol) EntitiesByRole added in v0.4.0

func (p *Protocol) EntitiesByRole(protocol, role string) []Entity

EntitiesByRole returns all entities that implement a specific protocol role.

func (*Protocol) EntitiesInComponent added in v0.4.0

func (p *Protocol) EntitiesInComponent(componentID string) []Entity

EntitiesInComponent returns all entities that belong to a component. Returns an empty slice if the component is not found.

func (*Protocol) EntitiesWithProtocolRoles added in v0.4.0

func (p *Protocol) EntitiesWithProtocolRoles() []Entity

EntitiesWithProtocolRoles returns all entities that have protocol roles defined.

func (*Protocol) EntitiesWithStates added in v0.4.0

func (p *Protocol) EntitiesWithStates() []Entity

EntitiesWithStates returns all entities that have states defined.

func (*Protocol) EntityByID

func (p *Protocol) EntityByID(id string) *Entity

EntityByID returns the entity with the given ID, or nil if not found.

func (*Protocol) EntityIDs

func (p *Protocol) EntityIDs() []string

EntityIDs returns a slice of all entity IDs.

func (*Protocol) EntityIndex added in v0.7.0

func (p *Protocol) EntityIndex(id string) int

EntityIndex returns the position of entity id in Entities, or -1.

func (*Protocol) Flatten added in v0.7.0

func (p *Protocol) Flatten() *Protocol

Flatten returns a single-flow Protocol holding every scenario's message flows exactly once, in document order. Include steps are dropped, since each fragment contributes its own flows. Use it for whole-document checks such as security analysis, where expanding fragments into every scenario that includes them would repeat their findings. For a document without scenarios it returns a copy of p.

func (*Protocol) FlowsByPhase

func (p *Protocol) FlowsByPhase(phaseID string) []Flow

FlowsByPhase returns all flows belonging to the given phase.

func (*Protocol) GroupByID added in v0.9.0

func (p *Protocol) GroupByID(id string) *Group

GroupByID returns the group with the given ID, or nil.

func (*Protocol) HasScenarios added in v0.7.0

func (p *Protocol) HasScenarios() bool

HasScenarios reports whether the document uses named scenarios rather than a single top-level flows list.

func (*Protocol) IncludeSpan added in v0.7.0

func (p *Protocol) IncludeSpan(f Flow) (string, []string)

IncludeSpan returns the label for an include step's box and the participants the box spans, in entities order. The label is the step's Label, else the fragment's name, else its ID. Participants are limited to entities present in p, so a box never spans a participant the diagram does not show.

func (*Protocol) IsProcessSpec added in v0.5.0

func (p *Protocol) IsProcessSpec() bool

IsProcessSpec returns true if this is a process specification.

func (*Protocol) IsResolved added in v0.4.0

func (p *Protocol) IsResolved() bool

IsResolved returns true if the protocol has been resolved.

func (*Protocol) IsValid

func (p *Protocol) IsValid() bool

IsValid returns true if the Protocol passes validation.

func (*Protocol) Kind added in v0.5.0

func (p *Protocol) Kind() ProtocolKind

Kind returns the protocol kind, defaulting to "protocol".

func (*Protocol) LLMSteps added in v0.5.0

func (p *Protocol) LLMSteps() []Entity

LLMSteps returns all entities that are LLM-powered steps.

func (*Protocol) NeedsResolution added in v0.4.0

func (p *Protocol) NeedsResolution() bool

NeedsResolution returns true if the protocol has imports or extends that need resolution.

func (*Protocol) OrderEntities added in v0.7.0

func (p *Protocol) OrderEntities(ids []string) []string

OrderEntities returns ids sorted by their position in Entities, with duplicates removed. IDs that are not entities sort last, in their original relative order.

func (*Protocol) OrderedScenarios added in v0.9.0

func (p *Protocol) OrderedScenarios() []int

OrderedScenarios returns indexes into Scenarios in output order. Main scenarios come first: grouped scenarios in group order, then scenarios without a known group, each in document order within its section, with every variant placed directly after its base in document order. Fragments follow in document order. A file without groups or variants keeps document order.

func (*Protocol) Outline added in v0.7.0

func (p *Protocol) Outline() Outline

Outline returns an ordered summary of the protocol. A document without scenarios appears as a single scenario named after the protocol.

func (*Protocol) PhaseByID

func (p *Protocol) PhaseByID(id string) *Phase

PhaseByID returns the phase with the given ID, or nil if not found.

func (*Protocol) PhaseDepth added in v0.2.0

func (p *Protocol) PhaseDepth(phaseID string) int

PhaseDepth returns the nesting depth of a phase (0 for root phases).

func (*Protocol) PhaseIDs

func (p *Protocol) PhaseIDs() []string

PhaseIDs returns a slice of all phase IDs.

func (*Protocol) ProcessSteps added in v0.5.0

func (p *Protocol) ProcessSteps() []Entity

ProcessSteps returns all entities that have process step semantics (StepType set).

func (*Protocol) Resolve added in v0.4.0

func (p *Protocol) Resolve(opts ResolveOptions) (*Protocol, error)

Resolve resolves all imports and extends in the protocol, returning a new fully-resolved Protocol. The original is not modified.

func (*Protocol) ResolveSamples added in v0.9.0

func (p *Protocol) ResolveSamples(read SourceReader) (*SampleLock, error)

ResolveSamples reads every sample source and returns a lock with its code and hash. It reports every source that cannot be read or extracted.

func (*Protocol) RootPhases added in v0.2.0

func (p *Protocol) RootPhases() []Phase

RootPhases returns phases that have no parent (top-level phases).

func (*Protocol) SampleSources added in v0.9.0

func (p *Protocol) SampleSources() []SampleSource

SampleSources returns every distinct sample source in the document, in document order.

func (*Protocol) Scenario added in v0.7.0

func (p *Protocol) Scenario(id string, opts ProjectOptions) (*Protocol, error)

Scenario returns a single-flow Protocol for scenario id, so code that works on Protocol.Flows (renderers, the executor, the debugger) can handle one scenario at a time.

The result keeps document order: entities are filtered to the scenario's participants in entities order, and phases to those the scenario uses (with their ancestors) in phases order. Metadata is shared. The protocol name becomes "<protocol> — <scenario>".

For a document without scenarios, Scenario("") returns a copy of p.

func (*Protocol) ScenarioByID added in v0.7.0

func (p *Protocol) ScenarioByID(id string) *Scenario

ScenarioByID returns the scenario with the given ID, or nil. It also finds the fragments a collapsed projection carries in Fragments.

func (*Protocol) ScenarioIDs added in v0.7.0

func (p *Protocol) ScenarioIDs(includeFragments bool) []string

ScenarioIDs returns scenario IDs in output order (see OrderedScenarios). Fragments are included only when includeFragments is true.

func (*Protocol) ScenarioParticipants added in v0.7.0

func (p *Protocol) ScenarioParticipants(id string) []string

ScenarioParticipants returns the entities shown for scenario id, in entities order. It is the scenario's Participants when set; otherwise the entities its flows use plus the participants of the fragments it includes. It returns nil for an unknown scenario.

func (*Protocol) ScenarioSummaries added in v0.7.0

func (p *Protocol) ScenarioSummaries() []ScenarioSummary

ScenarioSummaries lists the scenarios in output order (see OrderedScenarios): main scenarios by group with variants after their base, then fragments in document order. Positions match the file numbering used when rendering every scenario.

func (*Protocol) SourceLanguage added in v0.9.0

func (p *Protocol) SourceLanguage() string

SourceLanguage returns the protocol's narration source language.

func (*Protocol) StateTransitions added in v0.4.0

func (p *Protocol) StateTransitions() []StateTransition

StateTransitions extracts all state transitions from the protocol's flows.

func (*Protocol) StateTransitionsForEntity added in v0.4.0

func (p *Protocol) StateTransitionsForEntity(entityID string) []StateTransition

StateTransitionsForEntity returns state transitions for a specific entity.

func (*Protocol) StepNarration added in v0.9.0

func (p *Protocol) StepNarration(f Flow, rep, lang string) (text string, ok bool)

StepNarration returns a flow's narration in lang for representation rep, falling back from the representation's narration to the flow's own, and from lang to the source language. ok is false when there is none; tools then use the flow's description.

func (*Protocol) ToJSON

func (p *Protocol) ToJSON() ([]byte, error)

ToJSON serializes a Protocol to JSON with indentation.

func (*Protocol) ToJSONCompact

func (p *Protocol) ToJSONCompact() ([]byte, error)

ToJSONCompact serializes a Protocol to compact JSON.

func (*Protocol) TokenByID added in v0.4.0

func (p *Protocol) TokenByID(id string) *TokenDefinition

TokenByID returns the token definition with the given ID, or nil if not found.

func (*Protocol) TokenUsage added in v0.7.0

func (p *Protocol) TokenUsage(id string) (issuedIn, verifiedIn []string)

TokenUsage returns the scenarios whose own flows issue and verify token id (through FlowSecurity.Issues and Verifies), each in output order: main scenarios first, then fragments.

func (*Protocol) TrustRelationByID added in v0.4.0

func (p *Protocol) TrustRelationByID(id string) *TrustRelationship

TrustRelationByID returns the trust relation with the given ID, or nil if not found.

func (*Protocol) TrustRelationsByType added in v0.4.0

func (p *Protocol) TrustRelationsByType(relType string) []TrustRelationship

TrustRelationsByType returns all trust relations of a given type. Returns an empty slice if no relations match or Metadata is nil.

func (*Protocol) TrustRelationsFrom added in v0.4.0

func (p *Protocol) TrustRelationsFrom(id string) []TrustRelationship

TrustRelationsFrom returns all trust relations originating from an entity or component. Returns an empty slice if no relations match or Metadata is nil.

func (*Protocol) TrustRelationsTo added in v0.4.0

func (p *Protocol) TrustRelationsTo(id string) []TrustRelationship

TrustRelationsTo returns all trust relations targeting an entity or component. Returns an empty slice if no relations match or Metadata is nil.

func (*Protocol) Validate

func (p *Protocol) Validate() ValidationErrors

Validate checks the Protocol for errors and returns all found issues.

func (*Protocol) ValidateProcess added in v0.5.0

func (p *Protocol) ValidateProcess() ValidationErrors

ValidateProcess performs process-specific validation. These validations only apply when protocol.kind is "process".

func (*Protocol) Walkthrough added in v0.8.0

func (p *Protocol) Walkthrough(findings []Finding) Walkthrough

Walkthrough builds the walkthrough. findings, typically from the analyzer, are attached to the steps whose written flow they locate; a fragment flow's findings appear in every scenario that includes it.

func (*Protocol) WithSampleSet added in v0.9.0

func (p *Protocol) WithSampleSet(set *SampleSet) (*Protocol, error)

WithSampleSet returns a copy of the protocol with the set's samples attached to the steps they address, after the step's own samples. A step without an example gets one holding only the samples, citing the set's name. It fails when the set is for another protocol, an address names no step, or a source is not resolved. The receiver is not modified.

func (*Protocol) WithSamples added in v0.9.0

func (p *Protocol) WithSamples(lock *SampleLock) *Protocol

WithSamples returns a copy of the protocol whose source samples carry their locked code, ready for generation. Sources missing from the lock keep empty code. The receiver is not modified.

func (*Protocol) WriteFile

func (p *Protocol) WriteFile(filename string) error

WriteFile writes the Protocol to a file as JSON. It creates any necessary parent directories.

type ProtocolDiff added in v0.4.0

type ProtocolDiff struct {
	// BaseProtocolID is the ID of the base protocol.
	BaseProtocolID string `json:"base_protocol_id"`

	// NewProtocolID is the ID of the new protocol.
	NewProtocolID string `json:"new_protocol_id"`

	// Items contains all differences found.
	Items []DiffItem `json:"items"`

	// Summary provides aggregate statistics.
	Summary DiffSummary `json:"summary"`
}

ProtocolDiff contains the complete comparison result.

func Compare added in v0.4.0

func Compare(base, new *Protocol, opts DiffOptions) *ProtocolDiff

Compare compares two protocols and returns the differences.

func (*ProtocolDiff) HasChanges added in v0.4.0

func (d *ProtocolDiff) HasChanges() bool

HasChanges returns true if there are any differences.

func (*ProtocolDiff) String added in v0.4.0

func (d *ProtocolDiff) String() string

String returns a human-readable text representation of the diff.

func (*ProtocolDiff) ToJSON added in v0.4.0

func (d *ProtocolDiff) ToJSON() ([]byte, error)

ToJSON returns the diff as JSON bytes.

func (*ProtocolDiff) ToMarkdown added in v0.4.0

func (d *ProtocolDiff) ToMarkdown() string

ToMarkdown returns a markdown representation of the diff.

type ProtocolExtends added in v0.4.0

type ProtocolExtends struct {
	// Path is the file path to the base protocol (relative to current file).
	Path string `json:"path"`

	// ExcludeEntities lists entity IDs from the base to exclude.
	ExcludeEntities []string `json:"exclude_entities,omitempty"`

	// ExcludePhases lists phase IDs from the base to exclude.
	ExcludePhases []string `json:"exclude_phases,omitempty"`

	// ExcludeFlows lists flow indices from the base to exclude.
	ExcludeFlows []int `json:"exclude_flows,omitempty"`

	// ExcludeScenarios lists scenario IDs from the base to remove.
	ExcludeScenarios []string `json:"exclude_scenarios,omitempty"`
}

ProtocolExtends specifies a base protocol to extend.

type ProtocolImport added in v0.4.0

type ProtocolImport struct {
	// Path is the file path to import (relative to current file).
	Path string `json:"path"`

	// Alias prefixes imported IDs to avoid collisions (e.g., "oauth_").
	Alias string `json:"alias,omitempty"`

	// Entities lists specific entity IDs to import (empty = all).
	Entities []string `json:"entities,omitempty"`

	// Phases lists specific phase IDs to import (empty = none unless entities need them).
	Phases []string `json:"phases,omitempty"`

	// IncludeFlows imports flows between the specified entities.
	IncludeFlows bool `json:"include_flows,omitempty"`

	// Scenarios lists scenario IDs to import. Fragments they include are
	// imported with them. With Alias set, scenario IDs, include targets,
	// entity references and phases get the alias prefix.
	Scenarios []string `json:"scenarios,omitempty"`
}

ProtocolImport specifies another protocol file to import from.

type ProtocolKind added in v0.5.0

type ProtocolKind string

ProtocolKind identifies the PIDL profile type.

const (
	// ProtocolKindProtocol is the default for protocol choreography.
	ProtocolKindProtocol ProtocolKind = "protocol"
	// ProtocolKindProcess is for workflow/process specifications.
	ProtocolKindProcess ProtocolKind = "process"
)

type ProtocolMeta

type ProtocolMeta struct {
	// ID is the unique identifier for the protocol.
	ID string `json:"id"`

	// Name is the human-readable name.
	Name string `json:"name"`

	// Kind identifies the PIDL profile type (protocol or process).
	Kind ProtocolKind `json:"kind,omitempty"`

	// Version of this protocol description.
	Version string `json:"version,omitempty"`

	// Description provides a brief summary.
	Description string `json:"description,omitempty"`

	// Category classifies the protocol type.
	Category Category `json:"category,omitempty"`

	// References links to relevant specifications.
	References []Reference `json:"references,omitempty"`

	// Language is the BCP 47 tag of the document's source language, used
	// for narration that does not name another language and as the
	// fallback. It defaults to "en-US".
	Language string `json:"language,omitempty"`
}

ProtocolMeta contains metadata about a protocol.

type ProtocolMetadata added in v0.3.0

type ProtocolMetadata struct {
	// Networks defines network boundary configurations.
	Networks map[string]*NetworkConfig `json:"networks,omitempty"`
	// NetworkLayout configures network diagram layout.
	NetworkLayout *NetworkLayoutConfig `json:"network_layout,omitempty"`
	// Tokens defines token types used in the protocol.
	Tokens []TokenDefinition `json:"tokens,omitempty"`
	// Components defines logical deployment components.
	Components []DeploymentComponent `json:"components,omitempty"`
	// TrustRelations defines trust relationships between entities or components.
	TrustRelations []TrustRelationship `json:"trust_relations,omitempty"`
}

ProtocolMetadata contains additional protocol-level configuration.

type ProtocolRole added in v0.4.0

type ProtocolRole struct {
	// Protocol is the protocol identifier (e.g., "oauth", "scim", "aauth", "authzen", "mcp", "a2a", "spiffe").
	Protocol string `json:"protocol"`
	// Role is the role within that protocol (e.g., "authorization_server", "client", "pep", "pdp").
	Role string `json:"role"`
	// Variant is an optional sub-role or variant (e.g., "person_server" vs "access_server" for AAuth).
	Variant string `json:"variant,omitempty"`
	// Description provides additional context.
	Description string `json:"description,omitempty"`
}

ProtocolRole defines a protocol-specific role that an entity implements.

type Reference

type Reference struct {
	// Name of the reference (e.g., "RFC 6749").
	Name string `json:"name"`

	// URL to the reference.
	URL string `json:"url"`
}

Reference links to external documentation.

type RepresentationNarration added in v0.9.0

type RepresentationNarration struct {
	// Narration replaces the step's narration for this representation.
	Narration Narration `json:"narration,omitempty"`
}

RepresentationNarration overrides a step's narration when the reader views the step in one representation, such as cURL or Go code.

type RequestFidelity added in v0.10.0

type RequestFidelity string

RequestFidelity says whether an observation's requests are the messages servers received or what a client sent before a proxy changed them.

const (
	// RequestFidelityWire marks requests as the messages on the wire, as a
	// server's trace or a proxy in front of the servers records them.
	RequestFidelityWire RequestFidelity = "wire"
	// RequestFidelityClient marks requests as what a client sent, before a
	// proxy such as a signing helper changed them.
	RequestFidelityClient RequestFidelity = "client"
)

type ResolveOptions added in v0.4.0

type ResolveOptions struct {
	// BasePath is the directory to resolve relative paths from.
	BasePath string

	// FS, when set, is the file system extends and imports paths are read
	// from, such as an embedded set of documents. Paths are then
	// slash-separated and relative to the file system's root, and may not
	// leave it.
	FS fs.FS

	// MaxDepth limits import nesting depth (default: 10).
	MaxDepth int
}

ResolveOptions configures protocol resolution behavior.

func DefaultResolveOptions added in v0.4.0

func DefaultResolveOptions() ResolveOptions

DefaultResolveOptions returns default resolution options.

type RetryStrategy added in v0.5.0

type RetryStrategy struct {
	// MaxAttempts is the maximum number of retry attempts.
	MaxAttempts int `json:"max_attempts,omitempty"`

	// InitialDelay is the delay before the first retry.
	InitialDelay string `json:"initial_delay,omitempty"`

	// MaxDelay is the maximum delay between retries.
	MaxDelay string `json:"max_delay,omitempty"`

	// BackoffMultiplier increases delay between retries.
	BackoffMultiplier float64 `json:"backoff_multiplier,omitempty"`

	// RetryOn lists failure mode IDs that trigger retry.
	RetryOn []string `json:"retry_on,omitempty"`
}

RetryStrategy configures retry behavior for a step.

type Sample added in v0.9.0

type Sample struct {
	// Language names the code's language with a common highlighter name,
	// such as "go", "typescript", "python" or "csharp". Samples are also
	// representations a step's narration can be overridden for.
	Language string `json:"language"`

	// Label distinguishes samples in one language, such as "Agent" and
	// "Resource".
	Label string `json:"label,omitempty"`

	// Role is the entity ID whose developer writes this code.
	Role string `json:"role,omitempty"`

	// Code is inline code, or a source's code once resolved. A sample has
	// Code, Source, or both.
	Code string `json:"code,omitempty"`

	// Source refers to a marked region of a file in a repository.
	Source *SampleSource `json:"source,omitempty"`
}

Sample is code that sends or handles a step's message, such as a Go SDK call. It is either inline Code or a Source reference to a marked region of a tested file, resolved into a SampleLock.

type SampleLock added in v0.9.0

type SampleLock struct {
	Version int               `json:"version"`
	Samples []SampleLockEntry `json:"samples"`
}

SampleLock records the code each sample source resolved to, so documents generate the same output without the source repositories at hand.

func ParseSampleLock added in v0.9.0

func ParseSampleLock(data []byte) (*SampleLock, error)

ParseSampleLock parses a lock file's contents.

func ReadSampleLock added in v0.9.0

func ReadSampleLock(path string) (*SampleLock, error)

ReadSampleLock reads a lock file.

func (*SampleLock) Lookup added in v0.9.0

func (l *SampleLock) Lookup(src SampleSource) *SampleLockEntry

Lookup returns the entry for src, or nil.

func (*SampleLock) WriteFile added in v0.9.0

func (l *SampleLock) WriteFile(path string) error

WriteFile writes the lock with entries sorted by source.

type SampleLockEntry added in v0.9.0

type SampleLockEntry struct {
	SampleSource
	// SHA256 is the hex SHA-256 of Code.
	SHA256 string `json:"sha256"`
	Code   string `json:"code"`
}

SampleLockEntry is one resolved source.

type SampleSet added in v0.9.0

type SampleSet struct {
	// Format names the format and its major version: pidl-samples/v1.
	Format string `json:"format"`

	// Protocol is the ID of the protocol the set is for. When set, the
	// set applies only to that protocol.
	Protocol string `json:"protocol,omitempty"`

	// Name names the implementation, such as "example-sdk-go". It is the
	// source cited by examples the set creates for steps without one.
	Name string `json:"name,omitempty"`

	// Samples are the set's samples, each attached to a step.
	Samples []SampleSetEntry `json:"samples"`
}

SampleSet holds code samples for a protocol, kept apart from the protocol document. An implementation of a protocol, such as an SDK, keeps its own set beside its tested code, so the protocol document stays independent of any language or implementation. Generation joins one or more sets to the document.

A set is also its own lock: resolving a set writes each source's code and hash into it, so it generates without the source repository at hand.

func ParseSampleSet added in v0.9.0

func ParseSampleSet(data []byte) (*SampleSet, error)

ParseSampleSet parses a sample set. It refuses another major version of the format.

func ReadSampleSet added in v0.9.0

func ReadSampleSet(path string) (*SampleSet, error)

ReadSampleSet reads a sample set file.

func (*SampleSet) Check added in v0.9.0

func (s *SampleSet) Check(read SourceReader) []string

Check reports entries whose source is not resolved, whose recorded code does not match its hash, or, when read is not nil, whose source region changed since it was resolved.

func (*SampleSet) Resolve added in v0.9.0

func (s *SampleSet) Resolve(read SourceReader) error

Resolve reads each entry's source and records its code and hash. It reports every source that cannot be read or extracted.

func (*SampleSet) Validate added in v0.9.0

func (s *SampleSet) Validate() ValidationErrors

Validate checks each entry: a step address, a language that is not a generated representation, code or a source, and a source path inside its repository.

func (*SampleSet) WriteFile added in v0.9.0

func (s *SampleSet) WriteFile(path string) error

WriteFile writes the set, keeping the order of its samples.

type SampleSetEntry added in v0.9.0

type SampleSetEntry struct {
	// Step is the address of a step as written: "<scenario>/<step-id>" for
	// a step of a scenario or fragment, "<scenario>" for the scenario's
	// own samples, or "<step-id>" in a document without scenarios.
	Step string `json:"step"`

	Sample

	// SHA256 is the hex SHA-256 of Code, recorded when Source is resolved.
	SHA256 string `json:"sha256,omitempty"`
}

SampleSetEntry is one sample and the step it belongs to.

type SampleSource added in v0.9.0

type SampleSource struct {
	// Repo is the repository's module-style path, such as
	// "github.com/aauth-dev/aauth-go".
	Repo string `json:"repo"`

	// Ref is a tag or commit to read the file at. Empty reads the
	// checkout's working tree.
	Ref string `json:"ref,omitempty"`

	// Path is the file's path within the repository.
	Path string `json:"path"`

	// Region is the marked region's name.
	Region string `json:"region"`
}

SampleSource refers to the code between "pidl:begin <region>" and "pidl:end <region>" markers, in comments, in a file of a repository.

func (SampleSource) Key added in v0.9.0

func (s SampleSource) Key() string

Key identifies the source in a SampleLock.

type Scenario added in v0.7.0

type Scenario struct {
	// ID is the unique identifier, used by include steps and CLI selection.
	ID string `json:"id"`

	// Name is the human-readable display name.
	Name string `json:"name"`

	// Description of the scenario.
	Description string `json:"description,omitempty"`

	// Participants selects the entities shown for this scenario. It must
	// list entity IDs in entities order. When empty, participants are the
	// entities used by the scenario's flows and includes.
	Participants []string `json:"participants,omitempty"`

	// Fragment marks a reusable sub-flow that other scenarios include.
	Fragment bool `json:"fragment,omitempty"`

	// Group is the ID of the group this scenario is listed under.
	Group string `json:"group,omitempty"`

	// VariantOf is the ID of the scenario this one is a variant of, such
	// as a with-approval form of an autonomous flow. A variant shares its
	// base's navigation entry and follows it in output order.
	VariantOf string `json:"variant_of,omitempty"`

	// VariantLabel names the variant in a toggle, such as "With user
	// approval". It is required with VariantOf.
	VariantLabel string `json:"variant_label,omitempty"`

	// Narration is spoken when the scenario opens, keyed by language.
	Narration Narration `json:"narration,omitempty"`

	// Briefing introduces the scenario: why it exists, its key points,
	// and what is spoken over them.
	Briefing *Briefing `json:"briefing,omitempty"`

	// Samples are code for the scenario as a whole, such as the setup a
	// role needs before the first step.
	Samples []Sample `json:"samples,omitempty"`

	// Flows are the scenario's steps, in order.
	Flows []Flow `json:"flows"`
}

Scenario is a named, ordered sequence of flows within a protocol, such as one access mode or user journey. A fragment scenario is a reusable sub-flow that other scenarios include.

type ScenarioSummary added in v0.7.0

type ScenarioSummary struct {
	// Position is the 1-based position used for numbered output: main
	// scenarios first in document order, then fragments.
	Position     int      `json:"position"`
	ID           string   `json:"id"`
	Name         string   `json:"name"`
	Fragment     bool     `json:"fragment,omitempty"`
	Group        string   `json:"group,omitempty"`
	VariantOf    string   `json:"variant_of,omitempty"`
	VariantLabel string   `json:"variant_label,omitempty"`
	Participants []string `json:"participants"`
	Steps        int      `json:"steps"`
	Includes     []string `json:"includes,omitempty"`
}

ScenarioSummary describes one scenario for listings.

type SchemaRegistry added in v0.5.0

type SchemaRegistry struct {
	// contains filtered or unexported fields
}

SchemaRegistry holds loaded JSON schemas for validation.

func NewSchemaRegistry added in v0.5.0

func NewSchemaRegistry() *SchemaRegistry

NewSchemaRegistry creates a new schema registry.

func (*SchemaRegistry) LoadSchema added in v0.5.0

func (r *SchemaRegistry) LoadSchema(uri string) (interface{}, error)

LoadSchema loads a JSON Schema from a URI or file path. Supported URI formats:

  • file:///path/to/schema.json
  • ./relative/path/schema.json
  • /absolute/path/schema.json
  • #/definitions/TypeName (inline reference)

func (*SchemaRegistry) RegisterSchema added in v0.5.0

func (r *SchemaRegistry) RegisterSchema(uri string, schema interface{})

RegisterSchema registers a schema with a given URI.

func (*SchemaRegistry) SetBasePath added in v0.5.0

func (r *SchemaRegistry) SetBasePath(path string)

SetBasePath sets the base directory for resolving relative schema paths.

type SchemaValidationError added in v0.5.0

type SchemaValidationError struct {
	// Path is the JSON path to the invalid field.
	Path string
	// Message describes the validation failure.
	Message string
	// SchemaPath is the path in the schema that failed.
	SchemaPath string
}

SchemaValidationError represents a single validation error.

type SchemaValidationResult added in v0.5.0

type SchemaValidationResult struct {
	// Valid indicates if the data passed validation.
	Valid bool
	// Errors contains validation error messages.
	Errors []SchemaValidationError
}

SchemaValidationResult holds the result of schema validation.

func ValidateData added in v0.5.0

func ValidateData(data interface{}, schema interface{}) *SchemaValidationResult

ValidateData validates data against a JSON Schema. This is a basic implementation that checks type constraints. For full JSON Schema validation, use a dedicated library like github.com/santhosh-tekuri/jsonschema/v5.

func (*SchemaValidationResult) Error added in v0.5.0

func (r *SchemaValidationResult) Error() string

Error returns the validation errors as a string.

type SecurityRequirement added in v0.4.0

type SecurityRequirement string

SecurityRequirement represents a security mechanism required for a flow.

const (
	// SecurityRequirementToken requires a bearer or bound token.
	SecurityRequirementToken SecurityRequirement = "token"
	// SecurityRequirementSignature requires message signing.
	SecurityRequirementSignature SecurityRequirement = "signature"
	// SecurityRequirementEncryption requires message encryption.
	SecurityRequirementEncryption SecurityRequirement = "encryption"
	// SecurityRequirementMTLS requires mutual TLS authentication.
	SecurityRequirementMTLS SecurityRequirement = "mtls"
	// SecurityRequirementMAC requires message authentication code.
	SecurityRequirementMAC SecurityRequirement = "mac"
)

type SourceReader added in v0.9.0

type SourceReader func(repo, ref, path string) ([]byte, error)

SourceReader reads a file of a repository at a ref ("" for the working tree).

func CheckoutSourceReader added in v0.9.0

func CheckoutSourceReader(dir string) SourceReader

CheckoutSourceReader reads every repository's files from one checkout, dir, whatever the repository: for samples whose sources all live in the repository at hand. With a ref it reads the file at that ref through git.

func LocalSourceReader added in v0.9.0

func LocalSourceReader(root string) SourceReader

LocalSourceReader reads repositories checked out under root, at root/<repo>. With a ref it reads the file at that ref through git.

type StateChange added in v0.4.0

type StateChange struct {
	// Entity is the entity ID.
	Entity string `json:"entity"`

	// FromState is the prior state (empty if not tracked).
	FromState string `json:"from_state,omitempty"`

	// ToState is the new state.
	ToState string `json:"to_state"`
}

StateChange records a single state mutation.

type StateMutation added in v0.4.0

type StateMutation struct {
	// Entity is the ID of the entity whose state changes.
	Entity string `json:"entity"`

	// To is the target state ID.
	To string `json:"to"`

	// From is the optional required prior state (for validation).
	From string `json:"from,omitempty"`
}

StateMutation represents a state change for an entity triggered by a flow.

type StateTransition added in v0.4.0

type StateTransition struct {
	// EntityID is the entity undergoing the state change.
	EntityID string
	// FromState is the prior state (empty if not specified).
	FromState string
	// ToState is the target state.
	ToState string
	// FlowAction is the action that triggers this transition.
	FlowAction string
	// FlowLabel is the display label for the triggering flow.
	FlowLabel string
}

StateTransition represents a state transition extracted from flows.

type StepExecutionStatus added in v0.5.0

type StepExecutionStatus string

StepExecutionStatus represents the execution status of a process step.

const (
	StepStatusPending    StepExecutionStatus = "pending"
	StepStatusReady      StepExecutionStatus = "ready"
	StepStatusBlocked    StepExecutionStatus = "blocked"
	StepStatusInProgress StepExecutionStatus = "in_progress"
	StepStatusCompleted  StepExecutionStatus = "completed"
	StepStatusFailed     StepExecutionStatus = "failed"
	StepStatusSkipped    StepExecutionStatus = "skipped"
)

type StepMatch added in v0.10.0

type StepMatch struct {
	// Method is the HTTP method.
	Method string `json:"method,omitempty"`

	// Path is a template, whose segments in braces match any one segment
	// ("/pending/{id}"), or a regular expression when it starts with "^".
	Path string `json:"path,omitempty"`

	// Status is the response status.
	Status int `json:"status,omitempty"`

	// Headers maps a header name, compared without regard to case, to a
	// value: exact, a prefix when it ends with "*", or a regular expression
	// when it starts with "^". Response headers are searched before request
	// headers.
	Headers map[string]string `json:"headers,omitempty"`

	// Body maps a JSON pointer into the request body to the value it must
	// have, or to true when the member must merely exist.
	Body map[string]json.RawMessage `json:"body,omitempty"`

	// Repeat lets the step take every consecutive exchange that matches it,
	// such as a client polling.
	Repeat bool `json:"repeat,omitempty"`

	// Optional lets a run omit the step without failing a check.
	Optional bool `json:"optional,omitempty"`
}

StepMatch is a rule that says which observed exchanges are a step. Every field is optional; a field left empty is not tested.

func (StepMatch) Validate added in v0.10.0

func (m StepMatch) Validate(field string) ValidationErrors

Validate checks the rule's regular expressions, status and JSON pointers.

type StepType added in v0.5.0

type StepType string

StepType classifies the processing nature of a process step.

const (
	// StepTypeDeterministic is for repeatable, predictable processing.
	StepTypeDeterministic StepType = "deterministic"
	// StepTypeLLM is for LLM/AI-powered non-deterministic processing.
	StepTypeLLM StepType = "llm"
	// StepTypeHuman is for human-in-the-loop steps.
	StepTypeHuman StepType = "human"
	// StepTypeExternal is for external API/service calls.
	StepTypeExternal StepType = "external"
	// StepTypeTool is for tool invocations (MCP-style).
	StepTypeTool StepType = "tool"
	// StepTypeParallel is for parallel execution blocks.
	StepTypeParallel StepType = "parallel"
	// StepTypeConditional is for conditional branching.
	StepTypeConditional StepType = "conditional"
)

type TokenCarriage added in v0.10.0

type TokenCarriage struct {
	// In is "header" or "body".
	In string `json:"in"`
	// Name is the header's name, for a token in a header.
	Name string `json:"name,omitempty"`
	// Param is the structured field parameter holding the token, such as
	// "jwt" in Signature-Key; empty when the token is the whole value.
	Param string `json:"param,omitempty"`
	// Path is a JSON pointer to the token in the body, for a token in a body.
	Path string `json:"path,omitempty"`

	// Typ is the JWT typ header a value found here must have to be this
	// token, such as "aa-agent+jwt". Several tokens can travel in one place,
	// such as whichever token a request presents in Signature-Key; typ says
	// which one a value is.
	Typ string `json:"typ,omitempty"`
}

TokenCarriage is one place a token travels.

type TokenClaim added in v0.7.0

type TokenClaim struct {
	// Name is the claim name, such as "aud" or "agent_jkt".
	Name string `json:"name"`

	// CheckedBy lists the entities that check this claim.
	CheckedBy []string `json:"checked_by,omitempty"`

	// Description explains what the claim carries or how it is checked.
	Description string `json:"description,omitempty"`
}

TokenClaim is one claim in a token and the entities that check it.

type TokenDefinition added in v0.4.0

type TokenDefinition struct {
	// ID is the unique identifier for this token definition.
	ID string `json:"id"`
	// Name is the human-readable display name.
	Name string `json:"name,omitempty"`
	// Type is the token type: jwt, opaque, saml, api_key.
	Type string `json:"type,omitempty"`
	// Issuer is the entity ID that issues this token.
	Issuer string `json:"issuer,omitempty"`
	// Audience is the entity ID that consumes this token.
	Audience string `json:"audience,omitempty"`
	// Binding is the token binding method: bearer, mtls, dpop.
	Binding string `json:"binding,omitempty"`
	// Description provides additional context.
	Description string `json:"description,omitempty"`

	// VerifiedBy lists the entities that check this token. Outputs list
	// them in entities order.
	VerifiedBy []string `json:"verified_by,omitempty"`

	// CarriedIn says where the token travels in messages, so tokens can be
	// found and decoded in exchanges observed in a real system.
	CarriedIn []TokenCarriage `json:"carried_in,omitempty"`

	// Claims lists the claims checkers rely on, in display order.
	Claims []TokenClaim `json:"claims,omitempty"`
}

TokenDefinition describes a token type used in the protocol.

type TrustLevel added in v0.4.0

type TrustLevel string

TrustLevel represents the trust classification of an entity.

const (
	// TrustLevelTrusted is for fully trusted internal systems.
	TrustLevelTrusted TrustLevel = "trusted"
	// TrustLevelSemiTrusted is for partially trusted systems (DMZ, partners).
	TrustLevelSemiTrusted TrustLevel = "semi_trusted"
	// TrustLevelUntrusted is for external/public systems.
	TrustLevelUntrusted TrustLevel = "untrusted"
	// TrustLevelAuthoritative is for sources of truth (IdPs, CAs).
	TrustLevelAuthoritative TrustLevel = "authoritative"
)

type TrustRelationship added in v0.4.0

type TrustRelationship struct {
	// ID is an optional unique identifier for this relationship.
	ID string `json:"id,omitempty"`
	// From is the source entity or component ID.
	From string `json:"from"`
	// To is the target entity or component ID.
	To string `json:"to"`
	// Type is the relationship type (e.g., "authenticates", "validates", "delegates").
	Type string `json:"type"`
	// Credentials lists what credentials are exchanged in this relationship.
	Credentials []string `json:"credentials,omitempty"`
	// Mutual indicates if this is a bidirectional trust (e.g., mTLS).
	Mutual bool `json:"mutual,omitempty"`
	// Description provides additional context.
	Description string `json:"description,omitempty"`
}

TrustRelationship defines a trust relationship between entities or components.

type ValidationError

type ValidationError struct {
	Field   string
	Message string
}

ValidationError represents a validation error with context.

func (ValidationError) Error

func (e ValidationError) Error() string

type ValidationErrors

type ValidationErrors []ValidationError

ValidationErrors is a collection of validation errors.

func (ValidationErrors) Error

func (e ValidationErrors) Error() string

func (ValidationErrors) HasErrors

func (e ValidationErrors) HasErrors() bool

HasErrors returns true if there are any validation errors.

type VerificationTier added in v0.6.0

type VerificationTier string

VerificationTier records how well-substantiated a flow is. Values match the aisecurity-incidents deepdive.json vocabulary.

const (
	VerificationTierReported            VerificationTier = "reported"
	VerificationTierCorroborated        VerificationTier = "corroborated"
	VerificationTierReproduced          VerificationTier = "reproduced"
	VerificationTierPartiallyReproduced VerificationTier = "partially_reproduced"
)

type Walkthrough added in v0.8.0

type Walkthrough struct {
	// Format names the format and its major version, "pidl-walkthrough/v1".
	Format      string `json:"format"`
	ID          string `json:"id"`
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	// Language is the source language of the narration.
	Language       string                       `json:"language"`
	Pronunciations map[string]map[string]string `json:"pronunciations,omitempty"`
	Roles          []OutlineRole                `json:"roles"`
	Groups         []Group                      `json:"groups,omitempty"`
	Scenarios      []WalkthroughScenario        `json:"scenarios"`
	Tokens         []WalkthroughToken           `json:"tokens,omitempty"`
	// Findings holds findings that do not locate a single flow, such as an
	// unused role.
	Findings []Finding `json:"findings,omitempty"`
}

Walkthrough is a protocol prepared for step-by-step presentation: roles in entities order and, for each scenario in output order, its steps with fragments expanded in place. Viewers render it without needing PIDL's include, ordering or analysis rules.

type WalkthroughScenario added in v0.8.0

type WalkthroughScenario struct {
	Position     int               `json:"position"`
	ID           string            `json:"id"`
	Name         string            `json:"name"`
	Description  string            `json:"description,omitempty"`
	Fragment     bool              `json:"fragment,omitempty"`
	Group        string            `json:"group,omitempty"`
	VariantOf    string            `json:"variant_of,omitempty"`
	VariantLabel string            `json:"variant_label,omitempty"`
	Narration    Narration         `json:"narration,omitempty"`
	Briefing     *Briefing         `json:"briefing,omitempty"`
	Samples      []Sample          `json:"samples,omitempty"`
	Participants []string          `json:"participants"`
	Steps        []WalkthroughStep `json:"steps"`

	// ObservedRun is set on a scenario entry that shows a run observed in a
	// real system: one instance of the scenario found in a capture.
	ObservedRun *ObservedRun `json:"observed_run,omitempty"`
	// ObservedExtra are the run's exchanges that matched no step, each
	// placed after the step it followed.
	ObservedExtra []ObservedExtra `json:"observed_extra,omitempty"`
}

WalkthroughScenario is one scenario with its expanded steps.

type WalkthroughStep added in v0.8.0

type WalkthroughStep struct {
	// Number is the 1-based position within the expanded scenario.
	Number int `json:"number"`
	// ID is the step's flow ID, qualified as "<include>.<id>" for a step
	// inside an included fragment; empty when the flow has no ID.
	ID       string `json:"id,omitempty"`
	From     string `json:"from"`
	To       string `json:"to"`
	Label    string `json:"label"`
	Response bool   `json:"response,omitempty"`
	Phase    string `json:"phase,omitempty"`
	// Fragments names the fragments this step sits inside, outermost first.
	Fragments   []string  `json:"fragments,omitempty"`
	Description string    `json:"description,omitempty"`
	Narration   Narration `json:"narration,omitempty"`
	// Representations holds narration overrides by representation.
	Representations map[string]RepresentationNarration `json:"representations,omitempty"`
	Note            string                             `json:"note,omitempty"`
	SignedBy        string                             `json:"signed_by,omitempty"`
	Issues          []string                           `json:"issues,omitempty"`
	Verifies        []string                           `json:"verifies,omitempty"`
	Example         *FlowExample                       `json:"example,omitempty"`

	// Match is the step's own rule for matching observed exchanges, from
	// the document. DefinedIn is the scenario or fragment that defines the
	// step and FlowID its unqualified ID, which a binding's step keys name.
	// They serve generation in process and are not part of the format.
	Match     *StepMatch `json:"-"`
	DefinedIn string     `json:"-"`
	FlowID    string     `json:"-"`

	// Observed is the exchange a real run produced for this step, in a
	// scenario entry with an ObservedRun. ObservedStatus is matched,
	// notSeen, skipped, unmatchable or unobservable; ObservedStrength is
	// strong or weak for a matched step.
	Observed         *ObservedMessage `json:"observed,omitempty"`
	ObservedStatus   string           `json:"observed_status,omitempty"`
	ObservedStrength string           `json:"observed_strength,omitempty"`
	// Curl is a curl command equivalent to the example request.
	Curl     string    `json:"curl,omitempty"`
	Location string    `json:"location"`
	Findings []Finding `json:"findings,omitempty"`
}

WalkthroughStep is one message of an expanded scenario.

type WalkthroughToken added in v0.8.0

type WalkthroughToken struct {
	ID         string       `json:"id"`
	Name       string       `json:"name"`
	Type       string       `json:"type,omitempty"`
	Issuer     string       `json:"issuer,omitempty"`
	Audience   string       `json:"audience,omitempty"`
	VerifiedBy []string     `json:"verified_by,omitempty"`
	Claims     []TokenClaim `json:"claims,omitempty"`
}

WalkthroughToken is a token definition with the claims its checkers use.

Directories

Path Synopsis
Package analyze provides security analysis for PIDL protocols.
Package analyze provides security analysis for PIDL protocols.
cmd
pidl command
Command pidl is the CLI tool for the Protocol Interaction Description Language.
Command pidl is the CLI tool for the Protocol Interaction Description Language.
Package examples provides embedded PIDL example protocols.
Package examples provides embedded PIDL example protocols.
Package export provides exporters for converting PIDL protocols to workflow engine formats.
Package export provides exporters for converting PIDL protocols to workflow engine formats.
Package observe shows runs observed in real systems in walkthroughs.
Package observe shows runs observed in real systems in walkthroughs.
adapter/sandbox
Package sandbox reads the message trace of the aauth-go sandbox as a PIDL observation.
Package sandbox reads the message trace of the aauth-go sandbox as a PIDL observation.
match
Package match matches observed exchanges to the steps of a walkthrough's scenarios.
Package match matches observed exchanges to the steps of a walkthrough's scenarios.
Package render provides diagram rendering for PIDL protocols.
Package render provides diagram rendering for PIDL protocols.
svg
Package svg provides SVG rendering utilities for PIDL protocols.
Package svg provides SVG rendering utilities for PIDL protocols.
Package schema provides the embedded JSON Schemas: PIDL, the source format people write; the walkthrough format PIDL generates; the sample set format implementations keep their code samples in; and the observation and binding formats for matching real runs to steps.
Package schema provides the embedded JSON Schemas: PIDL, the source format people write; the walkthrough format PIDL generates; the sample set format implementations keep their code samples in; and the observation and binding formats for matching real runs to steps.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL