migrationai

package
v1.1.2 Latest Latest
Warning

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

Go to latest
Published: May 15, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package migrationai provides AST-based schema delta detection and AI-assisted SQL migration generation for nSelf projects.

Index

Constants

This section is empty.

Variables

View Source
var ExportedSanitizeSlug = sanitizeSlug

ExportedSanitizeSlug is a test-only export of the sanitizeSlug function. Use sanitizeSlug directly in production code.

Functions

func DeleteMigrationFile

func DeleteMigrationFile(path string) error

DeleteMigrationFile removes a staged migration file (user rejected the proposal). It is a no-op if the file does not exist.

func DiffSummary

func DiffSummary(deltas []SchemaFieldDelta) string

DiffSummary returns a human-readable summary of the detected schema deltas.

func WriteMigrationFile

func WriteMigrationFile(migrationsDir, slug, sql, warningSQL string) (string, error)

WriteMigrationFile stages the migration file at migrationsDir/YYYYMMDDHHMMSS_auto_<slug>.sql. It enforces the additive-only rule: any DROP, TRUNCATE, or DELETE statement in the SQL body is converted to a comment warning regardless of AI output.

Returns the absolute path of the written file.

Types

type Config

type Config struct {
	// AIEndpoint is the base URL of the nself-ai plugin service.
	// Defaults to http://localhost:3001 (standard plugin-ai port).
	AIEndpoint string

	// ConfidenceMin is the minimum AI confidence required to accept a proposal.
	// Proposals below this threshold are rejected. Defaults to 0.75.
	ConfidenceMin float64

	// MigrationsDir is the directory where migration files are written.
	// Defaults to "migrations" in the current working directory.
	MigrationsDir string

	// AutoApply controls whether to apply the migration automatically.
	// This MUST always be false in production. The field exists only for
	// programmatic use in tests. The CLI enforces this via the env guard.
	AutoApply bool

	// Timeout for AI calls. Defaults to 30s.
	Timeout time.Duration
}

Config holds all parameters for the migration generator.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns a Config populated from environment variables. NSELF_MIGRATION_WATCH_ENABLED, NSELF_MIGRATION_AI_CONFIDENCE_MIN, and NSELF_MIGRATION_AUTO_APPLY are read but the CLI enforces AutoApply=false regardless of environment in production profiles.

type DartClass

type DartClass struct {
	Name   string
	Fields []DartField
}

DartClass represents a parsed Dart class and its fields.

func ParseDartClasses

func ParseDartClasses(src string) []DartClass

ParseDartClasses scans Dart source text and returns all class definitions with their field names and types. Constructor parameters are not included.

type DartField

type DartField struct {
	Name  string
	Type  string
	Final bool
	Late  bool
}

DartField is a single field extracted from a Dart class.

type ErrLowConfidence

type ErrLowConfidence struct {
	Got      float64
	Required float64
}

ErrLowConfidence is returned when the AI confidence score is below the minimum threshold.

func (*ErrLowConfidence) Error

func (e *ErrLowConfidence) Error() string

type GenerateRequest

type GenerateRequest struct {
	Prompt     string             `json:"prompt"`
	Deltas     []SchemaFieldDelta `json:"deltas,omitempty"`
	SchemaHint string             `json:"schema_hint,omitempty"`
}

GenerateRequest is the request sent to the AI migration endpoint.

type GenerateResponse

type GenerateResponse struct {
	SQL        string  `json:"sql"`
	WarningSQL string  `json:"warning_sql,omitempty"`
	Confidence float64 `json:"confidence"`
	AIModel    string  `json:"ai_model"`
}

GenerateResponse is the response from the AI migration endpoint.

type Generator

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

Generator produces AI-assisted SQL migration proposals from natural-language prompts.

func NewGenerator

func NewGenerator(cfg Config) *Generator

NewGenerator creates a Generator with the given config.

func (*Generator) Generate

func (g *Generator) Generate(ctx context.Context, prompt string, deltas []SchemaFieldDelta) (*MigrationProposal, error)

Generate calls the AI plugin to produce a migration proposal for the given prompt. deltas may be nil when the prompt is the sole input (nself migrate generate mode).

Returns ErrLowConfidence when the AI model's confidence is below ConfidenceMin.

type GoField

type GoField struct {
	Name    string
	Type    string
	Tag     string // raw struct tag value (may contain `db:"..."` or `json:"..."`)
	Pointer bool
}

GoField represents a single field extracted from a Go struct.

type GoStruct

type GoStruct struct {
	Name   string
	Fields []GoField
}

GoStruct represents a parsed struct and its fields.

func ParseGoStructs

func ParseGoStructs(src string) ([]GoStruct, error)

ParseGoStructs parses Go source code and returns all exported structs and their fields. It only inspects exported types (capitalized name) that are struct kinds. Source must be valid Go; parse errors are returned verbatim.

type MigrationProposal

type MigrationProposal struct {
	// Slug is the sanitized natural-language description used in the filename.
	Slug string

	// SQL is the proposed migration SQL (additive only in default mode).
	SQL string

	// WarningSQL contains DROP or dangerous statements the AI suggested but that
	// the additive-only guard blocked. It is surfaced as a comment in the migration file.
	WarningSQL string

	// Confidence is a 0.0–1.0 value returned by the AI model.
	Confidence float64

	// AIModel is the model that generated the proposal.
	AIModel string

	// FilePath is the path to the staged migration file.
	FilePath string
}

MigrationProposal is the result of an AI-assisted migration generation.

type Op

type Op int

Op is the type of schema field change detected.

const (
	OpAdd    Op = iota // field added to a struct/interface/class
	OpRemove           // field removed from a struct/interface/class
)

type SchemaFieldDelta

type SchemaFieldDelta struct {
	StructName string
	FieldName  string
	FieldType  string
	Tag        string // struct tag if available
	Op         Op
}

SchemaFieldDelta describes a single field-level schema change.

func DiffDartClasses

func DiffDartClasses(old, new []DartClass) []SchemaFieldDelta

DiffDartClasses computes the field-level delta between old and new Dart classes.

func DiffGoStructs

func DiffGoStructs(old, new []GoStruct) []SchemaFieldDelta

DiffGoStructs computes the field-level delta between an old and new version of a struct. It matches structs by name and returns a SchemaFieldDelta slice. Structs that appear only in old are flagged as removed (which triggers the additive-only safety guard in the proposal writer).

func DiffTSInterfaces

func DiffTSInterfaces(old, new []TSInterface) []SchemaFieldDelta

DiffTSInterfaces computes the field-level delta between old and new TypeScript interfaces.

type TSField

type TSField struct {
	Name     string
	Type     string
	Optional bool // true when the declaration uses `name?: type`
}

TSField is a single field extracted from a TypeScript interface or type alias.

type TSInterface

type TSInterface struct {
	Name   string
	Fields []TSField
}

TSInterface represents a parsed TypeScript interface and its fields.

func ParseTSInterfaces

func ParseTSInterfaces(src string) []TSInterface

ParseTSInterfaces scans TypeScript source text and returns all interface-like definitions with their field names and types. This is a best-effort heuristic parser. For production diff accuracy use ts-morph.

Jump to

Keyboard shortcuts

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