service

package
v0.6.13 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: Apache-2.0 Imports: 53 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 service holds the importable, transport-neutral service implementations (CONSTRAINTS C13). Every method has a plain protobuf signature ((ctx, *pb.XRequest) (*pb.XResponse, error)) and classifies its errors with this package's sentinels. The transports (Connect, in internal/server) are thin translation layers over them. Each implementation depends on injected I/O ports (Workspace, Loader, NativeRenderer) and never on os, so the same code runs on the server, in tests, and in WASM (C1). All file I/O lives in cmd/agni's OS-backed adapters, which also wire the services.

Index

Constants

View Source
const DesignDescriptorName = "design.yaml"

DesignDescriptorName is the file that declares a folder's design. internal/projects owns the name and a test there holds this copy to it.

View Source
const DesignFilesMaxBytes = 256 << 20

DesignFilesMaxBytes bounds a design's file set. A set over it is refused rather than truncated, because a partial set analyses as a design missing its board or its profiles and reads clean. It sits above the largest set the in-browser engine was measured to handle (a 97 MB KiCad board in agni issue 852), so the page's own threshold, not this bound, decides which designs go to the browser.

View Source
const ProjectDescriptorName = "project.yaml"

ProjectDescriptorName is the file that makes a folder a project. internal/projects owns the name and a test there holds this copy to it, since this package cannot import that one.

View Source
const RuleDocsBase = "https://panyam.github.io/agni/reference/rules/"

RuleDocsBase is where the published docsite serves the rule reference pages.

Variables

View Source
var (
	ErrNotFound        = errors.New("not found")
	ErrInvalidArgument = errors.New("invalid argument")
	ErrInternal        = errors.New("internal error")
	// ErrResourceExhausted marks a query that stopped at its work budget (agni issue 792). It may
	// well be a good question, but it costs more than this deployment or this request allows.
	ErrResourceExhausted = errors.New("resource exhausted")
	ErrUnavailable       = errors.New("unavailable")
)

The implementations classify every failure with these error sentinels. The transport adapter in internal/server then maps them to its codes without knowing which port an error came from.

ErrNotFound        -> not found (unknown mount, absent resource, unknown sheet)
ErrInvalidPath     -> invalid argument (containment violation; declared in workspace.go)
ErrInvalidArgument -> invalid argument (unloadable design, unsupported operation)
ErrNative*         -> the native-render gate codes (declared below)
ErrInternal        -> internal (an unexpected failure in an otherwise-gated path)
ErrUnavailable     -> unavailable (a service this one depends on could not be reached, such as
                      the PartSpec service behind --params-url)
ErrResourceExhausted -> resource exhausted (a query stopped at its work budget)

An unclassified error reaching a transport is treated as an invalid argument, the common case for load/parse failures.

View Source
var (
	ErrNativeNoTool     = errors.New("no native renderer for this format")
	ErrNativeNotEnabled = errors.New("native renderer not enabled")
	ErrNativeNotFound   = errors.New("native renderer tool not found")
)

An adapter reports these native-render gate failures, so a transport maps them without importing the cmd tool cache. NoTool maps to unimplemented, and NotEnabled and NotFound map to failed precondition.

View Source
var (
	// ErrStale is a snapshot whose files changed since they were read. UpdateSnapshot reads it again.
	ErrStale = errors.New("stale")
	// ErrAlreadyExists is an Ingest naming a snapshot id already in use.
	ErrAlreadyExists = errors.New("already exists")
)
View Source
var DiffColumns = []webapi.TableColumn{
	{Name: "change_class"},
	{Name: "subject", Type: webapi.ColumnType_COLUMN_TYPE_NAME},
	{Name: "old_name", Type: webapi.ColumnType_COLUMN_TYPE_NAME},
	{Name: "field"},
	{Name: "old_value"},
	{Name: "new_value"},
	{Name: "added", Type: webapi.ColumnType_COLUMN_TYPE_NAME},
	{Name: "removed", Type: webapi.ColumnType_COLUMN_TYPE_NAME},
	{Name: "old_source_file"},
	{Name: "new_source_file"},
	{Name: "match_old_coverage", Type: webapi.ColumnType_COLUMN_TYPE_NUMBER},
	{Name: "match_old_coverage_significant", Type: webapi.ColumnType_COLUMN_TYPE_NUMBER},
	{Name: "match_new_coverage_significant", Type: webapi.ColumnType_COLUMN_TYPE_NUMBER},
}

DiffColumns is the diff table's header, the one `diff --format csv` published. A diff is four collections of different shapes, and one table with change_class naming each row's kind lets a reader filter back to any one of them and sort across all of them at once. A row leaves the columns its class does not use empty. The match_ columns are filled on a near rename only, since a near match is a judgement, and a reviewer triages it by the numbers that decided it.

View Source
var ErrBlobsMissing = errors.New("blobs missing")

ErrBlobsMissing reports an Ingest naming files whose contents the host does not hold. The error is a *BlobsMissingError, which names them.

View Source
var ErrInvalidPath = errors.New("invalid path")

ErrInvalidPath marks a containment or argument violation an adapter returns, such as a path escaping its mount. Transports map it to their invalid-argument code. Adapters wrap it so the service can classify without importing os.

View Source
var ErrReviewStoreNotConfigured = errors.New("no review store configured")

ErrReviewStoreNotConfigured is returned by every review resource method when the server was started without a review store. It is its own sentinel, like ErrNativeNotEnabled and ErrExtractNotEnabled, so the transport maps it to failed-precondition rather than invalid-argument. The request was fine, and the deployment lacks the store.

View Source
var FindingColumns = []webapi.TableColumn{
	{Name: "severity"},
	{Name: "inconclusive"},
	{Name: "rule"},
	{Name: "kind"},
	{Name: "subject", Type: webapi.ColumnType_COLUMN_TYPE_NAME},
	{Name: "pin", Type: webapi.ColumnType_COLUMN_TYPE_NAME},
	{Name: "net_id", Type: webapi.ColumnType_COLUMN_TYPE_NAME},
	{Name: "message"},
	{Name: "source_file"},
	{Name: "native_id"},
	{Name: "context"},
}

FindingColumns is the findings table's header. `check --format csv` published it before this projection existed, and a script binding to it still works. Datasheet citations are left out, because each is a document, page and section and does not fit one cell. json has them.

View Source
var PinMapColumns = []webapi.TableColumn{
	{Name: "device", Type: webapi.ColumnType_COLUMN_TYPE_NAME},
	{Name: "pin", Type: webapi.ColumnType_COLUMN_TYPE_NAME},
	{Name: "function"},
	{Name: "net", Type: webapi.ColumnType_COLUMN_TYPE_NAME},
	{Name: "wired_net", Type: webapi.ColumnType_COLUMN_TYPE_NAME},
	{Name: "far_end", Type: webapi.ColumnType_COLUMN_TYPE_NAME},
	{Name: "route"},
	{Name: "pin_check"},
	{Name: "net_check"},
	{Name: "far_end_check"},
	{Name: "function_check"},
	{Name: "outcome"},
}

PinMapColumns is the pin_map table's header. pin is the map's spelling. wired_net is the resolved pin's net, empty when the pin resolved to no net or did not resolve. The four _check columns are each rule's outcome. outcome is the row's own. It is fail when any rule failed, then inconclusive, then pass, and not-considered when no rule could judge the row.

View Source
var ReviewColumns = []webapi.TableColumn{
	{Name: "area"},
	{Name: "id", Type: webapi.ColumnType_COLUMN_TYPE_NAME},
	{Name: "title"},
	{Name: "outcome"},
	{Name: "note"},
	{Name: "findings"},
	{Name: "unmet"},
}

ReviewColumns is the review table's header. findings names each firing behind an item as rule=kind:ref, and unmet each part whose datasheet the item needed, so a failed or undecided row says what to look at.

View Source
var ShippedRules = sync.OnceValue(func() map[string]bool {
	out := map[string]bool{}
	for _, r := range check.DefaultCatalog().Rules() {
		out[r.Name] = true
	}
	return out
})

ShippedRules returns the names of the rules in agni's default catalog. A sanitized report may name these rules (agni issue 1057). They are composed once, since the shipped set is fixed for the process.

View Source
var VerdictColumns = []webapi.TableColumn{
	{Name: "verdict_id"},
	{Name: "url"},
	{Name: "rule"},
	{Name: "outcome"},
	{Name: "subjects", Type: webapi.ColumnType_COLUMN_TYPE_NAME},
	{Name: "statement"},
	{Name: "context"},
	{Name: "terms"},
	{Name: "reason"},
}

VerdictColumns is the verdicts table's header, the one `check --verdicts --format csv` published. Only a caller that can link to a viewer fills url, such as the CLI with --server. The TableService has no viewer to link to and leaves it empty. subjects spells a relation's whole tuple as kind:ref pairs, since a relation commonly joins different kinds and two bare refs do not say which is which.

View Source
var WalkBoundaryColumns = []webapi.TableColumn{
	{Name: "hop", Type: webapi.ColumnType_COLUMN_TYPE_NUMBER},
	{Name: "ref_des", Type: webapi.ColumnType_COLUMN_TYPE_NAME},
	{Name: "class"},
	{Name: "net", Type: webapi.ColumnType_COLUMN_TYPE_NAME},
	{Name: "reason"},
}

WalkBoundaryColumns is the walk_boundary table's header.

View Source
var WalkColumns = []webapi.TableColumn{
	{Name: "hop", Type: webapi.ColumnType_COLUMN_TYPE_NUMBER},
	{Name: "net", Type: webapi.ColumnType_COLUMN_TYPE_NAME},
	{Name: "from_net", Type: webapi.ColumnType_COLUMN_TYPE_NAME},
	{Name: "through", Type: webapi.ColumnType_COLUMN_TYPE_NAME},
	{Name: "enter_pin", Type: webapi.ColumnType_COLUMN_TYPE_NAME},
	{Name: "exit_pin", Type: webapi.ColumnType_COLUMN_TYPE_NAME},
	{Name: "paired"},
	{Name: "also_through", Type: webapi.ColumnType_COLUMN_TYPE_NAME},
	{Name: "ended"},
	{Name: "parts", Type: webapi.ColumnType_COLUMN_TYPE_NAME},
	{Name: "parts_elided", Type: webapi.ColumnType_COLUMN_TYPE_NUMBER},
}

WalkColumns is the walk table's header. through, enter_pin and exit_pin say how the walk first entered the net, paired says whether it crossed as a through pair, and also_through names the parts that crossed into it later. parts lists the other parts on it, and parts_elided how many more the list left out.

View Source
var WalkGoalColumns = []webapi.TableColumn{
	{Name: "outcome"},
	{Name: "reason"},
	{Name: "route", Type: webapi.ColumnType_COLUMN_TYPE_NUMBER},
	{Name: "step", Type: webapi.ColumnType_COLUMN_TYPE_NUMBER},
	{Name: "net", Type: webapi.ColumnType_COLUMN_TYPE_NAME},
	{Name: "through", Type: webapi.ColumnType_COLUMN_TYPE_NAME},
	{Name: "enter_pin", Type: webapi.ColumnType_COLUMN_TYPE_NAME},
	{Name: "exit_pin", Type: webapi.ColumnType_COLUMN_TYPE_NAME},
	{Name: "parts", Type: webapi.ColumnType_COLUMN_TYPE_NAME},
	{Name: "note"},
}

WalkGoalColumns is the walk_goal table's header, one row per net of each route a goal found. route numbers the routes from 1 and step the nets along one from 0. through, enter_pin and exit_pin say how the route entered the net. A goal with no route writes one row with its outcome and reason and the rest empty, so a "no route" answer is never an empty file.

Functions

func AnnotateReport

func AnnotateReport(rep *checkspb.CheckReport, g *geom.SchematicGeometry, m LocateSource)

AnnotateReport fills the sheet membership of every finding nested in a CheckReport, the report-shaped counterpart of AnnotateSheets (which takes a flat slice). It flattens the report's severity sections and rule groups to one slice and annotates in place, so the CLI's `check --format report` and the GetCheckReport RPC share one annotation path rather than two copies of the walk. With both g and d nil it is a no-op and findings keep empty sheets, as with AnnotateSheets. A net-only channel (design set, geometry nil) still annotates net subjects.

func AnnotateRunSheets added in v0.3.8

func AnnotateRunSheets(resp *webapi.CheckDesignResponse, g *geom.SchematicGeometry, m LocateSource)

AnnotateRunSheets fills a check run's findings and its verdicts from one walk of the geometry. A verdict gets the sheets that draw its subjects, so a viewer opens one before drawing the proof. A passing verdict has no finding to borrow them from, and it gets them too (agni issue 1151).

func AnnotateSheets

func AnnotateSheets(findings []*checkspb.Finding, g *geom.SchematicGeometry, m LocateSource)

AnnotateSheets fills each finding's sheets in place. It is a post-pass over FindingProto's output rather than a FindingProto parameter, so the canonical conversion keeps its shape and a caller without either source skips the pass. Geometry supplies component and pin badges, plus net badges for formats whose wires carry names. The design supplies the authoritative net membership (AttrSheets, WS9-028), which covers the wireless sub-sheet nets that geometry misses. With both nil the pass is a no-op, and findings keep empty sheets, which the viewer handles. A net-only channel, with the design set and the geometry nil, still annotates net subjects.

func AnnotateTraceSheets added in v0.2.2

func AnnotateTraceSheets(t *webapi.Trace, g *geom.SchematicGeometry, m LocateSource)

AnnotateTraceSheets fills a trace's per-net and per-endpoint sheet ids, the same way AnnotateSheets fills a finding's.

The ids are PER NET rather than one sheet for the answer. When a route crosses three sheets, a reader wants to choose which to open. The panel already renders a list of badges for a finding and for a query cell (agni issue 657).

Both outcomes are annotated. On a no-route the two endpoints' nets are still drawn somewhere. A reader wants that picture once they learn the pins do not join. Empty sheet ids mean the net is drawn nowhere, rather than that nobody looked.

func AnnotateWalkSheets added in v0.6.0

func AnnotateWalkSheets(w *webapi.Walk, g *geom.SchematicGeometry, m LocateSource)

AnnotateWalkSheets fills a walk's per-net sheet ids and its start's, as AnnotateTraceSheets does for a trace, and its goal's route nets and pin. A walk started from a part locates by the part.

func AppendEqualNets added in v0.2.2

func AppendEqualNets(resp *webapi.DiffDesignsResponse, r *diff.Report)

AppendEqualNets adds the nets that did not change to a response's report, as kind "equal" after the changes (agni issue 818). The status maps are left alone, so a viewer tinting by status does not mark every unchanged net.

func BindingsFromProto added in v0.2.2

func BindingsFromProto(m map[string]*webapi.QueryValue) (query.Bindings, error)

BindingsFromProto converts a request's bindings to the values the engine binds (agni issue 793). A value that sets no field binds the empty text, as `""` written in the query would, and a list binds the variable to each of its values (agni issue 1121). A list inside a list is an InvalidArgument.

func BindingsProto added in v0.2.2

func BindingsProto(b query.Bindings) map[string]*webapi.QueryValue

