Guide

Build with the Component SDK

Create collectors, tools, utilities, and remote adapters.

Prerequisites

  • Go 1.27+
  • epack CLI installed

Create a component

epack sdk new collector myservice

This creates a ready-to-build component project. Pass --module to set its Go module path:

epack-collector-myservice/
├── cmd/epack-collector-myservice/
│   └── main.go                       # Entrypoint
├── internal/collector/
│   ├── collector.go                  # Collection logic
│   ├── config.go                     # Config from epack.yaml
│   ├── handler.go                    # Run: config, secrets, client, emit
│   ├── gaps.go                       # Values left out, with their codes
│   ├── collectortest_test.go         # Fault, schema, and credential checks
│   ├── fixtures_test.go              # Canned API responses
│   ├── record_test.go                # Records a real run (build tag: record)
│   └── recording_scrub_test.go       # Checks committed recordings are scrubbed
├── internal/myservice/
│   └── client.go                     # The vendor's API
├── docs/schema/                      # The artifact's and config's JSON Schemas and trace map, embedded
│   ├── v1.0.0.json
│   ├── config.json                   # Config schema, checked before Run
│   ├── trace-map.json
│   └── embed.go
├── testdata/conformance.json         # Config the conformance harness collects with
├── Makefile                          # build, test, lint, conformance
├── go.mod                            # With a toolchain line matching epack's
├── LICENSE                           # Apache 2.0
├── README.md
├── .gitignore
├── docs/                             # Registry documentation
│   ├── overview.md
│   ├── configuration.md
│   ├── examples.md
│   └── levels.md
├── .slsa-goreleaser/                 # Multi-platform build configs
│   └── *.yml
└── .github/workflows/
    ├── ci.yaml                       # Calls epack's shared collector workflow
    ├── publish.yaml                  # Publishes a draft release once its check passes
    └── release.yaml                  # SLSA Level 3 + Sigstore signing

A collector's CI calls locktivity/epack/.github/workflows/collector-ci.yaml, pinned to the commit of the epack release in go.mod. It runs the tests, including the collectortest suite, lint, release builds, conformance, the trace map check, the surface check when docs/surface.yaml exists, and govulncheck, and on a pull request compares each scenario's evidence with the newest release's. Tools, utilities, and remotes keep their implementation in main.go.

Component types

epack sdk new collector myservice    # Gathers evidence from APIs
epack sdk new tool analyzer          # Processes packs
epack sdk new utility viewer         # Standalone CLI tool
epack sdk new remote mycloud         # Push/pull adapter

Build a collector with a coding agent

The building-epack-collectors skill takes a coding agent through a collector from scoping the evidence to a signed release: the test account, the scaffold, a recording of every call before the collection is written, the output contract, the collectortest suite, a live run before each tag, the docs pages, and the release. It is a single Markdown file in the Agent Skills format, which Codex, Claude Code, GitHub Copilot, and other coding agents read. Save it in your agent's skills directory, in the directory where you will create the collector:

mkdir -p .agents/skills/building-epack-collectors
curl -fsSL https://epack.dev/skills/building-epack-collectors/SKILL.md \
  -o .agents/skills/building-epack-collectors/SKILL.md

Many agents, including Codex and GitHub Copilot, read .agents/skills/. Claude Code reads .claude/skills/, so use that directory in place of .agents/skills/ for Claude Code. The same path under your home directory, such as ~/.agents/skills/, makes the skill available in every project. Check your agent's documentation if it reads skills from somewhere else. An agent without skill support can still follow the file as instructions when you give it the URL.

Then ask the agent to build a collector for your service. It asks you to approve the scope and the fields before it writes code, and it leaves credentials, the repository, and release tags to you.

Develop with watch mode

Run your component with automatic rebuild on file changes:

cd epack-collector-myservice
epack sdk run --watch .

Pass arguments after --:

epack sdk run --watch . -- --capabilities

Generate test data

Create sample inputs for testing:

# Generate test fixtures
epack sdk mock tool              # Creates sample-evidence.epack
epack sdk mock collector         # Creates config.json and run-collector.sh
epack sdk mock tool -o testdata  # Output to testdata/

Run conformance tests

Verify your component implements the protocol correctly:

# Build and test
epack sdk test .

# Test a binary directly
epack sdk test ./epack-collector-myservice

# Verbose output
epack sdk test --verbose .

# Collect with a config, and check how the collector handles its credential
epack sdk test --config testdata/conformance.json --secret MYSERVICE_API_TOKEN .

# What CI runs in a collector project
make conformance

