model

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Sep 29, 2026 License: AGPL-3.0 Imports: 1 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

This section is empty.

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
	Name       string
	Owner      *string
	Status     string
	APIKeyHash string
	Level      string
	ExpiresAt  *time.Time
	CreatedAt  time.Time
	UpdatedAt  time.Time
}

Agent is an authenticated AI database client.

type Approval

type Approval struct {
	ID        string
	AuditID   *int64
	AgentID   *string
	SQLRaw    *string
	Reason    *string
	Status    string
	Approver  *string
	DecidedAt *time.Time
	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
	DatasourceID *string
	SessionID    *string
	MCPTool      *string
	Decisions    []string
	StmtTypes    []string
	RiskMin      *int
	RiskMax      *int
	Keyword      string
	ObjectLike   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
	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 supported database dialect: postgres or mysql.

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
	Name          string
	DBType        string
	Host          string
	Port          int
	Database      string
	Username      string
	PasswordEnc   string
	ConnLimit     int
	StmtTimeoutMS int
	RowLimit      int
	CreatedAt     time.Time
	UpdatedAt     time.Time
}

Datasource is a protected PostgreSQL or MySQL connection target.

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
	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
	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 Policy

type Policy struct {
	ID                    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
	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
	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
	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
	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 Rule

type Rule struct {
	ID          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.

Jump to

Keyboard shortcuts

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