screening

package
v0.5.1 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2026 License: MIT Imports: 10 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package screening decides whether a write may enter the store.

It combines airlock's two detectors and turns their output into a single enforcement decision. Neither detector is trusted alone:

  • detect is keyword-anchored regex over normalized text. It is fast, free, and defeated completely by paraphrase. A clean detect result proves nothing.
  • screen asks a model whether the text is addressed to an AI, and requires a verbatim quote as evidence. It catches novel phrasings, costs a model call, and is only available when a generator is configured and reachable.

The structural protection is elsewhere: internal/fence marks stored content as data wherever it reaches a model, and holds whether or not anything here fires. This package is the second line -- it keeps the worst content out of the store in the first place, so the fence is not the only thing standing between a poisoned write and a future session.

Where it runs

Daemon-side, wrapping the store, so every write path is covered: the HTTP API, the extraction pipeline that mints facts from transcripts without a human in the loop, and anything added later. A control that each new call site has to remember to invoke is a control that will eventually be missed.

Index

Constants

View Source
const DefaultTimeout = 60 * time.Second

DefaultTimeout bounds a single screening call.

Screening is not in the synchronous write path. A write lands as OutcomePending -- durable, and excluded from every read -- and returns immediately; an async worker screens it afterwards and flips it to allowed or blocked. Nobody is waiting on this call, so it can afford to be patient.

That matters, because patience is what the measurements demanded. At an earlier 5s default, four of five screens against a real daemon timed out. Under pending-is-invisible semantics that is not a degraded mode, it is an outage: nearly every write would sit unreadable waiting for a screen that never finished. Observed latency is around 7s per fact, so this leaves substantial headroom for a loaded or cold model rather than sitting just above the average.

View Source
const ReasonModelThreat = "model-threat"

ReasonModelThreat is the only block reason: a verified model verdict at or above the threat threshold. Fixed string, never derived from content.

Variables

View Source
var Exclusions = []string{
	"Notes, designs, or postmortems ABOUT prompt injection, jailbreaks, or AI security",
	"Stored instructions the user wrote for their own agents, tools, or workflows",
	"Coding conventions and repo rules phrased as imperatives to a developer",
	"Quoted attack strings appearing in test fixtures, security notes, or bug reports",
	"Descriptions of what a tool, agent, or command does when invoked",
}

Exclusions are memstore's domain-specific "this is NOT an injection" rules, appended to screen's generic list.

These exist because memstore's corpus is unusual: it is largely notes about building software, including notes about prompt injection, agent instructions, and this very package. A screener that flags a fact for describing an attack would make the store unable to remember its own security work -- and that failure mode is not hypothetical, it is the first thing this corpus will produce.

Functions

This section is empty.

Types

type Decision

type Decision struct {
	// Outcome is the enforcement result.
	Outcome Outcome

	// Threat is the model's 0-10 score, or 0 when no model screen ran.
	Threat int

	// Category is the screen category, [screen.CategoryNone] when clean, or
	// [screen.CategoryUnclassified] when the model returned one outside the
	// vocabulary.
	Category string

	// Verified reports that the model's cited evidence was located in the content.
	// An unverified threat is not blockable evidence -- see Screen.
	Verified bool

	// DetectScore is detect's 0-100 aggregate. It is recorded as corroboration and
	// as a triage signal, and it never blocks a write on its own.
	//
	// That is not timidity about false positives in general -- it is specific to this
	// corpus. detect is keyword-anchored regex, so it fires on any text that CONTAINS
	// a canonical phrasing, including a note quoting one. Memstore holds the user's
	// notes about building software, prompt injection and this package among them: a
	// fact reading "memstore fences content so a fact containing 'ignore all previous
	// instructions' cannot pose as a directive" scores 80, the same as the attack it
	// describes. Enforcing on that score would make the store unable to remember its
	// own security work, and would do it silently.
	//
	// Distinguishing a description of an attack from an attack is exactly what the
	// model screen and [Exclusions] are for, so the decision waits for them. When no
	// model is reachable the write goes to OutcomePending, where it is durable but
	// unreadable -- so nothing is lost and nothing hostile is served in the meantime.
	DetectScore int

	// DetectRules lists the rule IDs that fired, for triage. Rule IDs come from
	// airlock's corpus, not from the content, so they are safe to store and log.
	DetectRules []string

	// Obfuscated reports that the raw content carried stacked combining marks
	// suggesting deliberate obfuscation. Independent of the rules: normalization
	// strips the marks before matching, so obfuscated text can trip nothing at all.
	Obfuscated bool

	// ModelScreened reports that a model verdict contributed. False means regex
	// evidence only, either because no generator is configured or because the call
	// failed -- in which case Outcome is OutcomePending and the write is queued.
	ModelScreened bool

	// Reason names which signal drove a block, in fixed vocabulary. Empty unless
	// Outcome is OutcomeBlocked.
	Reason string
}

