Documentation
¶
Overview ¶
Package largebody defines the internal provider-neutral DTO contracts for the large-payload streaming fast path (#503, work order #532).
The package carries bounded facts only: replay source handles, raw spans, body/rewrite contracts, protocol proof, session/recorder inputs, canonical semantic identity, assessment and wire facts, rewrite plans, execution results, and the sensitive session-response carrier.
Design references (design.md): section 4 (static pre-capture disposition), section 6 (protocol proof and canonical semantic identity), section 7 (generation-frozen authority classification and WireEligibilitySummary), section 8 (side-effect-free assessment), section 9 (backend wire contract), section 10 (secure session and sensitive carrier), section 11 (post-commit runtime facts, no shadow Call), section 13 (ExecutionResult and frontend bridge). Eligibility compilation (section 7) is composition-time only: CompileWireEligibilitySummary is a pure function of frozen generation facts, and the published summary carries fixed bitsets/enums plus a bounded generation binding (Requirements 5, 6, 22).
Hard constraints (Task 2.2, Requirements 4, 5, 6, 7, 8, 9, 14, 16, 18, 22): no provider SDK or frontend-specific types (only stdlib plus pkg/lipapi), no raw arbitrary header bags, no prompt text, no temp/spool paths, no unbounded maps, and no DTO mirroring lipapi.Call.
Boundedness: every Validate method takes the configured semantic-fact budget (server.large_payload_fast_path.max_semantic_fact_bytes) and rejects oversize strings and over-count slices.
This package holds zero behavior-change plumbing only: types plus pure validation. No logic consumes these DTOs yet (later tasks).
Index ¶
- Constants
- Variables
- func AssessAuthorityGate(summary WireEligibilitySummary, census DependencyCensus, expectedGenID string) (AssessmentDecision, DeclineReason)
- func CheckedSpliceLength(prefixLen, replacementLen, suffixLen int64) (int64, error)
- func ClassifySummaryBlocker(summary WireEligibilitySummary) string
- func ContextWithWireProof(ctx context.Context, proof Proof, explicitRequestID string) context.Context
- func EncodeModelToken(model string) ([]byte, error)
- func IsSemanticFactBudgetExceeded(err error) bool
- func IsSpoolBudgetExhausted(err error) bool
- func ResolveStaticDeclineReason(summary WireEligibilitySummary, reason StaticWireReason) string
- func ResolveStaticDisposition(summary WireEligibilitySummary, in StaticDispositionInput) (StaticWireDisposition, StaticWireReason)
- func SemanticFactBudget(ctx context.Context) int64
- func SetUseWholeMessageMarshalForTest(v bool)
- func SizeBucket(sizeBytes int64) string
- func SpliceModelTokenBytes(source []byte, span Span, replacement string) ([]byte, error)
- func StaticDisposition(summary WireEligibilitySummary, in StaticDispositionInput) (StaticWireDisposition, StaticWireReason)
- func ValidateAssessmentStamp(stamp AssessmentStamp, live LiveExecutionFacts) error
- func ValidateExecuteLargeBody(accepted Assessment, src Source, live LiveExecutionFacts) error
- func ValidateModelSpan(sourceSize int64, span Span) error
- func ValidateModelSpans(sourceSize int64, spans ...Span) error
- func WireEligibilityPlaneID(index int) (string, bool)
- func WireEligibilityPlaneIndex(id string) (int, bool)
- func WithSemanticFactBudget(ctx context.Context, budget int64) context.Context
- func WithWireClientTurnShape(ctx context.Context, shape ClientTurnShape) context.Context
- func WithWireIdentity(ctx context.Context, requestID, traceID string) context.Context
- func WithWireSessionInput(ctx context.Context, in SessionInput) context.Context
- type Assessment
- type AssessmentDecision
- type AssessmentRequest
- type AssessmentStamp
- func (s AssessmentStamp) BodyBytes() int64
- func (s AssessmentStamp) BodyMode() BodyMode
- func (s AssessmentStamp) CandidateDomainGeneration() string
- func (s AssessmentStamp) CompactionDigest() [32]byte
- func (s AssessmentStamp) GenerationID() string
- func (s AssessmentStamp) IdentityDigest() IdentityDigest
- func (s AssessmentStamp) IsZero() bool
- func (s AssessmentStamp) ProfileID() string
- func (s AssessmentStamp) RequiredCapabilities() []lipapi.Capability
- func (s AssessmentStamp) RequiredCapabilitiesDigest() [32]byte
- func (s AssessmentStamp) Revalidate(live LiveExecutionFacts) error
- func (s AssessmentStamp) Rewrite() RewriteSemantics
- func (s AssessmentStamp) SourceDigest() SourceDigest
- func (s AssessmentStamp) Validate(maxFactBytes int64) error
- type AuthorityAssessmentGate
- type AuthorityAssessor
- type BackendWireProofAssessor
- func (a *BackendWireProofAssessor) AssessLargeBody(ctx context.Context, proof Proof) (Assessment, error)
- func (a *BackendWireProofAssessor) ComposeOverrideCandidate(ctx context.Context, overrideSelector string, acceptedDomain WireDomainFacts) ([]routing.AttemptCandidate, bool, DeclineReason)
- func (a *BackendWireProofAssessor) ExecuteLargeBody(ctx context.Context, accepted Assessment, src Source) (ExecutionResult, error)
- func (a *BackendWireProofAssessor) VerifyOverrideCandidate(ctx context.Context, acceptedDomain WireDomainFacts, ...) (bool, DeclineReason)
- type BackendWireProofGate
- func (g *BackendWireProofGate) ComposeOverrideCandidate(ctx context.Context, overrideSelector string, acceptedDomain WireDomainFacts) ([]routing.AttemptCandidate, bool, DeclineReason)
- func (g *BackendWireProofGate) Evaluate(ctx context.Context, proof Proof) (AssessmentDecision, DeclineReason, WireRequestFacts, WireDomainFacts, ...)
- func (g *BackendWireProofGate) LegalDomainBackends() []string
- func (g *BackendWireProofGate) VerifyOverrideCandidate(ctx context.Context, acceptedDomain WireDomainFacts, ...) (bool, DeclineReason)
- type BodyMode
- type BoundedRouteDomainAuthority
- type BoundedRouteDomainContract
- type CallIdentityConfig
- type CallIdentityWriter
- func (w *CallIdentityWriter) AddItem(item lipapi.Item) error
- func (w *CallIdentityWriter) AddMessage(msg lipapi.Message) error
- func (w *CallIdentityWriter) BeginMessage(role lipapi.Role) (*MessageIdentityWriter, error)
- func (w *CallIdentityWriter) BeginMessageItem(id string, status lipapi.ItemStatus, role lipapi.Role, ...) (*ItemIdentityWriter, error)
- func (w *CallIdentityWriter) Digest() (IdentityDigest, error)
- func (w *CallIdentityWriter) SetClientModel(model string, extKeys ...string) error
- func (w *CallIdentityWriter) SetRouteSelector(sel string) error
- func (w *CallIdentityWriter) StartItems() error
- func (w *CallIdentityWriter) StartMessages() error
- func (w *CallIdentityWriter) WriteCall(call *lipapi.Call) (IdentityDigest, error)
- type CaptureConfig
- type CaptureOutcome
- type CaptureReader
- type CaptureReaderConfig
- type CaptureResult
- type ClientTurnItemShape
- type ClientTurnPartShape
- type ClientTurnShape
- func ClientTurnShapeFromCall(call *lipapi.Call, maxFactBytes int64) (ClientTurnShape, error)
- func ClientTurnShapeFromItems(items []lipapi.Item, maxFactBytes int64) (ClientTurnShape, error)
- func ClientTurnShapeFromMessages(msgs []lipapi.Message, maxFactBytes int64) (ClientTurnShape, error)
- func WireClientTurnShapeFromContext(ctx context.Context) (ClientTurnShape, bool)
- type CompletedSource
- func (s *CompletedSource) ActiveReaders() int
- func (s *CompletedSource) Close() error
- func (s *CompletedSource) Digest() SourceDigest
- func (s *CompletedSource) FilePath() string
- func (s *CompletedSource) HasSpilled() bool
- func (s *CompletedSource) IsClosed() bool
- func (s *CompletedSource) IsDeletePending() bool
- func (s *CompletedSource) MemoryBytes() []byte
- func (s *CompletedSource) Open() (io.ReadCloser, error)
- func (s *CompletedSource) Size() int64
- func (s *CompletedSource) SourceDigest() SourceDigest
- func (s *CompletedSource) String() string
- type CompletedSourceConfig
- type ConservativeDependencyAssessmentGate
- type ControlRequirements
- type DeclineReason
- type DependencyCensus
- type DependencyClass
- type DiagnosticsObserver
- type ExactTokenizerDeclarer
- type ExactTokenizerSemantics
- type ExecutionResult
- type HookChain
- type HookEligibilityInput
- type IdentityDigest
- type InitialRouteAssessmentGate
- func (g *InitialRouteAssessmentGate) Evaluate(ctx context.Context, proof Proof) (AssessmentDecision, DeclineReason, []routing.AttemptCandidate)
- func (g *InitialRouteAssessmentGate) EvaluateRouteFacts(ctx context.Context, route WireRouteFacts, protocol WireProtocolFacts, ...) (AssessmentDecision, DeclineReason, []routing.AttemptCandidate)
- func (g *InitialRouteAssessmentGate) EvaluateTurnFacts(ctx context.Context, facts WireTurnFacts) (AssessmentDecision, DeclineReason, []routing.AttemptCandidate)
- func (g *InitialRouteAssessmentGate) ProveCandidateSet(ctx context.Context, proof Proof, expected []routing.AttemptCandidate) (AssessmentDecision, DeclineReason)
- type InitialRouteAssessor
- type ItemIdentityWriter
- type LargeBodyAssessor
- type LargeBodyExecutor
- type LargeBodyStaticDispositionProvider
- type LargeBodyWireExecutor
- type LateSelectorAssessmentGate
- type LateSelectorAssessor
- type LiveExecutionFacts
- type MessageIdentityWriter
- type NarrowPortEligibilityInput
- type NoopDiagnosticsObserver
- func (NoopDiagnosticsObserver) OnActiveSpoolBytes(uint64, int64)
- func (NoopDiagnosticsObserver) OnCapture(string, StorageKind)
- func (NoopDiagnosticsObserver) OnDecline(string)
- func (NoopDiagnosticsObserver) OnPipelineStage(PipelineStage)
- func (NoopDiagnosticsObserver) OnReplay()
- func (NoopDiagnosticsObserver) OnRewrite()
- func (NoopDiagnosticsObserver) OnStageDuration(string, time.Duration)
- type PipelineStage
- type PlaneAccess
- type PlaneEligibilityInput
- type PortDependency
- type Proof
- type ProtocolFacts
- type ReplayChunkReaderConfig
- type ReplayChunkReaderResult
- type ResponseFacts
- type RewriteKind
- type RewritePlan
- type RewriteSemantics
- type RouteHintAuthority
- type RouteOverrideAssessmentGate
- type RouteOverrideAssessor
- type SafeDiagnosticsObserver
- func (s *SafeDiagnosticsObserver) OnActiveSpoolBytes(seq uint64, bytes int64)
- func (s *SafeDiagnosticsObserver) OnCapture(sizeBucket string, storage StorageKind)
- func (s *SafeDiagnosticsObserver) OnDecline(reason string)
- func (s *SafeDiagnosticsObserver) OnPipelineStage(stage PipelineStage)
- func (s *SafeDiagnosticsObserver) OnReplay()
- func (s *SafeDiagnosticsObserver) OnRewrite()
- func (s *SafeDiagnosticsObserver) OnStageDuration(stage string, d time.Duration)
- type ScanningWireCounter
- type SelectorMutatorAuthority
- type SensitiveString
- func (s SensitiveString) ByteLen() int
- func (s SensitiveString) Format(f fmt.State, _ rune)
- func (s SensitiveString) GoString() string
- func (s SensitiveString) IsZero() bool
- func (s SensitiveString) MarshalJSON() ([]byte, error)
- func (s SensitiveString) MarshalText() ([]byte, error)
- func (s SensitiveString) Reveal() string
- func (s SensitiveString) String() string
- type SessionInput
- func (s SessionInput) CorrelationID() string
- func (s SessionInput) Format(f fmt.State, _ rune)
- func (s SessionInput) GoString() string
- func (s SessionInput) LogValue() slog.Value
- func (s SessionInput) MarshalJSON() ([]byte, error)
- func (s SessionInput) ProvesFreshALeg() bool
- func (s SessionInput) SessionRef() lipapi.SessionRef
- func (s SessionInput) String() string
- func (s SessionInput) Validate(maxFactBytes int64) error
- type SessionInputSource
- type SessionResponseCarrier
- type Source
- type SourceDigest
- type Span
- type SpillBuffer
- func (b *SpillBuffer) ActiveReaders() int
- func (b *SpillBuffer) BytesWritten() int64
- func (b *SpillBuffer) Close() error
- func (b *SpillBuffer) Complete() (*CompletedSource, error)
- func (b *SpillBuffer) DetachReservation() *SpoolReservation
- func (b *SpillBuffer) Digest() SourceDigest
- func (b *SpillBuffer) FileBytes() int64
- func (b *SpillBuffer) FilePath() string
- func (b *SpillBuffer) GoString() string
- func (b *SpillBuffer) HasSpilled() bool
- func (b *SpillBuffer) HasUnwrittenSuffix() bool
- func (b *SpillBuffer) IsCompleted() bool
- func (b *SpillBuffer) IsDeletePending() bool
- func (b *SpillBuffer) MemoryBytes() []byte
- func (b *SpillBuffer) Open() (io.ReadCloser, error)
- func (b *SpillBuffer) ReadFrom(r io.Reader) (int64, error)
- func (b *SpillBuffer) Reservation() *SpoolReservation
- func (b *SpillBuffer) ShrinkReservation() error
- func (b *SpillBuffer) Size() int64
- func (b *SpillBuffer) SourceDigest() SourceDigest
- func (b *SpillBuffer) String() string
- func (b *SpillBuffer) TakeUnwrittenSuffix() []byte
- func (b *SpillBuffer) UnwrittenSuffix() []byte
- func (b *SpillBuffer) Write(p []byte) (int, error)
- type SpillConfig
- type SpillFile
- type SpliceReader
- func SpliceModelToken(source any, span Span, replacement string) (*SpliceReader, error)
- func SpliceModelTokenAt(r io.ReaderAt, sourceSize int64, span Span, replacement string) (*SpliceReader, error)
- func SpliceModelTokenPlan(source any, plan RewritePlan, maxFactBytes int64) (*SpliceReader, error)
- func SpliceModelTokenReader(r io.Reader, sourceSize int64, span Span, replacement string) (*SpliceReader, error)
- func (s *SpliceReader) Close() error
- func (s *SpliceReader) Read(p []byte) (int, error)
- func (s *SpliceReader) ReplacementBytes() []byte
- func (s *SpliceReader) ReplacementToken() string
- func (s *SpliceReader) RewrittenLength() int64
- func (s *SpliceReader) SourceSize() int64
- func (s *SpliceReader) Span() Span
- func (s *SpliceReader) WriteTo(w io.Writer) (int64, error)
- type SpoolBudgetConfig
- type SpoolLedger
- func (l *SpoolLedger) ActiveReservations() int64
- func (l *SpoolLedger) AvailableBytes() int64
- func (l *SpoolLedger) BeginReservation() (*SpoolReservation, error)
- func (l *SpoolLedger) InflightBytes() int64
- func (l *SpoolLedger) MaxInflightSpoolBytes() int64
- func (l *SpoolLedger) MemorySpoolBytes() int64
- func (l *SpoolLedger) Reserve(knownBytes int64) (*SpoolReservation, error)
- func (l *SpoolLedger) SetObserver(obs SpoolObserver)
- type SpoolObserver
- type SpoolReservation
- func (r *SpoolReservation) MemoryBytes() int64
- func (r *SpoolReservation) MemorySpoolBytes() int64
- func (r *SpoolReservation) Release() int64
- func (r *SpoolReservation) ReserveMore(additionalBytes int64) error
- func (r *SpoolReservation) ReservedBytes() int64
- func (r *SpoolReservation) ShrinkTo(finalBytes int64) error
- func (r *SpoolReservation) SpillBytes() int64
- type StampInvariantError
- type StampValidatingExecutor
- type StaticDispositionInput
- type StaticWireDisposition
- type StaticWireReason
- type StorageKind
- type StreamingEscapeWriter
- type StreamingProofConfig
- type StreamingProofResult
- type TrimSpaceWriter
- type WireBackend
- type WireBackendMap
- type WireBackendProvider
- type WireBackendResolver
- type WireBackendResolverFunc
- type WireCompactionMeta
- type WireContinuationLineage
- type WireConversationObserverFacts
- type WireCountInput
- type WireCountResult
- type WireCounter
- type WireCounterProvider
- type WireDependencyFacts
- type WireDomainFacts
- type WireDomainSupport
- type WireEconomicFacts
- type WireEligibilityInput
- type WireEligibilitySummary
- func (s WireEligibilitySummary) GenerationID() string
- func (s WireEligibilitySummary) HasStaticBlocker() bool
- func (s WireEligibilitySummary) HookBlockers() HookChain
- func (s WireEligibilitySummary) HookOccupancy() HookChain
- func (s WireEligibilitySummary) PinnedTo(generationID string) bool
- func (s WireEligibilitySummary) PlaneBlockers() uint32
- func (s WireEligibilitySummary) PortBlockers() WirePortBlocker
- func (s WireEligibilitySummary) Sealed() bool
- func (s WireEligibilitySummary) StaticDisposition(in StaticDispositionInput) (StaticWireDisposition, StaticWireReason)
- func (s WireEligibilitySummary) String() string
- func (s WireEligibilitySummary) Validate(maxFactBytes int64) error
- type WireIdentity
- type WireIdentityFacts
- type WireInterleavedStateFacts
- type WireMaxOutputFacts
- type WireOpenRequest
- type WireOpener
- type WireOpenerProvider
- type WirePortBlocker
- type WireProtocolFacts
- type WireReceiveView
- type WireRequestFacts
- type WireRequestSupport
- type WireRewriteFacts
- type WireRouteFacts
- type WireSessionFacts
- type WireSourceFacts
- type WireSupportReason
- type WireTerminalFacts
- type WireTokenCountGateInput
- type WireTokenCountGateResult
- type WireTurnFacts
- func (f WireTurnFacts) AssertConsumerCoverage() error
- func (f WireTurnFacts) AssertNoShadowCall() error
- func (f WireTurnFacts) AuditNamedConsumers() map[string]string
- func (f WireTurnFacts) ToCompactionMeta(blegID string, attemptSeq int, transactionID, ruleID string) WireCompactionMeta
- func (f WireTurnFacts) ToContinuationLineage() WireContinuationLineage
- func (f WireTurnFacts) ToConversationObserverFacts(stage, revision string, ruleCount int) WireConversationObserverFacts
- func (f WireTurnFacts) ToDependencyFacts() WireDependencyFacts
- func (f WireTurnFacts) ToReceiveView() WireReceiveView
- func (f WireTurnFacts) ToResponseFacts(effectiveModel string) ResponseFacts
- func (f WireTurnFacts) ToSessionResponseCarrier() SessionResponseCarrier
- func (f WireTurnFacts) ToTerminalFacts() WireTerminalFacts
- func (f WireTurnFacts) ToWireDomainFacts(universal bool, candidateModels ...string) WireDomainFacts
- func (f WireTurnFacts) ToWireRequestFacts(candidateModel string) WireRequestFacts
- func (f WireTurnFacts) Validate(maxFactBytes int64) error
Constants ¶
const ( DeclineReasonLocalTurn = "local_turn" DeclineReasonSecretGuard = "secret_guard" DeclineReasonTerminalDecision = "terminal_decision" DeclineReasonFrontendRouteResolver = "frontend_route_resolver" DeclineReasonTraffic = "traffic" DeclineReasonAccountingCounting = "accounting_counting" DeclineReasonCustomCallCallback = "custom_call_callback" DeclineReasonBackendDomain = "backend_domain" DeclineReasonFeatureDisabled = "feature_disabled" DeclineReasonBelowThreshold = "below_threshold" DeclineReasonGzipCompressed = "gzip_compressed" DeclineReasonStaticBlocker = "static_blocker" DeclineReasonSpoolBudgetExhausted = "spool_budget_exhausted" DeclineReasonLimitExceeded = "limit_exceeded" DeclineReasonReadError = "read_error" )
Static decline reasons (bounded taxonomy per Task 19.1 and Requirements 20, 22).
const ( DefinitelyCanonical = StaticWireDefinitelyCanonical NeedsRequestAssessment = StaticWireNeedsRequestAssessment )
Vocabulary aliases matching design section 4 and task requirements:
const ( // DefaultCopyBufferSize is the fixed size of the reusable copy buffer (32 KiB) // used for streaming I/O. It bounds copy-buffer heap allocation (Requirement 20.1). DefaultCopyBufferSize = 32 * 1024 // DefaultMemorySpoolBytes is the default per-capture in-memory ceiling (64 KiB) // before spilling excess request bytes to disk (Requirement 20.1). DefaultMemorySpoolBytes int64 = 64 * 1024 )
const ( // DefaultMaxWireScanBytes bounds the replay size evaluated by a wire token counter // under the held decode permit (5 MiB). Replays exceeding this bound decline to // canonical processing to avoid unbounded permit-hold latency. DefaultMaxWireScanBytes int64 = 5 * 1024 * 1024 // DefaultMaxPermitHoldCPU bounds the wall-clock CPU duration a wire token counter // is permitted to hold before declining to canonical processing. DefaultMaxPermitHoldCPU time.Duration = 250 * time.Millisecond )
Default ceilings for permit-hold CPU bounding (Requirements 6.8, 15.5, 21.4; Task 10.4).
const DefaultMaxSemanticFactBytes int64 = 256 * 1024
DefaultMaxSemanticFactBytes is the default ceiling on profile-derived and wire-resolution semantic facts (256 KiB; Requirement 4, design section 3).
const DefaultMaxTrailingWhitespaceBytes = 64 * 1024
DefaultMaxTrailingWhitespaceBytes is the maximum buffer size for pending trailing whitespace in TrimSpaceWriter to preserve bounded memory (Requirement 19.3 O(facts+buffers) invariant).
const DefaultThresholdBytes int64 = 1 << 20
DefaultThresholdBytes is the fallback decoded-size gate (1 MiB) when StaticDispositionInput.ThresholdBytes is not configured (> 0).
const DefaultWireMaxAttempts = 3
DefaultWireMaxAttempts is the pre-route retry-budget default carried in WireRouteFacts when route-plan assembly has not yet supplied a budget. Route-plan assembly owns the authoritative retry budget; this constant only seeds pre-route facts so the inventory stays complete without a Call.
const (
// WireEligibilityPlaneCount is the closed V1 plane census (Task 1.9).
WireEligibilityPlaneCount = 28
)
Variables ¶
var ( CapabilitiesDigest = capabilityfacts.CapabilitiesDigest DeriveRequiredCapabilities = capabilityfacts.DeriveRequiredCapabilities )
var ( // ErrSpillClosed is returned when attempting an operation on a closed SpillBuffer. ErrSpillClosed = errors.New("largebody: spill buffer is closed") // ErrSpillFileCreationFailed is returned when creating a temporary spill file fails. ErrSpillFileCreationFailed = errors.New("largebody: failed to create spill file") // ErrSpillWriteFailed is returned when writing to the spill file fails. ErrSpillWriteFailed = errors.New("largebody: spill file write failed") // ErrInvalidSpillConfig is returned when a SpillConfig parameter violates bounds. ErrInvalidSpillConfig = errors.New("largebody: invalid spill configuration") )
var ( // ErrCountCallOnly is returned when the counter only supports CountCall and lacks wire counting. ErrCountCallOnly = errors.New("largebody: counter does not support wire replay counting (CountCall only)") // ErrInexactTokenizerSemantics is returned when exact tokenizer semantics are not declared. ErrInexactTokenizerSemantics = errors.New("largebody: exact tokenizer semantics not declared") // ErrUnboundedReplayScan is returned when replay source size exceeds the wire scan budget. ErrUnboundedReplayScan = errors.New("largebody: replay source size exceeds wire count budget") // ErrPermitHoldCPUExceeded is returned when wire counting times out or exceeds CPU budget. ErrPermitHoldCPUExceeded = errors.New("largebody: wire counting timed out or exceeded permit-hold CPU budget") )
var ErrAlreadyCompleted = errors.New("largebody: spill buffer is already completed")
ErrAlreadyCompleted is returned when attempting to complete or write to an already completed SpillBuffer.
var ErrBodySessionMetadataRejected = errors.New("largebody: body-carried LIP session metadata rejected by profile")
ErrBodySessionMetadataRejected indicates that the profile rejected body-carried LIP session metadata (Requirement 14.2, Requirement 17.5).
var ErrInvalidReservation = errors.New("largebody: invalid spool reservation parameter")
ErrInvalidReservation is returned when a reservation parameter violates bounds or checked int64 arithmetic, such as negative byte counts or overflow.
var ErrNilRemainingBody = errors.New("largebody: remaining body reader must not be nil")
ErrNilRemainingBody is returned when constructing a CaptureReader without a remaining body.
var ErrReservationClosed = errors.New("largebody: spool reservation already released")
ErrReservationClosed is returned when attempting to mutate or grow a spool reservation that has already been released.
var ErrSemanticFactBudgetExceeded = capabilityfacts.ErrSemanticFactBudgetExceeded
ErrSemanticFactBudgetExceeded indicates that normalized item/part metadata or fact attributes exceeded the configured semantic-fact budget, requiring pre-commit fallback to canonical processing (Requirement 14.4).
var ErrSourceClosed = errors.New("largebody: source is closed")
ErrSourceClosed is returned when attempting an operation on a closed CompletedSource.
var ErrSpliceClosed = errors.New("largebody: splice reader is closed")
ErrSpliceClosed is returned when attempting an operation on a closed SpliceReader.
var ErrSpoolBudgetExhausted = errors.New("largebody: spool budget exhausted (optimization decline)")
ErrSpoolBudgetExhausted is returned when a logical spool reservation cannot be granted or grown because the global in-flight spool budget (max_inflight_spool_bytes) has been reached or the requested byte count exceeds available capacity.
Per Requirement 1.5 and Requirement 20.5 (design section 5), budget exhaustion is an optimization decline, NOT a client error (do NOT map to 413 Request Entity Too Large). The request must decline to canonical processing.
var ErrStampDisagreement = errors.New("largebody: assessment stamp disagreement (invariant failure)")
ErrStampDisagreement is returned when live execution facts disagree with the bound AssessmentStamp (Requirements 6.6, 6.7, 8.5; Task 11.8). This is an internal invariant failure, never a fallback to canonical.
var ErrUnconsumedSuffix = errors.New("largebody: unwritten suffix must be consumed via TakeUnwrittenSuffix before new writes")
ErrUnconsumedSuffix is returned when attempting to Write to a SpillBuffer that still holds an unwritten suffix from a previous failed or partial write. Callers must consume the suffix via TakeUnwrittenSuffix() before retrying new writes (Task 4.2 review suggestion; Requirement 20.6).
Functions ¶
func AssessAuthorityGate ¶
func AssessAuthorityGate(summary WireEligibilitySummary, census DependencyCensus, expectedGenID string) (AssessmentDecision, DeclineReason)
AssessAuthorityGate evaluates authority eligibility directly from summary, census, and expected generation ID.
func CheckedSpliceLength ¶
CheckedSpliceLength returns prefixLen+replacementLen+suffixLen using checked int64 math before provider open (Requirement 9.4).
func ClassifySummaryBlocker ¶
func ClassifySummaryBlocker(summary WireEligibilitySummary) string
ClassifySummaryBlocker maps a WireEligibilitySummary with static blockers to a specific static decline reason.
func ContextWithWireProof ¶
func ContextWithWireProof(ctx context.Context, proof Proof, explicitRequestID string) context.Context
ContextWithWireProof enriches ctx with assessed proof Session, Turn, and canonical Request/Trace IDs in one pass so all frontend lanes cannot forget part of the handoff. RequestID derives from proof.Identity.CallID(explicitRequestID) matching diag.StableCallID (explicit ID or "call_"+token); TraceID equals RequestID under the canonical single-identity contract. Overwrites any prior Wire* values so a stale or conflicting caller ctx cannot replace assessed proof. No Call materialization, no payload decode, no new IDs: only already-derived bounded proof facts are carried. SessionInput strings are immutable; TurnShape shallow copy shares bounded read-only slices consumed without mutation by PrepareSecureSession/RecordClientTurnWithShape.
func EncodeModelToken ¶
EncodeModelToken validates and encodes a model name into a complete JSON string token with standard JSON escaping (Requirement 9.2).
If model is already a complete, valid quoted JSON string token (e.g. from pre-encoding), it is returned directly to prevent redundant double-encoding.
func IsSemanticFactBudgetExceeded ¶
IsSemanticFactBudgetExceeded reports whether err is or wraps ErrSemanticFactBudgetExceeded.
func IsSpoolBudgetExhausted ¶
IsSpoolBudgetExhausted reports whether err is or wraps ErrSpoolBudgetExhausted.
func ResolveStaticDeclineReason ¶
func ResolveStaticDeclineReason(summary WireEligibilitySummary, reason StaticWireReason) string
ResolveStaticDeclineReason maps static pre-capture gate reasons and summary blockers to a bounded diagnostic decline reason string.
func ResolveStaticDisposition ¶
func ResolveStaticDisposition(summary WireEligibilitySummary, in StaticDispositionInput) (StaticWireDisposition, StaticWireReason)
ResolveStaticDisposition is an alias for StaticDisposition.
func SemanticFactBudget ¶
SemanticFactBudget returns the configured semantic-fact budget from ctx, or DefaultMaxSemanticFactBytes if not set or non-positive.
func SetUseWholeMessageMarshalForTest ¶
func SetUseWholeMessageMarshalForTest(v bool)
SetUseWholeMessageMarshalForTest configures whether AddMessage and AddItem fall back to whole-message json.Marshal instead of streaming parts in fixed buffers. Exported for mutation verification and testing only.
func SizeBucket ¶
SizeBucket returns a bounded static label for payload size in bytes (Requirement 22.2). Buckets: lt_32k, 32k_256k, 256k_1m, 1m_5m, 5m_20m, gte_20m.
func SpliceModelTokenBytes ¶
SpliceModelTokenBytes is a convenience helper that splices in-memory bytes and returns the complete rewritten byte slice.
func StaticDisposition ¶
func StaticDisposition(summary WireEligibilitySummary, in StaticDispositionInput) (StaticWireDisposition, StaticWireReason)
StaticDisposition evaluates whether a request is definitely canonical or needs request assessment. It is a constant-time, allocation-free pure function. It NEVER returns wire-eligible.
func ValidateAssessmentStamp ¶
func ValidateAssessmentStamp(stamp AssessmentStamp, live LiveExecutionFacts) error
ValidateAssessmentStamp revalidates the bound AssessmentStamp against live execution facts (Requirements 6.6, 6.7, 8.5; Task 11.8). Any disagreement returns a *StampInvariantError wrapping ErrStampDisagreement. Execute disagreement is an invariant failure, NEVER a fallback to canonical.
func ValidateExecuteLargeBody ¶
func ValidateExecuteLargeBody(accepted Assessment, src Source, live LiveExecutionFacts) error
ValidateExecuteLargeBody validates an accepted Assessment, its bound stamp, and source against live execution facts before wire execution proceeds (Requirements 6.6, 6.7; Task 11.8).
func ValidateModelSpan ¶
ValidateModelSpan validates that span describes a non-empty, in-bounds byte range for a body of sourceSize using checked int64 arithmetic (Requirements 9.1, 9.4).
func ValidateModelSpans ¶
ValidateModelSpans validates that all provided spans are valid and non-overlapping within sourceSize (Requirement 9.5).
func WireEligibilityPlaneID ¶
WireEligibilityPlaneID resolves a fixed plane index to its stable ID.
func WireEligibilityPlaneIndex ¶
WireEligibilityPlaneIndex resolves a stable plane ID to its fixed index. Unknown IDs fail closed (ok=false); composition-time linear scan only.
func WithSemanticFactBudget ¶
WithSemanticFactBudget attaches a configured semantic-fact budget to ctx.
func WithWireClientTurnShape ¶
func WithWireClientTurnShape(ctx context.Context, shape ClientTurnShape) context.Context
WithWireClientTurnShape attaches a ClientTurnShape to ctx for wire execution (Requirement 14).
func WithWireIdentity ¶
WithWireIdentity attaches a WireIdentity to ctx for wire execution.
func WithWireSessionInput ¶
func WithWireSessionInput(ctx context.Context, in SessionInput) context.Context
WithWireSessionInput attaches a bounded SessionInput to ctx for wire execution (Requirement 14).
Types ¶
type Assessment ¶
type Assessment struct {
Decision AssessmentDecision
Reason DeclineReason
Stamp AssessmentStamp
WireRequest WireRequestFacts
WireDomain WireDomainFacts
CompactionFacts compactionfacts.RequestFacts
CompactionComplete bool
}
Assessment is the bounded assessment outcome containing an opaque generation/proof-bound stamp and bounded facts only (design section 8, Task 11.1). The frontend supplies proof only; it cannot synthesize route/backend internals (Requirements 6, 22).
func NewAcceptedAssessment ¶
func NewAcceptedAssessment(stamp AssessmentStamp, wireReq WireRequestFacts, wireDomain WireDomainFacts) (Assessment, error)
NewAcceptedAssessment creates an accepted Assessment with an opaque stamp and bounded facts.
func NewDeclinedAssessment ¶
func NewDeclinedAssessment(reason DeclineReason) (Assessment, error)
NewDeclinedAssessment creates a declined Assessment with a bounded decline reason.
func (Assessment) Accepted ¶
func (a Assessment) Accepted() bool
Accepted reports whether the assessment accepted the wire turn.
func (Assessment) Declined ¶
func (a Assessment) Declined() bool
Declined reports whether the assessment declined to canonical processing.
func (Assessment) Validate ¶
func (a Assessment) Validate(maxFactBytes int64) error
Validate enforces decision/reason/stamp consistency and bounds on facts.
func (Assessment) WithCompactionFacts ¶
func (a Assessment) WithCompactionFacts(facts compactionfacts.RequestFacts, complete bool) Assessment
WithCompactionFacts returns a copy of Assessment with the provided compaction facts.
type AssessmentDecision ¶
type AssessmentDecision uint8
AssessmentDecision is the bounded assessment outcome.
const ( // AssessmentDecisionUnknown is the zero value and never validates. AssessmentDecisionUnknown AssessmentDecision = iota // AssessmentDecisionDecline selects canonical decode under the held permit. AssessmentDecisionDecline // AssessmentDecisionAccept crosses the one-way wire commit. AssessmentDecisionAccept )
func (AssessmentDecision) String ¶
func (d AssessmentDecision) String() string
String returns a bounded static label for metrics/diagnostics.
type AssessmentRequest ¶
AssessmentRequest carries proof plus immutable generation facts only (design section 8). It never carries a body reader: assessment inspects bounded facts, not prompt content (Requirement 6.2).
func (AssessmentRequest) Validate ¶
func (r AssessmentRequest) Validate(maxFactBytes int64) error
Validate enforces the generation binding and proof bounds.
type AssessmentStamp ¶
type AssessmentStamp struct {
// contains filtered or unexported fields
}
AssessmentStamp is the opaque generation/proof-bound acceptance stamp (design sections 8, 11.8). Execution revalidates it and treats disagreement as an invariant failure, never fallback (Requirement 6.7).
func BindAssessmentStamp ¶
func BindAssessmentStamp(generationID string, proof Proof, candidateDomainGen ...string) (AssessmentStamp, error)
BindAssessmentStamp binds generation identity, profile/proof identity, source digest/size, body mode/rewrite contract, canonical identity, and candidate/domain proof generation from the proof and generation identifiers (Requirements 6.7, 8.5; Task 11.8).
func NewAssessmentStamp ¶
func NewAssessmentStamp( generationID, profileID string, source SourceDigest, bodyBytes int64, mode BodyMode, rewrite RewriteSemantics, identity IdentityDigest, candidateDomainGen ...string, ) (AssessmentStamp, error)
NewAssessmentStamp binds generation identity, profile/proof identity, source digest/size, the body/rewrite contract, and candidate/domain proof generation. Budget-bounded length checks run in Validate; the constructor enforces structural binding only. If candidateDomainGen is omitted or empty, it defaults to generationID.
func (AssessmentStamp) BodyBytes ¶
func (s AssessmentStamp) BodyBytes() int64
BodyBytes returns the bound body size.
func (AssessmentStamp) BodyMode ¶
func (s AssessmentStamp) BodyMode() BodyMode
BodyMode returns the bound body contract.
func (AssessmentStamp) CandidateDomainGeneration ¶
func (s AssessmentStamp) CandidateDomainGeneration() string
CandidateDomainGeneration returns the bound candidate/domain proof generation.
func (AssessmentStamp) CompactionDigest ¶
func (s AssessmentStamp) CompactionDigest() [32]byte
CompactionDigest returns the bound compaction facts digest.
func (AssessmentStamp) GenerationID ¶
func (s AssessmentStamp) GenerationID() string
GenerationID returns the bound generation identity.
func (AssessmentStamp) IdentityDigest ¶
func (s AssessmentStamp) IdentityDigest() IdentityDigest
IdentityDigest returns the bound canonical identity.
func (AssessmentStamp) IsZero ¶
func (s AssessmentStamp) IsZero() bool
IsZero reports whether the stamp is the zero value.
func (AssessmentStamp) ProfileID ¶
func (s AssessmentStamp) ProfileID() string
ProfileID returns the bound profile identity.
func (AssessmentStamp) RequiredCapabilities ¶
func (s AssessmentStamp) RequiredCapabilities() []lipapi.Capability
RequiredCapabilities returns a copy of the bound required capabilities.
func (AssessmentStamp) RequiredCapabilitiesDigest ¶
func (s AssessmentStamp) RequiredCapabilitiesDigest() [32]byte
RequiredCapabilitiesDigest returns the bound required capabilities digest.
func (AssessmentStamp) Revalidate ¶
func (s AssessmentStamp) Revalidate(live LiveExecutionFacts) error
Revalidate checks the stamp against live execution facts (Requirement 6.7, Task 11.8). Any disagreement is an invariant failure, never a fallback.
func (AssessmentStamp) Rewrite ¶
func (s AssessmentStamp) Rewrite() RewriteSemantics
Rewrite returns the bound rewrite contract.
func (AssessmentStamp) SourceDigest ¶
func (s AssessmentStamp) SourceDigest() SourceDigest
SourceDigest returns the bound source evidence.
func (AssessmentStamp) Validate ¶
func (s AssessmentStamp) Validate(maxFactBytes int64) error
Validate enforces the stamp binding under the semantic-fact budget.
type AuthorityAssessmentGate ¶
type AuthorityAssessmentGate struct {
Summary WireEligibilitySummary
Census DependencyCensus
GenerationID string
}
AuthorityAssessmentGate evaluates whether the frozen authority summary and current dependency census allow large-body fast-path execution (Task 11.3; Requirements 5, 13, 14, 15, 19).
Invariants (Requirements 5.3, 5.7, 5.9, 5.10, 6.2, 19.4): - Every typed plane, hook chain, and non-plane port/callback must be known wire-safe. - Unknown port or plane declines immediately with DeclineReasonAuthorityBlocker. - Static summary is defensively rechecked (sealed, pinned to generation, zero blockers). - Zero hot-path reflection, zero heap allocations, zero I/O, zero network/store reads.
func NewAuthorityAssessmentGate ¶
func NewAuthorityAssessmentGate(summary WireEligibilitySummary, census DependencyCensus, generationID string) *AuthorityAssessmentGate
NewAuthorityAssessmentGate constructs an authority assessment gate.
func (*AuthorityAssessmentGate) Evaluate ¶
func (g *AuthorityAssessmentGate) Evaluate() (AssessmentDecision, DeclineReason)
Evaluate evaluates the gate, returning AssessmentDecisionAccept if all authorities and census dependencies are wire-safe, or AssessmentDecisionDecline with a bounded reason (DeclineReasonAuthorityBlocker or DeclineReasonGenerationMismatch).
type AuthorityAssessor ¶
type AuthorityAssessor struct {
Gate AuthorityAssessmentGate
AcceptStamp AssessmentStamp
AcceptWireReq WireRequestFacts
AcceptDomain WireDomainFacts
}
AuthorityAssessor implements LargeBodyAssessor using the Task 11.3 authority gate (Requirements 5, 6, 13, 14, 15, 19).
func NewAuthorityAssessor ¶
func NewAuthorityAssessor(gate AuthorityAssessmentGate) *AuthorityAssessor
NewAuthorityAssessor constructs an AuthorityAssessor.
func (*AuthorityAssessor) AssessLargeBody ¶
func (a *AuthorityAssessor) AssessLargeBody(ctx context.Context, proof Proof) (Assessment, error)
AssessLargeBody evaluates proof through the authority assessment gate. If the gate declines, a declined Assessment is returned with the bounded reason. If the gate accepts, the accepted assessment is returned.
type BackendWireProofAssessor ¶
type BackendWireProofAssessor struct {
Gate BackendWireProofGate
GenerationID string
CandidateDomainGeneration string
AcceptStamp AssessmentStamp
AcceptWireReq WireRequestFacts
AcceptDomain WireDomainFacts
WireExecutor LargeBodyWireExecutor
}
BackendWireProofAssessor implements LargeBodyAssessor and LargeBodyWireExecutor using BackendWireProofGate (Task 11.7, 11.8; Requirements 6, 7, 8, 9, 21).
func NewBackendWireProofAssessor ¶
func NewBackendWireProofAssessor(gate BackendWireProofGate) *BackendWireProofAssessor
NewBackendWireProofAssessor constructs a BackendWireProofAssessor.
func (*BackendWireProofAssessor) AssessLargeBody ¶
func (a *BackendWireProofAssessor) AssessLargeBody(ctx context.Context, proof Proof) (Assessment, error)
AssessLargeBody evaluates proof across exact candidate and domain backend proof gates.
func (*BackendWireProofAssessor) ComposeOverrideCandidate ¶
func (a *BackendWireProofAssessor) ComposeOverrideCandidate( ctx context.Context, overrideSelector string, acceptedDomain WireDomainFacts, ) ([]routing.AttemptCandidate, bool, DeclineReason)
ComposeOverrideCandidate delegates candidate composition and verification to the underlying gate.
func (*BackendWireProofAssessor) ExecuteLargeBody ¶
func (a *BackendWireProofAssessor) ExecuteLargeBody(ctx context.Context, accepted Assessment, src Source) (ExecutionResult, error)
ExecuteLargeBody implements LargeBodyWireExecutor (Requirement 6.7, Task 11.8). It revalidates the assessment stamp against live facts (generation, profile, source, size, mode, rewrite, and candidate/domain proof generation). Any disagreement is an invariant failure, never fallback to canonical.
func (*BackendWireProofAssessor) VerifyOverrideCandidate ¶
func (a *BackendWireProofAssessor) VerifyOverrideCandidate( ctx context.Context, acceptedDomain WireDomainFacts, cand routing.AttemptCandidate, ) (bool, DeclineReason)
VerifyOverrideCandidate delegates candidate verification to the underlying gate.
type BackendWireProofGate ¶
type BackendWireProofGate struct {
InitialGate *InitialRouteAssessmentGate
OverrideGate *RouteOverrideAssessmentGate
LateSelectorGate *LateSelectorAssessmentGate
BackendResolver WireBackendResolver
}
BackendWireProofGate composes exact initial-route candidate proof and late-route domain proof (route override and late selector envelopes), verifying pure backend wire support across all candidates and domain members (Task 11.7; Requirements 7, 8, 9, 21).
Invariants (Requirements 7.2, 7.3, 7.4, 7.5, 8.1, 8.2, 8.3, 8.4, 9.1, 9.6, 21.5): - Pass immutable body mode and rewrite facts to every resolver call (both ResolveWireRequest and ResolveWireDomain). - Any candidate or domain member incompatibility declines the entire request (no pruning). - Homogeneous same-wire domain accepts; heterogeneous incompatible domain declines. - Proves whether a post-BeginTurn route override change falls strictly inside the accepted domain. - Pure and side-effect-free: strictly zero live store reads, zero provider network I/O.
func NewBackendWireProofGate ¶
func NewBackendWireProofGate( initialGate *InitialRouteAssessmentGate, overrideGate *RouteOverrideAssessmentGate, lateSelectorGate *LateSelectorAssessmentGate, backendResolver WireBackendResolver, ) *BackendWireProofGate
NewBackendWireProofGate constructs a BackendWireProofGate.
func (*BackendWireProofGate) ComposeOverrideCandidate ¶
func (g *BackendWireProofGate) ComposeOverrideCandidate( ctx context.Context, overrideSelector string, acceptedDomain WireDomainFacts, ) ([]routing.AttemptCandidate, bool, DeclineReason)
ComposeOverrideCandidate composes the candidate set for an override selector under the active generation's routing rules and verifies that every resulting candidate is wire-compatible inside the accepted domain (Requirements 7.4, 8.3).
func (*BackendWireProofGate) Evaluate ¶
func (g *BackendWireProofGate) Evaluate( ctx context.Context, proof Proof, ) (AssessmentDecision, DeclineReason, WireRequestFacts, WireDomainFacts, []routing.AttemptCandidate)
Evaluate evaluates exact initial candidate wire proof and late route domain wire proof. Threads immutable body/rewrite facts to every resolver call. Any candidate or domain member incompatibility declines the entire request.
func (*BackendWireProofGate) LegalDomainBackends ¶
func (g *BackendWireProofGate) LegalDomainBackends() []string
LegalDomainBackends returns the sorted union of all backend IDs that can legally be selected by post-commit route authorities under the gate's configured generation and late authorities.
func (*BackendWireProofGate) VerifyOverrideCandidate ¶
func (g *BackendWireProofGate) VerifyOverrideCandidate( ctx context.Context, acceptedDomain WireDomainFacts, cand routing.AttemptCandidate, ) (bool, DeclineReason)
VerifyOverrideCandidate proves whether a candidate produced post-BeginTurn by a live route override falls strictly inside the accepted domain envelope and is wire-compatible without requiring canonical fallback (Task 11.7; Requirements 7.4, 8.3).
type BodyMode ¶
type BodyMode string
BodyMode names the certified body representation (design sections 6, 9). Wave 1 supports identity JSON only; decoded/compressed modes need a separate certification wave and are rejected here.
type BoundedRouteDomainAuthority ¶
type BoundedRouteDomainAuthority interface {
BoundedRouteDomainContract() (BoundedRouteDomainContract, bool)
}
BoundedRouteDomainAuthority is an optional interface that a route hint provider or selector mutator can implement to declare a certified bounded route-domain contract (Requirement 7.6).
type BoundedRouteDomainContract ¶
type BoundedRouteDomainContract struct {
// TargetBackends is the non-empty finite set of backend IDs this authority can target.
TargetBackends []string
// TargetModels is the optional finite set of model IDs this authority can target.
// When empty and UniversalModel is false, models are constrained to the candidate/client model.
// When UniversalModel is true, backend universal proof (AnyAcceptedModel) is required.
TargetModels []string
// UniversalModel specifies whether the authority may select any model accepted by the backend.
UniversalModel bool
}
BoundedRouteDomainContract defines an explicit certified bounded route domain for a late selector authority such as a route hint provider or selector mutator (Requirements 5, 7.6, 13.3, 19.4).
An authority without this contract is considered full-Call / uncontracted and blocks wire execution.
func NewBoundedRouteDomainContractFromKeys ¶
func NewBoundedRouteDomainContractFromKeys(keys []string) (BoundedRouteDomainContract, error)
NewBoundedRouteDomainContractFromKeys parses candidate keys of the form "backend:model" into an explicit BoundedRouteDomainContract.
Note: backends and models are collected as independent sets, so the contract authorizes the cross product (e.g. ["b1:m1","b2:m2"] permits b1:m2). This is safe but imprecise widening: every target backend is still proven wire-compatible per-backend via ResolveWireDomain during evaluation, so no unproven backend enters the envelope — only unproven backend/model pairs within proven backends.
func (BoundedRouteDomainContract) ToWireDomainFacts ¶
func (c BoundedRouteDomainContract) ToWireDomainFacts(proof Proof) WireDomainFacts
ToWireDomainFacts converts this contract into WireDomainFacts for backend verification.
func (BoundedRouteDomainContract) Validate ¶
func (c BoundedRouteDomainContract) Validate(maxFactBytes int64) error
Validate checks internal consistency and budget limits.
type CallIdentityConfig ¶
type CallIdentityConfig struct {
ExplicitID string
Session lipapi.SessionRef
SessionInput SessionInput
Route lipapi.RouteIntent
RouteSelector string
ClientModel string
Instructions []lipapi.Message
PreviousResponseID string
PromptCacheKey string
SemanticExtensions []lipapi.SemanticExtension
Tools []lipapi.ToolDef
ToolChoice lipapi.ToolChoice
Options lipapi.GenerationOptions
Extensions map[string]json.RawMessage
}
CallIdentityConfig specifies metadata for Call identity derivation (Requirements 4, 16, 17; design section 6).
type CallIdentityWriter ¶
type CallIdentityWriter struct {
// contains filtered or unexported fields
}
CallIdentityWriter constructs the exact canonical semantic identity digest for a Call without retaining large string payloads (Requirements 4, 16, 17; design section 6).
func NewCallIdentityWriter ¶
func NewCallIdentityWriter(cfg CallIdentityConfig) (*CallIdentityWriter, error)
NewCallIdentityWriter returns a new CallIdentityWriter configured with cfg.
func (*CallIdentityWriter) AddItem ¶
func (w *CallIdentityWriter) AddItem(item lipapi.Item) error
AddItem appends a fully formed Item to the identity stream.
func (*CallIdentityWriter) AddMessage ¶
func (w *CallIdentityWriter) AddMessage(msg lipapi.Message) error
AddMessage appends a fully formed Message to the identity stream.
func (*CallIdentityWriter) BeginMessage ¶
func (w *CallIdentityWriter) BeginMessage(role lipapi.Role) (*MessageIdentityWriter, error)
BeginMessage opens a new message for streaming parts.
func (*CallIdentityWriter) BeginMessageItem ¶
func (w *CallIdentityWriter) BeginMessageItem(id string, status lipapi.ItemStatus, role lipapi.Role, phase lipapi.AssistantPhase) (*ItemIdentityWriter, error)
BeginMessageItem opens a new message Item for streaming content parts.
func (*CallIdentityWriter) Digest ¶
func (w *CallIdentityWriter) Digest() (IdentityDigest, error)
Digest finalizes the stream and returns the exact canonical IdentityDigest.
func (*CallIdentityWriter) SetClientModel ¶
func (w *CallIdentityWriter) SetClientModel(model string, extKeys ...string) error
SetClientModel sets or overrides the client model in Extensions. If extKeys is empty, it defaults to "openai.model". This supports late-discovered models (e.g. model field appearing after messages in JSON).
func (*CallIdentityWriter) SetRouteSelector ¶
func (w *CallIdentityWriter) SetRouteSelector(sel string) error
SetRouteSelector sets the route selector if the prefix has not yet been written.
func (*CallIdentityWriter) StartItems ¶
func (w *CallIdentityWriter) StartItems() error
StartItems explicitly opens the Items array, ensuring an empty array [] is emitted if no items are added (preserving non-nil empty vs nil semantics).
func (*CallIdentityWriter) StartMessages ¶
func (w *CallIdentityWriter) StartMessages() error
StartMessages explicitly opens the Messages array, ensuring an empty array [] is emitted if no messages are added (preserving non-nil empty vs nil semantics).
func (*CallIdentityWriter) WriteCall ¶
func (w *CallIdentityWriter) WriteCall(call *lipapi.Call) (IdentityDigest, error)
WriteCall streams all fields of call through the writer and returns its IdentityDigest.
type CaptureConfig ¶
type CaptureConfig struct {
// MaxBytes is the authoritative request body ceiling.
MaxBytes int64
// ResponseWriter is an optional http.ResponseWriter for ceiling enforcement.
ResponseWriter http.ResponseWriter
// CopyBufferSize is the chunk size used for reading from the client body.
// Defaults to DefaultCopyBufferSize (32 KiB).
CopyBufferSize int
// OnChunk is an optional callback invoked for each chunk read from the client body
// before writing to storage (e.g. for streaming JSON scanner in Task 5).
OnChunk func(chunk []byte) error
}
CaptureConfig configures capturing an incoming request body (Requirement 20).
type CaptureOutcome ¶
type CaptureOutcome uint8
CaptureOutcome indicates the result of a CaptureRequestBody operation.
const ( // CaptureOutcomeCompleted indicates the entire request body was captured // to EOF without error or decline. CaptureOutcomeCompleted CaptureOutcome = iota // CaptureOutcomeDeclined indicates capture encountered a recoverable decline // (spool reservation exhausted, spill write/create failure, or callback decline) // and produced a lossless canonical continuation reader. CaptureOutcomeDeclined // CaptureOutcomeLimitExceeded indicates the request body exceeded MaxBytes. CaptureOutcomeLimitExceeded // CaptureOutcomeReadError indicates reading from the client socket failed // with a non-recoverable error (e.g. client cancellation or disconnect). CaptureOutcomeReadError // CaptureOutcomeTerminalError indicates capture could not continue or fall back // due to an unrecoverable failure (such as failure to construct the lossless continuation reader). CaptureOutcomeTerminalError )
func (CaptureOutcome) String ¶
func (o CaptureOutcome) String() string
String returns a bounded diagnostic representation.
type CaptureReader ¶
type CaptureReader struct {
// contains filtered or unexported fields
}
CaptureReader is a lossless mid-capture canonical continuation reader (Requirements 1.4, 2.4, 20.6, 20.7, 20.8; design section 5).
It composes:
- Retained prefix: bytes successfully committed to storage before decline.
- Unwritten suffix: bytes read from the client socket in the current chunk that were not yet committed to storage.
- Still-unread request body: the remaining unread client socket stream.
Invariants:
- Never rereads or restarts the client socket (forward-only streaming; Requirement 20.8).
- Preserves exact request body ceiling semantics (returns *http.MaxBytesError; Requirement 2.6).
- Preserves non-limit read errors (cancellation, disconnect) without converting to 413.
- Closing the reader idempotently closes the underlying client body and releases retained prefix resources (deleting temporary spill files; Requirement 20.9).
func NewCaptureReader ¶
func NewCaptureReader(cfg CaptureReaderConfig) (*CaptureReader, error)
NewCaptureReader constructs an initialized CaptureReader from configuration.
func NewContinuationReader ¶
func NewContinuationReader(spill *SpillBuffer, remaining io.ReadCloser, maxBytes int64) (*CaptureReader, error)
NewContinuationReader is a convenience constructor creating a CaptureReader from a SpillBuffer and remaining body under the given ceiling.
func (*CaptureReader) Close ¶
func (c *CaptureReader) Close() error
Close closes the continuation reader (implements io.Closer). It is idempotent and closes the underlying client body, retained prefix reader, and associated SpillBuffer (deleting temporary spill files if pending).
func (*CaptureReader) Read ¶
func (c *CaptureReader) Read(p []byte) (int, error)
Read reads from the continuation stream (implements io.Reader). It serves bytes from the retained prefix first, then the unwritten suffix, then the still-unread client body.
func (*CaptureReader) RetainedBytes ¶
func (c *CaptureReader) RetainedBytes() int64
RetainedBytes reports the byte size of the retained prefix.
func (*CaptureReader) TotalRead ¶
func (c *CaptureReader) TotalRead() int64
TotalRead reports total bytes read across all segments through this reader.
func (*CaptureReader) UnwrittenBytes ¶
func (c *CaptureReader) UnwrittenBytes() int64
UnwrittenBytes reports the byte size of the unwritten suffix.
type CaptureReaderConfig ¶
type CaptureReaderConfig struct {
// Spill is the optional SpillBuffer holding the retained prefix and/or unwritten suffix.
// If provided and Spill.BytesWritten() > 0 and RetainedReader is nil, Spill.Open()
// is automatically called to supply the retained prefix reader.
Spill *SpillBuffer
// RetainedReader optionally overrides the retained prefix reader.
// If nil and Spill != nil and Spill.BytesWritten() > 0, Spill.Open() is used.
RetainedReader io.ReadCloser
// RetainedBytes is the byte length of the retained prefix if known.
RetainedBytes int64
// UnwrittenSuffix is any unwritten suffix bytes from the last chunk.
// If nil and Spill != nil, Spill.TakeUnwrittenSuffix() is automatically consumed.
UnwrittenSuffix []byte
// Remaining is the still-unread client request body stream (must not be nil).
Remaining io.ReadCloser
// MaxBytes is the authoritative request body ceiling. If > 0, reads exceeding
// MaxBytes return an *http.MaxBytesError honoring standard reqbody.TooLarge semantics.
MaxBytes int64
// ResponseWriter is an optional http.ResponseWriter passed to http.MaxBytesReader.
ResponseWriter http.ResponseWriter
}
CaptureReaderConfig configures a CaptureReader for lossless mid-capture canonical continuation (Requirements 1.4, 2.4, 20.6, 20.7, 20.8; design section 5).
type CaptureResult ¶
type CaptureResult struct {
Outcome CaptureOutcome
Source Source
Continuation *CaptureReader
Digest SourceDigest
BytesRead int64
Err error
}
CaptureResult is the outcome returned by CaptureRequestBody.
func CaptureRequestBody ¶
func CaptureRequestBody(body io.ReadCloser, spill *SpillBuffer, cfg CaptureConfig) CaptureResult
CaptureRequestBody streams from body into spillBuffer up to maxBytes.
Invariants:
- If capture completes to EOF, it returns CaptureOutcomeCompleted.
- If a recoverable decline occurs (reservation exhausted, spill failure, etc.), it constructs and returns a lossless CaptureReader (canonical continuation) composing retained prefix + unwritten suffix + remaining client body. Declined ⇒ non-nil continuation is enforced by construction. If continuation reader construction fails, it returns CaptureOutcomeTerminalError instead of CaptureOutcomeDeclined, releasing all resources.
- If body exceeds maxBytes, it returns CaptureOutcomeLimitExceeded with *http.MaxBytesError.
- If reading from body fails, it returns CaptureOutcomeReadError with the read error.
- Consumes any unwritten suffix from spillBuffer before retrying new writes (Task 4.2 review suggestion).
type ClientTurnItemShape ¶
type ClientTurnItemShape = capabilityfacts.TurnItemShape
ClientTurnPartShape describes one normalized content part by kind and attributed byte size only. Prompt text is never materialized for the recorder (Requirement 14.5).
type ClientTurnPartShape ¶
type ClientTurnPartShape = capabilityfacts.TurnPartShape
ClientTurnPartShape describes one normalized content part by kind and attributed byte size only. Prompt text is never materialized for the recorder (Requirement 14.5).
type ClientTurnShape ¶
type ClientTurnShape = capabilityfacts.TurnShape
ClientTurnPartShape describes one normalized content part by kind and attributed byte size only. Prompt text is never materialized for the recorder (Requirement 14.5).
func ClientTurnShapeFromCall ¶
func ClientTurnShapeFromCall(call *lipapi.Call, maxFactBytes int64) (ClientTurnShape, error)
ClientTurnShapeFromCall derives a bounded ClientTurnShape equivalent to lipapi.NormalizedItems for the given call without retaining or materializing prompt text (Requirements 14.3, 14.5). If call is nil or has no items, an empty ClientTurnShape is returned. If the derived shape exceeds maxFactBytes, it returns an error wrapping ErrSemanticFactBudgetExceeded (Requirement 14.4).
func ClientTurnShapeFromItems ¶
func ClientTurnShapeFromItems(items []lipapi.Item, maxFactBytes int64) (ClientTurnShape, error)
ClientTurnShapeFromItems derives a bounded ClientTurnShape from normalized items without retaining or materializing prompt text.
func ClientTurnShapeFromMessages ¶
func ClientTurnShapeFromMessages(msgs []lipapi.Message, maxFactBytes int64) (ClientTurnShape, error)
ClientTurnShapeFromMessages derives a bounded ClientTurnShape from a message slice without synthesizing a lipapi.Call. It maps message parts with exact equivalence to canonical partsToContentParts without allocating payload-sized strings.
func WireClientTurnShapeFromContext ¶
func WireClientTurnShapeFromContext(ctx context.Context) (ClientTurnShape, bool)
WireClientTurnShapeFromContext extracts ClientTurnShape from ctx if attached.
type CompletedSource ¶
type CompletedSource struct {
// contains filtered or unexported fields
}
func NewCompletedSource ¶
func NewCompletedSource(cfg CompletedSourceConfig) (*CompletedSource, error)
NewCompletedSource validates configuration and constructs an initialized CompletedSource.
func NewMemorySource ¶
func NewMemorySource(data []byte) *CompletedSource
NewMemorySource constructs an immutable in-memory CompletedSource from data.
func (*CompletedSource) ActiveReaders ¶
func (s *CompletedSource) ActiveReaders() int
ActiveReaders reports the current count of open readers.
func (*CompletedSource) Close ¶
func (s *CompletedSource) Close() error
Close releases the completed source (implements io.Closer and Source).
Invariants (Requirement 20.9):
- Idempotent and nonblocking.
- Releases any associated spool reservation.
- If active readers exist, deletion is marked pending and final removal occurs when the last reader closes (Windows open-file safety).
func (*CompletedSource) Digest ¶
func (s *CompletedSource) Digest() SourceDigest
Digest reports the bound source integrity digest (Requirements 15, 16, 20; design section 5). The source digest is for replay/attempt evidence only and is never a substitute for canonical semantic identity (Requirement 16.5).
func (*CompletedSource) FilePath ¶
func (s *CompletedSource) FilePath() string
FilePath returns the spill file path, or empty string if not spilled.
func (*CompletedSource) HasSpilled ¶
func (s *CompletedSource) HasSpilled() bool
HasSpilled reports whether the source is backed by secondary spill storage.
func (*CompletedSource) IsClosed ¶
func (s *CompletedSource) IsClosed() bool
IsClosed reports whether root Close() has been called.
func (*CompletedSource) IsDeletePending ¶
func (s *CompletedSource) IsDeletePending() bool
IsDeletePending reports whether file deletion is deferred until all readers close.
func (*CompletedSource) MemoryBytes ¶
func (s *CompletedSource) MemoryBytes() []byte
MemoryBytes returns a copy of the in-memory portion of the source.
func (*CompletedSource) Open ¶
func (s *CompletedSource) Open() (io.ReadCloser, error)
Open returns an independent offset-zero reader over the captured body (implements Source). Multiple readers can be opened concurrently and read independently.
func (*CompletedSource) Size ¶
func (s *CompletedSource) Size() int64
Size reports the exact captured body size in bytes (implements Source).
func (*CompletedSource) SourceDigest ¶
func (s *CompletedSource) SourceDigest() SourceDigest
SourceDigest reports the bound source integrity digest (alias for Digest).
func (*CompletedSource) String ¶
func (s *CompletedSource) String() string
String returns a bounded diagnostic representation without leaking prompt content, model names, or filesystem paths (Requirement 20.3).
type CompletedSourceConfig ¶
type CompletedSourceConfig struct {
// Memory is the in-memory prefix of the captured body (if any).
Memory []byte
// FilePath is the path to the spilled temporary file (if any).
FilePath string
// Size is the exact captured body size in bytes.
Size int64
// Digest is the replay/attempt source integrity digest (Requirements 15, 16, 20; design section 5).
// If zero and data is in-memory without spill, it is automatically computed via SHA-256.
Digest SourceDigest
// Reservation is an optional logical spool reservation released on root close.
Reservation *SpoolReservation
// OpenFile optionally overrides opening the spill file for readers (for testing/fault injection).
OpenFile func(path string) (io.ReadCloser, error)
// RemoveFile optionally overrides spill file deletion (for testing/fault injection).
RemoveFile func(path string) error
}
CompletedSourceConfig configures an immutable CompletedSource (Requirements 10, 20; design section 5).
type ConservativeDependencyAssessmentGate ¶
type ConservativeDependencyAssessmentGate struct {
AuthorityGate AuthorityAssessmentGate
}
ConservativeDependencyAssessmentGate evaluates authority eligibility combining static census validation with per-request dependency assessment (Requirements 13, 19; Task 12.3).
func NewConservativeDependencyAssessmentGate ¶
func NewConservativeDependencyAssessmentGate(summary WireEligibilitySummary, census DependencyCensus, generationID string) *ConservativeDependencyAssessmentGate
NewConservativeDependencyAssessmentGate constructs a ConservativeDependencyAssessmentGate.
func (*ConservativeDependencyAssessmentGate) Evaluate ¶
func (g *ConservativeDependencyAssessmentGate) Evaluate(facts WireDependencyFacts) (AssessmentDecision, DeclineReason)
Evaluate evaluates both static authority census and per-request dependency facts. Content/trajectory uses cause decline with DeclineReasonAuthorityBlocker. Metadata-only uses and response-only uses accept.
type ControlRequirements ¶
type ControlRequirements = capabilityfacts.ControlRequirements
ClientTurnPartShape describes one normalized content part by kind and attributed byte size only. Prompt text is never materialized for the recorder (Requirement 14.5).
type DeclineReason ¶
type DeclineReason uint16
DeclineReason is the bounded assessment-decline taxonomy for diagnostics. Labels are static; backend/model/session/user IDs never appear here (Requirement 22.2).
const ( // DeclineReasonNone accompanies accept decisions only. DeclineReasonNone DeclineReason = iota // DeclineReasonProofUncertain means profile proof could not certify the shape. DeclineReasonProofUncertain // DeclineReasonAuthorityBlocker means a frozen authority blocks wire mode. DeclineReasonAuthorityBlocker // DeclineReasonRouteIncompatible means the route domain is not wire-compatible. DeclineReasonRouteIncompatible // DeclineReasonBackendIncompatible means a candidate lacks exact/domain proof. DeclineReasonBackendIncompatible // DeclineReasonRewriteUnsupported means the rewrite has no certified contract. DeclineReasonRewriteUnsupported // DeclineReasonSessionUnsupported means session facts lack a wire view. DeclineReasonSessionUnsupported // DeclineReasonMeteringUnsupported means metering lacks a wire-native path. DeclineReasonMeteringUnsupported // DeclineReasonCountingUnsupported means token counting lacks an exact wire contract. DeclineReasonCountingUnsupported // DeclineReasonGenerationMismatch means execution disagrees with the stamp. DeclineReasonGenerationMismatch // DeclineReasonCanceled means assessment observed a canceled context. DeclineReasonCanceled )
func (DeclineReason) String ¶
func (r DeclineReason) String() string
String returns a bounded static label for metrics/diagnostics.
type DependencyCensus ¶
type DependencyCensus struct {
Planes []PlaneEligibilityInput
Hooks HookEligibilityInput
Ports NarrowPortEligibilityInput
TwoPhaseExecutorAvailable bool
ExtraPorts []PortDependency
}
DependencyCensus represents the frozen inventory of typed planes, hook chains, and narrow runtime ports/callbacks evaluated for wire eligibility (Task 11.3; Requirements 5, 13, 14, 15, 19; evidence 1.8, 1.9).
func NewStandardDependencyCensus ¶
func NewStandardDependencyCensus(generationID string) DependencyCensus
NewStandardDependencyCensus constructs a baseline dependency census covering all 28 standard planes (unoccupied, with pinned V1 access classes), empty hook bus, clear narrow ports (backends present), and two-phase executor available. The census itself is generation-agnostic: generation pinning lives on the sealed WireEligibilitySummary and is rechecked per evaluation. generationID is accepted for call-site symmetry with the gate constructor and is intentionally unused.
func (*DependencyCensus) AddPort ¶
func (c *DependencyCensus) AddPort(name string, occupied bool)
AddPort registers a port by name, automatically looking up its standard classification. If the port is unfamiliar, it is registered with DependencyClassUnknown (fails closed).
func (*DependencyCensus) RegisterPort ¶
func (c *DependencyCensus) RegisterPort(name string, class DependencyClass, occupied bool)
RegisterPort registers or updates a narrow port or custom callback entry.
type DependencyClass ¶
type DependencyClass uint8
DependencyClass categorizes a dependency's wire compatibility (Requirement 19.4).
const ( // DependencyClassUnknown is the zero value: unclassified or unfamiliar dependency. // Any unknown dependency causes assessment decline (Requirements 5.3, 5.7, 19.4). DependencyClassUnknown DependencyClass = iota // DependencyClassWireSafe indicates the dependency operates on bounded facts, // response events, or immutable source/digest contracts without full Call materialization. DependencyClassWireSafe // DependencyClassBlocker indicates the dependency requires full canonical Call // access or mutating request behavior. When occupied/active, assessment must decline. DependencyClassBlocker )
func LookupStandardPort ¶
func LookupStandardPort(name string) (DependencyClass, bool)
LookupStandardPort returns the default classification for a known narrow port.
func (DependencyClass) IsBlocker ¶
func (c DependencyClass) IsBlocker() bool
IsBlocker reports whether the dependency is a canonical-required blocker.
func (DependencyClass) IsUnknown ¶
func (c DependencyClass) IsUnknown() bool
IsUnknown reports whether the dependency is unclassified or unfamiliar.
func (DependencyClass) IsWireSafe ¶
func (c DependencyClass) IsWireSafe() bool
IsWireSafe reports whether the dependency is proven wire-safe.
func (DependencyClass) String ¶
func (c DependencyClass) String() string
String returns a bounded static label for metrics and diagnostics.
type DiagnosticsObserver ¶
type DiagnosticsObserver interface {
OnPipelineStage(stage PipelineStage)
OnDecline(reason string)
OnCapture(sizeBucket string, storage StorageKind)
OnReplay()
OnRewrite()
OnStageDuration(stage string, d time.Duration)
OnActiveSpoolBytes(seq uint64, bytes int64)
}
DiagnosticsObserver is the pure diagnostic observation interface for the large payload lane. Implementations must not retain prompt bodies, file paths, or sensitive tokens (Requirement 22).
func NewSafeDiagnosticsObserver ¶
func NewSafeDiagnosticsObserver(inner DiagnosticsObserver) DiagnosticsObserver
NewSafeDiagnosticsObserver returns a non-nil DiagnosticsObserver wrapping inner.
type ExactTokenizerDeclarer ¶
type ExactTokenizerDeclarer interface {
ExactTokenizerSemantics(model string) (ExactTokenizerSemantics, bool)
}
ExactTokenizerDeclarer is an optional interface implemented by profiles, backends, or model catalogs to declare exact tokenizer semantics for an effective model (Task 10.4).
type ExactTokenizerSemantics ¶
ExactTokenizerSemantics declares whether exact tokenizer semantics are proven for an effective model under a profile/backend (Requirement 15.5; Task 10.4).
func (ExactTokenizerSemantics) IsExact ¶
func (s ExactTokenizerSemantics) IsExact() bool
IsExact reports whether exact tokenizer semantics are proven.
type ExecutionResult ¶
type ExecutionResult struct {
Stream lipapi.EventStream
Facts ResponseFacts
Session SessionResponseCarrier
}
ExecutionResult is the wire execution output (design section 13): the canonical event stream plus bounded response facts. An EventStream alone is insufficient (Requirement 18.1).
func (ExecutionResult) ResponseFacts ¶
func (r ExecutionResult) ResponseFacts() ResponseFacts
ResponseFacts returns the bounded provider-neutral response facts (Requirement 18.2).
func (ExecutionResult) Validate ¶
func (r ExecutionResult) Validate(maxFactBytes int64) error
Validate requires the canonical stream and valid bounded facts.
type HookChain ¶
type HookChain uint8
HookChain is a fixed bitset over the four hook-bus chains (Task 3.3). The bus owns exactly these chains, separate from the plane manifest.
const ( // HookChainSubmit names the submit chain (canonical request pre-route). HookChainSubmit HookChain = 1 << iota // HookChainRequestPart names the request-part chain (request mutation). HookChainRequestPart // HookChainResponsePart names the response-part chain (events only). HookChainResponsePart // HookChainTool names the tool-reactor chain (tool lifecycle). HookChainTool )
type HookEligibilityInput ¶
type HookEligibilityInput struct {
SubmitOccupied bool
RequestPartOccupied bool
ResponsePartOccupied bool
ToolOccupied bool
}
HookEligibilityInput is the frozen hook-bus occupancy: one bit per chain. Occupied submit/request-part/tool chains block without a wire contract; the response-only chain is recorded but never blocks statically (Task 3.3).
type IdentityDigest ¶
type IdentityDigest struct {
// contains filtered or unexported fields
}
IdentityDigest is the exact canonical semantic identity digest equivalent to the post-frontend-decode/pre-core canonical Call identity for the supported subset, derived without retaining prompt content (Requirement 16). It is a distinct type from SourceDigest so a raw-body hash can never substitute for canonical economic/request identity (Requirement 16.5).
func CanonicalCallIdentity ¶
func CanonicalCallIdentity(call *lipapi.Call) IdentityDigest
CanonicalCallIdentity computes the exact canonical semantic identity digest for call, producing output byte-for-byte identical to diag.StableCallSum (Requirements 16, 17; design section 6).
func NewIdentityDigest ¶
func NewIdentityDigest(sum [32]byte) IdentityDigest
NewIdentityDigest wraps an already-computed canonical sum.
func (IdentityDigest) CallID ¶
func (d IdentityDigest) CallID(explicitID string) string
CallID returns explicitID when non-empty, otherwise "call_" followed by the 16-hex-character token, matching diag.StableCallIDFromSum.
func (IdentityDigest) IsZero ¶
func (d IdentityDigest) IsZero() bool
IsZero reports whether no sum was provided.
func (IdentityDigest) String ¶
func (d IdentityDigest) String() string
String renders the sum as hex for diagnostics.
func (IdentityDigest) Sum ¶
func (d IdentityDigest) Sum() [32]byte
Sum returns the wrapped canonical sum.
func (IdentityDigest) Token ¶
func (d IdentityDigest) Token() string
Token returns the deterministic 16-hex-character fingerprint for this identity digest, matching diag.StableCallTokenFromSum.
func (IdentityDigest) Unix ¶
func (d IdentityDigest) Unix() int64
Unix returns the deterministic Unix timestamp derived from the call sum, matching diag.StableUnixFromSum byte-for-byte and second-for-second.
type InitialRouteAssessmentGate ¶
type InitialRouteAssessmentGate struct {
Aliases *routing.AliasResolver
DefaultBackend string
BackendExecutionResolver routing.BackendExecutionResolver
ExecutionCompositionPolicy config.ExecutionCompositionPolicy
NativeModelResolver routing.NativeModelResolver
BackendResolver WireBackendResolver
}
InitialRouteAssessmentGate evaluates whether the exact initial route candidate set derived under canonical rules is wire-compatible across all candidates (Task 11.4; Requirements 7, 8, 10).
Invariants (Requirements 7.3, 8.3, 8.4, 10.3, 10.4): - Reuses current alias resolution, default backend, execution composition, and native model rules. - Preserves sequential/fallback, weighted, and parallel/race candidate order and membership exactly. - Proves backend wire support for every possible candidate; any incompatible candidate declines the whole request. - Core shall NOT prune or reorder candidates to force wire compatibility. - Pure and side-effect-free: zero provider network I/O, zero store reads/writes.
func NewInitialRouteAssessmentGate ¶
func NewInitialRouteAssessmentGate( aliases *routing.AliasResolver, defaultBackend string, execResolver routing.BackendExecutionResolver, policy config.ExecutionCompositionPolicy, nativeResolver routing.NativeModelResolver, backendResolver WireBackendResolver, ) *InitialRouteAssessmentGate
NewInitialRouteAssessmentGate constructs an InitialRouteAssessmentGate.
func (*InitialRouteAssessmentGate) Evaluate ¶
func (g *InitialRouteAssessmentGate) Evaluate(ctx context.Context, proof Proof) (AssessmentDecision, DeclineReason, []routing.AttemptCandidate)
Evaluate evaluates proof through canonical routing composition and verifies pure wire support across the entire initial candidate set. If any candidate is incompatible, the entire request declines (no pruning).
func (*InitialRouteAssessmentGate) EvaluateRouteFacts ¶
func (g *InitialRouteAssessmentGate) EvaluateRouteFacts( ctx context.Context, route WireRouteFacts, protocol WireProtocolFacts, rewrite WireRewriteFacts, source WireSourceFacts, maxOutput WireMaxOutputFacts, ) (AssessmentDecision, DeclineReason, []routing.AttemptCandidate)
EvaluateRouteFacts evaluates routing candidates directly from Task 12.1 bounded wire facts.
func (*InitialRouteAssessmentGate) EvaluateTurnFacts ¶
func (g *InitialRouteAssessmentGate) EvaluateTurnFacts( ctx context.Context, facts WireTurnFacts, ) (AssessmentDecision, DeclineReason, []routing.AttemptCandidate)
EvaluateTurnFacts evaluates routing candidates directly from WireTurnFacts.
func (*InitialRouteAssessmentGate) ProveCandidateSet ¶
func (g *InitialRouteAssessmentGate) ProveCandidateSet(ctx context.Context, proof Proof, expected []routing.AttemptCandidate) (AssessmentDecision, DeclineReason)
ProveCandidateSet verifies that expected matches the canonical composition output in exact order and membership, and that every candidate in that set is wire-compatible without pruning.
type InitialRouteAssessor ¶
type InitialRouteAssessor struct {
Gate InitialRouteAssessmentGate
AcceptStamp AssessmentStamp
AcceptWireReq WireRequestFacts
AcceptDomain WireDomainFacts
}
InitialRouteAssessor implements LargeBodyAssessor using the Task 11.4 initial route gate (Requirements 7, 8, 10).
func NewInitialRouteAssessor ¶
func NewInitialRouteAssessor(gate InitialRouteAssessmentGate) *InitialRouteAssessor
NewInitialRouteAssessor constructs an InitialRouteAssessor.
func (*InitialRouteAssessor) AssessLargeBody ¶
func (a *InitialRouteAssessor) AssessLargeBody(ctx context.Context, proof Proof) (Assessment, error)
AssessLargeBody evaluates proof through the initial route assessment gate.
type ItemIdentityWriter ¶
type ItemIdentityWriter struct {
// contains filtered or unexported fields
}
ItemIdentityWriter writes item content parts to the identity stream.
func (*ItemIdentityWriter) AddContentPart ¶
func (it *ItemIdentityWriter) AddContentPart(part lipapi.ContentPart) error
AddContentPart appends a completed ContentPart to the item.
func (*ItemIdentityWriter) BeginTextContentPart ¶
func (it *ItemIdentityWriter) BeginTextContentPart() (io.WriteCloser, error)
BeginTextContentPart opens a streaming writer for an Item ContentPart of kind text.
func (*ItemIdentityWriter) EndItem ¶
func (it *ItemIdentityWriter) EndItem() error
EndItem closes the content array and item object.
type LargeBodyAssessor ¶
type LargeBodyAssessor interface {
// AssessLargeBody is side-effect-free proof assessment over bounded facts.
AssessLargeBody(ctx context.Context, proof Proof) (Assessment, error)
}
LargeBodyAssessor evaluates frontend proof and returns an Assessment containing an opaque generation/proof-bound stamp and bounded facts only (Task 11.1). The frontend supplies proof only; it cannot synthesize route/backend internals (Requirements 6, 22).
func AsLargeBodyAssessor ¶
func AsLargeBodyAssessor(exec lipsdk.ExecutorView) (LargeBodyAssessor, bool)
AsLargeBodyAssessor safely probes the executor for the internal large-body assessor capability. A nil executor or an executor without the capability reports ok=false so the caller continues on the canonical path.
type LargeBodyExecutor ¶
type LargeBodyExecutor interface {
LargeBodyAssessor
LargeBodyWireExecutor
}
LargeBodyExecutor is the internal optional large-body capability for the large-payload streaming fast path (design section 8, assessor/executor interface, Task 11.1).
It is deliberately NOT part of the public lipsdk.ExecutorView contract (Requirements 1, 22): existing public ExecutorView remains supported and unchanged, and external/manual frontends/executors stay source-compatible and canonical-only. The standard bundled frontend path type-asserts this capability from its lipsdk.ExecutorView; absence selects the canonical path with no behavior change.
Ownership (steering structure SDK zones, product core/plugin ownership): provider-neutral DTOs and this seam live in internal core; provider/frontend semantics stay in adapters/plugins. Core never imports concrete plugins or provider SDKs here (stdlib plus pkg/lipsdk only).
func AsLargeBodyExecutor ¶
func AsLargeBodyExecutor(exec lipsdk.ExecutorView) (LargeBodyExecutor, bool)
AsLargeBodyExecutor safely probes the standard frontend executor for the internal large-body capability. A nil executor or an executor without the capability reports ok=false so the caller continues on the canonical path.
type LargeBodyStaticDispositionProvider ¶
type LargeBodyStaticDispositionProvider interface {
LargeBodyStaticDisposition(profileID string) (StaticWireDisposition, StaticWireReason)
}
LargeBodyStaticDispositionProvider provides an O(1) static wire disposition for a given profile.
type LargeBodyWireExecutor ¶
type LargeBodyWireExecutor interface {
// ExecuteLargeBody runs the accepted wire turn from the bound assessment and
// immutable replay source. It is reachable only after assessment accepts.
ExecuteLargeBody(ctx context.Context, accepted Assessment, src Source) (ExecutionResult, error)
}
LargeBodyWireExecutor runs an accepted wire turn from the bound assessment and immutable replay source (Task 11.1, Requirements 6, 22).
type LateSelectorAssessmentGate ¶
type LateSelectorAssessmentGate struct {
// RouteHints contains optional SDK routehint.Provider instances.
// Providers that do not implement BoundedRouteDomainAuthority consume a full *lipapi.Call
// and are rejected as authority blockers.
RouteHints []routehint.Provider
// RouteHintAuthorities contains explicit route hint authority descriptors.
RouteHintAuthorities []RouteHintAuthority
// SelectorMutators contains explicit selector mutator authority descriptors.
SelectorMutators []SelectorMutatorAuthority
// GenerationValidator validates backends against the active generation.
GenerationValidator *routing.GenerationSelectorValidator
// KnownBackends is the set of backends known to the current generation.
// If GenerationValidator is provided, its KnownBackends is used by default.
KnownBackends map[string]struct{}
// AllowedBackends is an optional subset of allowed backend IDs (e.g. initial candidates).
// If non-nil, contracts targeting backends outside AllowedBackends decline wire.
AllowedBackends map[string]struct{}
// BackendResolver resolves configured backend IDs into WireBackend instances.
BackendResolver WireBackendResolver
}
LateSelectorAssessmentGate evaluates whether other late selector authorities (route hints and selector mutators) are wire-compatible (Task 11.6; Requirements 5, 7, 13, 19).
Invariants (Requirements 5.5, 7.6, 13.2, 13.3, 19.4):
- Full-Call route hints and selector mutators without an explicit bounded route-domain contract are canonical-required blockers and decline wire with DeclineReasonAuthorityBlocker.
- Mutators and route hints with certified bounded contracts are proven within the domain envelope: every target backend must be known and proven wire-compatible.
- Frontend legacy full-body resolver (frontendpipe.Spec.ResolveRouteSelector) is gated pre-capture (Requirement 13.2) and is out of scope here.
- Pure and side-effect-free: strictly zero live store reads, zero network I/O, zero BeginTurn.
func NewLateSelectorAssessmentGate ¶
func NewLateSelectorAssessmentGate( routeHints []routehint.Provider, mutators []SelectorMutatorAuthority, val *routing.GenerationSelectorValidator, backendResolver WireBackendResolver, ) *LateSelectorAssessmentGate
NewLateSelectorAssessmentGate constructs a LateSelectorAssessmentGate.
func (*LateSelectorAssessmentGate) CandidateBackends ¶
func (g *LateSelectorAssessmentGate) CandidateBackends() []string
CandidateBackends returns the sorted set of all backend IDs targeted by configured certified late selector authorities.
func (*LateSelectorAssessmentGate) Evaluate ¶
func (g *LateSelectorAssessmentGate) Evaluate(ctx context.Context, proof Proof) (AssessmentDecision, DeclineReason, WireDomainFacts)
Evaluate evaluates all configured route hints and selector mutators. Returns AssessmentDecisionAccept if all authorities are certified and proven within the domain envelope (or if no late selector authorities are configured).
type LateSelectorAssessor ¶
type LateSelectorAssessor struct {
InitialGate *InitialRouteAssessmentGate
OverrideGate *RouteOverrideAssessmentGate
LateSelectorGate LateSelectorAssessmentGate
AcceptStamp AssessmentStamp
AcceptWireReq WireRequestFacts
AcceptDomain WireDomainFacts
}
LateSelectorAssessor implements LargeBodyAssessor with initial route, route override, and late selector authority gates (Requirements 5, 7, 13, 19).
func NewLateSelectorAssessor ¶
func NewLateSelectorAssessor( initialGate *InitialRouteAssessmentGate, overrideGate *RouteOverrideAssessmentGate, lateSelectorGate LateSelectorAssessmentGate, ) *LateSelectorAssessor
NewLateSelectorAssessor constructs a LateSelectorAssessor.
func (*LateSelectorAssessor) AssessLargeBody ¶
func (a *LateSelectorAssessor) AssessLargeBody(ctx context.Context, proof Proof) (Assessment, error)
AssessLargeBody evaluates proof across initial route, route override, and late selector gates.
type LiveExecutionFacts ¶
type LiveExecutionFacts struct {
GenerationID string
ProfileID string
Source SourceDigest
BodyBytes int64
Mode BodyMode
Rewrite RewriteSemantics
CandidateDomainGeneration string
}
LiveExecutionFacts carries the live execution-time facts that must agree with the bound AssessmentStamp before wire execution can begin (Requirements 6.7, 8.5; Task 11.8).
func (LiveExecutionFacts) Validate ¶
func (f LiveExecutionFacts) Validate(maxFactBytes int64) error
Validate enforces bounds under the semantic-fact budget.
type MessageIdentityWriter ¶
type MessageIdentityWriter struct {
// contains filtered or unexported fields
}
MessageIdentityWriter writes message parts to the identity stream.
func (*MessageIdentityWriter) AddPart ¶
func (m *MessageIdentityWriter) AddPart(part lipapi.Part) error
AddPart appends a completed Part to the message.
func (*MessageIdentityWriter) BeginTextPart ¶
func (m *MessageIdentityWriter) BeginTextPart() (io.WriteCloser, error)
BeginTextPart opens a streaming writer for a Text part.
func (*MessageIdentityWriter) EndMessage ¶
func (m *MessageIdentityWriter) EndMessage() error
EndMessage closes the Parts array and message object.
type NarrowPortEligibilityInput ¶
type NarrowPortEligibilityInput struct {
BackendsEmpty, ConversationViewReaderOccupied, ConversationReaderFreshALegSupported bool
ConversationViewTaggerOccupied, SteeringWriterFactoryOccupied, ExposureAdmissionOccupied bool
BillingIdentityCustomCallbacks, CapsResolverOccupied, CapsResolverWireProofSubsumed bool
CatalogResolverOccupied, EligibilityResolverOccupied, RequestTokenEstimatorOccupied bool
PreflightEnabled, PreflightHasExactCounter, StreamUsageOccupied, AdminCountServiceOccupied bool
InterleavedProcessorOccupied, CompactionDetectorOccupied, CompactionDetectorWireSupported bool
TrafficCapturing, TokenCountingRequired, TokenCountingHasExactCounter, CustomCallCallbacksPresent bool
}
NarrowPortEligibilityInput is the frozen narrow-port occupancy/mode record (Task 3.4). Fields that can never block (bounded knobs, observational sinks, nil-safe coordinators) are omitted: they contribute no eligibility fact. Present-but-model-dependent backend compatibility stays dynamic and is not represented here.
type NoopDiagnosticsObserver ¶
type NoopDiagnosticsObserver struct{}
NoopDiagnosticsObserver implements DiagnosticsObserver with no-op operations.
func (NoopDiagnosticsObserver) OnActiveSpoolBytes ¶
func (NoopDiagnosticsObserver) OnActiveSpoolBytes(uint64, int64)
func (NoopDiagnosticsObserver) OnCapture ¶
func (NoopDiagnosticsObserver) OnCapture(string, StorageKind)
func (NoopDiagnosticsObserver) OnDecline ¶
func (NoopDiagnosticsObserver) OnDecline(string)
func (NoopDiagnosticsObserver) OnPipelineStage ¶
func (NoopDiagnosticsObserver) OnPipelineStage(PipelineStage)
func (NoopDiagnosticsObserver) OnReplay ¶
func (NoopDiagnosticsObserver) OnReplay()
func (NoopDiagnosticsObserver) OnRewrite ¶
func (NoopDiagnosticsObserver) OnRewrite()
func (NoopDiagnosticsObserver) OnStageDuration ¶
func (NoopDiagnosticsObserver) OnStageDuration(string, time.Duration)
type PipelineStage ¶
type PipelineStage string
PipelineStage defines a bounded stage in the large-payload fast path (Task 19.1; Requirements 20, 22; design sections 2, 8).
const ( // StageConsidered marks candidate evaluation entry. StageConsidered PipelineStage = "considered" // StageStaticCanonical marks pre-capture static decline to canonical processing. StageStaticCanonical PipelineStage = "static_canonical" // StageCaptured marks successful body capture into replay storage. StageCaptured PipelineStage = "captured" // StageProfileProven marks successful protocol proof compilation and validation. StageProfileProven PipelineStage = "profile_proven" // StageAssessmentEligible marks side-effect-free assessment acceptance. StageAssessmentEligible PipelineStage = "assessment_eligible" // StageWire marks one-way wire commit execution. StageWire PipelineStage = "wire" // StageCanonical marks canonical pipeline execution (direct or fallback). StageCanonical PipelineStage = "canonical" )
type PlaneAccess ¶
type PlaneAccess uint8
PlaneAccess mirrors pkg/lipsdk/feature.RequestBodyAccess without importing the plane registry: the compiler stays leaf-pure and the composition mapper converts explicitly. Numeric values and static labels match exactly; TestWireEligibility_PlaneAccessParityWithFeature pins the parity.
const ( // PlaneAccessUnclassified is the zero value: no wire classification. // It fails compilation so a new or unannotated plane fails closed. PlaneAccessUnclassified PlaneAccess = iota // PlaneAccessCanonicalRequired marks planes receiving or mutating the // full canonical request: occupied blocks the wire lane in V1. PlaneAccessCanonicalRequired // PlaneAccessMetadataOnly marks planes carrying only bounded // session/workspace/int metadata. PlaneAccessMetadataOnly // PlaneAccessResponseOnly marks planes operating on canonical output // events only. PlaneAccessResponseOnly // PlaneAccessWireContract marks planes carrying an explicit certified // wire contract. None exists in V1; the value is accepted so a future // certified contract does not read as unknown. PlaneAccessWireContract )
func (PlaneAccess) String ¶
func (a PlaneAccess) String() string
String returns a bounded static label for metrics/diagnostics.
type PlaneEligibilityInput ¶
type PlaneEligibilityInput struct {
ID string
Access PlaneAccess
Occupied bool
}
PlaneEligibilityInput is one frozen plane fact: stable ID, V1 access class, and generation occupancy. The slice must cover exactly the 28 known planes in any order; unknown, duplicate, missing, or unclassified entries fail compilation.
type PortDependency ¶
type PortDependency struct {
Name string
Class DependencyClass
Occupied bool
}
PortDependency represents one narrow port or callback fact in the dependency census.
type Proof ¶
type Proof struct {
ProfileID string
Operation lipapi.Operation
Delivery lipapi.DeliveryMode
RouteSelector string
ClientModel string
MaxOutputTokens int64
Facts ProtocolFacts
Mode BodyMode
Rewrite RewriteSemantics
ModelSpan Span
Identity IdentityDigest
Turn ClientTurnShape
Session SessionInput
Source SourceDigest
BodyBytes int64
CompactionFacts compactionfacts.RequestFacts
CompactionComplete bool
RequiredCapabilities []lipapi.Capability
}
Proof is the bounded frontend profile proof over the validated replay stream (design section 6). Every field has a named downstream consumer; this must never grow into a shadow lipapi.Call (design section 11).
func (Proof) AggregateFactBytes ¶
AggregateFactBytes returns the aggregate in-memory byte size of proof metadata and compaction facts.
func (Proof) CompactionDigest ¶
CompactionDigest returns the deterministic digest of the compaction facts and completeness.
type ProtocolFacts ¶
ProtocolFacts carries profile-certified protocol requirements as bounded scalar facts (design section 6). RequirementsID is a bounded static profile-defined requirement-set label (never user/model/session text); ControlCount counts certified control carriers, never prompt content.
func (ProtocolFacts) Validate ¶
func (f ProtocolFacts) Validate(maxFactBytes int64) error
Validate enforces scalar bounds under the semantic-fact budget.
type ReplayChunkReaderConfig ¶
type ReplayChunkReaderConfig struct {
Reader io.Reader
MaxBytes int64
ChunkSize int
Scanner *jsonshape.Scanner
Hasher hash.Hash
OnChunk func(chunk []byte) error
}
ReplayChunkReaderConfig configures reading replay bytes in fixed-size buffers.
type ReplayChunkReaderResult ¶
ReplayChunkReaderResult summarizes the outcome of reading replay chunks.
func ProcessReplayChunks ¶
func ProcessReplayChunks(cfg ReplayChunkReaderConfig) (ReplayChunkReaderResult, error)
ProcessReplayChunks reads replay bytes from Reader in fixed-size buffers (default 32 KiB), simultaneously streaming them into Hasher (if non-nil), Scanner (if non-nil), and OnChunk (if non-nil) in one pass without calling io.ReadAll. It enforces MaxBytes if > 0.
type ResponseFacts ¶
type ResponseFacts struct {
RequestID string
TraceID string
ALegID string
SessionID string
Operation lipapi.Operation
Delivery lipapi.DeliveryMode
EffectiveModel string
Source SourceDigest
BodyBytes int64
RewrittenLength int64
}
ResponseFacts carries bounded provider-neutral response facts for frontend wrapping/encoding (Requirement 18.2): request/trace identity, A-leg/session facts, operation/delivery, and replay/rewrite evidence. The sensitive session-response carrier travels separately.
func (ResponseFacts) Validate ¶
func (f ResponseFacts) Validate(maxFactBytes int64) error
Validate enforces identity presence and bounds.
type RewriteKind ¶
type RewriteKind uint8
RewriteKind classifies the certified rewrite applied to one attempt.
const ( // RewriteKindNone means the captured bytes are forwarded unchanged. RewriteKindNone RewriteKind = iota // RewriteKindModelToken means the scanner-recorded top-level model token // span is spliced with a JSON-encoded replacement model. RewriteKindModelToken )
func (RewriteKind) String ¶
func (k RewriteKind) String() string
String returns a bounded static label for metrics/diagnostics.
type RewritePlan ¶
type RewritePlan struct {
Rewrite RewriteSemantics
ReplacementModel string
RewrittenLength int64
}
RewritePlan is the per-attempt certified splice: exact scanner span plus JSON-encoded replacement model plus the checked rewritten body length. A splice reader emits prefix + replacement + suffix without a second full body (Requirement 9.3).
func (RewritePlan) Validate ¶
func (p RewritePlan) Validate(maxFactBytes int64) error
Validate requires certified rewrite semantics, a bounded replacement model, and a positive rewritten length.
type RewriteSemantics ¶
type RewriteSemantics struct {
// contains filtered or unexported fields
}
RewriteSemantics is the immutable certified rewrite contract passed to every backend exact/domain resolver (design section 9). A resolver may declare NeedsModelRewrite only when the profile certified it here; the flag can never grant an uncertified transformation.
func NewModelTokenRewrite ¶
func NewModelTokenRewrite(span Span) (RewriteSemantics, error)
NewModelTokenRewrite returns the immutable model-token splice contract for an exact, non-empty scanner-recorded span.
func NewNoRewrite ¶
func NewNoRewrite() RewriteSemantics
NewNoRewrite returns the immutable no-rewrite contract.
func (RewriteSemantics) Kind ¶
func (r RewriteSemantics) Kind() RewriteKind
Kind reports the certified rewrite kind.
func (RewriteSemantics) NeedsModelRewrite ¶
func (r RewriteSemantics) NeedsModelRewrite() bool
NeedsModelRewrite reports whether attempts must splice a replacement model.
func (RewriteSemantics) Span ¶
func (r RewriteSemantics) Span() Span
Span returns the certified rewrite span (meaningful for model-token rewrites).
func (RewriteSemantics) String ¶
func (r RewriteSemantics) String() string
String returns a bounded description of the certified rewrite semantics.
func (RewriteSemantics) Validate ¶
func (r RewriteSemantics) Validate() error
Validate rejects unknown kinds and invalid spans.
type RouteHintAuthority ¶
type RouteHintAuthority struct {
ID string
Provider routehint.Provider
HasFullCallAccess bool
Contract *BoundedRouteDomainContract
}
RouteHintAuthority describes a route hint authority for wire assessment (Requirement 7.6).
type RouteOverrideAssessmentGate ¶
type RouteOverrideAssessmentGate struct {
// OverrideReader is the optional narrow route-override snapshot reader.
// When nil, route overrides are not configured and the gate accepts with no domain.
// When non-nil, its presence alone must not block; the gate derives the legal
// envelope without calling Snapshot or reading the store.
OverrideReader routeoverride.Reader
// GenerationValidator encapsulates the route validation policy of the active generation.
GenerationValidator *routing.GenerationSelectorValidator
// KnownBackends is the set of backends known to the current generation.
// If GenerationValidator is provided, its KnownBackends is used by default.
KnownBackends map[string]struct{}
// ExecutionCompositionPolicy is the generation's execution composition policy.
// BackendExecutionResolver resolves backend execution classes.
// Both are carried for constructor symmetry with the generation validator;
// execution-mode domain narrowing is 11.7 scope. The 11.5 envelope treats
// every known backend as a legal post-override target (exact set, not a superset).
ExecutionCompositionPolicy config.ExecutionCompositionPolicy
BackendExecutionResolver routing.BackendExecutionResolver
// BackendResolver resolves configured backend IDs into WireBackend instances
// for pure domain support checks.
BackendResolver WireBackendResolver
// CandidateModels specifies an optional finite model catalog.
// When empty/nil, the model domain is unbounded (UniversalModel: true)
// and requires backend universal proof (AnyAcceptedModel).
CandidateModels []string
}
RouteOverrideAssessmentGate evaluates whether the late route-override compatibility envelope derived from generation validator, known backends, and execution composition policy is wire-compatible across all legal outcomes (Task 11.5; Requirements 7, 8).
Invariants (Requirements 6.2, 7.1, 7.2, 7.3, 7.5, 8.2, 8.3, 8.4, 8.5): - Mere presence of RouteOverrideReader shall NOT automatically block. - Pure and side-effect-free: strictly ZERO live store reads (no Snapshot/Get calls). - Derives all legal outcomes from generation validator + known backends + execution policy. - Unbounded override model domain requires universal backend proof (AnyAcceptedModel); otherwise decline. - Any incompatible candidate backend declines the entire request (no candidate pruning).
func NewRouteOverrideAssessmentGate ¶
func NewRouteOverrideAssessmentGate( reader routeoverride.Reader, val *routing.GenerationSelectorValidator, backendResolver WireBackendResolver, ) *RouteOverrideAssessmentGate
NewRouteOverrideAssessmentGate constructs a RouteOverrideAssessmentGate.
func (*RouteOverrideAssessmentGate) CandidateBackends ¶
func (g *RouteOverrideAssessmentGate) CandidateBackends() []string
CandidateBackends returns the sorted set of all backend IDs that can legally be selected by a post-commit route override under this generation's validator. Returns nil if KnownBackends is unconstrained (nil).
func (*RouteOverrideAssessmentGate) Evaluate ¶
func (g *RouteOverrideAssessmentGate) Evaluate(ctx context.Context, proof Proof) (AssessmentDecision, DeclineReason, WireDomainFacts)
Evaluate derives the legal post-override outcome envelope and verifies pure wire domain support across all legal outcomes WITHOUT reading the live store.
type RouteOverrideAssessor ¶
type RouteOverrideAssessor struct {
InitialGate *InitialRouteAssessmentGate
OverrideGate RouteOverrideAssessmentGate
LateSelectorGate *LateSelectorAssessmentGate
AcceptStamp AssessmentStamp
AcceptWireReq WireRequestFacts
}
RouteOverrideAssessor implements LargeBodyAssessor using RouteOverrideAssessmentGate and an optional InitialRouteAssessmentGate (Requirements 7, 8).
func NewRouteOverrideAssessor ¶
func NewRouteOverrideAssessor( initialGate *InitialRouteAssessmentGate, overrideGate RouteOverrideAssessmentGate, ) *RouteOverrideAssessor
NewRouteOverrideAssessor constructs a RouteOverrideAssessor.
func (*RouteOverrideAssessor) AssessLargeBody ¶
func (a *RouteOverrideAssessor) AssessLargeBody(ctx context.Context, proof Proof) (Assessment, error)
AssessLargeBody evaluates proof through the initial route gate (if configured), the route override assessment gate, and the late selector gate (if configured).
type SafeDiagnosticsObserver ¶
type SafeDiagnosticsObserver struct {
// contains filtered or unexported fields
}
SafeDiagnosticsObserver wraps a DiagnosticsObserver and guards against nil receivers.
func (*SafeDiagnosticsObserver) OnActiveSpoolBytes ¶
func (s *SafeDiagnosticsObserver) OnActiveSpoolBytes(seq uint64, bytes int64)
func (*SafeDiagnosticsObserver) OnCapture ¶
func (s *SafeDiagnosticsObserver) OnCapture(sizeBucket string, storage StorageKind)
func (*SafeDiagnosticsObserver) OnDecline ¶
func (s *SafeDiagnosticsObserver) OnDecline(reason string)
func (*SafeDiagnosticsObserver) OnPipelineStage ¶
func (s *SafeDiagnosticsObserver) OnPipelineStage(stage PipelineStage)
func (*SafeDiagnosticsObserver) OnReplay ¶
func (s *SafeDiagnosticsObserver) OnReplay()
func (*SafeDiagnosticsObserver) OnRewrite ¶
func (s *SafeDiagnosticsObserver) OnRewrite()
func (*SafeDiagnosticsObserver) OnStageDuration ¶
func (s *SafeDiagnosticsObserver) OnStageDuration(stage string, d time.Duration)
type ScanningWireCounter ¶
type ScanningWireCounter struct {
CountFunc func(ctx context.Context, model string, r io.Reader) (int, error)
}
ScanningWireCounter implements WireCounter by streaming replay bytes through a token counting function without constructing a full lipapi.Call.
func NewScanningWireCounter ¶
func NewScanningWireCounter(fn func(ctx context.Context, model string, r io.Reader) (int, error)) *ScanningWireCounter
NewScanningWireCounter constructs a ScanningWireCounter with the given count function.
func (*ScanningWireCounter) CountWire ¶
func (s *ScanningWireCounter) CountWire(ctx context.Context, in WireCountInput) (WireCountResult, error)
CountWire scans replay bytes from the source and emits exact token counts.
type SelectorMutatorAuthority ¶
type SelectorMutatorAuthority struct {
ID string
HasFullCallAccess bool
Contract *BoundedRouteDomainContract
}
SelectorMutatorAuthority describes a selector mutator authority for wire assessment (Requirement 7.6, 13.3).
type SensitiveString ¶
type SensitiveString struct {
// contains filtered or unexported fields
}
SensitiveString is an opaque bearer value (resume tokens) that must never reach backends, telemetry, logs, or metrics (Requirements 14, 22). Every default rendering is redacted; the owning frontend extracts the value via Reveal to emit authoritative session/resume headers.
func NewSensitiveString ¶
func NewSensitiveString(value string) SensitiveString
NewSensitiveString wraps a bearer value without exposing it.
func (SensitiveString) ByteLen ¶
func (s SensitiveString) ByteLen() int
ByteLen returns the length of the sensitive string in bytes without formatting or revealing it.
func (SensitiveString) Format ¶
func (s SensitiveString) Format(f fmt.State, _ rune)
Format redacts the value for every verb.
func (SensitiveString) GoString ¶
func (s SensitiveString) GoString() string
GoString redacts the value.
func (SensitiveString) IsZero ¶
func (s SensitiveString) IsZero() bool
IsZero reports whether no value is wrapped.
func (SensitiveString) MarshalJSON ¶
func (s SensitiveString) MarshalJSON() ([]byte, error)
MarshalJSON redacts the value.
func (SensitiveString) MarshalText ¶
func (s SensitiveString) MarshalText() ([]byte, error)
MarshalText redacts the value.
func (SensitiveString) Reveal ¶
func (s SensitiveString) Reveal() string
Reveal returns the wrapped value for the owning frontend boundary.
type SessionInput ¶
type SessionInput struct {
AuthoritativeSessionID string
ClientSessionID string
ALegID string
ResumeToken SensitiveString
NewSessionRequested bool
}
SessionInput carries the exact bounded client/session authority inputs that canonical BeginTurn receives, sourced through normal frontend/header/body precedence (Requirement 14.1). The resume token is sensitive: it never reaches backends or telemetry.
func BuildSessionInput ¶
func BuildSessionInput(src SessionInputSource, maxFactBytes int64) (SessionInput, error)
BuildSessionInput builds an exact bounded SessionInput from raw source inputs. It enforces:
- Header-over-body precedence for authoritative session ID and resume token (Requirement 14.1);
- Rejection of body-carried LIP session metadata when RejectBodyMetadata is true (Requirements 14.2, 17.5);
- Bounded sizes under lipapi envelope caps and semantic-fact budget;
- SensitiveString wrapping for resume tokens so they never leak into telemetry or backends (Requirements 14.1, 22);
- Accurate NewSessionRequested determination (true when both authoritative session ID and resume token are empty).
func SessionInputFromRef ¶
func SessionInputFromRef(ref lipapi.SessionRef) SessionInput
SessionInputFromRef constructs a SessionInput from a canonical lipapi.SessionRef.
func WireSessionInputFromContext ¶
func WireSessionInputFromContext(ctx context.Context) (SessionInput, bool)
WireSessionInputFromContext extracts SessionInput from ctx if attached.
func (SessionInput) CorrelationID ¶
func (s SessionInput) CorrelationID() string
CorrelationID returns a stable identifier for diagnostics and traffic capture: authoritative session ID when set, otherwise client session ID.
func (SessionInput) Format ¶
func (s SessionInput) Format(f fmt.State, _ rune)
Format ensures that even under custom fmt verbs, the resume token is never printed.
func (SessionInput) GoString ¶
func (s SessionInput) GoString() string
GoString implements fmt.GoStringer.
func (SessionInput) LogValue ¶
func (s SessionInput) LogValue() slog.Value
LogValue implements slog.LogValuer to ensure resume tokens are never logged.
func (SessionInput) MarshalJSON ¶
func (s SessionInput) MarshalJSON() ([]byte, error)
MarshalJSON redacts the resume token while preserving presence signals.
func (SessionInput) ProvesFreshALeg ¶
func (s SessionInput) ProvesFreshALeg() bool
ProvesFreshALeg reports whether the session input definitely proves a fresh, unresumed A-leg. Returns true only when NewSessionRequested is true, AuthoritativeSessionID is empty, ALegID is empty, and ResumeToken is zero or empty.
func (SessionInput) SessionRef ¶
func (s SessionInput) SessionRef() lipapi.SessionRef
SessionRef converts the bounded SessionInput into a canonical lipapi.SessionRef.
func (SessionInput) String ¶
func (s SessionInput) String() string
String implements fmt.Stringer to ensure resume tokens are never formatted.
func (SessionInput) Validate ¶
func (s SessionInput) Validate(maxFactBytes int64) error
Validate enforces scalar bounds under the semantic-fact budget.
type SessionInputSource ¶
type SessionInputSource struct {
HeaderAuthoritativeSessionID string
HeaderResumeToken string
HeaderALegID string
HeaderClientSessionHint string
BodyAuthoritativeSessionID string
BodyResumeToken string
HasBodySessionMetadata bool
RejectBodyMetadata bool
}
SessionInputSource carries raw candidate session values from inbound HTTP headers and body metadata before precedence and bounds enforcement.
type SessionResponseCarrier ¶
type SessionResponseCarrier struct {
AuthoritativeSessionID string
ALegID string
ResumeToken SensitiveString
}
SessionResponseCarrier returns new-session BeginTurn response values to the frontend: authoritative session ID, A-leg ID, and the raw resume token (design section 10, Requirement 14.6). Values are never metrics labels/log fields and are released with request lifetime (Requirements 14.7, 22.3): every default rendering is redacted and the frontend extracts values explicitly for session/resume headers.
func (SessionResponseCarrier) Format ¶
func (c SessionResponseCarrier) Format(f fmt.State, _ rune)
Format renders presence signals only for every verb.
func (SessionResponseCarrier) GoString ¶
func (c SessionResponseCarrier) GoString() string
GoString renders presence signals only; values stay redacted.
func (SessionResponseCarrier) MarshalJSON ¶
func (c SessionResponseCarrier) MarshalJSON() ([]byte, error)
MarshalJSON emits presence signals only; values stay redacted.
func (SessionResponseCarrier) String ¶
func (c SessionResponseCarrier) String() string
String renders presence signals only; values stay redacted.
func (SessionResponseCarrier) Validate ¶
func (c SessionResponseCarrier) Validate(maxFactBytes int64) error
Validate enforces bounds under the semantic-fact budget.
type Source ¶
type Source interface {
// Size reports the exact captured body size in bytes.
Size() int64
// Open returns an independent offset-zero reader over the capture.
Open() (io.ReadCloser, error)
// Close releases the root capture; it is idempotent.
Close() error
}
Source is an immutable completed replay capture (design section 5). After EOF the source exposes independent offset-zero readers; each provider/credential retry opens and closes a fresh reader. The concrete spool implementation (Task 4) lives elsewhere; this is the contract seam.
type SourceDigest ¶
type SourceDigest struct {
// contains filtered or unexported fields
}
SourceDigest is the replay/attempt source-integrity evidence. It is explicitly not a substitute for canonical identity (Requirement 16.5, design section 6).
func NewSourceDigest ¶
func NewSourceDigest(sum [32]byte) SourceDigest
NewSourceDigest wraps an already-computed source integrity sum.
func (SourceDigest) IsZero ¶
func (d SourceDigest) IsZero() bool
IsZero reports whether no sum was provided.
func (SourceDigest) String ¶
func (d SourceDigest) String() string
String renders the sum as hex for diagnostics.
type Span ¶
Span is an exact raw byte range inside the captured body, used for certified rewrite splices such as the top-level model token (Requirements 4, 9).
type SpillBuffer ¶
type SpillBuffer struct {
// contains filtered or unexported fields
}
SpillBuffer provides bounded RAM capture with secure temporary file spill (Requirements 20; design section 5).
Invariants (Task 4.2; Requirements 20.1, 20.2, 20.6, 20.9, 20.10):
- Memory retained in Go heap is bounded by configured MemorySpoolBytes plus a fixed reusable copy buffer; it never uses a payload-growing bytes.Buffer.
- Excess bytes spill to an unpredictable file name (crypto/rand hex, no prompt/ session/model metadata) with restrictive permissions (0600 where supported).
- Preserves the current chunk/unwritten suffix if a write fails or is short, ensuring no bytes read from the client socket are discarded (Requirement 20.6).
- Root Close() is idempotent and nonblocking; if readers are active, deletion is marked pending and removal occurs when tracked readers close (Requirement 20.9).
- Incrementally hashes committed writes (SHA-256) during capture writes (Task 4.5; Requirements 15, 16.5, 20).
- Thread-safe for concurrent read/close operations.
func NewSpillBuffer ¶
func NewSpillBuffer(cfg SpillConfig) (*SpillBuffer, error)
NewSpillBuffer validates configuration and constructs an initialized SpillBuffer.
func (*SpillBuffer) ActiveReaders ¶
func (b *SpillBuffer) ActiveReaders() int
ActiveReaders reports the current count of open readers.
func (*SpillBuffer) BytesWritten ¶
func (b *SpillBuffer) BytesWritten() int64
BytesWritten reports total committed bytes across memory and spill storage.
func (*SpillBuffer) Close ¶
func (b *SpillBuffer) Close() error
Close releases the spill buffer (implements io.Closer and Source).
Invariants (Requirement 20.9):
- Idempotent and nonblocking.
- Releases the associated spool reservation back to the ledger.
- Closes the write file handle immediately.
- If active readers exist, deletion is marked pending and final removal occurs when the last reader closes (Windows open-file safety).
func (*SpillBuffer) Complete ¶
func (b *SpillBuffer) Complete() (*CompletedSource, error)
Complete transitions the SpillBuffer into an immutable CompletedSource (Requirements 10, 20; design section 5). It syncs and closes the write file handle (if any), shrinks the spool reservation to actual bytes written, binds the incrementally computed SourceDigest, seals the buffer against further writes, and returns the immutable CompletedSource.
func (*SpillBuffer) DetachReservation ¶
func (b *SpillBuffer) DetachReservation() *SpoolReservation
DetachReservation releases association with the reservation and returns it, transferring ownership to the caller.
func (*SpillBuffer) Digest ¶
func (b *SpillBuffer) Digest() SourceDigest
Digest returns the running source integrity digest computed over all bytes committed so far (Requirements 15, 16, 20; design section 5). It returns a zero SourceDigest if no bytes have been written yet.
func (*SpillBuffer) FileBytes ¶
func (b *SpillBuffer) FileBytes() int64
FileBytes reports the count of bytes spilled to secondary storage.
func (*SpillBuffer) FilePath ¶
func (b *SpillBuffer) FilePath() string
FilePath reports the spill file path, or empty string if not spilled.
func (*SpillBuffer) GoString ¶
func (b *SpillBuffer) GoString() string
GoString implements fmt.GoStringer without leaking internal fields, prompt content, or filesystem paths.
func (*SpillBuffer) HasSpilled ¶
func (b *SpillBuffer) HasSpilled() bool
HasSpilled reports whether any bytes have spilled to secondary storage.
func (*SpillBuffer) HasUnwrittenSuffix ¶
func (b *SpillBuffer) HasUnwrittenSuffix() bool
HasUnwrittenSuffix reports whether an unwritten suffix is currently held.
func (*SpillBuffer) IsCompleted ¶
func (b *SpillBuffer) IsCompleted() bool
IsCompleted reports whether the buffer has been transitioned to a CompletedSource.
func (*SpillBuffer) IsDeletePending ¶
func (b *SpillBuffer) IsDeletePending() bool
IsDeletePending reports whether file deletion is deferred until all readers close.
func (*SpillBuffer) MemoryBytes ¶
func (b *SpillBuffer) MemoryBytes() []byte
MemoryBytes returns the in-memory portion of the captured body.
func (*SpillBuffer) Open ¶
func (b *SpillBuffer) Open() (io.ReadCloser, error)
Open returns an independent offset-zero reader over the captured body (implements Source). Multiple readers can be opened concurrently and read independently.
func (*SpillBuffer) ReadFrom ¶
func (b *SpillBuffer) ReadFrom(r io.Reader) (int64, error)
ReadFrom reads from r until EOF or error using a fixed reusable copy buffer. It never allocates a payload-growing buffer (Requirement 20.1).
func (*SpillBuffer) Reservation ¶
func (b *SpillBuffer) Reservation() *SpoolReservation
Reservation returns the associated spool reservation, or nil if none.
func (*SpillBuffer) ShrinkReservation ¶
func (b *SpillBuffer) ShrinkReservation() error
ShrinkReservation shrinks the associated logical spool reservation to the actual bytes committed, returning any over-reserved budget back to the global ledger.
func (*SpillBuffer) Size ¶
func (b *SpillBuffer) Size() int64
Size reports the exact captured body size in bytes (implements Source).
func (*SpillBuffer) SourceDigest ¶
func (b *SpillBuffer) SourceDigest() SourceDigest
SourceDigest returns the running source integrity digest computed so far.
func (*SpillBuffer) String ¶
func (b *SpillBuffer) String() string
String returns a bounded diagnostic representation without leaking prompt content, model names, or filesystem paths (Requirement 20.3).
func (*SpillBuffer) TakeUnwrittenSuffix ¶
func (b *SpillBuffer) TakeUnwrittenSuffix() []byte
TakeUnwrittenSuffix returns the unwritten suffix and clears it from the buffer, transferring ownership to the caller (e.g. for canonical continuation).
func (*SpillBuffer) UnwrittenSuffix ¶
func (b *SpillBuffer) UnwrittenSuffix() []byte
UnwrittenSuffix returns any unwritten portion of the last chunk from a failed or short write (Requirement 20.6).
func (*SpillBuffer) Write ¶
func (b *SpillBuffer) Write(p []byte) (int, error)
Write writes p to the bounded buffer. If within MemorySpoolBytes, p is appended to the in-memory buffer. Excess bytes are spilled to a secure temporary file.
Invariants (Requirement 20.6): If the write fails or is short, the unwritten portion of p is preserved in UnwrittenSuffix() and can be recovered for canonical continuation.
type SpillConfig ¶
type SpillConfig struct {
// SpoolDir is the directory where temporary spill files are created.
// If empty, the OS default temp directory is used (Requirement 20.2;
// config.LargePayloadFastPathConfig.EffectiveSpoolDir).
SpoolDir string
// MemorySpoolBytes bounds retained request bytes in Go heap before spilling
// excess bytes to secondary storage. If 0, all data is spilled directly to disk.
// Must be >= 0 (Requirement 20.1).
MemorySpoolBytes int64
// CopyBufferSize is the size in bytes of the fixed reusable copy buffer
// used for streaming reads. If <= 0, DefaultCopyBufferSize (32 KiB) is used.
CopyBufferSize int
// Reservation is an optional logical spool reservation used for budget
// accounting (Task 4.1, Requirement 20.4). If nil, no reservation ledger
// accounting is performed.
Reservation *SpoolReservation
// CreateFile optionally overrides spill file creation (for fault injection).
CreateFile func(dir string) (SpillFile, string, error)
// OpenFile optionally overrides opening the spill file for readers.
OpenFile func(path string) (io.ReadCloser, error)
// RemoveFile optionally overrides spill file deletion.
RemoveFile func(path string) error
}
SpillConfig configures bounded RAM + secure spill capture (Requirements 20; design section 5).
type SpillFile ¶
SpillFile represents the file abstraction used for spill storage. It is implemented directly by *os.File in production and can be substituted for fault injection in tests (Requirement 20.10).
type SpliceReader ¶
type SpliceReader struct {
// contains filtered or unexported fields
}
SpliceReader streams a spliced body (prefix + replacement + suffix) without constructing a second full body in memory (Requirements 9.3, 9.4). It implements io.Reader, io.Closer, io.ReadCloser, and io.WriterTo.
func SpliceModelToken ¶
func SpliceModelToken(source any, span Span, replacement string) (*SpliceReader, error)
SpliceModelToken constructs a streaming SpliceReader for source, replacing span with the JSON-encoded replacement model (Requirements 9.1–9.4).
Supported source types:
- []byte
- string
- Source (largebody.Source)
- *CompletedSource
- *SpillBuffer
- io.ReadSeeker (with known size or seekable)
- io.ReaderAt (with Size() int64)
func SpliceModelTokenAt ¶
func SpliceModelTokenAt(r io.ReaderAt, sourceSize int64, span Span, replacement string) (*SpliceReader, error)
SpliceModelTokenAt creates a streaming SpliceReader from an io.ReaderAt with known sourceSize.
func SpliceModelTokenPlan ¶
func SpliceModelTokenPlan(source any, plan RewritePlan, maxFactBytes int64) (*SpliceReader, error)
SpliceModelTokenPlan applies a certified RewritePlan to a source. It verifies that the plan is valid, uses plan.Rewrite.Span(), encodes plan.ReplacementModel, and asserts that the computed rewritten length matches plan.RewrittenLength (Requirements 9.1–9.4).
func SpliceModelTokenReader ¶
func SpliceModelTokenReader(r io.Reader, sourceSize int64, span Span, replacement string) (*SpliceReader, error)
SpliceModelTokenReader creates a streaming SpliceReader from an arbitrary io.Reader with known sourceSize.
func (*SpliceReader) Close ¶
func (s *SpliceReader) Close() error
Close releases the underlying source reader if it implements io.Closer.
func (*SpliceReader) Read ¶
func (s *SpliceReader) Read(p []byte) (int, error)
Read implements io.Reader, streaming the prefix, replacement, and suffix in sequence.
func (*SpliceReader) ReplacementBytes ¶
func (s *SpliceReader) ReplacementBytes() []byte
ReplacementBytes returns a copy of the JSON-encoded replacement bytes.
func (*SpliceReader) ReplacementToken ¶
func (s *SpliceReader) ReplacementToken() string
ReplacementToken returns the JSON-encoded replacement token as a string.
func (*SpliceReader) RewrittenLength ¶
func (s *SpliceReader) RewrittenLength() int64
RewrittenLength reports the exact checked rewritten body length in bytes (Requirement 9.4).
func (*SpliceReader) SourceSize ¶
func (s *SpliceReader) SourceSize() int64
SourceSize reports the original source body length in bytes.
func (*SpliceReader) Span ¶
func (s *SpliceReader) Span() Span
Span reports the exact scanner span being replaced.
type SpoolBudgetConfig ¶
type SpoolBudgetConfig struct {
// MemorySpoolBytes bounds retained request bytes in Go heap per capture
// before spilling to secondary storage.
MemorySpoolBytes int64
// MaxInflightSpoolBytes bounds global logical spool reservations across
// all concurrent in-flight captures. This is an optimization budget only.
MaxInflightSpoolBytes int64
}
SpoolBudgetConfig configures the logical spool ledger budgets (Requirements 1, 20, 21; design sections 3, 5).
type SpoolLedger ¶
type SpoolLedger struct {
// contains filtered or unexported fields
}
SpoolLedger tracks global in-flight logical spool reservations (Task 4.1). It acts as the pure reservation accounting ledger for large-payload capture. All operations use checked int64 math and are safe for concurrent use.
func NewSpoolLedger ¶
func NewSpoolLedger(cfg SpoolBudgetConfig) (*SpoolLedger, error)
NewSpoolLedger validates budget configuration and constructs a SpoolLedger. MaxInflightSpoolBytes must be > 0. MemorySpoolBytes must be >= 0 and <= MaxInflightSpoolBytes.
func (*SpoolLedger) ActiveReservations ¶
func (l *SpoolLedger) ActiveReservations() int64
ActiveReservations reports the count of currently unreleased reservations.
func (*SpoolLedger) AvailableBytes ¶
func (l *SpoolLedger) AvailableBytes() int64
AvailableBytes reports remaining available capacity before budget exhaustion.
func (*SpoolLedger) BeginReservation ¶
func (l *SpoolLedger) BeginReservation() (*SpoolReservation, error)
BeginReservation is a convenience alias for Reserve(0) for unknown/chunked captures.
func (*SpoolLedger) InflightBytes ¶
func (l *SpoolLedger) InflightBytes() int64
InflightBytes reports the total bytes currently reserved across all active captures.
func (*SpoolLedger) MaxInflightSpoolBytes ¶
func (l *SpoolLedger) MaxInflightSpoolBytes() int64
MaxInflightSpoolBytes reports the configured global in-flight budget limit.
func (*SpoolLedger) MemorySpoolBytes ¶
func (l *SpoolLedger) MemorySpoolBytes() int64
MemorySpoolBytes reports the configured per-capture memory ceiling.
func (*SpoolLedger) Reserve ¶
func (l *SpoolLedger) Reserve(knownBytes int64) (*SpoolReservation, error)
Reserve allocates an initial logical spool reservation for a known body length (e.g. Content-Length for identity JSON) or 0 for an unknown/chunked stream.
If requested bytes exceed available capacity, ErrSpoolBudgetExhausted is returned without allocating. Negative bytes or int64 overflow return ErrInvalidReservation.
func (*SpoolLedger) SetObserver ¶
func (l *SpoolLedger) SetObserver(obs SpoolObserver)
SetObserver sets an optional observer to receive active spool byte updates. If obs is non-nil, it is immediately notified of the current active spool bytes.
type SpoolObserver ¶
SpoolObserver receives active spool byte updates from SpoolLedger.
type SpoolReservation ¶
type SpoolReservation struct {
// contains filtered or unexported fields
}
SpoolReservation represents an active logical reservation against a SpoolLedger. It tracks reserved bytes, provides checked incremental growth, and guarantees exact-once release on fallback/success/cancel/error (Requirement 20.4).
func (*SpoolReservation) MemoryBytes ¶
func (r *SpoolReservation) MemoryBytes() int64
MemoryBytes reports how many of the reserved bytes reside within the in-memory window.
func (*SpoolReservation) MemorySpoolBytes ¶
func (r *SpoolReservation) MemorySpoolBytes() int64
MemorySpoolBytes reports the per-capture memory budget threshold for this reservation.
func (*SpoolReservation) Release ¶
func (r *SpoolReservation) Release() int64
Release frees all reserved bytes held by this reservation back to the ledger and decrements the active reservation count.
Release is idempotent and safe for concurrent use: exactly one call frees the reservation and returns the number of bytes released. Subsequent calls return 0.
func (*SpoolReservation) ReserveMore ¶
func (r *SpoolReservation) ReserveMore(additionalBytes int64) error
ReserveMore increments the reservation by additionalBytes using checked int64 math. Used as chunks arrive during streaming/chunked capture.
If the requested growth exceeds the ledger's budget, ErrSpoolBudgetExhausted is returned. Crucially, previously reserved bytes remain held so that retained prefix memory/spill remains accounted for during canonical continuation (Requirements 1.4, 20.6, 20.7).
func (*SpoolReservation) ReservedBytes ¶
func (r *SpoolReservation) ReservedBytes() int64
ReservedBytes reports the total bytes currently reserved by this reservation.
func (*SpoolReservation) ShrinkTo ¶
func (r *SpoolReservation) ShrinkTo(finalBytes int64) error
ShrinkTo reduces the reservation down to finalBytes using checked int64 math, returning the difference to the ledger. finalBytes must be >= 0 and <= ReservedBytes().
func (*SpoolReservation) SpillBytes ¶
func (r *SpoolReservation) SpillBytes() int64
SpillBytes reports how many of the reserved bytes exceed the memory ceiling and spill.
type StampInvariantError ¶
StampInvariantError details which specific field of the AssessmentStamp disagreed with live execution facts. It wraps ErrStampDisagreement so errors.Is(err, ErrStampDisagreement) evaluates to true, signaling a terminal invariant failure (Requirement 6.7).
func (*StampInvariantError) Error ¶
func (e *StampInvariantError) Error() string
Error formats the disagreement for telemetry and invariant logging.
func (*StampInvariantError) IsInvariantFailure ¶
func (e *StampInvariantError) IsInvariantFailure() bool
IsInvariantFailure reports whether this error represents an internal invariant failure that must never trigger canonical fallback (Requirement 6.6, 6.7).
func (*StampInvariantError) Unwrap ¶
func (e *StampInvariantError) Unwrap() error
Unwrap returns ErrStampDisagreement for error classification.
type StampValidatingExecutor ¶
type StampValidatingExecutor struct {
LiveFacts LiveExecutionFacts
LiveProvider func() LiveExecutionFacts
Delegate LargeBodyWireExecutor
}
StampValidatingExecutor wraps a LargeBodyWireExecutor (or acts standalone) to enforce assessment stamp revalidation against live execution facts at ExecuteLargeBody time (Requirements 6.6, 6.7, 8.5; Task 11.8).
func NewStampValidatingExecutor ¶
func NewStampValidatingExecutor(live LiveExecutionFacts, delegate LargeBodyWireExecutor) *StampValidatingExecutor
NewStampValidatingExecutor constructs a StampValidatingExecutor.
func (*StampValidatingExecutor) ExecuteLargeBody ¶
func (e *StampValidatingExecutor) ExecuteLargeBody(ctx context.Context, accepted Assessment, src Source) (ExecutionResult, error)
ExecuteLargeBody revalidates the assessment stamp against live facts before proceeding. Any disagreement aborts execution immediately with an invariant failure error, never falling back to canonical.
type StaticDispositionInput ¶
type StaticDispositionInput struct {
// FeatureEnabled reports whether the large payload fast path is enabled.
FeatureEnabled bool
// GenerationID optionally binds the request to an expected generation identity.
GenerationID string
// ThresholdBytes is the decoded-size consideration gate. When <= 0, DefaultThresholdBytes is used.
ThresholdBytes int64
// HasKnownLength reports whether ContentLength is a known parsed byte length.
HasKnownLength bool
// ContentLength is the parsed Content-Length in bytes when known. Negative indicates unknown/chunked.
ContentLength int64
// GzipCompressed reports whether Content-Encoding indicates gzip compression.
GzipCompressed bool
// LegacyResolverConfigured reports whether a pre-preflight legacy full-body route resolver is configured.
LegacyResolverConfigured bool
}
StaticDispositionInput carries cheap request facts available before body capture. No body bytes, no reader, no maps, no heap-allocated structures.
type StaticWireDisposition ¶
type StaticWireDisposition uint8
StaticWireDisposition classifies a candidate request before spooling or scanning.
const ( // StaticWireUnknown is the zero value and represents an uninitialized disposition. StaticWireUnknown StaticWireDisposition = iota // StaticWireDefinitelyCanonical directs the request immediately to the canonical path without spool/scanner setup. StaticWireDefinitelyCanonical // StaticWireNeedsRequestAssessment directs the request to capture and two-phase assessment. // NOTE: Static disposition NEVER says wire-eligible. StaticWireNeedsRequestAssessment )
func (StaticWireDisposition) IsDefinitelyCanonical ¶
func (d StaticWireDisposition) IsDefinitelyCanonical() bool
IsDefinitelyCanonical reports whether the disposition is definitely canonical.
func (StaticWireDisposition) IsNeedsRequestAssessment ¶
func (d StaticWireDisposition) IsNeedsRequestAssessment() bool
IsNeedsRequestAssessment reports whether the disposition requires request assessment.
func (StaticWireDisposition) String ¶
func (d StaticWireDisposition) String() string
String returns a bounded static label for metrics and diagnostics.
type StaticWireReason ¶
type StaticWireReason uint16
StaticWireReason is the bounded taxonomy of static pre-capture decline reasons. Labels are static enums; provider/backend/user strings never appear here (Requirement 22.2).
const ( // StaticWireReasonNone accompanies StaticWireNeedsRequestAssessment (no static blocker). StaticWireReasonNone StaticWireReason = iota // StaticWireReasonFeatureDisabled indicates server.large_payload_fast_path.enabled is false. StaticWireReasonFeatureDisabled // StaticWireReasonStaticBlocker indicates a frozen generation authority or unsealed summary blocks wire mode. StaticWireReasonStaticBlocker // StaticWireReasonBelowThreshold indicates a known uncompressed body length is below the fast-path threshold. StaticWireReasonBelowThreshold // StaticWireReasonGzipCompressed indicates the body is gzip/compressed (unsupported in Wave 1). StaticWireReasonGzipCompressed // StaticWireReasonLegacyResolverConfigured indicates a pre-preflight legacy full-body route resolver is configured without a wire contract. StaticWireReasonLegacyResolverConfigured )
func (StaticWireReason) String ¶
func (r StaticWireReason) String() string
String returns a bounded static label for metrics and diagnostics.
type StorageKind ¶
type StorageKind string
StorageKind classifies capture storage (memory vs file spill).
const ( // StorageMemory indicates body was held entirely within the in-memory window. StorageMemory StorageKind = "memory" // StorageFile indicates body spilled to a secure temporary spill file. StorageFile StorageKind = "file" )
type StreamingEscapeWriter ¶
type StreamingEscapeWriter struct {
// contains filtered or unexported fields
}
StreamingEscapeWriter writes JSON-escaped string characters into an underlying io.Writer without retaining large strings in memory (Requirements 4, 16; design section 6). Output is byte-for-byte identical to the interior of Go's json.Marshal for strings, including HTML safety (<, >, &) and Unicode line separators (\u2028, \u2029).
func NewStreamingEscapeWriter ¶
func NewStreamingEscapeWriter(w io.Writer) *StreamingEscapeWriter
NewStreamingEscapeWriter returns an initialized StreamingEscapeWriter.
func (*StreamingEscapeWriter) Close ¶
func (s *StreamingEscapeWriter) Close() error
Close flushes buffered content and handles any incomplete trailing UTF-8 sequence.
func (*StreamingEscapeWriter) Write ¶
func (s *StreamingEscapeWriter) Write(p []byte) (int, error)
Write processes incoming unescaped bytes and writes their JSON-escaped representation.
func (*StreamingEscapeWriter) WriteString ¶
func (s *StreamingEscapeWriter) WriteString(str string) (int, error)
WriteString processes incoming unescaped string and writes its JSON-escaped representation without allocating heap byte slices.
type StreamingProofConfig ¶
type StreamingProofConfig struct {
Reader io.Reader
MaxBytes int64
ChunkSize int
CallIdentityConfig CallIdentityConfig
ScannerLimits jsonshape.Limits
ScannerOptions []jsonshape.Option
OnChunk func(chunk []byte) error
}
StreamingProofConfig configures streaming proof compilation across replay chunks.
type StreamingProofResult ¶
type StreamingProofResult struct {
BytesRead int64
BodyHash [32]byte
Digest IdentityDigest
}
StreamingProofResult returns the compiled proof output from streaming execution.
func CompileStreamingProof ¶
func CompileStreamingProof(ctx context.Context, cfg StreamingProofConfig) (StreamingProofResult, error)
CompileStreamingProof compiles proof and semantic identity from replay bytes in a single pass. It feeds replay bytes through jsonshape.Scanner, computes raw body SHA-256, and drives CallIdentityWriter without allocating or retaining the full body in memory.
type TrimSpaceWriter ¶
type TrimSpaceWriter struct {
// contains filtered or unexported fields
}
TrimSpaceWriter wraps an io.Writer and trims leading and trailing Unicode whitespace in a streaming manner with bounded memory.
func NewTrimSpaceWriter ¶
func NewTrimSpaceWriter(out io.Writer) *TrimSpaceWriter
NewTrimSpaceWriter returns an initialized TrimSpaceWriter wrapping out.
func (*TrimSpaceWriter) Close ¶
func (w *TrimSpaceWriter) Close() error
func (*TrimSpaceWriter) TrimmedBytes ¶
func (w *TrimSpaceWriter) TrimmedBytes() int64
TrimmedBytes returns the total number of bytes written to the underlying writer after trimming leading and trailing whitespace.
type WireBackend ¶
type WireBackend interface {
ResolveWireRequest(ctx context.Context, facts WireRequestFacts, cand routing.AttemptCandidate) WireRequestSupport
ResolveWireDomain(ctx context.Context, facts WireDomainFacts) WireDomainSupport
}
WireBackend is the optional internal interface implemented by backends capable of evaluating direct wire compatibility (Task 8.1, Requirements 7, 8, 9).
func AsWireBackend ¶
func AsWireBackend(v any) (WireBackend, bool)
AsWireBackend probes a value for the internal WireBackend capability.
type WireBackendMap ¶
type WireBackendMap map[string]WireBackend
WireBackendMap adapts a map into a WireBackendResolver.
func (WireBackendMap) ResolveWireBackend ¶
func (m WireBackendMap) ResolveWireBackend(backendID string) (WireBackend, bool)
type WireBackendProvider ¶
type WireBackendProvider interface {
AsWireBackend() WireBackend
}
WireBackendProvider is an optional interface for types that adapt into a WireBackend.
type WireBackendResolver ¶
type WireBackendResolver interface {
ResolveWireBackend(backendID string) (WireBackend, bool)
}
WireBackendResolver resolves a configured backend into its WireBackend capability for pure wire compatibility checks (Requirements 7, 8).
type WireBackendResolverFunc ¶
type WireBackendResolverFunc func(backendID string) (WireBackend, bool)
WireBackendResolverFunc adapts a function into a WireBackendResolver.
func (WireBackendResolverFunc) ResolveWireBackend ¶
func (f WireBackendResolverFunc) ResolveWireBackend(backendID string) (WireBackend, bool)
type WireCompactionMeta ¶
type WireCompactionMeta struct {
TraceID string
SessionID string
ALegID string
BLegID string
AttemptSeq int
TransactionID string
RuleID string
}
WireCompactionMeta provides bounded preservation metadata for compaction observation without retaining lipapi.Call (Requirements 13.7, 19.4).
func (WireCompactionMeta) Validate ¶
func (m WireCompactionMeta) Validate(maxFactBytes int64) error
Validate checks bounds under maxFactBytes.
type WireContinuationLineage ¶
type WireContinuationLineage struct {
ParentRef string
TrajectoryRef string
ProgressRef string
Attempt uint8
}
WireContinuationLineage provides bounded metadata for continuation lineage without retaining parent trajectory or prompt content (Requirements 13.7, 19.4).
func (WireContinuationLineage) Validate ¶
func (l WireContinuationLineage) Validate(maxFactBytes int64) error
Validate checks bounds under maxFactBytes.
type WireConversationObserverFacts ¶
type WireConversationObserverFacts struct {
ALegID string
TraceID string
Stage string
Revision string
RuleCount int
}
WireConversationObserverFacts carries bounded observation metadata for conversation events without prompt content (Requirements 13.7, 19.4).
func (WireConversationObserverFacts) Validate ¶
func (f WireConversationObserverFacts) Validate(maxFactBytes int64) error
Validate checks bounds under maxFactBytes.
type WireCountInput ¶
type WireCountInput struct {
Source Source
Model string
Backend string
CallID string
ProfileID string
TokenizerID string
}
WireCountInput supplies bounded facts and the immutable replay source to a WireCounter (Requirement 15.5; Task 10.4). Prompt text or a full lipapi.Call is never passed here.
type WireCountResult ¶
type WireCountResult struct {
InputTokens int
TotalTokens int
Accounting lipapi.UsageAccountingMetadata
}
WireCountResult is the bounded result of exact wire token counting. Raw body bytes are NEVER substituted for tokens (Requirement 15.5).
type WireCounter ¶
type WireCounter interface {
CountWire(ctx context.Context, in WireCountInput) (WireCountResult, error)
}
WireCounter is the optional contract for counting tokens directly from an immutable replay source without constructing a full lipapi.Call or materializing prompt text (Requirements 6.2, 15.5, 21; Task 10.4).
func AsWireCounter ¶
func AsWireCounter(v any) (WireCounter, bool)
AsWireCounter probes a value for the internal WireCounter capability.
type WireCounterProvider ¶
type WireCounterProvider interface {
AsWireCounter() WireCounter
}
WireCounterProvider is an optional interface for types that adapt into a WireCounter.
type WireDependencyFacts ¶
type WireDependencyFacts struct {
ReceiveView WireReceiveView
TerminalFacts WireTerminalFacts
HasConversationReader bool
HasConversationTagger bool
HasSteeringWriter bool
ActiveSteeringOverlays int
ActiveNeverBackendRules int
HasContinuationIntent bool
HasParentContinuation bool
ContinuationLineage WireContinuationLineage
HasInterleavedProcessor bool
InterleavedActive bool
HasCompactionDetector bool
HasCompactionPreserver bool
CompactionMeta WireCompactionMeta
TerminalDecisionActive bool
}
WireDependencyFacts carries the per-request dependency state across the receive, terminal, conversation, continuation, interleaved, and compaction surfaces (Requirements 13, 19; Task 12.3).
type WireDomainFacts ¶
type WireDomainFacts struct {
ProfileID string
Operation lipapi.Operation
Delivery lipapi.DeliveryMode
BodyMode BodyMode
Rewrite RewriteSemantics
UniversalModel bool
CandidateModels []string
RequiredCapabilities []lipapi.Capability
}
WireDomainFacts is the provider-neutral input to a backend late-route domain proof (design section 9, Requirement 7). A universal domain (AnyAcceptedModel) must not also enumerate models, and a finite domain must enumerate at least one proven model.
func (WireDomainFacts) Validate ¶
func (f WireDomainFacts) Validate(maxFactBytes int64) error
Validate enforces universal/finite exclusivity and bounds.
type WireDomainSupport ¶
type WireDomainSupport struct {
Compatible bool
AnyAcceptedModel bool
Reason WireSupportReason
}
WireDomainSupport represents the pure late-route domain wire compatibility outcome (design section 9, Requirement 7).
func (WireDomainSupport) Validate ¶
func (s WireDomainSupport) Validate() error
Validate checks internal consistency of the domain support outcome.
type WireEconomicFacts ¶
type WireEconomicFacts struct {
// BillingCallID is the BillingCallID-scoped identity string.
// Named consumer: BillingCallID-scoped exposure admission, usage append, journal commands.
BillingCallID string
// AccountID is the customer/principal account identifier.
// Named consumer: cheap pre-route credit gate, exposure admission.
AccountID string
// CustomerPricingRef is the customer pricing configuration version reference.
// Named consumer: post-usage rating, exposure quote.
CustomerPricingRef string
// ChargePolicyRef is the charge policy version reference.
// Named consumer: charge policy evaluation.
ChargePolicyRef string
// RequestCount is the request quantity fact (always 1 for single-request wire turn).
// Named consumer: metering quantities builder, clamp exposure quantities.
RequestCount int64
// MaxOutputQuantity is the max output quantity fact.
// Named consumer: metering checkpoint quantities.
MaxOutputQuantity int64
}
WireEconomicFacts holds bounded billing and metering facts. Every field has an explicit named downstream consumer (Requirement 15, 19.1, 19.4).
func (WireEconomicFacts) Validate ¶
func (f WireEconomicFacts) Validate(maxFactBytes int64) error
Validate enforces non-empty billing call ID and bounds.
type WireEligibilityInput ¶
type WireEligibilityInput struct {
GenerationID string
Planes []PlaneEligibilityInput
Hooks HookEligibilityInput
Ports NarrowPortEligibilityInput
TwoPhaseExecutorAvailable bool
}
WireEligibilityInput is the complete frozen generation fact set compiled once at composition time. It carries bounded static facts only: stable plane IDs, access enums, occupancy bools, and a bounded generation binding. No request data can be expressed in it.
type WireEligibilitySummary ¶
type WireEligibilitySummary struct {
// contains filtered or unexported fields
}
WireEligibilitySummary is the published bounded summary. The zero value is fail-closed: unsealed and reporting a static blocker. Only the compiler produces sealed values; fields are unexported so published summaries are immutable and cannot alias caller memory.
func CompileWireEligibilitySummary ¶
func CompileWireEligibilitySummary(in WireEligibilityInput, maxFactBytes int64) (WireEligibilitySummary, error)
CompileWireEligibilitySummary compiles frozen generation facts into a sealed summary. It is deterministic across plane input order, copies all inputs (published summaries never alias caller memory), and fails closed: malformed input returns an error with an unsealed blocking summary.
func (WireEligibilitySummary) GenerationID ¶
func (s WireEligibilitySummary) GenerationID() string
GenerationID returns the bound generation identity (Requirement 6.7).
func (WireEligibilitySummary) HasStaticBlocker ¶
func (s WireEligibilitySummary) HasStaticBlocker() bool
HasStaticBlocker reports whether the generation is definitely canonical: unsealed summaries and any recorded plane/hook/port blocker block. Allocation-free; suitable for the Task 3.6 hot projection.
func (WireEligibilitySummary) HookBlockers ¶
func (s WireEligibilitySummary) HookBlockers() HookChain
HookBlockers returns the occupied mutating-chain subset (never the response-only chain).
func (WireEligibilitySummary) HookOccupancy ¶
func (s WireEligibilitySummary) HookOccupancy() HookChain
HookOccupancy returns the frozen hook-bus occupancy bits.
func (WireEligibilitySummary) PinnedTo ¶
func (s WireEligibilitySummary) PinnedTo(generationID string) bool
PinnedTo reports whether the summary is sealed and bound to the given generation. A reload publishes a new generation ID, so a mismatch detects staleness without reading any other generation state.
func (WireEligibilitySummary) PlaneBlockers ¶
func (s WireEligibilitySummary) PlaneBlockers() uint32
PlaneBlockers returns the fixed plane blocker mask: bit i (see WireEligibilityPlaneID) names an occupied canonical-required plane.
func (WireEligibilitySummary) PortBlockers ¶
func (s WireEligibilitySummary) PortBlockers() WirePortBlocker
PortBlockers returns the fixed narrow-port blocker mask.
func (WireEligibilitySummary) Sealed ¶
func (s WireEligibilitySummary) Sealed() bool
Sealed reports whether the summary is a complete valid compilation. Only sealed summaries are usable; the zero value is unsealed.
func (WireEligibilitySummary) StaticDisposition ¶
func (s WireEligibilitySummary) StaticDisposition(in StaticDispositionInput) (StaticWireDisposition, StaticWireReason)
StaticDisposition evaluates whether a request is definitely canonical on the summary receiver.
func (WireEligibilitySummary) String ¶
func (s WireEligibilitySummary) String() string
String renders bounded static labels only: generation binding plus fixed masks. No backend/model/user/session content can appear.
func (WireEligibilitySummary) Validate ¶
func (s WireEligibilitySummary) Validate(maxFactBytes int64) error
Validate enforces the generation binding under the semantic-fact budget.
type WireIdentity ¶
WireIdentity carries logical RequestID and TraceID for wire execution.
func WireIdentityFromContext ¶
func WireIdentityFromContext(ctx context.Context) (WireIdentity, bool)
WireIdentityFromContext extracts WireIdentity from ctx if attached.
type WireIdentityFacts ¶
type WireIdentityFacts struct {
// RequestID is the canonical logical request identifier.
// Named consumer: trace correlation, frontend-ingress checkpoint ID, stable call ID.
RequestID string
// TraceID is the runtime trace identifier.
// Named consumer: distributed tracing, diagnostics, checkpoint correlation.
TraceID string
// CanonicalDigest is the exact canonical semantic identity digest.
// Named consumer: deterministic response IDs, timestamps, stable call token.
CanonicalDigest IdentityDigest
// CheckpointID is the deterministic public checkpoint identity.
// Named consumer: metering public checkpoint identification.
CheckpointID string
}
WireIdentityFacts holds bounded request and trace identity evidence. Every field has an explicit named downstream consumer (Requirement 16, 19.1, 19.4).
func (WireIdentityFacts) Validate ¶
func (f WireIdentityFacts) Validate(maxFactBytes int64) error
Validate enforces identity presence and bounds.
type WireInterleavedStateFacts ¶
WireInterleavedStateFacts provides bounded metadata for interleaved thinking state without prompt content (Requirements 13.7, 19.4).
func (WireInterleavedStateFacts) Validate ¶
func (f WireInterleavedStateFacts) Validate(maxFactBytes int64) error
Validate checks bounds under maxFactBytes.
type WireMaxOutputFacts ¶
type WireMaxOutputFacts struct {
// MaxOutputTokens is the effective maximum output token bound.
// Named consumer: clamp preview, attempt authority admission, metering quantities.
MaxOutputTokens int64
// ClampedMaxOutput is the optional narrow-down clamped bound from authority admission.
// Named consumer: attempt narrow-down clamp enforcement.
ClampedMaxOutput *int64
}
WireMaxOutputFacts holds bounded max-output token bounds. Every field has an explicit named downstream consumer (Requirement 19.1, 19.4).
func (WireMaxOutputFacts) Validate ¶
func (f WireMaxOutputFacts) Validate(maxFactBytes int64) error
Validate enforces non-negative bounds.
type WireOpenRequest ¶
type WireOpenRequest struct {
Candidate routing.AttemptCandidate
Body io.ReadCloser
ContentLength int64
WireRequest WireRequestFacts
TraceID string
ALegID string
BLegID string
Header http.Header
}
WireOpenRequest carries bounded facts and a fresh offset-zero source reader required by a backend to open an attempt without constructing a lipapi.Call (Requirement 8, 9, 10, 12).
func (WireOpenRequest) Validate ¶
func (r WireOpenRequest) Validate() error
Validate checks internal consistency of the wire open request.
type WireOpener ¶
type WireOpener interface {
OpenWire(ctx context.Context, req WireOpenRequest) (lipapi.ManagedEventStream, error)
}
WireOpener is an optional internal interface implemented by backends capable of opening a wire attempt without constructing a lipapi.Call (Requirement 8, 12).
func AsWireOpener ¶
func AsWireOpener(v any) (WireOpener, bool)
AsWireOpener probes a value for the internal WireOpener capability.
type WireOpenerProvider ¶
type WireOpenerProvider interface {
AsWireOpener() WireOpener
}
WireOpenerProvider is an optional interface for types that adapt into a WireOpener.
type WirePortBlocker ¶
type WirePortBlocker uint32
WirePortBlocker is a fixed bitset over V1 static narrow-port blockers (Task 3.4). Each bit names one unconditional composition-time blocker; present-but-model-dependent backend facts stay dynamic (Task 11) and never set a bit here.
const ( // WirePortBackendsEmpty names an empty backend map: no candidate exists // for any request (1.8 section 3.1; 3.4 core.backends nil state). WirePortBackendsEmpty WirePortBlocker = 1 << iota // WirePortConversationViewReader names occupied trajectory reads without // a source-backed contract (3.4 core.conversation_view_reader). WirePortConversationViewReader // WirePortConversationViewTagger names occupied local-turn tagging with // content-shaped identity derivation (3.4 core.conversation_view_tagger). WirePortConversationViewTagger // WirePortSteeringWriterFactory names a Call-returning steering resolver // (3.4 core.steering_writer_factory). WirePortSteeringWriterFactory // WirePortExposureAdmission names the Call-embedding exposure input // pending the Task 10.5 bounded-facts refactor (3.4 billing). WirePortExposureAdmission // WirePortBillingIdentityCallbacks names custom func(ctx, Call) billing // resolvers without a bounded fact contract (3.4 billing, req 15.6). WirePortBillingIdentityCallbacks // WirePortCapsResolver names an occupied full-Call capability resolver // (3.4 routing; Task 12.2). WirePortCapsResolver // WirePortCatalogResolver names an occupied full-Call catalog resolver // (3.4 routing; Task 12.2). WirePortCatalogResolver // WirePortEligibilityResolver names an occupied full-Call eligibility // check (3.4 routing; Task 12.2). WirePortEligibilityResolver // WirePortRequestTokenEstimator names an occupied full-Call token // estimator without an exact source contract (3.4 routing; Task 10.4). WirePortRequestTokenEstimator // WirePortPreflightCountOnly names enabled CountCall-only preflight // without an exact wire counter (3.4 accounting; Task 10.4). WirePortPreflightCountOnly // WirePortStreamUsage names occupied stream usage with a Call-backed // input-count leg (3.4 accounting). WirePortStreamUsage // WirePortAdminCountService names occupied token-dependent counting // (3.4 accounting; Tasks 10.4/12.2). WirePortAdminCountService // WirePortInterleavedProcessor names occupied thinker/executor shaping // or continuation re-projection (3.4 interleaved; Task 12.3). WirePortInterleavedProcessor // WirePortCompactionDetector names the Call-shaped RequestOpened leg // (3.4 compaction; Task 12.3). WirePortCompactionDetector // WirePortTrafficCapturing names a non-no-op traffic bundle: capturing, // observing, or redacting legs (3.4 traffic; req 13.1). WirePortTrafficCapturing // WirePortTokenCounting names required input-token counting without an // exact wire counter; body bytes are never tokens (3.4 counting). WirePortTokenCounting // WirePortCustomCallCallbacks names any other Call-shaped callback // without an explicit bounded fact contract (3.4 custom; req 5.6/5.12). WirePortCustomCallCallbacks // WirePortTwoPhaseExecutorMissing names an executor without the internal // two-phase capability (design section 4). WirePortTwoPhaseExecutorMissing )
type WireProtocolFacts ¶
type WireProtocolFacts struct {
// Operation is the certified request operation.
// Named consumer: frontend-pipeline dispatch, wire-open framing.
Operation lipapi.Operation
// Delivery is the certified delivery mode (streaming vs non-streaming).
// Named consumer: attempt execution, holdalive wrapping, response pipeline.
Delivery lipapi.DeliveryMode
// RequirementsID is the static profile-defined requirement-set label.
// Named consumer: protocol conformance check, candidate feature requirements.
RequirementsID string
// ControlCount counts certified protocol control carriers.
// Named consumer: protocol-control validation without prompt content.
ControlCount int64
}
WireProtocolFacts holds bounded protocol requirements and framing facts. Every field has an explicit named downstream consumer (Requirement 19.1, 19.4).
func (WireProtocolFacts) Validate ¶
func (f WireProtocolFacts) Validate(maxFactBytes int64) error
Validate enforces bounds under the semantic-fact budget.
type WireReceiveView ¶
type WireReceiveView struct {
TraceID string
ALegID string
RequestID string
SessionID string
RoutePrefs []string
CandidateModel string
ClientModel string
BillingCallID string
AccountID string
CustomerPricing string
ChargePolicy string
IdentityStamped bool
Operation lipapi.Operation
Delivery lipapi.DeliveryMode
MaxOutputTokens int64
}
WireReceiveView provides a bounded, read-only metadata view of receive-turn facts for wire execution without retaining or dereferencing lipapi.Call (Requirements 13.7, 19.1, 19.4).
func (WireReceiveView) HookMeta ¶
func (v WireReceiveView) HookMeta(blegID string, attemptSeq int, backend string) (traceID, aLegID, bLegID, backendID string, seq int)
HookMeta returns bounded metadata for hook invocation without lipapi.Call.
func (WireReceiveView) Validate ¶
func (v WireReceiveView) Validate(maxFactBytes int64) error
Validate checks string lengths and numeric bounds under maxFactBytes.
type WireRequestFacts ¶
type WireRequestFacts struct {
ProfileID string
Operation lipapi.Operation
Delivery lipapi.DeliveryMode
BodyMode BodyMode
Rewrite RewriteSemantics
ClientModel string
CandidateModel string
MaxOutputTokens int64
RequiredCapabilities []lipapi.Capability
}
WireRequestFacts is the immutable provider-neutral input to a backend exact wire proof (design section 9). Outbound header construction stays backend-owned; no client headers travel here.
func (WireRequestFacts) Validate ¶
func (f WireRequestFacts) Validate(maxFactBytes int64) error
Validate enforces bounds under the semantic-fact budget.
type WireRequestSupport ¶
type WireRequestSupport struct {
Compatible bool
NeedsModelRewrite bool
Reason WireSupportReason
}
WireRequestSupport represents the pure exact wire compatibility outcome for one candidate (design section 9, Requirements 8, 9).
func (WireRequestSupport) Validate ¶
func (s WireRequestSupport) Validate() error
Validate checks internal consistency of the support outcome.
type WireRewriteFacts ¶
type WireRewriteFacts struct {
// Semantics is the certified rewrite semantics contract.
// Named consumer: backend wire proof validation (ResolveWireRequest, ResolveWireDomain).
Semantics RewriteSemantics
// ModelSpan is the exact byte range of the model token.
// Named consumer: streaming model token splice reader.
ModelSpan Span
// ReplacementModel is the per-attempt candidate model identifier.
// Named consumer: per-attempt replacement model encoding.
ReplacementModel string
// RewrittenLength is the computed outbound body length.
// Named consumer: outbound HTTP Content-Length header calculation.
RewrittenLength int64
// RewriteDigest is the digest of the model rewrite token/splice.
// Named consumer: backend attempt checkpoint evidence (WireBackendIngressInput.RewriteDigest).
RewriteDigest [32]byte
}
WireRewriteFacts holds bounded rewrite contract and splice details. Every field has an explicit named downstream consumer (Requirement 9, 19.1, 19.4).
func (WireRewriteFacts) Validate ¶
func (f WireRewriteFacts) Validate(maxFactBytes int64) error
Validate enforces rewrite contract consistency and bounds.
type WireRouteFacts ¶
type WireRouteFacts struct {
// ProfileID identifies the certified frontend profile.
// Named consumer: candidate profile validation, backend wire proof lookup.
ProfileID string
// RouteSelector is the extracted route selector string.
// Named consumer: buildRoutePlan, candidate resolution, late route-override validation.
RouteSelector string
// ClientModel is the client-requested model identifier.
// Named consumer: route selection, backend capability check, default model fallback.
ClientModel string
// CandidateModel is the selected candidate model identifier for attempt execution.
// Named consumer: candidate execution, model token splice, attempt verification.
CandidateModel string
// RoutePrefs contains caller-specified provider preferences.
// Named consumer: candidate filtering, affinity key resolution.
RoutePrefs []string
// MaxAttempts bounds total attempt count.
// Named consumer: retry budget enforcement in route plan.
MaxAttempts int
// DefaultBackend is the fallback backend identifier.
// Named consumer: default backend selection in route plan.
DefaultBackend string
}
WireRouteFacts holds bounded route and candidate selection facts. Every field has an explicit named downstream consumer (Requirement 19.1, 19.4).
func (WireRouteFacts) Validate ¶
func (f WireRouteFacts) Validate(maxFactBytes int64) error
Validate enforces bounds under the semantic-fact budget.
type WireSessionFacts ¶
type WireSessionFacts struct {
// Input holds authoritative session IDs and resume tokens.
// Named consumer: PrepareSecureSession, ExecuteBeginTurn post-commit.
Input SessionInput
// TurnShape holds the bounded normalized client-turn shape without prompt text.
// Named consumer: RecordClientTurnAfterGate.
TurnShape ClientTurnShape
}
WireSessionFacts holds bounded session inputs and turn shapes. Every field has an explicit named downstream consumer (Requirement 14, 19.1, 19.4).
func (WireSessionFacts) Validate ¶
func (f WireSessionFacts) Validate(maxFactBytes int64) error
Validate enforces session and turn shape bounds under maxFactBytes.
type WireSourceFacts ¶
type WireSourceFacts struct {
// SourceDigest is the SHA-256 digest of captured source payload.
// Named consumer: replay reader integrity check, attempt checkpoint evidence.
SourceDigest SourceDigest
// BodyBytes is the exact captured body size.
// Named consumer: body limit check, spool reservation verification, response facts.
BodyBytes int64
// BodyMode is the certified body representation mode.
// Named consumer: framing and media-type validation.
BodyMode BodyMode
}
WireSourceFacts holds bounded source integrity and body bounds. Every field has an explicit named downstream consumer (Requirement 19.1, 19.4, 20).
func (WireSourceFacts) Validate ¶
func (f WireSourceFacts) Validate(maxFactBytes int64) error
Validate enforces source presence and non-negative body size.
type WireSupportReason ¶
type WireSupportReason uint8
WireSupportReason classifies the compatibility or decline reason for a backend wire resolution (design section 9, Requirement 8).
const ( WireSupportReasonNone WireSupportReason = iota WireSupportReasonUnsupported WireSupportReasonProfileUnsupported WireSupportReasonOperationUnsupported WireSupportReasonDeliveryUnsupported WireSupportReasonBodyModeUnsupported WireSupportReasonModelUnsupported WireSupportReasonRewriteUnsupported WireSupportReasonClampUnsupported WireSupportReasonCapabilityUnsupported )
func (WireSupportReason) String ¶
func (r WireSupportReason) String() string
type WireTerminalFacts ¶
type WireTerminalFacts struct {
TraceID string
ALegID string
RequestID string
SessionID string
BillingCallID string
AccountID string
CustomerPricing string
ChargePolicy string
IdentityStamped bool
RoutePrefs []string
CandidateModel string
ClientModel string
Operation lipapi.Operation
Delivery lipapi.DeliveryMode
BodyBytes int64
SourceDigest SourceDigest
CanonicalDigest IdentityDigest
}
WireTerminalFacts is the bounded terminal-facing metadata view required for terminal settlement, billing, and affinity commit without retaining lipapi.Call (Requirements 13.7, 19.1, 19.4).
func (WireTerminalFacts) Validate ¶
func (f WireTerminalFacts) Validate(maxFactBytes int64) error
Validate checks string lengths and numeric bounds under maxFactBytes.
type WireTokenCountGateInput ¶
type WireTokenCountGateInput struct {
Source Source
Model string
Backend string
CallID string
ProfileID string
Counter any // can be WireCounter, preflight.Counter, app.LocalCounter, etc.
Semantics ExactTokenizerSemantics
MaxScanBytes int64 // Maximum bytes allowed to scan; <= 0 uses DefaultMaxWireScanBytes
MaxPermitHoldCPU time.Duration // CPU time budget; <= 0 uses DefaultMaxPermitHoldCPU
AccountingEnabled bool
}
WireTokenCountGateInput supplies the parameters evaluated by the exact wire counter gate.
type WireTokenCountGateResult ¶
type WireTokenCountGateResult struct {
Proceed bool
DeclineReason DeclineReason
Count WireCountResult
Duration time.Duration
MeasuredCPU bool
Err error
}
WireTokenCountGateResult is the bounded outcome of the exact wire counter gate.
func EvaluateWireTokenCounting ¶
func EvaluateWireTokenCounting(ctx context.Context, in WireTokenCountGateInput) WireTokenCountGateResult
EvaluateWireTokenCounting executes the exact wire counter gate (Task 10.4):
- If accounting is not enabled, wire proceeds immediately with zero counting cost (Requirement 15.4).
- If accounting is enabled and only CountCall exists (no WireCounter), dynamic assessment declines under the same permit with DeclineReasonCountingUnsupported (Requirement 15.5).
- Only when exact tokenizer semantics exist for the effective model does wire proceed, else same-permit canonical decline with DeclineReasonCountingUnsupported (Requirement 15.5).
- Permit-hold CPU is bounded and measured; if exact counting is expensive/unbounded (e.g. source size exceeds MaxScanBytes or duration exceeds budget), dynamic assessment declines under the same permit with DeclineReasonCountingUnsupported (Requirements 6.8, 21.13).
- Prompt text or lipapi.Call is NEVER materialized for CountCall; raw bytes are NEVER substituted for tokens.
type WireTurnFacts ¶
type WireTurnFacts struct {
Route WireRouteFacts
Protocol WireProtocolFacts
MaxOutput WireMaxOutputFacts
Identity WireIdentityFacts
Session WireSessionFacts
Source WireSourceFacts
Rewrite WireRewriteFacts
Economic WireEconomicFacts
}
WireTurnFacts groups the 8 explicit bounded runtime wire-fact domains. Every single fact has a named downstream consumer; no shadow Call schema is retained (Requirements 19.1, 19.4, 19.7; Design section 11).
func DefaultTestWireTurnFacts ¶
func DefaultTestWireTurnFacts() WireTurnFacts
DefaultTestWireTurnFacts returns a fully populated, valid WireTurnFacts for tests and benchmarks.
func NewWireTurnFactsFromProof ¶
func NewWireTurnFactsFromProof(proof Proof, stamp AssessmentStamp, requestID, traceID, billingCallID string) (WireTurnFacts, error)
NewWireTurnFactsFromProof constructs a WireTurnFacts from a validated Proof and AssessmentStamp.
func (WireTurnFacts) AssertConsumerCoverage ¶
func (f WireTurnFacts) AssertConsumerCoverage() error
AssertConsumerCoverage mechanically verifies the "only facts with named consumers" ratchet (Requirements 19.1, 19.4): every direct field of all 8 fact domains must have a non-empty AuditNamedConsumers entry, and every audit key must resolve to a real struct field (stale entries fail too).
func (WireTurnFacts) AssertNoShadowCall ¶
func (f WireTurnFacts) AssertNoShadowCall() error
AssertNoShadowCall verifies structurally that WireTurnFacts retains no shadow Call schema: no prompt content, messages, tools, attachments, raw headers, history, and no lipapi.Call reference anywhere in the 8 fact domains (Requirements 19.1, 19.4, 19.7).
func (WireTurnFacts) AuditNamedConsumers ¶
func (f WireTurnFacts) AuditNamedConsumers() map[string]string
AuditNamedConsumers returns the complete mapping of every fact in the inventory to its explicit named downstream consumer (Requirement 19.1, 19.4).
func (WireTurnFacts) ToCompactionMeta ¶
func (f WireTurnFacts) ToCompactionMeta(blegID string, attemptSeq int, transactionID, ruleID string) WireCompactionMeta
ToCompactionMeta projects bounded compaction preservation metadata.
func (WireTurnFacts) ToContinuationLineage ¶
func (f WireTurnFacts) ToContinuationLineage() WireContinuationLineage
ToContinuationLineage projects bounded continuation lineage facts.
func (WireTurnFacts) ToConversationObserverFacts ¶
func (f WireTurnFacts) ToConversationObserverFacts(stage, revision string, ruleCount int) WireConversationObserverFacts
ToConversationObserverFacts projects bounded conversation observer facts.
func (WireTurnFacts) ToDependencyFacts ¶
func (f WireTurnFacts) ToDependencyFacts() WireDependencyFacts
ToDependencyFacts constructs a baseline WireDependencyFacts from WireTurnFacts, populated with clean (non-blocking) metadata-only views.
func (WireTurnFacts) ToReceiveView ¶
func (f WireTurnFacts) ToReceiveView() WireReceiveView
ToReceiveView projects bounded receive view from WireTurnFacts.
func (WireTurnFacts) ToResponseFacts ¶
func (f WireTurnFacts) ToResponseFacts(effectiveModel string) ResponseFacts
ToResponseFacts projects facts into ResponseFacts for frontend response bridging.
func (WireTurnFacts) ToSessionResponseCarrier ¶
func (f WireTurnFacts) ToSessionResponseCarrier() SessionResponseCarrier
ToSessionResponseCarrier projects facts into SessionResponseCarrier for frontend session headers.
func (WireTurnFacts) ToTerminalFacts ¶
func (f WireTurnFacts) ToTerminalFacts() WireTerminalFacts
ToTerminalFacts projects bounded terminal facts from WireTurnFacts.
func (WireTurnFacts) ToWireDomainFacts ¶
func (f WireTurnFacts) ToWireDomainFacts(universal bool, candidateModels ...string) WireDomainFacts
ToWireDomainFacts projects facts into a WireDomainFacts for domain evaluation.
func (WireTurnFacts) ToWireRequestFacts ¶
func (f WireTurnFacts) ToWireRequestFacts(candidateModel string) WireRequestFacts
ToWireRequestFacts projects facts into a WireRequestFacts for candidate attempt evaluation.
func (WireTurnFacts) Validate ¶
func (f WireTurnFacts) Validate(maxFactBytes int64) error
Validate checks bounds across all 8 fact domains under maxFactBytes.
Source Files
¶
- authority_gate.go
- backend_wire_proof.go
- capability.go
- capture.go
- conservative_dependencies.go
- diagnostics.go
- disposition.go
- doc.go
- eligibility.go
- identity.go
- initial_route_gate.go
- largebody.go
- late_selector_gate.go
- route_override_gate.go
- session_input.go
- source.go
- spill.go
- splice.go
- spool.go
- stamp_validation.go
- streaming_proof.go
- turn_shape.go
- wire_counter.go
- wire_runtime_facts.go
- wire_support.go