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

model

package
v1.9.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: 3 Imported by: 0

Documentation

Overview

Package model defines the frozen contracts shared by AgentSQL components.

Index

Constants

View Source
const (
	RedactionKeyStateStandby = "standby"
	RedactionKeyStateActive  = "active"
	RedactionKeyStateLegacy  = "legacy"
	RedactionKeyStateRetired = "retired"
)

Variables

This section is empty.

Functions

func IsNative added in v0.5.0

func IsNative(dbType string) bool

func SupportedDatasourceType added in v0.5.0

func SupportedDatasourceType(value string) bool

SupportedDatasourceType reports whether the type is registered. Native adapter availability and SQL capabilities are separate from registration.

func TaskReadOnlySelect added in v0.7.0

func TaskReadOnlySelect(sqlText string, ast *AST) bool

Types

type AST

type AST struct {
	Dialect            DBDialect
	RawSQL             string
	Normalized         string
	StmtType           StmtType
	IsMulti            bool
	Tables             []ObjectRef
	Columns            []string
	DirectProjections  []DirectProjectionRef
	ProjectionLineages []ProjectionLineage
	HasWhere           bool
	WhereTautology     bool
	HasLimit           bool
	HasGroupBy         bool
	IsPureAggregate    bool
	Functions          []string
	Operations         []string
	Explain            *ExplainInfo
}

AST is the normalized SQL representation shared by parsers and guards.

type Agent

type Agent struct {
	ID         string
	TenantID   string
	Name       string
	Owner      *string
	Status     string
	APIKeyHash string
	Level      string
	ExpiresAt  *time.Time
	CreatedAt  time.Time
	UpdatedAt  time.Time
	// TaskGrantID is set only on an Agent authenticated with a temporary task
	// key. It is never persisted as an Agent field.
	TaskGrantID string
	// TaskGrantIssuerUserID is bound from the authenticated task key before
	// SQL validation so denied attempts retain their issuer in traffic audit.
	// It is runtime-only and is never serialized or persisted as Agent data.
	TaskGrantIssuerUserID string `json:"-"`
}

Agent is an authenticated AI database client.

type Approval

type Approval struct {
	ID                    string
	TenantID              string
	RequesterUserID       *string
	AuditID               *int64
	AgentID               *string
	DatasourceID          *string
	DatasourceFingerprint *string
	SQLRaw                *string
	SQLNorm               *string
	Reason                *string
	RequestReason         *string
	DecisionComment       *string
	Seal                  *string
	Status                string
	Approver              *string
	DecidedAt             *time.Time
	ExpiresAt             *time.Time
	ClaimedAt             *time.Time
	FinishedAt            *time.Time
	ExecutionAuditID      *int64
	OutcomeCode           *string
	CreatedAt             time.Time
	UpdatedAt             time.Time
}

Approval is a persisted decision request associated with an audit record.

type Assessment

type Assessment struct {
	Decision     Decision
	Risk         RiskLevel
	StmtType     StmtType
	Hits         []RuleHit
	EstScanRows  int64
	Reason       string
	Suggestion   string
	Normalized   string
	Objects      []ObjectRef
	StageLatency map[string]int64
}

Assessment is the complete guard decision returned by the pipeline.

type AuditFilter

type AuditFilter struct {
	TimeStart    *time.Time
	TimeEnd      *time.Time
	AgentID      *string
	Actor        *string
	DatasourceID *string
	SessionID    *string
	MCPTool      *string
	Action       *string
	ErrorCode    *string
	EventUUID    *string
	TaskGrantID  *string
	Decisions    []string
	StmtTypes    []string
	RiskMin      *int
	RiskMax      *int
	Keyword      string
	ObjectLike   string
	RuleLike     string
}

AuditFilter describes optional immutable audit-log query constraints.

func (AuditFilter) IsEmpty

func (filter AuditFilter) IsEmpty() bool

IsEmpty reports whether no audit-log constraint is configured.

type AuditLog

type AuditLog struct {
	ID             int64
	TenantID       string `json:"tenant_id,omitempty"`
	TS             time.Time
	AgentID        *string
	DatasourceID   *string
	SessionID      *string
	ConversationID *string
	MCPTool        *string
	DBType         *string
	SQLRaw         *string
	SQLNorm        *string
	StmtType       *string
	Objects        *string
	Decision       string
	RuleHits       *string
	RiskLevel      *int
	EstRows        *int64
	RowsReturned   *int
	LatencyMS      *int64
	ClientIP       *string
	ModelName      *string
	ErrorMsg       *string
	ErrorCode      *string `json:"error_code,omitempty"`
	Action         *string
	ActorType      *string
	ActorID        *string
	DetailsJSON    *string
	EventUUID      *string
}