Decision is the outcome of screening one write, plus the payload-free evidence behind it.

It carries no attacker-authored bytes: not the quoted evidence, not the model's prose. Those would be a second delivery path into logs, dashboards, and error strings, none of which are fenced. See screen.Finding for the full argument. The content itself is held separately, in quarantine, where reads are fenced.

func (Decision) Blocked

func (d Decision) Blocked() bool

Blocked reports whether the write was rejected.

type Generator

type Generator interface {
	Generate(ctx context.Context, prompt string) (string, error)
	Model() string
}

Generator is the subset of memstore.Generator this package needs. Declared here rather than imported so screening does not depend on the root package, which would make the store decorator an import cycle.

type Outcome

type Outcome string

Outcome is what the policy decided about a write.

const (
	// OutcomeAllowed means the write proceeds and was fully screened.
	OutcomeAllowed Outcome = "allowed"

	// OutcomeBlocked means the write was rejected.
	OutcomeBlocked Outcome = "blocked"

	// OutcomePending means the write proceeded on regex evidence alone because the
	// model screen could not run, and is queued to be screened again later.
	OutcomePending Outcome = "pending"

	// OutcomeAbandoned means screening failed repeatedly and the worker gave up. The
	// content stays stored and unreadable; it was never judged either way.
	OutcomeAbandoned Outcome = "abandoned"
)

type PendingFact

type PendingFact struct {
	ID       int64
	Content  string
	Attempts int
}

PendingFact is a write awaiting screening.

It carries only what the screener needs plus the attempt count, which is the worker's evidence that a fact is not merely slow but stuck.

type PendingStore

type PendingStore interface {
	// PendingFacts returns facts awaiting screening, oldest first. It must not
	// return facts that have been abandoned, or the worker will spin on them.
	PendingFacts(ctx context.Context, limit int) ([]PendingFact, error)

	// Resolve applies a terminal decision. An allowed fact becomes readable; a
	// blocked one is removed from the readable corpus and recorded. Either way the
	// fact stops being pending.
	Resolve(ctx context.Context, id int64, d Decision) error

	// Defer records a failed attempt and leaves the fact pending for a later tick.
	// The reason is a fixed-vocabulary string, never model or content text.
	Defer(ctx context.Context, id int64, reason string) error

	// Abandon stops the worker retrying a fact. The fact stays pending, and pending
	// means unreadable, so giving up is safe: the content is retained for review but
	// never served. It must no longer be returned by PendingFacts.
	Abandon(ctx context.Context, id int64, reason string) error
}

PendingStore is the storage the worker drives. Kept to four methods so the state machine is legible: a pending fact either resolves, gets another try, or is given up on.

type Policy

type Policy struct {
	// BlockThreat is the lowest screen threat score (0-10) that blocks a write.
	// A verdict below it is recorded and allowed.
	//
	// The model verdict is the only blocking signal. detect's score is recorded as
	// corroboration but never rejects a write on its own -- see the note on
	// [Decision.DetectScore] for why that would be actively harmful here.
	BlockThreat int

	// Enforce turns blocking on. With Enforce false the policy screens and records
	// exactly as it would otherwise but never rejects a write, so a deployment can
	// measure its false-positive rate before anything is lost.
	Enforce bool
}

Policy is the enforcement configuration.

The thresholds are the only knobs, and they are deliberately few. Every additional dial is another way to end up in a state nobody intended and nobody can describe.

func DefaultPolicy

func DefaultPolicy() Policy

