Documentation
¶
Overview ¶
Package transform implements BatchWeaver's first end-to-end transformation path: consuming semantic proof certificates, planning deterministic source-preserving rewrites, generating the first production transformation (static slice/array loop prefetch for certified read-only operations), and executing transformed code through Go build overlays without modifying the source tree.
The package never transforms a candidate unless a current, valid, strategy-specific proof certificate proves it eligible. It produces a versioned transformation IR that references stable analysis identities and proof certificates and never serializes AST nodes, SSA values, token positions, or pointer identities.
Transformation is non-mutating by default: plans are applied through a standard Go `-overlay` file so build, test, and run observe the transformed bytes while the working tree is untouched. Materialization is a separate, explicit, atomic, reversible operation with a backup manifest.
Index ¶
- Constants
- Variables
- func CleanPlans(root string) error
- func EnsureSavedOverlay(root string, plan *Plan) (string, int, error)
- func ListPlans(root string) ([]string, error)
- func ModuleRoot(dir string) (string, error)
- func OverlayManifestDigest(plan *Plan) string
- func PlanDiff(plan *Plan, context int) string
- func RenderInspect(w io.Writer, plan *Plan, candidate string)
- func RenderPlanJSON(w io.Writer, plan *Plan) error
- func RenderPlanText(w io.Writer, plan *Plan) error
- func RuntimeStrategies(s StrategyID) bool
- func SavePlan(root string, plan *Plan) error
- func UnifiedDiff(path string, original, transformed []byte, context int) string
- func VerifySQLSynthesisPlan(plan *Plan) error
- func WriteOverlay(root string, plan *Plan) (string, int, error)
- type BackupFile
- type BackupManifest
- type BuildConfig
- type Certificate
- type Diagnostic
- type Edit
- type EditKind
- type FilePlan
- type Filter
- type GeneratedRole
- type MaterializationState
- type MaterializeResult
- type Phase
- type Plan
- type RecoverStatus
- type Request
- type RevertResult
- type SQLPlanRequest
- type SkippedCandidate
- type SourceAnchor
- type SourceMap
- type SourceMapSegment
- type StrategyID
- type Transformation
- type ValidationState
- type ValidationSummary
Constants ¶
const ( AnchorExact = "exact" AnchorRelocatedUnique = "relocated-unambiguous" AnchorAmbiguous = "ambiguous" AnchorMissing = "missing" AnchorStructuralChanged = "structurally-changed" AnchorDigestMismatch = "digest-mismatch" )
Anchor resolution outcomes.
const ( SkipCertificateStale = "certificate-stale" SkipUnsupportedLoopForm = "unsupported-loop-form" SkipAssumptionMissing = "explicit-assumption-missing" SkipOverlappingRegion = "overlapping-source-region" SkipStrategyNotRequested = "strategy-not-requested" SkipNotEligible = "not-proven-eligible" SkipAnchorUnresolved = "source-anchor-unresolved" )
Skip reason codes.
const ( CodeSQLTransformInput = "BW3510" CodeSQLTransformPlan = "BW3511" CodeSQLTransformTypecheck = "BW3512" )
SQL transformation rejection codes. They remain in the BW35xx compiler transformation range and fail closed before an overlay is persisted.
const BackupManifestSchema = "batchweaver.backup/v1alpha1"
BackupManifestSchema versions the backup manifest.
const DefaultDiffContext = 3
DefaultDiffContext is the number of unchanged context lines around each hunk.
const RuntimeABIVersion = "batchweaver.bridge/v1alpha1"
RuntimeABIVersion identifies the generated-bridge ABI the transformer targets. It must match the bridge package's ABI version; a mismatch invalidates plans.
const SchemaVersion = "batchweaver.transform/v1alpha1"
SchemaVersion identifies the transformation IR schema. It is independent from the analysis and proof schema versions and is alpha because the model is not yet a stable public contract.
const SourceMapSchema = "batchweaver.sourcemap/v1alpha1"
SourceMapSchema versions the source-map artifact.
const StateDir = ".batchweaver"
StateDir is the ignored directory under the workspace root where plans, overlays, and backups live.
const StrategyVersion = "1"
StrategyVersion versions the strategy implementations. It contributes to plan identity so regenerated plans invalidate when the generator changes.
Variables ¶
var ErrSQLTransformation = errors.New("SQL synthesis transformation rejected")
ErrSQLTransformation marks a rejected SQL source-generation plan.
Functions ¶
func CleanPlans ¶
CleanPlans removes all cached transformation plans under the workspace root.
func EnsureSavedOverlay ¶
EnsureSavedOverlay saves a plan (if needed) and writes its overlay, returning the overlay path.
func ModuleRoot ¶
ModuleRoot returns the workspace module root for a directory. It is exported for command wiring.
func OverlayManifestDigest ¶
OverlayManifestDigest returns a stable digest of a plan's overlay mapping in workspace-relative terms, for recording in execution results.
func PlanDiff ¶
PlanDiff renders the full unified diff for a plan across all files in stable path order. Created files are shown as additions against /dev/null.
func RenderInspect ¶
RenderInspect writes a detailed inspection of a plan, optionally filtered to one candidate.
func RenderPlanJSON ¶
RenderPlanJSON writes the plan as deterministic, indented JSON.
func RenderPlanText ¶
RenderPlanText writes the human-readable transformation-plan summary.
func RuntimeStrategies ¶
func RuntimeStrategies(s StrategyID) bool
RuntimeStrategies reports whether s lowers a call site through the runtime bridge (as opposed to a purely static rewrite).
func SavePlan ¶
SavePlan persists a plan and its transformed file bytes under the workspace state directory using atomic writes. Transformed bytes are stored content-addressed; the deterministic plan.json stores only digests.
func UnifiedDiff ¶
UnifiedDiff returns a deterministic unified diff between original and transformed content. Paths are rendered with the conventional a/ and b/ prefixes. No timestamps are emitted, so the output is stable across runs and hosts.
func VerifySQLSynthesisPlan ¶
VerifySQLSynthesisPlan rechecks a persisted SQL plan's content hashes, generated symbols, structural state, and canonical plan identity. SQL plans are generated from an explicit query rather than rediscovered Go call sites, so verification is self-contained and does not rerun general candidate analysis.
func WriteOverlay ¶
WriteOverlay writes a Go command overlay manifest for a saved plan, mapping each original source file to its content-addressed transformed backing file. It returns the absolute overlay path and the number of mapped files. The plan must already be saved (its backing files present under the state directory).
Types ¶
type BackupFile ¶
type BackupFile struct {
Path string `json:"path"`
OriginalDigest string `json:"original_digest"`
TransformedDigest string `json:"transformed_digest"`
BackupObject string `json:"backup_object"`
Committed bool `json:"committed"`
// Created is true for a generated file that did not exist before
// materialization; revert deletes it rather than restoring an original.
Created bool `json:"created,omitempty"`
}
BackupFile is one file's backup entry.
type BackupManifest ¶
type BackupManifest struct {
SchemaVersion string `json:"schema_version"`
MaterializationID string `json:"materialization_id"`
PlanID string `json:"plan_id"`
Workspace string `json:"workspace"`
Tool string `json:"tool"`
State MaterializationState `json:"state"`
Files []BackupFile `json:"files"`
}
BackupManifest records everything needed to revert a materialization.
type BuildConfig ¶
type BuildConfig struct {
GOOS string `json:"goos,omitempty"`
GOARCH string `json:"goarch,omitempty"`
Tags []string `json:"tags,omitempty"`
Tests bool `json:"tests,omitempty"`
}
BuildConfig records the build configuration a plan is valid for.
type Certificate ¶
type Certificate struct {
CandidateID string
ProofID string
Operation string
Location string
Decision proof.Decision
Strategies map[string]proof.Decision // strategy -> per-strategy status
Assumptions []string
NonGuarantees []string
CandidateDigest string
}
Certificate is a typed, validated view of a proof certificate. The transformation strategy consumes this rather than raw proof JSON.
type Diagnostic ¶
type Diagnostic struct {
Code string `json:"code"`
Severity string `json:"severity"`
Message string `json:"message"`
Location string `json:"location,omitempty"`
Candidate string `json:"candidate,omitempty"`
Plan string `json:"plan,omitempty"`
Remediation string `json:"remediation,omitempty"`
Fingerprint string `json:"fingerprint"`
}
Diagnostic is a transformation diagnostic (BW3xxx range documented in docs/reference/diagnostics.md).
type Edit ¶
type Edit struct {
ID string `json:"id"`
File string `json:"file"`
Kind EditKind `json:"kind"`
StartOffset int `json:"start_offset"`
EndOffset int `json:"end_offset"`
OriginalDigest string `json:"original_digest"`
Replacement string `json:"replacement"`
Transformation string `json:"transformation"`
Order int `json:"order"`
}
Edit is an immutable source edit.
type EditKind ¶
type EditKind string
EditKind is the kind of a source edit. Only implemented kinds are exposed.
type FilePlan ¶
type FilePlan struct {
Path string `json:"path"`
OriginalDigest string `json:"original_digest"`
TransformedDigest string `json:"transformed_digest"`
InsertedLines int `json:"inserted_lines"`
RemovedLines int `json:"removed_lines"`
// Created is true for a generated file that does not exist in the source tree
// (for example a runtime bridge file). Such files are added by the overlay and
// created (not backed up) by materialization; revert removes them.
Created bool `json:"created,omitempty"`
// Generated is true for a BatchWeaver-generated file carrying the
// "DO NOT EDIT" header. It is always also Created.
Generated bool `json:"generated,omitempty"`
// contains filtered or unexported fields
}
FilePlan describes the transformed content of one file.
func (FilePlan) Transformed ¶
Transformed returns the generated bytes for a file plan (in-memory only).
type GeneratedRole ¶
type GeneratedRole string
GeneratedRole classifies a source-map segment.
const ( RoleInvariantBinding GeneratedRole = "invariant-binding" RoleKeyCollection GeneratedRole = "key-collection" RoleBatchCall GeneratedRole = "batch-call" RoleGlobalErrorCheck GeneratedRole = "global-error-check" RoleResultRecon GeneratedRole = "result-reconstruction" RoleScalarReplay GeneratedRole = "scalar-order-replay" RoleSQLSynthesis GeneratedRole = "sql-synthesis" )
Generated roles.
type MaterializationState ¶
type MaterializationState string
MaterializationState is the lifecycle state of a materialization.
const ( MatPlanned MaterializationState = "planned" MatWriting MaterializationState = "writing" MatCommitted MaterializationState = "committed" MatReverted MaterializationState = "reverted" MatRevertConflict MaterializationState = "revert-conflict" MatRecoveryReq MaterializationState = "recovery-required" )
Materialization states.
type MaterializeResult ¶
MaterializeResult summarizes a materialization.
func Materialize ¶
func Materialize(root, tool string, plan *Plan) (*MaterializeResult, error)
Materialize writes a plan's transformed files into the working tree after verifying every source precondition, taking a full backup first. It is atomic per file and refuses to proceed if any source file changed since planning.
type Phase ¶
type Phase string
Phase names a generated transformation phase. Only phases actually required by a transformation appear in its IR.
const ( PhaseBindInvariants Phase = "bind-invariants" PhaseCollectKeys Phase = "collect-keys" PhaseInvokeBatch Phase = "invoke-batch-provider" PhaseValidateGlobal Phase = "validate-global-result" PhaseMapResults Phase = "map-results" PhaseReplayScalarOrder Phase = "replay-scalar-order" PhaseExecuteOriginal Phase = "execute-original-body" PhaseFinalize Phase = "finalize" PhaseSynthesizeSQL Phase = "synthesize-sql" )
Transformation phases.
type Plan ¶
type Plan struct {
SchemaVersion string `json:"schema_version"`
ID string `json:"id"`
Workspace string `json:"workspace"`
Toolchain string `json:"toolchain"`
BuildConfig BuildConfig `json:"build_config"`
AnalysisDigest string `json:"analysis_digest"`
ProofSchema string `json:"proof_schema"`
ContractDigest string `json:"contract_digest,omitempty"`
StrategyVersion string `json:"strategy_version"`
Transformations []Transformation `json:"transformations"`
Files []FilePlan `json:"files"`
Skipped []SkippedCandidate `json:"skipped,omitempty"`
Diagnostics []Diagnostic `json:"diagnostics,omitempty"`
Validation ValidationSummary `json:"validation"`
Digest string `json:"digest"`
}
Plan is the deterministic, versioned transformation plan for a workspace.
func BuildPlan ¶
BuildPlan builds a deterministic transformation plan for the requested packages. It consumes proof certificates and transforms only candidates that are currently proven eligible for a requested strategy. It never modifies source files.
func BuildSQLSynthesisPlan ¶
func BuildSQLSynthesisPlan(ctx context.Context, req SQLPlanRequest) (*Plan, error)
BuildSQLSynthesisPlan creates a content-addressed transformation plan whose generated Go file exposes the synthesized query and its integrity digest. It type-checks the new file in an in-memory overlay and does not write source.
type RecoverStatus ¶
type RecoverStatus struct {
MaterializationID string
State MaterializationState
CommittedFiles int
TotalFiles int
}
RecoverStatus reports the recoverable state of an interrupted materialization.
func Recover ¶
func Recover(root string) ([]RecoverStatus, error)
Recover inspects incomplete materializations under the workspace and reports their state. It is idempotent and never mutates source files on its own.
type Request ¶
type Request struct {
Patterns []string
Dir string
Strategies []StrategyID
BuildConfig BuildConfig
Filter Filter
ToolVersion string
Toolchain string
}
Request describes a transformation-planning run.
type RevertResult ¶
RevertResult summarizes a revert.
func Revert ¶
func Revert(root, matID string) (*RevertResult, error)
Revert restores the original files recorded in a materialization backup. It refuses to overwrite files that were edited after materialization (a transformed-digest mismatch) and reports them as conflicts.
type SQLPlanRequest ¶
type SQLPlanRequest struct {
Workspace string
PackageName string
PackagePath string
Output string
Constant string
Operation string
Synthesis adapter.SynthPlan
}
SQLPlanRequest describes a generated, compile-checked Go binding for one validated SQL synthesis plan. Output is workspace-relative and must name a new .go file in the target package.
type SkippedCandidate ¶
type SkippedCandidate struct {
CandidateID string `json:"candidate_id"`
Operation string `json:"operation"`
Reason string `json:"reason"`
Detail string `json:"detail,omitempty"`
}
SkippedCandidate records a proven candidate not transformed and why.
type SourceAnchor ¶
type SourceAnchor struct {
File string `json:"file"`
Package string `json:"package"`
Function string `json:"function"`
StartLine int `json:"start_line"`
StartCol int `json:"start_col"`
EndLine int `json:"end_line"`
EndCol int `json:"end_col"`
StructuralHash string `json:"structural_hash"`
Resolution string `json:"resolution"`
}
SourceAnchor locates a candidate in a way tolerant of unrelated edits.
type SourceMap ¶
type SourceMap struct {
SchemaVersion string `json:"schema_version"`
PlanID string `json:"plan_id"`
Segments []SourceMapSegment `json:"segments"`
}
SourceMap is a versioned map from generated code back to candidates and roles.
func BuildSourceMap ¶
BuildSourceMap builds a source map for a plan. Segments are located by scanning each transformed file for the generated identifiers of each transformation. The mapping is line-granular and deterministic; sub-line precision is a documented limitation of this stage.
type SourceMapSegment ¶
type SourceMapSegment struct {
ID string `json:"id"`
File string `json:"file"`
GeneratedStart int `json:"generated_start_line"`
GeneratedEnd int `json:"generated_end_line"`
Role GeneratedRole `json:"role"`
Transformation string `json:"transformation"`
Candidate string `json:"candidate"`
Certificate string `json:"certificate"`
}
SourceMapSegment maps generated code back to a candidate and role.
type StrategyID ¶
type StrategyID string
StrategyID names a transformation strategy.
const ( // StrategyStaticLoopPrefetch hoists proven-safe key collection and a single // batch call out of a certified read-only slice/array loop, then replays // results in source order. StrategyStaticLoopPrefetch StrategyID = "static-loop-prefetch" // StrategyRuntimeCallCoalescing lowers a certified standalone or sibling // scalar call site into a typed runtime bridge call that coalesces compatible // same-scope calls and falls back to the scalar call when no scope is active. StrategyRuntimeCallCoalescing StrategyID = "runtime-call-coalescing" // StrategyStaticSiblingFusion lowers a straight-line group of certified // sibling scalar calls through the runtime bridge, preserving lexical order. StrategyStaticSiblingFusion StrategyID = "static-sibling-fusion" // StrategyFanoutCoalescing lowers certified scalar calls that already run // concurrently (goroutine or errgroup fan-out) through the runtime bridge, // which coalesces the naturally overlapping calls without adding concurrency. StrategyFanoutCoalescing StrategyID = "fanout-coalescing" // StrategyErrgroupCoalescing is the errgroup-specific fan-out lowering; it // shares the runtime-bridge mechanism with fanout-coalescing. StrategyErrgroupCoalescing StrategyID = "errgroup-coalescing" // StrategyExactKeySQLSynthesis generates a content-addressed PostgreSQL // batch-query binding for a validated scalar exact-key read. StrategyExactKeySQLSynthesis StrategyID = "exact-key-sql-synthesis" // StrategyCompositeKeySQLSynthesis extends exact-key generation to multiple // parameterized key components with deterministic placeholder ordering. StrategyCompositeKeySQLSynthesis StrategyID = "composite-key-sql-synthesis" // StrategyBoundedJoinSQLSynthesis generates a query only for a parsed join // carrying an explicit at-most-one cardinality contract. StrategyBoundedJoinSQLSynthesis StrategyID = "bounded-join-sql-synthesis" )
type Transformation ¶
type Transformation struct {
ID string `json:"id"`
CandidateID string `json:"candidate_id"`
CertificateID string `json:"certificate_id"`
Strategy StrategyID `json:"strategy"`
Operation string `json:"operation"`
Source SourceAnchor `json:"source"`
Phases []Phase `json:"phases"`
GeneratedSymbols []string `json:"generated_symbols"`
Edits []string `json:"edit_ids"`
Assumptions []string `json:"assumptions,omitempty"`
NonGuarantees []string `json:"non_guarantees,omitempty"`
// Bridge is the workspace-relative path of the generated runtime bridge file
// this transformation depends on, for runtime-lowering strategies.
Bridge string `json:"bridge,omitempty"`
// RuntimeABI is the bridge ABI version, present for runtime-lowering
// strategies; a mismatch invalidates the transformation.
RuntimeABI string `json:"runtime_abi,omitempty"`
Digest string `json:"digest"`
}
Transformation is one certified, planned rewrite.
type ValidationState ¶
type ValidationState string
ValidationState is the outcome of a validation phase.
const ( ValidationNotRun ValidationState = "not-run" ValidationPassed ValidationState = "passed" ValidationFailed ValidationState = "failed" ValidationSkipped ValidationState = "skipped-with-reason" )
Validation states.
type ValidationSummary ¶
type ValidationSummary struct {
Parse ValidationState `json:"parse"`
TypeCheck ValidationState `json:"type_check"`
Preconditions ValidationState `json:"proof_preconditions"`
Structural ValidationState `json:"structural_verification"`
Detail string `json:"detail,omitempty"`
}
ValidationSummary records plan-level validation outcomes.