check

package
v0.3.2 Latest Latest
Warning

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

Go to latest
Published: Oct 20, 2026 License: Apache-2.0 Imports: 21 Imported by: 1 module, 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 check runs rule checks over a netlist IR Design. Pure IR operations, no I/O (CONSTRAINTS C1).

A rule is a Rule value whose Eval is written against the query primitives in query.go (Select/Exists/Count over a shared Model) rather than raw loops over the IR. The built-in rules and their Spec twins (spec.go) live in stdlib/rules/builtin and install through RegisterBuiltins. See docsite/content/architecture/rules-and-checks.md#the-evaluation-model.

Index

Constants

View Source
const (
	ClassResistor             = model.ClassResistor
	ClassCapacitor            = model.ClassCapacitor
	ClassInductor             = model.ClassInductor
	ClassFerrite              = model.ClassFerrite
	ClassThermistor           = model.ClassThermistor
	ClassDiode                = model.ClassDiode
	ClassLED                  = model.ClassLED
	ClassTVS                  = model.ClassTVS
	ClassZener                = model.ClassZener
	ClassFuse                 = model.ClassFuse
	ClassConnector            = model.ClassConnector
	ClassTestConnector        = model.ClassTestConnector
	ClassTestPoint            = model.ClassTestPoint
	ClassClock                = model.ClassClock
	ClassOscillator           = model.ClassOscillator
	ClassCrystal              = model.ClassCrystal
	ClassCeramicResonator     = model.ClassCeramicResonator
	ClassIC                   = model.ClassIC
	ClassTransistor           = model.ClassTransistor
	ClassIdealDiodeController = model.ClassIdealDiodeController
	ClassUnknown              = model.ClassUnknown

	RoleAnode   = model.RoleAnode
	RoleCathode = model.RoleCathode
	RolePower   = model.RolePower
	RoleGround  = model.RoleGround
	RoleGate    = model.RoleGate
	RoleSource  = model.RoleSource
	RoleDrain   = model.RoleDrain
	RoleUnknown = model.RoleUnknown
)

The component.class and pin-role vocabularies, re-exported from model.

View Source
const (
	KindNet       = "net"
	KindComponent = "component"
	KindPin       = "pin"
	// KindEndpoint is a geometric location rather than a captured entity. Its Ref is a dangling wire
	// endpoint's "x,y" in the sheet geometry frame.
	KindEndpoint = "endpoint"
	// KindBus is a source bus construct, not a net. Its Ref is the display label and its geometry
	// join key is the construct's uuid (Finding.Prov.NativeId), sent to the client as
	// Subject.bus_id so a bus-not-modeled finding highlights its own drawn bus (WS7-042b).
	KindBus = "bus"
	// KindSymbol is a symbol REFERENCE that failed to resolve (WS1-052), naming an absent file rather
	// than anything placed. Its Ref is the reference as the source spelled it (`res.sym`,
	// `Library:Symbol`). Not KindComponent, because one missing file is one finding however many parts
	// it cost pins; the affected ref-des live in Message and the reader.unresolved_symbol relation.
	KindSymbol = "symbol"
	// KindSignal is a REQUIREMENT SLOT, the role a profile asks for ("STB", "CANL"), with Ref the
	// signal name as the profile spells it. It is the one kind that may name something the design
	// lacks. An interface rule's verdict subject is (host, role), so a host missing four signals gets
	// four distinct verdict ids rather than one id on four rows. It never highlights, since the
	// finding's own subject is the component.
	KindSignal = "signal"
)

Finding subject kinds, the values of Entity.Kind.

View Source
const (
	KeyCategory     = "category"     // human organization bucket (provider-specific)
	KeyTier         = "tier"         // expressiveness tier (docsite/content/architecture/rules-and-checks.md#expressiveness-tiers): "P" | "R" | "A" | "X"
	KeyDistribution = "distribution" // how the rule's source may be shared (see Dist* values)
	KeySite         = "site"         // where the rule is evaluated; see Site* values
	KeySource       = "source"       // the owning RuleSource's name, stamped by Catalog composition (absent = built-in)
)

Well-known Tag keys the built-in rules populate. Tags is open, so any rule may add its own keys; these are the axes the catalog and default group-by understand.

View Source
const (
	SiteCheck      = "check"
	SiteDiagnostic = "diagnostic"
)

Implementation-site tag values (Tags[KeySite]). SiteCheck, the default when absent, is an analysis over the netlist IR. SiteDiagnostic means the reader detects the problem at ingestion and records it in InputDiagnostics, and the rule only reports what the reader found, because the signal cannot be reconstructed from the normalized IR. See docsite/content/architecture/rules-and-checks.md#where-a-rule-runs.

View Source
const (
	CategoryConnectivity = "connectivity" // ERC-style: pins, nets, drivers, connectivity
	CategoryNaming       = "naming"       // conventions and pairing over names
	CategoryPower        = "power"        // rails, decoupling, protection
	CategoryDatasheet    = "datasheet"    // derating and margin rules that join a parameter
	CategoryBoard        = "board"        // geometric DRC over the board tier (WS3-008)
	CategoryIntegrity    = "integrity"    // read-health tripwires: a firing means fix the read, not the design
)

Category tag values used by the built-in rules (set as Tags[KeyCategory]). The engine attaches no meaning to them; they only group the catalog.

View Source
const (
	DistOpen            = "open"             // derivable from open sources (KiCad DRC, gov specs)
	DistPublicReference = "public-reference" // encodes a public-referenced fact (IPC, vendor app notes)
	DistProprietary     = "proprietary"      // vendor/customer-locked; studied for coverage only
)

Distribution tag values say how a rule's source may be shared. They also gate catalog visibility, so the shareable build surfaces open and public-reference rules while proprietary suites load separately, out of repo.

View Source
const (
	LocatableNormal   = ""               // a normal entity; no explanation
	LocateVirtual     = "virtual_symbol" // a `#`-ref power port / flag (#PWR/#FLG), not a placed part
	LocatePowerRail   = "power_rail"     // a power/ground rail distributed via taps, no drawn wire
	LocateNotInDesign = "not_in_design"  // the ref/net is absent from the loaded netlist
)

LocateReason codes (WS9-039) say why the entity named by (kind, subject) may not be highlightable in a faithful view. The empty string means a normal entity, expected to highlight. These are netlist facts and so layout-independent. The UI pairs the reason with an actual on-screen resolution check before showing it, so a rail that DOES highlight on an auto-layout never surfaces a note. service/sheets.go maps each code onto the checks.proto LocateReason enum.

View Source
const (
	NetClassConstraintKind   = kicadNetClassKind
	BoardRulesConstraintKind = "board_rules"
)

NetClassConstraintKind and BoardRulesConstraintKind are the ir.Constraint kinds this model reads, exported so a reader's own constants can be held to them by a test outside core.

View Source
const DefaultTraceHops = 6

DefaultTraceHops is the radius a trace searches to when the caller names none.

Unlike ProtectionReachHops and its neighbours this number is a SEARCH BUDGET and not an electrical claim. Those radii encode a physical fact (a clamp six resistors away does not protect the pin), so widening one turns real findings into false passes. Nothing about a trace degrades with distance, and a route eight crossings long is still the route. The bound is here so the walk terminates on a large board and so a "no route" answer is a statement someone can check, which is why the radius is printed with the answer and exposed as a flag rather than fixed here.

View Source
const DesignWideReason = "concludes about the design as a whole, so it is not asked of a net or part"

DesignWideReason is the skipped-rule reason a scoped run gives for a ScopeDesignWide rule.

View Source
const NoBoardReason = "design carries no board geometry (WS1-006 sidecar)"

NoBoardReason is the reason Available gives a rule that reads the board tier when the run attached no board. A caller saying "no board was read" compares against it rather than a copy of the text (agni issue 848).

View Source
const PowerPathReachHops = 3

PowerPathReachHops is the radius the power-entry walk asks at (UnprotectedPowerReach), one hop wider than ProtectionReachHops. A power entry crosses connector, fuse and bead before the regulator's input node, and the signal radius would stop short of the regulator and read an unprotected path as having nothing to protect.

View Source
const ProtectionReachHops = 2

ProtectionReachHops is the radius every protection guard asks at, so a clamp, fuse or power pin counts only within two series crossings of the net. The number is ELECTRICAL (series impedance before the clamp conducts), not a search budget, so it is much smaller than query.reachHops, which answers a topology question. Widening it credits distant clamps and turns unprotected pins into silent passes. See docsite/content/architecture/net-solving.md#how-far-a-walk-crosses-series-parts.

View Source
const PullUpReachHops = 3

PullUpReachHops bounds the walk from an I2C bus to the rail its pull-up returns it to. Like the hop constants in reach.go it is ELECTRICAL, not a search budget. A pull-up behind a series isolation resistor is an ordinary two hops, and past three the series resistance is comparable to the pull-up, so the bus no longer returns high in time. Widening it passes buses that are electrically unheld. See docsite/content/architecture/net-solving.md#how-far-a-walk-crosses-series-parts.

View Source
const SupplyPathReachHops = 1

SupplyPathReachHops is the radius a supply-compatibility question asks at (WS3-028). One crossing lets a filter bead or series resistor between a regulator and its load through. Wider is wrong because voltage does NOT degrade along the path, so every part would look fed by every regulator. See docsite/content/architecture/net-solving.md#how-far-a-walk-crosses-series-parts.

View Source
const ToolNetNamePattern = `^(N\$|unconnected-\(|Net-\(|\$)`

ToolNetNamePattern matches the names a tool gives a net no designer named: an EDIF or synthetic "N$1", "$N1", and KiCad's "Net-(R1-Pad2)" and "unconnected-(J1A-MID0-PadK40)". A KiCad name is built from a pin's own name, so a rule that reads meaning from a net's name must skip these, or the pin name inside reads as the designer's (agni issue 1019).

View Source
const UnitOhm = classify.UnitOhm

UnitOhm is the canonical ohm symbol a Quantity carries, re-exported so a rule comparing resistances does not import the classify package for one string.

Variables

View Source
var (
	DefaultClassVocab   = classify.DefaultClassVocab
	BuildClassVocab     = classify.BuildClassVocab
	SetActiveClassVocab = classify.SetActiveClassVocab
	ActiveClassVocab    = classify.ActiveClassVocab
	ParseComponentClass = classify.ParseComponentClass

	// The role-lexicon functions, re-exported from classify (WS3-072). SetActiveRoleVocab/ActiveRoleVocab
	// address the same process-global the net.role stamp reads, so a --conventions role override set
	// through check.SetActiveRoleVocab takes effect at ReadDesign time (StampNetRoles).
	DefaultRoleVocab   = classify.DefaultRoleVocab
	BuildRoleVocab     = classify.BuildRoleVocab
	SetActiveRoleVocab = classify.SetActiveRoleVocab
	ActiveRoleVocab    = classify.ActiveRoleVocab
)

The classification-lexicon functions, re-exported from classify. SetActiveClassVocab/ActiveClassVocab address the same process-global vocab the ingestion pass reads, so a --conventions class override set through check.SetActiveClassVocab takes effect at ReadDesign time.

View Source
var RenderRoute = model.RenderRoute

RenderRoute is the single renderer for a series route, re-exported so a rule printing one need not import core/model for the format alone.

Functions

func ACCoupled

func ACCoupled(m Model, n *ir.Net) bool

ACCoupled reports whether a SERIES capacitor carries the net, the structural signature of AC coupling (WS3-088). It tells a coupling cap from a decoupling one by the far side. A decoupling cap returns to ground or a rail, while a coupling cap's far side is another signal.

func Available

func Available(r *Rule, m Model) (ok bool, reason string)

Available reports whether r can produce meaningful findings over m, and if not, a short reason a UI can show. It derives from r.Reads, so a rule is unavailable when it reads a fact whose tier is absent for this design. m is nil for the design-less catalog listing, where the param tier is absent and board and capability rules are available. The review runner treats the result as an authoritative per-run gate, not only a listing hint.

func AvailableBoardUnread added in v0.3.0

func AvailableBoardUnread(r *Rule, m Model, board bool) (ok bool, reason string)

AvailableBoardUnread is Available for a model built without its board tier, given whether the run would attach a board. ListRules asks it, because opening a design must not parse the board (agni issue 943) while the listing must still say what a run of that design would skip (agni issue 950). The parameter set and every source-format capability are read off m exactly as the run's model answers them, so m must be built from the same netlist, overlay and corpus as the run's. Whether a board is attached is known from the board tier's format without reading it, as GetDesign lists the Board sheet.

func BuiltinSpecs

func BuiltinSpecs() map[string]*Spec

BuiltinSpecs returns the built-in rules' declarative-twin map (empty when stdlib/rules/builtin is not imported). Callers must not mutate the returned map.

func CapRatedVoltageLimits

func CapRatedVoltageLimits(spec *parampb.PartSpec) []*parampb.Parameter

CapRatedVoltageLimits selects a cap spec's rated-voltage rows, in volts. A row matches on the alias set or on a printed name containing "rated voltage", since vendors print one limit as "VDC", "WV" or "Rated Voltage". The kind may be recommended-operating or absolute-max, because a rated voltage is the operating envelope and some sheets state it as a maximum.

func Citation

func Citation(spec *parampb.PartSpec, p *parampb.Parameter) string

Citation renders the datasheet side of a finding's provenance as a message string, naming the document revision, page, table and extraction method the limit came from. The design side is Finding.Prov. Finding.DatasheetProv carries these same facts structured (via DatasheetCitationOf), so a renderer should read that rather than parse this text.

func CompFinding

func CompFinding(msg string) func(*ir.Component) Finding

CompFinding is the component-subject counterpart of NetFinding.

func CompareToBound added in v0.2.0

func CompareToBound(measured float64, unit string, b Bound, quantity, limitName string) (Outcome, *Witness)

CompareToBound is the single comparison a limit rule makes, returning the outcome AND the witness from one call so a rule cannot reach a Pass without the statement that justifies it. An unstated bound returns NoLimit and a nil witness.

quantity names what is being measured for the human statement ("nominal"), limitName names the bound as the datasheet spells it ("absolute maximum", "recommended range").

func ComponentProv added in v0.2.2

func ComponentProv(m Model, refDes string) *ir.Provenance

ComponentProv locates a component in its source file, or nil when the design carries no provenance for it. A rule that builds a finding on a component subject passes it through, so the finding stays locatable in the viewer.

func ComponentValue

func ComponentValue(m Model, refDes string) (value float64, unit string, ok bool)

ComponentValue returns a component's value in its unit's SI BASE unit, the unit symbol, and whether a number is available (WS3-118).