epack sdk test builds cmd/<directory name>, or the only package under cmd/, and passes a collector project's testdata/conformance.json unless --config names another. With a config, the output, signal, and timeout checks run against a real collection. Each --secret is set to a canary value on every run: the checks fail when the canary shows up in output, files, or error messages, and when the collector reports a rejected credential without exiting 3. With a config and a --secret, a collector that exits 2 on the run that should collect has rejected its config: C-020 and COL-040 fail, naming the config file and quoting the last line of the collector's stderr. make conformance takes the secret names from CONFORMANCE_SECRETS in the Makefile.

COL-080 fails a trust-level collector result that holds request rows, the principal's ID or tenant, call or step counts or times, a gap's warning, error text, scope, call number, or unmeasured count, or a run warning's message or scope. The tenant, count, time, call number, and unmeasured rules apply only to a result whose operations carry retried, so a result from an older SDK still passes them.

The harness also runs --version and --capabilities (COL-060 to COL-063) and reads the test kit suites the capabilities list, which the SDK copies from the trace map. It fails a collector whose capabilities list no suite, or a suite that declares no operations or runs no scenario (COL-110), a collector no suite of which replays a recording of the test account (COL-113), and a waiver with no reason, no date, or a date that has passed (COL-114). The checks read the capabilities, so they run in CI, where conformance has only canary secrets. A collector with no sandbox yet waives the recording with WaiveRecording, the sandbox it stands for, a reason, and an expiry; COL-113 then passes and reports the waiver until it lapses. Each message names the fix: epack sdk map and a commit of the map, Suite.Operations, collectortest.Record, or the waiver to renew or remove.

Implement a collector

The handler, Run in internal/collector/handler.go, reads config and secrets, calls the API through the SDK's HTTP client, and emits artifacts. It fails only for invalid configuration or a failed sign-in. The scaffold's collect function records a gap for each value it cannot read:

internal/collector/handler.go
func Run(ctx componentsdk.CollectorContext) error {
    // Get config from epack.yaml
    cfg, err := ParseConfig(ctx.Config())
    if err != nil {
        return componentsdk.NewConfigError("%w", err)
    }

    // Get secrets from environment
    token := ctx.Secret("MYSERVICE_API_TOKEN")
    if token == "" {
        return componentsdk.NewConfigError("MYSERVICE_API_TOKEN is required")
    }

    // Retries, rate limits, and credential guards for every call
    httpClient := componentsdk.NewHTTPClient(ctx, componentsdk.HTTPOptions{
        CredentialHosts: []string{myservice.Host},
    })
    output, err := collect(ctx, myservice.NewClient(httpClient, cfg.Organization, token))
    if err != nil {
        return err
    }

    // Emit collected artifacts
    return ctx.Emit([]componentsdk.CollectedArtifact{
        componentsdk.JSONArtifact(artifactPath, output, componentsdk.ArtifactMeta{
            DisplayName: "MyService posture",
            Description: "MFA and user posture from MyService",
            Controls:    []string{"SOC2-CC6.1"},
        }),
    })
}

artifactPath is artifacts/myservice.details.json, the path componentsdk.ArtifactPath("myservice", "") gives the collector's own file. Every data artifact sits at artifacts/<collector>.<kind>.json, where the kind is the name in its schema ID, or details for a file with no schema ID. Name files by the collector's own name in code. A run configured under another name in epack.yaml writes under that name, and the SDK moves every path in its output. componentsdk.RunPath gives the path a run writes, for a collector that puts a file's path inside another file's data.

Artifact metadata is recorded in the pack manifest. Use DisplayName and Description for readable epack inspect and epack list output, and Controls to tag artifacts with the controls they support.

A collector that exits 0 must emit at least one artifact. Empty output, JSON null, or text that is not JSON fails the collector with invalid_output.

The collector spec

Spec in handler.go tells the SDK the collector's name, schemas, config schema, and the kinds of evidence it writes:

internal/collector/handler.go
func Spec(version, commit string) componentsdk.CollectorSpec {
    return componentsdk.CollectorSpec{
        Name:         "myservice",
        Version:      version,
        Commit:       commit,
        Timeout:      5 * time.Minute,
        Schemas:      map[string][]byte{artifactPath: schema.Artifact},
        TraceMap:     schema.TraceMap,
        ConfigSchema: schema.Config,
        // Only for a collector that writes an artifact with a schema ID
        Writes:       []string{"evidencepack/idp-posture@v1"},
    }
}

ConfigSchema is a JSON Schema for the collector's config. A scaffolded collector keeps it in docs/schema/config.json. The SDK checks the config against it before Run, and skips the keys it reads itself, level and collect. A config that does not match fails the run with config_invalid and exit 2, and the error gives the JSON pointer of each value that does not match. A malformed value is then never read in as a default.

Writes lists the schema IDs of the artifacts the collector can write. It appears in --capabilities and the build file. A detailed artifact with no schema ID is not listed. The test kit's writes check fails a run that writes a schema ID Writes does not list.

Error types

