Engineering standard

Go / CLI

Introduction: purpose and core principles

Go / CLI is Solution200’s engineering standard for command-line applications, importers, network services and background processes. It defines how to organize code, specify an operation’s contract and verify its result before production use.

One standard for different programs

The full corpus contains 89 rules covering formatting, documentation, concurrency, dependencies, security and data publication. A common baseline applies to all Go code; additional requirements apply to the boundaries a program owns. An HTTP service, a local command and an importer have different operational contracts.

Code structure and documentation

Each package owns a defined capability. Repeated behavior has a single owner, and small interfaces are formed at the consumer boundary. Comments explain purpose, invariants, units, side effects and failure modes. Formatting follows gofmt; syntax conventions from another language are not imposed on Go.

Command contracts and errors

  • Arguments and configuration for the selected operation are validated before its side effects begin.
  • Machine-readable results are separate from diagnostics; exit codes distinguish supported outcomes and failures.
  • Long-running calls receive context.Context, time limits and a cancellation mechanism.
  • Errors preserve their cause. Write, close and process-completion failures cannot be hidden behind success.

Configuration, credentials and networks

Inputs have typed schemas and size limits. Unknown or duplicate configuration keys, invalid encoding and conflicting options are rejected. Secrets are required only by the operation that uses them and stay out of repositories, command arguments and logs.

Network calls have explicit destinations, time limits and volume bounds. Redirect policy applies to HTTP; other protocols define their own checks. Retries have a bounded budget and require safe operation semantics.

Importers and background work

A run has an identity, scope and declared bounds. Its terminal result carries structured counts and failure reasons. Partial work is not reported as complete success. Data is validated before atomic publication; a failed import preserves the last valid state.

Exclusion of overlapping runs matches the execution environment. Distributed leases require expiry, renewal and protection against stale publishers. Restart behavior accounts for idempotency and ambiguous outcomes from previous operations.

Dependencies and verification

The standard library is the starting point. External dependencies require a justification, pinned versions and review of licensing, transitive dependencies and known vulnerabilities. Go and verification-tool versions are pinned for reproducible execution.

go test -mod=readonly -count=1 ./...
go vet -mod=readonly ./...
staticcheck ./...
govulncheck ./...

These commands are part of verification for one explicitly selected module. The full set also covers gofmt, the diff from a verified base revision, owning tests for functions and material outcomes, architecture constraints, race checks and applicable integration and fuzz scenarios. Nested modules are verified separately. One successful command does not establish compliance with the entire standard.

Applying the standard

Before a change, identify the owning package, applicable rules and acceptance criteria. After implementation, review the exact diff and verify the declared scenarios. Missing checks, unverified outcomes and approved exceptions are recorded separately.

Server Bootstrap CLI is one application in Solution200’s Go direction. The shared rules also serve importers and workers. This page explains the main principles; the versioned engineering standard owns the exact requirements and acceptance criteria.

Package organization by capability

A Go module should let readers find a capability by its purpose. Its contract, implementation, values, errors and tests form one understandable area of responsibility. Package boundaries explain dependencies and what the code does.

GO-PKG-001 One capability per package

A package owns one semantic capability; its files are named after operations. An operation becomes a sub-package when its distinct dependencies, failure surface or consumer justify the import boundary and the exports it creates. Apply the same criterion recursively.

Rationale. Contracts and behavior stay together. A small file count does not justify merging independent operations. Shared details remain unexported or under internal/.

Review criterion. Path, package name, documentation and tests identify the same capability. Distinct dependencies and failure modes have been assessed. Platform variants use build constraints and an explicit unsupported twin as required by GO-PLAT-001.

GO-PKG-002 Names explain purpose

Package and directory names describe a domain capability or a specific mechanism. The technical catchall names listed below are prohibited.

Rationale. A package named validation or atomicwrite guides the reader; a technical container hides unrelated responsibilities.

Review criterion. Check directory basenames and package clauses. A GO-PKG-002 exception must record the path, the domain meaning of the word and its owner; the architecture test reads that exception list.

Prohibited technical names: util, utils, common, misc, service, services, dto, model, models, entity, types, provider, providers, adapter, adapters, handler, handlers, manager, helper, helpers, base, shared.

GO-PKG-003 Thin commands, explicit routing

cmd/<name> contains only argument parsing, configuration loading, dependency composition, operation routing and exit-code mapping. Each command family has its own file. Operation behavior, response encoding helpers and domain vocabularies belong in capability packages.

Rationale. A capability can be called and tested without the CLI. Shared protocol identifiers, operation registries and response envelopes have one canonical definition in one owning package.

Review criterion. main and routing files contain no operation implementation. If another program must mirror a shared definition, a contract test proves equality.

GO-PKG-004 Reuse the lowest semantic owner

Before adding a package, search existing modules for the same capability by meaning. Reuse a fitting contract; record the closest rejected candidates and their semantic differences.

Rationale. Product-independent behavior belongs to the lowest reusable owner of its contract and dependencies, even with one consumer. The application retains product policy, runtime values and composition.

Review criterion. Compare contract, nullability, validation and failure behavior. Infrastructure duplicated across modules requires a recorded reason and a contract test proving equivalence.

GO-PKG-005 Test the architecture

Ordinary Go tests enumerate the repository’s own source tree and check names, documentation under GO-DOC-002, dependency direction, prohibited modules and the third-party module allowlist under GO-DEP-001.

Rationale. Enumeration also finds new packages. The standard library — go/parser, go/ast, go/build, go/types or go list -json — supports architecture checks without adding a dependency.

Review criterion. Check directory names and package clauses rather than a manually maintained package list. A focused negative test must reject a violating fixture under testdata/. The go tool ignores this directory; the architecture test reads it explicitly.

Educational example: command and capability boundary

This is a teaching layout for a Go module. Here validation owns validation behavior; checker composes dependencies and calls it. The standard mandates neither a universal directory depth, a file length nor a pkg/ directory.

cmd/
└── checker/
    └── main.go
internal/
├── validation/
│   ├── validate.go
│   └── validate_test.go
└── architecture/
    ├── architecture_test.go
    └── testdata/
        └── violations/
            └── utils/
                └── invalid.go

Prove that the check can fail

A focused negative test passes a fixture from testdata/violations/utils/, declaring package utils, to the analyzer and expects a GO-PKG-002 diagnostic. The expected outcome is rejection of the fixture with this rule’s diagnostic.

A negative test: one check, two outcomes

This minimal teaching example checks one prohibited name. A complete architecture test walks the tree and checks the full name list, documentation and dependencies.

// Package architecture demonstrates package-name checks in tests.
package architecture

import (
	"errors"
	"fmt"
	"go/parser"
	"go/token"
	"testing"
)

// errTechnicalName identifies the prohibited-name diagnostic in this example.
var errTechnicalName = errors.New("GO-PKG-002: technical package name")

// rejectUtils illustrates one package-name restriction using the Go parser.
func rejectUtils(source string) error {
	file, err := parser.ParseFile(token.NewFileSet(), "fixture.go", source, parser.PackageClauseOnly)
	if err != nil {
		return fmt.Errorf("parse package clause: %w", err)
	}
	if file.Name.Name == "utils" {
		return errTechnicalName
	}
	return nil
}

// TestRejectsTechnicalName checks both accepted and rejected package clauses.
func TestRejectsTechnicalName(t *testing.T) {
	if err := rejectUtils("package validation"); err != nil {
		t.Fatalf("valid package: %v", err)
	}
	if err := rejectUtils("package utils"); !errors.Is(err, errTechnicalName) {
		t.Fatalf("expected GO-PKG-002, got %v", err)
	}
}

Contracts and documentation

A reusable API explains the promises that its signature cannot express. Documentation, types and compatibility evidence make those promises reviewable.

GO-DOC-001 A package has an ownership contract

Every non-generated package, including package main, has a meaningful package comment; an external x_test package is covered by its package’s comment. doc.go is conventional, not mandatory. A materially significant package also has discoverable repository or package documentation of its ownership boundary.

Rationale. Names and implementation samples do not explain who owns a capability or what consumers may rely on.

Review criterion. Together, the documents describe purpose, owner, consumers, responsibilities and exclusions, primary entry points and dependency direction; where applicable, compatibility and persistence ownership. They state which runtime, deployment or security properties the package does not claim.

GO-DOC-002 Document every declaration meaningfully

Document every package-level type, constant, variable and function, every method and interface method, and every field of a named struct, including unexported declarations, test helpers and tests. Use a meaningful doc comment or trailing line comment. Function-local declarations and anonymous struct-literal fields are exempt; files recognized by ast.IsGenerated are excluded.

Rationale. Exported comments explain the consumer contract; unexported comments explain purpose and why this form is needed. A signature repeated in prose adds no contract.

Review criterion. A repository-local architecture test parses the package tree and rejects missing comments; review checks meaning. A test comment names the behavior proved. The opening sentence starts with the name or reads naturally with it as subject. A shared const/var group may have one comment only when all members share its meaning; differing members need their own. For a non-trivial API, review the applicable contract dimensions below.

  • Input: applicable values, invariants, units and the zero value.
  • Ownership: mutation, side effects, idempotency and durability.
  • Result: error identities and partial results.
  • Execution: cancellation, blocking and concurrency safety.
  • Trust: redaction boundaries. Explain why canonicalization, security, concurrency, bounds and state-transition constraints exist.

GO-DOC-003 Examples demonstrate reusable contracts

Important reusable APIs should provide executable examples or contract tests. A deprecated export has a canonical Deprecated: paragraph naming its replacement, retains consumer coverage and records a deliberate removal condition outside source history.

Rationale. A runnable example teaches observable behavior and can reveal a contract that drifts. Deprecation gives consumers a usable migration path.

Review criterion. Review the examples or contract tests and retained consumer coverage. Check the replacement and recorded removal condition. Personal author tags are not mandatory in source comments; ownership belongs in repository governance and review history unless an exact product rule requires otherwise.

GO-DOC-004 The repository supports handoff

The module README or linked accepted documentation identifies purpose and ownership, supported Go/toolchain and operating systems, build/test/verification commands, executable entry points, compatibility/release policy, security-reporting route and accepted documentation index.

Rationale. A reader can build, verify and maintain the module without reconstructing its operating contract from source.

Review criterion. Each field is present or explicitly linked to organization policy. A private repository need not duplicate a public license or contribution template when organization governance deliberately owns it elsewhere.

GO-API-001 Types express semantic boundaries

Cross-package and external boundaries use named types, structs and typed results. Where a stable vocabulary exists, avoid any, map[string]any, stringly typed option bags and ambiguous boolean tuples.

Rationale. Distinct units, validation, privacy or lifecycle deserve named semantic types so callers cannot silently confuse their meanings.

Review criterion. Check those semantic distinctions at boundaries. External and durable representations declare explicit wire names and schema/version behavior.

GO-API-002 Construction and ownership are explicit

Constructors and parsers validate invariants before returning a usable value. The zero value is deliberately useful, or its unsupported use is clearly documented and rejected at the boundary. A constructor does not hide network activity, process startup or durable writes unless that effect is central to its documented contract.

Rationale. A caller needs to know when a value is usable and who can mutate its data. Hidden effects and shared mutable storage can invalidate the promise made at construction.

Review criterion. State ownership of slices, maps, byte buffers and mutable pointers. Copy on input or output when mutation would violate invariants; copying is conditional on that risk. Internal maps or slices must not be exposed as read-only merely by convention. Check zero-value behavior and documented central side effects.

GO-API-003 Compatibility has consumer evidence

API, wire and durable-state changes require consumer discovery and compatibility evidence. Compatibility aliases and deprecated paths have a documented replacement, retained consumer/round-trip tests, an explicit migration owner and a removal condition or version boundary.

Rationale. Keeping an old name alone does not demonstrate that consumers or stored data still work.

Review criterion. Identify the affected consumers and inspect compatibility evidence. For each alias or deprecated path, verify all four migration requirements and the retained tests.

Ownership and the zero value

The teaching Batch validates names, copies inputs and outputs, and explicitly rejects its zero value. Tests mutate both copies; ExampleBatch checks the consumer result.

// Package batch illustrates explicit validation and ownership at a Go API boundary.
package batch

import (
	"errors"
	"slices"
	"strings"
)

// ErrInvalid identifies an empty batch or a name containing only whitespace.
var ErrInvalid = errors.New("batch requires non-empty names")

// Name identifies a task label; New validates whether it can enter a batch.
type Name string

// Batch owns a validated sequence of names. Its zero value is invalid;
// Names rejects it with ErrInvalid. Construction performs no external effects.
type Batch struct {
	// names belongs exclusively to the batch and is never returned directly.
	names []Name
}

// New validates each name and copies the input so later caller mutations are isolated.
func New(names []Name) (Batch, error) {
	if len(names) == 0 {
		return Batch{}, ErrInvalid
	}
	for _, name := range names {
		if strings.TrimSpace(string(name)) == "" {
			return Batch{}, ErrInvalid
		}
	}
	return Batch{names: slices.Clone(names)}, nil
}

// Names returns a caller-owned copy, or ErrInvalid for the invalid zero value.
func (b Batch) Names() ([]Name, error) {
	if len(b.names) == 0 {
		return nil, ErrInvalid
	}
	return slices.Clone(b.names), nil
}
Read the example and tests
package batch

import (
	"errors"
	"fmt"
	"testing"
)

// TestOwnsInputAndOutput proves caller mutations cannot change an existing batch.
func TestOwnsInputAndOutput(t *testing.T) {
	input := []Name{"daily"}
	value, err := New(input)
	if err != nil {
		t.Fatal(err)
	}
	input[0] = "changed input"
	output, err := value.Names()
	if err != nil {
		t.Fatal(err)
	}
	output[0] = "changed output"
	again, err := value.Names()
	if err != nil {
		t.Fatal(err)
	}
	if len(again) != 1 || again[0] != "daily" {
		t.Fatalf("caller mutation reached the batch: %v", again)
	}
}

// TestRejectsInvalidInputAndZeroValue protects construction and the public read boundary.
func TestRejectsInvalidInputAndZeroValue(t *testing.T) {
	for _, input := range [][]Name{nil, {}, {""}, {" "}} {
		if _, err := New(input); !errors.Is(err, ErrInvalid) {
			t.Fatalf("expected ErrInvalid, got %v", err)
		}
	}
	var zero Batch
	if _, err := zero.Names(); !errors.Is(err, ErrInvalid) {
		t.Fatalf("zero value: expected ErrInvalid, got %v", err)
	}
}

// ExampleBatch documents the successful consumer path with an executable result.
func ExampleBatch() {
	value, err := New([]Name{"daily"})
	if err != nil {
		fmt.Println("invalid batch")
		return
	}
	names, err := value.Names()
	if err != nil {
		fmt.Println("invalid batch")
		return
	}
	fmt.Println(names)
	// Output: [daily]
}

Errors and failure decisions

An error contract tells callers what failed, which identity remains stable and what action is safe. Human-readable context supports diagnosis; typed identities and classifications guide program behavior.

GO-ERR-001 Return expected failures

Expected operational, validation and user-controlled failures return error. Reserve panic for an impossible programmer invariant or a process startup condition that cannot be represented safely. Reusable packages return errors; log.Fatal and os.Exit belong only at the real process boundary.

Rationale. The caller owns the response to an expected failure. A goroutine or handler processing independent units recovers only at the unit or request boundary: it reports a permanent internal failure of that unit and never resumes using shared state that may be inconsistent.

Review criterion. Exercise expected failures and boundary recovery. Check that recovery reports the failed unit without unsafe continuation, and that reusable code cannot terminate the process.

GO-ERR-002 Preserve error identity

Use %w when callers need the underlying identity, and inspect it with errors.Is or errors.As. Sentinel and typed identities have stable compatibility semantics. Create a sentinel once as a package-level variable; a fresh errors.New with the same text at each failure site does not preserve identity.

Rationale. Machine behavior cannot depend on parsing human messages. Context names the failed operation without repeating the same log-and-return message at every layer. Error text normally starts lower-case and has no terminal punctuation; proper names and stable external protocols may require different casing. Multiple %w operands deliberately expose multiple underlying errors.

Review criterion. Tests assert identity with errors.Is or errors.As. Text assertions are reserved for a text contract, such as redaction, a stable CLI message or a wire error body. Review every multi-wrap for intentional multi-error semantics.

GO-ERR-003 Handle errors that affect the result

Handle failures of writes, Close, Flush, Sync, rollback, lock release and cleanup whenever they affect correctness, durability or the promised result. A deferred close that can invalidate success needs named-result handling or explicit finalization.

Rationale. Returning success before finalization can hide a failed operation. An ignored error is acceptable only when structurally harmless and locally justified; assigning it to _ does not supply that justification.

Review criterion. A repository architecture test using go/ast and go/types, or an equivalent pinned analyzer, rejects discarded results from Close, Flush, Sync, Rollback, Unlock and repository-listed functions. Behavioral tests cover consequential finalization failures; review checks the justification for harmless omissions.

GO-ERR-004 Keep public context safe

An error crossing a trust boundary contains only safe context. Exclude secrets, credentials, raw payloads, private state, full command lines and uncontrolled infrastructure errors. Redaction fails closed and has tests.

Rationale. A useful public explanation identifies the operation without exposing internal causes or sensitive data. A locally wrapped cause remains within its diagnostic trust boundary.

Review criterion. Exercise public error serialization and redaction with sensitive and unexpected causes. Verify that a redaction failure cannot fall back to exposing the original error.

GO-ERR-005 Classify failures for safe action

When callers choose between retry, give-up and operator inspection, expose a typed classification. The classified error carries Reason, a named string type with constants declared by its owning package. Parse externally decoded values with a function that rejects unknown tokens; a test enumerates the vocabulary.

Rationale. Similar messages can require different actions. Wrap the underlying cause for local diagnostics and keep it inside the trust boundary. Caller-requested context.Canceled means interruption, never transient failure. A deadline exceeded after a write was sent means an ambiguous outcome.

Baseline failure classes and safe next actions
ClassMeaningSafe action
PermanentThe same input fails again: invalid configuration or a schema or contract violation.Give up on repeating the same input; correct the cause.
TransientA bounded retry may succeed: a timeout, rate limit or temporary unavailability.Apply a bounded retry only when the operation is safe to repeat.
Ambiguous outcomeThe effect may or may not have happened, such as a lost response after a write.Reconcile or inspect; never retry blindly.
Ownership lostA lease, lock or fence no longer authorizes the caller.Stop work without publishing.

A non-success answer within an external system’s normal contract, such as a child process exit status or an upstream “no data” response, is a typed result value rather than an error.

Review criterion. Cover all four classes, rejection of unknown reasons, vocabulary enumeration, caller cancellation, a deadline after sending a write and loss of ownership. Assert typed decisions and safe public context without parsing message text.

Error identity and a reason vocabulary

The teaching example preserves a sentinel through %w, enumerates valid Reason tokens and rejects unknown values. This is part of an error contract; the operation context determines its failure class.

// Package failure illustrates a closed reason vocabulary and stable error identity.
package failure

import "errors"

// ErrUnknownReason identifies a reason token outside the accepted vocabulary.
var ErrUnknownReason = errors.New("unknown failure reason")

// ErrUnavailable is a stable identity retained when a local caller adds context.
var ErrUnavailable = errors.New("service unavailable")

// Reason is a semantic token. ParseReason validates values received from outside.
type Reason string

const (
	// InvalidInput means the same invalid input needs correction.
	InvalidInput Reason = "invalid_input"
	// ServiceUnavailable means a temporary availability condition needs bounded handling.
	ServiceUnavailable Reason = "service_unavailable"
	// ReplyLost means a sent operation needs reconciliation before another attempt.
	ReplyLost Reason = "reply_lost"
	// OwnershipLost means the caller must stop acting under the lost authority.
	OwnershipLost Reason = "ownership_lost"
)

// ParseReason rejects unknown and empty tokens instead of guessing their meaning.
func ParseReason(raw string) (Reason, error) {
	switch value := Reason(raw); value {
	case InvalidInput, ServiceUnavailable, ReplyLost, OwnershipLost:
		return value, nil
	default:
		return "", ErrUnknownReason
	}
}
Read the example and tests
package failure

import (
	"errors"
	"fmt"
	"testing"
)

// TestReasonVocabulary enumerates every accepted token and rejects unsupported inputs.
func TestReasonVocabulary(t *testing.T) {
	for _, expected := range []Reason{InvalidInput, ServiceUnavailable, ReplyLost, OwnershipLost} {
		actual, err := ParseReason(string(expected))
		if err != nil || actual != expected {
			t.Fatalf("known reason: got %q, %v", actual, err)
		}
	}
	for _, raw := range []string{"", "unknown", "REPLY_LOST"} {
		if _, err := ParseReason(raw); !errors.Is(err, ErrUnknownReason) {
			t.Fatalf("expected ErrUnknownReason, got %v", err)
		}
	}
}

// TestWrappingKeepsIdentity verifies context does not erase the caller's error contract.
func TestWrappingKeepsIdentity(t *testing.T) {
	err := fmt.Errorf("read snapshot: %w", ErrUnavailable)
	if !errors.Is(err, ErrUnavailable) {
		t.Fatalf("underlying identity was lost: %v", err)
	}
}

Context and cancellation

A context carries the deadline and stop signal of one operation. Returning from a function must not leave work running without a named owner.

GO-CTX-001 Context belongs to the call

When an operation accepts context.Context, it is the first parameter after a receiver, conventionally ctx. Do not pass nil, add context only for optional behavior or hide it in a variadic parameter or option field. Storing it in a struct requires an exceptional lifetime contract explaining why per-operation propagation is impossible. Committed production code does not use context.TODO().

Rationale. Context values carry request-scoped metadata across an API boundary. They do not replace configuration or optional function arguments.

Review criterion. Review signatures, call sites and struct fields. For an exception, inspect the lifetime contract; for context values, verify that they belong to a specific request.

GO-CTX-002 Propagate cancellation and finish work

Caller cancellation and deadlines reach blocking I/O, processes and network work. Every derived CancelFunc runs on every path, normally through defer cancel() immediately after construction. A library does not silently replace the caller context with context.Background().

Rationale. The only permitted detachment is bounded cleanup that must outlive cancellation: lease release, rollback or a final report. Immediately bound context.WithoutCancel(ctx) with its own short timeout. Returning must leave no unowned background work; cancellation and partial results belong to the API contract.

Review criterion. Test cancellation and deadline propagation, release of all CancelFuncs and completion of started work. A separate test proves that cleanup outlives caller cancellation, has its own deadline and returns a controlled failure.

Cleanup after cancellation

This educational example passes the caller context to write and detaches only release, bounding it with its own one-second timeout. Callbacks must honor their contexts; a timeout cannot forcibly interrupt arbitrary Go code. A write error does not prove the absence of an external effect.

// Package cleanup illustrates cancellation propagation and bounded resource release.
// It does not implement transactions, lease fencing or a durable write protocol.
package cleanup

import (
	"context"
	"errors"
	"time"
)

// ErrMissingOperation rejects incomplete callbacks before any operation starts.
var ErrMissingOperation = errors.New("write and release callbacks are required")

