apicontract

package
v0.36.1 Latest Latest
Warning

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

Go to latest
Published: Sep 15, 2026 License: MIT Imports: 17 Imported by: 0

Documentation

Overview

Package apicontract holds the Go types for every shared JSON type and envelope in the core-investigation-loop Feature's normative transport appendix (spec/features/core-investigation-loop/api-contract.md, hub datatug/datatug), with the exact json:"..." field names that document declares - the schema authority datatug-cli (server) and datatug-apps (client) consume, per Phase 1 corrective Task 12.

Every type's Validate method enforces the appendix's own stated rules - required fields, closed enums, cross-field pairings, canonical string forms - so a value that unmarshals successfully but violates the contract is still caught before it crosses a trust boundary. TypedValue and Scope's carrying types additionally reject unknown fields, duplicate JSON keys and (via DecodeStrict) explicitly named security-relevant fields such as a client-supplied principal or role.

pkg/apicontract/fixtures holds the frozen JSON fixtures generated from these types - one file per envelope/error case the appendix's "Acceptance and migration" section requires coverage for.

Every POST endpoint in the appendix's "Endpoint table" has a request envelope type here: ExecutionRequest (exec/run_query), ApplicableRequest (queries/applicable), RelatedRequest (semantic/related) and RelatedRowsRequest (semantic/related/rows). Each flattens its Scope fields (project/environment/securityContextId) into its own top level, never nesting them under a "scope" key - confirmed against the live server (Task 12 lane S77).

Index

Constants

View Source
const (
	BindingOriginSelection = "selection"
	BindingOriginContext   = "context"
	BindingOriginManual    = "manual"
	BindingOriginDefault   = "default"
)
View Source
const (
	BindingOriginEvidenceServerDefault  = "server-default"
	BindingOriginEvidenceClientReported = "client-reported"
)
View Source
const (
	CandidateStateRunnable          = "runnable"
	CandidateStateNeedsInput        = "needs-input"
	CandidateStateNeedsTarget       = "needs-target"
	CandidateStateSourceUnavailable = "source-unavailable"
)
View Source
const (
	CompareSideScope  CompareSideKind = "scope"
	CompareSideFacts  CompareSideKind = "facts"
	CompareSideRecord CompareSideKind = "record"

	CompareCohortAffected = "affected"
	// CompareCohortControl is deliberately distinct from incidents.FactRoleHealthyControl.
	// The service maps this public spelling to the internal incident role.
	CompareCohortControl = "control"

	CompareColumnLeft  = "left"
	CompareColumnRight = "right"

	CompareDefaultLimit              = 100
	CompareMaximumLimit              = 500
	CompareDistributionMaximumValues = 50
)
View Source
const (
	MeasurementAggregateFirst    = "first"
	MeasurementAggregateSum      = "sum"
	MeasurementAggregateMin      = "min"
	MeasurementAggregateMax      = "max"
	MeasurementAggregateAvg      = "avg"
	MeasurementAggregateCount    = "count"
	MeasurementAggregateRowCount = "rowCount"
)
View Source
const (
	MeasurementComplete    = "complete"
	MeasurementUnavailable = "unavailable"

	MeasurementReasonNoRows        = "no-rows"
	MeasurementReasonNonNumeric    = "non-numeric"
	MeasurementReasonPolicyLimited = "policy-limited"
	MeasurementReasonTruncated     = "truncated"
	MeasurementReasonSourceRefused = "source-refused"
)
View Source
const (
	SnapshotAvailable = "available"
	SnapshotExpired   = "expired"
	SnapshotDeleted   = "deleted"
)
View Source
const (
	FactOriginSelection = investigation.FactOriginSelection
	FactOriginContext   = investigation.FactOriginContext
	FactOriginManual    = investigation.FactOriginManual

	FactRoleAffected       = investigation.FactRoleAffected
	FactRoleHealthyControl = investigation.FactRoleHealthyControl
	FactRoleSuspected      = investigation.FactRoleSuspected
	FactRoleExcluded       = investigation.FactRoleExcluded
	FactRoleRecovered      = investigation.FactRoleRecovered
	FactLayerCanonical     = investigation.FactLayerCanonical

	FactMappingDeclared = investigation.FactMappingDeclared
	FactMappingInferred = investigation.FactMappingInferred

	FactConditionEqual              = investigation.FactConditionEqual
	FactConditionNotEqual           = investigation.FactConditionNotEqual
	FactConditionGreaterThan        = investigation.FactConditionGreaterThan
	FactConditionGreaterThanOrEqual = investigation.FactConditionGreaterThanOrEqual
	FactConditionLessThan           = investigation.FactConditionLessThan
	FactConditionLessThanOrEqual    = investigation.FactConditionLessThanOrEqual
)
View Source
const (
	SemanticProvenanceDeclared = "declared"
	SemanticProvenanceInferred = "inferred"
)
View Source
const (
	ProvenanceModeLive     = "live"
	ProvenanceModeSnapshot = "snapshot"
)
View Source
const (
	ExecutionProfileProtected        = "protected"
	ExecutionProfileOpaquePrivileged = "opaque-privileged"
)
View Source
const (
	ValueTypeString   = investigation.ValueTypeString
	ValueTypeNumber   = investigation.ValueTypeNumber
	ValueTypeInteger  = investigation.ValueTypeInteger
	ValueTypeDecimal  = investigation.ValueTypeDecimal
	ValueTypeBoolean  = investigation.ValueTypeBoolean
	ValueTypeDate     = investigation.ValueTypeDate
	ValueTypeDatetime = investigation.ValueTypeDatetime
	ValueTypeNull     = investigation.ValueTypeNull
)
View Source
const (
	ValueTypeSet = "set"
)

Variables

This section is empty.

Functions

func CanonicalQueryID added in v0.28.1

func CanonicalQueryID(folderPath, id string) string

CanonicalQueryID returns the folder-qualified query ID for a query with bare id under folderPath ("" for the queries root).

func CompareTypedKeys added in v0.36.0

func CompareTypedKeys(left, right []TypedValue) (int, error)

CompareTypedKeys implements the portable natural order for typed composite keys. Components must have matching types. Numbers, integers and decimals sort numerically; booleans false before true; dates and datetimes chronologically; and strings by UTF-8 bytes (binary collation).

Decimal and datetime representations that denote the same value retain a deterministic text tie-break, because TypedValue equality preserves their exact canonical transport spelling.

func DecodeStrict

func DecodeStrict(data []byte, v any, forbidden ...string) error