componentsdk.NewConfigError("missing field: %s", field)   # Exit 2
componentsdk.NewAuthError("invalid token")                 # Exit 3
componentsdk.NewNetworkError("request failed: %v", err)    # Exit 4

A typed error keeps its exit code when wrapped with %w. Any other error exits with the exit code of the code componentsdk.Classify gives it: an HTTP status, a deadline, a reset connection, or malformed JSON each map to one. Before a non-zero exit, the SDK prints a failure line with the code, which epack reports in place of its guess from the exit code. See collector run failures.

Calling APIs and recording gaps

Call APIs through componentsdk.NewHTTPClient. It retries safe requests on 429, 5xx, and connection errors, honors Retry-After within the collector's deadline, and refuses to send credentials to a host outside CredentialHosts. HTTPOptions.ThrottleWait sets the wait for a throttled response that still has requests left in its limit, such as GitHub's answer over a secondary rate limit. Name each call's operation, so the collector result can count it:

client := componentsdk.NewHTTPClient(ctx, componentsdk.HTTPOptions{
    CredentialHosts: []string{"api.example.com"},
})
rec := componentsdk.Records(ctx)

reqCtx := componentsdk.WithOperation(ctx.Context(), componentsdk.Operation{Name: "users.list"})
req, err := http.NewRequestWithContext(reqCtx, http.MethodGet, "https://api.example.com/users", nil)
if err != nil {
    return err
}
resp, err := client.Do(req)
if err != nil {
    rec.NotCollected(componentsdk.Location{Path: "artifacts/myservice.details.json", Pointer: "/user_count"}, err)
}

A value the collector could not read is left out of the artifact, absent or null, with a gap that records why. Never write a default such as 0, false, or an empty list in its place: a reader cannot tell it from a real answer. A collection with gaps succeeds and exits 0. Each gap and failure carries one of these codes, and its owner says whose move it is:

Code Owner Exit Meaning
auth_failedcustomer3The credential was rejected
permission_deniedcustomer3The credential works but lacks a permission or role
config_invalidcustomer2The configuration is missing or invalid
not_licensednobody1The account's plan does not include the feature
unsupportednobody1The vendor does not report the value at all, such as a normalized field it has no data for. It does not make a run partial
not_readpublisher1The vendor reports the value, but the collector does not read it, such as a value behind a call it does not make. It does not make a run partial
rate_limitedvendor4The vendor throttled the collector and retries ran out
vendor_errorvendor4The vendor failed: a 5xx status, a reset connection, or a DNS failure
timeoutvendor or runner4A call, or the collection as a whole, ran out of time
invalid_responsepublisher1The response was not what the collector expects
too_largepublisher1The vendor holds more than the collector reads, such as an audit log longer than the collector's cap on events
internalpublisher1A bug in the collector
not_sharednobodynoneThe customer left the value out of this pack with the collect config key. Only the SDK records it, and it never fails a run

Use unsupported only for a value the vendor never reports, so no release of the collector could read it. When the vendor reports the value and the collector does not read it yet, use not_read. A reader then knows that a later release could add it. Record either one with rec.NotCollectedCode, passing componentsdk.CodeUnsupported or componentsdk.CodeNotRead.

Open a named step around each part of the run, so the result groups its calls and timing, and give a gap the permission to grant and a message for the operator:

people, step := componentsdk.StartCollectorStep(ctx, "people", "People and sign-in methods")
users, err := client.ListUsers(people.Context())
step.End()
if err != nil {
    rec.NotCollected(componentsdk.Location{Path: "artifacts/myservice.details.json", Pointer: "/users"}, err,
        componentsdk.MissingPermission("users.read"), componentsdk.Warning("users: grant users.read"))
}

A helper of your own that records gaps calls rec.Helper() first, so a gap's source names the line that called the helper.

You can declare the permission a call needs on its operation instead, as componentsdk.Operation{Name: "users.list", Permission: "users.read"}. The collector result lists it with the operation. A permission_denied gap recorded from the call's error then records it as missing_permission without an option, and a MissingPermission option on the gap overrides it. When granting the permission would not lift a denial, such as AWS's explicit deny from a service control policy, return false from HTTPOptions.NamesPermission, and the gap records no permission.

A gap can also carry one piece of advice. componentsdk.Fix(instruction) gives the step that fixes collection, NoAction() marks a gap where nothing needs to change now, and Decide(question, options...) offers a choice of two or more ChoiceOptions. Scope(text) names the account, tenant, or region affected. Advice is written at every level, so it holds fixed wording and permission, plan, and region names, and never names a resource, person, or account. The scope is written from the audit level. rec.Warn(message, opts...) records a warning about the whole run, such as a list the collector caps, and takes the same options. rec.Warnings() returns the warnings recorded so far.

