devloop

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 25 Imported by: ? 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 devloop implements a model-agnostic GPU kernel hot-reload dev-loop engine with layered security controls, compare-and-swap (CAS) generation management, redacted audit receipts, a live SSE event bus, append-only txtar session notebooks, and a canonical kernel slot registry.

Security architecture (Layers 2–7):

  • Layer 2 (transport ceilings): EffectiveTier = min(PodTier, Transport.Ceiling()), plus Origin and Sec-Fetch-Site validation on mutations.
  • Layer 3 (endpoint guard): HTTPGuard enforces exact Host allowlisting, constant-time bearer token authentication (0600 TokenStore) or HttpOnly SameSite=Strict HMAC session cookies on read-only UI paths, and strict application/json Content-Type on mutations.
  • Layer 4 (immutable capability tiers): observe < kernel < config < code, fixed at startup via TierPolicy with no runtime elevation API.
  • Layer 5 (input validation): kernel source #include allowlists and size caps, rejection of caller-supplied compiler flags at kernel tier, env key denylists, typed config schemas, pull URL allowlists, safe relative path checks, #define-safe CUDA kernel signature locks, and log redaction.
  • Layer 6–7 (audit & notebooks): monotonic generation IDs separated from serving_generation_id, redacted JSONL receipts, and append-only txtar session notebooks with pre-edit acts_on locking, query provenance, and content-addressed profile references.

This package is outside the compatibility promise of github.com/tmc/lib/nvidia. Its API may change or be removed in patch releases.

Index

Constants

View Source
const (
	// SessionCookieName is the HttpOnly SameSite=Strict HMAC session cookie for /ui/.
	SessionCookieName = "devloop_ui_session"

	// DefaultMaxKernelSourceBytes is the default Layer 5 kernel source size cap (512 KiB).
	DefaultMaxKernelSourceBytes = 512 * 1024

	// DefaultMaxLogBytes is the default Layer 5 compiler/runtime log cap (16 KiB).
	DefaultMaxLogBytes = 16 * 1024

	// DefaultMaxMutationBodyBytes is the default Layer 3 HTTP mutation body size cap (4 MiB).
	DefaultMaxMutationBodyBytes int64 = 4 << 20

	// DefaultContentSecurityPolicy is the strict zero-script, zero-CDN CSP set by HTTPGuard.
	DefaultContentSecurityPolicy = "" /* 128-byte string literal not displayed */
)
View Source
const (
	// DefaultMaxSharedMemBytes is the default dynamic shared memory per block cap (228 KiB).
	DefaultMaxSharedMemBytes uint32 = 228 * 1024

	// DefaultMaxBlockThreads is the CUDA architectural cap on threads per block.
	DefaultMaxBlockThreads uint32 = 1024

	// DefaultWarpSize is the CUDA warp width.
	DefaultWarpSize uint32 = 32

	// DefaultMinRegsPerThread is the minimum explicit NVRTC/PTX register cap when non-zero.
	DefaultMinRegsPerThread = 16

	// DefaultMaxRegsPerThread is the architectural maximum registers per thread.
	DefaultMaxRegsPerThread = 255
)
View Source
const NoCAS int64 = -1

NoCAS disables compare-and-swap generation checking when passed as ExpectedGeneration. ExpectedGeneration == 0 is a real CAS check expecting generation 0 (baseline), never a wildcard.

Variables

View Source
var (
	ErrInvalidTier          = errors.New("devloop: invalid capability tier")
	ErrTierRaiseForbidden   = errors.New("devloop: capability tier is fixed at startup and cannot be raised")
	ErrTierInsufficient     = errors.New("devloop: effective tier insufficient for operation")
	ErrInvalidTransport     = errors.New("devloop: invalid transport")
	ErrForbiddenHost        = errors.New("devloop: forbidden Host header")
	ErrUnauthorized         = errors.New("devloop: unauthorized")
	ErrForbiddenOrigin      = errors.New("devloop: forbidden browser Origin or Sec-Fetch-Site")
	ErrUnsupportedMediaType = errors.New("devloop: unsupported media type; application/json required")
	ErrForbiddenEnvKey      = errors.New("devloop: forbidden environment variable key")
	ErrUnknownConfigSetting = errors.New("devloop: unknown configuration setting")
	ErrInvalidConfigValue   = errors.New("devloop: invalid configuration setting value")
	ErrForbiddenPullURL     = errors.New("devloop: pull URL violates allowlist")
	ErrUnsafePath           = errors.New("devloop: unsafe or traversal path")
	ErrInvalidKernelSource  = errors.New("devloop: kernel source violates validation rules")
	ErrForbiddenFlags       = errors.New("devloop: caller-supplied compiler flags are forbidden at kernel tier")
	ErrSignatureMismatch    = errors.New("devloop: CUDA kernel signature lock violation")
)
View Source
var (
	ErrSessionNotFound    = errors.New("devloop: session not found")
	ErrHypothesisNotFound = errors.New("devloop: hypothesis not found")
	ErrAttemptNotFound    = errors.New("devloop: attempt not found")
	ErrInvalidHypothesis  = errors.New("devloop: invalid hypothesis status")
	ErrInvalidFeedback    = errors.New("devloop: invalid feedback entry")
	ErrActsOnAfterEdit    = errors.New("devloop: acts_on must be declared before an edit attaches to the attempt")
	ErrAttemptClosed      = errors.New("devloop: attempt is closed and immutable")
)
View Source
var (
	// ErrInvalidLaunchConfig is returned when a SlotLaunchConfig violates geometry or hardware bounds.
	ErrInvalidLaunchConfig = errors.New("devloop: invalid slot launch config")

	// ErrInvalidSlotSpec is returned when a SlotSpec or SlotEditRequest is malformed.
	ErrInvalidSlotSpec = errors.New("devloop: invalid kernel slot spec")
)
View Source
var (
	ErrSlotNotFound       = errors.New("devloop: kernel slot not found")
	ErrGenerationNotFound = errors.New("devloop: generation not found")
	ErrConflict           = errors.New("devloop: compare-and-swap generation conflict")
)
View Source
var DefaultAllowedIncludes = []string{
	"cuda_runtime.h",
	"cuda_fp16.h",
	"cuda_bf16.h",
	"cuda_fp8.h",
	"cooperative_groups.h",
	"stdint.h",
	"stddef.h",
	"math.h",
	"float.h",
	"limits.h",
	"cstdint",
	"cstddef",
	"cmath",
	"cfloat",
}

DefaultAllowedIncludes is the default bundled header allowlist for NVRTC kernel compilation.

Functions

func ApplyUnifiedDiff

func ApplyUnifiedDiff(baseText, diffText string) (string, error)

ApplyUnifiedDiff applies a unified diff produced by UnifiedDiff onto baseText.

func CheckTier

func CheckTier(w http.ResponseWriter, r *http.Request, minTier Tier) bool

CheckTier verifies that the request carries an AuthInfo with EffectiveTier >= minTier. On failure, it writes 403 Forbidden and returns false.

func ExtractBearerToken

func ExtractBearerToken(r *http.Request) (string, bool)

ExtractBearerToken parses an HTTP Authorization: Bearer <token> header.

func FormatTxtar

func FormatTxtar(files []TxtarFile) []byte

FormatTxtar formats files into standard `-- name --` txtar archive bytes, losslessly escaping any content line matching `-- name --` (or already backslash-escaped marker lines) so embedded content cannot inject forged txtar file boundaries.

func HTTPGuard

func HTTPGuard(cfg GuardConfig) func(http.Handler) http.Handler