BindingsProto converts bound values to their wire form: a value carrying a number is a number, any other is text, and a variable bound to anything but exactly one value is a list.

func BuildGeometry

func BuildGeometry(ctx context.Context, loader GeometryLoader, uri artifact.URI, opts ...ReadOption) *geom.SchematicGeometry

BuildGeometry loads a design's default-layout, glyph-symbol schematic geometry for LOCATING results on sheets (AnnotateSheets badges, indexSheets query-cell navigation). It never feeds a rule, so surfaces that run rules without locating them (GetComponentParams, scalar-only queries) skip it. It is best-effort. A netlist-only file or an unresolvable layout yields nil, NOT an error, and the caller shows no sheet badges. So geometry is not a BuildModel tier, since a bad board or params tier there fails the run.

Pass the same ReadOptions the Model was built with (agni issue 347). A geometry read without them misses a project's declared symbol library, so findings are placed on sheets that lack the components they name.

func BuildModel

func BuildModel(ctx context.Context, loader ModelLoader, uri, boardURI artifact.URI, specs param.ParamProvider, opts ...ReadOption) (check.Model, error)

BuildModel constructs the FULL check Model for a design (netlist, board tier, params tier), so every rule-running service surface builds the same Model and none drops a tier (WS9-048). A plain check.NewModel gates every board-DRC and datasheet rule to not-applicable. The board tier reads the design's own sidecar, or boardURI when set (WS3-089's --board-path). specs is the datasheet provider and may be nil when serve ran without --params. The CLI's counterpart is readModelWithParams.

A boardURI that yields no board geometry is an error. Without that error, an explicit board request that read nothing would report the board items clean without checking them. When a design's OWN path has no board (a netlist), that is the normal nil-board case.

func BuildModelCached added in v0.2.2

func BuildModelCached(ctx context.Context, loader ModelLoader, uri, boardURI artifact.URI, ov Overlay, serverSpecs param.ParamProvider) (check.Model, func(*facts.Registry) *query.Base, error)

BuildModelCached is BuildModel kept in the loader's DesignCache, keyed on the tiers and the overlay's identity. The model is SHARED between requests rather than copied. That is safe, because rules only read it and its memo (check.Memo) is built for concurrent use. Two kinds of request build their own model. One has an overlay that cannot identify itself. The other fetches its datasheet corpus over the network, where nothing here can tell that it changed.

It returns the fact base too, built on first use, so a query does not spend 100ms projecting every relation again.

func BuildModelCachedTier added in v0.2.2

func BuildModelCachedTier(ctx context.Context, loader ModelLoader, uri, boardURI artifact.URI, ov Overlay, serverSpecs param.ParamProvider, board BoardTier) (check.Model, func(*facts.Registry) *query.Base, error)

BuildModelCachedTier is BuildModelCached with the board tier chosen by the caller. The two tiers are kept apart. A SkipBoard request takes a model already kept WITH the board when there is one, since that model answers everything the board-less one would. So a server that has run checks on a design builds no second model for its coverage panel (agni issues 985, 987).

func BuildModelTier added in v0.2.2

func BuildModelTier(ctx context.Context, loader ModelLoader, uri, boardURI artifact.URI, specs param.ParamProvider, board BoardTier, opts ...ReadOption) (check.Model, error)

BuildModelTier is BuildModel with the board tier chosen by the caller. With SkipBoard the loader is never asked for a board, boardURI included.

func CellLocation added in v0.2.2

func CellLocation(resp *webapi.RunQueryResponse, r *webapi.QueryRow, i int) ([]string, checkspb.LocateReason)

CellLocation returns where an answer cell's entity is drawn and why it cannot be located. It reads them through the response's entity table (agni issue 916). A scalar cell has neither.

func CheckReportProto

func CheckReportProto(source string, fs []check.Finding, rules []*check.Rule) *checkspb.CheckReport

CheckReportProto assembles the severity-organized CheckReport (WS3-022) from one run. Sections run worst first (custom severities lead, then error, warning, info), and empty severities are omitted. Findings are grouped by rule in run order. Each group is stamped with the rule's catalog Summary from the rules that ran. Those come from the injected catalog, so an embedder's rules resolve too. This is THE report pivot. The CLI's markdown/report formats, the web report panel, and a report rebuilt from a written results document all render this proto from the one results.Pivot, and none of them re-derives the grouping.

func ChecklistOf added in v0.2.2

func ChecklistOf(doc *checkspb.CheckResults, meta report.Checklist) report.Checklist

ChecklistOf maps one review's document onto the checklist page's model, with meta supplying the header and the links.

Area and item ORDER is the manifest's, untouched. The check report sorts rules worst-first because nobody authored that order, while a checklist's order is the team's.

func ClassifyLoadErr added in v0.2.2

func ClassifyLoadErr(err error) error

ClassifyLoadErr keeps an already-classified loader error (unknown mount, containment) and wraps anything else, such as a resolve or parse failure, as an invalid argument. It is exported for the datasheet service, which lives in another module (agni issue 744), so its errors map to the same sentinels.

func ConventionYAML added in v0.4.0

func ConventionYAML(conv *configpb.NamingConvention) ([]byte, error)

ConventionYAML writes conv with field names as the YAML binding reads them, in the order the schema declares them, so naming.Parse reads it back to the same message.

func DeclaredChecklists added in v0.2.2

func DeclaredChecklists(lists []*webapi.NamedChecklist) string

DeclaredChecklists names what a project does declare, for a message saying it lacks the one asked for.

func DesignName

func DesignName(parent, id string) string

DesignName builds a design resource name, "projects/{project}/designs/{design}".

func DeviceClassLookup added in v0.2.2

func DeviceClassLookup(specs param.ParamProvider) func(string) string

DeviceClassLookup adapts a param provider for the ingestion class pass. That pass asks the provider one question, the device_class a seeded spec states for an MPN. readers/formats takes this function and never the provider, so the datasheet layer is kept out of the readers.

A nil provider returns a nil function rather than panicking later. A caller that composed no corpus holds a nil interface, which looks the same as an empty corpus at the call site.

func DiffResponseProto

func DiffResponseProto(r *diff.Report) *webapi.DiffDesignsResponse

DiffResponseProto converts a diff.Report into its webapi wire form, and no other code does. The RPC and the CLI's `diff --format json` share it (C31). It also derives the highlight maps, ref_des -> added|removed|changed and net name -> new|deleted|renamed|hard|soft. A renamed net is keyed under BOTH names, so each side of a visual diff joins by the name in its own geometry.

func DiffTable added in v0.2.2

func DiffTable(resp *webapi.DiffDesignsResponse) *webapi.Table

DiffTable is one row per change, components first and then nets, in the order the diff reported them. That order is by ref des, by ref des then field, and nets by kind then name. The unchanged nets come last when the diff included them. A net row's class is its kind under a net- prefix, so the table names kinds exactly as the diff does.

func FindingFromProto added in v0.2.4

func FindingFromProto(p *checkspb.Finding) check.Finding

FindingFromProto is the inverse of FindingProto, for a consumer that reads findings back off the wire or out of a saved document. A review's items, `agni results` and a remote check all do. Sheets and locate_reason are not read back, since the server fills them from the design's drawing and check.Finding has no field for either.

func FindingProto

func FindingProto(f check.Finding) *checkspb.Finding

FindingProto is the one place a check.Finding becomes its wire form, shared by the rpc and the CLI's `check --format json` (C31). Subject is the highlight join key, and Provenance is carried when present so a consumer can link back to the source. A bus subject's join key is handled in subjectProto.

func FindingProtos

func FindingProtos(fs []check.Finding) []*checkspb.Finding

FindingProtos maps a slice of findings through FindingProto, preserving order (check.Run sorts by rule then subject).

func FindingsFromProto added in v0.2.4

func FindingsFromProto(ps []*checkspb.Finding) []check.Finding

FindingsFromProto maps a slice through FindingFromProto, preserving order. It returns an empty slice rather than nil for no findings.

func FindingsTable added in v0.2.2

func FindingsTable(findings []*checkspb.Finding) *webapi.Table

FindingsTable is one row per finding, in the order the run produced them.

func FormatBindings added in v0.3.11

func FormatBindings(m map[string]*webapi.QueryValue) []string

FormatBindings spells an answer's echoed bindings as a document states them beside its query, or gives the reason they could not be read.

func FormatForExt

func FormatForExt(name string) string

FormatForExt returns the design format label for a file name, or "" when no reader understands it. It derives from the formats registry, so adding a reader there labels its extension here. Exported so an adapter can pre-filter.

func IsCompanion

func IsCompanion(d *webapi.Design, ref string) bool

IsCompanion reports whether ref is one of the views this design declared of itself.

func KindForName

func KindForName(name string) webapi.FileKind

KindForName returns which client opens a file. A design wins over a datasheet if an extension is both, since a reader registered for an extension outranks this package's one constant.

func LoaderFor added in v0.2.2

func LoaderFor(base *formats.Loader, opts ...ReadOption) *formats.Loader

LoaderFor picks the formats.Loader one read should use. A read with no options gets the shared loader, and any other read gets a COPY carrying its options. The shared loader is never mutated, so two concurrent reads with different project conventions cannot see each other's (WS3-102, on the WS3-106 value).

A nil base is supported (see formats.Loader's own nil handling) and is never dereferenced. The copy then starts from a zero loader carrying only the read's options.

Every loader adapter calls this. That covers the CLI's, the server's, and the in-memory one that the wasm engine uses. So a read option reaches the read the same way whichever host made it.

func LoaderIn added in v0.2.2

func LoaderIn(ctx context.Context, base *formats.Loader, opts ...ReadOption) *formats.Loader

LoaderIn is LoaderFor for a read made on behalf of ctx. When a DesignCache is building an entry, ctx carries a recorder for the read's files, and this hands it to the Loader. A host's Design, Geometry, Report and Board reads go through this, and a read that does not is simply never cached.

func LoaderOr added in v0.3.0

func LoaderOr[L any](s Snap, l L) L

LoaderOr returns the loader to read s through. That is its upload's, or else the service's l.

func ManifestFromProto

func ManifestFromProto(p *checkspb.ReviewManifest) review.Manifest

ManifestFromProto converts a wire manifest to the engine's value. A nil message yields the zero Manifest, which validation then reports as absent.

It does NOT validate. Validation compiles the manifest's queries, so the caller decides when to spend that cost. Every service path that converts an inbound manifest validates it.

func ManifestProto

func ManifestProto(m review.Manifest) *checkspb.ReviewManifest

ManifestProto converts an engine manifest to its wire form, for a caller that obtained one from its own source (the CLI reads the YAML file the user named with --checklist) and now has to send it.

func OrderTables added in v0.2.2

func OrderTables(tables []*webapi.Table, orderBy []string, types map[string]webapi.ColumnType) error

OrderTables sorts each table by orderBy, as TabulateRequest.order_by describes, with types overriding a column's own type by name. It sorts in place and is stable.

func OutcomeWord added in v0.2.2

func OutcomeWord(o checkspb.Outcome) string

OutcomeWord is a verdict outcome as the lower-case word every surface prints. An unrecognised value is "unspecified" and never blank, since a blank would read as nothing to report.

func PageReviews

func PageReviews(newestFirst []string, pageSize int, pageToken, designFilter string, load func(string) *checkspb.CheckResults, nameOf func(string) string) ([]*checkspb.CheckResults, []string, string, error)

PageReviews applies the filter, the page token, and the page size to an ids slice that is ALREADY newest-first, loading each kept document through load. Every ReviewStore pages through it, so no adapter can disagree about whether a token is inclusive and make a client skip or repeat a run at a page boundary.

The token is the id to resume AFTER. It is still valid when runs are created or deleted between pages, and an offset would not be. nameOf builds each kept run's resource name, because only the store knows which parent an id lives under.

func ParseArtifactURI added in v0.2.2

func ParseArtifactURI(s string) (artifact.URI, error)

ParseArtifactURI parses a request's artifact URI, classifying a malformed one for the transport. Every rpc naming an artifact goes through here, and a parsed URI cannot name a location outside its mount, so containment is a property of the type and the adapters below the ports do not re-check it (#179 replaced 26 separate containment checks). Exported for the same reason as ClassifyLoadErr.

func PickChecklist added in v0.2.2

func PickChecklist(lists []*webapi.NamedChecklist, name string) *webapi.NamedChecklist

PickChecklist returns the checklist called name, or the first, which is the project's default, when name is empty. It returns nil when there is none.

func PinMapSections added in v0.3.11

func PinMapSections(t *webapi.Table) []rpt.PinMap

PinMapSections groups the pin_map table by device, in the order each device first appears. The HTML report lays it out the same way ("Pins on U1"). It reads the table rather than the run, so the page and every csv of the run encode one projection (C35).

func PinMapTable added in v0.3.11

func PinMapTable(ioMap []*configpb.PinAssignment, verdicts []*checkspb.Verdict) *webapi.Table

PinMapTable returns one row per declared pin, in the map's order, each joined to its verdicts. A rule left out of the run leaves its column empty. PinMapTable returns nil when the run carries no map.

func ProjectID

func ProjectID(name string) (string, bool)

ProjectID extracts the declared id from a project resource name, reporting whether the name was well formed. A missing prefix, an empty id, or a separator inside the id is rejected, because the id reaches a store that may resolve it against a filesystem and must not be steerable out of its tree.

func ProjectName

func ProjectName(id string) string

ProjectName builds a project resource name from its declared id.

func ProposeFromFiles added in v0.2.2

func ProposeFromFiles(mount string, files []string, read func(string) ([]byte, error)) *webapi.ProposeDesignsResponse

ProposeFromFiles applies the grouping rules to a list of mount-relative file paths. read returns a file's bytes, and is used only to find a KiCad sheet's child sheets and a Capture design's block files.

The rules, in the order they claim files:

  • A folder holding a `design.yaml` is DECLARED, and every file under it belongs to that design. The proposal reports the descriptor rather than guessing over it.
  • A `project.yaml` and the files it names (profiles, params, symbols, lib, queries) are support files, not unread ones, and a design proposed under it extends it.
  • (Netlists go first, so a netlist claims the KiCad schematic and board of its own name as its views before either can become a design of its own; see the netlist rule below.)
  • A `.kicad_pro` claims the `.kicad_sch` of its stem as the entry, that sheet's child sheets, and the `.kicad_pcb` of its stem as the board companion.
  • A `.kicad_sch` that no other sheet names as a child is a root, and makes a design the same way.
  • In each folder, netlists whose names share a first word (board.edn, board-rev-b.edn) are ONE design's revisions, never merged. The entry is the first with a `.eds` of its stem, or else the first. Each `.eds` of a netlist's stem is that netlist's schematic companion, and every other netlist is a revision. A netlist's companions are the `.eds`, `.kicad_sch` and `.kicad_pcb` of its own stem. Netlists with different first words are separate designs. Inferring this is safe here because the visitor sees the proposal and edits it first. On a server it is not safe (agni 528).
  • A `.eds` with no netlist of its stem is a design of its own, with a note, since a drawing's counts are not a netlist's.
  • A file whose format places blocks from other files (an OrCAD `.DSN`, `formats.Format.Blocks`) that no other such file places is a root. It claims every block file it reaches, matched without case as the reader opens them, so a dropped Clay folder is one design, not eleven.
  • Any other file a reader opens is a design of its own. KiCad libraries belong to the KiCad design beside or above them.
  • Everything left is unread, with the reason.

func QueryResultTable added in v0.3.11

func QueryResultTable(resp *webapi.RunQueryResponse, title, queryText, source string) rpt.Table

QueryResultTable lays out one query's answer as the report model renders it. `query --format html|markdown` writes this projection, and the check report's Queries sections reuse it. Per-cell sheet badges and locate reasons are panel navigation and mean nothing in a file, so they are dropped here.

source is the design's URI, never a host path, since a saved view gets committed and pasted into tickets (agni issue 501).

func QuerySetFromProto added in v0.2.2

func QuerySetFromProto(p *webapi.QuerySet) (query.QuerySet, error)

QuerySetFromProto converts the wire form of a query set to the engine's. A binding holding a list inside a list is an ErrInvalidArgument naming its query.

func QuerySetProto added in v0.2.2

func QuerySetProto(s query.QuerySet) *webapi.QuerySet

QuerySetProto converts a query set to its wire form, for a caller that read one from a file.

func QuerySetTable added in v0.3.11

func QuerySetTable(resp *webapi.RunQueriesResponse, failed func(i int) rpt.Table) rpt.TableSet

QuerySetTable is a query set's answers as one report table set, a section per query in the set's order. failed gives the text and bindings of a query that has no result, since the response does not echo them. A nil failed leaves a failed section with its error alone.

func QueryTable added in v0.2.2

func QueryTable(name string, resp *webapi.RunQueryResponse) *webapi.Table

QueryTable lays out a query answer's columns, with its provenance as the last column, as `query --format csv` prints it. A column the answer types as an entity kind orders as a name, and a row's cell_why holds the reason an aggregate cell is absent.

func ReachableFromProto added in v0.6.11

func ReachableFromProto(p *webapi.ReachablePinsResponse) check.Reachable

ReachableFromProto converts the wire answer back, for a client that prints it.

func ReachableProto added in v0.6.11

func ReachableProto(r check.Reachable) *webapi.ReachablePinsResponse

ReachableProto converts a check.Reachable to its wire form. `agni trace --reachable --format json` prints the same fields.

func RenameOptionsFromProto added in v0.2.2

func RenameOptionsFromProto(p *webapi.NearRenameOptions) diff.RenameOptions

RenameOptionsFromProto turns a request's near-rename options into the diff's. A nil message turns the pass off. An empty message selects the calibrated defaults, and each set field overrides one threshold.

func ReportFromProto added in v0.2.2

func ReportFromProto(p *webapi.ConversionReport) *graph.ConversionReport

ReportFromProto is reportToProto's inverse. It gives the pair the deep-equality round-trip guard C26 asks of a hand-written twin, and lets `agni render --report --report-format json` emit the same message GetLayoutReport returns (#632).

func ReportProto added in v0.2.2

ReportProto is reportToProto exported, for a caller outside this package that holds the engine's report and wants the wire form (the CLI's --report-format json).