AuditLog is an immutable record of one AgentSQL operation.

type AuditPage

type AuditPage struct {
	Total    int64
	Page     int
	PageSize int
	List     []AuditLog
}

AuditPage is one immutable audit-log result page.

type ColumnDependency

type ColumnDependency struct {
	Origin ColumnOrigin
	Role   DependencyRole
}

ColumnDependency records both the physical origin and how it influences the result. Relation.Alias is not part of physical identity and must be empty.

type ColumnOrigin

type ColumnOrigin struct {
	Relation ObjectRef
	Column   string
	Route    LineageRoute
}

ColumnOrigin identifies a physical column and the route used to reach it.

type DBDialect

type DBDialect string

DBDialect identifies a registered business database type. Only relational values also identify SQL dialects.

const (
	DialectPostgres    DBDialect = "postgres"
	DialectVastbase    DBDialect = "vastbase"
	DialectHighGo      DBDialect = "highgo"
	DialectMySQL       DBDialect = "mysql"
	DialectDM          DBDialect = "dm"
	DialectOracle      DBDialect = "oracle"
	DialectYashan      DBDialect = "yashan"
	DialectSQLServer   DBDialect = "sqlserver"
	DialectRedis       DBDialect = "redis"
	DialectValkey      DBDialect = "valkey"
	DialectMemcached   DBDialect = "memcached"
	DialectMongoDB     DBDialect = "mongodb"
	DialectCouchbase   DBDialect = "couchbase"
	DialectCouchDB     DBDialect = "couchdb"
	DialectCassandra   DBDialect = "cassandra"
	DialectHBase       DBDialect = "hbase"
	DialectScylla      DBDialect = "scylla"
	DialectNeo4j       DBDialect = "neo4j"
	DialectJanusGraph  DBDialect = "janusgraph"
	DialectNebula      DBDialect = "nebula"
	DialectInfluxDB    DBDialect = "influxdb"
	DialectPrometheus  DBDialect = "prometheus"
	DialectTimescaleDB DBDialect = "timescaledb"
	DialectClickHouse  DBDialect = "clickhouse"
	DialectDoris       DBDialect = "doris"
	DialectStarRocks   DBDialect = "starrocks"
	DialectMilvus      DBDialect = "milvus"
	DialectQdrant      DBDialect = "qdrant"
	DialectWeaviate    DBDialect = "weaviate"
)

type DBErrorCode

type DBErrorCode string

DBErrorCode is a stable public error code shared by database, pipeline, and audit boundaries.

const (
	DBErrorCodeObjectNotFound       DBErrorCode = "DB_OBJECT_NOT_FOUND"
	DBErrorCodeColumnNotFound       DBErrorCode = "DB_COLUMN_NOT_FOUND"
	DBErrorCodeAlreadyExists        DBErrorCode = "DB_OBJECT_ALREADY_EXISTS"
	DBErrorCodeSyntax               DBErrorCode = "DB_SYNTAX_ERROR"
	DBErrorCodeSemantic             DBErrorCode = "DB_SEMANTIC_ERROR"
	DBErrorCodeData                 DBErrorCode = "DB_DATA_EXCEPTION"
	DBErrorCodeConstraint           DBErrorCode = "DB_CONSTRAINT_VIOLATION"
	DBErrorCodeRetryable            DBErrorCode = "DB_RETRYABLE_CONFLICT"
	DBErrorCodeTransaction          DBErrorCode = "DB_TRANSACTION_STATE"
	DBErrorCodeResource             DBErrorCode = "DB_RESOURCE_EXHAUSTED"
	DBErrorCodeTimeout              DBErrorCode = "DB_QUERY_TIMEOUT"
	DBErrorCodeInterrupted          DBErrorCode = "DB_QUERY_INTERRUPTED"
	DBErrorCodePermission           DBErrorCode = "DB_PERMISSION_DENIED"
	DBErrorCodeReadOnly             DBErrorCode = "DB_READ_ONLY_VIOLATION"
	DBErrorCodeAuthentication       DBErrorCode = "DB_AUTHENTICATION_FAILED"
	DBErrorCodeDatabaseNotFound     DBErrorCode = "DB_DATABASE_NOT_FOUND"
	DBErrorCodeConnection           DBErrorCode = "DB_DATASOURCE_UNREACHABLE"
	DBErrorCodeExecution            DBErrorCode = "DB_EXECUTION_FAILED"
	DBErrorCodeGatewayInternal      DBErrorCode = "GATEWAY_INTERNAL"
	DBErrorCodeAuditUnavailable     DBErrorCode = "AUDIT_UNAVAILABLE"
	DBErrorCodeAuditOverloaded      DBErrorCode = "AUDIT_OVERLOADED"
	DBErrorCodeCommitOutcomeUnknown DBErrorCode = "COMMIT_OUTCOME_UNKNOWN"
)

