validate

package
v0.7.179 Latest Latest
Warning

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

Go to latest
Published: Sep 14, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Index

Constants

View Source
const DefaultMaxAttempts = 3

DefaultMaxAttempts is the default number of consecutive Stop hook re-signals before chunk gives up and tells the agent to ask the user for help.

View Source
const DefaultTimeout = 300

DefaultTimeout is the per-command execution timeout in seconds.

Variables

View Source
var ErrNotConfigured = errors.New("no validate commands configured")

ErrNotConfigured indicates no validate commands are configured.

View Source
var ErrWorkspaceNotFound = errors.New("workspace directory not found on sidecar")

ErrWorkspaceNotFound is returned when the remote workspace directory does not exist.

Functions

func BuildCacheKey added in v0.7.144

func BuildCacheKey(in CacheKeyInputs) (string, bool)

BuildCacheKey constructs the cache key for a validate run from the working-tree fingerprint, the serialized project config, and the execution target.

The second return value is false when the fingerprint is the zero Worktree — gitutil.Fingerprint could not establish the tree's state — or the config cannot be serialized. Callers must not read or write the cache in that case: with no trustworthy git state the key would depend only on the config and would therefore stay stable across code changes, turning every subsequent run into a false cache hit.

func ExpandCommand added in v0.7.147

func ExpandCommand(workDir, command string) string

ExpandCommand replaces template variables in command before execution. {{CHANGED_PACKAGES}} expands to the space-separated list of Go package paths whose source files appear in `git diff HEAD`. Expands to "./..." when no .go files changed.

Exported because every path that ships a configured command somewhere else to run must expand it first. Skipping expansion does not fail loudly: the literal {{CHANGED_PACKAGES}} reaches the shell, which exits non-zero for a reason that has nothing to do with the code under test.

func HooksDisabled added in v0.7.51

func HooksDisabled(workDir string, envDisabled bool) bool

HooksDisabled reports whether chunk validate hooks are currently suppressed. envDisabled should be set by the caller from CHUNK_HOOKS_DISABLED; it returns true when that flag is set or the sentinel file .chunk/hooks-disabled exists under workDir. On any error other than ErrNotExist the function fails open (returns false) so hooks continue to run when the check is uncertain.

func List

func List(cfg *config.ProjectConfig, status iostream.StatusFunc) error

List prints all configured command names and their run strings, tagged with where each one runs and any role that decides it. Without the tags there is no way to see which commands `chunk validate --mark-remote` would change.

func NewHookExitError added in v0.7.51

func NewHookExitError(code int) error

NewHookExitError returns a HookExitError with the given exit code.

func ReadAttempts added in v0.7.143

func ReadAttempts(sessionID string) int

ReadAttempts returns the current failure count for the given session without modifying it. Returns 0 when no state file exists.

func ResetAttempts added in v0.7.31

func ResetAttempts(sessionID string)

ResetAttempts clears the failure counter for the given session.

func RunDryRun

func RunDryRun(cfg *config.ProjectConfig, name string, status iostream.StatusFunc) error

RunDryRun prints commands without executing them.

func RunRemote

func RunRemote(ctx context.Context, execFn func(ctx context.Context, script string) (stdout, stderr string, exitCode int, err error), cfg *config.ProjectConfig, name, dest, localWorkDir string, status iostream.StatusFunc, streams iostream.Streams) error

RunRemote runs commands on a remote sidecar via SSH. If name is non-empty, only the named command is run. localWorkDir is used to expand {{CHANGED_PACKAGES}} against the local git diff before sending the command to the remote (which has a clean checkout).

func RunRemoteInline added in v0.7.29

func RunRemoteInline(ctx context.Context, execFn func(ctx context.Context, script string) (stdout, stderr string, exitCode int, err error), name, command, dest string, status iostream.StatusFunc, streams iostream.Streams) error

RunRemoteInline runs a single inline command on a remote sidecar via SSH.

func RunRemoteInlineStreamed added in v0.7.179

func RunRemoteInlineStreamed(ctx context.Context, execFn func(ctx context.Context, script string) (stdout, stderr string, exitCode int, err error), name, command, dest string, status iostream.StatusFunc, streams iostream.Streams) error

RunRemoteInlineStreamed runs an inline remote command whose executor has already written stdout and stderr to streams as they arrive.