func ResolveExtends added in v0.2.2

func ResolveExtends(ctx context.Context, store ProjectStore, p *webapi.Project) (*webapi.AnalysisConfig, error)

ResolveExtends returns the project's config with everything it inherits already layered underneath. It is exported for a caller that reads one tier of the composed config directly, as the CLI reads a project's checklists, so the answer cannot differ from what a run composes.

The chain is walked leaf-to-root and composed root-FIRST, so a project overrides what it inherits, the same direction as request over project over deployment default. docsite/content/architecture/projects-and-designs.md#sharing-config-between-projects explains why inheritance is declared rather than ambient.

A nil store is fine for a project that extends nothing. A project may declare an extends that the store cannot resolve. That project gets an error rather than a subset of its declared config.

func ReviewName

func ReviewName(parent, id string) string

ReviewName builds a resource name from a parent and a bare store id, and SplitReviewName is its inverse. A store deals in (parent, id) and the API in names, so both go through these two rather than spelling the shape by hand and ending up storing a name as an id.

An empty parent yields the unparented form, "reviews/{id}", for a design that belongs to no project.

func ReviewOf added in v0.2.2

func ReviewOf(name string, doc *checkspb.CheckResults) *webapi.Review

ReviewOf is the Review resource for a stored document, with its summary computed from the document's item outcomes (agni issue 734). Every rpc returning a review builds it here, so the summary is never stored and a document written before the field existed answers with one. The CLI uses it too, for a document it read from a file.

func ReviewTables added in v0.2.2

func ReviewTables(rv *webapi.Review) []*webapi.Table

ReviewTables returns a review's items and its one-row summary. Each item gets one row, in the checklist's own order, since a reviewer reads a checklist in the order it was written.

func RevisionOf added in v0.2.2

func RevisionOf(d *webapi.Design, ref string) *webapi.Design

RevisionOf returns the declared revision ref belongs to, as its entry or one of its companions, shaped as a Design whose entry and companions are that revision's. It returns nil when ref is the current revision's or belongs to none, so the design is resolved as it always was.

func RowCites added in v0.2.2

func RowCites(resp *webapi.RunQueryResponse, r *webapi.QueryRow) []string

RowCites is a row's citations, read through the response's sources table (agni issue 916).

func RowWitnesses added in v0.3.8

func RowWitnesses(resp *webapi.RunQueryResponse, r *webapi.QueryRow) []rpt.Witness

RowWitnesses are a row's witnesses as a document renders them (agni issue 794), with each citation read through the response's sources as RowCites reads a row's. Nil when the request asked for none.

func RuleDocURL added in v0.3.6

func RuleDocURL(r *check.Rule) string

RuleDocURL is the published page explaining r, or "" when r names no page (check.Rule.DocPage).

func RunConfigProto

func RunConfigProto(p RunProvenance, ratifiedFloor float64) *checkspb.RunConfig

RunConfigProto is the one place a RunProvenance becomes a results document's RunConfig, so the CLI's check path and the service's review path cannot describe the same tiers differently.

func ServerTiming added in v0.2.2

func ServerTiming(s timing.Snapshot) string

ServerTiming renders a snapshot as a Server-Timing header value for a browser's network panel to draw. The value lists the total first. Then it lists each stage once, in the order the stage first started, summed when it ran more than once.

func SeverityRank

func SeverityRank(s string) int

SeverityRank orders severities for report sections and fail-on gating; higher is worse. An unknown severity ranks above error so a provider's custom level is never silently dropped below a CI gate or buried at the bottom of a report.

The implementation lives in core/results, with the report pivot it orders, so a reloaded results document and a live run cannot disagree on which severity is worse. Kept exported here because the CLI's --fail-on gate calls it through the service surface.

func SkippedRuleDocs added in v0.2.2

func SkippedRuleDocs(in []*webapi.SkippedRule) []*checkspb.SkippedRule

SkippedRuleDocs carries a run's skipped rules into a document's form.

func SkippedTable added in v0.2.2

func SkippedTable(skipped []*webapi.SkippedRule) *webapi.Table

SkippedTable lists the selected rules that could not run on this design, and why, so a workbook of a run says which rules it is silent on. A revision read with no board lists its board-tier rules here (agni issue 848). The reason is check.Available's own words.

func SortReviewIDsDescending

func SortReviewIDsDescending(ids []string)

SortReviewIDsDescending orders ids newest-first for a store whose ids are time-sortable strings, such as the os-backed adapter's, so it lists chronologically with no document reads.

func SplitDesignName

func SplitDesignName(name string) (parent, id string, ok bool)

SplitDesignName splits a design resource name into its parent project name and its design id, with the same containment rejections as ProjectID applied to both halves.

func SplitReviewName

func SplitReviewName(name string) (parent, id string, ok bool)

SplitReviewName splits a review resource name into its parent project name (empty when the run is unparented) and its store id, reporting whether the name was well formed.

An empty id, a separator inside the id, or a `.`/`..` id is rejected, because an id reaches a filesystem-backed adapter and must not steer it out of the store directory. The parent, when present, is validated as a project resource name for the same reason.

func TextPositionOf added in v0.2.4

func TextPositionOf(err error) *webapi.TextPosition

TextPositionOf returns the place err points to in its query's text when err is a query that would not parse, and nil otherwise. The Connect transport attaches it to a RunQuery failure as an error detail, and RunQueries sets it on the query that failed, so a client can point at the place.

func TimingProto added in v0.2.2

func TimingProto(procedure string, s timing.Snapshot) *webapi.RequestTiming

TimingProto is a request's timing snapshot as the RequestTiming a client reads (agni issue 914).

func TraceFromProto

func TraceFromProto(p *webapi.Trace) check.Trace

TraceFromProto is TraceProto's inverse.

func TraceProto

func TraceProto(t check.Trace) *webapi.Trace

TraceProto and TraceFromProto convert a trace between its Go form and its wire form.

The twin is hand-written because check.Trace is a domain value. The engine returns it with its evidence attached, and its outcome is a Go string type that the wire spells as an enum. Per C26 the pair has a round-trip guard (TestTraceProtoRoundTrip) and a field census. So a new field on check.Trace has to be placed on the wire or excluded explicitly.

func VerdictCountsTable added in v0.2.2

func VerdictCountsTable(verdicts []*checkspb.Verdict) *webapi.Table

VerdictCountsTable is one row per rule, in the order rules first appear among the verdicts, counting each outcome and the total, so a reader sees which rules decided most and which declined.

func VerdictFromProto

func VerdictFromProto(p *checkspb.Verdict) check.Verdict

VerdictFromProto is the inverse. Id is not read back, because it derives from the other fields and trusting an inbound one would let a producer rename a verdict.

func VerdictProto

func VerdictProto(v check.Verdict) *checkspb.Verdict

VerdictProto and VerdictFromProto are the conversion pair for the considered set. check.Verdict is a hand-written twin of a wire message, so the pair has a C26 round-trip guard (TestVerdictProtoRoundTrip). Without it, a field the converter never learned is invisible to any assertion on the proto. naming.Lexicon and Profile.HostClass each hit this.

Verdict.Finding is DELIBERATELY not on the wire. A failing verdict's finding travels in CheckDesignResponse.findings, and a second copy here could disagree with it. TestVerdictFieldCensus fails when a field is added to check.Verdict, so whoever adds one decides whether it goes on the wire.

func VerdictProtos

func VerdictProtos(vs []check.Verdict) []*checkspb.Verdict

VerdictProtos maps a verdict list, the counterpart of FindingProtos.

func VerdictReport added in v0.2.2

func VerdictReport(run *webapi.CheckDesignResponse, rules []*check.Rule, meta report.Report) report.Report

VerdictReport aggregates one run into a report model. The HTML page and the CLI's verdict text both render that model, so the two cannot disagree about what the run held or in what order (agni issue 380). rules is the composed catalog the run read, overlay rules included.

func VerdictsTable added in v0.2.2

func VerdictsTable(verdicts []*checkspb.Verdict, link func(*checkspb.Verdict) string) *webapi.Table

VerdictsTable is one row per verdict, passes included, in run order. link gives a verdict's viewer URL, and nil leaves the url column empty.

func WalkFromProto added in v0.6.0

func WalkFromProto(p *webapi.Walk) check.Walk

WalkFromProto is WalkProto's inverse.

func WalkProto added in v0.6.0

func WalkProto(w check.Walk) *webapi.Walk

WalkProto and WalkFromProto convert a walk between its Go form and its wire form. Each net is a TraceNet and each crossing a TraceCross, so a walk and a trace render through the same pieces. TestWalkProtoRoundTrip holds the pair to each other (C26).

func WalkTables added in v0.6.0

func WalkTables(w *webapi.Walk) []*webapi.Table

WalkTables returns a walk's nets in the order it reached them, the parts it left at the boundary, and its goal's routes. The walk_goal table has no rows when the walk asked no goal.

func WriteTableCSV added in v0.2.2

func WriteTableCSV(w io.Writer, t *webapi.Table) error

WriteTableCSV writes one table as csv, its column names as the header row and every cell guarded against spreadsheet formulas (rpt.SanitizeCell). It is the one csv encoding of a Table. `--format csv` on every command and the Encode rpc both write it, so a file saved from the viewer and one written by the CLI are the same bytes. It writes the rows in the order they are in.

Types

type BlobStore added in v0.2.2

type BlobStore interface {
	Get(ctx context.Context, key string) ([]byte, error)
	Put(ctx context.Context, key string, b []byte) error
}

A BlobStore keeps bytes across processes, for a DesignCache's persistent tier (agni issue 911). It has the shape of goapplib's wasmhost.Cache, and the browser engine hands it one. So this package names no host. Any error from Get, a miss included, means the read runs again, and an error from Put means only that the next process reads again too. A key is 64 lowercase hex digits.

type BlobsMissingError added in v0.3.0

type BlobsMissingError struct{ Hashes []string }

BlobsMissingError names the contents an Ingest needs sent. A transport sends it as a webapi.BlobsMissing detail.

func (*BlobsMissingError) Detail added in v0.3.0

func (e *BlobsMissingError) Detail() *webapi.BlobsMissing

Detail is the error as the wire carries it.

func (*BlobsMissingError) Error added in v0.3.0

func (e *BlobsMissingError) Error() string

func (*BlobsMissingError) Unwrap added in v0.3.0

func (e *BlobsMissingError) Unwrap() error

type BoardTier added in v0.2.2

type BoardTier bool

A BoardTier says whether a model reads the design's board. On a large board, most of a model's memory is the board's geometry and the per-net copper built from it (385 of 547 MB on the Jetson seed, agni issue 987). So a request that asks nothing of the copper skips it.

const (
	// ReadBoard reads the board tier, as every rule run does.
	ReadBoard BoardTier = true
	// SkipBoard builds the model without one, so it reports HasBoard false and every board.*
	// relation is empty. Use it only for a request that reads no board fact, such as a query naming
	// no board.* relation (see boardTierFor), interface coverage, or a part's parameters.
	SkipBoard BoardTier = false
)

type CacheableLoader added in v0.2.2

type CacheableLoader interface {
	Loader
	ReviewLoader
	ConventionLoader
}

CacheableLoader holds the read ports that a CachingLoader wraps. A host hands one to its services.

type CachingLoader added in v0.2.2

type CachingLoader struct {
	CacheableLoader
	// contains filtered or unexported fields
}

CachingLoader is a host's loader with its design, drawing and board reads kept in a DesignCache. Every other port passes through. Each answer is a copy of what the cache holds. Callers stamp classes into a design they were handed, as check.NewModel's datasheet pass does. A copy of a large board's design and drawing costs about 10ms, against a read of over a second.

func NewCachingLoader added in v0.2.2

func NewCachingLoader(l CacheableLoader, c *DesignCache) *CachingLoader

NewCachingLoader wraps l. A nil cache passes every read through.

func (*CachingLoader) Board added in v0.2.2

Board returns a copy of the board sidecar. A board read takes no options, so its key is the URI.

func (*CachingLoader) BoardPersisted added in v0.3.0

func (l *CachingLoader) BoardPersisted(uri artifact.URI) bool

BoardPersisted reports whether the board read for uri is in the cache's persistent tier, so another process over the same files restores it rather than parsing it.