// WriteAndRelease runs write with the caller's non-nil context, then releases
// an already-owned resource even if the caller canceled. Release receives the
// caller's values and its own one-second deadline. Both callbacks must honor
// their contexts; this function starts no goroutines and joins both errors.
// A write error does not establish whether an external effect happened.
func WriteAndRelease(ctx context.Context, write, release func(context.Context) error) error {
	if write == nil || release == nil {
		return ErrMissingOperation
	}
	writeErr := write(ctx)
	// Only resource release is detached; its own timeout bounds the cleanup.
	cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), time.Second)
	defer cancel()
	return errors.Join(writeErr, release(cleanupCtx))
}
Read the example and tests
package cleanup

import (
	"context"
	"errors"
	"testing"
)

// traceKey isolates the request-scoped metadata used by this contract test.
type traceKey struct{}

// errRelease identifies the cleanup failure expected to survive error joining.
var errRelease = errors.New("release failed")

// TestCanceledCallerStillReleases proves propagation, bounded detachment and final cancellation.
func TestCanceledCallerStillReleases(t *testing.T) {
	parent := context.WithValue(t.Context(), traceKey{}, "demo")
	ctx, cancel := context.WithCancel(parent)
	cancel()
	var retained context.Context
	write := func(received context.Context) error {
		if !errors.Is(received.Err(), context.Canceled) {
			t.Fatal("write did not receive caller cancellation")
		}
		return received.Err()
	}
	release := func(received context.Context) error {
		if received.Err() != nil {
			t.Fatal("release inherited caller cancellation")
		}
		if _, ok := received.Deadline(); !ok {
			t.Fatal("release has no deadline")
		}
		if received.Value(traceKey{}) != "demo" {
			t.Fatal("request metadata was lost")
		}
		retained = received
		return errRelease
	}
	err := WriteAndRelease(ctx, write, release)
	if !errors.Is(err, context.Canceled) || !errors.Is(err, errRelease) {
		t.Fatalf("missing write or release identity: %v", err)
	}
	if retained == nil || !errors.Is(retained.Err(), context.Canceled) {
		t.Fatal("cleanup cancel function was not called before return")
	}
}

Concurrency with explicit ownership

A goroutine is part of an operation’s lifecycle. Its capacity bound, completion and error handling should be clear from the contract.

GO-CON-001 Bound and join goroutines

Every goroutine has a named owner, completion condition, cancellation or shutdown path and error disposition. Concurrency growth has a documented capacity bound, admission rule or backpressure mechanism. Fire-and-forget is prohibited in authority, persistence and security paths.

Rationale. A function starting background work documents how it stops. A per-call bound is not a service-wide bound: the higher-level owner controls admission of new calls.

Review criterion. Identify the owner, capacity bound, cancellation and completion wait for every goroutine. Test one participant failing and the others stopping; returning must not hide unfinished work.

GO-CON-002 Own channels and shared state

Only the component owning the producers’ lifecycle closes a channel; a channel need not be closed merely for cleanup. Shared state is synchronized or confined. Locks and types containing synchronization primitives are not copied after first use.

Rationale. Do not hold a lock across a callback or unbounded I/O without an explicit invariant and deadlock analysis. A result channel needs no close when its consumer knows the exact result count and waits for all producers.

Review criterion. Inspect closure ownership, shared-state access and lock copying. The race-detector lane must actually execute concurrent paths; a green run proves only the paths exercised.

GO-CON-003 Coordinate tests with signals

Concurrent tests use signals, barriers, channels or injected schedulers instead of timing guesses. time.Sleep is not a correctness synchronization primitive.

Rationale. Cover cancellation, duplicate work, interruption, partial failure and shutdown wherever those states are possible. A test timeout can guard against a hang; signals establish the expected order.

Review criterion. Identify the signal making each wait deterministic. Deliberately remove cancellation or completion waiting: the test must detect a broken contract rather than happen to run fast enough.

Two tasks: cancel and join

RunPair starts exactly two goroutines per call, cancels the sibling after a failure and collects both results. The test’s started channel establishes order without sleep. This is not a service-wide limit or a deduplication mechanism.

// Package parallel illustrates per-call concurrency bounds and joined cancellation.
// It provides no service-wide admission, deduplication or persistence guarantee.
package parallel

import (
	"context"
	"errors"
)

// ErrMissingTask rejects an incomplete pair before either task starts.
var ErrMissingTask = errors.New("two tasks are required")

// Task performs one operation and returns its failures; it must honor cancellation.
// A Task shared by callers must synchronize any mutable state it captures.
type Task func(context.Context) error

// RunPair owns exactly two goroutines per valid call and waits for both results.
// The caller supplies a non-nil context and controls admission across calls.
// The first failure cancels the sibling; both failures remain discoverable with
// errors.Is or errors.As. Error text order is not a contract. Cancellation is
// cooperative: a task ignoring its context can prevent this call from returning.
func RunPair(ctx context.Context, first, second Task) error {
	if first == nil || second == nil {
		return ErrMissingTask
	}
	ctx, cancel := context.WithCancel(ctx)
	defer cancel()
	outcomes := make(chan error, 2)
	for _, task := range []Task{first, second} {
		go func() { outcomes <- task(ctx) }()
	}
	var result error
	for range 2 {
		if err := <-outcomes; err != nil {
			cancel()
			result = errors.Join(result, err)
		}
	}
	// The exact receive count joins both producers; cleanup needs no channel close.
	return result
}
Read the example and tests
package parallel

import (
	"context"
	"errors"
	"testing"
	"time"
)

// errTask identifies the initiating failure without relying on message text.
var errTask = errors.New("task failed")

// errStopped proves the canceled sibling completed before RunPair returned.
var errStopped = errors.New("sibling stopped")

// TestFailureCancelsAndJoins uses a start barrier and checks both result identities.
func TestFailureCancelsAndJoins(t *testing.T) {
	// The timeout guards a broken implementation; the channel determines ordering.
	ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
	defer cancel()
	started := make(chan struct{})
	first := func(ctx context.Context) error {
		close(started)
		<-ctx.Done()
		return errors.Join(ctx.Err(), errStopped)
	}
	second := func(context.Context) error {
		<-started
		return errTask
	}
	err := RunPair(ctx, first, second)
	for _, expected := range []error{errTask, errStopped, context.Canceled} {
		if !errors.Is(err, expected) {
			t.Fatalf("missing error identity %v: %v", expected, err)
		}
	}
}

// TestCallerCancellationJoinsBoth proves both tasks observe a canceled caller.
func TestCallerCancellationJoinsBoth(t *testing.T) {
	ctx, cancel := context.WithCancel(t.Context())
	cancel()
	first := func(ctx context.Context) error {
		if !errors.Is(ctx.Err(), context.Canceled) {
			return nil
		}
		return errors.Join(ctx.Err(), errStopped)
	}
	second := func(ctx context.Context) error {
		if !errors.Is(ctx.Err(), context.Canceled) {
			return nil
		}
		return errors.Join(ctx.Err(), errTask)
	}
	err := RunPair(ctx, first, second)
	if !errors.Is(err, context.Canceled) || !errors.Is(err, errStopped) || !errors.Is(err, errTask) {
		t.Fatalf("caller cancellation lost a result: %v", err)
	}
}

// TestSuccessAndInvalidAdmission covers normal completion and validation before effects.
func TestSuccessAndInvalidAdmission(t *testing.T) {
	outcomes := make(chan struct{}, 2)
	task := func(context.Context) error {
		outcomes <- struct{}{}
		return nil
	}
	if err := RunPair(t.Context(), task, task); err != nil {
		t.Fatal(err)
	}
	if len(outcomes) != 2 {
		t.Fatal("success returned before both tasks completed")
	}
	if err := RunPair(t.Context(), task, nil); !errors.Is(err, ErrMissingTask) {
		t.Fatalf("invalid admission: %v", err)
	}
	if len(outcomes) != 2 {
		t.Fatal("invalid admission started a task")
	}
}

Configuration and secret sources

Configuration determines a selected operation’s behavior before its side effects. The public diagnostic representation must remain safe.

GO-CFG-001 Validate configuration before work

Decode configuration into a typed structure and validate it completely at startup for the selected operation, before network, process or durable work. Reject unknown and duplicate keys, malformed values, conflicting options and template placeholders. Read environment variables through one explicit parser with an allowlist of names rather than scattered os.Getenv calls.

Rationale. Help, version and operations without production dependencies do not require their credentials. Secret-store bootstrap permits only an explicitly declared, bounded authenticated lookup after bootstrap configuration validation; validate returned secrets before constructing operational clients. The package owns defaults and exposes them through its configuration type; the application supplies runtime values and necessary overrides. Defaults hide no application-specific endpoints, credentials or product policy.

Review criterion. Tests reject unknown and duplicate keys, malformed values, conflicts and placeholders. Verify the selected operation’s configuration, default ownership and a way to print effective settings without secrets.

GO-CFG-002 Load only the secrets an operation needs

Secrets come only from the runtime environment, a private file satisfying GO-FS-001, a dedicated secret store or an explicitly selected protected stdin/file descriptor. Tracked files, command-line arguments and defaults are prohibited. Startup validates required presence and format without printing, logging or embedding the value in an error.

Rationale. Only the operation needing a secret loads it. A stdin/descriptor contract defines ownership, bounded framing and size, cancellation, descriptor lifetime and protection from terminal echo, unrelated consumers and diagnostics. Never silently fall back to an interactive prompt or treat arbitrary input as a secret.

Review criterion. Use fictional data to test missing and malformed secrets and redaction. Help and version work without production secrets; the selected source is not replaced by an implicit fallback.

A strict parser without secrets

This educational parser owns only two DEMO_ names and validates duplicates, unknown keys and bounds. Other namespaces are ignored by an explicit contract. It loads no credentials and does not replace full application bootstrap.

// Package settings parses a small, non-secret DEMO_ environment namespace.
// It does not load credentials or define application endpoints or product policy.
package settings

import (
	"errors"
	"strconv"
	"strings"
	"time"
)

// ErrInvalid identifies invalid input without including the supplied value.
var ErrInvalid = errors.New("invalid demo limits")

// Limits contains package-owned budgets; its zero value is invalid.
type Limits struct {
	// Timeout bounds an operation to at most thirty seconds.
	Timeout time.Duration
	// MaxBytes bounds a payload to at most 65536 bytes.
	MaxBytes int
}

// Defaults returns usable, non-secret package defaults without external effects.
func Defaults() Limits {
	return Limits{Timeout: 2 * time.Second, MaxBytes: 1024}
}

// Parse validates an already captured environment snapshot with at most 128 entries.
// Only DEMO_TIMEOUT and DEMO_MAX_BYTES belong to this parser; other namespaces
// are ignored. Owned entries are at most 256 bytes, unique and never placeholders.
// The returned value contains no credentials and is safe for diagnostics.
func Parse(entries []string) (Limits, error) {
	if len(entries) > 128 {
		return Limits{}, ErrInvalid
	}
	limits := Defaults()
	seen := make(map[string]bool, 2)
	for _, entry := range entries {
		if !strings.HasPrefix(entry, "DEMO_") {
			continue
		}
		if len(entry) > 256 {
			return Limits{}, ErrInvalid
		}
		name, value, ok := strings.Cut(entry, "=")
		if !ok || seen[name] {
			return Limits{}, ErrInvalid
		}
		seen[name] = true
		switch name {
		case "DEMO_TIMEOUT":
			duration, err := time.ParseDuration(value)
			if err != nil || duration <= 0 || duration > 30*time.Second {
				return Limits{}, ErrInvalid
			}
			limits.Timeout = duration
		case "DEMO_MAX_BYTES":
			count, err := strconv.Atoi(value)
			if err != nil || count < 1 || count > 65536 {
				return Limits{}, ErrInvalid
			}
			limits.MaxBytes = count
		default:
			return Limits{}, ErrInvalid
		}
	}
	return limits, nil
}
Read the example and tests
package settings

import (
	"errors"
	"strings"
	"testing"
	"time"
)

// TestDefaultsAndOverrides proves namespace isolation and typed package defaults.
func TestDefaultsAndOverrides(t *testing.T) {
	defaults, err := Parse(nil)
	if err != nil || defaults != Defaults() {
		t.Fatalf("defaults: %v, %v", defaults, err)
	}
	limits, err := Parse([]string{"PATH=/example", "DEMO_TIMEOUT=3s", "DEMO_MAX_BYTES=64"})
	if err != nil || limits.Timeout != 3*time.Second || limits.MaxBytes != 64 {
		t.Fatalf("overrides: %v, %v", limits, err)
	}
}

// TestRejectsAmbiguityAndBounds protects the entire owned environment namespace.
func TestRejectsAmbiguityAndBounds(t *testing.T) {
	cases := [][]string{
		{"DEMO_UNKNOWN=1"}, {"DEMO_TIMEOUT"}, {"DEMO_TIMEOUT="},
		{"DEMO_TIMEOUT=2s", "DEMO_TIMEOUT=3s"}, {"DEMO_TIMEOUT=CHANGE_ME"},
		{"DEMO_TIMEOUT=0s"}, {"DEMO_TIMEOUT=31s"}, {"DEMO_MAX_BYTES=0"},
		{"DEMO_MAX_BYTES=65537"}, {"DEMO_MAX_BYTES=not-a-number"},
		{"DEMO_TIMEOUT=" + strings.Repeat("x", 256)}, make([]string, 129),
	}
	for _, entries := range cases {
		limits, err := Parse(entries)
		if !errors.Is(err, ErrInvalid) || limits != (Limits{}) {
			t.Fatalf("invalid configuration was accepted: %v, %v", limits, err)
		}
	}
}

Processes: exact commands and output bounds

An external command is a separate trust boundary. Executable, arguments, environment, cancellation and output must be explicit.

GO-SEC-003 Execute without shell interpolation

Launch a known executable with an explicit argument vector, normally through exec.CommandContext. Do not build a shell command from input, invoke sh -c for convenience or hide interpolation in a wrapper. Bound captured output, deliberately set the required environment and propagate cancellation.

Rationale. A separate argument remains data for the known program. An argument vector alone does not prohibit dangerous options of a particular executable: review its own contract too. An ordinary nonzero exit status is a typed result under GO-ERR-005 rather than uncontrolled infrastructure error text.

Review criterion. Verify the exact executable and argument vector, literal special characters, cancellation and stdout/stderr bounds. Errors contain no raw command line or private input. This conditional profile applies to code actually launching processes.

A known command with bounded capture

This Linux example runs deployment-trusted /usr/bin/printf with fixed format %s. Text is a separate non-secret argument; stdout and stderr retain at most 128 bytes each. Bounds, deadline and WaitDelay are example contracts, not a sandbox or service-wide admission.

// Package process illustrates bounded execution of a trusted Linux printf binary.
// It accepts non-secret text, not executable names, shell programs or credentials.
package process

import (
	"context"
	"errors"
	"os/exec"
	"time"
)

// ErrInput rejects oversized input before process creation.
var ErrInput = errors.New("diagnostic text exceeds input limit")

// ErrExecution reports an infrastructure failure without exposing command text.
var ErrExecution = errors.New("diagnostic process could not run")

// ErrOutput rejects truncated stdout or stderr rather than presenting partial success.
var ErrOutput = errors.New("diagnostic output exceeds capture limit")

// Status distinguishes completed process outcomes from infrastructure failures.
type Status string

const (
	// Succeeded identifies a normal zero exit status.
	Succeeded Status = "succeeded"
	// Exited identifies a normal nonzero exit status.
	Exited Status = "exited"
)

// Result contains the completed outcome, not a verified authority claim.
type Result struct {
	// Status is set only after completion with a bounded output capture.
	Status Status
	// ExitCode is the actual exit status, including a normal nonzero status.
	ExitCode int
	// Output contains only the caller's non-secret diagnostic text.
	Output string
}

// capture drains a pipe while retaining no more than its fixed 128-byte buffer.
type capture struct {
	// data holds the bounded prefix without input-sized allocation.
	data [128]byte
	// used is the number of retained bytes.
	used int
	// truncated records any bytes omitted from the retained prefix.
	truncated bool
}

// Write consumes every byte so a full capture cannot block the child's pipe.
func (c *capture) Write(p []byte) (int, error) {
	stored := copy(c.data[c.used:], p)
	c.used += stored
	c.truncated = c.truncated || stored < len(p)
	return len(p), nil
}

// Print runs the deployment-trusted /usr/bin/printf with fixed format and argv.
// It owns the child, inherits no ambient environment, propagates the caller's
// non-nil context and uses its own two-second deadline and one-second pipe wait.
// Input is at most 256 bytes; each stream retains at most 128 bytes. Truncation
// returns ErrOutput with no partial Result. This Linux example verifies neither
// executable inode identity nor a sandbox or service-wide admission policy.
func Print(ctx context.Context, text string) (Result, error) {
	if len(text) > 256 {
		return Result{}, ErrInput
	}
	ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
	defer cancel()
	command := exec.CommandContext(ctx, "/usr/bin/printf", "%s", text)
	command.Env = []string{"LANG=C", "LC_ALL=C"}
	command.Dir = "/"
	command.WaitDelay = time.Second
	var stdout, stderr capture
	command.Stdout, command.Stderr = &stdout, &stderr
	err := command.Run()
	if ctx.Err() != nil {
		return Result{}, ctx.Err()
	}
	if stdout.truncated || stderr.truncated {
		return Result{}, ErrOutput
	}
	status, exitCode := Succeeded, 0
	if err != nil {
		var exited *exec.ExitError
		if !errors.As(err, &exited) || exited.ExitCode() < 0 {
			return Result{}, ErrExecution
		}
		status, exitCode = Exited, exited.ExitCode()
	}
	return Result{Status: status, ExitCode: exitCode, Output: string(stdout.data[:stdout.used])}, nil
}
Read the example and tests
package process

import (
	"context"
	"errors"
	"strings"
	"testing"
)

// TestLiteralArgument proves metacharacters and format verbs remain literal data.
func TestLiteralArgument(t *testing.T) {
	text := "$(printf demo); %s --help"
	result, err := Print(t.Context(), text)
	if err != nil || result.Status != Succeeded || result.ExitCode != 0 || result.Output != text {
		t.Fatalf("literal argument contract failed: %v, %v", result, err)
	}
}

// TestInputOutputAndCancellation proves bounds and interruption without a shell.
func TestInputOutputAndCancellation(t *testing.T) {
	for _, tc := range []struct {
		size int
		want error
	}{{129, ErrOutput}, {257, ErrInput}} {
		result, err := Print(t.Context(), strings.Repeat("x", tc.size))
		if !errors.Is(err, tc.want) || result != (Result{}) {
			t.Fatalf("bound: %v, %v", result, err)
		}
	}
	ctx, cancel := context.WithCancel(t.Context())
	cancel()
	result, err := Print(ctx, "demo")
	if !errors.Is(err, context.Canceled) || result != (Result{}) {
		t.Fatalf("cancellation: %v, %v", result, err)
	}
}

// TestCaptureDrainsBothStreams proves bounded retention for either stream's writer.
func TestCaptureDrainsBothStreams(t *testing.T) {
	var output capture
	n, err := output.Write([]byte(strings.Repeat("x", 200)))
	if err != nil || n != 200 || output.used != 128 || !output.truncated {
		t.Fatal("capture did not drain and bound input")
	}
}

Resources: bounds and finalization

Receiving a response does not finish the operation. Its owner bounds reading, releases the resource and accounts for finalization failures.

GO-SEC-006 Close resources and check completion

HTTP clients and servers declare applicable timeouts and request/response body limits. Close response bodies and database rows, check terminal iterator errors and keep TLS verification enabled. Intentionally long-lived streams document a separate deadline and shutdown contract.

Rationale. A byte limit does not replace a deadline. Closing a resource does not prove successful reading or iteration. The detailed HTTP, SSH or database transport profile belongs to its client rather than a universal copy of the same settings.

Review criterion. Test oversized bodies, read failures, Close failures and terminal iteration errors. Real transports need their own timeout, cancellation and TLS tests. This conditional profile applies where such network or iterator resources exist.

Read limits and Close failures

The example takes ownership of a body, reads at most limit+1 bytes and closes it even for an invalid limit. Read or Close failures invalidate returned data. The client owner configures TLS, transport cancellation and network timeouts; this helper does not implement them.

// Package payload illustrates bounded body consumption and consequential close errors.
// The caller owns transport TLS, deadlines and cancellation; a byte bound cannot
// interrupt a blocking Reader by itself. This package provides no HTTP client.
package payload

import (
	"errors"
	"io"
)

// ErrBody rejects a missing body before ownership can be transferred.
var ErrBody = errors.New("body is required")

// ErrLimit rejects unsupported limits before allocation.
var ErrLimit = errors.New("body limit must be between 1 and 4096 bytes")

// ErrSize rejects an oversized body instead of returning a truncated success.
var ErrSize = errors.New("body exceeds limit")

// Read takes ownership of a non-nil body and closes it on every return path.
// It reads at most limit+1 bytes to detect overflow. A read or close error returns
// no usable data; joined underlying causes remain local diagnostic information.
func Read(body io.ReadCloser, limit int) (data []byte, err error) {
	if body == nil {
		return nil, ErrBody
	}
	defer func() {
		err = errors.Join(err, body.Close())
		if err != nil {
			data = nil
		}
	}()
	if limit < 1 || limit > 4096 {
		return nil, ErrLimit
	}
	data, err = io.ReadAll(io.LimitReader(body, int64(limit)+1))
	if err != nil {
		return nil, err
	}
	if len(data) > limit {
		return nil, ErrSize
	}
	return data, nil
}
Read the example and tests
package payload

import (
	"errors"
	"strings"
	"testing"
)

// errClose identifies a finalization failure that must invalidate successful data.
var errClose = errors.New("close failed")

// errRead identifies a read failure that must survive a simultaneous close failure.
var errRead = errors.New("read failed")

// testBody records finalization and can inject independent read and close failures.
type testBody struct {
	// reader supplies the deterministic payload.
	reader *strings.Reader
	// readErr fails the read before returning any payload.
	readErr error
	// closeErr is returned after recording finalization.
	closeErr error
	// closed records whether ownership was released.
	closed bool
}

// Read either injects a read failure or forwards the payload without external I/O.
func (b *testBody) Read(p []byte) (int, error) {
	if b.readErr != nil {
		return 0, b.readErr
	}
	return b.reader.Read(p)
}

// Close records release before returning its injected failure.
func (b *testBody) Close() error {
	b.closed = true
	return b.closeErr
}

// TestBoundsAndFinalization covers success, oversized data and both failure causes.
func TestBoundsAndFinalization(t *testing.T) {
	for _, tc := range []struct {
		limit    int
		readErr  error
		closeErr error
		want     error
	}{{4, nil, nil, nil}, {3, nil, nil, ErrSize}, {0, nil, nil, ErrLimit},
		{4097, nil, nil, ErrLimit}, {4, nil, errClose, errClose}, {4, errRead, errClose, errRead}} {
		body := &testBody{reader: strings.NewReader("demo"), readErr: tc.readErr, closeErr: tc.closeErr}
		data, err := Read(body, tc.limit)
		if !body.closed || !errors.Is(err, tc.want) {
			t.Fatalf("release or result failed: closed=%v, err=%v", body.closed, err)
		}
		if tc.closeErr != nil && !errors.Is(err, tc.closeErr) {
			t.Fatal("close identity was lost")
		}
		if tc.want == nil && string(data) != "demo" {
			t.Fatal("successful bytes were changed")
		}
		if tc.want != nil && data != nil {
			t.Fatal("failure returned usable data")
		}
	}
}