func RunRemoteStreamed added in v0.7.179

func RunRemoteStreamed(ctx context.Context, execFn func(ctx context.Context, script string) (stdout, stderr string, exitCode int, err error), cfg *config.ProjectConfig, name, dest, localWorkDir string, status iostream.StatusFunc, streams iostream.Streams) error

RunRemoteStreamed runs remote commands whose executor has already written stdout and stderr to streams as they arrive.

func TestSuitesTemplate added in v0.7.52

func TestSuitesTemplate(workDir string) string

TestSuitesTemplate returns the contents of .circleci/test-suites.yml for the detected toolchain in workDir, or "" if no toolchain template applies.

The returned YAML targets CircleCI Smarter Testing: `<< test.atoms >>` is substituted at run time with the subset of test atoms picked by the platform.

func TrackFailedAttempt added in v0.7.31

func TrackFailedAttempt(sessionID string, warn io.Writer) int

TrackFailedAttempt increments the failure counter for the given session and returns the new count. warn is an optional writer for diagnostic messages (pass nil to suppress).

func WorkspaceExists added in v0.7.49

func WorkspaceExists(ctx context.Context, execFn func(context.Context, string) (string, string, int, error), dest string) error

WorkspaceExists checks whether dest exists as a directory on the remote sidecar.

func WrapHookResult added in v0.7.31

func WrapHookResult(sessionID string, execErr error, maxAttempts int, warn io.Writer) error

WrapHookResult applies Stop hook lifecycle to the result of running validate commands. On success it resets the attempt counter. On failure it increments the counter and returns a HookExitError with code 2 to re-signal the agent, or prints a give-up message and returns nil once maxAttempts is reached.

Types

type CacheKeyInputs added in v0.7.144

type CacheKeyInputs struct {
	// Worktree fingerprints the tree the run will validate.
	Worktree gitutil.Worktree
	// CommandName is the single command being run, or "" when all commands run.
	CommandName string
	// Config is the project config driving the run, hashed whole. The commands
	// are the obvious input, but the environment block decides what those
	// commands run against, and a project that gitignores .chunk/ gets no
	// invalidation from the working-tree digest when any of it changes.
	Config *config.ProjectConfig
	// Target identifies where the commands execute: "" for a local run,
	// otherwise an opaque description of the sidecar. Sidecar routing depends on
	// mutable state outside the repo, so it has to participate in the key — a
	// working tree validated against one sidecar says nothing about another.
	Target string
}

CacheKeyInputs collects the working-tree fingerprint plus everything outside the tree that can change the outcome of a validate run.

type CachedResult

type CachedResult struct {
	CachedAt time.Time `json:"cached_at"`
}

CachedResult records the timestamp of a successful validate run. Only successful runs are cached; failures are never stored so the agent always retries after a fix, even when the working tree has not changed.

CachedAt is a debugging breadcrumb: presence of the entry is what marks a run as successful, and expiry works off the entry file's modification time, which records the same instant. It is here so a cache directory can be read by eye.

type Detection added in v0.7.174

type Detection struct {
	Commands []config.Command
	Source   string   // human-readable origin, empty when nothing was detected
	Notes    []string // what detection could not resolve
}

Detection is the outcome of validate-command detection: the commands, where they came from, and anything detection could not resolve. Provenance matters to the user — commands lifted from a CircleCI config can look nothing like the toolchain defaults, and a bare list gives no way to tell why.

func DetectCommands added in v0.7.2

func DetectCommands(ctx context.Context, claude *anthropic.Client, workDir string) (Detection, error)

DetectCommands returns the full set of validate commands for the repo with metadata.

A checked-in CircleCI config is preferred over everything else: it names the checks that actually gate the branch, where root filenames only suggest a toolchain. Repos whose real build system is outranked by a stray manifest — a bazel monorepo containing a package.json, say — are misdetected otherwise.

Failing that, known toolchains return richer commands without calling Claude. Claude is only used as a fallback for unknown toolchains, and only when a client is provided.

type DistributedJobResult added in v0.7.179

type DistributedJobResult struct {
	Passed         int
	Fallback       bool
	Err            error
	UnavailableErr error
}

DistributedJobResult reports the outcome of one remotely scheduled command.

type DistributedRunOptions added in v0.7.179