func (*CachingLoader) Cache added in v0.2.2

func (l *CachingLoader) Cache() *DesignCache

Cache is the DesignCache this loader reads through, for the services that keep a model on top.

func (*CachingLoader) Design added in v0.2.2

func (l *CachingLoader) Design(ctx context.Context, uri artifact.URI, opts ...ReadOption) (*ir.Design, error)

Design returns a copy of the design's IR, derived once per identity from the parse while its files are unchanged. Both are stored. A later worker under the same overlay restores the derived design. A worker under another overlay restores the parse and runs only the derive, which costs about a tenth of the parse on a large board.

func (*CachingLoader) Geometry added in v0.2.2

func (l *CachingLoader) Geometry(ctx context.Context, uri artifact.URI, layout string, faithfulSymbols bool, opts ...ReadOption) (*geom.SchematicGeometry, error)

Geometry returns a copy of the drawing, read once per layout, symbol source and identity.

type CheckService

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

CheckService runs the rule checks over a design's netlist IR and serves the rule catalog, over the same injected Loader the design service uses (C13). It was split out of DesignService (WS9-026) and knows no transport.

func NewCheckService

func NewCheckService(loader Loader, catalog *check.Catalog, specs param.ParamProvider, baseConvention string, conventions ConventionLoader, projects *ProjectResolver) *CheckService

NewCheckService returns a CheckService backed by the given loader, rule catalog, and (optional) datasheet provider. Pass check.DefaultCatalog() for the built-ins alone and a nil provider when no datasheet corpus is wired.

baseConvention names the startup convention already composed into catalog, so a request that sends its own replaces it rather than stacking on it; pass "" when the catalog carries none.

func (*CheckService) CheckDesign

CheckDesign runs the rule checks over a loaded design's netlist IR. A geometry-only file with no netlist is an invalid argument. request.rules selects the subset to run, empty meaning the whole catalog. request.subjects selects the nets and parts to answer for, empty meaning all of them. Each finding's sheets locate its subject in the design's geometry (WS9-024). A design with no resolvable geometry gets findings without sheets rather than an error.

func (*CheckService) GetCheckReport

GetCheckReport runs the same selected rules CheckDesign runs and returns their severity pivot. It is a separate RPC rather than a client-side regrouping of CheckDesign, so every consumer renders the one canonical report shape. Findings carry the same sheet annotation as CheckDesign's (WS9-024), so the report panel shares the sheet-navigation join.

func (*CheckService) GetComponentParams

GetComponentParams returns the datasheet join read-only (WS9-035), listing every component whose MPN resolves to a seeded PartSpec with that spec's parameters. A nil provider or an unseeded design yields an empty list rather than an error. The join needs no board, so none is passed.

func (*CheckService) GetExpectations

GetExpectations returns a design's expected findings from its sidecar (WS6-006). A missing sidecar yields an empty list, and only an invalid uri or a malformed sidecar is an error. The `fires` entries come first, then the `pending` ones, which the client reconciles against CheckDesign.

func (*CheckService) GetInterfaceCoverage

GetInterfaceCoverage projects the run's interface profiles onto the loaded design's coverage matrix (WS9-041), with one entry per DETECTED interface listing each required signal, its matched net and its state. It reuses profiles.Coverage, which runs the same datalog the profile rules compile to, so the coverage panel and the findings never disagree. A design with no detected interface yields an empty list rather than an error, since the rules are silent there too.

It reads the design the way CheckDesign does, through the design's overlay and declared tiers, and walks the profiles that run's rules came from (Overlay.ProfileIndex). Until agni issue 833 it read the bare file against the built-ins alone, so a project's lexicon, its own profiles and its intent were absent from the panel while present in the findings beside it.

func (*CheckService) GetNamingConvention

GetNamingConvention resolves a stored convention config into the value an OverlayConfig carries. It validates before returning, so a malformed config is reported once, here, naming what is wrong, rather than on every run that sends it.

func (*CheckService) ListRules

ListRules returns the catalog that a check of the same snapshot would run, each rule in its wire form with its availability. A rule is available exactly when a whole CheckDesign of that snapshot does not report it in `skipped` (listedGate). The design's netlist is read for it, and its board is not. The snapshot is optional, and without one the server's own catalog is listed with the design-less availability, so ListRules works before a file is chosen.

func (*CheckService) RenderCheckReport added in v0.2.2

RenderCheckReport writes a run the caller already holds as a file to keep (agni issue 127). It runs no rules. The JSON form is a CheckResults document, the same one `agni check --results-out` writes. The HTML form is the page that `agni check --verdicts --format html` writes. It has a Queries section per query set the caller answered and sent (agni issue 1190). Both CLI paths call this, so a report saved from the viewer and one the CLI wrote differ only in their timestamps.

The request has to name the snapshot and rules the run used. They decide which catalog the report describes and which netlist tier's content hash it records. Nothing here can check them against the run.

func (*CheckService) Snapshots added in v0.3.0

func (s *CheckService) Snapshots() *SnapshotService

Snapshots is the SnapshotService over this service's loader, resolver, datasheet corpus and base convention, so a snapshot is composed exactly as a check of it reads (agni issue 1061). A host serves it beside this service rather than building one of its own.

func (*CheckService) WithEnv added in v0.2.2

func (s *CheckService) WithEnv(env ReviewEnv) *CheckService

WithEnv sets the deployment provenance that a written document records. That is the producer version, and whether profiles and intent were composed into the catalog. A review run records the same ReviewEnv, so a check document and a review document from one deployment state the same build.

func (*CheckService) WithProfileIndex added in v0.2.2

func (s *CheckService) WithProfileIndex(byName map[string][]profiles.Profile) *CheckService

WithProfileIndex gives the service the deployment's interface-profile index, keyed by name. The coverage panel walks it with a design's own profiles layered on. Pass the same index the ReviewService was built with, so the panel and a review describe an interface by one definition. It returns s for chaining. Without it the panel walks the built-ins.

type ConfigResolver

type ConfigResolver interface {
	// ResolveConfig loads what cfg's URIs point at.
	//
	// namespace is the catalog source name a profile set is registered under. The caller passes it
	// because a project's config is namespaced by its id and a request's has no id, and two projects on
	// one server would otherwise contribute rule sources of the same name.
	ResolveConfig(ctx context.Context, cfg *webapi.AnalysisConfig, namespace string) (ResolvedConfig, error)
}

ConfigResolver turns the ref-shaped tiers of an AnalysisConfig into engine inputs for a run. This port keeps file I/O out of a service (C13). A config names its profiles and parameters as URIs, and only an adapter can read them.

It resolves ANY AnalysisConfig, a request's as well as a project's, so the two cannot drift apart. Which config is being resolved shows up only as the namespace. A tier the config does not name is a ZERO VALUE, never an error, because most configs declare only some tiers.

type ConventionLoader

type ConventionLoader interface {
	Convention(ctx context.Context, uri artifact.URI) (*configpb.NamingConvention, error)
}

ConventionLoader reads a stored naming-convention config, mount-scoped by the impl.

It is NOT on the path that RUNS checks. A convention reaches a check run as a value on the request (C22), so CheckDesign needs no filesystem. It backs the resolver rpc. A client with a ref and no filesystem calls that rpc first.

type DesignCache added in v0.2.2

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

A DesignCache keeps what reading a design produced, so a second request for the same design does not read it again (agni issue 895). It holds three levels, each keyed on the one below (agni issue 1061). CachingLoader keeps the parse, which reads no configuration. It also keeps the design derived from that parse under an overlay's conventions and corpus, along with the drawings and the board. Every surface reads through CachingLoader. On top, BuildModelCached keeps the check model and its fact base. A query or a check needs them, and building them costs a further 100ms on a large board. The rule results a check keeps live on the model's entry (keptresults.go).

An entry is keyed by what was asked, which is the URI, the layout and the read options' identity. Every hit checks the entry against what the read touched. That is every file the read opened, walked or looked for, recorded as a formats.Touched. A hit whose files stamp differently is read again. So the key never has to name a file. A hierarchical schematic's sub-sheets, a declared companion and a symbol library all invalidate the entry, and nobody has to list them.

Two rules keep it from serving a wrong answer. A read whose options carry no identity is never cached past the parse (see WithIdentity). Nothing is cached from a read that recorded no files, since that read went around the formats.Loader and nothing could tell when it went stale.

`agni serve` and the browser engine run the same code. In the browser the engine is rebuilt on every mount change, and that drops its in-memory entries. The parse, the derived design, the drawing and the board are also kept in a BlobStore that outlives the worker (see Persist).

func NewDesignCache added in v0.2.2

func NewDesignCache(max int) *DesignCache

NewDesignCache keeps at most max entries, evicting the least recently used. Each layer's entry counts once, so a design asked for by both a query and a drawing holds about four. max <= 0 means a cache that keeps nothing.

func (*DesignCache) AfterLoad added in v0.2.2

func (c *DesignCache) AfterLoad(loaded func()) *DesignCache

AfterLoad runs loaded after each layer the cache reads, builds or restores, before the value is served. The browser engine passes runtime.GC (agni issue 1000). Wasm memory never shrinks, so the garbage left by a board's parse sets the floor that the rules stage grows from. One collection there took the Jetson seed's check from a 1.34 GB peak to 805 MB. A server leaves it unset, since its memory is returned to the system and a full collection per layer would cost every request.

func (*DesignCache) Persist added in v0.2.2

func (c *DesignCache) Persist(store BlobStore, check FingerprintCheck, version string) *DesignCache

Persist keeps the cache's parsed designs, drawings and boards in store as well, so another process over the same files restores them rather than reading them again (agni issue 911). The model and fact base are rebuilt from a restored design, at about a tenth of a read's cost, because they have no serialized form and C8 keeps it that way.

A stored entry holds a content fingerprint of every name its read touched (formats.Touched.Fingerprint). It is used only when check says they all read the same now. So a file edited, added or removed since then reads again, as it does in memory. version names what wrote the entry. An engine that reads a file differently must pass a different version, or it restores what the older engine parsed. An empty version persists nothing.

func (*DesignCache) Restored added in v0.2.2

func (c *DesignCache) Restored() int64

Restored is how many misses were answered from the persistent tier rather than by a read.

func (*DesignCache) Stats added in v0.2.2

func (c *DesignCache) Stats() (hits, misses int64)

Stats reports hits and misses since the cache was made, for a log line or a test.

type DesignLoader

type DesignLoader interface {
	Design(ctx context.Context, uri artifact.URI, opts ...ReadOption) (*ir.Design, error)
	Geometry(ctx context.Context, uri artifact.URI, layout string, faithfulSymbols bool, opts ...ReadOption) (*geom.SchematicGeometry, error)
}

DesignLoader is the slice of Loader that the diff tier needs. It reads the netlist IR for both sides, plus each side's default-layout geometry for the sheet-membership annotation (WS9-006). Geometry is best-effort there (see annotateDiffSheets). Any Loader satisfies it.

type DesignService

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

DesignService loads and renders one design over injected ports (CONSTRAINTS C13). It resolves a design's IR/geometry via a Loader, renders golden pages via a NativeRenderer, and does the pure select/pack/label itself. It performs no file I/O and knows no transport. Rule checks are the separate CheckService (checks.go).

func NewDesignService

func NewDesignService(loader Loader, native NativeRenderer, style render.Style, projects *ProjectResolver) *DesignService

NewDesignService returns a DesignService backed by the given ports and render style. A nil projects resolver means this deployment resolves no projects.

func (*DesignService) GetDesign

GetDesign answers what a design is. With no read_mask it returns the summary the viewer opens with, unchanged, holding counts, sheets, layout and content hash. With a mask it returns exactly the paths named, and those may include the design's IR (agni issue 836). `design` asks for all of it, `design.nets` or `design.components.mpn` for parts, and `*` for everything. A mask entirely under `design` skips the drawing and reads the netlist alone. nets and ref_des narrow which entities the IR carries.

func (*DesignService) GetLayoutReport

GetLayoutReport explains how an auto-layout would draw each component under the requested symbol source. A resolve error (unknown mount / escaping path) is returned. A file with no netlist has nothing to classify, so it gets an empty report rather than an error.

func (*DesignService) GetSheet

GetSheet resolves the file's geometry, selects one sheet, and renders it in the requested format. A sheet is selected by id, name, or 0-based index, and an empty selector picks the first. PACKED, the default, is tier-2 geometry for the WebGL viewer. SVG is the render.SheetSVG reference. NATIVE uses the format's own tool. A bad selector classifies as ErrNotFound. An unexpected native-render failure past the ErrNative* gates classifies as ErrInternal.

func (*DesignService) HighlightSheet

HighlightSheet resolves highlight specs against one rendered sheet and returns the drawable overlay layer, apart from the base render. PACKED yields primitive-index groups that join the GetSheet PackedSheet by index. SVG yields a transparent overlay document framed exactly like the GetSheet SVG. The sheet/layout/symbols selection mirrors GetSheet, so the overlay describes the same geometry as the base render under it. NATIVE is a golden shell-out with no overlay concept, so it classifies as ErrInvalidArgument.

func (*DesignService) ListWalkKinds added in v0.6.0

ListWalkKinds lists check.WalkKinds. It reads no design.

func (*DesignService) LocateSubjects added in v0.5.0

LocateSubjects answers which sheets draw each subject (agni issue 1325). It reads the snapshot's netlist and schematic, and its board only when the request asks. It uses the same index a check run's findings use (sheetIndex), so a subject locates here exactly where its finding badges.

A subject drawn nowhere carries the reason a finding would: NOT_IN_DESIGN for a name the netlist lacks, a power rail or a virtual symbol for those, and NO_GEOMETRY otherwise. A request naming no subjects is an invalid argument, since an empty answer would read as "drawn nowhere". A design with no board answers without the board sheet rather than failing, because "board" asks where the subject is drawn and a board-less design draws it on no board.

func (*DesignService) ReachablePins added in v0.6.11

ReachablePins answers which pins a trace from one pin reaches within a radius (agni issue 1541). It reads the snapshot's netlist, as TraceDesign does, and no geometry.

func (*DesignService) Snapshots added in v0.3.0

func (s *DesignService) Snapshots() *SnapshotService

Snapshots is the SnapshotService over this service's loader and resolver, which holds the snapshots its questions name (agni issue 1061).

func (*DesignService) TraceDesign

TraceDesign walks from one pin to another over the design's netlist and returns the route.

It calls the same check.TracePins the CLI calls, so a route in a terminal and a route on the canvas cannot disagree. A design with no netlist is an ERROR rather than an empty trace, because an empty answer is indistinguishable from "these two pins are not connected".

func (*DesignService) WalkDesign added in v0.6.0

WalkDesign walks outwards from one part or pin over the snapshot's netlist (agni issue 1339). It calls the same check.WalkFrom the CLI calls. An unknown kind is ErrInvalidArgument, and a start that names nothing is an answer with its reason set, as TraceDesign answers an unresolved endpoint. A request with a goal also asks it from the walk (check.WalkGoalFrom, agni issue 1340). An unknown goal kind is ErrInvalidArgument, and a goal that names nothing is an answer with its outcome set.

type DesignSources