HTTPGuard enforces Layer 2 (transport ceilings + Origin/Sec-Fetch-Site), Layer 3 (exact Host, constant-time bearer token or /ui/ session cookie, application/json on mutations), and Layer 4 (effective tier injection) on every endpoint.

func RequireTier

func RequireTier(minTier Tier) func(http.Handler) http.Handler

RequireTier returns middleware enforcing that the request's effective tier is at least minTier.

func SanitizeLog

func SanitizeLog(raw string, maxBytes int, secrets ...string) string

SanitizeLog strips control characters, redacts any provided secrets as well as bearer/session-cookie patterns, and caps the output to maxBytes (default 16 KiB).

func UnifiedDiff

func UnifiedDiff(oldText, newText, name string) string

UnifiedDiff produces a standard unified diff between oldText and newText for name.

func ValidateCompilerFlags

func ValidateCompilerFlags(flags []string) error

ValidateCompilerFlags rejects any caller-supplied compiler flags at kernel tier. NVRTC uses fixed per-arch options only.

func ValidateConfigSetting

func ValidateConfigSetting(key string, val any, schema ConfigSchema) error

ValidateConfigSetting checks key against the env denylist and schema, then validates val.

func ValidateEnvKey

func ValidateEnvKey(key string) error

ValidateEnvKey enforces the Layer 5 hard denylist covering code-loading and linker/runtime environment variables (LD_*, PYTHON*, PATH, CUDA_INJECTION*, *_PRELOAD, DYLD_*, etc.).

func ValidateKernelSource

func ValidateKernelSource(slot, source string, allowedIncludes []string, maxBytes int) error

ValidateKernelSource enforces Layer 5 kernel-tier guards: valid slot name, no null bytes, size cap, and strict #include validation (no absolute paths, no ".." traversal, only headers in allowedIncludes).

func ValidateLaunchConfig

func ValidateLaunchConfig(cfg SlotLaunchConfig, bounds SlotLaunchBounds) error

ValidateLaunchConfig enforces strict geometry, warp-multiple, shared-memory, register-cap, and PDL bounds on cfg.

func ValidatePullURL

func ValidatePullURL(rawURL string, allowlist PullAllowlist) error

ValidatePullURL validates rawURL against Layer 5 pull rules: rejects http://, file://, off-allowlist scheme/host/bucket/prefix, userinfo, and path traversal.

func ValidateSafeRelPath

func ValidateSafeRelPath(p string) error

ValidateSafeRelPath rejects empty, absolute, backslash, null-byte, newline, or ".." traversal paths.

func ValidateSlotName

func ValidateSlotName(slot string) error

ValidateSlotName validates a registered kernel slot filename (strict basename, no traversal).

func VerifySignatureLock

func VerifySignatureLock(baselineSource, candidateSource string) error

VerifySignatureLock ensures candidateSource preserves the exact set of CUDA kernel entry points, qualifiers, template signatures, parameter counts, and normalized parameter types from baselineSource.

Types

type AgentInfo

type AgentInfo struct {
	Actor       string         `json:"actor"`
	Transport   Transport      `json:"transport"`
	ConnectedAt time.Time      `json:"connected_at"`
	Meta        map[string]any `json:"meta,omitempty"`
}

AgentInfo tracks a connected agent on the live dev-loop.

type Attempt

type Attempt struct {
	ID             string         `json:"id"`
	HypothesisID   string         `json:"hypothesis_id"`
	Actor          string         `json:"actor"`
	Intent         string         `json:"intent"`
	ActsOn         []string       `json:"acts_on,omitempty"`
	Slot           string         `json:"slot,omitempty"`
	PatchDiff      string         `json:"patch_diff,omitempty"`
	Source         string         `json:"source,omitempty"`
	Result         *AttemptResult `json:"result,omitempty"`
	Queries        []QueryRecord  `json:"queries,omitempty"`
	ProfileSummary string         `json:"profile_summary,omitempty"`
	Profiles       []ProfileRef   `json:"profiles,omitempty"`
	Log            string         `json:"log,omitempty"`
	EndNote        string         `json:"end_note,omitempty"`
	Open           bool           `json:"open"`
	StartedAt      time.Time      `json:"started_at"`
	EndedAt        time.Time      `json:"ended_at,omitempty"`
	// contains filtered or unexported fields
}

Attempt is a numbered, immutable-history step inside a session notebook.

func (Attempt) EditAttached

func (a Attempt) EditAttached() bool

EditAttached reports whether an edit/generation has already attached to this attempt. Once true, acts_on is locked and cannot be added or mutated post-hoc.

type AttemptResult

type AttemptResult struct {
	GenerationID int64          `json:"generation_id,omitempty"`
	Slot         string         `json:"slot,omitempty"`
	SourceSHA256 string         `json:"source_sha256,omitempty"`
	Status       Status         `json:"status"`
	ActsOn       []string       `json:"acts_on,omitempty"`
	Parity       *ParityResult  `json:"parity,omitempty"`
	Timings      map[string]any `json:"timings,omitempty"`
	Stages       map[string]any `json:"stages,omitempty"`
	Queries      []QueryRecord  `json:"queries,omitempty"`
	ReceiptID    string         `json:"receipt_id,omitempty"`
	StartedAt    time.Time      `json:"started_at"`
	EndedAt      time.Time      `json:"ended_at,omitempty"`
}

AttemptResult is serialized as `-- attempts/<id>/result.json --`.

type AuthInfo

type AuthInfo struct {
	PodTier       Tier
	Transport     Transport
	EffectiveTier Tier
	Actor         string
	ViaCookie     bool
	BrowserOrigin bool
}

AuthInfo carries verified Layer 2/3/4 authentication and tier metadata in request context.

func AuthFromContext

func AuthFromContext(ctx context.Context) (AuthInfo, bool)

AuthFromContext retrieves the verified AuthInfo set by HTTPGuard.

type CaptureShape

type CaptureShape struct {
	Name          string  `json:"name"`
	Batch         int     `json:"batch"`
	SeqLen        int     `json:"seq_len"`
	Hidden        int     `json:"hidden"`
	Intermediate  int     `json:"intermediate,omitempty"`
	TopK          int     `json:"top_k,omitempty"`
	Experts       int     `json:"experts,omitempty"`
	HeadDim       int     `json:"head_dim,omitempty"`
	CapturedUS    float64 `json:"captured_us,omitempty"`
	CaptureDigest string  `json:"capture_digest,omitempty"`
	HeldOut       bool    `json:"held_out"`
}

CaptureShape records a workload shape extracted from a profiler capture. HeldOut distinguishes scorer-only held-out shapes from dev iteration shapes.

type ConfigSchema

type ConfigSchema map[string]SettingSpec

ConfigSchema maps allowed configuration setting keys to their SettingSpec.

func DefaultConfigSchema

func DefaultConfigSchema() ConfigSchema

DefaultConfigSchema returns the default schema for config-tier settings.

type ConflictError

type ConflictError struct {
	Slot               string `json:"slot"`
	Actor              string `json:"actor"`
	ExpectedGeneration int64  `json:"expected_generation"`
	CurrentGeneration  int64  `json:"current_generation"`
	GenerationID       int64  `json:"generation_id"`
	ReceiptID          string `json:"receipt_id"`
}

ConflictError is returned when SubmitEdit or Revert fails compare-and-swap on ExpectedGeneration.

func (*ConflictError) Error

func (e *ConflictError) Error() string

func (*ConflictError) Is

func (e *ConflictError) Is(target error) bool

type Event