rec.NotCollected(at, err, componentsdk.Fix("Grant the token the users:read scope."))
rec.Warn("The audit log list stops at 10,000 events.", componentsdk.NoAction())

A collector that compares vendor values with names of its own, such as event types, keeps the vendor's values in a vocabulary file refreshed from the vendor's catalog. componentsdk.MustLoadVocabulary(raw) reads it. Must(values...) returns the collector's constants and panics on one the vocabulary lacks, so a misspelled constant fails every test. Seen(ctx, value) reports whether a value the vendor sent is known, and lists an unknown one in the collector result's unrecognized.

componentsdk.NextLink(resp) returns the next page from a response's Link headers, read as RFC 8288 defines them. componentsdk.Percent(count, total, rounding) returns a whole percentage rounded with RoundDown, RoundUp, or RoundNearest, and nil when total is 0. Round each percentage the way its schema's x-epack-rounding says.

When it emits, an SDK collector adds artifacts/myservice.collector-result.json, with schema evidencepack/collector-result@v1: the outcome, each gap with the operation, call, and line of code behind it, each step's timing and calls, each operation's calls, retries, and statuses, and the identity it signed in as. It also adds artifacts/myservice.collector-build.json, with schema evidencepack/collector-build@v1: the collector's schemas, its trace map, and the record of its test suites, the same for every run of one build. Artifacts are checked against the schemas in CollectorSpec.Schemas, and findings are listed in the result. For DNS lookups and TLS connections, use componentsdk.NewResolver and componentsdk.NewDialer. The collect protocol covers rollups, schema keywords, and the result's fields.

Below the audit level, the result leaves out the tenant ID, each operation's counts, statuses, and errors, each step's times and counts, and a gap's call number and unmeasured count, since these grow with the account's size or identify it. Operations keep retried, status_codes, and error_codes at every level, and steps keep any_failed, so a trust result still says which calls failed or were retried.

Testing with collectortest

componentsdk/collectortest runs the collector in process against canned responses, then injects faults into each operation: 401, 403, 404, 429, 500, a timeout, a reset connection, and truncated, malformed, or empty bodies. Under each fault every value must keep its clean value or be left out with a gap whose code matches the fault. It sets each field the collector reads to null, drops it, and empties each list, and no number or boolean may change without a gap. It also checks that no secret reaches an artifact and no credential reaches another host:

func TestCollector(t *testing.T) {
    collectortest.Run(t, collectortest.Suite{
        Spec:       spec,
        Run:        run,
        Secrets:    map[string]string{"MYSERVICE_API_TOKEN": "example-token-0123456789"},
        Scenarios:  []collectortest.Scenario{clean},
        Required:   []string{"me.get"},
        Operations: []string{"me.get", "users.list"},
    })
}

collectortest.Record records a real run as a scenario, scrubbing secrets, emails, addresses, and IDs, and collectortest.LoadScenario replays it. With COLLECTORTEST_OUT set, each scenario writes what it emitted, and epack-collector-diff compares two such trees, which is how CI shows a pull request's change to the evidence. Each suite writes under its Suite.Name, so two suites in one package need names of their own. See the collect protocol for scenarios, faults, and recordings.

Beside the fault matrix, the suite runs named checks. Each check reports a violation in these cases:

Check Reports
levelsA field marked with a level that appears below that level, as a value or as null, or a higher level that drops something a lower level emits
labelsA number or true-or-false value with no x-epack-label or no x-epack-summary in its schema, or an x-epack-goal that does not fit the value. Every field in the SDK's normalized schemas has both
pathsA data artifact anywhere but componentsdk.ArtifactPath(collector, schemaID), which is artifacts/<collector>.<kind>.json, with details as the kind of the file with no schema ID
normalizedA copy of a normalized schema in CollectorSpec.Schemas, which replaces the SDK's and falls behind it. Give the collector's methods in CollectorSpec.Methods instead. Also a Methods entry that names no field
methodsA number or true-or-false value with no x-epack-method in the collector's schema. This covers each such value in a normalized artifact and each one a trust run writes in a detailed artifact
writesAn artifact whose schema ID CollectorSpec.Writes does not list
permissionsA gap whose missing_permission differs from the permission its operation declares
redactionA gap, advice, warning, or failure message with a run hidden as a possible secret, such as a long error code with digits in it
guidanceAdvice that holds a value from the scenario's answers or config that identifies a resource, person, or account. Also a second piece of advice on one gap, and a choice with fewer than two options
responsesA canned answer that does not match the vendor's schema in Suite.ResponseSchemas, or that has a field the schema does not define
pagesA next page an answer offers that the run never requests. For each operation that pages by Link header or body field, the check also adds a next page to the last answer and checks that the run requests it
vocabularyA value in a scenario's answers that the collector's vocabulary lacks
orderA value that changes when the lists in one operation's answers are reversed
variantsA value that does not follow a Suite.Variants rewrite, such as an ARN prefix the collector hard-codes, or a request the rewritten scenario cannot answer
fieldsWith Suite.FieldSensitivity on, a state field, such as a status, enabled flag, or condition, whose change leaves every value the same in an object the collector reads
field_faultsA number or true-or-false value that changes when a field the collector reads is set to null, dropped, or, for a list, emptied, instead of keeping its value or being left out with a gap. The check runs in every suite. Suite.Populations declares a list whose emptying is a real answer, such as a users list, and Suite.Omissions a field the vendor leaves out to mean a value
populationA value that is set although its denominator is 0 or was not read, or its x-epack-present flag is false or was not read. A percentage over an empty population is written as null, and left out only with a gap
tracemapA committed trace map whose source lines no longer match the code, or that lacks a field, an operation, or a gap line the runs find
coverageA call with no operation name, a suite with no Operations, an operation no scenario reaches, or a call the list lacks
waiversA waiver past its expiry, whose check runs again, or a recording waiver in a suite that replays a recording
ratiosA percentage that differs from its numerator over its denominator, rounded as its x-epack-rounding says, or a numerator larger than its denominator