DefaultPolicy blocks on a verified model verdict at the midpoint of the threat scale.

Threat 6 is a judgment call, not a calibrated figure -- airlock does not claim its scale is calibrated and neither does this. It sits above the range where the model reports unease it cannot pin to a span (those verdicts fail evidence verification and never produce a finding at all) and below the top of the scale, so an unambiguous instruction aimed at a model does not need to be maximally florid to be caught.

type Screener

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

Screener applies a Policy to candidate writes.

The zero Generator is valid: with no generator, every write is screened by regex alone and returns OutcomePending, so it is picked up once one is configured.

func NewScreener

func NewScreener(p Policy, gen Generator, log *slog.Logger) *Screener

NewScreener builds a Screener. A nil generator disables the model half; a nil logger discards screening logs.

func (*Screener) Policy

func (s *Screener) Policy() Policy

Policy returns the configured policy.

func (*Screener) Screen

func (s *Screener) Screen(ctx context.Context, content string) Decision

Screen evaluates content and returns the enforcement decision.

It never returns an error. A screening failure is not the caller's problem to handle: there is exactly one sensible response to "the model did not answer", and it is the fail-open-and-queue behavior encoded here, not something each call site should re-decide. Failures are logged and surface as OutcomePending.

func (*Screener) SetTimeout

func (s *Screener) SetTimeout(d time.Duration)

SetTimeout overrides the per-call model timeout. Zero restores the default.

type Stats

type Stats struct {
	Screened  atomic.Int64
	Allowed   atomic.Int64
	Blocked   atomic.Int64
	Deferred  atomic.Int64
	Abandoned atomic.Int64
}

Stats are cumulative worker counters, safe to read while it runs.

type Worker

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

Worker screens pending writes in the background.

Screening is deliberately outside the synchronous write path. A write returns as soon as it is durable, marked pending and therefore invisible to every read, and this worker decides its fate afterwards. That is what buys the generous per-call timeout: a screen taking 7 seconds against a loaded local model is fine when nothing is waiting on it, and fatal when a user is.

The safety property holds throughout. At no point between the write returning and the screen completing is the content retrievable, so a slow, backlogged, or entirely stopped worker delays memories from appearing but never serves an unscreened one. Failure lands on the side of losing availability, not containment.

func NewWorker

func NewWorker(store PendingStore, sc *Screener, cfg WorkerConfig, log *slog.Logger) *Worker

NewWorker builds a screening worker. A nil logger discards its output.

func (*Worker) ProcessOnce

func (w *Worker) ProcessOnce(ctx context.Context) int

ProcessOnce claims one batch of pending facts and screens them. Exposed for tests and for a one-shot backfill.

It returns the number of facts it took a terminal decision on.

func (*Worker) Start

func (w *Worker) Start()

Start begins the background loop.

func (*Worker) Stats

func (w *Worker) Stats() *Stats

Stats returns the worker's counters.

func (*Worker) Stop

func (w *Worker) Stop()

Stop signals the loop to stop and waits for the current tick to finish.

type WorkerConfig

type WorkerConfig struct {
	// Interval is how often to poll for pending facts.
	Interval time.Duration

	// Concurrency is how many facts are screened at once.
	//
	// Each screen is one model call, so this is the knob that decides whether the
	// backlog drains or grows, and also the one that can flatten a local model
	// serving other work. At roughly 7s per screen, concurrency 1 clears about 500
	// facts an hour -- fine for steady state, slow for a first pass over a corpus of
	// thousands. Raise it to backfill, lower it to stay polite.
	Concurrency int

	// Batch is how many pending facts to claim per tick. It is clamped to at least
	// Concurrency, since a batch smaller than the worker pool leaves workers idle.
	Batch int

	// MaxAttempts is how many failed screens a fact gets before the worker abandons
	// it.
	//
	// Without a ceiling one unscreenable fact stalls the queue forever: PendingFacts
	// returns oldest-first, so the same row comes back every tick and the backlog
	// behind it never moves. Abandoning is safe precisely because pending is
	// unreadable -- the content is kept for review, just never served and never
	// retried.
	MaxAttempts int
}

WorkerConfig tunes the worker. Zero values take documented defaults.

Jump to

Keyboard shortcuts

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