service

package
v0.2.5 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2026 License: Apache-2.0 Imports: 46 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 and in tests and stays runnable 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.

Variables

View Source
var (
	ErrNotFound        = errors.New("not found")
	ErrInvalidArgument = errors.New("invalid argument")
	ErrInternal        = errors.New("internal error")
	// ErrResourceExhausted is 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")
)

Error sentinels the implementations classify every failure with, so a transport adapter (internal/server) 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")
)

Native-render gate failures an adapter reports so a transport maps them without importing the cmd tool cache: NoTool -> unimplemented; NotEnabled / NotFound -> failed precondition.

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 the numbers that decided it are what a reviewer triages it by.

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, since the request was fine and the deployment is what is missing.

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, which `check --format csv` has published since before this projection existed, so a script binding to it keeps working. Datasheet citations are left out because each is a document, page and section, which does not fit one cell; json has them.

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 is the names of the rules agni ships, its default catalog's, which a sanitized report may name (agni issue 1057). 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. url is filled only by a caller that can link to a viewer (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.

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. Both g and d nil is a no-op (findings keep empty sheets), same as AnnotateSheets; a net-only channel (design set, geometry nil) still annotates net subjects.

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 (and net badges for formats whose wires carry names), and the design supplies the authoritative net membership (AttrSheets, WS9-028) that covers the wireless sub-sheet nets geometry misses. Both nil is a no-op and findings keep empty sheets, which the viewer handles. A net-only channel (design set, 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.

PER NET rather than one sheet for the answer, because a route crossing three sheets is when a reader wants to choose which to open, and 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, and that is the picture a reader wants once they learn the pins do not join. Empty sheet ids mean the net is drawn nowhere, rather than that nobody looked.

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) map[string]query.Value

BindingsFromProto converts a request's bindings to the values the engine binds (agni issue 793). A value that sets neither field binds the empty text, as `""` written in the query would.

func BindingsProto added in v0.2.2

func BindingsProto(m map[string]query.Value) map[string]*webapi.QueryValue

BindingsProto converts bound values to their wire form: a value carrying a number is a number, any other is text.

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. That is why geometry is not a BuildModel tier, where a bad board or params tier 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 land on sheets missing 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, since an explicit board request that read nothing would report the board items clean without checking them. A design's OWN path carrying no board (a netlist) 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, which is safe because rules only read it and its memo (check.Memo) is built for concurrent use. A request whose overlay cannot identify itself, or whose datasheet corpus is fetched over the network (where nothing here can tell that it changed), builds its own.