Every check is on. Suite.Waivers turns one off or softens one, for a stated reason and until a date at most a year out, and the build file reports the waiver. A waiver names a check from collectortest.CheckNames(), or one of the softenings: WaiveFault leaves a fault out of the matrix, WaiveInsensitive marks an operation whose responses change no value, such as a token exchange, WaiveCapped an operation that may leave a page unread, such as a list the collector cuts short with a partial gap or a polling API that always offers another page, WaiveOrdered an operation whose answers come in an order the vendor documents, WaiveIgnore values that may change under a fault without a gap, WaiveIgnoredField a state field the collector may ignore, and WaiveRecording a sandbox the suite has no recording of yet. From the expiry the kit runs the check again and reports the waiver under waivers. A suite that still sets SkipChecks, SkipFaults, Ignore, Insensitive, Capped, Ordered, or IgnoredFields fails with the waiver to add. Suite.Paged lists operations that page by Link header when the scenarios do not show it. Each of Suite.Variants rewrites the clean scenario for another deployment of the vendor, such as AWS GovCloud, with old and new string pairs. InProcessResult.Operations counts each operation's calls at every level, so the fault matrix and credential checks work for a suite that runs at the trust level.

componentsdk/collectortest/roster describes a test account as a roster, and roster.Derive gives the value each normalized field should have under the schema's definitions. componentsdk/collectortest/simulate builds a simulator of the service from a roster, with each answer copied from the test account's recording, and compares the collector's normalized values with the derived ones. It fails on a simulated answer the recording doesn't hold unless the simulator lists it with a reason, and it runs a matrix of roster variants and rules over random rosters.

Collector CI runs the tests under the race detector with Go's default timeout of 10 minutes. For a suite that takes longer, set the shared workflow's test-timeout input under with: in ci.yaml, such as test-timeout: 30m.

Schema annotations

The collector's schema says what each value means with x-epack keywords. The SDK and the test kit read them to check the output:

Keyword Meaning
x-epack-levelThe lowest level whose output includes the field. At the schema's root it marks the whole artifact, which the SDK leaves out below that level. A required property above the run's level is not reported missing
x-epack-labelA label of a few words, in sentence case, such as "Disk encryption"
x-epack-summaryOne or two plain sentences on what the value counts or says, for a reviewer reading the pack
x-epack-goalThe better value, where one is better. It is true or false on a true-or-false value, and higher or lower on a count. A percentage takes its direction from x-epack-rounding
x-epack-methodOne plain sentence on how the collector measures the value, such as "Reads each S3 bucket's default encryption setting." It goes in the collector's own schema. For a normalized artifact it goes in CollectorSpec.Methods, keyed by schema ID and field, and the SDK adds it to its own schema
x-epack-denominatorThe count a percentage or ratio is taken over
x-epack-numeratorThe count a percentage is taken of. On a boolean, the boolean is true exactly when the numerator equals the denominator
x-epack-presentA boolean field that is true when the value's population has any members, for a level that leaves the denominator out
x-epack-roundingfloor, ceil, or nearest. A percentage where more is better rounds down, and one where more is worse rounds up
x-epack-replaced-byOn a deprecated field, where its value is now, as {"schema", "path", "same", "reason"}. path is absent on a block, and on a field nothing replaces. same is true when the new field holds the same value in the artifact from the same collector. A profile test can move to it as it is only when the schema stays the same, since a test on another schema reads that schema's artifacts from every system. reason is one sentence on why the field moved, for someone editing a profile. A field with no reason of its own takes its block's. Every deprecated field in the SDK's normalized schemas has one
x-epack-rollupA count or percentage of the rows in a list, such as the users with MFA. among lists conditions that pick the rows it covers, such as active apps only, and where names the field a counted row must have