type Event struct {
	Seq          uint64         `json:"seq"`
	At           time.Time      `json:"at"`
	Type         EventType      `json:"type"`
	Actor        string         `json:"actor,omitempty"`
	Slot         string         `json:"slot,omitempty"`
	GenerationID int64          `json:"generation_id,omitempty"`
	Data         map[string]any `json:"data,omitempty"`
}

Event is a single event distributed on the SSE EventBus.

type EventBus

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

EventBus is a thread-safe SSE-ready pub/sub bus with a bounded ring buffer and agent tracking.

func NewEventBus

func NewEventBus(bufCap int) *EventBus

NewEventBus creates an EventBus retaining the last bufCap events (default 512).

func (*EventBus) ActiveAgents

func (b *EventBus) ActiveAgents() []AgentInfo

ActiveAgents returns a sorted snapshot of currently connected agents.

func (*EventBus) ConnectAgent

func (b *EventBus) ConnectAgent(actor string, transport Transport, meta map[string]any) Event

ConnectAgent registers an active agent and publishes an agent_connected event.

func (*EventBus) DisconnectAgent

func (b *EventBus) DisconnectAgent(actor string) Event

DisconnectAgent unregisters an agent and publishes an agent_disconnected event.

func (*EventBus) Publish

func (b *EventBus) Publish(ev Event) Event

Publish assigns a monotonic Seq and UTC timestamp, appends a deep-cloned event to the ring buffer, and delivers independent deep-cloned copies non-blockingly to all active subscribers so callers and subscribers can never race on Event.Data.

func (*EventBus) Recent

func (b *EventBus) Recent(limit int) []Event

Recent returns up to limit deep-cloned most recent events in chronological order.

func (*EventBus) Subscribe

func (b *EventBus) Subscribe(sinceSeq uint64) (replay []Event, ch <-chan Event, cancel func())

Subscribe returns deep-cloned buffered events with Seq > sinceSeq, a live event channel, and an idempotent cancel function.

type EventType

type EventType string

EventType identifies a live SSE event emitted on the EventBus.

const (
	EventEditSubmitted     EventType = "edit_submitted"
	EventCompileOK         EventType = "compile_ok"
	EventCompileError      EventType = "compile_error"
	EventPatched           EventType = "patched"
	EventReverted          EventType = "reverted"
	EventParity            EventType = "parity"
	EventProfile           EventType = "profile"
	EventConflict          EventType = "conflict"
	EventAgentConnected    EventType = "agent_connected"
	EventAgentDisconnected EventType = "agent_disconnected"
	EventSessionEvent      EventType = "session_event"
)

type FeedbackEntry

type FeedbackEntry struct {
	At          time.Time    `json:"at"`
	Actor       string       `json:"actor"`
	Summary     string       `json:"summary"`
	Suggestion  string       `json:"suggestion,omitempty"`
	ReceiptID   string       `json:"receipt_id,omitempty"`
	FindingID   string       `json:"finding_id,omitempty"`
	Kind        FeedbackKind `json:"kind,omitempty"`
	Evidence    string       `json:"evidence,omitempty"`
	Engine      string       `json:"engine,omitempty"`
	QuerySHA256 string       `json:"query_sha256,omitempty"`
}

FeedbackEntry is appended to `-- feedback.jsonl --`.

type FeedbackKind

type FeedbackKind string

FeedbackKind classifies explicit advise feedback entries.

const (
	FeedbackCorrection FeedbackKind = "correction"
	FeedbackSuggestion FeedbackKind = "suggestion"
	FeedbackConfusing  FeedbackKind = "confusing"
)

type GenerationRecord

type GenerationRecord struct {
	GenerationID       int64          `json:"generation_id"`
	Slot               string         `json:"slot"`
	Actor              string         `json:"actor"`
	Transport          Transport      `json:"transport"`
	Tier               Tier           `json:"tier"`
	Operation          Operation      `json:"operation"`
	Status             Status         `json:"status"`
	Source             string         `json:"source,omitempty"`
	SourceSHA256       string         `json:"source_sha256,omitempty"`
	ParentGeneration   int64          `json:"parent_generation,omitempty"`
	RestoredGeneration int64          `json:"restored_generation,omitempty"`
	UnifiedDiff        string         `json:"unified_diff,omitempty"`
	PTXDiff            string         `json:"ptx_diff,omitempty"`
	SASSDiff           string         `json:"sass_diff,omitempty"`
	CompilerLog        string         `json:"compiler_log,omitempty"`
	Parity             *ParityResult  `json:"parity,omitempty"`
	Profile            *ProfileResult `json:"profile,omitempty"`
	ReceiptID          string         `json:"receipt_id"`
	StartedAt          time.Time      `json:"started_at"`
	EndedAt            time.Time      `json:"ended_at,omitempty"`
	DurationMS         int64          `json:"duration_ms,omitempty"`
}

GenerationRecord holds the full state of a single monotonic generation attempt.

type GenerationSummary

type GenerationSummary struct {
	GenerationID int64     `json:"generation_id"`
	Status       Status    `json:"status"`
	Actor        string    `json:"actor"`
	SourceSHA256 string    `json:"source_sha256"`
	StartedAt    time.Time `json:"started_at"`
	EndedAt      time.Time `json:"ended_at,omitempty"`
	DurationMS   int64     `json:"duration_ms,omitempty"`
	P50MS        *float64  `json:"p50_ms,omitempty"`
	ParityPass   *bool     `json:"parity_pass,omitempty"`
}

GenerationSummary is a compact per-slot history item for UI sparklines and slot listings.

type GuardConfig

type GuardConfig struct {
	// PodTier is the immutable tier of the runtime (defaults to DefaultTier).
	PodTier Tier
	// Transport is the transport served by this listener (defaults to TransportLoopback).
	Transport Transport
	// Port, when > 0, populates allowed Host headers with 127.0.0.1:<port> and localhost:<port>.
	Port int
	// AllowedHosts explicitly specifies exact allowed Host header values (in addition to Port).
	AllowedHosts []string
	// Tokens validates bearer tokens and HMAC session cookies. Required (nil fails closed).
	Tokens *TokenStore
	// SessionCookiePrefixes lists URL path prefixes where an HttpOnly HMAC session cookie
	// is accepted for safe GET/HEAD reads. Defaults to []string{"/ui/"}.
	SessionCookiePrefixes []string
	// RejectAnyOriginOnMutations forces rejection of any non-empty Origin header on
	// mutations (even same-origin). This behavior is now ON by default unless
	// AllowSameOriginMutations is explicitly set to true (and RejectAnyOriginOnMutations is false).
	// Cross-site Origin and cross-site/same-site Sec-Fetch-Site are ALWAYS rejected on mutations.
	RejectAnyOriginOnMutations bool
	// AllowSameOriginMutations explicitly opts in to permitting same-origin browser
	// mutations on non-/mcp paths when RejectAnyOriginOnMutations is false.
	AllowSameOriginMutations bool
	// MaxMutationBodyBytes caps request body bytes on mutation methods via http.MaxBytesReader.
	// Defaults to DefaultMaxMutationBodyBytes (4 MiB) when <= 0.
	MaxMutationBodyBytes int64
	// ContentSecurityPolicy overrides the strict default CSP header when non-empty.
	ContentSecurityPolicy string
}

GuardConfig configures the Layer 2/3/4 HTTP security middleware.

type Hypothesis

type Hypothesis struct {
	ID         string               `json:"id"`
	Claim      string               `json:"claim"`
	Prediction string               `json:"prediction"`
	Falsifier  string               `json:"falsifier"`
	Actor      string               `json:"actor"`
	CreatedAt  time.Time            `json:"created_at"`
	Revisions  []HypothesisRevision `json:"revisions"`
}