// TestReadBudgetAndMissingBody proves early validation and a strict consumed-byte bound.
func TestReadBudgetAndMissingBody(t *testing.T) {
	if _, err := Read(nil, 4); !errors.Is(err, ErrBody) {
		t.Fatalf("missing body: %v", err)
	}
	reader := strings.NewReader(strings.Repeat("x", 100))
	body := &testBody{reader: reader}
	if _, err := Read(body, 3); !errors.Is(err, ErrSize) || !body.closed || reader.Len() != 96 {
		t.Fatal("reading exceeded limit+1 or failed to close")
	}
}

Structured logging

A log is a distinct data-output boundary. Its format, levels and sensitive-value redaction belong to the contract.

GO-LOG-001 Inject the logger and keep attributes stable

Programs use log/slog with structured key-value attributes and stable names. A reusable package receives a *slog.Logger or handler from its caller and does not write to the global default logger, stdout or stderr itself.

Rationale. Handle an error or return it with context; do not both log and return it at every layer. Log levels have documented meaning, and an event requiring operator action is distinguishable from diagnostic detail.

Review criterion. Inspect caller-injected logging, stable attribute names and event levels. A test with an owned handler proves the destination; review identifies repeated log-and-return.

GO-LOG-002 Redact before log serialization

A secret-bearing type implements slog.LogValuer or an equivalent redacting representation so logging the value cannot reveal the secret. Do not log raw request/response payloads, credentials, tokens or private paths.

Rationale. Pass the typed value to the handler. Converting it to an ordinary string or embedding it into a message beforehand bypasses the redacting representation.

Review criterion. Inspect the actual serialized log: tests assert the absence of a fictional secret and the presence of its stable safe representation. Also inspect grouped attributes and the event structure.

A typed secret in a structured log

The example checks JSON actually written by the injected handler, including a grouped attribute. LogValuer protects the slog path; it cannot protect a string already built from the secret through fmt or concatenation. Only a fictional value is used.

// Package eventlog illustrates caller-owned structured logging and slog redaction.
package eventlog

import (
	"context"
	"errors"
	"log/slog"
)

// ErrLogger rejects missing logging ownership instead of using a global fallback.
var ErrLogger = errors.New("an explicit logger is required")

// Secret is a teaching type whose slog representation never contains its value.
// It must not be converted to a raw string or preformatted into a message.
// This type demonstrates the slog boundary, not a general-purpose secret store.
type Secret string

// LogValue redacts the value before a slog handler serializes it, including groups.
func (s Secret) LogValue() slog.Value {
	return slog.StringValue("[redacted]")
}

// Report writes one informational completion diagnostic to the supplied logger.
// Info means ordinary completion; it is not an actionable operator alarm or proof
// of log delivery. Error handling and operation execution belong to the caller.
func Report(ctx context.Context, logger *slog.Logger, credential Secret) error {
	if logger == nil {
		return ErrLogger
	}
	logger.InfoContext(ctx, "probe completed",
		slog.String("event", "probe.completed"),
		slog.Group("auth", slog.Any("credential", credential)),
	)
	return nil
}
Read the example and tests
package eventlog

import (
	"bytes"
	"encoding/json"
	"errors"
	"log/slog"
	"strings"
	"testing"
)

// TestOwnedStructuredLogRedacts proves actual JSON output rather than type shape.
func TestOwnedStructuredLogRedacts(t *testing.T) {
	const fictional = "fictional-secret-for-this-test"
	var output bytes.Buffer
	logger := slog.New(slog.NewJSONHandler(&output, nil))
	if err := Report(t.Context(), logger, Secret(fictional)); err != nil {
		t.Fatal(err)
	}
	if strings.Contains(output.String(), fictional) {
		t.Fatal("a secret reached serialized output")
	}
	var event struct {
		Level string `json:"level"`
		Event string `json:"event"`
		Auth  struct {
			Credential string `json:"credential"`
		} `json:"auth"`
	}
	if err := json.Unmarshal(output.Bytes(), &event); err != nil {
		t.Fatal("the caller's handler received no valid event")
	}
	if event.Level != "INFO" || event.Event != "probe.completed" || event.Auth.Credential != "[redacted]" {
		t.Fatal("stable structured fields were lost")
	}
	if err := Report(t.Context(), nil, Secret(fictional)); !errors.Is(err, ErrLogger) {
		t.Fatalf("missing logger was accepted: %v", err)
	}
}

Network clients and servers

The profile depends on protocol and operation. Transport, retries, admission and shutdown need explicit owners.

GO-NET-001 Define the complete outbound client contract

Use an explicit client per destination with connection and total-operation deadlines, cancellation, bounded response bytes and an endpoint allowlist. HTTP adds a TLS-handshake deadline when TLS is used, an explicit redirect policy and body limits. SSH and databases define their own handshake, authentication, framing and transport-security policies; do not mechanically copy HTTP controls to other protocols.

Rationale. Retries apply only to idempotent operations or operations with an idempotency key: bounded attempts, exponential backoff and jitter within a retry budget, honoring server rate-limit signals. Cut off a persistently failing dependency for a bounded interval. Coalesce identical coalescible reads for a missing value using single-flight; include authorization scope and every result-affecting input in the key, preserving caller cancellation and bounded waiting.

Review criterion. Test destination policy, redirects, TLS, deadlines, cancellation and response limits. The contract and tests define coalescing applicability: writes, streams, independently authenticated and observation-sensitive operations are not automatically coalescible. Implement the mechanism locally or admit it under GO-DEP-001. Verify retry budgets and bounded circuit cutoff.

GO-NET-002 Bound input and shut the server down deliberately

An HTTP server sets ReadHeaderTimeout, read/write/idle timeouts, request-body limits through http.MaxBytesReader and header-size limits. Safe methods have no side effects. Mutating routes require authorization, cross-site request protection for browser clients, an explicit CORS policy and idempotency for retried deliveries such as webhooks.

Rationale. Server.Shutdown follows the root context with a bounded drain period. Public error responses expose no internal errors. Setting Server fields alone does not implement lifecycle, authorization or idempotency.

Review criterion. Test body/header limits, safe-method behavior, rejection of unauthorized mutations and browser policy. Lifecycle tests prove bounded drain and shutdown; error responses contain only safe context.

One destination and a bounded response

This example shows a transport profile for a non-secret HTTPS observation: one endpoint per client, deadlines, no redirect following and body consumption through the earlier payload helper. Each call is a separate observation, so coalescing does not apply. Retry, circuit breaking and global admission are not implemented. Tests substitute transport and do not exercise a real TLS handshake.

// Package probe illustrates a transport-only profile for non-secret HTTPS observations.
// Each call needs a fresh observation, so this operation is not coalescible.
// Retry budgets, circuit cutoff and service-wide admission are not implemented here.
package probe

import (
	"context"
	"crypto/tls"
	"errors"
	"net"
	"net/http"
	"net/url"
	"time"

	"example.org/go-public/payload"
)

// ErrEndpoint rejects unsupported endpoint shapes without exposing the supplied URL.
var ErrEndpoint = errors.New("an explicit HTTPS endpoint without credentials or query is required")

// ErrRequest reports a failed request without serializing private transport details.
var ErrRequest = errors.New("probe request failed")

// ErrBody reports unreadable or oversized data without returning partial bytes.
var ErrBody = errors.New("probe body failed validation")

// Result preserves non-success HTTP statuses as typed outcomes, including redirects.
type Result struct {
	// HTTPStatus is the upstream status, not an authenticated authority claim.
	HTTPStatus int
	// Body is caller-owned non-secret observation data, at most 1024 bytes.
	Body []byte
}

// Client owns one immutable configured URL and its HTTP transport.
// The configuration owner approves the destination; this is not an SSRF filter.
type Client struct {
	// endpoint is the exact per-client allowlisted URL, never a per-call argument.
	endpoint string
	// http owns connection pooling, deadlines and the no-follow redirect policy.
	http *http.Client
}

// New validates the operator-approved destination before constructing a client.
// It makes no network call, uses no ambient proxy and keeps certificate checking.
// HTTPS port443 is supported; production protocol profiles may differ explicitly.
func New(endpoint string) (*Client, error) {
	if len(endpoint) > 2048 {
		return nil, ErrEndpoint
	}
	u, err := url.Parse(endpoint)
	if err != nil || u.Scheme != "https" || u.Hostname() == "" || u.User != nil ||
		u.RawQuery != "" || u.ForceQuery || u.Fragment != "" || u.Opaque != "" ||
		(u.Port() != "" && u.Port() != "443") {
		return nil, ErrEndpoint
	}
	transport := &http.Transport{
		DialContext:           (&net.Dialer{Timeout: time.Second}).DialContext,
		TLSClientConfig:       &tls.Config{MinVersion: tls.VersionTLS12},
		TLSHandshakeTimeout:   2 * time.Second,
		ResponseHeaderTimeout: 2 * time.Second,
		IdleConnTimeout:       30 * time.Second,
		MaxIdleConnsPerHost:   2,
	}
	client := &http.Client{
		Transport: transport,
		Timeout:   5 * time.Second,
		CheckRedirect: func(*http.Request, []*http.Request) error {
			// Return the bounded redirect response to the caller without following it.
			return http.ErrUseLastResponse
		},
	}
	return &Client{endpoint: u.String(), http: client}, nil
}

// Get makes one observation with the caller's non-nil context and closes its body.
// HTTP non-success remains a Result; transport and body failures return safe errors.
// The zero Client is invalid; construction must go through New.
func (c *Client) Get(ctx context.Context) (Result, error) {
	if c == nil || c.http == nil {
		return Result{}, ErrEndpoint
	}
	request, err := http.NewRequestWithContext(ctx, http.MethodGet, c.endpoint, nil)
	if err != nil {
		return Result{}, ErrRequest
	}
	response, err := c.http.Do(request)
	if err != nil {
		if ctx.Err() != nil {
			return Result{}, ctx.Err()
		}
		return Result{}, ErrRequest
	}
	data, err := payload.Read(response.Body, 1024)
	if err != nil {
		return Result{}, ErrBody
	}
	return Result{HTTPStatus: response.StatusCode, Body: data}, nil
}

// Close releases idle connections after the owning application has joined its calls.
func (c *Client) Close() {
	if c != nil && c.http != nil {
		c.http.CloseIdleConnections()
	}
}
Read the example and tests
package probe

import (
	"context"
	"errors"
	"io"
	"net/http"
	"strings"
	"testing"
)

// roundTrip substitutes deterministic transport without DNS, sockets or credentials.
type roundTrip func(*http.Request) (*http.Response, error)

// RoundTrip forwards the already-built request to the injected contract fixture.
func (f roundTrip) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }

// trackedBody proves ownership release after success and validation failure.
type trackedBody struct {
	// Reader supplies bounded fixture bytes.
	io.Reader
	// closed records whether the consumer released the body.
	closed bool
}

// Close records resource release without an external effect.
func (b *trackedBody) Close() error { b.closed = true; return nil }

// TestRedirectAndBodyLimit proves one destination, deadlines, typed status and close.
func TestRedirectAndBodyLimit(t *testing.T) {
	for _, size := range []int{4, 1025} {
		client, err := New("https://example.invalid/health")
		if err != nil {
			t.Fatal(err)
		}
		defer client.Close()
		body := &trackedBody{Reader: strings.NewReader(strings.Repeat("x", size))}
		calls := 0
		client.http.Transport = roundTrip(func(r *http.Request) (*http.Response, error) {
			calls++
			if r.URL.String() != client.endpoint {
				return nil, errors.New("unexpected target")
			}
			if _, ok := r.Context().Deadline(); !ok {
				return nil, errors.New("missing deadline")
			}
			return &http.Response{
				StatusCode: 302,
				Header:     http.Header{"Location": {"https://other.invalid/"}},
				Body:       body, Request: r,
			}, nil
		})
		result, err := client.Get(t.Context())
		if calls != 1 || !body.closed {
			t.Fatal("redirect followed or body left open")
		}
		if size > 1024 {
			if !errors.Is(err, ErrBody) || result.Body != nil {
				t.Fatal("oversized response became success")
			}
		} else if err != nil || result.HTTPStatus != 302 || len(result.Body) != size {
			t.Fatalf("typed response failed: %v", err)
		}
	}
}

// TestCancellationAndEndpointPolicy proves interruption and fail-closed construction.
func TestCancellationAndEndpointPolicy(t *testing.T) {
	for _, endpoint := range []string{
		"http://example.invalid/",
		"https://user:[email protected]/",
		"https://example.invalid/?key=fake",
		"https://example.invalid:8080/",
	} {
		if _, err := New(endpoint); !errors.Is(err, ErrEndpoint) {
			t.Fatal("endpoint accepted")
		}
	}
	client, err := New("https://example.invalid/health")
	if err != nil {
		t.Fatal(err)
	}
	defer client.Close()
	observedCanceled := false
	client.http.Transport = roundTrip(func(r *http.Request) (*http.Response, error) {
		observedCanceled = errors.Is(r.Context().Err(), context.Canceled)
		return nil, r.Context().Err()
	})
	ctx, cancel := context.WithCancel(t.Context())
	cancel()
	if _, err := client.Get(ctx); !errors.Is(err, context.Canceled) || !observedCanceled {
		t.Fatal("caller cancellation lost")
	}
}

// TestTransportProfile proves the constructor keeps TLS verification and bounded waits.
func TestTransportProfile(t *testing.T) {
	client, err := New("https://example.invalid/health")
	if err != nil {
		t.Fatal(err)
	}
	defer client.Close()
	transport := client.http.Transport.(*http.Transport)
	if transport.Proxy != nil || transport.TLSClientConfig.InsecureSkipVerify || transport.DialContext == nil ||
		transport.TLSHandshakeTimeout <= 0 || transport.ResponseHeaderTimeout <= 0 || client.http.Timeout <= 0 {
		t.Fatal("transport protections missing")
	}
}

// TestTransportFailureIsSafe proves raw adapter details cannot cross this API boundary.
func TestTransportFailureIsSafe(t *testing.T) {
	client, err := New("https://example.invalid/health")
	if err != nil {
		t.Fatal(err)
	}
	defer client.Close()
	client.http.Transport = roundTrip(func(*http.Request) (*http.Response, error) {
		return nil, errors.New("fictional-private-adapter-detail")
	})
	result, err := client.Get(t.Context())
	if !errors.Is(err, ErrRequest) || result.Body != nil || strings.Contains(err.Error(), "fictional-private") {
		t.Fatal("transport details escaped or produced usable data")
	}
}
An HTTP server without mutating routes

The factory sets timeouts and headers; the handler allows only GET/HEAD /health, bounds its body and returns no internal errors. The ErrorLog adapter discards raw traces before serialization and emits only a stable event. This is not full server bootstrap: the listener, root-context Shutdown with bounded drain, and authorization and replay policy for future mutating routes remain application responsibilities.

// Package intake illustrates read-only HTTP input and server configuration.
// The application still owns listener admission and root-context bounded Shutdown.
package intake

import (
	"errors"
	"io"
	"log"
	"log/slog"
	"net/http"
	"time"
)

// ErrConfig rejects missing runtime address or logging ownership.
var ErrConfig = errors.New("address and logger are required")

// serverLog bridges net/http diagnostics without exposing raw traces or private paths.
type serverLog struct {
	// logger belongs to the application and receives only the stable event.
	logger *slog.Logger
}

// Write discards uncontrolled diagnostic text before structured log serialization.
// This operational signal does not promise durable audit delivery.
func (w serverLog) Write(message []byte) (int, error) {
	w.logger.Error("HTTP server diagnostic", slog.String("event", "http.server.diagnostic"))
	return len(message), nil
}

// New configures a server but starts no listener or background work.
// Only GET/HEAD /health exist: mutating methods are rejected, not authorized.
// A production mutating route needs its own authorization, browser and replay policy.
func New(address string, logger *slog.Logger) (*http.Server, error) {
	if address == "" || logger == nil {
		return nil, ErrConfig
	}
	return &http.Server{
		Addr:              address,
		Handler:           http.HandlerFunc(health),
		ErrorLog:          log.New(serverLog{logger: logger}, "", 0),
		ReadHeaderTimeout: 2 * time.Second,
		ReadTimeout:       5 * time.Second,
		WriteTimeout:      5 * time.Second,
		IdleTimeout:       30 * time.Second,
		MaxHeaderBytes:    8192,
	}, nil
}

// health handles a side-effect-free route and bounds consumed request bytes.
// net/http owns request-body closure; this handler does not take that ownership.
func health(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path != "/health" {
		w.WriteHeader(http.StatusNotFound)
		return
	}
	if r.Method != http.MethodGet && r.Method != http.MethodHead {
		w.Header().Set("Allow", "GET, HEAD")
		w.WriteHeader(http.StatusMethodNotAllowed)
		return
	}
	body := http.MaxBytesReader(w, r.Body, 1024)
	if _, err := io.Copy(io.Discard, body); err != nil {
		var oversized *http.MaxBytesError
		if errors.As(err, &oversized) {
			w.WriteHeader(http.StatusRequestEntityTooLarge)
		} else {
			w.WriteHeader(http.StatusBadRequest)
		}
		return
	}
	w.WriteHeader(http.StatusNoContent)
}
Read the example and tests
package intake

import (
	"bytes"
	"io"
	"log/slog"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
)

// TestReadOnlyAndBodyLimit verifies actual statuses through the configured handler.
func TestReadOnlyAndBodyLimit(t *testing.T) {
	server, err := New("127.0.0.1:0", slog.New(slog.NewJSONHandler(io.Discard, nil)))
	if err != nil {
		t.Fatal(err)
	}
	for _, tc := range []struct {
		method string
		size   int
		status int
	}{
		{method: http.MethodGet, size: 0, status: 204},
		{method: http.MethodHead, size: 0, status: 204},
		{method: http.MethodGet, size: 1025, status: 413},
		{method: http.MethodPost, size: 0, status: 405},
	} {
		request := httptest.NewRequest(tc.method, "/health", strings.NewReader(strings.Repeat("x", tc.size)))
		response := httptest.NewRecorder()
		server.Handler.ServeHTTP(response, request)
		if response.Code != tc.status || response.Body.Len() != 0 {
			t.Fatal("unsafe status or error detail")
		}
	}
	if server.ReadHeaderTimeout <= 0 || server.ReadTimeout <= 0 || server.WriteTimeout <= 0 ||
		server.IdleTimeout <= 0 || server.MaxHeaderBytes <= 0 {
		t.Fatal("server limits missing")
	}
}

// TestServerDiagnosticRedacts proves raw net/http traces cannot reach the log output.
func TestServerDiagnosticRedacts(t *testing.T) {
	var output bytes.Buffer
	server, err := New("127.0.0.1:0", slog.New(slog.NewJSONHandler(&output, nil)))
	if err != nil {
		t.Fatal(err)
	}
	server.ErrorLog.Print("fictional-private-path/trace fictional-private-token")
	if strings.Contains(output.String(), "fictional-private") ||
		!strings.Contains(output.String(), `"event":"http.server.diagnostic"`) {
		t.Fatal("raw server diagnostics escaped or the safe event was lost")
	}
}

Determinism and semantic identity

Equal semantic input should produce equal output. Incidental environment properties must not silently change identity or persisted bytes.

GO-DET-001 Make ambient influences explicit

When time, randomness, environment, cwd, host identity, network or filesystem order affects canonical identity, persisted bytes, verdicts or reproducible artifacts, supply it explicitly or isolate it in an adapter. These inputs remain valid at configuration, logging, metrics and runtime-adapter boundaries without a determinism claim.

Rationale. Inject clocks and randomness for tested or canonical outcomes. Machine instants, deadlines and lease expiries use UTC in a documented RFC3339 precision or Unix time with units in field names. In-process durations and deadlines use the monotonic clock; compare time.Time with Equal/Before/After rather than ==.

Review criterion. A local calendar contract carries an explicit IANA zone with embedded time/tzdata; derive day boundaries through calendar arithmetic rather than adding fixed seconds. Cover both DST transitions. A timestamp or random staging name enters semantic identity only when the specification names it.

GO-DET-002 Stabilize observable order

Sort map, set and filesystem projections before serialization, hashing, comparison or ordered public output whenever order is observable. Define tie-breakers.

Rationale. Map iteration is valid when order is unobservable or the chosen canonical encoder guarantees the required order. A contract may reject an ambiguous duplicate instead of selecting an arbitrary winner.

Review criterion. Two input orders with the same semantic content produce identical bytes. Tests define equal-key behavior; input collections are not mutated without declared ownership.

GO-DET-003 Give identity its own format

Canonical IDs and digests have a versioned domain, one canonical renderer and byte-level fixtures. Hash intended semantic bytes, not Go struct layout or incidental staging metadata.

Rationale. A domain version distinguishes different meanings of the same bytes. Ordering, delimiters and a final LF belong to the particular format rather than incidental fmt behavior.

Review criterion. Compare exact bytes with a literal fixture and the digest with its expected value. Reruns over equal semantic input keep the same result.

Equal data, equal bytes

The example defines its own ASCII label/count format, copies input and sorts unique labels. The versioned domain enters the digest; no clock, staging metadata or randomness is used. This is neither general canonical JSON nor a calendar-arithmetic example.

// Package canonical renders a small versioned ASCII label-count projection.
// It owns no clock, environment, filesystem or authority verification.
package canonical

import (
	"crypto/sha256"
	"encoding/hex"
	"errors"
	"slices"
	"strconv"
	"strings"
)

// ErrInput rejects an unsupported projection without including its contents.
var ErrInput = errors.New("invalid label projection")

// domain versions the exact semantic byte format, including its final LF.
const domain = "solution200.example.labels/v1\n"

// Label is an ASCII lower-case name of one to thirty-two letters.
type Label string

// Count is a nonnegative tally, bounded to one million by Render.
type Count uint32

// Entry binds one unique label to its semantic tally.
type Entry struct {
	// Label determines bytewise canonical ordering and must be unique.
	Label Label
	// Count is serialized as unsigned base-ten without leading zeroes.
	Count Count
}

// Render validates at most 64 entries, copies them and sorts by their unique label.
// It returns domain then label=count LF lines, including the final newline.
// Empty input is valid; unsupported text and duplicate labels fail closed.
func Render(entries []Entry) ([]byte, error) {
	if len(entries) > 64 {
		return nil, ErrInput
	}
	for _, entry := range entries {
		if len(entry.Label) < 1 || len(entry.Label) > 32 || entry.Count > 1000000 {
			return nil, ErrInput
		}
		for _, letter := range []byte(entry.Label) {
			if letter < 'a' || letter > 'z' {
				return nil, ErrInput
			}
		}
	}
	ordered := slices.Clone(entries)
	slices.SortFunc(ordered, func(left, right Entry) int {
		return strings.Compare(string(left.Label), string(right.Label))
	})
	output := make([]byte, 0, len(domain)+len(ordered)*48)
	output = append(output, domain...)
	for index, entry := range ordered {
		if index > 0 && entry.Label == ordered[index-1].Label {
			return nil, ErrInput
		}
		output = append(output, entry.Label...)
		output = append(output, '=')
		output = strconv.AppendUint(output, uint64(entry.Count), 10)
		output = append(output, '\n')
	}
	return output, nil
}