A value copied from the detailed artifact with Recorder.Mirror uses the method of the value it copies, so a collector that fills its normalized artifact from its detailed one writes each method once. The collect protocol's output checks section lists every keyword and its form.

Trace maps

A trace map links each field of the collector's artifacts to the operations whose failure leaves it out or changes it, the lines of code that compute it, and the lines that record its gaps. epack sdk map builds it from the collectortest suites and the source and writes docs/schema/trace-map.json. Commit it and pass it, embedded, as CollectorSpec.TraceMap, and every pack's build file carries it:

epack sdk map            # Rebuild docs/schema/trace-map.json
epack sdk map --check    # Fail when the committed map is stale

Collector CI runs epack sdk map --check, and a suite run fails when it finds a field or an operation the committed map lacks, or a line of the map that no longer matches the code. So a change to the code that moves the map fails until you run epack sdk map again. The map also keeps each suite's record under suites: the operations it declares, its scenario and recording counts, and its waivers. --capabilities lists the same suites, and conformance reads them (COL-110 to COL-114), so run epack sdk map again after a change to a suite, not only to the code. See the collect protocol's build file section.

Surface check

What a collector leaves out of a vendor's API should come from the vendor's description, not from memory. epack sdk surface matches each request in the collector's recordings to an operation of the vendor's OpenAPI description, given with --spec. What the collector reads is then a fact of the recordings, and every other read operation in scope needs a verdict in docs/surface.yaml: a not_collected item with the sentence the documentation shows, or an irrelevant one with the reason. An item covers operations by name, tag, category or path prefix, and a named operation wins over a broad selector.

epack sdk surface --spec openapi.json            # Report what needs a verdict
epack sdk surface --spec openapi.json --write    # Render the Not Collected section and docs/coverage.md
epack sdk surface --spec openapi.json --check    # Fail when a verdict or a document is stale
epack sdk surface --check                           # Fetch the description docs/surface.yaml names by url, then check

Two documents are rendered from the verdicts. The Not Collected section of docs/overview.md shows the overview headlines, each folding items into the one sentence a buyer needs, and points at the coverage reference. docs/coverage.md leads with what the collector reads by area, then holds every item with its operations, the calls the sandbox never exercises, what is left out as irrelevant and why, and the recorded calls outside the description. spec.sha256 pins the description, so a refreshed one fails the check until its new operations are reviewed. See the collect protocol's surface check section.

A collector checked against several descriptions, such as Microsoft Graph and the Azure resource providers, lists them under specs, each with a name, and passes --spec once per entry; a description may be a directory of files. An entry can name the description's url, pinned to a revision and checked against its sha256, and epack sdk surface fetches it into epack's cache, so CI needs no committed copy. A verdict item may select by path_contains, be limited to named descriptions with in, and carry a priority that wins over more specific items. Collector CI's surface job runs the check for a collector with a docs/surface.yaml, through make surface when the Makefile has the target and at the go.mod epack version otherwise.

Collection levels

Collectors can gate optional fields on the caller's requested level. Read it via ctx.Level() and compare with AtLeast. Absent, empty, or unknown values downgrade to LevelTrust with a warning on stderr, so collectors never silently gather more than was asked for.

level := ctx.Level()

if level.AtLeast(componentsdk.LevelAudit) {
    // gather per-resource detail an auditor would want
}
if level.AtLeast(componentsdk.LevelInternal) {
    // gather raw inventory (user lists, audit-log slices, etc.)
}

Each collector documents which of its fields appear at audit vs internal. The SDK writes the run's level to the collector result as run.level. The normalized schemas do not declare collected_at_level, and endpoint-posture does not allow it.

A schema can set x-epack-level at its root to mark the whole artifact. A collector whose normalized artifact carries what profiles read marks its detailed schema audit, so a trust run leaves the detailed file out and the normalized values copied from it stay. The SDK drops the gaps inside a file it leaves out, except a gap Recorder.Mirror copied to a normalized value. A collector with no normalized artifact keeps its detailed artifact at trust, and each field's level decides what appears.

IDs of the company's own accounts and resources, such as account IDs and ARNs, sit at audit or above. Such a field can stay in its object's required list, since the schema check skips a required property above the run's level.

Choosing what to collect

The reserved collect config key lists the kinds of evidence a collector collects, such as [cloud-posture, details]. A kind is the name in a schema ID, and a collector's own detailed file is the kind details. Without the key, a collector collects every kind its level allows. Emit leaves out each kind the key does not list and records a not_shared gap for it, so a collector honors the key with no code of its own. To skip the calls that feed only one kind, check componentsdk.Selected first:

if componentsdk.Selected(ctx, componentsdk.Location{Schema: "evidencepack/idp-posture@v1"}) {
    // calls only the normalized artifact needs
}

Selected is also false for a file whose schema marks it for a higher level than the run. When the key leaves out a normalized kind, the values Recorder.Mirror copied from it into other files are removed too, each with a not_shared gap. So is each value Recorder.Moved placed beside it, with the gaps inside that value. Both hold when Selected ruled the kind out and the collector never built it.

Declaring targets

Recorder.Targets declares what a run was pointed at: its container, such as an organization or tenant, and the resources it assessed, such as accounts or repositories. Each declaration points at where the targets sit in the artifacts and says how they were chosen, and the SDK writes them to the collector result. See the collect protocol's targets section.

componentsdk.Records(ctx).Targets(componentsdk.TargetEndpoint, componentsdk.Location{Path: "artifacts/tls.tls.json", Pointer: "/endpoints"}, "/host", "/port").
    ChosenBy(componentsdk.ChosenByConfig, "endpoints")

Normalized artifacts

A normalized artifact holds the same fields for every service of one type, so a profile reads it the same way whichever collector wrote it. The SDK has a schema for each type below, and Emit checks each normalized artifact against it. componentsdk.NormalizedSchemaJSON(schemaID) returns the schema.

Schema ID What it covers
evidencepack/idp-posture@v1An identity provider's users, MFA, apps, privileged access, account lifecycle, and sign-in policy
evidencepack/cloud-posture@v1Storage, databases, logging, network rules, backups, and threat detection in each cloud account
evidencepack/vcs-posture@v1Repository coverage and branch protection in a code host
evidencepack/endpoint-posture@v1Device management, compliance, hardening, patching, and protection across a fleet
evidencepack/access-posture@v1Sign-in rules, members, admins, root accounts, machine credentials, and connected apps for one system
evidencepack/vuln-scanning@v1Each scanner's coverage and open findings by severity for one system
evidencepack/email-dns@v1MX, SPF, DKIM, and DMARC records for each domain
evidencepack/tls@v1The certificate and TLS settings of each endpoint

A collector writes one access-posture file and one vuln-scanning file for each system it reads, such as GitHub, AWS, or ClickHouse. A system with several accounts or subscriptions holds totals across them, and lists each one in scopes at the audit level. cloud-posture has no iam, vuln_scanning, or workforce_sign_in, and vcs-posture has no org_security or security_features. Those values are in access-posture and vuln-scanning.

In access-posture, a member or admin is local when they can sign in without SSO, even if their account is linked to SSO. Local and SSO members can overlap when the system does not require SSO. A credential is unrestricted when it has neither an IP limit nor a scope narrower than full access. With scopes, a top-level sign_in value is false when any scope's value is false. Otherwise it is null when any scope's value is null, and true when every scope's value is true.

In vuln-scanning, a scanner turned on per resource, such as per repository, is enabled when it is on for at least one resource. Its coverage_pct gives the share of resources it covers.

In every type, the counts are written from the audit level, except in the tls and email-dns summaries. A *_present flag beside each count is written at every level and says whether the population has any members. A percentage over an empty population is null. This is an access-posture file from a trust run:

artifacts/myservice.access-posture.json
{
  "schema_version": "1.0.0",
  "collected_at": "2026-11-05T14:30:00Z",
  "provider": "myservice",
  "system_type": "saas",
  "sign_in": {
    "sso_configured": true,
    "sso_required": false,
    "mfa_required": true,
    "scim_enabled": true
  },
  "members": {
    "members_present": true,
    "sso_coverage_pct": 92,
    "local_members_present": true,
    "local_mfa_coverage_pct": 100
  },
  "admins": {
    "admins_present": true,
    "admin_share_pct": 4
  },
  "credentials": {
    "credentials_present": false,
    "never_expiring_pct": null,
    "unused_pct": null,
    "unrestricted_pct": null,
    "write_access_pct": null,
    "rotation_overdue_pct": null
  }
}

List each normalized schema ID in CollectorSpec.Writes, and name the file with componentsdk.ArtifactPath(spec.Name, schemaID). Copy each value the detailed artifact also holds with Recorder.Mirror(from, to), which copies its gap and its x-epack-method. For each value the collector computes for the normalized artifact alone, give the method sentence in CollectorSpec.Methods:

Methods: map[string]map[string]string{
    "evidencepack/access-posture@v1": {
        "/sign_in/sso_required": "Reads the workspace's sign-in setting and checks that only SSO sign-in is allowed.",
    },
},

Never copy a normalized schema into CollectorSpec.Schemas. A copy replaces the SDK's schema and falls behind it, and the test kit's normalized check reports it. CollectorSpec.ArtifactSchemas() returns the schemas Emit uses, with the methods added.