type Datasource

type Datasource struct {
	ID            string
	TenantID      string
	Name          string
	DBType        string
	Host          string
	Port          int
	Database      string
	Username      string
	PasswordEnc   string
	ConnLimit     int
	StmtTimeoutMS int
	RowLimit      int
	TLSMode       string
	TLSServerName string
	TLSCAFile     string
	// TrustServerCertificate is only accepted with SQL Server verify-full mode
	// for controlled development environments. It must remain false in
	// production because it disables server identity verification.
	TrustServerCertificate bool
	CreatedAt              time.Time
	UpdatedAt              time.Time
}

Datasource is a protected business-database connection target. SQL Server normalizes an empty TLSMode to strict. PostgreSQL supports an explicit verify-full mode with a CA file; an empty mode keeps the legacy connection behavior for existing datasources and must not be described as verified TLS.

type DatasourceCategory added in v0.5.0

type DatasourceCategory string

DatasourceCategory identifies a connection family's capabilities. Native sources in v0.5 have connection-level support, not SQL pipeline support.

const (
	CategoryRelational DatasourceCategory = "relational"
	CategoryKeyValue   DatasourceCategory = "keyvalue"
	CategoryDocument   DatasourceCategory = "document"
	CategoryWideColumn DatasourceCategory = "widecolumn"
	CategoryGraph      DatasourceCategory = "graph"
	CategoryTimeSeries DatasourceCategory = "timeseries"
	CategoryOLAP       DatasourceCategory = "olap"
	CategoryVector     DatasourceCategory = "vector"
)

func CategoryOf added in v0.5.0

func CategoryOf(dbType string) (DatasourceCategory, bool)

type DatasourceTypeSpec added in v0.5.0

type DatasourceTypeSpec struct {
	Category         DatasourceCategory
	DisplayName      string
	DefaultPort      int
	RequiresDatabase bool
	RequiresUsername bool
	RequiresPassword bool
}

func TypeSpecFor added in v0.5.0

func TypeSpecFor(dbType string) (DatasourceTypeSpec, bool)

type Decision

type Decision string

Decision is a pipeline outcome. Deny, approve, warn, and allow are rule or authorization outcomes; error is reserved for execution/database failures and must never be emitted by the rule engine.

const (
	// DecisionError reports a classified execution/database failure.
	DecisionError Decision = "error"
	// DecisionDeny rejects execution.
	DecisionDeny Decision = "deny"
	// DecisionApprove requires human approval and does not execute immediately.
	DecisionApprove Decision = "approve"
	// DecisionWarn allows execution while retaining a warning.
	DecisionWarn Decision = "warn"
	// DecisionAllow allows execution without a rule hit.
	DecisionAllow Decision = "allow"
)

type DependencyRole

type DependencyRole string

DependencyRole distinguishes value sources from side-channel and control inputs that also require protection.

const (
	DependencyValue   DependencyRole = "value"
	DependencyControl DependencyRole = "control"
	DependencyGroup   DependencyRole = "group"
	DependencyOrder   DependencyRole = "order"
	DependencyFilter  DependencyRole = "filter"
)

type DirectProjectionRef

type DirectProjectionRef struct {
	Column  string
	Offset  int
	FromEnd bool
	Source  ObjectRef
}

DirectProjectionRef identifies a top-level direct column projection, its position in the result set, and its uniquely resolved physical source.

type ExplainInfo

type ExplainInfo struct {
	EstScanRows int64
	EstCost     float64
	UsesIndex   bool
	SeqScan     bool
	Raw         string
}

ExplainInfo contains normalized database query-plan signals.

type LineageArm

type LineageArm struct {
	Kind              LineageKind
	Operation         string
	Status            LineageStatus
	Dependencies      []ColumnDependency
	PossibleRelations []ObjectRef
}

LineageArm describes one ordinary projection or one leaf of a set operation. PossibleRelations is restricted to relations that can actually contribute to this projection.

type LineageKind

type LineageKind string

LineageKind classifies the value-shaping SQL construct.

const (
	LineageDirect      LineageKind = "direct"
	LineageTransparent LineageKind = "transparent"
	LineageComposite   LineageKind = "composite"
	LineageAggregate   LineageKind = "aggregate"
	LineageWindow      LineageKind = "window"
	LineageConstant    LineageKind = "constant"
	LineageWildcard    LineageKind = "wildcard"
	LineageOpaque      LineageKind = "opaque"
)