// Digest hashes only Render's versioned semantic bytes, never staging metadata.
func Digest(entries []Entry) (string, error) {
	data, err := Render(entries)
	if err != nil {
		return "", err
	}
	digest := sha256.Sum256(data)
	return "labels-v1:" + hex.EncodeToString(digest[:]), nil
}
Read the example and tests
package canonical

import (
	"bytes"
	"errors"
	"slices"
	"testing"
)

// TestCanonicalBytesAndIdentity proves ordering, a literal digest and input ownership.
func TestCanonicalBytesAndIdentity(t *testing.T) {
	input := []Entry{{Label: "beta", Count: 2}, {Label: "alpha", Count: 1}}
	original := slices.Clone(input)
	const fixture = "solution200.example.labels/v1\nalpha=1\nbeta=2\n"
	data, err := Render(input)
	if err != nil || !bytes.Equal(data, []byte(fixture)) || !slices.Equal(input, original) {
		t.Fatal("canonical bytes or caller ownership changed")
	}
	want := "labels-v1:e2e0b4ad5bc08f059496957662236fe02f79efe93e106db27feb1c6fa12f2f77"
	for _, entries := range [][]Entry{input, {input[1], input[0]}} {
		identity, err := Digest(entries)
		if err != nil || identity != want {
			t.Fatal("semantic identity changed with input order")
		}
	}
}

// TestRejectsAmbiguousProjection proves bounds and duplicate rejection before success.
func TestRejectsAmbiguousProjection(t *testing.T) {
	oversized := make([]Entry, 65)
	for index := range oversized {
		label := "a" + string(rune('a'+index/26)) + string(rune('a'+index%26))
		oversized[index] = Entry{Label: Label(label), Count: 1}
	}
	for _, entries := range [][]Entry{
		{{Label: "same", Count: 1}, {Label: "same", Count: 2}},
		{{Label: "bad=name", Count: 1}}, {{Label: "", Count: 0}},
		{{Label: "alpha", Count: 1000001}}, oversized,
	} {
		data, err := Render(entries)
		if !errors.Is(err, ErrInput) || data != nil {
			t.Fatal("invalid projection produced usable bytes")
		}
	}
}

// TestEmptyAndDecimalFormat pins allowed emptiness and nontrivial decimal counts.
func TestEmptyAndDecimalFormat(t *testing.T) {
	data, err := Render(nil)
	if err != nil || string(data) != "solution200.example.labels/v1\n" {
		t.Fatal("empty projection contract changed")
	}
	data, err = Render([]Entry{{Label: "gamma", Count: 1000000}})
	if err != nil || string(data) != "solution200.example.labels/v1\ngamma=1000000\n" {
		t.Fatal("decimal count format changed")
	}
}

Strict external-data decoding

Successful JSON parsing does not establish a valid contract. Bounds, schema, ambiguity and states are checked separately.

GO-DATA-001 Bound and validate JSON before unbounded allocation

At untrusted, authority-bearing, canonical or durable JSON boundaries, applicable byte, depth and cardinality limits precede unbounded allocation. Require valid UTF-8, exactly one top-level value, duplicate-key rejection where ambiguity changes meaning, unknown-field rejection for typed authority contracts and explicit missing/empty/null semantics.

Rationale. Unmarshaling into a struct alone rejects neither unknown fields nor duplicate keys. DisallowUnknownFields alone rejects neither trailing values nor duplicates. Evolvable ingestion may deliberately tolerate unknown fields only under a tested compatibility contract; looser inspection uses a separately typed non-authoritative path.

Review criterion. Negative fixtures cover oversized input, nesting and cardinality, invalid UTF-8, duplicates, unknown keys, a second value and missing/empty/null. A successful Unmarshal alone is not the check.

GO-DATA-002 Version schema and canonical bytes

Reject unknown schema versions fail-closed. Durable and external values declare wire names and a compatibility policy. Canonical output defines ordering, escaping, normalization and trailing-newline behavior.

Rationale. The same content may have many valid JSON spellings; its contract defines canonical bytes and input normalization. Changing that rule changes the format.

Review criterion. Byte-round-trip fixtures keep canonical bytes unchanged after decoding/encoding, normalize accepted noncanonical input deliberately and reject unknown schema versions.

GO-DATA-003 Keep non-success states explicit

Unknown, planned, unavailable, unverified, rejected and the zero value must not silently become success or authority. Represent materially different states with named types or enums rather than loosely related booleans.

Rationale. A state transition needs its own condition. A missing field, empty token or default is not positive evidence.

Review criterion. Exercise every non-success token and the zero value. Reject unknown tokens; preserve the meaning of planned or unverified through a round trip.

A strict schema without automatic authority

The example accepts at most 256 UTF-8 bytes and one flat version/state/name object with scalar values. Duplicates, unknown fields, nested values, null and unknown versions are rejected. It returns Evidence or Plan, never execution permission; transport acquisition, durable publication and general JSON parsing are not implemented here.

// Package envelope illustrates a bounded, flat, non-authoritative JSON contract.
// It can produce evidence and plans, never permission to execute or verified authority.
package envelope

import (
	"bytes"
	"encoding/json"
	"errors"
	"io"
	"unicode/utf8"
)

// ErrInput rejects malformed, ambiguous or unsupported data without exposing it.
var ErrInput = errors.New("invalid evidence envelope")

// ErrNotPlanned rejects a transition that the decoded evidence does not represent.
var ErrNotPlanned = errors.New("evidence is not a valid plan")

// State names a non-success interpretation; its empty zero value is invalid.
type State string

const (
	// Unknown records absence of a conclusion, not a successful check.
	Unknown State = "unknown"
	// Planned describes intended work without permission to execute it.
	Planned State = "planned"
	// Unavailable records that evidence could not be obtained.
	Unavailable State = "unavailable"
	// Unverified records data whose authority has not been established.
	Unverified State = "unverified"
	// Rejected records a negative outcome without promoting it to success.
	Rejected State = "rejected"
)

// known limits the wire vocabulary to declared non-success states.
func (state State) known() bool {
	switch state {
	case Unknown, Planned, Unavailable, Unverified, Rejected:
		return true
	default:
		return false
	}
}

// Evidence is decoded non-authoritative input; even its valid values carry no authority.
// The zero value is invalid and cannot be rendered or converted to a Plan.
type Evidence struct {
	// state preserves the explicitly decoded non-success interpretation.
	state State
	// name is a one-to-twenty-four-character ASCII lower-case/digit identifier.
	name string
}

// Plan represents intended work only; it grants no executable capability.
type Plan struct {
	// name identifies the intended item, not an authority token.
	name string
}

// Name returns the plan label; an empty zero Plan is not executable either.
func (plan Plan) Name() string { return plan.name }

// State returns the evidence interpretation without changing its trust level.
func (evidence Evidence) State() State { return evidence.state }

// validName rejects escaping and normalization ambiguity within this ASCII schema.
func validName(name string) bool {
	if len(name) < 1 || len(name) > 24 {
		return false
	}
	for _, letter := range []byte(name) {
		if (letter < 'a' || letter > 'z') && (letter < '0' || letter > '9') {
			return false
		}
	}
	return true
}

// Decode accepts at most 256 UTF-8 bytes and exactly one flat three-field object.
// Version must be the JSON integer token 1. All fields are required and non-null;
// unknown/duplicate keys, nested values and unknown states fail. Depth is fixed
// by scalar field validation; this is not a generic recursive JSON decoder.
// The caller must also bound acquisition of input before calling this function.
func Decode(input []byte) (Evidence, error) {
	if len(input) > 256 || !utf8.Valid(input) {
		return Evidence{}, ErrInput
	}
	decoder := json.NewDecoder(bytes.NewReader(input))
	decoder.UseNumber()
	opening, err := decoder.Token()
	if err != nil || opening != json.Delim('{') {
		return Evidence{}, ErrInput
	}
	seen := make(map[string]bool, 3)
	var evidence Evidence
	for decoder.More() {
		if len(seen) >= 3 {
			return Evidence{}, ErrInput
		}
		keyToken, err := decoder.Token()
		key, isString := keyToken.(string)
		if err != nil || !isString || seen[key] {
			return Evidence{}, ErrInput
		}
		seen[key] = true
		if key != "version" && key != "state" && key != "name" {
			return Evidence{}, ErrInput
		}
		value, err := decoder.Token()
		if err != nil {
			return Evidence{}, ErrInput
		}
		switch key {
		case "version":
			version, ok := value.(json.Number)
			if !ok || version.String() != "1" {
				return Evidence{}, ErrInput
			}
		case "state":
			text, ok := value.(string)
			evidence.state = State(text)
			if !ok || !evidence.state.known() {
				return Evidence{}, ErrInput
			}
		case "name":
			text, ok := value.(string)
			evidence.name = text
			if !ok || !validName(text) {
				return Evidence{}, ErrInput
			}
		}
	}
	closing, err := decoder.Token()
	if err != nil || closing != json.Delim('}') || len(seen) != 3 {
		return Evidence{}, ErrInput
	}
	if _, err := decoder.Token(); !errors.Is(err, io.EOF) {
		return Evidence{}, ErrInput
	}
	return evidence, nil
}

// Encode renders validated evidence as version/state/name, compact ASCII JSON plus LF.
// Name/state restrictions make escaping unnecessary; input whitespace and key order
// normalize to this one representation. Unknown schemas have no fallback.
func Encode(evidence Evidence) ([]byte, error) {
	if !evidence.state.known() || !validName(evidence.name) {
		return nil, ErrInput
	}
	return []byte(`{"version":1,"state":"` + string(evidence.state) + `","name":"` + evidence.name + `"}` + "\n"), nil
}

// PlanFromEvidence converts only a valid planned interpretation to a distinct Plan.
// It performs no verification of authority and starts no operation.
func PlanFromEvidence(evidence Evidence) (Plan, error) {
	if evidence.state != Planned || !validName(evidence.name) {
		return Plan{}, ErrNotPlanned
	}
	return Plan{name: evidence.name}, nil
}
Read the example and tests
package envelope

import (
	"bytes"
	"errors"
	"strings"
	"testing"
)

// TestCanonicalRoundTrip proves exact wire bytes and normalization without state promotion.
func TestCanonicalRoundTrip(t *testing.T) {
	for _, state := range []State{Unknown, Planned, Unavailable, Unverified, Rejected} {
		fixture := `{"version":1,"state":"` + string(state) + `","name":"demo"}` + "\n"
		evidence, err := Decode([]byte(fixture))
		if err != nil || evidence.State() != state {
			t.Fatal("non-success state was lost")
		}
		encoded, err := Encode(evidence)
		if err != nil || !bytes.Equal(encoded, []byte(fixture)) {
			t.Fatal("canonical byte round trip changed")
		}
	}
	input := []byte(` { "name": "de\u006do", "state": "unverified", "version": 1 } `)
	evidence, err := Decode(input)
	if err != nil {
		t.Fatal(err)
	}
	encoded, err := Encode(evidence)
	if err != nil || string(encoded) != "{\"version\":1,\"state\":\"unverified\",\"name\":\"demo\"}\n" {
		t.Fatal("normalization policy changed")
	}
}

// TestRejectsAmbiguityAndLimits covers the entire flat decoder boundary.
func TestRejectsAmbiguityAndLimits(t *testing.T) {
	cases := []string{
		`{"version":2,"state":"unverified","name":"demo"}`,
		`{"version":1.0,"state":"unverified","name":"demo"}`,
		`{"version":1,"state":"verified","name":"demo"}`,
		`{"version":1,"state":"success","name":"demo"}`,
		`{"version":1,"state":"","name":"demo"}`,
		`{"version":1,"state":null,"name":"demo"}`,
		`{"version":1,"state":"unverified"}`,
		`{"version":1,"state":"unverified","name":""}`,
		`{"version":1,"state":"unverified","name":null}`,
		`{"version":1,"state":"unverified","name":[]}`,
		`{"version":1,"state":{"nested":true},"name":"demo"}`,
		`{"version":1,"state":"planned","state":"unverified","name":"demo"}`,
		`{"version":1,"\u0076ersion":1,"state":"planned","name":"demo"}`,
		`{"version":1,"state":"unverified","extra":0}`,
		`{"version":1,"state":"unverified","name":"demo","extra":0}`,
		`{"version":1,"state":"unverified","name":"demo"} {}`,
		`{"version":1,"state":"unverified","name":"de\ud800"}`,
		strings.Repeat(" ", 257) + `{"version":1,"state":"planned","name":"demo"}`,
		strings.Repeat(" ", 257), string([]byte{0xff}), `null`, `[]`,
	}
	for _, input := range cases {
		evidence, err := Decode([]byte(input))
		if !errors.Is(err, ErrInput) || evidence != (Evidence{}) {
			t.Fatal("ambiguous input produced usable evidence")
		}
	}
}

// TestPlansAreNotAuthority proves zero/non-planned rejection and the explicit typed transition.
func TestPlansAreNotAuthority(t *testing.T) {
	if _, err := Encode(Evidence{}); !errors.Is(err, ErrInput) {
		t.Fatal("zero evidence encoded")
	}
	for _, evidence := range []Evidence{{}, {state: Unverified, name: "demo"}, {state: Rejected, name: "demo"}} {
		if _, err := PlanFromEvidence(evidence); !errors.Is(err, ErrNotPlanned) {
			t.Fatal("a non-plan became a plan")
		}
	}
	evidence, err := Decode([]byte(`{"version":1,"state":"planned","name":"demo"}`))
	if err != nil {
		t.Fatal(err)
	}
	plan, err := PlanFromEvidence(evidence)
	if err != nil || plan.Name() != "demo" {
		t.Fatal("explicit plan transition failed")
	}
}

Evidence, plans and execution authority

Observations and plans support a decision but do not themselves grant authority.

GO-AUTH-001 Earn authority through a distinct boundary

Authority-bearing, evidence-only, inspection and planned values use distinct types or constructors. Plain decoded DTOs, filesystem presence and successful exit status are only evidence inputs; they do not automatically become verified authority.

Rationale. A type helps distinguish trust levels, but calling it Verified is insufficient. The authority owner defines verification and the permitted transition; a generic reader does not invent that policy.

Review criterion. The decoder example returns only Evidence; a planned value can become a separate Plan. It supplies no authority constructor or executable capability. Tests reject success/verified tokens and prevent a zero value from becoming a plan.

Security before execution and serialization

Secrecy, input bounds and cryptographic primitives belong to the contract. A timeout or successful parsing does not replace validation.

GO-SEC-001 Keep secrets out of ordinary outputs

Never commit, log, format into errors or persist secrets, credentials or private payloads in ordinary evidence, examples or durable task state. Examples use fictional sanitized data. Redact before serialization and fail closed on ambiguity.

Rationale. Inspect the actual output path: errors, structured logs, serialized DTOs and evidence. Protecting one handler does not protect earlier conversion of a secret into a string elsewhere.

Review criterion. Negative fixtures with fictional values assert absence from actual output. Failed redaction never falls back to the original payload.

GO-SEC-002 Validate untrusted input before use

Validate untrusted size, cardinality, vocabulary and identity before allocation, lookup or execution. Unsupported, ambiguous and partially verified input fails closed.

Rationale. A timeout bounds time but does not replace byte/count limits or identity checks. Successful syntax parsing is not positive evidence of the required object.

Review criterion. Test oversized and ambiguous input at the exact boundary. Static patterns alone prove neither containment, durability nor authority.

GO-SEC-004 Use reviewed primitives and explicit networking

Use reviewed standard cryptographic primitives and crypto/rand for secrets. math/rand and math/rand/v2 serve non-security uses; reproducible simulation receives an explicit seed. Custom cryptography requires a separately approved design.

Rationale. Network operations declare destination policy, TLS behavior, timeout/cancellation and bounded response handling. Networking is never an implicit fallback. A semantic digest alone proves neither provenance nor authority.

Review criterion. Review randomness sources and primitive choices; tests exercise applicable network bounds. Never replace cryptographic randomness with a reproducible simulation RNG.

Paths, metadata and object identity

A lexically valid name is only the first check. Safe object access needs a stronger platform-specific contract.

GO-SEC-005 Cleaning does not prove containment

filepath.Clean normalizes text but proves neither containment nor object identity. Security-sensitive paths require an explicit root, traversal rejection, symlink policy, object-type validation and pre/post identity checks appropriate to the platform and threat model.

Rationale. Archive extraction also bounds entry count and expanded size, rejects absolute/traversing/link entries outside policy and never trusts a filename alone after resolution.

Review criterion. Exercise traversal, symlinks, object replacement and archive limits where applicable. The example opens no file: it validates only a component and supplied metadata evidence.

GO-FS-001 Check the private object, not just mode bits

Private or authority-bearing filesystem state checks expected regular-file/directory type, owner, mode and link/symlink policy. Typical least-privilege defaults are 0600 files and 0700 directories under an explicit deployment contract.

Rationale. Never automatically follow or repair ambiguous pre-existing paths. Cleanup uses verified stable identity rather than a freshly resolved ambient basename.

Review criterion. Actual filesystem-adapter tests exercise owner/type/mode/links and identity. A clean metadata snapshot proves neither the current path binding nor permission to clean it up.

Names and metadata are evidence only

The example checks one ASCII component and supplied metadata fields under a narrow regular 0600/single-link policy. It opens no path and proves neither containment, snapshot freshness, actual identity nor cleanup permission. Zero device/inode values are explicitly unsupported here.

// Package pathpolicy illustrates lexical and supplied-metadata checks without I/O.
// It proves neither path containment nor a current filesystem object's identity.
package pathpolicy

import (
	"errors"
	"io/fs"
)

// ErrPolicy rejects unsupported names or snapshots without exposing private data.
var ErrPolicy = errors.New("path evidence does not satisfy the example policy")

// Name is one validated ASCII component, not a resolved or authorized path.
// Its empty zero value is invalid; no filesystem operation accepts Name here.
type Name struct {
	// text is bounded and contains no path separator or traversal component.
	text string
}

// ParseName accepts one to 48 ASCII bytes, starting with a lower-case letter or digit.
// Remaining characters may also be dot, underscore or hyphen. It never cleans
// input into a different name: traversal and absolute/drive spellings fail.
func ParseName(input string) (Name, error) {
	if len(input) < 1 || len(input) > 48 {
		return Name{}, ErrPolicy
	}
	for index, letter := range []byte(input) {
		alphaNumeric := (letter >= 'a' && letter <= 'z') || (letter >= '0' && letter <= '9')
		if !alphaNumeric && (index == 0 || (letter != '.' && letter != '_' && letter != '-')) {
			return Name{}, ErrPolicy
		}
	}
	return Name{text: input}, nil
}

// String returns the component only; it is not permission to open or delete it.
func (name Name) String() string { return name.text }

// Snapshot is untrusted metadata evidence supplied by an external adapter.
// Matching this policy does not prove the snapshot is fresh or truthful.
type Snapshot struct {
	// Mode carries Go file type and permission bits from the claimed observation.
	Mode fs.FileMode
	// UID identifies the claimed owner; the expected owner is an explicit input.
	UID uint32
	// Links is the claimed hard-link count; the example allows exactly one.
	Links uint64
	// Device is the claimed device identity; zero is unsupported in this example.
	Device uint64
	// Inode is the claimed object identity; zero is unsupported in this example.
	Inode uint64
}

// CheckSnapshot checks a regular 0600 single-link file under this narrow policy.
// It opens no path, follows no symlink and repairs nothing. A nil error is only
// a statement about supplied fields, never a capability or cleanup authorization.
func CheckSnapshot(snapshot Snapshot, expectedUID uint32) error {
	if snapshot.Mode != fs.FileMode(0o600) || snapshot.UID != expectedUID ||
		snapshot.Links != 1 || snapshot.Device == 0 || snapshot.Inode == 0 {
		return ErrPolicy
	}
	return nil
}
Read the example and tests
package pathpolicy

import (
	"errors"
	"io/fs"
	"strings"
	"testing"
)

// TestRejectsTraversalWithoutNormalization proves lexical rejection, not containment.
func TestRejectsTraversalWithoutNormalization(t *testing.T) {
	for _, input := range []string{"", ".", "..", "../private", "a/../b", "/absolute", `a\b`,
		"c:drive", "name\x00", "Upper", "імя", ".hidden", "_start", "-start", strings.Repeat("a", 49)} {
		name, err := ParseName(input)
		if !errors.Is(err, ErrPolicy) || name != (Name{}) {
			t.Fatal("unsupported name was accepted")
		}
	}
	for _, input := range []string{"a", "draft-1.json", strings.Repeat("a", 48)} {
		name, err := ParseName(input)
		if err != nil || name.String() != input {
			t.Fatal("valid component changed")
		}
	}
}

// TestSnapshotPolicyRejectsMetadata verifies every supplied-evidence constraint.
func TestSnapshotPolicyRejectsMetadata(t *testing.T) {
	valid := Snapshot{Mode: 0o600, UID: 1000, Links: 1, Device: 1, Inode: 42}
	if err := CheckSnapshot(valid, 1000); err != nil {
		t.Fatal(err)
	}
	cases := []Snapshot{valid, valid, valid, valid, valid, valid, valid}
	cases[0].Mode = 0o644
	cases[1].Mode = fs.ModeSymlink | 0o600
	cases[2].Mode = fs.ModeDir | 0o700
	cases[3].UID = 2000
	cases[4].Links = 2
	cases[5].Device = 0
	cases[6].Inode = 0
	for _, snapshot := range cases {
		if !errors.Is(CheckSnapshot(snapshot, 1000), ErrPolicy) {
			t.Fatal("unsupported metadata accepted")
		}
	}
}

File publication and ambiguous outcomes

Atomic visibility, crash durability and published-object verification are distinct properties. An intermediate result does not become confirmed success.

GO-FS-002 Separate visibility, durability and verification

Same-directory temporary publication with validated Close and rename may provide atomic visibility. A crash-durability promise additionally needs file and directory sync as required by the platform and interrupted-write reconciliation.

Rationale. No-replace and post-publication reopen/revalidation are required only when activated by the collision or verification contract. Never report visible-but-unverified output as fully committed.

Review criterion. APIs and tests distinguish prepared, committed, verified and ambiguous results wherever interruption separates them. The callback model below proves only ordering and failure handling; actual platform/filesystem evidence belongs to its adapter.

GO-FS-003 Own lock and multi-file protocols

Locks have stable identity, ownership records and stale-recovery policy. Append-only and ordering claims are explicit. Independent renames in sequence are not an atomic multi-file operation.

Rationale. Use a journal, manifest/commit marker or transactional owner for multiple files, and define idempotent reconciliation after interruption.

Review criterion. Test competing owners, interruption and repeated recovery under the contract. A single-file model proves neither locking nor a multi-file transaction.

GO-FS-004 Account for consequential finalization failures

Sync, close, rename, unlock, rollback and cleanup failures affecting durability or safety change the returned result. Never overwrite unknown existing output, recursively delete unverified paths or turn ambiguous recovery into success.

Rationale. After possible publication, cleanup must not remove another owner’s or already-visible output. Causes may stay within a trusted diagnostic boundary; public error descriptions remain safe.

Review criterion. Inject failures into every phase and cleanup. Assert retained error identities, ordering, no blind retry and no destructive cleanup after ambiguous visibility.