Hypothesis represents a falsifiable hypothesis with an append-only revision log.

func (Hypothesis) CurrentStatus

func (h Hypothesis) CurrentStatus() HypothesisStatus

CurrentStatus returns the latest status in the hypothesis's append-only revision log.

type HypothesisRevision

type HypothesisRevision struct {
	Rev      int              `json:"rev"`
	At       time.Time        `json:"at"`
	Actor    string           `json:"actor"`
	Status   HypothesisStatus `json:"status"`
	Evidence []string         `json:"evidence,omitempty"`
	Note     string           `json:"note,omitempty"`
}

HypothesisRevision is an append-only revision entry for a hypothesis.

type HypothesisStatus

type HypothesisStatus string

HypothesisStatus is the bounded status enum for session hypotheses.

const (
	HypothesisOpen      HypothesisStatus = "open"
	HypothesisSupported HypothesisStatus = "supported"
	HypothesisRefuted   HypothesisStatus = "refuted"
	HypothesisAbandoned HypothesisStatus = "abandoned"
)

type KernelParam

type KernelParam struct {
	Raw            string `json:"raw"`
	NormalizedType string `json:"normalized_type"`
	Name           string `json:"name,omitempty"`
}

KernelParam represents a single parameter of a CUDA kernel declaration.

type KernelSignature

type KernelSignature struct {
	Qualifier      string        `json:"qualifier"`
	ExternC        bool          `json:"extern_c,omitempty"`
	TemplateParams string        `json:"template_params,omitempty"`
	ReturnType     string        `json:"return_type"`
	Name           string        `json:"name"`
	Params         []KernelParam `json:"params"`
	Canonical      string        `json:"canonical"`
}

KernelSignature represents a parsed __global__ or __tile_global__ CUDA kernel signature.

func ExtractCUDASignatures

func ExtractCUDASignatures(source string) ([]KernelSignature, error)

ExtractCUDASignatures parses all __global__ and __tile_global__ kernel declarations in source, supporting extern "C", template<...>, __launch_bounds__(...), and multi-line parameter lists. Preprocessor #define macro bodies (including backslash continuations) are skipped so macro templates defining __global__ void NAME(...) are not misparsed as conflicting declarations.

type KernelSlot

type KernelSlot = SlotSpec

KernelSlot is the canonical alias for SlotSpec.

type Operation

type Operation string

Operation is a bounded enum for dev-loop audit receipts.

const (
	OpSubmitKernel Operation = "submit_kernel"
	OpCompile      Operation = "compile"
	OpPatch        Operation = "patch"
	OpParity       Operation = "parity"
	OpProfile      Operation = "profile"
	OpRevert       Operation = "revert"
	OpConflict     Operation = "conflict"
)

type ParityResult

type ParityResult struct {
	Passed      bool    `json:"passed"`
	MaxError    float64 `json:"max_error"`
	Matched     int     `json:"matched"`
	Attempted   int     `json:"attempted"`
	SuiteDigest string  `json:"suite_digest,omitempty"`
	Details     string  `json:"details,omitempty"`
}

ParityResult records correctness verification for a generation.

type ProfileRef

type ProfileRef struct {
	Kind   string `json:"kind"`
	SHA256 string `json:"sha256"`
	Bytes  int64  `json:"bytes"`
	Path   string `json:"path"`
}

ProfileRef is a content-addressed reference to a binary profile kept on disk.

type ProfileResult

type ProfileResult struct {
	P50MS      float64  `json:"p50_ms"`
	GBS        float64  `json:"gb_s"`
	Regs       int      `json:"regs"`
	DiffPrevMS *float64 `json:"diff_prev_ms,omitempty"`
	Summary    string   `json:"summary,omitempty"`
}

ProfileResult records cudaprof / benchmark metrics for a generation.

type PullAllowlist

type PullAllowlist struct {
	Schemes  []string // e.g. ["https", "s3", "oci"]; "http" and "file" are always rejected
	Hosts    []string // exact allowed hostnames (for https/oci)
	Buckets  []string // exact allowed bucket names (for s3/gs)
	Prefixes []string // allowed path prefixes (e.g. "/models/", "checkpoints/")
	MaxBytes int64    // optional size cap
}

PullAllowlist defines Layer 5 pull validation constraints.

type QueryRecord

type QueryRecord struct {
	QuerySHA256 string    `json:"query_sha256"`
	Engine      string    `json:"engine"`
	Database    string    `json:"database,omitempty"`
	Actor       string    `json:"actor,omitempty"`
	Rows        int       `json:"rows"`
	Bytes       int64     `json:"bytes,omitempty"`
	DurationMS  float64   `json:"duration_ms"`
	At          time.Time `json:"at"`
}

QueryRecord records audited tracedb query evidence executed during a session/attempt.

type Receipt

type Receipt struct {
	RunID                string    `json:"run_id"`
	GenerationID         int64     `json:"generation_id"`
	ServingGenerationID  int64     `json:"serving_generation_id"`
	ReceiptID            string    `json:"receipt_id"`
	Actor                string    `json:"actor"`
	Transport            Transport `json:"transport"`
	Tier                 Tier      `json:"tier"`
	Operation            Operation `json:"operation"`
	Slot                 string    `json:"slot"`
	SourceSHA256         string    `json:"source_sha256,omitempty"`
	RestoredGenerationID int64     `json:"restored_generation_id,omitempty"`
	Status               Status    `json:"status"`
	StartedAt            time.Time `json:"started_at"`
	EndedAt              time.Time `json:"ended_at"`
	DurationMS           int64     `json:"duration_ms"`
}

Receipt is a Layer 7 terminal audit receipt appended to receipts.jsonl. It never contains tokens, raw source, or secrets.

type ReferenceSpec

type ReferenceSpec struct {
	Script       string  `json:"script,omitempty"`
	OpName       string  `json:"op_name"`
	GoldenPath   string  `json:"golden_path,omitempty"`
	GoldenSHA256 string  `json:"golden_sha256,omitempty"`
	MaxAbsTol    float64 `json:"max_abs_tol"`
	RMSTol       float64 `json:"rms_tol,omitempty"`
	ExactIndices bool    `json:"exact_indices"`
}

ReferenceSpec binds a kernel slot to its golden reference implementation and parity tolerances.

type ReplayAttemptInput

type ReplayAttemptInput struct {
	AttemptID      string         `json:"attempt_id"`
	Intent         string         `json:"intent"`
	ActsOn         []string       `json:"acts_on,omitempty"`
	Slot           string         `json:"slot,omitempty"`
	PatchDiff      string         `json:"patch_diff,omitempty"`
	Source         string         `json:"source,omitempty"`
	ExpectedResult *AttemptResult `json:"expected_result,omitempty"`
	Profiles       []ProfileRef   `json:"profiles,omitempty"`
}

ReplayAttemptInput contains the parsed artifacts for one numbered attempt in a txtar notebook.

type ReplayAttemptOutcome

type ReplayAttemptOutcome struct {
	AttemptID  string `json:"attempt_id"`
	Passed     bool   `json:"passed"`
	Status     Status `json:"status"`
	Error      string `json:"error,omitempty"`
	DurationMS int64  `json:"duration_ms"`
	Details    string `json:"details,omitempty"`
}

ReplayAttemptOutcome is the result of replaying a single attempt.

type ReplayReport

