modgen

package
v1.7.0 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: MIT Imports: 15 Imported by: 2 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package modgen is the AI module generator module's domain layer: the brief, project, and validation value types, the generation/store ports, the envelope parser, and the Go/module-contract validator. Provider adapters (the OpenAI-compatible client) live in infrastructure; the filesystem store lives in store; neither is imported by the domain.

Index

Constants

View Source
const (
	// FindingSeverityError blocks install.
	FindingSeverityError = "error"
	// FindingSeverityWarning surfaces in the UI without blocking.
	FindingSeverityWarning = "warning"
)

Variables

View Source
var (
	// ErrInvalidBrief reports an empty or over-long generation brief.
	ErrInvalidBrief = errors.New("invalid brief")
	// ErrInvalidProjectName reports a module name outside the slug grammar.
	ErrInvalidProjectName = errors.New("invalid module name")
	// ErrPathNotAllowed reports a project file path outside the allowlist.
	ErrPathNotAllowed = errors.New("path not allowed")
	// ErrSizeLimitExceeded reports a project file or total exceeding the caps.
	ErrSizeLimitExceeded = errors.New("size limit exceeded")
	// ErrGenerationFailed reports an AI generation or repair failure.
	ErrGenerationFailed = errors.New("generation failed")
	// ErrProjectExists reports an install colliding with an existing project.
	ErrProjectExists = errors.New("project exists")
	// ErrProjectNotFound reports a lookup for a missing project.
	ErrProjectNotFound = errors.New("project not found")
	// ErrGenerationUnavailable reports generation without an AI key.
	ErrGenerationUnavailable = errors.New("generation unavailable")
	// ErrInvalidSurfaces reports an unknown surface declaration.
	ErrInvalidSurfaces = errors.New("invalid surfaces")
	// ErrApplyUnavailable reports an apply without an enabled applier: the
	// feature flag is off, no Go toolchain is on PATH, or the server does
	// not run from a source checkout.
	ErrApplyUnavailable = errors.New("apply unavailable")
	// ErrAlreadyApplied reports an apply for a module already present in
	// the checkout's modules tree.
	ErrAlreadyApplied = errors.New("already applied")
	// ErrTreeDirty reports an apply refused because a shared registry file
	// carries uncommitted operator changes, or a machine-owned path holds
	// hand-written files without the generated marker.
	ErrTreeDirty = errors.New("tree dirty")
	// ErrNotCheckout reports an apply outside a Lesstruct source checkout.
	ErrNotCheckout = errors.New("not a checkout")
	// ErrNotApplied reports an unapply for a module the checkout registry
	// does not hold. Only applied trees may be removed.
	ErrNotApplied = errors.New("not applied")
	// ErrConfirmationRequired reports a destructive call without its
	// explicit confirmation.
	ErrConfirmationRequired = errors.New("confirmation required")
	// ErrApplyFailed reports an apply whose writes or verification failed.
	ErrApplyFailed = errors.New("apply failed")
)

Functions

func IsKnownSurface

func IsKnownSurface(surface string) bool

IsKnownSurface reports whether surface names a generatable kernel capability surface.

func KnownSurfaces

func KnownSurfaces() []string

KnownSurfaces returns the canonical generatable surface list.

func ValidateBrief

func ValidateBrief(brief Brief) error

ValidateBrief enforces the generation brief contract: non-empty and capped at 5,000 runes; surfaces must be known when present (empty lets the model infer them from the description).

func ValidateProjectFiles

func ValidateProjectFiles(files map[string]string) error

ValidateProjectFiles enforces the v1 module contract: go.mod plus module.go plus README.md required, allowlisted paths only, per-file 512 KiB, 4 MiB total, and at most maxFileCount files.

func ValidateProjectName

func ValidateProjectName(name string) error

ValidateProjectName reports whether name is an installable module name: lowercase alphanumerics, hyphen-free (so the package clause needs no rename), 2–50 runes, not reserved.

Types

type Applier

type Applier interface {
	Apply(ctx context.Context, project Project, replace, confirm bool) (ApplyResult, error)
	Unapply(ctx context.Context, name string, confirm bool) (UnapplyResult, error)
	Applied(ctx context.Context) ([]string, error)
}

Applier stages a generated project into a source checkout: it copies the project tree, registers the module in the machine-writable registries, regenerates the custom-edition wiring, and verifies the result compiles and tests green. Apply is refused — never partial — when the checkout guard fails; verification failures keep the applied tree and report per-step outcomes instead of rolling back.

type ApplyResult

type ApplyResult struct {
	Applied         bool
	Verified        bool
	Steps           []ApplyStep
	AppliedModules  []string
	RequiresRestart bool
}

ApplyResult is the outcome of applying a staged project to a source checkout: whether the tree was written, whether verification passed, the per-step outcomes, and every module the custom edition now carries.