What the model states mean
State Known outcome Safe next step
Not published Publish was not attempted or the adapter reported no destination effect. Cleanup success is not implied. Inspect the failure and staging-cleanup result.
Ambiguous outcome Destination effects are unknown or the adapter response is inconsistent. Inspect/reconcile; no blind retry or Discard.
Visible, unverified Visibility was reported but later durability/check steps did not finish. Keep visible output; inspect the actual object through its adapter.
Steps passed Every injected step returned success. This is not a physical filesystem guarantee. The real adapter and its evidence determine permissible stronger claims.
A publication model with injected steps

Prepared is a trusted-adapter contract, not a filesystem implementation. The model tests Sync/Close/Publish/DirectorySync/Check ordering, failures and bounded cleanup. ChecksPassed means only callback success, not proven crash durability or authority. After possible visibility it calls no Discard or blind retry; callbacks must honor context.

// Package publication models finalization through trusted, injected operations.
// It executes no filesystem calls and proves no crash durability or authority.
package publication

import (
	"context"
	"errors"
	"time"
)

// ErrProtocol identifies missing ownership or an inconsistent adapter response.
var ErrProtocol = errors.New("invalid publication protocol response")

// Visibility is the adapter's claim about the destination after Publish.
// Its zero or any unknown value means visibility cannot be established.
type Visibility string

const (
	// NotVisible guarantees Publish had no destination effect under the adapter contract.
	NotVisible Visibility = "not_visible"
	// Visible claims the destination is visible but does not establish durability.
	Visible Visibility = "visible"
)

// State describes protocol progress, not a verified filesystem capability.
type State string

const (
	// NotPublished means publication was not performed, not that cleanup succeeded.
	NotPublished State = "not_published"
	// Ambiguous means destination effects cannot be safely inferred or retried.
	Ambiguous State = "ambiguous"
	// VisibleUnverified preserves visible output whose later checks did not complete.
	VisibleUnverified State = "visible_unverified"
	// ChecksPassed means every injected step succeeded, not proven physical durability.
	ChecksPassed State = "checks_passed"
)

// Outcome reports only the model's progress. Its zero value is not success.
type Outcome struct {
	// state is set only by Run; it grants no operational authority.
	state State
}

// State returns observed protocol progress without promoting it to authority.
func (outcome Outcome) State() State { return outcome.state }

// Prepared is a fully initialized, already-written resource owned by Run.
// The real adapter must prove stable identity, metadata and collision policy;
// callbacks must cooperate with cancellation. This interface is not that proof.
type Prepared interface {
	// SyncFile completes the selected file-durability step before publication.
	SyncFile(ctx context.Context) error
	// Close releases the prepared stream even after caller cancellation.
	Close(ctx context.Context) error
	// Publish applies the adapter's collision policy and reports possible visibility.
	Publish(ctx context.Context) (Visibility, error)
	// SyncDirectory completes the platform's selected directory-durability step.
	SyncDirectory(ctx context.Context) error
	// CheckPublished performs the explicitly activated post-publication check.
	CheckPublished(ctx context.Context) error
	// Discard removes only the adapter-verified staging object, never the destination.
	Discard(ctx context.Context) error
}

// failure keeps its cause local while providing a fixed safe public message.
type failure struct {
	// step is an internal stable name, never untrusted error text.
	step string
	// cause remains available for local errors.Is/errors.As, not public serialization.
	cause error
}

// Error exposes only the failed protocol step, never raw adapter data or paths.
func (err failure) Error() string { return "publication " + err.step + " failed" }

// Unwrap preserves the local cause inside its diagnostic trust boundary.
func (err failure) Unwrap() error { return err.cause }

// wrap returns a safe description while retaining a non-nil local cause.
func wrap(step string, cause error) error {
	if cause == nil {
		return nil
	}
	return failure{step: step, cause: cause}
}

// release detaches only bounded cleanup, preserving caller metadata.
func release(ctx context.Context, operation func(context.Context) error) error {
	cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), time.Second)
	defer cancel()
	return operation(cleanup)
}

// Run owns one prepared resource and starts no goroutines or automatic retries.
// Close always follows SyncFile; staging discard is allowed only before a possible
// destination effect. The selected profile requires directory sync and recheck.
// All returned causes remain local; expose only safe Error text across a boundary.
func Run(ctx context.Context, prepared Prepared) (Outcome, error) {
	if prepared == nil {
		return Outcome{}, ErrProtocol
	}
	err := wrap("sync_file", prepared.SyncFile(ctx))
	err = errors.Join(err, wrap("close_file", release(ctx, prepared.Close)))
	if err != nil {
		err = errors.Join(err, wrap("discard", release(ctx, prepared.Discard)))
		return Outcome{state: NotPublished}, err
	}
	visibility, publishErr := prepared.Publish(ctx)
	if publishErr != nil {
		err := wrap("publish", publishErr)
		if visibility == NotVisible {
			return Outcome{state: NotPublished}, errors.Join(err, wrap("discard", release(ctx, prepared.Discard)))
		}
		if visibility == Visible {
			return Outcome{state: VisibleUnverified}, err
		}
		return Outcome{state: Ambiguous}, err
	}
	if visibility != Visible {
		return Outcome{state: Ambiguous}, ErrProtocol
	}
	if err := prepared.SyncDirectory(ctx); err != nil {
		return Outcome{state: VisibleUnverified}, wrap("sync_directory", err)
	}
	if err := prepared.CheckPublished(ctx); err != nil {
		return Outcome{state: VisibleUnverified}, wrap("check_published", err)
	}
	return Outcome{state: ChecksPassed}, nil
}
Read the example and tests
package publication

import (
	"context"
	"errors"
	"slices"
	"strings"
	"testing"
)

// errStep is fictional adapter data that must retain identity without public text.
var errStep = errors.New("fictional-private/path adapter failure")

// errCleanup independently identifies a consequential staging cleanup failure.
var errCleanup = errors.New("fictional-private/path cleanup failure")

// fixture records protocol calls and injects deterministic per-step failures.
type fixture struct {
	// calls proves ordering and absence of forbidden post-publication cleanup.
	calls []string
	// failures selects stable step names for this fixture only.
	failures map[string]error
	// visibility is the claimed destination state after Publish.
	visibility Visibility
	// cleanupBounded records independent contexts received by release callbacks.
	cleanupBounded bool
	// cancelAfter chooses a completed step after which the caller cancels.
	cancelAfter string
	// cancel simulates cancellation without timing guesses.
	cancel context.CancelFunc
}

// invoke records one step and honors cancellation for ordinary operations.
func (f *fixture) invoke(ctx context.Context, name string, cleanup bool) error {
	f.calls = append(f.calls, name)
	if cleanup {
		_, bounded := ctx.Deadline()
		f.cleanupBounded = f.cleanupBounded && bounded && ctx.Err() == nil
	}
	if ctx.Err() != nil {
		return ctx.Err()
	}
	err := f.failures[name]
	if name == f.cancelAfter && f.cancel != nil {
		f.cancel()
	}
	return err
}

// SyncFile records the file sync phase.
func (f *fixture) SyncFile(ctx context.Context) error { return f.invoke(ctx, "sync", false) }

// Close records finalization through the detached cleanup context.
func (f *fixture) Close(ctx context.Context) error { return f.invoke(ctx, "close", true) }

// Publish returns the explicit visibility claim and its possible failure.
func (f *fixture) Publish(ctx context.Context) (Visibility, error) {
	return f.visibility, f.invoke(ctx, "publish", false)
}

// SyncDirectory records the directory durability phase.
func (f *fixture) SyncDirectory(ctx context.Context) error { return f.invoke(ctx, "directory", false) }

// CheckPublished records the selected post-publication check.
func (f *fixture) CheckPublished(ctx context.Context) error { return f.invoke(ctx, "check", false) }

// Discard records cleanup of the adapter-owned staging identity only.
func (f *fixture) Discard(ctx context.Context) error { return f.invoke(ctx, "discard", true) }

// TestProtocolOutcomes proves order, per-stage failures and no destructive ambiguous cleanup.
func TestProtocolOutcomes(t *testing.T) {
	cases := []struct {
		fail       string
		visibility Visibility
		state      State
		calls      []string
	}{
		{visibility: Visible, state: ChecksPassed, calls: []string{"sync", "close", "publish", "directory", "check"}},
		{fail: "sync", state: NotPublished, calls: []string{"sync", "close", "discard"}},
		{fail: "close", state: NotPublished, calls: []string{"sync", "close", "discard"}},
		{
			fail: "publish", visibility: NotVisible, state: NotPublished,
			calls: []string{"sync", "close", "publish", "discard"},
		},
		{fail: "publish", state: Ambiguous, calls: []string{"sync", "close", "publish"}},
		{fail: "publish", visibility: Visible, state: VisibleUnverified, calls: []string{"sync", "close", "publish"}},
		{
			fail: "directory", visibility: Visible, state: VisibleUnverified,
			calls: []string{"sync", "close", "publish", "directory"},
		},
		{
			fail: "check", visibility: Visible, state: VisibleUnverified,
			calls: []string{"sync", "close", "publish", "directory", "check"},
		},
	}
	for _, tc := range cases {
		failures := make(map[string]error)
		if tc.fail != "" {
			failures[tc.fail] = errStep
		}
		f := &fixture{failures: failures, visibility: tc.visibility, cleanupBounded: true}
		outcome, err := Run(t.Context(), f)
		if outcome.State() != tc.state || !slices.Equal(f.calls, tc.calls) || !f.cleanupBounded {
			t.Fatalf("incorrect outcome or order: %v %v", outcome.State(), f.calls)
		}
		if tc.fail == "" && err != nil {
			t.Fatal(err)
		}
		if tc.fail != "" && (!errors.Is(err, errStep) || strings.Contains(err.Error(), "fictional-private")) {
			t.Fatal("failure lost identity or leaked raw details")
		}
	}
}

// TestCleanupAndCancellation proves error joining and bounded cleanup after cancellation.
func TestCleanupAndCancellation(t *testing.T) {
	f := &fixture{failures: map[string]error{"sync": errStep, "discard": errCleanup}, cleanupBounded: true}
	outcome, err := Run(t.Context(), f)
	if outcome.State() != NotPublished || !errors.Is(err, errStep) || !errors.Is(err, errCleanup) {
		t.Fatal("cleanup failure was lost")
	}
	ctx, cancel := context.WithCancel(t.Context())
	cancel()
	f = &fixture{cleanupBounded: true}
	outcome, err = Run(ctx, f)
	if outcome.State() != NotPublished || !errors.Is(err, context.Canceled) || !f.cleanupBounded ||
		!slices.Equal(f.calls, []string{"sync", "close", "discard"}) {
		t.Fatal("caller cancellation skipped owned cleanup")
	}
}

// TestInvalidAdapterIsNotSuccess rejects absent ownership and inconsistent visibility.
func TestInvalidAdapterIsNotSuccess(t *testing.T) {
	outcome, err := Run(t.Context(), nil)
	if !errors.Is(err, ErrProtocol) || outcome.State() == ChecksPassed {
		t.Fatal("missing ownership accepted")
	}
	f := &fixture{visibility: NotVisible, cleanupBounded: true}
	outcome, err = Run(t.Context(), f)
	if outcome.State() != Ambiguous || !errors.Is(err, ErrProtocol) || slices.Contains(f.calls, "discard") {
		t.Fatal("inconsistent publication became success or destructive cleanup")
	}
}

// TestCancellationAfterVisibility keeps visible output and never discards its destination.
func TestCancellationAfterVisibility(t *testing.T) {
	for _, after := range []string{"publish", "directory"} {
		ctx, cancel := context.WithCancel(t.Context())
		f := &fixture{visibility: Visible, cleanupBounded: true, cancelAfter: after, cancel: cancel}
		outcome, err := Run(ctx, f)
		cancel()
		if outcome.State() != VisibleUnverified || !errors.Is(err, context.Canceled) ||
			slices.Contains(f.calls, "discard") {
			t.Fatal("cancellation converted visible output to success or destructive cleanup")
		}
	}
}

// TestUnknownVisibilityIsAmbiguous rejects zero, unknown and inconsistent adapter claims.
func TestUnknownVisibilityIsAmbiguous(t *testing.T) {
	for _, visibility := range []Visibility{"", "unsupported"} {
		for _, cause := range []error{nil, errStep} {
			f := &fixture{visibility: visibility, cleanupBounded: true, failures: map[string]error{"publish": cause}}
			outcome, err := Run(t.Context(), f)
			if outcome.State() != Ambiguous || err == nil || slices.Contains(f.calls, "discard") {
				t.Fatal("unknown visibility became success or cleanup")
			}
		}
	}
}

Bounded background jobs

This conditional profile applies to scheduled or long-lived jobs and programs that import remote data or publish derived state. Correctness includes overlap, cancellation and lost coordination.

GO-JOB-001 Identify and bound every run

Every run has a unique identity, an explicit scope and declared maximum items, bytes, runtime and request rate. Its typed result contains that identity and structured expected, accepted, rejected, published, unchanged and failed counts, plus the failure classification of every rejected or failed unit. Any rejected or failed unit makes the run partial, never successful; GO-CLI-001 maps partial to a documented exit code distinct from success and total failure.

Rationale. Logs and metrics carry the run identity without secrets or raw payloads. A completed loop does not mean every unit succeeded.

Review criterion. Review all bounds and counts, per-unit classifications and the process exit mapping. Exercise a mixed run and confirm that even one rejection or failure produces partial.

GO-JOB-002 Exclude competing effects and fence stale publishers

Effect-producing runs for the same scope use coordination with a documented ownership and failure model. A distributed TTL lease declares its owner token, expiry and renewal rule; release compares the token, and failed renewal stops effects before expiry. A kernel-owned process lock can rely on process-exit release without a TTL or heartbeat only when every competing publisher belongs to that lock domain. Read-only dry runs declare whether consistent observation needs exclusion and obtain no publication authority.

Rationale. A lease cannot stop a paused holder resuming after expiry. Where stale authority can survive, each durable publication carries a monotonic fence or generation obtained when work began; the store checks it and applies the effect in the same atomic operation. A process lock is not a distributed fence. Any alternative proves stale effects impossible under the actual process/store model. Lost or evicted coordination state fails closed: a new generation comes only from the accepted mechanism, never reconstruction of an old value.

Review criterion. Exercise overlap, stale publication, renewal failure, wrong-owner release and coordination-state loss. Verify the real store primitive checks the fence atomically with the durable effect; an in-memory model establishes only its own behavior.

GO-JOB-006 Specify schedules, shutdown and dry run

Schedules declare time zone, daylight-saving behavior, overlap policy, catch-up after downtime and configuration/version-change effects. Use one accepted scheduling mechanism without adding another inside the worker. On root-context cancellation under GO-CLI-001, stop admitting work, finish or abandon in-flight units at a defined boundary, release the lease through bounded detached cleanup allowed by GO-CTX-002 and report interrupted.

Rationale. Dry run follows the complete fetch, validation and planning path, reports what would be published and performs no writes. Shutdown boundaries make interruption and subsequent recovery predictable.

Review criterion. Check both daylight-saving transitions, local day boundaries, catch-up and version changes. Cancel at declared boundaries, verify bounded cleanup and interrupted reporting, and inspect dry-run output and absence of writes.

A typed run summary

The model derives counts and closed failure classes for at most 64 units, including pending work on interruption. It validates caller-issued run/scope labels; it neither generates globally unique IDs nor executes jobs or enforces runtime, byte, rate or retry budgets. ExitCode is an example mapping, not a real CLI total-failure policy.

// Package runreport models bounded summaries, not job execution or run-ID issuance.
package runreport

import (
	"errors"
	"slices"
	"strings"

	"example.org/go-public/failure"
)

// ErrInput rejects inconsistent summary data without exposing payloads.
var ErrInput = errors.New("invalid run summary")

// UnitState identifies one processed unit's outcome.
type UnitState string

const (
	Published UnitState = "published" // Published records a replacement.
	Unchanged UnitState = "unchanged" // Unchanged records an accepted no-op.
	Rejected  UnitState = "rejected"  // Rejected records permanent invalid input.
	Failed    UnitState = "failed"    // Failed requires a classified reason.
)

// Termination keeps natural completion distinct from interruption.
type Termination string

const (
	Finished Termination = "finished" // Finished accounts for every expected unit.
	Stopped  Termination = "stopped"  // Stopped permits explicit pending work.
)

// State preserves partial progress even when interruption also happened.
type State string

const (
	Complete           State = "complete"            // Complete contains no rejected, failed or pending work.
	Partial            State = "partial"             // Partial contains rejected or failed units.
	Interrupted        State = "interrupted"         // Interrupted stopped after all accepted units.
	InterruptedPartial State = "interrupted_partial" // InterruptedPartial also has incomplete/failed work.
)

// Class is a machine recovery category, not parsed error text.
type Class string

const (
	Permanent     Class = "permanent"      // Permanent requires correcting input.
	Transient     Class = "transient"      // Transient may permit a bounded safe retry.
	Ambiguous     Class = "ambiguous"      // Ambiguous requires reconciliation.
	OwnershipLost Class = "ownership_lost" // OwnershipLost stops effects.
)

// Unit is validated reporting input, never a raw source payload.
type Unit struct {
	ID     string         // ID is unique within the run.
	State  UnitState      // State names the processed outcome.
	Reason failure.Reason // Reason is empty for accepted and required for failed/rejected units.
}

// Issue retains the owning example's closed reason and derived classification.
type Issue struct {
	UnitID string         // UnitID identifies the unit without its contents.
	Class  Class          // Class guides a separate recovery policy.
	Reason failure.Reason // Reason is checked through failure.ParseReason.
}

// Counts uses disjoint processed counts plus an explicit pending remainder.
type Counts struct {
	Expected  int // Expected is the declared run cardinality.
	Accepted  int // Accepted equals Published plus Unchanged.
	Rejected  int // Rejected counts refused units.
	Published int // Published counts replacements.
	Unchanged int // Unchanged counts accepted no-ops.
	Failed    int // Failed counts classified failures.
	Pending   int // Pending is unprocessed work during interruption.
}

// Report is derived summary data; it proves no actual durable effects.
// Its zero value has no successful exit code.
type Report struct {
	runID  string  // runID is caller-issued; parsing cannot prove global uniqueness.
	scope  string  // scope is an explicit bounded reporting label.
	state  State   // state preserves partial progress and interruption.
	counts Counts  // counts is a scalar snapshot.
	issues []Issue // issues is owned and returned only as a copy.
}

// token checks bounded ASCII labels before internal allocation.
func token(value string, minimum, maximum int) bool {
	if len(value) < minimum || len(value) > maximum {
		return false
	}
	for _, character := range []byte(value) {
		if (character < 'a' || character > 'z') && (character < '0' || character > '9') && character != '-' {
			return false
		}
	}
	return true
}

// classify fixes the reason/class mapping for this teaching contract.
func classify(reason failure.Reason) (Class, error) {
	if _, err := failure.ParseReason(string(reason)); err != nil {
		return "", ErrInput
	}
	switch reason {
	case failure.InvalidInput:
		return Permanent, nil
	case failure.ServiceUnavailable:
		return Transient, nil
	case failure.ReplyLost:
		return Ambiguous, nil
	case failure.OwnershipLost:
		return OwnershipLost, nil
	default:
		return "", ErrInput
	}
}

// New derives counts for at most 64 units; a finished run accounts for all expected work.
// Runtime, byte/rate budgets and run-ID uniqueness still belong to the real runner.
func New(runID, scope string, expected int, units []Unit, termination Termination) (Report, error) {
	if !token(runID, 8, 64) || !token(scope, 1, 32) || expected < 0 || expected > 64 || len(units) > expected ||
		(termination != Finished && termination != Stopped) || (termination == Finished && len(units) != expected) {
		return Report{}, ErrInput
	}
	counts := Counts{Expected: expected, Pending: expected - len(units)}
	seen := make(map[string]bool, len(units))
	issues := make([]Issue, 0, len(units))
	for _, unit := range units {
		if !token(unit.ID, 1, 32) || seen[unit.ID] {
			return Report{}, ErrInput
		}
		seen[unit.ID] = true
		switch unit.State {
		case Published, Unchanged:
			if unit.Reason != "" {
				return Report{}, ErrInput
			}
			counts.Accepted++
			if unit.State == Published {
				counts.Published++
			} else {
				counts.Unchanged++
			}
		case Rejected, Failed:
			class, err := classify(unit.Reason)
			if err != nil || (unit.State == Rejected && class != Permanent) {
				return Report{}, ErrInput
			}
			issues = append(issues, Issue{UnitID: strings.Clone(unit.ID), Class: class, Reason: failure.Reason(strings.Clone(string(unit.Reason)))})
			if unit.State == Rejected {
				counts.Rejected++
			} else {
				counts.Failed++
			}
		default:
			return Report{}, ErrInput
		}
	}
	state := Complete
	if counts.Rejected+counts.Failed+counts.Pending > 0 {
		state = Partial
	}
	if termination == Stopped {
		if state == Partial {
			state = InterruptedPartial
		} else {
			state = Interrupted
		}
	}
	return Report{runID: strings.Clone(runID), scope: strings.Clone(scope), state: state, counts: counts, issues: issues}, nil
}

// State returns the validated run disposition.
func (report Report) State() State { return report.state }

// Counts returns the reporting snapshot by value.
func (report Report) Counts() Counts { return report.counts }

// Issues returns a caller-owned classification slice.
func (report Report) Issues() []Issue { return slices.Clone(report.issues) }

// RunID returns the caller-issued identity for logs or metrics.
func (report Report) RunID() string { return report.runID }

// Scope returns the explicit reporting scope.
func (report Report) Scope() string { return report.scope }

// ExitCode maps complete to 0, partial to 2, interruption to 130 and invalid to 1.
// It does not call os.Exit or define a real runner’s total-failure policy.
func (report Report) ExitCode() int {
	switch report.state {
	case Complete:
		return 0
	case Partial:
		return 2
	case Interrupted, InterruptedPartial:
		return 130
	default:
		return 1
	}
}
Read the example and tests
package runreport

import (
	"errors"
	"testing"

	"example.org/go-public/failure"
)

// TestMixedRunPreservesCountsAndClasses keeps partial results distinct from success.
func TestMixedRunPreservesCountsAndClasses(t *testing.T) {
	units := []Unit{
		{ID: "one", State: Published}, {ID: "two", State: Unchanged},
		{ID: "three", State: Rejected, Reason: failure.InvalidInput},
		{ID: "four", State: Failed, Reason: failure.ServiceUnavailable},
		{ID: "five", State: Failed, Reason: failure.ReplyLost},
		{ID: "six", State: Failed, Reason: failure.OwnershipLost},
	}
	report, err := New("demo-run-1", "observations", 6, units, Finished)
	want := Counts{Expected: 6, Accepted: 2, Rejected: 1, Published: 1, Unchanged: 1, Failed: 3}
	if err != nil || report.State() != Partial || report.ExitCode() != 2 || report.Counts() != want ||
		report.RunID() != "demo-run-1" || report.Scope() != "observations" {
		t.Fatalf("incorrect mixed summary: %v %v", report, err)
	}
	issues := report.Issues()
	classes := []Class{Permanent, Transient, Ambiguous, OwnershipLost}
	for index, class := range classes {
		if issues[index].Class != class || issues[index].Reason != units[index+2].Reason ||
			issues[index].UnitID != units[index+2].ID {
			t.Fatal("classification lost its owning unit")
		}
	}
	issues[0].Class = "changed"
	units[2].Reason = "changed"
	if report.Issues()[0].Class != Permanent || report.Issues()[0].Reason != failure.InvalidInput {
		t.Fatal("caller mutation changed the report")
	}
}