type DistributedRunOptions[T any] struct {
	Parallelism int
	Acquire     func(context.Context) (T, error)
	Release     func(T)
	WorkerName  func(T) string
	Run         func(context.Context, T, config.Command, iostream.StatusFunc, iostream.Streams) DistributedJobResult
	Status      iostream.StatusFunc
	Streams     iostream.Streams
}

DistributedRunOptions supplies resource management and command execution. The scheduler owns jobs; Acquire and Release adapt any concrete worker pool.

type DistributedRunOutput added in v0.7.179

type DistributedRunOutput struct {
	Command config.Command
	Stdout  string
	Stderr  string
}

DistributedRunOutput is buffered output from one concurrently run command.

type DistributedRunResult added in v0.7.179

type DistributedRunResult struct {
	Passed         int
	FellBack       []config.Command
	Output         []DistributedRunOutput
	Err            error
	UnavailableErr error
}

DistributedRunResult aggregates remotely scheduled validation commands.

func RunDistributed added in v0.7.179

func RunDistributed[T any](ctx context.Context, commands []config.Command, opts DistributedRunOptions[T]) DistributedRunResult

RunDistributed schedules commands in configuration order onto the next available worker. A worker is held for the run and consumes commands from a shared queue, so faster workers naturally process more jobs.

type HookExitError added in v0.7.31

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

HookExitError signals a specific process exit code without printing additional error output. All output must be written before this error is returned.

func (*HookExitError) Error added in v0.7.31

func (e *HookExitError) Error() string

func (*HookExitError) ExitCode added in v0.7.31

func (e *HookExitError) ExitCode() int

type PackageManager added in v0.7.2

type PackageManager struct {
	Name           string
	InstallCommand string
}

PackageManager holds the name and CI-safe install command for a detected package manager.

func DetectPackageManager added in v0.7.2

func DetectPackageManager(workDir string) *PackageManager

DetectPackageManager returns the detected package manager and its CI-safe install command, or nil.

type Placement added in v0.7.179

type Placement uint8

Placement controls where validation commands execute.

const (
	// PlacementRemote runs every selected command remotely.
	PlacementRemote Placement = iota
	// PlacementLocal runs every selected command locally.
	PlacementLocal
	// PlacementConfigured honors explicit local placement and defaults to remote.
	PlacementConfigured
)

type Plan added in v0.7.179

type Plan struct {
	LocalCommands  []config.Command
	RemoteCommands []config.Command
	PoolSize       int
}

Plan separates command placement from the number of remote workers needed.

func PlanCommands added in v0.7.179

func PlanCommands(commands []config.Command, placement Placement, maxRemoteWorkers int) Plan

PlanCommands assigns commands to local or remote execution and caps the remote worker count to the amount of remote work available.

type Result added in v0.7.151

type Result struct {
	Passed int
	Total  int
}

Result holds the pass/fail counts from a validate run.

func RunAll

func RunAll(ctx context.Context, workDir string, cfg *config.ProjectConfig, envVars map[string]string, status iostream.StatusFunc, streams iostream.Streams) (Result, error)

RunAll runs all configured commands, stopping at the first failure.

func RunInline

func RunInline(ctx context.Context, workDir, name, command string, envVars map[string]string, status iostream.StatusFunc, streams iostream.Streams) (Result, error)

RunInline runs an inline command string.

func RunNamed

func RunNamed(ctx context.Context, workDir, name string, cfg *config.ProjectConfig, envVars map[string]string, status iostream.StatusFunc, streams iostream.Streams) (Result, error)

RunNamed runs a single named command from config.

func RunRemoteResult added in v0.7.179

func RunRemoteResult(ctx context.Context, execFn func(ctx context.Context, script string) (stdout, stderr string, exitCode int, err error), cfg *config.ProjectConfig, name, dest, localWorkDir string, status iostream.StatusFunc, streams iostream.Streams) (Result, error)

RunRemoteResult runs remote commands and reports how many completed before the first failure.

func RunRemoteStreamedResult added in v0.7.179

func RunRemoteStreamedResult(ctx context.Context, execFn func(ctx context.Context, script string) (stdout, stderr string, exitCode int, err error), cfg *config.ProjectConfig, name, dest, localWorkDir string, status iostream.StatusFunc, streams iostream.Streams) (Result, error)

RunRemoteStreamedResult is RunRemoteResult for executors that stream output.

Jump to

Keyboard shortcuts

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