{"modulePath":"github.com/tmc/lib/nvidia","version":"v0.1.0","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package devloop\n\nPackage 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.\n\nSecurity architecture (Layers 2–7):\n\n  - Layer 2 (transport ceilings): EffectiveTier = min(PodTier, Transport.Ceiling()), plus Origin and Sec-Fetch-Site validation on mutations.\n  - 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.\n  - Layer 4 (immutable capability tiers): observe \\\u003c kernel \\\u003c config \\\u003c code, fixed at startup via TierPolicy with no runtime elevation API.\n  - 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.\n  - Layer 6–7 (audit \u0026 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.\n\nThis package is outside the compatibility promise of github.com/tmc/lib/nvidia. Its API may change or be removed in patch releases.\n\n## Constants\n\n```go\nconst (\n\t// SessionCookieName is the HttpOnly SameSite=Strict HMAC session cookie for /ui/.\n\tSessionCookieName = \"devloop_ui_session\"\n\n\t// DefaultMaxKernelSourceBytes is the default Layer 5 kernel source size cap (512 KiB).\n\tDefaultMaxKernelSourceBytes = 512 * 1024\n\n\t// DefaultMaxLogBytes is the default Layer 5 compiler/runtime log cap (16 KiB).\n\tDefaultMaxLogBytes = 16 * 1024\n\n\t// DefaultMaxMutationBodyBytes is the default Layer 3 HTTP mutation body size cap (4 MiB).\n\tDefaultMaxMutationBodyBytes int64 = 4 \u003c\u003c 20\n\n\t// DefaultContentSecurityPolicy is the strict zero-script, zero-CDN CSP set by HTTPGuard.\n\tDefaultContentSecurityPolicy = \"default-src 'none'; style-src 'unsafe-inline'; img-src 'self' data:; frame-ancestors 'none'; base-uri 'none'; form-action 'none'\"\n)\n```\n\n```go\nconst (\n\t// DefaultMaxSharedMemBytes is the default dynamic shared memory per block cap (228 KiB).\n\tDefaultMaxSharedMemBytes uint32 = 228 * 1024\n\n\t// DefaultMaxBlockThreads is the CUDA architectural cap on threads per block.\n\tDefaultMaxBlockThreads uint32 = 1024\n\n\t// DefaultWarpSize is the CUDA warp width.\n\tDefaultWarpSize uint32 = 32\n\n\t// DefaultMinRegsPerThread is the minimum explicit NVRTC/PTX register cap when non-zero.\n\tDefaultMinRegsPerThread = 16\n\n\t// DefaultMaxRegsPerThread is the architectural maximum registers per thread.\n\tDefaultMaxRegsPerThread = 255\n)\n```\n\n```go\nconst NoCAS int64 = -1\n```\nNoCAS disables compare-and-swap generation checking when passed as ExpectedGeneration. ExpectedGeneration == 0 is a real CAS check expecting generation 0 (baseline), never a wildcard.\n\n## Variables\n\n```go\nvar (\n\tErrInvalidTier          = errors.New(\"devloop: invalid capability tier\")\n\tErrTierRaiseForbidden   = errors.New(\"devloop: capability tier is fixed at startup and cannot be raised\")\n\tErrTierInsufficient     = errors.New(\"devloop: effective tier insufficient for operation\")\n\tErrInvalidTransport     = errors.New(\"devloop: invalid transport\")\n\tErrForbiddenHost        = errors.New(\"devloop: forbidden Host header\")\n\tErrUnauthorized         = errors.New(\"devloop: unauthorized\")\n\tErrForbiddenOrigin      = errors.New(\"devloop: forbidden browser Origin or Sec-Fetch-Site\")\n\tErrUnsupportedMediaType = errors.New(\"devloop: unsupported media type; application/json required\")\n\tErrForbiddenEnvKey      = errors.New(\"devloop: forbidden environment variable key\")\n\tErrUnknownConfigSetting = errors.New(\"devloop: unknown configuration setting\")\n\tErrInvalidConfigValue   = errors.New(\"devloop: invalid configuration setting value\")\n\tErrForbiddenPullURL     = errors.New(\"devloop: pull URL violates allowlist\")\n\tErrUnsafePath           = errors.New(\"devloop: unsafe or traversal path\")\n\tErrInvalidKernelSource  = errors.New(\"devloop: kernel source violates validation rules\")\n\tErrForbiddenFlags       = errors.New(\"devloop: caller-supplied compiler flags are forbidden at kernel tier\")\n\tErrSignatureMismatch    = errors.New(\"devloop: CUDA kernel signature lock violation\")\n)\n```\n\n```go\nvar (\n\tErrSessionNotFound    = errors.New(\"devloop: session not found\")\n\tErrHypothesisNotFound = errors.New(\"devloop: hypothesis not found\")\n\tErrAttemptNotFound    = errors.New(\"devloop: attempt not found\")\n\tErrInvalidHypothesis  = errors.New(\"devloop: invalid hypothesis status\")\n\tErrInvalidFeedback    = errors.New(\"devloop: invalid feedback entry\")\n\tErrActsOnAfterEdit    = errors.New(\"devloop: acts_on must be declared before an edit attaches to the attempt\")\n\tErrAttemptClosed      = errors.New(\"devloop: attempt is closed and immutable\")\n)\n```\n\n```go\nvar (\n\t// ErrInvalidLaunchConfig is returned when a SlotLaunchConfig violates geometry or hardware bounds.\n\tErrInvalidLaunchConfig = errors.New(\"devloop: invalid slot launch config\")\n\n\t// ErrInvalidSlotSpec is returned when a SlotSpec or SlotEditRequest is malformed.\n\tErrInvalidSlotSpec = errors.New(\"devloop: invalid kernel slot spec\")\n)\n```\n\n```go\nvar (\n\tErrSlotNotFound       = errors.New(\"devloop: kernel slot not found\")\n\tErrGenerationNotFound = errors.New(\"devloop: generation not found\")\n\tErrConflict           = errors.New(\"devloop: compare-and-swap generation conflict\")\n)\n```\n\n```go\nvar DefaultAllowedIncludes = []string{\n\t\"cuda_runtime.h\",\n\t\"cuda_fp16.h\",\n\t\"cuda_bf16.h\",\n\t\"cuda_fp8.h\",\n\t\"cooperative_groups.h\",\n\t\"stdint.h\",\n\t\"stddef.h\",\n\t\"math.h\",\n\t\"float.h\",\n\t\"limits.h\",\n\t\"cstdint\",\n\t\"cstddef\",\n\t\"cmath\",\n\t\"cfloat\",\n}\n```\nDefaultAllowedIncludes is the default bundled header allowlist for NVRTC kernel compilation.\n\n## Functions\n\n```go\nfunc ApplyUnifiedDiff(baseText, diffText string) (string, error)\n```\nApplyUnifiedDiff applies a unified diff produced by UnifiedDiff onto baseText.\n\n```go\nfunc CheckTier(w http.ResponseWriter, r *http.Request, minTier Tier) bool\n```\nCheckTier verifies that the request carries an AuthInfo with EffectiveTier \u003e= minTier. On failure, it writes 403 Forbidden and returns false.\n\n```go\nfunc ExtractBearerToken(r *http.Request) (string, bool)\n```\nExtractBearerToken parses an HTTP Authorization: Bearer \\\u003ctoken\u003e header.\n\n```go\nfunc FormatTxtar(files []TxtarFile) []byte\n```\nFormatTxtar 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.\n\n```go\nfunc HTTPGuard(cfg GuardConfig) func(http.Handler) http.Handler\n```\nHTTPGuard 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.\n\n```go\nfunc RequireTier(minTier Tier) func(http.Handler) http.Handler\n```\nRequireTier returns middleware enforcing that the request's effective tier is at least minTier.\n\n```go\nfunc SanitizeLog(raw string, maxBytes int, secrets ...string) string\n```\nSanitizeLog strips control characters, redacts any provided secrets as well as bearer/session-cookie patterns, and caps the output to maxBytes (default 16 KiB).\n\n```go\nfunc UnifiedDiff(oldText, newText, name string) string\n```\nUnifiedDiff produces a standard unified diff between oldText and newText for name.\n\n```go\nfunc ValidateCompilerFlags(flags []string) error\n```\nValidateCompilerFlags rejects any caller-supplied compiler flags at kernel tier. NVRTC uses fixed per-arch options only.\n\n```go\nfunc ValidateConfigSetting(key string, val any, schema ConfigSchema) error\n```\nValidateConfigSetting checks key against the env denylist and schema, then validates val.\n\n```go\nfunc ValidateEnvKey(key string) error\n```\nValidateEnvKey enforces the Layer 5 hard denylist covering code-loading and linker/runtime environment variables (LD\\_\\*, PYTHON\\*, PATH, CUDA\\_INJECTION\\*, \\*\\_PRELOAD, DYLD\\_\\*, etc.).\n\n```go\nfunc ValidateKernelSource(slot, source string, allowedIncludes []string, maxBytes int) error\n```\nValidateKernelSource 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).\n\n```go\nfunc ValidateLaunchConfig(cfg SlotLaunchConfig, bounds SlotLaunchBounds) error\n```\nValidateLaunchConfig enforces strict geometry, warp-multiple, shared-memory, register-cap, and PDL bounds on cfg.\n\n```go\nfunc ValidatePullURL(rawURL string, allowlist PullAllowlist) error\n```\nValidatePullURL validates rawURL against Layer 5 pull rules: rejects http://, file://, off-allowlist scheme/host/bucket/prefix, userinfo, and path traversal.\n\n```go\nfunc ValidateSafeRelPath(p string) error\n```\nValidateSafeRelPath rejects empty, absolute, backslash, null-byte, newline, or \"..\" traversal paths.\n\n```go\nfunc ValidateSlotName(slot string) error\n```\nValidateSlotName validates a registered kernel slot filename (strict basename, no traversal).\n\n```go\nfunc VerifySignatureLock(baselineSource, candidateSource string) error\n```\nVerifySignatureLock ensures candidateSource preserves the exact set of CUDA kernel entry points, qualifiers, template signatures, parameter counts, and normalized parameter types from baselineSource.\n\n## Types\n\n```go\ntype AgentInfo struct {\n\tActor       string         `json:\"actor\"`\n\tTransport   Transport      `json:\"transport\"`\n\tConnectedAt time.Time      `json:\"connected_at\"`\n\tMeta        map[string]any `json:\"meta,omitempty\"`\n}\n```\nAgentInfo tracks a connected agent on the live dev-loop.\n\n```go\ntype Attempt struct {\n\tID             string         `json:\"id\"`\n\tHypothesisID   string         `json:\"hypothesis_id\"`\n\tActor          string         `json:\"actor\"`\n\tIntent         string         `json:\"intent\"`\n\tActsOn         []string       `json:\"acts_on,omitempty\"`\n\tSlot           string         `json:\"slot,omitempty\"`\n\tPatchDiff      string         `json:\"patch_diff,omitempty\"`\n\tSource         string         `json:\"source,omitempty\"`\n\tResult         *AttemptResult `json:\"result,omitempty\"`\n\tQueries        []QueryRecord  `json:\"queries,omitempty\"`\n\tProfileSummary string         `json:\"profile_summary,omitempty\"`\n\tProfiles       []ProfileRef   `json:\"profiles,omitempty\"`\n\tLog            string         `json:\"log,omitempty\"`\n\tEndNote        string         `json:\"end_note,omitempty\"`\n\tOpen           bool           `json:\"open\"`\n\tStartedAt      time.Time      `json:\"started_at\"`\n\tEndedAt        time.Time      `json:\"ended_at,omitempty\"`\n\t// contains filtered or unexported fields\n}\n```\nAttempt is a numbered, immutable-history step inside a session notebook.\n\n```go\nfunc (a Attempt) EditAttached() bool\n```\nEditAttached 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.\n\n```go\ntype AttemptResult struct {\n\tGenerationID int64          `json:\"generation_id,omitempty\"`\n\tSlot         string         `json:\"slot,omitempty\"`\n\tSourceSHA256 string         `json:\"source_sha256,omitempty\"`\n\tStatus       Status         `json:\"status\"`\n\tActsOn       []string       `json:\"acts_on,omitempty\"`\n\tParity       *ParityResult  `json:\"parity,omitempty\"`\n\tTimings      map[string]any `json:\"timings,omitempty\"`\n\tStages       map[string]any `json:\"stages,omitempty\"`\n\tQueries      []QueryRecord  `json:\"queries,omitempty\"`\n\tReceiptID    string         `json:\"receipt_id,omitempty\"`\n\tStartedAt    time.Time      `json:\"started_at\"`\n\tEndedAt      time.Time      `json:\"ended_at,omitempty\"`\n}\n```\nAttemptResult is serialized as \\`-- attempts/\\\u003cid\u003e/result.json --\\`.\n\n```go\ntype AuthInfo struct {\n\tPodTier       Tier\n\tTransport     Transport\n\tEffectiveTier Tier\n\tActor         string\n\tViaCookie     bool\n\tBrowserOrigin bool\n}\n```\nAuthInfo carries verified Layer 2/3/4 authentication and tier metadata in request context.\n\n```go\nfunc AuthFromContext(ctx context.Context) (AuthInfo, bool)\n```\nAuthFromContext retrieves the verified AuthInfo set by HTTPGuard.\n\n```go\ntype CaptureShape struct {\n\tName          string  `json:\"name\"`\n\tBatch         int     `json:\"batch\"`\n\tSeqLen        int     `json:\"seq_len\"`\n\tHidden        int     `json:\"hidden\"`\n\tIntermediate  int     `json:\"intermediate,omitempty\"`\n\tTopK          int     `json:\"top_k,omitempty\"`\n\tExperts       int     `json:\"experts,omitempty\"`\n\tHeadDim       int     `json:\"head_dim,omitempty\"`\n\tCapturedUS    float64 `json:\"captured_us,omitempty\"`\n\tCaptureDigest string  `json:\"capture_digest,omitempty\"`\n\tHeldOut       bool    `json:\"held_out\"`\n}\n```\nCaptureShape records a workload shape extracted from a profiler capture. HeldOut distinguishes scorer-only held-out shapes from dev iteration shapes.\n\n```go\ntype ConfigSchema map[string]SettingSpec\n```\nConfigSchema maps allowed configuration setting keys to their SettingSpec.\n\n```go\nfunc DefaultConfigSchema() ConfigSchema\n```\nDefaultConfigSchema returns the default schema for config-tier settings.\n\n```go\ntype ConflictError struct {\n\tSlot               string `json:\"slot\"`\n\tActor              string `json:\"actor\"`\n\tExpectedGeneration int64  `json:\"expected_generation\"`\n\tCurrentGeneration  int64  `json:\"current_generation\"`\n\tGenerationID       int64  `json:\"generation_id\"`\n\tReceiptID          string `json:\"receipt_id\"`\n}\n```\nConflictError is returned when SubmitEdit or Revert fails compare-and-swap on ExpectedGeneration.\n\n```go\nfunc (e *ConflictError) Error() string\n```\n\n```go\nfunc (e *ConflictError) Is(target error) bool\n```\n\n```go\ntype Event struct {\n\tSeq          uint64         `json:\"seq\"`\n\tAt           time.Time      `json:\"at\"`\n\tType         EventType      `json:\"type\"`\n\tActor        string         `json:\"actor,omitempty\"`\n\tSlot         string         `json:\"slot,omitempty\"`\n\tGenerationID int64          `json:\"generation_id,omitempty\"`\n\tData         map[string]any `json:\"data,omitempty\"`\n}\n```\nEvent is a single event distributed on the SSE EventBus.\n\n```go\ntype EventBus struct {\n\t// contains filtered or unexported fields\n}\n```\nEventBus is a thread-safe SSE-ready pub/sub bus with a bounded ring buffer and agent tracking.\n\n```go\nfunc NewEventBus(bufCap int) *EventBus\n```\nNewEventBus creates an EventBus retaining the last bufCap events (default 512).\n\n```go\nfunc (b *EventBus) ActiveAgents() []AgentInfo\n```\nActiveAgents returns a sorted snapshot of currently connected agents.\n\n```go\nfunc (b *EventBus) ConnectAgent(actor string, transport Transport, meta map[string]any) Event\n```\nConnectAgent registers an active agent and publishes an agent\\_connected event.\n\n```go\nfunc (b *EventBus) DisconnectAgent(actor string) Event\n```\nDisconnectAgent unregisters an agent and publishes an agent\\_disconnected event.\n\n```go\nfunc (b *EventBus) Publish(ev Event) Event\n```\nPublish 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.\n\n```go\nfunc (b *EventBus) Recent(limit int) []Event\n```\nRecent returns up to limit deep-cloned most recent events in chronological order.\n\n```go\nfunc (b *EventBus) Subscribe(sinceSeq uint64) (replay []Event, ch \u003c-chan Event, cancel func())\n```\nSubscribe returns deep-cloned buffered events with Seq \u003e sinceSeq, a live event channel, and an idempotent cancel function.\n\n```go\ntype EventType string\n```\nEventType identifies a live SSE event emitted on the EventBus.\n\n```go\nconst (\n\tEventEditSubmitted     EventType = \"edit_submitted\"\n\tEventCompileOK         EventType = \"compile_ok\"\n\tEventCompileError      EventType = \"compile_error\"\n\tEventPatched           EventType = \"patched\"\n\tEventReverted          EventType = \"reverted\"\n\tEventParity            EventType = \"parity\"\n\tEventProfile           EventType = \"profile\"\n\tEventConflict          EventType = \"conflict\"\n\tEventAgentConnected    EventType = \"agent_connected\"\n\tEventAgentDisconnected EventType = \"agent_disconnected\"\n\tEventSessionEvent      EventType = \"session_event\"\n)\n```\n\n```go\ntype FeedbackEntry struct {\n\tAt          time.Time    `json:\"at\"`\n\tActor       string       `json:\"actor\"`\n\tSummary     string       `json:\"summary\"`\n\tSuggestion  string       `json:\"suggestion,omitempty\"`\n\tReceiptID   string       `json:\"receipt_id,omitempty\"`\n\tFindingID   string       `json:\"finding_id,omitempty\"`\n\tKind        FeedbackKind `json:\"kind,omitempty\"`\n\tEvidence    string       `json:\"evidence,omitempty\"`\n\tEngine      string       `json:\"engine,omitempty\"`\n\tQuerySHA256 string       `json:\"query_sha256,omitempty\"`\n}\n```\nFeedbackEntry is appended to \\`-- feedback.jsonl --\\`.\n\n```go\ntype FeedbackKind string\n```\nFeedbackKind classifies explicit advise feedback entries.\n\n```go\nconst (\n\tFeedbackCorrection FeedbackKind = \"correction\"\n\tFeedbackSuggestion FeedbackKind = \"suggestion\"\n\tFeedbackConfusing  FeedbackKind = \"confusing\"\n)\n```\n\n```go\ntype GenerationRecord struct {\n\tGenerationID       int64          `json:\"generation_id\"`\n\tSlot               string         `json:\"slot\"`\n\tActor              string         `json:\"actor\"`\n\tTransport          Transport      `json:\"transport\"`\n\tTier               Tier           `json:\"tier\"`\n\tOperation          Operation      `json:\"operation\"`\n\tStatus             Status         `json:\"status\"`\n\tSource             string         `json:\"source,omitempty\"`\n\tSourceSHA256       string         `json:\"source_sha256,omitempty\"`\n\tParentGeneration   int64          `json:\"parent_generation,omitempty\"`\n\tRestoredGeneration int64          `json:\"restored_generation,omitempty\"`\n\tUnifiedDiff        string         `json:\"unified_diff,omitempty\"`\n\tPTXDiff            string         `json:\"ptx_diff,omitempty\"`\n\tSASSDiff           string         `json:\"sass_diff,omitempty\"`\n\tCompilerLog        string         `json:\"compiler_log,omitempty\"`\n\tParity             *ParityResult  `json:\"parity,omitempty\"`\n\tProfile            *ProfileResult `json:\"profile,omitempty\"`\n\tReceiptID          string         `json:\"receipt_id\"`\n\tStartedAt          time.Time      `json:\"started_at\"`\n\tEndedAt            time.Time      `json:\"ended_at,omitempty\"`\n\tDurationMS         int64          `json:\"duration_ms,omitempty\"`\n}\n```\nGenerationRecord holds the full state of a single monotonic generation attempt.\n\n```go\ntype GenerationSummary struct {\n\tGenerationID int64     `json:\"generation_id\"`\n\tStatus       Status    `json:\"status\"`\n\tActor        string    `json:\"actor\"`\n\tSourceSHA256 string    `json:\"source_sha256\"`\n\tStartedAt    time.Time `json:\"started_at\"`\n\tEndedAt      time.Time `json:\"ended_at,omitempty\"`\n\tDurationMS   int64     `json:\"duration_ms,omitempty\"`\n\tP50MS        *float64  `json:\"p50_ms,omitempty\"`\n\tParityPass   *bool     `json:\"parity_pass,omitempty\"`\n}\n```\nGenerationSummary is a compact per-slot history item for UI sparklines and slot listings.\n\n```go\ntype GuardConfig struct {\n\t// PodTier is the immutable tier of the runtime (defaults to DefaultTier).\n\tPodTier Tier\n\t// Transport is the transport served by this listener (defaults to TransportLoopback).\n\tTransport Transport\n\t// Port, when \u003e 0, populates allowed Host headers with 127.0.0.1:\u003cport\u003e and localhost:\u003cport\u003e.\n\tPort int\n\t// AllowedHosts explicitly specifies exact allowed Host header values (in addition to Port).\n\tAllowedHosts []string\n\t// Tokens validates bearer tokens and HMAC session cookies. Required (nil fails closed).\n\tTokens *TokenStore\n\t// SessionCookiePrefixes lists URL path prefixes where an HttpOnly HMAC session cookie\n\t// is accepted for safe GET/HEAD reads. Defaults to []string{\"/ui/\"}.\n\tSessionCookiePrefixes []string\n\t// RejectAnyOriginOnMutations forces rejection of any non-empty Origin header on\n\t// mutations (even same-origin). This behavior is now ON by default unless\n\t// AllowSameOriginMutations is explicitly set to true (and RejectAnyOriginOnMutations is false).\n\t// Cross-site Origin and cross-site/same-site Sec-Fetch-Site are ALWAYS rejected on mutations.\n\tRejectAnyOriginOnMutations bool\n\t// AllowSameOriginMutations explicitly opts in to permitting same-origin browser\n\t// mutations on non-/mcp paths when RejectAnyOriginOnMutations is false.\n\tAllowSameOriginMutations bool\n\t// MaxMutationBodyBytes caps request body bytes on mutation methods via http.MaxBytesReader.\n\t// Defaults to DefaultMaxMutationBodyBytes (4 MiB) when \u003c= 0.\n\tMaxMutationBodyBytes int64\n\t// ContentSecurityPolicy overrides the strict default CSP header when non-empty.\n\tContentSecurityPolicy string\n}\n```\nGuardConfig configures the Layer 2/3/4 HTTP security middleware.\n\n```go\ntype Hypothesis struct {\n\tID         string               `json:\"id\"`\n\tClaim      string               `json:\"claim\"`\n\tPrediction string               `json:\"prediction\"`\n\tFalsifier  string               `json:\"falsifier\"`\n\tActor      string               `json:\"actor\"`\n\tCreatedAt  time.Time            `json:\"created_at\"`\n\tRevisions  []HypothesisRevision `json:\"revisions\"`\n}\n```\nHypothesis represents a falsifiable hypothesis with an append-only revision log.\n\n```go\nfunc (h Hypothesis) CurrentStatus() HypothesisStatus\n```\nCurrentStatus returns the latest status in the hypothesis's append-only revision log.\n\n```go\ntype HypothesisRevision struct {\n\tRev      int              `json:\"rev\"`\n\tAt       time.Time        `json:\"at\"`\n\tActor    string           `json:\"actor\"`\n\tStatus   HypothesisStatus `json:\"status\"`\n\tEvidence []string         `json:\"evidence,omitempty\"`\n\tNote     string           `json:\"note,omitempty\"`\n}\n```\nHypothesisRevision is an append-only revision entry for a hypothesis.\n\n```go\ntype HypothesisStatus string\n```\nHypothesisStatus is the bounded status enum for session hypotheses.\n\n```go\nconst (\n\tHypothesisOpen      HypothesisStatus = \"open\"\n\tHypothesisSupported HypothesisStatus = \"supported\"\n\tHypothesisRefuted   HypothesisStatus = \"refuted\"\n\tHypothesisAbandoned HypothesisStatus = \"abandoned\"\n)\n```\n\n```go\ntype KernelParam struct {\n\tRaw            string `json:\"raw\"`\n\tNormalizedType string `json:\"normalized_type\"`\n\tName           string `json:\"name,omitempty\"`\n}\n```\nKernelParam represents a single parameter of a CUDA kernel declaration.\n\n```go\ntype KernelSignature struct {\n\tQualifier      string        `json:\"qualifier\"`\n\tExternC        bool          `json:\"extern_c,omitempty\"`\n\tTemplateParams string        `json:\"template_params,omitempty\"`\n\tReturnType     string        `json:\"return_type\"`\n\tName           string        `json:\"name\"`\n\tParams         []KernelParam `json:\"params\"`\n\tCanonical      string        `json:\"canonical\"`\n}\n```\nKernelSignature represents a parsed \\_\\_global\\_\\_ or \\_\\_tile\\_global\\_\\_ CUDA kernel signature.\n\n```go\nfunc ExtractCUDASignatures(source string) ([]KernelSignature, error)\n```\nExtractCUDASignatures parses all \\_\\_global\\_\\_ and \\_\\_tile\\_global\\_\\_ kernel declarations in source, supporting extern \"C\", template\\\u003c...\u003e, \\_\\_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.\n\n```go\ntype KernelSlot = SlotSpec\n```\nKernelSlot is the canonical alias for SlotSpec.\n\n```go\ntype Operation string\n```\nOperation is a bounded enum for dev-loop audit receipts.\n\n```go\nconst (\n\tOpSubmitKernel Operation = \"submit_kernel\"\n\tOpCompile      Operation = \"compile\"\n\tOpPatch        Operation = \"patch\"\n\tOpParity       Operation = \"parity\"\n\tOpProfile      Operation = \"profile\"\n\tOpRevert       Operation = \"revert\"\n\tOpConflict     Operation = \"conflict\"\n)\n```\n\n```go\ntype ParityResult struct {\n\tPassed      bool    `json:\"passed\"`\n\tMaxError    float64 `json:\"max_error\"`\n\tMatched     int     `json:\"matched\"`\n\tAttempted   int     `json:\"attempted\"`\n\tSuiteDigest string  `json:\"suite_digest,omitempty\"`\n\tDetails     string  `json:\"details,omitempty\"`\n}\n```\nParityResult records correctness verification for a generation.\n\n```go\ntype ProfileRef struct {\n\tKind   string `json:\"kind\"`\n\tSHA256 string `json:\"sha256\"`\n\tBytes  int64  `json:\"bytes\"`\n\tPath   string `json:\"path\"`\n}\n```\nProfileRef is a content-addressed reference to a binary profile kept on disk.\n\n```go\ntype ProfileResult struct {\n\tP50MS      float64  `json:\"p50_ms\"`\n\tGBS        float64  `json:\"gb_s\"`\n\tRegs       int      `json:\"regs\"`\n\tDiffPrevMS *float64 `json:\"diff_prev_ms,omitempty\"`\n\tSummary    string   `json:\"summary,omitempty\"`\n}\n```\nProfileResult records cudaprof / benchmark metrics for a generation.\n\n```go\ntype PullAllowlist struct {\n\tSchemes  []string // e.g. [\"https\", \"s3\", \"oci\"]; \"http\" and \"file\" are always rejected\n\tHosts    []string // exact allowed hostnames (for https/oci)\n\tBuckets  []string // exact allowed bucket names (for s3/gs)\n\tPrefixes []string // allowed path prefixes (e.g. \"/models/\", \"checkpoints/\")\n\tMaxBytes int64    // optional size cap\n}\n```\nPullAllowlist defines Layer 5 pull validation constraints.\n\n```go\ntype QueryRecord struct {\n\tQuerySHA256 string    `json:\"query_sha256\"`\n\tEngine      string    `json:\"engine\"`\n\tDatabase    string    `json:\"database,omitempty\"`\n\tActor       string    `json:\"actor,omitempty\"`\n\tRows        int       `json:\"rows\"`\n\tBytes       int64     `json:\"bytes,omitempty\"`\n\tDurationMS  float64   `json:\"duration_ms\"`\n\tAt          time.Time `json:\"at\"`\n}\n```\nQueryRecord records audited tracedb query evidence executed during a session/attempt.\n\n```go\ntype Receipt struct {\n\tRunID                string    `json:\"run_id\"`\n\tGenerationID         int64     `json:\"generation_id\"`\n\tServingGenerationID  int64     `json:\"serving_generation_id\"`\n\tReceiptID            string    `json:\"receipt_id\"`\n\tActor                string    `json:\"actor\"`\n\tTransport            Transport `json:\"transport\"`\n\tTier                 Tier      `json:\"tier\"`\n\tOperation            Operation `json:\"operation\"`\n\tSlot                 string    `json:\"slot\"`\n\tSourceSHA256         string    `json:\"source_sha256,omitempty\"`\n\tRestoredGenerationID int64     `json:\"restored_generation_id,omitempty\"`\n\tStatus               Status    `json:\"status\"`\n\tStartedAt            time.Time `json:\"started_at\"`\n\tEndedAt              time.Time `json:\"ended_at\"`\n\tDurationMS           int64     `json:\"duration_ms\"`\n}\n```\nReceipt is a Layer 7 terminal audit receipt appended to receipts.jsonl. It never contains tokens, raw source, or secrets.\n\n```go\ntype ReferenceSpec struct {\n\tScript       string  `json:\"script,omitempty\"`\n\tOpName       string  `json:\"op_name\"`\n\tGoldenPath   string  `json:\"golden_path,omitempty\"`\n\tGoldenSHA256 string  `json:\"golden_sha256,omitempty\"`\n\tMaxAbsTol    float64 `json:\"max_abs_tol\"`\n\tRMSTol       float64 `json:\"rms_tol,omitempty\"`\n\tExactIndices bool    `json:\"exact_indices\"`\n}\n```\nReferenceSpec binds a kernel slot to its golden reference implementation and parity tolerances.\n\n```go\ntype ReplayAttemptInput struct {\n\tAttemptID      string         `json:\"attempt_id\"`\n\tIntent         string         `json:\"intent\"`\n\tActsOn         []string       `json:\"acts_on,omitempty\"`\n\tSlot           string         `json:\"slot,omitempty\"`\n\tPatchDiff      string         `json:\"patch_diff,omitempty\"`\n\tSource         string         `json:\"source,omitempty\"`\n\tExpectedResult *AttemptResult `json:\"expected_result,omitempty\"`\n\tProfiles       []ProfileRef   `json:\"profiles,omitempty\"`\n}\n```\nReplayAttemptInput contains the parsed artifacts for one numbered attempt in a txtar notebook.\n\n```go\ntype ReplayAttemptOutcome struct {\n\tAttemptID  string `json:\"attempt_id\"`\n\tPassed     bool   `json:\"passed\"`\n\tStatus     Status `json:\"status\"`\n\tError      string `json:\"error,omitempty\"`\n\tDurationMS int64  `json:\"duration_ms\"`\n\tDetails    string `json:\"details,omitempty\"`\n}\n```\nReplayAttemptOutcome is the result of replaying a single attempt.\n\n```go\ntype ReplayReport struct {\n\tSessionID string                 `json:\"session_id\"`\n\tBase      SessionBase            `json:\"base\"`\n\tAttempts  []ReplayAttemptOutcome `json:\"attempts\"`\n\tPassed    int                    `json:\"passed\"`\n\tFailed    int                    `json:\"failed\"`\n\tAllPassed bool                   `json:\"all_passed\"`\n}\n```\nReplayReport summarizes replaying every numbered attempt in a session txtar notebook.\n\n```go\nfunc ReplaySession(ctx context.Context, txtarBytes []byte, runner ReplayRunner) (*ReplayReport, error)\n```\nReplaySession 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.\n\n```go\ntype ReplayRunner interface {\n\tRunAttempt(ctx context.Context, base SessionBase, attempt ReplayAttemptInput) (ReplayAttemptOutcome, error)\n}\n```\nReplayRunner executes a replayed attempt against base metadata.\n\n```go\ntype ReplayRunnerFunc func(ctx context.Context, base SessionBase, attempt ReplayAttemptInput) (ReplayAttemptOutcome, error)\n```\nReplayRunnerFunc adapts a function to ReplayRunner.\n\n```go\nfunc (f ReplayRunnerFunc) RunAttempt(ctx context.Context, base SessionBase, attempt ReplayAttemptInput) (ReplayAttemptOutcome, error)\n```\n\n```go\ntype RevertRequest struct {\n\tSlot               string    `json:\"slot\"`\n\tTargetGeneration   int64     `json:\"target_generation\"`\n\tExpectedGeneration int64     `json:\"expected_generation,omitempty\"`\n\tActor              string    `json:\"actor\"`\n\tTransport          Transport `json:\"transport\"`\n}\n```\nRevertRequest requests reverting a registered slot to TargetGeneration (0 = baseline).\n\n```go\ntype SessionBase struct {\n\tRepoCommit  string            `json:\"repo_commit,omitempty\"`\n\tImageDigest string            `json:\"image_digest,omitempty\"`\n\tProfile     string            `json:\"profile,omitempty\"`\n\tCUDACompat  string            `json:\"cuda_compat,omitempty\"`\n\tExtra       map[string]string `json:\"extra,omitempty\"`\n}\n```\nSessionBase records the immutable baseline metadata for a session notebook.\n\n```go\ntype SessionMeta struct {\n\tSessionID string        `json:\"session_id\"`\n\tRunID     string        `json:\"run_id\"`\n\tActor     string        `json:\"actor\"`\n\tGoal      string        `json:\"goal\"`\n\tStartedAt time.Time     `json:\"started_at\"`\n\tBase      SessionBase   `json:\"base\"`\n\tTier      Tier          `json:\"tier\"`\n\tQueries   []QueryRecord `json:\"queries,omitempty\"`\n}\n```\nSessionMeta is serialized as \\`-- session.json --\\` in the txtar notebook.\n\n```go\ntype SessionSnapshot struct {\n\tMeta          SessionMeta     `json:\"meta\"`\n\tHypotheses    []Hypothesis    `json:\"hypotheses\"`\n\tAttempts      []Attempt       `json:\"attempts\"`\n\tFeedback      []FeedbackEntry `json:\"feedback,omitempty\"`\n\tConclusion    string          `json:\"conclusion,omitempty\"`\n\tOpenAttemptID string          `json:\"open_attempt_id,omitempty\"`\n}\n```\nSessionSnapshot is an observe-tier read-only snapshot of a session notebook.\n\n```go\ntype SessionSummary struct {\n\tSessionID       string    `json:\"session_id\"`\n\tRunID           string    `json:\"run_id\"`\n\tActor           string    `json:\"actor\"`\n\tGoal            string    `json:\"goal\"`\n\tTier            Tier      `json:\"tier\"`\n\tStartedAt       time.Time `json:\"started_at\"`\n\tHypothesisCount int       `json:\"hypothesis_count\"`\n\tAttemptCount    int       `json:\"attempt_count\"`\n\tConcluded       bool      `json:\"concluded\"`\n}\n```\nSessionSummary is an observe-tier listing item returned by SessionList.\n\n```go\ntype SettingSpec struct {\n\tType string   // \"string\", \"int\", \"float\", \"bool\", \"enum\"\n\tEnum []string // allowed values for \"enum\"\n\tMin  *float64 // optional numeric minimum\n\tMax  *float64 // optional numeric maximum\n}\n```\nSettingSpec describes a schema entry for Layer 4/5 config-tier settings.\n\n```go\ntype SlotEditReceipt struct {\n\tRunID               string    `json:\"run_id\"`\n\tGenerationID        int64     `json:\"generation_id\"`\n\tServingGenerationID int64     `json:\"serving_generation_id\"`\n\tReceiptID           string    `json:\"receipt_id\"`\n\tActor               string    `json:\"actor\"`\n\tTransport           Transport `json:\"transport\"`\n\tTier                Tier      `json:\"tier\"`\n\tOperation           Operation `json:\"operation\"`\n\tSlot                string    `json:\"slot\"`\n\tModel               string    `json:\"model\"`\n\tKernelClass         string    `json:\"kernel_class\"`\n\tSourceSHA256        string    `json:\"source_sha256\"`\n\tLaunchConfigSHA256  string    `json:\"launch_config_sha256\"`\n\tRecompileSkipped    bool      `json:\"recompile_skipped\"`\n\tGraphPatchOnly      bool      `json:\"graph_patch_only\"`\n\tActsOn              []string  `json:\"acts_on,omitempty\"`\n\tStatus              Status    `json:\"status\"`\n\tStartedAt           time.Time `json:\"started_at\"`\n\tEndedAt             time.Time `json:\"ended_at\"`\n\tDurationMS          int64     `json:\"duration_ms\"`\n}\n```\nSlotEditReceipt is the Layer 7 audit receipt recorded for every slot edit or CAS conflict. It never contains tokens, raw CUDA source, or secrets.\n\n```go\ntype SlotEditRequest struct {\n\tSlot               string            `json:\"slot\"`\n\tSource             string            `json:\"source,omitempty\"`\n\tLaunchConfig       *SlotLaunchConfig `json:\"launch_config,omitempty\"`\n\tExpectedGeneration int64             `json:\"expected_generation,omitempty\"`\n\tActor              string            `json:\"actor,omitempty\"`\n\tTransport          Transport         `json:\"transport,omitempty\"`\n\tFlags              []string          `json:\"flags,omitempty\"`\n\tIntent             string            `json:\"intent,omitempty\"`\n\tActsOn             []string          `json:\"acts_on,omitempty\"`\n}\n```\nSlotEditRequest submits a source and/or launch-config edit to a registered kernel slot.\n\n```go\ntype SlotEditResult struct {\n\tGenerationID       int64            `json:\"generation_id\"`\n\tSlot               string           `json:\"slot\"`\n\tModel              string           `json:\"model\"`\n\tKernelClass        string           `json:\"kernel_class\"`\n\tSourceFile         string           `json:\"source_file\"`\n\tActor              string           `json:\"actor\"`\n\tStatus             Status           `json:\"status\"`\n\tSourceSHA256       string           `json:\"source_sha256\"`\n\tLaunchConfig       SlotLaunchConfig `json:\"launch_config\"`\n\tLaunchConfigSHA256 string           `json:\"launch_config_sha256\"`\n\tRecompileSkipped   bool             `json:\"recompile_skipped\"`\n\tGraphPatchOnly     bool             `json:\"graph_patch_only\"`\n\tCacheHit           bool             `json:\"cache_hit\"`\n\tUnifiedDiff        string           `json:\"unified_diff,omitempty\"`\n\tReceiptID          string           `json:\"receipt_id\"`\n\tActsOn             []string         `json:\"acts_on,omitempty\"`\n\tCurrentGeneration  int64            `json:\"current_generation\"`\n\tServingGeneration  int64            `json:\"serving_generation\"`\n\tStartedAt          time.Time        `json:\"started_at\"`\n\tEndedAt            time.Time        `json:\"ended_at\"`\n\tDurationMS         int64            `json:\"duration_ms\"`\n}\n```\nSlotEditResult reports the outcome of a validated SubmitSlotEdit call.\n\n```go\ntype SlotInfo struct {\n\tName              string              `json:\"name\"`\n\tPath              string              `json:\"path,omitempty\"`\n\tSignatures        []KernelSignature   `json:\"signatures\"`\n\tCurrentGeneration int64               `json:\"current_generation\"`\n\tServingGeneration int64               `json:\"serving_generation\"`\n\tSourceSHA256      string              `json:\"source_sha256\"`\n\tHistory           []GenerationSummary `json:\"history\"`\n\tBaselineSource    string              `json:\"baseline_source\"`\n\tCurrentSource     string              `json:\"current_source\"`\n}\n```\nSlotInfo describes a registered hot-reloadable CUDA kernel slot.\n\n```go\nfunc (s SlotInfo) AgentView() SlotInfo\n```\nAgentView returns a sanitized read-only copy of SlotInfo safe for agent consumption, stripping internal host filesystem paths.\n\n```go\ntype SlotLaunchBounds struct {\n\tMaxGrid             [3]uint32 `json:\"max_grid\"`\n\tMinBlockThreads     uint32    `json:\"min_block_threads\"`\n\tMaxBlockThreads     uint32    `json:\"max_block_threads\"`\n\tMaxBlockDims        [3]uint32 `json:\"max_block_dims\"`\n\tRequireWarpMultiple bool      `json:\"require_warp_multiple\"`\n\tMaxSharedMemBytes   uint32    `json:\"max_shared_mem_bytes\"`\n\tMinRegs             int       `json:\"min_regs\"`\n\tMaxRegs             int       `json:\"max_regs\"`\n\tAllowPDL            *bool     `json:\"allow_pdl,omitempty\"`\n}\n```\nSlotLaunchBounds defines strict hardware and per-slot safety bounds for SlotLaunchConfig.\n\n```go\nfunc DefaultLaunchBounds() SlotLaunchBounds\n```\nDefaultLaunchBounds returns architectural launch configuration bounds.\n\n```go\ntype SlotLaunchConfig struct {\n\tGrid          [3]uint32 `json:\"grid\"`\n\tBlock         [3]uint32 `json:\"block\"`\n\tSharedMem     uint32    `json:\"shared_mem\"`\n\tPDL           bool      `json:\"pdl\"`\n\tMaxRegs       int       `json:\"max_regs\"`\n\tWarpsPerBlock int       `json:\"warps_per_block\"`\n}\n```\nSlotLaunchConfig holds editable CUDA kernel launch geometry and execution knobs. Caller-supplied compiler flags are never part of SlotLaunchConfig (enforced by Layer 5).\n\n```go\nfunc (c SlotLaunchConfig) Digest() string\n```\nDigest returns the deterministic SHA-256 hex digest of the launch configuration.\n\n```go\ntype SlotRegistry struct {\n\t// contains filtered or unexported fields\n}\n```\nSlotRegistry manages kernel slots loaded from \\*.slot.json + .cu descriptors or registered programmatically via RegisterSlot, validates source \u0026 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.\n\n```go\nfunc NewSlotRegistry(cfg SlotRegistryConfig) (*SlotRegistry, error)\n```\nNewSlotRegistry constructs a SlotRegistry backed by a single authoritative Store (using cfg.Store when provided, or creating a dedicated Store otherwise) and loads any \\\u003cSlotsDir\u003e/\\*.slot.json descriptors paired with sibling .cu files.\n\n```go\nfunc (r *SlotRegistry) AgentView(model string) []SlotSpec\n```\nAgentView returns sorted agent-safe views of all registered slots (optionally filtered by model), excluding held-out shapes and scorer-only reference paths/digests.\n\n```go\nfunc (r *SlotRegistry) Bus() *EventBus\n```\nBus returns the EventBus used for slot SSE notifications.\n\n```go\nfunc (r *SlotRegistry) GetSlot(name string) (*SlotSpec, bool)\n```\nGetSlot returns a deep copy of a registered slot by canonical slot name (or unique source\\_file).\n\n```go\nfunc (r *SlotRegistry) GetSlotAgentView(name string) (*SlotSpec, bool)\n```\nGetSlotAgentView returns an agent-safe view of a single registered slot, redacting held-out shapes and scorer-only oracle paths/digests.\n\n```go\nfunc (r *SlotRegistry) ListSlots(model string) []SlotSpec\n```\nListSlots returns sorted deep copies of all registered slots, optionally filtered by model.\n\n```go\nfunc (r *SlotRegistry) Models() []string\n```\nModels returns the sorted unique list of model identifiers registered in the registry.\n\n```go\nfunc (r *SlotRegistry) Receipts(limit int) []SlotEditReceipt\n```\nReceipts returns up to limit most recent slot edit receipts.\n\n```go\nfunc (r *SlotRegistry) RecordCompileResult(genID int64, ok bool, compilerLog, ptxDiff, sassDiff string, durationMS int64) (*GenerationRecord, error)\n```\nRecordCompileResult records a compile outcome on the backing Store and, on success, marks the generation's source hash as compiled in the warm compile cache.\n\n```go\nfunc (r *SlotRegistry) RecordPatched(genID int64, durationMS int64) (*GenerationRecord, error)\n```\nRecordPatched marks genID as actively serving on the backing Store and synchronizes slot state.\n\n```go\nfunc (r *SlotRegistry) RegisterSlot(spec SlotSpec) error\n```\nRegisterSlot validates and registers a canonical SlotSpec in the registry.\n\n```go\nfunc (r *SlotRegistry) RunID() string\n```\nRunID returns the immutable run\\_id associated with this SlotRegistry.\n\n```go\nfunc (r *SlotRegistry) Store() *Store\n```\nStore returns the authoritative Store backing this SlotRegistry.\n\n```go\nfunc (r *SlotRegistry) SubmitSlotEdit(ctx context.Context, req SlotEditRequest) (*SlotEditResult, error)\n```\nSubmitSlotEdit validates and applies a source and/or launch\\_config edit to a registered slot. It enforces:\n\n  - Layer 2/4 effective tier \u003e= kernel\n  - ValidateCompilerFlags (zero caller compiler flags)\n  - ValidateLaunchConfig (geometry, warp-multiple, shared memory, register bounds, PDL)\n  - ValidateKernelSource (#include allowlist, size cap, null-byte guard)\n  - VerifySignatureLock (exact CUDA signature lock against baseline \u0026 fixed entry)\n  - Compare-and-swap on ExpectedGeneration (emitting conflict SSE event on mismatch)\n  - Warm source/launch-config hash cache (launch-config-only tweaks skip NVRTC recompile)\n  - Atomic writes into watchDir, monotonic generation allocation, receipt recording, edit\\_submitted SSE publication, and attachment to any open session attempt.\n\n```go\ntype SlotRegistryConfig struct {\n\tStore           *Store\n\tSlotsDir        string\n\tWatchDir        string\n\tStateDir        string\n\tPodTier         Tier\n\tAllowedIncludes []string\n\tMaxSourceBytes  int\n\tTokens          *TokenStore\n}\n```\nSlotRegistryConfig configures a model-agnostic kernel SlotRegistry.\n\n```go\ntype SlotSpec struct {\n\tName               string           `json:\"name\"`\n\tModel              string           `json:\"model\"`\n\tKernelClass        string           `json:\"kernel_class\"`\n\tSourceFile         string           `json:\"source_file\"`\n\tEntry              string           `json:\"entry\"`\n\tFixedSignature     string           `json:\"fixed_signature\"`\n\tLaunchConfig       SlotLaunchConfig `json:\"launch_config\"`\n\tLaunchBounds       SlotLaunchBounds `json:\"launch_bounds\"`\n\tReference          ReferenceSpec    `json:\"reference\"`\n\tShapes             []CaptureShape   `json:\"shapes\"`\n\tCurrentGeneration  int64            `json:\"current_generation\"`\n\tServingGeneration  int64            `json:\"serving_generation\"`\n\tSourceSHA256       string           `json:\"source_sha256\"`\n\tLaunchConfigSHA256 string           `json:\"launch_config_sha256\"`\n\tBaselineSource     string           `json:\"baseline_source,omitempty\"`\n\tCurrentSource      string           `json:\"current_source,omitempty\"`\n\tUpdatedAt          time.Time        `json:\"updated_at\"`\n}\n```\nSlotSpec is the canonical model-agnostic kernel slot descriptor for fast GPU hot-reload iteration.\n\n```go\nfunc (s SlotSpec) AgentView() SlotSpec\n```\nAgentView 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.\n\n```go\nfunc (s SlotSpec) DevShapes() []CaptureShape\n```\nDevShapes returns a copy of non-held-out capture shapes for fast iteration.\n\n```go\nfunc (s SlotSpec) HeldOutShapes() []CaptureShape\n```\nHeldOutShapes returns a copy of held-out capture shapes reserved for scorer parity.\n\n```go\ntype Status string\n```\nStatus is a bounded enum representing the outcome of a generation or audit receipt.\n\n```go\nconst (\n\tStatusPending      Status = \"pending\"\n\tStatusCompiling    Status = \"compiling\"\n\tStatusOK           Status = \"ok\"\n\tStatusCompileError Status = \"compile_error\"\n\tStatusParityFailed Status = \"parity_failed\"\n\tStatusReverted     Status = \"reverted\"\n\tStatusConflict     Status = \"conflict\"\n)\n```\n\n```go\ntype Store struct {\n\t// contains filtered or unexported fields\n}\n```\nStore coordinates registered kernel slots, monotonic generations, CAS edits, audit receipts, the live SSE EventBus, and append-only session notebooks.\n\n```go\nfunc NewStore(cfg StoreConfig) (*Store, error)\n```\nNewStore creates a Store, validating its PodTier and scanning WatchDir if configured.\n\n```go\nfunc (s *Store) AddFeedbackEntry(sessionID string, entry FeedbackEntry) error\n```\nAddFeedbackEntry sanitizes and appends a FeedbackEntry to the session's feedback.jsonl log.\n\n```go\nfunc (s *Store) AttachProfile(sessionID, attemptID, kind string, rawBytes []byte, summaryText string) (ProfileRef, error)\n```\nAttachProfile writes rawBytes content-addressed on disk under:\n\n  - \\\u003cstateDir\u003e/profiles/\\\u003csha\\[0:2]\u003e/\\\u003csha\u003e.pb.gz (for pprof kinds)\n  - \\\u003cstateDir\u003e/captures/\\\u003csha\u003e/capture.bin (for cudaprof kinds)\n\nand records only the {kind, sha256, bytes, path} reference in profiles.json plus summaryText in profile-summary.txt.\n\n```go\nfunc (s *Store) AttachQueryEvidence(sessionID, actor string, rec QueryRecord) error\n```\nAttachQueryEvidence 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/\\\u003cid\u003e/result.json).\n\n```go\nfunc (s *Store) AttemptBegin(sessionID, actor, hypothesisID, intent string, actsOn ...string) (string, error)\n```\nAttemptBegin 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.\n\n```go\nfunc (s *Store) AttemptEnd(sessionID, actor, attemptID, note string) error\n```\nAttemptEnd closes an open attempt without altering previously recorded attempt artifacts.\n\n```go\nfunc (s *Store) Bus() *EventBus\n```\nBus returns the Store's live SSE EventBus.\n\n```go\nfunc (s *Store) GetGeneration(id int64) (*GenerationRecord, bool)\n```\nGetGeneration returns a copy of the GenerationRecord for id.\n\n```go\nfunc (s *Store) GetSlot(name string) (*SlotInfo, bool)\n```\nGetSlot returns a snapshot of a single registered slot (by canonical name or source file alias).\n\n```go\nfunc (s *Store) HypothesisAdd(sessionID, actor, claim, prediction, falsifier string) (string, error)\n```\nHypothesisAdd appends a new falsifiable hypothesis (H1, H2, ...) to the session.\n\n```go\nfunc (s *Store) HypothesisUpdate(sessionID, actor, id string, status HypothesisStatus, evidence []string, note string) error\n```\nHypothesisUpdate appends a new revision to an existing hypothesis without mutating prior revisions.\n\n```go\nfunc (s *Store) ListGenerations(slot string, limit int) []GenerationRecord\n```\nListGenerations returns recent generations (optionally filtered by slot).\n\n```go\nfunc (s *Store) ListSlots() []SlotInfo\n```\nListSlots returns a sorted snapshot of all registered kernel slots.\n\n```go\nfunc (s *Store) PodTier() Tier\n```\nPodTier returns the immutable capability tier.\n\n```go\nfunc (s *Store) Receipts(limit int) []Receipt\n```\nReceipts returns up to limit most recent audit receipts.\n\n```go\nfunc (s *Store) RecordCompileResult(genID int64, ok bool, compilerLog, ptxDiff, sassDiff string, durationMS int64) (*GenerationRecord, error)\n```\nRecordCompileResult 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.\n\n```go\nfunc (s *Store) RecordParity(genID int64, parity ParityResult, durationMS int64) (*GenerationRecord, error)\n```\nRecordParity records correctness gate results for genID, appends a receipt, and emits parity.\n\n```go\nfunc (s *Store) RecordPatched(genID int64, durationMS int64) (*GenerationRecord, error)\n```\nRecordPatched marks genID as actively serving on its slot, appends a receipt, and emits patched.\n\n```go\nfunc (s *Store) RecordProfile(genID int64, profile ProfileResult, durationMS int64) (*GenerationRecord, error)\n```\nRecordProfile records performance metrics for genID, computing diff\\_prev\\_ms against the previous profiled generation on the same slot if not already supplied.\n\n```go\nfunc (s *Store) RegisterSlot(name, path, source string) (*SlotInfo, error)\n```\nRegisterSlot registers a kernel slot with its baseline source and locked CUDA signatures.\n\n```go\nfunc (s *Store) Revert(ctx context.Context, req RevertRequest) (*GenerationRecord, error)\n```\nRevert 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.\n\n```go\nfunc (s *Store) RunID() string\n```\nRunID returns the immutable run\\_id for this Store.\n\n```go\nfunc (s *Store) ScanWatchDir() error\n```\nScanWatchDir registers any .cu and .cuh files found directly inside WatchDir, automatically allowlisting sibling .cuh headers for kernel #include validation.\n\n```go\nfunc (s *Store) SendAdviseFeedback(sessionID, actor, findingID string, kind FeedbackKind, note, evidence, receiptID string) error\n```\nSendAdviseFeedback records explicit advise feedback (correction, suggestion, or confusing) linked to findingID in feedback.jsonl. Corrections require non-empty evidence.\n\n```go\nfunc (s *Store) SendFeedback(sessionID, actor, summary, suggestion, receiptID string) error\n```\nSendFeedback appends a feedback entry to the session's feedback.jsonl log.\n\n```go\nfunc (s *Store) SessionConclude(sessionID, actor, summary string) error\n```\nSessionConclude writes the conclusion markdown for a session.\n\n```go\nfunc (s *Store) SessionExportTxtar(sessionID string) (string, []byte, error)\n```\nSessionExportTxtar renders the session notebook as a clean txtar archive, writes it to \\\u003cstateDir\u003e/sessions/\\\u003csessionID\u003e.txtar when stateDir is configured, and returns (path, bytes, nil).\n\n```go\nfunc (s *Store) SessionList() []SessionSummary\n```\nSessionList returns observe-tier summaries of all sessions in creation order.\n\n```go\nfunc (s *Store) SessionRead(sessionID string) (*SessionSnapshot, bool)\n```\nSessionRead returns an observe-tier snapshot of a session notebook.\n\n```go\nfunc (s *Store) SessionStart(actor, goal string, baseMeta SessionBase, tier Tier) (string, error)\n```\nSessionStart begins a new append-only session txtar notebook and emits a session\\_event.\n\n```go\nfunc (s *Store) SetAttemptActsOn(sessionID, actor, attemptID string, actsOn ...string) error\n```\nSetAttemptActsOn 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.\n\n```go\nfunc (s *Store) StatusSnapshot() StoreStatus\n```\nStatusSnapshot returns an observe-tier overview of the Store.\n\n```go\nfunc (s *Store) SubmitEdit(ctx context.Context, req SubmitRequest) (*GenerationRecord, error)\n```\nSubmitEdit 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.\n\n```go\nfunc (s *Store) TryRaiseTier(target Tier) error\n```\nTryRaiseTier always fails per Layer 4.\n\n```go\ntype StoreConfig struct {\n\tRunID           string\n\tWatchDir        string\n\tStateDir        string\n\tPodTier         Tier\n\tAllowedIncludes []string\n\tMaxSourceBytes  int\n\tMaxLogBytes     int\n\tTokens          *TokenStore\n\tEventBufferSize int\n}\n```\nStoreConfig configures a devloop Store.\n\n```go\ntype StoreStatus struct {\n\tRunID            string      `json:\"run_id\"`\n\tPodTier          Tier        `json:\"pod_tier\"`\n\tLatestGeneration int64       `json:\"latest_generation\"`\n\tSlotCount        int         `json:\"slot_count\"`\n\tReceiptCount     int         `json:\"receipt_count\"`\n\tActiveAgents     []AgentInfo `json:\"active_agents\"`\n}\n```\nStoreStatus is a read-only overview of the Store for observe-tier endpoints.\n\n```go\ntype SubmitRequest struct {\n\tSlot               string    `json:\"slot\"`\n\tSource             string    `json:\"source\"`\n\tExpectedGeneration int64     `json:\"expected_generation,omitempty\"`\n\tActor              string    `json:\"actor\"`\n\tTransport          Transport `json:\"transport\"`\n\tFlags              []string  `json:\"flags,omitempty\"`\n\tIntent             string    `json:\"intent,omitempty\"`\n}\n```\nSubmitRequest requests a compare-and-swap kernel edit on a registered slot.\n\n```go\ntype Tier string\n```\nTier represents a Layer 4 capability tier fixed at process/runtime creation.\n\n```go\nconst (\n\tTierObserve Tier = \"observe\"\n\tTierKernel  Tier = \"kernel\"\n\tTierConfig  Tier = \"config\"\n\tTierCode    Tier = \"code\"\n\n\t// DefaultTier is the default capability tier per Layer 4.\n\tDefaultTier Tier = TierKernel\n)\n```\n\n```go\nfunc EffectiveTier(podTier Tier, transport Transport) Tier\n```\nEffectiveTier computes min(podTier, transport.Ceiling()) per Layer 2. If either input is invalid, it fails closed by returning an empty Tier (rank 0).\n\n```go\nfunc MinTier(a, b Tier) Tier\n```\nMinTier returns the lower of two valid tiers. If either is invalid, returns \"\".\n\n```go\nfunc ParseTier(raw string) (Tier, error)\n```\nParseTier parses a tier string, rejecting unknown values.\n\n```go\nfunc (t Tier) Rank() int\n```\nRank returns the ordering rank of a tier (observe \\\u003c kernel \\\u003c config \\\u003c code), or 0 if invalid.\n\n```go\nfunc (t Tier) Valid() bool\n```\nValid reports whether t is a known capability tier.\n\n```go\ntype TierPolicy struct {\n\t// contains filtered or unexported fields\n}\n```\nTierPolicy holds an immutable capability tier fixed at construction. There is intentionally no API to raise the tier.\n\n```go\nfunc NewTierPolicy(podTier Tier) (*TierPolicy, error)\n```\nNewTierPolicy constructs a TierPolicy fixed to podTier (defaults to DefaultTier when empty).\n\n```go\nfunc (p *TierPolicy) Tier() Tier\n```\nTier returns the immutable capability tier.\n\n```go\nfunc (p *TierPolicy) TryRaiseTier(target Tier) error\n```\nTryRaiseTier always fails: capability tiers are fixed at startup and cannot be raised via any API.\n\n```go\ntype TokenStore struct {\n\t// contains filtered or unexported fields\n}\n```\nTokenStore 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.\n\n```go\nfunc LoadTokenStore(path string) (*TokenStore, error)\n```\nLoadTokenStore loads an existing bearer token from a file on disk.\n\n```go\nfunc NewTokenStore(path string) (*TokenStore, error)\n```\nNewTokenStore 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.\n\n```go\nfunc (ts *TokenStore) GoString() string\n```\nGoString prevents accidental %#v logging of token contents.\n\n```go\nfunc (ts *TokenStore) MintSessionCookie(actor string, ttl time.Duration) *http.Cookie\n```\nMintSessionCookie creates an HttpOnly, SameSite=Strict HMAC-signed session cookie bound to actor and expiring after ttl (defaults to 8 hours if ttl \\\u003c= 0).\n\n```go\nfunc (ts *TokenStore) Path() string\n```\nPath returns the filesystem path of the token file (empty if in-memory).\n\n```go\nfunc (ts *TokenStore) Redact(s string) string\n```\nRedact replaces the token value inside s with \\[REDACTED].\n\n```go\nfunc (ts *TokenStore) String() string\n```\nString prevents accidental logging of token contents.\n\n```go\nfunc (ts *TokenStore) ValidateSessionCookie(r *http.Request) (string, bool)\n```\nValidateSessionCookie validates the HMAC session cookie on r and returns the authenticated actor.\n\n```go\nfunc (ts *TokenStore) ValidateToken(candidate string) bool\n```\nValidateToken compares candidate against the stored bearer token in constant time.\n\n```go\ntype Transport string\n```\nTransport represents a Layer 2 listener transport with an associated tier ceiling.\n\n```go\nconst (\n\tTransportLoopback Transport = \"loopback\"\n\tTransportTailnet  Transport = \"tailnet\"\n\tTransportBrowser  Transport = \"browser\"\n)\n```\n\n```go\nfunc ParseTransport(raw string) (Transport, error)\n```\nParseTransport parses a transport string, rejecting unknown values.\n\n```go\nfunc (tr Transport) Ceiling() Tier\n```\nCeiling returns the highest capability tier permitted on this transport per Layer 2.\n\n```go\nfunc (tr Transport) Valid() bool\n```\nValid reports whether tr is a known transport.\n\n```go\ntype TxtarFile struct {\n\tName string\n\tData []byte\n}\n```\nTxtarFile is a single named entry inside a txtar archive.\n\n```go\nfunc ParseTxtar(data []byte) ([]TxtarFile, error)\n```\nParseTxtar parses a \\`-- name --\\` txtar archive into ordered TxtarFile entries, validating every entry path with ValidateSafeRelPath and unescaping marker lines escaped by FormatTxtar.\n\n","path":"github.com/tmc/lib/nvidia/x/host/devloop","name":"devloop","synopsis":"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.","isRedistributable":true}
