schema

package module
v0.31.0 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2026 License: Apache-2.0 Imports: 32 Imported by: 0

README

peasant-labs/schema

The canonical data / wire contract for peasant and the village transcript commons: one contract-only Go leaf module that every backend produces and every client consumes.

Use this module whenever code produces, validates, or consumes a peasant-labs wire payload. Go services import the canonical structs and validators directly; TypeScript applications import the matching generated types and Zod schemas. API-aware TypeScript tooling can additionally import type-only paths and operations contracts from @peasant-labs/schema/local-api or @peasant-labs/schema/village-api. Those subpaths describe request and response shapes; they do not perform network requests.

module github.com/peasant-labs/schema

It holds the domain + wire types, the closed-set enums, the publish/pull/push envelopes, the versioned OpenAPI specs, the publish-request validator, the typed fixtures, the generated TypeScript bindings, and the codegen + release-guard tooling. It has no service runtime: no HTTP server, WebSocket hub, transport client, or CLI product. Everything here is contract data, validators, generated specs, fixtures, and the gates that keep them honest.


Why this module exists

The peasant backend, the village backend, and their frontends all speak the same session_detail / publish / pull wire. If each side kept its own copy of those types, the copies would drift, and a silent wire mismatch between a producer and a consumer is exactly the class of bug that is expensive to find.

This module is the single source of truth for that wire. It was extracted from peasant's old nested pkg/schema into a standalone, public, versioned Go module so that:

  • One definition, many consumers. The Go types here ARE the contract. peasant emits SessionDetailPayload / PublishRequest; the village validates and stores the same shapes; the frontends render them. Nobody redefines the wire.
  • Served ≡ enforced. The village serves its OpenAPI doc from VillageAPISpecJSON(). PublishRequestSchemaJSON() and AnnotationPushRequestSchemaJSON() extract the two operation request schemas from those same embedded bytes; their canonical Go boundaries validate the documented shape before applying typed relational rules. The documented spec and the enforced schema therefore have one source artifact.
  • It stays a leaf. The module depends on nothing first-party except bestiary (a sibling), imports no runtime machinery, and a leaf-audit gate keeps its dependency set pinned. That is what lets consumers pin it cheaply (see Pinning).

The data path end-to-end: the contract defines the wire, the peasant and village backends produce it, and transcript-browser (embedded by the two frontends) renders it.

flowchart LR
    schema["schema module<br/>the wire contract"]
    peasant["peasant backend"]
    village["village backend"]
    tb["transcript-browser"]
    pweb["peasant web"]
    vfe["village frontend"]

    schema -->|defines the wire| peasant
    schema -->|defines the wire| village
    peasant -->|SessionDetailPayload| tb
    village -->|SessionDetailPayload| tb
    pweb -->|embeds| tb
    vfe -->|embeds| tb

Coordinates & status

Module path github.com/peasant-labs/schema
Default branch develop (releases are cut from it; main/tags carry the releases)
Latest tag v0.1.3-rc1 (Village collectives contract surface release candidate) - stable v0.1.2 remains published
License Apache-2.0
Spec versions Village API 0.14.0 · PublishRequest 0.14.0 · AnnotationPushRequest 0.14.0 · Local API 0.9.0 · Types 0.14.0 (see versions.go)
Consumers
Consumer Language How it pins / uses the contract
peasant (Go backend + web) Go go.mod currently requires github.com/peasant-labs/schema@v0.1.2; produces SessionDetailPayload, imports the enums, mirrors AllLicenses in its SQLite CHECKs.
village (Go backend) Go backend/go.mod currently requires github.com/peasant-labs/schema@v0.1.2; serves GET /openapi.json from VillageAPISpecJSON() and enforces inbound publishes via ValidatePublishRequest (both read the embedded spec, so served ≡ enforced).
TypeScript consumers (@peasant-labs/schema) TypeScript npm install @peasant-labs/schema (published to npm from typescript/, version tracking the module release tag) for generated named types, Zod schemas, schema-owned fixtures, and type-only Local/Village paths and operations contracts. It provides no transport client. @peasant-labs/types is deprecated and must not receive new contract definitions.

Both backends currently pin v0.1.2; their final re-pins happen in separate downstream changes after this release. Because the module is normal go get-pinned, each consumer moves independently, so they can briefly sit on different tags between re-pins; a re-pin is a one-line go.mod change plus go mod tidy.


What's in the contract

The Go source (all package schema in the repo root) is grouped by surface. Every identifier and enum below is a wire type: a JSON-tagged struct or a closed-set string newtype with IsValid() / String() / a JSONSchema() exposer and an All... canonical list.

Surface File(s) Representative types
Local dashboard / session-detail wire local_api.go SessionDetailPayload, TurnDetail, ToolCallDetail, SessionSummary, SessionScorecard, ChildSessionRef, DashboardPayload, TrendsPayload, QualityPayload, project-familiarity payloads, the WebSocket envelope (ClientMessage / ServerMessage, MessageType, ChannelTopic, ChannelSubscription), CreateAnnotationRequest/Response
Session metadata & git metadata.go UnifiedMetadata, RedactionInfo, TimestampInfo, SourceInfo, CommitInfo, GitContext, ProjectContext, SessionStats, SubagentRef, DiagnosticsInfo; the MetadataSchemaVersion constant
Content layer content.go, identity.go SessionEntry (1:1 with an indexed transcript entry), SessionIdentity
Publish envelope publish.go, publish_validate.go, annotation_push_request_validate.go PublishRequest, PublishResponse, ModelInfo; the annotation push wire (AnnotationPushItem / Request / Response), SchemaVersionResponse; ValidatePublishRequest, ValidateAnnotationPushRequest
Pull envelope pull.go TranscriptID, PullTranscriptInfo, PullListResponse, PullAnnotation
Push content envelope push_content.go TranscriptContent (self-describing, versioned blob body), ContractVersion / PushContractVersion, ContentKind
Map / Review REST map_api.go MapGraphPayload, MapNode, MapEdge, ActivityEdge, EdgeViolation, MapNodeDetailPayload, TaskSummary, CommitRef, SessionAssociation, RewrittenCommit, TimelineSessionRef, ProjectResolutionPayload, ProjectTasksPayload, ProjectSummary, ReviewListPayload, ChangeSummary, ChangeDetailPayload, ChangeDiffPayload, FrictionCluster, FileChange, DiffHunk
Search REST search_api.go SearchPayload, SearchResult
Quality metrics quality.go QualityMetrics, QualitySession (session stats + derived quality/cost signals)
Annotations annotation.go, annotation_enums.go, annotation_manifest.go, annotation_registry.go, annotation_validate.go AnnotationSummary, AnnotationTypeSummary, AnnotatorSummary, ValueDomain, Provenance, TaxonomyNode, batch request/response types; the enums AnnotatorKind, AnnotationStatus, TargetKind, ScaleKind, ValueDomainKind, AnnotationDatatype, TypeOrigin
Identifiers & enums types.go Validated newtypes SessionID, ModelID, ProjectHash, HostSlug (+ TranscriptID in pull.go); closed enums Role, EntryType, ToolCallKind, StopReason, SessionOutcome, SourceFormat, Visibility, License, and Harness (re-exported from bestiary)
Auth & commands auth.go, command.go ExchangeCodeRequest/Response, CLILoginQuery; BuiltinCommand + IsClaudeBuiltinCommand
Redaction fixtures redactions.go RedactionInfo staleness helpers, RedactionFixtureLevel, the RedactionExamples corpus, LoadRedactionExamples (the redaction engine stays in peasant; this module carries only the metadata type and the fixture corpus)
Embedded specs & fixtures specs.go, contract_embeds.go, fixtures.go VillageAPISpecJSON(), PublishRequestSchemaJSON(), AnnotationPushRequestSchemaJSON(), EvalSchemaJSON, ContractCorpusFS, and the embedded YAML/JSON fixture corpora

SchemaVersionResponse.contentCapabilities is a forward-open list used to avoid silently losing optional meaning-, provenance-, or safety-bearing content. observed_model_v1 is the first known token. Clients match exact tokens and refuse unsupported enriched publication before upload; server deployments advertise only behavior they prove end to end. See the authoritative content capability negotiation specification for wire semantics, guarantees, evolution, and contributor policy.

The session-detail payload (the central object)

SessionDetailPayload is the object every producer builds and every renderer consumes. It travels two ways:

  • On peasant's local session_detail WebSocket channel, and
  • Wrapped in a TranscriptContent envelope as the versioned peasant push wire body (replacing raw provider JSONL with a normalized, self-describing blob).

It carries the session header (Harness, timing, token totals), the ordered []TurnDetail (each with its []ToolCallDetail, optional exact source-observed assistant model, ACP-aligned enrichment, and optional thinking / stop-reason / token fields), an optional SessionScorecard, and the resolved SessionOutcome. The session-level model is the initial root-assistant seed, never the latest or final model; consumers derive sticky effective state from ordered observedModel evidence.

Its composition ([] = has-many; a * pointer = optional):

classDiagram
    class SessionDetailPayload {
        Harness harness
        int totalTokens
        int turnCount
        int toolCallCount
        SessionOutcome outcome
    }
    class TurnDetail {
        int index
        Role role
        string content
        ObservedModelID observedModel
        EntryType entryType
        StopReason stopReason
    }
    class ToolCallDetail {
        string name
        string arguments
        string result
        ToolCallKind toolKind
    }
    class ChildSessionRef {
        string id
        string project
    }
    class SessionScorecard {
        float specQualityScore
        float m2TokenOutcomeRatio
        int m4ConsecutiveErrorMax
    }
    SessionDetailPayload "1" *-- "many" TurnDetail : turns
    SessionDetailPayload "1" *-- "many" ChildSessionRef : childSessions
    SessionDetailPayload "1" o-- "0..1" SessionScorecard : scorecard
    TurnDetail "1" *-- "many" ToolCallDetail : toolCalls

The enum field types (Role, EntryType, StopReason, ToolCallKind, SessionOutcome, FileChangeStatus, and DiffLineKind) are schema newtypes; Harness is re-exported from bestiary. File-change statuses retain the Git wire tokens M, A, D, and R; diff-line kinds retain context, add, and del.

A trimmed excerpt of the top-level shape (local_api.go):

type SessionDetailPayload struct {
    Harness       Harness           `json:"harness"`
    Turns         []TurnDetail      `json:"turns"`
    ChildSessions []ChildSessionRef `json:"childSessions,omitempty"`
    Outcome       SessionOutcome    `json:"outcome,omitempty"`
    Scorecard     *SessionScorecard `json:"scorecard,omitempty"`
    // + session header: timing, token totals, turn/tool-call counts
}
The License surface

The content-license menu is owned by this contract (types.go), so producers, enforcers, and UIs all read one closed set:

Symbol Value / behaviour
License Closed string newtype
LicenseCC0 / LicenseCCBY / LicenseCCBYSA CC0-1.0 · CC-BY-4.0 · CC-BY-SA-4.0
AllLicenses The canonical ordered menu
License.IsValid() Reports membership in the menu
LicenseMenu() The menu as a comma-separated string for help text / errors (derived from AllLicenses, never a literal)

The publish/pull wire carries it as an optional license field (PublishRequest, PullTranscriptInfo); the generated JSON-Schema's license enum is derived from AllLicenses, so widening the menu flows through the schema automatically. village enforces it; peasant mirrors it in two SQLite CHECK constraints.

Generated OpenAPI specs (generated/)

go run ./cmd/schema-gen renders the Go source into OpenAPI 3.1 specs, committed as byte-frozen goldens (JSON + YAML) plus standalone PublishRequest and AnnotationPushRequest JSON Schemas (draft 2020-12). Three OpenAPI spec families and two standalone JSON Schemas are emitted from the builders in openapi/:

Spec family Builder Covers Current version
village API BuildVillageAPISpec publish / pull / annotations / auth / schema-version 0.12.0
PublishRequest JSON Schema BuildPublishRequestSchema the standalone publish request validator schema 0.12.0
AnnotationPushRequest JSON Schema BuildAnnotationPushRequestSchema the standalone annotation push request validator schema 0.12.0
peasant local API BuildPeasantLocalAPISpec the local dashboard REST + Map / Review / Search surface 0.7.0
types BuildTypesSpec the foundational shared domain-type catalog 0.10.0

The current specs are read back into the binary via //go:embed generated. Three version-aware accessors expose the bytes so consumers follow the go.mod pin without vendoring their own copy:

  • VillageAPISpecJSON(): the current village API spec (village serves it as GET /openapi.json).
  • PublishRequestSchemaJSON(): the current PublishRequest JSON-Schema (the single byte-source ValidatePublishRequest compiles and the village enforces through).
  • AnnotationPushRequestSchemaJSON(): the current annotation-push operation schema. ValidateAnnotationPushRequest compiles it, decodes the request, and applies the runtime entry-target rule endIndex > entryIndex that standard JSON Schema cannot represent.

All three derive their filename from the version constant in versions.go, so a version bump re-points them in lockstep: consumers need no change.


Versioned specs & frozen goldens

Released spec versions are immutable. The rule is bump, don't mutate: you never add or change surface on an already-shipped spec in place. You bump the relevant version constant in versions.go (minor for additive surface, major for a breaking change), regenerate, and commit: the new version is emitted while every prior version stays byte-frozen exactly as shipped.

flowchart TD
    change["a surface change<br/>(additive or breaking)"]
    bump["bump the version constant<br/>versions.go (minor / major)"]
    regen["go run ./cmd/schema-gen"]
    current["new current spec in generated/<br/>codegen-freshness gate"]
    frozen["every prior version byte-frozen<br/>retired-versions immutability guard<br/>(retired_specs_test.go)"]
    change --> bump --> regen
    regen --> current
    regen --> frozen

Two gates enforce this (both run in make check via cmd/schema-gen):

  • Codegen-freshness gate: the committed artifacts under generated/ (and the generated redaction fixture) must be byte-identical to what the generator emits from the Go source. A stale or hand-edited current spec fails the build; the fix is go run ./cmd/schema-gen + commit. (make freshness is the git-diff backstop for the same invariant.)
  • Retired-versions immutability guard (cmd/schema-gen/retired_specs_test.go): every retired version is content-hash-pinned (sha256 of its committed bytes) in a registry and asserted present-and-frozen. It fails loudly on both an in-place edit (hash mismatch) and a deletion (missing file): the exact gap the freshness gate can't see, because freshness only diffs versions the generator still emits. A version is moved into the registry at the moment it is frozen (the same change that bumps the live constant past it), so there is never a window where a retired spec is mutable-and-unguarded. A permanent negative-control self-test proves the guard actually fires.

The exact retired inventory and hashes live in cmd/schema-gen/testdata/retired_specs.yaml. The still-generated current versions (Village API, PublishRequest, and AnnotationPushRequest 0.12.0, Peasant Local API 0.7.0, and Types 0.10.0) live under the freshness gate instead. When a Village API version is frozen, register both JSON-only request schemas alongside the OpenAPI golden in that manifest.

The versioning procedure itself is codified in the versions.go doc comments, the "Regeneration & gates" section of CONTRIBUTING.md, and the release ceremony in docs/release-runbook.md; there is no separate versioning document.


How pinning works

Because the contract is a normal published, tagged Go module, a consumer pins one version:

go get github.com/peasant-labs/schema@v0.1.0

That single pin replaces the old model of vendoring an in-tree copy of the types. It also structurally retires the cross-repo cost that model carried: there is no vendorHash / private-module-auth tax to fold first-party schema source into a consumer's build. The Nix buildGoModule vendorHash covers only the third-party module graph, and a no-local-replace rule (proven by TestVendorHashStableOnFirstPartyEdit) forbids the local-path replace directive that would fold first-party source into the vendor graph, so a schema edit can never drift a consumer's hash.

The ceremony (in effect): a contract change lands as its own schema-repo PR + tag first, and only then do the consumer PRs that re-pin to the new tag land. The wire is defined once, published once, and adopted deliberately. Never edited in two repos at once. Because the village both serves and enforces from the same pinned module bytes, its served spec and its enforcement can't drift from each other or from the tag.


Contract gates

Gate Tool Consequence
OpenAPI breaking diff oasdiff breaking --fail-on ERR Hard - fails on an ERR-level breaking change vs the prior golden.
OpenAPI lint vacuum lint -r .vacuum.yaml Hard - fails on error-severity findings in the generated specs.
Exported-Go-API diff go-apidiff Advisory while pre-1.0 - an incompatible exported-Go-API change surfaces a workflow warning + a single sticky PR comment listing the changed/removed symbols (and any additive changes), then exits success. Detection is unchanged; only the consequence is. An unrecognizable diff-tool output still fails closed.

The advisory posting runs in a write-scoped companion workflow (go-apidiff-comment.yml) so the read-only Tests workflow can be reused as a gate. Alongside these, make check runs the codegen-freshness gate, the retired-versions immutability guard, the leaf-audit, the vendorHash-stability proof, and the synthetic-break tests that prove the oasdiff / go-apidiff gates actually fire.

TypeScript bindings

The typescript/ directory is the source of the @peasant-labs/schema package, first shipped with the module's v0.1.0-rc6 tag. It mirrors the Go contract architecture:

  • the package root is the canonical Types 0.10 projection of the complete public Go wire/domain catalog, including Zod runtime schemas and Go-shaped closed sets and guards;
  • /local-api and /village-api retain type-only OpenAPI paths and operations namespaces for consumers that need endpoint request/response contracts; shared payloads resolve to the canonical root identities;
  • /types remains a deprecated compatibility re-export of the canonical root;
  • no HTTP or WebSocket transport client SDK is generated;
  • /testcase owns generic validation behavior and a strict YAML decoder;
  • /fixtures/quality and /fixtures/timeline provide typed access to generated data from the same canonical YAML corpora consumed by Go.

The Go source and generated OpenAPI catalogs remain authoritative. Hey API's Zod plugin derives root TypeScript definitions and runtime schemas without enabling its SDK/client plugins. openapi-typescript derives the type-only Local/Village operation contracts. Canonical shared payload names preserve their root identity.

The package is published to npm as @peasant-labs/schema. The committed typescript/package.json stays 0.0.0-development + private: true as the local safety; the release pipeline (release.yml's npm-publish job, behind the same guard → nix-vendor-hash → contract-gates gates as the GitHub Release, and authenticated via npm Trusted Publishing / OIDC rather than a stored token) stamps the real version from the tag and publishes at release time. The published version follows the schema module release tag, not the individual Village, local, or types document versions: an -rcN tag publishes under the npm dist-tag next, a final vX.Y.Z under latest. See docs/release-runbook.md for the npm publication ceremony (the one-time GitHub environment + npm Trusted Publisher setup) and troubleshooting. The old @peasant-labs/types package is deprecated rather than migrated: do not add new handwritten wire interfaces there.


Develop, build, regenerate

Everything is provisioned through Nix: the flake devShell is the dev-dependency manifest (Go has no dev/prod dependency split). You do not install Go or any tool globally.

Prerequisites: Nix with flakes enabled, and (recommended) direnv with nix-direnv.

# Option A: direnv (recommended)
cd <this-worktree>
direnv allow          # loads the flake devShell on cd; the committed .envrc is `use flake .`

# Option B: nix develop
nix develop           # drops you into the Go 1.26 dev shell

Inside the shell (go, gopls, golangci-lint, oasdiff, go-apidiff, vacuum, actionlint, Node, pnpm, ... on PATH):

pnpm --dir typescript install --frozen-lockfile --ignore-scripts # install the exact locked generator/toolchain
make check                            # Go + TypeScript generation, tests, and package gates
                                      #   (incl. leaf-audit, freshness, immutability, and the synthetic-break tests)
make gates BASE_REF=origin/develop    # breaking-change gates vs a base ref (oasdiff + go-apidiff + vacuum)
make schema                           # regenerate OpenAPI/Redoc and TypeScript contract outputs
nix build                             # hermetic buildGoModule (cmd/schema-gen + cmd/release-guard)

The Go test packages remain runnable with a bare Go toolchain. Full make check also needs the locked Node dependencies because freshness regenerates the TypeScript package. If they are absent, the gate names the exact pnpm install command. After any change to the Go schema source, regenerate and commit both generated/ and the generated TypeScript sources; freshness enforces byte-identity.

The leaf rule

The module's go.mod direct require set must stay a subset of the allowed contract dependencies, enforced by TestLeafAudit_GoModRequiresAreAllowed:

github.com/dayvidpham/bestiary
github.com/google/go-github/v88          # runtime seam for cmd/release-guard's GitHub API, not a dev tool
github.com/santhosh-tekuri/jsonschema/v5
github.com/swaggest/jsonschema-go
github.com/swaggest/openapi-go
golang.org/x/crypto
gopkg.in/yaml.v3

Dev/CI tools (oasdiff, go-apidiff, vacuum, linters) live in the flake devTools, never in go.mod. See CONTRIBUTING.md for the leaf-audit and no-local-replace (vendorHash-stability) rules and the go.work workflow for co-developing consumers against a local worktree before a version is cut.


Testing

The suite keeps the contract honest rather than exercising a runtime: the committed specs stay byte-identical to the Go source, released spec versions stay frozen, a breaking wire change is caught before it ships, and the module stays a dependency leaf. Three layers do this: the contract gates (codegen freshness, retired-version immutability, the oasdiff / vacuum / go-apidiff gates, the leaf-purity audit, and the vendor-hash guard, each with a real test plus a synthetic-break meta-gate that proves it fires); unit tests alongside every source (closed enums, JSON shapes, validator behaviour); and typed fixture families under testdata/. The whole suite runs with a bare go toolchain, the tool-gated tests skipping when oasdiff / go-apidiff / vacuum are absent.

Case corpora live in fixtures, not inline. When a test drives a set of cases, the cases live in a testdata/*.yaml corpus loaded through one idiom: a typed struct with yaml: tags, a //go:embed of the file, a yaml.Unmarshal, a small Load...Fixtures loader, and a row-count guard that fails loudly on an empty or mis-keyed corpus (so an iterating test can never pass on no cases). New corpora adopt the canonical testcase standard (a generic Case[I, E] / Corpus[I, E] with closed-set classification and provenance + mutation metadata, a pure loader, and its *testing.T seams split into testcase/assert), so each case also records why it exists and the single change it embodies. Fixtures that split into heterogeneous behavioral arms use the segmented form: a typed struct of named per-arm Corpus fields, each guarded by RequireMin + RequireValid. A contract change then updates one corpus instead of N inline tables, and a new test follows this by default. The corpora sit under testdata/ (annotations, contract, publish, pull, quality, session-detail, sync), internal/release/testdata/ (grammar, workflow), and cmd/release-guard/testdata/github.

See TESTING.md for the full strategy and the test behind each gate.


Releasing

Releases are cut by merging a PR titled release(vX.Y.Z[-rcN]): <summary> into develop. Never by hand-tagging. The title/tag grammar and final-release guard live once in internal/release, exposed through cmd/release-guard, the single canonical release-gating tool (built on go-github; it also serves peasant via a per-repo .github/release-guard.policy.yml). On merge, the release workflow mints the annotated tag and publishes a GitHub Release (prerelease for -rcN) with the generated/ OpenAPI specs attached as assets.

The maintainer-approval assertion in the release PR is deferred to the public flip (a single active maintainer plus GitHub's no-self-approval rule make it unsatisfiable today); the release-guard check-approval guard code stays live and tested, re-enabled alongside branch protection at the flip. The full operator guide (secrets, the GitHub App, the ceremony, and the public-flip checklist) is in docs/release-runbook.md.


Repository layout

Path What
*.go (root, package schema) The contract: domain + wire types, enums, content-hashing, metadata, publish/pull/push envelopes, annotations, the embedded-spec accessors
versions.go Single source of truth for the versioned-spec semvers
openapi/ OpenAPI 3.1 spec builders (BuildVillageAPISpec, BuildPeasantLocalAPISpec, BuildTypesSpec)
generated/ Committed OpenAPI spec goldens (JSON + YAML) + the PublishRequest JSON-Schema - gate-checked; regenerate with go run ./cmd/schema-gen
typescript/ Published @peasant-labs/schema package source: generated named wire types, testcase helpers, typed fixtures, and package gates
external/, testdata/, fixtures.go Vendored external schemas + typed test fixtures
cmd/schema-gen/ Regenerates generated/; hosts the freshness / immutability / surface gate tests
cmd/release-guard/ + internal/release/ The PR-title/tag grammar + release-gating CLI
docs/release-runbook.md · CONTRIBUTING.md · CHANGELOG.md Operator + contributor references
docs/content-capability-negotiation.md Authoritative optional-content negotiation protocol and contributor decision policy

License

Apache-2.0, see LICENSE.

Documentation

Index

Constants

View Source
const (
	VillageCollectiveAcceptanceOpen            = VillageGroupAcceptanceOpen
	VillageCollectiveAcceptanceVerifiedOnly    = VillageGroupAcceptanceVerifiedOnly
	VillageCollectiveAcceptanceCurated         = VillageGroupAcceptanceCurated
	VillageCollectiveDataAccessMembersOnly     = VillageGroupDataAccessMembersOnly
	VillageCollectiveDataAccessContributors    = VillageGroupDataAccessContributors
	VillageCollectiveDataAccessPublic          = VillageGroupDataAccessPublic
	VillageCollectiveRoleOwner                 = VillageGroupRoleOwner
	VillageCollectiveRoleMember                = VillageGroupRoleMember
	VillageCollectiveRoleContributor           = VillageGroupRoleContributor
	VillageCollectiveRolePending               = VillageGroupRolePending
	VillageAssignableCollectiveRoleContributor = VillageAssignableGroupRoleContributor
	VillageAssignableCollectiveRoleMember      = VillageAssignableGroupRoleMember
	VillageCollectiveViewerRoleNone            = VillageGroupViewerRoleNone
	VillageCollectiveViewerRoleOwner           = VillageGroupViewerRoleOwner
	VillageCollectiveViewerRoleMember          = VillageGroupViewerRoleMember
	VillageCollectiveViewerRoleContributor     = VillageGroupViewerRoleContributor
	VillageCollectiveViewerRolePending         = VillageGroupViewerRolePending
)
View Source
const (
	MaxCollectiveObservationURLBytes   = 1024
	MaxContributionTraversalTokenBytes = 4096
	MaxContributionPageLimit           = 200
	MaxCollectiveFetchItems            = 10000
	MaxCollectiveOperationIssueBytes   = 2048
)
View Source
const (
	HarnessClaudeCode  = bestiary.HarnessClaudeCode
	HarnessGeminiCLI   = bestiary.HarnessGeminiCLI
	HarnessCodex       = bestiary.HarnessCodex
	HarnessOpenCode    = bestiary.HarnessOpenCode
	HarnessCursor      = bestiary.HarnessCursor
	HarnessAntigravity = bestiary.HarnessAntigravity
	HarnessStrike      = bestiary.HarnessStrike
	HarnessPi          = bestiary.HarnessPi
)
View Source
const (
	// VillageAPIVersion is the info.version of the Village API spec. Bumped to
	// 0.2.0 when the /api/v1/pull surface was added (additive = minor bump).
	// Bumped to 0.3.0 (rc2 #118) when model + model.harness/model.model became
	// required — a tightening of the publish contract (selective required arrays on
	// operation-specific publish request + SchemaModelInfo). Bumped to 0.4.0 when
	// PublishRequest.License + PullTranscriptInfo.License were added (additive
	// optional field = minor bump). Bumped to 0.5.0 when the pull skip-gate surface
	// (POST /api/v1/pull/transcripts/skip-gate) was added (additive = minor bump).
	// Bumped to 0.6.0 when shared operation components adopted exact canonical
	// Types schemas and the stricter publish HTTP body gained a distinct component
	// identity instead of shadowing the canonical PublishRequest.
	// Bumped to 0.7.0 when TargetKind gained the file_version and association
	// members and AnnotationSummary gained TargetFilePath/TargetContentHash and
	// TargetAssociationID;
	// harmonizeSharedTypeComponents propagates both into this spec's embedded
	// annotation components (additive = minor bump).
	// Bumped to 0.8.0 when the publish wire gained owner-scoped published
	// associations and annotation ingress gained targetAssociationId plus its
	// documented Village POST operation (additive = minor bump).
	// Bumped to 0.9.0 when Harness gained Strike and SessionID gained the two
	// observed Strike identifier forms (additive = minor bump).
	// Bumped to 0.10.0 when the owner transcript update operation
	// (PATCH /api/v1/transcripts/{id}) was declared: an operation the village
	// already served but the published contract never stated, together with its
	// tri-state license semantics, its narrowed visibility menu, and its full
	// reachable refusal set (additive = minor bump).
	// Each prior version's generated goldens are retained byte-frozen under the
	// retired-spec immutability guard.
	// Bumped to 0.11.0 when publication gained canonical operation currency,
	// authoritative success receipts, real multipart transport, and a complete
	// successor owner-update projection (additive = minor bump).
	// Bumped to 0.12.0 when authoritative publication identity adopted its
	// declared parentSessionId key while historical SessionIdentity retained
	// parentUuid (corrective additive version).
	// Bumped to 0.13.0 when schema negotiation gained optional enriched-content
	// capability advertisements (additive = minor bump).
	// Bumped to 0.14.0 when the Village API spec gained the schema-owned
	// collectives, contribution, review, and linked-repository web routes.
	// Bumped to 0.15.0 when the canonical harness inventory gained Pi.
	// Bumped to 0.16.0 when the pull request prompt attachment surface was
	// declared: the GitHub webhook receiver, the attachment read, confirm, and
	// detach routes, the prompt-request and user-settings routes, and two
	// collective settings (additive = minor bump).
	// Bumped to 0.17.0 for grouped transcript listings, helper-member reads,
	// durable provenance, and authorized relationship navigation.
	// Bumped to 0.18.0 when the prompt digest's commit items gained the
	// optional per-commit change counts, which harmonizeSharedTypeComponents
	// propagates into this spec's embedded digest item component (additive =
	// minor bump).
	// Bumped to 0.19.0 when a prompt digest skill item gained the optional args
	// typed after the command, propagated the same way (additive = minor bump).
	// Bumped to 0.20.0 when the group repository surface gained the available-
	// repositories read that feeds the repository picker (additive operation =
	// minor bump).
	// Bumped to 0.21.0 when the prompt-request list gained the pull request's
	// head remote beside its base, so a push from a clone of a fork matches the
	// request waiting on that fork's author (additive field = minor bump).
	// Bumped for retained unknown source evidence and preservation negotiation.
	// Bumped to 0.23.0 for the transcript pull request read, the caller's
	// totals, the automatic pull request linking setting, pull request titles,
	// head branches, and list summaries, the collective and repository counts,
	// and a create request that accepts a null organization (additive = minor
	// bump).
	// Bumped to 0.25.0 for the optional thinking level and its raw native
	// spelling on session metadata, session detail, and assistant turns, the
	// in-session thinking-level history, plus the thinking_level_v1 content
	// capability (additive = minor bump).
	// Bumped to 0.26.0 when the transcript pull list gained the optional
	// collectives filter, which narrows the list to the approved shares of the
	// listed collectives the caller belongs to (additive parameter = minor bump).
	// Canonical collective routes retain deprecated groups for a full release window.
	VillageAPIVersion = "0.27.0"
	// PeasantLocalAPIVersion is the info.version of the local dashboard API spec.
	// Bumped to 0.2.0 when the Map/Review/Search surface was added (8 additive ops
	// + FrictionCluster = minor bump). Bumped to 0.3.0 when the project Git
	// timeline gained normalized session identities and authoritative many-to-many
	// commit bindings. Bumped to 0.4.0 when file-change statuses and diff-line
	// kinds became named closed sets while retaining their existing JSON tokens.
	// Bumped to 0.5.0 when the git+session timeline and insight-first code map
	// surface landed: durable atomic session-to-commit associations, ghost/rewrite
	// mapping, the mechanical insight envelope, node-grain
	// read-state/comprehension signals, and TaskSummary.ReadFiles (all
	// additive).
	// Bumped to 0.6.0 when Harness gained Strike and SessionID gained the two
	// observed Strike identifier forms (additive = minor bump).
	// Bumped to 0.7.0 when TurnDetail gained optional exact model observation
	// evidence for assistant-generated turns (additive = minor bump).
	// Bumped to 0.8.0 when process-local UI capability discovery was added
	// (additive = minor bump).
	// Bumped to 0.9.0 when the session payloads gained the producer's declared
	// session origin and the by-id session-summaries operation was declared
	// (additive = minor bump).
	// Prior versions stay byte-frozen.
	// Bumped to 0.10.0 for detailed usage and native metadata evidence.
	// Bumped to 0.11.0 when TurnDetail gained the optional CommandInvocation
	// for skill and user slash-command turns (additive = minor bump).
	// Bumped to 0.12.0 for independent optional tool namespace evidence.
	// Bumped to 0.13.0 for grouped session listings, helper-member reads, and
	// the flat detail read projection with relationship navigation.
	// Bumped for retained unknown source evidence and durable diagnostics.
	// Bumped to 0.15.0 for publishing from the transcript: the publication
	// read, the typed collectives push, the collectives proxy, the declared
	// sign-in and redaction preview routes with sign-out, the settings routes,
	// the typed sync chooser status, and the declared cross-origin refusal on
	// write routes (additive = minor bump).
	// The Local API embeds Village catalog rows: VillageUserGroup in the
	// collectives proxy, VillagePromptRequest in push results, and
	// VillageShareStatus in the publication audience, with their closed sets.
	// A change to any of them also bumps this version;
	// testdata/local-api/village_components.yaml pins them per Local version.
	// Bumped to 0.16.0 for rule-required hooks that stop publishing when their
	// last active binding is removed, retaining the existing response fields.
	// Bumped to 0.17.0 for an optional stored-session target on rule creation.
	// Bumped to 0.18.0 when the session summary gained the optional
	// parentUnresolved marker and the sync row gained the optional
	// parentSessionId and parentUnresolved fields (additive = minor bump).
	// Bumped to 0.19.0 for the optional thinking level and raw native spelling
	// on session detail and assistant turns, and the in-session thinking-level
	// history (additive = minor bump).
	// Bumped to 0.20.0 for forward sync pages and metadata-only project options.
	// Bumped to 0.21.0 for independent account-scoped collective observations
	// and bounded contribution evidence, retaining the forward sync views.
	PeasantLocalAPIVersion = "0.21.0"
	// TypesVersion is the info.version of the types spec (the foundational shared
	// domain types catalog; formerly "shared-types").
	// Bumped to 0.2.0 when the catalog became the comprehensive canonical
	// cross-language contract surface instead of a small set of seed types.
	// Bumped to 0.3.0 when the map/review diff string fields became named closed
	// sets with generated runtime inventories and predicates.
	// Bumped to 0.4.0 when the Local API 0.5.0 surface's new catalog types
	// (SessionAssociation, RewrittenCommit, SessionInsight and their closed
	// sets) and the widened TargetKind landed (additive = minor bump).
	// Bumped to 0.5.0 when GitContext gained PublishedAssociation and annotation
	// push items gained TargetAssociationID (additive = minor bump).
	// Bumped to 0.6.0 when Harness gained Strike and SessionID gained the two
	// observed Strike identifier forms (additive = minor bump).
	// Bumped to 0.7.0 when the owner transcript update request, its narrowed
	// visibility menu, and its three-valued license entered the catalog so both
	// language bindings carry them (additive = minor bump). The operation's
	// refusal envelope is deliberately NOT catalogued: it is operation-scoped so
	// a release cannot freeze a transcript-update-specific name onto a generic
	// error shape.
	// Bumped to 0.8.0 for canonical publication operation, authoritative receipt,
	// publish visibility intent, and successor owner-update types.
	// Bumped to 0.9.0 when AuthoritativeSessionIdentity adopted parentSessionId
	// independently from the historical SessionIdentity parentUuid wire.
	// Bumped to 0.10.0 when TurnDetail gained optional exact model observation
	// evidence for assistant-generated turns (additive = minor bump).
	// Bumped to 0.11.0 for the content-capability contract catalog.
	// Bumped to 0.12.0 for the open process-local UI capabilities envelope.
	// Bumped to 0.13.0 when the declared session-origin closed set entered the
	// catalog and both session payloads gained its optional field (additive =
	// minor bump).
	// Bumped to 0.14.0 when the Village collectives, contribution, review, and
	// linked-repository DTOs entered the catalog.
	// Bumped to 0.15.0 for optional local metadata adapter/parser provenance.
	// Bumped to 0.16.0 for detailed usage and native metadata evidence while
	// retaining the adapter/parser provenance contract.
	// Bumped to 0.17.0 when CommandInvocation, the PromptDigest projection with
	// its DigestItemKind closed set, and the Village pull request attachment
	// DTOs entered the catalog.
	// Bumped to 0.18.0 for independent optional tool namespace evidence.
	// Bumped to 0.19.0 for durable session graph provenance, independent input
	// submission counts, flat read navigation, and grouped list DTOs.
	// Bumped to 0.20.0 when PromptDigestItem gained the optional additions,
	// deletions, and filesChanged counts a commit anchor carries (additive =
	// minor bump).
	// Bumped to 0.21.0 when a prompt digest skill item gained the optional args
	// typed after the command (additive = minor bump).
	// Bumped to 0.22.0 when the group available-repositories read added its
	// response types to the catalog (additive = minor bump).
	// Bumped to 0.23.0 when the catalog's prompt request gained the pull
	// request's head remote beside its base (additive = minor bump).
	// Bumped for retained unknown source evidence and durable diagnostics.
	// Bumped to 0.25.0 when the local publishing, sign-in, and settings types
	// and the Village pull request read, summary, and totals types entered the
	// catalog (additive = minor bump).
	// Bumped to 0.27.0 to describe rule-required hook consent in the local
	// publication indicator, without changing any field or enum.
	// Bumped to 0.28.0 for the mutually exclusive session-target rule request.
	// Bumped to 0.29.0 when SessionSummary gained the optional parentUnresolved
	// marker and LocalSyncSummary gained the optional parentSessionId and
	// parentUnresolved fields (additive = minor bump).
	// Bumped to 0.30.0 for the ThinkingLevel closed set, the bounded
	// ThinkingLevelRaw native spelling, and the ThinkingLevelChange history
	// entry (additive = minor bump).
	// Bumped to 0.31.0 for concrete sync pages, tokens, and project options.
	// Bumped to 0.32.0 for scoped collective observations, retained contribution
	// evidence and deprecated collective envelopes alongside shared sync pages.
	TypesVersion = "0.32.0"
)

Versioned-spec info.version values. These are the SINGLE SOURCE OF TRUTH for each versioned OpenAPI spec's semantic version: they feed WithVersion(...) in the openapi.Build*Spec functions (re-exported there as openapi.VillageAPIVersion etc.), the generated artifact filenames, AND the version-aware accessors in this package (e.g. VillageAPISpecJSON). A version bump is a one-line edit here.

They live in the contract root (not the openapi sub-package) so the embedded-spec accessors below can key off them without an import cycle (openapi imports this package, so this package cannot import openapi).

Bump the relevant one when its API surface changes (minor for additive surface, major for breaking changes). Retired versions stay byte-frozen under the retired-spec immutability guard; new surface goes on a new version.

View Source
const CollectiveTimestampPattern = `^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]{1,9})?Z$`

CollectiveTimestampPattern is the lossless UTC RFC3339 wire grammar for collective evidence: seconds are required, precision is at most nanoseconds.

View Source
const MetadataSchemaVersion = 12

MetadataSchemaVersion is the schema version written by this build of the ingest tool. v1: initial schema v2: SQLite persistence layer, store integration v3: transcript filename {sessionId}--transcript.{ext} (was {unixMillis}--),

timestamp extraction scans all lines (was first/last line only)

v4: GitContext.Commits field added (session-to-commit linking) v5: Claude indexer fixes — system content extraction, tool_result tool_use_id linking v6: ContentHash, MetadataHash, RedactionInfo — deferred redaction model v7: CWD field — real working directory for context-aware slug redaction v8: DerivedAt field — Unix ms when metadata.json was derived from DB (DB as SOT) v9: harness key unification — UnifiedMetadata.ModelHarness re-keyed json:"modelHarness"

-> json:"harness" (emit-side flip). The bump forces the DIFF stage to
re-classify existing on-disk sessions as Updated so the stale "modelHarness" key
self-heals (re-extract + rewrite) on next ingest; UnmarshalJSON still accepts the
legacy key on pre-v9 files in the meantime.

v10: optional AdapterVersion records the successful Peasant adapter/parser.

The v9-to-v10 change is local metadata bookkeeping, not a reason to read
native sources again. Consumers can losslessly adopt v9 metadata without
inventing the missing producer revision. Native refresh is a separate decision.

v11: session graph provenance.

v12: optional thinking level, raw native spelling, and in-session level history; optional-only, stays refresh-free.

View Source
const PublicRefUTF8ByteFormat = "public-ref-utf8-96-bytes"

PublicRefUTF8ByteFormat identifies the format assertion shared by generated validators for opaque public references. Unlike maxLength, which counts Unicode code points, this assertion counts the encoded UTF-8 bytes.

View Source
const RecordedCostSourceHarnessEstimate = "recorded_harness_estimate"
View Source
const ThinkingLevelRawMaxBytes = 128

ThinkingLevelRawMaxBytes is the encoded UTF-8 byte bound of ThinkingLevelRaw.

View Source
const ThinkingLevelRawUTF8ByteFormat = "thinking-level-raw-utf8-128-bytes"

ThinkingLevelRawUTF8ByteFormat identifies the JSON Schema format assertion that counts encoded UTF-8 bytes of a ThinkingLevelRaw. maxLength counts code points, so this assertion carries the byte rule.

View Source
const TranscriptUpdateTitleMaxLength = 500

Validate checks the closed-set fields a client can get wrong locally, so a caller learns about a bad enum value before spending a network round trip on a guaranteed 400. It deliberately does NOT attempt to predict the server's ownership check or the irrevocability refusal: both depend on stored state this request cannot see, and pretending otherwise would produce a local success that the server then contradicts. TranscriptUpdateTitleMaxLength is the declared bound on a title, mirroring the storage column. It is a named constant because three places must agree: this validator, the reflector tag that emits maxLength into both documents, and the corpus rows that exercise the boundary.

It counts RUNES, matching the column's code-point counting. A generated JavaScript validator counts UTF-16 code units instead and is therefore stricter on astral input; that divergence is deliberate and documented on Title above.

Variables

View Source
var AllAnnotationAxes = []AnnotationAxis{
	AxisType,
	AxisSession,
	AxisProject,
}

AllAnnotationAxes is the canonical list of annotation subscription axes.

AllAnnotationDatatypes is the canonical list of all known annotation datatypes.

AllAnnotationPushStatuses is the canonical list of annotation push outcomes.

AllAnnotationStatuses is the canonical list of all known annotation statuses.

AllAnnotatorKinds is the canonical list of all known annotator kinds.

AllAssociationConclusions is the canonical list of association conclusions.

AllAssociationEvidenceKinds is the canonical list and order of atomic association evidence observations.

AllAutoPublishEvents is the canonical auto-publish hook menu.

AllAutoPublishHookStatuses is the canonical hook state menu.

AllAutoPublishRuleKinds is the canonical rule kind menu.

AllChangeBindings is the canonical list of session-to-change bindings.

AllChannelTopics is the canonical list of subscribable WebSocket topics.

AllClaudeBuiltinCmds is the canonical list of all known Claude Code built-in commands.

AllConfidences is the canonical list of confidence levels.

AllContentCapabilities is the canonical closed capability inventory.

AllContentKinds is the canonical list of transcript content envelope kinds.

AllDecayLevels is the canonical list of project familiarity decay levels.

AllDiffLineKinds is the canonical inventory of unified-diff line kinds.

AllDigestItemKinds is the canonical inventory, in the order a renderer documents them.

AllEdgeViolationKinds is the canonical list of map structure violations.

AllEntryTypes is the canonical list of all known entry types.

AllFileChangeStatuses is the canonical inventory of file change statuses.

AllHarnesses is the canonical list of harnesses that peasant supports for ingestion.

AllInsightKinds is the canonical list of insight kinds.

AllInsightProvenances is the canonical list of insight provenances.

AllInteractionTypes is the canonical list of project familiarity interactions.

AllLicenses is the canonical menu of known licenses.

AllLocalCollectiveSuggestionReasons is the canonical suggestion reason menu.

AllLocalPublicationStates is the canonical publication state menu.

AllLocalSettingKinds is the canonical setting value kind menu.

AllMapNodeKinds is the canonical list of map node classifications.

AllMessageTypes is the canonical list of WebSocket message discriminators.

AllOutcomes is the canonical list of all known session outcomes.

AllOwnerUpdateRequestBehaviours is the canonical ordered closed set. The suite derives its minimum from this list AND asserts every member is exercised, so adding a behaviour without a row fails rather than silently reducing coverage.

AllOwnerUpdateSpecProbeKinds is the canonical ordered closed set. The spec test asserts the corpus covers every member, so adding a probe kind without a fixture row fails rather than silently reducing coverage.

AllReadAttributionStates is the canonical list of read attribution states.

AllReadStateGrades is the canonical ordered list of read-state grades, ascending: none < viewed < reviewed < reviewed_in_detail.

AllRewriteMethods is the canonical list of rewrite resolution methods.

AllRewriteResolutions is the canonical list of rewrite resolutions.

AllRoles is the canonical list of all known roles.

AllScaleKinds is the canonical list of all known scale kinds.

AllSessionOriginBehaviours is the canonical ordered closed set. The corpus declares the same set, and the loader compares the two by MEMBERSHIP, so adding a behaviour without a row fails rather than silently reducing coverage.

AllSessionOriginPayloadKinds is the canonical ordered closed set.

AllSessionOrigins is the canonical menu of declared session origins.

AllSessionSummariesByIDAnchors is the canonical ordered closed set. The corpus declares one row per member and the loader compares the two by membership.

AllSourceFormats is the canonical list of transcript source formats.

AllStopReasons is the canonical list of all known stop reasons.

AllSyncHoldReasons is the canonical hold reason menu.

AllSyncLoginStatuses is the canonical sign-in result menu.

AllSyncLogoutStatuses is the canonical sign-out result menu.

AllSyncPushSessionStatuses is the canonical per-session push outcome menu.

AllSyncPushStepOutcomes is the canonical push step outcome menu.

AllSyncPushSteps is the canonical push step menu.

AllSyncStatuses is the canonical sync chooser status menu.

AllTargetKinds is the canonical list of all known target kinds.

AllThinkingLevels lists the nine levels in canonical order, off..ultracode.

AllToolCallKinds is the canonical list of all known tool call kinds.

View Source
var AllTranscriptUpdateLicenses = func() []TranscriptUpdateLicense {
	values := make([]TranscriptUpdateLicense, 0, len(AllLicenses)+1)
	values = append(values, TranscriptUpdateLicenseClear)
	for _, license := range AllLicenses {
		values = append(values, TranscriptUpdateLicense(license))
	}
	return values
}()

AllTranscriptUpdateLicenses is the canonical menu of values this operation accepts: the clear sentinel first, then every canonical menu license in order. It is DERIVED from AllLicenses rather than restated, so widening the license menu widens this operation with no second edit to forget.

AllTranscriptUpdateVisibilities is the canonical menu of visibility values this operation accepts, in declaration order. The generated schema enum is derived from it so a widening is a one-line edit that cannot drift from the documented contract.

AllTypeOrigins is the canonical list of all known type origins.

View Source
var AllValueDomainKinds = []ValueDomainKind{
	DomainEnumerated, DomainDescribed,
}

AllValueDomainKinds is the canonical list of all known value domain kinds.

View Source
var AllVillageAssignableCollectiveRoles = AllVillageAssignableGroupRoles
View Source
var AllVillageCollectiveAcceptanceModes = AllVillageGroupAcceptanceModes
View Source
var AllVillageCollectiveDataAccessPolicies = AllVillageGroupDataAccessPolicies
View Source
var AllVillageCollectiveRoles = AllVillageGroupRoles
View Source
var AllVillageCollectiveViewerRoles = AllVillageGroupViewerRoles

AllVisibilities is the canonical list of all known visibility levels.

View Source
var AnnotationsYAML []byte

AnnotationsYAML contains the raw YAML content for annotation test fixtures.

View Source
var AssociationAnnotationIngressYAML []byte

AssociationAnnotationIngressYAML contains the cross-language association publication and annotation ingress validation corpus.

View Source
var ContractCorpusFS embed.FS

ContractCorpusFS is the push/pull back-compat golden corpus tree (testdata/contract/**): the current contract shape plus the retained legacy shapes (legacy-metadata-field / legacy-provider-keyed / legacy-raw-jsonl). Exported as an embed.FS so consumers (peasant internal/push back-compat round-trip tests) enumerate and read the corpus through the contract leaf rather than a cross-module filesystem path. Walk it from the "testdata/contract" root (e.g. fs.ReadDir(schema.ContractCorpusFS, "testdata/contract")).

View Source
var ErrCycleDetected = errors.New("annotation type dependency cycle detected")

ErrCycleDetected is returned when adding a dependency would create a cycle in the annotation_type_deps graph (V14: depth limit 20).

View Source
var ErrInvalidValue = errors.New("invalid annotation value")

ErrInvalidValue is returned when a value is not permissible for an annotation domain. Callers should wrap this error with fmt.Errorf("%w: ...", ErrInvalidValue) for context.

View Source
var ErrTypeNotFound = errors.New("annotation type not found")

ErrTypeNotFound is returned when a requested annotation type does not exist in the registry.

View Source
var EvalSchemaJSON []byte

EvalSchemaJSON is the vendored EEE (eval) JSON Schema (external/eee/eval.schema.json) — the contract that peasant's `export` surface validates its evaluation payloads against. Exported so consumers (peasant internal/export conformance + drift tests) read the schema through the contract leaf instead of a cross-module filesystem path. Provenance and re-vendoring policy: external/eee/PROVENANCE.md.

View Source
var OwnerUpdateYAML []byte

OwnerUpdateYAML contains the owner transcript update corpus: request validation verdicts, exact tri-state license encodings, and the generated Village document probes for the declared operation.

View Source
var PublishVerdictsYAML []byte

PublishVerdictsYAML contains the shared publish schema verdict corpus.

View Source
var PullManifestExampleJSON []byte

PullManifestExampleJSON is the golden one-complete-PullManifest example (round-trip shape-pin source).

View Source
var PullRefsYAML []byte

PullRefsYAML contains the raw YAML content for transcript-reference parse fixtures (internal/pull.ParseTranscriptRef).

View Source
var PullStatusesYAML []byte

PullStatusesYAML contains the raw YAML content for PullStatus<->wire mappings.

View Source
var QualitySessionsYAML []byte

QualitySessionsYAML contains the raw YAML content for mock quality sessions.

ReadStateGradeRegistrySeedPermissibleValues is AllReadStateGrades with the unstated zero grade "none" removed, in the same ascending order: the registered set the peasant-side read-state registry seed's PermissibleValues must byte-equal. TestReadStateGradeRegistrySeedCrossCheck pins this module's half of the cross-check; the peasant-side registry seed test pins the other half against this exported value.

View Source
var RedactionExamples = []RedactionExample{
	{
		Name:                "aws_access_key",
		RuleID:              "aws_access_key",
		Category:            "secrets",
		Level:               RedactionLevelMinimal,
		OriginalText:        "AKIAIOSFODNN7EXAMPLE",
		RedactedReplacement: "<AWS_ACCESS_KEY>",
		Confidence:          98,
		LineNumber:          142,
		Description:         "AWS access key ID (pkg/redact rule: aws_access_key)",
	},
	{
		Name:                "email_address",
		RuleID:              "email",
		Category:            "pii",
		Level:               RedactionLevelStandard,
		OriginalText:        "vitor.eduardo@company.com",
		RedactedReplacement: "<EMAIL>",
		Confidence:          94,
		LineNumber:          587,
		Description:         "Email address (pkg/redact rule: email)",
	},
	{
		Name:                "home_directory",
		RuleID:              "unix_home_path",
		Category:            "paths",
		Level:               RedactionLevelMinimal,
		OriginalText:        "/Users/acme-dev/Projects/internal-api",
		RedactedReplacement: "/Users/<USER>/Projects/internal-api",
		Confidence:          72,
		LineNumber:          23,
		Description:         "Unix home directory path with username (pkg/redact rule: unix_home_path)",
	},
	{
		Name:                "github_token",
		RuleID:              "github_pat",
		Category:            "secrets",
		Level:               RedactionLevelMinimal,
		OriginalText:        "ghp_xK9mN2pL4qR7sT8vW1yZ3aB5cD6eF0gH12ab",
		RedactedReplacement: "<GITHUB_PAT>",
		Confidence:          96,
		LineNumber:          310,
		Description:         "GitHub personal access token (pkg/redact rule: github_pat)",
	},
	{
		Name:                "git_remote_url",
		RuleID:              "git_remote_https",
		Category:            "project",
		Level:               RedactionLevelMaximum,
		OriginalText:        "https://github.com/acme-corp/internal-api",
		RedactedReplacement: "<PROJECT_URL>",
		Confidence:          61,
		LineNumber:          445,
		Description:         "Git remote URL exposing project identity (pkg/redact rule: git_remote_https)",
	},
	{
		Name:                "phone_number",
		RuleID:              "phone_us",
		Category:            "pii",
		Level:               RedactionLevelStandard,
		OriginalText:        "+1-555-867-5309",
		RedactedReplacement: "<PHONE>",
		Confidence:          89,
		LineNumber:          712,
		Description:         "US phone number (pkg/redact rule: phone_us)",
	},
	{
		Name:                "database_connection",
		RuleID:              "basic_auth_uri",
		Category:            "secrets",
		Level:               RedactionLevelMinimal,
		OriginalText:        "postgresql://admin:s3cretPass99@db.prod.internal:5432/maindb",
		RedactedReplacement: "postgresql://<BASIC_AUTH_URI>@db.prod.internal:5432/maindb",
		Confidence:          99,
		LineNumber:          18,
		Description:         "URL with embedded basic-auth credentials (pkg/redact rule: basic_auth_uri)",
	},
	{
		Name:                "workspace_path",
		RuleID:              "unix_home_path",
		Category:            "paths",
		Level:               RedactionLevelMinimal,
		OriginalText:        "/home/deploy/apps/acme-billing-service",
		RedactedReplacement: "/home/<USER>/apps/acme-billing-service",
		Confidence:          65,
		LineNumber:          891,
		Description:         "Unix home directory path with username (pkg/redact rule: unix_home_path)",
	},
	{
		Name:                "ip_address",
		RuleID:              "ip_address",
		Category:            "pii",
		Level:               RedactionLevelStandard,
		OriginalText:        "192.168.1.42",
		RedactedReplacement: "<IP_ADDRESS>",
		Confidence:          85,
		LineNumber:          156,
		Description:         "IPv4 address (pkg/redact rule: ip_address)",
	},
	{
		Name:                "slack_webhook",
		RuleID:              "slack_webhook_url",
		Category:            "secrets",
		Level:               RedactionLevelMinimal,
		OriginalText:        "https://hooks.slack.com/services/T024BE7LD/B0DAF2RC3/bJTqg8NS27FYm2pQL0jAiE",
		RedactedReplacement: "<SLACK_WEBHOOK_URL>",
		Confidence:          58,
		LineNumber:          234,
		Description:         "Slack incoming webhook URL (pkg/redact rule: slack_webhook_url)",
	},
	{
		Name:                "stripe_secret",
		RuleID:              "stripe_key",
		Category:            "secrets",
		Level:               RedactionLevelMinimal,
		OriginalText:        "sk_live_4eC39HqLyjWDarjtT1zdp7dc",
		RedactedReplacement: "<STRIPE_KEY>",
		Confidence:          92,
		LineNumber:          67,
		Description:         "Stripe API secret key (pkg/redact rule: stripe_key)",
	},
}

RedactionExamples is the canonical redaction example corpus — the CURRENT session-detail mock cases only (NOT the full pkg/redact corpus). Every RedactedReplacement here is the verbatim output of the real pkg/redact engine run on OriginalText at Level; the peasant conformance test (pkg/redact/redactconform_test.go) enforces that and fails on any drift.

View Source
var RedactionsYAML []byte

RedactionsYAML contains the GENERATED redaction example corpus (testdata/session-detail/redactions.yaml). It is produced by `go run ./cmd/schema-gen` from RedactionExamples (see redactions.go) and is the single source of truth consumed by peasant's behavioural conformance test (pkg/redact) and the web mock codegen. Regenerate + commit on any change to RedactionExamples; the leaf freshness gate enforces byte-identity.

View Source
var SessionGraphProvenanceYAML []byte

SessionGraphProvenanceYAML contains primitive graph validation cases.

View Source
var SessionsYAML []byte

SessionsYAML contains the raw YAML content for mock sessions.

View Source
var TimelineYAML []byte

TimelineYAML contains project timeline validation cases.

Functions

func AnnotationPushRequestSchemaJSON

func AnnotationPushRequestSchemaJSON() []byte

AnnotationPushRequestSchemaJSON returns the standalone JSON Schema bytes for the current Village annotation-push operation. The generator extracts it from the same operation schema Village serves, so ValidateAnnotationPushRequest validates the documented wire shape before invoking the typed request validator for relational entry-target rules.

func BuildAuthoritativePublicationProjections added in v0.19.0

func BuildAuthoritativePublicationProjections(detail SessionDetailPayload, metadata UnifiedMetadata, schemaVersion int, projectedMainCount bool) (AuthoritativeSessionIdentity, AuthoritativeSessionStats, []AuthoritativeSubagentRef, error)

BuildAuthoritativePublicationProjections derives the publication identity, statistics, and legacy child projection from one durable detail payload. The metadata argument is a mirror check, not a second authority. projectedMainCount must be true only when the caller positively identified a projected-format generation whose TurnCount is defined as emitted main records. Legacy callers pass false so their established metadata and export turn totals can remain different. InputSubmissionCount presence does not identify the projection format.

func CollectiveFetchHTTPStatus added in v0.31.0

func CollectiveFetchHTTPStatus(report CollectiveFetchReport) int

CollectiveFetchHTTPStatus chooses the transport status without dropping any domain effects. Validate the report first; malformed reports fail closed.

func ComputeAnnotationHash

func ComputeAnnotationHash(
	annotationTypeID string,
	annotatorID string,
	value string,
	sessionID *string,
	entryIndex *int,
	endIndex *int,
	confidence *float64,
	reason *string,
	provenance *Provenance,
) string

ComputeAnnotationHash computes a SHA3-256 content hash over the core fields of an annotation for deduplication purposes. The hash is deterministic: the same annotation content always produces the same hex string.

Parameters mirror the annotation's content-bearing fields. Target-specific fields (sessionID, entryIndex, endIndex) are optional and contribute to the hash only when set (ensuring session-level and entry-level annotations of the same type/value/annotator produce different hashes).

func ComputeManifestDigest

func ComputeManifestDigest(hashes []string) string

ComputeManifestDigest computes a deterministic SHA3-256 digest over a SET of content-hashes. The result depends only on the underlying set, not on input order or duplicate multiplicity: the hashes are sorted and de-duplicated before hashing. Two callers observing the same logical set always produce the same digest, which is what makes the no-op short-circuit correct across machines.

The empty set hashes to a fixed, well-defined value (the digest of no input), so two empty manifests compare equal.

func ComputeMetadataHash

func ComputeMetadataHash(meta *UnifiedMetadata) string

ComputeMetadataHash computes the SHA3-256 hash of metadata fields, excluding ContentHash, MetadataHash, and Redaction to avoid circular dependency. Changing any content-bearing metadata field produces a different hash.

func ComputeTranscriptHash

func ComputeTranscriptHash(transcriptBytes []byte) string

ComputeTranscriptHash computes the SHA3-256 hash of raw transcript bytes. Used to detect content changes for incremental re-processing and stale redaction detection.

func ConstructSessionGraphRef added in v0.19.0

func ConstructSessionGraphRef(i SessionGraphRefInput) (string, error)

func DecodeNativeMetadataDataRaw added in v0.16.0

func DecodeNativeMetadataDataRaw(raw []byte) (json.RawMessage, error)

func HarnessDisplayName

func HarnessDisplayName(h Harness) string

HarnessDisplayName returns the human-readable name for a harness.

func HarnessJSONSchema

func HarnessJSONSchema() jsonschema.Schema

HarnessJSONSchema returns the JSON Schema for the Harness type. This is a standalone function because Harness is a type alias for bestiary.Harness, and Go does not allow methods on imported types.

func IsClaudeBuiltinCommand

func IsClaudeBuiltinCommand(name string) bool

IsClaudeBuiltinCommand reports whether name (with any leading slash stripped) matches a known Claude Code built-in command. Skill names like "aura:epoch" or "user-defined-command" will return false.

Examples:

IsClaudeBuiltinCommand("exit")   → true
IsClaudeBuiltinCommand("/exit")  → true
IsClaudeBuiltinCommand("aura:epoch") → false

func LicenseMenu

func LicenseMenu() string

LicenseMenu returns the known license IDs as a comma-separated string, derived from AllLicenses so help text and error messages can't drift from the canonical menu when a license is added.

func NewJSONSchemaCompiler added in v0.19.0

func NewJSONSchemaCompiler() *jsonschema.Compiler

NewJSONSchemaCompiler returns the canonical compiler for schema-owned validation assets. Custom wire formats are assertions, not annotations, so callers cannot accidentally compile a schema that silently ignores them.

func PublishRequestSchemaJSON

func PublishRequestSchemaJSON() []byte

PublishRequestSchemaJSON returns the standalone JSON-Schema (draft 2020-12) bytes for the PublishRequest wire format at the CURRENT VillageAPIVersion — the schema extracted from the Village API spec by openapi.BuildPublishRequestSchema and committed under generated/publish-request-<VillageAPIVersion>.schema.json.

This is the SINGLE BYTE-SOURCE the publish-enforce path validates against: schema.ValidatePublishRequest (root publish_validate.go) compiles exactly these bytes, and village's publish handler enforces through it rather than vendoring its own schema copy. Routing both the documented spec and the enforced schema through this one accessor means they can never drift (it retired the hand-maintained validate/schema.json, which had diverged from the generated artifact, and — rc2 #118 — folded the standalone `validate` subpackage into the root schema package).

It is version-aware: the filename is derived from VillageAPIVersion, never a literal, so a version bump in versions.go re-points it in lockstep. The bytes are embedded at compile time, so a miss here is a build/generation bug, not a runtime condition — it panics with an actionable message. The codegen-freshness gate and TestPublishRequestSchemaJSON_MatchesGenerated keep this unreachable in a healthy tree.

func ReconcileVillageContributionAttempt added in v0.31.0

ReconcileVillageContributionAttempt reconciles one identity against the latest retained value. Callers must select the authenticated storage scope first and call this under their write transaction, not against an earlier network-read snapshot. A new ordinal is a separate identity and must be passed with nil saved evidence; gaps do not imply missing attempts.

On conflict the saved evidence is returned unchanged along with an error. The result never aliases either input's decision timestamp. FirstSeenAt belongs to local evidence and is preserved on every existing-identity reconciliation.

func RemoteLabel added in v0.1.2

func RemoteLabel(remote string) (label string, ok bool)

RemoteLabel formats a git remote as the canonical "host:owner/repo" display label, using the FULL host for every host so self-hosted and enterprise forges are distinguishable (github.com:peasant-labs/village, gitlab.example.corp:team/repo). There is no host allowlist and no short-prefix table: a host that is not a well-known forge keeps its full hostname rather than failing closed.

The port, when a remote carries one, is DROPPED: "gitlab.example.corp:2222" and "gitlab.example.corp:2200" both render as "gitlab.example.corp". This is a deliberate collision, not an oversight — two forges reachable at the same host on different ports are indistinguishable in the rendered label by design. An IPv6 literal host keeps its brackets with the port removed from inside them ("[::1]:2222" -> "[::1]"); the bracket delimiters are never mistaken for a port separator. Port stripping applies only to a syntactic host component (the URL-scheme and bare-normalized forms); the SCP-like form's colon is a path separator, never a port, so nothing there is stripped — see the port-handling note below.

RemoteLabel accepts the normalized bare form ("host/owner/repo") and, defensively, an HTTPS or SSH remote URL that was not pre-normalized ("https://host/owner/repo[.git]", "git@host:owner/repo[.git]", "ssh://git@host/owner/repo[.git]"). Any userinfo embedded in the remote (user:pass@ or user:TOKEN@ — e.g. a personal access token baked into a CI/CD or git-credential-store remote) is stripped before the host is extracted, so a credential can never reach a rendered label. A trailing ".git" is dropped.

ok is false when remote is empty or does not contain a recognizable host + path pair; the caller MUST fall back to another display tier in that case.

The signature is deliberately two-valued: there is no RemoteLabelSource discriminator, because no consumer of this rule needs one.

func RunPublishVerdicts

func RunPublishVerdicts(t *testing.T, validate func([]byte) error)

RunPublishVerdicts drives a publish-body validator over the ENTIRE shared publish-verdict corpus (testdata/publish/verdicts.yaml), in two passes — first the Acceptances() (schema_accepts:true), then the Rejections() (schema_accepts:false) — asserting each row's expectation with ASSERT-WHERE-PRESENT semantics (FINDING-2a):

  • an accepted row MUST validate with no error;
  • a rejected row MUST error;
  • WHERE a rejected row pins error_contains, the validator message MUST contain that exact (minimal/stable) substring — but rows WITHOUT error_contains are NOT required to carry one (no false-fail on the ~half the corpus that pins only error_category); and
  • EVERY rejected row MUST carry a non-empty error_category (no vacuous reject).

It is the one-call, reusable form of the accept/reject loop every corpus consumer would otherwise open-code, so the corpus stays the SINGLE source of publish-validation cases. Pass the validator under test — e.g. schema.RunPublishVerdicts(t, schema.ValidatePublishRequest) for the root client validator, or a compiled-schema closure for the extracted-schema side.

ERROR-STRING BREADCRUMB (FINDING-2b): the pinned error_contains substrings are coupled to the message text of github.com/santhosh-tekuri/jsonschema/v5, pinned at v5.3.1 (see go.mod). They are kept MINIMAL/stable on purpose — e.g. "value must be one of", "missing properties: 'model'"/'harness'", "does not match pattern". If a future jsonschema/v5 bump changes the wording, the error_contains assertions here (and TestPublishVerdicts_ErrorContainsPinnedStrings) fail loudly so the drift is diagnosable at the dep, not silently tolerated.

NOTE on placement: this helper takes *testing.T, so it necessarily imports "testing". It is isolated in this dedicated file (not the production-logic files) and is consumed only by _test packages (publish_validate_test, openapi); production code never calls it.

func ScanRawJSONDocument added in v0.16.0

func ScanRawJSONDocument(raw []byte, p RawJSONPathPolicy) error

func TranscriptUpdateVisibilityMenu

func TranscriptUpdateVisibilityMenu() string

TranscriptUpdateVisibilityMenu renders the accepted values for help text and error messages, derived from AllTranscriptUpdateVisibilities so a message can never drift from the enum.

func ValidateAnnotationPushRequest

func ValidateAnnotationPushRequest(data []byte) error

ValidateAnnotationPushRequest validates an annotation-push JSON body against the generated operation schema, then decodes AnnotationPushRequest and calls its typed validator. The schema enforces the documented structural contract; the typed validator additionally enforces relational rules such as entryTarget.endIndex being greater than entryTarget.entryIndex.

func ValidateAnnotationValue

func ValidateAnnotationValue(domain ValueDomain, value string) error

ValidateAnnotationValue checks that value is permissible for the given ValueDomain.

Rules:

  • value must not be empty (regardless of domain kind).
  • For enumerated domains: value must be in PermissibleValues.
  • For described domains: delegates to ValidateDescribedValue (datatype coercion + JSON schema).

Returns nil if valid. Returns an error wrapping ErrInvalidValue otherwise.

func ValidateContentCapabilityAdvertisements added in v0.1.1

func ValidateContentCapabilityAdvertisements(advertised []ContentCapability) error

ValidateContentCapabilityAdvertisements validates a server-produced list. Discovery readers stay forward-open, but producers must emit only known, unique tokens in canonical lexicographic order.

func ValidateContributionHistoryQuery added in v0.31.0

func ValidateContributionHistoryQuery(q LocalContributionHistoryQuery, current ContributionTraversalRevision) int

ValidateContributionHistoryQuery returns 400 for malformed requests, 409 for a valid but different selected category token, and 200 otherwise. Tokens never select scope and no overall cache revision participates in this comparison.

func ValidateDescribedValue

func ValidateDescribedValue(domain ValueDomain, value string) error

ValidateDescribedValue validates that value is permissible for the given described ValueDomain. It performs two checks in order:

  1. Datatype coercion: the string value must parse as the declared Datatype before schema validation. This catches "3.7" for an integer field before jsonschema sees it.

  2. JSON-schema validation: the ConstraintSpec is compiled (with caching) and the coerced Go value is validated against it.

Returns nil if valid, or an error wrapping ErrInvalidValue when rejected. Returns a non-ErrInvalidValue error when the ConstraintSpec is malformed JSON.

Callers:

  • ValidateAnnotationValue (delegated for described domains)

Where: annotation_validate.go ValidateDescribedValue.

func ValidateInputSubmissionCount added in v0.19.0

func ValidateInputSubmissionCount(value *int64, path string) error

ValidateInputSubmissionCount preserves unknown (nil) separately from measured zero and limits present values to the exact integer range shared with JS.

func ValidateNativeMetadata added in v0.16.0

func ValidateNativeMetadata(v SessionDetailPayload) error

func ValidateNativeMetadataRecords added in v0.16.0

func ValidateNativeMetadataRecords(records []NativeMetadataRecord, targets []TurnDetail) error

ValidateNativeMetadataRecords validates metadata and its public targets before a producer attaches them to a harness-specific session envelope.

func ValidateObservedModelEvidence added in v0.1.1

func ValidateObservedModelEvidence(role Role, observed ObservedModelID) error

ValidateObservedModelEvidence enforces the enriched-publish attribution rule. Subagent output uses the assistant role at a nonzero depth, so RoleAssistant covers both root assistants and subagents. Omitted evidence is valid. Servers advertising observed_model_v1 guarantee this validation completes before any persistence or other side effect and that accepted observedModel value bytes survive publish, storage, migration, rewrite, and serving exactly. JSON whitespace, object-key ordering, and other formatting are not guaranteed.

func ValidatePublicRefJSONSchemaFormat added in v0.19.0

func ValidatePublicRefJSONSchemaFormat(value any) bool

ValidatePublicRefJSONSchemaFormat implements PublicRefUTF8ByteFormat for JSON Schema runtimes. Register it as a format assertion before compiling a schema that exposes one of the public reference types.

func ValidatePublicationRequest

func ValidatePublicationRequest(r AuthoritativePublishRequest) error

ValidatePublicationRequest validates the complete successor publication request. PublishRequest.Validate retains the released rc11 association-only behavior for source compatibility.

func ValidatePublishRequest

func ValidatePublishRequest(data []byte) error

ValidatePublishRequest validates a legacy rc11 publish-request JSON body against the byte-frozen Village 0.10.0 schema. It intentionally does not follow the current Village API version: successor authoritative multipart metadata is validated by DecodeAuthoritativePublishRequest. A non-nil error means the body is invalid — a type/enum/pattern violation, the rc2 (#118) required model object or its harness/model fields missing (e.g. "missing properties: 'model'"/'harness'), or not valid JSON — and the caller must reject it (the village maps this to HTTP 422). It returns nil for a conforming body, or the compile error if the embedded schema fails to compile on first use.

func ValidateRetainedUnknown added in v0.24.0

func ValidateRetainedUnknown(value SessionDetailPayload) error

ValidateRetainedUnknown checks complete retained evidence and its source order. Payload text keeps the normal scanner bounds, never metadata-only budgets. Outer byte limits belong to the actual raw input/output serialization, not a semantic validator's alternate encoding of the same typed value.

func ValidateScaleDomainCombo

func ValidateScaleDomainCombo(scale ScaleKind, domain ValueDomainKind) error

ValidateScaleDomainCombo returns an error when the (scale, domain) combination is structurally incoherent:

  • described + ordinal: rejected because ordinal requires explicit ordering via permissible values (enumerated), not a range constraint.
  • enumerated + continuous: rejected because continuous ranges must be described with a JSON-schema constraint, not a finite list of permissible values.

func ValidateSessionDetailPayload added in v0.16.0

func ValidateSessionDetailPayload(value SessionDetailPayload) error

func ValidateSessionRelationships added in v0.19.0

func ValidateSessionRelationships(rs []SessionRelationship) error

func ValidateThinkingLevelEvidence added in v0.29.0

func ValidateThinkingLevelEvidence(role Role, level ThinkingLevel, raw ThinkingLevelRaw) error

ValidateThinkingLevelEvidence enforces the producer rule that a thinking level or raw spelling may appear only on assistant-generated output (root assistants and subagents both use RoleAssistant). Generated shape validators cannot express this role condition. Omitted evidence is valid.

func ValidateThinkingLevelRawJSONSchemaFormat added in v0.29.0

func ValidateThinkingLevelRawJSONSchemaFormat(value any) bool

ValidateThinkingLevelRawJSONSchemaFormat implements ThinkingLevelRawUTF8ByteFormat for JSON Schema runtimes. Non-string values pass so type assertions remain the responsibility of the "type" keyword.

func ValidateTranscriptContent added in v0.16.0

func ValidateTranscriptContent(v TranscriptContent) error

func ValidateUsageDetail added in v0.16.0

func ValidateUsageDetail(v UsageDetail) error

func VillageAPISpecJSON

func VillageAPISpecJSON() []byte

VillageAPISpecJSON returns the JSON bytes of the CURRENT Village API OpenAPI spec — the version named by VillageAPIVersion. It is version-aware: the filename is derived from the single-source VillageAPIVersion constant, never a literal, so a version bump in versions.go re-points this accessor in lockstep and consumers (e.g. village's GET /openapi.json) need no change.

The bytes are embedded at compile time, so a failure here means the committed generated/ artifact for VillageAPIVersion is missing — a build/generation bug, not a runtime condition. It panics with an actionable message in that case; the codegen-freshness gate and TestVillageAPISpecJSON_MatchesCurrentVersion make this unreachable in a healthy tree.

Types

type ActivityEdge

type ActivityEdge struct {
	From      string `json:"from"`
	To        string `json:"to"`
	TaskCount int    `json:"taskCount"` // distinct tasks that edited both
}

ActivityEdge is a co-edit observation: two nodes repeatedly edited by the same tasks.

type ActorOrigin added in v0.19.0

type ActorOrigin string
const (
	ActorOriginOperator      ActorOrigin = "operator"
	ActorOriginAgentDelegate ActorOrigin = "agent_delegate"
	ActorOriginHarness       ActorOrigin = "harness"
	ActorOriginUnknown       ActorOrigin = "unknown"
)

func NewActorOrigin added in v0.19.0

func NewActorOrigin(raw string) (ActorOrigin, error)

func (ActorOrigin) IsValid added in v0.19.0

func (v ActorOrigin) IsValid() bool

func (ActorOrigin) JSONSchema added in v0.19.0

func (ActorOrigin) JSONSchema() (jsonschema.Schema, error)

type AnnotationAxis

type AnnotationAxis string

AnnotationAxis is the subscription dimension for annotation channels.

const (
	AxisType    AnnotationAxis = "type"
	AxisSession AnnotationAxis = "session"
	AxisProject AnnotationAxis = "project"
)

func (AnnotationAxis) IsValid

func (a AnnotationAxis) IsValid() bool

IsValid reports whether a is a defined annotation subscription axis.

func (AnnotationAxis) JSONSchema

func (AnnotationAxis) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (AnnotationAxis) String

func (a AnnotationAxis) String() string

String returns the wire representation of the annotation axis.

type AnnotationDatatype

type AnnotationDatatype string

AnnotationDatatype is the storage type for annotation values.

const (
	DatatypeText    AnnotationDatatype = "text"
	DatatypeInteger AnnotationDatatype = "integer"
	DatatypeReal    AnnotationDatatype = "real"
	DatatypeBoolean AnnotationDatatype = "boolean"
)

func (AnnotationDatatype) IsValid

func (d AnnotationDatatype) IsValid() bool

IsValid returns true if the annotation datatype is one of the known variants.

func (AnnotationDatatype) JSONSchema

func (AnnotationDatatype) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (AnnotationDatatype) String

func (d AnnotationDatatype) String() string

type AnnotationEntryTarget

type AnnotationEntryTarget struct {
	SessionID  string `json:"sessionId"`
	EntryIndex int    `json:"entryIndex"`
	EndIndex   int    `json:"endIndex"` // half-open [start, end)
}

AnnotationEntryTarget identifies an entry-level annotation target. EndIndex is a half-open range [EntryIndex, EndIndex).

func (AnnotationEntryTarget) Validate

func (target AnnotationEntryTarget) Validate() error

Validate checks the semantic invariants of an entry-level annotation target. JSON Schema can enforce the non-empty session identifier, while this runtime predicate owns the relational half-open range rule shared by every Go request and response path that validates an entry target.

type AnnotationFixtureSummary

type AnnotationFixtureSummary struct {
	Name                string `yaml:"name"`
	ID                  string `yaml:"id"`
	TargetKind          string `yaml:"targetKind"`
	TargetSessionID     string `yaml:"targetSessionId,omitempty"`
	TargetEntryIndex    *int   `yaml:"targetEntryIndex,omitempty"`
	TargetEntryEndIndex *int   `yaml:"targetEntryEndIndex,omitempty"`
	TargetAnnotationID  string `yaml:"targetAnnotationId,omitempty"`
	TargetProjectHash   string `yaml:"targetProjectHash,omitempty"`
	TargetAssociationID string `yaml:"targetAssociationId,omitempty"`
	TargetFilePath      string `yaml:"targetFilePath,omitempty"`
	TargetContentHash   string `yaml:"targetContentHash,omitempty"`
	IsPrimary           bool   `yaml:"isPrimary"`
	AnnotatorKind       string `yaml:"annotatorKind"`
	AnnotatorName       string `yaml:"annotatorName"`
	TypeID              string `yaml:"typeId"`
	TypeName            string `yaml:"typeName"`
	Value               string `yaml:"value"`
	CreatedAt           int64  `yaml:"createdAt"`
}

AnnotationFixtureSummary is a named annotation template in YAML.

func (*AnnotationFixtureSummary) ToAnnotationSummary

func (f *AnnotationFixtureSummary) ToAnnotationSummary() AnnotationSummary

ToAnnotationSummary converts the fixture to a real AnnotationSummary.

type AnnotationFixtures

type AnnotationFixtures struct {
	Summaries         []AnnotationFixtureSummary                                                   `yaml:"annotation_summaries"`
	Validations       []SubscriptionValidationCase                                                 `yaml:"subscription_validations"`
	TargetValidations testcase.Corpus[AnnotationSummary, bool]                                     `yaml:"annotation_target_validations"`
	TargetRepairs     testcase.Corpus[annotationTargetRepairInput, annotationTargetRepairExpected] `yaml:"annotation_target_repairs"`
}

AnnotationFixtures is the top-level YAML structure for annotation test data.

func LoadAnnotationFixtures

func LoadAnnotationFixtures() (*AnnotationFixtures, error)

LoadAnnotationFixtures parses AnnotationsYAML into structured fixtures.

func (*AnnotationFixtures) FindSummary

func (f *AnnotationFixtures) FindSummary(name string) *AnnotationFixtureSummary

FindSummary returns the fixture annotation with the given name, or nil.

type AnnotationManifestResponse

type AnnotationManifestResponse struct {
	// Hex-encoded SHA3-256 annotation content-hashes the village holds for the owner (sorted, de-duplicated).
	// Always emitted as a (possibly empty) NON-null array: NewAnnotationManifestResponse
	// normalizes via sortedUniqueHashes, which never returns nil — so nullable:"false"
	// is the correct wire contract (matches develop's served village-api spec).
	Hashes []string `` /* 148-byte string literal not displayed */
	// Deterministic, order-independent digest over the hash set; a client computing the same digest over its local set knows nothing diverged.
	Digest string `` /* 164-byte string literal not displayed */
}

AnnotationManifestResponse is the body returned by GET /api/v1/annotations/manifest. It advertises the SET of annotation content-hashes the village currently holds for the authenticated owner, so a push client can SKIP any local annotation whose hash already appears here (server-authoritative skip-gate).

Hashes are hex-encoded SHA3-256 content-hashes — the SAME identity the client already computes via content_hash.go (ComputeContentHash / ComputeAnnotationHash). No annotation CONTENT is carried, only its hash, so the manifest is privacy-safe.

Digest is a deterministic, ORDER-INDEPENDENT digest over the hash set (see ComputeManifestDigest). A no-op re-push can short-circuit: if the client computes the same digest over its own local hash set, nothing has diverged.

This type is ADDITIVE — it introduces a new endpoint's response shape and does not alter any existing publish/annotation-push wire contract.

func NewAnnotationManifestResponse

func NewAnnotationManifestResponse(hashes []string) AnnotationManifestResponse

NewAnnotationManifestResponse builds a manifest from a set of content-hashes, normalizing the set (sorted + de-duplicated) and computing the matching digest.

Normalizing on construction means the wire payload is canonical: two villages holding the same logical set emit byte-identical manifests, and the Digest is always consistent with the Hashes it accompanies.

func (AnnotationManifestResponse) ComputeDigest

func (r AnnotationManifestResponse) ComputeDigest() string

ComputeDigest recomputes the order-independent digest over this manifest's Hashes. It is provided so a client can verify the server's Digest field or compare against its own locally-derived digest for the no-op short-circuit.

type AnnotationPushItem

type AnnotationPushItem struct {
	ContentHash         string                 `json:"contentHash"`
	TargetKind          TargetKind             `json:"targetKind"`
	TargetAssociationID *AssociationID         `json:"targetAssociationId,omitempty"`
	SessionID           *string                `json:"sessionId,omitempty"`
	EntryTarget         *AnnotationEntryTarget `json:"entryTarget,omitempty"`
	AnnotationID        *string                `json:"annotationId,omitempty"`
	ProjectHash         *ProjectHash           `json:"projectHash,omitempty"`
	TypeID              string                 `json:"typeId"`
	Value               string                 `json:"value"`
	IsPrimary           bool                   `json:"isPrimary"`
	Confidence          *float64               `json:"confidence,omitempty"`
	Reason              *string                `json:"reason,omitempty"`
	AnnotatorName       string                 `json:"annotatorName,omitempty"`
	Provenance          *Provenance            `json:"provenance,omitempty"`
}

AnnotationPushItem is the wire type for a single annotation in a push request. ContentHash is SHA3-256 of the canonical JSON representation of all other fields, computed by ComputeContentHash(). Used for server-side deduplication.

func (*AnnotationPushItem) ComputeContentHash

func (item *AnnotationPushItem) ComputeContentHash() string

ComputeContentHash computes a SHA3-256 content hash over the canonical JSON representation of the AnnotationPushItem, excluding the ContentHash field itself.

The hash is deterministic: the same logical annotation always produces the same hex string regardless of struct field order. This is because encoding/json marshals struct fields in declaration order, producing stable output for the same values.

Use case: server-side deduplication. The caller sets item.ContentHash to this value before adding it to an AnnotationPushRequest.

func (AnnotationPushItem) Validate

func (item AnnotationPushItem) Validate() error

Validate checks that an annotation push item names one exclusive target arm. Association target validation is shared with AnnotationSummary so ingress and returned annotations cannot disagree about when targetAssociationId is valid.

type AnnotationPushRequest

type AnnotationPushRequest struct {
	Annotations []AnnotationPushItem `json:"annotations" required:"true" nullable:"false"`
	Retractions []string             `json:"retractions,omitempty"`
}

AnnotationPushRequest is the body sent to POST /api/v1/annotations.

Retractions is an ADDITIVE, backwards-compatible field: a set of content-hashes the client wants the village to DROP (tombstone) for this owner. It carries propagated deletions/supersessions inline on the existing push request rather than via a separate DELETE endpoint (avoids a second auth/owner-scoping path and round-trip). The hashes are the SAME hex SHA3 content-hashes used for dedup; only hashes the owner authored AND locally retired are sent, so a foreign machine's annotation can never be retracted. omitempty preserves the prior wire shape for clients that send no retractions.

func (AnnotationPushRequest) Validate

func (r AnnotationPushRequest) Validate() error

Validate checks every annotation in a pushed batch through the public item validator. A caller can reject the batch before persistence when one item is malformed, preserving all-or-nothing handler semantics.

type AnnotationPushResponse

type AnnotationPushResponse struct {
	Created int                    `json:"created"`
	Updated int                    `json:"updated"`
	Skipped int                    `json:"skipped"`
	Errors  int                    `json:"errors"`
	Results []AnnotationPushResult `json:"results,omitempty"`
}

AnnotationPushResponse is returned by the village after processing an annotation push.

type AnnotationPushResult

type AnnotationPushResult struct {
	ContentHash string               `json:"contentHash,omitempty"`
	Status      AnnotationPushStatus `json:"status"`
	Error       string               `json:"error,omitempty"`
}

AnnotationPushResult is the per-item result within an AnnotationPushResponse.

type AnnotationPushStatus

type AnnotationPushStatus string

AnnotationPushStatus is the per-item outcome status from the village.

const (
	PushStatusCreated AnnotationPushStatus = "created"
	PushStatusUpdated AnnotationPushStatus = "updated"
	PushStatusSkipped AnnotationPushStatus = "skipped"
	PushStatusError   AnnotationPushStatus = "error"
)

func (AnnotationPushStatus) IsValid

func (s AnnotationPushStatus) IsValid() bool

IsValid reports whether s is a defined annotation push outcome.

func (AnnotationPushStatus) JSONSchema

func (AnnotationPushStatus) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (AnnotationPushStatus) String

func (s AnnotationPushStatus) String() string

String returns the string representation of the push status.

type AnnotationRegistry

type AnnotationRegistry interface {
	AnnotationTypeReader

	// Register inserts a new annotation type from the given definition.
	// Returns the newly created AnnotationTypeSummary (status=proposed by default).
	Register(ctx context.Context, def TypeDefinition) (*AnnotationTypeSummary, error)

	// Activate transitions a type from proposed -> active.
	Activate(ctx context.Context, typeID string) error

	// Deprecate transitions a type from active -> deprecated, recording the superseding typeID.
	Deprecate(ctx context.Context, typeID string, supersededBy string) error

	// AddDependency records that typeID depends on dependsOn (V14: cycle detection enforced).
	// required=true means the dependency must be satisfied before typeID can produce a value.
	// rationale documents the reason for the dependency.
	AddDependency(ctx context.Context, typeID, dependsOn string, required bool, rationale string) error

	// GetDependencies returns the dependency entries for typeID.
	GetDependencies(ctx context.Context, typeID string) ([]TypeDependency, error)
}

AnnotationRegistry extends AnnotationTypeReader with mutation operations. Used by admin commands and the registry management layer.

type AnnotationStatus

type AnnotationStatus string

AnnotationStatus is the lifecycle state of an annotation type (ISO 11179 Part 6).

const (
	StatusProposed   AnnotationStatus = "proposed"
	StatusActive     AnnotationStatus = "active"
	StatusDeprecated AnnotationStatus = "deprecated"
	StatusRetired    AnnotationStatus = "retired"
)

func (AnnotationStatus) IsValid

func (s AnnotationStatus) IsValid() bool

IsValid returns true if the annotation status is one of the known variants.

func (AnnotationStatus) JSONSchema

func (AnnotationStatus) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (AnnotationStatus) String

func (s AnnotationStatus) String() string

type AnnotationSummary

type AnnotationSummary struct {
	ID                  string       `json:"id"`
	TargetKind          TargetKind   `json:"targetKind" yaml:"targetKind"`
	TargetSessionID     *string      `json:"targetSessionId,omitempty" yaml:"targetSessionId,omitempty"`
	TargetEntryIndex    *int         `json:"targetEntryIndex,omitempty" yaml:"targetEntryIndex,omitempty"`
	TargetEntryEndIndex *int         `json:"targetEntryEndIndex,omitempty" yaml:"targetEntryEndIndex,omitempty"` // V16: half-open [start, end)
	TargetAnnotID       *string      `json:"targetAnnotationId,omitempty" yaml:"targetAnnotationId,omitempty"`
	TargetProjectHash   *ProjectHash `json:"targetProjectHash,omitempty" yaml:"targetProjectHash,omitempty"`
	// TargetAssociationID identifies a durable session-to-commit association.
	// It is an ID target, never an embedded association copy.
	TargetAssociationID *AssociationID `json:"targetAssociationId,omitempty" yaml:"targetAssociationId,omitempty"`
	// TargetFilePath and TargetContentHash discriminate a TargetFileVersion
	// annotation (the 5th TPT arm): a whole-file
	// read-state receipt keyed to a specific content hash of a specific
	// repo-relative path, so an agent edit that changes the content hash
	// invalidates the receipt without deleting it.
	TargetFilePath    *string       `json:"targetFilePath,omitempty" yaml:"targetFilePath,omitempty"`
	TargetContentHash *string       `json:"targetContentHash,omitempty" yaml:"targetContentHash,omitempty"`
	IsPrimary         bool          `json:"isPrimary"`
	AnnotatorKind     AnnotatorKind `json:"annotatorKind"`
	AnnotatorName     string        `json:"annotatorName"`
	TypeID            string        `json:"typeId"`
	TypeName          string        `json:"typeName"`
	Value             string        `json:"value"`
	Confidence        *float64      `json:"confidence,omitempty"`
	Reason            *string       `json:"reason,omitempty"`
	Provenance        *Provenance   `json:"provenance,omitempty"`
	ContentHash       *string       `json:"contentHash,omitempty"` // V16: push dedup
	CreatedAt         int64         `json:"createdAt"`
	SupersededBy      *string       `json:"supersededBy,omitempty"`
}

AnnotationSummary is the wire format for annotations in API responses. TargetKind is derived via TPT child table JOINs (annotations_with_target view).

func (AnnotationSummary) Validate

func (a AnnotationSummary) Validate() error

Validate checks that TargetKind selects exactly one AnnotationSummary target arm. It validates the response contract at its shared boundary so producers cannot emit mixed target identities.

type AnnotationTypeReader

type AnnotationTypeReader interface {
	// GetType returns the annotation type summary for the given type_id string.
	// Returns an error wrapping ErrTypeNotFound if no matching type exists.
	GetType(ctx context.Context, typeID string) (*AnnotationTypeSummary, error)

	// ListTypes returns all annotation types matching the given filter.
	// An empty TypeFilter returns all non-deprecated/retired types.
	ListTypes(ctx context.Context, f TypeFilter) ([]AnnotationTypeSummary, error)

	// ValidateValue validates that value is permissible for the annotation type identified by typeID.
	// Returns nil if valid. Returns an error wrapping ErrTypeNotFound if the type does not exist,
	// or an error wrapping ErrInvalidValue if the value is not permissible.
	ValidateValue(ctx context.Context, typeID string, value string) error
}

AnnotationTypeReader provides read-only access to the annotation type registry. Consumed by classifiers, the ingest pipeline, and the REST API handler. Returns AnnotationTypeSummary (wire type) — the internal domain object stays in internal/annotations.

type AnnotationTypeSummary

type AnnotationTypeSummary struct {
	ID               string           `json:"id,omitempty"` // UUID PK — populated from store for CLI use; omitted in REST responses
	TypeID           string           `json:"typeId"`
	Version          int              `json:"version"`
	DisplayName      string           `json:"displayName"`
	Description      string           `json:"description,omitempty"`
	Family           string           `json:"family"`
	Class            string           `json:"class"`
	ScaleKind        ScaleKind        `json:"scaleKind,omitempty"` // measurement level (ISO 11179 Part 5)
	ValueDomain      ValueDomain      `json:"valueDomain"`
	LowerIsBetter    *bool            `json:"lowerIsBetter,omitempty"`
	Status           AnnotationStatus `json:"status"`
	Origin           TypeOrigin       `json:"origin"`
	PriorityOverride *int             `json:"priorityOverride,omitempty"`
	// AllowedTargetKinds lists the target kinds this type may annotate (V16).
	// Empty/omitted means the type places no restriction (all kinds allowed).
	// Clients filter entry-level pickers to types whose list includes "entry".
	AllowedTargetKinds []TargetKind `json:"allowedTargetKinds,omitempty"`
}

AnnotationTypeSummary is the wire format for annotation types in API responses. Class is derived via the annotation_families → annotation_classes join (BCNF: no redundant column).

type AnnotationsPayload

type AnnotationsPayload struct {
	Axis        AnnotationAxis      `json:"axis"`
	ID          string              `json:"id"`
	Annotations []AnnotationSummary `json:"annotations"`
}

AnnotationsPayload is the data sent on the annotations WebSocket channel. Axis and ID echo the subscription parameters so clients can correlate updates.

type AnnotatorKind

type AnnotatorKind string

AnnotatorKind identifies the type of entity that produced an annotation. Priority for effective annotation resolution: human(3) > agent(2) > rule(1).

const (
	AnnotatorHuman AnnotatorKind = "human"
	AnnotatorAgent AnnotatorKind = "agent"
	AnnotatorRule  AnnotatorKind = "rule"
)

func (AnnotatorKind) IsValid

func (k AnnotatorKind) IsValid() bool

IsValid returns true if the annotator kind is one of the known variants.

func (AnnotatorKind) JSONSchema

func (AnnotatorKind) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (AnnotatorKind) Priority

func (k AnnotatorKind) Priority() int

Priority returns the resolution priority for effective annotation selection. Higher value wins: human(3) > agent(2) > rule(1). Returns 0 for unknown kinds.

func (AnnotatorKind) String

func (k AnnotatorKind) String() string

type AnnotatorSummary

type AnnotatorSummary struct {
	ID          string        `json:"id"`
	Kind        AnnotatorKind `json:"kind"`
	Name        string        `json:"name"`
	DisplayName string        `json:"displayName"`
	Description string        `json:"description,omitempty"`
	ModelID     *string       `json:"modelId,omitempty"`
	// DO NOT TOUCH (TRAP): ProviderKey is the model-VENDOR credential
	// (e.g. "anthropic"), a DIFFERENT axis from the coding-tool Harness. The
	// harness-key changeover left this as json:"providerKey" on purpose.
	// Never flip it to json:"harness" — enforced by ast-grep/no-trap-harness-flip.yml.
	ProviderKey *string `json:"providerKey,omitempty"`
	Status      string  `json:"status"`
}

AnnotatorSummary is the wire format for annotators in API responses. ModelID and ProviderKey are only populated for agent annotators.

type AssociationConclusion

type AssociationConclusion string

AssociationConclusion is the producer-supplied conclusion for a session to commit relationship. Schema validates the closed set, not the inference policy that produced the conclusion.

const (
	AssociationConclusionConfirmed AssociationConclusion = "confirmed"
	AssociationConclusionCandidate AssociationConclusion = "candidate"
)

AssociationConclusion values.

func (AssociationConclusion) IsValid

func (c AssociationConclusion) IsValid() bool

IsValid reports whether c is a defined association conclusion.

func (AssociationConclusion) JSONSchema

func (AssociationConclusion) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (AssociationConclusion) String

func (c AssociationConclusion) String() string

String returns the wire representation of the association conclusion.

func (AssociationConclusion) Validate

func (c AssociationConclusion) Validate() error

Validate rejects values outside the closed association-conclusion set.

type AssociationEvidenceKind

type AssociationEvidenceKind string

AssociationEvidenceKind identifies one atomic observation supporting a session-to-commit association. The order in AllAssociationEvidenceKinds is also the required canonical evidence order.

const (
	AssociationEvidenceRecordedCommit   AssociationEvidenceKind = "recorded_commit"
	AssociationEvidenceTouchedFile      AssociationEvidenceKind = "touched_file"
	AssociationEvidenceBranchMembership AssociationEvidenceKind = "branch_membership"
	AssociationEvidenceTimeWindow       AssociationEvidenceKind = "time_window"
)

AssociationEvidenceKind values.

func (AssociationEvidenceKind) IsValid

func (k AssociationEvidenceKind) IsValid() bool

IsValid reports whether k is a defined association evidence kind.

func (AssociationEvidenceKind) JSONSchema

JSONSchema implements jsonschema.Exposer.

func (AssociationEvidenceKind) String

func (k AssociationEvidenceKind) String() string

String returns the wire representation of the association evidence kind.

func (AssociationEvidenceKind) Validate

func (k AssociationEvidenceKind) Validate() error

Validate rejects values outside the closed association-evidence-kind set.

type AssociationEvidenceObservation

type AssociationEvidenceObservation struct {
	Kind               AssociationEvidenceKind `json:"kind" yaml:"kind" required:"true"`
	RecordedCommitHash *string                 `json:"recordedCommitHash,omitempty" yaml:"recordedCommitHash,omitempty"`
	TouchedFilePath    *string                 `json:"touchedFilePath,omitempty" yaml:"touchedFilePath,omitempty"`
	BranchName         *string                 `json:"branchName,omitempty" yaml:"branchName,omitempty"`
	WindowStartMs      *int64                  `json:"windowStartMs,omitempty" yaml:"windowStartMs,omitempty"`
	WindowEndMs        *int64                  `json:"windowEndMs,omitempty" yaml:"windowEndMs,omitempty"`
}

AssociationEvidenceObservation is one atomic, typed observation supporting a session-to-commit association. Exactly the fields for Kind's selected arm are populated; producers must send canonical order and never rely on schema to normalize a wire value.

func (AssociationEvidenceObservation) Validate

Validate checks that Kind selects exactly one structurally valid detail arm. Git hash and branch-name grammars are producer policy; schema only requires that their supplied strings are non-empty.

type AssociationID

type AssociationID string

AssociationID is Peasant's opaque, durable identifier for one association between a project, session, and observed session-era commit. Consumers treat it as an identifier only: they do not derive, parse, rank, or recompute it.

func NewAssociationID

func NewAssociationID(raw string) (AssociationID, error)

NewAssociationID validates and constructs an opaque association identifier.

func (AssociationID) JSONSchema

func (AssociationID) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (AssociationID) String

func (id AssociationID) String() string

String returns the wire representation of the association identifier.

func (AssociationID) Validate

func (id AssociationID) Validate() error

Validate rejects an association identifier that cannot cross the wire boundary. The identifier is ASCII-only, one to 128 bytes, starts alphanumerically, and thereafter uses only alphanumeric, dot, underscore, colon, or hyphen characters.

type AuthoritativeCommitInfo

type AuthoritativeCommitInfo CommitInfo

type AuthoritativeDiagnosticEntry

type AuthoritativeDiagnosticEntry DiagnosticEntry

type AuthoritativeDiagnosticsInfo

type AuthoritativeDiagnosticsInfo struct {
	Warnings []AuthoritativeDiagnosticEntry `json:"warnings"`
	Partial  *bool                          `json:"partial,omitempty"`
}

type AuthoritativeGitContext

type AuthoritativeGitContext struct {
	Branch       *string                   `json:"branch,omitempty"`
	Remote       *string                   `json:"remote,omitempty"`
	Worktree     *string                   `json:"worktree,omitempty"`
	Tracking     *string                   `json:"tracking,omitempty"`
	Commits      []AuthoritativeCommitInfo `json:"commits,omitempty"`
	Associations []PublishedAssociation    `json:"associations,omitempty"`
}

type AuthoritativeModelInfo

type AuthoritativeModelInfo ModelInfo

type AuthoritativeProjectContext

type AuthoritativeProjectContext ProjectContext

type AuthoritativePublishRequest

type AuthoritativePublishRequest struct {
	Identity         AuthoritativeSessionIdentity `json:"identity,omitempty"`
	Model            AuthoritativeModelInfo       `json:"model" required:"true"`
	Timestamp        AuthoritativeTimestampInfo   `json:"timestamp,omitempty"`
	Source           AuthoritativeSourceInfo      `json:"source,omitempty"`
	Git              AuthoritativeGitContext      `json:"git,omitempty"`
	Project          AuthoritativeProjectContext  `json:"project,omitempty"`
	Stats            AuthoritativeSessionStats    `json:"stats,omitempty"`
	Quality          *AuthoritativeQualityMetrics `json:"quality,omitempty"`
	Entries          []AuthoritativeSessionEntry  `json:"entries,omitempty"`
	Subagents        []AuthoritativeSubagentRef   `json:"subagents,omitempty"`
	Diagnostics      AuthoritativeDiagnosticsInfo `json:"diagnostics,omitempty"`
	License          License                      `json:"license,omitempty"`
	ContentHash      TranscriptContentHash        `json:"contentHash" required:"true"`
	VisibilityIntent VisibilityIntent             `json:"visibilityIntent,omitempty"`
}

func DecodeAuthoritativePublishMetadataRaw added in v0.16.0

func DecodeAuthoritativePublishMetadataRaw(raw []byte) (AuthoritativePublishRequest, error)

func DecodeAuthoritativePublishRequest

func DecodeAuthoritativePublishRequest(data []byte) (AuthoritativePublishRequest, error)

func (*AuthoritativePublishRequest) UnmarshalJSON

func (value *AuthoritativePublishRequest) UnmarshalJSON(data []byte) error

type AuthoritativePublishResponse

type AuthoritativePublishResponse struct {
	TranscriptID                TranscriptID              `json:"transcriptId"`
	TranscriptURL               string                    `json:"transcriptUrl"`
	Visibility                  Visibility                `json:"visibility"`
	ContentHash                 TranscriptContentHash     `json:"contentHash"`
	RequestOperationFingerprint PublishRequestFingerprint `json:"requestOperationFingerprint"`
	Applied                     PublishAppliedState       `json:"applied"`
	BlobKey                     string                    `json:"blobKey"`
	BlobSizeBytes               int64                     `json:"blobSizeBytes"`
	PublishedAt                 int64                     `json:"publishedAt"`
	UpdatedAt                   int64                     `json:"updatedAt"`
	Created                     bool                      `json:"created"`
}

func DecodePublishResponse

func DecodePublishResponse(data []byte) (AuthoritativePublishResponse, error)

func (*AuthoritativePublishResponse) UnmarshalJSON

func (value *AuthoritativePublishResponse) UnmarshalJSON(data []byte) error

func (AuthoritativePublishResponse) Validate

func (response AuthoritativePublishResponse) Validate() error

type AuthoritativeQualityMetrics

type AuthoritativeQualityMetrics QualityMetrics

type AuthoritativeSessionEntry

type AuthoritativeSessionEntry SessionEntry

type AuthoritativeSessionIdentity

type AuthoritativeSessionIdentity struct {
	SessionID       SessionID             `json:"sessionId"`
	ParentSessionID *SessionID            `json:"parentSessionId,omitempty" nullable:"false"`
	RootSessionID   *SessionID            `json:"rootSessionId,omitempty" nullable:"false"`
	Purpose         SessionPurpose        `json:"purpose,omitempty"`
	Relationships   []SessionRelationship `json:"relationships,omitempty"`
	SchemaVersion   int                   `json:"schemaVersion"`
}

Successor publication projections have distinct component identities so recursive unknown-field rejection does not tighten legacy uses of shared metadata components.

type AuthoritativeSessionStats

type AuthoritativeSessionStats SessionStats

type AuthoritativeSourceInfo

type AuthoritativeSourceInfo SourceInfo

type AuthoritativeSubagentRef

type AuthoritativeSubagentRef SubagentRef

type AuthoritativeTimestampInfo

type AuthoritativeTimestampInfo TimestampInfo

type AutoPublishEvent added in v0.25.0

type AutoPublishEvent string

AutoPublishEvent is the git hook that publishes a rule's sessions.

const (
	AutoPublishPrePush    AutoPublishEvent = "pre-push"
	AutoPublishPostCommit AutoPublishEvent = "post-commit"
)

func (AutoPublishEvent) IsValid added in v0.25.0

func (e AutoPublishEvent) IsValid() bool

func (AutoPublishEvent) JSONSchema added in v0.25.0

func (AutoPublishEvent) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (AutoPublishEvent) String added in v0.25.0

func (e AutoPublishEvent) String() string

type AutoPublishHook added in v0.25.0

type AutoPublishHook struct {
	Event  AutoPublishEvent       `json:"event"`
	Status AutoPublishHookStatus  `json:"status"`
	Remedy *AutoPublishHookRemedy `json:"remedy,omitempty" nullable:"false"`
}

AutoPublishHook is the state of one repository's hook for one event. Only a blocked or failed hook carries a remedy.

func (AutoPublishHook) Validate added in v0.25.0

func (h AutoPublishHook) Validate() error

Validate checks the event, the status, and the remedy pairing.

type AutoPublishHookRemedy added in v0.25.0

type AutoPublishHookRemedy struct {
	Message string `json:"message" minLength:"1"`
	Snippet string `json:"snippet,omitempty"`
}

AutoPublishHookRemedy tells the user what to do about a blocked or failed hook. Snippet, present only for a blocked hook Peasant could otherwise manage, is the exact section of hook script to add to the existing hook by hand.

type AutoPublishHookStatus added in v0.25.0

type AutoPublishHookStatus string

AutoPublishHookStatus is the state of one repository's hook for one event.

const (
	// AutoPublishHookAbsent: no hook file exists; installing is offered.
	AutoPublishHookAbsent AutoPublishHookStatus = "absent"
	// AutoPublishHookInstalled: Peasant's own hook is installed.
	AutoPublishHookInstalled AutoPublishHookStatus = "installed"
	// AutoPublishHookBlocked: Peasant will not manage the hook, because a file
	// it did not write is in the way or the hook path is shared outside the
	// repository. Peasant never overwrites such a file. It carries a remedy.
	AutoPublishHookBlocked AutoPublishHookStatus = "blocked"
	// AutoPublishHookFailed: installing the hook failed. Only an install
	// response reports it, and it carries a remedy naming the failure. A rule
	// or a removal response never reports it.
	AutoPublishHookFailed AutoPublishHookStatus = "failed"
)

func (AutoPublishHookStatus) IsValid added in v0.25.0

func (s AutoPublishHookStatus) IsValid() bool

func (AutoPublishHookStatus) JSONSchema added in v0.25.0

func (AutoPublishHookStatus) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (AutoPublishHookStatus) String added in v0.25.0

func (s AutoPublishHookStatus) String() string

type AutoPublishInstallRequest added in v0.25.0

type AutoPublishInstallRequest struct {
	Path string `json:"path" minLength:"1"`
}

AutoPublishInstallRequest is the body of POST /api/v1/settings/auto-publish/{id}/install: the one recorded repository to install the rule's hooks in.

func (AutoPublishInstallRequest) Validate added in v0.25.0

func (r AutoPublishInstallRequest) Validate() error

Validate checks that the request names a repository.

type AutoPublishRemovalResponse added in v0.25.0

type AutoPublishRemovalResponse struct {
	ID           string                  `json:"id" minLength:"1"`
	Repositories []AutoPublishRepository `json:"repositories" nullable:"false"`
}

AutoPublishRemovalResponse is the response of DELETE /api/v1/settings/auto-publish/{id}: the removed rule's identifier and the hooks of the repositories it matched, as they are. Removing a rule keeps hook files but stops their rule-required uploads unless another active rule covers the repository and event. Paused rules grant no publishing consent. Hooks installed separately from the terminal keep their independent consent.

func (AutoPublishRemovalResponse) Validate added in v0.25.0

func (r AutoPublishRemovalResponse) Validate() error

Validate checks every repository and that each appears once.

type AutoPublishRepository added in v0.25.0

type AutoPublishRepository struct {
	// Path is the repository's root on this computer.
	Path string `json:"path" minLength:"1"`
	// Label is the repository's schema.RemoteLabel, present when it has a
	// remote.
	Label string            `json:"label,omitempty"`
	Hooks []AutoPublishHook `json:"hooks" nullable:"false"`
}

AutoPublishRepository is one recorded repository a rule matches, with the state of its hook for each of the rule's events.

func (AutoPublishRepository) Validate added in v0.25.0

func (r AutoPublishRepository) Validate() error

Validate checks the repository and that each event appears once.

type AutoPublishRule added in v0.25.0

type AutoPublishRule struct {
	ID           string                  `json:"id" minLength:"1"`
	Kind         AutoPublishRuleKind     `json:"kind"`
	Match        string                  `json:"match" minLength:"1"`
	Events       []AutoPublishEvent      `json:"events" nullable:"false"`
	Collectives  []VillageUUID           `json:"collectives" nullable:"false"`
	Repositories []AutoPublishRepository `json:"repositories" nullable:"false"`
}

AutoPublishRule is one saved auto-publish rule with the recorded repositories it matches. Saving a rule installs nothing: each repository reports its hooks as they are, and installing is a separate call per repository.

func (AutoPublishRule) Validate added in v0.25.0

func (r AutoPublishRule) Validate() error

Validate checks the rule, each repository, and that every repository reports exactly the rule's events.

type AutoPublishRuleKind added in v0.25.0

type AutoPublishRuleKind string

AutoPublishRuleKind says what a rule's match pattern names.

const (
	// AutoPublishRuleFolder: Match is a folder glob on this computer.
	AutoPublishRuleFolder AutoPublishRuleKind = "folder"
	// AutoPublishRuleRemote: Match is a git remote pattern.
	AutoPublishRuleRemote AutoPublishRuleKind = "remote"
)

func (AutoPublishRuleKind) IsValid added in v0.25.0

func (k AutoPublishRuleKind) IsValid() bool

func (AutoPublishRuleKind) JSONSchema added in v0.25.0

func (AutoPublishRuleKind) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (AutoPublishRuleKind) String added in v0.25.0

func (k AutoPublishRuleKind) String() string

type AutoPublishRuleRequest added in v0.25.0

type AutoPublishRuleRequest struct {
	Kind        AutoPublishRuleKind `json:"kind,omitempty"`
	Match       string              `json:"match,omitempty" minLength:"1"`
	SessionID   *SessionID          `json:"sessionId,omitempty" nullable:"false"`
	Events      []AutoPublishEvent  `json:"events" nullable:"false"`
	Collectives []VillageUUID       `json:"collectives" nullable:"false"`
}

AutoPublishRuleRequest is the body of PUT /api/v1/settings/auto-publish/{id}. An explicit pattern names Kind and Match. A session target instead names SessionID: the server resolves that stored session's directory to its current Git repository and saves an escaped exact-folder rule for that root. The two targets are mutually exclusive. A missing session, missing directory or failed Git resolution is refused before saving, without a remote or cwd fallback. An empty Events list keeps the rule and publishes nothing. Saving installs nothing; installing remains a separate explicit request.

func (AutoPublishRuleRequest) PrepareJSONSchema added in v0.27.0

func (AutoPublishRuleRequest) PrepareJSONSchema(s *jsonschema.Schema) error

PrepareJSONSchema keeps the existing pattern body and the session-target body distinct in every generated validator, including their property presence.

func (*AutoPublishRuleRequest) UnmarshalJSON added in v0.27.0

func (r *AutoPublishRuleRequest) UnmarshalJSON(data []byte) error

UnmarshalJSON preserves target exclusivity even when an explicit pattern property is empty. Null is not an omitted session target.

func (AutoPublishRuleRequest) Validate added in v0.25.0

func (r AutoPublishRuleRequest) Validate() error

Validate checks the mutually exclusive target and each event and collective.

type BatchCreateAnnotationsErrorResponse

type BatchCreateAnnotationsErrorResponse struct {
	Error        string `json:"error"`
	FailingIndex int    `json:"failingIndex"`
}

BatchCreateAnnotationsErrorResponse is the JSON error response for POST /api/v1/annotations/batch (400). FailingIndex is the zero-based index of the first annotation that failed validation.

type BatchCreateAnnotationsRequest

type BatchCreateAnnotationsRequest struct {
	Annotations []CreateAnnotationRequest `json:"annotations"`
}

BatchCreateAnnotationsRequest is the JSON body for POST /api/v1/annotations/batch. All annotations are committed as a single all-or-nothing SQLite transaction.

type BatchCreateAnnotationsResponse

type BatchCreateAnnotationsResponse struct {
	IDs []string `json:"ids"`
}

BatchCreateAnnotationsResponse is the JSON response for POST /api/v1/annotations/batch (201 Created). IDs are returned in the same order as the request Annotations slice.

type BuiltinCommand

type BuiltinCommand string

BuiltinCommand represents a built-in slash command supported by Claude Code. These are first-party commands that ship with the tool (e.g. /exit, /compact). Slash-command entries in transcripts whose name matches a BuiltinCommand are structural signals rather than user-initiated tool calls.

const (
	ClaudeBuiltinCmdExit             BuiltinCommand = "exit"
	ClaudeBuiltinCmdCompact          BuiltinCommand = "compact"
	ClaudeBuiltinCmdClear            BuiltinCommand = "clear"
	ClaudeBuiltinCmdNew              BuiltinCommand = "new"
	ClaudeBuiltinCmdModel            BuiltinCommand = "model"
	ClaudeBuiltinCmdUsage            BuiltinCommand = "usage"
	ClaudeBuiltinCmdCost             BuiltinCommand = "cost"
	ClaudeBuiltinCmdContext          BuiltinCommand = "context"
	ClaudeBuiltinCmdPlugin           BuiltinCommand = "plugin"
	ClaudeBuiltinCmdPermissions      BuiltinCommand = "permissions"
	ClaudeBuiltinCmdLogin            BuiltinCommand = "login"
	ClaudeBuiltinCmdResume           BuiltinCommand = "resume"
	ClaudeBuiltinCmdPlan             BuiltinCommand = "plan"
	ClaudeBuiltinCmdFast             BuiltinCommand = "fast"
	ClaudeBuiltinCmdVoice            BuiltinCommand = "voice"
	ClaudeBuiltinCmdTodos            BuiltinCommand = "todos"
	ClaudeBuiltinCmdReloadPlugins    BuiltinCommand = "reload-plugins"
	ClaudeBuiltinCmdSandbox          BuiltinCommand = "sandbox"
	ClaudeBuiltinCmdConfig           BuiltinCommand = "config"
	ClaudeBuiltinCmdStatusline       BuiltinCommand = "statusline"
	ClaudeBuiltinCmdUpgrade          BuiltinCommand = "upgrade"
	ClaudeBuiltinCmdExtraUsage       BuiltinCommand = "extra-usage"
	ClaudeBuiltinCmdRateLimitOptions BuiltinCommand = "rate-limit-options"
	ClaudeBuiltinCmdPrivacySettings  BuiltinCommand = "privacy-settings"
	ClaudeBuiltinCmdHelp             BuiltinCommand = "help"
	ClaudeBuiltinCmdCommands         BuiltinCommand = "commands"
)

func (BuiltinCommand) IsValid

func (c BuiltinCommand) IsValid() bool

IsValid returns true if the command is one of the known built-in variants. Derived from AllClaudeBuiltinCmds (single source of truth).

func (BuiltinCommand) JSONSchema

func (BuiltinCommand) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (BuiltinCommand) String

func (c BuiltinCommand) String() string

type CLILoginQuery

type CLILoginQuery struct {
	Port  int    `json:"port" query:"port" description:"Local callback server port"`
	State string `json:"state" query:"state" description:"OAuth state parameter for CSRF protection"`
}

CLILoginQuery represents the query parameters for the CLI login initiation endpoint. GET /api/v1/auth/cli/login?port={port}&state={state}

type CanonicalPublishGitContext

type CanonicalPublishGitContext struct {
	Branch   *string                   `json:"branch"`
	Remote   *string                   `json:"remote"`
	Worktree *string                   `json:"worktree"`
	Tracking *string                   `json:"tracking"`
	Commits  []AuthoritativeCommitInfo `json:"commits" nullable:"false"`
}

type CanonicalPublishOperation

type CanonicalPublishOperation struct {
	Replacement  CanonicalPublishReplacement `json:"replacement"`
	License      PublishLicenseOperation     `json:"license"`
	Associations PublishAssociationOperation `json:"associations"`
	ContentHash  TranscriptContentHash       `json:"contentHash"`
}

func DecodeCanonicalPublishOperation

func DecodeCanonicalPublishOperation(data []byte) (CanonicalPublishOperation, error)

func (CanonicalPublishOperation) Validate

func (operation CanonicalPublishOperation) Validate() error

type CanonicalPublishReplacement

type CanonicalPublishReplacement struct {
	Identity    AuthoritativeSessionIdentity `json:"identity"`
	Model       AuthoritativeModelInfo       `json:"model"`
	Timestamp   AuthoritativeTimestampInfo   `json:"timestamp"`
	Source      AuthoritativeSourceInfo      `json:"source"`
	Git         CanonicalPublishGitContext   `json:"git"`
	Project     AuthoritativeProjectContext  `json:"project"`
	Stats       AuthoritativeSessionStats    `json:"stats"`
	Quality     *AuthoritativeQualityMetrics `json:"quality"`
	Entries     []AuthoritativeSessionEntry  `json:"entries" nullable:"false"`
	Subagents   []AuthoritativeSubagentRef   `json:"subagents" nullable:"false"`
	Diagnostics AuthoritativeDiagnosticsInfo `json:"diagnostics"`
}

type ChangeBinding

type ChangeBinding string

ChangeBinding states how strongly a session is tied to a change (contract §2 binding rule, spec §6.2).

const (
	ChangeBindingBound     ChangeBinding = "bound"
	ChangeBindingCandidate ChangeBinding = "candidate"
)

ChangeBinding values. A session is bound when at least one of its linked commits is contained in the branch AND its recorded edits overlap the branch's changed files; one-arm matches (or git_branch equality alone) are candidates. Candidates are never silently dropped.

func (ChangeBinding) IsValid

func (b ChangeBinding) IsValid() bool

IsValid reports whether b is one of the defined bindings.

func (ChangeBinding) JSONSchema

func (ChangeBinding) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (ChangeBinding) String

func (b ChangeBinding) String() string

String returns the wire representation of the binding.

type ChangeDetailPayload

type ChangeDetailPayload struct {
	Branch            string          `json:"branch"`
	BaseRef           string          `json:"baseRef"` // merge-base hash
	DefaultBranch     string          `json:"defaultBranch"`
	Files             []FileChange    `json:"files"`
	Slice             MapSlice        `json:"slice"` // touched nodes + 1-hop
	NewEdges          []MapEdge       `json:"newEdges"`
	RemovedEdges      []MapEdge       `json:"removedEdges"`
	NewNodes          []string        `json:"newNodes"` // node IDs
	RemovedNodes      []string        `json:"removedNodes"`
	Violations        []EdgeViolation `json:"violations"` // NEW violations introduced by this change
	Work              []ChangeSession `json:"work"`
	UnrecordedCommits []CommitRef     `json:"unrecordedCommits"`
	// Unusual holds NEUTRAL rate-elevation observations vs the project baseline
	// (e.g. more retry loops per conversation than usual) — facts, never a
	// verdict or grade.
	Unusual []UnusualSignal `json:"unusual"`
	// Frictions holds NEUTRAL recurring-friction counts keyed by (kind, file):
	// "this kind of friction touched this file N times across M conversations"
	// Facts are for orientation, never a verdict.
	Frictions []FrictionCluster `json:"frictions"`
	// Insights carries mechanical and mined insight envelopes for this change.
	// It is additive alongside Unusual/Frictions above, never a replacement
	// for them.
	Insights     []SessionInsight `json:"insights" required:"true" nullable:"false"`
	LinesAdded   int              `json:"linesAdded"`
	LinesRemoved int              `json:"linesRemoved"`
	OutputTokens int64            `json:"outputTokens"` // SUM of output_tokens over bound sessions
	CostUsd      *float64         `json:"costUsd,omitempty"`
}

ChangeDetailPayload backs the Review change-detail surface, served by GET /api/v1/review/{projectHash}/change?branch=<name>.

func NewChangeDetailPayload

func NewChangeDetailPayload(branch string) *ChangeDetailPayload

NewChangeDetailPayload returns a ChangeDetailPayload with all slices (including the nested MapSlice's) initialized to empty (never-nil marshal guarantee).

func (ChangeDetailPayload) Validate

func (p ChangeDetailPayload) Validate() error

Validate checks that Insights is non-nil and every entry is well-formed, including the Classification-must-be-nil rule. It also validates each UnrecordedCommit's shape. Other ChangeDetailPayload fields do not currently define validation rules here.

type ChangeDiffPayload

type ChangeDiffPayload struct {
	Branch    string           `json:"branch"`
	File      string           `json:"file"` // the new path
	OldPath   *string          `json:"oldPath,omitempty"`
	Status    FileChangeStatus `json:"status"`
	Binary    bool             `json:"binary"`
	Truncated bool             `json:"truncated"`
	Hunks     []DiffHunk       `json:"hunks"`
}

ChangeDiffPayload is the rendered unified diff of ONE changed file of a change (branch vs its merge-base with the default branch) — the lazy per-file companion to ChangeDetailPayload (contract §3, GET /review/{projectHash}/diff ?branch=&file=). Binary files come back Binary=true with no hunks; files exceeding the size cap come back Truncated.

func NewChangeDiffPayload

func NewChangeDiffPayload(branch, file string) *ChangeDiffPayload

NewChangeDiffPayload returns a ChangeDiffPayload with Hunks initialized to empty (never-nil marshal guarantee).

type ChangeSession

type ChangeSession struct {
	SessionID string        `json:"sessionId"`
	Title     string        `json:"title"`
	Harness   string        `json:"harness"`
	StartMs   *int64        `json:"startMs,omitempty"`
	Binding   ChangeBinding `json:"binding"` // bound = commit-in-branch AND touch overlap; candidate = one arm only
	Tasks     []TaskSummary `json:"tasks"`
}

ChangeSession is one recorded session behind a change, with its tasks.

func NewChangeSession

func NewChangeSession(sessionID string, binding ChangeBinding) ChangeSession

NewChangeSession returns a ChangeSession with all slices initialized to empty (never-nil marshal guarantee).

type ChangeSummary

type ChangeSummary struct {
	Branch       string `json:"branch"`
	AheadCount   int    `json:"aheadCount"`
	BehindCount  int    `json:"behindCount"`
	FilesChanged int    `json:"filesChanged"`
	SessionCount int    `json:"sessionCount"`
	TaskCount    int    `json:"taskCount"`
	NewEdges     int    `json:"newEdges"`
	RemovedEdges int    `json:"removedEdges"`
	Violations   int    `json:"violations"`
	LastWorkMs   *int64 `json:"lastWorkMs,omitempty"`
	Merged       bool   `json:"merged"`
	MergedAtMs   *int64 `json:"mergedAtMs,omitempty"`
	// Reverted is true when this change was merged and later undone by a
	// `git revert` on the default branch (git-native signal only).
	Reverted bool `json:"reverted,omitempty"`

	// Graph anchors (Changes graph): how this row attaches to lane 0
	// (ReviewListPayload.RecentCommits). Open branches fork at BaseHash and
	// sit at TipCommitMs; merged rows rejoin at MergeCommitHash.
	BaseHash        string `json:"baseHash,omitempty"`        // merge-base commit hash (fork anchor; open branches)
	TipCommitMs     *int64 `json:"tipCommitMs,omitempty"`     // branch tip committer time (row position; open branches)
	MergeCommitHash string `json:"mergeCommitHash,omitempty"` // merge commit hash (join anchor; merged rows)
}

ChangeSummary is one row of the Review list: a local branch measured against the default branch.

type ChannelSubscription

type ChannelSubscription struct {
	Topic ChannelTopic   `json:"topic"`
	ID    string         `json:"id,omitempty"`
	Axis  AnnotationAxis `json:"axis,omitempty"`
}

ChannelSubscription describes a single channel subscription. Topic is always required. Additional fields are topic-specific:

  • TopicSessionDetail: ID = session ID
  • TopicAnnotations: Axis + ID

type ChannelTopic

type ChannelTopic string

ChannelTopic identifies a subscribable data stream.

const (
	TopicDashboard          ChannelTopic = "dashboard"
	TopicSessions           ChannelTopic = "sessions"
	TopicSessionDetail      ChannelTopic = "session_detail"
	TopicTrends             ChannelTopic = "trends"
	TopicQuality            ChannelTopic = "quality"
	TopicAnnotations        ChannelTopic = "annotations"
	TopicProjectFamiliarity ChannelTopic = "project_familiarity"
)

func (ChannelTopic) IsValid

func (t ChannelTopic) IsValid() bool

IsValid reports whether t is a defined WebSocket channel topic.

func (ChannelTopic) JSONSchema

func (ChannelTopic) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (ChannelTopic) String

func (t ChannelTopic) String() string

String returns the wire representation of the channel topic.

type ChildSessionRef

type ChildSessionRef struct {
	ID        string    `json:"id"`
	StartTime time.Time `json:"startTime"`
	Project   string    `json:"project,omitempty"`
}

ChildSessionRef is a lightweight reference to a child (subagent) session.

type ClientMessage

type ClientMessage struct {
	Type     MessageType           `json:"type"`
	Channels []ChannelSubscription `json:"channels,omitempty"`
}

ClientMessage is sent from the browser to the server via WebSocket.

type CollectiveEvidenceCoverage added in v0.31.0

type CollectiveEvidenceCoverage string
const (
	CollectiveEvidenceCoverageAvailable CollectiveEvidenceCoverage = "available"
	CollectiveEvidenceCoverageUnknown   CollectiveEvidenceCoverage = "unknown"
)

func (CollectiveEvidenceCoverage) IsValid added in v0.31.0

func (v CollectiveEvidenceCoverage) IsValid() bool

func (CollectiveEvidenceCoverage) JSONSchema added in v0.31.0

type CollectiveFetchAssociationResults added in v0.31.0

type CollectiveFetchAssociationResults struct {
	Requested int                                     `json:"requested" minimum:"0" maximum:"10000"`
	Completed int                                     `json:"completed" minimum:"0" maximum:"10000"`
	Failed    int                                     `json:"failed" minimum:"0" maximum:"10000"`
	Scopes    []CollectiveFetchAssociationScopeResult `json:"scopes" maxItems:"10000" nullable:"false"`
}

func (*CollectiveFetchAssociationResults) UnmarshalJSON added in v0.31.0

func (v *CollectiveFetchAssociationResults) UnmarshalJSON(data []byte) error

type CollectiveFetchAssociationScopeResult added in v0.31.0

type CollectiveFetchAssociationScopeResult struct {
	TranscriptID TranscriptID          `json:"transcriptId"`
	State        CollectiveFetchState  `json:"state"`
	Commit       CollectiveFetchCommit `json:"commit"`
	ObservedAt   *time.Time            `json:"observedAt,omitempty"`
	CompletedAt  *time.Time            `json:"completedAt,omitempty"`
	Issue        *OperationIssue       `json:"issue,omitempty"`
}

func (*CollectiveFetchAssociationScopeResult) UnmarshalJSON added in v0.31.0

func (v *CollectiveFetchAssociationScopeResult) UnmarshalJSON(data []byte) error

type CollectiveFetchCommit added in v0.31.0

type CollectiveFetchCommit string
const (
	CollectiveFetchCommitUpdated   CollectiveFetchCommit = "updated"
	CollectiveFetchCommitUnchanged CollectiveFetchCommit = "unchanged"
	CollectiveFetchCommitRetained  CollectiveFetchCommit = "retained"
)

func (CollectiveFetchCommit) IsValid added in v0.31.0

func (v CollectiveFetchCommit) IsValid() bool

func (CollectiveFetchCommit) JSONSchema added in v0.31.0

func (CollectiveFetchCommit) JSONSchema() (jsonschema.Schema, error)

type CollectiveFetchDomain added in v0.31.0

type CollectiveFetchDomain string
const (
	CollectiveFetchDomainCatalog      CollectiveFetchDomain = "catalog"
	CollectiveFetchDomainHistory      CollectiveFetchDomain = "history"
	CollectiveFetchDomainAssociations CollectiveFetchDomain = "associations"
)

func (CollectiveFetchDomain) IsValid added in v0.31.0

func (v CollectiveFetchDomain) IsValid() bool

func (CollectiveFetchDomain) JSONSchema added in v0.31.0

func (CollectiveFetchDomain) JSONSchema() (jsonschema.Schema, error)

type CollectiveFetchDomainResult added in v0.31.0

type CollectiveFetchDomainResult struct {
	Domain                CollectiveFetchDomain              `json:"domain"`
	Requested             bool                               `json:"requested"`
	State                 CollectiveFetchState               `json:"state"`
	Commit                CollectiveFetchCommit              `json:"commit"`
	StartedAt             *time.Time                         `json:"startedAt,omitempty"`
	LastAttemptAt         *time.Time                         `json:"lastAttemptAt,omitempty"`
	CompletedAt           *time.Time                         `json:"completedAt,omitempty"`
	LastCompletedAt       *time.Time                         `json:"lastCompletedAt,omitempty"`
	LastInstalledRevision *string                            `json:"lastInstalledRevision,omitempty"`
	Coverage              CollectiveEvidenceCoverage         `json:"coverage"`
	SourceOutcomes        []CollectiveFetchSourceResult      `json:"sourceOutcomes" maxItems:"10000" nullable:"false"`
	Associations          *CollectiveFetchAssociationResults `json:"associations,omitempty"`
	Issue                 *OperationIssue                    `json:"issue,omitempty"`
}

func (*CollectiveFetchDomainResult) UnmarshalJSON added in v0.31.0

func (v *CollectiveFetchDomainResult) UnmarshalJSON(data []byte) error

func (CollectiveFetchDomainResult) Validate added in v0.31.0

func (d CollectiveFetchDomainResult) Validate() error

type CollectiveFetchDomainSummary added in v0.31.0

type CollectiveFetchDomainSummary struct {
	LastAttemptAt         *time.Time                 `json:"lastAttemptAt,omitempty"`
	LastCompletedAt       *time.Time                 `json:"lastCompletedAt,omitempty"`
	LastInstalledRevision *string                    `json:"lastInstalledRevision,omitempty"`
	State                 CollectiveFetchState       `json:"state"`
	Coverage              CollectiveEvidenceCoverage `json:"coverage"`
	Issue                 *OperationIssue            `json:"issue,omitempty"`
}

func (*CollectiveFetchDomainSummary) UnmarshalJSON added in v0.31.0

func (v *CollectiveFetchDomainSummary) UnmarshalJSON(data []byte) error

func (CollectiveFetchDomainSummary) Validate added in v0.31.0

func (s CollectiveFetchDomainSummary) Validate() error

type CollectiveFetchOutcome added in v0.31.0

type CollectiveFetchOutcome string
const (
	CollectiveFetchOutcomeComplete CollectiveFetchOutcome = "complete"
	CollectiveFetchOutcomePartial  CollectiveFetchOutcome = "partial"
	CollectiveFetchOutcomeFailed   CollectiveFetchOutcome = "failed"
)

func (CollectiveFetchOutcome) IsValid added in v0.31.0

func (v CollectiveFetchOutcome) IsValid() bool

func (CollectiveFetchOutcome) JSONSchema added in v0.31.0

type CollectiveFetchReport added in v0.31.0

type CollectiveFetchReport struct {
	Scope         CollectiveObservationScope    `json:"scope"`
	InvocationID  VillageUUID                   `json:"invocationId"`
	CacheRevision string                        `json:"cacheRevision" pattern:"^(0|[1-9][0-9]{0,19})$"`
	Outcome       CollectiveFetchOutcome        `json:"outcome"`
	Domains       []CollectiveFetchDomainResult `json:"domains" minItems:"3" maxItems:"3" nullable:"false"`
	Issues        []OperationIssue              `json:"issues" maxItems:"10000" nullable:"false"`
}

func (*CollectiveFetchReport) UnmarshalJSON added in v0.31.0

func (v *CollectiveFetchReport) UnmarshalJSON(data []byte) error

func (CollectiveFetchReport) Validate added in v0.31.0

func (r CollectiveFetchReport) Validate() error

type CollectiveFetchSourceResult added in v0.31.0

type CollectiveFetchSourceResult struct {
	Source     CollectiveObservationSource `json:"source"`
	Outcome    CollectiveSourceOutcome     `json:"outcome"`
	ObservedAt *time.Time                  `json:"observedAt,omitempty"`
	Complete   bool                        `json:"complete"`
	Issue      *OperationIssue             `json:"issue,omitempty"`
}

func (*CollectiveFetchSourceResult) UnmarshalJSON added in v0.31.0

func (v *CollectiveFetchSourceResult) UnmarshalJSON(data []byte) error

type CollectiveFetchState added in v0.31.0

type CollectiveFetchState string
const (
	CollectiveFetchStateComplete     CollectiveFetchState = "complete"
	CollectiveFetchStateFailed       CollectiveFetchState = "failed"
	CollectiveFetchStateCancelled    CollectiveFetchState = "cancelled"
	CollectiveFetchStateSuperseded   CollectiveFetchState = "superseded"
	CollectiveFetchStateNotRequested CollectiveFetchState = "not_requested"
)

func (CollectiveFetchState) IsValid added in v0.31.0

func (v CollectiveFetchState) IsValid() bool

func (CollectiveFetchState) JSONSchema added in v0.31.0

func (CollectiveFetchState) JSONSchema() (jsonschema.Schema, error)

type CollectiveFetchSummary added in v0.31.0

type CollectiveFetchSummary struct {
	LastCompletedFetchAt *time.Time                   `json:"lastCompletedFetchAt,omitempty"`
	LastAttemptAt        *time.Time                   `json:"lastAttemptAt,omitempty"`
	LatestReport         *CollectiveFetchReport       `json:"latestReport,omitempty"`
	Catalog              CollectiveFetchDomainSummary `json:"catalog"`
	History              CollectiveFetchDomainSummary `json:"history"`
	Associations         CollectiveFetchDomainSummary `json:"associations"`
}

func (*CollectiveFetchSummary) UnmarshalJSON added in v0.31.0

func (v *CollectiveFetchSummary) UnmarshalJSON(data []byte) error

func (CollectiveFetchSummary) Validate added in v0.31.0

func (s CollectiveFetchSummary) Validate() error

type CollectiveObservation added in v0.31.0

type CollectiveObservation struct {
	ID             VillageUUID                   `json:"id"`
	Name           string                        `json:"name"`
	Description    *string                       `json:"description,omitempty"`
	AcceptanceMode *VillageGroupAcceptanceMode   `json:"acceptanceMode,omitempty"`
	DataAccess     *VillageGroupDataAccess       `json:"dataAccess,omitempty"`
	Reasons        []CollectiveObservationReason `json:"reasons" nullable:"false" maxItems:"4"`
	ObservedAt     time.Time                     `json:"observedAt"`
	State          CollectiveObservationState    `json:"state"`
}

func (*CollectiveObservation) UnmarshalJSON added in v0.31.0

func (v *CollectiveObservation) UnmarshalJSON(data []byte) error

func (CollectiveObservation) Validate added in v0.31.0

func (o CollectiveObservation) Validate() error

type CollectiveObservationReason added in v0.31.0

type CollectiveObservationReason string
const (
	CollectiveObservationReasonMembership   CollectiveObservationReason = "membership"
	CollectiveObservationReasonContribution CollectiveObservationReason = "contribution"
	CollectiveObservationReasonOrganization CollectiveObservationReason = "organization"
	CollectiveObservationReasonExplicit     CollectiveObservationReason = "explicit"
)

func (CollectiveObservationReason) IsValid added in v0.31.0

func (v CollectiveObservationReason) IsValid() bool

func (CollectiveObservationReason) JSONSchema added in v0.31.0

type CollectiveObservationResponse added in v0.31.0

type CollectiveObservationResponse struct {
	Scope         CollectiveObservationScope `json:"scope"`
	CacheRevision string                     `json:"cacheRevision" pattern:"^(0|[1-9][0-9]{0,19})$"`
	Collectives   []CollectiveObservation    `json:"collectives" maxItems:"10000" nullable:"false"`
	Fetch         CollectiveFetchSummary     `json:"fetch"`
}

func (*CollectiveObservationResponse) UnmarshalJSON added in v0.31.0

func (v *CollectiveObservationResponse) UnmarshalJSON(data []byte) error

func (CollectiveObservationResponse) Validate added in v0.31.0

func (r CollectiveObservationResponse) Validate() error

type CollectiveObservationScope added in v0.31.0

type CollectiveObservationScope struct {
	VillageURL string      `json:"villageUrl" maxLength:"1024"`
	UserID     VillageUUID `json:"userId"`
}

CollectiveObservationScope identifies private evidence, never credentials or authority. The caller selects its authenticated scope before validating tokens.

func NormalizeCollectiveObservationScope added in v0.31.0

func NormalizeCollectiveObservationScope(raw string, userID VillageUUID) (CollectiveObservationScope, error)

func (*CollectiveObservationScope) UnmarshalJSON added in v0.31.0

func (v *CollectiveObservationScope) UnmarshalJSON(data []byte) error

func (CollectiveObservationScope) Validate added in v0.31.0

func (s CollectiveObservationScope) Validate() error

type CollectiveObservationSource added in v0.31.0

type CollectiveObservationSource string
const (
	CollectiveObservationSourceMembership            CollectiveObservationSource = "membership"
	CollectiveObservationSourceContributionDiscovery CollectiveObservationSource = "contribution-discovery"
	CollectiveObservationSourceOrganization          CollectiveObservationSource = "organization"
	CollectiveObservationSourceExplicit              CollectiveObservationSource = "explicit"
	CollectiveObservationSourceSubmissions           CollectiveObservationSource = "submissions"
	CollectiveObservationSourceAttempts              CollectiveObservationSource = "attempts"
	CollectiveObservationSourceAssociations          CollectiveObservationSource = "associations"
)

func (CollectiveObservationSource) IsValid added in v0.31.0

func (v CollectiveObservationSource) IsValid() bool

func (CollectiveObservationSource) JSONSchema added in v0.31.0

type CollectiveObservationState added in v0.31.0

type CollectiveObservationState string
const (
	CollectiveObservationStateObserved    CollectiveObservationState = "observed"
	CollectiveObservationStateUnavailable CollectiveObservationState = "unavailable"
	CollectiveObservationStateInvalidated CollectiveObservationState = "invalidated"
)

func (CollectiveObservationState) IsValid added in v0.31.0

func (v CollectiveObservationState) IsValid() bool

func (CollectiveObservationState) JSONSchema added in v0.31.0

type CollectiveOperation added in v0.31.0

type CollectiveOperation string
const (
	CollectiveOperationPublish CollectiveOperation = "publish"
	CollectiveOperationShare   CollectiveOperation = "share"
	CollectiveOperationFetch   CollectiveOperation = "fetch"
	CollectiveOperationPull    CollectiveOperation = "pull"
)

func (CollectiveOperation) IsValid added in v0.31.0

func (v CollectiveOperation) IsValid() bool

func (CollectiveOperation) JSONSchema added in v0.31.0

func (CollectiveOperation) JSONSchema() (jsonschema.Schema, error)

type CollectiveSourceOutcome added in v0.31.0

type CollectiveSourceOutcome string
const (
	CollectiveSourceDisclosed    CollectiveSourceOutcome = "disclosed"
	CollectiveSourceNotDisclosed CollectiveSourceOutcome = "not_disclosed"
	CollectiveSourceFailed       CollectiveSourceOutcome = "failed"
)

func (CollectiveSourceOutcome) IsValid added in v0.31.0

func (v CollectiveSourceOutcome) IsValid() bool

func (CollectiveSourceOutcome) JSONSchema added in v0.31.0

type CommandInvocation added in v0.17.0

type CommandInvocation struct {
	Name string `json:"name"`
	Args string `json:"args,omitempty"`
}

CommandInvocation records that a turn invoked a skill or a user-defined slash command rather than typing a prompt. Name is slash-prefixed, for example "/superpowers:brainstorming". Args is the text that followed the command on the same line and may be empty. A harness that records a bare command name gets the slash added by the producer before construction; the constructor does not add it.

Built-in harness commands (see BuiltinCommand) are structural signals and are never emitted as a CommandInvocation.

Compatibility: the field is optional and safely ignorable. The invocation name is already present in the turn's content text, so a consumer that drops the field loses a structured duplicate, not meaning, provenance, or safety. Under docs/content-capability-negotiation.md that is an additive minor bump with no content-capability token.

func NewCommandInvocation added in v0.17.0

func NewCommandInvocation(name, args string) (CommandInvocation, error)

NewCommandInvocation validates and constructs a CommandInvocation. Name must be a single slash-prefixed token that is not a built-in harness command. Args is carried as given.

func (CommandInvocation) Validate added in v0.17.0

func (c CommandInvocation) Validate() error

Validate reports whether c would be accepted by NewCommandInvocation.

type CommitInfo

type CommitInfo struct {
	Hash        string `json:"hash"`        // commit SHA-1 (full or abbreviated)
	Message     string `json:"message"`     // commit message first line
	AuthorName  string `json:"authorName"`  // author display name
	AuthorEmail string `json:"authorEmail"` // author email (used for attribution filtering)
	CommitTime  int64  `json:"commitTime"`  // committer date, Unix millis
	AuthorTime  int64  `json:"authorTime"`  // author date, Unix millis
}

CommitInfo records a single git commit linked to a session.

type CommitRef

type CommitRef struct {
	Hash       string `json:"hash" yaml:"hash"`
	Subject    string `json:"subject" yaml:"subject"`
	TimeMs     *int64 `json:"timeMs,omitempty" yaml:"timeMs,omitempty"`
	HasSession bool   `json:"hasSession" yaml:"hasSession"` // compatibility mirror of len(SessionIDs) > 0
	// SessionIDs names authoritative session_commits bindings in the same
	// strictly increasing rank order as ReviewListPayload.Sessions.
	SessionIDs []SessionID `json:"sessionIds" yaml:"sessionIds" required:"true" nullable:"false"`
	// Associations keeps each SessionIDs binding as a first-class durable
	// relationship with its conclusion, confidence, and atomic observations. It
	// mirrors SessionIDs one-for-one in the same rank order:
	// Associations[i].SessionID == SessionIDs[i] for every i.
	Associations []SessionAssociation `json:"associations" yaml:"associations" required:"true" nullable:"false"`
}

CommitRef is lightweight commit metadata for time strips and rail panels.

func NewCommitRef

func NewCommitRef(hash, subject string) CommitRef

NewCommitRef returns commit metadata with non-nil session ID and association arrays.

type Confidence

type Confidence string

Confidence classifies how strongly the evidence behind a derived relationship (a session<->commit association, or a ghost-commit rewrite resolution) supports its conclusion.

const (
	ConfidenceHigh   Confidence = "high"
	ConfidenceMedium Confidence = "medium"
	ConfidenceLow    Confidence = "low"
)

Confidence values.

func (Confidence) IsValid

func (c Confidence) IsValid() bool

IsValid reports whether c is one of the defined confidence levels.

func (Confidence) JSONSchema

func (Confidence) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (Confidence) String

func (c Confidence) String() string

String returns the wire representation of the confidence level.

func (Confidence) Validate

func (c Confidence) Validate() error

Validate rejects values that cannot cross the confidence wire boundary.

type ContentCapability added in v0.1.1

type ContentCapability string

ContentCapability identifies an optional transcript-content behavior that a client must negotiate before emitting evidence that older servers may lose.

const (
	// ContentCapabilityObservedModelV1 guarantees exact observedModel survival
	// through publish, typed migration, canonical rewrite, and re-emission. Its
	// meaning is immutable; an incompatible contract requires a new token.
	ContentCapabilityObservedModelV1  ContentCapability = "observed_model_v1"
	ContentCapabilityDetailedUsageV1  ContentCapability = "detailed_usage_v1"
	ContentCapabilityNativeMetadataV1 ContentCapability = "native_metadata_v1"
	// ContentCapabilitySessionGraphProvenanceV1 guarantees preservation of
	// durable session relationships, retained history, submission counts, and
	// per-block provenance.
	ContentCapabilitySessionGraphProvenanceV1 ContentCapability = "session_graph_provenance_v1"
	// ContentCapabilityToolNamespaceV1 guarantees exact separate namespace
	// presence and value survival, including an explicitly recorded empty string.
	ContentCapabilityToolNamespaceV1 ContentCapability = "tool_namespace_v1"
	// ContentCapabilityRetainedUnknownV1 guarantees complete redacted unknown
	// payload, source location, order, and partial-interpretation preservation.
	ContentCapabilityRetainedUnknownV1 ContentCapability = "retained_unknown_v1"
	// ContentCapabilityThinkingLevelV1 guarantees validated, byte-exact
	// preservation of thinkingLevel/thinkingLevelRaw (and their absence) on the
	// session detail and every turn.
	ContentCapabilityThinkingLevelV1 ContentCapability = "thinking_level_v1"
)

func KnownContentCapabilities added in v0.1.1

func KnownContentCapabilities(advertised []ContentCapability) []ContentCapability

KnownContentCapabilities filters unknown discovery tokens, removes duplicates, and returns known tokens in canonical lexicographic order.

func MissingContentCapabilities added in v0.1.1

func MissingContentCapabilities(advertised, required []ContentCapability) []ContentCapability

MissingContentCapabilities returns required tokens absent from discovery. Unknown discovery tokens are ignored and omitted and empty lists are equal.

func RequiredContentCapabilities added in v0.1.1

func RequiredContentCapabilities(payload SessionDetailPayload) []ContentCapability

RequiredContentCapabilities scans root and nested turns for optional evidence. The session-level Model seed is legacy metadata and does not require a capability. An observedModel on any assistant turn, including a nested subagent turn, requires observed_model_v1. A thinkingLevel, thinkingLevelRaw, or non-empty thinkingLevelHistory on the detail, or a thinkingLevel or thinkingLevelRaw on any main or earlier-history turn, requires thinking_level_v1.

func (ContentCapability) IsValid added in v0.1.1

func (c ContentCapability) IsValid() bool

IsValid reports whether c belongs to the closed capability inventory.

func (ContentCapability) JSONSchema added in v0.1.1

func (ContentCapability) JSONSchema() (jsonschema.Schema, error)

JSONSchema deliberately leaves discovery tokens forward-open. Go producers still use Validate and AllContentCapabilities as their closed inventory.

func (ContentCapability) Validate added in v0.1.1

func (c ContentCapability) Validate() error

Validate rejects capability identifiers outside the canonical inventory.

type ContentCapabilityAdvertisementInput added in v0.19.0

type ContentCapabilityAdvertisementInput struct {
	JSON string `yaml:"json"`
}

type ContentCapabilityDetailInput added in v0.19.0

type ContentCapabilityDetailInput struct {
	DetailJSON          string `yaml:"detail_json"`
	ReadJSON            string `yaml:"read_json,omitempty"`
	RejectedDurableJSON string `yaml:"rejected_durable_json,omitempty"`
}

type ContentCapabilityExpected added in v0.19.0

type ContentCapabilityExpected struct {
	Capabilities  []ContentCapability `yaml:"capabilities,omitempty"`
	Known         []ContentCapability `yaml:"known,omitempty"`
	Missing       []ContentCapability `yaml:"missing,omitempty"`
	Accepted      bool                `yaml:"accepted,omitempty"`
	ErrorContains string              `yaml:"error_contains,omitempty"`
}

type ContentCapabilityFixtureNames added in v0.19.0

type ContentCapabilityFixtureNames struct {
	Derivation []string `yaml:"derivation"`
	Reader     []string `yaml:"reader"`
	Producer   []string `yaml:"producer"`
}

type ContentCapabilityProducerInput added in v0.19.0

type ContentCapabilityProducerInput struct {
	Tokens []ContentCapability `yaml:"tokens"`
}

type ContentCapabilitySessionGraphFixtures added in v0.19.0

type ContentCapabilitySessionGraphFixtures struct {
	RequiredNames ContentCapabilityFixtureNames                                                   `yaml:"required_names"`
	Derivation    testcase.Corpus[ContentCapabilityDetailInput, ContentCapabilityExpected]        `yaml:"derivation"`
	Reader        testcase.Corpus[ContentCapabilityAdvertisementInput, ContentCapabilityExpected] `yaml:"reader"`
	Producer      testcase.Corpus[ContentCapabilityProducerInput, ContentCapabilityExpected]      `yaml:"producer"`
}

func DecodeContentCapabilitySessionGraphFixtures added in v0.19.0

func DecodeContentCapabilitySessionGraphFixtures(data []byte) (ContentCapabilitySessionGraphFixtures, error)

DecodeContentCapabilitySessionGraphFixtures strictly decodes a supplied corpus. Generators use this seam to consume the same YAML bytes.

func LoadContentCapabilitySessionGraphFixtures added in v0.19.0

func LoadContentCapabilitySessionGraphFixtures() (ContentCapabilitySessionGraphFixtures, error)

LoadContentCapabilitySessionGraphFixtures exposes the canonical source corpus used by Go validation and by generated TypeScript fixture consumers.

type ContentKind

type ContentKind string

ContentKind discriminates the concrete payload carried inside a TranscriptContent envelope. It exists so the village can dispatch on the kind without sniffing the payload, and so future kinds (e.g. raw-jsonl passthrough) can be added without changing the envelope shape.

const ContentKindSessionDetail ContentKind = "session_detail"

ContentKindSessionDetail marks an envelope whose SessionDetail field carries a normalized SessionDetailPayload. It is the only kind peasant currently emits.

func (ContentKind) IsValid

func (k ContentKind) IsValid() bool

IsValid reports whether k is a defined content envelope kind.

func (ContentKind) JSONSchema

func (ContentKind) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (ContentKind) String

func (k ContentKind) String() string

String returns the bare kind string for serialization/log boundaries.

type ContentOrigin added in v0.19.0

type ContentOrigin string
const (
	ContentOriginSubmittedInput     ContentOrigin = "submitted_input"
	ContentOriginHarnessContext     ContentOrigin = "harness_context"
	ContentOriginAgentOutput        ContentOrigin = "agent_output"
	ContentOriginAgentCommunication ContentOrigin = "agent_communication"
	ContentOriginToolActivity       ContentOrigin = "tool_activity"
	ContentOriginSystemControl      ContentOrigin = "system_control"
	ContentOriginGeneratedSummary   ContentOrigin = "generated_summary"
	ContentOriginUnknown            ContentOrigin = "unknown"
)

func NewContentOrigin added in v0.19.0

func NewContentOrigin(raw string) (ContentOrigin, error)

func (ContentOrigin) IsValid added in v0.19.0

func (v ContentOrigin) IsValid() bool

func (ContentOrigin) JSONSchema added in v0.19.0

func (ContentOrigin) JSONSchema() (jsonschema.Schema, error)

type ContentOwnership added in v0.19.0

type ContentOwnership string
const (
	ContentOwnershipLocal     ContentOwnership = "local"
	ContentOwnershipInherited ContentOwnership = "inherited"
	ContentOwnershipUncertain ContentOwnership = "uncertain"
)

func NewContentOwnership added in v0.19.0

func NewContentOwnership(raw string) (ContentOwnership, error)

func (ContentOwnership) IsValid added in v0.19.0

func (v ContentOwnership) IsValid() bool

func (ContentOwnership) JSONSchema added in v0.19.0

func (ContentOwnership) JSONSchema() (jsonschema.Schema, error)

type ContentProvenance added in v0.19.0

type ContentProvenance struct {
	Origin        ContentOrigin    `json:"origin" yaml:"origin"`
	Actor         ActorOrigin      `json:"actor" yaml:"actor"`
	Delivery      DeliveryOrigin   `json:"delivery" yaml:"delivery"`
	Ownership     ContentOwnership `json:"ownership" yaml:"ownership"`
	Evidence      EvidenceKind     `json:"evidence" yaml:"evidence"`
	InputModality InputModality    `json:"inputModality" yaml:"inputModality"`
	SubmissionRef SubmissionRef    `json:"submissionRef,omitempty" yaml:"submissionRef"`
}

func (ContentProvenance) Validate added in v0.19.0

func (p ContentProvenance) Validate() error

type ContractVersion

type ContractVersion string

ContractVersion is the semantic version of a peasant/village WIRE contract. It is a newtype over string so that the version flows through the codebase typed rather than stringly. The same value-type carries BOTH axes (push and pull): they share one semver shape and one comparison/classification machinery, and the field/constant NAME disambiguates the axis (PushContractVersion vs PullContractVersion). See the PushContractVersion alias below.

It tracks the push/village wire SEPARATELY from:

  • MetadataSchemaVersion (the on-disk {sessionId}--metadata.json structure), and
  • ingest.CurrentIndexVersion (the local indexer evolution),

mirroring the CurrentIndexVersion precedent: a single canonical constant (defaults.PublishSchemaVersion) is the source of truth, bumped on a breaking change to the push wire format.

func (ContractVersion) String

func (v ContractVersion) String() string

String returns the bare semver string for serialization boundaries (OpenAPI filenames, JSON tags handled by the marshaller, CLI output).

type ContributionTraversalIdentity added in v0.31.0

type ContributionTraversalIdentity struct {
	Scope       CollectiveObservationScope    `json:"scope"`
	Incarnation VillageUUID                   `json:"incarnation"`
	Kind        LocalContributionEvidenceKind `json:"kind"`
	Generation  string                        `json:"generation"`
}

ContributionTraversalIdentity is codec input, not an authorization token or a server revision. Generation belongs ONLY to the selected category payload and coverage, never a cache revision, poll timestamp, or joined catalog label.

func ParseContributionTraversalRevision added in v0.31.0

func ParseContributionTraversalRevision(token ContributionTraversalRevision) (ContributionTraversalIdentity, error)

type ContributionTraversalRevision added in v0.31.0

type ContributionTraversalRevision string

func EncodeContributionTraversalRevision added in v0.31.0

func EncodeContributionTraversalRevision(identity ContributionTraversalIdentity) (ContributionTraversalRevision, error)

func (ContributionTraversalRevision) JSONSchema added in v0.31.0

type CreateAnnotationRequest

type CreateAnnotationRequest struct {
	SessionID     string   `json:"sessionId"`
	TypeID        string   `json:"typeId"`
	Value         string   `json:"value"`
	IsPrimary     bool     `json:"isPrimary"`
	Confidence    *float64 `json:"confidence,omitempty"`
	Reason        *string  `json:"reason,omitempty"`
	AnnotatorName string   `json:"annotatorName,omitempty"`
	// Entry-level targeting — if set, creates an annotation_target_entry row.
	// TargetEntryEndIndex defaults to TargetEntryIndex+1 (single-entry span) when omitted.
	TargetEntryIndex    *int `json:"targetEntryIndex,omitempty"`
	TargetEntryEndIndex *int `json:"targetEntryEndIndex,omitempty"`
	// Meta-annotation targeting — if set, creates an annotation_target_annotation row.
	TargetAnnotationID *string `json:"targetAnnotationId,omitempty"`
}

CreateAnnotationRequest is the JSON body for POST /api/v1/annotations. Target selection rules (mutually exclusive):

  • Session-level: SessionID set, no entry/annotation fields.
  • Entry-level: SessionID + TargetEntryIndex set; TargetEntryEndIndex optional (defaults to index+1).
  • Meta-annotation: TargetAnnotationID set (annotation on annotation).

type CreateAnnotationResponse

type CreateAnnotationResponse struct {
	ID string `json:"id"`
}

CreateAnnotationResponse is the JSON response for POST /api/v1/annotations (201 Created).

type DashboardPayload

type DashboardPayload struct {
	TotalSessions      int             `json:"totalSessions"`
	TotalTokens        int             `json:"totalTokens"`
	AvgDurationMins    float64         `json:"avgDurationMins"`
	HarnessBreakdown   map[Harness]int `json:"harnessBreakdown"`
	AvgTurnsPerSession float64         `json:"avgTurnsPerSession"`
	AcceptanceRate     float64         `json:"acceptanceRate"`
}

DashboardPayload is the data sent on the dashboard WebSocket channel.

type DayStats

type DayStats struct {
	Date     string `json:"date"` // "2006-01-02" format
	Tokens   int    `json:"tokens"`
	Sessions int    `json:"sessions"`
}

DayStats holds aggregated data for a single day in trends.

type DecayLevel

type DecayLevel string

DecayLevel classifies how recently a file was engaged.

const (
	DecayFresh      DecayLevel = "fresh"
	DecayFading     DecayLevel = "fading"
	DecayStale      DecayLevel = "stale"
	DecayUnexplored DecayLevel = "unexplored"
)

func (DecayLevel) IsValid

func (d DecayLevel) IsValid() bool

IsValid reports whether d is a defined familiarity decay level.

func (DecayLevel) JSONSchema

func (DecayLevel) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (DecayLevel) String

func (d DecayLevel) String() string

type DeliveryOrigin added in v0.19.0

type DeliveryOrigin string
const (
	DeliveryOriginSessionAdmission DeliveryOrigin = "session_admission"
	DeliveryOriginGuardianReview   DeliveryOrigin = "guardian_review"
	DeliveryOriginSubagentDelivery DeliveryOrigin = "subagent_delivery"
	DeliveryOriginInheritedContext DeliveryOrigin = "inherited_context"
	DeliveryOriginToolDelivery     DeliveryOrigin = "tool_delivery"
	DeliveryOriginSystemLifecycle  DeliveryOrigin = "system_lifecycle"
	DeliveryOriginUnknown          DeliveryOrigin = "unknown"
)

func NewDeliveryOrigin added in v0.19.0

func NewDeliveryOrigin(raw string) (DeliveryOrigin, error)

func (DeliveryOrigin) IsValid added in v0.19.0

func (v DeliveryOrigin) IsValid() bool

func (DeliveryOrigin) JSONSchema added in v0.19.0

func (DeliveryOrigin) JSONSchema() (jsonschema.Schema, error)

type DiagnosticEntry

type DiagnosticEntry struct {
	ErrorType   string `json:"errorType"`   // e.g. "parse_error", "permission_denied", "copy_failed"
	Location    string `json:"location"`    // e.g. "line 47", "debug/tool_output_3.json"
	Message     string `json:"message"`     // Human-readable description
	Remediation string `json:"remediation"` // Actionable fix suggestion
}

DiagnosticEntry is a structured error object recorded during ingestion or processing.

type DiagnosticsInfo

type DiagnosticsInfo struct {
	Warnings []DiagnosticEntry `json:"warnings"`
	Partial  *bool             `json:"partial,omitempty"` // true if any file copy failed; nil if not determined
}

DiagnosticsInfo records issues encountered during ingestion.

type DiffHunk

type DiffHunk struct {
	OldStart int        `json:"oldStart"`
	OldLines int        `json:"oldLines"`
	NewStart int        `json:"newStart"`
	NewLines int        `json:"newLines"`
	Header   string     `json:"header,omitempty"`
	Lines    []DiffLine `json:"lines"`
	// Attribution (the mission climax): the recorded conversation that wrote
	// most of this hunk's added lines, resolved via git blame → commit →
	// session. Empty when the hunk's new lines trace to no recorded session
	// (hand-written, or authored outside this tool).
	SessionID    string `json:"sessionId,omitempty"`
	SessionTitle string `json:"sessionTitle,omitempty"`
}

DiffHunk is one "@@ -oldStart,oldLines +newStart,newLines @@" section. Line numbers in the gutter are derivable from OldStart/NewStart plus position.

type DiffLine

type DiffLine struct {
	Kind DiffLineKind `json:"kind"`
	Text string       `json:"text"`
}

DiffLine is one line within a hunk. Kind is "context" | "add" | "del"; Text excludes the leading +/-/space marker.

type DiffLineKind

type DiffLineKind string

DiffLineKind classifies a unified-diff line.

const (
	DiffLineKindContext DiffLineKind = "context"
	DiffLineKindAdd     DiffLineKind = "add"
	DiffLineKindDelete  DiffLineKind = "del"
)

func (DiffLineKind) IsValid

func (k DiffLineKind) IsValid() bool

IsValid reports whether k is a canonical diff line kind.

func (DiffLineKind) JSONSchema

func (DiffLineKind) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (DiffLineKind) String

func (k DiffLineKind) String() string

String returns the wire representation of the diff line kind.

func (DiffLineKind) Validate

func (k DiffLineKind) Validate() error

Validate rejects values that cannot cross a diff-line wire boundary.

type DigestItemKind added in v0.17.0

type DigestItemKind string

DigestItemKind is the closed set of item kinds in a PromptDigest chain.

const (
	// DigestItemSession marks where one recorded session began.
	DigestItemSession DigestItemKind = "session"
	// DigestItemPrompt is one human-typed user turn.
	DigestItemPrompt DigestItemKind = "prompt"
	// DigestItemSkill marks a skill or user slash-command invocation at the
	// position it happened.
	DigestItemSkill DigestItemKind = "skill"
	// DigestItemCommit anchors the chain to a commit in the pull request.
	DigestItemCommit DigestItemKind = "commit"
)

func (DigestItemKind) IsValid added in v0.17.0

func (k DigestItemKind) IsValid() bool

IsValid reports whether k is a known kind.

func (DigestItemKind) JSONSchema added in v0.17.0

func (DigestItemKind) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (DigestItemKind) String added in v0.17.0

func (k DigestItemKind) String() string

type DurableGraphFixtures added in v0.19.0

type DurableGraphFixtures struct {
	RoundTrip     testcase.Corpus[durableJSONInput, durableRoundTripExpected] `yaml:"round_trip"`
	Counts        testcase.Corpus[durableJSONInput, durableCountExpected]     `yaml:"counts"`
	InvalidCounts testcase.Corpus[durableJSONInput, durableErrorExpected]     `yaml:"invalid_counts"`
	Mirrors       testcase.Corpus[DurableMirrorInput, durableMirrorExpected]  `yaml:"mirrors"`
	Digest        testcase.Corpus[durableDigestInput, durableDigestExpected]  `yaml:"digest"`
	RequiredNames []string                                                    `yaml:"required_names"`
}

func (DurableGraphFixtures) Validate added in v0.19.0

func (c DurableGraphFixtures) Validate() error

type DurableMirrorInput added in v0.19.0

type DurableMirrorInput struct {
	DetailCount        *int64 `yaml:"detail_count"`
	MetadataCount      *int64 `yaml:"metadata_count"`
	Parent             string `yaml:"parent"`
	GraphParent        string `yaml:"graph_parent"`
	DetailRoot         string `yaml:"detail_root"`
	MetadataRoot       string `yaml:"metadata_root"`
	ProjectedMainCount bool   `yaml:"projected_main_count"`
	DetailTurnCount    int    `yaml:"detail_turn_count"`
	MetadataTurnCount  int    `yaml:"metadata_turn_count"`
}

type EarlierHistorySection added in v0.19.0

type EarlierHistorySection struct {
	State          EarlierHistoryState    `json:"state" yaml:"state"`
	Turns          []TurnDetail           `json:"turns" yaml:"turns" nullable:"false"`
	NativeMetadata []NativeMetadataRecord `json:"nativeMetadata,omitempty" yaml:"nativeMetadata"`
}

func (EarlierHistorySection) Validate added in v0.19.0

func (s EarlierHistorySection) Validate() error

type EarlierHistoryState added in v0.19.0

type EarlierHistoryState string
const (
	EarlierHistoryUncertainMigrated   EarlierHistoryState = "uncertain_migrated"
	EarlierHistoryUncertainUnresolved EarlierHistoryState = "uncertain_unresolved"
)

func NewEarlierHistoryState added in v0.19.0

func NewEarlierHistoryState(raw string) (EarlierHistoryState, error)

func (EarlierHistoryState) IsValid added in v0.19.0

func (v EarlierHistoryState) IsValid() bool

func (EarlierHistoryState) JSONSchema added in v0.19.0

func (EarlierHistoryState) JSONSchema() (jsonschema.Schema, error)

type EdgeViolation

type EdgeViolation struct {
	Kind EdgeViolationKind `json:"kind"`
	From string            `json:"from"`
	To   string            `json:"to"`
}

EdgeViolation flags an edge that breaks the layering discipline.

type EdgeViolationKind

type EdgeViolationKind string

EdgeViolationKind classifies a structural violation on the map.

const (
	EdgeViolationCycle    EdgeViolationKind = "cycle"
	EdgeViolationWrongWay EdgeViolationKind = "wrong_way"
)

EdgeViolationKind values (mirrors codegraph's violation kinds).

func (EdgeViolationKind) IsValid

func (k EdgeViolationKind) IsValid() bool

IsValid reports whether k is one of the defined violation kinds.

func (EdgeViolationKind) JSONSchema

func (EdgeViolationKind) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (EdgeViolationKind) String

func (k EdgeViolationKind) String() string

String returns the wire representation of the violation kind.

type EntryType

type EntryType string

EntryType classifies a single entry within an agent session transcript.

const (
	EntryTypeText       EntryType = "text"
	EntryTypeToolUse    EntryType = "tool_use"
	EntryTypeToolResult EntryType = "tool_result"
	EntryTypeThinking   EntryType = "thinking"
	EntryTypeSystem     EntryType = "system"
	EntryTypeError      EntryType = "error"
	EntryTypeResult     EntryType = "result"
)

func (EntryType) IsValid

func (e EntryType) IsValid() bool

IsValid returns true if the entry type is one of the known variants.

func (EntryType) JSONSchema

func (EntryType) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (EntryType) String

func (e EntryType) String() string

type EvidenceKind added in v0.19.0

type EvidenceKind string
const (
	EvidenceNativeTyped      EvidenceKind = "native_typed"
	EvidenceLifecycleTyped   EvidenceKind = "lifecycle_typed"
	EvidenceExistingAdapter  EvidenceKind = "existing_adapter"
	EvidenceRetainedLastGood EvidenceKind = "retained_last_good"
	EvidenceUnknown          EvidenceKind = "unknown"
	EvidenceConflict         EvidenceKind = "conflict"
)

func NewEvidenceKind added in v0.19.0

func NewEvidenceKind(raw string) (EvidenceKind, error)

func (EvidenceKind) IsValid added in v0.19.0

func (v EvidenceKind) IsValid() bool

func (EvidenceKind) JSONSchema added in v0.19.0

func (EvidenceKind) JSONSchema() (jsonschema.Schema, error)

type ExchangeCodeRequest

type ExchangeCodeRequest struct {
	Code  string `json:"code"`
	State string `json:"state"`
}

ExchangeCodeRequest is the JSON body sent to the village CLI auth exchange endpoint. POST /api/v1/auth/cli/exchange

type ExchangeCodeResponse

type ExchangeCodeResponse struct {
	APIKey   string `json:"api_key"`
	KeyID    string `json:"key_id"`
	UserID   string `json:"user_id"`
	Username string `json:"username"`
}

ExchangeCodeResponse is the JSON response from the village CLI auth exchange endpoint.

type FamiliarityPayload

type FamiliarityPayload struct {
	ProjectHash     ProjectHash        `json:"projectHash"`
	FamiliarityPct  float64            `json:"familiarityPct"`  // % of source files engaged
	UnexploredCount int                `json:"unexploredCount"` // source files with 0 engagement
	FreshnessDays   *int               `json:"freshnessDays"`   // days since last learning session
	Files           []FileFamiliarity  `json:"files"`
	Trails          []WalkthroughTrail `json:"trails"`
	Suggestions     []ReviewSuggestion `json:"suggestions"`
}

FamiliarityPayload is the data sent on the project_familiarity WebSocket channel.

type FileChange

type FileChange struct {
	Path         string           `json:"path"`
	Status       FileChangeStatus `json:"status"`
	OldPath      *string          `json:"oldPath,omitempty"`
	LinesAdded   int              `json:"linesAdded"`
	LinesRemoved int              `json:"linesRemoved"`
}

FileChange is one file-level delta of a change (branch vs merge-base). LinesAdded/LinesRemoved are the per-file numstat churn (0 for binary files or when numstat is unavailable) — the change-weight treemap's sizing input Always present; 0 is meaningful, so no omitempty.

type FileChangeStatus

type FileChangeStatus string

FileChangeStatus classifies a file-level delta using Git's canonical one-letter status tokens.

const (
	FileChangeStatusModified FileChangeStatus = "M"
	FileChangeStatusAdded    FileChangeStatus = "A"
	FileChangeStatusDeleted  FileChangeStatus = "D"
	FileChangeStatusRenamed  FileChangeStatus = "R"
)

func (FileChangeStatus) IsValid

func (s FileChangeStatus) IsValid() bool

IsValid reports whether s is a canonical file change status.

func (FileChangeStatus) JSONSchema

func (FileChangeStatus) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (FileChangeStatus) String

func (s FileChangeStatus) String() string

String returns the wire representation of the file change status.

func (FileChangeStatus) Validate

func (s FileChangeStatus) Validate() error

Validate rejects values that cannot cross a file-change wire boundary.

type FileFamiliarity

type FileFamiliarity struct {
	Path          string     `json:"path"`
	Depth         int        `json:"depth"` // 0=unexplored, 1=touched, 2=engaged, 3=deep
	SessionCount  int        `json:"sessionCount"`
	TotalTurns    int        `json:"totalTurns"`
	HumanTurns    int        `json:"humanTurns"`
	LastEngagedAt *string    `json:"lastEngagedAt"` // ISO 8601, nil if never
	DaysSince     *int       `json:"daysSince"`     // nil if never engaged
	DecayLevel    DecayLevel `json:"decayLevel"`
	IsSourceFile  bool       `json:"isSourceFile"` // true for relevant source files, false for config/generated
}

FileFamiliarity represents familiarity data for a single file.

type FrictionCluster

type FrictionCluster struct {
	Kind     string `json:"kind"`     // signal slug, e.g. "retryLoop"
	Label    string `json:"label"`    // plain, neutral (e.g. "retry loops")
	File     string `json:"file"`     // repo-relative path
	Count    int    `json:"count"`    // occurrences (retry-loop tasks touching this file)
	Sessions int    `json:"sessions"` // distinct conversations those occurrences span
}

FrictionCluster is a NEUTRAL count of a recurring friction signal keyed to a file: "this kind of friction touched this file N times across M conversations". A fact for orientation — the surface shows, it does not grade Kind is a stable slug ("retryLoop") so more kinds can be added without a breaking change.

type GitContext

type GitContext struct {
	Branch       *string                `json:"branch,omitempty"`       // Current git branch
	Remote       *string                `json:"remote,omitempty"`       // Git remote URL
	Worktree     *string                `json:"worktree,omitempty"`     // Worktree path (if applicable)
	Tracking     *string                `json:"tracking,omitempty"`     // Upstream tracking branch (e.g. "origin/main")
	Commits      []CommitInfo           `json:"commits,omitempty"`      // Commits produced during this session (v4+)
	Associations []PublishedAssociation `json:"associations,omitempty"` // Durable observed session-to-commit relationships
}

GitContext holds git repository state at the time of the session.

func (GitContext) Validate

func (g GitContext) Validate() error

Validate checks request-local published association invariants. Associations are optional for publishers that predate this contract. When supplied, IDs and observed hashes are each unique so a request cannot introduce either an ambiguous durable identity or a same-relationship alias.

type Harness

type Harness = bestiary.Harness

Harness identifies the coding tool or AI-assisted development environment that is driving the model interaction. Re-exported from bestiary.

func Harnesses

func Harnesses() []Harness

Harnesses returns every harness identifier known to bestiary — the full set, a superset of AllHarnesses (which is only the ingestion-supported subset). Re-exported so callers can enumerate the canonical known set without importing bestiary directly.

type HealthResponse

type HealthResponse struct {
	Status string `json:"status"`
}

HealthResponse is the JSON response for GET /api/v1/health.

type HelperContextSummary added in v0.19.0

type HelperContextSummary struct {
	GroupID     string                       `json:"groupId" yaml:"groupId"`
	OwnerStatus RelationshipNavigationStatus `json:"ownerStatus" yaml:"ownerStatus"`
}

func (HelperContextSummary) Validate added in v0.19.0

func (s HelperContextSummary) Validate() error

type HelperGroupSummary added in v0.19.0

type HelperGroupSummary struct {
	GroupID           string         `json:"groupId" yaml:"groupId"`
	Purpose           SessionPurpose `json:"purpose" yaml:"purpose"`
	HelperThreadCount int            `json:"helperThreadCount" yaml:"helperThreadCount" minimum:"0" maximum:"9007199254740991"`
	MemberScope       string         `json:"memberScope" yaml:"memberScope"`
}

func (HelperGroupSummary) Validate added in v0.19.0

func (s HelperGroupSummary) Validate() error

type HostSlug

type HostSlug string

HostSlug is a sanitized, filesystem-safe identifier derived from git remote. Contains [a-zA-Z0-9._<>-] characters. The <> characters support redaction placeholders like <USER> and <PATH> in redacted slugs.

func NewHostSlug

func NewHostSlug(raw string) (HostSlug, error)

NewHostSlug validates and constructs a HostSlug.

func (HostSlug) JSONSchema

func (HostSlug) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (HostSlug) String

func (h HostSlug) String() string

type IDCasing

type IDCasing struct {
	Name      string `yaml:"name"`
	Transform string `yaml:"transform"`
}

IDCasing is one entry of the id_casings axis: a named transform of values.uuid_lower (lower / upper / mixed).

type InputModality added in v0.19.0

type InputModality string
const (
	InputModalityNone       InputModality = "none"
	InputModalityText       InputModality = "text"
	InputModalityMedia      InputModality = "media"
	InputModalityUserAction InputModality = "user_action"
	InputModalityMixed      InputModality = "mixed"
	InputModalityUnknown    InputModality = "unknown"
)

func NewInputModality added in v0.19.0

func NewInputModality(raw string) (InputModality, error)

func (InputModality) IsValid added in v0.19.0

func (v InputModality) IsValid() bool

func (InputModality) JSONSchema added in v0.19.0

func (InputModality) JSONSchema() (jsonschema.Schema, error)

type InsightClassification

type InsightClassification struct {
	Category      string `json:"category" yaml:"category"`
	Cause         string `json:"cause" yaml:"cause"`
	SeverityScope string `json:"severityScope" yaml:"severityScope"`
	SeverityLocus string `json:"severityLocus" yaml:"severityLocus"`
	Resolution    string `json:"resolution" yaml:"resolution"`
}

InsightClassification is the reserved taxonomy tuple (category x cause x severity(scope, locus) x resolution). Its bare string fields keep the wire shape stable for future closed sets. The current contract requires SessionInsight.Classification to remain nil; see SessionInsight.Validate.

type InsightEvidence

type InsightEvidence struct {
	SessionID  SessionID `json:"sessionId" yaml:"sessionId" required:"true"`
	EntryIndex *int      `json:"entryIndex,omitempty" yaml:"entryIndex,omitempty"`
	File       string    `json:"file,omitempty" yaml:"file,omitempty"`
	CommitHash string    `json:"commitHash,omitempty" yaml:"commitHash,omitempty"`
}

InsightEvidence is one traceability pointer for a SessionInsight: the recorded session (and, when known, the turn / file / commit) that grounds it. Every mechanical insight carries at least one.

func (InsightEvidence) Validate

func (e InsightEvidence) Validate() error

Validate checks that the evidence item carries a traceable session identity.

type InsightKind

type InsightKind string

InsightKind classifies a SessionInsight.

const (
	InsightKindDecision  InsightKind = "decision"
	InsightKindFriction  InsightKind = "friction"
	InsightKindUnusual   InsightKind = "unusual"
	InsightKindRetryLoop InsightKind = "retry_loop"
)

InsightKind values.

func (InsightKind) IsValid

func (k InsightKind) IsValid() bool

IsValid reports whether k is one of the defined insight kinds.

func (InsightKind) JSONSchema

func (InsightKind) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (InsightKind) String

func (k InsightKind) String() string

String returns the wire representation of the insight kind.

func (InsightKind) Validate

func (k InsightKind) Validate() error

Validate rejects values that cannot cross the insight-kind wire boundary.

type InsightProvenance

type InsightProvenance string

InsightProvenance classifies how a SessionInsight was produced: mechanical (rule-derived) or mined.

const (
	InsightProvenanceMechanical InsightProvenance = "mechanical"
	InsightProvenanceMined      InsightProvenance = "mined"
)

InsightProvenance values.

func (InsightProvenance) IsValid

func (p InsightProvenance) IsValid() bool

IsValid reports whether p is one of the defined insight provenances.

func (InsightProvenance) JSONSchema

func (InsightProvenance) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (InsightProvenance) String

func (p InsightProvenance) String() string

String returns the wire representation of the insight provenance.

func (InsightProvenance) Validate

func (p InsightProvenance) Validate() error

Validate rejects values that cannot cross the insight-provenance wire boundary.

type InteractionType

type InteractionType string

InteractionType classifies how deeply a session engaged with a file.

const (
	InteractionMentioned  InteractionType = "mentioned"
	InteractionRead       InteractionType = "read"
	InteractionDiscussed  InteractionType = "discussed"
	InteractionQuestioned InteractionType = "questioned"
)

func (InteractionType) IsValid

func (i InteractionType) IsValid() bool

IsValid reports whether i is a defined interaction type.

func (InteractionType) JSONSchema

func (InteractionType) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (InteractionType) String

func (i InteractionType) String() string

type InterpretationDiagnostics added in v0.24.0

type InterpretationDiagnostics struct {
	Partial bool `json:"partial"`
}

InterpretationDiagnostics is durable interpretation state, independent of conversational outcome. Partial means retained evidence was not interpreted; it does not authorize loss of that evidence or imply damaged input is valid.

type InvalidRefCategory

type InvalidRefCategory struct {
	Category    string              `yaml:"category"`
	ErrContains string              `yaml:"err_contains"`
	Cases       []InvalidRefSubcase `yaml:"cases"`
}

InvalidRefCategory is a group of explicit reject cases sharing an expected error substring (attached to the category; a case may override it).

type InvalidRefSubcase

type InvalidRefSubcase struct {
	Name        string `yaml:"name"`
	Input       string `yaml:"input,omitempty"`
	Template    string `yaml:"template,omitempty"`
	ErrContains string `yaml:"err_contains,omitempty"` // overrides category default
}

InvalidRefSubcase is one reject case. Exactly one of Input/Template is set.

type License

type License string

License is the content license a contributor selects for a published transcript. Closed menu: the village `licenses` table (its migration 026) carries each license's obligations, and the peasant local store mirrors the set in a CHECK (migration v37). This is the single source of truth for the menu on the publish/pull wire.

const (
	LicenseCC0    License = "CC0-1.0"
	LicenseCCBY   License = "CC-BY-4.0"
	LicenseCCBYSA License = "CC-BY-SA-4.0"
)

func (License) IsValid

func (l License) IsValid() bool

IsValid reports whether the license is one of the known menu entries.

func (License) JSONSchema

func (License) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (License) String

func (l License) String() string

type LocalCollectiveSuggestion added in v0.25.0

type LocalCollectiveSuggestion struct {
	Reason LocalCollectiveSuggestionReason `json:"reason"`
	Match  string                          `json:"match"`
}

LocalCollectiveSuggestion is the server's reason to suggest one collective. Match is what matched: the linked repository's schema.RemoteLabel for a linked_repository suggestion, or the organization login for a linked_github_org suggestion.

type LocalCollectiveSuggestionReason added in v0.25.0

type LocalCollectiveSuggestionReason string

LocalCollectiveSuggestionReason is why the server suggests a collective for a session.

const (
	// LocalCollectiveSuggestionLinkedRepository: the collective links the session's
	// repository.
	LocalCollectiveSuggestionLinkedRepository LocalCollectiveSuggestionReason = "linked_repository"
	// LocalCollectiveSuggestionLinkedGithubOrg: the collective links the GitHub
	// organization that owns the session's repository.
	LocalCollectiveSuggestionLinkedGithubOrg LocalCollectiveSuggestionReason = "linked_github_org"
)

func (LocalCollectiveSuggestionReason) IsValid added in v0.25.0

func (LocalCollectiveSuggestionReason) JSONSchema added in v0.25.0

JSONSchema implements jsonschema.Exposer.

func (LocalCollectiveSuggestionReason) String added in v0.25.0

type LocalConfirmedContributionOutcome added in v0.31.0

type LocalConfirmedContributionOutcome string
const (
	LocalConfirmedContributionPublished LocalConfirmedContributionOutcome = "published"
	LocalConfirmedContributionSubmitted LocalConfirmedContributionOutcome = "submitted"
)

func (LocalConfirmedContributionOutcome) IsValid added in v0.31.0

func (LocalConfirmedContributionOutcome) JSONSchema added in v0.31.0

type LocalConfirmedContributionReceipt added in v0.31.0

type LocalConfirmedContributionReceipt struct {
	ReceiptID       string                            `json:"receiptId" minLength:"1" maxLength:"256"`
	Operation       CollectiveOperation               `json:"operation"`
	TranscriptID    TranscriptID                      `json:"transcriptId"`
	CollectiveID    *VillageUUID                      `json:"collectiveId,omitempty"`
	ConfirmedAt     time.Time                         `json:"confirmedAt"`
	Outcome         LocalConfirmedContributionOutcome `json:"outcome"`
	SourceReceiptID *string                           `json:"sourceReceiptId,omitempty" maxLength:"256"`
}

func (*LocalConfirmedContributionReceipt) UnmarshalJSON added in v0.31.0

func (v *LocalConfirmedContributionReceipt) UnmarshalJSON(data []byte) error

func (LocalConfirmedContributionReceipt) Validate added in v0.31.0

type LocalContributionEvidenceKind added in v0.31.0

type LocalContributionEvidenceKind string
const (
	LocalContributionEvidenceRemoteAttempts       LocalContributionEvidenceKind = "remote-attempts"
	LocalContributionEvidenceReceipts             LocalContributionEvidenceKind = "receipts"
	LocalContributionEvidenceOperationDiagnostics LocalContributionEvidenceKind = "operation-diagnostics"
)

func (LocalContributionEvidenceKind) IsValid added in v0.31.0

func (v LocalContributionEvidenceKind) IsValid() bool

func (LocalContributionEvidenceKind) JSONSchema added in v0.31.0

type LocalContributionHistoryQuery added in v0.31.0

type LocalContributionHistoryQuery struct {
	Kind         LocalContributionEvidenceKind  `json:"kind"`
	CollectiveID *VillageUUID                   `json:"collectiveId,omitempty"`
	Page         int                            `json:"page"`
	Limit        int                            `json:"limit"`
	Revision     *ContributionTraversalRevision `json:"revision,omitempty"`
}

type LocalContributionHistoryResponse added in v0.31.0

type LocalContributionHistoryResponse struct {
	Scope                CollectiveObservationScope          `json:"scope"`
	Kind                 LocalContributionEvidenceKind       `json:"kind"`
	TraversalRevision    ContributionTraversalRevision       `json:"traversalRevision"`
	Page                 int                                 `json:"page" minimum:"1" maximum:"9007199254740991"`
	Limit                int                                 `json:"limit" minimum:"1" maximum:"200"`
	Total                int64                               `json:"total" minimum:"0" maximum:"9007199254740991"`
	Coverage             CollectiveEvidenceCoverage          `json:"coverage"`
	RemoteAttempts       []LocalRemoteContributionAttempt    `json:"remoteAttempts,omitempty" maxItems:"200" nullable:"false"`
	Receipts             []LocalConfirmedContributionReceipt `json:"receipts,omitempty" maxItems:"200" nullable:"false"`
	OperationDiagnostics []LocalOperationDiagnostic          `json:"operationDiagnostics,omitempty" maxItems:"200" nullable:"false"`
}

func (LocalContributionHistoryResponse) MarshalJSON added in v0.31.0

func (r LocalContributionHistoryResponse) MarshalJSON() ([]byte, error)

func (*LocalContributionHistoryResponse) UnmarshalJSON added in v0.31.0

func (r *LocalContributionHistoryResponse) UnmarshalJSON(data []byte) error

func (LocalContributionHistoryResponse) Validate added in v0.31.0

type LocalContributionTraversalConflict added in v0.31.0

type LocalContributionTraversalConflict struct {
	CurrentTraversalRevision ContributionTraversalRevision `json:"currentTraversalRevision"`
	Issue                    OperationIssue                `json:"issue"`
}

type LocalHelperMembersPayload added in v0.19.0

type LocalHelperMembersPayload struct {
	Members []LocalSessionListItem `json:"members" nullable:"false"`
	Page    int                    `json:"page" minimum:"1" maximum:"9007199254740991"`
	Limit   int                    `json:"limit" minimum:"1" maximum:"9007199254740991"`
	Total   int                    `json:"total" minimum:"0" maximum:"9007199254740991"`
}

LocalHelperMembersPayload is a page of saved helper sessions selected by an opaque scope returned from the originating grouped query.

func (*LocalHelperMembersPayload) UnmarshalJSON added in v0.19.0

func (p *LocalHelperMembersPayload) UnmarshalJSON(raw []byte) error

UnmarshalJSON preserves required member-page presence before Go zero values can turn a missing or null total into a measured zero.

func (LocalHelperMembersPayload) Validate added in v0.19.0

func (p LocalHelperMembersPayload) Validate() error

Validate checks a typed, non-null member page and every row mirror.

type LocalOperationDiagnostic added in v0.31.0

type LocalOperationDiagnostic struct {
	OperationID  VillageUUID                     `json:"operationId"`
	Operation    CollectiveOperation             `json:"operation"`
	TranscriptID *TranscriptID                   `json:"transcriptId,omitempty"`
	CollectiveID *VillageUUID                    `json:"collectiveId,omitempty"`
	AttemptedAt  time.Time                       `json:"attemptedAt"`
	Outcome      LocalOperationDiagnosticOutcome `json:"outcome"`
	Issue        OperationIssue                  `json:"issue"`
}

func (*LocalOperationDiagnostic) UnmarshalJSON added in v0.31.0

func (v *LocalOperationDiagnostic) UnmarshalJSON(data []byte) error

func (LocalOperationDiagnostic) Validate added in v0.31.0

func (d LocalOperationDiagnostic) Validate() error

type LocalOperationDiagnosticOutcome added in v0.31.0

type LocalOperationDiagnosticOutcome string
const (
	LocalOperationDiagnosticFailed    LocalOperationDiagnosticOutcome = "failed"
	LocalOperationDiagnosticUncertain LocalOperationDiagnosticOutcome = "uncertain"
)

func (LocalOperationDiagnosticOutcome) IsValid added in v0.31.0

func (LocalOperationDiagnosticOutcome) JSONSchema added in v0.31.0

type LocalPublication added in v0.25.0

type LocalPublication struct {
	SessionID string                `json:"sessionId"`
	State     LocalPublicationState `json:"state"`
	// TranscriptID, TranscriptURL, and PublishedAt are present exactly when
	// State is published. PublishedAt is when Village last accepted this
	// session's content, by a first publish or an update; a client counts the
	// turns recorded after it to say about how many turns are new. The count
	// is approximate: it compares this computer's turn times with Village's
	// accept time.
	TranscriptID  *TranscriptID `json:"transcriptId,omitempty" nullable:"false"`
	TranscriptURL string        `json:"transcriptUrl,omitempty"`
	PublishedAt   *time.Time    `json:"publishedAt,omitempty" nullable:"false"`
	// LastAttempt is the most recent failed attempt, absent when none is
	// recorded.
	LastAttempt *LocalPublicationAttemptFailure `json:"lastAttempt,omitempty" nullable:"false"`
	// AutoPublish reports that an executable Peasant upload hook can publish
	// this session on a commit or push. Rule-required hooks need an active rule
	// for that repository and event; removing or pausing the last binding makes
	// the retained hook dormant. Separately installed terminal hooks have their
	// own consent. False outside the saved selection or when rules cannot be read.
	AutoPublish bool `` /* 423-byte string literal not displayed */
	// OutsideSelection reports that the saved selection leaves this session
	// out of the local lists. The read ignores the selection, so such a
	// session is still returned.
	OutsideSelection bool `json:"outsideSelection"`
	// Audience lists the collectives the transcript is shared with. It is
	// present on a published row exactly when the request asked for
	// include=audience, as [] when the transcript is shared with no
	// collective, and never on an unpublished row.
	Audience *[]LocalPublicationAudienceMember `json:"audience,omitempty" nullable:"false"`
}

LocalPublication is the durable publication state of one local session for the Village account this computer is signed in to: the stored credential's Village and user. A publication recorded for another account is not reported, and a signed-out computer reports every session unpublished.

func (LocalPublication) Validate added in v0.25.0

func (p LocalPublication) Validate() error

Validate checks the state pairing and the audience of one publication row.

type LocalPublicationAttemptFailure added in v0.25.0

type LocalPublicationAttemptFailure struct {
	AttemptedAt time.Time `json:"attemptedAt"`
	Message     string    `json:"message"`
}

LocalPublicationAttemptFailure is the most recent failed publish attempt recorded for a session. A client compares AttemptedAt with the publication's PublishedAt to tell whether the failure is newer than the last success.

type LocalPublicationAudienceMember added in v0.25.0

type LocalPublicationAudienceMember struct {
	CollectiveID VillageUUID        `json:"collectiveId"`
	Name         string             `json:"name"`
	Status       VillageShareStatus `json:"status"`
}

LocalPublicationAudienceMember is one collective a published transcript is shared with. Status is the collective's current share status: approved means its members can read the transcript, pending means the collective's owner has not approved it yet.

type LocalPublicationState added in v0.25.0

type LocalPublicationState string

LocalPublicationState is whether a local session has a publication on Village.

const (
	// LocalPublicationUnpublished: no publication of this session is recorded.
	LocalPublicationUnpublished LocalPublicationState = "unpublished"
	// LocalPublicationPublished: Village holds a transcript of this session.
	LocalPublicationPublished LocalPublicationState = "published"
)

func (LocalPublicationState) IsValid added in v0.25.0

func (s LocalPublicationState) IsValid() bool

func (LocalPublicationState) JSONSchema added in v0.25.0

func (LocalPublicationState) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (LocalPublicationState) String added in v0.25.0

func (s LocalPublicationState) String() string

type LocalPublicationsResponse added in v0.25.0

type LocalPublicationsResponse struct {
	Publications []LocalPublication `json:"publications" nullable:"false"`
}

LocalPublicationsResponse is the response of GET /api/v1/publications. It holds one row per requested session that exists on this computer; an identifier that names no session is omitted.

func (LocalPublicationsResponse) Validate added in v0.25.0

func (r LocalPublicationsResponse) Validate() error

Validate checks every row and that each session appears once.

type LocalRemoteContributionAttempt added in v0.31.0

type LocalRemoteContributionAttempt struct {
	CollectiveID VillageUUID       `json:"collectiveId"`
	TranscriptID TranscriptID      `json:"transcriptId"`
	Attempt      VillageShareEvent `json:"attempt"`
	FirstSeenAt  time.Time         `json:"firstSeenAt"`
}

LocalRemoteContributionAttempt is retained owner-history evidence. Attempt is a projection of a server attempt, not an immutable status-change event. The enclosing storage scope supplies the Village URL and authenticated user.

func (*LocalRemoteContributionAttempt) UnmarshalJSON added in v0.31.0

func (v *LocalRemoteContributionAttempt) UnmarshalJSON(data []byte) error

func (LocalRemoteContributionAttempt) Validate added in v0.31.0

func (attempt LocalRemoteContributionAttempt) Validate() error

type LocalSessionListItem added in v0.19.0

type LocalSessionListItem struct {
	Kind         SessionListItemKind   `json:"kind"`
	Transcript   *LocalSessionRow      `json:"transcript,omitempty"`
	Context      *HelperContextSummary `json:"context,omitempty"`
	HelperGroups []HelperGroupSummary  `json:"helperGroups,omitempty" nullable:"false"`
}

LocalSessionListItem is exactly one transcript row or owner context container, with zero or more collapsed helper groups.

func (LocalSessionListItem) Validate added in v0.19.0

func (i LocalSessionListItem) Validate() error

Validate checks the discriminated item arm and every nested route row/group.

type LocalSessionListPayload added in v0.19.0

type LocalSessionListPayload struct {
	Items                []LocalSessionListItem `json:"items" nullable:"false"`
	Page                 int                    `json:"page" minimum:"1" maximum:"9007199254740991"`
	Limit                int                    `json:"limit" minimum:"1" maximum:"9007199254740991"`
	TotalItems           int                    `json:"totalItems" minimum:"0" maximum:"9007199254740991"`
	OrdinarySessionTotal int                    `json:"ordinarySessionTotal" minimum:"0" maximum:"9007199254740991"`
	HelperThreadTotal    int                    `json:"helperThreadTotal" minimum:"0" maximum:"9007199254740991"`
}

LocalSessionListPayload is the opt-in grouped REST list response.

func (LocalSessionListPayload) Validate added in v0.19.0

func (p LocalSessionListPayload) Validate() error

Validate checks non-null collection and pagination/count boundaries.

type LocalSessionRow added in v0.19.0

type LocalSessionRow struct {
	Session SessionSummary    `json:"session"`
	Sync    *LocalSyncSummary `json:"sync,omitempty"`
	Matches []SearchResult    `json:"matches,omitempty" nullable:"false"`
}

LocalSessionRow is one concrete local route row. Sync and Matches retain the existing route-specific data instead of coercing every route into one shape.

func (LocalSessionRow) Validate added in v0.19.0

func (r LocalSessionRow) Validate() error

Validate checks route-variant identity and count mirrors without deriving one metric from another.

type LocalSetting added in v0.25.0

type LocalSetting struct {
	// Key is the setting's dotted configuration path, for example
	// push.concurrency.
	Key  string           `json:"key" minLength:"1"`
	Kind LocalSettingKind `json:"kind"`
	// Value is what the configuration file names for the key, or null when
	// the file does not name it. A choice value may lie outside Options when
	// the server still accepts it from an existing file but no longer offers
	// it; Effective then names what applies.
	Value LocalSettingValue `json:"value"`
	// Effective is the value that applies now: normally Value when the key is
	// set, otherwise the server's default, and it can differ from Value when
	// something outside the file, such as an environment variable, overrides
	// it. It is null only when no value applies. A client shows Effective, so
	// an unset key never reads as off or blank when its default is on or
	// filled.
	Effective LocalSettingValue `json:"effective"`
	// Options is the menu of a choice setting; an option may be the empty
	// string when that is a meaningful setting. Other kinds have none.
	Options []string `json:"options,omitempty" nullable:"false"`
	// Editable reports that PATCH /api/v1/settings accepts this key. A key
	// that changes another way, such as village.connected through sign-in and
	// sign-out, is shown but not editable.
	Editable bool `json:"editable"`
	// InPeasantConfig reports that the terminal editor `peasant config` can
	// also change this setting.
	InPeasantConfig bool `json:"inPeasantConfig"`
	// Description is Peasant's product text for the setting.
	Description string `json:"description,omitempty"`
}

LocalSetting is one Peasant setting with its metadata.

func (LocalSetting) Validate added in v0.25.0

func (s LocalSetting) Validate() error

Validate checks the key, the kind, the options, and that the value matches the kind.

type LocalSettingKind added in v0.25.0

type LocalSettingKind string

LocalSettingKind is the JSON type of one setting's value. Peasant owns the key set, each key's description, and which keys are editable; this contract owns the value shapes.

const (
	// LocalSettingBoolean: the value is a JSON boolean.
	LocalSettingBoolean LocalSettingKind = "boolean"
	// LocalSettingInteger: the value is a JSON integer.
	LocalSettingInteger LocalSettingKind = "integer"
	// LocalSettingString: the value is a JSON string.
	LocalSettingString LocalSettingKind = "string"
	// LocalSettingStringList: the value is a JSON array of strings.
	LocalSettingStringList LocalSettingKind = "string_list"
	// LocalSettingChoice: the value is one of the setting's options.
	LocalSettingChoice LocalSettingKind = "choice"
	// LocalSettingStructured: the value is the key's configuration value as a
	// JSON object or array, for example a list of custom redaction patterns.
	// It is only for a list or map of records; Peasant owns its shape. A key
	// whose value fits another kind uses that kind.
	LocalSettingStructured LocalSettingKind = "structured"
)

func (LocalSettingKind) IsValid added in v0.25.0

func (k LocalSettingKind) IsValid() bool

func (LocalSettingKind) JSONSchema added in v0.25.0

func (LocalSettingKind) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (LocalSettingKind) String added in v0.25.0

func (k LocalSettingKind) String() string

type LocalSettingRefusal added in v0.25.0

type LocalSettingRefusal struct {
	Key   string `json:"key" minLength:"1"`
	Error string `json:"error" minLength:"1"`
}

LocalSettingRefusal is the body of a refused setting update: the key and why it was not changed. A refused update changes nothing.

func (LocalSettingRefusal) Validate added in v0.25.0

func (r LocalSettingRefusal) Validate() error

Validate checks that the refusal names the key and the reason.

type LocalSettingUpdateRequest added in v0.25.0

type LocalSettingUpdateRequest struct {
	Key   string            `json:"key" minLength:"1"`
	Value LocalSettingValue `json:"value"`
}

LocalSettingUpdateRequest is the body of PATCH /api/v1/settings. One request changes one key; a null value unsets it so the server's default applies.

func (LocalSettingUpdateRequest) Validate added in v0.25.0

func (r LocalSettingUpdateRequest) Validate() error

Validate checks that the request names a key and carries a value. The server checks the value against the key's kind with ValidateFor.

type LocalSettingValue added in v0.25.0

type LocalSettingValue []byte

LocalSettingValue is one setting's JSON value, held as its exact JSON text. The setting's kind chooses which JSON type it is. JSON null means the key is unset: the configuration file does not name it and the server's default applies. In an update, null unsets the key.

func LocalSettingNull added in v0.25.0

func LocalSettingNull() LocalSettingValue

LocalSettingNull returns a fresh JSON null, which a producer sets for an unset value or when no effective value applies.

func (LocalSettingValue) IsUnset added in v0.25.0

func (v LocalSettingValue) IsUnset() bool

IsUnset reports whether the value is JSON null. A nil value is unset too: it marshals as null.

func (LocalSettingValue) JSONSchema added in v0.25.0

func (LocalSettingValue) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (LocalSettingValue) MarshalJSON added in v0.25.0

func (v LocalSettingValue) MarshalJSON() ([]byte, error)

MarshalJSON emits the held JSON text.

func (*LocalSettingValue) UnmarshalJSON added in v0.25.0

func (v *LocalSettingValue) UnmarshalJSON(data []byte) error

UnmarshalJSON keeps the JSON text as received, in fresh storage so decoding never writes into a value another variable shares.

func (LocalSettingValue) ValidateFor added in v0.25.0

func (v LocalSettingValue) ValidateFor(kind LocalSettingKind, options []string) error

ValidateFor checks that a set value has the JSON type kind names and, for a choice, is one of options. An unset value, nil or JSON null, is valid for every kind. A producer checks an update's value against the key's kind with this method.

type LocalSettingsResponse added in v0.25.0

type LocalSettingsResponse struct {
	Settings    []LocalSetting    `json:"settings" nullable:"false"`
	AutoPublish []AutoPublishRule `json:"autoPublish" nullable:"false"`
}

LocalSettingsResponse is the response of GET /api/v1/settings: every setting the settings page shows and every auto-publish rule.

func (LocalSettingsResponse) Validate added in v0.25.0

func (r LocalSettingsResponse) Validate() error

Validate checks every setting and rule and that keys and identifiers do not repeat.

type LocalSyncProjectOption added in v0.30.0

type LocalSyncProjectOption struct {
	ProjectHash ProjectHash `json:"projectHash"`
	ProjectName string      `json:"projectName"`
}

type LocalSyncProjectOptions added in v0.30.0

type LocalSyncProjectOptions struct {
	Projects []LocalSyncProjectOption `json:"projects" nullable:"false"`
}

LocalSyncProjectOptions contains the complete selected root picker, independent of the chosen root project/publication filter. No counts or enrichment.

func (LocalSyncProjectOptions) Validate added in v0.30.0

func (o LocalSyncProjectOptions) Validate() error

type LocalSyncPublicationFilter added in v0.30.0

type LocalSyncPublicationFilter string

LocalSyncPublicationFilter narrows the selected root cohort before paging.

const (
	LocalSyncPublicationAll          LocalSyncPublicationFilter = "all"
	LocalSyncPublicationNotPublished LocalSyncPublicationFilter = "not-published"
	LocalSyncPublicationPublished    LocalSyncPublicationFilter = "published"
	LocalSyncPublicationAuto         LocalSyncPublicationFilter = "auto"
)

func (LocalSyncPublicationFilter) IsValid added in v0.30.0

func (f LocalSyncPublicationFilter) IsValid() bool

func (LocalSyncPublicationFilter) JSONSchema added in v0.30.0

func (LocalSyncPublicationFilter) String added in v0.30.0

type LocalSyncSessionPage added in v0.30.0

type LocalSyncSessionPage = Page[LocalSyncSessionRow]

LocalSyncSessionPage is the concrete wire instantiation, not a second shape.

type LocalSyncSessionRow added in v0.30.0

type LocalSyncSessionRow struct {
	Sync        LocalSyncSummary `json:"sync"`
	Publication LocalPublication `json:"publication"`
	Title       string           `json:"title"`
	Preview     string           `json:"preview"`
	ChildCount  int              `json:"childCount" minimum:"0"`
}

LocalSyncSessionRow hydrates only a returned session, sharing the canonical sync/publication projections. Preview is bounded and redaction-safe.

func (LocalSyncSessionRow) Validate added in v0.30.0

func (r LocalSyncSessionRow) Validate() error

type LocalSyncSessionsPayload added in v0.19.0

type LocalSyncSessionsPayload struct {
	Sessions []LocalSyncSummary `json:"sessions" nullable:"false"`
}

LocalSyncSessionsPayload is the exact omitted-view response produced by the existing local sync chooser. Every row carries its status; a session absent from the response has no status here, and a client must not read absence as new.

func (LocalSyncSessionsPayload) Validate added in v0.25.0

func (p LocalSyncSessionsPayload) Validate() error

Validate checks that the flat sync list is an array of valid rows and lists each session once.

type LocalSyncSessionsQuery added in v0.30.0

type LocalSyncSessionsQuery struct {
	View            string                      `` /* 200-byte string literal not displayed */
	MaxItems        *int                        `` /* 197-byte string literal not displayed */
	PageToken       *PageToken                  `` /* 171-byte string literal not displayed */
	ParentSessionID *string                     `query:"parentSessionId" nullable:"false" minLength:"1"`
	ProjectHash     *ProjectHash                `query:"projectHash" nullable:"false"`
	Publication     *LocalSyncPublicationFilter `query:"publication" nullable:"false" default:"all"`
}

LocalSyncSessionsQuery keeps forward paging opt-in on the existing resource. Validate before applying defaults: explicit root filters are invalid on children.

func ParseLocalSyncSessionsQuery added in v0.30.0

func ParseLocalSyncSessionsQuery(values url.Values) (LocalSyncSessionsQuery, error)

ParseLocalSyncSessionsQuery preserves parameter presence and rejects ambiguous repeated values before handlers dispatch to a domain reader.

func (LocalSyncSessionsQuery) PageRequest added in v0.30.0

func (q LocalSyncSessionsQuery) PageRequest() PageRequest

PageRequest applies the Home transport's default and cap after validation.

func (LocalSyncSessionsQuery) Validate added in v0.30.0

func (q LocalSyncSessionsQuery) Validate() error

type LocalSyncSummary added in v0.19.0

type LocalSyncSummary struct {
	ID                   string      `json:"id"`
	Harness              Harness     `json:"harness"`
	ProjectName          string      `json:"projectName"`
	ProjectHash          ProjectHash `json:"projectHash"`
	HostSlug             string      `json:"hostSlug"`
	StartTime            string      `json:"startTime"`
	DurationMs           int64       `json:"durationMs"`
	TotalTokens          int         `json:"totalTokens"`
	TurnCount            int         `json:"turnCount"`
	Model                string      `json:"model"`
	InputSubmissionCount *int64      `json:"inputSubmissionCount,omitempty" minimum:"0" maximum:"9007199254740991" nullable:"false"`
	SyncStatus           SyncStatus  `json:"syncStatus"`
	// HoldReason says why a held row waits. Only a held row carries one.
	HoldReason SyncHoldReason `json:"holdReason,omitempty"`
	// PreviouslyPushed reports durable evidence that this session was
	// published before. It is independent of SyncStatus: a held row can have
	// been published, so a client reads this field instead of inferring it.
	PreviouslyPushed bool `json:"previouslyPushed"`
	// ParentSessionID is the durable logical parent of a spawned child, the
	// same value its SessionSummary carries. It may name a session this store
	// does not hold. Absent for a root or a fork.
	ParentSessionID *string `json:"parentSessionId,omitempty" nullable:"false"`
	// ParentUnresolved marks a known spawned child whose parent cannot be
	// named. At most one of ParentSessionID and ParentUnresolved=true is set.
	ParentUnresolved *bool `json:"parentUnresolved,omitempty" nullable:"false"`
}

LocalSyncSummary preserves the existing sync-list row alongside its matching SessionSummary when grouped list mode is requested.

func (LocalSyncSummary) Validate added in v0.25.0

func (s LocalSyncSummary) Validate() error

Validate checks the typed status, the hold reason pairing, and the count bounds of one sync chooser row. PreviouslyPushed is independent evidence: a held row can have been published before, so no status implies its value.

type LocalVillageCollective added in v0.25.0

type LocalVillageCollective struct {
	Group VillageUserGroup `json:"group"`
	// Suggestion is present when the server suggests this collective for the
	// requested session.
	Suggestion *LocalCollectiveSuggestion `json:"suggestion,omitempty" nullable:"false"`
}

LocalVillageCollective is one Village collective the signed-in user belongs to, as Village returns it, with the suggestion the local server computed.

type LocalVillageCollectivesResponse added in v0.25.0

type LocalVillageCollectivesResponse struct {
	Collectives []LocalVillageCollective `json:"collectives" nullable:"false"`
}

LocalVillageCollectivesResponse is the response of GET /api/v1/village/collectives.

func (LocalVillageCollectivesResponse) Validate added in v0.25.0

Validate checks every suggestion and that each collective appears once.

type MapEdge

type MapEdge struct {
	From  string `json:"from"` // node ID
	To    string `json:"to"`
	Count int    `json:"count"` // underlying import count (aggregated)
}

MapEdge is a structure (import) dependency between two nodes.

type MapGraphPayload

type MapGraphPayload struct {
	ProjectHash     ProjectHash     `json:"projectHash"`
	RepoFound       bool            `json:"repoFound"` // canonical_cwd resolved to a git repo
	RepoPath        string          `json:"repoPath,omitempty"`
	ParsedLanguages []string        `json:"parsedLanguages"` // e.g. ["go","typescript"]; empty => activity-only
	Nodes           []MapNode       `json:"nodes"`           // all zoom levels; parent links form the tree
	StructureEdges  []MapEdge       `json:"structureEdges"`  // parsed imports, aggregated per node pair
	ActivityEdges   []ActivityEdge  `json:"activityEdges"`   // co-EDIT observations
	Violations      []EdgeViolation `json:"violations"`      // cycles + wrong-way edges
	GeneratedAtMs   int64           `json:"generatedAtMs"`
	AtCommit        string          `json:"atCommit,omitempty"` // set when ?commit= was used
}

MapGraphPayload is the full map graph for one project, served by GET /api/v1/map/{projectHash}.

func NewMapGraphPayload

func NewMapGraphPayload(projectHash ProjectHash) *MapGraphPayload

NewMapGraphPayload returns a MapGraphPayload with all slices initialized to empty (never-nil marshal guarantee).

type MapNode

type MapNode struct {
	ID            string      `json:"id"`               // repo-relative path ("internal/ingest", "web/src/lib/api.ts")
	Parent        string      `json:"parent,omitempty"` // ID of parent node ("" for top-level modules)
	Kind          MapNodeKind `json:"kind"`
	Name          string      `json:"name"` // display leaf ("ingest")
	Language      string      `json:"language,omitempty"`
	Layer         int         `json:"layer"`         // 0 = top row; deterministic
	Order         int         `json:"order"`         // stable sort within layer
	Loc           int         `json:"loc"`           // size metric (lines)
	FileCount     int         `json:"fileCount"`     // 1 for files
	RecordedFiles int         `json:"recordedFiles"` // files whose last edit is attributable to a recorded session
	TotalFiles    int         `json:"totalFiles"`
	TouchCount    int         `json:"touchCount"`    // recorded edits in window (activity size metric)
	EffortDensity float64     `json:"effortDensity"` // 0..1 per-file re-edit/error density rollup (0 when unknown)

	// AgentEditedCount / ReadCount / ReadAttribution are the node-grain
	// comprehension signals behind the ranked entry list's tri-state debt
	// tag. ReadAttribution is the honesty field:
	// a zero ReadCount is "unavailable" (no recoverable per-file read
	// attribution for any editing session), "partial" (some do), or
	// "complete" (all do) - never silently indistinguishable from unread.
	AgentEditedCount int                  `json:"agentEditedCount"`
	ReadCount        int                  `json:"readCount"`
	ReadAttribution  ReadAttributionState `json:"readAttribution" required:"true"`

	// ReadState is the composed effective read-state grade for the node's
	// current content version. ChangedRegionCount
	// / AttributedRegionCount / ReviewedRegionCount are the minimal per-node
	// region-coverage counts over that same current version: total changed
	// hunks, hunks the server could attribute to a producing turn, and
	// attributed hunks whose producing turn carries a reviewed+ grade. They
	// supply the client's hunk-linked hover ("N of M changed regions
	// reviewed"). All are server-computed; the client-side debt
	// derivation stays a pure function over these MapNode scalars.
	ReadState             ReadStateGrade `json:"readState" required:"true"`
	ChangedRegionCount    int            `json:"changedRegionCount"`
	AttributedRegionCount int            `json:"attributedRegionCount"`
	ReviewedRegionCount   int            `json:"reviewedRegionCount"`
}

MapNode is one square card on the map: a module, package, or file.

func (MapNode) Validate

func (n MapNode) Validate() error

Validate checks a MapNode's closed-set fields fail closed. It does not check cross-region-count consistency (e.g. ReviewedRegionCount <= AttributedRegionCount <= ChangedRegionCount); those are producer-side invariants, not wire shape rules.

type MapNodeDetailPayload

type MapNodeDetailPayload struct {
	Path          string      `json:"path"`
	Kind          MapNodeKind `json:"kind"`
	Language      string      `json:"language,omitempty"` // e.g. "go", "typescript"; "" for activity-only nodes
	Loc           int         `json:"loc"`
	RecordedFiles int         `json:"recordedFiles"`
	TotalFiles    int         `json:"totalFiles"`
	SessionCount  int         `json:"sessionCount"`
	TaskCount     int         `json:"taskCount"`
	LastTouchMs   *int64      `json:"lastTouchMs,omitempty"`
	// DependsOn / UsedBy are the node's structural role, derived deterministically
	// from the parsed import graph (what this area does): the node IDs
	// this node imports, and those that import it. Most-connected first, capped.
	// Empty when there is no parsed graph (activity-only) or no edges.
	DependsOn     []string      `json:"dependsOn"`
	UsedBy        []string      `json:"usedBy"`
	ShapedBy      []TaskSummary `json:"shapedBy"`          // most recent first, cap 20
	RecentCommits []CommitRef   `json:"recentCommits"`     // touching this node, cap 10
	RetryLoops    int           `json:"retryLoops"`        // summed over touching sessions
	ReEdits       int           `json:"reEdits"`           // re-edited files within this node
	CostUsd       *float64      `json:"costUsd,omitempty"` // nil when unknown
	// RewrittenCommits lists ghost commits touching this node. It is empty when
	// the resolver found no ghosts here.
	RewrittenCommits []RewrittenCommit `json:"rewrittenCommits" required:"true" nullable:"false"`
	// Insights carries mechanical and mined insight envelopes for this node.
	// It is additive alongside the per-change Unusual/Frictions signals, never
	// a replacement for them.
	Insights []SessionInsight `json:"insights" required:"true" nullable:"false"`
}

MapNodeDetailPayload backs the node rail panel, served by GET /api/v1/map/{projectHash}/node?path=<id>.

func NewMapNodeDetailPayload

func NewMapNodeDetailPayload(path string) *MapNodeDetailPayload

NewMapNodeDetailPayload returns a MapNodeDetailPayload with all slices initialized to empty (never-nil marshal guarantee).

func (MapNodeDetailPayload) Validate

func (p MapNodeDetailPayload) Validate() error

Validate checks the additive rewrite and insight invariants: slices are non-nil, every RecentCommit and RewrittenCommit is well-formed, every RewrittenCommit's SuccessorHash (when set) is present in RecentCommits, shared successor and ledger associations are identical, and every SessionInsight is well-formed (including the Classification-must-be-nil rule). Unlike ReviewListPayload, a node detail payload carries no independent session table, so RewrittenCommits.SessionIDs are checked for well-formedness only (not cross-referenced against a session list this payload does not have).

type MapNodeKind

type MapNodeKind string

MapNodeKind classifies a map node within the path-derived tree.

const (
	MapNodeKindModule  MapNodeKind = "module"
	MapNodeKindPackage MapNodeKind = "package"
	MapNodeKindFile    MapNodeKind = "file"
)

MapNodeKind values. Top-level directories are modules, nested directories are packages, and files are leaves (mirrors codegraph's node kinds).

func (MapNodeKind) IsValid

func (k MapNodeKind) IsValid() bool

IsValid reports whether k is one of the defined node kinds.

func (MapNodeKind) JSONSchema

func (MapNodeKind) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (MapNodeKind) String

func (k MapNodeKind) String() string

String returns the wire representation of the node kind.

type MapSlice

type MapSlice struct {
	Nodes          []MapNode      `json:"nodes"` // layer/order preserved from full map
	StructureEdges []MapEdge      `json:"structureEdges"`
	ActivityEdges  []ActivityEdge `json:"activityEdges"`
}

MapSlice is a scoped sub-map: the touched nodes plus their one-hop neighborhood, with layer/order preserved from the full map.

func NewMapSlice

func NewMapSlice() MapSlice

NewMapSlice returns a MapSlice with all slices initialized to empty (never-nil marshal guarantee).

type MessageType

type MessageType string

MessageType represents the type discriminator for WebSocket messages.

const (
	MsgSubscribe          MessageType = "subscribe"
	MsgUnsubscribe        MessageType = "unsubscribe"
	MsgDashboard          MessageType = "dashboard"
	MsgSessions           MessageType = "sessions"
	MsgSessionDetail      MessageType = "session_detail"
	MsgTrends             MessageType = "trends"
	MsgQuality            MessageType = "quality"
	MsgAnnotations        MessageType = "annotations"
	MsgProjectFamiliarity MessageType = "project_familiarity"
	MsgConnected          MessageType = "connected"
	MsgError              MessageType = "error"
)

func (MessageType) IsValid

func (m MessageType) IsValid() bool

IsValid reports whether m is a defined WebSocket message discriminator.

func (MessageType) JSONSchema

func (MessageType) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (MessageType) String

func (m MessageType) String() string

String returns the wire representation of the message discriminator.

type MockConfigResponse

type MockConfigResponse struct {
	Enabled bool     `json:"enabled"`
	Web     []string `json:"web,omitempty"`
	TUI     []string `json:"tui,omitempty"`
	API     []string `json:"api,omitempty"`
}

MockConfigResponse is the JSON response for GET /api/v1/config/mock.

type ModelID

type ModelID string

ModelID identifies a specific model version (e.g. "claude-opus-4-6").

func NewModelID

func NewModelID(raw string) (ModelID, error)

NewModelID validates and constructs a ModelID.

func (ModelID) JSONSchema

func (ModelID) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (ModelID) String

func (m ModelID) String() string

type ModelInfo

type ModelInfo struct {
	Harness        Harness  `json:"harness" required:"true"`
	Model          ModelID  `json:"model" required:"true"`
	HarnessVersion string   `json:"version,omitempty"`
	HostSlug       HostSlug `json:"hostSlug,omitempty"`
}

ModelInfo holds harness and model version information for a session. JSON tags use camelCase to match CLI UnifiedMetadata wire format. The harness is keyed json:"harness" (emit-side flip; was json:"modelHarness").

rc2 (#118): Harness and Model carry required:"true" so swaggest emits a SchemaModelInfo.required:["harness","model"] array — the village rejects a model object missing either key (the harness/model-within-model contract). Metadata only: these tags change the GENERATED schema's `required`, not the Go wire shape.

type NativeAttachmentRef added in v0.16.0

type NativeAttachmentRef struct {
	TurnIndex  *int   `json:"turnIndex,omitempty"`
	ToolCallID string `json:"toolCallId,omitempty"`
}

type NativeLimitInput added in v0.19.0

type NativeLimitInput struct {
	MainRecords    int    `yaml:"main_records"`
	EarlierRecords []int  `yaml:"earlier_records"`
	DataBytes      int    `yaml:"data_bytes"`
	DetailJSON     string `yaml:"detail_json"`
	RecordJSON     string `yaml:"record_json"`
	SectionJSON    string `yaml:"section_json"`
}

type NativeMetadataKind added in v0.16.0

type NativeMetadataKind string
const (
	NativeMetadataPiCustomData           NativeMetadataKind = "pi.custom.data"
	NativeMetadataPiCustomMessageDetails NativeMetadataKind = "pi.custommessage.details"
	NativeMetadataPiToolResultDetails    NativeMetadataKind = "pi.toolresult.details"
	NativeMetadataPiCompactionDetails    NativeMetadataKind = "pi.compaction.details"
	NativeMetadataPiBranchSummaryDetails NativeMetadataKind = "pi.branchsummary.details"
)

func NewNativeMetadataKind added in v0.16.0

func NewNativeMetadataKind(raw string) (NativeMetadataKind, error)

func (NativeMetadataKind) IsValid added in v0.16.0

func (v NativeMetadataKind) IsValid() bool

func (NativeMetadataKind) JSONSchema added in v0.16.0

func (NativeMetadataKind) JSONSchema() (jsonschema.Schema, error)

type NativeMetadataRecord added in v0.16.0

type NativeMetadataRecord struct {
	ID         string               `json:"id"`
	Kind       NativeMetadataKind   `json:"kind"`
	Source     NativeSourceRef      `json:"source"`
	Attachment *NativeAttachmentRef `json:"attachment,omitempty"`
	CustomType string               `json:"customType,omitempty"`
	Data       json.RawMessage      `json:"data"`
}

func DecodeNativeMetadataRecordsRaw added in v0.16.0

func DecodeNativeMetadataRecordsRaw(raw []byte, targets []TurnDetail) ([]NativeMetadataRecord, error)

DecodeNativeMetadataRecordsRaw preserves presence and lexical evidence before validating the same record matrix used by detail and transcript consumers.

type NativeMetadataSourceType added in v0.16.0

type NativeMetadataSourceType string
const (
	NativeSourcePiCustom        NativeMetadataSourceType = "pi.custom"
	NativeSourcePiCustomMessage NativeMetadataSourceType = "pi.custom_message"
	NativeSourcePiMessage       NativeMetadataSourceType = "pi.message"
	NativeSourcePiCompaction    NativeMetadataSourceType = "pi.compaction"
	NativeSourcePiBranchSummary NativeMetadataSourceType = "pi.branch_summary"
)

func NewNativeMetadataSourceType added in v0.16.0

func NewNativeMetadataSourceType(raw string) (NativeMetadataSourceType, error)

func (NativeMetadataSourceType) IsValid added in v0.16.0

func (v NativeMetadataSourceType) IsValid() bool

func (NativeMetadataSourceType) JSONSchema added in v0.16.0

type NativePiMessageRole added in v0.16.0

type NativePiMessageRole string
const NativePiMessageRoleToolResult NativePiMessageRole = "toolResult"

func NewNativePiMessageRole added in v0.16.0

func NewNativePiMessageRole(raw string) (NativePiMessageRole, error)

func (NativePiMessageRole) IsValid added in v0.16.0

func (v NativePiMessageRole) IsValid() bool

func (NativePiMessageRole) JSONSchema added in v0.16.0

func (NativePiMessageRole) JSONSchema() (jsonschema.Schema, error)

type NativeSourceRef added in v0.16.0

type NativeSourceRef struct {
	EntryRef    SourceEntryRef           `json:"entryRef"`
	SourceType  NativeMetadataSourceType `json:"sourceType"`
	MessageRole NativePiMessageRole      `json:"messageRole,omitempty"`
}

type NegativeLookalike

type NegativeLookalike struct {
	Name        string `yaml:"name"`
	Template    string `yaml:"template"`
	ErrContains string `yaml:"err_contains"`
}

NegativeLookalike is a first-class reject case that LOOKS valid (e.g. a URL whose last path segment is a UUID but whose path is not the canonical /transcripts/<uuid> shape). ParseTranscriptRef rejects all of these, so each asserts LIVE in the InvalidCases loop.

type ObservedModelID added in v0.1.1

type ObservedModelID ModelID

ObservedModelID is a model identifier observed on one assistant-generated turn. Producers preserve exact observations, including repeats and omissions; consumers carry observations forward only when deriving effective sticky state. Carry-forward never populates an omitted ObservedModel on the wire. Producers enforce that observations belong only to assistant or subagent output because generated shape validators cannot express that role condition.

func NewObservedModelID added in v0.1.1

func NewObservedModelID(raw string) (ObservedModelID, error)

NewObservedModelID validates and constructs an ObservedModelID. Accepted bytes are preserved exactly. Values must be valid UTF-8, non-empty, and may not have a Unicode White_Space code point at either edge. Internal whitespace and all other valid Unicode are retained without normalization or canonicalization.

func (ObservedModelID) JSONSchema added in v0.1.1

func (ObservedModelID) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (ObservedModelID) String added in v0.1.1

func (m ObservedModelID) String() string

String returns the exact source-observed identifier bytes.

type OperationIssue added in v0.31.0

type OperationIssue struct {
	Code      OperationIssueCode  `json:"code"`
	Operation CollectiveOperation `json:"operation"`
	Message   string              `json:"message" minLength:"1" maxLength:"2048"`
	Retry     string              `json:"retry" minLength:"1" maxLength:"2048"`
}

func (*OperationIssue) UnmarshalJSON added in v0.31.0

func (v *OperationIssue) UnmarshalJSON(data []byte) error

func (OperationIssue) Validate added in v0.31.0

func (i OperationIssue) Validate() error

type OperationIssueCode added in v0.31.0

type OperationIssueCode string
const (
	OperationIssueAuth        OperationIssueCode = "auth"
	OperationIssueRemote      OperationIssueCode = "remote"
	OperationIssueContract    OperationIssueCode = "contract"
	OperationIssueDeadline    OperationIssueCode = "deadline"
	OperationIssuePersistence OperationIssueCode = "persistence"
	OperationIssueSuperseded  OperationIssueCode = "superseded"
)

func (OperationIssueCode) IsValid added in v0.31.0

func (v OperationIssueCode) IsValid() bool

func (OperationIssueCode) JSONSchema added in v0.31.0

func (OperationIssueCode) JSONSchema() (jsonschema.Schema, error)

type OwnerTranscriptUpdateRequest

type OwnerTranscriptUpdateRequest struct {
	Title       *string                     `json:"title,omitempty" maxLength:"500" nullable:"false"`
	Description *string                     `json:"description,omitempty" nullable:"false"`
	Tags        *[]string                   `json:"tags,omitempty" nullable:"false"`
	License     OwnerUpdateLicenseIntent    `json:"license,omitempty"`
	Visibility  *TranscriptUpdateVisibility `json:"visibility,omitempty" nullable:"false"`
}

OwnerTranscriptUpdateRequest is the successor owner update request. Every field is optional; empty text and tags clear, while license null requests clear.

func DecodeOwnerTranscriptUpdateRequest

func DecodeOwnerTranscriptUpdateRequest(data []byte) (OwnerTranscriptUpdateRequest, error)

func (OwnerTranscriptUpdateRequest) MarshalJSON

func (request OwnerTranscriptUpdateRequest) MarshalJSON() ([]byte, error)

func (*OwnerTranscriptUpdateRequest) UnmarshalJSON

func (request *OwnerTranscriptUpdateRequest) UnmarshalJSON(data []byte) error

func (OwnerTranscriptUpdateRequest) Validate

func (request OwnerTranscriptUpdateRequest) Validate() error

type OwnerTranscriptUpdateResponse

type OwnerTranscriptUpdateResponse struct {
	TranscriptID  TranscriptID               `json:"transcriptId"`
	TranscriptURL string                     `json:"transcriptUrl"`
	Title         *string                    `json:"title"`
	Description   *string                    `json:"description"`
	Tags          []string                   `json:"tags" nullable:"false"`
	License       *License                   `json:"license"`
	Visibility    TranscriptUpdateVisibility `json:"visibility"`
	UpdatedAt     int64                      `json:"updatedAt"`
}

OwnerTranscriptUpdateResponse is the complete authoritative editable state.

func (*OwnerTranscriptUpdateResponse) UnmarshalJSON

func (response *OwnerTranscriptUpdateResponse) UnmarshalJSON(data []byte) error

func (OwnerTranscriptUpdateResponse) Validate

func (response OwnerTranscriptUpdateResponse) Validate() error

type OwnerUpdateEncodingInput

type OwnerUpdateEncodingInput struct {
	SetTitle       bool   `yaml:"set_title"`
	Title          string `yaml:"title"`
	SetDescription bool   `yaml:"set_description"`
	Description    string `yaml:"description"`
	SetVisibility  string `yaml:"set_visibility"`
	SetLicense     bool   `yaml:"set_license"`
	License        string `yaml:"license"`
}

OwnerUpdateEncodingInput is a Go-side update intent expressed so the fixture can distinguish "field not set" from "field set to an empty value". Each set_* flag makes the corresponding value participate; without it the field stays nil and must not reach the wire. That separation is the whole point of the arm: it is what proves preserve, clear, and replace stay distinguishable.

func (OwnerUpdateEncodingInput) ToRequest

ToRequest builds the real TranscriptUpdateRequest a caller would construct. It returns the production type rather than a test-local mirror so the encoding arm exercises the shipped marshaling behavior.

type OwnerUpdateFixtures

type OwnerUpdateFixtures struct {
	// RequiredBehaviours is the closed set, declared in the corpus itself so both
	// language bindings read ONE source instead of each keeping a copy. A
	// hand-mirrored list in the other language protects only the members someone
	// remembered to copy, while claiming both sides are guarded.
	RequiredBehaviours []OwnerUpdateRequestBehaviour `yaml:"required_behaviours"`
	// RequiredDescriptionAnchors is the count the anchors row must carry. The
	// anchors are prose, so a closed set does not fit them; a count in the corpus
	// at least makes a silent deletion from the row fail.
	RequiredDescriptionAnchors int                                                               `yaml:"required_description_anchors"`
	RequestValidations         testcase.Corpus[string, OwnerUpdateValidationExpectation]         `yaml:"request_validations"`
	Encodings                  testcase.Corpus[OwnerUpdateEncodingInput, string]                 `yaml:"encodings"`
	SpecExpectations           testcase.Corpus[OwnerUpdateSpecProbe, OwnerUpdateSpecExpectation] `yaml:"spec_expectations"`
}

OwnerUpdateFixtures is the segmented owner-update corpus: one named arm per behavior under test. The arms are heterogeneous on purpose. Request validation works on raw client bytes, encoding works on a Go-side intent, and the spec probes work on the generated document, so a single input type would have to be a union that hides which behavior a row actually exercises.

func LoadOwnerUpdateFixtures

func LoadOwnerUpdateFixtures() (*OwnerUpdateFixtures, error)

LoadOwnerUpdateFixtures parses OwnerUpdateYAML into the segmented corpus. It rejects unknown fields, trailing documents, and any case missing its classification, provenance, or mutation metadata, so a row cannot enter the corpus without recording why it exists and what it changes.

type OwnerUpdateLicenseIntent

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

OwnerUpdateLicenseIntent preserves omission separately from explicit null. Omission preserves, null requests clear, and a canonical value replaces.

func NewOwnerUpdateLicenseIntent

func NewOwnerUpdateLicenseIntent(value *License) (OwnerUpdateLicenseIntent, error)

func (OwnerUpdateLicenseIntent) IsSet

func (v OwnerUpdateLicenseIntent) IsSet() bool

func (OwnerUpdateLicenseIntent) JSONSchema

func (OwnerUpdateLicenseIntent) MarshalJSON

func (v OwnerUpdateLicenseIntent) MarshalJSON() ([]byte, error)

func (*OwnerUpdateLicenseIntent) UnmarshalJSON

func (v *OwnerUpdateLicenseIntent) UnmarshalJSON(data []byte) error

func (OwnerUpdateLicenseIntent) Value

func (v OwnerUpdateLicenseIntent) Value() (License, bool)

type OwnerUpdateRequestBehaviour

type OwnerUpdateRequestBehaviour string

OwnerUpdateRequestBehaviour is the closed set of contract behaviours the request_validations arm must cover.

It exists because a row-count floor cannot protect a corpus. A minimum with slack in it lets rows carrying a whole behaviour be deleted without any assertion noticing, and a fixture row is not code, so no mutation of the production source can reach it. Naming the behaviours and asserting coverage per member makes the corpus itself guarded input: losing every null-refusal row now fails, where losing six of twenty rows previously did not.

const (
	// OwnerUpdateBehaviourVisibilityAccepted covers an accepted visibility value.
	OwnerUpdateBehaviourVisibilityAccepted OwnerUpdateRequestBehaviour = "visibility_accepted"
	// OwnerUpdateBehaviourVisibilityRefused covers a visibility outside the menu.
	OwnerUpdateBehaviourVisibilityRefused OwnerUpdateRequestBehaviour = "visibility_refused"
	// OwnerUpdateBehaviourLicenseAccepted covers a canonical menu license.
	OwnerUpdateBehaviourLicenseAccepted OwnerUpdateRequestBehaviour = "license_accepted"
	// OwnerUpdateBehaviourLicenseClearAccepted covers the clear sentinel, the
	// value that makes un-licensing requestable and therefore refusable.
	OwnerUpdateBehaviourLicenseClearAccepted OwnerUpdateRequestBehaviour = "license_clear_accepted"
	// OwnerUpdateBehaviourLicenseRefused covers a license off the menu.
	OwnerUpdateBehaviourLicenseRefused OwnerUpdateRequestBehaviour = "license_refused"
	// OwnerUpdateBehaviourNullRefused covers an explicit JSON null, which the
	// server would read as preserve rather than the clear a caller intends.
	OwnerUpdateBehaviourNullRefused OwnerUpdateRequestBehaviour = "null_refused"
	// OwnerUpdateBehaviourUnknownFieldRefused covers a field the server accepts
	// and silently discards.
	OwnerUpdateBehaviourUnknownFieldRefused OwnerUpdateRequestBehaviour = "unknown_field_refused"
	// OwnerUpdateBehaviourOmissionAccepted covers omission meaning unchanged.
	OwnerUpdateBehaviourOmissionAccepted OwnerUpdateRequestBehaviour = "omission_accepted"
	// OwnerUpdateBehaviourEmptyStringAccepted covers the empty string as a real
	// clearing value rather than an omission.
	OwnerUpdateBehaviourEmptyStringAccepted OwnerUpdateRequestBehaviour = "empty_string_accepted"
	// OwnerUpdateBehaviourTitleBoundEnforced covers the declared title bound at
	// its two decisive points. The bound was previously asserted only as text in
	// the published document, so the Go validator accepted a title the generated
	// JavaScript validator refused.
	OwnerUpdateBehaviourTitleBoundEnforced OwnerUpdateRequestBehaviour = "title_bound_enforced"
)

func (OwnerUpdateRequestBehaviour) IsValid

func (b OwnerUpdateRequestBehaviour) IsValid() bool

IsValid reports whether the behaviour is a known member.

type OwnerUpdateSpecExpectation

type OwnerUpdateSpecExpectation struct {
	Strings []string `yaml:"strings"`
}

OwnerUpdateSpecExpectation is the exact set of strings a probe must observe. It is an exact set rather than a subset so a widening (an extra enum member, an extra declared status) fails the row and has to be stated deliberately.

type OwnerUpdateSpecProbe

type OwnerUpdateSpecProbe struct {
	Probe OwnerUpdateSpecProbeKind `yaml:"probe"`
}

OwnerUpdateSpecProbe selects which generated-document property a row asserts.

type OwnerUpdateSpecProbeKind

type OwnerUpdateSpecProbeKind string

OwnerUpdateSpecProbeKind is the closed set of generated-document properties the spec arm can assert. It is closed so a fixture cannot silently name a probe no test implements, which would let a row pass by doing nothing.

const (
	// OwnerUpdateProbeOperationDeclared asserts the operation exists and carries
	// its declared operation id.
	OwnerUpdateProbeOperationDeclared OwnerUpdateSpecProbeKind = "operation_declared"
	// OwnerUpdateProbePathParameter asserts the transcript id is a required path
	// parameter.
	OwnerUpdateProbePathParameter OwnerUpdateSpecProbeKind = "path_parameter"
	// OwnerUpdateProbeBodyIsReference asserts the request body is a component
	// reference rather than an inline object.
	OwnerUpdateProbeBodyIsReference OwnerUpdateSpecProbeKind = "body_is_reference"
	// OwnerUpdateProbeResponseStatuses asserts the declared refusal status set.
	OwnerUpdateProbeResponseStatuses OwnerUpdateSpecProbeKind = "response_statuses"
	// OwnerUpdateProbeVisibilityEnum asserts the declared visibility members.
	OwnerUpdateProbeVisibilityEnum OwnerUpdateSpecProbeKind = "visibility_enum"
	// OwnerUpdateProbeLicenseEnum asserts the declared license members.
	OwnerUpdateProbeLicenseEnum OwnerUpdateSpecProbeKind = "license_enum"
	// OwnerUpdateProbeBodyProperties asserts the exact property set the body
	// declares. Without it the payload, which is the operation's whole subject,
	// has nothing pinning its field names.
	OwnerUpdateProbeBodyProperties OwnerUpdateSpecProbeKind = "body_properties"
	// OwnerUpdateProbePathParameterIsCanonical asserts the path parameter is the
	// canonical validated identifier rather than a bare string, so the contract
	// stops describing ids the server refuses outright.
	OwnerUpdateProbePathParameterIsCanonical OwnerUpdateSpecProbeKind = "path_parameter_is_canonical"
	// OwnerUpdateProbeTitleMaxLength asserts the declared title bound matches the
	// storage column, so an over-long title is refused before it becomes an
	// opaque server error.
	OwnerUpdateProbeTitleMaxLength OwnerUpdateSpecProbeKind = "title_max_length"
	// OwnerUpdateProbeBodyIsRequired asserts the request body is declared
	// required. Reflection defaults it to optional, which would describe a
	// request the server always refuses.
	OwnerUpdateProbeBodyIsRequired OwnerUpdateSpecProbeKind = "body_is_required"
	// OwnerUpdateProbeDescriptionAnchors asserts the operation description still
	// carries the claims a consumer relies on. The description is the only place
	// several contract decisions are explained, and prose is otherwise unguarded:
	// deleting it changes no assertion and breaks no build.
	OwnerUpdateProbeDescriptionAnchors OwnerUpdateSpecProbeKind = "description_anchors"
	// OwnerUpdateProbeRefusalEnvelopeProperties asserts the EXACT property set of
	// the refusal envelope. Asserting that a property exists cannot detect a
	// property that appears: an invented field on the envelope shipped with the
	// whole suite green, because nothing said which properties the envelope has.
	// This is the response-side twin of the request body's property probe.
	OwnerUpdateProbeRefusalEnvelopeProperties OwnerUpdateSpecProbeKind = "refusal_envelope_properties"
	// OwnerUpdateProbeBodyIsClosed asserts the body rejects unknown properties
	// rather than accepting and discarding them.
	OwnerUpdateProbeBodyIsClosed OwnerUpdateSpecProbeKind = "body_is_closed"
	// OwnerUpdateProbeSuccessHasNoBody asserts the success status is declared but
	// carries no content schema. It guards the deliberate omission in BOTH
	// directions: dropping the status, or inventing a success body the village
	// does not serve, each fail.
	OwnerUpdateProbeSuccessHasNoBody OwnerUpdateSpecProbeKind = "success_has_no_body"
)

func (OwnerUpdateSpecProbeKind) IsValid

func (k OwnerUpdateSpecProbeKind) IsValid() bool

IsValid reports whether the probe kind is a known member.

func (OwnerUpdateSpecProbeKind) String

func (k OwnerUpdateSpecProbeKind) String() string

type OwnerUpdateValidationExpectation

type OwnerUpdateValidationExpectation struct {
	Accepted      bool                        `yaml:"accepted"`
	ErrorContains string                      `yaml:"error_contains"`
	Behaviour     OwnerUpdateRequestBehaviour `yaml:"behaviour"`
}

OwnerUpdateValidationExpectation is the verdict for one raw request body: whether the contract accepts it and, for a refusal, a distinctive fragment of the actionable message. ErrorContains is empty exactly when Accepted is true.

type Page added in v0.30.0

type Page[T any] struct {
	Items []T       `json:"items" nullable:"false"`
	Next  PageToken `json:"next"`
}

Page has at most the requested maximum items. Only empty Next means done: a short or empty Items array may still carry continuation.

func (Page[T]) Validate added in v0.30.0

func (p Page[T]) Validate() error

Validate checks the common array contract and any item-owned validations. Request-specific bounds and token scope belong to the domain reader.

type PageReader added in v0.30.0

type PageReader[T any] interface {
	ReadPage(context.Context, PageRequest) (Page[T], error)
}

PageReader reads forward within constructor-configured domain scope.

type PageRequest added in v0.30.0

type PageRequest struct {
	MaxItems int
	Token    PageToken
}

PageRequest is Go-only reader input. Domain adapters own defaults and caps.

type PageToken added in v0.30.0

type PageToken string

PageToken is an opaque continuation. Empty starts traversal or marks its end. Tokens are not credentials, authorization, or a snapshot-consistency promise.

func (PageToken) JSONSchema added in v0.30.0

func (PageToken) JSONSchema() (jsonschema.Schema, error)

type ProjectContext

type ProjectContext struct {
	Hash     ProjectHash `json:"hash"`               // SHA-256 of project origin URL or path
	FilePath string      `json:"filePath,omitempty"` // Local repo path
	Name     string      `json:"name"`               // Repo basename
}

ProjectContext identifies the project associated with a session.

type ProjectHash

type ProjectHash string

ProjectHash is a SHA-256 hex digest of the project's origin URL or local path.

func NewProjectHash

func NewProjectHash(raw string) (ProjectHash, error)

NewProjectHash validates and constructs a ProjectHash.

func (ProjectHash) JSONSchema

func (ProjectHash) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (ProjectHash) String

func (p ProjectHash) String() string

func (ProjectHash) Validate

func (p ProjectHash) Validate() error

Validate reports whether p is the canonical 64-character lowercase hex project identity accepted at wire boundaries.

type ProjectResolutionPayload

type ProjectResolutionPayload struct {
	Project     string      `json:"project" required:"true"`
	ProjectHash ProjectHash `json:"projectHash" required:"true"`
}

ProjectResolutionPayload resolves one explicitly requested project display identity to its opaque hash without enumerating sibling projects. It exists for stable deep links when discovery lists are narrowed by user selection.

type ProjectSummariesPayload

type ProjectSummariesPayload struct {
	Projects []ProjectSummary `json:"projects"`
}

ProjectSummariesPayload backs the home project picker, served by GET /api/v1/projects/summary.

func NewProjectSummariesPayload

func NewProjectSummariesPayload() *ProjectSummariesPayload

NewProjectSummariesPayload returns a ProjectSummariesPayload with all slices initialized to empty (never-nil marshal guarantee).

type ProjectSummary

type ProjectSummary struct {
	ProjectHash   ProjectHash `json:"projectHash"`
	Project       string      `json:"project"`       // display name (canonical cwd, else the hash)
	Sessions      int         `json:"sessions"`      // recorded session count
	RecordedFiles int         `json:"recordedFiles"` // coverage numerator (same rule as MapNode)
	TotalFiles    int         `json:"totalFiles"`    // coverage denominator
	LastWorkMs    *int64      `json:"lastWorkMs,omitempty"`
	OpenChanges   int         `json:"openChanges"` // local non-default branches not merged (0 when no repo)
}

ProjectSummary is one row of the home picker: a project with its recorded stats (sessions · recorded coverage · last work · open changes).

type ProjectTasksPayload

type ProjectTasksPayload struct {
	ProjectHash ProjectHash   `json:"projectHash"`
	Tasks       []TaskSummary `json:"tasks"` // reverse-chronological, cap 500
	FileFilter  string        `json:"fileFilter,omitempty"`
}

ProjectTasksPayload backs the Tasks lens, served by GET /api/v1/map/{projectHash}/tasks?file=<path>.

func NewProjectTasksPayload

func NewProjectTasksPayload(projectHash ProjectHash) *ProjectTasksPayload

NewProjectTasksPayload returns a ProjectTasksPayload with all slices initialized to empty (never-nil marshal guarantee).

type PromptDigest added in v0.17.0

type PromptDigest struct {
	Header PromptDigestHeader  `json:"header"`
	Skills []PromptDigestSkill `json:"skills" nullable:"false"`
	Items  []PromptDigestItem  `json:"items" nullable:"false"`
}

PromptDigest is the reviewer-facing projection of the prompts behind a pull request. It is always the complete chain across every attached transcript; the comment and check-run budgets described in the design are applied by the renderer, never by dropping items from this type.

func (PromptDigest) Validate added in v0.17.0

func (d PromptDigest) Validate() error

Validate checks every item, the chronological order of the chain, the header skills, and that the header counts describe the complete chain.

type PromptDigestHeader added in v0.17.0

type PromptDigestHeader struct {
	SessionCount   int     `json:"sessionCount"`
	PromptCount    int     `json:"promptCount"`
	CommitsCovered int     `json:"commitsCovered"`
	CommitsTotal   int     `json:"commitsTotal"`
	Harness        Harness `json:"harness"`
	RedactionLevel string  `json:"redactionLevel"`
	VillageURL     string  `json:"villageUrl"`
}

PromptDigestHeader summarises the complete chain. Counts describe the whole digest, never a rendered tier.

type PromptDigestItem added in v0.17.0

type PromptDigestItem struct {
	Kind         DigestItemKind `json:"kind"`
	TranscriptID TranscriptID   `json:"transcriptId"`
	Timestamp    time.Time      `json:"timestamp"`
	Text         string         `json:"text"`
	// TurnIndex deep-links a prompt or skill marker into the transcript viewer.
	TurnIndex *int `json:"turnIndex,omitempty"`
	// Ordinal is the 1-based prompt number a reviewer sees. Prompts only.
	Ordinal *int `json:"ordinal,omitempty"`
	// CommitSHA is the full or abbreviated SHA of a commit anchor. Commits only.
	CommitSHA string `json:"commitSha,omitempty"`
	// PromptCount and CommitCount summarise a session boundary. Sessions only.
	PromptCount *int `json:"promptCount,omitempty"`
	CommitCount *int `json:"commitCount,omitempty"`
	// Additions, Deletions, and FilesChanged are the lines added, the lines
	// deleted, and the number of files a commit touched, as the hosting
	// provider reports them. Commits only, and all three together or not at
	// all; they are absent when the counts were not read.
	Additions    *int `json:"additions,omitempty"`
	Deletions    *int `json:"deletions,omitempty"`
	FilesChanged *int `json:"filesChanged,omitempty"`
	// Args is the text that followed a skill or user command invocation on the
	// same line, as the producer recorded it (for example "add retries" in
	// "/plan add retries"). Skill items only and optional; it is absent when the
	// invocation carried no argument.
	Args string `json:"args,omitempty"`
}

PromptDigestItem is one entry in the chronological chain. Which optional fields are set depends on Kind; Validate states the rule for each kind.

func (PromptDigestItem) Validate added in v0.17.0

func (i PromptDigestItem) Validate() error

Validate enforces the per-kind field rules.

type PromptDigestSkill added in v0.17.0

type PromptDigestSkill struct {
	Name            string `json:"name"`
	InvocationCount int    `json:"invocationCount"`
}

PromptDigestSkill is one distinct skill or user slash command across every attached session, with how many times it was invoked. Name is a slash-prefixed skill or user command as recorded by the harness, or a bare plugin identifier for a tool provider observed through tool calls. Renderers distinguish the two by the leading slash.

type Provenance

type Provenance struct {
	Method   string            `json:"method"` // "heuristic", "regex", "llm_judge", "manual"
	Function string            `json:"function,omitempty"`
	Version  string            `json:"version,omitempty"`
	Details  map[string]string `json:"details,omitempty"`
}

Provenance records how a non-human annotator derived its annotation value. Only populated for rule-based and agent annotators; nil for human annotations.

type PublicRevisionRef added in v0.19.0

type PublicRevisionRef string

func NewPublicRevisionRef added in v0.19.0

func NewPublicRevisionRef(raw string) (PublicRevisionRef, error)

func (PublicRevisionRef) JSONSchema added in v0.19.0

func (PublicRevisionRef) JSONSchema() (jsonschema.Schema, error)

func (PublicRevisionRef) Validate added in v0.19.0

func (v PublicRevisionRef) Validate() error

type PublicSourceAnchor added in v0.19.0

type PublicSourceAnchor struct {
	Kind              PublicSourceAnchorKind `json:"kind" yaml:"kind"`
	SourceEntryRef    SourceEntryRef         `json:"sourceEntryRef,omitempty" yaml:"sourceEntryRef"`
	SourceRevisionRef PublicRevisionRef      `json:"sourceRevisionRef,omitempty" yaml:"sourceRevisionRef"`
}

func (PublicSourceAnchor) Validate added in v0.19.0

func (a PublicSourceAnchor) Validate() error

type PublicSourceAnchorKind added in v0.19.0

type PublicSourceAnchorKind string
const (
	PublicSourceAnchorGeneral PublicSourceAnchorKind = "general_source_session"
	PublicSourceAnchorBefore  PublicSourceAnchorKind = "before_redacted_entry"
	PublicSourceAnchorThrough PublicSourceAnchorKind = "through_redacted_entry"
)

func NewPublicSourceAnchorKind added in v0.19.0

func NewPublicSourceAnchorKind(raw string) (PublicSourceAnchorKind, error)

func (PublicSourceAnchorKind) IsValid added in v0.19.0

func (v PublicSourceAnchorKind) IsValid() bool

func (PublicSourceAnchorKind) JSONSchema added in v0.19.0

type PublishAppliedState

type PublishAppliedState struct {
	License          *License                `json:"license"`
	Associations     []PublishedAssociation  `json:"associations" nullable:"false"`
	NormalizedValues PublishNormalizedValues `json:"normalizedValues"`
}

func (*PublishAppliedState) UnmarshalJSON

func (value *PublishAppliedState) UnmarshalJSON(data []byte) error

func (PublishAppliedState) Validate

func (state PublishAppliedState) Validate() error

type PublishAssociationOperation

type PublishAssociationOperation struct {
	Kind         PublishOperationKind   `json:"kind"`
	Associations []PublishedAssociation `json:"associations" nullable:"false"`
}

type PublishLicenseOperation

type PublishLicenseOperation struct {
	Kind    PublishOperationKind `json:"kind"`
	License *License             `json:"license"`
}

type PublishNormalizedValues

type PublishNormalizedValues struct {
	RootHarness    Harness    `json:"rootHarness"`
	EntryHarnesses []Harness  `json:"entryHarnesses" nullable:"false"`
	DerivedTitle   *string    `json:"derivedTitle"`
	Visibility     Visibility `json:"visibility"`
	SchemaVersion  string     `json:"schemaVersion"`
}

PublishNormalizedValues is the complete set of values Village normalizes.

func (*PublishNormalizedValues) UnmarshalJSON

func (value *PublishNormalizedValues) UnmarshalJSON(data []byte) error

type PublishOperationKind

type PublishOperationKind string
const (
	PublishOperationPreserve PublishOperationKind = "preserve"
	PublishOperationReplace  PublishOperationKind = "replace"
	PublishOperationAppend   PublishOperationKind = "append"
)

func (PublishOperationKind) IsValid

func (v PublishOperationKind) IsValid() bool

func (PublishOperationKind) JSONSchema

func (v PublishOperationKind) JSONSchema() (jsonschema.Schema, error)

type PublishRequest

type PublishRequest struct {
	Identity    SessionIdentity `json:"identity"`
	Model       ModelInfo       `json:"model" required:"true"`
	Timestamp   TimestampInfo   `json:"timestamp"`
	Source      SourceInfo      `json:"source"`
	Git         GitContext      `json:"git"`
	Project     ProjectContext  `json:"project"`
	Stats       SessionStats    `json:"stats"`
	Quality     *QualityMetrics `json:"quality,omitempty"`
	Entries     []SessionEntry  `json:"entries,omitempty"`
	Subagents   []SubagentRef   `json:"subagents,omitempty"`
	Diagnostics DiagnosticsInfo `json:"diagnostics"`
	// License is the content license the contributor selected for this transcript
	// (CC0-1.0 / CC-BY-4.0 / CC-BY-SA-4.0). Optional — omitempty ⇒ a publish with no
	// license stores NULL (legacy/un-set). The village persists it to
	// transcripts.license_id; the vendored schema enum makes an invalid value a
	// documented schema-422. NOT `required` (keeps the Village publish body required set at [model]).
	License License `json:"license,omitempty"`
}

PublishRequest is the frozen rc11/Village 0.10.0 metadata shape retained for compatibility. Village 0.12.0 publishing uses AuthoritativePublishRequest.

Uses nested composites for logical grouping. The JSON tags on each composite struct preserve CLI wire compatibility — the top-level keys are identity, model, timestamp, source, git, project, stats, quality, subagents, and diagnostics.

MIGRATION NOTE: The CLI's current flat UnifiedMetadata will need a coordinated update to send this nested structure. This is NOT backward-compatible with the current village handler — both CLI and village must update together.

The Village operation-specific publish component requires model, so a body without it is rejected; this changes generated validation requiredness, not the canonical Go wire shape.

func (PublishRequest) Validate

func (r PublishRequest) Validate() error

Validate checks the request-local associations carried in the publish wire. Other publish-body validation remains the responsibility of the generated PublishRequest JSON Schema at the HTTP boundary.

type PublishRequestFingerprint

type PublishRequestFingerprint string

PublishRequestFingerprint identifies one canonical accepted publish operation.

func FingerprintPublishOperation

func FingerprintPublishOperation(operation CanonicalPublishOperation) (PublishRequestFingerprint, error)

func NewPublishRequestFingerprint

func NewPublishRequestFingerprint(raw string) (PublishRequestFingerprint, error)

func (PublishRequestFingerprint) JSONSchema

func (PublishRequestFingerprint) String

func (v PublishRequestFingerprint) String() string

func (PublishRequestFingerprint) Validate

func (v PublishRequestFingerprint) Validate() error

type PublishResponse

type PublishResponse struct {
	TranscriptID  string `json:"transcriptId"`
	BlobKey       string `json:"blobKey"`
	BlobSizeBytes int64  `json:"blobSizeBytes"`
	PublishedAt   int64  `json:"publishedAt"`
	UpdatedAt     int64  `json:"updatedAt"`
	Created       bool   `json:"created"`
}

PublishResponse is the released rc11 response retained for source and frozen artifact compatibility. Village API 0.12.0 uses AuthoritativePublishResponse.

type PublishVerdictCase

type PublishVerdictCase struct {
	Name   string                    `yaml:"name"`
	Body   string                    `yaml:"body"`
	Expect PublishVerdictExpectation `yaml:"expect"`
}

PublishVerdictCase is one concrete publish body and its schema/HTTP verdict.

func (PublishVerdictCase) ModelHarness

func (c PublishVerdictCase) ModelHarness() (string, bool, error)

ModelHarness returns body.model.harness when the case body contains one.

type PublishVerdictExpectation

type PublishVerdictExpectation struct {
	SchemaAccepts bool   `yaml:"schema_accepts"`
	LegacyAccepts *bool  `yaml:"legacy_accepts,omitempty"`
	HTTPStatus    int    `yaml:"http_status,omitempty"`
	ErrorCategory string `yaml:"error_category,omitempty"`
	ErrorContains string `yaml:"error_contains,omitempty"`
}

PublishVerdictExpectation attaches expected outcomes to a publish verdict row.

type PublishVerdictFixtures

type PublishVerdictFixtures struct {
	Cases []PublishVerdictCase `yaml:"cases"`
}

PublishVerdictFixtures is the parsed testdata/publish/verdicts.yaml corpus.

func LoadPublishVerdictFixtures

func LoadPublishVerdictFixtures() (*PublishVerdictFixtures, error)

LoadPublishVerdictFixtures parses PublishVerdictsYAML into structured fixtures.

func (*PublishVerdictFixtures) Acceptances

func (f *PublishVerdictFixtures) Acceptances() []PublishVerdictCase

Acceptances returns the corpus rows the schema MUST accept (schema_accepts:true). It is the accept-pass input to RunPublishVerdicts; together with Rejections it partitions Cases exactly (the partition-completeness guard in RunPublishVerdicts depends on len(Acceptances)+len(Rejections)==len(Cases)).

func (*PublishVerdictFixtures) CaseByName

func (f *PublishVerdictFixtures) CaseByName(name string) (PublishVerdictCase, bool)

CaseByName returns the verdict row with the given stable name.

func (*PublishVerdictFixtures) Rejections

func (f *PublishVerdictFixtures) Rejections() []PublishVerdictCase

Rejections returns the corpus rows the schema MUST reject (schema_accepts:false). It is the reject-pass input to RunPublishVerdicts (see Acceptances).

type PublishedAssociation

type PublishedAssociation struct {
	ID                 AssociationID `json:"id" yaml:"id"`
	ObservedCommitHash string        `json:"observedCommitHash" yaml:"observedCommitHash"`
}

PublishedAssociation is the producer-owned durable identity for one observed session-to-commit relationship published with a transcript. Its ID is opaque to consumers. The enclosing PublishRequest.Identity.SessionID supplies the session identity, so it is deliberately not repeated here.

Within a publish request, both ID and ObservedCommitHash must be unique. Consumers retain one durable ID for each owner, transcript, and observed commit hash: an exact replay is idempotent, while a changed binding or a second ID for the same relationship must be rejected rather than aliased.

func (PublishedAssociation) Validate

func (a PublishedAssociation) Validate() error

Validate checks that a published association can be addressed durably by a consumer. ObservedCommitHash remains producer data rather than a re-parsed Git object, but it must be present so it can participate in canonical owner/transcript/observed-hash identity.

type PullAnnotation

type PullAnnotation struct {
	AnnotationSummary        // embedded existing summary (annotator entity, content hash, etc.)
	AuthorUserID      string `json:"authorUserId"`
	AuthorUsername    string `json:"authorUsername"`
}

PullAnnotation is the authored-annotation row for the pull surface (GET /api/v1/pull/transcripts/{id}/annotations). It embeds the existing AnnotationSummary and adds the village account identity (AuthorUserID / AuthorUsername) the summary does not carry — required to foreign-mark pulled annotations and to exclude the requester's own authored rows during the annotation-refresh path (creds.UserID == AuthorUserID).

type PullAssociationMetadataResult added in v0.31.0

type PullAssociationMetadataResult struct {
	State      PullAssociationMetadataState `json:"state"`
	ObservedAt *time.Time                   `json:"observedAt,omitempty"`
	Warning    *OperationIssue              `json:"warning,omitempty"`
}

func (*PullAssociationMetadataResult) UnmarshalJSON added in v0.31.0

func (v *PullAssociationMetadataResult) UnmarshalJSON(data []byte) error

func (PullAssociationMetadataResult) Validate added in v0.31.0

func (r PullAssociationMetadataResult) Validate() error

type PullAssociationMetadataState added in v0.31.0

type PullAssociationMetadataState string
const (
	PullAssociationMetadataObserved    PullAssociationMetadataState = "observed"
	PullAssociationMetadataStale       PullAssociationMetadataState = "stale"
	PullAssociationMetadataUnknown     PullAssociationMetadataState = "unknown"
	PullAssociationMetadataInvalidated PullAssociationMetadataState = "invalidated"
)

func (PullAssociationMetadataState) IsValid added in v0.31.0

func (v PullAssociationMetadataState) IsValid() bool

func (PullAssociationMetadataState) JSONSchema added in v0.31.0

type PullListResponse

type PullListResponse struct {
	Transcripts []PullTranscriptInfo `json:"transcripts"`
	Page        int                  `json:"page"`
	Limit       int                  `json:"limit"`
	Total       int                  `json:"total"`
}

PullListResponse is the village's paginated listing of pullable transcripts (GET /api/v1/pull/transcripts) — own + group-shared (public excluded by the canPullTranscript policy).

type PullRefFixtures

type PullRefFixtures struct {
	Values            PullRefValues        `yaml:"values"`
	IDCasings         []IDCasing           `yaml:"id_casings"`
	RefForms          []RefForm            `yaml:"ref_forms"`
	ValidGeneration   ValidGeneration      `yaml:"valid_generation"`
	InvalidRefs       []InvalidRefCategory `yaml:"invalid_refs"`
	NegativeLookalike []NegativeLookalike  `yaml:"negative_lookalikes"`
}

PullRefFixtures is the top-level parsed transcript_refs.yaml structure.

func LoadPullRefFixtures

func LoadPullRefFixtures() (*PullRefFixtures, error)

LoadPullRefFixtures parses PullRefsYAML into structured fixtures. Mirrors LoadAnnotationFixtures.

func (*PullRefFixtures) AllCases

func (f *PullRefFixtures) AllCases() ([]RefCase, error)

AllCases is ValidCases followed by InvalidCases — the full materialised suite internal/pull/types_test.go ranges over.

func (*PullRefFixtures) InvalidCases

func (f *PullRefFixtures) InvalidCases() ([]RefCase, error)

InvalidCases materialises the explicit invalid_refs plus the negative_lookalikes. Every case expects an error with the category/case-attached substring.

func (*PullRefFixtures) UUIDLower

func (f *PullRefFixtures) UUIDLower() string

UUIDLower returns the canonical lowercase UUID the fixture owns (== testutil TestTranscriptUUID).

func (*PullRefFixtures) ValidCases

func (f *PullRefFixtures) ValidCases() ([]RefCase, error)

ValidCases materialises the valid cross-product (id_casings x ref_forms) with the generator-attached expectation: every case parses, normalizes its ID to values.uuid_lower, and reports FromURL per its ref_form.

func (*PullRefFixtures) VillageHost

func (f *PullRefFixtures) VillageHost() string

VillageHost returns the canonical village host the fixture owns (== testutil TestVillageHost).

type PullRefValues

type PullRefValues struct {
	UUIDLower   string `yaml:"uuid_lower"`
	VillageHost string `yaml:"village_host"`
}

PullRefValues are the self-contained canonical strings the fixture owns. They are ADOPTED VERBATIM from internal/testutil (which re-exports them), so the fixture is the single source of truth with zero behaviour change.

type PullSkipGateItem

type PullSkipGateItem struct {
	// The id of a transcript the client holds and is asking about.
	TranscriptID TranscriptID `json:"transcriptId" description:"The id of a transcript the client holds and is asking about."`
	// Hex-encoded SHA3-256 content-hash the client currently holds for this
	// transcript's served blob; compared by VALUE against the server's stored hash
	// to decide contentCurrent.
	ContentHash string `` /* 178-byte string literal not displayed */
	// The client's OWN annotation content-hashes for this transcript (the set it
	// already has locally). Compared as a SET against the owner-scoped server set to
	// decide annotationsCurrent. NewPullSkipGateRequest sorts + de-duplicates it, so it
	// is always a (possibly empty) NON-null array.
	AnnotationHashes []string `` /* 197-byte string literal not displayed */
}

PullSkipGateItem is one transcript the client holds and wants a currency answer for: the transcript id, the content-hash the client currently has for it, and the set of annotation content-hashes the client itself holds for that transcript.

type PullSkipGateRequest

type PullSkipGateRequest struct {
	// The per-transcript items the client is asking a currency question about.
	// NewPullSkipGateRequest orders them by transcriptId and never returns nil, so the
	// wire is a canonical, (possibly empty) NON-null array.
	Items []PullSkipGateItem `` /* 181-byte string literal not displayed */
}

PullSkipGateRequest is the body a pulling client POSTs to the pull skip-gate endpoint. For each transcript it already holds, the client sends the id plus the content-hash it holds and its OWN annotation-hash set for that id, so the server can answer, per id, whether the stored transcript and the client's annotations are still current, letting the client skip re-downloading what has not diverged. Only the client's held HASHES travel, never content, so the request is privacy-safe.

This type is ADDITIVE: it introduces a new endpoint's request shape and does not alter any existing pull/publish/annotation-push wire contract.

func NewPullSkipGateRequest

func NewPullSkipGateRequest(items []PullSkipGateItem) PullSkipGateRequest

NewPullSkipGateRequest builds a CANONICAL skip-gate request: each item's annotation-hash set is sorted + de-duplicated (the server compares it as a SET, so order and multiplicity are irrelevant), and the items are ordered by transcriptId. Provided the request's transcript ids are UNIQUE, two clients asking about the same logical state emit byte-identical requests: the items are ordered with an unstable sort on transcriptId, so byte-identity holds only when that key has no ties (one item per transcript id, which a well-formed request satisfies). Every item's AnnotationHashes is a non-null array.

type PullSkipGateResponse

type PullSkipGateResponse struct {
	// The per-id currency answers, present ONLY for pullable ids (non-pullable ids
	// are omitted; see the type doc). NewPullSkipGateResponse orders them by
	// transcriptId and never returns nil, so the wire is a canonical, (possibly
	// empty) NON-null array.
	Results []PullSkipGateResult `` /* 170-byte string literal not displayed */
}

PullSkipGateResponse is the per-id currency answer for a PullSkipGateRequest.

LEAK-FREE WITHHELD SEMANTICS: Results carries an entry ONLY for transcript ids the caller may PULL. A non-pullable id is OMITTED from Results entirely, never echoed with a "denied" or "unknown" marker, because any per-id echo would itself be an existence / currency oracle over arbitrary ids the caller cannot pull. So the caller sends N ids and receives <= N results; an ABSENT id means "unanswered / withheld", the 404-not-403 anti-enumeration spirit applied to a batch currency probe.

This is enforced in two distinct places. The RESPONSE SHAPE carries no denial or marker field a withheld id could ride on: it is exactly {results: [{transcriptId, contentCurrent, annotationsCurrent}]}, checked by this module's exact-key-set response test, so adding and populating a wire-visible extra field reddens the assertion. An inert zero-valued `omitempty` field is not emitted and is outside this check. The actual OMISSION of non-pullable ids from Results is the village handler's pull-scoping test, since only the server knows which ids are pullable; this constructor merely canonicalizes the entries it is given and never invents one.

This type is ADDITIVE: it introduces a new endpoint's response shape and does not alter any existing pull/publish/annotation-push wire contract.

func NewPullSkipGateResponse

func NewPullSkipGateResponse(results []PullSkipGateResult) PullSkipGateResponse

NewPullSkipGateResponse builds a CANONICAL skip-gate response from the per-id answers the server computed for the PULLABLE ids ONLY. Non-pullable ids must already be omitted by the caller (see PullSkipGateResponse's leak-free contract); this constructor does not invent entries. Results are ordered by transcriptId so the wire payload is deterministic, PROVIDED the response's transcript ids are UNIQUE: the results are ordered with an unstable sort on transcriptId, so determinism holds only when that key has no ties (one result per pullable id, which the pull-scope answer satisfies). The slice is never nil.

type PullSkipGateResult

type PullSkipGateResult struct {
	// The transcript id this answer is for (always one the caller may pull).
	TranscriptID TranscriptID `json:"transcriptId" description:"The transcript id this currency answer is for (always one the caller may pull)."`
	// True when the server's stored served-blob content-hash equals the hash the
	// client sent for this id; false when it has diverged (or the server holds none).
	ContentCurrent bool `` /* 174-byte string literal not displayed */
	// True when the owner-scoped annotation set the server holds for this id equals
	// the client's held annotation set; false when it differs (missing or extra).
	AnnotationsCurrent bool `` /* 172-byte string literal not displayed */
}

PullSkipGateResult is the currency answer for one PULLABLE transcript id: whether the stored blob still matches the client's held content-hash, and whether the owner-scoped annotation set still matches the client's held annotation set.

type PullStatusFixtures

type PullStatusFixtures struct {
	Statuses []PullStatusMapping `yaml:"statuses"`
}

PullStatusFixtures is the parsed pull_statuses.yaml structure.

func LoadPullStatusFixtures

func LoadPullStatusFixtures() (*PullStatusFixtures, error)

LoadPullStatusFixtures parses PullStatusesYAML into structured fixtures.

func (*PullStatusFixtures) WireFor

func (f *PullStatusFixtures) WireFor(constName string) (string, bool)

WireFor returns the expected wire string for a given const_name, or "".

type PullStatusMapping

type PullStatusMapping struct {
	Name      string `yaml:"name"`
	ConstName string `yaml:"const_name"`
	Wire      string `yaml:"wire"`
}

PullStatusMapping is one PullStatus<->wire row.

type PullTranscriptInfo

type PullTranscriptInfo struct {
	TranscriptID    TranscriptID    `json:"transcriptId"`
	LocalID         string          `json:"localId,omitempty"` // peasant SessionID at publish — round-trip correlation
	OwnerUserID     string          `json:"ownerUserId"`
	OwnerUsername   string          `json:"ownerUsername"`
	Title           string          `json:"title,omitempty"`
	Harness         Harness         `json:"harness,omitempty"` // existing typed form
	ProjectName     string          `json:"projectName,omitempty"`
	Visibility      Visibility      `json:"visibility"`                // existing typed form
	License         License         `json:"license,omitempty"`         // legal axis; omitempty ⇒ legacy/un-set
	ContentHash     string          `json:"contentHash,omitempty"`     // SERVED-BLOB hash; empty ⇒ server has none
	ContractVersion ContractVersion `json:"contractVersion,omitempty"` // push contract the blob was published under
	PublishedAt     int64           `json:"publishedAt"`
	UpdatedAt       int64           `json:"updatedAt"`
	AnnotationCount int             `json:"annotationCount"`
}

PullTranscriptInfo is the village's metadata view of a single pullable transcript (GET /api/v1/pull/transcripts/{id}). ContentHash is the SERVER-COMPUTED hash of the served blob bytes (empty when the village has not yet computed one), and is distinct from UnifiedMetadata.ContentHash (the ingest-time, pre-push-redaction hash). ContractVersion records the push content contract the blob was published under (the blob carries its own publish-time version; the pull envelope does not version the blob).

type PushContractVersion

type PushContractVersion = ContractVersion

PushContractVersion is a zero-churn alias for ContractVersion kept for the push axis. Existing references (SchemaVersionResponse push fields, the defaults push constants) keep compiling unchanged; new code may use either name (they are the identical type).

type QualityFixtureName

type QualityFixtureName string
const (
	QualityFixtureResolvedTypical    QualityFixtureName = "resolved_typical"
	QualityFixtureResolvedHighTokens QualityFixtureName = "resolved_high_tokens"
	QualityFixturePartialMedium      QualityFixtureName = "partial_medium"
	QualityFixtureFailedComplex      QualityFixtureName = "failed_complex"
	QualityFixtureResolvedMinimal    QualityFixtureName = "resolved_minimal"
)

type QualityFixtureSet

type QualityFixtureSet struct {
	Name  QualityFixtureSetName `json:"name" yaml:"name"`
	Cases []QualityFixtureName  `json:"cases" yaml:"cases"`
}

QualityFixtureSet is a named reusable list of quality-session fixture rows.

type QualityFixtureSetName

type QualityFixtureSetName string
const (
	QualityFixtureSetProjectMix QualityFixtureSetName = "project_mix"
)

type QualityFixtures

type QualityFixtures struct {
	Sessions   []QualitySessionFixture `json:"sessions" yaml:"quality_sessions"`
	Sets       []QualityFixtureSet     `json:"sets" yaml:"quality_fixture_sets"`
	Variations QualityVariations       `json:"variations" yaml:"quality_variations"`
}

QualityFixtures is the parsed testdata/quality/sessions.yaml corpus.

func LoadQualityFixtures

func LoadQualityFixtures() (*QualityFixtures, error)

LoadQualityFixtures parses QualitySessionsYAML into structured fixtures.

func (*QualityFixtures) QualitySessions

func (f *QualityFixtures) QualitySessions() []QualitySession

QualitySessions returns all quality-session fixtures as wire payload rows.

func (*QualityFixtures) QualitySessionsForSet

func (f *QualityFixtures) QualitySessionsForSet(name QualityFixtureSetName) ([]QualitySession, error)

QualitySessionsForSet returns a named fixture set as wire payload rows.

func (*QualityFixtures) SessionByName

SessionByName returns the named quality-session fixture row.

func (*QualityFixtures) SetByName

SetByName returns the named quality fixture set.

type QualityMetricVariation

type QualityMetricVariation struct {
	Name  string  `json:"name" yaml:"name"`
	Value float64 `json:"value" yaml:"value"`
}

type QualityMetricVariations

type QualityMetricVariations struct {
	RetryLoops       []QualityMetricVariation `json:"retryLoops" yaml:"retry_loops"`
	SignalDensity    []QualityMetricVariation `json:"signalDensity" yaml:"signal_density"`
	SpecQualityScore []QualityMetricVariation `json:"specQualityScore" yaml:"spec_quality_score"`
	FilesTouched     []QualityMetricVariation `json:"filesTouched" yaml:"files_touched"`
	LinesChanged     []QualityMetricVariation `json:"linesChanged" yaml:"lines_changed"`
}

type QualityMetrics

type QualityMetrics struct {
	// Basic session counts
	TurnCount            *int            `json:"turnCount,omitempty"`
	SubagentCount        *int            `json:"subagentCount,omitempty"`
	TotalTokens          *int            `json:"totalTokens,omitempty"`
	InputTokens          *int            `json:"inputTokens,omitempty"`
	OutputTokens         *int            `json:"outputTokens,omitempty"`
	ToolCalls            *int            `json:"toolCalls,omitempty"`
	TitleGenerated       *string         `json:"titleGenerated,omitempty"`
	Outcome              *SessionOutcome `json:"outcome,omitempty"`
	FilesTouched         *int            `json:"filesTouched,omitempty"`
	LinesChanged         *int            `json:"linesChanged,omitempty"`
	RetryLoops           *int            `json:"retryLoops,omitempty"`
	RetryTokensWasted    *int            `json:"retryTokensWasted,omitempty"`
	WithinSessionReverts *int            `json:"withinSessionReverts,omitempty"`
	SignalDensity        *float64        `json:"signalDensity,omitempty"`
	SpecQualityScore     *float64        `json:"specQualityScore,omitempty"`
	ExplorationRatio     *float64        `json:"explorationRatio,omitempty"`
	ScopeBreadth         *int            `json:"scopeBreadth,omitempty"`
	DiscoveryTurns       *int            `json:"discoveryTurns,omitempty"`
	DurationMinutes      *float64        `json:"durationMinutes,omitempty"`
	// M-series advanced metrics (v2 computed)
	M2TokenOutcomeRatio     *float64 `json:"m2TokenOutcomeRatio,omitempty"`
	M3UniqueToolCount       *int     `json:"m3UniqueToolCount,omitempty"`
	M4ErrorRecoveryCount    *int     `json:"m4ErrorRecoveryCount,omitempty"`
	M4ConsecutiveErrorMax   *int     `json:"m4ConsecutiveErrorMax,omitempty"`
	M5ContextUtilizationPct *float64 `json:"m5ContextUtilizationPct,omitempty"`
	M5PeakContextTokens     *int     `json:"m5PeakContextTokens,omitempty"`
	M5AvgMessageTokens      *int     `json:"m5AvgMessageTokens,omitempty"`
	M6OutputSurvivalPct     *float64 `json:"m6OutputSurvivalPct,omitempty"`
	M6LinesSurvived         *int     `json:"m6LinesSurvived,omitempty"`
	M6LinesTotal            *int     `json:"m6LinesTotal,omitempty"`
	M7SpecWordCount         *int     `json:"m7SpecWordCount,omitempty"`
	M7SpecHasExamples       *bool    `json:"m7SpecHasExamples,omitempty"`
	M7SpecHasConstraints    *bool    `json:"m7SpecHasConstraints,omitempty"`
	// v3 cost analytics
	CostInputUSD      *float64 `json:"costInputUsd,omitempty"`
	CostOutputUSD     *float64 `json:"costOutputUsd,omitempty"`
	CostReasoningUSD  *float64 `json:"costReasoningUsd,omitempty"`
	CostCacheReadUSD  *float64 `json:"costCacheReadUsd,omitempty"`
	CostCacheWriteUSD *float64 `json:"costCacheWriteUsd,omitempty"`
	CostTotalUSD      *float64 `json:"costTotalUsd,omitempty"`
	CostModelID       *string  `json:"costModelId,omitempty"`
	// v3 scope classification
	Scope *string `json:"scope,omitempty"`
	// Compute metadata
	ComputedAt     *int64 `json:"computedAt,omitempty"`     // Unix millis
	ComputeVersion *int   `json:"computeVersion,omitempty"` // 0=v1 migrated, 1+=v2 computed
}

QualityMetrics holds session statistics and derived quality signals for a session. The type name is intentionally broad post-unification: it covers two distinct groups.

Group A — Basic session stats (TurnCount, SubagentCount, TotalTokens, InputTokens, OutputTokens, ToolCalls, TitleGenerated, Outcome, DurationMinutes): populated for all fully-ingested sessions; a nil value here indicates the session has not been fully ingested.

Group B — Derived quality signals (FilesTouched, LinesChanged, RetryLoops, M-series fields, SignalDensity, SpecQualityScore, ExplorationRatio, etc.): populated only when quality analysis has run. Nil = "not computed" — analysis may not have been performed yet.

All fields are pointers with omitempty so that serialisation omits fields that have not been populated, regardless of which group they belong to. JSON tags use camelCase to match the backend data contract (QualitySession) field names.

type QualityPayload

type QualityPayload struct {
	Sessions []QualitySession `json:"sessions"`
}

QualityPayload is the data sent on the quality WebSocket channel.

type QualityRatioVariation

type QualityRatioVariation struct {
	Name       string  `json:"name" yaml:"name"`
	InputRatio float64 `json:"inputRatio" yaml:"inputRatio"`
}

type QualitySession

type QualitySession struct {
	ID              string  `json:"id"`
	Date            string  `json:"date"` // "2006-01-02" format
	Project         string  `json:"project"`
	TotalTokens     int     `json:"totalTokens"`
	InputTokens     int     `json:"inputTokens"`
	OutputTokens    int     `json:"outputTokens"`
	TurnCount       int     `json:"turnCount"`
	ToolCalls       int     `json:"toolCalls"`
	DurationMinutes float64 `json:"durationMinutes"`
	// v2 fields -- zero-valued until implemented.
	Scope                string  `json:"scope"`
	Title                string  `json:"title"`
	Outcome              string  `json:"outcome"`
	FilesTouched         int     `json:"filesTouched"`
	LinesChanged         int     `json:"linesChanged"`
	RetryLoops           int     `json:"retryLoops"`
	RetryTokensWasted    int     `json:"retryTokensWasted"`
	WithinSessionReverts int     `json:"withinSessionReverts"`
	SignalDensity        float64 `json:"signalDensity"`
	SpecQualityScore     float64 `json:"specQualityScore"`
	ExplorationRatio     float64 `json:"explorationRatio"`
	ScopeBreadth         int     `json:"scopeBreadth"`
	DiscoveryTurns       int     `json:"discoveryTurns"`
	// EffectiveAnnotations are the non-superseded annotations for this session.
	// Clients derive display labels (e.g. humanLabel, agentLabel) by filtering
	// on typeId and annotatorKind — no pre-computed string fields needed.
	EffectiveAnnotations []AnnotationSummary `json:"effectiveAnnotations,omitempty"`
}

QualitySession is the analytics payload for the quality dashboard.

type QualitySessionFixture

type QualitySessionFixture struct {
	Name                 QualityFixtureName `json:"name" yaml:"name"`
	ID                   string             `json:"id" yaml:"id"`
	Date                 string             `json:"date" yaml:"date"`
	Project              string             `json:"project" yaml:"project"`
	Scope                string             `json:"scope" yaml:"scope"`
	Title                string             `json:"title" yaml:"title"`
	TotalTokens          int                `json:"totalTokens" yaml:"totalTokens"`
	InputTokens          int                `json:"inputTokens" yaml:"inputTokens"`
	OutputTokens         int                `json:"outputTokens" yaml:"outputTokens"`
	TurnCount            int                `json:"turnCount" yaml:"turnCount"`
	ToolCalls            int                `json:"toolCalls" yaml:"toolCalls"`
	Outcome              string             `json:"outcome" yaml:"outcome"`
	FilesTouched         int                `json:"filesTouched" yaml:"filesTouched"`
	LinesChanged         int                `json:"linesChanged" yaml:"linesChanged"`
	DurationMinutes      float64            `json:"durationMinutes" yaml:"durationMinutes"`
	RetryLoops           int                `json:"retryLoops" yaml:"retryLoops"`
	RetryTokensWasted    int                `json:"retryTokensWasted" yaml:"retryTokensWasted"`
	WithinSessionReverts int                `json:"withinSessionReverts" yaml:"withinSessionReverts"`
	SignalDensity        float64            `json:"signalDensity" yaml:"signalDensity"`
	SpecQualityScore     float64            `json:"specQualityScore" yaml:"specQualityScore"`
	ExplorationRatio     float64            `json:"explorationRatio" yaml:"explorationRatio"`
	ScopeBreadth         int                `json:"scopeBreadth" yaml:"scopeBreadth"`
	DiscoveryTurns       int                `json:"discoveryTurns" yaml:"discoveryTurns"`
}

QualitySessionFixture is one named quality-session fixture row.

func (QualitySessionFixture) ToQualitySession

func (f QualitySessionFixture) ToQualitySession() QualitySession

ToQualitySession converts a named fixture row to the wire payload shape.

type QualityStringVariation

type QualityStringVariation struct {
	Value string `json:"value" yaml:"value"`
}

type QualityVariations

type QualityVariations struct {
	Outcomes    []QualityStringVariation `json:"outcomes" yaml:"outcomes"`
	Projects    []QualityStringVariation `json:"projects" yaml:"projects"`
	Scopes      []QualityStringVariation `json:"scopes" yaml:"scopes"`
	TaskTitles  []QualityStringVariation `json:"taskTitles" yaml:"task_titles"`
	TokenRatios []QualityRatioVariation  `json:"tokenRatios" yaml:"token_ratios"`
	Metrics     QualityMetricVariations  `json:"metrics" yaml:"metrics"`
}

QualityVariations is the reusable combinatorial input catalog carried by the canonical quality fixture document.

type RawJSONPathPolicy added in v0.16.0

type RawJSONPathPolicy struct {
	MaxDocumentBytes       int
	MaxDocumentDepth       int
	OpaqueMetadataPointers []string
	CostPointers           []string
}

type ReadAttributionState

type ReadAttributionState string

ReadAttributionState reports whether per-file read attribution is recoverable for a node's editing sessions. It is the honesty axis that keeps a zero ReadCount from being misread as "known unread" when it is really "never recorded".

const (
	ReadAttributionComplete    ReadAttributionState = "complete"
	ReadAttributionPartial     ReadAttributionState = "partial"
	ReadAttributionUnavailable ReadAttributionState = "unavailable"
)

ReadAttributionState values.

func (ReadAttributionState) IsValid

func (s ReadAttributionState) IsValid() bool

IsValid reports whether s is one of the defined read attribution states.

func (ReadAttributionState) JSONSchema

func (ReadAttributionState) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (ReadAttributionState) String

func (s ReadAttributionState) String() string

String returns the wire representation of the read attribution state.

func (ReadAttributionState) Validate

func (s ReadAttributionState) Validate() error

Validate rejects values that cannot cross the read-attribution wire boundary.

type ReadStateGrade

type ReadStateGrade string

ReadStateGrade is the ordinal closed set of explicit read-state acts (the read-state grade design): none < viewed < reviewed < reviewed_in_detail. The ordering is registry data (the peasant-side system-origin TypeDefinition seed); this Go closed set is the sole typed copy on the wire, kept identical to the registry seed by ReadStateGradeRegistrySeedPermissibleValues.

const (
	ReadStateGradeNone             ReadStateGrade = "none"
	ReadStateGradeViewed           ReadStateGrade = "viewed"
	ReadStateGradeReviewed         ReadStateGrade = "reviewed"
	ReadStateGradeReviewedInDetail ReadStateGrade = "reviewed_in_detail"
)

ReadStateGrade values, in ascending ordinal order.

func (ReadStateGrade) IsValid

func (g ReadStateGrade) IsValid() bool

IsValid reports whether g is one of the defined read-state grades.

func (ReadStateGrade) JSONSchema

func (ReadStateGrade) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (ReadStateGrade) String

func (g ReadStateGrade) String() string

String returns the wire representation of the read-state grade.

func (ReadStateGrade) Validate

func (g ReadStateGrade) Validate() error

Validate rejects values that cannot cross the read-state-grade wire boundary.

type RecordedCostAmount added in v0.16.0

type RecordedCostAmount string

type RecordedCostDetail added in v0.16.0

type RecordedCostDetail struct {
	Input      *RecordedCostAmount `json:"input,omitempty"`
	Output     *RecordedCostAmount `json:"output,omitempty"`
	CacheRead  *RecordedCostAmount `json:"cacheRead,omitempty"`
	CacheWrite *RecordedCostAmount `json:"cacheWrite,omitempty"`
	Total      *RecordedCostAmount `json:"total,omitempty"`
	Source     string              `json:"source"`
}

type RedactionExample

type RedactionExample struct {
	// Name is the stable case key (snake_case). The web codegen joins its
	// presentation side-table (UI context snippets) to a case by this Name.
	Name string `yaml:"name"`
	// RuleID is the pkg/redact rule that fires on OriginalText (e.g. "github_pat").
	RuleID string `yaml:"ruleId"`
	// Category is the ENGINE category vocabulary: "secrets" | "pii" | "paths" |
	// "project". This is the ONE canonical category vocabulary; the web display
	// enum (CREDENTIAL|PII|PATH|INTERNAL) is a derived, audited projection.
	Category string `yaml:"category"`
	// Level is the minimum redaction level at which RuleID fires.
	Level RedactionFixtureLevel `yaml:"level"`
	// OriginalText is a realistic, public-safe secret FORMAT (non-functional
	// example value) that the engine genuinely detects.
	OriginalText string `yaml:"originalText"`
	// RedactedReplacement is the engine-APPLIED output, stored verbatim. For
	// back-reference rules this is the partially-redacted form
	// (e.g. "/Users/<USER>/Projects/internal-api"), not a bare label.
	RedactedReplacement string `yaml:"redactedReplacement"`
	// Confidence is a presentation-only 0-100 score shown in the mock UI.
	Confidence int `yaml:"confidence"`
	// LineNumber is a presentation-only source line shown in the mock UI.
	LineNumber int `yaml:"lineNumber"`
	// Description is a human-readable label shown in the mock UI.
	Description string `yaml:"description"`
}

RedactionExample is one entry in the redaction example corpus. It is the single source of truth for the redaction session-detail fixture: the leaf STORES this data and a format-only generator serialises it to testdata/session-detail/redactions.yaml. The leaf never recomputes RedactedReplacement — the redaction ENGINE lives only in peasant (pkg/redact), and a peasant-side behavioural conformance test binds RedactedReplacement to the real engine output (the no-drift guarantee).

func LoadRedactionExamples

func LoadRedactionExamples() ([]RedactionExample, error)

LoadRedactionExamples parses RedactionsYAML (the embedded, generated artifact) into typed cases. Consumers (peasant conformance test, web codegen) bind to the PUBLISHED bytes via this loader rather than the in-memory RedactionExamples slice, so they validate exactly what ships; the leaf freshness gate keeps the two in lockstep.

type RedactionFixtureLevel

type RedactionFixtureLevel string

RedactionFixtureLevel is the redaction level at which a fixture case's rule fires. The string values are byte-identical to peasant pkg/redact's RedactionLevel ("minimal"/"standard"/"maximum") so the peasant conformance test can construct a redactor at the exact firing level via redact.RedactionLevel(string(level)) with no translation table.

Default firing semantics are category-based, but the engine may give an individual rule a stricter minimum:

  • secrets, paths -> fire at Minimal and above (unconditional)
  • pii, project -> normally fire at Standard and above
  • selected project rules may require Maximum

The fixture stores the MINIMUM level at which each case's rule fires so the conformance test exercises the narrowest level that still triggers the rule (avoids entropy/AST over-redaction that only Maximum adds).

const (
	// RedactionLevelMinimal redacts only secrets and paths.
	RedactionLevelMinimal RedactionFixtureLevel = "minimal"
	// RedactionLevelStandard adds PII and most project-identity redaction.
	RedactionLevelStandard RedactionFixtureLevel = "standard"
	// RedactionLevelMaximum adds stricter project rules, AST anonymization, and entropy detection.
	RedactionLevelMaximum RedactionFixtureLevel = "maximum"
)

func (RedactionFixtureLevel) IsValid

func (l RedactionFixtureLevel) IsValid() bool

IsValid reports whether l is one of the three known levels.

func (RedactionFixtureLevel) String

func (l RedactionFixtureLevel) String() string

String returns the wire form of the level.

type RedactionInfo

type RedactionInfo struct {
	Applied             bool   `json:"applied"`
	Level               string `json:"level,omitempty"`                  // redaction level used (validate with redact.RedactionLevel)
	RuleSetVersion      string `json:"rule_set_version,omitempty"`       // rule set version that produced this redaction (e.g. "1.1.0")
	RedactedAtMs        *int64 `json:"redacted_at_ms,omitempty"`         // unix ms when redacted
	ContentHashAtRedact string `json:"content_hash_at_redact,omitempty"` // content hash snapshot at redaction time
}

RedactionInfo tracks whether and when redaction was applied to a session's transcript. Level is stored as a string because this schema module is a public contract module that must not import internal packages. Callers should validate using redact.RedactionLevel(level).IsValid().

func (RedactionInfo) IsCurrent

func (r RedactionInfo) IsCurrent(currentContentHash string) bool

IsCurrent returns true if the redaction matches the current content.

func (RedactionInfo) IsRaw

func (r RedactionInfo) IsRaw() bool

IsRaw returns true if no redaction has been applied.

func (RedactionInfo) IsStale

func (r RedactionInfo) IsStale(currentContentHash string) bool

IsStale returns true if the content has changed since redaction was applied.

type RefCase

type RefCase struct {
	// Name is a stable, human-readable case identifier (used as the t.Run name).
	Name string
	// Input is the raw string fed to ParseTranscriptRef.
	Input string
	// WantID is the expected canonical (lowercase) TranscriptID string for a
	// PARSING case; empty for a reject case.
	WantID string
	// WantFromURL is the expected TranscriptRef.FromURL for a parsing case.
	WantFromURL bool
	// WantErr is true when ParseTranscriptRef is expected to return an error.
	WantErr bool
	// ErrContains is a substring the returned error must contain (reject cases).
	ErrContains string
}

RefCase is a single concrete ParseTranscriptRef test case, materialised from the axes/categories. It is what internal/pull/types_test.go ranges over.

type RefForm

type RefForm struct {
	Name     string `yaml:"name"`
	Template string `yaml:"template"`
	FromURL  bool   `yaml:"from_url"`
}

RefForm is one entry of the ref_forms axis: a templated reference shape plus the FromURL the parser is expected to report for it.

type RelationshipNavigationStatus added in v0.19.0

type RelationshipNavigationStatus string
const (
	RelationshipNavigationResolved         RelationshipNavigationStatus = "resolved"
	RelationshipNavigationGeneralLinkOnly  RelationshipNavigationStatus = "general_link_only"
	RelationshipNavigationKnownUnavailable RelationshipNavigationStatus = "known_unavailable"
	RelationshipNavigationInaccessible     RelationshipNavigationStatus = "inaccessible"
	RelationshipNavigationUnknown          RelationshipNavigationStatus = "unknown"
	RelationshipNavigationConflicting      RelationshipNavigationStatus = "conflicting"
)

func NewRelationshipNavigationStatus added in v0.19.0

func NewRelationshipNavigationStatus(raw string) (RelationshipNavigationStatus, error)

func (RelationshipNavigationStatus) IsValid added in v0.19.0

func (v RelationshipNavigationStatus) IsValid() bool

func (RelationshipNavigationStatus) JSONSchema added in v0.19.0

type RelationshipTargetState added in v0.19.0

type RelationshipTargetState string
const (
	RelationshipTargetKnown                            RelationshipTargetState = "target_known"
	RelationshipTargetKnownRetained                    RelationshipTargetState = "target_known_retained"
	RelationshipTargetExplicitNone                     RelationshipTargetState = "explicit_none"
	RelationshipTargetUnknown                          RelationshipTargetState = "unknown"
	RelationshipTargetConflictingCurrentNativeEvidence RelationshipTargetState = "conflicting_current_native_evidence"
)

func NewRelationshipTargetState added in v0.19.0

func NewRelationshipTargetState(raw string) (RelationshipTargetState, error)

func (RelationshipTargetState) IsValid added in v0.19.0

func (v RelationshipTargetState) IsValid() bool

func (RelationshipTargetState) JSONSchema added in v0.19.0

type RetainedUnknownRecord added in v0.24.0

type RetainedUnknownRecord struct {
	SourceRef   string `json:"sourceRef" minLength:"1"`
	RecordIndex int64  `json:"recordIndex" minimum:"0" maximum:"9007199254740991"`
	Position    int64  `json:"position" minimum:"0" maximum:"9007199254740991"`
	Pointer     string `json:"pointer" pattern:"^(?:/(?:[^~]|~[01])*)*$"`
	Namespace   string `json:"namespace" minLength:"1"`
	Kind        string `json:"kind" minLength:"1"`
	Payload     string `json:"payload" minLength:"1"`
}

RetainedUnknownRecord preserves an uninterpreted source record or block after ordinary producer redaction. Payload is complete JSON TEXT, not a parsed JSON value: this preserves numeric literals outside JavaScript's number domain. SourceRef identifies a source stream, never a filesystem path. RecordIndex counts every source record, including known records, starting at zero; it is assigned by traversal and does not depend on a native ordinal. Pointer is an RFC 6901 pointer within that record (empty for the whole record). Position is the zero-based traversal position of the record/block within the source stream. Namespace disambiguates native discriminators such as record and message.block. Neither Namespace nor Kind is a closed vocabulary.

type ReviewListPayload

type ReviewListPayload struct {
	ProjectHash   ProjectHash          `json:"projectHash"`
	RepoFound     bool                 `json:"repoFound"`
	DefaultBranch string               `json:"defaultBranch,omitempty"`
	Changes       []ChangeSummary      `json:"changes" required:"true" nullable:"false"`       // open first, then merged
	RecentCommits []CommitRef          `json:"recentCommits" required:"true" nullable:"false"` // default-branch, cap 200 (time strip)
	Sessions      []TimelineSessionRef `json:"sessions" required:"true" nullable:"false"`      // complete visible project timeline identities, including sessions not linked to displayed commits
	// RewrittenCommits lists the project's full session-era commit resolution
	// ledger. Only non-live rows render as ghosts; live rows remain valid history
	// entries. It is empty when the resolver found no relevant session-era rows.
	RewrittenCommits []RewrittenCommit `json:"rewrittenCommits" required:"true" nullable:"false"`
}

ReviewListPayload lists a project's changes, served by GET /api/v1/review/{projectHash}.

func NewReviewListPayload

func NewReviewListPayload(projectHash ProjectHash) *ReviewListPayload

NewReviewListPayload returns a ReviewListPayload with all slices initialized to empty (never-nil marshal guarantee).

func (ReviewListPayload) Validate

func (p ReviewListPayload) Validate() error

Validate checks the normalized timeline relationship and compatibility invariants. It does not infer candidate or temporal associations, and it validates each CommitRef's shape before checking timeline membership and rank-order rules.

type ReviewSuggestion

type ReviewSuggestion struct {
	Path            string `json:"path"`
	LastEngaged     string `json:"lastEngaged"`
	DaysSince       int    `json:"daysSince"`
	SuggestedPrompt string `json:"suggestedPrompt"`
}

ReviewSuggestion nudges the user to revisit a fading file.

type RewriteMethod

type RewriteMethod string

RewriteMethod names the mechanism the resolver used to map a ghost commit to its successor, in the order the resolver attempts them.

const (
	RewriteMethodHash            RewriteMethod = "hash"
	RewriteMethodPatchID         RewriteMethod = "patch_id"
	RewriteMethodAuthorIdentity  RewriteMethod = "author_identity"
	RewriteMethodMessageEmbedded RewriteMethod = "message_embedded"
	RewriteMethodTemporal        RewriteMethod = "temporal"
	RewriteMethodNone            RewriteMethod = "none"
)

RewriteMethod values.

func (RewriteMethod) IsValid

func (m RewriteMethod) IsValid() bool

IsValid reports whether m is one of the defined rewrite methods.

func (RewriteMethod) JSONSchema

func (RewriteMethod) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (RewriteMethod) String

func (m RewriteMethod) String() string

String returns the wire representation of the rewrite method.

func (RewriteMethod) Validate

func (m RewriteMethod) Validate() error

Validate rejects values that cannot cross the rewrite-method wire boundary.

type RewriteResolution

type RewriteResolution string

RewriteResolution classifies whether a ledger-observed commit hash is still live on the default branch, was rewritten to a resolvable successor, or could not be resolved.

const (
	RewriteResolutionLive       RewriteResolution = "live"
	RewriteResolutionRewritten  RewriteResolution = "rewritten"
	RewriteResolutionUnresolved RewriteResolution = "unresolved"
)

RewriteResolution values.

func (RewriteResolution) IsValid

func (r RewriteResolution) IsValid() bool

IsValid reports whether r is one of the defined rewrite resolutions.

func (RewriteResolution) JSONSchema

func (RewriteResolution) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (RewriteResolution) String

func (r RewriteResolution) String() string

String returns the wire representation of the rewrite resolution.

func (RewriteResolution) Validate

func (r RewriteResolution) Validate() error

Validate rejects values that cannot cross the rewrite-resolution wire boundary.

type RewrittenCommit

type RewrittenCommit struct {
	GhostHash string `json:"ghostHash" yaml:"ghostHash" required:"true"`
	// Subject and AuthorTimeMs are "" / nil when the ledger row never
	// recorded that metadata (degraded providers).
	Subject      string      `json:"subject" yaml:"subject"`
	AuthorTimeMs *int64      `json:"authorTimeMs,omitempty" yaml:"authorTimeMs,omitempty"`
	SessionIDs   []SessionID `json:"sessionIds" yaml:"sessionIds" required:"true" nullable:"false"`
	// Associations mirrors SessionIDs one-for-one in the same order. These are
	// the original session-era relationships and retain their IDs even when a
	// successor commit is displayed.
	Associations []SessionAssociation `json:"associations" yaml:"associations" required:"true" nullable:"false"`
	// SuccessorHash is nil when Resolution is unresolved; non-nil when
	// rewritten. It is never populated for Resolution=live (a live ledger
	// hash is not a ghost).
	SuccessorHash *string           `json:"successorHash,omitempty" yaml:"successorHash,omitempty"`
	Resolution    RewriteResolution `json:"resolution" yaml:"resolution" required:"true"`
	Method        RewriteMethod     `json:"method" yaml:"method" required:"true"`
	Confidence    Confidence        `json:"confidence" yaml:"confidence" required:"true"`
}

RewrittenCommit is one session-era commit resolution ledger row. The row may record a live commit, a rewritten ghost, or an unresolved ghost; only non-live rows render as ghosts in timeline views.

func (RewrittenCommit) Validate

func (r RewrittenCommit) Validate() error

Validate checks a single RewrittenCommit's own fields: the resolution and method enums are in-set, SessionIDs are present and non-empty, SuccessorHash presence matches Resolution, and Method==none iff Resolution==unresolved. It does not check cross-references to a payload's session table or commit set; callers with that context use validateRewrittenCommits.

type Role

type Role string

Role represents the sender of a message turn.

const (
	RoleUser      Role = "user"
	RoleAssistant Role = "assistant"
	RoleTool      Role = "tool"
	RoleSystem    Role = "system"
)

func (Role) IsValid

func (r Role) IsValid() bool

IsValid returns true if the role is one of the known variants.

func (Role) JSONSchema

func (Role) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (Role) String

func (r Role) String() string

type ScaleKind

type ScaleKind string

ScaleKind classifies the measurement level of an annotation value domain (Stevens 1946 levels of measurement, ISO 11179 Part 5).

  • nominal: categories without order (e.g. session scope: feature/bug/docs)
  • ordinal: ordered categories with no meaningful interval (e.g. approval: deny<approve)
  • continuous: numeric range with meaningful intervals (e.g. confidence 0.0–1.0)

Valid combinations with ValueDomainKind:

  • enumerated + nominal: OK (categories without order)
  • enumerated + ordinal: OK (ordered categories with permissible values list)
  • described + continuous: OK (range with JSON schema constraint spec)
  • described + nominal: OK (pattern-constrained categories)
  • described + ordinal: REJECTED (ordinal requires explicit ordering via permissible values)
  • enumerated + continuous: REJECTED (continuous ranges must be described, not enumerated)
const (
	ScaleNominal    ScaleKind = "nominal"
	ScaleOrdinal    ScaleKind = "ordinal"
	ScaleContinuous ScaleKind = "continuous"
)

func (ScaleKind) IsValid

func (k ScaleKind) IsValid() bool

IsValid returns true if the scale kind is one of the known variants.

func (ScaleKind) JSONSchema

func (ScaleKind) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (ScaleKind) String

func (k ScaleKind) String() string

type SchemaVersionResponse

type SchemaVersionResponse struct {
	AnnotationSchemaVersion string              `json:"annotationSchemaVersion"`
	SupportedTargetKinds    []string            `json:"supportedTargetKinds"`
	SupportedTypeIDs        []string            `json:"supportedTypeIds"`
	PushContractVersion     PushContractVersion `json:"pushContractVersion"`
	MinPushContractVersion  PushContractVersion `json:"minPushContractVersion"`
	PullContractVersion     PushContractVersion `json:"pullContractVersion,omitempty"`
	MinPullContractVersion  PushContractVersion `json:"minPullContractVersion,omitempty"`
	// ContentCapabilities advertises optional enriched-content contracts proven
	// safe through the server's publish, storage, migration, and serving paths.
	// Omitted and empty mean no capability; JSON null is outside the contract.
	// Readers use exact token membership, ignore unknown tokens, and never infer
	// SemVer ordering. Advertisements are deployment-specific: clients preflight
	// the destination immediately before remote upload and refuse locally when a
	// payload requirement is missing, without stripping evidence. A dry run may
	// perform only this local negotiation and must not upload remotely. Duplicate
	// server output is invalid, clients tolerate and deduplicate it, order has no
	// meaning, and canonical server serialization is lexicographically sorted.
	ContentCapabilities []ContentCapability `json:"contentCapabilities,omitempty"`
}

SchemaVersionResponse is returned by GET /api/v1/schema/version. It communicates which annotation schema AND which push CONTENT contract the village currently supports, so the CLI can preflight and version-negotiate.

PushContractVersion / MinPushContractVersion advertise the village's accept WINDOW [Min, Current] for the TranscriptContent push wire:

  • PushContractVersion is the CURRENT contract the village emits/prefers.
  • MinPushContractVersion is the PUSH-ACCEPTANCE FLOOR: the oldest contract the village will still accept on the publish path. A CLI ahead of Current downgrade-emits toward this window (never "upgrade the village").

TWO DISTINCT FLOORS: MinPushContractVersion is the push-acceptance floor (gates INCOMING uploads). It is deliberately SEPARATE from the village's display MIGRATE-ON-READ floor (how far back stored blobs can be normalized for rendering), which may reach FURTHER back than MinPushContractVersion — the village can still render a legacy stored blob it would no longer ACCEPT as a fresh push. The migrate-on-read floor lives village-side and is not advertised here; only the push-acceptance window is negotiated over the wire.

PullContractVersion / MinPullContractVersion advertise the village's PULL envelope WINDOW [Min, Current] (PullTranscriptInfo/PullListResponse/ PullAnnotation shapes, the /api/v1/pull/* endpoint semantics, ETag behaviour). This window is DISTINCT from the push window: it does NOT version the blob (the stored blob carries its own publish-time push contract version). Both fields are `omitempty` so an OLDER village that predates the pull surface emits the prior wire shape; the CLI treats an ABSENT advertisement as "village too old for pull" (actionable error), not as compatible.

func (*SchemaVersionResponse) UnmarshalJSON added in v0.19.0

func (r *SchemaVersionResponse) UnmarshalJSON(data []byte) error

type SearchPayload

type SearchPayload struct {
	Query   string         `json:"query"`
	Results []SearchResult `json:"results"`
}

SearchPayload is the result set for one query, served by GET /api/v1/search.

func NewSearchPayload

func NewSearchPayload(query string) *SearchPayload

NewSearchPayload returns a SearchPayload with Results initialized to empty (never-nil marshal guarantee).

type SearchResult

type SearchResult struct {
	SessionID   string      `json:"sessionId"`
	Project     string      `json:"project"`               // raw canonical_cwd (else hash); web formats for display
	ProjectHash ProjectHash `json:"projectHash,omitempty"` // for round-trips
	EntryIndex  int         `json:"entryIndex"`            // depth-0 turn index — deep-link coordinate
	Role        string      `json:"role"`                  // user | assistant | ... (display facet)
	Snippet     string      `json:"snippet"`               // FTS5 snippet() with [match] markers
	Score       float64     `json:"score"`                 // negated bm25: higher = more relevant (result order is authoritative)
}

SearchResult is one FTS5 hit: a single message entry, ranked by relevance, with a snippet for display and the coordinates to deep-link to it.

type ServerMessage

type ServerMessage struct {
	Type    MessageType    `json:"type"`
	Data    any            `json:"data,omitempty"`
	Message string         `json:"message,omitempty"` // for error type
	Version string         `json:"version,omitempty"` // for connected type
	Topic   ChannelTopic   `json:"topic,omitempty"`   // failed subscription topic for error type
	ID      string         `json:"id,omitempty"`      // failed topic identity, when applicable
	Axis    AnnotationAxis `json:"axis,omitempty"`    // failed annotation axis, when applicable
}

ServerMessage is a message sent from the server to the browser via WebSocket.

type SessionAssociation

type SessionAssociation struct {
	ID         AssociationID                    `json:"id" yaml:"id" required:"true"`
	SessionID  SessionID                        `json:"sessionId" yaml:"sessionId" required:"true"`
	Conclusion AssociationConclusion            `json:"conclusion" yaml:"conclusion" required:"true"`
	Confidence Confidence                       `json:"confidence" yaml:"confidence" required:"true"`
	Evidence   []AssociationEvidenceObservation `json:"evidence" yaml:"evidence" required:"true" nullable:"false"`
}

SessionAssociation keeps an authoritative session-to-commit relationship as a durable identity, producer conclusion, confidence, and ordered atomic evidence observations.

func (SessionAssociation) Validate

func (a SessionAssociation) Validate() error

Validate checks a single association's own fields are well-formed. It does not check cross-references to a payload's session table or its surrounding parent shape.

type SessionDetailPayload

type SessionDetailPayload struct {
	SchemaVersion        PushContractVersion `json:"schemaVersion,omitempty"`
	ID                   string              `json:"id"`
	Harness              Harness             `json:"harness"`
	StartTime            time.Time           `json:"startTime"`
	EndTime              time.Time           `json:"endTime"`
	DurationMins         float64             `json:"durationMins"`
	TotalTokens          int                 `json:"totalTokens"`
	TokensIn             int                 `json:"tokensIn"`
	TokensOut            int                 `json:"tokensOut"`
	TurnCount            int                 `json:"turnCount"`
	InputSubmissionCount *int64              `json:"inputSubmissionCount,omitempty" minimum:"0" maximum:"9007199254740991" nullable:"false"`
	ToolCallCount        int                 `json:"toolCallCount"`
	Turns                []TurnDetail        `json:"turns"`
	// Optional fields — populated when backend has the data.
	Source  string `json:"source,omitempty"`
	Status  string `json:"status,omitempty"`
	Project string `json:"project,omitempty"`
	// Model seeds sticky model resolution for the root assistant before the first
	// valid turn observation. It is the earliest valid root-assistant model in
	// canonical order when one is available, otherwise legacy stored metadata. It
	// is never the latest, most common, or final session model.
	Model string `json:"model,omitempty"`
	// ThinkingLevel seeds sticky level resolution for the root assistant before
	// the first valid turn observation: the earliest valid root-assistant
	// observation in source order when available, otherwise the stored session
	// seed; never latest, most common, or final. Raw rides the same rule.
	ThinkingLevel    ThinkingLevel    `json:"thinkingLevel,omitempty"`
	ThinkingLevelRaw ThinkingLevelRaw `json:"thinkingLevelRaw,omitempty"`
	// ThinkingLevelHistory records the in-session level changes observed after
	// the seed, in source order, with consecutive duplicates collapsed. The
	// first value stays in ThinkingLevel/ThinkingLevelRaw above; each entry here
	// carries the later canonical level and/or its exact native spelling.
	ThinkingLevelHistory []ThinkingLevelChange   `json:"thinkingLevelHistory,omitempty"`
	WorkingDirectory     string                  `json:"workingDirectory,omitempty"`
	GitBranch            string                  `json:"gitBranch,omitempty"`
	GitRemote            string                  `json:"gitRemote,omitempty"`
	ChildSessions        []ChildSessionRef       `json:"childSessions,omitempty"`
	ParentSessionID      *SessionID              `json:"parentSessionId,omitempty"`
	RootSessionID        *SessionID              `json:"rootSessionId,omitempty"`
	Purpose              SessionPurpose          `json:"purpose,omitempty"`
	Relationships        []SessionRelationship   `json:"relationships,omitempty"`
	EarlierHistory       []EarlierHistorySection `json:"earlierHistory,omitempty"`
	// Outcome is the heuristic resolution status of the session
	// (resolved/partial/failed), sourced from session_metrics.outcome. Empty
	// when the session has no computed outcome. The metadata columns expose no
	// per-signal reason, so no reason field accompanies it yet.
	Outcome SessionOutcome `json:"outcome,omitempty"`
	// SessionOrigin is the producer's declaration of who drove this session.
	// Absent when the producer expressed no opinion; see SessionOrigin for the
	// rule a consumer applies to an absent or "unknown" value.
	SessionOrigin SessionOrigin `json:"sessionOrigin,omitempty"`
	// Scorecard carries the per-session quality signals used by the "How this
	// session went" self-assessment card. Nil when the session has no computed
	// metrics. Sourced from the same session_metrics row that backs QualitySession.
	Scorecard       *SessionScorecard          `json:"scorecard,omitempty"`
	NativeMetadata  []NativeMetadataRecord     `json:"nativeMetadata,omitempty"`
	RetainedUnknown []RetainedUnknownRecord    `json:"retainedUnknown,omitempty" nullable:"false"`
	Diagnostics     *InterpretationDiagnostics `json:"diagnostics,omitempty" nullable:"false"`
}

SessionDetailPayload is the data sent on the session_detail WebSocket channel AND promoted to the versioned `peasant push` wire body inside a TranscriptContent envelope.

SchemaVersion is the EMBEDDED push-contract version. It is advisory: when this payload travels inside a TranscriptContent envelope the envelope's ContractVersion is authoritative (see TranscriptContent's conflict-winner note). The embedded copy keeps the payload self-describing when stored on its own. It is omitempty so the local WebSocket session_detail channel (which never sets it) does not gain a spurious "schemaVersion":"" field; the push builder sets it explicitly.

func DecodeSessionDetailPayloadRaw added in v0.16.0

func DecodeSessionDetailPayloadRaw(raw []byte) (SessionDetailPayload, error)

type SessionDetailReadPayload added in v0.19.0

type SessionDetailReadPayload struct {
	SessionDetailPayload
	RelationshipNavigation []SessionRelationshipNavigation `json:"relationshipNavigation,omitempty"`
}

SessionDetailReadPayload is the local read projection. Anonymous embedding keeps every durable detail field at the JSON root while adding authorized navigation metadata that is never part of published transcript content.

type SessionEntry

type SessionEntry struct {
	SessionID      SessionID          `json:"sessionId"`
	EntryIndex     int                `json:"entryIndex"`
	Harness        Harness            `json:"harness"`
	EntryType      EntryType          `json:"entryType"`
	Role           Role               `json:"role"`
	TimestampMs    *int64             `json:"timestampMs,omitempty"`
	ContentPreview *string            `json:"contentPreview,omitempty"` // max 500 chars
	TokensIn       *int               `json:"tokensIn,omitempty"`
	TokensOut      *int               `json:"tokensOut,omitempty"`
	HasToolUse     bool               `json:"hasToolUse"`
	ToolKind       *ToolCallKind      `json:"toolKind,omitempty"` // ACP-aligned tool classification
	ToolNamesCSV   *string            `json:"toolNamesCsv,omitempty"`
	HasThinking    bool               `json:"hasThinking"`
	IsError        bool               `json:"isError"`
	StopReason     *StopReason        `json:"stopReason,omitempty"` // ACP per-turn stop reason
	RawByteLength  *int               `json:"rawByteLength,omitempty"`
	ToolCallID     *string            `json:"toolCallId,omitempty"`    // MCP correlation (was toolUseId)
	EntryID        *string            `json:"entryId,omitempty"`       // Provider-native ID
	ParentEntryID  *string            `json:"parentEntryId,omitempty"` // Parent entry link
	Depth          int                `json:"depth"`                   // 0 = message, 1 = content part
	ParentIndex    *int               `json:"parentIndex,omitempty"`   // entryIndex of parent (nil for depth=0)
	ToolInput      *string            `json:"toolInput,omitempty"`     // tool_use input JSON
	ToolOutput     *string            `json:"toolOutput,omitempty"`    // tool_result output JSON
	Extra          *string            `json:"extra,omitempty"`         // JSON overflow for provider-specific data
	PartType       *string            `json:"partType,omitempty"`      // provider's original part type label (nil for depth=0)
	SourceEntryRef SourceEntryRef     `json:"sourceEntryRef,omitempty"`
	Provenance     *ContentProvenance `json:"provenance,omitempty"`
}

SessionEntry represents a single indexed entry within a session transcript. Defined for v2 content-layer use; NOT used in v1 PublishRequest wire format. Maps 1:1 to a row in the session_entries table. All optional fields use pointer types to distinguish absent from zero. JSON tags use camelCase aligned with ACP content model.

type SessionGraphEnumInput added in v0.19.0

type SessionGraphEnumInput struct {
	Enum    string   `yaml:"enum"`
	Members []string `yaml:"members"`
	Empty   string   `yaml:"empty"`
	Unknown string   `yaml:"unknown"`
}

type SessionGraphFixtureCorpus added in v0.19.0

type SessionGraphFixtureCorpus struct {
	TypeScriptConstraints struct {
		CountCarriers []string                  `yaml:"count_carriers"`
		StrictObjects map[string]map[string]any `yaml:"strict_objects"`
	} `yaml:"typescript_constraints"`
	Durable               DurableGraphFixtures                                                        `yaml:"durable"`
	Refs                  testcase.Corpus[SessionGraphRefInput, SessionGraphRefExpected]              `yaml:"refs"`
	Enums                 testcase.Corpus[SessionGraphEnumInput, struct{}]                            `yaml:"enums"`
	Relationships         testcase.Corpus[SessionRelationship, SessionGraphFixtureExpected]           `yaml:"relationships"`
	RelationshipSets      testcase.Corpus[SessionRelationshipsInput, SessionGraphFixtureExpected]     `yaml:"relationship_sets"`
	Provenance            testcase.Corpus[ContentProvenance, SessionGraphFixtureExpected]             `yaml:"provenance"`
	Navigation            testcase.Corpus[SessionRelationshipNavigation, SessionGraphFixtureExpected] `yaml:"navigation"`
	HelperGroups          testcase.Corpus[HelperGroupSummary, SessionGraphFixtureExpected]            `yaml:"helper_groups"`
	HelperContexts        testcase.Corpus[HelperContextSummary, SessionGraphFixtureExpected]          `yaml:"helper_contexts"`
	EarlierHistory        testcase.Corpus[EarlierHistorySection, SessionGraphFixtureExpected]         `yaml:"earlier_history"`
	RawRelationships      testcase.Corpus[SessionGraphRawInput, SessionGraphRawExpected]              `yaml:"raw_relationships"`
	RawNavigation         testcase.Corpus[SessionGraphRawInput, SessionGraphRawExpected]              `yaml:"raw_navigation"`
	Recursive             testcase.Corpus[SessionGraphRawInput, SessionGraphFixtureExpected]          `yaml:"recursive"`
	RawDurable            testcase.Corpus[SessionGraphRawInput, SessionGraphFixtureExpected]          `yaml:"raw_durable"`
	NativeLimits          testcase.Corpus[NativeLimitInput, SessionGraphFixtureExpected]              `yaml:"native_limits"`
	AuthoritativeRaw      testcase.Corpus[SessionGraphRawInput, SessionGraphFixtureExpected]          `yaml:"authoritative_raw"`
	RecursiveRequired     []string                                                                    `yaml:"recursive_required_names"`
	RawDurableRequired    []string                                                                    `yaml:"raw_durable_required_names"`
	NativeLimitRequired   []string                                                                    `yaml:"native_limit_required_names"`
	AuthoritativeRequired []string                                                                    `yaml:"authoritative_required_names"`
}

func LoadSessionGraphFixtures added in v0.19.0

func LoadSessionGraphFixtures() (SessionGraphFixtureCorpus, error)

type SessionGraphFixtureExpected added in v0.19.0

type SessionGraphFixtureExpected struct {
	ErrorContains string `yaml:"error_contains,omitempty"`
}

type SessionGraphRawExpected added in v0.19.0

type SessionGraphRawExpected struct {
	RawJSON       string `yaml:"rawJson,omitempty"`
	ErrorContains string `yaml:"error_contains,omitempty"`
}

type SessionGraphRawInput added in v0.19.0

type SessionGraphRawInput struct {
	RawJSON string `yaml:"rawJson"`
}

type SessionGraphRefExpected added in v0.19.0

type SessionGraphRefExpected struct {
	ValueBase64   string `yaml:"valueBase64,omitempty"`
	ErrorContains string `yaml:"errorContains,omitempty"`
}

type SessionGraphRefInput added in v0.19.0

type SessionGraphRefInput struct {
	Alias       string `yaml:"alias"`
	BytesBase64 string `yaml:"bytesBase64"`
}

type SessionID

type SessionID string

SessionID is a validated session identifier from a source provider. Accepted formats:

  • UUID: "99d59925-36bc-424c-a789-8be54d9702ba"
  • Claude subagent: "agent-a3aee4f"
  • ACP session: "sess_3cd91f52effeXd3QAJ54jOyzv5" (ACP sess_ prefix)
  • OpenCode session: "ses_3cd91f52effeXd3QAJ54jOyzv5"
  • OpenCode message: "msg_001abc"
  • Strike timestamped: "20260728T123456.123456789Z-ABCDEFGHIJKLMNOPQRST234567"
  • Strike bare: "ABCDEFGHIJKLMNOPQRST234567"

func NewSessionID

func NewSessionID(raw string) (SessionID, error)

NewSessionID validates and constructs a SessionID.

func (SessionID) JSONSchema

func (SessionID) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (SessionID) String

func (s SessionID) String() string

type SessionIdentity

type SessionIdentity struct {
	SessionID       SessionID  `json:"sessionId"`
	ParentSessionID *SessionID `json:"parentUuid,omitempty"`
	SchemaVersion   int        `json:"schemaVersion"`
}

SessionIdentity holds the identification fields for a session. JSON tags use camelCase to match CLI UnifiedMetadata wire format.

type SessionInsight

type SessionInsight struct {
	Kind       InsightKind       `json:"kind" yaml:"kind" required:"true"`
	Provenance InsightProvenance `json:"provenance" yaml:"provenance" required:"true"`
	Confidence Confidence        `json:"confidence" yaml:"confidence" required:"true"`
	Title      string            `json:"title" yaml:"title" required:"true"`
	Summary    string            `json:"summary,omitempty" yaml:"summary,omitempty"`
	// Subjects names the node ids / file paths the insight is about.
	Subjects []string `json:"subjects" yaml:"subjects" required:"true" nullable:"false"`
	// Evidence is the traceability spine: every mechanical insight carries
	// at least one item.
	Evidence []InsightEvidence `json:"evidence" yaml:"evidence" required:"true" nullable:"false"`
	// Classification MUST be nil under the current contract (see Validate).
	// The field is reserved until its per-field taxonomy sets are defined.
	Classification *InsightClassification `json:"classification,omitempty" yaml:"classification,omitempty"`
}

SessionInsight is one insight: a (kind x provenance x confidence) envelope with evidence and subjects, additive alongside ChangeDetailPayload's existing Unusual/Frictions signals. Current mechanical producers leave Classification nil. A future contract may define closed classification sets without changing this envelope's shape.

func (SessionInsight) Validate

func (i SessionInsight) Validate() error

Validate checks the insight invariants: Kind/Provenance/Confidence are in-set, Subjects and Evidence are non-nil, every evidence item carries a non-empty session identity, every mechanical insight carries at least one evidence item, and Classification is nil. A future contract may replace the must-be-nil rule with per-field closed sets without changing the shape.

type SessionListItemKind added in v0.19.0

type SessionListItemKind string
const (
	SessionListItemTranscript       SessionListItemKind = "transcript"
	SessionListItemContextContainer SessionListItemKind = "context_container"
)

func NewSessionListItemKind added in v0.19.0

func NewSessionListItemKind(raw string) (SessionListItemKind, error)

func (SessionListItemKind) IsValid added in v0.19.0

func (v SessionListItemKind) IsValid() bool

func (SessionListItemKind) JSONSchema added in v0.19.0

func (SessionListItemKind) JSONSchema() (jsonschema.Schema, error)

type SessionOrigin added in v0.1.2

type SessionOrigin string

SessionOrigin is who drove a recorded session, as declared by the producer that recorded it.

CONTRACT RULE, binding on every consumer:

  • "user" and "agent" are decisions. A consumer stores the declared value and does not re-derive it.
  • "unknown" is also a decision: the producer looked and could not tell. A consumer MUST fall back to whatever rule it would have applied had the field been absent. It MUST NOT store "unknown" in place of a judgement it is itself capable of making.
  • An ABSENT field means the producer expressed no opinion, typically a build older than this field. A consumer falls back the same way.

So "unknown" and absent produce identical behaviour. They stay distinct because they are different facts: one producer examined the session, the other never knew the question existed. Only the first is evidence; both instruct the consumer to decide for itself.

const (
	// SessionOriginUser: a person drove the session.
	SessionOriginUser SessionOrigin = "user"
	// SessionOriginAgent: a program started the session.
	SessionOriginAgent SessionOrigin = "agent"
	// SessionOriginUnknown: the producer examined the session and could not
	// establish who drove it. It instructs the consumer to apply its own rule.
	SessionOriginUnknown SessionOrigin = "unknown"
)

func (SessionOrigin) IsValid added in v0.1.2

func (o SessionOrigin) IsValid() bool

IsValid reports whether o is a value this contract accepts on the wire. It accepts the empty string: an absent declaration is valid and means the producer expressed no opinion.

func (SessionOrigin) JSONSchema added in v0.1.2

func (SessionOrigin) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer. The published enum is the declared menu only; the empty string is the absence of the field, which omitempty already expresses, so it is not a menu member.

func (SessionOrigin) String added in v0.1.2

func (o SessionOrigin) String() string

type SessionOriginBehaviour added in v0.1.2

type SessionOriginBehaviour string

SessionOriginBehaviour is the closed set of contract behaviours the declared session-origin corpus must cover.

It exists because a row-count floor cannot protect a corpus: rows carrying a whole behaviour can be deleted with no assertion noticing, and a fixture row is not code, so no mutation of the production source can reach it. Naming the behaviours and asserting coverage per member makes the corpus itself guarded input.

const (
	// SessionOriginBehaviourMenuMemberAccepted covers a declared menu member.
	SessionOriginBehaviourMenuMemberAccepted SessionOriginBehaviour = "menu_member_accepted"
	// SessionOriginBehaviourAbsentDeclarationAccepted covers the empty string:
	// an absent declaration is valid and means the producer expressed no opinion.
	SessionOriginBehaviourAbsentDeclarationAccepted SessionOriginBehaviour = "absent_declaration_accepted"
	// SessionOriginBehaviourOutOfMenuRejected covers a token outside the menu,
	// which neither the Go predicate nor the published schema may accept.
	SessionOriginBehaviourOutOfMenuRejected SessionOriginBehaviour = "out_of_menu_rejected"
	// SessionOriginBehaviourDetailRoundTrip covers the field surviving a JSON
	// round trip on the session detail payload.
	SessionOriginBehaviourDetailRoundTrip SessionOriginBehaviour = "detail_round_trip"
	// SessionOriginBehaviourSummaryRoundTrip covers the same on the session
	// summary, which carries the field independently of the detail payload.
	SessionOriginBehaviourSummaryRoundTrip SessionOriginBehaviour = "summary_round_trip"
	// SessionOriginBehaviourAbsentFieldOmitted covers omitempty: an undeclared
	// origin must not appear on the wire as an empty string, because a consumer
	// would then have to treat "" as a fourth token.
	SessionOriginBehaviourAbsentFieldOmitted SessionOriginBehaviour = "absent_field_omitted"
	// SessionOriginBehaviourPublishedSchemaRefusal covers the published Types
	// component refusing an out-of-menu token, so a non-Go consumer inherits the
	// same closed set.
	SessionOriginBehaviourPublishedSchemaRefusal SessionOriginBehaviour = "published_schema_refusal"
)

func (SessionOriginBehaviour) IsValid added in v0.1.2

func (b SessionOriginBehaviour) IsValid() bool

IsValid reports whether b is a member of the closed behaviour set.

func (SessionOriginBehaviour) String added in v0.1.2

func (b SessionOriginBehaviour) String() string

type SessionOriginFixtures added in v0.1.2

type SessionOriginFixtures struct {
	// RequiredBehaviours is the closed set, declared in the corpus itself so a
	// reader of the fixture sees the coverage contract without reading Go. The
	// loader compares it to AllSessionOriginBehaviours by membership.
	RequiredBehaviours []SessionOriginBehaviour `yaml:"required_behaviours"`
	// RequiredMenu is the declared menu the validity arm must exercise in full.
	// The loader compares it to AllSessionOrigins by membership, so widening the
	// enum without adding a row fails here.
	// ByIDOperation is the declared shape of the by-id session-summaries
	// operation, the link-resolution surface a hidden session still reaches.
	ByIDOperation SessionSummariesByIDContract                                                    `yaml:"by_id_operation"`
	RequiredMenu  []SessionOrigin                                                                 `yaml:"required_menu"`
	Validities    testcase.Corpus[string, SessionOriginValidityExpectation]                       `yaml:"validities"`
	RoundTrips    testcase.Corpus[SessionOriginRoundTripInput, SessionOriginRoundTripExpectation] `yaml:"round_trips"`
	SchemaProbes  testcase.Corpus[SessionOriginSchemaProbe, SessionOriginSchemaExpectation]       `yaml:"schema_probes"`
}

SessionOriginFixtures is the segmented declared-session-origin corpus: one named arm per behaviour family. The arms are heterogeneous on purpose. The predicate arm works on raw tokens, the round-trip arm on encoded payloads, and the schema arm on the generated document, so a single input type would have to be a union that hides which behaviour a row actually exercises.

func LoadSessionOriginFixtures added in v0.1.2

func LoadSessionOriginFixtures() (*SessionOriginFixtures, error)

LoadSessionOriginFixtures parses the corpus and boundary-validates it. It rejects unknown fields, trailing documents, a case missing its classification, provenance or mutation metadata, a verdict inconsistent with its classification, a refusal naming no expected error fragment, and any declared menu or behaviour the Go closed sets do not carry.

type SessionOriginPayloadKind added in v0.1.2

type SessionOriginPayloadKind string

SessionOriginPayloadKind names which payload a round-trip row exercises. It is a closed set because the two payloads carry the field independently: a row that could name an unimplemented payload would assert nothing.

const (
	// SessionOriginPayloadDetail is SessionDetailPayload.
	SessionOriginPayloadDetail SessionOriginPayloadKind = "session_detail"
	// SessionOriginPayloadSummary is SessionSummary.
	SessionOriginPayloadSummary SessionOriginPayloadKind = "session_summary"
)

func (SessionOriginPayloadKind) IsValid added in v0.1.2

func (k SessionOriginPayloadKind) IsValid() bool

IsValid reports whether k is a member of the closed payload set.

func (SessionOriginPayloadKind) String added in v0.1.2

func (k SessionOriginPayloadKind) String() string

type SessionOriginRoundTripExpectation added in v0.1.2

type SessionOriginRoundTripExpectation struct {
	FieldPresent bool                   `json:"fieldPresent" yaml:"field_present"`
	EncodedJSON  string                 `json:"encodedJson" yaml:"encoded_json"`
	Decoded      string                 `json:"decoded" yaml:"decoded"`
	Behaviour    SessionOriginBehaviour `json:"behaviour" yaml:"behaviour"`
}

SessionOriginRoundTripExpectation says what the encoded payload must look like and what must survive decoding it again. FieldPresent false asserts the omitempty behaviour: the key is absent, not present and empty.

type SessionOriginRoundTripInput added in v0.1.2

type SessionOriginRoundTripInput struct {
	Payload SessionOriginPayloadKind `json:"payload" yaml:"payload"`
	Origin  string                   `json:"origin" yaml:"origin"`
}

SessionOriginRoundTripInput names a payload and the origin token to encode into it.

type SessionOriginSchemaExpectation added in v0.1.2

type SessionOriginSchemaExpectation struct {
	Accepted      bool                   `json:"accepted" yaml:"accepted"`
	ErrorContains string                 `json:"errorContains" yaml:"error_contains"`
	Behaviour     SessionOriginBehaviour `json:"behaviour" yaml:"behaviour"`
}

SessionOriginSchemaExpectation is the published schema's verdict on a probe.

ErrorContains is authored in the corpus as an INDEPENDENT literal and is never taken from a production message constant: a needle derived from the code under test cannot detect that code changing.

type SessionOriginSchemaProbe added in v0.1.2

type SessionOriginSchemaProbe struct {
	Origin string `json:"origin" yaml:"origin"`
}

SessionOriginSchemaProbe is one token offered to the published SessionOrigin component from the generated Types document.

type SessionOriginValidityExpectation added in v0.1.2

type SessionOriginValidityExpectation struct {
	Valid     bool                   `json:"valid" yaml:"valid"`
	Behaviour SessionOriginBehaviour `json:"behaviour" yaml:"behaviour"`
}

SessionOriginValidityExpectation is the verdict SessionOrigin.IsValid must return for a raw token, plus the behaviour the row contributes.

type SessionOutcome

type SessionOutcome string

SessionOutcome represents the resolution status of a session.

const (
	OutcomeResolved SessionOutcome = "resolved"
	OutcomePartial  SessionOutcome = "partial"
	OutcomeFailed   SessionOutcome = "failed"
)

func (SessionOutcome) IsValid

func (o SessionOutcome) IsValid() bool

IsValid returns true if the outcome is one of the known variants.

func (SessionOutcome) JSONSchema

func (SessionOutcome) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (SessionOutcome) String

func (o SessionOutcome) String() string

type SessionPurpose added in v0.19.0

type SessionPurpose string
const (
	SessionPurposeInteraction   SessionPurpose = "interaction"
	SessionPurposeDelegatedWork SessionPurpose = "delegated_work"
	SessionPurposeHelperReview  SessionPurpose = "helper_review"
	SessionPurposeUnknown       SessionPurpose = "unknown"
)

func NewSessionPurpose added in v0.19.0

func NewSessionPurpose(raw string) (SessionPurpose, error)

func (SessionPurpose) IsValid added in v0.19.0

func (v SessionPurpose) IsValid() bool

func (SessionPurpose) JSONSchema added in v0.19.0

func (SessionPurpose) JSONSchema() (jsonschema.Schema, error)

type SessionRelationship added in v0.19.0

type SessionRelationship struct {
	Kind          SessionRelationshipKind `json:"kind" yaml:"kind"`
	TargetState   RelationshipTargetState `json:"targetState" yaml:"targetState"`
	TargetLocalID *SessionID              `json:"targetLocalId,omitempty" yaml:"targetLocalId"`
	Evidence      EvidenceKind            `json:"evidence" yaml:"evidence"`
	Anchor        *PublicSourceAnchor     `json:"anchor,omitempty" yaml:"anchor"`
}

func ValidateRawRelationshipFixture added in v0.19.0

func ValidateRawRelationshipFixture(i SessionGraphRawInput) (SessionRelationship, error)

func (SessionRelationship) Validate added in v0.19.0

func (r SessionRelationship) Validate() error

type SessionRelationshipKind added in v0.19.0

type SessionRelationshipKind string
const (
	SessionRelationshipStartedBy   SessionRelationshipKind = "started_by"
	SessionRelationshipContextFrom SessionRelationshipKind = "context_from"
)

func NewSessionRelationshipKind added in v0.19.0

func NewSessionRelationshipKind(raw string) (SessionRelationshipKind, error)

func (SessionRelationshipKind) IsValid added in v0.19.0

func (v SessionRelationshipKind) IsValid() bool

func (SessionRelationshipKind) JSONSchema added in v0.19.0

type SessionRelationshipNavigation added in v0.19.0

type SessionRelationshipNavigation struct {
	Kind         SessionRelationshipKind      `json:"kind" yaml:"kind"`
	Status       RelationshipNavigationStatus `json:"status" yaml:"status"`
	LocalID      *SessionID                   `json:"localId,omitempty" yaml:"localId"`
	TranscriptID *TranscriptID                `json:"transcriptId,omitempty" yaml:"transcriptId"`
	Anchor       *PublicSourceAnchor          `json:"anchor,omitempty" yaml:"anchor"`
}

func ValidateRawNavigationFixture added in v0.19.0

func ValidateRawNavigationFixture(i SessionGraphRawInput) (SessionRelationshipNavigation, string, error)

func (SessionRelationshipNavigation) Validate added in v0.19.0

func (n SessionRelationshipNavigation) Validate() error

type SessionRelationshipsInput added in v0.19.0

type SessionRelationshipsInput struct {
	Relationships []SessionRelationship `yaml:"relationships"`
}

type SessionScorecard

type SessionScorecard struct {
	// Token efficiency inputs.
	M2TokenOutcomeRatio     *float64 `json:"m2TokenOutcomeRatio,omitempty"`
	M5ContextUtilizationPct *float64 `json:"m5ContextUtilizationPct,omitempty"`
	M6OutputSurvivalPct     *float64 `json:"m6OutputSurvivalPct,omitempty"`
	RetryTokensWasted       *int     `json:"retryTokensWasted,omitempty"`
	TotalTokens             *int     `json:"totalTokens,omitempty"`
	CostTotalUSD            *float64 `json:"costTotalUsd,omitempty"`
	// Prompt quality inputs.
	SpecQualityScore     *float64 `json:"specQualityScore,omitempty"`
	SignalDensity        *float64 `json:"signalDensity,omitempty"`
	M7SpecHasExamples    *bool    `json:"m7SpecHasExamples,omitempty"`
	M7SpecHasConstraints *bool    `json:"m7SpecHasConstraints,omitempty"`
	// Loop efficiency inputs.
	M4ConsecutiveErrorMax *int `json:"m4ConsecutiveErrorMax,omitempty"`
	WithinSessionReverts  *int `json:"withinSessionReverts,omitempty"`
	// Outcome echoes the session outcome so the card can apply the
	// "failed outcome with above-median cost" token-efficiency trigger.
	Outcome SessionOutcome `json:"outcome,omitempty"`
}

SessionScorecard holds the deterministic per-session quality signals needed by the Highlights self-assessment card. It is a flat projection of the session_metrics fields the three axis cards (token efficiency, prompt quality, loop efficiency) consume. Fields are pointers so the client can distinguish "not computed" (nil) from a real zero value when applying threshold bands.

type SessionStats

type SessionStats struct {
	TurnCount            int    `json:"turnCount"`
	InputSubmissionCount *int64 `json:"inputSubmissionCount,omitempty" minimum:"0" maximum:"9007199254740991" nullable:"false"`
	ToolCallCount        int    `json:"toolCallCount"`
	SubagentCount        int    `json:"subagentCount"`
	DurationMs           int64  `json:"durationMs"`
	TokensIn             int    `json:"tokensIn"`
	TokensOut            int    `json:"tokensOut"`
	// ACP-aligned token breakdown (optional — not all providers report these).
	ThoughtTokens     *int `json:"thoughtTokens,omitempty"`     // Reasoning/thinking tokens
	CachedReadTokens  *int `json:"cachedReadTokens,omitempty"`  // Prompt cache hits
	CachedWriteTokens *int `json:"cachedWriteTokens,omitempty"` // Prompt cache writes
}

SessionStats holds aggregate metrics extracted from transcript data.

type SessionSummariesByIDAnchor added in v0.1.2

type SessionSummariesByIDAnchor string

SessionSummariesByIDAnchor names one clause the by-id session-summaries operation description must state. The description is prose, so a closed set cannot be derived from it; naming each required clause makes deleting one fail here instead of quietly weakening a stated contract.

const (
	// SessionSummariesByIDAnchorResolvesLinks: the operation exists to resolve
	// links, which is why the two scopes below do not apply to it.
	SessionSummariesByIDAnchorResolvesLinks SessionSummariesByIDAnchor = "resolves_links"
	// SessionSummariesByIDAnchorNoOriginScope: origin scope is a discovery
	// boundary and must not reach a by-id resolution.
	SessionSummariesByIDAnchorNoOriginScope SessionSummariesByIDAnchor = "no_origin_scope"
	// SessionSummariesByIDAnchorNoSelectionScope: selection scope is the same
	// kind of boundary and is excluded for the same reason.
	SessionSummariesByIDAnchorNoSelectionScope SessionSummariesByIDAnchor = "no_selection_scope"
	// SessionSummariesByIDAnchorUnknownIDOmitted: an identifier that names no
	// local session is omitted rather than failing the whole batch.
	SessionSummariesByIDAnchorUnknownIDOmitted SessionSummariesByIDAnchor = "unknown_identifier_omitted"
)

func (SessionSummariesByIDAnchor) IsValid added in v0.1.2

func (a SessionSummariesByIDAnchor) IsValid() bool

IsValid reports whether a is a member of the closed anchor set.

func (SessionSummariesByIDAnchor) String added in v0.1.2

type SessionSummariesByIDContract added in v0.1.2

type SessionSummariesByIDContract struct {
	Path               string                                  `json:"path" yaml:"path"`
	Method             string                                  `json:"method" yaml:"method"`
	OperationID        string                                  `json:"operationId" yaml:"operation_id"`
	QueryParameter     string                                  `json:"queryParameter" yaml:"query_parameter"`
	ResponseStatus     string                                  `json:"responseStatus" yaml:"response_status"`
	MediaType          string                                  `json:"mediaType" yaml:"media_type"`
	ResponseRef        string                                  `json:"responseRef" yaml:"response_ref"`
	DescriptionAnchors []SessionSummariesByIDDescriptionAnchor `json:"descriptionAnchors" yaml:"description_anchors"`
}

SessionSummariesByIDContract is the declared shape of the by-id session-summaries operation in the Local API document.

type SessionSummariesByIDDescriptionAnchor added in v0.1.2

type SessionSummariesByIDDescriptionAnchor struct {
	Name SessionSummariesByIDAnchor `json:"name" yaml:"name"`
	Text string                     `json:"text" yaml:"text"`
}

SessionSummariesByIDDescriptionAnchor is one required clause: its closed-set name and the literal text the published description must contain.

type SessionSummary

type SessionSummary struct {
	ID                   string    `json:"id"`
	Harness              Harness   `json:"harness"`
	StartTime            time.Time `json:"startTime"`
	DurationMins         float64   `json:"durationMins"`
	TotalTokens          int       `json:"totalTokens"`
	TurnCount            int       `json:"turnCount"`
	InputSubmissionCount *int64    `json:"inputSubmissionCount,omitempty" minimum:"0" maximum:"9007199254740991" nullable:"false"`
	ToolCallCount        int       `json:"toolCallCount"`
	Project              string    `json:"project,omitempty"`
	// ProjectHash is the opaque project identifier (projects.project_hash).
	// The frontend resolves display name → hash from this field for the
	// Map/Review REST endpoints (contract §9.1).
	ProjectHash ProjectHash `json:"projectHash,omitempty"`
	Outcome     string      `json:"outcome,omitempty"`
	// ParentSessionID is the durable logical parent of a spawned child. It may
	// name a session this store does not hold. Absent for a root or a fork.
	ParentSessionID *string `json:"parentSessionId,omitempty"`
	// ParentUnresolved marks a known spawned child whose parent cannot be
	// named. It is never set together with ParentSessionID. A client keeps
	// such a row out of the top-level list and does not invent a parent.
	ParentUnresolved *bool                 `json:"parentUnresolved,omitempty" nullable:"false"`
	RootSessionID    *SessionID            `json:"rootSessionId,omitempty"`
	Purpose          SessionPurpose        `json:"purpose,omitempty"`
	Relationships    []SessionRelationship `json:"relationships,omitempty"`
	// SessionOrigin is the producer's declaration of who drove this session.
	// Absent when the producer expressed no opinion; see SessionOrigin for the
	// rule a consumer applies to an absent or "unknown" value.
	SessionOrigin SessionOrigin `json:"sessionOrigin,omitempty"`
	// Preview is the raw first user message of the session, sourced from the
	// already-redacted indexed transcript (session_entries.content_preview). It
	// is redaction-safe by construction. Empty when the session has no indexed
	// user entry. The web client formats it for display.
	Preview string `json:"preview,omitempty"`
}

SessionSummary is a session without turns, used in the sessions list.

type SessionsPayload

type SessionsPayload struct {
	Sessions []SessionSummary `json:"sessions"`
}

SessionsPayload is the data sent on the sessions WebSocket channel.

type ShutdownResponse

type ShutdownResponse struct {
	Status string `json:"status"`
}

ShutdownResponse is the JSON response for POST /api/v1/shutdown.

type SourceEntryRef added in v0.19.0

type SourceEntryRef string

func NewSourceEntryRef added in v0.19.0

func NewSourceEntryRef(raw string) (SourceEntryRef, error)

func (SourceEntryRef) JSONSchema added in v0.19.0

func (SourceEntryRef) JSONSchema() (jsonschema.Schema, error)

func (SourceEntryRef) Validate added in v0.19.0

func (v SourceEntryRef) Validate() error

type SourceFormat

type SourceFormat string

SourceFormat identifies the transcript file format.

const (
	SourceFormatJSONL SourceFormat = "jsonl" // Claude Code JSONL transcripts
	SourceFormatJSON  SourceFormat = "json"  // OpenCode JSON transcripts
)

func (SourceFormat) IsValid

func (f SourceFormat) IsValid() bool

IsValid returns true if the SourceFormat is one of the known variants.

func (SourceFormat) JSONSchema

func (SourceFormat) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (SourceFormat) String

func (f SourceFormat) String() string

type SourceInfo

type SourceInfo struct {
	FilePath string       `json:"filePath,omitempty"` // Original source transcript path
	Format   SourceFormat `json:"format"`             // "jsonl" or "json"
}

SourceInfo identifies the original transcript file and its format.

type StopReason

type StopReason string

StopReason represents why a session or turn ended. ACP per-turn stop reasons; content-layer type for future use.

const (
	StopReasonEndTurn         StopReason = "end_turn"
	StopReasonCancelled       StopReason = "cancelled"
	StopReasonMaxTokens       StopReason = "max_tokens"
	StopReasonMaxTurnRequests StopReason = "max_turn_requests"
	StopReasonRefusal         StopReason = "refusal"
)

func (StopReason) IsValid

func (r StopReason) IsValid() bool

IsValid returns true if the stop reason is one of the known variants.

func (StopReason) JSONSchema

func (StopReason) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (StopReason) String

func (r StopReason) String() string

type SubagentRef

type SubagentRef struct {
	SessionID  SessionID `json:"sessionId"`
	ParentUUID SessionID `json:"parentUuid"`
}

SubagentRef records a reference to a subagent session spawned during a parent session.

type SubmissionRef added in v0.19.0

type SubmissionRef string

func NewSubmissionRef added in v0.19.0

func NewSubmissionRef(raw string) (SubmissionRef, error)

func (SubmissionRef) JSONSchema added in v0.19.0

func (SubmissionRef) JSONSchema() (jsonschema.Schema, error)

func (SubmissionRef) Validate added in v0.19.0

func (v SubmissionRef) Validate() error

type SubscriptionValidationCase

type SubscriptionValidationCase struct {
	Name  string `yaml:"name"`
	Topic string `yaml:"topic"`
	Axis  string `yaml:"axis,omitempty"`
	ID    string `yaml:"id,omitempty"`
	Valid bool   `yaml:"valid"`
}

SubscriptionValidationCase is a test case for ValidateSubscription.

type SyncAuthResponse added in v0.25.0

type SyncAuthResponse struct {
	Authenticated bool `json:"authenticated"`
	// Username, VillageURL, and VillageConfigured are present only when
	// Authenticated is true.
	Username          string `json:"username,omitempty"`
	VillageURL        string `json:"villageUrl,omitempty"`
	VillageConfigured bool   `json:"villageConfigured,omitempty"`
}

SyncAuthResponse is the response of GET /api/v1/sync/auth: whether this computer holds a valid Village credential.

func (SyncAuthResponse) Validate added in v0.25.0

func (r SyncAuthResponse) Validate() error

Validate checks that a signed-out response names no account.

type SyncHoldReason added in v0.25.0

type SyncHoldReason string

SyncHoldReason says why a held session cannot be published yet.

const (
	// SyncHoldReasonMetricsMissing: the session has no computed metrics yet.
	SyncHoldReasonMetricsMissing SyncHoldReason = "metrics_missing"
	// SyncHoldReasonMetadataMissing: the session's publication metadata is not
	// ready, so the capture and the index do not agree yet.
	SyncHoldReasonMetadataMissing SyncHoldReason = "metadata_missing"
)

func (SyncHoldReason) IsValid added in v0.25.0

func (r SyncHoldReason) IsValid() bool

func (SyncHoldReason) JSONSchema added in v0.25.0

func (SyncHoldReason) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (SyncHoldReason) String added in v0.25.0

func (r SyncHoldReason) String() string

type SyncLoginResponse added in v0.25.0

type SyncLoginResponse struct {
	Status SyncLoginStatus `json:"status"`
}

SyncLoginResponse is the response of POST /api/v1/sync/login.

func (SyncLoginResponse) Validate added in v0.25.0

func (r SyncLoginResponse) Validate() error

Validate checks the sign-in result.

type SyncLoginStatus added in v0.25.0

type SyncLoginStatus string

SyncLoginStatus is the result of POST /api/v1/sync/login.

const (
	// SyncLoginPending: the browser sign-in started; poll /api/v1/sync/auth.
	SyncLoginPending SyncLoginStatus = "pending"
	// SyncLoginAlreadyAuthenticated: this computer is already signed in.
	SyncLoginAlreadyAuthenticated SyncLoginStatus = "already_authenticated"
)

func (SyncLoginStatus) IsValid added in v0.25.0

func (s SyncLoginStatus) IsValid() bool

func (SyncLoginStatus) JSONSchema added in v0.25.0

func (SyncLoginStatus) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (SyncLoginStatus) String added in v0.25.0

func (s SyncLoginStatus) String() string

type SyncLogoutResponse added in v0.25.0

type SyncLogoutResponse struct {
	Status SyncLogoutStatus `json:"status"`
}

SyncLogoutResponse is the response of POST /api/v1/sync/logout.

func (SyncLogoutResponse) Validate added in v0.25.0

func (r SyncLogoutResponse) Validate() error

Validate checks the sign-out result.

type SyncLogoutStatus added in v0.25.0

type SyncLogoutStatus string

SyncLogoutStatus is the result of POST /api/v1/sync/logout.

const (
	// SyncLogoutLoggedOut: the stored Village credential was removed.
	SyncLogoutLoggedOut SyncLogoutStatus = "logged_out"
	// SyncLogoutAlreadyLoggedOut: this computer held no Village credential.
	SyncLogoutAlreadyLoggedOut SyncLogoutStatus = "already_logged_out"
)

func (SyncLogoutStatus) IsValid added in v0.25.0

func (s SyncLogoutStatus) IsValid() bool

func (SyncLogoutStatus) JSONSchema added in v0.25.0

func (SyncLogoutStatus) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (SyncLogoutStatus) String added in v0.25.0

func (s SyncLogoutStatus) String() string

type SyncPushCollectives added in v0.25.0

type SyncPushCollectives struct {
	Add    []VillageUUID `json:"add,omitempty" nullable:"false" description:"Collectives to share the published transcripts with"`
	Remove []VillageUUID `json:"remove,omitempty" nullable:"false" description:"Collectives to take the published transcripts back from"`
}

SyncPushCollectives names the collectives one push adds and removes. Add shares each published transcript with the collective; remove takes it back. Collectives named in neither list keep their current access.

type SyncPushRequest added in v0.25.0

type SyncPushRequest struct {
	SessionIDs []string `json:"sessionIds" nullable:"false" minItems:"1" description:"Local sessions to publish or update"`
	// RedactionLevel is a request for a level. Omission lets the server resolve
	// its configured default; the server refuses a level it does not offer.
	RedactionLevel string               `json:"redactionLevel,omitempty" description:"Requested redaction level; omit to use the configured default"`
	Collectives    *SyncPushCollectives `json:"collectives,omitempty" nullable:"false" description:"Audience changes; omit to keep each transcript's current audience"`
}

SyncPushRequest is the body of POST /api/v1/sync/push. Publishing is collectives only: the request carries no visibility and no license, and the server applies no default license to a publish that names collectives.

func (SyncPushRequest) Validate added in v0.25.0

func (r SyncPushRequest) Validate() error

Validate checks the session list and that no collective is both added and removed.

type SyncPushResponse added in v0.25.0

type SyncPushResponse struct {
	New      int                     `json:"new" minimum:"0"`
	Updated  int                     `json:"updated" minimum:"0"`
	Skipped  int                     `json:"skipped" minimum:"0"`
	Errors   int                     `json:"errors" minimum:"0"`
	Sessions []SyncPushSessionResult `json:"sessions" nullable:"false"`
}

SyncPushResponse is the response of POST /api/v1/sync/push: the counts the push already returned plus one result per session. New, Updated, Skipped, and Errors count the sessions with that status; held sessions are not counted.

func (SyncPushResponse) Validate added in v0.25.0

func (r SyncPushResponse) Validate() error

Validate checks the counts and every session result.

type SyncPushSessionResult added in v0.25.0

type SyncPushSessionResult struct {
	SessionID string `json:"sessionId"`
	// Status is the session's outcome. It describes the content: new or
	// updated when Village accepted it, skipped when it was already current
	// (also when only collectives changed), held when it cannot be published
	// yet, and error when any step failed or the session failed before,
	// between, or after its steps ran, for example while recording Village's
	// receipt on this computer. The response counts tally sessions by this status.
	Status SyncPushSessionStatus `json:"status"`
	Error  string                `json:"error,omitempty"`
	Title  string                `json:"title,omitempty"`
	// TranscriptURL is the Village page of the session's transcript. Every
	// session whose content step succeeded carries it.
	TranscriptURL string `json:"transcriptUrl,omitempty"`
	// Steps lists every step the push planned for this session, in the order
	// it ran them. When present, the content step comes first: skipped when
	// the content was already current or the session is held.
	Steps []SyncPushStepResult `json:"steps,omitempty" nullable:"false"`
	// WaitingPullRequests are the caller's Village prompt requests that wait
	// for a transcript from this session's repository.
	WaitingPullRequests []VillagePromptRequest `json:"waitingPullRequests,omitempty" nullable:"false"`
}

SyncPushSessionResult is the result for one session in a push.

func (SyncPushSessionResult) Validate added in v0.25.0

func (r SyncPushSessionResult) Validate() error

Validate checks one session result, its steps, and how the status follows from them. Steps start with the content step. A failed step makes the session an error. New and updated sessions have a succeeded content step, and any session whose content Village accepted carries a transcript URL. Skipped and held sessions have a skipped content step, and a held session can only take a transcript back from collectives or skip a share. A step is not_attempted after an earlier step failed, or in an error session, which is how a failure between steps is reported. Whether a later step still runs after a failure is the producer's choice, so taking a collective back is never forced to wait on an unrelated failure.

type SyncPushSessionStatus added in v0.25.0

type SyncPushSessionStatus string

SyncPushSessionStatus is the outcome of one session in a push.

const (
	SyncPushSessionNew     SyncPushSessionStatus = "new"
	SyncPushSessionUpdated SyncPushSessionStatus = "updated"
	SyncPushSessionSkipped SyncPushSessionStatus = "skipped"
	SyncPushSessionError   SyncPushSessionStatus = "error"
	SyncPushSessionHeld    SyncPushSessionStatus = "held"
)

func (SyncPushSessionStatus) IsValid added in v0.25.0

func (s SyncPushSessionStatus) IsValid() bool

func (SyncPushSessionStatus) JSONSchema added in v0.25.0

func (SyncPushSessionStatus) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (SyncPushSessionStatus) String added in v0.25.0

func (s SyncPushSessionStatus) String() string

type SyncPushStep added in v0.25.0

type SyncPushStep string

SyncPushStep is one step a push runs for a session: the content step, then one step per collective added or removed.

const (
	// SyncPushStepContent sends the redacted transcript to Village.
	SyncPushStepContent SyncPushStep = "content"
	// SyncPushStepAddCollective shares the transcript with one collective.
	SyncPushStepAddCollective SyncPushStep = "add_collective"
	// SyncPushStepRemoveCollective takes the transcript back from one collective.
	SyncPushStepRemoveCollective SyncPushStep = "remove_collective"
)

func (SyncPushStep) IsValid added in v0.25.0

func (s SyncPushStep) IsValid() bool

func (SyncPushStep) JSONSchema added in v0.25.0

func (SyncPushStep) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (SyncPushStep) String added in v0.25.0

func (s SyncPushStep) String() string

type SyncPushStepOutcome added in v0.25.0

type SyncPushStepOutcome string

SyncPushStepOutcome is the result of one push step.

const (
	// SyncPushStepSucceeded: Village applied the step.
	SyncPushStepSucceeded SyncPushStepOutcome = "succeeded"
	// SyncPushStepPendingApproval: the collective holds the share until its
	// owner approves it. Only an add_collective step has this outcome.
	SyncPushStepPendingApproval SyncPushStepOutcome = "pending_approval"
	// SyncPushStepSkipped: the step was not needed or not allowed, for example
	// a collective that already holds the transcript. It is not a failure and
	// carries its reason.
	SyncPushStepSkipped SyncPushStepOutcome = "skipped"
	// SyncPushStepFailed: the step failed, Village keeps what it had for it, and
	// the step carries its reason.
	SyncPushStepFailed SyncPushStepOutcome = "failed"
	// SyncPushStepNotAttempted: the step did not run because an earlier step of
	// the same session failed.
	SyncPushStepNotAttempted SyncPushStepOutcome = "not_attempted"
)

func (SyncPushStepOutcome) IsValid added in v0.25.0

func (o SyncPushStepOutcome) IsValid() bool

func (SyncPushStepOutcome) JSONSchema added in v0.25.0

func (SyncPushStepOutcome) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (SyncPushStepOutcome) String added in v0.25.0

func (o SyncPushStepOutcome) String() string

type SyncPushStepResult added in v0.25.0

type SyncPushStepResult struct {
	Step SyncPushStep `json:"step"`
	// CollectiveID names the collective of an add_collective or
	// remove_collective step. The content step has none.
	CollectiveID *VillageUUID        `json:"collectiveId,omitempty" nullable:"false"`
	Outcome      SyncPushStepOutcome `json:"outcome"`
	// Reason says why a skipped or failed step did not apply. No other outcome
	// carries one.
	Reason string `json:"reason,omitempty"`
}

SyncPushStepResult is the result of one step for one session.

func (SyncPushStepResult) Validate added in v0.25.0

func (r SyncPushStepResult) Validate() error

Validate checks the step, its collective, and the outcome pairing.

type SyncRedactionCategoryGroup added in v0.25.0

type SyncRedactionCategoryGroup struct {
	Category   string                   `json:"category"`
	TotalCount int                      `json:"totalCount" minimum:"0"`
	Rules      []SyncRedactionRuleGroup `json:"rules" nullable:"false"`
}

SyncRedactionCategoryGroup holds the rule groups of one category.

type SyncRedactionItem added in v0.25.0

type SyncRedactionItem struct {
	// Category is the redaction engine's category label, rendered verbatim.
	Category            string `json:"category"`
	RuleID              string `json:"ruleId"`
	RuleDisplayName     string `json:"ruleDisplayName"`
	OriginalText        string `json:"originalText"`
	RedactedReplacement string `json:"redactedReplacement"`
	Description         string `json:"description"`
	LineNumber          int    `json:"lineNumber" minimum:"0"`
	// EntryIndex is the TurnDetail.index of the turn that shows the match, so
	// a client can name and open the turn without projecting entries itself. A
	// match in a tool call's arguments or result names the turn that owns the
	// tool call, and ToolCallID names the call. One item stands for every
	// occurrence of the same text under the same rule, and EntryIndex names the
	// first. It is absent when the match lies outside every turn, for example
	// in session metadata.
	EntryIndex *int `json:"entryIndex,omitempty" minimum:"0" nullable:"false"`
	// ToolCallID is the ToolCallDetail.id of the tool call that holds the
	// match, present only when the match lies in a tool call.
	ToolCallID    string   `json:"toolCallId,omitempty"`
	ContextBefore []string `json:"contextBefore" nullable:"false"`
	ContextAfter  []string `json:"contextAfter" nullable:"false"`
}

SyncRedactionItem is one redaction match in the preview of what leaves the machine.

type SyncRedactionRuleGroup added in v0.25.0

type SyncRedactionRuleGroup struct {
	RuleID      string              `json:"ruleId"`
	DisplayName string              `json:"displayName"`
	Count       int                 `json:"count" minimum:"0"`
	Items       []SyncRedactionItem `json:"items" nullable:"false"`
}

SyncRedactionRuleGroup holds the deduplicated matches of one rule. Items is capped by the server, so it can hold fewer entries than Count.

type SyncRedactionsResponse added in v0.25.0

type SyncRedactionsResponse struct {
	Total      int                          `json:"total" minimum:"0"`
	Categories []SyncRedactionCategoryGroup `json:"categories" nullable:"false"`
}

SyncRedactionsResponse is the response of GET /api/v1/sync/redactions. Total counts every raw match; the groups count deduplicated matches.

func (SyncRedactionsResponse) Validate added in v0.25.0

func (r SyncRedactionsResponse) Validate() error

Validate checks the counts, the item cap, and that each item sits in the category and rule group that holds it.

type SyncStatus added in v0.25.0

type SyncStatus string

SyncStatus is the publication status the local sync chooser shows for one listed session. The server decides it; a client displays it and never infers a status from a row that is absent from the response.

const (
	// SyncStatusNew: the session has no recorded publication.
	SyncStatusNew SyncStatus = "new"
	// SyncStatusUpdated: the session changed after its last publication.
	SyncStatusUpdated SyncStatus = "updated"
	// SyncStatusSynced: the last publication carries the current content.
	SyncStatusSynced SyncStatus = "synced"
	// SyncStatusHeld: the session cannot be published until ingest completes.
	// A held row always names its hold reason.
	SyncStatusHeld SyncStatus = "held"
)

func (SyncStatus) IsValid added in v0.25.0

func (s SyncStatus) IsValid() bool

func (SyncStatus) JSONSchema added in v0.25.0

func (SyncStatus) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (SyncStatus) String added in v0.25.0

func (s SyncStatus) String() string

type TargetKind

type TargetKind string

TargetKind identifies which of an annotation's six target arms is populated: session, transcript entry, annotation, project, file_version, or association. The file_version arm identifies one repository-relative file at one content hash; the association arm identifies a durable association ID.

const (
	TargetSession     TargetKind = "session"
	TargetEntry       TargetKind = "entry"      // turn, tool call, tool result
	TargetAnnotation  TargetKind = "annotation" // meta-annotation
	TargetProject     TargetKind = "project"    // project-level annotation
	TargetFileVersion TargetKind = "file_version"
	TargetAssociation TargetKind = "association"
)

func (TargetKind) IsValid

func (k TargetKind) IsValid() bool

IsValid returns true if the target kind is one of the known variants.

func (TargetKind) JSONSchema

func (TargetKind) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (TargetKind) String

func (k TargetKind) String() string

type TaskSummary

type TaskSummary struct {
	SessionID   string   `json:"sessionId"`
	EntryIndex  int      `json:"entryIndex"` // depth-0 user-turn entry index (task identity)
	Title       string   `json:"title"`      // first words of the user turn, <=80 chars
	StartMs     *int64   `json:"startMs,omitempty"`
	Outcome     string   `json:"outcome,omitempty"` // session-level outcome
	EditedFiles []string `json:"editedFiles"`
	ReadCount   int      `json:"readCount"`
	// ReadFiles is the per-file derivation of ReadCount: repo-relative paths,
	// sorted, distinct, non-nil, mirroring
	// EditedFiles' invariants. Retroactively recoverable for any already-
	// ingested session with at least one depth-1 tool_use entry carrying
	// non-NULL tool_input (see MapNode.ReadAttribution for the honest
	// residual-gap signal when it is not).
	ReadFiles []string `json:"readFiles" required:"true" nullable:"false"`
	RetryLoop bool     `json:"retryLoop"` // an error streak >=2 occurs inside this task's range
	Labels    []string `json:"labels"`    // effective auto/manual annotation values, plain strings
}

TaskSummary is one task: a depth-0 user turn and everything until the next user turn (spec §2 "Task", v1 grain).

func NewTaskSummary

func NewTaskSummary(sessionID string, entryIndex int) TaskSummary

NewTaskSummary returns a TaskSummary with all slices initialized to empty (never-nil marshal guarantee).

func (TaskSummary) Validate

func (t TaskSummary) Validate() error

Validate checks TaskSummary's ReadFiles invariant: non-nil, sorted ascending, and free of duplicates (mirroring the invariants EditedFiles is already expected to carry).

type TaxonomyFamilyNode

type TaxonomyFamilyNode struct {
	Family string                  `json:"family"`
	Types  []AnnotationTypeSummary `json:"types"`
}

TaxonomyFamilyNode represents a family node with its associated annotation types.

type TaxonomyNode

type TaxonomyNode struct {
	Class    string               `json:"class"`
	Families []TaxonomyFamilyNode `json:"families"`
}

TaxonomyNode represents a class node in the class > family > type taxonomy tree.

type ThinkingLevel added in v0.29.0

type ThinkingLevel string

ThinkingLevel is the canonical reasoning-effort level recorded for assistant output. The set is closed. Absence means unknown; "off" is the single disabled state; "ultra" is above "max", and "ultracode" is a distinct level. Native harness spellings are mapping inputs, never wire values: a native spelling that differs from the canonical value travels as ThinkingLevelRaw.

const (
	ThinkingLevelOff       ThinkingLevel = "off"
	ThinkingLevelMinimal   ThinkingLevel = "minimal"
	ThinkingLevelLow       ThinkingLevel = "low"
	ThinkingLevelMedium    ThinkingLevel = "medium"
	ThinkingLevelHigh      ThinkingLevel = "high"
	ThinkingLevelXHigh     ThinkingLevel = "xhigh"
	ThinkingLevelMax       ThinkingLevel = "max"
	ThinkingLevelUltra     ThinkingLevel = "ultra"
	ThinkingLevelUltracode ThinkingLevel = "ultracode"
)

func (ThinkingLevel) IsValid added in v0.29.0

func (v ThinkingLevel) IsValid() bool

IsValid reports whether v is absent ("") or a member of AllThinkingLevels.

func (ThinkingLevel) JSONSchema added in v0.29.0

func (ThinkingLevel) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (ThinkingLevel) String added in v0.29.0

func (v ThinkingLevel) String() string

String returns the canonical level spelling.

type ThinkingLevelChange added in v0.29.0

type ThinkingLevelChange struct {
	Level ThinkingLevel    `json:"level,omitempty"`
	Raw   ThinkingLevelRaw `json:"raw,omitempty"`
}

ThinkingLevelChange is one in-session thinking-level change observed after the session seed. A session keeps its first value in thinkingLevel/thinkingLevelRaw and records each later change here, in source order, with consecutive duplicates collapsed. At least one of level or raw must be present: level may be empty only when raw carries the exact native spelling. Raw follows the same bounded rule as the session seed.

func (ThinkingLevelChange) IsValid added in v0.29.0

func (c ThinkingLevelChange) IsValid() bool

IsValid reports whether the change satisfies the history-entry rule. The generic raw-shape decoder calls it for each element of thinkingLevelHistory.

func (ThinkingLevelChange) PrepareJSONSchema added in v0.29.0

func (ThinkingLevelChange) PrepareJSONSchema(s *jsonschema.Schema) error

PrepareJSONSchema adds the at-least-one-field rule to the generated history entry shape, so the published JSON Schema (and the TypeScript runtime schema derived from it) refuse an empty entry exactly as Validate does. A struct cannot express this cross-field presence rule on its own.

func (ThinkingLevelChange) Validate added in v0.29.0

func (c ThinkingLevelChange) Validate() error

Validate enforces the history-entry rule and returns an actionable error.

type ThinkingLevelRaw added in v0.29.0

type ThinkingLevelRaw string

ThinkingLevelRaw is the exact native level spelling observed when it differs from the emitted canonical value (including when none could be mapped). Source evidence, never a canonical value; non-level evidence (e.g. a numeric budget) is never raw. Non-empty, valid UTF-8, <=128 encoded bytes, no edge Unicode White_Space.

func NewThinkingLevelRaw added in v0.29.0

func NewThinkingLevelRaw(raw string) (ThinkingLevelRaw, error)

NewThinkingLevelRaw validates and constructs a ThinkingLevelRaw. Accepted bytes are preserved exactly; nothing is trimmed or normalized.

func (ThinkingLevelRaw) IsValid added in v0.29.0

func (v ThinkingLevelRaw) IsValid() bool

IsValid reports whether v satisfies the raw rule. The empty string is not a valid raw value; omit the field instead.

func (ThinkingLevelRaw) JSONSchema added in v0.29.0

func (ThinkingLevelRaw) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (ThinkingLevelRaw) String added in v0.29.0

func (v ThinkingLevelRaw) String() string

String returns the exact native spelling.

func (ThinkingLevelRaw) Validate added in v0.29.0

func (v ThinkingLevelRaw) Validate() error

Validate returns the actionable constructor error for an invalid raw value.

type TimelineFixtureCase

type TimelineFixtureCase struct {
	Family         string                  `json:"family" yaml:"family"`
	Name           string                  `json:"name" yaml:"name"`
	Input          TimelineFixtureInput    `json:"input" yaml:"input"`
	Expected       TimelineFixtureExpected `json:"expected" yaml:"expected"`
	Classification testcase.Classification `json:"classification" yaml:"classification"`
	Provenance     testcase.Provenance     `json:"provenance" yaml:"provenance"`
	Mutation       testcase.Mutation       `json:"mutation" yaml:"mutation"`
}

TimelineFixtureCase is one public relationship case. Family is the stable behavioral identity; Name remains the executable testcase identity.

type TimelineFixtureCorpus

type TimelineFixtureCorpus struct {
	Cases                           []TimelineFixtureCase `json:"cases" yaml:"cases"`
	SuccessorAssociationMirrorCases []TimelineFixtureCase `json:"successorAssociationMirrorCases" yaml:"successorAssociationMirrorCases"`
}

TimelineFixtureCorpus is the project Git timeline validation corpus.

func LoadTimelineFixtures

func LoadTimelineFixtures() (TimelineFixtureCorpus, error)

LoadTimelineFixtures parses and validates the shared public timeline corpus.

func (TimelineFixtureCorpus) CheckMin

func (c TimelineFixtureCorpus) CheckMin(minimum int) error

CheckMin rejects a timeline corpus smaller than the required behavioral floor.

type TimelineFixtureExpected

type TimelineFixtureExpected struct {
	ErrorContains string                 `json:"errorContains,omitempty" yaml:"error_contains"`
	Repair        *timelineFixtureRepair `json:"repair,omitempty" yaml:"repair,omitempty"`
}

TimelineFixtureExpected records the validation error for a rejected input. A must-pass case leaves ErrorContains empty.

type TimelineFixtureInput

type TimelineFixtureInput struct {
	Sessions         []TimelineSessionRef `json:"sessions" yaml:"sessions"`
	Commits          []CommitRef          `json:"commits" yaml:"commits"`
	RewrittenCommits []RewrittenCommit    `json:"rewrittenCommits,omitempty" yaml:"rewrittenCommits,omitempty"`
}

TimelineFixtureInput is one normalized session and commit relationship.

type TimelineSessionRef

type TimelineSessionRef struct {
	SessionID        SessionID `json:"sessionId" yaml:"sessionId"`
	Title            string    `json:"title" yaml:"title"`
	Harness          Harness   `json:"harness" yaml:"harness"`
	StartMs          *int64    `json:"startMs,omitempty" yaml:"startMs,omitempty"`
	HasCommitBinding bool      `json:"hasCommitBinding" yaml:"hasCommitBinding"`
}

TimelineSessionRef is identity and display metadata for a recorded session available to the project timeline. Producers order these references by known startMs descending, then sessionId ascending; missing startMs follows every known timestamp and is likewise ordered by sessionId. HasCommitBinding is computed from the complete authoritative session_commits relation, not merely the bounded default-branch commit window returned alongside it. CommitRef.SessionIDs names bindings that are visible inside that window.

type TimestampInfo

type TimestampInfo struct {
	Start    int64  `json:"start"`              // Unix millis
	End      int64  `json:"end"`                // Unix millis
	Ingested *int64 `json:"ingested,omitempty"` // Unix millis; nil if not yet ingested
}

TimestampInfo records session timing in Unix milliseconds.

type TokenUsageDetail added in v0.16.0

type TokenUsageDetail struct {
	Input        *int64 `json:"input,omitempty"`
	Output       *int64 `json:"output,omitempty"`
	CacheRead    *int64 `json:"cacheRead,omitempty"`
	CacheWrite   *int64 `json:"cacheWrite,omitempty"`
	CacheWrite1h *int64 `json:"cacheWrite1h,omitempty"`
	Reasoning    *int64 `json:"reasoning,omitempty"`
	TotalTokens  *int64 `json:"totalTokens,omitempty"`
}

type ToolCallDetail

type ToolCallDetail struct {
	ID   string `json:"id"`
	Name string `json:"name"`
	// Namespace is independent source evidence, including a present empty string.
	// Omission means not recorded; producers preserve the exact redacted value.
	Namespace        *string            `json:"namespace,omitempty" nullable:"false"`
	Arguments        string             `json:"arguments"`
	Result           string             `json:"result"`
	DurationMs       *int               `json:"durationMs,omitempty"`
	ExitCode         *int               `json:"exitCode,omitempty"`
	FilePath         string             `json:"filePath,omitempty"`
	IsError          bool               `json:"isError,omitempty"`
	ToolKind         ToolCallKind       `json:"toolKind,omitempty"`
	CallEntryRef     SourceEntryRef     `json:"callEntryRef,omitempty"`
	ResultEntryRef   SourceEntryRef     `json:"resultEntryRef,omitempty"`
	CallProvenance   *ContentProvenance `json:"callProvenance,omitempty"`
	ResultProvenance *ContentProvenance `json:"resultProvenance,omitempty"`
	Usage            *UsageDetail       `json:"usage,omitempty"`
}

ToolCallDetail is a tool call in the detail view.

type ToolCallKind

type ToolCallKind string

ToolCallKind classifies a tool call in an agent session. Aligns with ACP's ToolCallUpdate.kind — enables ExplorationRatio without heuristic parsing.

const (
	ToolCallKindRead    ToolCallKind = "read"
	ToolCallKindEdit    ToolCallKind = "edit"
	ToolCallKindDelete  ToolCallKind = "delete"
	ToolCallKindMove    ToolCallKind = "move"
	ToolCallKindSearch  ToolCallKind = "search"
	ToolCallKindExecute ToolCallKind = "execute"
	ToolCallKindThink   ToolCallKind = "think"
	ToolCallKindFetch   ToolCallKind = "fetch"
	ToolCallKindOther   ToolCallKind = "other"
)

func (ToolCallKind) IsValid

func (k ToolCallKind) IsValid() bool

IsValid returns true if the tool call kind is one of the known variants.

func (ToolCallKind) JSONSchema

func (ToolCallKind) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (ToolCallKind) String

func (k ToolCallKind) String() string

type TranscriptContent

type TranscriptContent struct {
	ContractVersion PushContractVersion   `json:"contractVersion"`
	Kind            ContentKind           `json:"kind"`
	SessionDetail   *SessionDetailPayload `json:"sessionDetail,omitempty"`
}

TranscriptContent is the versioned, self-describing wire body that `peasant push` uploads in place of raw provider JSONL. The village decodes this envelope (migrate-on-read for legacy/older blobs) and renders SessionDetail.

VERSION CONFLICT-WINNER: a TranscriptContent envelope carries TWO version markers — the envelope's ContractVersion and the embedded SessionDetailPayload.SchemaVersion. They are emitted IN LOCKSTROKE by peasant (both equal defaults.PublishSchemaVersion). If a decoder ever observes them to DISAGREE (e.g. a hand-edited or partially-migrated blob), the ENVELOPE's ContractVersion WINS and is authoritative for migrate-on-read dispatch; the embedded SchemaVersion is advisory and exists so a SessionDetailPayload extracted and stored on its OWN (outside any envelope) remains self-describing. The village ContentMigrator MUST honor this same rule.

func DecodeTranscriptContentRaw added in v0.16.0

func DecodeTranscriptContentRaw(raw []byte) (TranscriptContent, error)

type TranscriptContentHash

type TranscriptContentHash string

TranscriptContentHash is the SHA3-256 digest of the exact transcript file bytes.

func ComputeTranscriptContentHash

func ComputeTranscriptContentHash(content []byte) TranscriptContentHash

func NewTranscriptContentHash

func NewTranscriptContentHash(raw string) (TranscriptContentHash, error)

func (TranscriptContentHash) JSONSchema

func (TranscriptContentHash) JSONSchema() (jsonschema.Schema, error)

func (TranscriptContentHash) String

func (v TranscriptContentHash) String() string

func (TranscriptContentHash) Validate

func (v TranscriptContentHash) Validate() error

type TranscriptID

type TranscriptID string

TranscriptID is a validated village-side transcript identifier. The village generates a UUID per published transcript (the same value carried in PublishResponse.TranscriptID); the pull surface keys off it. Newtype over string so the identifier flows typed across the pull pipeline, mirroring the SessionID/ProjectHash precedent.

func NewTranscriptID

func NewTranscriptID(raw string) (TranscriptID, error)

NewTranscriptID validates and constructs a TranscriptID. The input must be a canonical lowercase-hex UUID; anything else is rejected so a pasted URL slug, truncated id, or path-bearing string never reaches the filesystem layout ({villageHost}/{transcriptId}/...).

func (TranscriptID) JSONSchema

func (TranscriptID) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (TranscriptID) String

func (t TranscriptID) String() string

type TranscriptUpdateLicense

type TranscriptUpdateLicense string

TranscriptUpdateLicense is the license value the owner update operation accepts: any license on the canonical License menu, PLUS the empty string, which CLEARS the license.

The empty string is a real member of this operation's value set rather than a missing value, and that is the whole point of the type: it is what lets a caller distinguish "do not touch the license" (omit the field entirely) from "remove the license" (send ""). Collapsing the two would make the irrevocability rule below unexpressible.

Clearing is NOT always permitted. A license that was actually granted can never be cleared, because a Creative Commons grant is irrevocable for anyone who already received the work, so an un-license would misrepresent the legal state. The server refuses that with 400. Clearing a transcript that was never licensed is an accepted no-op, and replacing one menu license with a different one stays allowed.

const TranscriptUpdateLicenseClear TranscriptUpdateLicense = ""

TranscriptUpdateLicenseClear is the value that clears the license. It is spelled as a named constant so callers express the intent rather than an unexplained empty string.

func (TranscriptUpdateLicense) IsValid

func (l TranscriptUpdateLicense) IsValid() bool

IsValid reports whether the value is either the clear sentinel or a license on the canonical menu. It derives the menu from AllLicenses rather than repeating it, so widening the license menu widens this operation automatically.

func (TranscriptUpdateLicense) JSONSchema

JSONSchema implements jsonschema.Exposer.

func (TranscriptUpdateLicense) String

func (l TranscriptUpdateLicense) String() string

type TranscriptUpdateRequest

type TranscriptUpdateRequest struct {
	// Title replaces the transcript title when non-nil. The bound mirrors the
	// storage column, which is VARCHAR(500) and is enforced by nothing else on
	// the way in: an over-long title reaches the database and surfaces as an
	// opaque server error rather than a refusal naming the limit. Declaring it
	// lets a client catch the problem before it sends the request.
	//
	// The two limits count differently, and the difference is recorded here
	// rather than discovered later. The column counts CODE POINTS; a JavaScript
	// validator generated from this bound counts UTF-16 CODE UNITS, so an astral
	// character costs two there and one in the column. The direction is the safe
	// one: a JavaScript count is never smaller than the code-point count, so
	// nothing this bound accepts can be rejected by the column. The cost is at
	// the other end, where a title of more than 250 astral characters is refused
	// client-side though the column would take it. That band was judged worth
	// the far commoner case of an ordinary over-long title turning into a caught
	// validation error instead of an opaque server failure.
	Title *string `json:"title,omitempty" maxLength:"500"`
	// Description replaces the transcript description when non-nil.
	Description *string `json:"description,omitempty"`
	// Visibility replaces the access level when non-nil.
	Visibility *TranscriptUpdateVisibility `json:"visibility,omitempty"`
	// License preserves when nil, clears when it points at the clear sentinel,
	// and replaces when it points at a canonical menu license.
	License *TranscriptUpdateLicense `json:"license,omitempty"`
}

TranscriptUpdateRequest is the body of PATCH /api/v1/transcripts/{id}.

Every field is a pointer and every field is optional, because omission is meaningful: a nil field means "leave this unchanged", NOT "set this to the zero value". Title and Description are therefore settable to the empty string (a caller pointing at "" clears the text) without that being confusable with omitting them.

License carries the third state described on TranscriptUpdateLicense: nil preserves, a pointer to the clear sentinel removes, and a pointer to a menu value replaces.

JSON null is REFUSED on every field, and the refusal is the point. A caller reaching for null almost always means "clear this", but the village decodes a null into the same nil pointer an omitted field produces, so null would silently mean PRESERVE - the opposite of the obvious reading, on exactly the fields where clearing is what a caller wants. Rather than declare that trap, this contract rejects null and gives each intent its own unambiguous spelling: omit the field to leave it unchanged, and send the empty string to clear a title, a description, or a license. This is a deliberate narrowing of what the village tolerates, in the same spirit as the visibility menu: the contract never promises behavior the server lacks, it only declines to bless a spelling whose meaning would surprise the caller.

Unknown fields are refused for the same reason. The village accepts and silently discards a "tags" field, so a client that sent tags would receive a success and believe they applied; refusing the field turns that silent no-op into an actionable error.

func (*TranscriptUpdateRequest) UnmarshalJSON

func (r *TranscriptUpdateRequest) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes an owner-update body at the trust boundary, refusing two things the permissive default would wave through: an unknown field, and an explicit null.

Both refusals exist because the alternative is a SILENT wrong answer rather than a loud one. An unknown field (notably "tags", which the village decodes and discards) would otherwise be dropped and reported as success. An explicit null would otherwise decode to the same nil pointer an omitted field produces, so a caller who sent null meaning "clear this" would get "leave it unchanged" and no indication anything was ignored.

func (TranscriptUpdateRequest) Validate

func (r TranscriptUpdateRequest) Validate() error

type TranscriptUpdateVisibility

type TranscriptUpdateVisibility string

TranscriptUpdateVisibility is the closed set of visibility values the owner update operation accepts.

It is deliberately NARROWER than the general Visibility enum. Visibility carries a third member for organization-scoped access, which this operation does not declare: organization visibility is a deferred capability, not merely an unimplemented one, so declaring it here would publish deferred scope into the contract and advertise a value a client cannot successfully send. The general Visibility enum is unchanged; only what THIS operation declares is constrained.

const (
	// TranscriptUpdateVisibilityPrivate restricts the transcript to its owner.
	TranscriptUpdateVisibilityPrivate TranscriptUpdateVisibility = "private"
	// TranscriptUpdateVisibilityPublic makes the transcript openly readable.
	TranscriptUpdateVisibilityPublic TranscriptUpdateVisibility = "public"
)

func (TranscriptUpdateVisibility) IsValid

func (v TranscriptUpdateVisibility) IsValid() bool

IsValid reports whether the value is one of the accepted variants.

func (TranscriptUpdateVisibility) JSONSchema

JSONSchema implements jsonschema.Exposer.

func (TranscriptUpdateVisibility) String

type TrendsPayload

type TrendsPayload struct {
	Days          []DayStats `json:"days"`
	TotalTokens   int        `json:"totalTokens"`
	TotalSessions int        `json:"totalSessions"`
}

TrendsPayload is the data sent on the trends WebSocket channel.

type TurnDetail

type TurnDetail struct {
	Index       int              `json:"index"`
	Role        Role             `json:"role"`
	Content     string           `json:"content"`
	ToolCalls   []ToolCallDetail `json:"toolCalls,omitempty"`
	Timestamp   time.Time        `json:"timestamp"`
	Depth       int              `json:"depth"`
	ParentIndex *int             `json:"parentIndex,omitempty"`
	AgentName   string           `json:"agentName,omitempty"`
	// ObservedModel is the exact model identifier observed while producing this
	// assistant or subagent turn. It is optional source evidence: when present it
	// uses valid UTF-8 with no leading or trailing Unicode whitespace, while accepted
	// bytes are preserved exactly. Producers enforce the assistant-only role condition; generated shape
	// validators do not infer it from Role.
	ObservedModel ObservedModelID `json:"observedModel,omitempty"`
	// ThinkingLevel/ThinkingLevelRaw are assistant-turn evidence: set only on
	// assistant-generated output, never user or system turns. Raw follows the
	// same "differs from canonical, including unmapped" rule as the session field.
	ThinkingLevel    ThinkingLevel      `json:"thinkingLevel,omitempty"`
	ThinkingLevelRaw ThinkingLevelRaw   `json:"thinkingLevelRaw,omitempty"`
	SourceEntryRef   SourceEntryRef     `json:"sourceEntryRef,omitempty"`
	Provenance       *ContentProvenance `json:"provenance,omitempty"`
	Usage            *UsageDetail       `json:"usage,omitempty"`

	// Command is present when this turn invoked a skill or a user-defined
	// slash command. It is optional and safely ignorable; the invocation name
	// is also in Content. Producers set it on the turn that carries the
	// invocation, whatever Role that turn has: a harness-injected command
	// wrapper is commonly a RoleSystem turn. It is never set for built-in
	// harness commands. Consumers must not infer Role from Command or Command
	// from Role.
	Command *CommandInvocation `json:"command,omitempty"`

	// Enrichment fields — propagated from session_entries.
	EntryType   EntryType   `json:"entryType,omitempty"`
	HasThinking bool        `json:"hasThinking,omitempty"`
	StopReason  *StopReason `json:"stopReason,omitempty"`
	TokensIn    *int        `json:"tokensIn,omitempty"`
	TokensOut   *int        `json:"tokensOut,omitempty"`
}

TurnDetail is a turn with full content for the detail view.

type TypeDefinition

type TypeDefinition struct {
	// TypeID is the dot-notation identifier (e.g., "quality.my_signal").
	// Must match the CHECK (type_id LIKE '%.%') constraint.
	TypeID string

	// DisplayName is the human-readable name.
	DisplayName string

	// Description is optional free-text documentation.
	Description string

	// FamilyID is the UUID FK to annotation_families.id.
	FamilyID string

	// ValueDomain defines permissible values for this type.
	ValueDomain ValueDomain

	// LowerIsBetter is nil for non-ordinal types, false for higher-is-better, true for lower-is-better.
	LowerIsBetter *bool

	// Origin is who created this type (system, user, group).
	Origin TypeOrigin

	// AllowedTargetKinds specifies which target kinds this type allows (V16).
	// Nil or empty means all target kinds are allowed.
	AllowedTargetKinds []TargetKind
}

TypeDefinition is the input for registering a new annotation type.

type TypeDependency

type TypeDependency struct {
	// TypeID is the dependent annotation type.
	TypeID string

	// DependsOn is the type that must be computed first.
	DependsOn string

	// Required: true means this dependency must be satisfied before TypeID can produce a value.
	Required bool

	// Rationale documents why this dependency exists.
	Rationale string
}

TypeDependency represents a dependency edge in the annotation_type_deps table.

type TypeFilter

type TypeFilter struct {
	// Status filters to types with this status (e.g., StatusActive).
	// Zero value includes all statuses except deprecated/retired (unless IncludeDeprecated is set).
	Status AnnotationStatus

	// FamilyID filters to types in this family by UUID FK. "" means all families.
	FamilyID string

	// Origin filters to types from this origin. Zero value means all origins.
	Origin TypeOrigin

	// IncludeDeprecated includes deprecated types when true.
	// Has no effect when Status is set (Status takes precedence).
	IncludeDeprecated bool
}

TypeFilter constrains which annotation types ListTypes returns. Zero values mean "no filter" (include all non-deprecated types).

type TypeOrigin

type TypeOrigin string

TypeOrigin identifies who created an annotation type.

const (
	OriginSystem TypeOrigin = "system"
	OriginUser   TypeOrigin = "user"
	OriginGroup  TypeOrigin = "group"
)

func (TypeOrigin) IsValid

func (o TypeOrigin) IsValid() bool

IsValid returns true if the type origin is one of the known variants.

func (TypeOrigin) JSONSchema

func (TypeOrigin) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (TypeOrigin) String

func (o TypeOrigin) String() string

type UICapabilitiesResponse added in v0.1.1

type UICapabilitiesResponse struct {
	UICapabilities []string `` /* 422-byte string literal not displayed */
}

UICapabilitiesResponse reports optional UI behavior enabled for the running local Peasant server. Capability token meanings and lifecycle are owned by Peasant, not by the schema module. Omitted and empty both mean no optional capabilities; consumers compare known tokens by exact membership and ignore unknown tokens. Producers emit tokens in sorted order without duplicates.

type UnifiedMetadata

type UnifiedMetadata struct {
	SchemaVersion int        `json:"schemaVersion"`
	SessionID     SessionID  `json:"sessionId"`
	ParentUUID    *SessionID `json:"parentUuid"` // nil for root sessions, pointer for nullable JSON
	ModelHarness  Harness    `json:"harness"`
	Model         ModelID    `json:"model"`
	Version       string     `json:"version"` // provider tool version (e.g. "2.1.47")
	// ThinkingLevel is the session-level seed: the earliest valid root-assistant
	// level observation, or the stored seed on replay. Absent means unknown.
	ThinkingLevel ThinkingLevel `json:"thinkingLevel,omitempty"`
	// ThinkingLevelRaw is the exact native spelling when it differs from the
	// emitted canonical value (including when no canonical could be mapped);
	// absent when nothing was observed or the spelling is canonical.
	ThinkingLevelRaw ThinkingLevelRaw `json:"thinkingLevelRaw,omitempty"`
	// ThinkingLevelHistory records the in-session level changes observed after
	// the seed, in source order, with consecutive duplicates collapsed. The
	// session's first value stays in ThinkingLevel/ThinkingLevelRaw above; each
	// entry here carries the later canonical level and/or its exact native
	// spelling. Empty when the session never changed level or none was observed.
	ThinkingLevelHistory []ThinkingLevelChange `json:"thinkingLevelHistory,omitempty"`
	Timestamp            TimestampInfo         `json:"timestamp"`
	Source               SourceInfo            `json:"source"`
	Git                  GitContext            `json:"git"`
	Project              ProjectContext        `json:"project"`
	HostSlug             HostSlug              `json:"hostSlug"`
	Stats                SessionStats          `json:"stats"`
	Subagents            []SubagentRef         `json:"subagents"`
	RootSessionID        *SessionID            `json:"rootSessionId,omitempty"`
	Purpose              SessionPurpose        `json:"purpose,omitempty"`
	Relationships        []SessionRelationship `json:"relationships,omitempty"`
	CWD                  string                `json:"cwd,omitempty"`       // Real project working directory (v7+)
	DerivedAt            *int64                `json:"derivedAt,omitempty"` // Unix ms when metadata.json was derived from DB (v8+); nil if written before DB insert
	Diagnostics          DiagnosticsInfo       `json:"diagnostics"`
	ContentHash          string                `json:"contentHash"`  // SHA3-256 of transcript bytes
	MetadataHash         string                `json:"metadataHash"` // SHA3-256 of metadata (excluding hashes + redaction)
	Redaction            RedactionInfo         `json:"redaction"`
	// AdapterVersion identifies the Peasant adapter/parser that successfully
	// produced this artifact, not the native harness release in Version.
	// Omission means unknown historical provenance; a present value must be positive.
	AdapterVersion *int `` /* 230-byte string literal not displayed */
}

UnifiedMetadata is the on-disk JSON stored alongside each raw transcript. It drives the adapter layer for downstream consumers and incremental diff logic.

func NewUnifiedMetadata

func NewUnifiedMetadata() UnifiedMetadata

NewUnifiedMetadata creates a UnifiedMetadata with SchemaVersion set to MetadataSchemaVersion and empty slices initialized (not nil) so JSON serialization produces [] instead of null.

func (UnifiedMetadata) MarshalJSON added in v0.15.0

func (m UnifiedMetadata) MarshalJSON() ([]byte, error)

MarshalJSON preserves optional producer provenance and refuses invalid revisions even when the metadata was assembled directly rather than decoded from JSON.

func (*UnifiedMetadata) UnmarshalJSON

func (m *UnifiedMetadata) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes UnifiedMetadata, accepting the legacy pre-v9 on-disk harness key. The canonical key is json:"harness" (v9+); pre-v9 files wrote json:"modelHarness". When the canonical key is absent but the legacy key is present, the legacy value is adopted so a pre-v9 file still reads its harness correctly in the window before the v9 DIFF-stage re-extract rewrites it. AdapterVersion is positive when present; omission represents unknown provenance.

type UnusualSignal

type UnusualSignal struct {
	Kind       string  `json:"kind"`       // e.g. "retryLoops"
	Label      string  `json:"label"`      // plain, neutral
	PerChange  float64 `json:"perChange"`  // this change's per-conversation rate
	PerProject float64 `json:"perProject"` // the project's per-conversation baseline
}

UnusualSignal is one neutral rate-elevation: a per-conversation rate for this change that runs notably above the project baseline. Facts for orientation — the surface shows, it does not grade.

type UsageCompleteness added in v0.16.0

type UsageCompleteness string
const (
	UsageComplete UsageCompleteness = "complete"
	UsagePartial  UsageCompleteness = "partial"
	UsageUnknown  UsageCompleteness = "unknown"
)

func NewUsageCompleteness added in v0.16.0

func NewUsageCompleteness(raw string) (UsageCompleteness, error)

func (UsageCompleteness) IsValid added in v0.16.0

func (v UsageCompleteness) IsValid() bool

func (UsageCompleteness) JSONSchema added in v0.16.0

func (UsageCompleteness) JSONSchema() (jsonschema.Schema, error)

type UsageDetail added in v0.16.0

type UsageDetail struct {
	OwnerID        UsageOwnerID        `json:"ownerId"`
	SourceEntryRef SourceEntryRef      `json:"sourceEntryRef"`
	Scope          UsageScope          `json:"scope"`
	Completeness   UsageCompleteness   `json:"completeness"`
	Tokens         *TokenUsageDetail   `json:"tokens,omitempty"`
	Cost           *RecordedCostDetail `json:"cost,omitempty"`
}

type UsageOwnerID added in v0.16.0

type UsageOwnerID string

type UsageScope added in v0.16.0

type UsageScope string
const (
	UsageScopeAssistant UsageScope = "assistant"
	UsageScopeTool      UsageScope = "tool"
	UsageScopeSummary   UsageScope = "summary"
)

func NewUsageScope added in v0.16.0

func NewUsageScope(raw string) (UsageScope, error)

func (UsageScope) IsValid added in v0.16.0

func (v UsageScope) IsValid() bool

func (UsageScope) JSONSchema added in v0.16.0

func (UsageScope) JSONSchema() (jsonschema.Schema, error)

type ValidGenExpectation

type ValidGenExpectation struct {
	Parses         bool   `yaml:"parses"`
	WantID         string `yaml:"want_id"`           // casing name whose value is the expected normalized ID
	FromURLPerForm bool   `yaml:"from_url_per_form"` // take FromURL from each ref_form
}

ValidGenExpectation is the expectation attached to the valid generator.

type ValidGeneration

type ValidGeneration struct {
	Axes   []string            `yaml:"axes"`
	Expect ValidGenExpectation `yaml:"expect"`
}

ValidGeneration declares the valid cross-product and its attached expectation.

type ValueDomain

type ValueDomain struct {
	Kind              ValueDomainKind    `json:"kind"`
	Datatype          AnnotationDatatype `json:"datatype"`
	PermissibleValues []string           `json:"permissibleValues,omitempty"` // for enumerated
	ConstraintSpec    string             `json:"constraintSpec,omitempty"`    // for described; JSON
}

ValueDomain defines the permissible values for an annotation type (ISO 11179). For enumerated domains, PermissibleValues holds the finite set of allowed strings. For described domains, ConstraintSpec holds a JSON-encoded range or pattern.

type ValueDomainKind

type ValueDomainKind string

ValueDomainKind distinguishes enumerated (finite set of allowed values) from described (range or pattern constraint) annotation value domains (ISO 11179).

const (
	DomainEnumerated ValueDomainKind = "enumerated"
	DomainDescribed  ValueDomainKind = "described"
)

func (ValueDomainKind) IsValid

func (k ValueDomainKind) IsValid() bool

IsValid returns true if the value domain kind is one of the known variants.

func (ValueDomainKind) JSONSchema

func (ValueDomainKind) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (ValueDomainKind) String

func (k ValueDomainKind) String() string

type VillageAssignableCollectiveRole added in v0.31.0

type VillageAssignableCollectiveRole string

VillageAssignableGroupRole is the smaller role menu accepted by the member role update endpoint.

type VillageAssignableGroupRole deprecated added in v0.1.3

type VillageAssignableGroupRole = VillageAssignableCollectiveRole

Deprecated: use VillageAssignableCollectiveRole.

const (
	VillageAssignableGroupRoleContributor VillageAssignableGroupRole = "contributor"
	VillageAssignableGroupRoleMember      VillageAssignableGroupRole = "member"
)

func (VillageAssignableGroupRole) JSONSchema added in v0.1.3

type VillageAvailableRepositoriesResponse added in v0.22.0

type VillageAvailableRepositoriesResponse struct {
	Repositories []VillageAvailableRepository `json:"repositories" nullable:"false"`
}

type VillageAvailableRepository added in v0.22.0

type VillageAvailableRepository struct {
	Owner          string `json:"owner"`
	Name           string `json:"name"`
	IsPrivate      bool   `json:"is_private"`
	PublisherCount int32  `json:"publisher_count" minimum:"0"`
}

VillageAvailableRepository is one repository the App can offer a collective, used to populate the repository picker before a link is created. PublisherCount counts the distinct members who shared a transcript from this repository with this collective; transcripts not shared with it are not counted.

type VillageBatchReviewRequest added in v0.1.3

type VillageBatchReviewRequest struct {
	TranscriptIDs []TranscriptID        `json:"transcript_ids" nullable:"false"`
	Status        VillageReviewDecision `json:"status"`
}

type VillageBatchReviewResponse added in v0.1.3

type VillageBatchReviewResponse struct {
	Decided        []TranscriptID `json:"decided" nullable:"false"`
	AlreadyDecided []TranscriptID `json:"already_decided" nullable:"false"`
}

type VillageBatchShareEntry added in v0.1.3

type VillageBatchShareEntry struct {
	TranscriptID TranscriptID              `json:"transcript_id"`
	Status       VillageContributionStatus `json:"status"`
}

type VillageBatchShareRequest added in v0.1.3

type VillageBatchShareRequest struct {
	ProjectHash         ProjectHash    `json:"project_hash"`
	TranscriptIDs       []TranscriptID `json:"transcript_ids,omitempty"`
	VisibilityConfirmed bool           `json:"visibility_confirmed"`
}

type VillageBatchShareResponse added in v0.1.3

type VillageBatchShareResponse struct {
	ProjectHash   ProjectHash              `json:"project_hash"`
	Shared        []VillageBatchShareEntry `json:"shared" nullable:"false"`
	AlreadyShared []TranscriptID           `json:"already_shared" nullable:"false"`
}

type VillageCollective added in v0.31.0

type VillageCollective struct {
	ID                       VillageUUID                     `json:"id"`
	Name                     string                          `json:"name"`
	Description              *string                         `json:"description"`
	CreatedBy                VillageUUID                     `json:"created_by"`
	CreatedAt                time.Time                       `json:"created_at"`
	UpdatedAt                time.Time                       `json:"updated_at"`
	AcceptanceMode           VillageGroupAcceptanceMode      `json:"acceptance_mode"`
	DataAccess               VillageGroupDataAccess          `json:"data_access"`
	LinkedGithubOrg          *string                         `json:"linked_github_org"`
	DisplayMembers           bool                            `json:"display_members"`
	TranscriptDeletionPolicy VillageTranscriptDeletionPolicy `json:"transcript_deletion_policy"`
	// PostPromptsCheck controls whether the prompts check is created on pull
	// requests in this collective's linked repositories. Defaults to true.
	PostPromptsCheck bool `json:"post_prompts_check"`
	// PromptsCheckMode decides the check conclusion when no prompts are attached.
	PromptsCheckMode VillagePromptsCheckMode `json:"prompts_check_mode"`
}

VillageGroup is the full collective row returned by create, update, and detail routes.

type VillageCollectiveAcceptanceMode added in v0.31.0

type VillageCollectiveAcceptanceMode string

VillageGroupAcceptanceMode is the closed acceptance policy menu for a collective.

type VillageCollectiveContributor added in v0.31.0

type VillageCollectiveContributor struct {
	ID              VillageUUID `json:"id"`
	GithubUsername  string      `json:"github_username"`
	AvatarURL       *string     `json:"avatar_url"`
	TranscriptCount int32       `json:"transcript_count"`
}

type VillageCollectiveDataAccess added in v0.31.0

type VillageCollectiveDataAccess string

VillageGroupDataAccess is the closed read policy menu for a collective's pooled transcript data.

type VillageCollectiveDetailRecord added in v0.31.0

type VillageCollectiveDetailRecord struct {
	ID                       VillageUUID                     `json:"id"`
	Name                     string                          `json:"name"`
	Description              *string                         `json:"description"`
	CreatedBy                VillageUUID                     `json:"created_by"`
	CreatedAt                time.Time                       `json:"created_at"`
	UpdatedAt                time.Time                       `json:"updated_at"`
	AcceptanceMode           VillageGroupAcceptanceMode      `json:"acceptance_mode"`
	DataAccess               VillageGroupDataAccess          `json:"data_access"`
	LinkedGithubOrg          *string                         `json:"linked_github_org"`
	DisplayMembers           bool                            `json:"display_members"`
	TranscriptDeletionPolicy VillageTranscriptDeletionPolicy `json:"transcript_deletion_policy"`
	PostPromptsCheck         *bool                           `json:"post_prompts_check,omitempty"`
	PromptsCheckMode         *VillagePromptsCheckMode        `json:"prompts_check_mode,omitempty"`
}

VillageGroupDetailRecord preserves the released collective detail fields. Optional prompts settings are facts supplied by a capable producer, not defaults.

type VillageCollectiveDetailResponse added in v0.31.0

type VillageCollectiveDetailResponse struct {
	Group          VillageGroupDetailRecord     `json:"group"`
	Members        []VillageGroupMember         `json:"members" nullable:"false"`
	Stats          VillageGroupTranscriptStats  `json:"stats"`
	Models         []VillageGroupModelBreakdown `json:"models" nullable:"false"`
	Contributors   []VillageGroupContributor    `json:"contributors" nullable:"false"`
	CanRead        bool                         `json:"can_read"`
	YourRole       VillageGroupViewerRole       `json:"your_role"`
	Transcripts    []VillageGroupTranscript     `json:"transcripts" nullable:"false"`
	PendingMembers []VillageGroupMember         `json:"pending_members,omitempty" nullable:"false"`
}

type VillageCollectiveMember added in v0.31.0

type VillageCollectiveMember struct {
	Role           VillageGroupRole `json:"role"`
	JoinedAt       time.Time        `json:"joined_at"`
	ID             VillageUUID      `json:"id"`
	GithubUsername string           `json:"github_username"`
	DisplayName    *string          `json:"display_name"`
	AvatarURL      *string          `json:"avatar_url"`
	GithubOrgs     []string         `json:"github_orgs" nullable:"false"`
}

VillageGroupMember is one member row in a collective roster.

type VillageCollectiveMemberRoleRequest added in v0.31.0

type VillageCollectiveMemberRoleRequest struct {
	Role VillageAssignableGroupRole `json:"role"`
}

type VillageCollectiveMemberUsernameRequest added in v0.31.0

type VillageCollectiveMemberUsernameRequest struct {
	Username string `json:"username"`
}

type VillageCollectiveModelBreakdown added in v0.31.0

type VillageCollectiveModelBreakdown struct {
	ModelProvider   string `json:"model_provider"`
	TranscriptCount int32  `json:"transcript_count"`
}

type VillageCollectiveRole added in v0.31.0

type VillageCollectiveRole string

VillageGroupRole is the role stored for a user in one collective.

type VillageCollectiveSearchResponse added in v0.1.3

type VillageCollectiveSearchResponse struct {
	Collectives []VillageCollectiveSearchResult `json:"collectives" nullable:"false"`
}

type VillageCollectiveSearchResult added in v0.1.3

type VillageCollectiveSearchResult struct {
	ID              VillageUUID `json:"id"`
	Name            string      `json:"name"`
	Description     *string     `json:"description"`
	LinkedGithubOrg *string     `json:"linked_github_org"`
	MemberCount     int32       `json:"member_count"`
	TranscriptCount int32       `json:"transcript_count"`
}

VillageCollectiveSearchResult is one collective returned by search surfaces.

type VillageCollectiveStatusRoleResponse added in v0.31.0

type VillageCollectiveStatusRoleResponse struct {
	Status string           `json:"status"`
	Role   VillageGroupRole `json:"role"`
}

type VillageCollectiveSubmission added in v0.1.3

type VillageCollectiveSubmission struct {
	TranscriptID TranscriptID       `json:"transcript_id"`
	GroupID      VillageUUID        `json:"group_id"`
	Title        *string            `json:"title"`
	EventNum     int32              `json:"event_num"`
	Status       VillageShareStatus `json:"status"`
	RecordedAt   time.Time          `json:"recorded_at"`
}

type VillageCollectiveTranscript added in v0.31.0

type VillageCollectiveTranscript struct {
	ID                      TranscriptID                `json:"id"`
	OwnerID                 VillageUUID                 `json:"owner_id"`
	LocalID                 SessionID                   `json:"local_id"`
	Title                   *string                     `json:"title"`
	Description             *string                     `json:"description"`
	Visibility              VillageTranscriptVisibility `json:"visibility"`
	ModelProvider           string                      `json:"model_provider"`
	ModelName               *string                     `json:"model_name"`
	HarnessVersion          *string                     `json:"harness_version"`
	SessionStart            *time.Time                  `json:"session_start"`
	SessionEnd              *time.Time                  `json:"session_end"`
	TurnCount               *int32                      `json:"turn_count"`
	TokenCount              *int32                      `json:"token_count"`
	BlobSizeBytes           *int64                      `json:"blob_size_bytes"`
	SchemaVersion           string                      `json:"schema_version"`
	PublishedAt             time.Time                   `json:"published_at"`
	UpdatedAt               time.Time                   `json:"updated_at"`
	ParentSessionID         *SessionID                  `json:"parent_session_id"`
	IngestedAt              *time.Time                  `json:"ingested_at"`
	SourceFormat            *SourceFormat               `json:"source_format"`
	GitBranch               *string                     `json:"git_branch"`
	GitRemote               *string                     `json:"git_remote"`
	ProjectHash             ProjectHash                 `json:"project_hash"`
	ProjectName             *string                     `json:"project_name"`
	ProjectDisplayName      string                      `json:"project_display_name"`
	ProjectNameSource       VillageProjectNameSource    `json:"project_name_source"`
	ProjectRemoteLabel      string                      `json:"project_remote_label"`
	ToolCallCount           *int32                      `json:"tool_call_count"`
	SubagentCount           *int32                      `json:"subagent_count"`
	DurationMs              *int64                      `json:"duration_ms"`
	Subagents               *[]map[string]interface{}   `json:"subagents"`
	DiagnosticsWarnings     *[]string                   `json:"diagnostics_warnings"`
	DiagnosticsPartial      *bool                       `json:"diagnostics_partial"`
	TokensIn                *int64                      `json:"tokens_in"`
	TokensOut               *int64                      `json:"tokens_out"`
	TitleGenerated          *string                     `json:"title_generated"`
	Outcome                 *SessionOutcome             `json:"outcome"`
	FilesTouched            *int32                      `json:"files_touched"`
	LinesChanged            *int32                      `json:"lines_changed"`
	RetryLoops              *int32                      `json:"retry_loops"`
	RetryTokensWasted       *int32                      `json:"retry_tokens_wasted"`
	WithinSessionReverts    *int32                      `json:"within_session_reverts"`
	SignalDensity           *float32                    `json:"signal_density"`
	SpecQualityScore        *float32                    `json:"spec_quality_score"`
	ExplorationRatio        *float32                    `json:"exploration_ratio"`
	ScopeBreadth            *int32                      `json:"scope_breadth"`
	DiscoveryTurns          *int32                      `json:"discovery_turns"`
	M2TokenOutcomeRatio     *float32                    `json:"m2_token_outcome_ratio"`
	M3UniqueToolCount       *int32                      `json:"m3_unique_tool_count"`
	M4ErrorRecoveryCount    *int32                      `json:"m4_error_recovery_count"`
	M4ConsecutiveErrorMax   *int32                      `json:"m4_consecutive_error_max"`
	M5ContextUtilizationPct *float32                    `json:"m5_context_utilization_pct"`
	M5PeakContextTokens     *int32                      `json:"m5_peak_context_tokens"`
	M5AvgMessageTokens      *int32                      `json:"m5_avg_message_tokens"`
	M6OutputSurvivalPct     *float32                    `json:"m6_output_survival_pct"`
	M6LinesSurvived         *int32                      `json:"m6_lines_survived"`
	M6LinesTotal            *int32                      `json:"m6_lines_total"`
	M7SpecWordCount         *int32                      `json:"m7_spec_word_count"`
	M7SpecHasExamples       *bool                       `json:"m7_spec_has_examples"`
	M7SpecHasConstraints    *bool                       `json:"m7_spec_has_constraints"`
	ComputedAt              *time.Time                  `json:"computed_at"`
	ComputeVersion          *int32                      `json:"compute_version"`
	ContentHash             *TranscriptContentHash      `json:"content_hash"`
	LicenseID               *License                    `json:"license_id"`
	SessionOrigin           SessionOrigin               `json:"session_origin"`
	OwnerUsername           string                      `json:"owner_username"`
	OwnerAvatarURL          *string                     `json:"owner_avatar_url"`
	OwnerIsDiscoverable     bool                        `json:"owner_is_discoverable"`
	InputSubmissionCount    *int64                      `json:"input_submission_count,omitempty" minimum:"0" maximum:"9007199254740991" nullable:"false"`
	RootSessionID           *SessionID                  `json:"root_session_id,omitempty"`
	Purpose                 SessionPurpose              `json:"purpose,omitempty"`
	Relationships           []SessionRelationship       `json:"relationships,omitempty"`
	PullRequests            VillagePullRequestsSummary  `json:"pull_requests"`
}

VillageGroupTranscript deliberately lists the transcript fields instead of embedding VillageTranscript. Village flattens its embedded response on the JSON wire, and this shape preserves required fields in OpenAPI and TypeScript generation.

type VillageCollectiveTranscriptStats added in v0.31.0

type VillageCollectiveTranscriptStats struct {
	TotalTranscripts int32 `json:"total_transcripts"`
	ContributorCount int32 `json:"contributor_count"`
	TotalTurns       int64 `json:"total_turns"`
	TotalDurationMs  int64 `json:"total_duration_ms"`
	TotalTokens      int64 `json:"total_tokens"`
	PullRequestCount int32 `json:"pull_request_count" minimum:"0"`
}

VillageGroupTranscriptStats totals a collective's transcripts. PullRequestCount counts the distinct pull requests whose attachment is in state attached, includes a transcript counted in TotalTranscripts, and that the caller may read under the visibility rule of VillageTranscriptPullRequestsResponse, failing closed; detached pull requests are not counted.

type VillageCollectiveViewerRole added in v0.31.0

type VillageCollectiveViewerRole string

VillageGroupViewerRole is the viewer's role in one collective. The empty value is the current wire value for a signed-out or non-member viewer on the group-detail response.

type VillageContributableResponse added in v0.1.3

type VillageContributableResponse struct {
	GroupID     VillageUUID                      `json:"group_id"`
	Transcripts []VillageContributableTranscript `json:"transcripts" nullable:"false"`
}

type VillageContributableTranscript added in v0.1.3

type VillageContributableTranscript struct {
	ID                   TranscriptID                `json:"id"`
	LocalID              SessionID                   `json:"local_id"`
	Title                *string                     `json:"title"`
	Visibility           VillageTranscriptVisibility `json:"visibility"`
	ProjectHash          ProjectHash                 `json:"project_hash"`
	ProjectDisplayName   string                      `json:"project_display_name"`
	ProjectNameSource    VillageProjectNameSource    `json:"project_name_source"`
	GitBranch            *string                     `json:"git_branch"`
	ParentSessionID      *SessionID                  `json:"parent_session_id"`
	SessionOrigin        SessionOrigin               `json:"session_origin"`
	ModelProvider        string                      `json:"model_provider"`
	PublishedAt          time.Time                   `json:"published_at"`
	AlreadyShared        bool                        `json:"already_shared"`
	InputSubmissionCount *int64                      `json:"input_submission_count,omitempty" minimum:"0" maximum:"9007199254740991" nullable:"false"`
	RootSessionID        *SessionID                  `json:"root_session_id,omitempty"`
	Purpose              SessionPurpose              `json:"purpose,omitempty"`
	Relationships        []SessionRelationship       `json:"relationships,omitempty"`
}

type VillageContributedCollective added in v0.1.3

type VillageContributedCollective struct {
	ID                    VillageUUID `json:"id"`
	Name                  string      `json:"name"`
	Description           *string     `json:"description"`
	LinkedGithubOrg       *string     `json:"linked_github_org"`
	ApprovedCount         int32       `json:"approved_count" minimum:"0"`
	PendingCount          int32       `json:"pending_count" minimum:"0"`
	RejectedAttemptCount  int32       `json:"rejected_attempt_count" minimum:"0"`
	WithdrawnAttemptCount int32       `json:"withdrawn_attempt_count" minimum:"0"`
}

func (*VillageContributedCollective) UnmarshalJSON added in v0.31.0

func (v *VillageContributedCollective) UnmarshalJSON(data []byte) error

func (VillageContributedCollective) Validate added in v0.31.0

func (v VillageContributedCollective) Validate() error

type VillageContributedCollectivesResponse added in v0.1.3

type VillageContributedCollectivesResponse struct {
	Collectives []VillageContributedCollective `json:"collectives" nullable:"false"`
}

func (*VillageContributedCollectivesResponse) UnmarshalJSON added in v0.31.0

func (v *VillageContributedCollectivesResponse) UnmarshalJSON(data []byte) error

func (VillageContributedCollectivesResponse) Validate added in v0.31.0

type VillageContributionAttemptReconciliation added in v0.31.0

type VillageContributionAttemptReconciliation string

VillageContributionAttemptReconciliation describes the effect on retained evidence. Superseded is a valid older pending observation, not an error.

const (
	VillageContributionAttemptInserted   VillageContributionAttemptReconciliation = "inserted"
	VillageContributionAttemptUnchanged  VillageContributionAttemptReconciliation = "unchanged"
	VillageContributionAttemptUpdated    VillageContributionAttemptReconciliation = "updated"
	VillageContributionAttemptSuperseded VillageContributionAttemptReconciliation = "superseded"
)

type VillageContributionStatus added in v0.1.3

type VillageContributionStatus string

VillageContributionStatus is the status a new contribution can open in.

const (
	VillageContributionStatusApproved VillageContributionStatus = "approved"
	VillageContributionStatusPending  VillageContributionStatus = "pending"
)

func (VillageContributionStatus) JSONSchema added in v0.1.3

type VillageCreateCollectiveRequest added in v0.31.0

type VillageCreateCollectiveRequest struct {
	Name            string                     `json:"name"`
	Description     string                     `json:"description,omitempty"`
	AcceptanceMode  VillageGroupAcceptanceMode `json:"acceptance_mode,omitempty"`
	DataAccess      VillageGroupDataAccess     `json:"data_access,omitempty"`
	LinkedGithubOrg *string                    `json:"linked_github_org,omitempty"`
}

VillageCreateGroupRequest creates a collective. LinkedGithubOrg accepts null as "no organization", exactly as the update request does.

type VillageCreateGroupRequest deprecated added in v0.1.3

type VillageCreateGroupRequest = VillageCreateCollectiveRequest

Deprecated: use VillageCreateCollectiveRequest.

type VillageDeprecatedGroupedContributableResponse deprecated added in v0.31.0

type VillageDeprecatedGroupedContributableResponse struct {
	GroupID        VillageUUID               `json:"groupId"`
	TranscriptList VillageSessionListPayload `json:"transcriptList"`
}

VillageDeprecatedGroupedContributableResponse preserves the released grouped envelope on GET /api/v1/groups/{id}/contributable during the alias window.

Deprecated: use VillageGroupedContributableResponse on the collectives route.

func (VillageDeprecatedGroupedContributableResponse) Validate added in v0.31.0

type VillageEnrichedTranscriptShare added in v0.19.0

type VillageEnrichedTranscriptShare struct {
	TranscriptID   TranscriptID               `json:"transcript_id"`
	GroupID        VillageUUID                `json:"group_id"`
	GroupName      string                     `json:"group_name"`
	AcceptanceMode VillageGroupAcceptanceMode `json:"acceptance_mode"`
	Status         VillageShareStatus         `json:"status"`
	SharedAt       time.Time                  `json:"shared_at"`
}

type VillageErrorResponse added in v0.1.3

type VillageErrorResponse struct {
	Error string `json:"error"`
}

VillageErrorResponse is the common JSON refusal envelope emitted by Village handlers through writeError.

type VillageGitHubWebhookPayload added in v0.17.0

type VillageGitHubWebhookPayload map[string]any

VillageGitHubWebhookPayload is GitHub's event payload, forwarded verbatim. Village verifies the HMAC over the raw body and reads only the fields the event needs, so the contract leaves the object open.

func (VillageGitHubWebhookPayload) JSONSchema added in v0.17.0

type VillageGroup deprecated added in v0.1.3

type VillageGroup = VillageCollective

Deprecated: use VillageCollective. Retained for the complete alias release window.

type VillageGroupAcceptanceMode deprecated added in v0.1.3

type VillageGroupAcceptanceMode = VillageCollectiveAcceptanceMode

Deprecated: use VillageCollectiveAcceptanceMode.

const (
	VillageGroupAcceptanceOpen         VillageGroupAcceptanceMode = "open"
	VillageGroupAcceptanceVerifiedOnly VillageGroupAcceptanceMode = "verified_only"
	VillageGroupAcceptanceCurated      VillageGroupAcceptanceMode = "curated"
)

func (VillageGroupAcceptanceMode) JSONSchema added in v0.1.3

type VillageGroupContributor deprecated added in v0.1.3

type VillageGroupContributor = VillageCollectiveContributor

Deprecated: use VillageCollectiveContributor.

type VillageGroupDataAccess deprecated added in v0.1.3

type VillageGroupDataAccess = VillageCollectiveDataAccess

Deprecated: use VillageCollectiveDataAccess.

const (
	VillageGroupDataAccessMembersOnly  VillageGroupDataAccess = "members_only"
	VillageGroupDataAccessContributors VillageGroupDataAccess = "contributors"
	VillageGroupDataAccessPublic       VillageGroupDataAccess = "public"
)

func (VillageGroupDataAccess) JSONSchema added in v0.1.3

type VillageGroupDetailRecord deprecated added in v0.19.0

type VillageGroupDetailRecord = VillageCollectiveDetailRecord

Deprecated: use VillageCollectiveDetailRecord.

func (VillageGroupDetailRecord) Validate added in v0.19.0

func (r VillageGroupDetailRecord) Validate() error

type VillageGroupDetailResponse deprecated added in v0.1.3

type VillageGroupDetailResponse = VillageCollectiveDetailResponse

Deprecated: use VillageCollectiveDetailResponse.

type VillageGroupMember deprecated added in v0.1.3

type VillageGroupMember = VillageCollectiveMember

Deprecated: use VillageCollectiveMember.

type VillageGroupMemberRoleRequest deprecated added in v0.1.3

type VillageGroupMemberRoleRequest = VillageCollectiveMemberRoleRequest

Deprecated: use VillageCollectiveMemberRoleRequest.

type VillageGroupMemberUsernameRequest deprecated added in v0.1.3

type VillageGroupMemberUsernameRequest = VillageCollectiveMemberUsernameRequest

Deprecated: use VillageCollectiveMemberUsernameRequest.

type VillageGroupModelBreakdown deprecated added in v0.1.3

type VillageGroupModelBreakdown = VillageCollectiveModelBreakdown

Deprecated: use VillageCollectiveModelBreakdown.

type VillageGroupRole deprecated added in v0.1.3

type VillageGroupRole = VillageCollectiveRole

Deprecated: use VillageCollectiveRole.

const (
	VillageGroupRoleOwner       VillageGroupRole = "owner"
	VillageGroupRoleMember      VillageGroupRole = "member"
	VillageGroupRoleContributor VillageGroupRole = "contributor"
	VillageGroupRolePending     VillageGroupRole = "pending"
)

func (VillageGroupRole) JSONSchema added in v0.1.3

func (VillageGroupRole) JSONSchema() (jsonschema.Schema, error)

type VillageGroupStatusRoleResponse deprecated added in v0.1.3

type VillageGroupStatusRoleResponse = VillageCollectiveStatusRoleResponse

Deprecated: use VillageCollectiveStatusRoleResponse.

type VillageGroupTranscript deprecated added in v0.1.3

type VillageGroupTranscript = VillageCollectiveTranscript

Deprecated: use VillageCollectiveTranscript.

type VillageGroupTranscriptStats deprecated added in v0.1.3

type VillageGroupTranscriptStats = VillageCollectiveTranscriptStats

Deprecated: use VillageCollectiveTranscriptStats.

type VillageGroupViewerRole deprecated added in v0.1.3

type VillageGroupViewerRole = VillageCollectiveViewerRole

Deprecated: use VillageCollectiveViewerRole.

const (
	VillageGroupViewerRoleNone        VillageGroupViewerRole = ""
	VillageGroupViewerRoleOwner       VillageGroupViewerRole = "owner"
	VillageGroupViewerRoleMember      VillageGroupViewerRole = "member"
	VillageGroupViewerRoleContributor VillageGroupViewerRole = "contributor"
	VillageGroupViewerRolePending     VillageGroupViewerRole = "pending"
)

func (VillageGroupViewerRole) JSONSchema added in v0.1.3

type VillageGroupedCollectiveDetailResponse added in v0.31.0

type VillageGroupedCollectiveDetailResponse struct {
	Group          VillageGroupDetailRecord     `json:"group"`
	Members        []VillageGroupMember         `json:"members" nullable:"false"`
	Stats          VillageGroupTranscriptStats  `json:"stats"`
	Models         []VillageGroupModelBreakdown `json:"models" nullable:"false"`
	Contributors   []VillageGroupContributor    `json:"contributors" nullable:"false"`
	CanRead        bool                         `json:"can_read"`
	YourRole       VillageGroupViewerRole       `json:"your_role"`
	TranscriptList VillageSessionListPayload    `json:"transcriptList"`
	PendingMembers []VillageGroupMember         `json:"pending_members,omitempty" nullable:"false"`
}

type VillageGroupedContributableResponse added in v0.19.0

type VillageGroupedContributableResponse struct {
	GroupID        VillageUUID               `json:"group_id"`
	TranscriptList VillageSessionListPayload `json:"transcriptList"`
}

func (VillageGroupedContributableResponse) Validate added in v0.19.0

type VillageGroupedGroupDetailResponse deprecated added in v0.19.0

type VillageGroupedGroupDetailResponse = VillageGroupedCollectiveDetailResponse

Deprecated: use VillageGroupedCollectiveDetailResponse.

func (VillageGroupedGroupDetailResponse) Validate added in v0.19.0

type VillageHelperMembersPayload added in v0.19.0

type VillageHelperMembersPayload struct {
	Members []VillageSessionListItem `json:"members" nullable:"false"`
	Page    int                      `json:"page" minimum:"1" maximum:"9007199254740991"`
	Limit   int                      `json:"limit" minimum:"1" maximum:"9007199254740991"`
	Total   int                      `json:"total" minimum:"0" maximum:"9007199254740991"`
}

func (*VillageHelperMembersPayload) UnmarshalJSON added in v0.19.0

func (p *VillageHelperMembersPayload) UnmarshalJSON(raw []byte) error

func (VillageHelperMembersPayload) Validate added in v0.19.0

func (p VillageHelperMembersPayload) Validate() error

type VillageLinkRepositoryRequest added in v0.1.3

type VillageLinkRepositoryRequest struct {
	Owner string `json:"owner"`
	Name  string `json:"name"`
	// InstallationID is the GitHub App installation that grants the App access
	// to the repository. It is OPTIONAL: Village resolves the installation from
	// the repository using the App's own credentials, so a caller that does not
	// already know the id (for example a repository chosen from a picker) omits
	// it. Supplying it is still accepted and is used as given.
	InstallationID *int64 `json:"installation_id,omitempty"`
}

type VillageLinkedRepositoriesResponse added in v0.1.3

type VillageLinkedRepositoriesResponse struct {
	Repositories []VillageLinkedRepository `json:"repositories" nullable:"false"`
}

type VillageLinkedRepository added in v0.1.3

type VillageLinkedRepository struct {
	ID             VillageUUID `json:"id"`
	GroupID        VillageUUID `json:"group_id"`
	Owner          string      `json:"owner"`
	Name           string      `json:"name"`
	InstallationID int64       `json:"installation_id"`
	IsPrivate      bool        `json:"is_private"`
	LinkedBy       VillageUUID `json:"linked_by"`
	LastSyncedAt   *time.Time  `json:"last_synced_at"`
	CreatedAt      *time.Time  `json:"created_at"`
}

type VillageListTranscriptAttestation added in v0.19.0

type VillageListTranscriptAttestation struct {
	TranscriptID    TranscriptID `json:"transcript_id"`
	OrgLogin        string       `json:"org_login"`
	AttestationType string       `json:"attestation_type"`
	CreatedAt       time.Time    `json:"created_at"`
}

type VillageListUserOrganization added in v0.19.0

type VillageListUserOrganization struct {
	UserID    VillageUUID `json:"user_id"`
	OrgLogin  string      `json:"org_login"`
	AvatarURL *string     `json:"avatar_url"`
}

type VillageMetadataUserOrganization added in v0.19.0

type VillageMetadataUserOrganization struct {
	OrgLogin  string    `json:"org_login"`
	OrgID     int64     `json:"org_id"`
	AvatarURL *string   `json:"avatar_url"`
	Visible   bool      `json:"visible"`
	FetchedAt time.Time `json:"fetched_at"`
}

type VillageOrganizationCollective added in v0.31.0

type VillageOrganizationCollective struct {
	ID              VillageUUID `json:"id"`
	Name            string      `json:"name"`
	Description     *string     `json:"description"`
	MemberCount     int32       `json:"member_count" minimum:"0"`
	TranscriptCount int32       `json:"transcript_count" minimum:"0"`
}

VillageOrganizationCollective is the existing viewer-permitted collective projection returned by the organization read. It deliberately carries neither rosters nor a locally reconstructed visibility decision.

func (*VillageOrganizationCollective) UnmarshalJSON added in v0.31.0

func (v *VillageOrganizationCollective) UnmarshalJSON(data []byte) error

type VillageOrganizationCollectivesResponse added in v0.31.0

type VillageOrganizationCollectivesResponse struct {
	Collectives []VillageOrganizationCollective `json:"collectives" nullable:"false"`
}

VillageOrganizationCollectivesResponse is the narrow metadata consumer view of GET /orgs/{login}. The existing endpoint also returns organization stats and members; additive fields are permitted but are not retained by this contract projection or used to derive permissions.

func (*VillageOrganizationCollectivesResponse) UnmarshalJSON added in v0.31.0

func (v *VillageOrganizationCollectivesResponse) UnmarshalJSON(data []byte) error

func (VillageOrganizationCollectivesResponse) Validate added in v0.31.0

type VillagePendingShare added in v0.1.3

type VillagePendingShare struct {
	TranscriptID         TranscriptID          `json:"transcript_id"`
	Title                *string               `json:"title"`
	ModelProvider        string                `json:"model_provider"`
	OwnerID              VillageUUID           `json:"owner_id"`
	LocalID              SessionID             `json:"local_id"`
	ParentSessionID      *SessionID            `json:"parent_session_id"`
	ProjectHash          ProjectHash           `json:"project_hash"`
	ProjectName          *string               `json:"project_name"`
	Branch               *string               `json:"branch"`
	OwnerUsername        string                `json:"owner_username"`
	OwnerIsDiscoverable  bool                  `json:"owner_is_discoverable"`
	SharedAt             time.Time             `json:"shared_at"`
	InputSubmissionCount *int64                `json:"input_submission_count,omitempty" minimum:"0" maximum:"9007199254740991" nullable:"false"`
	RootSessionID        *SessionID            `json:"root_session_id,omitempty"`
	Purpose              SessionPurpose        `json:"purpose,omitempty"`
	Relationships        []SessionRelationship `json:"relationships,omitempty"`
}

type VillageProjectNameSource added in v0.1.3

type VillageProjectNameSource string

VillageProjectNameSource is the closed set of tiers that can produce a resolved project display name.

const (
	VillageProjectNameSourceOverride  VillageProjectNameSource = "override"
	VillageProjectNameSourceConsented VillageProjectNameSource = "consented"
	VillageProjectNameSourceRemote    VillageProjectNameSource = "remote"
	VillageProjectNameSourcePath      VillageProjectNameSource = "path"
	VillageProjectNameSourcePrivacy   VillageProjectNameSource = "privacy"
)

func (VillageProjectNameSource) JSONSchema added in v0.1.3

type VillagePromptRequest added in v0.17.0

type VillagePromptRequest struct {
	Owner       string                            `json:"owner"`
	Name        string                            `json:"name"`
	Number      int                               `json:"number"`
	State       VillagePullRequestAttachmentState `json:"state"`
	Remote      string                            `json:"remote"`
	HeadRemote  string                            `json:"head_remote"`
	RequestedAt time.Time                         `json:"requested_at"`
}

VillagePromptRequest is one attachment waiting on the caller's machine. Remote is the full name of the repository the pull request was opened against, and HeadRemote the full name of the repository its head came from: a fork's repository, or the base itself for a same-repository pull request. Together they let the CLI match the repository it is pushing, normalizing its own git remote first, without re-deriving either rule, so a push from a clone of a fork matches the request waiting on that fork's author.

type VillagePromptRequestsResponse added in v0.17.0

type VillagePromptRequestsResponse struct {
	Requests []VillagePromptRequest `json:"requests" nullable:"false"`
}

type VillagePromptsCheckMode added in v0.17.0

type VillagePromptsCheckMode string

VillagePromptsCheckMode decides the check-run conclusion a collective's linked repositories receive when no prompts are attached.

const (
	// VillagePromptsCheckInformational: neutral when nothing is attached. The default.
	VillagePromptsCheckInformational VillagePromptsCheckMode = "informational"
	// VillagePromptsCheckRequired: failure when nothing is attached, so branch protection can require prompts.
	VillagePromptsCheckRequired VillagePromptsCheckMode = "required"
)

func (VillagePromptsCheckMode) IsValid added in v0.17.0

func (m VillagePromptsCheckMode) IsValid() bool

func (VillagePromptsCheckMode) JSONSchema added in v0.17.0

func (VillagePromptsCheckMode) String added in v0.17.0

func (m VillagePromptsCheckMode) String() string

type VillagePublicCollective added in v0.31.0

type VillagePublicCollective struct {
	ID              VillageUUID                `json:"id"`
	Name            string                     `json:"name"`
	Description     *string                    `json:"description"`
	AcceptanceMode  VillageGroupAcceptanceMode `json:"acceptance_mode"`
	DataAccess      VillageGroupDataAccess     `json:"data_access"`
	LinkedGithubOrg *string                    `json:"linked_github_org"`
	CreatedAt       time.Time                  `json:"created_at"`
	MemberCount     int32                      `json:"member_count"`
	TranscriptCount int32                      `json:"transcript_count"`
}

VillagePublicGroup is the compact row returned by GET /api/v1/groups/public.

type VillagePublicGroup deprecated added in v0.1.3

type VillagePublicGroup = VillagePublicCollective

Deprecated: use VillagePublicCollective.

type VillagePullRequestAttachedTranscript added in v0.17.0

type VillagePullRequestAttachedTranscript struct {
	TranscriptID       TranscriptID                `json:"transcript_id"`
	Position           int                         `json:"position"`
	PreviousVisibility VillageTranscriptVisibility `json:"previous_visibility"`
	Title              *string                     `json:"title"`
	SessionStart       *time.Time                  `json:"session_start"`
}

VillagePullRequestAttachedTranscript is one transcript in an attachment, in chain order, with the visibility to restore on detach.

type VillagePullRequestAttachment added in v0.17.0

type VillagePullRequestAttachment struct {
	ID                  VillageUUID                       `json:"id"`
	Owner               string                            `json:"owner"`
	Name                string                            `json:"name"`
	Number              int                               `json:"number"`
	Title               *string                           `json:"title"`
	HeadRef             *string                           `json:"head_ref"`
	HeadSHA             string                            `json:"head_sha"`
	IsPrivateRepository bool                              `json:"is_private_repository"`
	State               VillagePullRequestAttachmentState `json:"state"`
	AuthorUserID        *VillageUUID                      `json:"author_user_id"`
	RequestedByGithubID *int64                            `json:"requested_by_github_id"`
	CommentID           *int64                            `json:"comment_id"`
	CheckRunID          *int64                            `json:"check_run_id"`
	CreatedAt           time.Time                         `json:"created_at"`
	UpdatedAt           time.Time                         `json:"updated_at"`
	ConfirmedAt         *time.Time                        `json:"confirmed_at"`
	DetachedAt          *time.Time                        `json:"detached_at"`
}

VillagePullRequestAttachment is one pull request's attachment row. Title and HeadRef are the pull request's title and head branch; they are null when Village does not know them.

type VillagePullRequestAttachmentResponse added in v0.17.0

type VillagePullRequestAttachmentResponse struct {
	Attachment     VillagePullRequestAttachment           `json:"attachment"`
	Digest         *PromptDigest                          `json:"digest"`
	Transcripts    []VillagePullRequestAttachedTranscript `json:"transcripts" nullable:"false"`
	ViewerIsAuthor bool                                   `json:"viewer_is_author"`
}

VillagePullRequestAttachmentResponse is the read, confirm, and detach response. Digest is null until the attachment reaches preview or attached.

type VillagePullRequestAttachmentState added in v0.17.0

type VillagePullRequestAttachmentState string

VillagePullRequestAttachmentState is the closed lifecycle of one pull request's prompt attachment. The design's state machine names each transition; the wire only carries the current state.

const (
	// VillagePullRequestAttachmentRequested: a non-author asked; nothing is exposed.
	VillagePullRequestAttachmentRequested VillagePullRequestAttachmentState = "requested"
	// VillagePullRequestAttachmentWaiting: the author consented; no matching transcript exists yet.
	VillagePullRequestAttachmentWaiting VillagePullRequestAttachmentState = "waiting"
	// VillagePullRequestAttachmentPreview: the digest is computed and awaits the author's confirm on Village.
	VillagePullRequestAttachmentPreview VillagePullRequestAttachmentState = "preview"
	// VillagePullRequestAttachmentAttached: the comment is posted and the transcripts are shared.
	VillagePullRequestAttachmentAttached VillagePullRequestAttachmentState = "attached"
	// VillagePullRequestAttachmentDetached: the comment is deleted and prior visibility restored.
	VillagePullRequestAttachmentDetached VillagePullRequestAttachmentState = "detached"
)

func (VillagePullRequestAttachmentState) IsValid added in v0.17.0

func (VillagePullRequestAttachmentState) JSONSchema added in v0.17.0

func (VillagePullRequestAttachmentState) String added in v0.17.0

type VillagePullRequestRef added in v0.25.0

type VillagePullRequestRef struct {
	Owner  string `json:"owner" minLength:"1"`
	Name   string `json:"name" minLength:"1"`
	Number int    `json:"number" minimum:"1"`
}

VillagePullRequestRef names one pull request.

func (VillagePullRequestRef) Validate added in v0.25.0

func (r VillagePullRequestRef) Validate() error

Validate checks that the reference names a repository and a pull request.

type VillagePullRequestsSummary added in v0.25.0

type VillagePullRequestsSummary struct {
	Count  int32                   `json:"count" minimum:"0"`
	Recent []VillagePullRequestRef `json:"recent" nullable:"false"`
}

VillagePullRequestsSummary summarizes the pull requests a transcript is attached to, for a list row. Count is the number of pull requests whose attachment is in state attached and that the caller may read under the visibility rule of VillageTranscriptPullRequestsResponse, failing closed; detached pull requests are not counted. Recent holds the most recent of them, at most as many as the server shows, so a row reads "#42, #45 +2" without one read per row.

func (VillagePullRequestsSummary) Validate added in v0.25.0

func (s VillagePullRequestsSummary) Validate() error

Validate checks that the recent list fits in the count and does not repeat.

type VillageRemoveCollectiveMemberResponse added in v0.31.0

type VillageRemoveCollectiveMemberResponse struct {
	Status    string `json:"status"`
	Retracted bool   `json:"retracted"`
}

type VillageRemoveGroupMemberResponse deprecated added in v0.1.3

type VillageRemoveGroupMemberResponse = VillageRemoveCollectiveMemberResponse

Deprecated: use VillageRemoveCollectiveMemberResponse.

type VillageRepositoryCommit added in v0.1.3

type VillageRepositoryCommit struct {
	SHA         string     `json:"sha"`
	Message     *string    `json:"message"`
	AuthorName  *string    `json:"author_name"`
	AuthorEmail *string    `json:"author_email"`
	AuthoredAt  *time.Time `json:"authored_at"`
	CommittedAt *time.Time `json:"committed_at"`
}

type VillageRepositoryCommitsResponse added in v0.1.3

type VillageRepositoryCommitsResponse struct {
	Owner       string                    `json:"owner"`
	Name        string                    `json:"name"`
	Refreshed   bool                      `json:"refreshed"`
	LastSynced  *time.Time                `json:"last_synced"`
	CommitCount int                       `json:"commit_count"`
	Commits     []VillageRepositoryCommit `json:"commits" nullable:"false"`
}

type VillageReviewDecision added in v0.1.3

type VillageReviewDecision string

VillageReviewDecision is the closed decision menu for collective review actions.

const (
	VillageReviewDecisionApproved VillageReviewDecision = "approved"
	VillageReviewDecisionRejected VillageReviewDecision = "rejected"
)

func (VillageReviewDecision) JSONSchema added in v0.1.3

func (VillageReviewDecision) JSONSchema() (jsonschema.Schema, error)

type VillageReviewShareRequest added in v0.1.3

type VillageReviewShareRequest struct {
	Status VillageReviewDecision `json:"status"`
}

type VillageReviewShareResponse added in v0.1.3

type VillageReviewShareResponse struct {
	Status VillageReviewDecision `json:"status"`
}

type VillageSessionListItem added in v0.19.0

type VillageSessionListItem struct {
	Kind         SessionListItemKind   `json:"kind"`
	Transcript   *VillageSessionRow    `json:"transcript,omitempty"`
	Context      *HelperContextSummary `json:"context,omitempty"`
	HelperGroups []HelperGroupSummary  `json:"helperGroups,omitempty" nullable:"false"`
}

func (VillageSessionListItem) Validate added in v0.19.0

func (i VillageSessionListItem) Validate() error

type VillageSessionListPayload added in v0.19.0

type VillageSessionListPayload struct {
	Items                []VillageSessionListItem `json:"items" nullable:"false"`
	Page                 int                      `json:"page" minimum:"1" maximum:"9007199254740991"`
	Limit                int                      `json:"limit" minimum:"1" maximum:"9007199254740991"`
	TotalItems           int                      `json:"totalItems" minimum:"0" maximum:"9007199254740991"`
	OrdinarySessionTotal int                      `json:"ordinarySessionTotal" minimum:"0" maximum:"9007199254740991"`
	HelperThreadTotal    int                      `json:"helperThreadTotal" minimum:"0" maximum:"9007199254740991"`
}

func (VillageSessionListPayload) Validate added in v0.19.0

func (p VillageSessionListPayload) Validate() error

type VillageSessionRow added in v0.19.0

type VillageSessionRow struct {
	Session       VillageTranscript               `json:"session"`
	Collective    *VillageGroupTranscript         `json:"collective,omitempty"`
	Pending       *VillagePendingShare            `json:"pending,omitempty"`
	MyShare       *VillageUserGroupShare          `json:"myShare,omitempty"`
	Contributable *VillageContributableTranscript `json:"contributable,omitempty"`
}

VillageSessionRow preserves the complete transcript summary and the one route-specific projection that produced it.

func (VillageSessionRow) Validate added in v0.19.0

func (r VillageSessionRow) Validate() error

Validate checks the route arm and the shared identity and count mirrors.

type VillageShareEvent added in v0.1.3

type VillageShareEvent struct {
	EventNum       int32                  `json:"event_num"`
	Status         VillageShareStatus     `json:"status"`
	RecordedAt     time.Time              `json:"recorded_at"`
	DecidedAt      *time.Time             `json:"decided_at"`
	DecidedByActor VillageShareEventActor `json:"decided_by_actor"`
}

func (*VillageShareEvent) UnmarshalJSON added in v0.31.0

func (v *VillageShareEvent) UnmarshalJSON(data []byte) error

func (VillageShareEvent) Validate added in v0.31.0

func (event VillageShareEvent) Validate() error

Validate checks the historical wire payload before reconciliation or emission. Approved attempts may have a null decided_at when initially auto-approved.

type VillageShareEventActor added in v0.1.3

type VillageShareEventActor string

VillageShareEventActor is the actor class attached to one share event. It is an actor class, not a user identity.

const (
	VillageShareEventActorNone       VillageShareEventActor = ""
	VillageShareEventActorOwner      VillageShareEventActor = "owner"
	VillageShareEventActorCollective VillageShareEventActor = "collective"
	VillageShareEventActorModerator  VillageShareEventActor = "moderator"
)

func VillageContributionAttemptActor added in v0.31.0

func VillageContributionAttemptActor(status VillageShareStatus) (VillageShareEventActor, error)

VillageContributionAttemptActor returns the status's actor capacity, not a moderator identity or proof that manual review occurred. Initial automatic approval has moderator capacity even without a decision timestamp.

func (VillageShareEventActor) JSONSchema added in v0.1.3

type VillageShareStatus added in v0.1.3

type VillageShareStatus string

VillageShareStatus is the full share-attempt ledger status menu. Pending, approved, and rejected can appear in current projections; retracted and revoked are terminal states kept for the historical event ledger.

const (
	VillageShareStatusPending   VillageShareStatus = "pending"
	VillageShareStatusApproved  VillageShareStatus = "approved"
	VillageShareStatusRejected  VillageShareStatus = "rejected"
	VillageShareStatusRetracted VillageShareStatus = "retracted"
	VillageShareStatusRevoked   VillageShareStatus = "revoked"
)

func (VillageShareStatus) JSONSchema added in v0.1.3

func (VillageShareStatus) JSONSchema() (jsonschema.Schema, error)

type VillageShareTranscriptRequest added in v0.1.3

type VillageShareTranscriptRequest struct {
	GroupIDs []VillageUUID `json:"group_ids" nullable:"false"`
}

type VillageStatusResponse added in v0.1.3

type VillageStatusResponse struct {
	Status string `json:"status"`
}

type VillageTag added in v0.19.0

type VillageTag struct {
	ID   VillageUUID `json:"id"`
	Name string      `json:"name"`
}

type VillageTranscript added in v0.1.3

type VillageTranscript struct {
	ID                      TranscriptID                `json:"id"`
	OwnerID                 VillageUUID                 `json:"owner_id"`
	LocalID                 SessionID                   `json:"local_id"`
	Title                   *string                     `json:"title"`
	Description             *string                     `json:"description"`
	Visibility              VillageTranscriptVisibility `json:"visibility"`
	ModelProvider           string                      `json:"model_provider"`
	ModelName               *string                     `json:"model_name"`
	HarnessVersion          *string                     `json:"harness_version"`
	SessionStart            *time.Time                  `json:"session_start"`
	SessionEnd              *time.Time                  `json:"session_end"`
	TurnCount               *int32                      `json:"turn_count"`
	TokenCount              *int32                      `json:"token_count"`
	BlobSizeBytes           *int64                      `json:"blob_size_bytes"`
	SchemaVersion           string                      `json:"schema_version"`
	PublishedAt             time.Time                   `json:"published_at"`
	UpdatedAt               time.Time                   `json:"updated_at"`
	ParentSessionID         *SessionID                  `json:"parent_session_id"`
	IngestedAt              *time.Time                  `json:"ingested_at"`
	SourceFormat            *SourceFormat               `json:"source_format"`
	GitBranch               *string                     `json:"git_branch"`
	GitRemote               *string                     `json:"git_remote"`
	ProjectHash             ProjectHash                 `json:"project_hash"`
	ProjectName             *string                     `json:"project_name"`
	ProjectDisplayName      string                      `json:"project_display_name"`
	ProjectNameSource       VillageProjectNameSource    `json:"project_name_source"`
	ProjectRemoteLabel      string                      `json:"project_remote_label"`
	ToolCallCount           *int32                      `json:"tool_call_count"`
	SubagentCount           *int32                      `json:"subagent_count"`
	DurationMs              *int64                      `json:"duration_ms"`
	Subagents               *[]map[string]interface{}   `json:"subagents"`
	DiagnosticsWarnings     *[]string                   `json:"diagnostics_warnings"`
	DiagnosticsPartial      *bool                       `json:"diagnostics_partial"`
	TokensIn                *int64                      `json:"tokens_in"`
	TokensOut               *int64                      `json:"tokens_out"`
	TitleGenerated          *string                     `json:"title_generated"`
	Outcome                 *SessionOutcome             `json:"outcome"`
	FilesTouched            *int32                      `json:"files_touched"`
	LinesChanged            *int32                      `json:"lines_changed"`
	RetryLoops              *int32                      `json:"retry_loops"`
	RetryTokensWasted       *int32                      `json:"retry_tokens_wasted"`
	WithinSessionReverts    *int32                      `json:"within_session_reverts"`
	SignalDensity           *float32                    `json:"signal_density"`
	SpecQualityScore        *float32                    `json:"spec_quality_score"`
	ExplorationRatio        *float32                    `json:"exploration_ratio"`
	ScopeBreadth            *int32                      `json:"scope_breadth"`
	DiscoveryTurns          *int32                      `json:"discovery_turns"`
	M2TokenOutcomeRatio     *float32                    `json:"m2_token_outcome_ratio"`
	M3UniqueToolCount       *int32                      `json:"m3_unique_tool_count"`
	M4ErrorRecoveryCount    *int32                      `json:"m4_error_recovery_count"`
	M4ConsecutiveErrorMax   *int32                      `json:"m4_consecutive_error_max"`
	M5ContextUtilizationPct *float32                    `json:"m5_context_utilization_pct"`
	M5PeakContextTokens     *int32                      `json:"m5_peak_context_tokens"`
	M5AvgMessageTokens      *int32                      `json:"m5_avg_message_tokens"`
	M6OutputSurvivalPct     *float32                    `json:"m6_output_survival_pct"`
	M6LinesSurvived         *int32                      `json:"m6_lines_survived"`
	M6LinesTotal            *int32                      `json:"m6_lines_total"`
	M7SpecWordCount         *int32                      `json:"m7_spec_word_count"`
	M7SpecHasExamples       *bool                       `json:"m7_spec_has_examples"`
	M7SpecHasConstraints    *bool                       `json:"m7_spec_has_constraints"`
	ComputedAt              *time.Time                  `json:"computed_at"`
	ComputeVersion          *int32                      `json:"compute_version"`
	ContentHash             *TranscriptContentHash      `json:"content_hash"`
	LicenseID               *License                    `json:"license_id"`
	SessionOrigin           SessionOrigin               `json:"session_origin"`
	InputSubmissionCount    *int64                      `json:"input_submission_count,omitempty" minimum:"0" maximum:"9007199254740991" nullable:"false"`
	RootSessionID           *SessionID                  `json:"root_session_id,omitempty"`
	Purpose                 SessionPurpose              `json:"purpose,omitempty"`
	Relationships           []SessionRelationship       `json:"relationships,omitempty"`
}

VillageTranscript is the current transcript row projection used by Village web list and collective routes. Storage object keys and source-machine paths are not part of this public projection.

type VillageTranscriptAttestation added in v0.19.0

type VillageTranscriptAttestation struct {
	ID               VillageUUID  `json:"id"`
	TranscriptID     TranscriptID `json:"transcript_id"`
	OrgLogin         string       `json:"org_login"`
	AttestationType  string       `json:"attestation_type"`
	Note             *string      `json:"note"`
	CreatedAt        time.Time    `json:"created_at"`
	AttesterUsername string       `json:"attester_username"`
	AttesterAvatar   *string      `json:"attester_avatar"`
}

type VillageTranscriptCollective added in v0.1.3

type VillageTranscriptCollective struct {
	ID              VillageUUID `json:"id"`
	Name            string      `json:"name"`
	Description     *string     `json:"description"`
	LinkedGithubOrg *string     `json:"linked_github_org"`
	SharedAt        time.Time   `json:"shared_at"`
}

type VillageTranscriptCollectivesResponse added in v0.1.3

type VillageTranscriptCollectivesResponse struct {
	Collectives []VillageTranscriptCollective `json:"collectives" nullable:"false"`
}

type VillageTranscriptDeletionPolicy added in v0.1.3

type VillageTranscriptDeletionPolicy string

VillageTranscriptDeletionPolicy is the closed policy menu used when a member leaves a collective.

const (
	VillageTranscriptDeletionUserChoice VillageTranscriptDeletionPolicy = "user_choice"
	VillageTranscriptDeletionMandatory  VillageTranscriptDeletionPolicy = "mandatory"
)

func (VillageTranscriptDeletionPolicy) JSONSchema added in v0.1.3

type VillageTranscriptListResponse added in v0.19.0

type VillageTranscriptListResponse struct {
	Transcripts []VillageTranscriptListRow `json:"transcripts" nullable:"false"`
	Total       int                        `json:"total"`
	AgentTotal  int                        `json:"agent_total"`
	Page        int                        `json:"page"`
	Limit       int                        `json:"limit"`
}

func (VillageTranscriptListResponse) Validate added in v0.19.0

func (r VillageTranscriptListResponse) Validate() error

type VillageTranscriptListRow added in v0.19.0

type VillageTranscriptListRow struct {
	Transcript   VillageTranscript                  `json:"transcript"`
	Tags         []VillageTag                       `json:"tags" nullable:"false"`
	Owner        VillageUser                        `json:"owner"`
	OwnerOrgs    []VillageListUserOrganization      `json:"owner_orgs"`
	Shares       []VillageEnrichedTranscriptShare   `json:"shares"`
	Attestations []VillageListTranscriptAttestation `json:"attestations"`
	PullRequests VillagePullRequestsSummary         `json:"pull_requests"`
}

type VillageTranscriptMetadataResponse added in v0.19.0

type VillageTranscriptMetadataResponse struct {
	Transcript             VillageTranscript                 `json:"transcript"`
	Tags                   []VillageTag                      `json:"tags" nullable:"false"`
	Shares                 []VillageTranscriptShare          `json:"shares" nullable:"false"`
	EnrichedShares         []VillageEnrichedTranscriptShare  `json:"enriched_shares" nullable:"false"`
	Owner                  VillageUser                       `json:"owner"`
	OwnerOrgs              []VillageMetadataUserOrganization `json:"owner_orgs" nullable:"false"`
	Attestations           []VillageTranscriptAttestation    `json:"attestations" nullable:"false"`
	RelationshipNavigation []SessionRelationshipNavigation   `json:"relationshipNavigation,omitempty"`
}

VillageTranscriptMetadataResponse is the existing flat transcript metadata response plus viewer-authorized relationship navigation. Durable content remains separate on the content endpoint.

func (VillageTranscriptMetadataResponse) Validate added in v0.19.0

type VillageTranscriptPullRequest added in v0.25.0

type VillageTranscriptPullRequest struct {
	Owner   string                            `json:"owner" minLength:"1"`
	Name    string                            `json:"name" minLength:"1"`
	Number  int                               `json:"number" minimum:"1"`
	Title   *string                           `json:"title"`
	HeadRef *string                           `json:"head_ref"`
	State   VillagePullRequestAttachmentState `json:"state"`
}

VillageTranscriptPullRequest is one pull request that includes a transcript, for the transcript page's list. It names the pull request and carries its title and head branch when Village knows them. It is narrower than the attachment row on purpose: a reader of a transcript needs to recognize the pull request, not the attachment's internal bookkeeping.

func (VillageTranscriptPullRequest) Validate added in v0.25.0

func (p VillageTranscriptPullRequest) Validate() error

Validate checks the reference and the state. The read lists only attached and detached pull requests, so a pending request never reaches a reader.

type VillageTranscriptPullRequestsResponse added in v0.25.0

type VillageTranscriptPullRequestsResponse struct {
	PullRequests []VillageTranscriptPullRequest `json:"pull_requests" nullable:"false"`
}

VillageTranscriptPullRequestsResponse is the response of GET /api/v1/transcripts/{id}/pulls: the pull requests that include the transcript, attached or detached, that the caller may read. This is the visibility rule the pull request counts refer to: an attachment on a private repository is listed only to the pull request author, a member of the collective the attachment belongs to, or, for an attached attachment, a reader of the repository, and one whose visibility check cannot complete is omitted.

func (VillageTranscriptPullRequestsResponse) Validate added in v0.25.0

Validate checks each pull request and that each appears once.

type VillageTranscriptShare added in v0.1.3

type VillageTranscriptShare struct {
	GroupID   VillageUUID `json:"group_id"`
	GroupName string      `json:"group_name"`
	SharedAt  time.Time   `json:"shared_at"`
}

type VillageTranscriptVisibility added in v0.1.3

type VillageTranscriptVisibility string

VillageTranscriptVisibility is the current Village transcript visibility menu. It deliberately uses the Village token shared, not the publish-contract token group used by Visibility.

const (
	VillageTranscriptVisibilityPrivate VillageTranscriptVisibility = "private"
	VillageTranscriptVisibilityShared  VillageTranscriptVisibility = "shared"
	VillageTranscriptVisibilityPublic  VillageTranscriptVisibility = "public"
)

func (VillageTranscriptVisibility) JSONSchema added in v0.1.3

type VillageUUID added in v0.1.3

type VillageUUID string

VillageUUID is the canonical lowercase UUID string form the Village emits for users, collectives, repositories, and other server-owned rows.

func (VillageUUID) JSONSchema added in v0.1.3

func (VillageUUID) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (VillageUUID) String added in v0.1.3

func (id VillageUUID) String() string

type VillageUpdateCollectiveRequest added in v0.31.0

type VillageUpdateCollectiveRequest struct {
	Name                     string                          `json:"name,omitempty"`
	Description              string                          `json:"description,omitempty"`
	DataAccess               VillageGroupDataAccess          `json:"data_access,omitempty"`
	AcceptanceMode           VillageGroupAcceptanceMode      `json:"acceptance_mode,omitempty"`
	LinkedGithubOrg          *string                         `json:"linked_github_org,omitempty"`
	DisplayMembers           *bool                           `json:"display_members,omitempty"`
	TranscriptDeletionPolicy VillageTranscriptDeletionPolicy `json:"transcript_deletion_policy,omitempty"`
	PostPromptsCheck         *bool                           `json:"post_prompts_check,omitempty"`
	PromptsCheckMode         VillagePromptsCheckMode         `json:"prompts_check_mode,omitempty"`
}

VillageUpdateGroupRequest mirrors the current update handler. Name and description are decoded as strings and are written even when omitted, so a caller that wants to preserve them must send their current values.

type VillageUpdateGroupRequest deprecated added in v0.1.3

type VillageUpdateGroupRequest = VillageUpdateCollectiveRequest

Deprecated: use VillageUpdateCollectiveRequest.

type VillageUpdateUserSettingsRequest added in v0.17.0

type VillageUpdateUserSettingsRequest struct {
	PreviewBeforeAttach    *bool `json:"preview_before_attach,omitempty"`
	AutoAttachPullRequests *bool `json:"auto_attach_pull_requests,omitempty"`
}

VillageUpdateUserSettingsRequest patches the caller's settings. An omitted field is left unchanged.

type VillageUser added in v0.19.0

type VillageUser struct {
	ID               VillageUUID `json:"id"`
	GithubID         int64       `json:"github_id"`
	GithubUsername   string      `json:"github_username"`
	DisplayName      *string     `json:"display_name"`
	AvatarURL        *string     `json:"avatar_url"`
	CreatedAt        time.Time   `json:"created_at"`
	UpdatedAt        time.Time   `json:"updated_at"`
	IsDiscoverable   bool        `json:"is_discoverable"`
	Provider         string      `json:"provider"`
	ProviderUserID   string      `json:"provider_user_id"`
	UsernameChosen   bool        `json:"username_chosen"`
	ProviderUsername *string     `json:"provider_username"`
}

type VillageUserCollective added in v0.31.0

type VillageUserCollective struct {
	ID                       VillageUUID                     `json:"id"`
	Name                     string                          `json:"name"`
	Description              *string                         `json:"description"`
	CreatedBy                VillageUUID                     `json:"created_by"`
	CreatedAt                time.Time                       `json:"created_at"`
	UpdatedAt                time.Time                       `json:"updated_at"`
	AcceptanceMode           VillageGroupAcceptanceMode      `json:"acceptance_mode"`
	DataAccess               VillageGroupDataAccess          `json:"data_access"`
	LinkedGithubOrg          *string                         `json:"linked_github_org"`
	DisplayMembers           bool                            `json:"display_members"`
	TranscriptDeletionPolicy VillageTranscriptDeletionPolicy `json:"transcript_deletion_policy"`
	Role                     VillageGroupRole                `json:"role"`
	MemberSince              time.Time                       `json:"member_since"`
	MemberCount              int32                           `json:"member_count"`
	TranscriptCount          int32                           `json:"transcript_count"`
}

VillageUserGroup is one collective the signed-in caller belongs to.

type VillageUserCollectiveShare added in v0.31.0

type VillageUserCollectiveShare struct {
	ID              TranscriptID                `json:"id"`
	Title           *string                     `json:"title"`
	ModelProvider   string                      `json:"model_provider"`
	ModelName       *string                     `json:"model_name"`
	Visibility      VillageTranscriptVisibility `json:"visibility"`
	PublishedAt     time.Time                   `json:"published_at"`
	TurnCount       *int32                      `json:"turn_count"`
	TokensIn        *int64                      `json:"tokens_in"`
	TokensOut       *int64                      `json:"tokens_out"`
	OwnerID         VillageUUID                 `json:"owner_id"`
	LocalID         SessionID                   `json:"local_id"`
	ParentSessionID *SessionID                  `json:"parent_session_id"`
	// Status uses the shared lifecycle enum. Current my-shares responses emit the
	// live subset today; terminal values are reserved for ledger history.
	Status               VillageShareStatus    `json:"status"`
	SharedAt             time.Time             `json:"shared_at"`
	InputSubmissionCount *int64                `json:"input_submission_count,omitempty" minimum:"0" maximum:"9007199254740991" nullable:"false"`
	RootSessionID        *SessionID            `json:"root_session_id,omitempty"`
	Purpose              SessionPurpose        `json:"purpose,omitempty"`
	Relationships        []SessionRelationship `json:"relationships,omitempty"`
}

type VillageUserGroup deprecated added in v0.1.3

type VillageUserGroup = VillageUserCollective

Deprecated: use VillageUserCollective.

type VillageUserGroupShare deprecated added in v0.1.3

type VillageUserGroupShare = VillageUserCollectiveShare

Deprecated: use VillageUserCollectiveShare.

type VillageUserSettings added in v0.17.0

type VillageUserSettings struct {
	PreviewBeforeAttach    bool `json:"preview_before_attach"`
	AutoAttachPullRequests bool `json:"auto_attach_pull_requests"`
}

VillageUserSettings is the caller's own settings surface. AutoAttachPullRequests is the caller's choice to link their own transcripts to a pull request automatically when it opens in a repository one of their collectives links. It is off by default and never changes who can read a transcript.

type VillageUserStats added in v0.25.0

type VillageUserStats struct {
	TotalTranscripts int32 `json:"total_transcripts" minimum:"0"`
	TotalTurns       int64 `json:"total_turns" minimum:"0"`
	TotalDurationMs  int64 `json:"total_duration_ms" minimum:"0"`
	TotalTokens      int64 `json:"total_tokens" minimum:"0"`
	PullRequestCount int32 `json:"pull_request_count" minimum:"0"`
}

VillageUserStats is the response of GET /api/v1/users/me/stats: totals over every transcript the caller published. PullRequestCount counts the distinct pull requests whose attachment is in state attached, includes one of those transcripts, and that the caller may read under the visibility rule of VillageTranscriptPullRequestsResponse, failing closed; detached pull requests are not counted.

func (VillageUserStats) Validate added in v0.25.0

func (s VillageUserStats) Validate() error

Validate checks that every total is nonnegative.

type VillageVisibleCollective added in v0.31.0

type VillageVisibleCollective struct {
	ID                       VillageUUID                     `json:"id"`
	Name                     string                          `json:"name"`
	Description              *string                         `json:"description"`
	CreatedBy                VillageUUID                     `json:"created_by"`
	CreatedAt                time.Time                       `json:"created_at"`
	UpdatedAt                time.Time                       `json:"updated_at"`
	AcceptanceMode           VillageGroupAcceptanceMode      `json:"acceptance_mode"`
	DataAccess               VillageGroupDataAccess          `json:"data_access"`
	LinkedGithubOrg          *string                         `json:"linked_github_org"`
	DisplayMembers           bool                            `json:"display_members"`
	TranscriptDeletionPolicy VillageTranscriptDeletionPolicy `json:"transcript_deletion_policy"`
	Role                     *VillageGroupRole               `json:"role"`
	MemberSince              *time.Time                      `json:"member_since"`
	MemberCount              int32                           `json:"member_count"`
	TranscriptCount          int32                           `json:"transcript_count"`
}

VillageVisibleGroup is one collective the signed-in caller may see. Role and member_since are null when the caller can see the collective but is not a member.

type VillageVisibleGroup deprecated added in v0.1.3

type VillageVisibleGroup = VillageVisibleCollective

Deprecated: use VillageVisibleCollective.

type Visibility

type Visibility string

Visibility controls who can access a published transcript.

const (
	VisibilityPrivate Visibility = "private"
	VisibilityGroup   Visibility = "group"
	VisibilityPublic  Visibility = "public"
)

func (Visibility) IsValid

func (v Visibility) IsValid() bool

IsValid returns true if the visibility is one of the known variants.

func (Visibility) JSONSchema

func (Visibility) JSONSchema() (jsonschema.Schema, error)

JSONSchema implements jsonschema.Exposer.

func (Visibility) String

func (v Visibility) String() string

type VisibilityIntent

type VisibilityIntent string

VisibilityIntent is the private-before-replacement visibility intent. Public intent never widens access during publish; widening is a separate owner update.

const (
	VisibilityIntentPrivate VisibilityIntent = "private"
	VisibilityIntentPublic  VisibilityIntent = "public"
)

func (VisibilityIntent) IsValid

func (v VisibilityIntent) IsValid() bool

func (VisibilityIntent) JSONSchema

func (v VisibilityIntent) JSONSchema() (jsonschema.Schema, error)

type WalkthroughStep

type WalkthroughStep struct {
	File    string `json:"file"`
	Line    *int   `json:"line,omitempty"`
	Excerpt string `json:"excerpt"`
}

WalkthroughStep is a single file visit in a session trail.

type WalkthroughTrail

type WalkthroughTrail struct {
	SessionID  string            `json:"sessionId"`
	Title      string            `json:"title"`
	Date       string            `json:"date"`
	TurnCount  int               `json:"turnCount"`
	Steps      []WalkthroughStep `json:"steps"`
	IsCoherent bool              `json:"isCoherent"` // true if linear path, false if scattered
}

WalkthroughTrail is the file path extracted from a single session.

Directories

Path Synopsis
cmd
gen-enum-corpora command
Command gen-enum-corpora writes the Local API 0.5.0 enum-exhaustion corpora to their committed artifacts.
Command gen-enum-corpora writes the Local API 0.5.0 enum-exhaustion corpora to their committed artifacts.
gen-license-corpus command
Command gen-license-corpus writes the enum-exhaustion license corpus to the committed artifact.
Command gen-license-corpus writes the enum-exhaustion license corpus to the committed artifact.
release-guard command
Command release-guard is the thin CLI the release workflows shell out to.
Command release-guard is the thin CLI the release workflows shell out to.
schema-gen command
Package enumcorpus generates the enum-exhaustion test corpora for the Local API 0.5.0 git+session timeline and insight-first code map closed sets (AssociationConclusion, AssociationEvidenceKind, Confidence, RewriteResolution, RewriteMethod, InsightKind, InsightProvenance, ReadAttributionState, ReadStateGrade) plus a regenerated TargetKind corpus (the file_version member added in the same tag).
Package enumcorpus generates the enum-exhaustion test corpora for the Local API 0.5.0 git+session timeline and insight-first code map closed sets (AssociationConclusion, AssociationEvidenceKind, Confidence, RewriteResolution, RewriteMethod, InsightKind, InsightProvenance, ReadAttributionState, ReadStateGrade) plus a regenerated TargetKind corpus (the file_version member added in the same tag).
internal
contractgates
Package contractgates holds the SYNTHETIC-BREAK tests for the schema repo's breaking-change contract gates: oasdiff for the OpenAPI specs and go-apidiff for the exported Go API.
Package contractgates holds the SYNTHETIC-BREAK tests for the schema repo's breaking-change contract gates: oasdiff for the OpenAPI specs and go-apidiff for the exported Go API.
release
Package release holds the pure, table-driven-testable logic that the release CI workflows depend on: the release-PR title grammar, the git-tag grammar, the typed release-kind derivation, and release workflow policy checks.
Package release holds the pure, table-driven-testable logic that the release CI workflows depend on: the release-PR title grammar, the git-tag grammar, the typed release-kind derivation, and release workflow policy checks.
Package licensecorpus generates the enum-exhaustion test corpus for the closed license menu (schema.AllLicenses).
Package licensecorpus generates the enum-exhaustion test corpus for the closed license menu (schema.AllLicenses).
Package openapi builds the committed OpenAPI 3.1 / JSON-Schema artifacts from the Go schema source.
Package openapi builds the committed OpenAPI 3.1 / JSON-Schema artifacts from the Go schema source.
Package testcase is the pure-data foundation for this module's canonical test-case corpus: a typed, generic Case/Corpus model with closed-set classification and provenance metadata, a pure YAML loader, and pure validators.
Package testcase is the pure-data foundation for this module's canonical test-case corpus: a typed, generic Case/Corpus model with closed-set classification and provenance metadata, a pure YAML loader, and pure validators.
assert
Package assert is the testing seam for the test-case corpus: helpers that take *testing.T and fail a test when a corpus violates its own invariants.
Package assert is the testing seam for the test-case corpus: helpers that take *testing.T and fail a test when a corpus violates its own invariants.

Jump to

Keyboard shortcuts

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