// TestCompletionAndInterruption keeps pending and failed work visible after stop.
func TestCompletionAndInterruption(t *testing.T) {
	cases := []struct {
		name        string
		expected    int
		units       []Unit
		termination Termination
		state       State
		code        int
		pending     int
	}{
		{"noop", 0, nil, Finished, Complete, 0, 0},
		{"accepted", 1, []Unit{{ID: "one", State: Unchanged}}, Finished, Complete, 0, 0},
		{"pending", 2, []Unit{{ID: "one", State: Published}}, Stopped, InterruptedPartial, 130, 1},
		{"failed", 1, []Unit{{ID: "one", State: Failed, Reason: failure.ReplyLost}}, Stopped, InterruptedPartial, 130, 0},
		{"stopped", 1, []Unit{{ID: "one", State: Published}}, Stopped, Interrupted, 130, 0},
	}
	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			report, err := New("demo-run-2", "observations", tc.expected, tc.units, tc.termination)
			if err != nil || report.State() != tc.state || report.ExitCode() != tc.code ||
				report.Counts().Pending != tc.pending {
				t.Fatalf("lost completion state: %v %v", report, err)
			}
		})
	}
	if (Report{}).ExitCode() == 0 {
		t.Fatal("zero report became success")
	}
}

// TestInvalidSummary rejects unknown vocabulary, inconsistent counts and duplicated units.
func TestInvalidSummary(t *testing.T) {
	cases := []struct {
		name     string
		expected int
		units    []Unit
	}{
		{"missing", 1, nil}, {"negative", -1, nil}, {"unbounded", 65, nil},
		{"duplicate", 2, []Unit{{ID: "one", State: Published}, {ID: "one", State: Published}}},
		{"unknown-state", 1, []Unit{{ID: "one", State: "unknown"}}},
		{"missing-reason", 1, []Unit{{ID: "one", State: Failed}}},
		{"unknown-reason", 1, []Unit{{ID: "one", State: Failed, Reason: "unknown"}}},
		{"accepted-reason", 1, []Unit{{ID: "one", State: Published, Reason: failure.InvalidInput}}},
		{"wrong-reject-class", 1, []Unit{{ID: "one", State: Rejected, Reason: failure.ReplyLost}}},
		{"bad-id", 1, []Unit{{ID: "private/input", State: Published}}},
		{"extra", 0, []Unit{{ID: "one", State: Published}}},
	}
	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			report, err := New("demo-run-3", "observations", tc.expected, tc.units, Finished)
			if !errors.Is(err, ErrInput) || report.ExitCode() == 0 {
				t.Fatal("invalid summary became successful")
			}
		})
	}
	for _, input := range [][2]string{{"short", "scope"}, {"demo-run-3", ""}, {"demo/run-3", "scope"}} {
		if _, err := New(input[0], input[1], 0, nil, Finished); !errors.Is(err, ErrInput) {
			t.Fatal("invalid identity accepted")
		}
	}
	if _, err := New("demo-run-3", "scope", 0, nil, "unknown"); !errors.Is(err, ErrInput) {
		t.Fatal("unknown termination accepted")
	}
}

Safe data imports

Fetch, validation, publication and progress form one recovery contract. Readers retain the last valid unit when a new attempt fails.

GO-JOB-003 Bound remote reads and preserve source provenance

Follow the protocol-specific outbound profile of GO-NET-001: an explicit host and scheme allowlist, authenticated transport with TLS verification where applicable, connect and total timeouts, and a maximum response size enforced while reading. HTTP declares redirect policy; partial reads, including HTTP ranges, validate returned range and size.

Rationale. Each fetched unit records source identifier, content digest and observation time. Store source-reported version or generation as reported. Unknown source provenance stays unknown; fetch time cannot stand in for it.

Review criterion. Exercise disallowed endpoints, redirects, timeouts, oversized and truncated reads and incorrect ranges. Inspect source identity, digest and observation time separately from known or unknown source-provided provenance.

GO-JOB-004 Validate the complete unit before atomic replacement

Decode, validate and normalize the entire publication unit before writing. Validate structure, units, cardinality, required coverage, finite numeric values and domain bounds. Any normalization of out-of-bound values follows a documented, tested rule and is never silent. Replace the whole unit in one atomic store operation, so readers cannot observe a partial write.

Rationale. Failed fetch, validation or publication preserves the last valid unit. Report failure in the run result instead of replacing good state with empty, zero or partial values.

Review criterion. Inject each failure and observe that readers retain the last good complete unit. Check normalization rules and the actual store replacement primitive; fake-store tests alone cannot prove production atomicity.

GO-JOB-005 Commit before acknowledging and replay safely

Acknowledge source items, advance checkpoints or write processed markers only after intended durable state commits. Assume at-least-once delivery and make every effect idempotent using a stable imported-unit identity. Record rejected units and reasons in a reject report; repeatedly failing units enter quarantine or operator recovery rather than endless retries.

Rationale. Under GO-ERR-005, transient failures use bounded attempts, backoff and jitter within a per-run retry budget; permanent failures stop the unit. Reconcile ambiguous outcomes or leave them for inspection, never retry blindly. An identical repeated upstream answer does not refresh source provenance.

Review criterion. Crash between durable commit and acknowledgement, replay the same identity, exhaust the retry budget and test permanent and ambiguous failures. Verify no duplicate effect, premature checkpoint or false freshness and a usable reject/recovery route.

One scope: fence, replace and acknowledge

This bounded in-memory model excludes local overlap and checks ownership in the same mutex critical section as replacement. Per-item acknowledgement follows local commit; historical replay produces no new effect or rollback. This is not an ordered checkpoint, durable queue, distributed lease or production-store atomicity/crash proof. Transport, source provenance, schedules, retries and warm-up after published-state eviction require separate implementation and tests.

// Package itemstore models one scope's coordination, fenced replacement and per-item ack in memory.
// The mutex proves only this process model, not production atomicity or durability.
package itemstore

import (
	"context"
	"errors"
	"strings"
	"sync"
)

// ErrInput rejects invalid scope,identity or complete-record values.
var ErrInput = errors.New("invalid model record")

// ErrBusy rejects an overlapping owner in this model.
var ErrBusy = errors.New("scope already owned")

// ErrOwnership rejects stale or foreign fences before effects.
var ErrOwnership = errors.New("model ownership lost")

// ErrCoordination rejects unknown/exhausted coordination without reconstruction.
var ErrCoordination = errors.New("model coordination unavailable")

// ErrReplay rejects changed semantics under an already committed input ID.
var ErrReplay = errors.New("model replay conflicts with committed input")

// ErrCapacity bounds retained in-memory history.
var ErrCapacity = errors.New("model history is full")

// ErrReceipt rejects ack without a matching committed input.
var ErrReceipt = errors.New("model commit receipt is invalid")

// Record is an immutable complete example unit; its zero value is invalid.
type Record struct {
	scope   string // scope identifies the one entity replaced by this unit.
	inputID string // inputID is a stable imported-unit identity,not fetch time.
	count   int    // count is a domain value from 0 to one million without clamping.
}

// validName checks the bounded ASCII model vocabulary before storage allocation.
func validName(value string) bool {
	if len(value) < 1 || len(value) > 32 {
		return false
	}
	for _, character := range []byte(value) {
		if (character < 'a' || character > 'z') && (character < '0' || character > '9') && character != '-' {
			return false
		}
	}
	return true
}

// NewRecord validates the whole scope/input/count schema before publication.
func NewRecord(scope, inputID string, count int) (Record, error) {
	if !validName(scope) || !validName(inputID) || count < 0 || count > 1000000 {
		return Record{}, ErrInput
	}
	return Record{scope: strings.Clone(scope), inputID: strings.Clone(inputID), count: count}, nil
}

// Count returns the value,not publication authority.
func (record Record) Count() int { return record.count }

// Fence binds one generation to this exact in-memory instance.
// It is not a distributed lease,heartbeat,portable token or durable generation.
type Fence struct {
	owner      *Store // owner prevents token reuse against a freshly allocated store.
	generation uint64 // generation must match in the same critical section as effects.
}

// Receipt is issued only for a committed or known replayed input in this model.
type Receipt struct {
	owner      *Store // owner is an in-memory identity,not a persistent backend ID.
	generation uint64 // generation binds ack to the current owner.
	inputID    string // inputID identifies one committed item,not an ordered checkpoint.
}

// Effect distinguishes replacement from an already committed duplicate input.
type Effect string

const (
	Replaced  Effect = "replaced"  // Replaced atomically changed the whole local record.
	Unchanged Effect = "unchanged" // Unchanged produced no duplicate effect.
)

// Publication is a model result,not durable commit evidence.
type Publication struct {
	Effect  Effect  // Effect names the local action.
	Receipt Receipt // Receipt permits only model per-item ack under the current fence.
}

// View uses one presence indicator for missing/ready data,never for authority.
type View struct {
	Available bool   // Available reports whether a whole model record exists.
	Record    Record // Record is a scalar copy,not mutable store internals.
}

// Store owns one scope and must never be copied after first use.
// Coordination loss fails closed permanently; no old counter is reconstructed.
type Store struct {
	mu         sync.Mutex        // mu protects fence checks and effects in one critical section.
	scope      string            // scope cannot be changed by a publisher.
	known      bool              // known distinguishes initialized coordination from zero/lost state.
	active     bool              // active excludes overlap only within this local lock domain.
	generation uint64            // generation monotonically increases until exhaustion or loss.
	history    map[string]Record // history retains at most 64 stable input identities.
	acked      map[string]bool   // acked records per-item ack,not stream checkpoint advance.
	current    Record            // current is last-known-good or zero when unavailable.
	effects    int               // effects counts replacements for replay verification.
}

// New constructs an empty bounded store for one scope without external effects.
func New(scope string) (*Store, error) {
	if !validName(scope) {
		return nil, ErrInput
	}
	return &Store{scope: strings.Clone(scope), known: true, history: make(map[string]Record), acked: make(map[string]bool)}, nil
}

// owns is called only under mu; it grants no authority outside this model.
func (store *Store) owns(fence Fence) bool {
	return store.known && store.active && fence.owner == store && fence.generation == store.generation
}

// Begin excludes overlap and issues a new local generation without inventing a TTL.
func (store *Store) Begin(ctx context.Context) (Fence, error) {
	store.mu.Lock()
	defer store.mu.Unlock()
	if ctx.Err() != nil {
		return Fence{}, ctx.Err()
	}
	if !store.known || store.generation == ^uint64(0) {
		return Fence{}, ErrCoordination
	}
	if store.active {
		return Fence{}, ErrBusy
	}
	store.generation++
	store.active = true
	return Fence{owner: store, generation: store.generation}, nil
}

// Release compares ownership so a stale holder cannot release a newer one.
func (store *Store) Release(ctx context.Context, fence Fence) error {
	store.mu.Lock()
	defer store.mu.Unlock()
	if ctx.Err() != nil {
		return ctx.Err()
	}
	if !store.owns(fence) {
		return ErrOwnership
	}
	store.active = false
	return nil
}

// Publish checks the fence atomically with whole-record replacement.
// Historical duplicate input is a no-op even after newer input; changed semantics
// under an old identity fail rather than replacing last-known-good data.
func (store *Store) Publish(ctx context.Context, fence Fence, record Record) (Publication, error) {
	store.mu.Lock()
	defer store.mu.Unlock()
	if ctx.Err() != nil {
		return Publication{}, ctx.Err()
	}
	if !store.owns(fence) {
		return Publication{}, ErrOwnership
	}
	if _, err := NewRecord(record.scope, record.inputID, record.count); err != nil || record.scope != store.scope {
		return Publication{}, ErrInput
	}
	effect := Unchanged
	if previous, exists := store.history[record.inputID]; exists {
		if previous != record {
			return Publication{}, ErrReplay
		}
	} else {
		if len(store.history) >= 64 {
			return Publication{}, ErrCapacity
		}
		store.history[record.inputID] = record
		store.current = record
		store.effects++
		effect = Replaced
	}
	return Publication{Effect: effect, Receipt: Receipt{
		owner: store, generation: fence.generation, inputID: record.inputID,
	}}, nil
}

// Ack records a committed item only after validating ownership and its receipt.
// Replay is idempotent; this is neither durable queue ack nor an ordered checkpoint.
func (store *Store) Ack(ctx context.Context, fence Fence, receipt Receipt) error {
	store.mu.Lock()
	defer store.mu.Unlock()
	if ctx.Err() != nil {
		return ctx.Err()
	}
	if !store.owns(fence) {
		return ErrOwnership
	}
	if receipt.owner != store || receipt.generation != fence.generation {
		return ErrReceipt
	}
	if _, exists := store.history[receipt.inputID]; !exists {
		return ErrReceipt
	}
	store.acked[receipt.inputID] = true
	return nil
}

// Read returns last-known-good data; empty state explicitly reports unavailable.
func (store *Store) Read() View {
	store.mu.Lock()
	defer store.mu.Unlock()
	return View{Available: store.current.scope != "", Record: store.current}
}

// LoseCoordination models eviction without resetting counters or deleting valid data.
func (store *Store) LoseCoordination() {
	store.mu.Lock()
	defer store.mu.Unlock()
	store.known = false
	store.active = false
}
Read the example and tests
package itemstore

import (
	"context"
	"errors"
	"fmt"
	"testing"
)

// fixture creates one owned scope and fails before starting any asynchronous work.
func fixture(t *testing.T) (*Store, Fence) {
	t.Helper()
	store, err := New("observations")
	if err != nil {
		t.Fatal(err)
	}
	fence, err := store.Begin(t.Context())
	if err != nil {
		t.Fatal(err)
	}
	return store, fence
}

// record constructs a complete validated unit without transport or source-time claims.
func record(t *testing.T, id string, count int) Record {
	t.Helper()
	result, err := NewRecord("observations", id, count)
	if err != nil {
		t.Fatal(err)
	}
	return result
}

// TestStalePublisher coordinates a paused old holder without sleep or timing guesses.
func TestStalePublisher(t *testing.T) {
	store, old := fixture(t)
	if _, err := store.Begin(t.Context()); !errors.Is(err, ErrBusy) {
		t.Fatal("overlap accepted")
	}
	resume := make(chan struct{})
	result := make(chan error, 1)
	oldRecord := record(t, "old", 1)
	go func() {
		<-resume
		_, err := store.Publish(t.Context(), old, oldRecord)
		result <- err
	}()
	// Cleanup always unblocks and joins the worker before checking the final record.
	newRecord := record(t, "new", 2)
	defer func() {
		close(resume)
		if !errors.Is(<-result, ErrOwnership) {
			t.Error("stale effect accepted")
		}
		if store.Read().Record != newRecord {
			t.Error("new record lost after joining the stale worker")
		}
	}()
	if err := store.Release(t.Context(), old); err != nil {
		t.Fatal(err)
	}
	current, err := store.Begin(t.Context())
	if err != nil {
		t.Fatal(err)
	}
	if err := store.Release(t.Context(), old); !errors.Is(err, ErrOwnership) {
		t.Fatal("old release accepted")
	}
	if _, err := store.Publish(t.Context(), current, newRecord); err != nil {
		t.Fatal(err)
	}

}

// TestCommitReplayAndAck models interruption after local commit but before per-item ack.
func TestCommitReplayAndAck(t *testing.T) {
	store, fence := fixture(t)
	if store.Read().Available || store.Ack(t.Context(), fence, Receipt{}) != ErrReceipt {
		t.Fatal("empty state or premature ack accepted")
	}
	first := record(t, "input-1", 4)
	published, err := store.Publish(t.Context(), fence, first)
	if err != nil || published.Effect != Replaced || len(store.acked) != 0 {
		t.Fatal("incorrect commit boundary")
	}
	if err := store.Release(t.Context(), fence); err != nil {
		t.Fatal(err)
	}
	fence, err = store.Begin(t.Context())
	if err != nil {
		t.Fatal(err)
	}
	if store.Ack(t.Context(), fence, published.Receipt) != ErrReceipt {
		t.Fatal("stale receipt accepted")
	}
	replayed, err := store.Publish(t.Context(), fence, first)
	if err != nil || replayed.Effect != Unchanged || store.effects != 1 {
		t.Fatal("duplicate effect")
	}
	for range 2 {
		if err := store.Ack(t.Context(), fence, replayed.Receipt); err != nil {
			t.Fatal(err)
		}
	}
	if len(store.acked) != 1 {
		t.Fatal("non-idempotent ack")
	}
	newer := record(t, "input-2", 8)
	if _, err := store.Publish(t.Context(), fence, newer); err != nil {
		t.Fatal(err)
	}
	if replay, err := store.Publish(t.Context(), fence, first); err != nil || replay.Effect != Unchanged ||
		store.Read().Record != newer || store.effects != 2 {
		t.Fatal("historical replay rolled back newer data")
	}
	if _, err := store.Publish(t.Context(), fence, record(t, "input-1", 9)); err != ErrReplay ||
		store.Read().Record != newer {
		t.Fatal("changed semantics replaced good data")
	}
}

// TestValidationAndCoordinationLoss preserves last good state and never reconstructs authority.
func TestValidationAndCoordinationLoss(t *testing.T) {
	store, fence := fixture(t)
	good := record(t, "input-1", 3)
	published, err := store.Publish(t.Context(), fence, good)
	if err != nil {
		t.Fatal(err)
	}
	for _, value := range []int{-1, 1000001} {
		if _, err := NewRecord("observations", "bad", value); err != ErrInput {
			t.Fatal("bounds accepted")
		}
	}
	if _, err := store.Publish(t.Context(), fence, Record{}); err != ErrInput {
		t.Fatal("zero record accepted")
	}
	foreign, _ := NewRecord("other", "input-2", 5)
	if _, err := store.Publish(t.Context(), fence, foreign); err != ErrInput {
		t.Fatal("foreign scope accepted")
	}
	ctx, cancel := context.WithCancel(t.Context())
	cancel()
	if _, err := store.Publish(ctx, fence, record(t, "input-2", 4)); !errors.Is(err, context.Canceled) {
		t.Fatal("canceled publication accepted")
	}
	if err := store.Ack(ctx, fence, published.Receipt); !errors.Is(err, context.Canceled) {
		t.Fatal(err)
	}
	if err := store.Release(ctx, fence); !errors.Is(err, context.Canceled) {
		t.Fatal(err)
	}
	if _, err := store.Begin(ctx); !errors.Is(err, context.Canceled) {
		t.Fatal(err)
	}
	generation := store.generation
	store.LoseCoordination()
	if _, err := store.Begin(t.Context()); err != ErrCoordination {
		t.Fatal("lost coordination reused")
	}
	if _, err := store.Publish(t.Context(), fence, good); err != ErrOwnership {
		t.Fatal("lost owner published")
	}
	if err := store.Ack(t.Context(), fence, published.Receipt); err != ErrOwnership {
		t.Fatal("lost owner acked")
	}
	if store.Read().Record != good || !store.Read().Available || store.generation != generation || store.effects != 1 {
		t.Fatal("failure changed last good state or reconstructed authority")
	}
}

// TestForeignZeroAndExhaustedState rejects portable or reconstructed model authority.
func TestForeignZeroAndExhaustedState(t *testing.T) {
	store, fence := fixture(t)
	other, otherFence := fixture(t)
	published, err := other.Publish(t.Context(), otherFence, record(t, "input", 1))
	if err != nil {
		t.Fatal(err)
	}
	if _, err := store.Publish(t.Context(), otherFence, record(t, "input", 1)); err != ErrOwnership {
		t.Fatal("foreign fence accepted")
	}
	if store.Ack(t.Context(), fence, published.Receipt) != ErrReceipt {
		t.Fatal("foreign receipt accepted")
	}
	zero := new(Store)
	if _, err := zero.Begin(t.Context()); err != ErrCoordination {
		t.Fatal("zero store became authority")
	}
	store.active = false
	store.generation = ^uint64(0)
	if _, err := store.Begin(t.Context()); err != ErrCoordination {
		t.Fatal("generation wrapped")
	}
	if _, err := New("invalid/scope"); err != ErrInput {
		t.Fatal("invalid scope accepted")
	}
}

// TestHistoryCapacity bounds model storage while allowing known-input replay at capacity.
func TestHistoryCapacity(t *testing.T) {
	store, fence := fixture(t)
	for index := range 64 {
		if _, err := store.Publish(t.Context(), fence, record(t, fmt.Sprintf("input-%d", index), index)); err != nil {
			t.Fatal(err)
		}
	}
	before := store.Read()
	if _, err := store.Publish(t.Context(), fence, record(t, "overflow", 65)); err != ErrCapacity || store.Read() != before {
		t.Fatal("capacity failure changed good state")
	}
	if replay, err := store.Publish(t.Context(), fence, record(t, "input-0", 0)); err != nil || replay.Effect != Unchanged ||
		store.Read() != before || store.effects != 64 {
		t.Fatal("capacity prevented safe replay or rolled back state")
	}
}

Tests for interrupted and competing jobs

Successful execution alone does not establish recovery or concurrency safety. Test the failure boundaries deliberately.

GO-JOB-007 Prove failure boundaries deterministically

Use injected clocks or testing/synctest, deterministic fakes and controlled faults to test concurrent exclusion and stale-holder rejection; crash or cancellation after every durable boundary; duplicate delivery and identical upstream answers; malformed, truncated, oversized and out-of-bounds input; empty or evicted published state; both daylight-saving transitions and local day boundaries.

Rationale. Assert consistent replayable state, no duplicate effects or false freshness, rejection before publication with the last valid unit intact, and documented warm-up or unavailable behavior. A successful end-to-end run does not establish interruption, retry or concurrency safety.

Review criterion. Check the calendar outcomes against the declared schedule contract. A fake store does not prove production-store atomicity: that evidence belongs to the GO-TST-008 integration lane.

Architecture with explicit ownership

Packages separate responsibilities while dependencies and side effects remain visible to readers and reviewers.

GO-ARC-001 Keep packages cohesive and commands thin

Each package owns one coherent responsibility. cmd/<name> is a thin process and composition boundary; reusable and business behavior belongs in cohesive packages, normally internal when no external consumer is intended.

Rationale. Dependency cycles, unjustified mutable global service state, demonstrably incoherent dumping-ground packages and business policy inside transport, storage or CLI wiring are prohibited. Neither a pkg/ directory nor arbitrary file or function length limits are mandated.

Review criterion. Compare package responsibilities and dependency direction; verify that command wiring only composes and starts behavior and that the prohibited patterns are absent.

GO-ARC-002 Compose explicitly and justify interfaces

Use concrete implementations by default. A consuming package introduces a small semantic interface when substitution, an adapter boundary or a test seam is real. Constructors make mandatory dependencies explicit and reject invalid configuration early.

Rationale. An intentional extension point with several real implementations is an exception: the capability owner declares its small interface and documents it as the extension contract. Each production implementation has its own package and a compile-time conformance assertion; in-memory and test implementations are exempt from those requirements. The owner supplies a <capability>test package with a shared conformance test, such as TestImplementation(t, newImplementation), following testing/fstest.TestFS; every implementation runs it. Do not create an interface merely to mirror every method of a concrete provider, or use service locators or package globals as hidden dependency injection.

Review criterion. Check the real need for every interface, explicit dependencies and early validation. For extension contracts, check ownership, implementation packages, compile-time assertions with the stated exemptions, and execution of the shared test by every implementation.