type DesignSources struct {
	// NetlistURI names the netlist the design team produces (C21). Component and connectivity
	// ANALYSIS reads it.
	NetlistURI string
	// BoardURI is where the board tier's copper comes from. It is often the same artifact, and it
	// differs when a design declares a separate board companion.
	BoardURI string
	// GeometryURI names the artifact that schematic sheets are rendered from and findings are located
	// on. A netlist entry has no geometry of its own, so a design declaring a schematic companion
	// locates on that companion's sheets. Under C21 a companion is a canvas and not a source.
	GeometryURI string
}

DesignSources names the artifact each tier of a read comes from, after the design's declaration is applied. They are URIs, the injected Loader resolves them, and no caller above the Loader may treat one as a host path (CONSTRAINTS C22).

func SourcesFor

func SourcesFor(d *webapi.Design, named string) DesignSources

SourcesFor resolves a design's declaration into the artifact each tier reads.

It lives here, above the store and below every client, so CLI and web do not each decide which companion supplies the board. A tier resolved differently in two places gives two findings lists with nothing to say why they differ.

`named` is the ref the caller actually asked for, "" when they named the design itself. A named companion KEEPS whatever tier it alone can supply (a board file's copper, a schematic's sheets), and only the netlist tier ever moves.

type DiffService

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

DiffService computes the semantic diff between two designs over an injected loader (C13). It reads both sides' netlist IR, runs the pure diff.Designs, and owns the wire shape, which the CLI's `diff --format json` shares through DiffResponseProto. See docsite/content/architecture/semantic-diff.md.

func NewDiffService

func NewDiffService(loader DesignLoader, projects *ProjectResolver) *DiffService

NewDiffService returns a DiffService backed by the given loader. A nil projects resolver means this deployment resolves no projects.

func (*DiffService) DiffDesigns

DiffDesigns loads both designs' netlist IR and returns the classified report plus the highlight maps. Either side failing to load fails the whole call with the classified error (unknown mount -> ErrNotFound, escaping path or parse failure -> invalid argument); there is no partial diff.

func (*DiffService) Snapshots added in v0.3.0

func (s *DiffService) Snapshots() *SnapshotService

Snapshots is the SnapshotService over this service's loader and resolver.

type DirEntry

type DirEntry struct {
	Name  string
	IsDir bool
}

DirEntry is one raw filesystem entry, before the service labels a file with its design format.

type FileReader added in v0.2.2

type FileReader interface {
	ReadFile(ctx context.Context, uri artifact.URI) ([]byte, error)
}

FileReader reads one file inside a mount. ListDesignFiles sizes and hashes files through this port. It is separate from Workspace, so the hosts that only browse (the datasheet service) need not read.

type FilesWithheldError added in v0.3.0

type FilesWithheldError struct{ Hashes []string }

FilesWithheldError reports a question that read a file whose contents its host was not given. The browser engine withholds a design's board until a question needs it (agni issue 992). Hashes are the withheld files' content hashes. A transport sends them as a webapi.BlobsMissing detail, the same shape an Ingest naming unsent files answers with, so a client sends those files and asks again.

func (*FilesWithheldError) Detail added in v0.3.0

func (e *FilesWithheldError) Detail() *webapi.BlobsMissing

Detail is the error as the wire carries it.

func (*FilesWithheldError) Error added in v0.3.0

func (e *FilesWithheldError) Error() string

type FingerprintCheck added in v0.2.2

type FingerprintCheck func(fp []byte) (*formats.Touched, bool)

A FingerprintCheck reports whether a stored read's content fingerprint (formats.Touched.Fingerprint) still matches the files the host serves now, and if so returns a recorder of those names as they stamp now. The host supplies it, because only the host can open the files (C13). formats.CheckFingerprint over the Loader's FS is the usual one.

type GeometryLoader

type GeometryLoader interface {
	Geometry(ctx context.Context, uri artifact.URI, layout string, faithfulSymbols bool, opts ...ReadOption) (*geom.SchematicGeometry, error)
}

GeometryLoader is the file surface BuildGeometry needs. The fat service.Loader and DiffService's DesignLoader both satisfy it.

type LexiconService added in v0.4.0

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

LexiconService answers how a snapshot's names were read (agni issue 1266). It is built from the CheckService of the same host, since comparing two lexicons runs that service's catalog over the same loader, corpus and projects, and a host cannot then serve the two over different ones.

func NewLexiconService added in v0.4.0

func NewLexiconService(checks *CheckService) *LexiconService

NewLexiconService returns the lexicon questions over checks' loader, catalog and projects.

func (*LexiconService) CompareLexicons added in v0.4.0

CompareLexicons reads the snapshot with the candidate convention in place of its own and diffs the roles and the findings of the two reads.

func (*LexiconService) ExplainNet added in v0.4.0

ExplainNet returns one net's stamped roles and the net-name entries its name matches.

func (*LexiconService) GetLexicon added in v0.4.0

GetLexicon lists the snapshot's effective lexicon with each entry's source.

func (*LexiconService) RenderConvention added in v0.4.0

RenderConvention writes a convention as a conventions file.

type LibraryModule added in v0.2.2

type LibraryModule struct {
	Path     string
	Language string
	Text     string
	Source   string
}

LibraryModule is one module of a project's own derived relations, as a ConfigResolver read it. It holds the module path that its members register under, the module's language and text, and Source. Source says where the module was read from, and an error names it so a reader can find the file.

type Loader

type Loader interface {
	// Design returns the netlist IR (for counts and checks). A geometry-only file has none and
	// returns an error the caller treats as "no netlist".
	Design(ctx context.Context, uri artifact.URI, opts ...ReadOption) (*ir.Design, error)
	// Geometry resolves drawable geometry for the layout and symbol source (the design's own
	// symbols when faithfulSymbols, else synthetic glyphs). It takes ReadOptions because a symbol
	// library changes what the read CONTAINS (agni issue 347). An unresolved symbol contributes no
	// shapes, so its placement and pickable entity keys drop out while its ref-des still draws, and
	// the sheet looks complete with every component and pin on it silently unclickable.
	Geometry(ctx context.Context, uri artifact.URI, layout string, faithfulSymbols bool, opts ...ReadOption) (*geom.SchematicGeometry, error)
	// Report classifies how an auto-layout draws each component (the conversion report). It takes
	// ReadOptions for the same reason Geometry does. Report would REPORT an unresolved symbol, so a
	// read blind to the project's library would diagnose a problem it caused.
	Report(ctx context.Context, uri artifact.URI, faithfulSymbols bool, opts ...ReadOption) (*graph.ConversionReport, error)
	// Expectations loads a design's `<path>.expect.yaml` sidecar (WS6-006). A design with no sidecar
	// returns a nil map and a nil error, since absence is normal. The caller then renders an empty
	// panel rather than an error.
	Expectations(ctx context.Context, uri artifact.URI) (*expect.Expectations, error)
	// Board returns the physical board sidecar (WS1-006) for formats that carry one
	// (.kicad_pcb, IPC-2581 .xml/.cvg). nil with a nil error means the format has none. That is
	// normal, as with Expectations, and the design then lists no board sheet.
	Board(ctx context.Context, uri artifact.URI) (*geom.BoardGeometry, error)
	// DesignHash returns "sha256:<hex>" over the design's entry file. A verdict link is checked
	// against this revision identity (agni issue 392). The review service's port and `agni check
	// --url-base` use this same method, so both sides of the link compare values from one
	// implementation.
	//
	// THE CALLER PASSES A RESOLVED TIER, never the request. A design has three spellings, the
	// folder, the entry and a declared companion, and all three analyse the same bytes. So the
	// identity is the NETLIST tier that `TierURIs` returned (C32). Hashing the request gives a
	// companion the companion's digest and a folder no hash at all, so one spelling reports a wrong
	// revision and another reports none.
	//
	// An error means this server could not hash the file, and GetDesign then reports an empty
	// content_hash. That is a THIRD state, distinct from a match and a mismatch. The response's doc
	// comment binds the consumer to keep it distinct.
	DesignHash(ctx context.Context, uri artifact.URI) (string, error)
}

Loader materializes a design's read model from an artifact.URI. osLoader in cmd/agni is the os-backed server adapter. All file I/O lives in the adapter, never here (CONSTRAINTS C13).

type LocateSource

type LocateSource interface {
	NetSource
	check.LocateModel
}

LocateSource is NetSource plus the three questions needed to EXPLAIN a subject that will not highlight. Is this ref a real component? Is this name a real net? Is that net a power rail?

Required rather than probed for with a type assertion, so a caller that cannot answer them fails to compile. LOCATE_REASON_UNSPECIFIED means "the entity IS drawn and should highlight", so leaving it on an undrawn subject tells the viewer to say nothing.

check.Model satisfies it, and both production callers pass one.

type MemReviewStore

type MemReviewStore struct {

	// Clock, when set, stamps created_at. Nil leaves it empty, as the CLI wants for a run it never
	// persists.
	Clock func() string
	// contains filtered or unexported fields
}

MemReviewStore is an in-memory ReviewStore. It backs most tests and `agni review`. That command is a thin client of CreateReview and must leave no files behind, since --results-out is how it writes a document.

Ids are the insertion ordinal rather than a timestamp. That keeps tests deterministic, and the store still lists newest first.

func NewMemReviewStore

func NewMemReviewStore() *MemReviewStore

NewMemReviewStore returns an empty in-memory store.

func (*MemReviewStore) Create

func (m *MemReviewStore) Create(_ context.Context, parent string, results *checkspb.CheckResults) (string, string, error)

func (*MemReviewStore) Delete

func (m *MemReviewStore) Delete(_ context.Context, name string) error

func (*MemReviewStore) Get

func (*MemReviewStore) List

func (m *MemReviewStore) List(_ context.Context, parent string, pageSize int, pageToken, designFilter string) ([]*checkspb.CheckResults, []string, string, error)

type ModelLoader

type ModelLoader interface {
	Design(ctx context.Context, uri artifact.URI, opts ...ReadOption) (*ir.Design, error)
	Board(ctx context.Context, uri artifact.URI) (*geom.BoardGeometry, error)
}

ModelLoader is the file surface BuildModel needs: the netlist design and its board sidecar, both mount-scoped by the impl. The fat service.Loader and the review ReviewLoader both satisfy it, so every service reaches BuildModel through the loader it already holds.

type MountInfo

type MountInfo struct {
	Name string
	Root string
}

MountInfo identifies one browseable root the workspace exposes.

type NamedQuerySet added in v0.2.2

type NamedQuerySet struct {
	Name   string
	Source string
	Set    query.QuerySet
}