type ReplayReport struct {
	SessionID string                 `json:"session_id"`
	Base      SessionBase            `json:"base"`
	Attempts  []ReplayAttemptOutcome `json:"attempts"`
	Passed    int                    `json:"passed"`
	Failed    int                    `json:"failed"`
	AllPassed bool                   `json:"all_passed"`
}

ReplayReport summarizes replaying every numbered attempt in a session txtar notebook.

func ReplaySession

func ReplaySession(ctx context.Context, txtarBytes []byte, runner ReplayRunner) (*ReplayReport, error)

ReplaySession parses txtarBytes, iterates every numbered attempt in order, applies its patch.diff (or source.cu) via runner, runs checks, and returns a per-attempt ReplayReport.

type ReplayRunner

type ReplayRunner interface {
	RunAttempt(ctx context.Context, base SessionBase, attempt ReplayAttemptInput) (ReplayAttemptOutcome, error)
}

ReplayRunner executes a replayed attempt against base metadata.

type ReplayRunnerFunc

type ReplayRunnerFunc func(ctx context.Context, base SessionBase, attempt ReplayAttemptInput) (ReplayAttemptOutcome, error)

ReplayRunnerFunc adapts a function to ReplayRunner.

func (ReplayRunnerFunc) RunAttempt

type RevertRequest

type RevertRequest struct {
	Slot               string    `json:"slot"`
	TargetGeneration   int64     `json:"target_generation"`
	ExpectedGeneration int64     `json:"expected_generation,omitempty"`
	Actor              string    `json:"actor"`
	Transport          Transport `json:"transport"`
}

RevertRequest requests reverting a registered slot to TargetGeneration (0 = baseline).

type SessionBase

type SessionBase struct {
	RepoCommit  string            `json:"repo_commit,omitempty"`
	ImageDigest string            `json:"image_digest,omitempty"`
	Profile     string            `json:"profile,omitempty"`
	CUDACompat  string            `json:"cuda_compat,omitempty"`
	Extra       map[string]string `json:"extra,omitempty"`
}

SessionBase records the immutable baseline metadata for a session notebook.

type SessionMeta

type SessionMeta struct {
	SessionID string        `json:"session_id"`
	RunID     string        `json:"run_id"`
	Actor     string        `json:"actor"`
	Goal      string        `json:"goal"`
	StartedAt time.Time     `json:"started_at"`
	Base      SessionBase   `json:"base"`
	Tier      Tier          `json:"tier"`
	Queries   []QueryRecord `json:"queries,omitempty"`
}

SessionMeta is serialized as `-- session.json --` in the txtar notebook.

type SessionSnapshot

type SessionSnapshot struct {
	Meta          SessionMeta     `json:"meta"`
	Hypotheses    []Hypothesis    `json:"hypotheses"`
	Attempts      []Attempt       `json:"attempts"`
	Feedback      []FeedbackEntry `json:"feedback,omitempty"`
	Conclusion    string          `json:"conclusion,omitempty"`
	OpenAttemptID string          `json:"open_attempt_id,omitempty"`
}

SessionSnapshot is an observe-tier read-only snapshot of a session notebook.

type SessionSummary

type SessionSummary struct {
	SessionID       string    `json:"session_id"`
	RunID           string    `json:"run_id"`
	Actor           string    `json:"actor"`
	Goal            string    `json:"goal"`
	Tier            Tier      `json:"tier"`
	StartedAt       time.Time `json:"started_at"`
	HypothesisCount int       `json:"hypothesis_count"`
	AttemptCount    int       `json:"attempt_count"`
	Concluded       bool      `json:"concluded"`
}

SessionSummary is an observe-tier listing item returned by SessionList.

type SettingSpec

type SettingSpec struct {
	Type string   // "string", "int", "float", "bool", "enum"
	Enum []string // allowed values for "enum"
	Min  *float64 // optional numeric minimum
	Max  *float64 // optional numeric maximum
}

SettingSpec describes a schema entry for Layer 4/5 config-tier settings.

type SlotEditReceipt

type SlotEditReceipt struct {
	RunID               string    `json:"run_id"`
	GenerationID        int64     `json:"generation_id"`
	ServingGenerationID int64     `json:"serving_generation_id"`
	ReceiptID           string    `json:"receipt_id"`
	Actor               string    `json:"actor"`
	Transport           Transport `json:"transport"`
	Tier                Tier      `json:"tier"`
	Operation           Operation `json:"operation"`
	Slot                string    `json:"slot"`
	Model               string    `json:"model"`
	KernelClass         string    `json:"kernel_class"`
	SourceSHA256        string    `json:"source_sha256"`
	LaunchConfigSHA256  string    `json:"launch_config_sha256"`
	RecompileSkipped    bool      `json:"recompile_skipped"`
	GraphPatchOnly      bool      `json:"graph_patch_only"`
	ActsOn              []string  `json:"acts_on,omitempty"`
	Status              Status    `json:"status"`
	StartedAt           time.Time `json:"started_at"`
	EndedAt             time.Time `json:"ended_at"`
	DurationMS          int64     `json:"duration_ms"`
}

SlotEditReceipt is the Layer 7 audit receipt recorded for every slot edit or CAS conflict. It never contains tokens, raw CUDA source, or secrets.

type SlotEditRequest

type SlotEditRequest struct {
	Slot               string            `json:"slot"`
	Source             string            `json:"source,omitempty"`
	LaunchConfig       *SlotLaunchConfig `json:"launch_config,omitempty"`
	ExpectedGeneration int64             `json:"expected_generation,omitempty"`
	Actor              string            `json:"actor,omitempty"`
	Transport          Transport         `json:"transport,omitempty"`
	Flags              []string          `json:"flags,omitempty"`
	Intent             string            `json:"intent,omitempty"`
	ActsOn             []string          `json:"acts_on,omitempty"`
}

SlotEditRequest submits a source and/or launch-config edit to a registered kernel slot.

type SlotEditResult

type SlotEditResult struct {
	GenerationID       int64            `json:"generation_id"`
	Slot               string           `json:"slot"`
	Model              string           `json:"model"`
	KernelClass        string           `json:"kernel_class"`
	SourceFile         string           `json:"source_file"`
	Actor              string           `json:"actor"`
	Status             Status           `json:"status"`
	SourceSHA256       string           `json:"source_sha256"`
	LaunchConfig       SlotLaunchConfig `json:"launch_config"`
	LaunchConfigSHA256 string           `json:"launch_config_sha256"`
	RecompileSkipped   bool             `json:"recompile_skipped"`
	GraphPatchOnly     bool             `json:"graph_patch_only"`
	CacheHit           bool             `json:"cache_hit"`
	UnifiedDiff        string           `json:"unified_diff,omitempty"`
	ReceiptID          string           `json:"receipt_id"`
	ActsOn             []string         `json:"acts_on,omitempty"`
	CurrentGeneration  int64            `json:"current_generation"`
	ServingGeneration  int64            `json:"serving_generation"`
	StartedAt          time.Time        `json:"started_at"`
	EndedAt            time.Time        `json:"ended_at"`
	DurationMS         int64            `json:"duration_ms"`
}

SlotEditResult reports the outcome of a validated SubmitSlotEdit call.

type SlotInfo

type SlotInfo struct {
	Name              string              `json:"name"`
	Path              string              `json:"path,omitempty"`
	Signatures        []KernelSignature   `json:"signatures"`
	CurrentGeneration int64               `json:"current_generation"`
	ServingGeneration int64               `json:"serving_generation"`
	SourceSHA256      string              `json:"source_sha256"`
	History           []GenerationSummary `json:"history"`
	BaselineSource    string              `json:"baseline_source"`
	CurrentSource     string              `json:"current_source"`
}

