worker

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 6, 2026 License: MIT Imports: 23 Imported by: 0

Documentation

Overview

Package worker invokes enrolled CLI agents and parses their structured reply.

Index

Constants

View Source
const (
	MaxDiffInlineBytes           = 64 * 1024
	MaxVerificationSummaryBytes  = 4 * 1024
	MaxHandoffFieldBytes         = 512
	MaxPlanFeedbackInlineBytes   = 4 * 1024
	MaxResearchAdviceInlineBytes = 8 * 1024
)

Prompt size budgets keep runtime prompts cache-friendly and bounded. Exact source stays on disk (DiffPath, review artifacts, logs); only the inlined excerpts are capped.

View Source
const (
	ProvenanceClaudeResult       = "claude.result"
	ProvenanceCodexTurnCompleted = "codex.turn.completed"
	ProvenanceCursorResult       = "cursor.result"
	ProvenanceOpenCodeStepFinish = "opencode.step_finish"
	ProvenanceAntigravityResult  = "antigravity.result"
)

Usage provenance labels identify which runtime event supplied measured counts.

View Source
const MaxLogTail = 1 << 20

MaxLogTail is the default number of bytes retained per invocation stream (stdout, stderr, and the combined lines.jsonl each independently). It is deliberately generous relative to observed invocation output (a single CLI agent turn in this codebase's own fixtures runs a few KB to a few hundred KB) while still bounding a runaway or looping agent. Request. LogTailBytes overrides it per invocation; JEVKIT_SDLC_LOG_TAIL_BYTES is the CLI-level override (see cmd/jevkit's sdlcLogTailBytes).

View Source
const MaxVerificationLogBytes = 256 * 1024

MaxVerificationLogBytes caps each check's stored stdout+stderr locally.

View Source
const TruncationMarkerPrefix = "[earlier output truncated:"