type LineageRoute

type LineageRoute uint8

LineageRoute is a bit set describing transparent relation boundaries.

const (
	RouteCTE LineageRoute = 1 << iota
	RouteDerived
	RouteScalarSubquery
	RouteLateral
)

type LineageStatus

type LineageStatus string

LineageStatus describes how conclusively an arm was resolved.

const (
	LineageResolved    LineageStatus = "resolved"
	LineageSourceFree  LineageStatus = "source_free"
	LineageAmbiguous   LineageStatus = "ambiguous"
	LineageOpaqueState LineageStatus = "opaque"
	LineageUnsupported LineageStatus = "unsupported"
)

type ManagementAuditOutbox

type ManagementAuditOutbox struct {
	EventUUID     string
	TenantID      string
	Action        string
	ActorType     string
	ActorID       string
	DetailsJSON   string
	CreatedAt     time.Time
	Attempts      int
	ClaimedBy     string
	ClaimedAt     *time.Time
	LastError     string
	NextAttemptAt time.Time
	DeliveredAt   *time.Time
}

ManagementAuditOutbox is one metadata-side management audit delivery.

type MaskRule

type MaskRule struct {
	ID                string
	TenantID          string
	DatasourceID      *string
	SchemaName        string
	TableName         string
	ColumnName        string
	SensitiveType     string
	Algo              string
	Enabled           bool
	RangeBucketWidth  *int64
	RangeBucketOffset *int64
	RangeGranularity  *string
	CreatedAt         time.Time
	UpdatedAt         time.Time
}

MaskRule configures redaction for one result column.

type ObjectRef

type ObjectRef struct {
	Schema string
	Table  string
	Alias  string
}

ObjectRef identifies a database object and its optional alias.

type Permission added in v0.5.0

type Permission struct {
	Code        string `json:"code"`
	Description string `json:"description"`
}

Permission is a stable, globally-defined action code assignable to roles.

type Policy

type Policy struct {
	ID                    string
	TenantID              string
	AgentID               string
	DatasourceID          string
	ObjectType            string
	ObjectName            string
	Columns               *string
	RowFilter             *string
	Action                string
	RelationBindingID     *string
	Revision              int64
	LegacyUnrepresentable bool
	RelationBinding       *RelationPolicyBinding
	ColumnPermissions     []PolicyColumnPermission
	ColumnStaging         []PolicyColumnPermissionStaging
	CreatedAt             time.Time
	UpdatedAt             time.Time
}

Policy grants or denies an agent access to a database object.

type PolicyColumnPermission

type PolicyColumnPermission struct {
	PolicyID             string
	TenantID             string
	RelationEnrollmentID string
	ColumnOrdinal        int
	ColumnName           string
	ColumnTypeDigest     string
	Usage                string
	ParentRevision       int64
}

PolicyColumnPermission is an ordinal-bound output/reference grant. An ordinal is never synthesized from a legacy CSV token.

type PolicyColumnPermissionStaging

type PolicyColumnPermissionStaging struct {
	PolicyID       string
	TenantID       string
	TokenOrdinal   int
	LegacyToken    string
	RequestedUsage string
	SourceCSVHash  string
	BindStatus     string
	ErrorCode      *string
}

PolicyColumnPermissionStaging retains an untrusted legacy token until S3 can bind it under the control-to-business two-phase protocol.

type PolicyDecision

type PolicyDecision struct {
	AllowedTables []string
	DeniedTables  []string
	ColumnACL     map[string][]string
	Level         string
}

PolicyDecision carries the merged policy inputs consumed by guard rules. Policy loading and merging remain the responsibility of T08.

type ProjectionLineage

type ProjectionLineage struct {
	SelectIndex int
	OutputName  string
	Variadic    bool
	SetOp       string
	Arms        []LineageArm
}

ProjectionLineage describes one SQL target-list item. Variadic items may occupy more than one result position; set operations retain every branch in Arms so a downstream redactor can make a fail-closed decision.

type QueryResult

type QueryResult struct {
	Columns   []string
	Rows      [][]string
	RowCount  int
	Truncated bool
	LatencyMS int64
}

QueryResult is the bounded, string-encoded result returned to a caller.

type RedactionKeyVersion

type RedactionKeyVersion struct {
	ID             string
	TenantID       string
	State          string
	Commitment     string
	Label          string
	ConfigRevision string
	CreatedAt      time.Time
	UpdatedAt      time.Time
	ActivatedAt    *time.Time
	RetiredAt      *time.Time
}