SlotInfo describes a registered hot-reloadable CUDA kernel slot.

func (SlotInfo) AgentView

func (s SlotInfo) AgentView() SlotInfo

AgentView returns a sanitized read-only copy of SlotInfo safe for agent consumption, stripping internal host filesystem paths.

type SlotLaunchBounds

type SlotLaunchBounds struct {
	MaxGrid             [3]uint32 `json:"max_grid"`
	MinBlockThreads     uint32    `json:"min_block_threads"`
	MaxBlockThreads     uint32    `json:"max_block_threads"`
	MaxBlockDims        [3]uint32 `json:"max_block_dims"`
	RequireWarpMultiple bool      `json:"require_warp_multiple"`
	MaxSharedMemBytes   uint32    `json:"max_shared_mem_bytes"`
	MinRegs             int       `json:"min_regs"`
	MaxRegs             int       `json:"max_regs"`
	AllowPDL            *bool     `json:"allow_pdl,omitempty"`
}

SlotLaunchBounds defines strict hardware and per-slot safety bounds for SlotLaunchConfig.

func DefaultLaunchBounds

func DefaultLaunchBounds() SlotLaunchBounds

DefaultLaunchBounds returns architectural launch configuration bounds.

type SlotLaunchConfig

type SlotLaunchConfig struct {
	Grid          [3]uint32 `json:"grid"`
	Block         [3]uint32 `json:"block"`
	SharedMem     uint32    `json:"shared_mem"`
	PDL           bool      `json:"pdl"`
	MaxRegs       int       `json:"max_regs"`
	WarpsPerBlock int       `json:"warps_per_block"`
}

SlotLaunchConfig holds editable CUDA kernel launch geometry and execution knobs. Caller-supplied compiler flags are never part of SlotLaunchConfig (enforced by Layer 5).

func (SlotLaunchConfig) Digest

func (c SlotLaunchConfig) Digest() string

Digest returns the deterministic SHA-256 hex digest of the launch configuration.

type SlotRegistry

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

SlotRegistry manages kernel slots loaded from *.slot.json + .cu descriptors or registered programmatically via RegisterSlot, validates source & launch edits, maintains a warm source/launch-config hash cache so launch-config-only tweaks skip NVRTC recompilation, and shares a single authoritative Store and lock for CAS, generation state, receipts, SSE, and sessions.

func NewSlotRegistry

func NewSlotRegistry(cfg SlotRegistryConfig) (*SlotRegistry, error)

