Write an evaluation schematic
An evaluation schematic reads the workspace and returns Findings: a list of places where the
code does not follow a rule. It never changes the workspace. Use one to check that the codebase
keeps a pattern, for example that every route has a guard or that no TODO is left. You run it
with builder validate, which turns its findings into an exit code for CI,
and other schematics can invoke it and act on
what it found.
A generator writes code; an evaluation reports on it. Both are schematics, and the role in the
Manifest tells them apart.
Requirements
Section titled “Requirements”@pbuilder/sdk0.20.0 or later to write and run an evaluation.@pbuilder/sdk0.22.0 or later and thebuilderCLI v0.20.0 to invoke one from another schematic.@pbuilder/sdk0.24.0 and thebuilderCLI v0.24.0 or later to read files up to 8 MiB and to catch a read over that cap; see Files over the read cap.@pbuilder/sdk0.26.0 and thebuilderCLI v0.26.0 or later for a read that nothing catches to fail with its own error code,execute_read_ceiling_exceeded.@pbuilder/sdk0.25.0 and thebuilderCLI v0.24.0 or later to read the path of a handle; see List the files with glob.
Every output below comes from builder v0.20.1 and @pbuilder/sdk 0.23.0, except the section on
files over the read cap, which comes from builder v0.24.0 and @pbuilder/sdk 0.24.0, except
its uncaught-read error, which comes from builder v0.26.0 and @pbuilder/sdk 0.26.0. The
section on glob shows no command output.
Create the schematic
Section titled “Create the schematic”Scaffold it as any schematic:
builder new schematic no-todo --title "Check for TODOs" --job "find a leftover TODO"From CLI v0.21.0, builder new schematic creates a generator and refuses to run without
--title and at least one --job. Once the entry declares another role, the CLI ignores its
title and jobs. builder new schematic has no --role flag yet, so add the role to its entry in
project-builder.json yourself:
"collections": { "default": { "no-todo": { "path": "./schematics/no-todo", "title": "Check for TODOs", "jobs": ["find a leftover TODO"], "role": "evaluation" } }}Then run codegen again so the generated types follow the role:
npx pbuilder-codegenFor an evaluation, schema.generated.ts gains the include and exclude inputs, which the role
adds to every evaluation, and types the Result as Findings:
export type Input = { /** Globs or literal paths to check */ include?: string[]; /** Globs or literal paths to skip */ exclude?: string[];};
export type Findings = { items: Array<{ rule: string; message: string; severity: "error" | "warning"; path?: string; range?: { start: { line: number; column: number }; end?: { line: number; column: number } }; fix?: { schematic: string; inputs?: { [key: string]: unknown } } }> };
export type Result = Findings;Codegen refuses a schema.json that declares an input named include or exclude
(an evaluation schematic declares the input "include", which the role imposes) or that declares
a Result of its own. Every input you do declare needs a label, or codegen fails with
property "x" is missing a label.
Return Findings
Section titled “Return Findings”The factory reads files and returns { items }. This one fails the check when a TODO is left
in either of two files:
import { find } from "@pbuilder/sdk/commons";import type { Input, Result } from "./schema.generated.ts";
const FILES = ["src/app.ts", "src/legacy.ts"];
export default async (input: Input): Promise<Result> => { const items: Result["items"] = []; for (const path of FILES) { const text = await find(path).read(); if (text?.includes("TODO")) { items.push({ rule: "no-todo", message: "a TODO is left", severity: "error", path, fix: { schematic: "default:clean-todo" }, }); } } return { items };};This factory names its files. To check every file that matches a pattern instead, list them with
glob; see List the files with glob.
The fields of a finding
Section titled “The fields of a finding”| Field | Required | Value |
|---|---|---|
rule |
yes | The name of the rule the finding breaks. |
message |
yes | What is wrong, for a person to read. |
severity |
yes | error or warning. Only an error fails builder validate. |
path |
no | The workspace-relative file. Omit the key when there is none; path: undefined fails the run. |
range |
no | A 1-based position in the file: { start: { line, column }, end?: { line, column } }. |
fix |
no | The schematic that would fix the finding, { schematic: "collection:name", inputs? }. builder validate prints it as given. From CLI v0.20.1, a schematic the Manifest does not have also adds the warning warn_fix_schematic_unresolved. |
source |
set by the SDK | The evaluation’s qualified name, collection:schematic. A finding that sets it fails the run. |
List the files with glob
Section titled “List the files with glob”From @pbuilder/sdk 0.25.0, every handle has a read-only path: the workspace-relative path its
ops act on. A handle from glob carries the path that glob listed, so an evaluation can list
its files with glob and put each handle’s path on the finding it reports. Use it when the rule
covers every file that matches a pattern rather than a fixed list:
import { glob } from "@pbuilder/sdk/commons";import type { Input, Result } from "./schema.generated.ts";
export default async (input: Input): Promise<Result> => { const items: Result["items"] = []; for (const file of await glob("src/**/*.ts")) { const text = await file.read(); if (text?.includes("TODO")) { items.push({ rule: "no-todo", message: "a TODO is left", severity: "error", path: file.path }); } } return { items };};glob returns its handles ordered by path, and an empty array when no file matches. Each
dialect’s glob, such as glob from @pbuilder/sdk/typescript, returns handles that carry
path the same way.
In an evaluation, the SDK narrows every glob result to the scope of the run: what --include
names, less what --exclude names. Without either flag nothing is narrowed. A file outside the
scope is never listed, so the factory never reads it. With src/a.ts, src/a.test.ts and
lib/b.ts in the workspace and --exclude='**/*.test.ts', glob("src/**") returns only the
handle of src/a.ts, and a finding on it carries "path":"src/a.ts".
find is not narrowed. A path passed to find is read even when it falls outside the scope,
and a finding on it is then dropped from the report.
What path holds:
- On a handle from
find, the path as you passed it. It is not normalized, sofind("./src/a.ts").pathis"./src/a.ts". - On a handle from
glob, the workspace-relative path thatgloblisted, such assrc/a.ts. - Inside a dialect’s
.inspect(), the AST keeps the file name the dialect parses under. Read the path from the handle, not from the AST.
A handle’s path lists what path holds on the
handles the write verbs return.
Query a C# file
Section titled “Query a C# file”The C# and ASP.NET dialects parse with tree-sitter. In @pbuilder/sdk 0.24.0 and later,
withTree(text, fn) from @pbuilder/sdk/csharp (also exported by @pbuilder/sdk/aspnet) parses
text, runs fn over the root node and frees the tree when fn returns or throws. Inside
.inspect(), it answers a question about a file without a parser of your own. Return plain data
from fn, such as strings or offsets: a node is unusable once the tree is freed.
This evaluation fails when a file still imports a legacy namespace:
import * as csharp from "@pbuilder/sdk/csharp";import type { Input, Result } from "./schema.generated.ts";
const FILES = ["src/Orders.cs", "src/Invoices.cs"];
export default async (input: Input): Promise<Result> => { const items: Result["items"] = []; for (const path of FILES) { const usings = await csharp.find(path).inspect((doc) => csharp.withTree(doc.text, (root) => root.descendantsOfType("using_directive").map((node) => node!.text), ), ); if (usings.some((text) => text.includes("Shop.Legacy"))) { items.push({ rule: "no-legacy-using", message: "imports Shop.Legacy", severity: "error", path }); } } return { items };};isValidCsharp(text), from the same modules, is true when text parses with no syntax error.
For what withTree does not cover, build a parser from astLibrary and language as the
C# dialect reference shows.
Files over the read cap
Section titled “Files over the read cap”The engine serves at most 8 MiB (8388608 bytes) of one file per read (rule E-41). The cap is per
read, never per Run, and a file of exactly 8 MiB is served. With @pbuilder/sdk 0.24.0 and CLI
v0.24.0 or later, a read of a larger file rejects with ReadTooLargeError from
@pbuilder/sdk/commons. It carries path, workspace-relative, size and limit, both in bytes.
It applies to find(path).read() and to a dialect handle’s read, inspect and modify.
The error concerns that read only. It does not fail the Session, so a factory that catches it goes on, and an evaluation still returns its Findings. This one reports each file it could not check as a warning, so the check never passes silently over a file it never read:
import { find, ReadTooLargeError } from "@pbuilder/sdk/commons";import type { Input, Result } from "./schema.generated.ts";
const FILES = ["src/app.ts", "src/generated/catalog.ts"];
export default async (input: Input): Promise<Result> => { const items: Result["items"] = []; for (const path of FILES) { let text: string | undefined; try { text = await find(path).read(); } catch (error) { if (!(error instanceof ReadTooLargeError)) throw error; items.push({ rule: "no-todo", message: `not checked: ${error.size} bytes, over the read limit of ${error.limit} bytes`, severity: "warning", path: error.path, }); continue; } if (text?.includes("TODO")) { items.push({ rule: "no-todo", message: "a TODO is left", severity: "error", path }); } } return { items };};A warning never fails builder validate. In a run on CLI v0.24.0 and SDK 0.24.0, an evaluation
that caught the error for a 9000051-byte file completed, and the skip it recorded read
{"src/domain/bench/big.ts":{"size":9000051,"limit":8388608}}.
Which to choose:
- Skip the file silently when the rule does not cover it, such as a bundle or a generated file.
- Report a finding when the rule does cover the file. A
warningkeeps the check passing and shows the gap; anerrorfails the check until the file is excluded or split. - Let it fail only when a check that cannot read every file must not report a result.
On a dialect handle, an op that meets the cap throws on the next await of that handle, or at
the end of the Run when the handle is never awaited. runFactoryForTest enforces the same cap
on its reads. With a CLI older than v0.24.0, the cap is 1 MiB and a read over it fails the whole
Run with a refusal a factory cannot catch.
When nothing catches the read
Section titled “When nothing catches the read”Left uncaught, the error fails the factory and the Run writes nothing. With CLI v0.26.0 and
@pbuilder/sdk 0.26.0 or later, builder execute and builder validate both answer with the
error execute_read_ceiling_exceeded (reason schematic_developer_fault) and exit with code 5,
so CI and an agent can tell a file that is too large from any other bug in the factory. Under
builder validate the outcome is error. With --output=json, when a factory reads a
9000051-byte big.txt without catching the error, the error field holds:
{"code":"execute_read_ceiling_exceeded","op":"native.execute","message":"the schematic read the file \"big.txt\", 9000051 bytes, over the read ceiling of 8388608 bytes, and did not catch the refusal","suggestions":["catch the read refusal in the schematic and skip the file, or read a smaller file"],"reason":"schematic_developer_fault","layer":"engine","detail":"","runner_note":"factory probe:big failed: the file \"big.txt\" is 9000051 bytes, over the read limit of 8388608 bytes","log_path":"~/.pbuilder/logs/runner-<id>.ndjson","log_written":true}The message names the path, the size and the limit, and runner_note keeps the runner’s own
line. Both sides are needed: SDK 0.26.0 reports the failure to the engine in a form it can type,
and the engine in CLI v0.26.0 reads it. With an older CLI or an older SDK, the same failure is
the generic engine_native_developer_fault, and only its runner_note names the file, its size
and the limit:
factory at bench/read-cost failed: the file "src/domain/bench/big.ts" is 9000051 bytes, over the read limit of 8388608 bytesThe code applies only when the factory that made the read is the one whose failure ends the Run.
A child that fails this way under invoke reaches its parent as a
ChildFailedError, and a parent that does not catch it fails with
engine_native_developer_fault, never with execute_read_ceiling_exceeded.
Run it with builder validate
Section titled “Run it with builder validate”builder validate default:no-todoWith a TODO in src/legacy.ts, the check fails and exits with code 6:
dry run: nothing is written to the workspace✓ done — no changesa finding's fix names the schematic "default:clean-todo", which does not resolve in the Manifesterror no-todo src/legacy.ts — a TODO is left (fix: default:clean-todo) [default:no-todo]✗ [CLI] the evaluation reported 1 finding(s) with the severity error validate_findings a finding with a fix names the schematic that would fix itdefault:clean-todo does not exist in this workspace, so the check warns with
warn_fix_schematic_unresolved and still reports the finding unchanged. With --output=json,
standard output holds the findings and that warning:
{"result":{"role":"evaluation","findings":[{"rule":"no-todo","message":"a TODO is left","severity":"error","path":"src/legacy.ts","fix":{"schematic":"default:clean-todo"},"source":"default:no-todo"}]},"warnings":[{"code":"warn_dry_run","message":"dry run: nothing is written to the workspace"},{"code":"warn_fix_schematic_unresolved","message":"a finding's fix names the schematic \"default:clean-todo\", which does not resolve in the Manifest"}]}--include and --exclude narrow the check: a finding whose path falls outside the scope is
dropped. builder validate default:no-todo --exclude=src/legacy.ts reports "findings":[]
and exits with code 0.
| Exit code | When |
|---|---|
| 0 | No finding has the severity error. |
| 6 | At least one finding has the severity error (validate_findings). |
| 2 | A usage error, such as an unknown schematic or --commit=always. |
| 5 | The evaluation failed while running, for example because it returned nothing. |
Check code with builder validate covers the output formats, running every
evaluation at once and the CI setup.
Invoke an evaluation from another schematic
Section titled “Invoke an evaluation from another schematic”A schematic can run an evaluation with invoke and receive its Findings as
the Result. This generator writes the findings of default:no-todo to a report:
import { create, invoke } from "@pbuilder/sdk/commons";
export default async () => { const findings = await invoke("default:no-todo"); create("reports/no-todo.json", { template: "{= .json =}\n", options: { json: JSON.stringify(findings) }, });};builder execute default:reportThe command exits with code 0, and reports/no-todo.json holds:
{"items":[{"rule":"no-todo","message":"a TODO is left","severity":"error","path":"src/legacy.ts","fix":{"schematic":"default:clean-todo"},"source":"default:no-todo"}]}What holds for an invoked evaluation:
-
It runs read-only. When it ends, its edits are discarded, even when it succeeds, and the rest of the Run commits as usual. An evaluation that created
review-scratch.txtleft no such file. -
Each finding carries the evaluation’s qualified name as
source. -
A finding with the severity
erroris data for the caller. It does not fail the invoke or the Run. -
It must return its Findings,
{ items: [] }when there are none. An invoked evaluation that returns nothing fails, and so does the Run:engine_native_developer_fault · factory at schematics/probe failed: the child schematic "default:silent" failed (exception): the child schematic failedThe runner log holds the cause:
invalid Result: Result is undefined.
An evaluation can invoke another evaluation and hand its findings on in its own Findings, as
received. They keep the child’s source. This evaluation adds one finding of its own to those of
default:review:
import { invoke } from "@pbuilder/sdk/commons";import type { Input, Result, Findings } from "./schema.generated.ts";
export default async (input: Input): Promise<Result> => { const review = (await invoke("default:review")) as Findings; return { items: [...review.items, { rule: "gate", message: "gate ran", severity: "warning" }] };};builder validate default:gate reports the no-todo finding with "source":"default:review"
and the gate finding with "source":"default:gate".
Limits
Section titled “Limits”These hold for the SDK and CLI versions above.
- The TypeScript dialect checks syntax only and parses each file on its own. Type information
does not cross files, so in
.inspect()or.modify(),getType()on a call imported from another file returnsany. - An evaluation may call any verb, but its edits never land:
builder validatenever writes, and an invoked evaluation’s edits are discarded. builder new schematichas no--roleflag yet (cli#269). Add the role toproject-builder.jsonand rerunnpx pbuilder-codegen.- Codegen requires a
labelon every input and fails withproperty "x" is missing a labelotherwise (sdk#307). - A read serves at most 8 MiB of one file. A larger file rejects with
ReadTooLargeError; see Files over the read cap. execute_read_ceiling_exceedednames only a read that the failing factory made itself. A child that fails on an uncaught read reaches the Run as a child failure; see When nothing catches the read.- A generator’s drift check needs an idempotent generator.
builder validateon a generator runs it against the current workspace, so a generator whosecreatehits a file it made on an earlier run fails withpath-collision(exit code 5) instead of reporting an empty Plan. Guard each insertion: read first, and write only what is missing. - With no positional and CLI v0.20.0 or earlier, one evaluation that fails hides the others and
resultis empty. From v0.20.1 the findings of the evaluations that ran are kept, anderrornames each one that could not run; see Run every evaluation.
The roadmap lists the open work on these limits.
Errors you may see
Section titled “Errors you may see”| Error | Where | Cause | Fix |
|---|---|---|---|
execute_schematic_not_executable (schematic_role_evaluation), exit 2 |
builder execute |
An evaluation cannot be executed | Run it with builder validate, or invoke it from a generator |
invalid Result: Result is undefined |
runner log, runner_note |
The evaluation returned nothing | Return { items }, { items: [] } when there are no findings |
invalid Result: Result.items[0].source is set by the SDK, and a finding may not set it |
runner log, runner_note |
A finding set source |
Remove source; the SDK sets it |
invalid Result: Result.items[0].path is undefined |
runner log, runner_note |
A finding has path: undefined |
Omit the path key when the finding has no file |
an evaluation schematic declares the input "include", which the role imposes |
pbuilder-codegen |
schema.json declares include or exclude |
Remove the input; the role provides it |
property "x" is missing a label |
pbuilder-codegen |
An input has no label |
Add a label to the input |
warn_fix_schematic_unresolved (warning, CLI v0.20.1) |
builder validate |
A finding’s fix names a schematic the Manifest does not have |
Create the schematic, or fix the name in fix |
cli_unknown_flag · --role |
builder new schematic |
The flag does not exist yet | Add the role in project-builder.json |
new_selection_metadata_invalid, exit 2 |
builder new schematic (CLI v0.21.0 or later) |
--title or --job is missing |
Pass --title and at least one --job |
execute_read_ceiling_exceeded (schematic_developer_fault), exit 5 |
builder execute, builder validate (CLI v0.26.0, SDK 0.26.0 or later) |
An uncaught ReadTooLargeError |
Catch it and skip or report the file; see When nothing catches the read |
the file "<path>" is <size> bytes, over the read limit of 8388608 bytes |
runner log, runner_note |
An uncaught ReadTooLargeError. Before CLI v0.26.0 or SDK 0.26.0, the error is engine_native_developer_fault |
Catch it and skip or report the file; see Files over the read cap |
Next steps
Section titled “Next steps”- Check code with
builder validate: output formats, every evaluation at once, and CI. - Invoke another schematic: every invoke error and how to recover.
- Testing schematics: test an evaluation and its callers in memory.