GO-ARC-003 Separate semantic ports from mechanics

Filesystem, storage, Git, process and network mechanics pass through deliberate adapters where they cross semantic logic. Methods express a use case instead of making callers select a backend through names such as SaveToFilesystem.

Rationale. Dynamic field, query, sort and command vocabularies use named types or explicit allowlists before reaching an adapter. Document persistence ownership and migration responsibility.

Review criterion. Trace each use case to its adapter; check types or allowlists for dynamic values and documented ownership of persistence and migrations.

GO-ARC-004 Make initialization explicit

Mutable package globals and init side effects require an explicit reason. init must not perform network or durable filesystem work, depend on secrets or start unmanaged goroutines.

Rationale. Prefer explicit construction that can return an error and be tested. Hidden initialization makes lifecycle and failure control harder.

Review criterion. Review global state and every init for justification and prohibited effects; check the explicit construction and error path.

Data schemas and platform boundaries

Persistent formats have an identified owner, and platform-dependent behavior has an explicit support boundary.

GO-ARC-005 Assign one owner to schemas and migrations

Where persistent schemas, key namespaces or published data formats exist, exactly one program or package defines, versions and migrates each of them. Migrations are versioned, immutable once released and tested against the real storage engine on an empty scratch instance.

Rationale. Several program instances must not run uncoordinated automatic migrations: migration is an explicit single-owner step. Readers that do not own the schema validate its version and fail closed on an unknown version.

Review criterion. For each schema, namespace and format, check its sole owner, versions, released migration immutability, real-engine empty-instance tests, migration coordination and reader rejection of unknown versions.

GO-PLAT-001 Isolate platform behavior and fail safely

Isolate platform-dependent behavior using build constraints or platform files with an explicit unsupported fallback. Unsupported security behavior fails closed.

Rationale. unsafe, raw syscalls and CGO require a documented threat model, supported target matrix and dedicated tests. An unsupported platform does not justify silently weakening protection.

Review criterion. Check platform separation, the explicit fallback and closed failure of security operations; for unsafe, syscalls and CGO, check the threat model, target matrix and dedicated tests.

A testable CLI process boundary

Process startup, cancellation and exit remain separate from behavior exercised through explicit inputs and outputs.

GO-CLI-001 Keep process control in main

Implement CLI behavior in a testable runner accepting explicit streams, arguments, environment/configuration and context. main creates the root context, normally using signal.NotifyContext for interrupt and termination signals, and passes it down. Every blocking or I/O operation below main accepts that context instead of creating context.Background().

Rationale. main maps errors to stable exit codes and owns os.Exit; libraries do not terminate the process. Reserve stdout for promised machine/user output and stderr for diagnostics. Help, JSON and error behavior have contract tests wherever consumers depend on them.

Review criterion. Check the runner through explicit inputs and streams, propagation of root cancellation to I/O, stable codes and sole ownership of os.Exit. Check stdout/stderr separation and contract tests for help, JSON and errors where consumers depend on them.

A read-only runner without global inputs

The example borrows output streams, takes captured arguments/environment and a required named function port, and reuses the earlier settings parser. It checks text/JSON/help, cancellation, safe diagnostics and output failures. The command consumes no stdin and performs no mutations. This is not an executable main or backend adapter: signal handling, real process exit, storage/migrations and platform guarantees need their own implementation and tests. Callbacks/writers must cooperate; timeout cannot forcibly interrupt them. A failed write may already be partially visible and is never retried.

// Package readycli models a read-only CLI runner with explicit dependencies.
// It creates no process context, reads no ambient environment and never exits.
package readycli

import (
	"context"
	"errors"
	"fmt"
	"io"

	"example.org/go-public/settings"
)

// ErrUsage identifies unsupported arguments or invalid owned configuration.
var ErrUsage = errors.New("invalid command or configuration")

// ErrDependency rejects missing runner dependencies, including its zero value.
var ErrDependency = errors.New("missing runner dependency")

// ErrOperation identifies a failed observation without exposing its raw cause.
var ErrOperation = errors.New("observation failed")

// ErrOutput identifies failed, short or over-budget output.
var ErrOutput = errors.New("command output failed")

// CountReady is the consumer's semantic seam for one read-only observation.
// Implementations must honor context, return a count in [0,1000000], and never
// perform mutations. A deadline cannot forcibly interrupt arbitrary Go code.
type CountReady func(context.Context) (int, error)

// Runner owns a required observation function, not its backend or process lifecycle.
// No constructor I/O occurs; the zero value is explicitly invalid.
type Runner struct {
	// count is supplied by composition, never selected through a service locator.
	count CountReady
}

// New rejects a missing callback without consulting process-global state.
func New(count CountReady) (Runner, error) {
	if count == nil {
		return Runner{}, ErrDependency
	}
	return Runner{count: count}, nil
}

// problem keeps diagnostic identity local while exposing only a fixed safe kind.
type problem struct {
	// kind is one of this package's static sentinel errors.
	kind error
	// cause may contain private adapter details and must not cross a public boundary.
	cause error
}

// Error returns safe text; it never concatenates an adapter's raw message.
func (failure problem) Error() string { return failure.kind.Error() }

// Unwrap retains both classifications for local errors.Is/errors.As only.
func (failure problem) Unwrap() []error { return []error{failure.kind, failure.cause} }

// writeAll rejects a broken short writer instead of accepting incomplete output.
func writeAll(destination io.Writer, text string) error {
	written, err := io.WriteString(destination, text)
	if err != nil {
		return problem{kind: ErrOutput, cause: err}
	}
	if written != len(text) {
		return problem{kind: ErrOutput, cause: io.ErrShortWrite}
	}
	return nil
}

// diagnose writes one fixed public message and preserves consequential stream errors.
func diagnose(stderr io.Writer, failure error) error {
	if err := writeAll(stderr, failure.Error()+"\n"); err != nil {
		return errors.Join(failure, err)
	}
	return failure
}

// Run accepts argument and environment snapshots plus borrowed output streams.
// The command consumes no stdin. Only --help or --json is accepted; default is text.
// Help bypasses operation configuration. Other paths use the existing settings
// parser and check cancellation before output or work. Streams/callbacks must
// cooperate with context; Run owns no stream Close or asynchronous worker.
func (runner Runner) Run(ctx context.Context, args, environment []string, stdout, stderr io.Writer) error {
	if runner.count == nil || stdout == nil || stderr == nil {
		return ErrDependency
	}
	if err := ctx.Err(); err != nil {
		return diagnose(stderr, problem{kind: ErrOperation, cause: err})
	}
	if len(args) > 1 || (len(args) == 1 && args[0] != "--json" && args[0] != "--help") {
		return diagnose(stderr, ErrUsage)
	}
	if len(args) == 1 && args[0] == "--help" {
		return writeAll(stdout, "usage: ready [--json | --help]\n")
	}
	limits, err := settings.Parse(environment)
	if err != nil {
		return diagnose(stderr, problem{kind: ErrUsage, cause: err})
	}
	operation, cancel := context.WithTimeout(ctx, limits.Timeout)
	defer cancel()
	count, err := runner.count(operation)
	if err != nil {
		return diagnose(stderr, problem{kind: ErrOperation, cause: err})
	}
	if err := operation.Err(); err != nil {
		return diagnose(stderr, problem{kind: ErrOperation, cause: err})
	}
	if count < 0 || count > 1000000 {
		return diagnose(stderr, ErrOperation)
	}
	output := fmt.Sprintf("%d\n", count)
	if len(args) == 1 {
		output = fmt.Sprintf("{\"ready\":%d}\n", count)
	}
	if len(output) > limits.MaxBytes {
		return diagnose(stderr, ErrOutput)
	}
	if err := writeAll(stdout, output); err != nil {
		// Output may already be partially visible. Do not retry or claim rollback.
		return diagnose(stderr, err)
	}
	return nil
}

// ExitCode is a pure example mapping used by a composing main before os.Exit.
// Output failure takes precedence, then usage, then cancellation; all other errors
// map to 1. This command has no mutating or partial-result operation.
func ExitCode(err error) int {
	switch {
	case err == nil:
		return 0
	case errors.Is(err, ErrOutput):
		return 1
	case errors.Is(err, ErrUsage):
		return 2
	case errors.Is(err, context.Canceled), errors.Is(err, context.DeadlineExceeded):
		return 130
	default:
		return 1
	}
}
Read the example and tests
package readycli

import (
	"bytes"
	"context"
	"errors"
	"io"
	"strings"
	"testing"
	"testing/synctest"
	"time"

	"example.org/go-public/settings"
)

// requestKey isolates caller-owned metadata in the context propagation test.
type requestKey struct{}

// TestOutputContracts verifies literal text/JSON/help and borrowed-stream behavior.
func TestOutputContracts(t *testing.T) {
	cases := []struct {
		name     string
		args     []string
		want     string
		observes bool
	}{
		{"text", nil, "7\n", true},
		{"json", []string{"--json"}, "{\"ready\":7}\n", true},
		{"help", []string{"--help"}, "usage: ready [--json | --help]\n", false},
	}
	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			called := false
			var observed context.Context
			runner, err := New(func(ctx context.Context) (int, error) {
				called = true
				observed = ctx
				if _, ok := ctx.Deadline(); !ok || ctx.Value(requestKey{}) != "request-1" {
					t.Fatal("context deadline or metadata lost")
				}
				return 7, nil
			})
			if err != nil || called {
				t.Fatal("construction performed work")
			}
			var stdout, stderr bytes.Buffer
			ctx := context.WithValue(t.Context(), requestKey{}, "request-1")
			err = runner.Run(ctx, tc.args, nil, &stdout, &stderr)
			if err != nil || ExitCode(err) != 0 || stdout.String() != tc.want || stderr.Len() != 0 ||
				called != tc.observes {
				t.Fatalf("unexpected result: %q %q %v", stdout.String(), stderr.String(), err)
			}
			if observed != nil && !errors.Is(observed.Err(), context.Canceled) {
				t.Fatal("operation cancel leaked")
			}
			// The caller still owns and can use the borrowed buffer after Run.
			stdout.WriteString("caller")
		})
	}
}

// TestRejectsBeforeObservation proves usage/configuration validation has no adapter effects.
func TestRejectsBeforeObservation(t *testing.T) {
	runner, err := New(func(context.Context) (int, error) {
		t.Fatal("invalid input reached observation")
		return 0, nil
	})
	if err != nil {
		t.Fatal(err)
	}
	cases := []struct{ args, environment []string }{
		{args: []string{"--unknown"}}, {args: []string{"--json", "extra"}},
		{environment: []string{"DEMO_UNKNOWN=1"}},
		{environment: []string{"DEMO_TIMEOUT=0s"}},
		{environment: []string{"DEMO_MAX_BYTES=2", "DEMO_MAX_BYTES=3"}},
	}
	for _, tc := range cases {
		var stdout, stderr bytes.Buffer
		err := runner.Run(t.Context(), tc.args, tc.environment, &stdout, &stderr)
		if !errors.Is(err, ErrUsage) || ExitCode(err) != 2 || stdout.Len() != 0 ||
			stderr.String() != "invalid command or configuration\n" {
			t.Fatal("invalid usage contract")
		}
	}
	// Help is self-contained even when the operation's environment is invalid.
	var stdout, stderr bytes.Buffer
	if err := runner.Run(t.Context(), []string{"--help"}, []string{"DEMO_TIMEOUT=0s"}, &stdout, &stderr); err != nil {
		t.Fatal(err)
	}
}

// TestPrivateFailureAndCancellation keeps identity local and output free of raw adapter data.
func TestPrivateFailureAndCancellation(t *testing.T) {
	private := errors.New("fictional-private-payload")
	runner, err := New(func(context.Context) (int, error) { return 0, private })
	if err != nil {
		t.Fatal(err)
	}
	var stdout, stderr bytes.Buffer
	err = runner.Run(t.Context(), nil, nil, &stdout, &stderr)
	if !errors.Is(err, private) || !errors.Is(err, ErrOperation) || ExitCode(err) != 1 || stdout.Len() != 0 ||
		stderr.String() != "observation failed\n" || strings.Contains(err.Error(), "fictional-private") {
		t.Fatal("failure leaked details or lost local identity")
	}
	for _, during := range []bool{false, true} {
		ctx, cancel := context.WithCancel(t.Context())
		called := false
		if !during {
			cancel()
		}
		runner, err := New(func(context.Context) (int, error) {
			called = true
			cancel()
			return 7, nil
		})
		if err != nil {
			t.Fatal(err)
		}
		stdout.Reset()
		stderr.Reset()
		err = runner.Run(ctx, nil, nil, &stdout, &stderr)
		cancel()
		if !errors.Is(err, context.Canceled) || ExitCode(err) != 130 || stdout.Len() != 0 || called != during {
			t.Fatal("cancellation produced successful output")
		}
	}
}

// brokenWriter reports either a raw failure or an invalid short success to the runner.
type brokenWriter struct {
	// cause is fictional diagnostic data; nil simulates a short write without an error.
	cause error
}

// Write is exercised by TestStreamFailuresAndBudgets; it never accepts complete output.
func (writer brokenWriter) Write([]byte) (int, error) { return 0, writer.cause }

// TestStreamFailuresAndBudgets verifies short writes, output budgets and failed diagnostics.
func TestStreamFailuresAndBudgets(t *testing.T) {
	private := errors.New("fictional-private-writer")
	runner, err := New(func(context.Context) (int, error) { return 7, nil })
	if err != nil {
		t.Fatal(err)
	}
	for _, cause := range []error{nil, private} {
		var stderr bytes.Buffer
		err := runner.Run(t.Context(), []string{"--json"}, nil, brokenWriter{cause: cause}, &stderr)
		want := cause
		if want == nil {
			want = io.ErrShortWrite
		}
		if !errors.Is(err, want) || !errors.Is(err, ErrOutput) || ExitCode(err) != 1 ||
			stderr.String() != "command output failed\n" || strings.Contains(err.Error(), "fictional-private") {
			t.Fatal("stream failure lost or leaked")
		}
	}
	var stdout, stderr bytes.Buffer
	err = runner.Run(t.Context(), []string{"--json"}, []string{"DEMO_MAX_BYTES=1"}, &stdout, &stderr)
	if !errors.Is(err, ErrOutput) || stdout.Len() != 0 {
		t.Fatal("over-budget output started")
	}
	err = runner.Run(t.Context(), []string{"--unknown"}, nil, &stdout, brokenWriter{cause: private})
	if !errors.Is(err, private) || !errors.Is(err, ErrUsage) || !errors.Is(err, ErrOutput) || ExitCode(err) != 1 ||
		strings.Contains(err.Error(), "fictional-private") {
		t.Fatal("diagnostic stream failure lost")
	}
	if ExitCode(context.DeadlineExceeded) != 130 {
		t.Fatal("deadline exit mapping lost")
	}
}

// TestDependencyAndAdapterBounds rejects the zero value and invalid adapter results.
func TestDependencyAndAdapterBounds(t *testing.T) {
	if _, err := New(nil); !errors.Is(err, ErrDependency) {
		t.Fatal("nil dependency accepted")
	}
	var stdout, stderr bytes.Buffer
	if err := (Runner{}).Run(t.Context(), nil, nil, &stdout, &stderr); err != ErrDependency {
		t.Fatal(err)
	}
	for _, count := range []int{-1, 1000001} {
		runner, err := New(func(context.Context) (int, error) { return count, nil })
		if err != nil {
			t.Fatal(err)
		}
		if err := runner.Run(t.Context(), nil, nil, &stdout, &stderr); err != ErrOperation || stdout.Len() != 0 {
			t.Fatal("invalid adapter count became output")
		}
		if err := runner.Run(t.Context(), nil, nil, nil, &stderr); err != ErrDependency {
			t.Fatal(err)
		}
		if err := runner.Run(t.Context(), nil, nil, &stdout, nil); err != ErrDependency {
			t.Fatal(err)
		}
	}
	runner, err := New(func(context.Context) (int, error) { return 0, nil })
	if err != nil {
		t.Fatal(err)
	}
	stdout.Reset()
	stderr.Reset()
	if err := runner.Run(t.Context(), nil, nil, &stdout, &stderr); err != nil || stdout.String() != "0\n" {
		t.Fatal("valid zero count was treated as unavailable")
	}
	// The shared settings identity survives without serializing its input.
	err = runner.Run(t.Context(), nil, []string{"DEMO_TIMEOUT=invalid"}, &stdout, &stderr)
	if !errors.Is(err, settings.ErrInvalid) {
		t.Fatal("configuration error identity lost")
	}
}

// partialWriter retains a visible prefix before returning a short or failed write.
type partialWriter struct {
	// visible is an observed effect that the runner cannot roll back.
	visible bytes.Buffer
	// calls counts output attempts because no retry is a material contract.
	calls int
	// cause distinguishes a short success from a partially visible failure.
	cause error
}

// Write is exercised by TestPartialWriteIsNotRetried with and without a cause.
func (writer *partialWriter) Write(data []byte) (int, error) {
	writer.calls++
	accepted := len(data) / 2
	writer.visible.Write(data[:accepted])
	return accepted, writer.cause
}

// TestPartialWriteIsNotRetried preserves the actual visible prefix without duplication.
func TestPartialWriteIsNotRetried(t *testing.T) {
	runner, err := New(func(context.Context) (int, error) { return 7, nil })
	if err != nil {
		t.Fatal(err)
	}
	private := errors.New("fictional-private-partial-write")
	for _, cause := range []error{nil, private} {
		writer := &partialWriter{cause: cause}
		var stderr bytes.Buffer
		err := runner.Run(t.Context(), []string{"--json"}, nil, writer, &stderr)
		wantCause := cause
		if wantCause == nil {
			wantCause = io.ErrShortWrite
		}
		if !errors.Is(err, wantCause) || ExitCode(err) != 1 || writer.calls != 1 ||
			writer.visible.String() != "{\"read" || stderr.String() != "command output failed\n" ||
			strings.Contains(err.Error(), "fictional-private") {
			t.Fatal("partial output was retried, lost or leaked")
		}
	}
}

// TestConfiguredTimeout uses fake time, not sleep, to expire the selected operation budget.
func TestConfiguredTimeout(t *testing.T) {
	synctest.Test(t, func(t *testing.T) {
		started := time.Now()
		runner, err := New(func(ctx context.Context) (int, error) {
			<-ctx.Done()
			return 0, ctx.Err()
		})
		if err != nil {
			t.Fatal(err)
		}
		var stdout, stderr bytes.Buffer
		err = runner.Run(t.Context(), nil, []string{"DEMO_TIMEOUT=3s"}, &stdout, &stderr)
		if !errors.Is(err, context.DeadlineExceeded) || ExitCode(err) != 130 || stdout.Len() != 0 ||
			stderr.String() != "observation failed\n" || time.Since(started) != 3*time.Second {
			t.Fatal("configured timeout did not stop observation without successful output")
		}
	})
}

Sources, scope and tooling

Before changing code, identify source ownership, task boundaries and a reproducible tooling policy.

GO-SCOPE-001 Separate the generic minimum from repository profiles

Apply reusable Go engineering minima. Canonical-byte formats, fail-closed authority documents, private POSIX modes, descriptor-pinned paths, crash-durable publication, no-replace behavior, multi-file transactions, dispatcher locks and platform-specific syscalls apply only where the package owns that boundary and an accepted repository contract or threat model activates the profile.

Rationale. Exact product, operating-system and deployment mechanics belong to repository overlays. Their contribution to this standard does not make them mandatory architecture for an ordinary service or library.

Verification criterion. For each specialized requirement, identify the boundary owner and accepted contract or threat model activating its profile; distinguish generic minima from repository overlays.

GO-SCOPE-002 Identify tracked scope before editing

Before changing code, identify tracked Go files, module and workspace files, generators and CI configuration. Read exact repository instructions and executable local configuration first.

Rationale. Third-party vendor, generated build output and runtime state are not handwritten source. Checked-in dependencies are governed by dependency integrity; local style remediation applies when the repository explicitly owns the fork. Generated Go remains subject to formatting and safe generation; documentation findings may be classified separately when a schema or generator is the canonical source.

Verification criterion. Compare the Git-tracked inventory with instructions and configuration; justify exclusions and establish ownership of each fork.

GO-SCOPE-003 Keep changes within their agreed scope

Every changed Go file must satisfy the current standard; format the complete changed Go scope. Broader cleanup requires explicit task scope.

Rationale. The standard does not authorize unrelated mass reformatting. Preserve the owner’s dirty work and keep broader cleanup reviewably separate from behavior changes.

Verification criterion. Review the complete changed Go scope, task boundaries, preservation of unrelated work and separation of behavior changes from broader cleanup.

GO-TOOL-001 Record the actual toolchain identity

The go directive defines the module language and compatibility line, not an exact patch-level security or CI pin. Verification records go env GOVERSION, GOMOD, GOWORK, the proven module root and selected toolchain policy.

Rationale. Protected-branch and release builds use an accepted, patched, explicitly selected toolchain. Install it deliberately and use GOTOOLCHAIN=local in controlled lanes unless the repository documents an equivalent reviewed policy. An unsupported toolchain requires an owner, reason and upgrade deadline.

Verification criterion. Compare the actual version, root, module and workspace with the accepted policy; verify deliberate selection of a patched toolchain and the conditions of every exception.

Formatting and text hygiene

Automated formatting governs file bytes; verification also covers repository text, tool status and imports.

GO-TEXT-001 Keep all tracked text clean

Tracked source, module, schema, workflow and documentation text uses LF, has no trailing whitespace and ends with exactly one LF. An exception requires an explicit binary or protocol format requirement.

Rationale. Checking changed lines alone does not prove repository hygiene: inspect all tracked text. git diff --check remains required for the current patch.

Verification criterion. Inspect all tracked text files for LF, trailing whitespace and exactly one final LF; separately check the current patch and the justification for format exceptions.

GO-FMT-001 Treat gofmt as authoritative

Every tracked Go file must be byte-clean after the repository-supported gofmt. Manual alignment and personal editor output do not override it.

Rationale. Run the gate from the proven module repository root. Generated or vendored path exclusions require an explicit, reviewed mechanism owned by the repository. A nonzero gofmt status and nonempty file-list output are separate failures; testing for empty output must not hide tool execution status.

Verification criterion. Verify the root, supported gofmt and reviewed exclusions; require both successful tool execution and an empty list of files needing formatting.

GO-IMP-001 Manage imports with Go tooling

Imports follow gofmt. A repository may require a pinned goimports version to add or remove imports and separate standard-library, third-party and local groups.

Rationale. Dot imports are prohibited except for a narrowly justified test compatibility case. Blank imports are allowed for deliberate side-effect registration; their purpose must be discoverable when package documentation does not make it obvious. Aliases resolve real collisions or clarify misleading package names only. Ordering by path length is prohibited. Pin goimports or any other external tool; @latest is not a reproducible gate.

Verification criterion. Check formatting and accepted groups, justified exceptions and aliases, discoverable side-effect purposes and the exact external-tool version.

What gofmt actually changes

This declaration-only excerpt shows formatting by the selected Go toolchain. Internal names, explicit state tokens and private fields are deliberate design choices; gofmt does not validate them. Compilation of declarations is not a behavior test or full conformance evidence.

Read the unformatted excerpt
// Package observation is a declaration-only formatting illustration.
package observation