TruncationMarkerPrefix identifies the truncation marker line prepended to a rolled-over stdout/stderr tail, so callers (e.g. cmd/jevkit's `sdlc logs`) can detect and skip past it without depending on the exact omitted-byte count it's followed by.

Variables

View Source
var KnownRuntimes = []string{"codex", "claude", "cursor", "opencode", "antigravity"}

KnownRuntimes is the full set of CLI runtimes command() and RuntimeMatrices know how to invoke. It is the enumeration source for the capability matrix, so adding a runtime to command() without adding it here is a compile-time omission, not a silently stale matrix.

Functions

func BoundText

func BoundText(text string, maxBytes int) string

BoundText head/tail-excerpts text to at most maxBytes. maxBytes <= 0 means unbounded. Exact retained source stays local; callers should point agents at the on-disk artifact when content is truncated.

func BoundVerificationSummary

func BoundVerificationSummary(content, localPath string, maxBytes int) string

BoundVerificationSummary bounds assessment / verification text injected into the next prompt and returns a retrieval hint when truncated.

func CaptureWorktreeIdentity

func CaptureWorktreeIdentity(ctx context.Context, workspace string) (string, error)

CaptureWorktreeIdentity returns the private-index tree hash of workspace. This is the candidate's actual worktree identity, distinct from patch.diff's bounded report hash. When the workspace is not a Git worktree, a stable nogit fingerprint of the resolved path is returned so verification can still bind receipts (mutation detection is unavailable without Git).

func CompactCodex

func CompactCodex(ctx context.Context, binary, workDir, threadID string) error

CompactCodex runs Codex's native app-server compaction protocol for an explicit thread ID. Completion, rather than request acceptance, is required.

func ProbeVersion

func ProbeVersion(ctx context.Context, binary string, args []string) (string, error)

ProbeVersion actually executes the runtime's CLI to confirm reach and report its version, instead of trusting a PATH lookup alone. Any failure (binary missing, non-zero exit, empty output) is reported as an error so a caller fails closed rather than assuming a capability that was never verified to run.

func ResolveSourceRevision

func ResolveSourceRevision(ctx context.Context, repoRoot string) (string, error)

ResolveSourceRevision returns the commit the supervisor records for fan-out.

func RuntimeMatrices

func RuntimeMatrices() map[string]RuntimeMatrix

RuntimeMatrices builds the capability matrix for every known runtime by calling the real command() function CLIExecutor.Execute uses, never by hand-typing expected flags. A test asserting a false capability (for example OpenCode's ReadOnlyExecution) is exercising the same fail-closed error path command() returns to CLIExecutor.Execute at invocation time.

func StablePrefixMetadata

func StablePrefixMetadata(role string) (int, string)

StablePrefixMetadata exposes content-free reuse evidence for cache decisions.

Types

type Activity

type Activity struct {
	Kind  string `json:"kind"`
	Label string `json:"label,omitempty"`
}

type CLIExecutor

type CLIExecutor struct{}

func (CLIExecutor) Execute

func (CLIExecutor) Execute(ctx context.Context, req Request) (Reply, error)

Execute uses argv, never a shell. The caller has already checked enrollment and reach, and must persist the returned result against the assignment.

type Executor

type Executor interface {
	Execute(context.Context, Request) (Reply, error)
}

type GitWorktreeCreator

type GitWorktreeCreator struct{}

GitWorktreeCreator uses `git worktree add --detach` at a recorded revision.

func (GitWorktreeCreator) Available

func (GitWorktreeCreator) Available(ctx context.Context, repoRoot string) bool

func (GitWorktreeCreator) Create

func (GitWorktreeCreator) Create(ctx context.Context, repoRoot, baseRev, dest string) (IsolatedWorkspace, error)

func (GitWorktreeCreator) Remove

type InvocationFailure

type InvocationFailure struct{ Err error }

InvocationFailure means the agent could not produce a usable result and its invocation left the workspace unchanged, so another binding may be tried.

func (*InvocationFailure) Error

func (e *InvocationFailure) Error() string

func (*InvocationFailure) Unwrap

func (e *InvocationFailure) Unwrap() error

type IsolatedWorkspace

type IsolatedWorkspace struct {
	Path       string
	Mode       string
	BaseRev    string
	RepoRoot   string
	Worktree   bool
	SecurityOK bool // true only when a runtime/enforcement layer is also active
}

IsolatedWorkspace is a proven write boundary at one recorded source revision. A Git worktree alone is not a security sandbox; callers must still enforce enrolled scopes and runtime isolation claims separately.

type LogLine

type LogLine struct {
	At       int64     `json:"at"`
	Stream   string    `json:"stream"`
	Text     string    `json:"text"`
	Activity *Activity `json:"activity,omitempty"`
}

type LogMeta

type LogMeta struct {
	Invocation string `json:"invocation"`
	Agent      string `json:"agent"`
	Runtime    string `json:"runtime"`
	StartedAt  string `json:"startedAt"`
}

LogMeta identifies the invocation behind a saved stream.

type PromptLayout

type PromptLayout struct {
	Prompt                  string
	StablePrefix            string
	StablePrefixBytes       int
	StablePrefixFingerprint string
}

PromptLayout is the assembled runtime prompt with content-free telemetry for the stable prefix. Fingerprint and byte count never include variable task, plan, revision, or diff text, and never cache prompt contents locally.

type Reply

type Reply struct {
	Outcome                 string                 `json:"outcome"`
	ReportedOutcome         string                 `json:"-"`
	Content                 string                 `json:"content"`
	CostUSD                 float64                `json:"costUsd"`
	CostReported            bool                   `json:"-"`
	Focus                   string                 `json:"focus,omitempty"`
	Reason                  string                 `json:"reason,omitempty"`
	NextSteps               []string               `json:"nextSteps,omitempty"`
	AcceptanceCriteria      []string               `json:"acceptanceCriteria,omitempty"`
	Checks                  []adaptive.Check       `json:"checks,omitempty"`
	Subtasks                *adaptive.SubtaskGraph `json:"subtasks,omitempty"`
	SessionID               string                 `json:"sessionId,omitempty"`
	InputTokens             *int64                 `json:"inputTokens,omitempty"`
	OutputTokens            *int64                 `json:"outputTokens,omitempty"`
	ToolCalls               *int64                 `json:"toolCalls,omitempty"`
	CacheReadTokens         *int64                 `json:"cacheReadTokens,omitempty"`
	CacheCreationTokens     *int64                 `json:"cacheCreationTokens,omitempty"`
	UsageProvenance         string                 `json:"usageProvenance,omitempty"`
	StablePrefixBytes       int                    `json:"stablePrefixBytes,omitempty"`
	StablePrefixFingerprint string                 `json:"stablePrefixFingerprint,omitempty"`
	// ElapsedMS is the invocation's wall-clock time, set by the caller that
	// timed Execute.
	ElapsedMS        int64    `json:"-"`
	CompactCompleted bool     `json:"-"`
	WorkspaceDrift   []string `json:"-"`
	DriftTruncated   bool     `json:"-"`
}

func ParseReply

func ParseReply(raw []byte) (Reply, error)

type Request

type Request struct {
	Agent          enrollment.Agent
	Assignment     adaptive.Assignment
	Task           string
	OriginalTask   string
	Plan           string
	Diff           string
	DiffPath       string
	WorkDir        string
	Workspace      string
	AllowRead      []string
	Yolo           bool
	SecurityPolicy string
	SDLCRunID      string
	LogDir         string
	// LogTailBytes overrides MaxLogTail for this invocation's saved
	// stdout/stderr/lines.jsonl bound. Zero or negative uses MaxLogTail.
	LogTailBytes     int
	LiveOutput       func(stream, line string)
	SessionID        string
	CaptureSession   bool
	Compact          bool
	JevkitHooks      bool
	JevkitMCP        bool
	JevkitBinary     string
	JevkitCompaction *bool
	// PromptCache controls Claude Code's invocation-wide provider prompt cache.
	// Nil leaves runtimes without a supported control unmanaged.
	PromptCache *bool
}

type RuntimeMatrix

type RuntimeMatrix struct {
	Runtime string
	// VersionArgs are the args used to probe CLI reach and version (see
	// ProbeVersion). "--version" is the common convention across all five
	// runtimes' documented CLIs as of the evidence dates in
	// internal/agents/capability_audit.go.
	VersionArgs []string
	// ReadOnlyExecution is true when command() can build a read-only
	// invocation for this runtime without erroring. False means the CLI
	// adapter cannot enforce read-only and must fail closed instead of
	// silently running with write access (see OpenCodeReadOnlyUnenforceable).
	ReadOnlyExecution bool
	// ReadOnlyUnenforceable explains why ReadOnlyExecution is false. Empty
	// when ReadOnlyExecution is true.
	ReadOnlyUnenforceable string
	// WritableExecution is true when command() can build a write-capable
	// (implementer) invocation for this runtime.
	WritableExecution bool
	// ReadOnlyApprovals and WritableApprovals describe the actual argument(s)
	// command() passes to control the runtime's own approval/permission
	// behavior for each invocation kind, in plain language grounded in the
	// literal flag(s) used. Kept separate so a runtime whose read-only and
	// writable paths differ (every runtime here) never has one overwrite the
	// other in display or in tests.
	ReadOnlyApprovals string
	WritableApprovals string
	// PermissionBypassArgument is the literal CLI flag, if any, that a
	// write-capable invocation passes to skip the runtime's own interactive
	// permission prompts entirely. Empty when no such flag is passed. This
	// must never be silently added to a runtime's writable command without
	// updating this field and the matching test.
	PermissionBypassArgument string
	// ShellHookCoverage mirrors agents.RuntimeCapability.ShellPolicyCoverage:
	// whether the installed pre-tool hook can inspect and rewrite an eligible
	// shell call before the runtime executes it. OpenCode is false; see
	// internal/agents/capability_audit.go and docs/AGENT-INTEGRATIONS.md.
	ShellHookCoverage bool
	// WorkdirScoped is true for every runtime: CLIExecutor.Execute always
	// sets cmd.Dir to req.WorkDir (worker.go), independent of the runtime
	// binary. It is not a per-runtime CLI flag.
	WorkdirScoped bool
	// SessionResume is true when command() accepts req.SessionID and passes
	// a runtime-specific resume argument.
	SessionResume bool
	// Cancellation and ChildCleanup are true for every runtime: both are
	// enforced by prepareRuntimeCommand/runRuntimeCommand (process_unix.go,
	// process_windows.go), which own a process group per invocation
	// regardless of which runtime binary it started. See
	// TestRuntimeCancellationKillsSpawnedChild and
	// TestRuntimeExitKillsSpawnedChild.
	Cancellation bool
	ChildCleanup bool
}

RuntimeMatrix is the tested, evidence-backed capability contract for one CLI runtime's invocation by CLIExecutor. Every boolean here is derived by actually calling command() (see RuntimeMatrices), never hand-asserted, so it cannot silently drift from what CLIExecutor.Execute really does.

type VerifyRequest

type VerifyRequest struct {
	Checks               []adaptive.Check
	ChecksDigest         string
	AuthorizedDigest     string
	PlanDigest           string
	CandidateFingerprint string // patch.diff / report hash (secondary identity)
	Workspace            string
	AllowRead            []string
	// LogDir is the absolute path for diagnostic streams (typically
	// <run>/logs/verification). Receipts themselves are written by the caller.
	LogDir string
	// OutputPathPrefix is the path prefix stored on receipts (relative to the
	// run root), e.g. "logs/verification".
	OutputPathPrefix string
	Now              time.Time
	MaxOutputBytes   int
	Security         *securityconfig.Config
	// RunArgv is optional; tests inject fakes. Default uses security.RunArgv.
	RunArgv func(context.Context, security.ArgvRequest) (security.ArgvResult, error)
	// CaptureIdentity is optional; tests inject fakes. Default captures the
	// private-index worktree tree hash.
	CaptureIdentity func(context.Context, string) (string, error)
}

VerifyRequest runs authorized planner checks against one exact candidate.

type VerifyResult

type VerifyResult struct {
	Record         adaptive.VerificationRecord
	FailureSummary string
	AllPassed      bool
	Invalidated    bool
}

VerifyResult is the supervisor-owned outcome: full receipts locally, and a bounded failure summary (plus log paths) suitable for the implementer.

func RunVerification

func RunVerification(ctx context.Context, req VerifyRequest) (VerifyResult, error)

RunVerification executes authorized argv checks against the exact candidate worktree. Manual checks are recorded but not executed. If a command mutates the worktree, the result is invalidated and prior receipts for this pass are marked failed. Bounded output stays under LogDir; only FailureSummary is meant for the next implementer prompt.

type WorktreeCreator

type WorktreeCreator interface {
	Create(ctx context.Context, repoRoot, baseRev, dest string) (IsolatedWorkspace, error)
	Remove(ctx context.Context, ws IsolatedWorkspace) error
	Available(ctx context.Context, repoRoot string) bool
}

WorktreeCreator creates and removes isolated Git worktrees. Tests inject fakes.

Jump to

Keyboard shortcuts

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