RedactionKeyVersion is a key-version registry record. It never contains key material.

type RelationPolicyBinding

type RelationPolicyBinding struct {
	ID                 string
	TenantID           string
	PolicyID           string
	DatasourceID       string
	SchemaName         string
	RelationName       string
	StableObjectID     *string
	CatalogFingerprint *string
	Status             string
	Revision           int64
	CreatedAt          time.Time
	UpdatedAt          time.Time
}

RelationPolicyBinding is the control-plane identity selected for a policy. S1 permits staging identities; only a later slice may mark them healthy.

type RiskLevel

type RiskLevel int

RiskLevel ranks a result as deny (1), approve (2), warn (3), or info (4).

const (
	// RiskDeny is the highest risk level.
	RiskDeny RiskLevel = 1
	// RiskApprove requires human approval.
	RiskApprove RiskLevel = 2
	// RiskWarn permits execution with a warning.
	RiskWarn RiskLevel = 3
	// RiskInfo represents an informational or allow result.
	RiskInfo RiskLevel = 4
)

type Role added in v0.5.0

type Role struct {
	ID          string    `json:"id"`
	TenantID    string    `json:"tenant_id"`
	Name        string    `json:"name"`
	Description string    `json:"description"`
	Builtin     bool      `json:"builtin"`
	ParentIDs   []string  `json:"parent_role_ids"`
	Permissions []string  `json:"permissions"`
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`
}

Role groups permissions inside exactly one tenant.

type Rule

type Rule struct {
	ID          string
	TenantID    string
	DBType      string
	Title       string
	RiskLevel   int
	PatternType string
	Definition  string
	Enabled     bool
	Builtin     bool
	CreatedAt   time.Time
	UpdatedAt   time.Time
}

Rule is a persisted SQL security-rule definition.

type RuleContext

type RuleContext struct {
	Agent      *Agent
	Datasource *Datasource
	AST        *AST
	Policy     *PolicyDecision
}

RuleContext contains the inputs available to a rule evaluation.

type RuleHit

type RuleHit struct {
	RuleID     string
	Risk       RiskLevel
	Decision   Decision
	Message    string
	Suggestion string
}

RuleHit records one rule result and its remediation guidance.

type StmtType

type StmtType string

StmtType identifies a SQL statement as SELECT, INSERT, UPDATE, DELETE, DDL, ADMIN, or UNKNOWN.

type TaskReadGrant added in v0.7.0

type TaskReadGrant struct {
	ID           string
	TenantID     string
	IssuerUserID string
	AgentID      string
	DatasourceID string
	SQLSHA256    string
	KeyHash      string
	MaxUses      *int64
	UsedCount    int64
	ExpiresAt    time.Time
	RevokedAt    *time.Time
	CreatedAt    time.Time
}

TaskReadGrant narrows one Agent to one datasource and one exact SELECT text. SQLSHA256 and KeyHash are digests; neither SQL nor the key is persisted.

type TaskReadGrantRequest added in v0.8.0

type TaskReadGrantRequest struct {
	ID              string
	TenantID        string
	RequesterUserID string
	AgentID         string
	DatasourceID    string
	SQLSHA256       string
	SQLCiphertext   string
	RequestDigest   string
	IdempotencyKey  string
	MaxUses         *int64
	ExpiresAt       time.Time
	Status          string
	ReviewerUserID  *string
	ReviewedAt      *time.Time
	IssuedAt        *time.Time
	GrantID         *string
	GrantRevokedAt  *time.Time
	CreatedAt       time.Time
}

TaskReadGrantRequest is the approval record for one exact-query grant. The SQL is encrypted for authorized reviewer inspection; the execution key is stored only as a digest on the issued grant.

type Tenant added in v0.5.0

type Tenant struct {
	ID        string    `json:"id"`
	Name      string    `json:"name"`
	Status    string    `json:"status"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

Tenant is an isolation boundary for control-plane identities and RBAC data.

type User added in v0.5.0

type User struct {
	ID              string    `json:"id"`
	TenantID        string    `json:"tenant_id"`
	Username        string    `json:"username"`
	DisplayName     string    `json:"display_name"`
	PasswordHash    string    `json:"-"`
	Status          string    `json:"status"`
	AuthProvider    string    `json:"auth_provider"`
	ExternalSubject *string   `json:"external_subject,omitempty"`
	CreatedAt       time.Time `json:"created_at"`
	UpdatedAt       time.Time `json:"updated_at"`
}

User is a human control-plane identity. PasswordHash is never serialized by the HTTP layer and contains only a slow password hash, never plaintext.

Jump to

Keyboard shortcuts

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