func NewApplyResult

func NewApplyResult(
	applied, verified bool,
	steps []ApplyStep,
	appliedModules []string,
	requiresRestart bool,
) ApplyResult

NewApplyResult assembles an apply result.

type ApplyStep

type ApplyStep struct {
	Name    string
	Passed  bool
	Skipped bool
	Output  string
}

ApplyStep is one verification outcome of an apply: the step name, whether it passed (or was skipped), and the failure-signaling output tail.

func NewApplyStep

func NewApplyStep(name string, passed, skipped bool, output string) ApplyStep

NewApplyStep assembles an apply verification step outcome.

type Brief

type Brief struct {
	Description string
	Surfaces    []string
}

Brief is the natural-language module request from the admin UI. Surfaces selects the kernel capability interfaces the module should implement; an empty list lets the model infer them from the description.

func NewBrief

func NewBrief(description string, surfaces []string) Brief

NewBrief assembles a generation brief from its parts.

type Finding

type Finding struct {
	Rule     string
	Severity string
	Message  string
}

Finding is one validation result: a rule hit with severity and detail. Errors block install; warnings surface in the UI only.

func NewFinding

func NewFinding(rule, severity, message string) Finding

NewFinding assembles a validation finding.

func ScanGeneratedProjectFiles

func ScanGeneratedProjectFiles(files map[string]string) []Finding

ScanGeneratedProjectFiles flags content a generated module must not ship that only string scanning can see: javascript: URLs in Go source. Import policy (cgo, os/exec, unsafe, syscall, plugin, net) lives in the AST validator, which never false-positives on comments or string literals. It runs only on the generation path so repair findings stay deterministic.

type InstalledProject

type InstalledProject struct {
	Name      string
	Surfaces  []string
	FileCount int
	CreatedAt time.Time
	Source    string
	Applied   bool
}

InstalledProject is the manifest projection the list endpoint serves: identity, declared surfaces, file count, creation time, provenance, and whether the project is applied to the checkout's modules tree.

func NewInstalledProject

func NewInstalledProject(
	name string,
	surfaces []string,
	fileCount int,
	createdAt time.Time,
	source string,
	applied bool,
) InstalledProject

NewInstalledProject assembles an installed-project projection.

type ModuleGenerationService

type ModuleGenerationService interface {
	GenerateProject(ctx context.Context, brief Brief, sources ModuleSources) (Project, error)
	RepairProject(ctx context.Context, brief Brief, sources ModuleSources, project Project, problems []string) (Project, error)
}

ModuleGenerationService generates module projects from a brief. Sources carries the readable kernel contract, the module grammar, and the exemplar sources the prompts ground on. RepairProject feeds validation problems back to the model and receives the same brief and sources so the contract stays identical.

type ModuleSources

type ModuleSources struct {
	Contract      string
	Grammar       string
	Examples      string
	KernelVersion string
}

ModuleSources is the prompt grounding: the distilled kernel contract, the module grammar (file layout and style rules), one exemplar module's sources, and the host versions the generated go.mod must pin.

func NewModuleSources

func NewModuleSources(
	contract, grammar, examples, kernelVersion string,
) ModuleSources

NewModuleSources assembles the prompt grounding material.

type Project

type Project struct {
	Name      string
	Surfaces  []string
	Files     map[string]string
	Rationale string
}

Project is a validated generated module project: an installable name, the kernel surfaces it implements, the relative-path → content file map the store persists, and the model's design rationale.

func NewProject

func NewProject(
	name string,
	surfaces []string,
	files map[string]string,
	rationale string,
) Project

NewProject assembles a project from its validated parts.

func ParseModuleEnvelope

func ParseModuleEnvelope(responseText string) (Project, error)

ParseModuleEnvelope validates the model's JSON envelope and splits it into a Project. The name and files run the slug and allowlist validators; markdown fences and surrounding commentary are rejected.

type ProjectManifest

type ProjectManifest struct {
	Name          string    `json:"name"`
	Surfaces      []string  `json:"surfaces"`
	KernelVersion string    `json:"kernelVersion"`
	Generator     string    `json:"generator"`
	CreatedAt     time.Time `json:"createdAt"`
	Source        string    `json:"source"`
}

ProjectManifest is the on-disk project.json metadata: identity, declared surfaces, the kernel version the generated go.mod pins, and provenance.

func NewProjectManifest

func NewProjectManifest(
	name string,
	surfaces []string,
	kernelVersion, generator string,
	createdAt time.Time,
	source string,
) ProjectManifest

NewProjectManifest assembles a manifest for an installed project.

type ProjectStore

type ProjectStore interface {
	Install(ctx context.Context, project Project) error
	List(ctx context.Context) ([]InstalledProject, error)
	Get(ctx context.Context, name string) (Project, error)
	Delete(ctx context.Context, name string) error
	Zip(ctx context.Context, name string) ([]byte, error)
}