File artifacts

Use file artifacts when a collector needs to package raw bytes such as PDFs, screenshots, or archives. The runner provides a per-collector staging directory; SDK collectors access it through componentsdk.Staging(ctx).

staging, ok := componentsdk.Staging(ctx)
if !ok || staging.OutputDir() == "" {
    return componentsdk.NewConfigError("file artifacts require epack v0.2.0 or newer")
}

name, err := staging.WriteStagedFile("documents/policy.pdf", pdfBytes)
if err != nil {
    return err
}

return ctx.Emit([]componentsdk.CollectedArtifact{
    componentsdk.FileArtifact("artifacts/documents/policy.pdf", name,
        componentsdk.ArtifactMeta{DisplayName: "Security policy"}),
})

For streaming output, use StageFile, close the returned handle, and emit the returned name. File artifacts require an explicit pack Path and are mutually exclusive with Data.

Implement a tool

main.go
func run(ctx componentsdk.ToolContext) error {
    // Access the pack
    pack := ctx.Pack()

    // Read an artifact
    data, err := pack.ReadArtifact("artifacts/github-repos.json")
    if err != nil {
        return err
    }

    // Analyze
    result := analyze(data)

    // Write output
    return ctx.WriteOutput("analysis.json", result)
}

Pack access

pack.Manifest()                                    # Get manifest
pack.ReadArtifact("artifacts/report.json")         # Read artifact
ctx.Warn("CODE", "message", "path")                  # Add warning
ctx.Error("CODE", "message", "path")                 # Add error

Implement a utility

main.go
func run(args []string) error {
    if len(args) == 0 {
        return fmt.Errorf("no pack file specified")
    }

    pack, err := componentsdk.OpenPack(args[0])
    if err != nil {
        return err
    }
    defer pack.Close()

    fmt.Printf("Stream: %s\n", pack.Manifest().Stream)
    return nil
}

Implement a remote adapter

main.go
type handler struct{}

func (h *handler) PushPrepare(req componentsdk.PushPrepareRequest) (*componentsdk.PushPrepareResponse, error) {
    url, token := generateUploadURL(req.Target.Workspace, req.Pack.Digest)
    return &componentsdk.PushPrepareResponse{
        Upload:        componentsdk.UploadInfo{Method: "PUT", URL: url},
        FinalizeToken: token,
    }, nil
}

func (h *handler) PushFinalize(req componentsdk.PushFinalizeRequest) (*componentsdk.PushFinalizeResponse, error) {
    release := createRelease(req.FinalizeToken)
    return &componentsdk.PushFinalizeResponse{
        Release: componentsdk.ReleaseResult{ReleaseID: release.ID, PackDigest: release.Digest},
    }, nil
}

func (h *handler) PullPrepare(req componentsdk.PullPrepareRequest) (*componentsdk.PullPrepareResponse, error) {
    url, digest, token := getDownloadURL(req.Target.Workspace, req.Ref)
    return &componentsdk.PullPrepareResponse{
        Download:      componentsdk.DownloadInfo{URL: url},
        Pack:          componentsdk.PackResult{Digest: digest},
        FinalizeToken: token,
    }, nil
}

func (h *handler) PullFinalize(req componentsdk.PullFinalizeRequest) (*componentsdk.PullFinalizeResponse, error) {
    return &componentsdk.PullFinalizeResponse{Confirmed: true}, nil
}

Release

Tag a release to trigger the scaffolded GitHub workflow:

git tag v0.2.0
git push origin v0.2.0

The workflow builds for linux/amd64, linux/arm64, darwin/amd64, darwin/arm64 with SLSA Level 3 provenance and Sigstore signing. A collector's release workflow runs CI first, so a tag cannot ship a stale trace map. With the repository variable SANDBOX_RELEASE_CHECK set to true, the tag creates a draft release, which publish.yaml publishes once a passing sandboxes commit status arrives from the account named in SANDBOX_STATUS_SENDER. Without the variable, the tag publishes at once.

epack shadow shows what a new version would change in a project that already runs the collector. Before you tag a release, run it with your local build:

epack shadow myservice --binary ./epack-collector-myservice

Configure in epack.yaml

Collectors and tools

epack.yaml
collectors:
  myservice:
    source: ghcr.io/yourorg/epack-collector-myservice@v1
    config:
      organization: acme
    secrets:
      - MYSERVICE_API_TOKEN

tools:
  analyzer:
    source: ghcr.io/yourorg/epack-tool-analyzer@v1

Remotes

epack.yaml
remotes:
  mycloud:
    source: ghcr.io/yourorg/epack-remote-mycloud@v1
    target:
      workspace: acme
    auth:
      mode: api_key

Utilities

Utilities are standalone CLI tools invoked directly:

epack utility viewer evidence.epack