// phase has explicit tokens rather than externally unstable numeric ordinals.
type phase string

const(
// phasePending means a result has not been observed.
phasePending phase="pending"
// phaseReady means a result has been observed.
phaseReady phase="ready"
)

// observation keeps internal fields private; it is not a serialization contract.
type observation struct{
// sourceID names the source without duplicating package context.
sourceID string
// phase expresses one named state instead of several contradictory booleans.
phase phase
}

After gofmt

// Package observation is a declaration-only formatting illustration.
package observation

// phase has explicit tokens rather than externally unstable numeric ordinals.
type phase string

const (
	// phasePending means a result has not been observed.
	phasePending phase = "pending"
	// phaseReady means a result has been observed.
	phaseReady phase = "ready"
)

// observation keeps internal fields private; it is not a serialization contract.
type observation struct {
	// sourceID names the source without duplicating package context.
	sourceID string
	// phase expresses one named state instead of several contradictory booleans.
	phase phase
}
What each check establishes
Check Checks Boundary
gofmt Formatting produced by the selected toolchain. Both tool failure and non-empty -l output must fail the gate. Does not establish names, API design or ownership.
Tracked-text gate LF, no trailing whitespace and one final LF across tracked text, with explicit format exceptions. A clean changed-line diff is not evidence for the whole tracked tree.
go vet composites Supporting detection of unkeyed literals of imported struct types. Does not replace review of local literals, names or declaration readability.
Semantic review Names, exports, compatibility, receiver strategy and data ownership. Record scope and evidence; formatter success does not replace this review.

Names, visibility and ownership

Names explain domain meaning; exports and mutation define deliberate contracts between packages.

GO-NAME-001 Choose meaningful, idiomatic names

Names communicate domain meaning without repeating package context. Package names are short, lower-case and singular where practical; dumping grounds such as util, common and misc are prohibited, with the full basename list defined by GO-PKG-002. Initialisms retain stable Go casing: ID, URL, HTTP, JSON and API.

Rationale. Getters normally omit Get; setters and mutations make their action explicit. Receiver names are short and stable for their type, never this or self. Boolean names describe a state or predicate; a cluster encoding a state machine becomes a named type. Wire values are explicit: unstable iota ordinals must not become durable or external values.

Verification criterion. Review naming context, package names, initialism casing, mutation actions, consistent receiver names, boolean-state models and explicit external values.

GO-NAME-002 Make declarations and literals readable

Struct composite literals use keyed fields. Positional literals are limited to small local value types whose field order is part of their meaning, such as a coordinate pair. Declare one struct field per line unless fields form an inseparable group such as coordinates X and Y of the same type.

Rationale. Single-letter names are limited to receivers, short loop indices and very small scopes with obvious meaning; parameters, results and package-level identifiers use descriptive names. Conventional short standard-library roles w, r, t, b, tb, ctx, err and ok are allowed. Break long expressions, calls and literals at semantic boundaries; there is no fixed line-length limit. gofmt governs layout rather than readability.

Verification criterion. Review keys and the qualified positional exception, field declarations, naming and semantic line breaks. go vet composites supports review by flagging unkeyed literals of imported struct types; the remaining requirements need review.

GO-VIS-001 Keep identifiers unexported by default

Every exported identifier is a deliberate cross-package contract; export only what a real consumer needs. Do not export fields merely for tests or JSON encoding: use a boundary DTO when serialization is the actual contract.

Rationale. New exports require documentation under GO-DOC-002 and compatibility review. Removing, renaming or changing an export requires consumer discovery and migration evidence.

Verification criterion. Establish each export’s real consumer, contract need, documentation and compatibility; check consumer discovery and migration evidence for changed contracts.

GO-VIS-002 Keep receivers and mutation boundaries consistent

A type uses a deliberate receiver strategy. Do not mix pointer and value receivers without a semantic reason; types containing locks or non-copyable state must not be copied.

Rationale. Maps, slices and pointers crossing an API boundary require explicit ownership. Use defensive copies when callers must not mutate internal state.

Verification criterion. Review receiver strategy and reasons for mixing, absence of copied locks or non-copyable state, ownership of shared data and defensive copies at the required boundaries.

Exact source and isolated tests

Prove which source runs and keep tests independent of ambient state.

GO-TST-001 Prove every module under test

Inventory every tracked go.mod before selecting modules; testing one module does not cover nested modules. Builds and tests must use the intended working-tree module rather than an ambient workspace or installed copy. Set GOWORK=off, use -mod=readonly, verify go env GOMOD and prove that every listed package directory stays below the repository root.

Rationale. Run the reference module inventory and source proof separately for every tracked module. An empty package inventory fails; a deliberate schema-only module needs a documented scoped replacement gate. An intentional go.work setup requires an equally explicit accepted workspace proof.

Verification criterion. Preserve any go list producer failure; a loop or pipeline must not replace it with success. Reject missing tracked paths and symlinks without repository-owned policy. Record module lanes as not-applicable only for a documentation-only repository; a product must cover its nested modules.

GO-TST-002 Assert behavior and failure contracts

Changed behavior needs unit or contract coverage for valid, invalid, failure, boundary and compatibility paths.

Rationale. Prefer table-driven tests when they clarify the contract; tables are not a mechanical requirement. Assertions prove semantic results and error identity, rather than incidental full error strings or implementation call counts unless those form the contract.

Verification criterion. Compare the changed contract with its cases and meaningful assertions; verify that each applicable path has coverage.

GO-TST-003 Keep tests hermetic and deterministic

Tests must not depend on the real home directory, credentials, external network, wall clock, global environment, execution order or mutable state owned by another package. Parallel tests own isolated state.

Rationale. Use t.TempDir, t.Setenv and t.Cleanup, with injected time and randomness. Disposable isolated inputs make outcomes reproducible without reading real credentials or contacting production dependencies.

Verification criterion. Inspect test inputs, cleanup and parallel state ownership; verify that environmental and timing dependencies are controlled.

Prove the working-tree module

Reference POSIX shell fragment for one ordinary module, after selecting the pinned Go binary. It rejects an unexpected module, an empty package list and directories outside the root, preserving go list failure. Inventory every tracked nested module separately; an accepted workspace or schema-only policy needs its own proof.

Read the reference commands
set -eu
export GOENV=off GOWORK=off GOTOOLCHAIN=local GOFLAGS=

root="$(pwd -P)"
test "$(go env GOMOD)" = "$root/go.mod"

package_dirs="$(mktemp)"
trap 'rm -f "$package_dirs"' 0
if go list -mod=readonly -f '{{.Dir}}' ./... >"$package_dirs"; then
    :
else
    go_list_status=$?
    exit "$go_list_status"
fi

test -s "$package_dirs"
while IFS= read -r dir; do
    case "$dir" in
        "$root"|"$root"/*) ;;
        *)
            printf 'package outside working tree: %s\n' "$dir" >&2
            exit 1
            ;;
    esac
done <"$package_dirs"

Testing and bounded evidence

Assertions and declared verification lanes establish the guarantees each result can support.

GO-TST-004 Exercise adversarial, race and fuzz paths

Concurrency and durable-state code covers cancellation, race-relevant paths, interruption, tampering and idempotent retry. Parsers, canonicalizers, path guards and decoders should have seed corpora and bounded fuzz lanes wherever malformed input is meaningful.

Rationale. Normal go test runs committed fuzz seeds. Active fuzzing is a separate time-bounded lane; retain minimized regressions. A departure from the seed/fuzz expectation needs a recorded reason.

Verification criterion. Review the adversarial scenarios and retained seeds. Declare race eligibility and supply an eligible race lane for concurrency-sensitive code; retain separate outcomes for normal seed execution and bounded active fuzzing.

GO-TST-005 Limit claims to demonstrated guarantees

A fake adapter proves application behavior against that fake; it does not prove production kernel, filesystem, network or privileged runtime guarantees. Record a required unavailable lane as unavailable, never as passed.

Rationale. An end-to-end label does not itself establish real production dependency semantics or runtime readiness. Verification, conformance, acceptance, release and runtime readiness remain separate conclusions.

Verification criterion. Match every claim to its actual commands, inputs, versions and terminal outcomes. A missing runner is an enforcement gap, and skipped tests cannot supply required evidence.

GO-TST-006 Give every function an owning test

Every handwritten function and method, exported or unexported, must be executed and asserted by at least one owning test, normally in the same package so private code is reachable. A function reached only through a higher-level test names that test in its doc comment.

Rationale. Use a coverage profile and the per-function coverage report to require no function at 0.0%, except generated files and documented exclusions. The total percentage supports the evidence; it does not replace this gate or meaningful assertions.

Verification criterion. Inventory functions, verify their owning assertions and higher-level test references, and run the zero-coverage function gate. The consumer supplies this gate; reference helpers do not implement it.

GO-TST-007 Assert every material outcome

Give each applicable material outcome its own assertion or table row: success, empty, boundary and maximum, invalid input, each GO-ERR-005 failure class, cancellation, duplicate or replayed input, lease loss, malformed upstream response and redaction.

Rationale. Statement coverage does not prove branch coverage. An executed line without an assertion for its material outcome does not establish the contract.

Verification criterion. Review the outcome list against the actual code and owning assertions. Supply a consumer-owned outcome check; neither total coverage nor reference helpers prove this requirement.

GO-TST-008 Verify real dependency semantics on scratch instances

When a package relies on atomicity, ordering, locking or transaction semantics of an external store, queue or service, it needs an integration lane against the production engine type. Run it behind a build tag or explicit switch on an empty scratch instance.

Rationale. Clean the scratch instance and verify its state afterwards. A fake or a skipped integration test does not establish this lane; production data and credentials are not test inputs.

Verification criterion. Verify engine identity, explicit activation, empty initial state, semantic assertions and verified cleanup. The consumer supplies the real-engine lane; an unavailable required lane remains unavailable.

CI and exact verification evidence

Declare applicable lanes and bind each result to the exact inputs it checks. Commands described here are requirements, not records of execution.

GO-CI-001 Run the complete deterministic baseline

Inventory every tracked go.mod and prove the intended working-tree module in each: GOWORK=off, -mod=readonly, matching go env GOMOD and package directories within the repository. Run module-local lanes in every inventoried module. Export GOENV=off GOWORK=off GOTOOLCHAIN=local GOFLAGS= GOPROXY=off GOSUMDB=off in the parent process for every command and analyzer, or apply the controlled run wrapper separately to every executable. Select pinned binaries explicitly.

Rationale. The baseline covers tracked text, module inventory and exact source proof, gofmt, module integrity and non-mutating tidy comparison, go test -mod=readonly -count=1 ./..., go vet -mod=readonly ./..., deterministic go test -mod=readonly -shuffle=20260713 -count=1 ./..., pinned staticcheck and govulncheck. Architecture and documentation tests run in the normal test lanes. Preserve command failures, including a failed package-list producer. Check proposed-diff whitespace using git diff --check against the verified review-system base with the base...HEAD range; unresolved base or head fails closed. Never infer the base from HEAD^; staged and worktree checks are additional evidence.

Verification criterion. Declare race eligibility for the pinned toolchain and GOOS/GOARCH: supported platform, CGO_ENABLED=1 and a usable C compiler are required. A newer or unknown toolchain requires support-matrix review. Unsupported is not-applicable, never pass; unusable CGO/compiler is unavailable, never not-applicable. Concurrency-sensitive code needs an eligible race lane or an explicit blocker or accepted scoped waiver. Build every supported target to a temporary path with explicit CGO policy and -trimpath; add platform, integration, bounded fuzz and security lanes for owned boundaries. Use go mod tidy -diff where available; otherwise tidy a temporary -modfile and byte-compare without writing to the checkout.

GO-CI-002 Pin the toolchain, analyzers and generators

Pin the accepted patch-level Go toolchain and every external analyzer and generator; reproducible lanes use GOTOOLCHAIN=local. Floating container tags, implicit host tools and go install ...@latest are prohibited evidence.

Rationale. The required baseline includes go vet, pinned staticcheck and govulncheck, and package-organization/documentation architecture tests. Pin analyzer tools in a separate tools module or as digested binaries; list their modules in a separate tools allowlist section, outside the product module graph. An optional aggregating linter must not replace or silence baseline checks; ignored-error analysis is recommended.

Verification criterion. Run hermetic checks with GOPROXY=off using a module cache or vendor directory populated and verified in a separate preceding step. Controlled lanes download neither tools nor toolchains. Configure govulncheck with a pinned, digested offline database, or declare a separate non-hermetic lane recording the database timestamp.

GO-CI-003 Harden automation

CI automation uses least privileges, explicit job timeouts and immutable full-commit action pins. Privileged secrets must not reach untrusted pull-request code.

Rationale. Cache keys include every input affecting correctness. A cache hit is never a substitute for a required check.

Verification criterion. Review permissions, timeouts, full pins, trust boundaries and cache inputs in the actual CI configuration.

GO-CI-004 Record exact evidence

Each lane records exact HEAD, index/worktree state or digest including required untracked inputs, command, Go/tool versions and terminal result. Record repository identity, verified review base, tracked modules, target matrix and dependency/database snapshot identities for admission.

Rationale. Missing, skipped, unavailable and passed are distinct. Evidence from another revision cannot be presented as current; probes use disposable isolation without real credentials or production dependencies in hermetic lanes.

Verification criterion. Retain lane inputs and outcomes. Use pass, confirmed-fail, candidate-review, not-applicable, unavailable or waived; a waiver names the rule, scope, revision, owner, reason and expiry or review trigger. An absent checker is an enforcement gap; a heuristic candidate needs contextual review.

GO-CI-005 Declare every verification lane

Declare every lane as required, conditional with its trigger, not_applicable with its reason, or forbidden.

Rationale. Silence does not establish non-applicability. A conditional lane with an active trigger cannot be declared not_applicable; missing runners are enforcement gaps, not implicit waivers.

Verification criterion. Compare the complete lane inventory with owned boundaries, including generation, coverage and material outcomes, real-engine scratch integration, fuzz, platform and security checks. Record explicit blockers or accepted scoped waivers for unmet obligations.

GO-CI-006 Keep freshness and lifecycle states separate

A result is valid only for its exact HEAD, index and worktree inputs. A change to an actual input of that lane makes its result stale.

Rationale. A documented command is not an executed result. Standard conformance, revision verification, owner acceptance, release and production readiness are separate states.

Verification criterion. Review the final task-owned diff before final gates; rerun only lanes invalidated by changed actual inputs or unresolved failure. Retain valid evidence and report each lifecycle state separately.

The baseline is a declared program

Reference commands require repository-owned helpers, pinned Go/analyzers, verified dependencies, a verified PR_BASE_SHA and the selected vulnerability database. These commands describe lanes to implement and execute; they are not results for this page or any product. Repeat module-local checks for every inventoried module, and add applicable race, integration, fuzz, generation and target-build lanes.

Read the reference commands
set -eu
# Select pinned binaries and prepare verified dependencies first.
export GOENV=off GOWORK=off GOTOOLCHAIN=local GOFLAGS= GOPROXY=off GOSUMDB=off

python3 scripts/repository-gates.py text
python3 scripts/repository-gates.py modules
scripts/go-quality-gates.sh gofmt .
scripts/go-quality-gates.sh go-list "$(pwd -P)" ./...
scripts/go-quality-gates.sh whitespace "$PR_BASE_SHA" HEAD
go mod verify
go test -mod=readonly -count=1 ./...
go vet -mod=readonly ./...
go test -mod=readonly -shuffle=20260713 -count=1 ./...
staticcheck ./...
govulncheck ./...

A denotes deterministic automation, S a pinned static or semantic checker, T tests and R recorded semantic review. A missing checker is an enforcement gap. A heuristic candidate needs review before it becomes a confirmed finding.

When a lane applies
State Meaning Required evidence
required Required for the declared scope. A current result; absence does not satisfy the obligation.
conditional Required when its declared trigger is present. Record the trigger and decision; an active trigger cannot become not-applicable.
not_applicable The declared boundary or trigger is absent. Record the reason and exact scope.
forbidden The lane is prohibited for this context. Record the constraint and do not execute it in that context.
How a result is reported
State Meaning Required evidence
pass The executed check passed for the recorded inputs. Command, exact source state, tool versions and terminal outcome.
confirmed-fail A failure is established in the reviewed context. Reproducible failure and the applicable requirement.
candidate-review A possible finding still needs context review. Candidate evidence; no confirmed-failure claim yet.
not-applicable Applicability was reviewed and the lane does not apply. Explicit reason for the exact revision and boundary.
unavailable A needed lane could not run or produce evidence. Blocking condition; neither pass nor not-applicable.
waived An explicit scoped waiver was accepted. Exact rule, scope, revision, owner, reason and expiry or review trigger.

Deliberate dependencies

Dependency admission covers the complete graph and remains distinct from tool provisioning.

GO-DEP-001 Admit dependencies through a closed allowlist

Use the standard library by default. Admit third-party modules only through a tracked, machine-readable, repository-local closed allowlist checked against the complete go list -m all graph; any unlisted module fails the gate.

Rationale. Every entry records purpose, why the standard library is insufficient, exact version, license, reviewed transitive dependencies and the govulncheck result. Direct requirements alone do not describe the full dependency graph.

Verification criterion. Compare all graph modules with the allowlist and review every required field. Prefer the standard library when sufficient, while avoiding reimplementation of security-sensitive primitives or complex protocols with an existing reviewed client.

GO-DEP-002 Verify module integrity

Keep go.mod and go.sum tidy and verified. Builds and tests use -mod=readonly. Committed local replace directives, unexplained dependency drift, floating tool versions and unreviewed retractions are prohibited.

Rationale. Integrity and tidy checks must expose drift without modifying the checkout merely to inspect it. Dependency and vulnerability evidence is refreshed before release.

Verification criterion. Run module verification and non-mutating tidy comparison in every inventoried module; review replacements, versions, retractions and graph changes. Use a temporary -modfile and byte comparison where tidy -diff is unavailable.

Owned generation and reproducible builds

Generated artifacts and build inputs have explicit owners, versions and reproducibility checks.

GO-GEN-001 Own generated source

Generated Go carries the canonical // Code generated … DO NOT EDIT. marker, a tracked source, a documented owner and a pinned generator/version.

Rationale. Generated output is not manually patched; corrections belong in its owned source or generator.

Verification criterion. Check the canonical marker, source tracking, ownership and exact generator pin, and review changes at their source.

GO-GEN-002 Regenerate to zero diff

Approved generation in a clean isolated checkout produces zero diff. Validate schema, examples, generated source and compatibility fixtures together; none contains private data.

Rationale. Isolated regeneration proves that committed output follows the approved inputs and pinned generator rather than an undocumented local edit.

Verification criterion. Regenerate from the declared clean inputs, compare all resulting artifacts and require zero diff; validate related fixtures and inspect for private data.

GO-BLD-001 Build with explicit targets and clean outputs

Do not commit build output, coverage files, runtime state or temporary state. Declare the supported target matrix and CGO policy. Release builds use -trimpath and deliberate version metadata.

Rationale. Builds must not depend on ambient workspaces or developer paths. Every supported target is built with its declared CGO policy to temporary output.

Verification criterion. Inspect tracked files and build inputs, verify every declared target and metadata policy, and establish isolation from ambient workspaces and machine paths.

Acceptance criteria

  • Every package has one explainable responsibility, with its contract, implementation and tests kept together.
  • Imports follow the documented dependency direction; reusable capabilities have an identified owner.
  • cmd keeps composition and routing; the operation can be tested without launching the CLI.
  • The architecture check detects a deliberate violation in a fixture and ties its diagnostic to a specific rule.
  • Documentation states input invariants, zero-value behavior, ownership and responsibility boundaries; significant changes retain compatibility evidence.
  • Tests exercise input and output copies, invalid inputs and the zero value. An executable example shows the expected consumer result.
  • Errors retain identity through errors.Is/errors.As; consequential finalization failures are handled and public context is checked for sensitive data.
  • Reasons have a closed vocabulary and classes prescribe safe actions; cancellation and ambiguous outcomes never become blind retries.
  • Caller cancellation and deadlines reach the work; every CancelFunc is released, and necessary cleanup has its own short timeout.
  • Every goroutine has an owner and a capacity bound. Signals prove completion and partial-failure handling in tests; the race detector executes these paths.
  • The selected operation validates strict typed settings before effects. Secrets have an explicit runtime source and stay out of diagnostics and argument vectors.
  • External programs have explicit arguments, environment, cancellation and output bounds. Resources close on every path; finalization and iteration failures affect the result.
  • The caller supplies logging ownership, with contracted attributes and levels. Serialized-log checks find no fictional secret value.
  • The network profile owns its destination, deadlines, body limits and completion. Retry/coalescing applicability is explicit; server mutations are protected and bounded shutdown is tested separately.
  • Semantic identity has a versioned domain and literal byte fixtures. Input permutations preserve the digest and do not mutate the caller’s collection.
  • JSON has pre-decoding bounds, an explicit schema and null/missing/empty semantics; duplicates and a second value are rejected. Canonical round trips preserve bytes and non-success states.
  • Decoded DTOs, Evidence and Plan do not automatically become authority. Execution permission requires its own verified transition.
  • Secrets and private payloads stay out of ordinary output; input is checked before use and crypto/network policy is explicit.
  • Paths have a separate containment/identity contract; lexical names and metadata snapshots grant neither access nor cleanup permission.
  • Visibility, durability and verification are distinct. Sync/close/cleanup failures affect the result; ambiguous publication triggers neither blind retry nor destination deletion.
  • Every run declares identity, scope and budgets. Typed counts and per-unit classes keep partial and interrupted outcomes distinct from success.
  • Same-scope effects exclude overlap; stale fences and wrong-owner release fail. Durable commit precedes progress, and replay preserves last good data without duplicate effects.
  • Schedule and dry-run contracts are explicit. Deterministic failure tests cover interruption, coordination loss, replay, bad input, empty/evicted state and daylight-saving boundaries; production atomicity has its own integration evidence.
  • Dependencies are explicit and semantic ports have real consumers. Constructors are testable; extension contracts include shared conformance tests and justified implementation boundaries.
  • Each schema/namespace/format has one owner and coordinated immutable migrations. Unknown versions and unsupported security behavior fail closed.
  • The CLI runner receives explicit inputs and context. Stable output/error contracts and safe diagnostics are tested; only main owns process signals and os.Exit.
  • The changed and tracked scope is identified; product overlays activate only owned boundaries. Foreign dirty work is preserved, and broader cleanup has its own authorization.
  • The exact selected toolchain and module identity are recorded. Whole tracked-text hygiene, formatting status/output and import policy have distinct checks.
  • Names communicate domain meaning; exports have consumers and compatibility evidence. Literals, receiver strategy, non-copyable state and mutable data ownership receive semantic review.
  • Every tracked module has source proof; deterministic owning tests assert functions and material outcomes, with separate applicable race, fuzz and real-engine lanes.
  • CI declares applicability and records exact commands, inputs, tool/database identities and outcomes. Missing evidence and stale results cannot satisfy the gate.
  • The complete dependency graph is admitted explicitly; generators are owned and pinned, regeneration is reproducible, and target builds use deliberate CGO/version policy with temporary output.

The principles in practice

Author’s article

When a prototype becomes a product: an evidence matrix for one end-to-end scenario

article.solution200.com

How to connect requirements, checks and unknowns in one scenario.

Read the article — opens in a new tab