NewSlotRegistry constructs a SlotRegistry backed by a single authoritative Store (using cfg.Store when provided, or creating a dedicated Store otherwise) and loads any <SlotsDir>/*.slot.json descriptors paired with sibling .cu files.

func (*SlotRegistry) AgentView

func (r *SlotRegistry) AgentView(model string) []SlotSpec

AgentView returns sorted agent-safe views of all registered slots (optionally filtered by model), excluding held-out shapes and scorer-only reference paths/digests.

func (*SlotRegistry) Bus

func (r *SlotRegistry) Bus() *EventBus

Bus returns the EventBus used for slot SSE notifications.

func (*SlotRegistry) GetSlot

func (r *SlotRegistry) GetSlot(name string) (*SlotSpec, bool)

GetSlot returns a deep copy of a registered slot by canonical slot name (or unique source_file).

func (*SlotRegistry) GetSlotAgentView

func (r *SlotRegistry) GetSlotAgentView(name string) (*SlotSpec, bool)

GetSlotAgentView returns an agent-safe view of a single registered slot, redacting held-out shapes and scorer-only oracle paths/digests.

func (*SlotRegistry) ListSlots

func (r *SlotRegistry) ListSlots(model string) []SlotSpec

ListSlots returns sorted deep copies of all registered slots, optionally filtered by model.

func (*SlotRegistry) Models

func (r *SlotRegistry) Models() []string

Models returns the sorted unique list of model identifiers registered in the registry.

func (*SlotRegistry) Receipts

func (r *SlotRegistry) Receipts(limit int) []SlotEditReceipt

Receipts returns up to limit most recent slot edit receipts.

func (*SlotRegistry) RecordCompileResult

func (r *SlotRegistry) RecordCompileResult(genID int64, ok bool, compilerLog, ptxDiff, sassDiff string, durationMS int64) (*GenerationRecord, error)

RecordCompileResult records a compile outcome on the backing Store and, on success, marks the generation's source hash as compiled in the warm compile cache.

func (*SlotRegistry) RecordPatched

func (r *SlotRegistry) RecordPatched(genID int64, durationMS int64) (*GenerationRecord, error)

RecordPatched marks genID as actively serving on the backing Store and synchronizes slot state.

func (*SlotRegistry) RegisterSlot

func (r *SlotRegistry) RegisterSlot(spec SlotSpec) error

RegisterSlot validates and registers a canonical SlotSpec in the registry.

func (*SlotRegistry) RunID

func (r *SlotRegistry) RunID() string

RunID returns the immutable run_id associated with this SlotRegistry.

func (*SlotRegistry) Store

func (r *SlotRegistry) Store() *Store

Store returns the authoritative Store backing this SlotRegistry.

func (*SlotRegistry) SubmitSlotEdit

func (r *SlotRegistry) SubmitSlotEdit(ctx context.Context, req SlotEditRequest) (*SlotEditResult, error)

SubmitSlotEdit validates and applies a source and/or launch_config edit to a registered slot. It enforces:

  • Layer 2/4 effective tier >= kernel
  • ValidateCompilerFlags (zero caller compiler flags)
  • ValidateLaunchConfig (geometry, warp-multiple, shared memory, register bounds, PDL)
  • ValidateKernelSource (#include allowlist, size cap, null-byte guard)
  • VerifySignatureLock (exact CUDA signature lock against baseline & fixed entry)
  • Compare-and-swap on ExpectedGeneration (emitting conflict SSE event on mismatch)
  • Warm source/launch-config hash cache (launch-config-only tweaks skip NVRTC recompile)
  • Atomic writes into watchDir, monotonic generation allocation, receipt recording, edit_submitted SSE publication, and attachment to any open session attempt.

type SlotRegistryConfig

type SlotRegistryConfig struct {
	Store           *Store
	SlotsDir        string
	WatchDir        string
	StateDir        string
	PodTier         Tier
	AllowedIncludes []string
	MaxSourceBytes  int
	Tokens          *TokenStore
}

SlotRegistryConfig configures a model-agnostic kernel SlotRegistry.

type SlotSpec

type SlotSpec struct {
	Name               string           `json:"name"`
	Model              string           `json:"model"`
	KernelClass        string           `json:"kernel_class"`
	SourceFile         string           `json:"source_file"`
	Entry              string           `json:"entry"`
	FixedSignature     string           `json:"fixed_signature"`
	LaunchConfig       SlotLaunchConfig `json:"launch_config"`
	LaunchBounds       SlotLaunchBounds `json:"launch_bounds"`
	Reference          ReferenceSpec    `json:"reference"`
	Shapes             []CaptureShape   `json:"shapes"`
	CurrentGeneration  int64            `json:"current_generation"`
	ServingGeneration  int64            `json:"serving_generation"`
	SourceSHA256       string           `json:"source_sha256"`
	LaunchConfigSHA256 string           `json:"launch_config_sha256"`
	BaselineSource     string           `json:"baseline_source,omitempty"`
	CurrentSource      string           `json:"current_source,omitempty"`
	UpdatedAt          time.Time        `json:"updated_at"`
}

SlotSpec is the canonical model-agnostic kernel slot descriptor for fast GPU hot-reload iteration.

func (SlotSpec) AgentView

func (s SlotSpec) AgentView() SlotSpec

AgentView returns a sanitized, read-only deep copy of SlotSpec safe for untrusted agent consumption: held-out scorer shapes are stripped (only dev shapes remain) and scorer-only oracle paths/digests (Reference.Script, Reference.GoldenPath, Reference.GoldenSHA256) are redacted while preserving public tolerances and metadata.

func (SlotSpec) DevShapes

func (s SlotSpec) DevShapes() []CaptureShape

DevShapes returns a copy of non-held-out capture shapes for fast iteration.

func (SlotSpec) HeldOutShapes

func (s SlotSpec) HeldOutShapes() []CaptureShape

HeldOutShapes returns a copy of held-out capture shapes reserved for scorer parity.

type Status

type Status string

Status is a bounded enum representing the outcome of a generation or audit receipt.

const (
	StatusPending      Status = "pending"
	StatusCompiling    Status = "compiling"
	StatusOK           Status = "ok"
	StatusCompileError Status = "compile_error"
	StatusParityFailed Status = "parity_failed"
	StatusReverted     Status = "reverted"
	StatusConflict     Status = "conflict"
)

type Store

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

Store coordinates registered kernel slots, monotonic generations, CAS edits, audit receipts, the live SSE EventBus, and append-only session notebooks.

func NewStore

func NewStore(cfg StoreConfig) (*Store, error)

NewStore creates a Store, validating its PodTier and scanning WatchDir if configured.

func (*Store) AddFeedbackEntry

func (s *Store) AddFeedbackEntry(sessionID string, entry FeedbackEntry) error

AddFeedbackEntry sanitizes and appends a FeedbackEntry to the session's feedback.jsonl log.

func (*Store) AttachProfile

func (s *Store) AttachProfile(sessionID, attemptID, kind string, rawBytes []byte, summaryText string) (ProfileRef, error)

AttachProfile writes rawBytes content-addressed on disk under:

  • <stateDir>/profiles/<sha[0:2]>/<sha>.pb.gz (for pprof kinds)
  • <stateDir>/captures/<sha>/capture.bin (for cudaprof kinds)

and records only the {kind, sha256, bytes, path} reference in profiles.json plus summaryText in profile-summary.txt.

func (*Store) AttachQueryEvidence

func (s *Store) AttachQueryEvidence(sessionID, actor string, rec QueryRecord) error

AttachQueryEvidence records audited tracedb query evidence (including query_sha256, engine, rows, duration_ms, at) on the active session notebook (persisted into session.json and, when an attempt is open, into attempts/<id>/result.json).

func (*Store) AttemptBegin

func (s *Store) AttemptBegin(sessionID, actor, hypothesisID, intent string, actsOn ...string) (string, error)

AttemptBegin opens a new numbered attempt (001, 002, ...) that automatically collects subsequent edits, compile logs, parity checks, and profiles from actor until AttemptEnd. Optional actsOn finding IDs link the attempt to advise findings it addresses.

func (*Store) AttemptEnd

func (s *Store) AttemptEnd(sessionID, actor, attemptID, note string) error

AttemptEnd closes an open attempt without altering previously recorded attempt artifacts.

func (*Store) Bus

func (s *Store) Bus() *EventBus

Bus returns the Store's live SSE EventBus.

func (*Store) GetGeneration

func (s *Store) GetGeneration(id int64) (*GenerationRecord, bool)

GetGeneration returns a copy of the GenerationRecord for id.

func (*Store) GetSlot

func (s *Store) GetSlot(name string) (*SlotInfo, bool)

GetSlot returns a snapshot of a single registered slot (by canonical name or source file alias).

func (*Store) HypothesisAdd

func (s *Store) HypothesisAdd(sessionID, actor, claim, prediction, falsifier string) (string, error)

HypothesisAdd appends a new falsifiable hypothesis (H1, H2, ...) to the session.

func (*Store) HypothesisUpdate

func (s *Store) HypothesisUpdate(sessionID, actor, id string, status HypothesisStatus, evidence []string, note string) error

HypothesisUpdate appends a new revision to an existing hypothesis without mutating prior revisions.

func (*Store) ListGenerations

func (s *Store) ListGenerations(slot string, limit int) []GenerationRecord

ListGenerations returns recent generations (optionally filtered by slot).

func (*Store) ListSlots

func (s *Store) ListSlots() []SlotInfo

ListSlots returns a sorted snapshot of all registered kernel slots.

func (*Store) PodTier

func (s *Store) PodTier() Tier

PodTier returns the immutable capability tier.

func (*Store) Receipts

func (s *Store) Receipts(limit int) []Receipt

Receipts returns up to limit most recent audit receipts.

func (*Store) RecordCompileResult

func (s *Store) RecordCompileResult(genID int64, ok bool, compilerLog, ptxDiff, sassDiff string, durationMS int64) (*GenerationRecord, error)

RecordCompileResult updates a generation with compilation results, emits compile_ok or compile_error on the SSE bus, appends a terminal receipt, and updates any linked session attempt. A compile error never alters the slot's serving_generation_id.

func (*Store) RecordParity

func (s *Store) RecordParity(genID int64, parity ParityResult, durationMS int64) (*GenerationRecord, error)

RecordParity records correctness gate results for genID, appends a receipt, and emits parity.

func (*Store) RecordPatched

func (s *Store) RecordPatched(genID int64, durationMS int64) (*GenerationRecord, error)

RecordPatched marks genID as actively serving on its slot, appends a receipt, and emits patched.

func (*Store) RecordProfile

func (s *Store) RecordProfile(genID int64, profile ProfileResult, durationMS int64) (*GenerationRecord, error)

RecordProfile records performance metrics for genID, computing diff_prev_ms against the previous profiled generation on the same slot if not already supplied.

func (*Store) RegisterSlot

func (s *Store) RegisterSlot(name, path, source string) (*SlotInfo, error)

RegisterSlot registers a kernel slot with its baseline source and locked CUDA signatures.

func (*Store) Revert

func (s *Store) Revert(ctx context.Context, req RevertRequest) (*GenerationRecord, error)

Revert restores a kernel slot to TargetGeneration (0 = baseline), allocating a new monotonic generation_id, writing a receipt with restored_generation_id, and emitting a reverted SSE event.

func (*Store) RunID

func (s *Store) RunID() string

RunID returns the immutable run_id for this Store.

func (*Store) ScanWatchDir

func (s *Store) ScanWatchDir() error

ScanWatchDir registers any .cu and .cuh files found directly inside WatchDir, automatically allowlisting sibling .cuh headers for kernel #include validation.

func (*Store) SendAdviseFeedback

func (s *Store) SendAdviseFeedback(sessionID, actor, findingID string, kind FeedbackKind, note, evidence, receiptID string) error

SendAdviseFeedback records explicit advise feedback (correction, suggestion, or confusing) linked to findingID in feedback.jsonl. Corrections require non-empty evidence.

func (*Store) SendFeedback

func (s *Store) SendFeedback(sessionID, actor, summary, suggestion, receiptID string) error

SendFeedback appends a feedback entry to the session's feedback.jsonl log.

func (*Store) SessionConclude

func (s *Store) SessionConclude(sessionID, actor, summary string) error

SessionConclude writes the conclusion markdown for a session.

func (*Store) SessionExportTxtar

func (s *Store) SessionExportTxtar(sessionID string) (string, []byte, error)

SessionExportTxtar renders the session notebook as a clean txtar archive, writes it to <stateDir>/sessions/<sessionID>.txtar when stateDir is configured, and returns (path, bytes, nil).

func (*Store) SessionList

func (s *Store) SessionList() []SessionSummary

SessionList returns observe-tier summaries of all sessions in creation order.

func (*Store) SessionRead

func (s *Store) SessionRead(sessionID string) (*SessionSnapshot, bool)

SessionRead returns an observe-tier snapshot of a session notebook.

func (*Store) SessionStart

func (s *Store) SessionStart(actor, goal string, baseMeta SessionBase, tier Tier) (string, error)

SessionStart begins a new append-only session txtar notebook and emits a session_event.

func (*Store) SetAttemptActsOn

func (s *Store) SetAttemptActsOn(sessionID, actor, attemptID string, actsOn ...string) error

SetAttemptActsOn sets or replaces the acts_on finding IDs for an attempt BEFORE any edit/generation has attached to that attempt. Once an edit attaches (or the attempt closes), attempting to add or mutate acts_on returns ErrActsOnAfterEdit so post-hoc attribution gaming is impossible.

func (*Store) StatusSnapshot

func (s *Store) StatusSnapshot() StoreStatus

StatusSnapshot returns an observe-tier overview of the Store.

func (*Store) SubmitEdit

func (s *Store) SubmitEdit(ctx context.Context, req SubmitRequest) (*GenerationRecord, error)

SubmitEdit enforces Layer 4/5 guards and compare-and-swap on ExpectedGeneration, writes the source atomically to WatchDir (when configured), records a monotonic generation and audit receipt, emits an SSE event, and auto-attaches to any open session attempt for req.Actor.

func (*Store) TryRaiseTier

func (s *Store) TryRaiseTier(target Tier) error

TryRaiseTier always fails per Layer 4.

type StoreConfig

type StoreConfig struct {
	RunID           string
	WatchDir        string
	StateDir        string
	PodTier         Tier
	AllowedIncludes []string
	MaxSourceBytes  int
	MaxLogBytes     int
	Tokens          *TokenStore
	EventBufferSize int
}

StoreConfig configures a devloop Store.

type StoreStatus

type StoreStatus struct {
	RunID            string      `json:"run_id"`
	PodTier          Tier        `json:"pod_tier"`
	LatestGeneration int64       `json:"latest_generation"`
	SlotCount        int         `json:"slot_count"`
	ReceiptCount     int         `json:"receipt_count"`
	ActiveAgents     []AgentInfo `json:"active_agents"`
}

StoreStatus is a read-only overview of the Store for observe-tier endpoints.

type SubmitRequest

type SubmitRequest struct {
	Slot               string    `json:"slot"`
	Source             string    `json:"source"`
	ExpectedGeneration int64     `json:"expected_generation,omitempty"`
	Actor              string    `json:"actor"`
	Transport          Transport `json:"transport"`
	Flags              []string  `json:"flags,omitempty"`
	Intent             string    `json:"intent,omitempty"`
}

SubmitRequest requests a compare-and-swap kernel edit on a registered slot.

type Tier

type Tier string

Tier represents a Layer 4 capability tier fixed at process/runtime creation.

const (
	TierObserve Tier = "observe"
	TierKernel  Tier = "kernel"
	TierConfig  Tier = "config"
	TierCode    Tier = "code"

	// DefaultTier is the default capability tier per Layer 4.
	DefaultTier Tier = TierKernel
)

func EffectiveTier

func EffectiveTier(podTier Tier, transport Transport) Tier

EffectiveTier computes min(podTier, transport.Ceiling()) per Layer 2. If either input is invalid, it fails closed by returning an empty Tier (rank 0).

func MinTier

func MinTier(a, b Tier) Tier

MinTier returns the lower of two valid tiers. If either is invalid, returns "".

func ParseTier

func ParseTier(raw string) (Tier, error)

ParseTier parses a tier string, rejecting unknown values.

func (Tier) Rank

func (t Tier) Rank() int

Rank returns the ordering rank of a tier (observe < kernel < config < code), or 0 if invalid.

func (Tier) Valid

func (t Tier) Valid() bool

Valid reports whether t is a known capability tier.

type TierPolicy

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

TierPolicy holds an immutable capability tier fixed at construction. There is intentionally no API to raise the tier.

func NewTierPolicy

func NewTierPolicy(podTier Tier) (*TierPolicy, error)

NewTierPolicy constructs a TierPolicy fixed to podTier (defaults to DefaultTier when empty).

func (*TierPolicy) Tier

func (p *TierPolicy) Tier() Tier

Tier returns the immutable capability tier.

func (*TierPolicy) TryRaiseTier

func (p *TierPolicy) TryRaiseTier(target Tier) error

TryRaiseTier always fails: capability tiers are fixed at startup and cannot be raised via any API.

type TokenStore

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

TokenStore manages a 32-byte random bearer token persisted to a 0600 file and an HMAC session cookie key derived from that token. It never logs or serializes the token.

func LoadTokenStore

func LoadTokenStore(path string) (*TokenStore, error)

LoadTokenStore loads an existing bearer token from a file on disk.

func NewTokenStore

func NewTokenStore(path string) (*TokenStore, error)

NewTokenStore generates a fresh 32-byte crypto/rand hex token and writes it to path with strict 0600 permissions (creating parent directories with 0700 if needed). If path is empty, the token is kept in memory only.

func (*TokenStore) GoString

func (ts *TokenStore) GoString() string

GoString prevents accidental %#v logging of token contents.

func (*TokenStore) MintSessionCookie

func (ts *TokenStore) MintSessionCookie(actor string, ttl time.Duration) *http.Cookie

MintSessionCookie creates an HttpOnly, SameSite=Strict HMAC-signed session cookie bound to actor and expiring after ttl (defaults to 8 hours if ttl <= 0).

func (*TokenStore) Path

func (ts *TokenStore) Path() string

Path returns the filesystem path of the token file (empty if in-memory).

func (*TokenStore) Redact

func (ts *TokenStore) Redact(s string) string

Redact replaces the token value inside s with [REDACTED].

func (*TokenStore) String

func (ts *TokenStore) String() string

String prevents accidental logging of token contents.

func (*TokenStore) ValidateSessionCookie

func (ts *TokenStore) ValidateSessionCookie(r *http.Request) (string, bool)

ValidateSessionCookie validates the HMAC session cookie on r and returns the authenticated actor.

func (*TokenStore) ValidateToken

func (ts *TokenStore) ValidateToken(candidate string) bool

ValidateToken compares candidate against the stored bearer token in constant time.

type Transport

type Transport string

Transport represents a Layer 2 listener transport with an associated tier ceiling.

const (
	TransportLoopback Transport = "loopback"
	TransportTailnet  Transport = "tailnet"
	TransportBrowser  Transport = "browser"
)

func ParseTransport

func ParseTransport(raw string) (Transport, error)

ParseTransport parses a transport string, rejecting unknown values.

func (Transport) Ceiling

func (tr Transport) Ceiling() Tier

Ceiling returns the highest capability tier permitted on this transport per Layer 2.

func (Transport) Valid

func (tr Transport) Valid() bool

Valid reports whether tr is a known transport.

type TxtarFile

type TxtarFile struct {
	Name string
	Data []byte
}

TxtarFile is a single named entry inside a txtar archive.

func ParseTxtar

func ParseTxtar(data []byte) ([]TxtarFile, error)

ParseTxtar parses a `-- name --` txtar archive into ordered TxtarFile entries, validating every entry path with ValidateSafeRelPath and unescaping marker lines escaped by FormatTxtar.

Jump to

Keyboard shortcuts

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