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
- Variables
- func ApplyUnifiedDiff(baseText, diffText string) (string, error)
- func CheckTier(w http.ResponseWriter, r *http.Request, minTier Tier) bool
- func ExtractBearerToken(r *http.Request) (string, bool)
- func FormatTxtar(files []TxtarFile) []byte
- func HTTPGuard(cfg GuardConfig) func(http.Handler) http.Handler
- func RequireTier(minTier Tier) func(http.Handler) http.Handler
- func SanitizeLog(raw string, maxBytes int, secrets ...string) string
- func UnifiedDiff(oldText, newText, name string) string
- func ValidateCompilerFlags(flags []string) error
- func ValidateConfigSetting(key string, val any, schema ConfigSchema) error
- func ValidateEnvKey(key string) error
- func ValidateKernelSource(slot, source string, allowedIncludes []string, maxBytes int) error
- func ValidateLaunchConfig(cfg SlotLaunchConfig, bounds SlotLaunchBounds) error
- func ValidatePullURL(rawURL string, allowlist PullAllowlist) error
- func ValidateSafeRelPath(p string) error
- func ValidateSlotName(slot string) error
- func VerifySignatureLock(baselineSource, candidateSource string) error
- type AgentInfo
- type Attempt
- type AttemptResult
- type AuthInfo
- type CaptureShape
- type ConfigSchema
- type ConflictError
- type Event
- type EventBus
- func (b *EventBus) ActiveAgents() []AgentInfo
- func (b *EventBus) ConnectAgent(actor string, transport Transport, meta map[string]any) Event
- func (b *EventBus) DisconnectAgent(actor string) Event
- func (b *EventBus) Publish(ev Event) Event
- func (b *EventBus) Recent(limit int) []Event
- func (b *EventBus) Subscribe(sinceSeq uint64) (replay []Event, ch <-chan Event, cancel func())
- type EventType
- type FeedbackEntry
- type FeedbackKind
- type GenerationRecord
- type GenerationSummary
- type GuardConfig
- type Hypothesis
- type HypothesisRevision
- type HypothesisStatus
- type KernelParam
- type KernelSignature
- type KernelSlot
- type Operation
- type ParityResult
- type ProfileRef
- type ProfileResult
- type PullAllowlist
- type QueryRecord
- type Receipt
- type ReferenceSpec
- type ReplayAttemptInput
- type ReplayAttemptOutcome
- type ReplayReport
- type ReplayRunner
- type ReplayRunnerFunc
- type RevertRequest
- type SessionBase
- type SessionMeta
- type SessionSnapshot
- type SessionSummary
- type SettingSpec
- type SlotEditReceipt
- type SlotEditRequest
- type SlotEditResult
- type SlotInfo
- type SlotLaunchBounds
- type SlotLaunchConfig
- type SlotRegistry
- func (r *SlotRegistry) AgentView(model string) []SlotSpec
- func (r *SlotRegistry) Bus() *EventBus
- func (r *SlotRegistry) GetSlot(name string) (*SlotSpec, bool)
- func (r *SlotRegistry) GetSlotAgentView(name string) (*SlotSpec, bool)
- func (r *SlotRegistry) ListSlots(model string) []SlotSpec
- func (r *SlotRegistry) Models() []string
- func (r *SlotRegistry) Receipts(limit int) []SlotEditReceipt
- func (r *SlotRegistry) RecordCompileResult(genID int64, ok bool, compilerLog, ptxDiff, sassDiff string, durationMS int64) (*GenerationRecord, error)
- func (r *SlotRegistry) RecordPatched(genID int64, durationMS int64) (*GenerationRecord, error)
- func (r *SlotRegistry) RegisterSlot(spec SlotSpec) error
- func (r *SlotRegistry) RunID() string
- func (r *SlotRegistry) Store() *Store
- func (r *SlotRegistry) SubmitSlotEdit(ctx context.Context, req SlotEditRequest) (*SlotEditResult, error)
- type SlotRegistryConfig
- type SlotSpec
- type Status
- type Store
- func (s *Store) AddFeedbackEntry(sessionID string, entry FeedbackEntry) error
- func (s *Store) AttachProfile(sessionID, attemptID, kind string, rawBytes []byte, summaryText string) (ProfileRef, error)
- func (s *Store) AttachQueryEvidence(sessionID, actor string, rec QueryRecord) error
- func (s *Store) AttemptBegin(sessionID, actor, hypothesisID, intent string, actsOn ...string) (string, error)
- func (s *Store) AttemptEnd(sessionID, actor, attemptID, note string) error
- func (s *Store) Bus() *EventBus
- func (s *Store) GetGeneration(id int64) (*GenerationRecord, bool)
- func (s *Store) GetSlot(name string) (*SlotInfo, bool)
- func (s *Store) HypothesisAdd(sessionID, actor, claim, prediction, falsifier string) (string, error)
- func (s *Store) HypothesisUpdate(sessionID, actor, id string, status HypothesisStatus, evidence []string, ...) error
- func (s *Store) ListGenerations(slot string, limit int) []GenerationRecord
- func (s *Store) ListSlots() []SlotInfo
- func (s *Store) PodTier() Tier
- func (s *Store) Receipts(limit int) []Receipt
- func (s *Store) RecordCompileResult(genID int64, ok bool, compilerLog, ptxDiff, sassDiff string, durationMS int64) (*GenerationRecord, error)
- func (s *Store) RecordParity(genID int64, parity ParityResult, durationMS int64) (*GenerationRecord, error)
- func (s *Store) RecordPatched(genID int64, durationMS int64) (*GenerationRecord, error)
- func (s *Store) RecordProfile(genID int64, profile ProfileResult, durationMS int64) (*GenerationRecord, error)
- func (s *Store) RegisterSlot(name, path, source string) (*SlotInfo, error)
- func (s *Store) Revert(ctx context.Context, req RevertRequest) (*GenerationRecord, error)
- func (s *Store) RunID() string
- func (s *Store) ScanWatchDir() error
- func (s *Store) SendAdviseFeedback(sessionID, actor, findingID string, kind FeedbackKind, ...) error
- func (s *Store) SendFeedback(sessionID, actor, summary, suggestion, receiptID string) error
- func (s *Store) SessionConclude(sessionID, actor, summary string) error
- func (s *Store) SessionExportTxtar(sessionID string) (string, []byte, error)
- func (s *Store) SessionList() []SessionSummary
- func (s *Store) SessionRead(sessionID string) (*SessionSnapshot, bool)
- func (s *Store) SessionStart(actor, goal string, baseMeta SessionBase, tier Tier) (string, error)
- func (s *Store) SetAttemptActsOn(sessionID, actor, attemptID string, actsOn ...string) error
- func (s *Store) StatusSnapshot() StoreStatus
- func (s *Store) SubmitEdit(ctx context.Context, req SubmitRequest) (*GenerationRecord, error)
- func (s *Store) TryRaiseTier(target Tier) error
- type StoreConfig
- type StoreStatus
- type SubmitRequest
- type Tier
- type TierPolicy
- type TokenStore
- func (ts *TokenStore) GoString() string
- func (ts *TokenStore) MintSessionCookie(actor string, ttl time.Duration) *http.Cookie
- func (ts *TokenStore) Path() string
- func (ts *TokenStore) Redact(s string) string
- func (ts *TokenStore) String() string
- func (ts *TokenStore) ValidateSessionCookie(r *http.Request) (string, bool)
- func (ts *TokenStore) ValidateToken(candidate string) bool
- type Transport
- type TxtarFile
Constants ¶
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 */ )
const ( 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 )
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 ¶
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") 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") )
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") )
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") )
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") )
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 ¶
ApplyUnifiedDiff applies a unified diff produced by UnifiedDiff onto baseText.
func CheckTier ¶
CheckTier verifies that the request carries an AuthInfo with EffectiveTier >= minTier. On failure, it writes 403 Forbidden and returns false.
func ExtractBearerToken ¶
ExtractBearerToken parses an HTTP Authorization: Bearer <token> header.
func FormatTxtar ¶
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 ¶
RequireTier returns middleware enforcing that the request's effective tier is at least minTier.
func SanitizeLog ¶
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 ¶
UnifiedDiff produces a standard unified diff between oldText and newText for name.
func ValidateCompilerFlags ¶
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 ¶
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 ¶
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 ¶
ValidateSafeRelPath rejects empty, absolute, backslash, null-byte, newline, or ".." traversal paths.
func ValidateSlotName ¶
ValidateSlotName validates a registered kernel slot filename (strict basename, no traversal).
func VerifySignatureLock ¶
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 ¶
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.
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 ¶
NewEventBus creates an EventBus retaining the last bufCap events (default 512).
func (*EventBus) ActiveAgents ¶
ActiveAgents returns a sorted snapshot of currently connected agents.
func (*EventBus) ConnectAgent ¶
ConnectAgent registers an active agent and publishes an agent_connected event.
func (*EventBus) DisconnectAgent ¶
DisconnectAgent unregisters an agent and publishes an agent_disconnected event.
func (*EventBus) Publish ¶
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.
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 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 ¶
func (f ReplayRunnerFunc) RunAttempt(ctx context.Context, base SessionBase, attempt ReplayAttemptInput) (ReplayAttemptOutcome, error)
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.
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"`
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"`
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 ¶
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.
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 ¶
AttemptEnd closes an open attempt without altering previously recorded attempt artifacts.
func (*Store) GetGeneration ¶
func (s *Store) GetGeneration(id int64) (*GenerationRecord, bool)
GetGeneration returns a copy of the GenerationRecord for id.
func (*Store) GetSlot ¶
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) 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 ¶
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) ScanWatchDir ¶
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 ¶
SendFeedback appends a feedback entry to the session's feedback.jsonl log.
func (*Store) SessionConclude ¶
SessionConclude writes the conclusion markdown for a session.
func (*Store) SessionExportTxtar ¶
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 ¶
SessionStart begins a new append-only session txtar notebook and emits a session_event.
func (*Store) SetAttemptActsOn ¶
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 ¶
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.
func EffectiveTier ¶
EffectiveTier computes min(podTier, transport.Ceiling()) per Layer 2. If either input is invalid, it fails closed by returning an empty Tier (rank 0).
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 ¶
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.
func ParseTransport ¶
ParseTransport parses a transport string, rejecting unknown values.
type TxtarFile ¶
TxtarFile is a single named entry inside a txtar archive.
func ParseTxtar ¶
ParseTxtar parses a `-- name --` txtar archive into ordered TxtarFile entries, validating every entry path with ValidateSafeRelPath and unescaping marker lines escaped by FormatTxtar.