ProjectStore persists generated projects on disk and builds download zips.

type ProjectValidator

type ProjectValidator interface {
	Validate(ctx context.Context, project Project) ValidationReport
}

ProjectValidator checks a generated project before install: size caps, Go parse shape, the kernel.Module contract, layer import policy, and migration hygiene.

func NewValidator

func NewValidator() ProjectValidator

NewValidator builds the default project validator without a kernel pin: the kernel require must exist, but its version is unchecked.

func NewValidatorWithKernelVersion

func NewValidatorWithKernelVersion(kernelVersion string) ProjectValidator

NewValidatorWithKernelVersion builds the default project validator pinned to the host kernel version the generated go.mod must require.

type Service

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

Service orchestrates module generation: brief validation, AI generation, validation gate with a bounded repair loop, and install as an inert source project under modules-gen/. Apply stages an installed project into a source checkout through the applier seam (nil applier disables applies).

func NewService

func NewService(
	generation ModuleGenerationService,
	validator ProjectValidator,
	store ProjectStore,
	sources func(ctx context.Context) ModuleSources,
) *Service

NewService builds the orchestration service. A nil store disables persistence (generation still validates); a nil sources func generates from the distilled contract alone.

func NewServiceWithApplier

func NewServiceWithApplier(
	generation ModuleGenerationService,
	validator ProjectValidator,
	store ProjectStore,
	applier Applier,
	sources func(ctx context.Context) ModuleSources,
) *Service

NewServiceWithApplier builds the orchestration service with a checkout applier. It is the constructor the composition root uses; NewService is the applier-less specialization tests and minimal embeddings use.

func (*Service) Apply

func (s *Service) Apply(ctx context.Context, name string, replace, confirm bool) (Project, ApplyResult, error)

Apply stages one installed project into the source checkout. The name resolves like Get; a nil applier reads as unavailable, like generation without a key.

func (*Service) Delete

func (s *Service) Delete(ctx context.Context, name string) (bool, error)

Delete removes an installed project, reporting whether the module is still applied in the checkout: the staged copy and the applied tree have independent lifecycles, and deleting the former must warn about the latter. The applied lookup degrades to unmarked on failure rather than failing the delete.

func (*Service) Generate

func (s *Service) Generate(
	ctx context.Context,
	brief Brief,
) (Project, ValidationReport, error)

Generate validates the brief, asks the model, validates the result, and installs it as an inert source project. A failing result is sent back to the model up to maxRepairAttempts times with its findings; a still-failing project is refused. The final report is returned alongside the project even on success so the UI can surface warnings.

func (*Service) Get

func (s *Service) Get(ctx context.Context, name string) (Project, error)

Get returns one installed project by name.

func (*Service) List

func (s *Service) List(ctx context.Context) ([]InstalledProject, error)

List returns the installed-project projections, marking each project the checkout applier reports as applied. A failing applied lookup degrades to unmarked rather than failing the list.

func (*Service) Unapply

func (s *Service) Unapply(ctx context.Context, name string, confirm bool) (UnapplyResult, error)

Unapply removes an applied module from the source checkout. Confirmation is enforced here so no caller can skip the destructive guard; the applier owns the registry-membership matrix.

func (*Service) Validate

func (s *Service) Validate(ctx context.Context, project Project) ValidationReport

Validate runs the validation gate without persisting.

func (*Service) Zip

func (s *Service) Zip(ctx context.Context, name string) ([]byte, error)

Zip builds the download archive for one installed project.

type UnapplyResult

type UnapplyResult struct {
	Removed          bool
	Verified         bool
	Steps            []ApplyStep
	AppliedModules   []string
	ModuleDirRemoved bool
}

UnapplyResult is the outcome of removing an applied module from a source checkout: whether anything was removed, whether the post-removal build passed, the per-step outcomes, the remaining edition modules, and whether the module tree itself was deleted (false when it was already gone).

func NewUnapplyResult

func NewUnapplyResult(
	removed, verified bool,
	steps []ApplyStep,
	appliedModules []string,
	moduleDirRemoved bool,
) UnapplyResult

NewUnapplyResult assembles an unapply result.

type ValidationReport

type ValidationReport struct {
	Valid    bool
	Findings []Finding
}

ValidationReport is the outcome of validating a project before install. Valid is false when any error-severity finding exists.

func NewFindingsReport

func NewFindingsReport(findings []Finding) ValidationReport

NewFindingsReport assembles a report whose Valid is derived from the findings: false when any error-severity finding exists.

func NewValidationReport

func NewValidationReport(valid bool, findings []Finding) ValidationReport

NewValidationReport assembles a validation report.

Jump to

Keyboard shortcuts

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