DecodeStrict decodes data into v with no leniency: unknown JSON fields are rejected (encoding/json's DisallowUnknownFields), duplicate keys at any nesting level are rejected (encoding/json silently keeps only the last occurrence otherwise - the appendix requires duplicate JSON keys to be "rejected, never reconciled by precedence") - including two spellings of one struct field that differ only in case ("project" and "Project"), which encoding/json matches to the same field - trailing data after the JSON value is rejected, and any field name listed in forbidden is rejected even when the target type has no field for it - the same "client-supplied principal or role are rejected" rule the appendix states, made explicit at every call site that carries security-relevant identity.

func FingerprintRecordset added in v0.30.0

func FingerprintRecordset(recordset Recordset) (string, error)

FingerprintRecordset returns a lowercase SHA-256 digest over the approved canonical JSON shape. Validation occurs before encoding. Nil and empty arrays normalize identically without changing column or row order.

func TypedKeySortKey added in v0.36.0

func TypedKeySortKey(values []TypedValue) (string, error)

TypedKeySortKey returns a stable string whose binary lexical order is the same as CompareTypedKeys. It is suitable for ordered-stream record IDs and opaque local-cache pagination keys. Callers must use binary rather than locale collation when ordering it.

func TypedValueSortKey added in v0.36.0

func TypedValueSortKey(value TypedValue) (string, error)

TypedValueSortKey returns the binary-sortable encoding for a value that is not necessarily a key. Null sorts before every non-null value. This is used by typed distributions, whose column may contain null cells.

Types

type AgentCapabilities

type AgentCapabilities struct {
	ProtectedQueries bool `json:"protectedQueries"`
	OpaqueReadOnly   bool `json:"opaqueReadOnly"`
}

AgentCapabilities reports what the session may do - never what it did; Result.Provenance.ExecutionProfile reports the actual executor used for a given run, "even a privileged principal running protected DTQL still receives protected provenance".

type AgentInfo

type AgentInfo struct {
	Version           string            `json:"version"`
	Principal         AgentPrincipal    `json:"principal"`
	SecurityContextID string            `json:"securityContextId"`
	Projects          []AgentProjectRef `json:"projects"`
	Capabilities      AgentCapabilities `json:"capabilities"`
}

AgentInfo is the exact success envelope of GET agent-info. api-contract.md "Endpoint table".

func (AgentInfo) Validate

func (a AgentInfo) Validate() error

Validate enforces Version and SecurityContextID are required, Principal is itself valid, and every Projects entry is itself valid.

type AgentPrincipal

type AgentPrincipal struct {
	ID     string   `json:"id"`
	Roles  []string `json:"roles"`
	Groups []string `json:"groups"`
}

AgentPrincipal is the effective identity agent-info reports - never the role inferred from a name; the server states it explicitly.

func (AgentPrincipal) Validate

func (p AgentPrincipal) Validate() error

type AgentProjectRef

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

AgentProjectRef is one project agent-info reports as registered.

func (AgentProjectRef) Validate

func (r AgentProjectRef) Validate() error

type Ambiguous

type Ambiguous struct {
	ParameterID string   `json:"parameterId"`
	FactIDs     []string `json:"factIds"`
}

Ambiguous names a parameter with more than one distinct candidate value within the highest eligible automatic binding tier.

func (Ambiguous) Validate

func (a Ambiguous) Validate() error

type ApplicableRequest added in v0.27.0

type ApplicableRequest struct {
	Project           string `json:"project"`
	Environment       string `json:"environment"`
	SecurityContextID string `json:"securityContextId"`
	Values            []Fact `json:"values"`
}

ApplicableRequest is POST queries/applicable's request body: "Scope + {values:Fact[]}" - api-contract.md "Endpoint table". Scope's three fields are flattened into the top level of the JSON body, exactly like ExecutionRequest, never nested under a "scope" key - confirmed against the live server (Task 12 lane S77).

func (ApplicableRequest) Validate added in v0.27.0

func (r ApplicableRequest) Validate() error

Validate enforces Project/Environment/SecurityContextID are required (the same Scope invariants every scoped call carries - api-contract.md "Scope and identity") and every Values entry is itself valid. An empty Values list is legitimate: a caller with no known facts still gets back every query's notYet candidate.

type ApplicableResponse

type ApplicableResponse struct {
	Applicable []Candidate `json:"applicable"`
	NotYet     []Candidate `json:"notYet"`
}

ApplicableResponse is the exact success envelope of POST queries/applicable. "applicable contains only runnable candidates. notYet contains authorized query metadata for needs-input/needs-target/ source-unavailable candidates... Candidates sort by queryId for deterministic tests." api-contract.md "Endpoint table".

func (ApplicableResponse) Validate

func (r ApplicableResponse) Validate() error

Validate enforces every candidate is itself valid, every Applicable entry has State "runnable", every NotYet entry does not, and both slices are sorted by QueryID.

type Binding

type Binding struct {
	ParameterID    string          `json:"parameterId"`
	Value          TypedValueOrSet `json:"value"`
	Origin         string          `json:"origin"`         // selection | context | manual | default
	OriginEvidence string          `json:"originEvidence"` // server-default | client-reported
	FactID         string          `json:"factId,omitempty"`
	ValueFactIDs   [][]string      `json:"valueFactIds,omitempty"`
}

Binding is one parameter's resolved value and its provenance. Returned bindings are execution-confirmed; a selection/context/manual origin's OriginEvidence remains explicitly "client-reported", never presented as server-attested; "server-default" is used only when a declared default was validated against the query definition. api-contract.md "Shared JSON types" / "Endpoint table".

func (Binding) Validate

func (b Binding) Validate() error

Validate enforces ParameterID is required, Value is itself valid, Origin and OriginEvidence are each one of their closed sets, and the two pair correctly: Origin "default" only with OriginEvidence "server-default", every other Origin only with "client-reported" - "The UI must not present client origins as server-attested provenance."

type BindingOriginEntry

type BindingOriginEntry struct {
	ParameterID  string     `json:"parameterId"`
	Origin       string     `json:"origin"` // selection | context | manual | default
	FactID       string     `json:"factId,omitempty"`
	ValueFactIDs [][]string `json:"valueFactIds,omitempty"`
}

BindingOriginEntry supplies display provenance for one submitted parameter - "never influences authorization". api-contract.md "Endpoint table".

func (BindingOriginEntry) Validate

func (e BindingOriginEntry) Validate() error

type Candidate

type Candidate struct {
	QueryID string            `json:"queryId"`
	Targets []CandidateTarget `json:"targets"`
	// SelectedSource is present only when exactly one eligible target
	// remains - "present only when one eligible target remains".
	SelectedSource string      `json:"selectedSource,omitempty"`
	Bindings       []Binding   `json:"bindings"`
	Chain          []ChainStep `json:"chain"`
	Missing        []string    `json:"missing"`
	Ambiguous      []Ambiguous `json:"ambiguous"`
	State          string      `json:"state"`
}

Candidate is one query's runnability against the caller's current facts: its authorized eligible targets, the bindings/chain it would apply, what is still missing or ambiguous, and its overall State. api-contract.md "Endpoint table".

func (Candidate) Validate

func (c Candidate) Validate() error

Validate enforces QueryID is required, every Target/Binding/ChainStep/ Ambiguous entry is itself valid, SelectedSource is set only when there is exactly one Target, and State is one of the closed set.

type CandidateTarget

type CandidateTarget struct {
	Source string `json:"source"`
	Label  string `json:"label"`
}

CandidateTarget is one authorized eligible source a saved query could run against.

func (CandidateTarget) Validate

func (t CandidateTarget) Validate() error

type CaptureBindingOrigin added in v0.28.1

type CaptureBindingOrigin struct {
	ParameterID string `json:"parameterId"`
	Origin      string `json:"origin"` // selection | context | manual
}

CaptureBindingOrigin records how one parameter was bound while the user explored. It is client-reported provenance, never server-attested, and carries no value and no fact ID.

func (CaptureBindingOrigin) Validate added in v0.28.1

func (b CaptureBindingOrigin) Validate() error

Validate enforces a required ParameterID and an origin of selection, context or manual - a default value is never captured, so "default" is not a capture origin.

type CaptureProvenance added in v0.28.1

type CaptureProvenance struct {
	// Author is the serving principal; omitted when the server runs with no
	// identified principal.
	Author string `json:"author,omitempty"`
	// Environment is the environment the source was resolved in.
	Environment string `json:"environment"`
	// Collection is the collection the query reads, derived from the DTQL.
	Collection string `json:"collection"`
}

CaptureProvenance is what the server itself recorded about a capture.

type CaptureQueryRequest added in v0.28.1

type CaptureQueryRequest struct {
	Project           string        `json:"project"`
	Environment       string        `json:"environment"`
	SecurityContextID string        `json:"securityContextId"`
	IfNoneMatch       bool          `json:"ifNoneMatch,omitempty"`
	IfMatch           string        `json:"ifMatch,omitempty"`
	Query             CapturedQuery `json:"query"`
}

CaptureQueryRequest is POST queries/capture's request body. Like every other POST envelope here it flattens Scope into its own top level.

func (CaptureQueryRequest) Validate added in v0.28.1

func (r CaptureQueryRequest) Validate() error

Validate enforces Scope's required fields, exactly one of IfNoneMatch or IfMatch, and the query's own rules (CapturedQuery.Validate), reporting a query field as "query.<field>".

type CaptureQueryResponse added in v0.28.1

type CaptureQueryResponse struct {
	// QueryID is the stored query's canonical, folder-qualified ID
	// (CanonicalQueryID) - the queryId exec/run_query and
	// queries/applicable use.
	QueryID string `json:"queryId"`
	// Revision identifies the stored bytes; send it back as IfMatch to
	// replace this exact revision. Opaque: compare for equality only.
	Revision   string            `json:"revision"`
	Query      CapturedQuery     `json:"query"`
	Provenance CaptureProvenance `json:"provenance"`
}

CaptureQueryResponse is POST queries/capture's success envelope, sent only after the store has persisted the pair.

func (CaptureQueryResponse) Validate added in v0.28.1

func (r CaptureQueryResponse) Validate() error

Validate enforces QueryID and Revision are present, QueryID is the query's own canonical ID, the query is itself valid and the provenance names its environment and collection.

type CapturedParameter added in v0.28.1

type CapturedParameter struct {
	ID         string          `json:"id"`
	Type       string          `json:"type"` // string | number | integer | decimal | boolean | date | datetime
	Title      string          `json:"title,omitempty"`
	IsRequired bool            `json:"isRequired"`
	Meta       *EntityFieldRef `json:"meta,omitempty"`
}

CapturedParameter is one typed parameter of a captured query. It has no default value: a captured default would persist a possibly protected value into git-tracked project files.

func (CapturedParameter) Validate added in v0.28.1

func (p CapturedParameter) Validate() error

Validate enforces a required ID, a type from the closed set and, when Meta is present, both its entity and field.

type CapturedQuery added in v0.28.1

type CapturedQuery struct {
	// FolderPath is the "/"-separated folder under the project's queries/
	// root; "" is the root itself.
	FolderPath string `json:"folderPath"`
	// ID is the query's bare ID: one file-name segment.
	ID      string `json:"id"`
	Title   string `json:"title"`
	Purpose string `json:"purpose"`
	// Source is the stable project-local source ID (SourceRef.source) the
	// captured lookup read; the server resolves it through the project
	// registry and binds the saved query to it.
	Source string `json:"source"`
	// DTQL is the query text persisted as "<id>.query.dtql".
	DTQL           string                 `json:"dtql"`
	Parameters     []CapturedParameter    `json:"parameters"`
	BindingOrigins []CaptureBindingOrigin `json:"bindingOrigins"`
}

CapturedQuery is the persisted definition of a captured query, as the client submits it and as the server returns it once stored.

func (CapturedQuery) Validate added in v0.28.1

func (q CapturedQuery) Validate() error

Validate enforces the shape rules both server and client apply: ID is one path segment and FolderPath is "" or "/"-separated segments, none empty, "." or ".." and none holding a backslash or NUL (the server applies its stricter file-name rules on top); Title, Purpose, Source and DTQL are required; every parameter has a unique ID, a type from the closed set and, when present, a complete Meta; every binding origin names a declared parameter at most once with origin selection, context or manual.

type ChainStep

type ChainStep struct {
	ParameterID  string     `json:"parameterId"`
	FactID       string     `json:"factId,omitempty"`
	ValueFactIDs [][]string `json:"valueFactIds,omitempty"`
	Explanation  string     `json:"explanation"`
}

ChainStep explains, per parameter, how its value was (or would be) derived - declared, inferred or manual - distinctly. "a missing parameter still has an explanation."

func (ChainStep) Validate

func (c ChainStep) Validate() error

type Column

type Column struct {
	Name string `json:"name"`
	Type string `json:"type"`
}

Column names one recordset column and its declared type.

func (Column) Validate

func (c Column) Validate() error

type CompareChangedRow added in v0.34.0

type CompareChangedRow struct {
	Key     []TypedValue          `json:"key"`
	Columns []CompareColumnChange `json:"columns"`
}

type CompareColumnChange added in v0.34.0

type CompareColumnChange struct {
	Column string     `json:"column"`
	Left   TypedValue `json:"left"`
	Right  TypedValue `json:"right"`
}

type CompareDistribution added in v0.34.0

type CompareDistribution struct {
	Column    string                     `json:"column"`
	Values    []CompareDistributionValue `json:"values"`
	Truncated bool                       `json:"truncated"`
}

type CompareDistributionSide added in v0.34.0

type CompareDistributionSide struct {
	Count int     `json:"count"`
	Pct   float64 `json:"pct"`
}

type CompareDistributionValue added in v0.34.0

type CompareDistributionValue struct {
	Value TypedValue              `json:"value"`
	Left  CompareDistributionSide `json:"left"`
	Right CompareDistributionSide `json:"right"`
	Ratio *float64                `json:"ratio"`
}

type CompareErrorResponse added in v0.34.0

type CompareErrorResponse struct {
	Error      ErrorBody                `json:"error"`
	Left       *CompareSideReceipt      `json:"left,omitempty"`
	Right      *CompareSideReceipt      `json:"right,omitempty"`
	Comparison *incidents.ComparisonRef `json:"comparison,omitempty"`
}

CompareErrorResponse preserves successfully persisted live-side receipts when comparison is incomplete. Comparison identifies an already-applied incident mutation; it does not imply a cached CompareResult exists.

func (CompareErrorResponse) Validate added in v0.34.0

func (r CompareErrorResponse) Validate() error

type CompareOneSidedColumn added in v0.34.0

type CompareOneSidedColumn struct {
	Column string `json:"column"`
	Side   string `json:"side"`
}

type CompareRequest added in v0.34.0

type CompareRequest struct {
	SecurityContextID  string          `json:"securityContextId"`
	QueryID            string          `json:"queryId"`
	Left               CompareSideSpec `json:"left"`
	Right              CompareSideSpec `json:"right"`
	Incident           *IncidentRef    `json:"incident,omitempty"`
	Key                []string        `json:"key,omitempty"`
	DistributionColumn string          `json:"distributionColumn,omitempty"`
	Limit              *int            `json:"limit,omitempty"`
	MutationID         string          `json:"mutationId,omitempty"`
}

func (CompareRequest) Validate added in v0.34.0

func (r CompareRequest) Validate() error

type CompareResult added in v0.34.0

type CompareResult struct {
	Left          CompareSideReceipt   `json:"left"`
	Right         CompareSideReceipt   `json:"right"`
	Columns       []Column             `json:"columns"`
	Key           []string             `json:"key"`
	Added         []CompareRow         `json:"added"`
	Removed       []CompareRow         `json:"removed"`
	Changed       []CompareChangedRow  `json:"changed"`
	Summary       CompareSummary       `json:"summary"`
	Distribution  *CompareDistribution `json:"distribution,omitempty"`
	PolicyLimited bool                 `json:"policyLimited"`
	Truncated     bool                 `json:"truncated"`
}

func (CompareResult) Validate added in v0.34.0

func (r CompareResult) Validate() error

type CompareRow added in v0.34.0

type CompareRow struct {
	Key []TypedValue `json:"key"`
	Row []TypedValue `json:"row"`
}

type CompareSideKind added in v0.34.0

type CompareSideKind string

type CompareSideReceipt added in v0.34.0

type CompareSideReceipt struct {
	Execution    ExecutionRef `json:"execution"`
	ExecutedAt   string       `json:"executedAt"`
	RowCount     int          `json:"rowCount"`
	Limitations  []Limitation `json:"limitations"`
	Reproducible bool         `json:"reproducible"`
}

func (CompareSideReceipt) Validate added in v0.34.0

func (r CompareSideReceipt) Validate() error

type CompareSideSpec added in v0.34.0

type CompareSideSpec struct {
	Kind        CompareSideKind       `json:"kind"`
	StoreID     string                `json:"storeId,omitempty"`
	Project     string                `json:"project,omitempty"`
	Environment string                `json:"environment,omitempty"`
	Parameters  map[string]TypedValue `json:"parameters,omitempty"`
	CohortRole  string                `json:"cohortRole,omitempty"`
	Execution   *ExecutionRef         `json:"execution,omitempty"`
}

CompareSideSpec is a strict, flattened discriminated union. Each kind accepts only its own fields: scope parameters, an incident-bound cohort, or a record.

func (*CompareSideSpec) UnmarshalJSON added in v0.34.0

func (s *CompareSideSpec) UnmarshalJSON(data []byte) error

func (CompareSideSpec) Validate added in v0.34.0

func (s CompareSideSpec) Validate() error

type CompareSummary added in v0.34.0

type CompareSummary struct {
	Added                int                     `json:"added"`
	Removed              int                     `json:"removed"`
	Changed              int                     `json:"changed"`
	Unchanged            int                     `json:"unchanged"`
	ColumnsOnlyOnOneSide []CompareOneSidedColumn `json:"columnsOnlyOnOneSide"`
}

type EntityFieldRef added in v0.28.1

type EntityFieldRef struct {
	Entity string `json:"entity"`
	Field  string `json:"field"`
}

EntityFieldRef is a semantic parameter's declaration that it requires a value of one entity field ("requires Customer.ID") - datatug-core's ParameterDef.Meta on the wire.

type ErrorBody

type ErrorBody struct {
	Code      string         `json:"code"`
	Message   string         `json:"message"`
	Field     string         `json:"field,omitempty"`
	RequestID string         `json:"requestId"`
	Targets   []TargetOption `json:"targets,omitempty"`
}

ErrorBody is the exact shape of every error's "error" field. "Messages and IDs must not reveal protected values or credentials. Tests assert both status and code, not English wording." api-contract.md "Security and errors".

func (ErrorBody) Validate

func (e ErrorBody) Validate() error

Validate enforces Code is one of the closed ErrorCode set, Message and RequestID are required, and Targets is populated only when Code is TARGET_REQUIRED - "Only TARGET_REQUIRED may include authorized target options."

type ErrorCode

type ErrorCode string

ErrorCode is the closed set of error codes api-contract.md "Security and errors" declares, each mapped to its exact HTTP status.

const (
	ErrCodeInvalidRequest                ErrorCode = "INVALID_REQUEST"
	ErrCodeTypeMismatch                  ErrorCode = "TYPE_MISMATCH"
	ErrCodeMissingParameter              ErrorCode = "MISSING_PARAMETER"
	ErrCodeAmbiguousBinding              ErrorCode = "AMBIGUOUS_BINDING"
	ErrCodeTargetRequired                ErrorCode = "TARGET_REQUIRED"
	ErrCodeUnauthenticated               ErrorCode = "UNAUTHENTICATED"
	ErrCodeAccessDenied                  ErrorCode = "ACCESS_DENIED"
	ErrCodeUnsupportedProtectedExecution ErrorCode = "UNSUPPORTED_PROTECTED_EXECUTION"
	ErrCodeNotFound                      ErrorCode = "NOT_FOUND"
	ErrCodeStaleContext                  ErrorCode = "STALE_CONTEXT"
	ErrCodeResponseTooLarge              ErrorCode = "RESPONSE_TOO_LARGE"
	ErrCodeSourceUnavailable             ErrorCode = "SOURCE_UNAVAILABLE"
	// ErrCodeSnapshotExpired reports that a required historical row snapshot
	// is absent, unretained, expired, or deleted. It never degrades to an empty
	// recordset or fingerprint-only comparison.
	ErrCodeSnapshotExpired ErrorCode = "SNAPSHOT_EXPIRED"
	ErrCodeTimeout         ErrorCode = "TIMEOUT"
	// ErrCodeRevisionConflict (409) refuses a project write whose
	// optimistic-concurrency condition failed: a create (ifNoneMatch) found
	// something already stored at the location, or an update (ifMatch) named
	// a revision that is no longer current. Nothing was written. It is
	// distinct from STALE_CONTEXT, which means the caller's securityContextId
	// is stale and is recovered by calling agent-info again - retrying a
	// stale revision that way would never succeed. Lead assumption
	// 2026-09-11 (Phase 2 task 2, queries/capture), pending an amendment of
	// api-contract.md's closed code set.
	ErrCodeRevisionConflict ErrorCode = "REVISION_CONFLICT"
)

func (ErrorCode) HTTPStatus

func (c ErrorCode) HTTPStatus() int

HTTPStatus returns c's exact HTTP status, or 0 for an unknown code.

func (ErrorCode) Valid

func (c ErrorCode) Valid() bool

Valid reports whether c is one of the closed set of error codes.

type ErrorEnvelope

type ErrorEnvelope struct {
	Error ErrorBody `json:"error"`
}

ErrorEnvelope is the exact shape of every error response. "{error:{code:string,message:string,field?:string,requestId:string, targets?:{source:string,label:string}[]}}" api-contract.md "Security and errors".

func (ErrorEnvelope) Validate

func (e ErrorEnvelope) Validate() error

type ExecutionListRequest added in v0.30.0

type ExecutionListRequest struct {
	Scope
	QueryID  string       `json:"queryId,omitempty"`
	Incident *IncidentRef `json:"incident,omitempty"`
	Since    string       `json:"since,omitempty"`
	Until    string       `json:"until,omitempty"`
	Limit    *int         `json:"limit,omitempty"`
}

func (ExecutionListRequest) Validate added in v0.30.0

func (r ExecutionListRequest) Validate() error

type ExecutionListResponse added in v0.30.0

type ExecutionListResponse struct {
	Executions []ExecutionRecordBrief `json:"executions"`
	Truncated  bool                   `json:"truncated"`
}

func (ExecutionListResponse) Validate added in v0.30.0

func (r ExecutionListResponse) Validate() error

type ExecutionPrincipal added in v0.30.0

type ExecutionPrincipal struct {
	ID     string   `json:"id"`
	Roles  []string `json:"roles"`
	Groups []string `json:"groups"`
}

func (ExecutionPrincipal) Validate added in v0.30.0

func (p ExecutionPrincipal) Validate() error

type ExecutionRecord added in v0.30.0

type ExecutionRecord struct {
	Ref               ExecutionRef               `json:"ref"`
	Scope             ExecutionRecordScope       `json:"scope"`
	QueryID           string                     `json:"queryId,omitempty"`
	QueryRevision     string                     `json:"queryRevision,omitempty"`
	DTQLHash          string                     `json:"dtqlHash,omitempty"`
	Parameters        map[string]TypedValueOrSet `json:"parameters"`
	BindingsApplied   []Binding                  `json:"bindingsApplied"`
	Principal         ExecutionPrincipal         `json:"principal"`
	PolicyFingerprint string                     `json:"policyFingerprint"`
	ExecutedAt        string                     `json:"executedAt"`
	DurationMS        int64                      `json:"durationMs"`
	Limitations       []Limitation               `json:"limitations"`
	Provenance        Provenance                 `json:"provenance"`
	AuthorizedFields  []FieldAccessRef           `json:"authorizedFields"`
	RowCount          int                        `json:"rowCount"`
	// ResultComplete is true when execution produced a complete result, false
	// when the result is known to be source-truncated or otherwise incomplete,
	// and nil for legacy records whose completeness is unknown.
	ResultComplete    *bool               `json:"resultComplete,omitempty"`
	ResultFingerprint string              `json:"resultFingerprint"`
	SnapshotRef       string              `json:"snapshotRef,omitempty"`
	Incident          *IncidentRef        `json:"incident,omitempty"`
	GrantUses         []GrantRef          `json:"grantUses,omitempty"`
	Measurements      []ScalarMeasurement `json:"measurements"`
}

ExecutionRecord is an immutable receipt. Snapshot lifecycle state is stored and transported separately from this value.

func (ExecutionRecord) Validate added in v0.30.0

func (r ExecutionRecord) Validate() error

type ExecutionRecordBrief added in v0.30.0

type ExecutionRecordBrief struct {
	Ref               ExecutionRef         `json:"ref"`
	Scope             ExecutionRecordScope `json:"scope"`
	QueryID           string               `json:"queryId,omitempty"`
	QueryRevision     string               `json:"queryRevision,omitempty"`
	DTQLHash          string               `json:"dtqlHash,omitempty"`
	ExecutedAt        string               `json:"executedAt"`
	DurationMS        int64                `json:"durationMs"`
	RowCount          int                  `json:"rowCount"`
	ResultFingerprint string               `json:"resultFingerprint"`
	SnapshotRef       string               `json:"snapshotRef,omitempty"`
	SnapshotState     *SnapshotState       `json:"snapshotState,omitempty"`
	Incident          *IncidentRef         `json:"incident,omitempty"`
}

ExecutionRecordBrief is the list-safe receipt subset. SnapshotState is the current separately stored lifecycle value, not a mutation of the receipt.

func (ExecutionRecordBrief) Validate added in v0.30.0

func (b ExecutionRecordBrief) Validate() error

type ExecutionRecordScope added in v0.30.0

type ExecutionRecordScope struct {
	StoreID     string `json:"storeId"`
	Project     string `json:"project"`
	Environment string `json:"environment"`
}

ExecutionRecordScope is the immutable source store, project and environment under which one execution ran. The evidence store lives in ExecutionRef.

func (ExecutionRecordScope) Validate added in v0.30.0

func (s ExecutionRecordScope) Validate() error

type ExecutionRef added in v0.30.0

type ExecutionRef = incidents.ExecutionRef

ExecutionRef is the shared transport spelling of incidents.ExecutionRef.

type ExecutionRequest

type ExecutionRequest struct {
	StoreID                string                     `json:"storeId,omitempty"`
	Project                string                     `json:"project"`
	Environment            string                     `json:"environment"`
	SecurityContextID      string                     `json:"securityContextId"`
	Source                 string                     `json:"source,omitempty"`
	QueryID                string                     `json:"queryId,omitempty"`
	DTQL                   string                     `json:"dtql,omitempty"`
	Parameters             map[string]TypedValueOrSet `json:"parameters"`
	BindingOrigins         []BindingOriginEntry       `json:"bindingOrigins"`
	Mode                   string                     `json:"mode"` // live | snapshot
	SnapshotID             string                     `json:"snapshotId,omitempty"`
	Limit                  *int                       `json:"limit,omitempty"`
	Incident               *IncidentRef               `json:"incident,omitempty"`
	Record                 bool                       `json:"record,omitempty"`
	Snapshot               bool                       `json:"snapshot,omitempty"`
	MeasurementProjections []MeasurementProjection    `json:"measurementProjections,omitempty"`
}

ExecutionRequest is POST exec/run_query's request body. "For ad-hoc DTQL, source is required. For saved queries, source obeys target resolution... Unknown parameters and type mismatches are rejected. The server never silently binds from stored browser context." api-contract.md "Endpoint table".

func (*ExecutionRequest) Normalize added in v0.30.0

func (r *ExecutionRequest) Normalize() error

Normalize canonicalizes every set parameter and preserves value-to-fact group alignment. Programmatic request builders should call this before Validate; JSON decoding calls it automatically.

func (*ExecutionRequest) UnmarshalJSON added in v0.30.0

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

UnmarshalJSON accepts valid request-order sets and canonicalizes their values together with binding provenance before the request is validated.

func (ExecutionRequest) Validate

func (r ExecutionRequest) Validate() error

Validate enforces: Project/Environment/SecurityContextID required; exactly one of QueryID/DTQL ("exactly one required"); DTQL set requires Source ("For ad-hoc DTQL, source is required"); every Parameters value is itself valid; BindingOrigins is checked for exactly the submitted Parameters keys - no more, no fewer - and each entry is itself valid; Mode is one of the closed set, snapshot Mode requires a SnapshotID; Limit, when present, is within (0, 500]; snapshot and measurement projections require recording.

type ExecutionSeriesPartition added in v0.30.0

type ExecutionSeriesPartition struct {
	EvidenceStoreID   string                `json:"evidenceStoreId"`
	SourceScope       ExecutionRecordScope  `json:"sourceScope"`
	Source            string                `json:"source"`
	PolicyFingerprint string                `json:"policyFingerprint"`
	QueryID           string                `json:"queryId,omitempty"`
	QueryRevision     string                `json:"queryRevision,omitempty"`
	DTQLHash          string                `json:"dtqlHash,omitempty"`
	BindingsApplied   []Binding             `json:"bindingsApplied"`
	Projection        MeasurementProjection `json:"projection"`
}

ExecutionSeriesPartition contains every immutable identity that must match before records may contribute points to one derived series.

func (ExecutionSeriesPartition) Validate added in v0.30.0

func (p ExecutionSeriesPartition) Validate() error

type ExecutionSeriesPoint added in v0.30.0

type ExecutionSeriesPoint struct {
	ExecutedAt   string       `json:"executedAt"`
	Execution    ExecutionRef `json:"execution"`
	Completeness string       `json:"completeness"`
	Value        *TypedValue  `json:"value,omitempty"`
	Reason       string       `json:"reason,omitempty"`
}

func (ExecutionSeriesPoint) Validate added in v0.30.0

func (p ExecutionSeriesPoint) Validate() error

type ExecutionSeriesRequest added in v0.30.0

type ExecutionSeriesRequest struct {
	Scope
	Partition ExecutionSeriesPartition `json:"partition"`
}

func (ExecutionSeriesRequest) Validate added in v0.30.0

func (r ExecutionSeriesRequest) Validate() error

type ExecutionSeriesResponse added in v0.30.0

type ExecutionSeriesResponse struct {
	Points  []ExecutionSeriesPoint `json:"points"`
	Omitted bool                   `json:"omitted"`
}

func (ExecutionSeriesResponse) Validate added in v0.30.0

func (r ExecutionSeriesResponse) Validate() error

type Fact

type Fact = investigation.Fact

Fact is an alias of the one canonical Investigation Context fact model.

type FieldAccessRef added in v0.30.0

type FieldAccessRef struct {
	StoreID     string `json:"storeId"`
	Project     string `json:"project"`
	Environment string `json:"environment"`
	Source      string `json:"source"`
	Collection  string `json:"collection,omitempty"`
	Column      string `json:"column"`
	Entity      string `json:"entity,omitempty"`
	Field       string `json:"field,omitempty"`
}

FieldAccessRef identifies one returned physical column and its optional semantic mapping without retaining a value.

func (FieldAccessRef) Validate added in v0.30.0

func (r FieldAccessRef) Validate() error

type GrantRef added in v0.30.0

type GrantRef struct {
	Incident           IncidentRef `json:"incident"`
	GrantID            string      `json:"grantId"`
	ApprovalMutationID string      `json:"approvalMutationId"`
}

GrantRef qualifies an incident-local grant and the access.approved mutation that made it active. Event resolution remains a server operation.

func (GrantRef) Validate added in v0.30.0

func (r GrantRef) Validate() error

type IncidentAppendRequest added in v0.29.0

type IncidentAppendRequest struct {
	IncidentScope
	MutationID  string                `json:"mutationId"`
	Incident    incidents.IncidentRef `json:"incident"`
	ExpectedSeq *uint64               `json:"expectedSeq,omitempty"`
	Event       IncidentEventInput    `json:"event"`
}

IncidentAppendRequest is POST /datatug/incidents/{id}/events.

func (IncidentAppendRequest) Validate added in v0.29.0

func (r IncidentAppendRequest) Validate() error

type IncidentAppendResponse added in v0.29.0

type IncidentAppendResponse struct {
	Event      incidents.Event        `json:"event"`
	Projection incidents.IncidentView `json:"projection"`
	Replayed   bool                   `json:"replayed"`
}

IncidentAppendResponse returns policy-filtered views of the committed event and projection. The provider-facing AppendResult remains canonical storage.

func (IncidentAppendResponse) Validate added in v0.29.0

func (r IncidentAppendResponse) Validate() error

type IncidentCreateRequest added in v0.29.0

type IncidentCreateRequest struct {
	IncidentScope
	MutationID       string                     `json:"mutationId"`
	Title            string                     `json:"title"`
	Description      string                     `json:"description,omitempty"`
	Projects         []incidents.ProjectRef     `json:"projects,omitempty"`
	CanonicalContext incidents.CanonicalContext `json:"canonicalContext"`
}

IncidentCreateRequest is POST /datatug/incidents. The server allocates the INC-n identifier and derives the reporter from the authenticated principal.

func (IncidentCreateRequest) Validate added in v0.29.0

func (r IncidentCreateRequest) Validate() error

func (IncidentCreateRequest) ValidateResolvedProject added in v0.31.0

func (r IncidentCreateRequest) ValidateResolvedProject(resolved incidents.ProjectRef) error

ValidateResolvedProject binds new fact provenance to the primary project scope resolved by the server. IncidentScope.StoreID remains only the route to the incident/evidence store and is not used as project provenance.

type IncidentEventInput added in v0.29.0

type IncidentEventInput struct {
	At        time.Time               `json:"at"`
	Type      incidents.EventType     `json:"type"`
	Assertion incidents.Assertion     `json:"assertion"`
	Refs      []incidents.ArtifactRef `json:"refs,omitempty"`
	Payload   json.RawMessage         `json:"payload"`
}

IncidentEventInput is the caller-controlled portion of an event. Actor and visibleAt are absent: the server attests both from its trusted context.

type IncidentEventsRequest added in v0.31.0

type IncidentEventsRequest struct {
	IncidentScope
	Incident *incidents.IncidentRef `json:"incident,omitempty"`
	Since    incidents.EventCursor  `json:"since,omitempty"`
}

IncidentEventsRequest selects either a single incident stream or the whole current store. Since is opaque to clients and interpreted only by the store.

func (IncidentEventsRequest) Validate added in v0.31.0

func (r IncidentEventsRequest) Validate() error

type IncidentListRequest added in v0.31.0

type IncidentListRequest struct {
	IncidentScope
	Statuses []incidents.Status `json:"statuses,omitempty"`
	QueryID  string             `json:"query,omitempty"`
	CheckID  string             `json:"check,omitempty"`
	BoardID  string             `json:"board,omitempty"`
}

IncidentListRequest is GET /datatug/incidents. Scope routes the incident store and identifies the source project for server resolution; the remaining fields are derived event back-links.

func (IncidentListRequest) ListQuery added in v0.31.0

ListQuery validates and carries the server-resolved project scope into both provider candidate selection and current-policy backlink filtering. IncidentScope's StoreID remains solely the incident/evidence-store route.

func (IncidentListRequest) Validate added in v0.31.0

func (r IncidentListRequest) Validate() error

type IncidentListResponse added in v0.29.0

type IncidentListResponse struct {
	Incidents []incidents.IncidentView `json:"incidents"`
}

IncidentListResponse is GET /datatug/incidents.

func (IncidentListResponse) Validate added in v0.29.0

func (r IncidentListResponse) Validate() error

type IncidentMergeRequest added in v0.29.0

type IncidentMergeRequest struct {
	IncidentScope
	MutationID string                `json:"mutationId"`
	Source     incidents.IncidentRef `json:"source"`
	Into       incidents.IncidentRef `json:"into"`
}

IncidentMergeRequest is POST /datatug/incidents/{id}/merge.

func (IncidentMergeRequest) Validate added in v0.29.0

func (r IncidentMergeRequest) Validate() error

type IncidentMergeResponse added in v0.29.0

type IncidentMergeResponse struct {
	Source   incidents.IncidentView `json:"source"`
	Into     incidents.IncidentView `json:"into"`
	Replayed bool                   `json:"replayed"`
}

IncidentMergeResponse returns current-policy projections after a recoverable merge; MergeResult remains the provider-facing canonical result.

func (IncidentMergeResponse) Validate added in v0.29.0

func (r IncidentMergeResponse) Validate() error

type IncidentRef added in v0.29.0

type IncidentRef = incidents.IncidentRef

IncidentRef is the shared transport spelling of incidents.IncidentRef.

type IncidentResponse added in v0.29.0

type IncidentResponse struct {
	Incident incidents.IncidentView `json:"incident"`
}

IncidentResponse is the success envelope shared by create and show.

func (IncidentResponse) Validate added in v0.29.0

func (r IncidentResponse) Validate() error

type IncidentScope added in v0.29.0

type IncidentScope Scope

IncidentScope is carried by every incident mutation. StoreID routes the incident/evidence store; Project and Environment identify the source project whose store the server resolves independently.

func (IncidentScope) Validate added in v0.29.0

func (s IncidentScope) Validate() error

type IncidentSearchRequest added in v0.31.0

type IncidentSearchRequest struct {
	IncidentScope
	Text  string                 `json:"text"`
	Facts []incidents.FactSignal `json:"facts,omitempty"`
}

func (IncidentSearchRequest) Validate added in v0.31.0

func (r IncidentSearchRequest) Validate() error

type IncidentSearchResponse added in v0.31.0

type IncidentSearchResponse struct {
	Matches []incidents.SearchMatch `json:"matches"`
}

func (IncidentSearchResponse) Validate added in v0.31.0

func (r IncidentSearchResponse) Validate() error

type IncidentSimilarRequest added in v0.31.0

type IncidentSimilarRequest struct {
	IncidentScope
	Incident incidents.IncidentRef `json:"incident"`
}

func (IncidentSimilarRequest) Validate added in v0.31.0

func (r IncidentSimilarRequest) Validate() error

type IncidentSimilarResponse added in v0.31.0

type IncidentSimilarResponse struct {
	Matches []incidents.SimilarMatch `json:"matches"`
}

func (IncidentSimilarResponse) Validate added in v0.31.0

func (r IncidentSimilarResponse) Validate() error

type IncidentStreamItem added in v0.31.0

type IncidentStreamItem = incidents.StreamItem

type InvestigationContext added in v0.31.0

type InvestigationContext = investigation.Context

InvestigationContext is the shared ordered context carried by an investigation and attached to an incident's canonical layer.

type Limitation

type Limitation struct {
	Policy        string   `json:"policy"`
	RowsFiltered  bool     `json:"rowsFiltered"`
	HiddenColumns []string `json:"hiddenColumns"`
}

Limitation reports an applied restriction, not the number of rejected rows or their values. Only names visible in authorized metadata may appear in HiddenColumns or Policy; use a generic policy label and an empty HiddenColumns where names are protected. api-contract.md "Shared JSON types" / "Limitations report applied restrictions...".

func (Limitation) Validate

func (l Limitation) Validate() error

Validate enforces Policy is required - a limitation with no named policy cannot be attributed to a rule, and the appendix requires attribution ("never silent, always attributable to a named rule").

type MeasurementProjection added in v0.30.0

type MeasurementProjection struct {
	ID        string `json:"id"`
	Column    string `json:"column,omitempty"`
	Aggregate string `json:"aggregate"`
}

func (MeasurementProjection) Validate added in v0.30.0

func (p MeasurementProjection) Validate() error

type PhysicalRef

type PhysicalRef = investigation.PhysicalRef

type ProjectScope added in v0.31.0

type ProjectScope = investigation.ProjectScope

ProjectScope is persisted fact provenance; request Scope additionally carries the current security-context staleness token and remains separate.

type Provenance

type Provenance struct {
	Source           string `json:"source"`
	Collection       string `json:"collection,omitempty"`
	QueryID          string `json:"queryId,omitempty"`
	Mode             string `json:"mode"` // live | snapshot
	SnapshotID       string `json:"snapshotId,omitempty"`
	ObservedAt       string `json:"observedAt"`
	ExecutionProfile string `json:"executionProfile"` // protected | opaque-privileged
}

Provenance describes where a Result actually came from: "Result.provenance .executionProfile reports the actual executor used for that run" - never the session's allowed capabilities, and a privileged principal running protected DTQL still receives protected provenance. api-contract.md "Shared JSON types" / "Security and errors".

func (Provenance) Validate

func (p Provenance) Validate() error

Validate enforces Source and ObservedAt are required (ObservedAt must be an RFC3339-UTC-normalized instant, the same rule TypedValue's "datetime" type enforces), Mode is one of the closed set, snapshot Mode requires a SnapshotID ("a snapshot requires explicit separate selection... and a configured snapshotId"), and ExecutionProfile is one of the closed set.

type Recordset

type Recordset struct {
	Columns []Column       `json:"columns"`
	Rows    [][]TypedValue `json:"rows"`
}

Recordset is Result's tabular payload. "Arrays are ordered; rows have exactly one value per returned column." api-contract.md "Shared JSON types".

func (Recordset) Validate

func (r Recordset) Validate() error

Validate enforces every column is itself valid, every row has exactly as many values as there are columns, and every cell value is itself valid.

type RelatedItem

type RelatedItem struct {
	LookupID   string `json:"lookupId"`
	Label      string `json:"label"`
	Source     string `json:"source"`
	Collection string `json:"collection"`
	Count      *int64 `json:"count"` // number | null
}

RelatedItem is one related-lookup target. Count is optional: nil means "return null if an exact authorized count cannot be obtained within a 2-second budget" - never the unrestricted count.

func (RelatedItem) Validate

func (i RelatedItem) Validate() error

type RelatedRequest added in v0.27.0

type RelatedRequest struct {
	Project           string `json:"project"`
	Environment       string `json:"environment"`
	SecurityContextID string `json:"securityContextId"`
	Fact              Fact   `json:"fact"`
	Limit             *int   `json:"limit,omitempty"`
}

RelatedRequest is POST semantic/related's request body: "Scope + {fact:Fact,limit?:number}" - api-contract.md "Endpoint table". Scope's three fields are flattened into the top level of the JSON body, exactly like ExecutionRequest, never nested under a "scope" key - confirmed against the live server (Task 12 lane S77). Related operations use POST so a semantic value is never copied into a URL, browser history or access log.

func (RelatedRequest) Validate added in v0.27.0

func (r RelatedRequest) Validate() error

Validate enforces Project/Environment/SecurityContextID are required, Fact is itself valid, and Limit, when present, is within (0, relatedMaxItems] - "Related discovery returns at most 50 targets" (api-contract.md "Bounded lookups and HTTP") bounds what a caller may ask for, not just what a response may contain, so this reuses the same relatedMaxItems the RelatedResponse envelope is capped at (responses.go).

type RelatedResponse

type RelatedResponse struct {
	Related   []RelatedItem `json:"related"`
	Truncated bool          `json:"truncated"`
}

RelatedResponse is the exact success envelope of POST semantic/related. api-contract.md "Endpoint table".

func (RelatedResponse) Validate

func (r RelatedResponse) Validate() error

Validate enforces every Related entry is itself valid and there are no more than relatedMaxItems of them.

type RelatedRowsRequest added in v0.27.0

type RelatedRowsRequest struct {
	StoreID           string     `json:"storeId,omitempty"`
	Project           string     `json:"project"`
	Environment       string     `json:"environment"`
	SecurityContextID string     `json:"securityContextId"`
	LookupID          string     `json:"lookupId"`
	Value             TypedValue `json:"value"`
	Limit             *int       `json:"limit,omitempty"`
	Record            bool       `json:"record,omitempty"`
	Snapshot          bool       `json:"snapshot,omitempty"`
}

RelatedRowsRequest is POST semantic/related/rows's request body: "Scope + {lookupId:string,value:TypedValue,limit?:number}" - api-contract.md "Endpoint table". Scope's fields are flattened into the top level of the JSON body, exactly like ExecutionRequest, never nested under a "scope" key. StoreID is additive and optional for legacy single-store callers; when it is omitted, the server resolves the configured primary store. LookupID is "an opaque handle to a server-validated relationship... not authority. Each rows request revalidates the relationship, value type, current source policy and limit" (api-contract.md "Bounded lookups and HTTP") - this type only enforces it is present and nonempty; the server revalidates everything it names.

func (RelatedRowsRequest) Validate added in v0.27.0

func (r RelatedRowsRequest) Validate() error

Validate enforces Project/Environment/SecurityContextID and LookupID are required, validates StoreID when supplied, validates Value, and requires Limit, when present, to be within (0, executionMaxLimit] - this endpoint returns a Result, the same shape exec/run_query returns, so it is bound by the same "Default result limit is 100 and maximum is 500" rule (api-contract.md "Bounded lookups and HTTP") ExecutionRequest.Limit already enforces.

type Result

type Result struct {
	Recordset       Recordset     `json:"recordset"`
	Limitations     []Limitation  `json:"limitations"`
	BindingsApplied []Binding     `json:"bindingsApplied"`
	Provenance      Provenance    `json:"provenance"`
	Truncated       bool          `json:"truncated"`
	Execution       *ExecutionRef `json:"execution,omitempty"`
}

Result is the exact success envelope of POST exec/run_query and POST semantic/related/rows. "Denied requests return no recordset, sample, true count, SQL text or hidden value." api-contract.md "Shared JSON types".

func (Result) Validate

func (r Result) Validate() error

Validate enforces Recordset, every Limitation, every applied Binding and Provenance are each themselves valid.

type ScalarMeasurement added in v0.30.0

type ScalarMeasurement struct {
	Projection   MeasurementProjection `json:"projection"`
	Completeness string                `json:"completeness"`
	Value        *TypedValue           `json:"value,omitempty"`
	Reason       string                `json:"reason,omitempty"`
}

func (ScalarMeasurement) Validate added in v0.30.0

func (m ScalarMeasurement) Validate() error

type Scope

type Scope struct {
	StoreID           string `json:"storeId,omitempty"`
	Project           string `json:"project"`
	Environment       string `json:"environment"`
	SecurityContextID string `json:"securityContextId"`
}

Scope identifies the project, environment and staleness-check security context every scoped call carries. "Scope = {storeId?: string, project: string, environment: string, securityContextId: string}" - api-contract.md "Scope and identity". Project and environment IDs are required, nonempty, and resolved within this server's registered projects; securityContextId is a staleness check, never authentication.

func (Scope) Validate

func (s Scope) Validate() error

Validate enforces "Project and environment IDs are required, nonempty" and the same for securityContextId (a call carrying a blank/absent staleness check cannot be validated against anything).

type SemanticColumnMapping

type SemanticColumnMapping struct {
	Column     string `json:"column"`
	Entity     string `json:"entity"`
	Field      string `json:"field"`
	Provenance string `json:"provenance"` // declared | inferred
}

SemanticColumnMapping is one physical column's resolved entity/field mapping. Unmapped columns are omitted from the response entirely, never listed with an empty entity/field.

func (SemanticColumnMapping) Validate

func (m SemanticColumnMapping) Validate() error

type SemanticColumnsResponse

type SemanticColumnsResponse struct {
	Columns []SemanticColumnMapping `json:"columns"`
}

SemanticColumnsResponse is the exact success envelope of GET semantic/columns. api-contract.md "Endpoint table".

func (SemanticColumnsResponse) Validate

func (r SemanticColumnsResponse) Validate() error

type SnapshotReadResponse added in v0.30.0

type SnapshotReadResponse struct {
	Execution     ExecutionRef  `json:"execution"`
	SnapshotRef   string        `json:"snapshotRef"`
	SnapshotState SnapshotState `json:"snapshotState"`
	Recordset     *Recordset    `json:"recordset,omitempty"`
	Limitations   []Limitation  `json:"limitations,omitempty"`
	Truncated     bool          `json:"truncated,omitempty"`
}

SnapshotReadResponse returns recorded evidence. It deliberately is not a Result: reading evidence does not execute a query and creates no provenance.

func (SnapshotReadResponse) Validate added in v0.30.0

func (r SnapshotReadResponse) Validate() error

type SnapshotState added in v0.30.0

type SnapshotState struct {
	Availability string `json:"availability"`
	ChangedAt    string `json:"changedAt"`
	Reason       string `json:"reason,omitempty"`
}

SnapshotState is mutable lifecycle state keyed separately by an immutable snapshotRef. It is never embedded in ExecutionRecord.

func (SnapshotState) Validate added in v0.30.0

func (s SnapshotState) Validate() error

func (SnapshotState) ValidateTransition added in v0.30.0

func (s SnapshotState) ValidateTransition(next SnapshotState) error

ValidateTransition accepts idempotent retries and the only state advance allowed by the lifecycle: available to one terminal state at a later time.

type SourceRef

type SourceRef struct {
	Source     string `json:"source"`
	Collection string `json:"collection"`
}

SourceRef names a stable project-local source, resolved through the project registry for the requested environment - never a filesystem path, arbitrary HTTP URL or credential. "SourceRef = {source: string, collection: string}" - api-contract.md "Scope and identity".

func (SourceRef) Validate

func (r SourceRef) Validate() error

Validate enforces both fields are required per the appendix's type.

type TargetOption

type TargetOption struct {
	Source string `json:"source"`
	Label  string `json:"label"`
}

TargetOption is one authorized eligible source offered on a TARGET_REQUIRED error - "the same authorized target options in error.targets, never hidden source IDs."

func (TargetOption) Validate

func (t TargetOption) Validate() error

type TypedValue

type TypedValue = investigation.TypedValue

func NewBooleanValue

func NewBooleanValue(v bool) TypedValue

func NewDateValue

func NewDateValue(v string) TypedValue

func NewDatetimeValue

func NewDatetimeValue(v string) TypedValue

func NewDecimalValue

func NewDecimalValue(v string) TypedValue

func NewIntegerValue

func NewIntegerValue(v string) TypedValue

func NewNullValue

func NewNullValue() TypedValue

func NewNumberValue

func NewNumberValue(v float64) TypedValue

func NewStringValue

func NewStringValue(v string) TypedValue

type TypedValueOrSet added in v0.30.0

type TypedValueOrSet struct {
	Scalar *TypedValue
	Set    *TypedValueSet
}

TypedValueOrSet is the exact wire union accepted in parameter and binding value positions. Its JSON is the contained scalar or set object, never an additional wrapper.

func ScalarValue added in v0.30.0

func ScalarValue(value TypedValue) TypedValueOrSet

func SetValue added in v0.30.0

func SetValue(value TypedValueSet) TypedValueOrSet

func (TypedValueOrSet) IsSet added in v0.30.0

func (v TypedValueOrSet) IsSet() bool

func (TypedValueOrSet) MarshalJSON added in v0.30.0

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

func (*TypedValueOrSet) UnmarshalJSON added in v0.30.0

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

func (TypedValueOrSet) Validate added in v0.30.0

func (v TypedValueOrSet) Validate() error

type TypedValueSet added in v0.30.0

type TypedValueSet struct {
	Values []TypedValue `json:"values"`
}

TypedValueSet is the bounded, canonical cohort value transported for a parameter that explicitly supports set binding. Values are non-null scalar TypedValues of one type, sorted by their canonical JSON bytes and unique.

func NewTypedValueSet added in v0.30.0

func NewTypedValueSet(values ...TypedValue) (TypedValueSet, error)

NewTypedValueSet deduplicates and orders values into the canonical wire representation required for deterministic execution and recording.

func NormalizeTypedValueSet added in v0.30.0

func NormalizeTypedValueSet(set TypedValueSet, valueFactIDs [][]string) (TypedValueSet, [][]string, error)

NormalizeTypedValueSet canonicalizes values and, when supplied, keeps each valueFactIds group attached to the value that produced it. Duplicate values merge their fact groups; values and fact IDs are then sorted and deduplicated.

func (TypedValueSet) MarshalJSON added in v0.30.0

func (s TypedValueSet) MarshalJSON() ([]byte, error)

func (*TypedValueSet) UnmarshalJSON added in v0.30.0

func (s *TypedValueSet) UnmarshalJSON(data []byte) error

func (TypedValueSet) Validate added in v0.30.0

func (s TypedValueSet) Validate() error

type ValidationError

type ValidationError = investigation.ValidationError

ValidationError remains an apicontract alias for compatibility.

type ValueType

type ValueType = investigation.ValueType

ValueType and TypedValue remain source-compatible aliases while the single canonical implementation is owned by the Investigation Context package.

Directories

Path Synopsis
Package fixtures holds the frozen JSON fixtures for pkg/apicontract's normative transport types (spec/features/core-investigation-loop/ api-contract.md, hub datatug/datatug) - one file per envelope/error case listed in the appendix's "Acceptance and migration" section.
Package fixtures holds the frozen JSON fixtures for pkg/apicontract's normative transport types (spec/features/core-investigation-loop/ api-contract.md, hub datatug/datatug) - one file per envelope/error case listed in the appendix's "Acceptance and migration" section.

Jump to

Keyboard shortcuts

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