ok is false when the component has no value attribute, has one the parser could not read, or is not a part that has a value at all. A rule treats all three the same way and skips, never guesses; a REPORT may want to tell them apart (see ComponentValueText).

THE UNIT IS RETURNED, NOT ASSUMED, and a caller comparing against a threshold must check it. An empty unit means the number is known and the unit is not (a bare value on a class the conventions do not cover). Treating it as the unit you wanted is the unlike-units coercion docsite/content/architecture/datasheet-layer.md#comparison-semantics forbids, so use ComponentValueIn for the common case.

func ComponentValueIn

func ComponentValueIn(m Model, refDes, unit string) (float64, bool)

ComponentValueIn returns a component's value only when it is expressed in the unit the caller asked for, in that unit's SI base. A rule should reach for this one, so a resistance check asking for ohms gets nothing from a capacitor instead of a farad count.

An EMPTY stored unit matches nothing, since a bare number is not evidence of the unit you want.

func ComponentValueText

func ComponentValueText(m Model, refDes string) (string, bool)

ComponentValueText returns the SOURCE TEXT a component's value was read from, and whether it carried one at all. A finding should quote this ("10k" rather than 10000) so a reviewer can find it on the schematic.

It is present even when the parse FAILED, so a report can tell "states DNP, no number read" apart from "states nothing".

func ConnDir

func ConnDir(m Model, c *ir.Connection) ir.PinDirection

ConnDir resolves one connection's electrical direction. The connection-level "direction" attribute wins, for a virtual power-symbol pin whose component is not in Components and so has no part-type pin (WS1-014). Otherwise the part-type pin decides, via PinDir.

func Count

func Count[T any](xs []T, pred func(T) bool) int

Count returns how many elements of xs match pred (the count primitive; the basis for the Tier-A aggregate rules).

func CountDir

func CountDir(dirs []ir.PinDirection, pred func(ir.PinDirection) bool) int

CountDir returns how many of dirs satisfy pred.

func DeclaredTiers

func DeclaredTiers(r *Rule) map[FactTier]bool

DeclaredTiers returns the gated tiers a rule's Reads declare, deduplicated.