It returns the fact base too, built on first use, so a query does not pay 100ms to project 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, and 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 is where an answer cell's entity is drawn and why it cannot be located, read 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 worst first (custom severities lead, then error, warning, info), empty severities omitted, findings grouped by rule in run order, each group stamped with the rule's catalog Summary from the rules that ran (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 rather than re-deriving the grouping on each side.

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. Exported for a service in another module, the datasheet service (agni issue 744), so its errors map to the same sentinels.

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 to the one question the ingestion class pass asks of it: the device_class a seeded spec states for an MPN. readers/formats takes this function and never the provider, so the datasheet layer stays 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 is the one place a diff.Report becomes its webapi wire form, shared by the RPC and the CLI's `diff --format json` (C31). It also derives the highlight maps, ref_des -> added|removed|changed and net name -> new|deleted|renamed|hard|soft, with a renamed net keyed under BOTH names so each side of a visual diff joins by the name its own geometry carries.

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 (by ref des, by ref des then field, nets by kind then name), with the unchanged nets last when the diff carried 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`, a remote check. 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 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, the CLI's, the server's and the in-memory one 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 the recorder the read's files go into, 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 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, so a caller decides when to pay for the query compilation validation performs. 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, so it stays valid when runs are created or deleted between pages, which an offset would not. 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 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.

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`'s folder lends its descriptor and its profiles, params, symbols and lib directories to the designs under it, so those are support files, not unread ones.
  • (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 (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, where it is not on a server (agni 528), because the visitor sees it and edits it first.
  • 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.
  • 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 QuerySetFromProto added in v0.2.2

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

QuerySetFromProto converts the wire form of a query set to the engine's.

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 QueryTable added in v0.2.2

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

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

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: nil is the pass off, an empty message 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. Why inheritance is declared rather than ambient is on docsite/content/architecture/projects-and-designs.md#sharing-config-between-projects.

A nil store is fine for a project that extends nothing. A project that declared an extends the store cannot resolve 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 is a review's items, one row each in the checklist's own order, since a reviewer reads a checklist in the order it was written, and its one-row summary.

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 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, which a browser's network panel draws: the total, then each stage once, summed when it ran more than once, in the order it first started.

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 is 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 is where in its query's text err points, 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 with its evidence attached, and its outcome is a Go string type the wire spells as an enum. Per C26 the pair has a round-trip guard (TestTraceProtoRoundTrip) and a field census, so a field added to 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 carries a C26 round-trip guard (TestVerdictProtoRoundTrip); a field the converter never learned is otherwise invisible to any assertion on the proto, as naming.Lexicon and Profile.HostClass each found.

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 the report model the HTML page and the CLI's verdict text both render, 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 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, which `--format csv` on every command and the Encode rpc both write, 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 is the shape of goapplib's wasmhost.Cache, which the browser engine hands it, 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 BoardTier added in v0.2.2

type BoardTier bool

A BoardTier says whether a model reads the design's board. On a large board the board's geometry, and the per-net copper the model builds from it, are most of what a model holds (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. Only for a request that reads no board fact: 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 is what a host hands its services: the read ports a CachingLoader wraps.

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, because callers stamp classes into a design they were handed (check.NewModel's datasheet pass), and 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) 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, read once per identity while its files are unchanged.

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. Each finding's sheets locate its subject in the design's geometry (WS9-024), and 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. A separate RPC (not 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 a run under the same uri and overlay would use, each rule in its wire form with its availability from check.Available. The uri is optional, and when given it picks the project whose catalog is listed. The design itself is never loaded, 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 the CheckResults document `agni check --results-out` writes, and the HTML form is the page `agni check --verdicts --format html` writes, and both CLI paths call this, so a report saved from the viewer and one the CLI wrote differ only in their timestamps.

The request's uri, overlay, rules, board_uri and as_named have to be the ones the run used. They decide the catalog the report describes and the netlist tier whose content hash it records, and nothing here can check them against the run.

func (*CheckService) WithEnv added in v0.2.2

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

WithEnv sets the deployment provenance a written document records: the producer version, and whether profiles and intent were composed into the catalog. It is the same ReviewEnv a review run records, 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, which the coverage panel walks 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 the engine inputs a run needs. It is the port that keeps file I/O out of a service (C13), since 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. This backs the resolver rpc a client with a ref and no filesystem calls 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 two layers. CachingLoader keeps the parsed design, its drawings and its board, which every surface reads through. BuildModelCached keeps the check model and its fact base on top, which a query or a check needs and building costs a further 100ms on a large board.

An entry is keyed by what was asked (the URI, the layout, the read options' identity) and checked on every hit against what the read touched: every file it opened, walked or looked for, as a formats.Touched. A hit whose files stamp differently is read again. So the key never has to name a file, which is what lets a hierarchical schematic's sub-sheets, a declared companion and a symbol library all invalidate it without anyone listing them.

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

It is the same code in `agni serve` and the browser engine. In the browser the engine is rebuilt on every mount change, which drops its in-memory entries with it, and the parsed design, drawing and 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 a board's parse leaves becomes the floor the rules stage grows from, and 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 carries a content fingerprint of every name its read touched (formats.Touched.Fingerprint) and is used only when check says they all read the same now, so a file edited, added or removed since reads again, as it does in memory. version names what wrote the entry: an engine that reads a file differently must pass a different one, 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 the diff tier needs, 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 is the summary the viewer opens with (counts, sheets, layout, content hash), unchanged. With one it carries exactly the paths named, which may include the design's IR (agni issue 836): `design` for all of it, `design.nets` or `design.components.mpn` for parts, `*` 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 that returns an empty report rather than an error.

func (*DesignService) GetSheet

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

func (*DesignService) HighlightSheet

HighlightSheet resolves highlight specs against one rendered sheet and returns the drawable overlay layer, decoupled from the base render: PACKED yields primitive-index groups joining 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 it stacks on. NATIVE (a golden shell-out with no overlay concept) classifies as ErrInvalidArgument.

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".

type DesignSources

type DesignSources struct {
	// NetlistURI is the artifact component and connectivity ANALYSIS reads, the netlist the design
	// team produces (C21).
	NetlistURI string
	// BoardURI is where the board tier's copper comes from. Often the same artifact, and different
	// when a design declares a separate board companion.
	BoardURI string
	// GeometryURI is where schematic sheets are rendered and findings located from. A netlist entry
	// carries none of its own, so a design declaring a schematic companion locates on that
	// companion's sheets (C21, a companion is a canvas and not a source).
	GeometryURI string
}

DesignSources is which artifact each tier of a read comes from, once a design's declaration has had its say. They are URIs the injected Loader resolves, 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.

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. It is the port ListDesignFiles sizes and hashes files through, separate from Workspace so the hosts that only browse (the datasheet service) need not read.

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. It is the host's, 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 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: the module path its members register under, the language and text it is written in, and Source, where it was read from, which an error names 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. This is the surface that 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 (absence is normal), so the caller 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, which 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, the revision identity a
	// verdict link is checked against (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. All three spellings of a design (the
	// folder, the entry, a declared companion) analyse the same bytes, so the identity is the NETLIST
	// tier `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, which GetDesign reports as an empty
	// content_hash. That is a THIRD state, distinct from a match and a mismatch, and the response's
	// doc comment binds the consumer to keep it so.
	DesignHash(ctx context.Context, uri artifact.URI) (string, error)
}

Loader materializes a design's read model from an artifact.URI. The server adapter (osLoader in cmd/agni) is os-backed. 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, and 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, which 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 `agni review`, a thin client of CreateReview that must leave no files behind (--results-out is how it writes a document), and most tests.

Ids are the insertion ordinal rather than a timestamp, which keeps tests deterministic and 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 these annotate helpers read, the netlist's nets for the AttrSheets membership (WS9-028). Declared at the point of use rather than taking the whole check.Model, which 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
	// travels with the rule sources so a run cannot compose one team's rules against another'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. See ResolvedConfig for why the flags travel rather than being
	// derived from Sources.
	Profiles bool
	Intent   bool
	// DesignIntent is the declared intent itself, nil when none was declared. Its rules are already in
	// Sources, and the value travels too because part of it is read by the MODEL rather than by a rule:
	// which connectors are internal (agni issue 831).
	DesignIntent *configpb.DesignIntent
	// InterfaceProfiles are the profile VALUES behind the profile source in Sources: a project's own
	// profiles/ and any a request's config names. Running a profile needs only its compiled rules, and
	// these are for the surfaces that read a profile itself, the coverage panel and a review's
	// interface-presence gate, so they 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
	// contains filtered or unexported fields
}

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

A convention carries rules AND a lexicon, and they land in different places. Rules extend the catalog, while 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 (a pattern that will not compile, an unknown component class) is an ERROR, never a skip, because an operator who silently got the built-ins would read the clean report as a clean design.

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, and for a review base holds the --profile-path and --intent-path sources, so 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 carrying baseConvention's name and nothing else. The built-ins and the profile and intent sources are not the request's to remove. A caller that names no base convention (the CLI) keeps the additive behaviour.

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 is the set of interface profiles this run's rules came from, keyed by name: base (the built-ins and a deployment's --profile-path, already composed) with this overlay's own profiles REPLACING 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 is what the overlay contributes to each design READ: the naming lexicon, the symbol paths, and the datasheet device-class lookup, each only when present.

func (Overlay) Registry added in v0.2.2

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

Registry is the query vocabulary this overlay's queries run over: 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. A member whose path the shipped vocabulary already defines is refused by name before composition, since 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: the project's own layered 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 the corpus it came from, because a limit transcribed outside the project now decides some of its verdicts, and a reader has to be able to see which. DECISIONS.md records the reversal from the project replacing the shared corpus outright. nil when neither exists.

type ProjectResolver

type ProjectResolver struct {
	Store  ProjectStore
	Config ConfigResolver
}

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

Every surface that runs rules needs both or neither, so they are one constructor parameter. Wired per surface, --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's project declares, inherited ones included in the order ResolveExtends composes them, and the project's name. A design in no project, or a deployment that resolves none, returns (nil, "", nil), and a project declaring none returns (nil, name, nil), so a caller can tell an operator which fix applies. A descriptor that exists and does not parse is an error, as for Overlay.

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 it another way, through the catalog and the datasheet provider the services hold and the process lexicon, so an overlay never carries them (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 ran the design against the built-in vocabulary, which on one folder 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's project keeps, inherited ones first, and the project's name, answering an absent project and an empty one as Checklists does. 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 project having no such set.

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), because a design's URI IS its directory (`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 is Sources with the refs parsed back into artifact URIs, which is what 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 PartSpecStore, AnnotationStore and ReviewStore, the interface lives here 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 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 the naive interpreter.

func NewQueryService

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

NewQueryService returns a QueryService backed by the given loader and (optional) datasheet provider, using the default naive datalog evaluator. Pass a nil provider when no datasheet corpus is wired; 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) RunQueries added in v0.2.2

RunQueries answers every query of a set over one read of the design (agni issue 729). Each result is what RunQuery would return for that query alone; a query that does not parse or names something the design's relations lack is reported against its 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 map[string]query.Value) (*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.

type ReadOption

type ReadOption func(*ReadOptions)

ReadOption configures one read.

func WithDesignIntent added in v0.2.2

func WithDesignIntent(di *configpb.DesignIntent) ReadOption

WithDesignIntent carries a design's declared intent to the model 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 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, which must be every one 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, 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 rides 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
	// 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. Naming the entry of a design that declares no
	// companion applies the declaration and changes nothing, which a caller narrating what it read
	// distinguishes from a ref that was never resolved.
	FromDeclaration bool
}

Resolution is what a ref resolved to, meaning the artifact each tier reads and how that was arrived at.

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

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 (the CLI over a store rooted at its argument's mount, a server over the store it was built with) and this says what to open. 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, which is
	// legal and costs the overlay its 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 is the deployment-level provenance a stored run records, naming which overlay tiers were composed into the catalog this service holds and what 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, the revision identity a stored run
	// records 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 the same self-contained CheckResults `agni review --results-out` writes, carrying 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. It is the one place in this service that 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 resolver CreateReview's overlay uses and 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.

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 PartSpecStore and AnnotationStore, the interface lives here and the os-backed adapter in cmd/agni owns all I/O (C1/C13). Unlike them it is not keyed by an artifact.URI holding ONE current value, because a design accumulates MANY runs, so this store mints identities and lists them.

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

type RunProvenance

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

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

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 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.

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 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) ListDesignFiles added in v0.2.2

ListDesignFiles lists every file a design's analysis reads (agni issue 853): the design's folder, recursively, which holds its entry, companions, revisions and descriptor; the project's descriptor; and every directory the project's config names (profiles, params, symbols, lib). It is what a host that analyses the design somewhere else, the in-browser engine first, fetches.

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, the rule ListDir applies 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