NamedQuerySet is one query set a project keeps: its name (the file's stem), the set, and the file it was read from.

type NativeRenderer

type NativeRenderer interface {
	Available(uri artifact.URI) bool
	Render(ctx context.Context, uri artifact.URI, page int) (string, error)
}

NativeRenderer renders a page with the format's own golden tool (a shell-out platform effect). Available reports whether NATIVE can be offered for a file; Render returns the page's SVG or one of the ErrNative* gate errors.

type NetSource

type NetSource interface {
	Nets() []*ir.Net
}

NetSource is the slice of the design Model that these annotate helpers read. It gives them the netlist's nets for the AttrSheets membership (WS9-028). It is declared at the point of use rather than taking the whole check.Model, and check.Model satisfies it structurally (WS1-044). It also keeps these helpers off the raw *ir.Design (C19).

type Overlay

type Overlay struct {
	Sources []check.RuleSource
	Lexicon *classify.Lexicon
	// Specs is the datasheet corpus this run checks part limits against, nil when there is none. It
	// is composed together with the rule sources, so a run cannot check one team's rules against
	// another team's data.
	Specs param.ParamProvider
	// SymbolPaths are the symbol-library directories this run's config named, added to the read.
	SymbolPaths []string
	// Profiles and Intent record whether this overlay's Sources include a project's interface profiles
	// and a design's intent declaration. ResolvedConfig says why the overlay records these flags
	// rather than deriving them from Sources.
	Profiles bool
	Intent   bool
	// DesignIntent is the declared intent itself, nil when none was declared. Its rules are already in
	// Sources. The overlay keeps the value too, because part of it is for the MODEL rather than for a
	// rule. The model reads which connectors are internal from it (agni issue 831).
	DesignIntent *configpb.DesignIntent
	// InterfaceProfiles are the profile VALUES behind the profile source in Sources. They come from a
	// project's own profiles/ and from any profiles a request's config names. Running a profile needs
	// only its compiled rules. Two surfaces read a profile itself, the coverage panel and a review's
	// interface-presence gate, and these values let them see the profiles the run's rules came from
	// (agni issue 833).
	InterfaceProfiles []profiles.Profile
	// Library and LibraryDocs are the project's own derived relations and their pages, composed into
	// a query vocabulary by Registry.
	Library     []LibraryModule
	LibraryDocs map[string]string
	// FlattenHierarchy reads the design's hierarchical netlist as its whole schematic (agni issue
	// 718). The snapshot chooses it, not a project's config. It sits on the overlay because every
	// read and every cache key already goes through ReadOptions and Identity. Set it with
	// WithFlattenHierarchy, which folds it into the identity.
	FlattenHierarchy bool
	// Convention is the convention this overlay's Lexicon was built from. It is nil when the read uses
	// the built-ins or the server's startup default. ConventionSource says which tier it came from.
	// Together they let a reader of the lexicon tell a built-in pattern from a project's (agni 1266).
	Convention       *configpb.NamingConvention
	ConventionSource webapi.LexiconSource
	// contains filtered or unexported fields
}

Overlay is one request's composed catalog configuration. It holds the rule sources to splice onto the service's catalog, and the naming lexicon to stamp on the request's design reads. Every surface that accepts overlay config composes it here, so they all compose identically (WS3-102).

A convention holds rules AND a lexicon, and the two go to different places. Rules extend the catalog. The lexicon has to reach the READ, because net roles are resolved once at ingestion. Doing only the catalog half compiles the naming rules and leaves every OTHER rule blind to the project's rail names.

func ComposeOverlay

func ComposeOverlay(cfg *webapi.OverlayConfig, baseConvention string) (Overlay, error)

ComposeOverlay resolves an OverlayConfig into engine inputs. A nil or empty config yields a zero Overlay, which changes nothing, so a request that names no overlay behaves exactly as before.

baseConvention is the catalog source name of the SERVER's startup convention, which this request's own convention replaces (WS3-124). Pass "" when the caller composed no such default, and nothing is replaced. It is a required parameter rather than an optional wither so that a call site forgetting it fails to compile instead of silently stacking conventions (WS3-102, WS3-109).

It performs no I/O, since the config arrives as a value. An invalid convention is an ERROR, never a skip, because an operator who silently got the built-ins would read the clean report as a clean design. A pattern that will not compile is invalid, and so is an unknown component class.

func OverlayFor

func OverlayFor(ctx context.Context, resolver ConfigResolver, store ProjectStore, p *webapi.Project, d *webapi.Design, req *webapi.OverlayConfig, baseConvention string) (Overlay, error)

OverlayFor composes the engine inputs for one design: the project's config where the design resolves to one, and nothing but the request's where it does not.

A design that resolves to NO project gets no project config, so it cannot be checked against another project's rules (#180). The motivating bug is on docsite/content/architecture/projects-and-designs.md#three-tiers-of-configuration.

baseConvention is as on ComposeOverlay. A REQUEST's own overlay wins over the project's.

func (Overlay) Catalog

func (o Overlay) Catalog(base *check.Catalog) (*check.Catalog, error)

Catalog splices this overlay's rule sources ONTO base, returning base unchanged when the overlay carries none.

It extends base rather than rebuilding a catalog (WS3-107). check.CatalogWith keeps the built-ins but drops base. For a review, base holds the --profile-path and --intent-path sources, so with CatalogWith one naming rule in a convention disabled every interface profile and the whole intent tier. Measured on one design, 19 items went pass -> needs-design-intent and 16 went pass -> not-automated.

A request's convention REPLACES the server's startup one rather than stacking on it (WS3-124). Catalog composition tags every rule with its source name (check.KeySource), so the replacement drops the rules tagged with baseConvention's name and nothing else. The built-ins and the profile and intent sources are not the request's to remove. A caller naming no base convention keeps the additive behaviour, and the CLI is one such caller.

A name collision returns an error rather than panicking, since the sources come from a REQUEST.

func (Overlay) Identity added in v0.2.2

func (o Overlay) Identity() (string, bool)

Identity returns a value that differs whenever anything this overlay was composed FROM differs, and reports false when the composition cannot be fully identified.

It is for a caller reusing work only under the same configuration, such as a check-result cache. Equal identities mean equal inputs. Different identities may still behave identically, since this compares inputs rather than outcomes, and that is the safe direction to be wrong in.

FALSE IS NOT AN ERROR. It means an input could not be identified, most often config a resolver read without reporting a digest. A caller must then do the work rather than reuse any, and must never treat the empty string as a key.

func (Overlay) ProfileIndex added in v0.2.2

func (o Overlay) ProfileIndex(base map[string][]profiles.Profile) map[string][]profiles.Profile

ProfileIndex returns the interface profiles this run's rules came from, keyed by name. It starts from base, which holds the built-ins and a deployment's --profile-path, already composed. This overlay's own profiles REPLACE a base profile of the same name, as their compiled source supersedes its rules. A surface reading a profile rather than running it uses this, so it never describes an interface by a definition the run did not check (agni issue 833). base is not modified.

func (Overlay) Provenance

func (o Overlay) Provenance(deployment RunProvenance) RunProvenance

Provenance reports what a run under this overlay actually had attached, meaning this overlay's own tiers unioned with the deployment defaults the caller composed into its catalog and specs.

Union rather than override, because the two stack for every tier except the convention. A server started with --profile-path serving a project that also declares profiles runs BOTH. The convention is already resolved here, since a request-supplied one replaces whatever was in place (WS3-124), so conventionName wins and the deployment's name is only the fallback.

func (Overlay) ReadOptions

func (o Overlay) ReadOptions() []ReadOption

ReadOptions returns the options the overlay adds to each design READ. It adds the naming lexicon, the symbol paths, the datasheet device-class lookup, the design intent and the flatten choice, each only when present.

func (Overlay) Registry added in v0.2.2

func (o Overlay) Registry() (*facts.Registry, error)

Registry returns the query vocabulary for this overlay's queries. That is the process default, plus the project's own library when it has one (agni issue 773). An overlay with no library gets facts.DefaultRegistry itself, so nothing changes for a project that declares none.

A library is composed once per distinct content and cached, because a server answers many queries over one project and composing checks every module. An error names the module's file. If the shipped vocabulary already defines a member's path, the member is refused by name before composition. The vocabulary's own message for that names the path and not the file that caused it.

func (Overlay) SpecsOver added in v0.2.2

func (o Overlay) SpecsOver(shared param.ParamProvider) param.ParamProvider

SpecsOver returns the datasheet corpus this run should use. It layers the project's own corpus over the shared one (--params or --params-url) per MPN, so the project decides every part it seeds and the shared corpus answers for the rest (agni issue 749). Each citation names its corpus. A limit transcribed outside the project now decides some of the project's verdicts, and a reader has to be able to see which. DECISIONS.md records the reversal from the project replacing the shared corpus outright. It returns nil when neither exists.

func (Overlay) WithFlattenHierarchy added in v0.3.2

func (o Overlay) WithFlattenHierarchy(on bool) Overlay

WithFlattenHierarchy returns o with its design reads flattening a hierarchical netlist when on is set, and o unchanged otherwise. The choice joins the identity, so a cache never serves a flattened read for an unflattened one. An overlay that cannot identify itself is still unidentifiable afterwards. A zero overlay gains an identity naming the choice alone.

type ProjectResolver

type ProjectResolver struct {
	Store  ProjectStore
	Config ConfigResolver
	// SnapshotLimit is how many snapshots the resolver holds before evicting the least recently asked
	// (agni issue 1061). Zero means defaultSnapshots.
	SnapshotLimit int
	// Uploads builds the host for reading a design that a client sends as files (see UploadHost).
	// Nil means this host takes no files, and an ingest of one is refused.
	Uploads UploadHost
	// UploadMaxBytes caps the uploaded content the host keeps. Past the cap the host drops the least
	// recently used. Zero means defaultUploadBytes.
	UploadMaxBytes int64
	// contains filtered or unexported fields
}

ProjectResolver holds the two ports a rule-running surface needs to answer "whose config applies to this design". The store maps an artifact to its project, and the loader turns that project's config into engine inputs.

Every surface that runs rules needs both or neither, so they are one constructor parameter. When each surface wired them itself, --conventions once reached `agni check` and not `agni review` (WS3-102, WS3-109).

A nil resolver means this deployment resolves no projects, and every design runs as one in no project, as on a server started with no descriptors.

func (*ProjectResolver) Checklists added in v0.2.2

func (r *ProjectResolver) Checklists(ctx context.Context, uri artifact.URI) ([]*webapi.NamedChecklist, string, error)

Checklists returns the checklists a design reads and the project's name. The checklists are its project's and its own, with inherited ones first in the order ResolveExtends composes them. A design in no project still has the checklists it declares itself. A design resolving nothing returns (nil, "", nil), and so does a deployment that resolves none. A project whose chain declares none returns (nil, name, nil). A caller can then tell an operator which fix applies. A descriptor that exists and does not parse is an error, as for Overlay.

func (*ProjectResolver) OptionalSnapshot added in v0.3.0

func (r *ProjectResolver) OptionalSnapshot(ctx context.Context, name string) (context.Context, Snap, bool, error)

OptionalSnapshot is Snapshot for a request where naming none is allowed, returning ok false then.

func (*ProjectResolver) Overlay

func (r *ProjectResolver) Overlay(ctx context.Context, uri artifact.URI, req *webapi.OverlayConfig, baseConvention string) (Overlay, error)

Overlay composes the config for one design, its project's where it has one, and the request's own on top. A design in no project gets the request's config alone. The serve flags reach a run another way. The services hold the catalog and the datasheet provider, and the process holds the lexicon, so an overlay never holds the flags (agni issue 755).

Finding NO descriptor is not an error, since a loose file belongs to no project, and neither is an unknown mount. A descriptor that EXISTS and does not parse is returned as an error, as ResolveDesign reports it. Swallowing it once ran the design against the built-in vocabulary. On one folder that gave 40 findings the project's lexicon would not have raised, and missed 95 it would have (#307). A malformed descriptor for an UNRELATED design still does not surface here. See docsite/content/architecture/projects-and-designs.md#resolution-is-an-interface-not-a-path-convention.

func (*ProjectResolver) QuerySets added in v0.2.2

func (r *ProjectResolver) QuerySets(ctx context.Context, uri artifact.URI) ([]NamedQuerySet, string, error)

QuerySets returns the query sets a design keeps and the project's name. The sets are its project's and its own, inherited ones first. An absent project and an empty one answer as they do for Checklists. Only the query-set tier is resolved, so a listing reads no profile, corpus or library, and a broken one cannot fail it. A set file that does not parse fails the listing, since leaving it out would read as the design having no such set.

func (*ProjectResolver) Snapshot added in v0.3.0

func (r *ProjectResolver) Snapshot(ctx context.Context, name string) (context.Context, Snap, error)

Snapshot returns the snapshot a question names and a context to answer it under. That context records onto the snapshot every file the answer reads. A name the host does not hold is a *SnapshotError, and so is a snapshot whose files changed since they were read.

func (*ProjectResolver) Sources added in v0.2.2

func (r *ProjectResolver) Sources(ctx context.Context, uri artifact.URI, asNamed bool) (Resolution, error)

Sources resolves an artifact ref to the artifact each tier should read, applying the enclosing design's declaration when there is one.

This is the served counterpart of what `cmd/agni` does around `ResolveSources`. Without it a netlist entry drew an auto-layout on the server while the CLI drew the declared companion's real sheets (agni issue 656, C32).

A nil resolver, a resolver with no store, and a ref belonging to no declared design all yield the ref in every tier. That is the ordinary case for a mounted folder, not an error.

isDir is derived rather than stat'ed (C13). A design's URI IS its directory, since `fsstore` sets it from the descriptor's folder, so only a ref equal to it names the design.

asNamed comes off the request, because the CLI is a client of these services and its --as-named asks for the file it named.

func (*ProjectResolver) TierURIs added in v0.2.2

func (r *ProjectResolver) TierURIs(ctx context.Context, u artifact.URI, boardOverride artifact.URI, asNamed bool) (netlist, board, geometry artifact.URI, err error)

TierURIs returns Sources with the refs parsed back into artifact URIs, the form every read takes.

It is the one call a service makes to learn which artifact each tier should open. Resolving here rather than in the loader keeps the loader a reader of what it is handed, so a caller can read a companion as a netlist by naming it.

boardOverride is the request's own board_uri and it WINS over the design's declaration, matching `--board-path` on the CLI. A zero override, which is nearly every call, leaves the declared board.

type ProjectService

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

ProjectService serves the project and design resources over an injected ProjectStore (C13). It does no I/O itself. It applies AIP-158 pagination and the one supported AIP-160 filter, and classifies errors for the transport.

It is AIP-shaped with GET and LIST only, the read-only-resource case in CONSTRAINTS C23. A project gets a resource name rather than an artifact URI because an operator DECLARES its identity, so the name survives the folder being renamed or moved between mounts and reviews can be parented by it.

Every caller goes through here, including the CLI. A second path reaching the store directly would drift on questions invisible from outside, such as whether an unresolved ref is an error or what a malformed descriptor does.

func NewProjectService

func NewProjectService(store ProjectStore) *ProjectService

NewProjectService returns a ProjectService backed by store. A nil store is legal and means this deployment declares no projects, so every method answers as though nothing resolved rather than failing.

func (*ProjectService) GetDesign

GetDesign returns one design by resource name, with the same malformed-vs-absent split as GetProject.

func (*ProjectService) GetProject

GetProject returns one project by resource name. A malformed name is ErrInvalidArgument and a well-formed name for a project that does not exist is ErrNotFound, so a client can tell a typo from a project it lacks.

func (*ProjectService) ListDesigns

ListDesigns returns one project's designs, ordered by resource name. A parent naming a project that does not exist is ErrNotFound rather than an empty list, so a client can tell a wrong parent from a project with no designs.

func (*ProjectService) ListProjects

ListProjects returns the projects visible across the server's mounts, ordered by resource name.

func (*ProjectService) ResolveDesign

ResolveDesign answers whether an artifact ref belongs to a declared design, and if so which.

A ref that resolves to nothing yields an EMPTY response, not an error. Most files on a mount belong to no declared design, and a client reading an empty response falls back to the plain built-in catalog rather than another project's config. Making that ordinary case an error would teach callers to ignore the failure path.

type ProjectStore

type ProjectStore interface {
	// Project returns one project by resource name. A name naming nothing is ErrNotFound.
	Project(ctx context.Context, name string) (*webapi.Project, error)
	// Projects returns every visible project, ordered by resource name.
	Projects(ctx context.Context) ([]*webapi.Project, error)
	// Design returns one design by resource name. A name naming nothing is ErrNotFound.
	Design(ctx context.Context, name string) (*webapi.Design, error)
	// Designs returns a project's designs, ordered by resource name. A parent naming nothing is
	// ErrNotFound, distinct from a project that exists and holds no designs (an empty slice).
	Designs(ctx context.Context, parent string) ([]*webapi.Design, error)
	// ResolveDesign maps an artifact ref to the design containing it and that design's project.
	//
	// A MISS is (nil, nil, nil), never ErrNotFound. A ref that belongs to no declared design is the
	// ORDINARY case on a mounted folder.
	ResolveDesign(ctx context.Context, uri artifact.URI) (*webapi.Design, *webapi.Project, error)
}

ProjectStore resolves the projects and designs a deployment declares (agni issue 170). Like ReviewStore here, and DraftStore and AnnotationStore in datasheet/dsservice, the interface is a port and an implementation lives behind it.

Nothing in these signatures names a file, a path or a walk. The shipped implementation (`internal/projects`) walks a directory tree for descriptors, and a database-backed store with designs on object storage should be a wiring change rather than a redesign.

It is READ-ONLY. Creating a project means authoring design intent from a design, which is a judgment step with a confidentiality boundary rather than a server operation.

Every method deals in the WIRE types, with no parallel value type. A `Project` is a resource whose content is the message, so a twin would be a field-for-field copy that can disagree with it (CONSTRAINTS C2, C8). `MountInfo` and `DirEntry` in workspace.go differ because they project a raw filesystem listing the service still has to interpret.

type QueryRead added in v0.3.4

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

A QueryRead is one snapshot read for a program that RunQuery does not evaluate. The MCP server is one such caller, since its query tool is jaala's (agni issue 910). A QueryRead holds the fact base, the vocabulary with the project's library, and the model. RunQuery reads the same three, so the evaluator answers over the same facts. Present turns its rows into the response RunQuery would give.

func (*QueryRead) Base added in v0.3.4

func (r *QueryRead) Base() *query.Base

Base is the fact base a program is evaluated over. Evaluate with query.EvalOptions(ctx), as RunQuery does, so a served work budget reaches it.

func (*QueryRead) Present added in v0.3.4

func (r *QueryRead) Present(ctx context.Context, q query.Query, queryText string, table *query.Table, lo, hi int, bind query.Bindings) (*webapi.RunQueryResponse, error)

Present returns the response for rows [lo, hi) of table, echoing queryText. q produced table by evaluating over Base with bind. Present is RunQuery's own projection, so a row's cells, kinds, entities and citations match what RunQuery gives for the same query. When the evaluation recorded witnesses, each row carries them, as RunQuery's rows do when asked (agni issue 794). Work is left zero, since the evaluation was not RunQuery's. Total is the table's length when the rows are a page of it.

func (*QueryRead) Vocabulary added in v0.3.4

func (r *QueryRead) Vocabulary() *ns.Vocabulary

Vocabulary is the vocabulary Base answers over, the project's library included.

type QueryService

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

QueryService evaluates ad-hoc datalog queries over a design's fact base (WS3-029) for the web query panel, over the same injected Loader the design and check services use (CONSTRAINTS C13). It answers what `agni query` answers and knows no transport. The evaluator sits behind query.Evaluator and defaults to query.Default, jaala's semi-naive evaluator.

func NewQueryService

func NewQueryService(loader Loader, specs param.ParamProvider, projects *ProjectResolver) *QueryService

NewQueryService returns a QueryService backed by the given loader and an optional datasheet provider. It evaluates with query.Default, jaala's semi-naive evaluator. Pass a nil provider when no datasheet corpus is wired, and the model's param.* relations then yield no rows (never an error).

func (*QueryService) ListQuerySets added in v0.2.2

ListQuerySets answers which query sets the design's project keeps, inherited ones first (agni issue 745). See ProjectResolver.QuerySets for what an absent project and an empty one answer.

func (*QueryService) ListRelations

ListRelations returns the queryable relation catalog (WS9-037) for the panel's relation picker: the built-in relations, the shipped library's derived relations and the predicates, plus any overlay-registered relations, pre-sorted by kind then name (query.Catalog). It loads no design, so it never fails on a bad path and the client can fetch it once at startup.

A request naming a path answers that one place in the namespace tree instead (describeEntry), and an unknown path is ErrInvalidArgument carrying the engine's suggestion.

func (*QueryService) ParseQuerySet added in v0.2.2

ParseQuerySet reads a set file's text into its wire form, checked as `agni query --set` checks it. A set that does not parse is an invalid argument, so a viewer shows the reason beside the file.

func (*QueryService) ReadQuery added in v0.3.4

func (s *QueryService) ReadQuery(ctx context.Context, snapshot string, q query.Query) (*QueryRead, error)

ReadQuery reads the named snapshot for q, with the board tier only when q reads a board.* relation, as RunQuery does (agni issue 987). A snapshot the host does not hold, or one whose files changed, is a *SnapshotError, as it is for RunQuery.

func (*QueryService) RunQueries added in v0.2.2

RunQueries answers every query of a set over one read of the design (agni issue 729). Each result matches what RunQuery would return for that query alone. A query may fail to parse or name something the design's relations lack. That failure is reported against the query's name, and the others still answer. A set that is unusable as a whole is an invalid argument, and a design that cannot be read fails the call as it would fail RunQuery.

func (*QueryService) RunQuery

RunQuery loads the design, parses and evaluates the datalog query over its fact base, and returns the projected columns and answer rows with provenance. A geometry-only file with no netlist and a malformed query are both invalid arguments, so the panel shows the parse error inline. A query that matches nothing returns an empty row set, not an error.

func (*QueryService) RunSpecLibQuery added in v0.2.4

func (s *QueryService) RunSpecLibQuery(ctx context.Context, fs param.FactSource, queryText, source string, bind query.Bindings, witnesses bool) (*webapi.RunQueryResponse, error)

RunSpecLibQuery answers a query over a datasheet corpus with no design (`agni query --speclib`): the param.* and part.* relations range over every spec in fs rather than one design's parts. It answers through the same projection RunQuery does, so its rows, kinds, citations and work are a RunQueryResponse built one way (agni issue 1045). source names the corpus for the response. A query that does not parse is an invalid argument, carrying its position as RunQuery's does. With witnesses each row carries how it was derived, as RunQueryRequest.witnesses asks.

func (*QueryService) Snapshots added in v0.3.0

func (s *QueryService) Snapshots() *SnapshotService

Snapshots is the SnapshotService over this service's loader, resolver and datasheet corpus.

func (*QueryService) Vocabulary added in v0.3.4

func (s *QueryService) Vocabulary(ctx context.Context, snapshot string) (*ns.Vocabulary, error)

Vocabulary returns the vocabulary that checks a question about the named snapshot, the project's library included. It is composed without reading the design, so describing it costs no read. With no snapshot it is the shipped vocabulary.

type ReadOption

type ReadOption func(*ReadOptions)

ReadOption configures one read.

func WithDesignIntent added in v0.2.2

func WithDesignIntent(di *configpb.DesignIntent) ReadOption

WithDesignIntent passes a design's declared intent to the model that BuildModel builds (see ReadOptions.Intent).

func WithDeviceClasses added in v0.2.2

func WithDeviceClasses(f func(mpn string) string) ReadOption

WithDeviceClasses supplies the datasheet device-class lookup for one read, so a design read inside a project that declares a params tier carries the classes only its corpus can establish.

func WithFlattenHierarchy added in v0.3.2

func WithFlattenHierarchy() ReadOption

WithFlattenHierarchy reads a hierarchical netlist as its whole schematic (agni issue 718).

func WithIdentity added in v0.2.2

func WithIdentity(id string, covers int) ReadOption

WithIdentity names the options before it. covers is how many options the identity describes. It must cover every option the read applies, or the identity is not used (see ReadOptions.Identity).

func WithLexicon

func WithLexicon(lex *classify.Lexicon) ReadOption

WithLexicon stamps the design being read with a project's naming vocabulary (WS3-106) instead of the built-in one, so which nets count as rails and grounds follows the request's conventions.

func WithSymbolPaths

func WithSymbolPaths(dirs []string) ReadOption

WithSymbolPaths adds a config's symbol search directories to one read, so a design whose project declares its libraries resolves them without the caller passing a flag.

type ReadOptions

type ReadOptions struct {
	// Lexicon is the naming vocabulary to stamp the design with; nil means the engine defaults.
	Lexicon *classify.Lexicon
	// SymbolPaths are directories to search for the schematic's external symbol libraries, ADDED to
	// whatever the loader was built with. They belong to the read because an unresolved symbol changes
	// what the design CONTAINS, not what is checked about it.
	SymbolPaths []string
	// DeviceClassFor answers a datasheet's device_class for an MPN, nil when this run has no corpus.
	// Like the lexicon, the class is stamped into the IR at ingestion. A model built later re-runs the
	// same additive, idempotent pass, so a corpus arriving after the read still gets the class, but
	// only a class stamped here reaches the DRAWING (agni issue 710).
	DeviceClassFor func(mpn string) string
	// Intent is the design's declared intent. It is for the MODEL built from this read rather than for
	// the read itself. BuildModel hands it to check.WithIntent, so the exposure rules know which
	// connectors the design declares internal (agni issue 831). It travels in the read options because
	// every surface that builds a model already passes Overlay.ReadOptions, so none can miss it.
	Intent *configpb.DesignIntent
	// Identity names everything the options above were composed from, so a cache can key a read on
	// it (agni issue 895). Set by WithIdentity, which Overlay.ReadOptions appends when its overlay
	// can identify itself. Empty means the options cannot be told apart from any others, and a read
	// under them is never cached.
	Identity string
	// FlattenHierarchy reads a hierarchical netlist as its whole schematic (formats.Loader's field of
	// the same name). It belongs to the PARSE, so CachingLoader keys the parse on it as well.
	FlattenHierarchy bool
	// contains filtered or unexported fields
}

ReadOptions is the per-read configuration a service passes down to its loader, for inputs that belong to the READ rather than to the rule catalog. A naming lexicon resolves net roles once at ingestion (WS3-072), so it has to arrive before the design is parsed.

The options are variadic on the Design method, so the type system forces every loader to accept them. An optional capability found by type assertion would let a loader silently ignore a project's conventions, which reads like a design that had none.

func ReadOpts

func ReadOpts(opts ...ReadOption) ReadOptions

ReadOpts resolves options to a value, for a loader implementation to read. Exported because the loaders live in cmd/agni (C1/C13).

type Resolution added in v0.2.2

type Resolution struct {
	DesignSources
	// NamedIsTheDesign is set when the ref named the design itself, which is a folder.
	NamedIsTheDesign bool
	// NamedIsTheEntry is set when the ref named the design's declared entry file.
	NamedIsTheEntry bool
	// FromDeclaration is set when the tiers came from the design's declaration rather than from the
	// ref alone. It does not mean a tier moved. Imagine a ref naming the entry of a design that
	// declares no companion. The declaration applies and changes nothing. A caller narrating what it
	// read still tells that case apart from a ref that was never resolved.
	FromDeclaration bool
}

Resolution records what a ref resolved to. It names the artifact each tier reads and how the resolver chose it.

The struct holds the flags so a caller does not recompute them. Imagine a caller re-deriving "was this the entry" against the path it typed instead of the ref it resolved. It compares unlike with unlike and narrates the wrong thing. The CLI's stderr note is written from these flags.

func ResolveSources added in v0.2.2

func ResolveSources(d *webapi.Design, ref string, isDir, asNamed bool) Resolution

ResolveSources decides which artifact each tier reads, for a ref that has already been resolved to a design. It is the DECISION half of resolution and does no I/O. The caller finds the design, and this says what to open. The CLI finds it over a store rooted at its argument's mount, and a server over the store it was built with. CLI and server both call it, so one design cannot read two ways (agni issue 656, constraint C32).

The four cases:

  • `d` is nil, so the ref belongs to no declared design. Read exactly what was named, which is the ordinary case for any mounted folder without descriptors.
  • The ref names the design itself (a folder) or its ENTRY. It gets the design's declared companions, because naming the entry IS naming the design.
  • The ref names a declared COMPANION. Analysis moves to the entry and the named artifact keeps whatever tier it alone supplies.
  • The ref names an UNDECLARED sibling. Read exactly what was named, since redirection is confined to files an operator listed (docsite/content/architecture/projects-and-designs.md#the-netlist-is-the-source-the-rest-are-views).

asNamed disables redirection, so the artifact named is read whatever the descriptor says. Reading a companion AS a netlist is a legitimate diagnostic.

type ResolvedConfig

type ResolvedConfig struct {
	// Sources are the catalog extensions it supplies: interface profiles, a design's intent.
	Sources []check.RuleSource
	// Specs is the seeded datasheet corpus, nil when there is none. A nil provider is legal and means
	// the datasheet-backed rules read needs-data rather than failing.
	Specs param.ParamProvider
	// SymbolPaths are the resolved symbol-library directories, as host paths the reader can search.
	SymbolPaths []string
	// Profiles and Intent record WHICH tiers the Sources came from, since a compiled interface profile
	// and a compiled intent declaration are both just rules in a catalog. A results document states
	// which tiers were attached. See
	// docsite/content/architecture/checks-contract.md#provenance-is-read-off-the-resolved-overlay.
	Profiles bool
	Intent   bool
	// InterfaceProfiles are the profile values compiled into Sources, nil when the config names none.
	// See Overlay.InterfaceProfiles.
	InterfaceProfiles []profiles.Profile
	// Library is the project's own derived relations (agni issue 773), one module per file of a
	// library directory, and LibraryDocs their optional reference pages keyed by member path. A query
	// run under this config reads them through Overlay.Registry.
	Library     []LibraryModule
	LibraryDocs map[string]string
	// QuerySets are the project's query sets (agni issue 745), one per file of a query-set
	// directory, in file order. Only ListQuerySets reads them.
	QuerySets []NamedQuerySet
	// Digest identifies the BYTES this resolution read, so an overlay composed from it can say
	// whether two runs saw the same config. Empty means this resolver does not report one. That is
	// legal, and it leaves the overlay with no identity (see Overlay.Identity).
	Digest string
}

ResolvedConfig is what one AnalysisConfig contributes to a run, as engine values.

type ReviewEnv

type ReviewEnv struct {
	// ProducerVersion is the engine build identity (version.Version() at the entrypoint).
	ProducerVersion string
	// Profiles reports that --profile-path overlay profiles were composed into the catalog.
	Profiles bool
	// Intent reports that a --intent-path design-intent declaration was composed into the catalog.
	Intent bool
}

ReviewEnv holds the deployment-level provenance of a stored run. It names which overlay tiers were composed into this service's catalog, and which build produced the document.

It is injected rather than derived because a composed catalog cannot answer "were profiles attached", since an overlay profile is just another rule in it. See docsite/content/architecture/checks-contract.md#provenance-is-read-off-the-resolved-overlay.

type ReviewLoader

type ReviewLoader interface {
	Design(ctx context.Context, uri artifact.URI, opts ...ReadOption) (*ir.Design, error)
	Board(ctx context.Context, uri artifact.URI) (*geom.BoardGeometry, error)
	Manifest(ctx context.Context, uri artifact.URI) (review.Manifest, error)
	// DesignHash returns "sha256:<hex>" over the design's bytes. That hash is the revision identity.
	// A stored run records it so a document is never re-read against a design that has since
	// changed. It is on the loader because hashing reads bytes and this package does no I/O (C13/C22).
	//
	// An unreadable design is NOT an error, since the run already succeeded. Return ("", nil), which
	// DesignRef.content_hash allows.
	DesignHash(ctx context.Context, uri artifact.URI) (string, error)
}

ReviewLoader is the narrow file surface ReviewService needs, defined at the point of use as a subset of service.Loader plus Manifest. It reads the netlist design, an optional separate board export (WS3-089) and a stored checklist manifest, each resolved inside a mount by the impl and never as a host path (C22).

Manifest is NOT on the run path (WS9-050). CreateReview takes the checklist as a value, so only GetReviewManifest calls it.

type ReviewService

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

ReviewService runs a review checklist manifest over one or more designs, the transport-neutral analogue of `agni review` (WS9-047). The catalog, the profile presence index and the datasheet provider are design-INDEPENDENT and injected once, as CheckService receives its catalog and specs. Only the Model and its presence/scope closures are per design. It knows no transport (C13).

func NewReviewService

func NewReviewService(loader ReviewLoader, store ReviewStore, catalog *check.Catalog, byName map[string][]profiles.Profile, specs param.ParamProvider, env ReviewEnv, baseConvention string, projects *ProjectResolver) *ReviewService

NewReviewService returns a ReviewService over the given loader, review store, composed rule catalog, profile presence index, and optional datasheet provider (nil when no corpus is wired).

store may be nil, which disables the review resource methods; pass a MemReviewStore for a caller that wants runs without persisting them, as `agni review` does.

func (*ReviewService) CreateReview

func (s *ReviewService) CreateReview(ctx context.Context, req *webapi.CreateReviewRequest) (*webapi.Review, error)

CreateReview runs the checklist against the design and persists the result (WS9-053). The run is all-or-nothing, so an invalid manifest, an unreadable design, or a board_ref at a file with no board geometry is an error and nothing is stored.

The checklist arrives as a VALUE (WS9-050) and is validated here rather than trusted. A manifest that never passed through review.Load has had no parser enforce its rules, and an item carrying two mutually-exclusive bindings would otherwise score a check its author did not ask for.

The stored document is a self-contained CheckResults, the same one `agni review --results-out` writes. It holds the checklist SNAPSHOT rather than its name (docsite/content/architecture/web-services.md).

func (*ReviewService) DeleteReview

func (s *ReviewService) DeleteReview(ctx context.Context, req *webapi.DeleteReviewRequest) (*emptypb.Empty, error)

DeleteReview removes a stored run. Deleting an absent run is ErrNotFound, so a client acting on a stale listing is told.

func (*ReviewService) GetReview

func (s *ReviewService) GetReview(ctx context.Context, req *webapi.GetReviewRequest) (*webapi.Review, error)

GetReview returns a stored run. It reads only the store, so neither the design nor the checklist it was about needs to still exist.

func (*ReviewService) GetReviewManifest

GetReviewManifest resolves a stored checklist into the value CreateReview takes. No other method in this service reads a file. So a caller already holding a manifest never triggers it, and a host with no filesystem need not serve it.

It validates before returning, so a malformed checklist is reported here with the item that is wrong rather than at scoring time.

func (*ReviewService) ListChecklists added in v0.2.2

ListChecklists answers which checklists the design's project declares, inherited ones included (agni issue 859). It reads the project through the same resolver as CreateReview's overlay, and it opens no file. So it serves a host with no filesystem, as CreateReview does. See ProjectResolver.Checklists for what an absent project and an empty one each answer.

func (*ReviewService) ListReviews

ListReviews returns stored runs newest first, paginated, optionally narrowed to one project and to one design.

An empty parent lists EVERY run, parented or not.

func (*ReviewService) RenderReviewReport added in v0.2.2

RenderReviewReport writes a review the caller holds as the checklist page (agni issue 1030). It reads neither the store nor the design, since the review's document carries the manifest's items, their outcomes and findings, and the content hash of the bytes the run read. `agni review --format html` and the viewer's Save report both call it, so the two pages differ only in their timestamps and in how each names the design.

A request with no review, or with links naming a design that is not a mount URI, is an invalid argument.

func (*ReviewService) Snapshots added in v0.3.0

func (s *ReviewService) Snapshots() *SnapshotService

Snapshots is the SnapshotService over this service's loader, resolver, datasheet corpus and base convention, as CheckService.Snapshots is.

type ReviewStore

type ReviewStore interface {
	// Create stores a completed run under a parent project ("" for a design that belongs to none) and
	// returns its assigned name and stamped creation time. The caller supplies neither, so it cannot
	// mint a colliding id or backdate a run.
	Create(ctx context.Context, parent string, results *checkspb.CheckResults) (name string, createdAt string, err error)
	// Get returns a stored run. A name that names nothing is ErrNotFound.
	Get(ctx context.Context, name string) (*checkspb.CheckResults, error)
	// List returns runs newest first, at most pageSize of them, starting after pageToken (empty starts
	// at the newest).
	//
	// parent narrows to one project's runs, and EMPTY means every run the store holds, parented or
	// not, so a client needs one call across both name shapes. designFilter, when non-empty, keeps
	// only runs whose DesignRef.source matches it exactly. The returned token is empty on the last
	// page.
	List(ctx context.Context, parent string, pageSize int, pageToken, designFilter string) (results []*checkspb.CheckResults, names []string, nextPageToken string, err error)
	// Delete removes a stored run. Deleting an absent run is ErrNotFound rather than a success, since
	// a client removing something that is not there holds a stale view.
	Delete(ctx context.Context, name string) error
}

ReviewStore persists review runs (WS9-053). Like DraftStore and AnnotationStore in datasheet/dsservice, the interface is a port, and the os-backed adapter in cmd/agni owns all I/O (C1/C13). Those two key on an artifact.URI holding ONE current value. A design accumulates MANY runs, so this store mints identities and lists them instead.

Create owns identity AND time. The os adapter derives an id from the creation instant. A listing can then sort chronologically without opening a document, and the id and the time cannot be assigned separately. Owning the time also keeps ReviewService free of a clock, so its output is fixed for given inputs.

type RoomTokens added in v0.3.9

type RoomTokens interface {
	// Mint returns a token admitting its holder to room alone, and the time it stops admitting a join.
	Mint(room string) (token string, expires time.Time, err error)
	// Bridges returns the relay subjects that the host's room bridges join as. A page answers these
	// subjects alone.
	Bridges() []string
}

RoomTokens mints relay tokens, and a viewer page joins its design's room with one. The host that runs the relay implements RoomTokens, since only that host holds the relay's key (internal/viewerrooms).

type RunProvenance

type RunProvenance struct {
	Params      bool
	Profiles    bool
	Intent      bool
	Conventions string
}

RunProvenance records which config tiers a run actually had attached. A results document's RunConfig records the same value.

The answer has two sources. A deployment composes its startup flags into the service's own catalog and specs, and a project composes its own onto the request. A document built from only the first reports `params: false` for a run scored against a project's seeded corpus.

type Snap added in v0.3.0

type Snap struct {
	Name string
	// Design is the design as the definition names it. A service still needs it to find the files
	// beside it (an expectation sidecar, a project's checklists and query sets).
	Design                   artifact.URI
	Netlist, Board, Geometry artifact.URI
	AsNamed                  bool
	Overlay                  Overlay
	// Config is the overlay config the definition carried, before it was composed with the project's.
	Config   *webapi.OverlayConfig
	Revision string
	// Imagine a client sends a design's files. A snapshot of those files reads through Loader and
	// Projects. A snapshot of files the host serves has both nil, and it reads through the service's
	// own (agni issue 1061). They are kept apart from the host's because a cache keys a read on its
	// URI. An upload names its files with the client's own mount, and the host may serve that mount
	// too.
	Loader   *CachingLoader
	Projects *ProjectResolver
}

Snap is a snapshot as a service reads it. It holds what its definition resolved to.

func (Snap) BoardOnly added in v0.6.3

func (s Snap) BoardOnly() bool

BoardOnly reports whether the design is drawn by its board alone. It is when no file draws its schematic and its board tier holds a board, such as an ODB++ job, an Altium or Allegro board, or an IPC-2581 file opened on its own. Such a design lists the Board sheet and no auto-layout, and every answer that says where a subject is drawn names the board (agni issue 1466). A grid of a board's netlist shows nothing the board does not. A netlist with no board keeps its auto-layout, since that is the only drawing it has.

func (Snap) BoardRead added in v0.3.0

func (s Snap) BoardRead() artifact.URI

BoardRead returns the artifact to read the board from. That is the board tier, or the netlist's own artifact for a format that holds its own copper.

func (Snap) ProjectsOr added in v0.3.0

func (s Snap) ProjectsOr(r *ProjectResolver) *ProjectResolver

ProjectsOr returns the resolver for s's project. That is its upload's, or else the service's r.

type SnapshotError added in v0.3.0

type SnapshotError struct {
	Name    string
	Stale   bool
	Changed []string
}

SnapshotError is why a question's snapshot cannot answer it: the host holds no snapshot by that name, or its files changed. It wraps ErrNotFound or ErrStale, and a transport carries it as a webapi.SnapshotUnavailable detail so a client can tell it from a design file that is missing.

func (*SnapshotError) Detail added in v0.3.0

Detail is the error as the wire carries it.

func (*SnapshotError) Error added in v0.3.0

func (e *SnapshotError) Error() string

func (*SnapshotError) Unwrap added in v0.3.0

func (e *SnapshotError) Unwrap() error

type SnapshotLoader added in v0.3.0

type SnapshotLoader interface {
	Design(ctx context.Context, uri artifact.URI, opts ...ReadOption) (*ir.Design, error)
}

SnapshotLoader is the loader that ingesting reads through. Ingest always reads the netlist. With read_board it also reads the model and its board, which needs a ModelLoader. Every service's loader satisfies it, so a test can ingest through whichever loader the service under test holds.

type SnapshotService added in v0.3.0

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

SnapshotService creates, reads, updates and deletes snapshots (webapi.SnapshotService). It holds what a CheckService does, because ingesting with read_board builds the model a check would.

func NewSnapshotService added in v0.3.0

func NewSnapshotService(loader SnapshotLoader, projects *ProjectResolver, specs param.ParamProvider, baseConvention string) *SnapshotService

NewSnapshotService ingests designs into projects' snapshots. baseConvention is the catalog source name of the server's --conventions default, as on NewCheckService.

func (*SnapshotService) DeleteSnapshot added in v0.3.0

func (s *SnapshotService) DeleteSnapshot(ctx context.Context, req *webapi.DeleteSnapshotRequest) (*emptypb.Empty, error)

DeleteSnapshot forgets a snapshot. The DesignCache keeps what it read for another snapshot to use.

func (*SnapshotService) GetSnapshot added in v0.3.0

GetSnapshot returns a snapshot's definition and what it resolved to.

func (*SnapshotService) Ingest added in v0.3.0

Ingest creates a snapshot from its definition and reads its netlist, and its board when read_board asks. An ingest may name an id already in use with the same definition. That makes no second snapshot. Ingest reads what read_board asks and returns the existing one. So a client may send its ingest again without first asking, to a host that may or may not hold it. The same id with a different definition is ErrAlreadyExists.

func (*SnapshotService) ListSnapshots added in v0.3.0

ListSnapshots lists the snapshots this host holds, by name. The one filter is `uri="..."`.

func (*SnapshotService) UpdateSnapshot added in v0.3.0

UpdateSnapshot replaces a snapshot's definition, whole or by update_mask, and reads it again under the same name. An update that cannot be read leaves the snapshot as it was.

func (*SnapshotService) UploadBlobs added in v0.3.0

UploadBlobs stores the contents of a design's files a client sends, keyed by their SHA-256, and answers each one's hash.

type SourceTable added in v0.2.2

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

SourceTable keeps a response's citations once and points each row at them (agni issue 916).

func NewSourceTable added in v0.2.2

func NewSourceTable(resp *webapi.RunQueryResponse) *SourceTable

NewSourceTable starts the sources table of resp.

func (*SourceTable) Cite added in v0.2.2

func (t *SourceTable) Cite(row *webapi.QueryRow, cites []string)

Cite records row's citations, adding each new one to the response's sources.

func (*SourceTable) Indexes added in v0.3.8

func (t *SourceTable) Indexes(cites []string) []int32

Indexes returns cites as indices into the response's sources, adding each new one. A row and a witness both cite, and both use it (agni issue 794). It returns nil for no citations.

type TableService added in v0.2.2

type TableService struct{}

TableService answers Tabulate. It holds nothing, so the zero value serves.

func (TableService) Encode added in v0.2.2

Encode writes each table as a file in the requested encoding (agni issue 956). An unspecified encoding is ErrInvalidArgument, and so is a table with no name, since its file would have none.

func (TableService) Tabulate added in v0.2.2

Tabulate projects the answer the request carries and orders each table as asked. An empty answer, a failed query in a set, or an order_by naming a column no table has is ErrInvalidArgument.

type UploadHost added in v0.3.0

type UploadHost func(mount string, files map[string][]byte) (CacheableLoader, *ProjectResolver)

A host reads a client's files through an UploadHost. It returns a loader over the files, keyed by their path within the one mount named mount, and a resolver over the projects those files declare. Only a host can make a file system (C13), so the host builds it. A nil UploadHost means the host takes no files from its clients.

type ViewerRoomService added in v0.3.9

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

ViewerRoomService answers an open viewer page before the page offers its tools to agents through its design's relay room (agni issue 1154). It tells the page which room to join, and gives it a token to join with.

func NewViewerRoomService added in v0.3.9

func NewViewerRoomService(projects *ProjectResolver, tokens RoomTokens, relayURL string) *ViewerRoomService

NewViewerRoomService answers JoinViewerRoom for a relay served at relayURL ("/relay/"), with tokens minted by tokens. Every other service holds the same resolver as projects. So a design names the same room here as in the bridge's WithRoomOf, which calls Room.

func (*ViewerRoomService) JoinViewerRoom added in v0.3.9

JoinViewerRoom names the design's room, mints a token for it, and names the bridges the page should answer. It stores nothing.

func (*ViewerRoomService) Room added in v0.3.9

func (s *ViewerRoomService) Room(ctx context.Context, design string) (string, error)

Room returns the room for a design named as mount/path or a mount:// URI. The room is "design:" followed by the design's declared entry. linkMountPath resolves the entry, as it does for a report's links (C32), so the folder, the entry and a declared companion name one room. An empty design is an invalid argument.

type Workspace

type Workspace interface {
	Mounts() []MountInfo
	ListDir(ctx context.Context, uri artifact.URI) ([]DirEntry, error)
}

Workspace is the file-browsing port, serving the configured mounts and one level of listing within a mount. Path containment is the adapter's responsibility. The server adapter is os-backed (mounts.Workspace) and the in-browser engine's is fshost's.

type WorkspaceService

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

WorkspaceService serves the mounted folders and their contents over an injected Workspace port (CONSTRAINTS C13). It maps mounts and directory listings to the proto responses and does no file I/O itself.

func NewWorkspaceService

func NewWorkspaceService(ws Workspace) *WorkspaceService

NewWorkspaceService returns a WorkspaceService backed by ws.

func (*WorkspaceService) DeclareCompanion added in v0.5.0

DeclareCompanion answers the design.yaml that declares companion_uri as a companion of the design whose entry is design_uri (agni issue 1367). It writes nothing; the page saves the text where it can and shows it where it cannot.

The companion must be in the design's mount and inside its folder, since a descriptor's companions stay inside it, and either is an invalid argument otherwise. An existing descriptor is edited as a YAML node tree, so its comments and other keys are kept, and a new one names the entry and extends the nearest project.yaml above the folder, since a design under a project that names none is a load error. internal/projects reads descriptors and imports this package, so the tests hold the answer to its parser (TestDeclaredDescriptorsLoad).

func (*WorkspaceService) ListDesignFiles added in v0.2.2

ListDesignFiles lists every file a design's analysis reads (agni issue 853). The list covers the design's folder, recursively, which holds its entry, companions, revisions and descriptor. It covers every file or directory the descriptor names. For each project up the extends chain, it covers that project's descriptor and what it names (profiles, params, symbols, lib, queries). A host that analyses the design somewhere else fetches this list, and the in-browser engine is the first such host.

Every listed path is in the design's own mount. A config URI naming another mount is refused, since a client mounting the files under one name would resolve it to nothing and analyse the design without that tier.

func (*WorkspaceService) ListDir

ListDir lists one level of a mount: its subdirectories and its files, directories first and each group sorted by name, every file labeled with its format and the kind of client that opens it. With Opens set, a subdirectory holding none of those kinds anywhere beneath it is left out, so a tree stops offering folders it can only ever show empty. A containment violation keeps ErrInvalidPath, and anything else from the adapter (unknown mount, missing directory) is wrapped as ErrNotFound.

func (*WorkspaceService) ListMounts

ListMounts returns the configured mounts in configuration order. It never errors. With Opens set, a mount holding none of those kinds anywhere beneath it is left out and counted in PrunedMounts. ListDir applies the same rule to subdirectories. A mount serving only datasheets is thus hidden from the DESIGN tree and shown in the datasheets tree.

The walk budget is per call and shared by every mount, so many roots cannot turn one page load into many full walks. A later mount can inherit an exhausted budget and be kept without being examined, which errs toward showing too much.

func (*WorkspaceService) ProposeDesigns added in v0.2.2

ProposeDesigns groups the files under a folder into the designs they make (agni issue 854). It lists the folder through the Workspace port and reads KiCad sheets through the FileReader, so it needs WithDesignFiles. Paths in the answer are mount-relative.

func (*WorkspaceService) WithDesignFiles added in v0.2.2

func (s *WorkspaceService) WithDesignFiles(projects *ProjectResolver, files FileReader) *WorkspaceService

WithDesignFiles enables ListDesignFiles, which needs the project resolver to find a design's project config and a reader to size and hash its files. Without it the rpc reports that this host does not offer it.

Jump to

Keyboard shortcuts

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