OptionalReads are INCLUDED, where Available skips them. Available asks whether an absent tier makes the rule inapplicable, and an optional read (esd-protection's ESD rating, used only to EXEMPT a finding) does not. This asks whether the author declared the tier at all, and an optional read is a declaration. Excluding them made the audit flag esd-protection's param tier as undeclared (WS3-122).

func DiffConventionPresent

func DiffConventionPresent(m Model) bool

DiffConventionPresent reports whether the design uses differential-pair naming at all, meaning at least one net has its expected complement (a complete X_P/X_N pair). Orphan reporting is gated on it, so a design with no differential pairs stays silent even when names happen to end in _P, _DP or +.

func DirString

func DirString(d ir.PinDirection) string

DirString maps a pin direction to the string vocabulary Specs and the pin.type relation compare against, spelled as KiCad spells the types. PASSIVE is mapped because unspecified-pin-with-driver reads "unspecified" as "the author declared nothing", and a passive pin declares something (otherwise every two-terminal part fires).

func DocTitle

func DocTitle(spec *parampb.PartSpec, docRef string) string

DocTitle resolves a doc_ref to its SourceDoc title within a spec; "" when the id names no doc, which a caller renders as "unknown source".

func DrainCurrentLimits

func DrainCurrentLimits(spec *parampb.PartSpec) []*parampb.Parameter

DrainCurrentLimits selects a spec's continuous drain-current rows, kind ABSOLUTE_MAX, in amps.

The rating is stated at a case or ambient temperature the conditions carry, and a real design derates well below it. This returns the vendor's number as printed, so a rule comparing against it can report only a current limit set above the part's own rating. It says nothing about whether a limit below the rating is derated enough.

func EntityRef added in v0.2.0

func EntityRef(e Entity) string

EntityRef is the kind-owned half of one element's name. A pin joins its ref-des and designator with a dot, which is already this codebase's pin-key spelling (a KiCad pad key is built as RefDes+"."+Number).

func EsdRatingLimits

func EsdRatingLimits(spec *parampb.PartSpec) []*parampb.Parameter

EsdRatingLimits selects a spec's ESD-rating rows, kind ABSOLUTE_MAX (an ESD rating is a max survivable stress), in volts, at or above icEsdFloorVolts, and system-level only. An ESD rating is printed in KILOVOLTS as often as in volts, and param.InBaseUnit converts it (agni issue 148).

func Exists

func Exists[T any](xs []T, pred func(T) bool) bool

Exists reports whether any element of xs matches pred (the exists primitive).

func ExpectedDiffNegative

func ExpectedDiffNegative(name string) (string, bool)

ExpectedDiffNegative returns the complementary negative net name for a differential-pair positive member, and ok=false when the name is not a positive member. The suffix families are "_P"/"_N", "_DP"/"_DN", and trailing "+"/"-". Matching is case-insensitive, and the returned name keeps the source casing.

func ExternalSignalNet

func ExternalSignalNet(m Model, n *ir.Net) bool

ExternalSignalNet reports the scope the ESD rules share, a connector-facing SIGNAL net that is not a rail or ground (by name or by fact), not a deliberately unconnected pad, and not on a power path (input-protection's, WS3-011). esd-protection and esd-clamp-not-tvs split these nets by what protects them (nothing, or a Zener clamp).

The net.connector_signal query relation projects it too, so a datalog ESD check scopes itself exactly as the Go rules do (WS3-061). It cannot be composed in datalog because its guards read net ATTRIBUTES that have no relation of their own.

func FailuresOnly added in v0.2.0

func FailuresOnly(eval func(context.Context, Model) []Finding) func(context.Context, Model) []Verdict

FailuresOnly adapts a pre-verdicts rule body to the Eval signature, turning each Finding into a Fail (or Inconclusive) verdict and claiming nothing about the subjects that did not fail. A built-in rule using it has not been converted (agni issue 391). Converting means deleting the wrapper, writing the map, and setting StatesConsideredSet. core/query's RuleFromQuery also uses it.

It invents no Witness. The Finding is the evidence, and a Witness restating the message would make an unconverted rule look converted.

func FetBreakdownLimits

func FetBreakdownLimits(spec *parampb.PartSpec) []*parampb.Parameter

FetBreakdownLimits selects a spec's drain-source breakdown rows, kind ABSOLUTE_MAX, in volts. Breakdown is an absolute maximum on a real datasheet (the voltage past which the part stops being a switch), so unlike OutputVoltageLimits the kind is constrained.

It is the third connection-aware extractor. SupplyAbsMaxLimits reads what a part can WITHSTAND on its supply, OutputVoltageLimits what a part DELIVERS, and this what a switch can BLOCK.

func ICESDRated

func ICESDRated(m Model, n *ir.Net) bool

ICESDRated reports whether a component on the net or within its 2-hop series reach declares a datasheet ESD rating at or above the credit floor. That is IC-integrated ESD, which protects a connector-facing signal without a discrete TVS (WS3-073). It is false without a seeded param set (m.PartSpec returns nil), so esd is unchanged on a design read with no datasheets.

func IntentionallyUnconnected

func IntentionallyUnconnected(m Model, n *ir.Net) bool

IntentionallyUnconnected reports whether a net's lack of connections is deliberate: a pin on it carries the format's no-connect flag, a connected pin resolves to the NO_CONNECT electrical type, or the designer named it as a no-connect. A tool's own stub name is not evidence, because KiCad names every unlabelled one-pin net "unconnected-(...)", flagged or not (agni issue 1019).

func IsBusLike

func IsBusLike(m Model, n *ir.Net) bool

IsBusLike reports a shared-DISTRIBUTION net the series-reach walk must not cross INTO. It is a ground, a net marked global, or one with more than maxWalkFan connections. A rail-looking NAME is NOT bus-like, since protection rules walk through nodes like VBUS and 5V_PROT, and neither is the power_driven fact, since a PWR_FLAG marks the power entry nets the walk exists to reach. The reach walk and the net.bus_like relation share this ONE definition (WS3-080), and the walk's start net is never treated as a stop.

func IsControlName added in v0.2.2

func IsControlName(name string) bool

IsControlName reports whether a net name is a regulator's enable or mode-select input. "20V_EN" enables the 20V converter and sits at the sequencer's logic level, not at 20V. These are safe to probe, unlike a feedback tap or a switch node, and are not rails because the voltage token names the converter rather than the net.

func IsDriver

func IsDriver(d ir.PinDirection) bool

IsDriver reports whether a pin can source a signal onto its net: a plain output, a power source (a regulator output or a PWR_FLAG, mapped to POWER_OUT), a bidirectional or tri-state pin (it drives when enabled), or an open-collector or open-emitter output (it drives one way). All but OUTPUT and POWER_OUT answer "is this net driven?" without being hard drivers for the two-drivers conflict, where a shared bus and a wire-OR are both legal (agni issue 1082).

func IsFeedbackName

func IsFeedbackName(name string) bool

IsFeedbackName reports whether a net name is a regulator feedback or sense node, a high-impedance divider tap that must not be probed. A rail-NAMED net like "VCC1.2_ETH_FB" reads as feedback rather than as a rail. Consults the active lexicon (WS3-069).

func IsGateDriveName added in v0.2.2

func IsGateDriveName(name string) bool

IsGateDriveName reports whether a net name is the supply a regulator's gate driver runs from ("12V_VDRV"). It is a supply, hence separate from IsControlName, but it sits at the driver's own rail rather than at the converter's output.

func IsGroundName

func IsGroundName(name string) bool

IsGroundName matches the ground-rail naming conventions (GND and variants, VSS, EARTH). Ground pins read as power_in while decoupling is asserted on the supply side, so matching by name keeps the rule from reporting every cap-less design a second time on its ground net. The patterns come from the active naming lexicon (WS3-069), so a project can extend them via --conventions.

func IsPassiveClass

func IsPassiveClass(c ComponentClass) bool

IsPassiveClass reports whether a component class is a two-terminal passive (plus test points): parts whose pins conduct rather than listen or drive, so direction-based rules treat them as transparent. Some libraries type a passive's pins INPUT (the Mentor EDIF corpus does for capacitors), and counting those as logic inputs is a false positive.

func IsPowerRailName

func IsPowerRailName(name string) bool

IsPowerRailName reports whether a net name follows a supply-rail convention (VCC, VDD, VBUS, VIN, +3V3, 12V, ...). It identifies rails in sources with no pin directions or power symbols (an EDIF netlist), where the name is the only evidence. Rail nets belong to input-protection and bulk-cap, not ESD. The patterns come from the active naming lexicon (WS3-069), so a project can extend them via --conventions, and hierarchical sheet prefixes ("/psu/12V") are stripped first.

func IsSwitchingName added in v0.2.2

func IsSwitchingName(name string) bool

IsSwitchingName reports whether a net name is a regulator's power-stage node (the switch node, its bootstrap cap, or the same node under a vendor spelling). "12V_SW" is named after the rail it produces and is not one. Read together with IsFeedbackName wherever a rule asks whether a rail-named net is really a rail.

func IsToolNetName added in v0.2.2

func IsToolNetName(name string) bool

IsToolNetName reports whether a net's name is one a tool made up rather than one a designer gave it.

func IsVirtualRef

func IsVirtualRef(ref string) bool

IsVirtualRef reports whether a connection's component is a virtual connectivity symbol (a KiCad #PWR/#FLG), which contributes power evidence but is not a physical part. Consumer-intent guards (a decoupling rule asking "does a real part draw from this rail") must not count it, while driver/ERC semantics (power-input-not-driven, the driver conflict) must.

func ListedAvailable added in v0.2.2

func ListedAvailable(r *Rule, params bool) (ok bool, reason string)

ListedAvailable is Available for a catalog listed with no design model, as ListRules does with no snapshot or one whose netlist cannot be read, given whether the run would carry a datasheet parameter set. Only a run can say whether a board or a source capability is present, so those gate nothing here, as with a nil model. The parameter set is known before any read, from the design's project and the host's own corpus, and asking a nil model instead called every datasheet-tier rule unavailable on a project with params/, so a viewer selecting only available rules never ran them (agni issue 940).

func LocateReason

func LocateReason(m LocateModel, kind, subject string) string

LocateReason classifies why the entity named by (kind, subject) may not highlight, from the design Model's indexed reads (never a raw-proto scan): a `#`-ref virtual power/flag symbol, a power/ground rail (no drawn wire on a faithful schematic), or a ref/net not in the design. It returns LocatableNormal ("") for an entity that should highlight. kind is check.KindComponent or check.KindNet; any other kind is LocatableNormal. Over-classifying a rail is safe because the caller only shows the reason when a highlight actually resolves nothing.

func Memo added in v0.2.2

func Memo(m Model, key any, build func() any) any

Memo returns the value cached on m under key, building it with build the first time it is asked for. A model that is not a Memoizer builds every time, which is correct and only slower.

It exists for derived structures several rules read whole, such as the datalog fact base every query-backed rule evaluates over (agni issue 810): rebuilding it per rule was most of a check's time on a large board. A value cached here must be a pure function of the model and the key, and must not be mutated by whoever reads it, because every later caller gets the same one. key should be a value of a type private to the caller's package, so two packages cannot collide.

func NetBias

func NetBias(m Model, n *ir.Net) (up, down bool)

NetBias reports which way a net is held by a bias resistor, toward a rail (up), toward ground (down), or neither (WS3-088). See netBias for the walk, and NetBiasResistors for the form that also names the resistors.

func NetBiasResistors

func NetBiasResistors(m Model, n *ir.Net) (refs []string, up, down bool)

NetBiasResistors returns the sorted ref-designators of the resistors that bias n toward a rail or ground, with the same direction NetBias reports. Use it when a caller has to say something ABOUT the resistor (its value) rather than only about the net. On a divider the refs are still returned while the direction is neither, since both resistors are real and only the net's LEVEL is ambiguous.

func NetDirs

func NetDirs(m Model, n *ir.Net) []ir.PinDirection

NetDirs resolves the electrical direction of every connection on a net, in connection order.

func NetFinding

func NetFinding(msg string) func(*ir.Net) Finding

NetFinding is the Report constructor for a net subject. It builds the subject with NetEntity, so the net's per-instance id travels with the finding.

func NetHasRole

func NetHasRole(n *ir.Net, role ir.Role, nameMatch func(string) bool) bool

NetHasRole reports whether a net carries a naming role (rail, ground, feedback, ...). When the net has ANY stamped role (ir.Net.roles, filled at ingestion by classify.StampNetRoles, WS3-072) the set is authoritative and a role is present iff it is in the set. Only an empty set, from a path that skipped the loader such as a hand-authored test IR, falls back to nameMatch. Same shape as the Model reading device_classes with a re-derive fallback. The Model's IsGroundNet/IsRailNet and the net-role relations (stdlib/relations) all read through it.

func NetRoleSource added in v0.2.0

func NetRoleSource(n *ir.Net, role ir.Role, nameMatch func(string) bool) (ir.RoleSource, bool)

NetRoleSource reports the evidence that established a role on a net, and whether the net carries that role at all. It is separate from NetHasRole because almost every caller wants only the boolean.

A net whose role came from the NAME fallback (no stamped set at all, e.g. a hand-authored test IR) reports ROLE_SOURCE_CONVENTION, since the fallback is a naming convention read at the point of use rather than at ingestion.

func NoConnectMarked added in v0.2.2

func NoConnectMarked(n *ir.Net) bool

NoConnectMarked reports whether a net carries a designer's no-connect: the reader's flag attribute, or a name the designer chose to say so (NC_..., no_connect...).

func NominalVoltageFromName

func NominalVoltageFromName(name string) (volts float64, ok bool)

NominalVoltageFromName derives a rail's nominal voltage from its net name (3V3 -> 3.3), the only voltage evidence a directionless netlist carries. ok is false when the name carries no parseable voltage token or two tokens disagree ("12V_TO_5V"), and every voltage rule relies on that refusal. It is exported so an out-of-package rule (the design-intent voltage-domain check) reads the same name->volts logic the net.nominal_voltage fact projects (C20).

func OcpThresholdLimits

func OcpThresholdLimits(spec *parampb.PartSpec) []*parampb.Parameter

OcpThresholdLimits selects a controller spec's overcurrent-threshold rows, in volts. Real controller sheets print this row in MILLIVOLTS and param.InBaseUnit converts it (agni issue 148). The limit kind is not constrained, since a trip threshold is a characteristic or recommended-operating row rather than an absolute maximum.

func OcpThresholdSymbols

func OcpThresholdSymbols() []string

OcpThresholdSymbols returns the overcurrent-threshold alias set for Rule.ParamSymbols, so a review runner can tell "this switch trips high enough" from "nothing on this design states a trip threshold". Without it, a design that seeds no controller resolves no load switch, the rule reports nothing, and the bound item scores a pass on a check that never ran.

func OhmsLawCurrent

func OhmsLawCurrent(volts, ohms float64) (amps float64, ok bool)

OhmsLawCurrent returns the current in AMPS that volts across ohms produces, and whether the inputs admit an answer. It is a NAMED PHYSICAL OPERATION rather than a Quantity.Div, the first arithmetic in the engine that crosses two units (WS3-085).

No general unit algebra, because every other consumer compares within one unit, and a dimension system for six units and three operations would have no second caller. The parameter names state which unit each side must be in, so passing farads is a visible mistake. Reconsider if a fourth or fifth physical relation shows up.

ok is false for a non-positive or non-finite resistance and for a non-finite voltage. Zero ohms matters most, since a sense resistor read as 0 (a short, or an unplaced value) would yield +Inf and read downstream as an enormous current. A NEGATIVE voltage is allowed (a low-side sense threshold is negative) and yields a negative current.

func OnResistanceLimits

func OnResistanceLimits(spec *parampb.PartSpec) []*parampb.Parameter

OnResistanceLimits selects a spec's RDS(on) rows, in ohms, any limit kind since RDS(on) is a characteristic row. A sheet ordinarily prints a modern FET's RDS(on) in milliohms, and param.InBaseUnit converts it (agni issue 148).

A real sheet states RDS(on) several times under different gate drives and junction temperatures (the seeded BSS138 carries three), so a caller gets several rows and must pick the one it means. There is no single on-resistance to return.

func OutputCurrentLimits

func OutputCurrentLimits(spec *parampb.PartSpec) []*parampb.Parameter

OutputCurrentLimits selects a spec's OUTPUT-CURRENT rows, in amps, any limit kind for OutputVoltageLimits' reason. Milliamps are the ordinary spelling for a sub-amp regulator and param.InBaseUnit converts them (agni issue 148).

func OutputCurrentSymbols

func OutputCurrentSymbols() []string

OutputCurrentSymbols returns the output-current alias set, for a rule to declare in Rule.ParamSymbols so the review runner can tell "the design is within budget" from "nothing on this design states an output current" (WS3-095). It is the list OutputCurrentLimits matches on, so the seeding gate and the extractor cannot drift apart.

func OutputVoltageLimits

func OutputVoltageLimits(spec *parampb.PartSpec) []*parampb.Parameter

OutputVoltageLimits selects a spec's OUTPUT-voltage rows, in volts, any limit kind (a regulator states its output as a recommended-operating or characteristic row). The max is what a downstream part is exposed to, which is the number a compatibility check needs.

It is the counterpart to SupplyAbsMaxLimits, which reads what a part can WITHSTAND where this reads what it DELIVERS. A connection-aware rule joins one of each across the net between two parts (WS3-028).

func PinCitation added in v0.2.0

func PinCitation(spec *parampb.PartSpec, pin *parampb.Pin) string

PinCitation renders the datasheet citation for a PIN's declaration, as Citation does for a parameter. param.Validate requires provenance on a pin function too, so a pin-level fact is as checkable against a page as a value.

func PowerPinReachable

func PowerPinReachable(m Model, n *ir.Net) bool

PowerPinReachable reports a power-direction pin on the net or on any net in its 2-hop series reach (WS3-011), so the split between esd and input-protection does not depend on whether a bead sits between the connector and the regulator.

func PullUpReachesRail added in v0.2.0

func PullUpReachesRail(m Model, n *ir.Net) bool

PullUpReachesRail reports whether a rail is reachable from n by crossing RESISTORS only, within PullUpReachHops, without passing through ground.

Not Reach, because Reach drops a bus-like net (more than maxWalkFan connections) outright, and a supply rail on a real board is one. This walk keeps the rail as a legal DESTINATION and never continues through it. ReachToTerminus does that too but crosses every pass class (agni issue 374).

RESISTORS only, since a pull-up is a resistor to a rail, and crediting a bead would pass buses on the strength of a filter. Ground is never crossed, since a resistor to ground is a pull-DOWN and ground is a plane that would make everything reachable.

It is the boolean projection of PullUpPathToRail, where the walk lives.

func PullUpVerdict added in v0.2.0

func PullUpVerdict(m Model, n *ir.Net) (Outcome, *Witness, []ContextSubject)

PullUpVerdict decides one I2C net and returns the outcome with its witness from a single call, as CompareToBound does for a limit, so a Pass always carries the path that justifies it.

A FAIL carries a witness too, stating the hop limit, since a bus whose pull-up sits four hops away is a different situation from one with no pull-up at all.

func QuantityEqual

func QuantityEqual(a, b float64) bool

QuantityEqual reports whether two quantities in the same unit are the same number within valueEpsilon. Use it instead of == whenever either side did not come from ParseQuantity.

Zero compares exactly, since a relative tolerance around zero is meaningless and zero is a legal resistance rather than a rounding artifact.

func RailMaxVoltage

func RailMaxVoltage(n *ir.Net, name string) (volts float64, ok bool)

RailMaxVoltage is the "net.max_voltage" fact, the rail voltage a net declares. A max_voltage attribute wins when present, otherwise the name-derived nominal (nominalVoltageFromName) is the only evidence a netlist carries. ok is false when neither yields a number, and consumers skip rather than guess.

func ReachableOfClass added in v0.2.0

func ReachableOfClass(m Model, n *ir.Net, class ComponentClass) string

ReachableOfClass names the first part of a class on n or within the protection reach, in walk order, or "" when there is none. It returns the REF rather than a bool so a witness can name the clamp a reviewer should go and look at.

func RecommendedOperatingLimits

func RecommendedOperatingLimits(spec *parampb.PartSpec) []*parampb.Parameter

RecommendedOperatingLimits selects a spec's supply-voltage rows, kind RECOMMENDED_OPERATING, in volts, with at least one of min/max present. The range is two-sided where SupplyAbsMaxLimits is a one-sided ceiling, so its consumer (rail-nominal-out-of-recommended) acts only on a part declaring a single such row. See singleRecommendedRow in stdlib/rules/builtin/rule_rail_nominal.go.

func RegisterBuiltins

func RegisterBuiltins(rules []*Rule, specs map[string]*Spec)

RegisterBuiltins installs the standard EE rule catalog as the anonymous built-in source, whose rules pass through the Catalog un-namespaced. stdlib/rules/builtin calls it from its init. rules is exposed through Builtins and BuiltinRules. specs holds the Go-eval'd rules' declarative twins (BuiltinSpecs), which the parity tests hold to their Go Eval. A second call replaces the set rather than appending, so the last import wins.

func RegisterSource

func RegisterSource(s RuleSource)

RegisterSource adds a rule source to the process-global registry, so a suite living in another module is picked up by the CLI and serve (both compose DefaultCatalog / CatalogWith) with no re-wiring. It is the rule-side twin of formats.Register (WS12-004). Call it from an init or the composing binary's main, and the rules appear in ListRules and CheckDesign as "<source>/<rule>".

RegisterSource panics on a nil source, an anonymous source, a name outside [a-z0-9-]+, or a duplicate source name, as image.RegisterFormat and sql.Register do. The deeper checks (no "/" in a rule name, no duplicate composed names) run when DefaultCatalog / CatalogWith builds.

func RegisterSpecFunc

func RegisterSpecFunc(name string, fn *SpecFunc)

RegisterSpecFunc registers fn for Spec Call nodes under name, replacing any existing registration. Registration is meant for package init time (an embedder wiring its own helpers before building rules); it is not synchronized for concurrent use.

func RelationCitation added in v0.2.0

func RelationCitation(spec *parampb.PartSpec, rel *parampb.PinRelation) string

RelationCitation renders the datasheet citation for a PIN RELATION, the third carrier of ParamProvenance after a parameter and a pin.

func ResistivePowerWatts

func ResistivePowerWatts(amps, ohms float64) (watts float64, ok bool)

ResistivePowerWatts returns the power in WATTS a current of amps dissipates in ohms, and whether the inputs admit an answer. Like OhmsLawCurrent, it is a NAMED operation so a rule does not spell its own `i*i*r`, where a unit bug could hide.

It sizes a load switch's pass FET at the current the design draws. The figure is REPORTED, never judged, because a verdict needs a thermal limit (package resistance, ambient, accepted rise) that no datasheet row or declaration states today.

ok is false for a non-finite current or resistance and for a negative resistance. A NEGATIVE current yields the same positive power. Zero is allowed on both sides, since a zero-ohm link dissipates nothing, unlike OhmsLawCurrent's zero divisor.

func RuleMetaProto

func RuleMetaProto(r Rule) *checkspb.RuleMeta

RuleMetaProto encodes a rule's identity, prose, and declared gates. Reads and Primitives are not carried, because both are derived from the rule's body by its compiler, and serializing them would let a definition assert reads that disagree with what it actually does.

func RunAll added in v0.2.2

func RunAll(ctx context.Context, m Model, rules []*Rule) ([]Finding, []Verdict, error)

RunAll is Run and RunVerdicts together, evaluating each rule ONCE (agni issue 810). A caller that wants both contracts, as a check response does, used to call the two and so ran the whole catalog twice, since a finding is a projection of a verdict. The findings and verdicts are exactly the ones Run and RunVerdicts return over the same rules, gate included.

func ScopeOf

func ScopeOf(name string) (scope, leaf string)

ScopeOf splits a KiCad-style qualified name into its sheet scope and leaf, so "/amp1/SIG" gives ("/amp1", "SIG") and a bare root name gives ("", name).

func ScopedComponents added in v0.3.0

func ScopedComponents(ctx context.Context, m Model) []*ir.Component

ScopedComponents is m.Components() narrowed to the scope ctx carries. A pin in the scope does not bring its component in, since a verdict about the part is not a verdict about one of its pins.

func ScopedNets added in v0.3.0

func ScopedNets(ctx context.Context, m Model) []*ir.Net

ScopedNets is m.Nets() narrowed to the scope ctx carries, every net when it carries none.

func SeedsAnySymbol

func SeedsAnySymbol(m Model, syms []string) bool

SeedsAnySymbol reports whether ANY component on the design carries a seeded datasheet parameter for one of syms, compared after alnumUpper so a spec written I_OUT answers for a declared IOUT. It is the review runner's WS3-097 gate for a rule that declares Rule.ParamSymbols. False means the rule had nothing to join against, so zero findings is a data gap and not a clean design.

Callers pass the symbols they want and never the rules for matching them, since symbol spelling is a model-layer concern.

func Select

func Select[T any](xs []T, pred func(T) bool) []T

Select returns the elements of xs matching pred (the select primitive).

func SpecNames

func SpecNames() (overs, collections, facts, funcs []string)

SpecNames returns the entity sets, collections, facts, and registered functions a definition may reference in this build, sorted. It is the spec language's lexicon made readable, for an error message, a documentation surface, or an author checking what a definition can name.

func SpecProto

func SpecProto(s Spec) *checkspb.SpecBody

SpecProto encodes a Spec as its wire form. It panics on a Term or Expr outside the closed vocabulary, which can only happen if a node type was added without a case here. That is a programming error, caught the first time anything encodes it, rather than a silently truncated definition.

func SubjectParam added in v0.3.0

func SubjectParam(e Entity) string

SubjectParam spells an entity the way a scoped check names it (agni issue 897): `net:NAME`, `component:REF`, or `pin:REF.PIN`. `agni check --subject` reads this spelling, a verdict link carries it as `subject=`, and the viewer parses it back, so a link asks the same scoped question the CLI does. It is "" for a kind no scope covers (a bus, an endpoint, a symbol).

The viewer's reader of this spelling is held to this one by core/check/testdata/subject_param_twin.json.

func SubjectParams added in v0.3.0

func SubjectParams(es []Entity) []string

SubjectParams spells each entity a scope can name, in order, leaving out the ones it cannot.

func SubjectRefs added in v0.2.0

func SubjectRefs(v Verdict) string

SubjectRefs joins a verdict's subject refs for the callers that ORDER or DISPLAY a tuple as one string (the report's row sort, the CLI table). The kinds are left out because those callers are arranging rather than naming; VerdictID is the name.

func SupplyAbsMaxLimits

func SupplyAbsMaxLimits(spec *parampb.PartSpec) []*parampb.Parameter

SupplyAbsMaxLimits selects a spec's supply-pin rows, kind ABSOLUTE_MAX, in volts. It is the datasheet lookup behind supply-exceeds-abs-max.

func SupplyInputPin

func SupplyInputPin(m Model, refDes, designator string) bool

SupplyInputPin reports whether a pin consumes a supply rail, format-neutrally. It is the entity both datasheet rail rules (supply-exceeds-abs-max, rail-nominal-out-of-recommended) quantify over. PinDir == POWER_IN suffices because classify.StampPowerInPins fills POWER_IN at ingestion on a supply-named input pin a reader (EDIF) left under-typed (WS3-072).

func TVSReachable

func TVSReachable(m Model, n *ir.Net) bool

TVSReachable reports a TVS on the net or on any net in its 2-hop series reach (WS3-011). ESD structures commonly put a series resistor between the connector and the clamped node, which splits the net.

func Unpopulated added in v0.3.0

func Unpopulated(m Model, n *ir.Net) bool

Unpopulated reports whether every part on a net is marked do-not-populate, so the assembled board carries the copper and nothing on it (agni issue 961). Power flags and power symbols count for neither side, and a net with no real part on it is not unpopulated. A rule that would demand something of the net, a capacitor or a clamp, leaves such a net out, since crediting no unfitted part while still judging the unfitted circuit reports a fault on hardware that is never built.

func UnprotectedPowerReach

func UnprotectedPowerReach(m Model, n *ir.Net) bool

UnprotectedPowerReach reports whether SOME power input the connector net reaches is unprotected. It is the bool the spec FFI and the declarative twin need, and PowerPathProtection is the same walk with the evidence kept.

func VerdictID added in v0.2.0

func VerdictID(v Verdict) string

VerdictID is a verdict's stable name, `<rule>:(<kind>:<ref>,...)`, DERIVED from the verdict so a CLI run and a server run compute the same name without persisting anything.

Built from Rule, Kind and the kind's own reference, and NOT the outcome, so a link filed last month still resolves after the answer flips. Each kind owns its REF grammar (EntityRef) rather than the id being a positional tuple of checks.Subject's fields, so adding a kind leaves existing ids untouched.

Readable, not hashed, so a person can construct `pin-exceeds-abs-max:(pin:U12.7)` and ask about a terminal without running check first.

GENERATED, NEVER PARSED. The structure travels typed in Subjects, which is why a ref may keep its own colons (`symbol:Library:Symbol`) and commas (an endpoint's `0,0`) behind encodeRef alone.

KNOWN LIMIT: two nets sharing a name share an id, because a NetID would make the id impossible to type. The wire Subject joins by name too, and duplicate net names are themselves a reported defect.

func WithSubjectScope added in v0.3.0

func WithSubjectScope(ctx context.Context, s *Scope) context.Context

WithSubjectScope returns ctx carrying s. A nil scope means the whole design.

func ZenerReachable

func ZenerReachable(m Model, n *ir.Net) bool

ZenerReachable reports a Zener clamp on the net or on any net in its 2-hop series reach, the same reach TVSReachable walks (WS3-011). A Zener is a slower clamp than a TVS, so esd-protection does not count it, and esd-clamp-not-tvs (WS3-078) reports it separately for the review to weigh.

Types

type And

type And struct{ Xs []Expr }

And is true when every member is (an empty And is true).

type BoardNet

type BoardNet = model.BoardNet

The design read-surface CONTRACT lives in package model (WS1-043) so consumers depend on the interface, not this implementation. These aliases keep the historical check.* names, so every rule, test, and external caller that referenced check.Model / check.ComponentClass / ... is unchanged, because a type alias is the same type. check.NewModel* still return model.Model, and irModel implements it (asserted below).

type BoardRules added in v0.2.2

type BoardRules = model.BoardRules

The design read-surface CONTRACT lives in package model (WS1-043) so consumers depend on the interface, not this implementation. These aliases keep the historical check.* names, so every rule, test, and external caller that referenced check.Model / check.ComponentClass / ... is unchanged, because a type alias is the same type. check.NewModel* still return model.Model, and irModel implements it (asserted below).

type BoardSeg

type BoardSeg = model.BoardSeg

The design read-surface CONTRACT lives in package model (WS1-043) so consumers depend on the interface, not this implementation. These aliases keep the historical check.* names, so every rule, test, and external caller that referenced check.Model / check.ComponentClass / ... is unchanged, because a type alias is the same type. check.NewModel* still return model.Model, and irModel implements it (asserted below).

type BoardVia

type BoardVia = model.BoardVia

The design read-surface CONTRACT lives in package model (WS1-043) so consumers depend on the interface, not this implementation. These aliases keep the historical check.* names, so every rule, test, and external caller that referenced check.Model / check.ComponentClass / ... is unchanged, because a type alias is the same type. check.NewModel* still return model.Model, and irModel implements it (asserted below).

type Bound added in v0.2.0

type Bound struct {
	Min *float64
	Max *float64
}

Bound is an optional two-sided limit, matching what a datasheet row can state: a maximum only, a minimum only, both, or neither. Neither is the case that produces NoLimit.

func (Bound) Margin added in v0.2.0

func (b Bound) Margin(measured float64) float64

Margin reports how much room a measured value has before it crosses the bound, in the bound's own unit. Negative means the bound is already violated and the magnitude says by how much. An unstated bound returns +Inf, since nothing constrains the value.

Use it to pick the BINDING row when a datasheet states several limits of one kind for a pin (under different conditions). The smallest margin governs, not the first row enumerated. That holds for every bound shape, since a violated row goes negative and beats any passing row, and an unstated bound loses to any real limit.

func (Bound) Stated added in v0.2.0

func (b Bound) Stated() bool

Stated reports whether the bound constrains anything at all.

type Call

type Call struct {
	Fn   string
	Args []Term
}

Call invokes a registered SpecFunc (the Go FFI escape hatch) with evaluated Args. The function also receives the entities in scope, so an entity-shaped helper (e.g. intentionally_unconnected) takes no explicit args.

type Capability

type Capability string

Capability names a source-format ability a rule needs to evaluate soundly (WS3-096). A rule that infers a defect from the ABSENCE of a construct the format cannot express would false-fire there, so it declares the capability and Available reports not-applicable instead of a silent pass. The value is a stable contract string matching the design-level fact the same gate reads. Which formats lack each one is tabled in docsite/content/architecture/rules-and-checks.md#source-format-capabilities.

const (
	// CapTypesPowerOut means the source format classifies power-OUTPUT pins. Without it a rail's
	// driver reads as a plain input and power-input-not-driven cannot conclude "unpowered". The
	// queryable twin is design.types_power_out / the design.types_power_out fact.
	CapTypesPowerOut Capability = "design.types_power_out"
	// CapNoConnectChannel means the design can express an intentional no-connect (a NO_CONNECT-typed
	// pin, a no-connect flag, or a designer's NC_ / no_connect net name; see NoConnectMarked). Without it unconnected-pin cannot tell a deliberate open pin from
	// a forgotten one. The queryable twin is design.has_nc_channel / design.nc_channel.
	CapNoConnectChannel Capability = "nc_channel"
	// CapNetClass means the design carries tool-assigned net-class membership (WS3-105). A rule scoped
	// by net class selects nothing without it and reports clean. It depends on the design's CONTENT,
	// not its format grammar. The queryable twin is design.has_netclass / the design.has_netclass fact.
	CapNetClass Capability = "netclass"

	// CapRefDesCollisions means the READER checked this design for ref-des collisions. It is declared
	// per read (ir.InputDiagnostics.supplied) because only the reader knows whether it looked, and
	// duplicate-ref-des read as passing on formats where nothing looked (agni issue 309). The
	// queryable twin is supplies_ref_des_collisions.
	CapRefDesCollisions Capability = "ref_des_collisions"

	// CapNetClassDefs means the design declares net-class DEFINITIONS, the clearance, track width and
	// via sizes a class's nets should route at (WS3-111). Separate from CapNetClass because a project
	// can assign nets to a class it never defines, and a declared-vs-actual rule gated on membership
	// would then run over zero comparisons and pass. The queryable twin is design.has_netclass_defs.
	CapNetClassDefs Capability = "netclass_defs"

	// CapJunctionTaps means the READER examined wire-end-on-wire-body taps and recorded both the joined
	// and the silent ones, declared per read like CapRefDesCollisions. Only the KiCad reader looks at
	// wire geometry, so elsewhere wire-no-junction would find nothing and read as a pass. It gates on
	// the JOINED half, since a reader recording only the silent taps (the KiCad reader until agni issue
	// 420) has not examined the considered set.
	CapJunctionTaps Capability = "junction_taps"
)

type Catalog

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

Catalog is the composed rule set the engine runs, one or more RuleSources merged under the namespace/collision policy (WS3-006). Rules come in source registration order, then each source's own order, so findings and ListRules are stable. Non-built-in rules are exposed as COPIES with the prefixed name and a stamped source tag. The source's own *Rule values are never mutated, so a suite can be registered into several catalogs.

func CatalogWith

func CatalogWith(extra ...RuleSource) *Catalog

CatalogWith composes the built-ins, then every RegisterSource'd source, then the caller's extra sources, under the same collision policy. Every engine surface builds through it so registered sources are never dropped. The CLI passes its --conventions source here, and an embedder that wants explicit control instead of the global RegisterSource passes its suites as extras. It panics on a composition error, as DefaultCatalog does.

func DefaultCatalog

func DefaultCatalog() *Catalog

DefaultCatalog is what the CLI and serve wire, the built-ins plus every source added via RegisterSource, in registration order. With no source registered it is the built-ins alone. It panics on a composition error, since the built-ins or a registered source failing the policy is a programming error the catalog tests catch first.

func NewCatalog

func NewCatalog(sources ...RuleSource) (*Catalog, error)

NewCatalog composes sources under the collision policy and returns an error at wiring time rather than letting one rule shadow another:

  • only one anonymous source (the built-ins) may be registered;
  • a named source must match [a-z0-9-]+ and be unique;
  • rule names may not contain "/" (the separator belongs to the catalog);
  • composed names must be unique. Prefixing already stops a named source shadowing a built-in, and duplicates within or across sources are rejected.

func (*Catalog) Filter

func (c *Catalog) Filter(f Facets) []*Rule

Filter selects over the composed catalog with the same Facets semantics as the package-level Filter. That includes the source tag, so "--tag source=<name>" selects one suite.

func (*Catalog) Lookup

func (c *Catalog) Lookup(name string) *Rule

Lookup returns the rule with the exact composed name (bare for built-ins, "source/name" for the rest), or nil.

func (*Catalog) Rules

func (c *Catalog) Rules() []*Rule

Rules returns the composed catalog in composition order. Callers must not mutate the returned rules; non-built-in entries are catalog-owned copies.

func (*Catalog) Superseded

func (c *Catalog) Superseded() []Supersession

Superseded returns the supersessions applied when this catalog was composed, naming which rules were dropped, and which source replaced them. It is empty for a catalog composed from ordinary sources. A surface uses it to REPORT the suppression, since otherwise a report whose rules were removed reads as clean. Callers must not mutate the returned slice.

func (*Catalog) With

func (c *Catalog) With(extra ...RuleSource) (*Catalog, error)

With returns a new catalog carrying every rule c already has, plus the rules of extra, composed under the same namespacing and collision policy. c is not modified.

Use it to EXTEND a catalog you did not compose. A *Catalog holds composed rules, not its inputs, so rebuilding from the standard sources instead drops whatever else it carried (WS3-107).

The base rules are carried across VERBATIM rather than re-composed, because they are already namespaced and a name like "profile-overlay/spi-nor-signal-missing" would be rejected for containing the separator. Only extra is namespaced, and its names are checked against everything already present, so an extension can never shadow a rule the base carried.

func (*Catalog) Without

func (c *Catalog) Without(f Facets) *Catalog

Without returns a new catalog carrying every rule of c EXCEPT those matching f, the exclusion complement of Filter (WS3-056). c is not modified. The recorded supersessions carry across, and an exclusion here is not recorded as one.

An empty Facets matches every rule, as in Filter, so Without(Facets{}) returns an EMPTY catalog rather than an unchanged one.

type ClassVocab

type ClassVocab = classify.ClassVocab

The classification lexicon (WS3-070) lives in package classify (WS3-071) so the loader can run the ingestion pass without importing check. These aliases keep the historical check.* names for the --conventions loader (check/naming) and external overlays.

type Cmp

type Cmp struct {
	L  Term
	Op string
	R  Term
}

Cmp compares two terms, with "==" and "!=" on any value and "<", "<=", ">", ">=" on ints. Ordering a non-int is false, never a panic.

type ComponentClass

type ComponentClass = model.ComponentClass

The design read-surface CONTRACT lives in package model (WS1-043) so consumers depend on the interface, not this implementation. These aliases keep the historical check.* names, so every rule, test, and external caller that referenced check.Model / check.ComponentClass / ... is unchanged, because a type alias is the same type. check.NewModel* still return model.Model, and irModel implements it (asserted below).

type ContextSubject added in v0.2.0

type ContextSubject struct {
	Entity
	Role string
}

ContextSubject is one entity a finding's message names but is not about, with the part it plays.

Role is a short lower-case noun from the rule author's vocabulary ("terminal", "rail", "source"), not a closed enum. A Role can repeat within a finding (i2c-address-collision's "A and B both strap to address N"), so treat Context as a list rather than a map. Order matches the order the message names them.

func Ctx added in v0.2.0

func Ctx(e Entity, role string) ContextSubject

Ctx pairs an entity with its role. Build the entity with one of the constructors below so a net's NetID or a pin's designator is not dropped at the call site.

type CountOf

type CountOf struct {
	Over  string
	Where Expr
}

CountOf counts the members of a collection ("net.connections") matching Where. It is the count primitive, and a nil Where counts every member.

type DatasheetCitation

type DatasheetCitation struct {
	Doc        string  // the SourceDoc title (vendor doc number + revision), resolved from DocRef; "" if unresolved
	DocRef     string  // the SourceDoc id the value cites (the stable join key into PartSpec.docs)
	Page       int32   // 1-based page in the document
	Section    string  // the table or figure the value was read from
	Method     string  // how the value was extracted ("hand", "derive/v0", "mock", ...)
	Confidence float64 // extraction confidence in (0, 1]; a low value flags "verify before trusting"
	// Verification says whether a person has checked this value and whether that still holds for the
	// revision the corpus now has (param.Unverified/Verified/Stale/Unknown). "" for a citation with no
	// parameter behind it (a pin declaration, a relation bound).
	//
	// Separate from Confidence, which is fixed at extraction. A verification goes stale when the
	// document moves, and a stale one still looks fully trustworthy by every other signal.
	Verification string
	// VerifiedRevision is the document identity as printed when the value was verified, "" if it never
	// was. Doc is resolved from the CURRENT SourceDoc, so after a re-seed this is the only place the
	// checked revision survives, which lets a stale citation say "verified against SCES650K, corpus now
	// holds SCES650L". Display only, never compared.
	VerifiedRevision string
	// Corpus names whose transcription the value rests on: param.CorpusProject for the design's own
	// project params/, param.CorpusShared for a corpus the project does not own (--params,
	// --params-url), "" when the provider cannot say. A project's corpus is layered over a shared one
	// per MPN, so one run can cite both, and a value from outside the project is the one a reader
	// needs to see flagged (agni issue 749). Stamped by Run and RunVerdicts, not by the rules.
	Corpus string
	// contains filtered or unexported fields
}

DatasheetCitation records which document, page and section a datasheet-backed value came from, and how it was extracted. It is the typed twin of the Citation string the built-in datasheet rules put in a message, so a renderer can show it in columns and surface a low Confidence as "verify before trusting". The design side of the provenance stays in Finding.Prov.

func DatasheetCitationOf

func DatasheetCitationOf(spec *parampb.PartSpec, p *parampb.Parameter) *DatasheetCitation

DatasheetCitationOf builds the structured datasheet Citation for one seeded parameter. It resolves the SourceDoc title from the parameter's doc_ref, copies the page, section, method, and confidence, and derives the verification state against the revision that SourceDoc records. Both the string Citation() and the typed Finding.DatasheetProv are built on it.

Verification is derived here rather than stored on the finding because it is a fact about the document as the corpus holds it right now. Computing it at citation time means a re-seed changes every subsequent answer without anything having to be re-stamped.

func DatasheetCitationOfProv added in v0.2.0

func DatasheetCitationOfProv(spec *parampb.PartSpec, prov *parampb.ParamProvenance) *DatasheetCitation

DatasheetCitationOfProv is the same build from a bare ParamProvenance, for the rows that carry one but are not parameters, such as a Pin's declaration and a PinRelation's bound. Like PinCitation on the string side, it keeps the doc_ref resolution in one place so the row types cannot drift.

func DatasheetProvFor

func DatasheetProvFor(m Model, refDes, symbol string) *DatasheetCitation

DatasheetProvFor resolves the structured datasheet Citation for a component's parameter by symbol, so a datalog-authored rule (query.RuleFromQuery) can carry the same doc/page/section/method/ confidence the built-in datasheet rules attach directly. refDes is the finding's component subject. Nil when the component has no seeded spec, or the spec has no parameter with that symbol.

type Endpoint added in v0.2.0

type Endpoint struct {
	RefDes string `json:"ref_des"`
	Pin    string `json:"pin"`
}

Endpoint names one pin of one component by its ref-des and pin designator.

func (Endpoint) String added in v0.2.0

func (e Endpoint) String() string

String renders the endpoint the way a person writes it, "U7.3".

type Entity added in v0.2.0

type Entity struct {
	Kind string // KindNet | KindComponent | KindPin | KindEndpoint | KindBus | KindSymbol
	Ref  string // net name (KindNet), ref_des (KindComponent | KindPin), or the kind's own spelling
	Pin  string // pin designator, set only when Kind == KindPin
	// NetID is the per-instance net identity (ir.Net.id) for a net entity, so two nets sharing a
	// name are distinguishable and each locates to ITS wires. Empty for every other kind, and for a
	// net reached by name only; a consumer then joins by Ref.
	NetID string
}

Entity names ONE design entity. Subjects and context lists share this type, so a consumer that only wants to point at something treats them alike. It carries identity only, never severity, message or provenance.

func BusEntity added in v0.2.0

func BusEntity(label string) Entity

BusEntity names a source bus construct by its display label, which is also its geometry join key.

func ComponentEntity added in v0.2.0

func ComponentEntity(refDes string) Entity

ComponentEntity names a placed part by its reference designator.

func EndpointEntity added in v0.2.0

func EndpointEntity(x, y int64) Entity

EndpointEntity names a geometric location in the sheet frame, for the wire-end diagnostics that have no captured entity to point at.

func NetEntity added in v0.2.0

func NetEntity(n *ir.Net) Entity

NetEntity names a net, carrying the per-instance id so a duplicate name stays distinguishable.

func NetNameEntity added in v0.2.0

func NetNameEntity(name string) Entity

NetNameEntity names a net the caller holds only by NAME, so it carries no per-instance id. Use it for a rule that resolved a rail through a name lookup and never had the net itself. A consumer joins it by name and may match either of two same-named nets.

func ParseSubjectParam added in v0.3.0

func ParseSubjectParam(s string) (Entity, error)

ParseSubjectParam reads SubjectParam's spelling back. The kind ends at the first colon, so a net name may hold colons, and a pin's ref and designator split at the LAST dot, so `pin:J1.A.1` is pin 1 of J1.A. A spelling naming no entity a scope covers is an error.

func PinEntity added in v0.2.0

func PinEntity(refDes, pin string) Entity

PinEntity names one terminal of one part. Both halves are required.

func SymbolEntity added in v0.2.0

func SymbolEntity(ref string) Entity

SymbolEntity names a symbol REFERENCE as the source spelled it, which names a file rather than anything placed in the design.

type ExistsIn

type ExistsIn struct {
	Over  string
	Where Expr
}

ExistsIn is true when any member of a collection matches Where.

type Expr

type Expr interface {
	// contains filtered or unexported methods
}

Expr is a Spec predicate over one entity. Closed for the same reason as Term.

type ExternalFetLoadSwitch

type ExternalFetLoadSwitch struct {
	// Controller is the ref-des of the part driving the gate, identified by its datasheet stating an
	// overcurrent threshold. Fet is the pass element it drives. Sense is the shunt across the
	// controller's sense pins.
	Controller string
	Fet        string
	Sense      string
	// GateNet is the net carrying the controller's drive and the FET's gate terminal.
	GateNet string
	// SenseOhms is the shunt's value in ohms, read from the DESIGN (the component's value attribute),
	// not from any datasheet. It is the half of the trip current the vendor does not know.
	SenseOhms float64
	// TripAmps is the current at which the switch limits, Ocp's threshold divided by SenseOhms.
	TripAmps float64
	// Ocp is the controller's overcurrent-threshold row the trip current was computed from, kept so a
	// caller can cite the document it came from. Where a controller states several, the HIGHEST binds,
	// because it is the most current the switch will pass before it acts and so the worst case for
	// everything downstream of it.
	Ocp *parampb.Parameter
	// OnResistance is the FET's worst-case RDS(on) row, which IS this switch's effective on-resistance.
	// Nil when the FET is unseeded or states no comparable row; a caller must treat nil as "not known"
	// and never as zero, since a zero on-resistance is a perfect switch.
	OnResistance *parampb.Parameter
}

ExternalFetLoadSwitch is a load switch resolved from a switch CONTROLLER, the EXTERNAL MOSFET it drives, and the external SENSE RESISTOR that sets the current limit, joined to the seeded datasheet set. Every field is populated; a switch that could not be resolved completely is not returned at all, rather than returned with holes a caller might read as zeroes.

func ExternalFetLoadSwitches

func ExternalFetLoadSwitches(m Model) []ExternalFetLoadSwitch

ExternalFetLoadSwitches resolves every controller-plus-external-FET load switch in the design.

An ambiguous switch yields no entry. That covers a FET whose gate net carries two candidate controllers, a controller with two candidate shunts, and a shunt whose value the design does not state in ohms. An over-current verdict computed from the wrong resistor is worse than no verdict, because it looks as authoritative as a correct one.

type Facets

type Facets struct {
	Names []string
	Tags  map[string][]string
}

Facets is a rule selection over the catalog. Names selects by exact rule Name; Tags selects by tag key -> acceptable values. An empty Facets selects every rule; within one tag key the listed values OR, while distinct constrained keys (and Names) intersect (a rule must match every constrained axis). The CLI (agni check) and the web service (CheckDesign subset) both select through it, so subsets mean the same on both. Any tag key works, including ones provider-supplied rules invent.

type Fact

type Fact struct{ Name string }

Fact reads a named fact of the entity in scope. Names use the read vocabulary of docsite/content/architecture/web-app.md directly ("net.pin_count", "pin.electrical_type", "component.class", ...) so a Spec's derived Reads are its fact names verbatim; see specFacts for the full vocabulary and which entity scope each fact resolves against.

type FactTier

type FactTier string

FactTier names a family of declared facts that a GATE keys on. Three gates read a rule's Reads to decide whether the rule can run at all, and each keys on a prefix rather than on individual fact names, so no gate distinguishes param.esd_rating from param.supply_abs_max. The tier is therefore the granularity at which a declaration matters, and the one the Reads audit checks (WS3-122).

const (
	// TierParam is the datasheet parameter tier, injected per run via --params. Available reports a
	// rule reading it not-applicable when no set is seeded.
	TierParam FactTier = "param"
	// TierBoard is the board-geometry tier, per artifact. Available reports a rule reading it
	// not-applicable when the design carries no board.
	TierBoard FactTier = "board"
	// TierConnectivity is the pin/net-membership family. Run reports a rule reading it inconclusive
	// while any symbol is unresolved, because a placement that lost its pins is indistinguishable
	// from one that was never wired (WS1-052).
	TierConnectivity FactTier = "connectivity"
)

func TierOf

func TierOf(fact string) FactTier

TierOf reports which gated tier a declared fact belongs to, or "" for a fact no gate keys on (net.names, component.class and the rest, which are always available once a design is read).

This is the ONE definition of those prefix tests. Available, the unresolved-symbol gate and the Reads audit all call it, so the audit cannot drift from the tiers the gates actually apply.

type Finding

type Finding struct {
	Severity string // "error" | "warning" | "info"
	// Inconclusive marks a subject the rule examined and could not decide, rather than a defect
	// (agni issue 74). It is a per-subject result and not one of the review's design-wide needs-*
	// preconditions, because some cases have nothing to supply. A netlist states reset polarity
	// nowhere, while an unclassified controller resolves once its spec is seeded, and both are
	// inconclusive. The remedy goes in Message, as for a defect.
	//
	// Set it only where the rule can NAME the thing it could not resolve. See
	// docsite/content/build/check-rule.md#five-outcomes-and-the-three-that-are-not-a-pass.
	Inconclusive bool
	Rule         string
	// Subject is the ONE entity a reader has to change to fix this. A Verdict's subject tuple names
	// everything the rule quantified over; a Finding picks the one to edit and puts the rest in
	// Context. Its Ref must be one of the verdict's subject refs, and that is checked. See
	// docsite/content/build/check-rule.md#a-tuple-in-the-verdict-one-entity-in-the-finding.
	Subject Entity
	Message string
	Prov    *ir.Provenance
	// Context are the entities this finding's message NAMES but is not ABOUT (agni issue 349). A
	// crystal-load-caps finding names the terminal net XOUT1 while its subject is the crystal, and
	// without Context the drawing could not say which terminal was at fault.
	//
	// Only real design entities go here. Values, thresholds and units stay in Message. Usually empty.
	// See ContextSubject for Role and ordering.
	Context []ContextSubject
	// DatasheetProv is the datasheet side of a finding's provenance, one citation per value the
	// conclusion rests on, so a consumer can show document, page and section without parsing Message.
	// Empty for a finding no seeded datasheet value backs. A slice because a connection-aware rule
	// reads more than one part's datasheet (WS3-028).
	//
	// The review ratifies a finding only when EVERY citation clears the confidence floor
	// (review.isUnratified), since one weak input weakens the whole conclusion. Across findings the
	// quantifier flips, and one trustworthy finding makes the item a Fail.
	DatasheetProv []*DatasheetCitation
	// VerdictIDs names the verdict or verdicts this finding was projected from, each spelled as
	// VerdictID computes it, so a consumer holding only the finding can link to the proof (agni issue
	// 485). A verdict id is not recoverable from a Finding, since the verdict may be keyed on a tuple,
	// on a context entity, or on an element such as a signal that a finding cannot name. The run stamps
	// it where it holds both. Empty for a rule that states no considered set, because that rule's
	// verdicts are never published and an id would name nothing a viewer can resolve.
	VerdictIDs []string
}

Finding is one rule violation. Prov locates it in the source, nil when the source carries no provenance for the subject. The subject is an Entity, built through NetFinding/CompFinding or an Entity constructor, so a consumer can group and highlight by kind without parsing a string.

func Report

func Report[T any](xs []T, mk func(T) Finding) []Finding

Report maps a selection to findings (the report step every rule ends with). Subject and Prov come from the selected entity via mk.

func Run

func Run(ctx context.Context, m Model, rules []*Rule) ([]Finding, error)

Run evaluates rules over a Model and returns findings sorted by rule, then subject. The caller picks the rules (the full set, a subset, diff gates); RunDesign is the shortcut for the standard checks over a design. On a design with an unresolved symbol, a connectivity rule emits one Inconclusive finding instead of evaluating (see unresolvedSymbolGate).

It checks ctx before each rule and returns its error when the caller has gone (agni issue 795), rather than the findings so far, which would read as a run that found nothing more.

func RunBackground added in v0.2.2

func RunBackground(m Model, rules []*Rule) []Finding

RunBackground is Run for a caller with no context to pass, such as a test or an example: it cannot be cancelled, so it cannot fail, and it returns the findings alone. A caller serving a request, or with a command's context, uses Run so the work stops when nobody is waiting for it.

func RunDesign

func RunDesign(d *ir.Design) []Finding

RunDesign runs the installed built-in rules over NewModel(d). The built-ins install by importing stdlib/rules/builtin; without that import the set is empty and RunDesign returns no findings.

It runs without a caller's context, so it cannot be cancelled; a caller that has one uses Run.

func VerdictsToFindings added in v0.2.0

func VerdictsToFindings(vs []Verdict) []Finding

VerdictsToFindings projects a verdict list down to the findings the `check` path reports, which is how Rule.Findings and a spec derive findings from verdicts. Fail and Inconclusive carry a finding; Pass, NotConsidered and NoLimit are silence to `check`.

type In

type In struct {
	T   Term
	Set []string
}

In is true when the term's value is one of Set (string membership).

type IsTrue

type IsTrue struct{ T Term }

IsTrue is true when the term evaluates to boolean true. It is how a bool Fact or a bool FFI Call is used as a predicate.

type Lexicon

type Lexicon = classify.Lexicon

Lexicon pairs the two vocabularies as the value a design is READ with (WS3-106), so a caller composing project conventions holds one thing rather than two.

type Lit

type Lit struct{ V any }

Lit is a literal value: a string, an int, or a bool.

type LocateModel added in v0.2.0

type LocateModel interface {
	HasComponent(refDes string) bool
	HasNetName(name string) bool
	IsPowerRail(name string) bool
}

LocateModel is the slice of Model that LocateReason reads: whether a ref is a real component, whether a name is a real net, and whether that net is a power rail.

Named separately so a caller holding less than a whole Model can still ask, such as the findings annotation's LocateSource in service/sheets.go (agni issue 366). Model satisfies it.

type Match

type Match struct {
	T       Term
	Pattern string
}

Match is true when the term's string value matches Pattern, an unanchored RE2 compiled once at Validate time.

type Memoizer added in v0.2.2

type Memoizer interface {
	Memo(key any, build func() any) any
}

Memoizer is a Model that can keep values derived from it, so work every rule would otherwise repeat is done once per model. The model built by NewModel is one.

type Model

type Model = model.Model

The design read-surface CONTRACT lives in package model (WS1-043) so consumers depend on the interface, not this implementation. These aliases keep the historical check.* names, so every rule, test, and external caller that referenced check.Model / check.ComponentClass / ... is unchanged, because a type alias is the same type. check.NewModel* still return model.Model, and irModel implements it (asserted below).

func NewModel

func NewModel(d *ir.Design, opts ...ModelOption) Model

NewModel builds the default IR-backed Model for a design. WithBoard and WithParamProvider attach the board and datasheet tiers; without them the model has neither, and the rules that need them are not-applicable. The design's MPNs are joined either way.

type ModelOption

type ModelOption func(*irModel)

ModelOption configures a Model at construction. Options are applied before anything is derived, so an option the derivation reads (the lexicon) is in place when it runs.

func WithBoard added in v0.2.2

func WithBoard(bg *geom.BoardGeometry) ModelOption

WithBoard attaches the board-geometry tier. A nil bg is the same as omitting the option: the model reports HasBoard false and every board rule is not-applicable.

func WithIntent added in v0.2.2

func WithIntent(di *configpb.DesignIntent) ModelOption

WithIntent tells the model what the design's intent declares about its components, so ExposedConnector answers for this product rather than for the part (agni issue 831). Omitting it, or passing a nil intent, leaves every connector exposed.

func WithLexicon

func WithLexicon(lex *classify.Lexicon) ModelOption

WithLexicon tells the model which naming vocabulary its design was READ with, so the residual name projections (the spec name FFIs, pin-role derivation, and the stamped-role fallback for a hand-built IR) answer with the project's conventions rather than a process global (WS3-106). Pass the same *classify.Lexicon the loader used; omitting it means the process defaults.

func WithParamProvider added in v0.2.2

func WithParamProvider(specs param.ParamProvider) ModelOption

WithParamProvider attaches the params tier. specs is any param.ParamProvider, so a directory-loaded ParamSet, an in-memory mock or a datasheet service all plug in without touching the model or any rule; the model only ever calls Lookup on it. A nil provider is the same as omitting the option.

It is the PROVIDER that is optional, not the join key. Every model builds the MPN map, because a part number is a fact about the design (agni issue 748). The map used to exist only on the params constructor, so a model built the other way answered component.mpn with nothing on a design where every component carried one (agni issue 757).

type NetClassCascade added in v0.2.2

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

NetClassCascade resolves what a project DECLARED for a net from its net-class definitions, the way KiCad composes an effective netclass, which is PER FIELD rather than per class. A net's classes are sorted by priority ascending, the Default class pinned last and applying to every net including unclassed ones, and each field comes from the first class that states it. So a net in a high-priority class declaring only a clearance still takes its track width from the next class down, and there is no single winning class to pick.

The net.declared_* relations and the netclass-conformance rules both resolve through it (agni 698).

func NewNetClassCascade added in v0.2.2

func NewNetClassCascade(defs []*ir.Constraint) *NetClassCascade

NewNetClassCascade indexes a design's net-class definitions (Model.NetClassDefs). With none, every lookup reports nothing stated.

func (*NetClassCascade) Declared added in v0.2.2

func (c *NetClassCascade) Declared(classes []string, param string) (value float64, class string, ok bool)

Declared resolves one numeric field for a net belonging to classes. It returns the value from the first class in cascade order that states it, and that class's name, so a finding can say whose limit it is. ok is false when no class states the field, which is a net the project did not constrain rather than one that passes. A class the net names but the project never defined states nothing.

type Not

type Not struct{ X Expr }

Not negates its operand.

type Or

type Or struct{ Xs []Expr }

Or is true when any member is (an empty Or is false).

type Outcome added in v0.2.0

type Outcome string

Outcome is what a rule concluded about ONE subject. It is narrower than the review layer's per-ITEM outcome and does not reuse its spellings. A review outcome answers "did we get an answer to this question", mostly from preconditions around the rule, and this answers "what did the rule conclude about this thing", decided inside it. The five outcomes are tabled in docsite/content/build/check-rule.md#five-outcomes-and-the-three-that-are-not-a-pass.

const (
	// Pass: the comparison was made and the design is on the right side of it.
	Pass Outcome = "pass"
	// Fail: the comparison was made and the design is on the wrong side of it.
	Fail Outcome = "fail"
	// Inconclusive: the rule had every input and reached its decision, but the design cannot
	// discriminate between the cases (a power-path transistor may be an ideal-diode controller or a
	// plain switch, and a netlist cannot tell which).
	//
	// The outcome form of Finding.Inconclusive, so a consumer must NOT count it as a failure. Never
	// map it to NotConsidered, which produces no finding and would delete one the check path reports.
	Inconclusive Outcome = "inconclusive"
	// NotConsidered: the rule applied to this subject and never reached a comparison, with Reason
	// naming the step that stopped it.
	//
	// The verdict list IS the considered set, so an enumerator must emit this rather than drop a
	// subject. A dropped subject reports the same nothing as a rule that never looked, and under an
	// addressable id it answers 404, which reads as "no such pin" rather than "this rule could not
	// judge it".
	NotConsidered Outcome = "not-considered"
	// NoLimit: the subject reached the comparison and the datasheet row stated no bound, so nothing
	// was checked. Without it, a row stating no maximum and a design under a stated maximum take the
	// same silent return out of a rule (#387). CompareToBound returns it for an unstated Bound.
	NoLimit Outcome = "no-limit"
)

type PinInst

type PinInst = model.PinInst

The design read-surface CONTRACT lives in package model (WS1-043) so consumers depend on the interface, not this implementation. These aliases keep the historical check.* names, so every rule, test, and external caller that referenced check.Model / check.ComponentClass / ... is unchanged, because a type alias is the same type. check.NewModel* still return model.Model, and irModel implements it (asserted below).

func ScopedPins added in v0.3.0

func ScopedPins(ctx context.Context, m Model) []PinInst

ScopedPins is m.Pins() narrowed to the scope ctx carries: the scope's pins and every pin of its components.

type PinNetConflict

type PinNetConflict = model.PinNetConflict

The design read-surface CONTRACT lives in package model (WS1-043) so consumers depend on the interface, not this implementation. These aliases keep the historical check.* names, so every rule, test, and external caller that referenced check.Model / check.ComponentClass / ... is unchanged, because a type alias is the same type. check.NewModel* still return model.Model, and irModel implements it (asserted below).

type PinRole

type PinRole = model.PinRole

The design read-surface CONTRACT lives in package model (WS1-043) so consumers depend on the interface, not this implementation. These aliases keep the historical check.* names, so every rule, test, and external caller that referenced check.Model / check.ComponentClass / ... is unchanged, because a type alias is the same type. check.NewModel* still return model.Model, and irModel implements it (asserted below).

type PowerPathReport added in v0.2.0

type PowerPathReport struct {
	// Loads counts the reached nets carrying a real power-input pin, which is how many power entries
	// this connector net feeds. Zero means the walk found no power path.
	Loads int
	// Unprotected names the first reached load with neither a fuse crossed on the way nor a
	// protector on any net along that path, "" when every load is protected.
	Unprotected string
	// Protector names the first fuse or TVS credited on a protected path, "" when there is none to
	// credit. It is the pass's evidence, the part a reviewer should go and look at.
	Protector string
}

PowerPathReport is what the power-entry walk found from one connector net.

Check Loads before calling a net protected. UnprotectedPowerReach is false both for a protected 5V entry and for a USB data pair that reaches no supply pin at all. The first is a pass, and the second is not a subject of a power-entry rule.

func PowerPathProtection added in v0.2.0

func PowerPathProtection(m Model, n *ir.Net) PowerPathReport

PowerPathProtection walks the connector net's series neighborhood (WS3-011) and reports, per reached power input, whether a fuse was crossed on the way there or a protector sits on a net along that path. The check is per target because one connector can feed a protected 5V path and an unprotected 3V3 path, and protection on one must not excuse the other.

type PullUpHop added in v0.2.0

type PullUpHop struct {
	Resistor string // ref-des of the resistor crossed
	Net      string // the net reached by crossing it
}

PullUpHop is one leg of the walk from an I2C net to a rail, the resistor crossed and the net it landed on. It names the resistor rather than the pin because a reader locating the pull-up wants the part.

func PullUpPathToRail added in v0.2.0

func PullUpPathToRail(m Model, n *ir.Net) []PullUpHop

PullUpPathToRail returns the hops from n to the first rail reachable under PullUpReachesRail's rules, and nil when none is. The last hop's Net is the rail.

The path is the proof a passing bus carries, so a reviewer can ask "show me the pull-up" (#387).

type PullUpTermination added in v0.2.1

type PullUpTermination struct {
	Resistor string      // the resistor whose far side is the rail
	Rail     string      // the rail it landed on
	Path     []PullUpHop // from the subject net to the rail, the last hop crossing Resistor
}

PullUpTermination is one resistor that takes a net to a rail, with the rail it landed on and the hops it took to get there.

func AllPullUpPathsToRail added in v0.2.1

func AllPullUpPathsToRail(m Model, n *ir.Net) []PullUpTermination

AllPullUpPathsToRail returns every DISTINCT resistor that takes n to a rail, with the rail each landed on. PullUpPathToRail answers whether there is one, and this answers how many, which is where a second pull-up shows up (agni issue 516). Two 2.2k in parallel are an effective 1.1k, so the bus sinks about twice the current it was sized for, and reachability alone cannot see it.

DISTINCT BY RESISTOR, not by path and not by rail. Two routes through one resistor are one pull-up, and one resistor reaching two rails is still one part to remove.

It is PullUpPathToRail's walk without the early return. The `seen` set still prunes revisits of INTERMEDIATE nets, which drops a second ROUTE but never a termination, because every net reached enumerates ALL resistors whose far side is a rail.

type Reach

type Reach = model.Reach

The design read-surface CONTRACT lives in package model (WS1-043) so consumers depend on the interface, not this implementation. These aliases keep the historical check.* names, so every rule, test, and external caller that referenced check.Model / check.ComponentClass / ... is unchanged, because a type alias is the same type. check.NewModel* still return model.Model, and irModel implements it (asserted below).

type ReachStep

type ReachStep = model.ReachStep

The design read-surface CONTRACT lives in package model (WS1-043) so consumers depend on the interface, not this implementation. These aliases keep the historical check.* names, so every rule, test, and external caller that referenced check.Model / check.ComponentClass / ... is unchanged, because a type alias is the same type. check.NewModel* still return model.Model, and irModel implements it (asserted below).

type RecordingModel

type RecordingModel struct {
	Model
	// contains filtered or unexported fields
}

RecordingModel wraps a Model and records which GATED tiers a rule actually reaches for while it evaluates, so a rule's declared Reads can be checked against its behaviour instead of trusted (WS3-122).

A rule without a Spec twin has nothing holding its declaration to its body, so the declaration is prose, and three gates trust it. A rule that reads datasheet params without declaring them RUNS where it should have been gated to not-applicable, and reports over a tier that was never attached. Nothing about that fails loudly.

It records TIERS, not fact names, because that is the granularity the gates key on. See FactTier.

What an observation proves, and what it does not

A recorded read is EVIDENCE that the rule called that accessor and so depends on that tier. An ABSENT read is not evidence of anything, because a rule that early-returns on the fixture it was given never reaches its accessors. So a caller may soundly assert "everything read is declared" and may NOT assert "everything declared is read". The second reads as an over-declaration report to a human, never as a gate.

It embeds Model, so accessors it does not override delegate unchanged and a Model method added later keeps compiling. Adding a method that reaches a gated tier means overriding it here too, which is why each override is annotated with its tier.

Not safe for concurrent use. Rules run sequentially within one Run.

func NewRecordingModel

func NewRecordingModel(m Model) *RecordingModel

NewRecordingModel wraps m. A nil inner Model is allowed, and any accessor then panics through the embedded nil interface. That is intended, since a recorder over no design records nothing and would silently report every rule as reading no tier.

func (*RecordingModel) BoardNets

func (r *RecordingModel) BoardNets() []BoardNet

board tier.

func (*RecordingModel) IsConnected

func (r *RecordingModel) IsConnected(refDes string) bool

func (*RecordingModel) PartSpec

func (r *RecordingModel) PartSpec(refDes string) *parampb.PartSpec

param tier: the seeded datasheet join. ComponentMPN is NOT here, because it is the design-side part identity (a BomLine or an attribute), declared as component.mpn, and present with or without a seeded set.

func (*RecordingModel) PinConnected

func (r *RecordingModel) PinConnected(refDes, pin string) bool

func (*RecordingModel) PinDeclared

func (r *RecordingModel) PinDeclared(refDes, pin string) bool

func (*RecordingModel) PinDir

func (r *RecordingModel) PinDir(refDes, pin string) ir.PinDirection

func (*RecordingModel) PinName added in v0.2.0

func (r *RecordingModel) PinName(refDes, pin string) string

func (*RecordingModel) PinNetConflicts

func (r *RecordingModel) PinNetConflicts() []PinNetConflict

func (*RecordingModel) PinNetName

func (r *RecordingModel) PinNetName(refDes, pin string) string

func (*RecordingModel) PinRole

func (r *RecordingModel) PinRole(refDes, pin string) PinRole

func (*RecordingModel) Pins

func (r *RecordingModel) Pins() []PinInst

connectivity tier: everything sourced from a component's pins, which a placement that lost its symbol does not have.

func (*RecordingModel) Read

func (r *RecordingModel) Read() []FactTier

Read returns the tiers observed since the last Reset, sorted for stable reporting.

func (*RecordingModel) Reset

func (r *RecordingModel) Reset()

Reset clears the observation set, so one wrapped Model can be reused across rules without a previous rule's reads being attributed to the next.

type RoleVocab

type RoleVocab = classify.RoleVocab

The naming (role) lexicon moved to classify in WS3-072 for the same reason (the net.role stamp runs at ingestion). RoleVocab keeps its check.* name here.

type RouteHop added in v0.2.2

type RouteHop = model.RouteHop

The design read-surface CONTRACT lives in package model (WS1-043) so consumers depend on the interface, not this implementation. These aliases keep the historical check.* names, so every rule, test, and external caller that referenced check.Model / check.ComponentClass / ... is unchanged, because a type alias is the same type. check.NewModel* still return model.Model, and irModel implements it (asserted below).

type Rule

type Rule struct {
	Name     string // stable identifier, e.g. "single-pin-net"
	Severity string // "error" | "warning" | "info"
	Summary  string // one-line description for listings
	Impact   string // what goes wrong when violated
	// Remedy is what to DO about a violation, in the imperative, as one hardware engineer would say it
	// to another. It is the fix for the RULE rather than the subject, so it names the class of change
	// ("add a bulk capacitor at the rail's entry") and never a designator or a computed value. Where
	// the fix needs a number the engine cannot derive (an I2C pull-up's resistance), say what to size
	// it from and stop, since an invented value would read as the engine's authority.
	Remedy     string
	Detail     string   // long-form markdown: meaning, rationale, diagram, query structure
	Primitives []string // query primitives Eval composes
	Reads      []string // facts the rule reads, in the fact vocabulary (net.pin_count, on_net, param.max(...))
	// OptionalReads is the subset of Reads a rule consults only to EXEMPT findings, so their absence
	// does not make it inapplicable. Available's tier gate skips them. esd-protection, for example,
	// credits an IC's ESD rating when a datasheet is attached and still runs without --params, unlike
	// supply-exceeds-abs-max, whose finding REQUIRES the datasheet. Still listed in Reads for twin
	// parity and docs.
	OptionalReads []string
	// RequiresCapability lists the source-format capabilities a rule needs to evaluate SOUNDLY
	// (WS3-096). Where the format cannot express a construct the rule reads, the rule finds nothing
	// and looks like a clean pass, so Available reports not-applicable instead. Unlike Reads, a
	// capability is a property of the source format, always answerable from the Model. Every entry
	// is required; a capability that only NARROWS a rule is handled in its own Eval (as
	// power-input-not-driven and unconnected-pin do).
	RequiresCapability []Capability
	// ParamSymbols lists the datasheet SYMBOLS a rule joins on (the vendor spellings, e.g. the
	// output-current alias set), the rule-bound twin of an inline query's param_symbol (WS3-097). A
	// symbol seeded on no component yields zero findings, which looks like a design within its
	// limits, so a review runner reads this to render needs-data. Reads/Available do not cover it,
	// since they gate only on the params tier being attached.
	//
	// Declare it only where a finding REQUIRES the symbol. A rule that consults a value only to
	// exempt findings leaves it out, as with OptionalReads.
	ParamSymbols []string
	Tags         map[string]string // open classification (category, tier, distribution, ...); see index.go Key*
	// Eval MAPS every subject the rule was applied to onto a verdict. A pass carries its proof, an
	// undecidable subject says so, and a violation carries its Finding. Findings are the projection
	// of this (VerdictsToFindings, taken by Run), so a rule's findings cannot disagree with its
	// verdicts.
	//
	// The context is the caller's. A rule that walks a whole board, or evaluates a query, should stop
	// when it is done (agni issue 795); the runners check it between rules regardless, so a rule that
	// ignores it delays a cancellation by one rule at most.
	Eval func(context.Context, Model) []Verdict

	// SubjectShape declares the KINDS of a verdict's subject tuple, in the rule's order, for a rule
	// whose subject is a relation between entities. Empty means one subject of whatever kind the rule
	// enumerates. It tells a reader how to spell a verdict id without running the check, e.g.
	// `regulator-output-exceeds-abs-max:(component:U1,net:+5V,component:U5)`, where nothing else says
	// the source comes before the rail (see verdict.go for the id form).
	//
	// The arity is FIXED. TestSubjectShapeHolds fails a rule that emits different tuple sizes.
	SubjectShape []string
	// StatesConsideredSet reports whether Eval's verdicts are the rule's full CONSIDERED SET or only
	// its failures. The signature cannot say which. A pre-verdicts rule wrapped in FailuresOnly
	// returns only Fail verdicts, indistinguishable from a rule that examined exactly those subjects
	// and found them all wanting. RunVerdicts filters on it, so an unconverted rule contributes
	// nothing. Forgetting it under-reports a converted rule and can never over-report one.
	//
	// MIGRATION-ONLY. Once every rule converts (agni issue 391) the filter in RunVerdicts is a
	// tautology and the field can go.
	StatesConsideredSet bool
	// Scoping says how the rule answers a run asked about some nets or parts (agni issue 897). The
	// zero value runs the rule whole and keeps what the scope covers; see Scoping.
	Scoping Scoping
	// contains filtered or unexported fields
}

Rule is a named, self-describing check over the IR. Summary, Impact, Remedy and Detail are its documentation, so a rule is authored in one file and listed without a separate catalog.

Only the fields the engine acts on are typed: Name, Severity, Reads and Eval. Reads gates availability by fact tier (TierOf matches on the name), so spell each fact as the fact vocabulary does. Everything classificatory lives in Tags, an open key -> value bag the catalog groups and filters on (TreeBy, Filter), so an operator's or embedder's rule can add its own axes. See docsite/content/architecture/rules-and-checks.md#a-rules-library-in-go.

Run stamps Rule and Severity from the rule's metadata, so a rule body never sets them.

func BuiltinRules

func BuiltinRules() []*Rule

BuiltinRules returns the installed built-in rule set (empty when stdlib/rules/builtin is not imported). Callers must not mutate the returned slice.

func Filter

func Filter(rules []*Rule, f Facets) []*Rule

Filter returns the rules matching f, preserving the input order. An empty Facets returns rules unchanged; each constrained axis narrows by membership, and the axes intersect.

func OnFittedParts added in v0.3.2

func OnFittedParts(r *Rule) *Rule

OnFittedParts marks r as a rule that judges a part on the assembled board, such as a part's own voltage rating or an LED's orientation, and returns it. A verdict that names a part marked do-not-populate, directly or through one of its pins, becomes not considered and says which part, because the assembled board has no such part to judge (agni issue 1082). It is the blame-side twin of a credit-side rule asking Model.IsFitted, which agni issue 961 made every crediting rule do.

It is opt-in, because a rule about a part can still matter when the part is not fitted: two unfitted parts sharing a reference designator are still a netlist defect. It wraps r's Eval in place, so every surface that evaluates r gets it, and marking a rule twice wraps it once.

func RuleMetaFromProto

func RuleMetaFromProto(p *checkspb.RuleMeta) Rule

RuleMetaFromProto decodes rule metadata into the Rule fields a compiler then completes with Eval and the derived Reads/Primitives.

func SplitDesignWide added in v0.3.0

func SplitDesignWide(s *Scope, rules []*Rule) (run, designWide []*Rule)

SplitDesignWide separates the rules a run under s evaluates from the design-wide rules it leaves out. A nil scope leaves nothing out.

func (*Rule) Findings added in v0.2.0

func (r *Rule) Findings(ctx context.Context, m Model) []Finding

Findings is the rule's verdicts projected onto the findings contract, the violations alone, which is what `check` and every consumer of its output read. It is a projection rather than a second body, so the two cannot disagree.

func (*Rule) JudgesFittedParts added in v0.3.2

func (r *Rule) JudgesFittedParts() bool

JudgesFittedParts reports whether OnFittedParts has marked r.

type RuleSource

type RuleSource interface {
	Name() string
	Rules() []*Rule
}

RuleSource is one origin of rules, such as the built-ins, an embedder's Go suite or a design's own rule file. Nothing downstream distinguishes where a rule came from (WS3-006). Name is the source's namespace. The empty name is reserved for the built-ins, whose rule names pass through bare, and every other source's rules are exposed as "<name>/<rule>" so an external suite cannot silently shadow a built-in.

var Builtins RuleSource = builtins{}

Builtins is the built-in rule set as a RuleSource, and the only anonymous source. It reads the set RegisterBuiltins installed at call time. Without stdlib/rules/builtin imported the set is empty and the engine runs only the sources that ARE registered.

func NewSource

func NewSource(name string, rules []*Rule) RuleSource

NewSource wraps a fixed rule slice as a named RuleSource, for an embedder's suite or a test source. The name becomes the namespace prefix and must match the Catalog's source-name grammar, lowercase [a-z0-9-]+.

func RegisteredSources

func RegisteredSources() []RuleSource

RegisteredSources returns the sources added via RegisterSource, in registration order (the built-ins are not included). Callers must not mutate the returned slice.

type Scope added in v0.3.0

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

Scope is the set of design entities a run is asked about, so a question about one net or part answers for that net or part without running each rule over the whole board (agni issue 897).

It travels on the run's context (WithSubjectScope), as the work budget does, because it narrows one request and changes no rule's meaning. A run under a scope keeps the findings and verdicts the scope covers, whatever the rule did, so a rule that ignores the scope is slower and never wrong. A rule that declares ScopeSubjects reads it (ScopedNets, ScopedComponents, ScopedPins) and evaluates only those subjects, and TestScopedRunMatchesFilteredFullRun holds that to the answer a whole run filtered to the same subjects gives.

func NewScope added in v0.3.0

func NewScope(es ...Entity) *Scope

NewScope builds a scope over the given entities. A net matches by NetID when both it and the scope's entry carry one, and by name otherwise. A component covers itself and every pin on it, and a pin covers that one pin. Any other kind names nothing a rule enumerates and is ignored, so a scope built from bus or endpoint entities alone is empty.

func SubjectScope added in v0.3.0

func SubjectScope(ctx context.Context) *Scope

SubjectScope returns the scope ctx carries, nil for a run over the whole design.

func (*Scope) Covers added in v0.3.0

func (s *Scope) Covers(e Entity) bool

Covers reports whether e is one of the scope's entities, or a pin on one of its components.

func (*Scope) NetNames added in v0.3.0

func (s *Scope) NetNames() []string

NetNames returns the names of the scope's nets, for a rule that binds them into a query.

func (*Scope) PinDesignators added in v0.3.0

func (s *Scope) PinDesignators() (pins []string, ok bool)

PinDesignators returns the designators of the scope's pins, for a pin rule that binds them beside the parts. ok is false when the scope also holds a component, since that reaches every pin of the part whatever its designator, and binding the designators would leave those out.

func (*Scope) RefDes added in v0.3.0

func (s *Scope) RefDes() []string

RefDes returns the reference designators the scope reaches, its components and the parts its pins sit on, for a rule that binds them into a query.

func (*Scope) Results added in v0.3.0

func (s *Scope) Results(fs []Finding, vs []Verdict) ([]Finding, []Verdict)

Results narrows one run's findings and verdicts to the scope, keeping each list's order, for a caller holding a whole run (the service's kept results). A verdict stays when a subject is covered, and a finding stays when its own subject is covered or it was projected from a verdict that stays, which is the answer a scoped run gives. A nil scope keeps everything.

type Scoping added in v0.3.0

type Scoping int

Scoping is how a rule answers under a Scope.

const (
	// ScopeFiltered rules evaluate the whole design and the run keeps what the scope covers. It is
	// the default, and always correct for a rule whose results name the subjects they are about.
	ScopeFiltered Scoping = iota
	// ScopeSubjects rules read the scope and evaluate only its subjects, which is where a scoped run
	// saves time. Declaring it promises the answer a filtered whole run gives.
	ScopeSubjects
	// ScopeDesignWide rules conclude about something other than a net, part or pin (a symbol file, a
	// drawn bus, a wire end), so no subset of nets or parts has an answer of its own. A scoped run
	// does not run them, and the service names them as skipped with DesignWideReason rather than
	// filtering their results down to nothing, which would read as a clean answer.
	ScopeDesignWide
)

type Spec

type Spec struct {
	Over string
	Let  map[string]Term
	// Scope is which elements of Over this rule JUDGES. Nil means all of them (#397).
	//
	// Where is the VIOLATION condition, so an element the rule was never about fails it just as a
	// healthy one does. Once the interpreter states a considered set, "Where is false" reads as a
	// claim that the subject is fine, so Scope has to drop the others first. test-point-coverage
	// declares Over "nets" and is about RAILS. On the tutorial gateway design that is 4 rails among
	// 15 nets, and without Scope the rule would assert that 11 signal nets carry a test point.
	//
	// Scope is a per-element predicate in Where's environment, so it may quantify into a member
	// collection (ExistsIn over net.connections). It does NOT widen what a subject is. A spec still
	// ranges over one entity set (agni issue 370).
	Scope Expr
	// Where is the violation condition, meaningful only for elements inside Scope. Nil matches every
	// in-scope element.
	Where   Expr
	Message string
}

Spec is a rule body as a value: select the Over entity set, keep the entities matching Where, and report one finding per survivor. Let names intermediate terms usable in both Where (via Var) and Message. Message is a template; "{name}" interpolates a Let binding or a Fact by name, and "{name:q}" quotes the value like %q. Kind, the finding subject, and the provenance derive from the Over entity set (see specOvers). Name, Severity, the prose, and Tags stay on the Rule a Spec binds into, since the Spec is only the body.

func SpecFromProto

func SpecFromProto(p *checkspb.SpecBody) (Spec, error)

SpecFromProto decodes a Spec and validates it against this build's vocabulary. The error names what it did not recognize, because a definition that cannot compile has to say so when it is read. A rule that silently fails to exist is indistinguishable from one that ran and found nothing.

func (*Spec) DerivedPrimitives

func (s *Spec) DerivedPrimitives() []string

DerivedPrimitives returns the query primitives the spec composes (the vocabulary of docsite/content/architecture/rules-and-checks.md), sorted. Every spec is a selection, so "select" is always present; quantifiers add exists/count plus their collection's traversal, Match adds pattern, facts and called functions add what they declare.

func (*Spec) DerivedReads

func (s *Spec) DerivedReads() []string

DerivedReads returns the facts the spec reads (the vocabulary of docsite/content/architecture/web-app.md), sorted. It is the union of the declared reads of its Over set, facts, collections, and called functions. Being computed from the body, a spec-built rule's Reads cannot say less or more than the rule does.

func (*Spec) Eval

func (s *Spec) Eval(ctx context.Context, m Model) []Finding

Eval runs the spec over a Model and returns findings with Kind/Subject/Message/Prov set (Rule and Severity are stamped by Run, same as a Go Eval). The spec must be valid; use Validate (or bind through Rule, which validates) before evaluating specs from an untrusted source.

func (*Spec) Rule

func (s *Spec) Rule(meta Rule) *Rule

Rule binds the spec into a *Rule: meta supplies the identity, severity, prose, and tags; the spec supplies Eval and the derived Reads and Primitives. It panics on an invalid spec, because binding happens at package init or registry-build time, where a bad spec is a programming error rather than an input error.

func (*Spec) Validate

func (s *Spec) Validate() error

Validate checks that the Over set and every Fact, collection, Call target, Var binding, Cmp operator, Match pattern, and message placeholder resolve in the interpreter's vocabulary. A valid spec cannot fail at Eval time, which lets Eval return findings instead of errors, the same contract as a Go Eval closure.

func (*Spec) Verdicts added in v0.2.0

func (s *Spec) Verdicts(ctx context.Context, m Model) []Verdict

Verdicts is the interpreter as a MAPPER, emitting one verdict per element of Over that the rule judges, passes included. It is what a spec-authored rule binds to Rule.Eval.

Scope decides membership of the considered set and Where decides the outcome inside it. An out-of-scope element is not a pass, so it gets no verdict at all.

A PASS NAMES THE CLAUSE THAT DECIDED IT. Where is a violation condition, so a pass refutes it and the witness names the conjunct that did. "The condition did not hold" would read the same on every passing subject, which docsite/content/build/evidence.md calls decoration.

It stops early when ctx is done, returning what it has; the runner that called it then reports the cancellation rather than these verdicts, so a partial list is never read as complete.

type SpecFunc

type SpecFunc struct {
	Reads      []string
	Primitives []string
	Fn         func(m Model, ents map[string]any, args []any) any
}

SpecFunc is a Go function registered for Spec Call nodes, the FFI escape hatch for logic the AST should not express (multi-clause heuristics like intentionally_unconnected). Reads and Primitives declare what the function consumes in the rules' vocabulary, and a Spec's derived metadata includes them.

Fn receives the Model, the entities in scope keyed by scope name ("net", "conn", "component", ...), and the evaluated Args. It returns a string, int, or bool.

type SupersedingSource

type SupersedingSource interface {
	RuleSource
	Supersedes() []Facets
}

SupersedingSource is an OPTIONAL capability a RuleSource may also implement, for a source that REPLACES rules another source contributed instead of running alongside them. Composition type-asserts for it, because widening RuleSource would break every out-of-module suite.

Each returned Facets selects superseded rules with Filter's vocabulary. Names supersedes individual rules (a house rule replacing one built-in) and Tags a whole family (every rule of one interface profile, via the "profile" tag).

A source's declaration never applies to its own rules. See applySupersessions for why.

func NewSupersedingSource

func NewSupersedingSource(name string, rules []*Rule, supersedes ...Facets) SupersedingSource

NewSupersedingSource wraps a fixed rule slice as a named source that supersedes every rule matching any of the given Facets, for when the superseded set is known at construction.

type Supersession

type Supersession struct {
	By    string   // Name() of the superseding source
	Rules []string // composed names of the rules that were dropped, in catalog order
}

Supersession records that one source's rules were dropped from a composed catalog because another source superseded them. The Catalog keeps these so a surface can SAY what it suppressed, since a silently dropped rule turns a false failure into an invisible gap.

type Term

type Term interface {
	// contains filtered or unexported methods
}

Term is a Spec expression that produces a value (string, int, or bool) for one entity. The Term set is closed by an unexported marker, which keeps the rule layer Datalog-class rather than Turing-complete (docsite/content/architecture/rules-and-checks.md) and keeps LLM-generated rules cheap to validate.

type Trace added in v0.2.0

type Trace struct {
	From    TraceEnd     `json:"from"`
	To      TraceEnd     `json:"to"`
	Outcome TraceOutcome `json:"outcome"`
	// Reason says why, for no-route and unresolved; empty for a route.
	Reason    string       `json:"reason,omitempty"`
	Radius    int          `json:"radius"`
	Crossings []TraceCross `json:"crossings,omitempty"`
	Nets      []TraceNet   `json:"nets,omitempty"`
}

Trace is one pin-to-pin question and its whole answer: the outcome, the route when there is one, and the radius the answer rests on.

func TracePins added in v0.2.0

func TracePins(m Model, from, to Endpoint, hops int) Trace

TracePins walks from one pin to another through series pass elements and returns the route with its outcome from a single call.

It produces the answer and its evidence together, as PullUpVerdict does, so a caller cannot reach a routed outcome without the route that justifies it. This is the artifact issue 518 asks for.

The walk admits a bus-like net as a destination (ReachToTerminus), because a device pin sitting on a rail is an ordinary endpoint, and still refuses to continue through one.

type TraceCross added in v0.2.0

type TraceCross struct {
	RefDes   string `json:"ref_des"`
	Class    string `json:"class,omitempty"`
	EnterPin string `json:"enter_pin,omitempty"`
	ExitPin  string `json:"exit_pin,omitempty"`
	FromNet  string `json:"from_net"`
	ToNet    string `json:"to_net"`
}

TraceCross is one series element crossed on the route, with its own pins on each side.

type TraceEnd added in v0.2.0

type TraceEnd struct {
	Endpoint
	// PinName is the functional name the part type declares for this pin ("SDA", "PTC11"), or ""
	// on a source carrying no part-type pin data. It is what a datasheet and a firmware header
	// call the pin, so it is what makes the endpoint recognisable to the person reading.
	PinName string `json:"pin_name,omitempty"`
	Net     string `json:"net"`
}

TraceEnd is one resolved endpoint of a trace.

type TraceNet added in v0.2.0

type TraceNet struct {
	Name  string      `json:"name"`
	Stubs []TraceStub `json:"stubs,omitempty"`
	// StubsElided is how many further parts sit on this net beyond the ones listed, so a capped
	// list reads as capped rather than as complete.
	StubsElided int `json:"stubs_elided,omitempty"`
	// BusLike marks a net the walk would refuse to continue through (a rail, a ground, or any
	// rail-scale fan-out). A route may END on one, so saying which net it was is what stops a
	// reader assuming the trace stopped early for some other reason.
	BusLike bool `json:"bus_like,omitempty"`
}

TraceNet is one net on the route, with what else sits on it.

type TraceOutcome added in v0.2.0

type TraceOutcome string

TraceOutcome is what a trace answered. The three are kept apart because two of them are ordinary answers and one is a failure to ask the question at all.

const (
	// TraceRouted means a route was found within the radius.
	TraceRouted TraceOutcome = "routed"
	// TraceNoRoute means both endpoints resolved and no route joins them within the radius,
	// which is a real answer about the design.
	TraceNoRoute TraceOutcome = "no-route"
	// TraceUnresolved means an endpoint does not name anything the design has, so nothing was
	// walked. This must never render as "not connected", because a pin named in a declaration that
	// the design spells differently is what a typo produces, and reporting it as a disconnection
	// sends the reader to look at the board instead of at the declaration.
	TraceUnresolved TraceOutcome = "unresolved"
)

type TraceStub added in v0.2.0

type TraceStub struct {
	RefDes string `json:"ref_des"`
	Pin    string `json:"pin"`
	Class  string `json:"class,omitempty"`
}

TraceStub is a part sitting on a net of the route that the route does not pass through.

These are reported rather than filtered. A test point on a path net is where a reviewer can put a probe, which is the most actionable thing on the line; a capacitor there is the filter someone is about to ask about. Reducing the output to the series elements removes the parts a person reads a trace to find.

type UnmetDependency added in v0.2.0

type UnmetDependency struct {
	MPN          string
	Manufacturer string // as the seeded spec states it; empty when SpecAbsent
	Symbol       string
	// SpecAbsent separates "no spec for this part" from "a spec that states no such symbol", because the
	// next step differs (extract a document, versus find one fact in one already read).
	SpecAbsent bool
}

UnmetDependency names one datasheet fact a check reached for and did not find, meaning the part, the symbol, and whether the part has any seeded spec at all. The unit is the PART, not the placement. A PartSpec is per-MPN, so ten instances of one component are one thing to seed, and deduplicating by MPN keeps this a work list rather than a copy of the bill of materials.

func UnseededSymbols added in v0.2.0

func UnseededSymbols(m Model, syms []string, classes []string) []UnmetDependency

UnseededSymbols reports the (part, symbol) pairs that SeedsAnySymbol found nothing for. It is the same walk, keeping what that one discards, because "does ANY part seed this" decides the verdict but gives nothing to act on.

classes gates the walk to an item's applies_to_class when it declares one, as the computed-n/a path does. Without it a symbol needed by three parts would name every part on the design that lacks it. The result is deduplicated by (mpn, symbol) and sorted, so a run written and re-read reproduces byte for byte. A component with no resolvable MPN yields nothing.

type Var

type Var struct{ Name string }

Var reads a Spec.Let binding, evaluated at most once per entity (memoized), so a value can be shared between the Where clause and the Message template.

type Verdict added in v0.2.0

type Verdict struct {
	Rule    string
	Outcome Outcome
	// Subjects is the tuple of entities this verdict is ABOUT, in the rule's own order, and it is the
	// verdict's IDENTITY. Never empty.
	//
	// A tuple because a rule about a RELATION (copper-clearance between two nets, a regulator feeding
	// a load across a rail) needs every entity in it to give each answer its own VerdictID (#404).
	// ORDER IS SIGNIFICANT (pin-tracking bounds subject-pin minus reference-pin), so the framework
	// never sorts and a symmetric relation canonicalises INSIDE the rule. ARITY IS FIXED PER RULE,
	// declared as Rule.SubjectShape and held by TestSubjectShapeHolds. See
	// docsite/content/build/check-rule.md#a-tuple-in-the-verdict-one-entity-in-the-finding.
	Subjects []Entity

	// Witness is what the outcome rests on. REQUIRED on Pass and Fail, since without it a pass is
	// silence. Nil only on NoLimit and NotConsidered, where there was nothing to rest on.
	Witness *Witness

	// Reason says why a NotConsidered verdict could not be decided, in the rule author's words
	// ("pin could not be resolved to a datasheet terminal"). Empty for every other outcome.
	//
	// An open string, like Rule.Tags and ContextSubject.Role, because the useful vocabulary is
	// rule-specific. The engine requires only that the reason EXISTS.
	Reason string

	// Context are the design entities this verdict's proof NAMES but is not ABOUT, typed so a
	// consumer can highlight them: the resistor and rail a pull-up passes through, the rail a pin
	// sits on. Ordered, and Role is the author's word for the part each plays.
	//
	// The split from Witness.Terms is whether clicking it should light something up. A Term's value
	// is a bare string ("R1" could be a component, net or pin), where a ContextSubject carries the
	// Kind a highlight joins on (#388).
	//
	// Excludes the entities in Subjects, so a consumer draws subject-as-figure and Context-as-ground,
	// the split focusStack implements in the web viewer.
	//
	// Finding.Context is the projection of this for a failing verdict, and can differ. A Finding
	// about a COMPONENT lists the pin in its context, where a pin-subject verdict does not, because
	// for the verdict the pin is the subject.
	Context []ContextSubject

	// Finding is the violation form, set on Fail and Inconclusive. VerdictsToFindings projects it
	// out so the `check` path keeps its existing output.
	Finding *Finding
}

Verdict is what one rule concluded about one subject, passes included, with the evidence the conclusion rests on. A finding records only a violation, so a pass is the absence of one; a Verdict is how a rule proves a pin is fine rather than merely not reporting it (#387). Its wire form is checks.Verdict in checks.proto. See docsite/content/build/check-rule.md#say-what-you-looked-at-not-only-what-failed.

func RunVerdicts added in v0.2.0

func RunVerdicts(ctx context.Context, m Model, rules []*Rule) ([]Verdict, error)

RunVerdicts collects verdicts from every rule that sets StatesConsideredSet, stamping Rule from the rule's name, and orders them as Run does (rule, then subject).

A rule that does not state a considered set contributes nothing, and a caller cannot tell that apart from a rule that considered no subjects. So this returns a verdict list rather than a coverage report, which over a part-converted catalog would overstate the run. See StatesConsideredSet for why the filter is a declaration.

Like Run, it checks ctx before each rule and returns its error rather than a partial list.

func RunVerdictsBackground added in v0.2.2

func RunVerdictsBackground(m Model, rules []*Rule) []Verdict

RunVerdictsBackground is RunVerdicts for a caller with no context to pass, on the same terms as RunBackground.

type VocabPatterns

type VocabPatterns = configpb.VocabPatterns

VocabPatterns is the GENERATED config type, re-exported rather than mirrored. The Go mirror it replaced, and the RoleVocabConfig beside it, existed only to be copied field by field out of this same message, and that copy lost a vocabulary twice (WS3-117, agni 680).

type Witness added in v0.2.0

type Witness struct {
	// Statement is the human rendering, always set. It is the whole witness for a text consumer.
	Statement string
	// Terms are the VALUES Statement rests on, kept separately so a UI can lay them out and a test
	// can assert on one without parsing prose: a measured voltage, a stated limit, a hop bound.
	//
	// Values only, never entities, which go in Verdict.Context with a Kind. So a witness whose proof
	// is entirely a path has NO terms, and that is correct.
	Terms []WitnessTerm
	// Datasheet is the provenance of any seeded value the verdict used, the same citation form a
	// Finding carries. Empty for a witness resting on nothing seeded.
	Datasheet []*DatasheetCitation
}

Witness is why a verdict holds: a one-line statement a person can read, the facts that statement rests on, and the datasheet provenance behind them.

Terms is an ordered open list rather than a measured/limit pair because a path proof from `net.reaches` ("SCL -> R7 -> +3V3") uses the same list with the hops as terms.

func ICESDCredit added in v0.2.0

func ICESDCredit(m Model, n *ir.Net) (string, *Witness)

ICESDCredit is ICESDRated with the EVIDENCE kept, returning the part whose datasheet credits the net and a witness stating the rating and where it was read. Deciding and justifying in one call means a rule cannot reach a pass and skip the justification. Returns "" and nil when nothing in reach carries a rating, which is every design read without --params.

func (*Witness) Render added in v0.2.0

func (w *Witness) Render() string

Render writes a witness the way a terminal shows it, the statement and then one line per datasheet citation. A nil witness renders as "".

type WitnessTerm added in v0.2.0

type WitnessTerm struct {
	Label string // "measured", "absolute maximum", "hop 1"
	Value string // "3.3 V", "3.6 V", "R7"
}

WitnessTerm is one labelled fact inside a witness.

Directories

Path Synopsis
Package naming compiles an operator-supplied net-naming convention into a check.RuleSource (WS3-015).
Package naming compiles an operator-supplied net-naming convention into a check.RuleSource (WS3-015).

Jump to

Keyboard shortcuts

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